From b06394581513b604976ea7c624463d5e6ca44e89 Mon Sep 17 00:00:00 2001 From: Ping Qiu Date: Sun, 6 Dec 2026 05:49:50 -0800 Subject: [PATCH] seaweed-block: a holder whose first heartbeats are refused serves once answered, without a restart (#13523) * seaweed-block: test: a holder whose first heartbeats are refused past the bound serves once answered (red) A master that refuses the holder's first heartbeats for longer than firstHeartbeatWait (its store failing over: Unavailable) and then answers leaves the holder fenced for good: the lease runtime installs its guard fenced at the bound and nothing un-fences it, so the holder never renews or serves without a restart. v1.1.1 retried. Red on master: no renewal and no serving after the answer. Twin: the assignment moved meanwhile; the renewal after the late answer is refused as moved and the holder never serves. Co-Authored-By: Claude Opus 5.5 * seaweed-block: an unanswered first heartbeat waits unserved instead of fencing the holder for good The lease runtime installed its guard fenced once firstHeartbeatWait (one lease validity) passed without an answered first heartbeat, and nothing un-fenced it: a master that refused the holder's heartbeats for 30 s (its store failing over, an ingest error, a re-registration race) left the host unserved until a restart. v1.1.1 retried. Now no guard is installed while the first heartbeat is unanswered: the view stays gated (no renewal, no serving), as before the bound. Past the bound the wait is the typed master-wait reason first_heartbeat_unanswered in /status and the journal. When the master answers this process's own first heartbeat (its incarnation), the guard is installed normally and serving still needs a granted renewal, which refuses an assignment that moved meanwhile. No new guard state; the fenced guard still never reopens. Co-Authored-By: Claude Opus 5.5 * seaweed-block: test: an answered first heartbeat ends the unanswered wait reason A renewal refused after the late answer (a busy store, not a final refusal) must not still be reported as first_heartbeat_unanswered. Mutants: fencing at the bound, installing at the bound without an answer, dropping the typed reason and never clearing it each fail a test. Co-Authored-By: Claude Opus 5.5 * seaweed-block: the unanswered first-heartbeat reason ranks after unreachable Review: a master that gives no reply at all is unreachable; the overdue first-heartbeat wait is named only while the master replies but has not answered this process's first heartbeat. Unit row for both, and the runtime tests now refuse with a reply (an ingest error) where they check the reason. Mutant: the old order fails the unit row. Co-Authored-By: Claude Opus 5.5 * seaweed-block: the unanswered first-heartbeat reason reports the startup wait's bound Review: refused heartbeats that are replies (an ingest error) open the chunk startup wait's contact window, whose bound still applies; the first_heartbeat_unanswered reason now reports it as Until instead of logging no bound. The startup policy is unchanged; the claim of no bound, fence or exit is scoped to the lease runtime. The pre-answer test loop is bounded, and a test comment is narrowed to what it checks. Co-Authored-By: Claude Opus 5.5 * seaweed-block: test: read the projection before the server state in the pre-answer loop Review: the loop sampled an unanswered server state and then read the projection; the master could answer and grant in between, and a correct recovery failed the test. The projection is now read first: if the server state read after it is still unanswered, the projection was read before any answer and must not serve. Test only. Co-Authored-By: Claude Opus 5.5 * seaweed-block: test: the refusal tests answer the master explicitly, after the bound Review: with a fixed count of refused heartbeats the heartbeat loop could finish them and be answered before the test looked, so the unanswered reason could appear and clear unseen. The three refusal tests now refuse every heartbeat until the test answers: the serving test and the moved twin after three bounds of checks that nothing renews or serves (the projection read before the server state), the reason test only after it has seen first_heartbeat_unanswered. Test only. Co-Authored-By: Claude Opus 5.5 * seaweed-block: test: the refusal helper counts its bounds from the runtime's own wait start Review: refuseThenAnswer measured three bounds from its own entry, so a lease runtime that started late could get its answer before crossing its bound, and the old fence-at-bound code would pass the serving test. The rig now records the runtime's wait start through firstHeartbeatWaitStarted (chained after any hook the test installed); the helper waits for it (bounded, 5 s) and withholds answers until three bounds past it, keeping its no-renewal/no-serving checks. Fence-at-bound fails the serving test and the moved twin. Test only. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- seaweed-block/core/host/volume/master_wait.go | 21 +- .../core/host/volume/master_wait_test.go | 32 ++ .../volume/workspace_first_heartbeat_test.go | 277 ++++++++++++++++-- .../core/host/volume/workspace_runtime.go | 27 +- .../host/volume/workspace_runtime_test.go | 9 +- seaweed-block/docs/design/invariants.md | 7 +- 6 files changed, 329 insertions(+), 44 deletions(-) diff --git a/seaweed-block/core/host/volume/master_wait.go b/seaweed-block/core/host/volume/master_wait.go index 476ac2daa1..bd1d2aa050 100644 --- a/seaweed-block/core/host/volume/master_wait.go +++ b/seaweed-block/core/host/volume/master_wait.go @@ -22,7 +22,9 @@ const masterWaitLogEvery = 10 * time.Minute // MasterWait is why a workspace primary is not yet granted, for /status. // Reason is unreachable (no reply), credentials (the master refused the -// node's credentials), barrier (Until is the master's barrier time), +// node's credentials), first_heartbeat_unanswered (assigned, but the master +// has not answered this process's first heartbeat within one lease +// validity; Until is the startup wait's bound when it has one), barrier (Until is the master's barrier time), // no_assignment, refused, moved or deleted. Until is zero while the wait // has no bound. type MasterWait struct { @@ -48,6 +50,7 @@ type masterWait struct { 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 + firstHB time.Time // start of a first-heartbeat wait past its bound; zero when none final string // "moved" or "deleted": a permanent refusal finalDetail string logged string // the reason last logged @@ -149,6 +152,17 @@ func (w *masterWait) call(err error) { } } +// firstHeartbeatOverdue records that the lease runtime has waited past its +// bound for the master to answer this process's first heartbeat, since the +// wait began at since; zero clears it (the heartbeat was answered). An +// observation only: it names the wait, and changes no bound or decision (the +// startup wait's bound, when it has one, is reported with it). +func (w *masterWait) firstHeartbeatOverdue(since time.Time) { + w.mu.Lock() + defer w.mu.Unlock() + w.firstHB = since +} + // identityDecay ends an identity refusal that is not repeated: replies keep // coming and no call was refused on identity for this long. const identityDecay = 30 * time.Second @@ -279,6 +293,11 @@ func (w *masterWait) snapshot(assigned bool) MasterWait { if w.down.IsZero() { out.Since = now } + case !w.firstHB.IsZero(): + // The master replies, but has not answered this process's first + // heartbeat (a master that gives no reply at all is unreachable). The + // startup wait's bound, when it has one, still applies and is shown. + out = MasterWait{Reason: "first_heartbeat_unanswered", Since: w.firstHB, Until: w.deadlineLocked()} case w.barrier.After(now): out = MasterWait{Reason: "barrier", Since: w.contact, Until: w.barrier} case w.window.IsZero(): diff --git a/seaweed-block/core/host/volume/master_wait_test.go b/seaweed-block/core/host/volume/master_wait_test.go index 17abd90af2..2e9cb7d05d 100644 --- a/seaweed-block/core/host/volume/master_wait_test.go +++ b/seaweed-block/core/host/volume/master_wait_test.go @@ -485,3 +485,35 @@ func TestRecordedRevocationFinalRequiresTypedFailedPrecondition(t *testing.T) { t.Fatal("log text became a terminal verdict") } } + +// The overdue first-heartbeat wait is named only while the master replies: a +// master that gives no reply at all is unreachable, overdue wait or not. It +// reports the startup wait's bound, which still runs on refused heartbeats. +func TestTheUnansweredFirstHeartbeatReasonNeedsAReplyingMaster(t *testing.T) { + now := time.Date(2026, 12, 6, 12, 0, 0, 0, time.UTC) + w := newMasterWait(func() time.Time { return now }, func(string, ...any) {}) + start := now.Add(-40 * time.Second) + w.firstHeartbeatOverdue(start) + w.call(status.Error(codes.Unavailable, "master down")) + if got := w.snapshot(true); got.Reason != "unreachable" { + t.Fatalf("a master that gives no reply: reason %q, want unreachable", got.Reason) + } + if got := w.snapshot(true); !got.Until.IsZero() { + t.Fatalf("no reply yet: the startup wait has no bound, got until %s", got.Until) + } + w.begin(now.Add(-time.Second)) // the startup wait began; its window opens at the first reply after it + w.call(status.Error(codes.Internal, "ingest error")) + got := w.snapshot(true) + if got.Reason != "first_heartbeat_unanswered" || !got.Since.Equal(start) { + t.Fatalf("a replying master that refuses the first heartbeat: %+v, want first_heartbeat_unanswered since %s", got, start) + } + // A refused heartbeat is still a reply: the startup wait's bound runs, and + // the reason reports it rather than claiming none. + if want := now.Add(MasterWaitLimit); !got.Until.Equal(want) { + t.Fatalf("the overdue first-heartbeat wait reports until %s, want the startup wait's bound %s", got.Until, want) + } + w.firstHeartbeatOverdue(time.Time{}) + if got := w.snapshot(true); got.Reason == "first_heartbeat_unanswered" { + t.Fatalf("after the answer the reason is still %q", got.Reason) + } +} diff --git a/seaweed-block/core/host/volume/workspace_first_heartbeat_test.go b/seaweed-block/core/host/volume/workspace_first_heartbeat_test.go index 2857be1e61..853bcd088c 100644 --- a/seaweed-block/core/host/volume/workspace_first_heartbeat_test.go +++ b/seaweed-block/core/host/volume/workspace_first_heartbeat_test.go @@ -17,6 +17,8 @@ import ( control "github.com/seaweedfs/seaweed-block/core/rpc/control" "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // orderServer is a master's two holder-facing services on one listener: it @@ -210,16 +212,15 @@ func TestAHolderRenewsOnlyAfterItsFirstHeartbeatWithItsIncarnation(t *testing.T) } // A holder whose first heartbeat is never answered does not renew and does -// not serve: the lease runtime waits the configured bound (one lease -// validity; shortened here), no less and not much more, then installs its -// guard fenced and returns. The wait is measured from its own start (a test -// hook), to its return; the tolerance covers the runtime's 50 ms poll and -// the fenced guard's install and drain. -func TestAHolderWhoseHeartbeatIsNeverAnsweredFencesRatherThanServes(t *testing.T) { +// not serve, and keeps waiting: no guard is installed, so nothing fences it +// for good. Past the bound (one lease validity; shortened here), no sooner +// and not much later, /status names the wait first_heartbeat_unanswered. +// The wait is measured from its own start (a test hook); the tolerance covers +// the runtime's 50 ms poll. +func TestAHolderWhoseHeartbeatIsNeverAnsweredWaitsUnservedWithATypedReason(t *testing.T) { const bound, tolerance = 300 * time.Millisecond, 500 * time.Millisecond previous, previousHook := firstHeartbeatWait, firstHeartbeatWaitStarted waitStarted := make(chan time.Time, 1) - firstHeartbeatWait = bound firstHeartbeatWaitStarted = func(at time.Time) { select { case waitStarted <- at: @@ -227,38 +228,258 @@ func TestAHolderWhoseHeartbeatIsNeverAnsweredFencesRatherThanServes(t *testing.T } } t.Cleanup(func() { firstHeartbeatWait, firstHeartbeatWaitStarted = previous, previousHook }) - s := newOrderServer() // never released - h, _, done := firstHeartbeatRig(t, s) - select { - case <-s.entered: - case <-time.After(5 * time.Second): - t.Fatal("the holder's first heartbeat never reached the master") - } + // The master replies, refusing every heartbeat (an ingest error), until told. + s := &refusingServer{refuse: 1 << 30, code: codes.Internal} + h, done := refusingRigDone(t, s, bound) var start time.Time select { case start = <-waitStarted: case <-time.After(5 * time.Second): t.Fatal("the lease runtime never started waiting for the first answered heartbeat") } - select { // suite protection only; the bound is checked below - case <-done: - case <-time.After(5 * time.Second): - t.Fatal("the lease runtime kept waiting past the bound instead of fencing") + overdue := func() bool { + w := h.MasterWaitStatus() + return w != nil && w.Reason == "first_heartbeat_unanswered" } - switch waited := time.Since(start); { - case waited < bound: - t.Fatalf("the lease runtime fenced after %s, before its %s bound", waited, bound) - case waited > bound+tolerance: - t.Fatalf("the lease runtime fenced after %s, past its %s bound plus %s", waited, bound, tolerance) + for !overdue() { + if time.Since(start) > bound+tolerance { + t.Fatalf("no first_heartbeat_unanswered wait reason %s after the wait began (bound %s): %+v", time.Since(start), bound, h.MasterWaitStatus()) + } + time.Sleep(time.Millisecond) + } + if waited := time.Since(start); waited < bound { + t.Fatalf("the wait was reported overdue after %s, before its %s bound", waited, bound) + } + if w := h.MasterWaitStatus(); !w.Since.Equal(start) { + t.Fatalf("the overdue wait reports since %s, want the wait's start %s", w.Since, start) + } + time.Sleep(2 * bound) // well past the bound: still waiting, nothing installed + select { + case <-done: + t.Fatal("the lease runtime returned instead of waiting for the first answered heartbeat") + default: + } + if g := h.view.workspaceGuard.Load(); g != nil { + t.Fatalf("a guard was installed before the first heartbeat was answered: %v", g.FenceCause()) } if s.renewed() { - t.Fatalf("a holder with no answered heartbeat renewed: %v", s.snapshot()) - } - guard := h.view.workspaceGuard.Load() - if guard == nil || !strings.Contains(guard.FenceCause(), "no heartbeat of this process answered within "+bound.String()) { - t.Fatalf("the guard was not installed fenced with the unanswered-heartbeat cause and its bound: %v", guard) + t.Fatal("a holder with no answered heartbeat renewed") } if h.ProjectionView().Projection().Healthy { t.Fatal("a holder with no answered heartbeat serves") } + s.answerFromNow() // answered late: the guard is installed and renews, without a restart + runtimeAwait(t, "a renewal after the late answer", s.renewed) + if overdue() { + t.Fatal("the wait reason stays first_heartbeat_unanswered after the answer") + } +} + +// refusingServer is a master that refuses a holder's first refuse heartbeats +// with code (default Unavailable: its store slow or failing over; Internal: +// an ingest error, which is a reply) and answers the later ones. A renewal is granted, or refused as moved when moved is set +// (the assignment moved while the heartbeats were refused), or refused with +// renewErr when set. +type refusingServer struct { + control.UnimplementedObservationServiceServer + control.UnimplementedWorkspaceServiceServer + refuse int + code codes.Code + // waitStarted receives when the lease runtime began waiting for the first + // answered heartbeat (the rig's firstHeartbeatWaitStarted hook). + waitStarted chan time.Time + moved bool + renewErr error + mu sync.Mutex + beats int + answered time.Time + renewals int +} + +func (s *refusingServer) ReportHeartbeat(context.Context, *control.HeartbeatReport) (*control.HeartbeatAck, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.beats++ + if s.beats <= s.refuse { + code := s.code + if code == codes.OK { + code = codes.Unavailable + } + return nil, status.Error(code, "master refuses the heartbeat") + } + if s.answered.IsZero() { + s.answered = time.Now() + } + return &control.HeartbeatAck{}, nil +} + +func (s *refusingServer) RenewWorkspaceLease(_ context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) { + s.mu.Lock() + s.renewals++ + moved, renewErr := s.moved, s.renewErr + s.mu.Unlock() + if renewErr != nil { + return nil, renewErr + } + if moved { + st, err := status.New(codes.FailedPrecondition, "workspace moved to holder node-b at epoch 4").WithDetails(&control.WorkspaceLeaseRefusal{Kind: control.WorkspaceLeaseRefusal_MOVED}) + if err != nil { + return nil, err + } + return nil, st.Err() + } + ttl := 5 * time.Second + return &control.WorkspaceLeaseFact{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, Epoch: id.Epoch, ValidForNs: int64(ttl), ExpiresAtNs: time.Now().Add(ttl).UnixNano()}, nil +} + +// answerFromNow makes the master answer every later heartbeat. +func (s *refusingServer) answerFromNow() { + s.mu.Lock() + s.refuse = s.beats + s.mu.Unlock() +} + +func (s *refusingServer) renewed() bool { _, n := s.state(); return n > 0 } + +func (s *refusingServer) state() (answered time.Time, renewals int) { + s.mu.Lock() + defer s.mu.Unlock() + return s.answered, s.renewals +} + +// refuseThenAnswer waits (bounded) for the lease runtime to report the start +// of its first-heartbeat wait, then lets s refuse every heartbeat until three +// bounds past that start, checking that the holder neither renews nor serves +// (the projection is read before the server state, which cannot change: +// nothing is answered yet), then makes s answer from now on. The answer comes +// after the runtime's own bound, whenever the runtime started. +func refuseThenAnswer(t *testing.T, h *Host, s *refusingServer, bound time.Duration) { + t.Helper() + var start time.Time + select { + case start = <-s.waitStarted: + case <-time.After(5 * time.Second): + t.Fatal("the lease runtime never started waiting for the first answered heartbeat") + } + for end := start.Add(3 * bound); time.Now().Before(end); time.Sleep(time.Millisecond) { + healthy := h.ProjectionView().Projection().Healthy + if answered, renewals := s.state(); !answered.IsZero() || renewals > 0 || healthy { + t.Fatalf("before any answer: answered=%v renewals=%d healthy=%v", !answered.IsZero(), renewals, healthy) + } + } + s.answerFromNow() +} + +// refusingRig starts an assigned holder (epoch 3) with a 20 ms heartbeat +// against s, its first-heartbeat bound shortened to bound, and its lease +// runtime. Cleanup cancels the runtime and joins it before teardown. +func refusingRig(t *testing.T, s *refusingServer, bound time.Duration) *Host { + t.Helper() + h, _ := refusingRigDone(t, s, bound) + return h +} + +// refusingRigDone is refusingRig, also returning the lease runtime's done. +func refusingRigDone(t *testing.T, s *refusingServer, bound time.Duration) (*Host, <-chan struct{}) { + t.Helper() + previous := firstHeartbeatWait + firstHeartbeatWait = bound + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + control.RegisterObservationServiceServer(srv, s) + control.RegisterWorkspaceServiceServer(srv, s) + go srv.Serve(ln) + t.Cleanup(srv.Stop) + t.Cleanup(func() { firstHeartbeatWait = previous }) + // Record the runtime's wait start for refuseThenAnswer, after any hook the + // test installed (both are told). + s.waitStarted = make(chan time.Time, 1) + previousHook := firstHeartbeatWaitStarted + firstHeartbeatWaitStarted = func(at time.Time) { + if previousHook != nil { + previousHook(at) + } + select { + case s.waitStarted <- at: + default: + } + } + t.Cleanup(func() { firstHeartbeatWaitStarted = previousHook }) + h := workspaceRuntimeHostEvery(t, ln.Addr().String(), true, 20*time.Millisecond) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + h.Start() + go func() { + defer close(done) + _ = h.RunWorkspaceLease(ctx, func(context.Context, *control.WorkspaceIdentity) (uint64, error) { return 0, nil }) + }() + t.Cleanup(func() { + cancel() + joinOrFailStop(done, 10*time.Second) + }) + return h, done +} + +// A holder whose first heartbeats are refused for longer than the bound (the +// master's store failing over) neither renews nor serves while they are +// refused, and serves once this process's own heartbeat is answered and a +// renewal is granted: no restart. (v1.1.2 rc: the guard was installed fenced +// at the bound, for good.) +func TestAHolderWhoseFirstHeartbeatsAreRefusedPastTheBoundServesOnceAnswered(t *testing.T) { + const bound = 100 * time.Millisecond + s := &refusingServer{refuse: 1 << 30} // Unavailable until told + h := refusingRig(t, s, bound) + refuseThenAnswer(t, h, s, bound) + runtimeAwait(t, "serving after the first answered heartbeat and a granted renewal", func() bool { + return h.ProjectionView().Projection().Healthy + }) + if _, renewals := s.state(); renewals == 0 { + t.Fatal("the holder serves without a granted renewal") + } + if g := h.view.workspaceGuard.Load(); g == nil || g.FenceCause() != "" { + t.Fatalf("the serving holder's guard is missing or fenced: %v", g) + } +} + +// Twin: the assignment moves while the first heartbeats are refused. The +// late answer leads to a renewal, which the master refuses as moved: the +// holder never serves. +func TestAHolderWhoseAssignmentMovedWhileItsFirstHeartbeatsWereRefusedNeverServes(t *testing.T) { + const bound = 100 * time.Millisecond + s := &refusingServer{refuse: 1 << 30, moved: true} + h := refusingRig(t, s, bound) + refuseThenAnswer(t, h, s, bound) + runtimeAwait(t, "a renewal after the late answer", func() bool { _, n := s.state(); return n > 0 }) + end := time.Now().Add(time.Second) + for time.Now().Before(end) { + if h.ProjectionView().Projection().Healthy { + t.Fatal("a holder whose assignment moved serves after its late first heartbeat answer") + } + time.Sleep(5 * time.Millisecond) + } +} + +// Once this process's first heartbeat is answered, the wait is no longer +// named first_heartbeat_unanswered, also while the renewal that follows is +// refused (a busy store, not a final refusal). The renewal counter shows the +// renewal reached the master; the check is only that the old reason is gone. +func TestAnAnsweredFirstHeartbeatEndsTheUnansweredWaitReason(t *testing.T) { + const bound = 100 * time.Millisecond + s := &refusingServer{refuse: 1 << 30, code: codes.Internal, renewErr: status.Error(codes.Aborted, "master store busy")} + h := refusingRig(t, s, bound) + runtimeAwait(t, "first_heartbeat_unanswered while the heartbeats are refused past the bound", func() bool { + w := h.MasterWaitStatus() + return w != nil && w.Reason == "first_heartbeat_unanswered" + }) + s.answerFromNow() // only after the reason was seen + runtimeAwait(t, "a renewal after the late answer", func() bool { _, n := s.state(); return n > 0 }) + if w := h.MasterWaitStatus(); w == nil || w.Reason == "first_heartbeat_unanswered" { + t.Fatalf("after the answer the wait reason is %+v, want it no longer first_heartbeat_unanswered", w) + } + if h.ProjectionView().Projection().Healthy { + t.Fatal("a holder whose renewal was refused serves") + } } diff --git a/seaweed-block/core/host/volume/workspace_runtime.go b/seaweed-block/core/host/volume/workspace_runtime.go index 04aaa08d85..756d00e4b0 100644 --- a/seaweed-block/core/host/volume/workspace_runtime.go +++ b/seaweed-block/core/host/volume/workspace_runtime.go @@ -32,10 +32,13 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context, return err } p := h.view.Projection() - // The first renewal waits for this process's first answered heartbeat, - // at most one lease validity: past that the guard is installed fenced - // (no renewal, no serving) rather than waiting for ever. - unanswered := "" + // The first renewal waits for this process's first answered heartbeat: + // before it the master holds only a predecessor's report. No guard is + // installed while it waits, so the view stays gated (no renewal, no + // serving). Past one lease validity the wait is a typed master-wait + // reason; it is not a fence, so a later answer (the master's store + // back, the host re-registered) still installs the guard without a + // restart. if p.Epoch > 0 && !h.firstHeartbeatAnswered() { if heartbeatWaitStart.IsZero() { heartbeatWaitStart = time.Now() @@ -44,10 +47,11 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context, } } if time.Since(heartbeatWaitStart) >= firstHeartbeatWait { - unanswered = fmt.Sprintf("no heartbeat of this process answered within %s; a renewal would be judged on another process's report", firstHeartbeatWait) + h.mw.firstHeartbeatOverdue(heartbeatWaitStart) } } - if p.Epoch > 0 && (unanswered != "" || h.firstHeartbeatAnswered()) { + if p.Epoch > 0 && h.firstHeartbeatAnswered() { + h.mw.firstHeartbeatOverdue(time.Time{}) id := &control.WorkspaceIdentity{VolumeId: h.cfg.VolumeID, ReplicaId: h.cfg.ReplicaID, ServerId: h.cfg.ServerID, Epoch: p.Epoch} guard, err := NewWorkspaceLeaseGuard(h.view, control.NewWorkspaceServiceClient(h.conn), id, func(c context.Context) (uint64, error) { return stop(c, id) }, nil) if err != nil { @@ -68,9 +72,6 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context, if ctx.Err() != nil { guard.fenceLocked("shutdown requested (context cancelled)") } - if unanswered != "" { - guard.fenceLocked(unanswered) - } guard.stopPending = h.workspaceStopPending h.view.workspaceGuard.Store(guard) h.workspaceLeaseMu.Unlock() @@ -84,8 +85,12 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context, } } -// firstHeartbeatWait bounds the wait for the first answered heartbeat at one -// lease validity. Tests shorten it. +// firstHeartbeatWait is how long the wait for the first answered heartbeat +// lasts before it is reported as the master-wait reason +// first_heartbeat_unanswered (one lease validity). The lease runtime's wait +// has no bound of its own and never fences or exits; the chunk startup wait +// keeps its own bound (MasterWaitLimit after the first reply), which the +// reason reports as Until. Tests shorten it. var firstHeartbeatWait = maxRenewalValidity // firstHeartbeatWaitStarted, when set (tests only), is told when the lease diff --git a/seaweed-block/core/host/volume/workspace_runtime_test.go b/seaweed-block/core/host/volume/workspace_runtime_test.go index bedb68f751..813a68283d 100644 --- a/seaweed-block/core/host/volume/workspace_runtime_test.go +++ b/seaweed-block/core/host/volume/workspace_runtime_test.go @@ -22,7 +22,14 @@ import ( func workspaceRuntimeHost(t *testing.T, addr string, required bool) *Host { t.Helper() - h, err := New(Config{MasterAddr: addr, ServerID: "node-a", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9100", CtrlAddr: "127.0.0.1:9101", EnableT1Readiness: true, WorkspaceLease: required}) + return workspaceRuntimeHostEvery(t, addr, required, 0) +} + +// workspaceRuntimeHostEvery is workspaceRuntimeHost with a heartbeat cadence +// (0: the default). +func workspaceRuntimeHostEvery(t *testing.T, addr string, required bool, heartbeat time.Duration) *Host { + t.Helper() + h, err := New(Config{MasterAddr: addr, ServerID: "node-a", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9100", CtrlAddr: "127.0.0.1:9101", EnableT1Readiness: true, WorkspaceLease: required, HeartbeatInterval: heartbeat}) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index accc347c10..8396fe5a0a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -391,7 +391,8 @@ stateDiagram-v2 state "Lease guard (host)" as G { [*] --> NoLease NoLease --> Valid: first heartbeat answered, then a renewal reply for this volume, replica and epoch - NoLease --> Fenced: first heartbeat unanswered within one lease validity, invalid reply, revoking, or shutdown + NoLease --> NoLease: first heartbeat not yet answered (past one lease validity: wait reason first_heartbeat_unanswered) + NoLease --> Fenced: invalid reply, revoking, or shutdown Valid --> Valid: renewal before the local deadline Valid --> StopPending: detach started (renew at once) StopPending --> StopPending: renewal, then sleep at most 250 ms @@ -419,7 +420,7 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | NoLease, Valid | Valid | from NoLease, a renewal is sent only after this process's first heartbeat was answered; the reply names this `{volume, replica, epoch}`, its validity is positive and at most 30 s, and it arrives before the old deadline; the new deadline is anchored to the request start | `core/host/volume/workspace_runtime.go` `runWorkspaceLease`, `firstHeartbeatAnswered`; `core/host/volume/workspace_lease.go` `Refresh` | `INV-WS-LEASE-001`, `INV-WS-FORCED-MOVE-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001` | -| NoLease, Valid, StopPending | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, the lease is revoking, or synchronous host shutdown fences through the guard; from NoLease also when no heartbeat of this process is answered within `firstHeartbeatWait` (one lease validity, 30 s); first cause is kept and a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh`, `fenceLocked`; `core/host/volume/workspace_runtime.go` `FenceWorkspaceLease`, `runWorkspaceLease` | `INV-WS-LEASE-001`, `INV-FMT-FINALIZE-001` | +| NoLease, Valid, StopPending | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, the lease is revoking, or synchronous host shutdown fences through the guard. An unanswered first heartbeat is not a cause: NoLease waits without a guard (gated, no renewal, no serving), named `first_heartbeat_unanswered` in /status past `firstHeartbeatWait` (one lease validity, 30 s) while the master replies (a master giving no reply is `unreachable`), with the chunk startup wait's own bound as Until; the lease runtime adds no bound, fence or exit, and leaves for Valid only through a renewal after the answer; first cause is kept and a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh`, `fenceLocked`; `core/host/volume/workspace_runtime.go` `FenceWorkspaceLease`, `runWorkspaceLease` | `INV-WS-LEASE-001`, `INV-FMT-FINALIZE-001` | | Valid | StopPending | a chunk detach of this volume starts (before its drain); the guard renews at once. Scheduling only: StopPending admits, fences and ACKs exactly as Valid | `core/frontend/durable/provider_chunk.go` `DetachVolume`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`; `core/host/volume/workspace_lease.go` `StopPending` | `INV-WS-STOP-PENDING-001` | | StopPending | StopPending | each sleep after a completed renewal is at most `stopPendingPoll` (250 ms); a renewal already in flight is not interrupted | `core/host/volume/workspace_lease.go` `renewDelay`, `Run` | `INV-WS-STOP-PENDING-001` | | StopPending | Valid | only the latest detach attempt, provably not applied, with serving resumed; an applied, fenced or unknown outcome, or an older attempt's resume, leaves StopPending | `core/frontend/durable/provider_chunk.go` `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `ClearStopPending` | `INV-WS-STOP-PENDING-001` | @@ -1072,7 +1073,7 @@ 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 leases and sets a memory intent under grant locks. First grants, renewals and regrants require the latest level-1 report 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` (`core/host/master/format_finalize_serving_test.go`); `TestFormatFinalizeIntentRequiresRegrantReport`, `TestFormatFinalizeCountsOnlyPossiblyLiveCurrentLeases`, `TestFormatFinalizeIntentDoesNotSurviveProcessExit`, `TestFormatFinalizeFailedCheckLeavesLevelZeroGrantsOpen`, `TestFormatFinalizeLiveRenewalChecksCurrentProcess`, `TestFormatFinalizeDeadlineProofSurvivesIntentCompletion` (`core/authority/format_finalize_test.go`); `TestFormatMoveRecordCannotServeBeforeReportedRenewal` (`core/host/master/format_place_lease_test.go`); `TestFormatFinalizeUncertainWriteFailStops` (`core/host/master/format_finalize_failure_test.go`); `TestQueuedFinalizeDoesNotHoldWorkspaceAdmission` (`core/host/master/format_finalize_review_test.go`); `TestAV100HeartbeatSupersedesTheCachedReportSoItsRenewalsAreRefused` (`core/host/master/format_identity_v100_test.go`); `TestAHolderRenewsOnlyAfterItsFirstHeartbeatWithItsIncarnation`, `TestAHolderWhoseHeartbeatIsNeverAnsweredFencesRatherThanServes` (`core/host/volume/workspace_first_heartbeat_test.go`) | 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-FINALIZE-001` | Finalize checks possibly-live leases and sets a memory intent under grant locks. First grants, renewals and regrants require the latest level-1 report 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` (`core/host/master/format_finalize_serving_test.go`); `TestFormatFinalizeIntentRequiresRegrantReport`, `TestFormatFinalizeCountsOnlyPossiblyLiveCurrentLeases`, `TestFormatFinalizeIntentDoesNotSurviveProcessExit`, `TestFormatFinalizeFailedCheckLeavesLevelZeroGrantsOpen`, `TestFormatFinalizeLiveRenewalChecksCurrentProcess`, `TestFormatFinalizeDeadlineProofSurvivesIntentCompletion` (`core/authority/format_finalize_test.go`); `TestFormatMoveRecordCannotServeBeforeReportedRenewal` (`core/host/master/format_place_lease_test.go`); `TestFormatFinalizeUncertainWriteFailStops` (`core/host/master/format_finalize_failure_test.go`); `TestQueuedFinalizeDoesNotHoldWorkspaceAdmission` (`core/host/master/format_finalize_review_test.go`); `TestAV100HeartbeatSupersedesTheCachedReportSoItsRenewalsAreRefused` (`core/host/master/format_identity_v100_test.go`); `TestAHolderRenewsOnlyAfterItsFirstHeartbeatWithItsIncarnation`, `TestAHolderWhoseHeartbeatIsNeverAnsweredWaitsUnservedWithATypedReason`, `TestAHolderWhoseFirstHeartbeatsAreRefusedPastTheBoundServesOnceAnswered`, `TestAHolderWhoseAssignmentMovedWhileItsFirstHeartbeatsWereRefusedNeverServes`, `TestAnAnsweredFirstHeartbeatEndsTheUnansweredWaitReason`, `TestTheUnansweredFirstHeartbeatReasonNeedsAReplyingMaster` (`core/host/volume/workspace_first_heartbeat_test.go`) | 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`); `TestFormatRefreshUsesItsOwnReportDespiteAnOldSibling`, `TestFormatReassignUsesItsOwnReportDespiteAnOldSibling`, `TestFormatPlacedLineKeepsItsReportWait` (`core/host/master/format_finalize_review_test.go`); `TestAMovedLineWaitsOnItsNewHolderOnly` (`core/host/master/format_level_new_cluster_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 |