diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index d3e98449f8..aaefdd3800 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -250,16 +250,18 @@ func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStar // sources; the provider rechecks the claim generation below. out := workspaceRetryOutcome("assignment_timeout", h, p.ChunkStartupSuperseded(f.volumeID, gen)) if h != nil { - // A typed MOVED or DELETED renewal refusal is permanent: 78 at once, + // A typed MOVED or DELETED master refusal is permanent: 78 at once, // never a restart loop to the unit's start limit. It is the reason // that ended the wait, so it names the exit even when a newer // foreign line was also observed (superseded). if _, final := h.MasterWaitState(); final != "" { - out = workspaceExit{code: exitWorkspaceSuperseded, reason: final} + out = workspaceExit{code: exitWorkspaceSuperseded, reason: final, detail: h.MasterWaitDetail()} } } if c, ok := p.(interface{ ChunkStartupCure(string, uint64) string }); ok { - out.detail = c.ChunkStartupCure(f.volumeID, gen) + if cure := c.ChunkStartupCure(f.volumeID, gen); cure != "" { + out.detail = cure + } } return p.ChooseChunkStartupExit(f.volumeID, gen, func() { e.chooseChunkStartup(out) }) } diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index bf97e862db..2a0a0bb49c 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -22,14 +22,15 @@ type exitAssignmentStream struct { control.UnimplementedAssignmentServiceServer control.UnimplementedObservationServiceServer control.UnimplementedWorkspaceServiceServer - revoke bool - refuse error // when set, every renewal is refused with it + revoke bool + refuse error // when set, every renewal is refused with it + streamRefuse error // the master may refuse a restarted source before an assignment // identityRefusals: the first this many stream calls are refused with // the typed IDENTITY detail. identityRefusals atomic.Int32 - ackError error - acks atomic.Int32 - facts chan *control.AssignmentFact + ackError error + acks atomic.Int32 + facts chan *control.AssignmentFact } func (s *exitAssignmentStream) RenewWorkspaceLease(_ context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) { @@ -49,6 +50,9 @@ func (s *exitAssignmentStream) ReportHeartbeat(context.Context, *control.Heartbe return &control.HeartbeatAck{}, nil } func (s *exitAssignmentStream) SubscribeAssignments(_ *control.SubscribeRequest, stream control.AssignmentService_SubscribeAssignmentsServer) error { + if s.streamRefuse != nil { + return s.streamRefuse + } if s.identityRefusals.Add(-1) >= 0 { st, _ := status.New(codes.FailedPrecondition, `assignment stream: server id "s" is not registered`). WithDetails(&control.WorkspaceLeaseRefusal{Kind: control.WorkspaceLeaseRefusal_IDENTITY, Identity: "unregistered"}) @@ -65,6 +69,37 @@ func (s *exitAssignmentStream) SubscribeAssignments(_ *control.SubscribeRequest, } } } + +func TestRestartedMovedSourceExits78WithoutAnOwnLine(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + refusal, err := status.New(codes.FailedPrecondition, "workspace moved to holder node-b at epoch 8"). + WithDetails(&control.WorkspaceLeaseRefusal{Kind: control.WorkspaceLeaseRefusal_MOVED}) + if err != nil { + t.Fatal(err) + } + h, _ := exitAuthorityHost(t, func(s *exitAssignmentStream) { s.streamRefuse = refusal.Err() }) + for { + if _, final := h.MasterWaitState(); final == "moved" { + break + } + select { + case <-ctx.Done(): + t.Fatal("the master's typed MOVED never reached the restarted source") + case <-time.After(time.Millisecond): + } + } + if h.Adapter().Projection().Epoch != 0 || h.IsCurrentReplicaSuperseded() { + t.Fatal("fixture acquired an own line or inferred supersession") + } + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, &exitStartupOutcome{expired: true}) { + t.Fatal("no startup decision") + } + if out := <-e.decision; out.code != 78 || out.reason != "moved" || out.detail != refusal.Message() { + t.Fatalf("moved restart chose %+v; want 78 moved, never retry 75", out) + } +} func exitAuthorityHost(t *testing.T, configure ...func(*exitAssignmentStream)) (*volume.Host, func(string, uint64)) { t.Helper() ln, err := net.Listen("tcp", "127.0.0.1:0") diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 808e5e2f58..9a5e3996fa 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -225,17 +225,19 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { } gap1PlannedStopDoesNotRestart(t, ws, unit, statusAddr, volume, after.Epoch, "r1", s["NRestarts"], s["InvocationID"]) gap1PrestartedTargetServesAfterMove(t, fixture, ws, remote, target, stem, filepath.Join(bin, "blockvolume"), args, root, volume, want) - gap1MovedSourceNeverServes(t, fixture, filepath.Join(bin, "blockvolume"), args, stem, statusAddr, volume) + moved, err := gap1ReadHead(t, remote) + if err != nil || moved.Holder != "s2/r1" { + t.Fatal("target did not claim the moved line", moved, err) + } + gap1MovedSourceNeverServes(t, fixture, filepath.Join(bin, "blockvolume"), args, stem, statusAddr, volume, moved.Epoch) } // gap1MovedSourceNeverServes is the negative case of the in-process wait: // after the volume moved to another host (and the new holder stopped), the // old source started again never serves and never adopts the line naming the -// other host. It has no lineage of its own from the master, so it exits 75 -// (retry: zero observed-own lineage selects retry, never a fence) rather than -// 78; the exit-78 refusal of a running holder that is moved is covered by -// the master-wait integration tests. -func gap1MovedSourceNeverServes(t *testing.T, fixture *gap1Fixture, exe string, args []string, stem, statusAddr, volume string) { +// other host. The master proves it was the issued move's source and returns +// typed MOVED even before any own assignment: exit 78, no restart loop. +func gap1MovedSourceNeverServes(t *testing.T, fixture *gap1Fixture, exe string, args []string, stem, statusAddr, volume string, epoch uint64) { t.Helper() // The simulated hosts share this kernel's per-host volume lock directory: // stop the new holder (the prestarted target) so the old source can open @@ -253,32 +255,30 @@ func gap1MovedSourceNeverServes(t *testing.T, fixture *gap1Fixture, exe string, switch s["ExecMainStatus"] { case "", "0": return false - case "75": + case "78": return true } - t.Fatalf("the moved-away source exited %s; want 75 (retry, no lineage of its own): %+v", s["ExecMainStatus"], s) + t.Fatalf("the moved-away source exited %s; want 78 moved, never retry 75: %+v", s["ExecMainStatus"], s) return false }) if gap1Operational(t, statusAddr, volume) { t.Fatal("the moved-away source served after its exit") } - // The exit must come from the move, not from an unassigned or - // disconnected timeout: the journal shows the source received the line - // naming the other host, refused it as another server's, and never adopted - // a lineage of its own. - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - journal, err := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=cat").CombinedOutput() - cancel() - if err != nil { - t.Fatalf("moved-away source journal: %v %s", err, journal) - } - for _, want := range []string{ - fmt.Sprintf("assignment identity refusal volume=%q replica=%q server=%q", volume, "r1", "s2"), - fmt.Sprintf("foreign assignment server=%q replica=%q recorded, not adopted", "s2", "r1"), - } { - if !strings.Contains(string(journal), want) { - t.Fatalf("the moved-away source's journal lacks %q: its exit is not proven to come from the move\n%s", want, journal) + // Observe beyond the shipped 5 s RestartSec. The prestarted target above + // is the opposite control: a genuine 75 was restarted by the same policy. + end := time.Now().Add(6 * time.Second) + for time.Now().Before(end) { + s := gap1Unit(t, unit) + if s["NRestarts"] != "0" || s["MainPID"] != "0" || s["ExecMainStatus"] != "78" { + t.Fatalf("moved source restarted or lost its terminal status: %+v", s) } + time.Sleep(100 * time.Millisecond) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + journal, err := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=cat").CombinedOutput() + if err != nil || !strings.Contains(string(journal), "status=78 reason=moved") || !strings.Contains(string(journal), fmt.Sprintf("holder s2 at epoch %d", epoch)) { + t.Fatalf("moved exit lacks the master's destination proof: %v %s", err, journal) } if strings.Contains(string(journal), "adopted as PRIMARY") { t.Fatalf("the moved-away source adopted a lineage:\n%s", journal) diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 3cf7c07e95..b66e6f8c22 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -328,6 +328,31 @@ func (p *Publisher) WorkspaceState(volume string) *WorkspaceState { return cloneWorkspace(p.workspace[volume]) } +// WorkspaceSourceMoved proves that a subscribing server was the source of an +// issued move and the current line now belongs to another known server. A new +// target with no prior line is not a moved source. This startup-only read takes +// the publisher lock; lease renewals keep their separate nonblocking view. +func (p *Publisher) WorkspaceSourceMoved(volume, replica, server string) (PublishedLine, bool) { + p.mu.Lock() + defer p.mu.Unlock() + if p.workspaceUncertain[volume] || server == "" { + return PublishedLine{}, false + } + line, found := p.PublishedAuthorityLine(volume) + owner, moved := line.Owner() + if !found || !moved || owner == "" || owner == server { + return PublishedLine{}, false + } + if s := p.workspace[volume]; s != nil { + for _, r := range s.Moves { + if r.Issued && r.OldHost == server && r.OldReplicaID == replica && r.OldEpoch < line.Epoch { + return line, true + } + } + } + return PublishedLine{}, false +} + func (p *Publisher) workspaceLineLocked(volume string) (subKey, assignmentState, bool) { var key subKey var line assignmentState diff --git a/seaweed-block/core/authority/workspace_source_moved_test.go b/seaweed-block/core/authority/workspace_source_moved_test.go new file mode 100644 index 0000000000..03a905a924 --- /dev/null +++ b/seaweed-block/core/authority/workspace_source_moved_test.go @@ -0,0 +1,38 @@ +package authority + +import "testing" + +// A known issued source is permanent only while another known server owns the +// current line. Unknown writes, a new waiting target, and a move back are not. +func TestWorkspaceSourceMovedProof(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*Publisher) + server, replica string + want bool + }{ + {"issued source", func(*Publisher) {}, "node-a", "r1", true}, + {"new waiting target", func(*Publisher) {}, "node-c", "r1", false}, + {"current target", func(*Publisher) {}, "node-b", "r1", false}, + {"wrong replica", func(*Publisher) {}, "node-a", "r2", false}, + {"no server", func(*Publisher) {}, "", "r1", false}, + {"uncertain", func(p *Publisher) { p.workspaceUncertain["v"] = true }, "node-a", "r1", false}, + {"reserved only", func(p *Publisher) { p.workspace["v"].Moves[0].Issued = false }, "node-a", "r1", false}, + {"no issued history", func(p *Publisher) { p.workspace["v"].Moves = nil }, "node-a", "r1", false}, + {"no line", func(p *Publisher) { delete(p.leaseViews, "v") }, "node-a", "r1", false}, + {"unknown owner", func(p *Publisher) { p.leaseViews["v"].d.issuedHost = "" }, "node-a", "r1", false}, + {"moved back", func(p *Publisher) { p.leaseViews["v"].d.issuedHost = "node-a" }, "node-a", "r1", false}, + {"line not newer", func(p *Publisher) { p.leaseViews["v"].d.epoch = 1 }, "node-a", "r1", false}, + } { + t.Run(tc.name, func(t *testing.T) { + p := NewPublisher(nil) + p.leaseViews["v"] = &leaseView{d: leaseDerived{bound: true, replica: "r1", epoch: 8, issuedHost: "node-b", ownerFromMove: true}} + p.workspace["v"] = &WorkspaceState{Moves: []WorkspaceMoveRecord{{Issued: true, OldHost: "node-a", OldReplicaID: "r1", OldEpoch: 1, NewHost: "node-b", NewEpoch: 8}}} + tc.edit(p) + line, moved := p.WorkspaceSourceMoved("v", tc.replica, tc.server) + if moved != tc.want || moved && (line.Epoch != 8 || line.IssuedHost != "node-b") { + t.Fatalf("line=%+v moved=%v; want %v", line, moved, tc.want) + } + }) + } +} diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index 1e3c82f6ac..45a3df563b 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -431,6 +431,10 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co if err := s.host.refuseWorkspaceHolderHost(ctx, "assignment stream", req.GetServerId()); err != nil { return identityRefusal(err) } + if line, moved := pub.WorkspaceSourceMoved(req.VolumeId, req.ReplicaId, req.ServerId); moved { + owner, _ := line.Owner() + return leaseRefusal(fmt.Sprintf("workspace moved to holder %s at epoch %d", owner, line.Epoch), control.WorkspaceLeaseRefusal_MOVED, 0) + } } type recv struct { diff --git a/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go b/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go index 7288dcb18b..3ca08c2168 100644 --- a/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go +++ b/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go @@ -70,6 +70,18 @@ func TestLeaseRefusalKinds(t *testing.T) { return &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: epoch, ServerId: server} } e1 := id("node-a", line.Epoch) + assignment := func(server string) error { + probeCtx, end := context.WithTimeout(ctx, 3*time.Second) + defer end() + stream, err := control.NewAssignmentServiceClient(conn).SubscribeAssignments(probeCtx, &control.SubscribeRequest{VolumeId: "v", ReplicaId: "r1", ServerId: server}) + if err == nil { + _, err = stream.Recv() + } + return err + } + if err := assignment("node-b"); err != nil { + t.Fatal("a prestarted target was mistaken for a moved source", err) + } if _, err := ws.RenewWorkspaceLease(ctx, e1); err != nil { t.Fatal("first grant:", err) } @@ -133,6 +145,10 @@ func TestLeaseRefusalKinds(t *testing.T) { if r == nil || r.GetKind() != control.WorkspaceLeaseRefusal_MOVED || text != "workspace lease: server identity does not match the current holder" { t.Fatalf("moved to another host: %q detail %v; want MOVED with the unchanged text", text, r) } + text, r = refusalOf(t, "restarted source assignment stream", assignment("node-a")) + if r == nil || r.GetKind() != control.WorkspaceLeaseRefusal_MOVED || !strings.Contains(text, "holder node-b at epoch ") { + t.Fatalf("restarted source did not receive destination-labelled MOVED: %q %v", text, r) + } // Move back to node-a: the stale node-a process at e2 is the same owner at // a newer epoch, so OTHER (no detail), never a false MOVED. @@ -140,6 +156,9 @@ func TestLeaseRefusalKinds(t *testing.T) { t.Fatal("grant to the moved host:", err) } e4 := id("node-a", cleanMove("move-back", e3, b)) + if err := assignment("node-a"); err != nil { + t.Fatal("a move back was rejected by historical source evidence", err) + } text, r = refusalOf(t, "moved and moved back", func() error { _, err := ws.RenewWorkspaceLease(ctx, e2); return err }()) if r != nil || text != "workspace lease: server identity does not match the current holder" { t.Fatalf("moved and moved back: %q detail %v; want the unchanged text, no detail", text, r) diff --git a/seaweed-block/core/host/master/workspace_moved_source_guard_test.go b/seaweed-block/core/host/master/workspace_moved_source_guard_test.go new file mode 100644 index 0000000000..37895cecdd --- /dev/null +++ b/seaweed-block/core/host/master/workspace_moved_source_guard_test.go @@ -0,0 +1,56 @@ +package master + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "slices" + "strings" + "testing" +) + +// This proof is only a startup stream refusal, never lease admission or a +// projection update. New readers must add their own causal probe here. +func TestMovedSourceProofCallers(t *testing.T) { + root := filepath.Join("..", "..", "..") + var sites []string + for _, top := range []string{"core", "cmd"} { + err := filepath.WalkDir(filepath.Join(root, top), func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { + return err + } + f, err := parser.ParseFile(token.NewFileSet(), p, nil, 0) + if err != nil { + return err + } + for _, decl := range f.Decls { + fn, ok := decl.(*ast.FuncDecl) + owner := "" + var scope ast.Node = decl + if ok { + if fn.Body == nil { + continue + } + owner, scope = fn.Name.Name, fn.Body + } + ast.Inspect(scope, func(n ast.Node) bool { + if s, ok := n.(*ast.SelectorExpr); ok && s.Sel.Name == "WorkspaceSourceMoved" { + rel, _ := filepath.Rel(root, p) + sites = append(sites, filepath.ToSlash(rel)+" "+owner) + } + return true + }) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + want := []string{"core/host/master/services.go SubscribeAssignments"} + if !slices.Equal(sites, want) { + t.Fatalf("moved-source readers changed: %v; each needs its own refusal/control probe", sites) + } +} diff --git a/seaweed-block/core/host/volume/master_wait.go b/seaweed-block/core/host/volume/master_wait.go index 69f8106fb8..5df85a8641 100644 --- a/seaweed-block/core/host/volume/master_wait.go +++ b/seaweed-block/core/host/volume/master_wait.go @@ -27,6 +27,7 @@ const masterWaitLogEvery = 10 * time.Minute // has no bound. type MasterWait struct { Reason string + Detail string // diagnostic text of a typed final refusal; never used as a guard Since time.Time Until time.Time } @@ -35,22 +36,23 @@ type MasterWait struct { // (heartbeat, assignment stream, lease renewal). It holds observations // only: no decision branches on it except the startup wait's end. type masterWait struct { - mu sync.Mutex - now func() time.Time - contact time.Time // start of the current contact streak; zero while none - last time.Time // the latest reply - down time.Time // first failure without a reply since the last contact - creds time.Time // first credentials refusal since the last accepted call - ident time.Time // first identity refusal since the last accepted call - identAt time.Time // the latest identity refusal - identOf string // its kind: unregistered or wrong_host - start time.Time // when the startup wait began (after the local open); zero before - window time.Time // the first reply at or after start in the current run of replies - barrier time.Time // T: request start + retry_after of the latest BARRIER refusal - final string // "moved" or "deleted": a permanent refusal - logged string // the reason last logged - loggedAt time.Time - logf func(string, ...any) + mu sync.Mutex + now func() time.Time + contact time.Time // start of the current contact streak; zero while none + last time.Time // the latest reply + down time.Time // first failure without a reply since the last contact + creds time.Time // first credentials refusal since the last accepted call + ident time.Time // first identity refusal since the last accepted call + identAt time.Time // the latest identity refusal + identOf string // its kind: unregistered or wrong_host + start time.Time // when the startup wait began (after the local open); zero before + window time.Time // the first reply at or after start in the current run of replies + barrier time.Time // T: request start + retry_after of the latest BARRIER refusal + final string // "moved" or "deleted": a permanent refusal + finalDetail string + logged string // the reason last logged + loggedAt time.Time + logf func(string, ...any) } func newMasterWait(now func() time.Time, logf func(string, ...any)) *masterWait { @@ -95,7 +97,8 @@ func masterCallClass(err error) (contact, credentials bool) { func (w *masterWait) call(err error) { contact, credentials := masterCallClass(err) identity := "" - if r := leaseRefusalDetail(err); r != nil && r.GetKind() == control.WorkspaceLeaseRefusal_IDENTITY { + r := leaseRefusalDetail(err) + if r != nil && r.GetKind() == control.WorkspaceLeaseRefusal_IDENTITY { contact, identity = false, r.GetIdentity() if identity == "" { identity = "unknown" @@ -104,6 +107,14 @@ func (w *masterWait) call(err error) { w.mu.Lock() defer w.mu.Unlock() now := w.now() + if r != nil && status.Code(err) == codes.FailedPrecondition { + switch r.GetKind() { + case control.WorkspaceLeaseRefusal_MOVED: + w.final, w.finalDetail = "moved", status.Convert(err).Message() + case control.WorkspaceLeaseRefusal_DELETED: + w.final, w.finalDetail = "deleted", status.Convert(err).Message() + } + } switch { case identity != "": w.endStreakLocked() @@ -191,10 +202,6 @@ func (w *masterWait) renewal(start time.Time, err error) { if t := start.Add(time.Duration(r.GetRetryAfterNs())); t.After(w.barrier) { w.barrier = t } - case control.WorkspaceLeaseRefusal_MOVED: - w.final = "moved" - case control.WorkspaceLeaseRefusal_DELETED: - w.final = "deleted" } } @@ -260,7 +267,7 @@ func (w *masterWait) snapshot(assigned bool) MasterWait { var out MasterWait switch { case w.final != "": - out = MasterWait{Reason: w.final, Since: now} + out = MasterWait{Reason: w.final, Detail: w.finalDetail, Since: now} case !w.creds.IsZero(): out = MasterWait{Reason: "credentials", Since: w.creds} case !w.ident.IsZero(): @@ -303,6 +310,13 @@ func (w *masterWait) snapshot(assigned bool) MasterWait { // permanent refusal of the lease ("moved" or "deleted"; "" when none). func (h *Host) MasterWaitState() (time.Time, string) { return h.mw.state() } +// MasterWaitDetail is diagnostic only; exit classification uses the typed kind. +func (h *Host) MasterWaitDetail() string { + h.mw.mu.Lock() + defer h.mw.mu.Unlock() + return h.mw.finalDetail +} + // MasterWaitStatus is why a workspace primary is not serving under a // grant, or nil when it holds one (or is not a workspace primary). func (h *Host) MasterWaitStatus() *MasterWait { diff --git a/seaweed-block/core/host/volume/master_wait_test.go b/seaweed-block/core/host/volume/master_wait_test.go index 48c6722d62..bea5c5745f 100644 --- a/seaweed-block/core/host/volume/master_wait_test.go +++ b/seaweed-block/core/host/volume/master_wait_test.go @@ -4,7 +4,11 @@ import ( "context" "errors" "fmt" + "go/ast" + "go/parser" + "go/token" "log" + "os" "strings" "sync" "testing" @@ -27,6 +31,72 @@ func refusalWith(t *testing.T, text string, kind control.WorkspaceLeaseRefusal_K return st.Err() } +func TestMovedAssignmentStreamIsFinalWithoutAnyOwnAssignment(t *testing.T) { + w := newMasterWait(nil, func(string, ...any) {}) + w.call(refusalWith(t, "workspace moved to holder node-b at epoch 8", control.WorkspaceLeaseRefusal_MOVED, 0)) + if _, final := w.state(); final != "moved" { + t.Fatalf("typed stream MOVED became %q; want final even without an own lineage", final) + } + if got := w.snapshot(false); got.Detail != "workspace moved to holder node-b at epoch 8" { + t.Fatal("moved status omitted the current holder and epoch", got) + } + w.call(status.Error(codes.Unavailable, "master unreachable")) + if _, final := w.state(); final != "moved" { + t.Fatal("transport failure erased the confirmed move", final) + } + unknown := newMasterWait(nil, func(string, ...any) {}) + unknown.call(status.Error(codes.Unavailable, "master unreachable")) + if _, final := unknown.state(); final != "" { + t.Fatal("unknown answer became permanent", final) + } + unknown.call(status.Error(codes.FailedPrecondition, "workspace moved to holder node-b at epoch 8")) + if _, final := unknown.state(); final != "" { + t.Fatal("diagnostic words without a typed proof became permanent", final) + } + transport, err := status.New(codes.Unavailable, "master unreachable").WithDetails(&control.WorkspaceLeaseRefusal{Kind: control.WorkspaceLeaseRefusal_MOVED}) + if err != nil { + t.Fatal(err) + } + unknown.call(transport.Err()) + if _, final := unknown.state(); final != "" { + t.Fatal("an unavailable result with a stale detail became permanent", final) + } +} + +// The typed final result has one writer and two readers. A new direct reader +// or writer must supply its own probe instead of silently adding a decision. +func TestMasterWaitFinalSites(t *testing.T) { + pkgs, err := parser.ParseDir(token.NewFileSet(), ".", func(f os.FileInfo) bool { + return strings.HasSuffix(f.Name(), ".go") && !strings.HasSuffix(f.Name(), "_test.go") + }, 0) + if err != nil { + t.Fatal(err) + } + sites := map[string]bool{} + for _, f := range pkgs["volume"].Files { + for _, d := range f.Decls { + fn, ok := d.(*ast.FuncDecl) + owner := "" + var scope ast.Node = d + if ok { + if fn.Body == nil { + continue + } + owner, scope = fn.Name.Name, fn.Body + } + ast.Inspect(scope, func(n ast.Node) bool { + if s, ok := n.(*ast.SelectorExpr); ok && s.Sel.Name == "final" { + sites[owner] = true + } + return true + }) + } + } + if len(sites) != 3 || !sites["call"] || !sites["state"] || !sites["snapshot"] { + t.Fatal("master-wait final sites changed; enumerate and probe each", sites) + } +} + // The startup wait's bound starts at the first answered contact, never // while the master gives no reply; a BARRIER moves it to T + 30 s; a // transport failure ends the streak (the next contact restarts it); @@ -196,10 +266,12 @@ func TestStatusShowsTheMasterWait(t *testing.T) { s := NewStatusServer(view) s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}}) since, until := time.Unix(1000, 0), time.Unix(1045, 0) - s.SetMasterWait(func() *MasterWait { return &MasterWait{Reason: "barrier", Since: since, Until: until} }) + s.SetMasterWait(func() *MasterWait { + return &MasterWait{Reason: "barrier", Since: since, Until: until, Detail: "diagnostic"} + }) got := s.statusProjection() if got.NotReadyReason != NotReadyLeaseNotHeld || got.MasterWait == nil || - *got.MasterWait != (MasterWaitStatus{Reason: "barrier", SinceMs: since.UnixMilli(), UntilMs: until.UnixMilli()}) { + *got.MasterWait != (MasterWaitStatus{Reason: "barrier", Detail: "diagnostic", SinceMs: since.UnixMilli(), UntilMs: until.UnixMilli()}) { t.Fatalf("status %q MasterWait %+v; want barrier since/until", got.NotReadyReason, got.MasterWait) } view.workspaceRequired = false @@ -260,8 +332,12 @@ type safeBuffer struct { b strings.Builder } -func (s *safeBuffer) Write(p []byte) (int, error) { s.mu.Lock(); defer s.mu.Unlock(); return s.b.Write(p) } -func (s *safeBuffer) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() } +func (s *safeBuffer) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} +func (s *safeBuffer) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() } // A flapping master (an answer, then no reply, every 10 s for 10 min) never // ends the wait early: each answer starts a new streak, so the bound is never diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index a811b9d247..4cacf73208 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -224,13 +224,15 @@ type StatusProjection struct { // credentials, "identity refused: " with kind unregistered or // wrong_host, barrier, no_assignment, refused, moved, deleted), since // when, and the startup wait's one bound or the master's barrier time - // (UntilMs, absent while there is no bound). + // (UntilMs, absent while there is no bound). Detail carries the master's + // diagnostic text for a typed final refusal, including a moved holder and epoch. MasterWait *MasterWaitStatus `json:",omitempty"` } // MasterWaitStatus is MasterWait on /status (unix milliseconds). type MasterWaitStatus struct { Reason string + Detail string `json:",omitempty"` SinceMs int64 UntilMs int64 `json:",omitempty"` } @@ -559,7 +561,7 @@ func (s *StatusServer) statusProjection() StatusProjection { p.NotReadyReason = NotReadyLeaseNotHeld if masterWait != nil { if w := masterWait(); w != nil { - p.MasterWait = &MasterWaitStatus{Reason: w.Reason, SinceMs: w.Since.UnixMilli()} + p.MasterWait = &MasterWaitStatus{Reason: w.Reason, Detail: w.Detail, SinceMs: w.Since.UnixMilli()} if !w.Until.IsZero() { p.MasterWait.UntilMs = w.Until.UnixMilli() } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index f1d606acc7..2d90feea50 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -188,7 +188,7 @@ a pre-issued publication. | Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node (the source itself only for a clean, non-force move), and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | | Expired | Granted | Same current primary server/replica/epoch, validated by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) with missing server refused, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-AUTH-HOLDER-IDENTITY-001` | -| Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait (`INV-WS-MASTER-WAIT-001`: 30 s of answered contact past the master's barrier time; no bound while the master gives no reply) or lease fence exits 75 after bounded cleanup; a typed MOVED or DELETED lease refusal exits 78 at once; a foreign master fact newer than nonzero observed-own lineage or exact foreign HEAD at or above the assigned epoch permits 78. Planned drain retires startup monitoring before cleanup; ACK and signal retain normal exit. Restart follows the unchanged grant and HEAD-claim gates. | `cmd/blockvolume/process_exit.go` `superviseProcess`, `watchChunkStartup`, `waitWorkspaceStop`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `INV-WS-STARTUP-RETRY-001` | +| Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait (`INV-WS-MASTER-WAIT-001`: 30 s of answered contact past the master's barrier time; no bound while the master gives no reply) or lease fence exits 75 after bounded cleanup; a typed master MOVED or DELETED refusal exits 78 at once (an issued moved source may be refused on subscription before any own assignment); a foreign master fact newer than nonzero observed-own lineage or exact foreign HEAD at or above the assigned epoch permits 78. Planned drain retires startup monitoring before cleanup; ACK and signal retain normal exit. Restart follows the unchanged grant and HEAD-claim gates. | `cmd/blockvolume/process_exit.go` `superviseProcess`, `watchChunkStartup`, `waitWorkspaceStop`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `INV-WS-STARTUP-RETRY-001` | | Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced @`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` | | none, Granted, Revoking or Expired | Deleting | the chunk volume delete is admitted with `WorkspaceHolderState` = never started or deleting (`TERM-LIVE-HOLDER-001`): HEAD, read by blockmaster before its locks, is below the line's epoch, or already past the fence (deleting, purging, deleted: the rerun of a delete that stopped midway); no move pending. From then on renewals, grants, re-grants, revocations and moves of the volume are refused; the delete's HEAD compare-and-swap to deleting is its linearization point: a claim applied before it makes the delete refuse `volume_in_use` and give the reservation back, a claim after it fails. The lifecycle `DeleteVolume` reads no HEAD and keeps the ACK rule | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence`; `core/frontend/chunkstore/volume_delete.go` (HEAD to deleting) | `INV-WS-DELETE-NO-LIVE-HOLDER-001`, `INV-WS-CLAIM-BEFORE-SERVE-001` | | Moved | epoch issued | the moved owner is captured with the assignment under pub.mu and persisted with the issuing move journal before publication; the stream uses that captured owner, empty when unknown, with placement fallback only for a move-less epoch; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/workspace_binding.go` `workspaceLineOwner`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` | @@ -837,10 +837,10 @@ Notes: | `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | | `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry after bounded cleanup. A master fact newer than nonzero observed-own, or an exact foreign HEAD at/above the assigned epoch, permits 78. ACK and signal keep normal exit; lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE | -| `INV-WS-MASTER-WAIT-001` | A workspace primary's startup wait has no bound while blockmaster gives no reply or refuses its credentials or identity; it ends 30 s after max(the first reply after the local open and recovery, the master's barrier time), and a typed MOVED or DELETED lease refusal ends it at once with 78. | M2 Awaiting assignment → Process exited | `core/host/volume/master_wait.go` `masterWait` (contact from heartbeat, stream and renewal results; the refusal kind from the status detail only); `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` (`ChunkMasterWait`); `cmd/blockvolume/process_exit.go` `chooseChunkStartupExit`; `core/host/master/workspace_service.go` `leaseRefusal`, `renewalMoved`; `core/authority/workspace_lease_view.go` `LeaseBarrierError`; `core/host/volume/workspace_lease.go` `renewDelay` (sleeps until just past the barrier time, jittered, at most 2 min; then a 200 ms poll for 5 s); `core/rpc/link/link.go` `MasterReconnect` | `TestChunkAuthorityWaitStartsAtFirstContact`, `TestLeaseGuardSleepsUntilTheBarrier`, `TestStatusShowsTheMasterWait`, `TestCredentialsRefusedForAnHourWaitsAndLogs`, `TestHeartbeatLogsTheMasterWait`, `TestFlappingMasterNeverExpiresEarly` (`core/host/volume/master_wait_test.go`); `TestMasterLinkReconnectsWithinTwoSeconds` (`core/host/volume/master_reconnect_test.go`); `TestChunkAuthorityWaitFollowsTheMasterWait`, `TestChunkAuthorityWaitPassesItsOwnStart`, `TestChunkGrantedAttachThatKeepsFailingIsBounded`, `TestChunkAuthorityWaitAttachesAGrantOnTheBoundsTick` (`core/frontend/durable/provider_master_wait_test.go`); `TestIdentityRefusalWaitsVisibly`, `TestChunkAuthorityWaitAfterASlowOpenGetsItsFullLimit`, `TestIdentityRefusalEndsAndDecays` (`core/host/volume/master_wait_test.go`); `TestIdentityRefusalEndsOnADeliveredAssignment` (`cmd/blockvolume/process_exit_authority_test.go`); `TestIdentityRefusalIsTyped` (`core/host/master/workspace_lease_refusal_kind_test.go`); `TestLeaseRefusalKinds`, `TestRenewalReplicaMismatchAtOlderLineEpochIsOther` (`core/host/master/workspace_lease_refusal_kind_test.go`); `TestChunkStartupExitFinalGives78` (`cmd/blockvolume/process_exit_authority_test.go`) | — | ACTIVE | +| `INV-WS-MASTER-WAIT-001` | Startup waits without a bound while the master gives no reply or refuses credentials or identity; after contact it ends 30 s beyond the later of recovery's first reply or the master barrier. Typed MOVED or DELETED ends it with 78, including a confirmed moved source without an own assignment. | M2 Awaiting assignment → Process exited | `core/host/volume/master_wait.go` `masterWait` (contact from heartbeat, stream and renewal results; the refusal kind from the status detail only); `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` (`ChunkMasterWait`); `cmd/blockvolume/process_exit.go` `chooseChunkStartupExit`; `core/host/master/workspace_service.go` `leaseRefusal`, `renewalMoved`; `core/authority/workspace.go` `WorkspaceSourceMoved`; `core/host/master/services.go` `SubscribeAssignments`; `core/authority/workspace_lease_view.go` `LeaseBarrierError`; `core/host/volume/workspace_lease.go` `renewDelay` (sleeps until just past the barrier time, jittered, at most 2 min; then a 200 ms poll for 5 s); `core/rpc/link/link.go` `MasterReconnect` | `TestChunkAuthorityWaitStartsAtFirstContact`, `TestLeaseGuardSleepsUntilTheBarrier`, `TestStatusShowsTheMasterWait`, `TestCredentialsRefusedForAnHourWaitsAndLogs`, `TestHeartbeatLogsTheMasterWait`, `TestFlappingMasterNeverExpiresEarly` (`core/host/volume/master_wait_test.go`); `TestMasterLinkReconnectsWithinTwoSeconds` (`core/host/volume/master_reconnect_test.go`); `TestChunkAuthorityWaitFollowsTheMasterWait`, `TestChunkAuthorityWaitPassesItsOwnStart`, `TestChunkGrantedAttachThatKeepsFailingIsBounded`, `TestChunkAuthorityWaitAttachesAGrantOnTheBoundsTick` (`core/frontend/durable/provider_master_wait_test.go`); `TestIdentityRefusalWaitsVisibly`, `TestChunkAuthorityWaitAfterASlowOpenGetsItsFullLimit`, `TestIdentityRefusalEndsAndDecays` (`core/host/volume/master_wait_test.go`); `TestIdentityRefusalEndsOnADeliveredAssignment` (`cmd/blockvolume/process_exit_authority_test.go`); `TestIdentityRefusalIsTyped` (`core/host/master/workspace_lease_refusal_kind_test.go`); `TestLeaseRefusalKinds`, `TestRenewalReplicaMismatchAtOlderLineEpochIsOther` (`core/host/master/workspace_lease_refusal_kind_test.go`); `TestChunkStartupExitFinalGives78`, `TestRestartedMovedSourceExits78WithoutAnOwnLine` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceSourceMovedProof`, `TestMovedSourceProofCallers`, `TestMasterWaitFinalSites`, `TestMovedAssignmentStreamIsFinalWithoutAnyOwnAssignment` | Real systemd moved-source and prestarted-target controls remain qualification gates. | ACTIVE | - `INV-WS-DELETE-NO-LIVE-HOLDER-001`: the verdict is the first admission's only. A rerun of a delete whose token already holds the reservation (or a committed one) is admitted without a new verdict and goes on to the catalog step, whose HEAD compare-and-swap is the fence: a HEAD a holder claimed in between is refused there and the reservation given back, so an interrupted delete strands neither the volume nor its id. A reservation may hold several tokens (one per delete request); a new token on an admitted reservation is decided by the verdict; on a committed one it skips the verdict too (committed only once the HEAD is being purged, so no holder can claim it). The HEAD read before the lock still runs for a rerun, and its result is then unused: it is kept outside the workspace lock on purpose. Availability window: a delete admitted for a never-started line that stops before it marks HEAD leaves the volume reserved for deletion; if the holder then claims HEAD, the volume cannot be used until that delete is re-run (the catalog step then refuses the live HEAD and gives the reservation back). Re-run an interrupted delete. -- `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process. +- `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75 unless the master proves this server was an issued move's source and returns typed MOVED), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process. - `INV-WS-MASTER-WAIT-001`: every reply produced by blockmaster's handler starts or continues a contact streak; a transport failure (`Unavailable`, `DeadlineExceeded`, `Canceled`) ends it. So a master that answers and drops in turn postpones the 30 s bound for as long as it flaps, also for an obsolete unit; it never ends the wait early (`TestFlappingMasterNeverExpiresEarly`). The barrier time travels as a duration the master computes from the same two predicates as admission, added by the volume to its own monotonic request start; the master re-checks the barrier on every re-grant, so a wrong duration only moves the 75 exit. The status codes alone still mean retry 75 (`INV-WS-STARTUP-RETRY-001`); only the typed `WorkspaceLeaseRefusal` detail (MOVED, DELETED) permits the early 78. Scale: after a master restart every lapsed volume has the same barrier time T and the master grants them one at a time, each grant one store write W under the publisher lock, so the last of N volumes is granted about T + 0.1 s + N x W; a volume whose grant comes 30 s past T exits 75 and is started again, so that starts at N >= 30 s / W. Measured: W p50 1.03 ms, p99 2.33 ms, max 14.5 ms (400 writes of the file authority store on an NVMe ext4 disk, `TestWorkspaceGrantStoreWriteTime`), so 200 volumes about T + 0.6 s and the 30 s point near 12,900 volumes (p99); 20 real volume processes served at most 0.81 s after T (`TestManyVolumesServeTogetherAfterMasterRestart`). The bound holds for that store device: on a device whose flushes stall (an fsync held for seconds), one stalled write puts every waiting volume behind it, so the blockmaster store's device is a deployment premise of serving within 2 s of the barrier. A granted process whose attach keeps failing (the chunk store unreachable) retries inside the same bound and then exits 75: it does not hold the lease while never serving. An identity refusal has no bound until an identity-checked call (a renewal, a delivered assignment) is accepted, or until 30 s of replies pass with no new identity refusal; the window then opens again. A serving holder that starts getting identity refusals is outside this row: its lease expires and it fences and exits 75 (`lease_expired`). - Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former; fencing compares the latter. Both use `IsSuperseded` with explicit lineage; zero lineage selects retry75 and no fence; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages`, `TestWorkspaceExitLineageIncludesBlockedOwnAssignment`, and `TestWorkspaceObservedLineageNeverTrailsAdoption` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal. - Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with a foreign master line newer than nonzero observed-own; absent proof means retry 75. diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 392f53b3ac..7787d282e7 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -37,8 +37,9 @@ The volume's authority and health projection. Go type `volume.StatusProjection`. | `CatchUp.ElapsedMs` | int64 | ElapsedMs is the time since this replica was admitted as a supporting replica at its current epoch. | | `CatchUp.LagLSN` | uint64 | LagLSN is the engine's H-R (primary head minus this replica's durable frontier) as last observed; 0 when unknown or caught up. | | `Warnings[]` | string | Warnings include routing disagreements and typed recovery warnings (e.g. wal_hole_suspected, issue #51). Visible, not an alert: they do not change Healthy or the frontend's readiness. (omitted when empty) | -| `MasterWait` | object | MasterWait is why a workspace primary holds no granted lease, present only while NotReadyReason is lease_not_held: Reason (unreachable, credentials, "identity refused: " with kind unregistered or wrong_host, barrier, no_assignment, refused, moved, deleted), since when, and the startup wait's one bound or the master's barrier time (UntilMs, absent while there is no bound). (omitted when empty) | +| `MasterWait` | object | MasterWait is why a workspace primary holds no granted lease, present only while NotReadyReason is lease_not_held: Reason (unreachable, credentials, "identity refused: " with kind unregistered or wrong_host, barrier, no_assignment, refused, moved, deleted), since when, and the startup wait's one bound or the master's barrier time (UntilMs, absent while there is no bound). Detail carries the master's diagnostic text for a typed final refusal, including a moved holder and epoch. (omitted when empty) | | `MasterWait.Reason` | string | — | +| `MasterWait.Detail` | string | — (omitted when empty) | | `MasterWait.SinceMs` | int64 | — | | `MasterWait.UntilMs` | int64 | — (omitted when empty) |