diff --git a/seaweed-block/.github/model-code-trace.tsv b/seaweed-block/.github/model-code-trace.tsv index d5d308588e..8ef6c74524 100644 --- a/seaweed-block/.github/model-code-trace.tsv +++ b/seaweed-block/.github/model-code-trace.tsv @@ -21,7 +21,7 @@ cmd/sw-block/volume_verbs.go CutTime.Poll cmd/sw-block/workspace_show.go MoveAdmission.ReadForMove core/authority/authority.go DeleteRetire.RetireLine core/authority/authority.go FormatGate.Finalize -core/authority/authority.go FormatGate.Grant +core/authority/authority.go FormatGate.Place core/authority/authority_store_file.go DeleteRetire.RetireLine core/authority/format_finalize.go FormatGate.Finalize core/authority/format_finalize.go FormatGate.Grant @@ -216,8 +216,9 @@ core/host/master/product_loop.go FencingRound.Decide core/host/master/product_loop.go Promotion.Decide core/host/master/services.go FormatGate.Report core/host/master/spec_retirement.go DeleteRetire.ReadOK +core/host/master/store_attestation.go FormatGate.Finalize core/host/master/store_attestation.go ReplicationPeer.Attest -core/host/master/workspace_binding.go FormatGate.Grant +core/host/master/workspace_binding.go FormatGate.Place core/host/master/workspace_binding.go MoveAdmission.Ack core/host/master/workspace_service.go FormatGate.Grant core/host/master/workspace_service.go FormatGate.Place diff --git a/seaweed-block/cmd/sw-block/volume_start_release_master_linux_test.go b/seaweed-block/cmd/sw-block/volume_start_release_master_linux_test.go index 96211b2bee..3f15164594 100644 --- a/seaweed-block/cmd/sw-block/volume_start_release_master_linux_test.go +++ b/seaweed-block/cmd/sw-block/volume_start_release_master_linux_test.go @@ -6,6 +6,9 @@ import ( "fmt" "net/http" "net/http/httptest" + "os" + "os/exec" + "regexp" "strings" "testing" "time" @@ -18,14 +21,26 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" ) // The real master issues the move and reports the current holder. Only the unit and holder // process are fixtures: enabling the unit renews the real assigned epoch; // the holder's stop ACK goes through the real detached-HEAD check. func TestVolumeStartReleaseAgainstRealMaster(t *testing.T) { - for _, loseAnswer := range []bool{false, true} { - t.Run(fmt.Sprintf("lost-answer-%v", loseAnswer), func(t *testing.T) { + if os.Getenv("VOLUME_START_MASTER_CHILD") != t.Name() { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1") + cmd.Env = append(os.Environ(), "VOLUME_START_MASTER_CHILD="+t.Name()) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("bounded master stop/restart/start child: %v\n%s", err, out) + } + return + } + for _, tc := range []struct{ loseAnswer, restartMaster bool }{{false, false}, {true, false}, {false, true}, {true, true}} { + loseAnswer := tc.loseAnswer + t.Run(fmt.Sprintf("lost-answer-%v/master-restart-%v", loseAnswer, tc.restartMaster), func(t *testing.T) { for _, key := range []string{"SW_BLOCK_TLS_CERT", "SW_BLOCK_TLS_KEY", "SW_BLOCK_TLS_CA"} { t.Setenv(key, "") } @@ -42,6 +57,7 @@ func TestVolumeStartReleaseAgainstRealMaster(t *testing.T) { } defer conn.Close() rpc := control.NewWorkspaceServiceClient(conn) + observations := control.NewObservationServiceClient(conn) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() h := newFakeHost(t) @@ -66,6 +82,12 @@ func TestVolumeStartReleaseAgainstRealMaster(t *testing.T) { exited79 := false env.Systemctl = func(ctx context.Context, args ...string) (string, error) { if args[0] == "enable" { + // A real newly enabled holder reports before it can receive its + // first serving deadline; a move record alone grants no I/O. + if _, err := observations.ReportHeartbeat(ctx, &control.HeartbeatReport{ReadsLevel: 1, ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "vol-f", ReplicaId: "r1", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"}}}); err != nil { + return "report", err + } ws, err := rpc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-f"}) if err != nil { return "query", err @@ -109,6 +131,22 @@ func TestVolumeStartReleaseAgainstRealMaster(t *testing.T) { if code, out, errs := runStop(env, stopOpts{Volume: "vol-f", NoCut: true, Timeout: time.Second}); code != 0 { t.Fatalf("stop=%d %s %s", code, out, errs) } + if tc.restartMaster { + // Keep the configured endpoint while losing all memory-only reports. + cfg.Listen = mh.Addr() + stop() + _ = conn.Close() + restarted, restartStop := startDeleteMaster(t, cfg) + defer restartStop() + restartedConn, err := grpc.NewClient(restarted.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer restartedConn.Close() + rpc = control.NewWorkspaceServiceClient(restartedConn) + observations = control.NewObservationServiceClient(restartedConn) + recorder.WorkspaceServiceClient = rpc + } code, out, errs := runStart(env, v, startOpts{Wait: time.Second}) if loseAnswer { if code != wsExitUnknown || h.called("enable") != 1 { diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index dcc07cd241..8dfbb966e0 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -164,9 +164,8 @@ type Publisher struct { // behaves as "never bound" until a new mint. loadErrs []error - observer PublishObserver - publicationAdmission PublicationAdmission - formatGrantProofSource func(AssignmentAsk, string) FormatReadProof // configured before serving + observer PublishObserver + publicationAdmission PublicationAdmission // Workspace state is serialized with assignment minting under mu. Remote // HEAD reads and subscriber delivery never run under this lock. @@ -530,26 +529,12 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr } } - var formatProof FormatReadProof - if p.formatGrantProofSource != nil { - server := "" - if grant != nil { - server = grant.request.TargetHost - } - formatProof = p.formatGrantProofSource(ask, server) - } p.beforeWorkspaceGrantLock("publication") p.mu.Lock() if p.deleteReserved[ask.VolumeID] { p.mu.Unlock() return ErrWorkspaceDeleteReserved } - // The report gate continues after the memory intent becomes durable level 1. - // In particular, revalidate a proof captured before that transition. - if err := p.formatReadProofError(formatProof, ask.ReplicaID, 0, ask.Incarnation); err != nil { - p.mu.Unlock() - return err - } if p.workspaceUncertain[ask.VolumeID] { p.mu.Unlock() if grant != nil { diff --git a/seaweed-block/core/authority/format_finalize.go b/seaweed-block/core/authority/format_finalize.go index b75ba1278a..42e1afedf6 100644 --- a/seaweed-block/core/authority/format_finalize.go +++ b/seaweed-block/core/authority/format_finalize.go @@ -112,9 +112,3 @@ func (p *Publisher) formatReadProofError(proof FormatReadProof, replica string, } return nil } - -// SetFormatGrantProofSource installs the master's in-memory report projection. -// Configure before serving. The source runs before mu/leaseMu, never under them. -func (p *Publisher) SetFormatGrantProofSource(source func(AssignmentAsk, string) FormatReadProof) { - p.formatGrantProofSource = source -} diff --git a/seaweed-block/core/authority/format_finalize_test.go b/seaweed-block/core/authority/format_finalize_test.go index d6b9c8427f..70f290f07c 100644 --- a/seaweed-block/core/authority/format_finalize_test.go +++ b/seaweed-block/core/authority/format_finalize_test.go @@ -159,85 +159,6 @@ func TestFormatFinalizeCountsOnlyPossiblyLiveCurrentLeases(t *testing.T) { } } -func TestFormatFinalizeIntentChecksTheMintReportAtCommit(t *testing.T) { - disk, _ := newTempStore(t) - clock := newTestClock() - p := level0Publisher(t, disk, 30*time.Second, clock) - revision := &atomic.Uint64{} - var reads atomic.Uint32 - p.SetFormatGrantProofSource(func(ask AssignmentAsk, _ string) FormatReadProof { - return FormatReadProof{Server: "node", Process: "process", Replica: ask.ReplicaID, Reported: true, Reads: reads.Load(), Revision: revision, Version: revision.Load()} - }) - if blocked := p.BeginFormatFinalize(nil, true); len(blocked) != 0 { - t.Fatal(blocked) - } - ask := AssignmentAsk{VolumeID: "fresh", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Incarnation: "process", Intent: IntentBind} - if err := p.apply(ask); err == nil { - t.Fatal("level-0 mint crossed intent with an old report") - } - reads.Store(1) - revision.Add(1) - p.testBeforeGrantLock = func(site string) { - if site == "publication" { - reads.Store(0) - revision.Add(1) - } - } - if err := p.apply(ask); err == nil { - t.Fatal("report changed after capture but the mint committed") - } - p.testBeforeGrantLock = nil - reads.Store(1) - revision.Add(1) - if err := p.apply(ask); err != nil { - t.Fatalf("capable mint during intent: %v", err) - } - if _, ok := p.PublishedAuthorityLine("fresh"); !ok { - t.Fatal("capable mint did not publish") - } -} - -func TestFormatFinalizeCompletedRaiseKeepsMintReportGate(t *testing.T) { - for _, state := range []string{"missing", "old", "changed-across-completion", "capable"} { - t.Run(state, func(t *testing.T) { - disk, _ := newTempStore(t) - p := level0Publisher(t, disk, 30*time.Second, newTestClock()) - revision := &atomic.Uint64{} - var reads atomic.Uint32 - reads.Store(1) - p.SetFormatGrantProofSource(func(ask AssignmentAsk, _ string) FormatReadProof { - return FormatReadProof{Server: "node", Process: "process", Replica: ask.ReplicaID, Reported: state != "missing", Reads: reads.Load(), Revision: revision, Version: revision.Load()} - }) - if blocked := p.BeginFormatFinalize(nil, true); len(blocked) != 0 { - t.Fatal(blocked) - } - if state == "changed-across-completion" { - p.testBeforeGrantLock = func(site string) { - if site == "publication" { - reads.Store(0) - revision.Add(1) - p.FinalizeFormatLevel() - } - } - } else { - p.FinalizeFormatLevel() - if state == "old" { - reads.Store(0) - } - } - err := p.apply(AssignmentAsk{VolumeID: "fresh", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Incarnation: "process", Intent: IntentBind}) - _, published := p.PublishedAuthorityLine("fresh") - if state == "capable" { - if err != nil || !published { - t.Fatalf("current capable publication failed: published=%v err=%v", published, err) - } - } else if err == nil || published { - t.Fatalf("invalid report crossed completed finalize: published=%v err=%v", published, err) - } - }) - } -} - func TestFormatFinalizeLiveRenewalChecksCurrentProcess(t *testing.T) { disk, _ := newTempStore(t) p := level0Publisher(t, disk, 30*time.Second, newTestClock()) @@ -277,3 +198,43 @@ func TestFormatFinalizeLiveRenewalChecksCurrentProcess(t *testing.T) { } } } + +func TestFormatFinalizeDeadlineProofSurvivesIntentCompletion(t *testing.T) { + for _, path := range []string{"first", "live", "regrant"} { + t.Run(path, func(t *testing.T) { + disk, _ := newTempStore(t) + clock := newTestClock() + p := level0Publisher(t, disk, 30*time.Second, clock) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if path != "first" { + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { + t.Fatal(err) + } + } + if path == "regrant" { + clock.at(120) + } + revision := &atomic.Uint64{} + proof := FormatReadProof{Server: "node", Replica: "r", Epoch: 1, Reported: true, Reads: 1, Revision: revision} + if blocked := p.BeginFormatFinalize(map[string]FormatReadProof{"v": proof}, true); len(blocked) != 0 { + t.Fatal(blocked) + } + p.testBeforeGrantLock = func(site string) { + if site == "renewal" { + revision.Add(1) // captured before the process report changed + p.FinalizeFormatLevel() + } + } + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err == nil { + t.Fatal("stale proof crossed intent completion into a serving deadline") + } + p.testBeforeGrantLock = nil + proof.Version = revision.Load() + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1, proof); err != nil { + t.Fatalf("current capable proof did not retry after completion: %v", err) + } + }) + } +} diff --git a/seaweed-block/core/host/master/format_finalize_failure_test.go b/seaweed-block/core/host/master/format_finalize_failure_test.go new file mode 100644 index 0000000000..8a8cd3c230 --- /dev/null +++ b/seaweed-block/core/host/master/format_finalize_failure_test.go @@ -0,0 +1,55 @@ +package master + +import ( + "context" + "errors" + "log" + "os" + "os/exec" + "strings" + "testing" + "time" +) + +type blockedFinalizeLog struct{} + +func (blockedFinalizeLog) Write([]byte) (int, error) { select {} } + +func TestFormatFinalizeUncertainWriteFailStops(t *testing.T) { + for _, sink := range []string{"normal", "blocked"} { + t.Run(sink, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFormatFinalizeUncertainWriteChild$", "-test.count=1") + cmd.Env = append(os.Environ(), "FINALIZE_FAILURE_CHILD="+sink) + out, err := cmd.CombinedOutput() + var exit *exec.ExitError + if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 1 { + t.Fatalf("uncertain finalize did not exit 1 itself: %v ctx=%v\n%s", err, ctx.Err(), out) + } + if sink == "normal" && (!strings.Contains(string(out), "ERROR") || !strings.Contains(string(out), "supervisor restarts")) { + t.Fatalf("missing persistence diagnostic: %s", out) + } + }) + } +} + +func TestFormatFinalizeUncertainWriteChild(t *testing.T) { + sink := os.Getenv("FINALIZE_FAILURE_CHILD") + if sink == "" { + t.Skip("bounded fault child") + } + r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir()) + for _, server := range []string{"node-a", "node-b"} { + if err := r.fgHeartbeat(server, 1); err != nil { + t.Fatal(err) + } + } + r.m.log = log.New(os.Stderr, "", 0) + if sink == "blocked" { + r.m.log = log.New(blockedFinalizeLog{}, "", 0) + } + syncAttestationDir = func(string) error { return errors.New("injected post-rename directory barrier failure") } + _, _, _ = r.m.FinalizeFormat(1) + os.Exit(42) // returning reopens grants after a possibly durable level raise +} diff --git a/seaweed-block/core/host/master/format_finalize_serving_test.go b/seaweed-block/core/host/master/format_finalize_serving_test.go index 7ef2c5a37e..3bd6763b5a 100644 --- a/seaweed-block/core/host/master/format_finalize_serving_test.go +++ b/seaweed-block/core/host/master/format_finalize_serving_test.go @@ -163,7 +163,7 @@ func TestFinalizeSerializesTheLevelZeroPublicationBoundary(t *testing.T) { t.Fatalf("known-old placement bypassed finalize intent: %v", err) } preview, err := r.ws.PreviewWorkspaceMove(r.ctx, &control.WorkspaceMove{RequestId: "during-finalize", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "forced", Force: true}) - if err != nil || preview.GetAdmitted() || preview.GetReasonCode() != lifecycleclient.ReasonFormatHostsTooOld { + if err != nil || preview.GetAdmitted() || preview.GetReasonCode() != lifecycleclient.ReasonBinaryTooOld { t.Fatalf("old guarded move bypassed finalize intent: %v %v", preview, err) } granted := make(chan error, 1) @@ -189,14 +189,15 @@ func TestFinalizeSerializesTheLevelZeroPublicationBoundary(t *testing.T) { case <-r.ctx.Done(): t.Fatal("finalize did not finish") } - // Completing the durable raise must not turn off the target report gate. + // Completing the durable raise keeps the renewal proof gate. Unknown + // move targets remain placeable and still face the ordinary lease barrier. r.m.reads.forget("node-b") if _, err := r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1, ServerId: "node-b"}); err == nil { t.Fatal("unreported process renewed after finalize completed") } preview, err = r.ws.PreviewWorkspaceMove(r.ctx, &control.WorkspaceMove{RequestId: "after-finalize", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "forced", Force: true}) - if err != nil || preview.GetAdmitted() || preview.GetReasonCode() != lifecycleclient.ReasonFormatHostsTooOld { - t.Fatalf("unreported guarded move bypassed completed finalize: %v %v", preview, err) + if err != nil || !strings.Contains(preview.GetReason(), "lease expiry plus clock-skew") { + t.Fatalf("unreported guarded move did not reach its existing lease barrier: %v %v", preview, err) } if err := r.fgProcessHeartbeat("node-b", "capable-v", "v", 1); err != nil { t.Fatal(err) diff --git a/seaweed-block/core/host/master/format_gate.go b/seaweed-block/core/host/master/format_gate.go index b9df6f9edf..147e3a0b24 100644 --- a/seaweed-block/core/host/master/format_gate.go +++ b/seaweed-block/core/host/master/format_gate.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "os" "sort" "strings" "sync" @@ -306,7 +307,7 @@ func (h *Host) grantWaits(now time.Time) map[string][]grantWaitEntry { // (create, move, restore target, a failover candidate), or "" when it may: // only a KNOWN-old report refuses. An unknown server is placeable, // since with one process per volume and create-then-start a placement target -// cannot have reported yet; the grant (formatTooOld) still needs its report. +// cannot have reported yet; a serving deadline still needs its own report. func (h *Host) placementTooOld(server string) string { level := h.admissionFormatLevel() if level == 0 { @@ -331,26 +332,6 @@ func (h *Host) formatRefusal(prefix, server string) error { return lifecycleclient.WithReason(status.New(codes.FailedPrecondition, prefix+why), lifecycleclient.ReasonBinaryTooOld).Err() } -// grantTooOld names why the process that will serve volume on server may not -// be granted its line, or "" when it may: the grant reads that process's own -// report (the (server, volume) entry), never a sibling process's, since -// with one process per volume a sibling's report says nothing about this -// one's binary. No report means no grant; a lower one is binary_too_old. -func (h *Host) grantTooOld(server, volume string) string { - level := h.admissionFormatLevel() - if level == 0 { - return "" - } - reads, ok := h.reads.entry(server, volume, h.servedBy(server)) - if !ok { - return fmt.Sprintf("node %q has not reported the format read level of its process for volume %q; the cluster's format level is %d (no grant before that process's report)", server, volume, level) - } - if reads < level { - return fmt.Sprintf("node %q's process for volume %q reads format level %d; the cluster's format level is %d (binary_too_old)", server, volume, reads, level) - } - return "" -} - // formatTooOld names why server is not format-eligible, or "" when it is. func (h *Host) formatTooOld(server string) string { if h.formatEligible(server) { @@ -513,7 +494,7 @@ func (h *Host) FinalizeFormat(level uint32) (already bool, unconfirmed []hostBel return false, nil, fmt.Errorf("format finalize: level %d; the only level to finalize is 1", level) } // Match RetireHost's lock order. Release workspaceMu before the store - // write; the intent then makes every publication use the level-1 gate. + // write; the intent then makes every serving deadline use the level-1 gate. h.workspaceMu.Lock() h.finalizeMu.Lock() defer h.finalizeMu.Unlock() @@ -552,6 +533,10 @@ func (h *Host) FinalizeFormat(level uint32) (already bool, unconfirmed []hostBel h.formatFinalizing.Store(true) h.workspaceMu.Unlock() if _, err := h.attest.finalize(); err != nil { + var uncertain *attestationWriteUncertain + if errors.As(err, &uncertain) { + h.failUncertainFormatFinalize(err) + } h.Publisher().CancelFormatFinalize() h.formatFinalizing.Store(false) return false, unconfirmed, fmt.Errorf("format finalize: %w", err) @@ -563,6 +548,15 @@ func (h *Host) FinalizeFormat(level uint32) (already bool, unconfirmed []hostBel return false, unconfirmed, nil } +// failUncertainFormatFinalize never reopens level-0 grants over a file whose +// rename may already have raised the durable level. Arm exit before logging: +// diagnostic delivery is best effort if the sink or its output lock is blocked. +func (h *Host) failUncertainFormatFinalize(err error) { + time.AfterFunc(time.Second, func() { os.Exit(1) }) + h.log.Printf("ERROR format finalize persistence failure store=%q error=%q; exiting so the supervisor restarts from durable state", h.attest.path, err) + os.Exit(1) +} + // RetireHost removes server from the node inventory, so it no longer counts // for the format finalize or for placement. It is refused while server // holds a lease or an assignment for any volume (FormatGate r2: a retire @@ -688,20 +682,3 @@ func formatReportVersion(e procLevel) uint64 { } return e.revision.Load() } - -func (h *Host) publicationFormatProof(ask authority.AssignmentAsk, server string) authority.FormatReadProof { - // An ordinary reassignment names the target by endpoints, which may be - // different from the current holder. Use the same target as the process - // incarnation lookup; a source holder's report cannot authorize its target. - if server == "" && h.obs != nil { - server, _ = h.obs.Store().ServerOfSlotAt(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr) - } - if server == "" { - var epoch uint64 - if line, ok := h.Publisher().PublishedAuthorityLine(ask.VolumeID); ok { - epoch = line.Epoch - } - server = h.workspaceSourceHost(ask.VolumeID, ask.ReplicaID, epoch) - } - return h.formatReadProof(ask.VolumeID, ask.ReplicaID, server, 0) -} diff --git a/seaweed-block/core/host/master/format_gate_test.go b/seaweed-block/core/host/master/format_gate_test.go index 7c1845d6b4..79c8aa1ab1 100644 --- a/seaweed-block/core/host/master/format_gate_test.go +++ b/seaweed-block/core/host/master/format_gate_test.go @@ -49,7 +49,7 @@ func binaryTooOld(err error) bool { // Every binary's heartbeat is taken and its read level recorded, at level 0 // and at level 1 alike (the refusal is at the grant, never at the // heartbeat); at level 1 a host whose process reads only level 0 is then -// known old, so placement skips it (its grant is refused at the publication +// known old, so placement skips it (publication is refused at the admission // boundary: TestThePublicationBoundaryRefusesAnAskForAnOldServer). func TestFormatGateRecordsAnOldBinarysHeartbeatAtLevel1(t *testing.T) { r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir()) @@ -69,8 +69,9 @@ func TestFormatGateRecordsAnOldBinarysHeartbeatAtLevel1(t *testing.T) { } // At level 1 no new work goes to a host that does not read it: a workspace -// placement and a move onto an old host (or one that never reported) are -// refused; at level 0 they are not refused for the format (FormatGate: +// placement and a move onto a known-old host are +// refused; an unreported target is allowed. At level 0 neither is refused +// for the format (FormatGate: // Assign, NoStrand). func TestFormatGateRefusesPlacementAndMoveOntoAnOldHost(t *testing.T) { for _, level := range []uint32{1, 0} { @@ -94,9 +95,9 @@ func TestFormatGateRefusesPlacementAndMoveOntoAnOldHost(t *testing.T) { _, moveErr := r.ws.MoveWorkspace(r.ctx, &control.WorkspaceMove{RequestId: "m1", VolumeId: "placed", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"}) if level == 1 && !reported { - // Placement alone grants nothing. A move issues a lease and - // therefore needs this target process's own report. - if placeErr != nil || reasonOf(moveErr) != lifecycleclient.ReasonFormatHostsTooOld { + // Neither placement nor a move record grants a serving deadline. + // An unreported target may pass this placement check. + if placeErr != nil || (moveErr != nil && strings.Contains(moveErr.Error(), "format")) { t.Fatalf("silent target: placement=%v move=%v", placeErr, moveErr) } return @@ -391,9 +392,10 @@ func TestAFailedFinalizeWriteLeavesLevel0(t *testing.T) { t.Fatal(err) } } - saved := syncAttestationDir - t.Cleanup(func() { syncAttestationDir = saved }) - syncAttestationDir = func(string) error { return errors.New("injected directory fsync failure") } + // A temp-path directory prevents the file write before any rename. + if err := os.Mkdir(r.m.attest.path+".tmp", 0o700); err != nil { + t.Fatal(err) + } if _, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); status.Code(err) != codes.Internal { t.Fatalf("a finalize whose envelope write failed: %v, want Internal (a failure, not a transient answer)", err) } @@ -521,8 +523,7 @@ func TestThePublicationBoundaryRefusesAnAskForAnOldServer(t *testing.T) { for _, tc := range []struct { name string old, silent bool - }{{"old-process", true, false}, {"silent (no report: no grant)", false, true}, {"control", false, false}} { - old := tc.old || tc.silent + }{{"old-process", true, false}, {"silent (placement only)", false, true}, {"control", false, false}} { t.Run(tc.name, func(t *testing.T) { r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir()) r.createVolume(t, "v") @@ -543,10 +544,7 @@ func TestThePublicationBoundaryRefusesAnAskForAnOldServer(t *testing.T) { if tc.old && (err == nil || published || !strings.Contains(err.Error(), "binary_too_old")) { t.Fatalf("level 1, node-b's process reads 0: err %v, published %v; want refused before the publish", err, published) } - if tc.silent && (err == nil || published || !strings.Contains(err.Error(), "has not reported")) { - t.Fatalf("level 1, node-b never reported: err %v, published %v; want no grant (refused before the publish)", err, published) - } - if !old && (err != nil || !published) { + if !tc.old && (err != nil || !published) { t.Fatalf("control: err %v, published %v; want published", err, published) } }) @@ -581,8 +579,8 @@ func TestEveryVolumeOfAHeartbeatKeepsItsLevel(t *testing.T) { t.Fatal(err) } r.m.format.v.Store(1) - if why := r.m.grantTooOld("node-b", "vb"); !strings.Contains(why, "binary_too_old") { - t.Fatalf("level 1: the grant for vb, held by the silent old process: %q, want binary_too_old", why) + if proof := r.m.formatReadProof("vb", "r-b", "node-b", 1); !proof.Reported || proof.Reads != 0 || proof.Process != "old-proc" { + t.Fatalf("the grant proof lost vb's own stale old report: %+v", proof) } r.m.format.v.Store(0) resp, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}) @@ -846,7 +844,7 @@ func upgradedStoreDir(t *testing.T) string { // two servers report the same volume and replica at different endpoints, one // process reading level 1 and one reading level 0; the ask at the first's // endpoints is published, the ask at the second's is refused binary_too_old, -// and an ask at endpoints nobody reports is not granted (no report). +// and an ask at unreported endpoints may publish, but grants no deadline. func TestAnOwnerlessGrantIsJudgedOnTheServerAtTheAsksEndpoints(t *testing.T) { r := newIsolationRig(t, false, t.TempDir(), t.TempDir()) if r.m.formatLevel() != 1 { @@ -870,8 +868,8 @@ func TestAnOwnerlessGrantIsJudgedOnTheServerAtTheAsksEndpoints(t *testing.T) { if published, err := grant("127.0.0.1:19601", "127.0.0.1:19602"); err == nil || published || !strings.Contains(err.Error(), "binary_too_old") { t.Fatalf("the ask at node-c's endpoints (its process reads 0): err %v, published %v; want refused binary_too_old", err, published) } - if published, err := grant("127.0.0.1:19701", "127.0.0.1:19702"); err == nil || published || !strings.Contains(err.Error(), "has not reported") { - t.Fatalf("the ask at endpoints no server reports: err %v, published %v; want no grant", err, published) + if published, err := grant("127.0.0.1:19701", "127.0.0.1:19702"); err != nil || !published { + t.Fatalf("the ask at unreported endpoints: err %v, published %v; want placement accepted", err, published) } if published, err := grant("127.0.0.1:19501", "127.0.0.1:19502"); err != nil || !published { t.Fatalf("the ask at node-b's endpoints (its process reads 1): err %v, published %v; want granted", err, published) diff --git a/seaweed-block/core/host/master/format_level_new_cluster_test.go b/seaweed-block/core/host/master/format_level_new_cluster_test.go index c737a7b648..3d0328ba33 100644 --- a/seaweed-block/core/host/master/format_level_new_cluster_test.go +++ b/seaweed-block/core/host/master/format_level_new_cluster_test.go @@ -72,8 +72,8 @@ func TestANewClusterStartsAtTheCurrentFormatLevel(t *testing.T) { // On a new cluster (level 1) a node that has not reported is placeable (one // process per volume, created then started, cannot have reported at its // placement) and shows as awaiting report; it is not granted until its own -// report: the publication of its line is refused and its publish never runs; -// after its first heartbeat (reads level 1) the line is published and the +// report: publication alone grants no serving deadline; after its own first +// heartbeat (reads level 1), its lease renewal grants a deadline and the // condition is gone. func TestANewClusterPlacesAnUnreportedNodeAndGrantsAfterItsReport(t *testing.T) { r := newIsolationRig(t, false, t.TempDir(), t.TempDir()) @@ -109,14 +109,22 @@ func TestANewClusterPlacesAnUnreportedNodeAndGrantsAfterItsReport(t *testing.T) func() error { published = true; return nil }) return published, err } - if published, err := grant(); err == nil || published { - t.Fatalf("the grant before node-b's report: err %v, published %v; want no grant", err, published) + if published, err := grant(); err != nil || !published { + t.Fatalf("publication before node-b's report: err %v, published %v; want placed", err, published) + } + if err := r.m.Controller().SubmitAssignmentAsk(authority.AssignmentAsk{VolumeID: "fresh", ReplicaID: "r1", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322", Intent: authority.IntentBind}); err != nil { + t.Fatal(err) + } + line := waitAuthorityLine(t, r.m.Publisher(), "fresh") + id := &control.WorkspaceIdentity{VolumeId: "fresh", ReplicaId: "r1", ServerId: "node-b", Epoch: line.Epoch} + if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err == nil { + t.Fatal("unreported process obtained its first serving deadline") } if err := r.fgProcessHeartbeat("node-b", "proc-b", "fresh", 1); err != nil { t.Fatal(err) } - if published, err := grant(); err != nil || !published { - t.Fatalf("the grant after node-b's report: err %v, published %v; want granted", err, published) + if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil { + t.Fatalf("first deadline after node-b's report: %v", err) } if awaiting() { t.Fatal("node-b still shows awaiting report after its first heartbeat") @@ -175,7 +183,7 @@ func TestAnEmptyAuthorityStoreOverAnExistingInventoryStartsAtLevel0(t *testing.T // The grant reads the holder's own report: on a server whose process for // volume u reported level 1, a new process for volume v that has not -// reported yet is not granted v's line; once v's own process reports level +// reported yet receives no serving deadline; once v's own process reports level // 1 it is (a sibling's report says nothing about this process's binary). func TestTheGrantReadsTheHoldersOwnReportNotASiblings(t *testing.T) { r := newIsolationRig(t, false, t.TempDir(), t.TempDir()) @@ -192,14 +200,22 @@ func TestTheGrantReadsTheHoldersOwnReportNotASiblings(t *testing.T) { func() error { published = true; return nil }) return published, err } - if published, err := grant(); err == nil || published { - t.Fatalf("v's grant on u's report only: err %v, published %v; want no grant", err, published) + if published, err := grant(); err != nil || !published { + t.Fatalf("v's placement on an unreported process: err %v, published %v", err, published) + } + if err := r.m.Controller().SubmitAssignmentAsk(authority.AssignmentAsk{VolumeID: "v", ReplicaID: "r1", DataAddr: "127.0.0.1:19331", CtrlAddr: "127.0.0.1:19332", Intent: authority.IntentBind}); err != nil { + t.Fatal(err) + } + line := waitAuthorityLine(t, r.m.Publisher(), "v") + id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", ServerId: "node-b", Epoch: line.Epoch} + if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err == nil { + t.Fatal("v's first deadline used u's report") } if err := r.fgProcessHeartbeat("node-b", "proc-v", "v", 1); err != nil { t.Fatal(err) } - if published, err := grant(); err != nil || !published { - t.Fatalf("v's grant after v's own report: err %v, published %v; want granted", err, published) + if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil { + t.Fatalf("v's first deadline after its own report: %v", err) } } diff --git a/seaweed-block/core/host/master/format_place_lease_test.go b/seaweed-block/core/host/master/format_place_lease_test.go new file mode 100644 index 0000000000..80baf01f30 --- /dev/null +++ b/seaweed-block/core/host/master/format_place_lease_test.go @@ -0,0 +1,117 @@ +package master + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// The move's stored lease is a reservation, not the target's permission to +// serve. Only an accepted renewal reply can open the production lease guard. +func TestFormatMoveRecordCannotServeBeforeReportedRenewal(t *testing.T) { + if !finalizeServingChild(t) { + return + } + for _, phase := range []string{"intent", "committed"} { + t.Run(phase, func(t *testing.T) { formatMoveRecordCannotServe(t, phase) }) + } +} + +func formatMoveRecordCannotServe(t *testing.T, phase string) { + r := newIsolationRig(t, false, upgradedStoreDir(t), t.TempDir()) + r.createVolume(t, "moved") + r.place(t, "moved", "node-a") + if err := ingestV11(r.m, authority.Observation{ServerID: "node-a", ObservedAt: time.Now().UTC(), + Slots: []authority.SlotFact{{VolumeID: "moved", ReplicaID: "r1", DataAddr: "127.0.0.1:19131", CtrlAddr: "127.0.0.1:19132"}}}); err != nil { + t.Fatal(err) + } + if _, err := r.m.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + waitAuthorityLine(t, r.m.Publisher(), "moved") + source := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "moved", ReplicaId: "r1", Epoch: 1} + if _, err := r.ws.RenewWorkspaceLease(r.ctx, source); err != nil { + t.Fatal(err) + } + if _, err := r.ws.RevokeWorkspace(r.ctx, source); err != nil { + t.Fatal(err) + } + if _, err := r.ws.AckWorkspaceRevoked(r.ctx, &control.WorkspaceRevocationAck{Identity: source, HeadGen: 9}); err != nil { + t.Fatal(err) + } + entered, release := make(chan struct{}), make(chan struct{}) + releaseOnce := sync.OnceFunc(func() { close(release) }) + previous := syncAttestationDir + if phase == "intent" { + syncAttestationDir = func(dir string) error { close(entered); <-release; return previous(dir) } + t.Cleanup(func() { syncAttestationDir = previous }) + } + finished := make(chan error, 1) + go func() { _, _, err := r.m.FinalizeFormat(1); finished <- err }() + joined := false + t.Cleanup(func() { + releaseOnce() + if !joined { + <-finished // the entire scenario is isolated in a bounded child + } + }) + if phase == "intent" { + select { + case <-entered: + case <-r.ctx.Done(): + t.Fatal("finalize did not reach the held write") + } + } else { + if err := <-finished; err != nil { + t.Fatal(err) + } + joined = true + } + // This target has never reported. Publication/move is Place, not a + // serving deadline; both the intent and level 1 must allow the move. + moved, err := r.ws.MoveWorkspace(r.ctx, &control.WorkspaceMove{RequestId: "lease-record-only", VolumeId: "moved", ExpectedReplicaId: "r1", ExpectedEpoch: 1, + TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"}) + if err != nil || !moved.GetIssued() { + t.Fatalf("unreported target move refused during %s: %v %v", phase, moved, err) + } + ws, err := r.ws.QueryWorkspace(r.ctx, &control.WorkspaceVolume{VolumeId: "moved"}) + if err != nil || ws.GetLease().GetEpoch() != moved.GetNewEpoch() || ws.GetLease().GetExpiresAtNs() <= time.Now().UnixNano() { + t.Fatalf("move did not issue a possibly-live lease record: %v %v", ws, err) + } + // The issued move and its positive lease record exist, but no renewal + // reply has reached the guard, and the target still has no report. + id := &control.WorkspaceIdentity{VolumeId: "moved", ReplicaId: "r1", ServerId: "node-b", Epoch: moved.GetNewEpoch()} + guard, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "moved", ReplicaID: "r1", Epoch: moved.GetNewEpoch(), Healthy: true}}, r.ws, id, + func(context.Context) (uint64, error) { + t.Fatal("a refused first renewal must not drain an ungranted guard") + return 0, nil + }, time.Now) + if err != nil { + t.Fatal(err) + } + if guard.Held() || guard.Projection().Healthy { + t.Fatal("issued move record opened serving before a renewal reply") + } + if err := guard.Refresh(r.ctx); err == nil || guard.Held() || guard.Projection().Healthy { + t.Fatalf("unreported target obtained serving from the issued record: %v", err) + } + if err := r.fgProcessHeartbeat("node-b", "", "moved", 1); err != nil { + t.Fatal(err) + } + if err := guard.Refresh(r.ctx); err != nil || !guard.Held() || !guard.Projection().Healthy { + t.Fatalf("reported target did not serve after an accepted renewal: %v", err) + } + releaseOnce() + if !joined { + if err := <-finished; err != nil { + t.Fatal(err) + } + joined = true + } +} diff --git a/seaweed-block/core/host/master/golden_v100_test.go b/seaweed-block/core/host/master/golden_v100_test.go index eaff498be9..f4c0f98dc8 100644 --- a/seaweed-block/core/host/master/golden_v100_test.go +++ b/seaweed-block/core/host/master/golden_v100_test.go @@ -276,8 +276,8 @@ func TestAttestationEnvelopeIsSyncedAtEveryStart(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := s.finalize(); err == nil || s.level() != 0 { - t.Fatalf("a failed directory fsync of the finalize's envelope: err=%v level=%d (want an error, level 0)", err, s.level()) + if _, err := s.finalize(); err == nil || s.level() != 1 { + t.Fatalf("a failed directory fsync keeps the possibly-written envelope selected until fail-stop: err=%v level=%d", err, s.level()) } // The process restarts: the envelope is on disk (the rename happened). s, err = loadStoreAttestations(dir) diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index aaf2c744b2..59d88c6333 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -313,7 +313,6 @@ func New(cfg Config) (*Host, error) { } holder.set(boot.Publisher) boot.Publisher.RequireFormatReadProofs() - boot.Publisher.SetFormatGrantProofSource(h.publicationFormatProof) // Bootstrap creates a fresh store directory: sample its file system only // now, or a first start would compare against an unknown device forever. // An unknown identity (stat error, unsupported platform) never matches. diff --git a/seaweed-block/core/host/master/store_attestation.go b/seaweed-block/core/host/master/store_attestation.go index 73cc199f09..5242b71d6b 100644 --- a/seaweed-block/core/host/master/store_attestation.go +++ b/seaweed-block/core/host/master/store_attestation.go @@ -205,7 +205,10 @@ func (s *storeAttestations) finalize() (already bool, err error) { } s.enveloped = true if err := s.persist(s.vols); err != nil { - s.enveloped = false + var uncertain *attestationWriteUncertain + if !errors.As(err, &uncertain) { + s.enveloped = false + } return false, err } return false, nil @@ -537,9 +540,17 @@ func (s *storeAttestations) persist(vols map[string]attestedStores) error { _ = os.Remove(temp) return fmt.Errorf("store attestations: %w", werr) } - return syncAttestationDir(filepath.Dir(s.path)) + if err := syncAttestationDir(filepath.Dir(s.path)); err != nil { + return &attestationWriteUncertain{err} + } + return nil } +// attestationWriteUncertain means the rename landed but its durability is unknown. +type attestationWriteUncertain struct{ error } + +func (e *attestationWriteUncertain) Unwrap() error { return e.error } + // ingestStoreAttestation records a heartbeat's attestation when the // reporting server holds the volume's published primary line at the // attested epoch (the line's replica and owner). Anything else is not a diff --git a/seaweed-block/core/host/master/workspace_binding.go b/seaweed-block/core/host/master/workspace_binding.go index 03d1a6261d..abd88d9f79 100644 --- a/seaweed-block/core/host/master/workspace_binding.go +++ b/seaweed-block/core/host/master/workspace_binding.go @@ -281,18 +281,17 @@ func (h *Host) admitWorkspacePublicationNow(ask authority.AssignmentAsk, publish epoch = line.Epoch } server := h.workspaceSourceHost(ask.VolumeID, ask.ReplicaID, epoch) - // The format gate at the grant: an authority line is published - // only to a server whose own report reads the cluster's level; no report - // means no grant (the ask waits for it), and an ask decided on - // observations taken before its server reported a lower level is not - // published. - // A line with no recorded owner (a static topology's) goes to the process - // the facts show at the ask's endpoints; its server is the one judged. - grantServer := server - if grantServer == "" && h.obs != nil { - grantServer, _ = h.obs.Store().ServerOfSlotAt(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr) + // Publication places an authority line; only a renewal reply authorizes + // serving. During finalize and at level 1, place only refuses known-old + // targets. Resolve the target at the ask's endpoints, not another source. + placeServer := "" + if h.obs != nil { + placeServer, _ = h.obs.Store().ServerOfSlotAt(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr) } - if why := h.grantTooOld(grantServer, ask.VolumeID); why != "" { + if placeServer == "" { + placeServer = server + } + if why := h.placementTooOld(placeServer); why != "" { return fmt.Errorf("workspace publication: %s", why) } b := lifecycle.WorkspaceBinding{VolumeID: ask.VolumeID, ServerID: server, DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index de39bb9595..a0db41ae07 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -463,18 +463,12 @@ func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req autho // after these endpoint and binding checks, also for a same-host target. case !replay && s.host.colocatedTargetRefused(target.ServerID): refusal.text = fmt.Sprintf("move target node %q shares the authority store's file system (strict journal isolation)", target.ServerID) - case !replay && s.host.formatFinalizing.Load() && s.host.grantTooOld(target.ServerID, q.GetVolumeId()) != "": - refusal = moveRefusal{"move target " + s.host.grantTooOld(target.ServerID, q.GetVolumeId()), lifecycleclient.ReasonFormatHostsTooOld} case !replay && s.host.placementTooOld(target.ServerID) != "": // Only a known-old report refuses a move target; the - // target's line is granted only after its own report. + // target receives a serving deadline only after its own report. refusal = moveRefusal{"move target " + s.host.placementTooOld(target.ServerID), s.host.formatTooOldReason(target.ServerID)} case !matched: refusal.text = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit)) - case !replay && s.host.grantTooOld(target.ServerID, q.GetVolumeId()) != "": - // A move issues a lease, unlike a placement. At level 1 it needs the - // target process's own report even when that server is not known old. - refusal = moveRefusal{"move target " + s.host.grantTooOld(target.ServerID, q.GetVolumeId()), lifecycleclient.ReasonFormatHostsTooOld} } return req, target, replay, refusal, nil } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0cffbc8a88..0face4a524 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -732,10 +732,10 @@ stateDiagram-v2 | From | To | Guard / action | Enforced in | Invariant | |---|---|---|---|---| | Level 0 | Finalizing | Preserve the existing known-old work check. Under Publisher mu then leaseMu, exclude unserved lines, clean ACKed releases and proven-ended leases; require each remaining current process's own level-1 report and set the admission intent. Report changes invalidate captured proofs. | `core/authority/format_finalize.go` `BeginFormatFinalize`; `core/host/master/format_gate.go` `FinalizeFormat` | `INV-FMT-FINALIZE-001` | -| Finalizing | Finalizing | New publications, move grants and every deadline-extending renewal require the current process's level-1 report during intent and at level 1. A live deadline alone does not admit a replacement process. Capable renewals remain memory-only; no grant lock spans the durable write. | `core/host/master/workspace_binding.go` `admitWorkspacePublication`; `core/authority/workspace_lease_view.go` `firstWorkspaceGrant`, `regrantWorkspaceLease` | `INV-FMT-FINALIZE-001`, `INV-WS-RENEW-NONBLOCKING-001` | -| Finalizing | Level 1 / Level 0 | On durable success publish level 1 under the grant locks; on failure clear the intent under those locks and report the store error. The in-memory intent is not a persisted format or a new authority fact. | `core/authority/workspace_lease_v100.go` `FinalizeFormatLevel`; `core/authority/format_finalize.go` `CancelFormatFinalize` | `INV-FMT-LEVEL-001`, `INV-FMT-FINALIZE-001` | +| Finalizing | Finalizing | Move and publication are placement: refuse only known-old targets. First serving deadlines, live renewals and regrants require the current process's level-1 report during intent and at level 1. A stored move lease alone permits no serving. Capable renewals stay memory-only; no grant lock spans the durable write. | `core/host/master/workspace_binding.go` `admitWorkspacePublication`; `core/authority/workspace_lease_view.go` `firstWorkspaceGrant`, `regrantWorkspaceLease` | `INV-FMT-FINALIZE-001`, `INV-WS-RENEW-NONBLOCKING-001` | +| Finalizing | Level 1 / Level 0 | On durable success publish level 1 under the grant locks; on a proven pre-rename failure clear the intent; an uncertain post-rename persistence failure retains the intent and fail-stops for recovery. The in-memory intent is not a persisted format or a new authority fact. | `core/authority/workspace_lease_v100.go` `FinalizeFormatLevel`; `core/authority/format_finalize.go` `CancelFormatFinalize` | `INV-FMT-LEVEL-001`, `INV-FMT-FINALIZE-001` | -This implementation interval refines FormatGate r11's atomic `Finalize`; the intent closes level-0 admission +This implementation interval refines FormatGate r12's atomic `Finalize`; the intent closes level-0 admission while the store write runs outside the grant locks. It neither grants authority nor raises a holder's effective level. ## Part B. Invariant ledger @@ -984,8 +984,8 @@ Notes: | `INV-WS-RESTART-GRACE-001` | At format level 1, a renewal writes nothing durable. A forced move, an expired re-grant and a no-live-lease proof wait for this process's deadline plus skew: its latest grant, or after a restart the restart floor (restart + TTL); no lease value an earlier process wrote is read. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted; any → DeleteReserved | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `regrantWorkspaceLease`, `newWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`, `AckWorkspaceRevocation`; `core/authority/authority.go` `reloadFromStore` (the restart floor) | `TestRenewalWritesNothingDurable`, `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceLeaseGuardServesThroughAStalledStore` (`core/host/master/workspace_lease_horizon_test.go`); `TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor`, `TestAfterARestartTheSameLiveHolderRenewsAtOnce` (`core/authority/workspace_restart_barrier_test.go`) | `LeaseRestart` `OneServer` (grace design) | ACTIVE | | `INV-WS-AUTH-RECORD-V2-001` | The format finalize writes the store's attestation file as format 2 (`INV-FMT-LEVEL-001`), on which a v1.0.x master refuses its whole start; from then on its authority records are envelope version 2 (a v1.0.x master would skip them); before it, both are v1.0's. It reads both forms of each. | M2 every workspace write; master start | `core/host/master/store_attestation.go` `ensureEnvelope`, `decodeStoreAttestations`; `core/host/master/host.go` `New`; `core/authority/authority_store.go` `storeEnvelopeVersion`, `encodeEnvelope`, `decodeEnvelope` | `TestAV100MasterRefusesTheAttestationEnvelope`, `TestAttestationsWriteTheV100FileUntilTheFinalize`, `TestAttestationsReadTheV100File` (`core/host/master/golden_v100_test.go`); `TestARecordWrittenNowFailsTheV100Decoder` (`core/authority/workspace_restart_grace_test.go`); `TestAuthorityStoreWritesTheV100Files`, `TestAuthorityStoreReadsTheV100Files` (`core/authority/golden_v100_test.go`) | — | ACTIVE | | `INV-FMT-LEVEL-001` | The cluster's format level is the attestation file's form: v1.0.x's bare map is level 0, the envelope (format 2, format_level 1) level 1. It only rises: the finalize is its only writer, and an envelope below level 1 is refused at start. | FormatGate Finalize (level 0 → 1) | `core/host/master/store_attestation.go` `decodeStoreAttestations`, `finalize`, `persist`, `level`; `core/host/master/host.go` `New` | `TestFinalizeFormatBlocksOnAnOldHolderAndIsDurable`, `TestAnAttestationEnvelopeBelowLevel1IsRefused` (`core/host/master/format_gate_test.go`); `TestAttestationsWriteTheV100FileUntilTheFinalize`, `TestAV100MasterRefusesTheAttestationEnvelope` (`core/host/master/golden_v100_test.go`) | `FormatGate` `OneWay` (mutation `level_lowered`) | ACTIVE | -| `INV-FMT-FINALIZE-001` | Finalize checks possibly-live holders and sets its memory intent under grant locks. During intent and at level 1, grants and extending renewals need the current process report. Durable I/O holds no grant lock; failure clears intent. ACKed releases and proven-ended leases do not block. | FormatGate Finalize | `core/host/master/format_gate.go` `FinalizeFormat`, `finalizeCheck`; `core/authority/workspace_lease_v100.go` `FinalizeFormatLevel`; `core/authority/format_finalize.go` `BeginFormatFinalize`, `CancelFormatFinalize` | `TestFinalizeFormatBlocksOnAnOldHolderAndIsDurable`, `TestFinalizeFormatListsTheHostsItCannotConfirm`, `TestAFailedFinalizeWriteLeavesLevel0`, `TestAHolderRestartedOnAnOldBinaryIsNotReissuedItsLine` (`core/host/master/format_gate_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted` (`core/host/volume/line_incarnation_test.go`); `TestClusterFinalizeFormat` (`cmd/sw-block/cluster_format_test.go`); `TestClusterFinalizeFormatTypedAnswer` (`cmd/sw-block/cluster_format_json_test.go`); `TestFinalizeRequiresTheGrantedHoldersReadReport`, `TestFinalizeSerializesTheLevelZeroPublicationBoundary`, `TestFormatFinalizeIntentRequiresRegrantReport`, `TestFormatFinalizeCountsOnlyPossiblyLiveCurrentLeases`, `TestFormatFinalizeIntentDoesNotSurviveProcessExit`, `TestFormatFinalizeFailedCheckLeavesLevelZeroGrantsOpen`, `TestFormatFinalizeLiveRenewalChecksCurrentProcess`, `TestFormatFinalizeCompletedRaiseKeepsMintReportGate` | FormatGate r11 Finalize, Grant, Renew / ServersReported, GrantReport, NoStrand; mutant finalize_ignores_unreported_server violates ServersReported; the admission intent splits the atomic action around the durable write without reopening level-0 grants | ACTIVE | -| `INV-FMT-ELIGIBLE-001` | At level L no new work goes to a server known to read below L: no placement or move target (binary_too_old). An unreported server is placeable; no line is granted to a holder process before its own report. Heartbeats are recorded, never refused. Placed work stays. Every assignment carries L. | FormatGate Assign (placement, move, failover) | `core/host/master/format_gate.go` `formatEligible`, `formatTooOld`, `placementTooOld`, `grantTooOld`; `core/host/master/journal_isolation.go` `newWorkRefused`, `reconcilePlacements`; `core/host/master/workspace_binding.go` `PlaceWorkspace`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/services.go` `ReportHeartbeat`, `assignmentFact` | `TestFormatGateRecordsAnOldBinarysHeartbeatAtLevel1`, `TestFormatGateRefusesPlacementAndMoveOntoAnOldHost`, `TestFormatGateProductLoopPlacesOnlyOnHostsThatReadTheLevel`, `TestAssignmentFactCarriesTheFormatLevel` (`core/host/master/format_gate_test.go`) | `FormatGate` `NoStrand` (mutation `place_ignores_reads_level`) | ACTIVE | +| `INV-FMT-FINALIZE-001` | Finalize checks possibly-live leases and sets a memory intent under grant locks. First grants, renewals and regrants require current reports during intent and at level 1. Move/publication is Place. I/O holds no grant lock; pre-rename failure clears intent; uncertain persistence fail-stops. | FormatGate Finalize | `core/host/master/format_gate.go` `FinalizeFormat`, `finalizeCheck`; `core/authority/workspace_lease_v100.go` `FinalizeFormatLevel`; `core/authority/format_finalize.go` `BeginFormatFinalize`, `CancelFormatFinalize` | `TestFinalizeFormatBlocksOnAnOldHolderAndIsDurable`, `TestFinalizeFormatListsTheHostsItCannotConfirm`, `TestAFailedFinalizeWriteLeavesLevel0`, `TestAHolderRestartedOnAnOldBinaryIsNotReissuedItsLine` (`core/host/master/format_gate_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted` (`core/host/volume/line_incarnation_test.go`); `TestClusterFinalizeFormat` (`cmd/sw-block/cluster_format_test.go`); `TestClusterFinalizeFormatTypedAnswer` (`cmd/sw-block/cluster_format_json_test.go`); `TestFinalizeRequiresTheGrantedHoldersReadReport`, `TestFinalizeSerializesTheLevelZeroPublicationBoundary`, `TestFormatFinalizeIntentRequiresRegrantReport`, `TestFormatFinalizeCountsOnlyPossiblyLiveCurrentLeases`, `TestFormatFinalizeIntentDoesNotSurviveProcessExit`, `TestFormatFinalizeFailedCheckLeavesLevelZeroGrantsOpen`, `TestFormatFinalizeLiveRenewalChecksCurrentProcess`, `TestFormatFinalizeDeadlineProofSurvivesIntentCompletion`, `TestFormatMoveRecordCannotServeBeforeReportedRenewal`, `TestFormatFinalizeUncertainWriteFailStops` | FormatGate r12 FinalizeBegin, FinalizeCommit, FinalizeAbort, Grant, Renew / ServersReported, GrantReport, NoStrand; serve_across_restart and grant_unchecked_in_intent are refused; move/publication is Place, and only a checked renewal reply grants serving | ACTIVE | +| `INV-FMT-ELIGIBLE-001` | At level L no new work goes to a server known to read below L: no placement or move target (binary_too_old). An unreported target may be placed or moved; its serving deadline requires its own report. Heartbeats are recorded, never refused. Placed work stays. Every assignment carries L. | FormatGate Assign (placement, move, failover) | `core/host/master/format_gate.go` `formatEligible`, `formatTooOld`, `placementTooOld`; `core/host/master/journal_isolation.go` `newWorkRefused`, `reconcilePlacements`; `core/host/master/workspace_binding.go` `PlaceWorkspace`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/services.go` `ReportHeartbeat`, `assignmentFact` | `TestFormatGateRecordsAnOldBinarysHeartbeatAtLevel1`, `TestFormatGateRefusesPlacementAndMoveOntoAnOldHost`, `TestFormatGateProductLoopPlacesOnlyOnHostsThatReadTheLevel`, `TestAssignmentFactCarriesTheFormatLevel` (`core/host/master/format_gate_test.go`) | `FormatGate` `NoStrand` (mutation `place_ignores_reads_level`) | ACTIVE | | `INV-FMT-LEVEL0-V100-001` | At format level 0 the master writes as v1.0: grants clamp to the persisted horizon, an extender keeps it current, forced moves and re-grants wait for the later of horizon and deadline plus skew, records are version 1. Every grant raises the deadline at both levels. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted (level 0) | `core/authority/workspace_lease_v100.go` `renewV100Locked`, `extendWorkspaceLease`, `forcedMoveBarrierV100Locked`, `ackValidityLocked`, `envelopeVersionLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease` | `TestALevel0RenewalKeepsTheHorizonCurrent`, `TestALevel0GrantIsClampedToTheHorizon`, `TestTheForcedBarrierFollowsTheFormatLevel`, `TestRecordEnvelopeVersionFollowsTheFormatLevel` (`core/authority/workspace_format_level_test.go`) | `FormatGateMaster` `OneServer`, `GraceOnlyFinal` (mutations `level0_no_horizon`, `old_starts_after_finalize`) | ACTIVE | | `INV-FMT-RETIRE-001` | A host retire, the node registry's only writer after start, is refused, naming the volumes, while the host holds a placement or a live line, and unless confirm repeats the id. A retired id is unregistered; if the host returns it registers again at its reported level. | FormatGate Retire | `core/host/master/format_gate.go` `RetireHost`; `core/host/master/journal_isolation.go` `volumesServedBy` | `TestRetireHostRefusesAHostThatHoldsWork` (`core/host/master/format_gate_test.go`); `TestACleanMoveReleasesTheTopologyHome`, `TestTheTopologyHomeHoldsTheVolumeBeforeAMove`, `TestTheTopologyHomeAloneHoldsTheVolumeBeforeAMove` (`core/host/master/served_topology_move_test.go`); `TestClusterRetireHost` (`cmd/sw-block/cluster_format_test.go`); `TestNodeRegistryIsWrittenOnlyAtStartup` (`cmd/blockmaster/node_registry_guard_test.go`) | `FormatGate` r2 `OneServer` (mutation `retire_holding_host`) | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/operations-manual.md b/seaweed-block/docs/operations-manual.md index d231d502b8..c1a005608e 100644 --- a/seaweed-block/docs/operations-manual.md +++ b/seaweed-block/docs/operations-manual.md @@ -593,12 +593,18 @@ writing the v1.0 format until you finalize. Until then you can go back. - A process with a possibly-live lease must have reported reading level 1. No report or an old report from a serving process refuses the finalize and names its host and volume. A clean ACKed release and a lease proven ended are excluded from this serving check; a placement alone is not proof of serving. During the durable - finalize and after level 1 commits, grants and deadline-extending renewals require the current process's + finalize and after level 1 commits, first serving deadlines and all renewal paths require the current process's level-1 report. A replacement old process cannot extend a live lease; capable renewals remain nonblocking. + Moves and authority publication may place an unreported target; an issued move does not permit serving. + The target starts, reports, and obtains a checked renewal reply before it serves. - **`listed`** names other hosts the master cannot confirm but that do not block the finalize: an unserved placement with no report, a host with no work or report, or a stale capable report. + - **Persistence fault.** If the attestation replacement may have landed, blockmaster retains the admission + intent and exits nonzero so its supervisor restarts from disk. Run it under a restarting supervisor. + ERROR delivery is best effort if logging is blocked; termination remains bounded. Inspect `format-level` + after recovery before retrying. A failure before replacement leaves level 0 and can be retried. - **Exit codes:** **0** finalized or already finalized; **2** refused; **75** blockmaster unreachable, retry; **1** - any other failure (the level is unchanged). + any other failure. After a persistence fault the recovered level may be 0 or 1. - **JSON only.** The typed codes (`FORMAT_HOSTS_TOO_OLD`, and `HOST_HOLDS_WORK` below) appear only with `--json`. Plain output says `refused`. @@ -1120,3 +1126,4 @@ the master and filer remain on A. Keep the same volume size, replica id and chun Section 12's removal also removes the per-instance TLS override (`/etc/systemd/system/sw-blockvolume@*.service.d`). Remove `/etc/sw-block/tls` with `/etc/sw-block`, and keep the CA key where it is. + diff --git a/seaweed-block/docs/releases/v1.1.2.md b/seaweed-block/docs/releases/v1.1.2.md index ccc5688604..5b81d94af1 100644 --- a/seaweed-block/docs/releases/v1.1.2.md +++ b/seaweed-block/docs/releases/v1.1.2.md @@ -6,6 +6,13 @@ if a possibly-serving process has not reported reading level 1. Silence and a stale level-0 report do not prove that the holder stopped. Upgrade and report from that holder, or finish its clean release, before retrying. The serving check excludes clean ACKed releases and leases proven ended; an unserved placement needs no report. -New grants, re-grants and deadline-extending renewals require the current process's level-1 report during +First serving deadlines, re-grants and live renewals require the current process's level-1 report during finalize and after level 1 commits. A replacement old or unreported process cannot extend a live lease. Current capable processes renew without waiting for the store write. This changes no persisted format or rollback-before-finalize rule. +Moves and authority publication remain placement: an unknown target may be placed; only a known-old report refuses it. +An issued move record alone permits no serving. The target must report and get an accepted renewal reply first. + +If finalize fails after replacing its attestation file, blockmaster exits nonzero so its supervisor restarts +from disk. ERROR delivery is best effort if logging is blocked; termination remains bounded. Run blockmaster +under a restarting supervisor and inspect `format-level` after recovery. Failures before replacement leave +level 0 and may be retried. diff --git a/seaweed-block/docs/time-bounds.tsv b/seaweed-block/docs/time-bounds.tsv index 55cbde057c..50fc5a8c6a 100644 --- a/seaweed-block/docs/time-bounds.tsv +++ b/seaweed-block/docs/time-bounds.tsv @@ -197,6 +197,7 @@ core/frontend/nvmerdma/target.go providerBackend.Sync context.WithTimeout 1 per- core/frontend/ublk/device_linux.go openWhenPresent time.Now().Add 1 per-call NONE: no model row maps this file yet one ublk device open wait core/frontend/ublk/lifecycle.go settleQueues time.NewTimer 1 per-call NONE: no model row maps this file yet one bounded wait core/frontend/write_budget.go WithWriteBudget context.WithDeadline 1 per-call NONE: no model row maps this file yet one guest write command's budget +core/host/master/format_gate.go Host.failUncertainFormatFinalize time.AfterFunc 1 availability-contract FormatGate.Finalize one-second fail-stop fallback independent of a blocked diagnostic sink core/host/master/host.go New http.Server.ReadHeaderTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection core/host/master/host.go New http.Server.ReadTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection core/host/master/host.go New http.Server.WriteTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection