From 8e508527b07fc46383f434d97ddcfe27a13f8c98 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 19:48:49 -0700 Subject: [PATCH 1/4] G9C: require post-close durable ack for recovered replica ready --- seaweed-block/core/adapter/adapter_test.go | 50 ++++++++++++++ seaweed-block/core/adapter/handoff_test.go | 50 ++++++++++++-- seaweed-block/core/engine/apply.go | 27 +++++++- seaweed-block/core/engine/apply_test.go | 19 +++++- .../core/engine/g5_5c_boundary_test.go | 51 ++++++++------- .../core/engine/g9c_replica_ready_test.go | 65 +++++++++++++++++++ seaweed-block/core/engine/projection.go | 9 +-- seaweed-block/core/engine/state.go | 13 ++++ .../core/host/volume/status_server_test.go | 25 ++++++- 9 files changed, 270 insertions(+), 39 deletions(-) create mode 100644 seaweed-block/core/engine/g9c_replica_ready_test.go diff --git a/seaweed-block/core/adapter/adapter_test.go b/seaweed-block/core/adapter/adapter_test.go index 23f43d083d..0e90889caf 100644 --- a/seaweed-block/core/adapter/adapter_test.go +++ b/seaweed-block/core/adapter/adapter_test.go @@ -159,6 +159,7 @@ func (m *mockExecutor) StartCatchUp(replicaID string, sessionID, epoch, endpoint m.commands = append(m.commands, "StartCatchUp") startCb := m.onSessionStart cb := m.onSessionClose + ackCb := m.onDurableAck autoStart := m.autoStart autoClose := m.autoClose startErr := m.catchUpErr @@ -189,6 +190,17 @@ func (m *mockExecutor) StartCatchUp(replicaID string, sessionID, epoch, endpoint AchievedLSN: targetLSN, }) } + if ackCb != nil { + ackCb(DurableAckResult{ + ReplicaID: replicaID, + SessionID: sessionID, + EndpointVersion: endpointVersion, + TransportEpoch: epoch, + DurableLSN: targetLSN, + PrimaryTailLSN: fromLSN, + PrimaryHeadLSN: targetLSN, + }) + } }() } return nil @@ -199,6 +211,7 @@ func (m *mockExecutor) StartRebuild(replicaID string, sessionID, epoch, endpoint m.commands = append(m.commands, "StartRebuild") startCb := m.onSessionStart cb := m.onSessionClose + ackCb := m.onDurableAck autoStart := m.autoStart autoClose := m.autoClose startErr := m.rebuildErr @@ -227,6 +240,16 @@ func (m *mockExecutor) StartRebuild(replicaID string, sessionID, epoch, endpoint AchievedLSN: targetLSN, }) } + if ackCb != nil { + ackCb(DurableAckResult{ + ReplicaID: replicaID, + SessionID: sessionID, + EndpointVersion: endpointVersion, + TransportEpoch: epoch, + DurableLSN: targetLSN, + PrimaryHeadLSN: targetLSN, + }) + } }() } return nil @@ -292,6 +315,15 @@ func (m *mockExecutor) fireClose(result SessionCloseResult) { } } +func (m *mockExecutor) fireDurableAck(result DurableAckResult) { + m.mu.Lock() + cb := m.onDurableAck + m.mu.Unlock() + if cb != nil { + cb(result) + } +} + func (m *mockExecutor) fireStart(result SessionStartResult) { m.mu.Lock() cb := m.onSessionStart @@ -1369,6 +1401,15 @@ func TestSessionStarted_ComesFromExecutorStartCallback(t *testing.T) { Success: true, AchievedLSN: 100, }) + exec.fireDurableAck(DurableAckResult{ + ReplicaID: "r1", + SessionID: sessionID, + EndpointVersion: 1, + TransportEpoch: 1, + DurableLSN: 100, + PrimaryTailLSN: 10, + PrimaryHeadLSN: 100, + }) time.Sleep(20 * time.Millisecond) if got := a.Projection().Mode; got != engine.ModeHealthy { @@ -1569,6 +1610,15 @@ func TestStaleCallback_OldSessionIgnoredAfterNewAssignment(t *testing.T) { Success: true, AchievedLSN: 120, }) + exec.fireDurableAck(DurableAckResult{ + ReplicaID: "r1", + SessionID: newSessionID, + EndpointVersion: 2, + TransportEpoch: 2, + DurableLSN: 120, + PrimaryTailLSN: 20, + PrimaryHeadLSN: 120, + }) time.Sleep(50 * time.Millisecond) if got := a.Projection().Mode; got != engine.ModeHealthy { diff --git a/seaweed-block/core/adapter/handoff_test.go b/seaweed-block/core/adapter/handoff_test.go index 824b48ba57..83bd09acc3 100644 --- a/seaweed-block/core/adapter/handoff_test.go +++ b/seaweed-block/core/adapter/handoff_test.go @@ -62,6 +62,44 @@ func waitProjection(t *testing.T, a *adapter.VolumeReplicaAdapter, want engine.M } } +func waitRecoveryCompleted(t *testing.T, a *adapter.VolumeReplicaAdapter, timeout time.Duration) engine.ReplicaProjection { + t.Helper() + deadline := time.After(timeout) + for { + p := a.Projection() + if p.SessionPhase == engine.PhaseCompleted { + return p + } + select { + case <-deadline: + t.Fatalf("timeout waiting for completed recovery, last=%s phase=%s decision=%s", + p.Mode, p.SessionPhase, p.RecoveryDecision) + default: + time.Sleep(20 * time.Millisecond) + } + } +} + +func waitRecoveredHealthy(t *testing.T, a *adapter.VolumeReplicaAdapter, replicaID string, timeout time.Duration) { + t.Helper() + p := waitRecoveryCompleted(t, a, timeout) + if p.Mode == engine.ModeHealthy { + return + } + // G9C: recovery-window close proves base+WAL+barrier closure, but + // supporting replica_ready waits for one post-close durable progress + // fact to prove the live feed still owns this replica. + a.OnDurableAck(adapter.DurableAckResult{ + ReplicaID: replicaID, + EndpointVersion: p.EndpointVersion, + TransportEpoch: p.Epoch, + DurableLSN: p.R, + PrimaryTailLSN: p.S, + PrimaryHeadLSN: p.H, + }) + waitProjection(t, a, engine.ModeHealthy, timeout) +} + // TestHandoff_OldPrimaryToNewPrimary_Converges proves the core P12 // route end-to-end: // @@ -87,7 +125,7 @@ func TestHandoff_OldPrimaryToNewPrimary_Converges(t *testing.T) { Epoch: 1, EndpointVersion: 1, DataAddr: ln.Addr(), CtrlAddr: ln.Addr(), }) - waitProjection(t, adapterA, engine.ModeHealthy, 3*time.Second) + waitRecoveredHealthy(t, adapterA, "r1", 3*time.Second) // Verify replica has A's data. for _, lba := range []uint32{0, 1, 2} { @@ -109,7 +147,7 @@ func TestHandoff_OldPrimaryToNewPrimary_Converges(t *testing.T) { Epoch: 2, EndpointVersion: 2, DataAddr: ln.Addr(), CtrlAddr: ln.Addr(), }) - waitProjection(t, adapterB, engine.ModeHealthy, 3*time.Second) + waitRecoveredHealthy(t, adapterB, "r1", 3*time.Second) // Verify replica has B's data (the "new truth"). for _, lba := range []uint32{0, 1, 2, 3} { @@ -139,7 +177,7 @@ func TestHandoff_StaleOldPrimaryTraffic_Rejected(t *testing.T) { Epoch: 1, EndpointVersion: 1, DataAddr: ln.Addr(), CtrlAddr: ln.Addr(), }) - waitProjection(t, adapterA, engine.ModeHealthy, 3*time.Second) + waitRecoveredHealthy(t, adapterA, "r1", 3*time.Second) // Primary B starts at epoch=2 with MORE data so recovery is // required (R < H). B's mutating traffic must establish @@ -156,7 +194,7 @@ func TestHandoff_StaleOldPrimaryTraffic_Rejected(t *testing.T) { Epoch: 2, EndpointVersion: 2, DataAddr: ln.Addr(), CtrlAddr: ln.Addr(), }) - waitProjection(t, adapterB, engine.ModeHealthy, 3*time.Second) + waitRecoveredHealthy(t, adapterB, "r1", 3*time.Second) // Now simulate stale A traffic: manually send a ship entry at // epoch=1 to the replica. It must be rejected because B already @@ -210,7 +248,7 @@ func TestHandoff_RejoinAfterNewPrimary_DataConsistent(t *testing.T) { Epoch: 1, EndpointVersion: 1, DataAddr: ln.Addr(), CtrlAddr: ln.Addr(), }) - waitProjection(t, adapterA, engine.ModeHealthy, 3*time.Second) + waitRecoveredHealthy(t, adapterA, "r1", 3*time.Second) // B writes a different, larger set. primaryB := storage.NewBlockStore(64, 4096) @@ -222,7 +260,7 @@ func TestHandoff_RejoinAfterNewPrimary_DataConsistent(t *testing.T) { Epoch: 2, EndpointVersion: 2, DataAddr: ln.Addr(), CtrlAddr: ln.Addr(), }) - waitProjection(t, adapterB, engine.ModeHealthy, 3*time.Second) + waitRecoveredHealthy(t, adapterB, "r1", 3*time.Second) // Every LBA that B wrote must match on the replica. allB := primaryB.AllBlocks() diff --git a/seaweed-block/core/engine/apply.go b/seaweed-block/core/engine/apply.go index 8e6d8380bd..50cf0da1b1 100644 --- a/seaweed-block/core/engine/apply.go +++ b/seaweed-block/core/engine/apply.go @@ -314,6 +314,14 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra st.Recovery.DurableAckR = fact.ReplicaR st.Recovery.DurableAckKnown = true } + if st.Recovery.RecoveryWindowClosed && fact.ReplicaR >= st.Recovery.R { + st.Recovery.PostCloseDurableAckKnown = true + if fact.ReplicaR > st.Recovery.PostCloseDurableAckR { + st.Recovery.PostCloseDurableAckR = fact.ReplicaR + } + trace("post_close_durable_ack", + fmt.Sprintf("R=%d closeR=%d", fact.ReplicaR, st.Recovery.R)) + } lag := durableAckLagDecision(st, fact) st.Recovery.LagDecision = lag trace("durable_ack_observed", @@ -355,6 +363,9 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra }) trace("command", "StartRebuild (durable ack below retention)") } + if st.Recovery.PostCloseDurableAckKnown { + decide(st, r, trace) + } } func updateDurableAckLagState(st *ReplicaState, fact ReplicaProgressFact) { @@ -495,6 +506,8 @@ func decide(st *ReplicaState, r *ApplyResult, trace func(string, string)) { EndpointVersion: st.Identity.EndpointVersion, }) trace("command", "FenceAtEpoch") + } else if recoveredReplicaWaitingForPostCloseAck(st) { + trace("publish_healthy_held", "waiting for post-close durable ack") } else { r.Commands = append(r.Commands, PublishHealthy{ReplicaID: st.Identity.ReplicaID}) } @@ -545,6 +558,10 @@ func hasActiveSession(st *ReplicaState) bool { return st.Session.Phase == PhaseStarting || st.Session.Phase == PhaseRunning } +func recoveredReplicaWaitingForPostCloseAck(st *ReplicaState) bool { + return st.Recovery.RecoveryWindowClosed && !st.Recovery.PostCloseDurableAckKnown +} + // --- Session lifecycle --- func applySessionPrepared(st *ReplicaState, e SessionPrepared, r *ApplyResult, trace func(string, string)) { @@ -564,6 +581,9 @@ func applySessionPrepared(st *ReplicaState, e SessionPrepared, r *ApplyResult, t TargetLSN: frontierHint, Phase: PhaseStarting, } + st.Recovery.RecoveryWindowClosed = false + st.Recovery.PostCloseDurableAckKnown = false + st.Recovery.PostCloseDurableAckR = 0 trace("session_prepared", string(e.Kind)) } @@ -622,6 +642,11 @@ func applySessionCompleted(st *ReplicaState, e SessionClosedCompleted, r *ApplyR if st.Session.Kind == SessionRebuild { st.Recovery.RebuildPinned = false } + if st.Session.Kind == SessionCatchUp || st.Session.Kind == SessionRebuild { + st.Recovery.RecoveryWindowClosed = true + st.Recovery.PostCloseDurableAckKnown = false + st.Recovery.PostCloseDurableAckR = 0 + } // A successful catch-up/rebuild session sent mutating traffic // at the current identity epoch, so the replica's lineage gate // is now at this epoch. Treat completion as an implicit fence. @@ -929,7 +954,7 @@ func derivePublication(st *ReplicaState, trace func(string, string)) { // replica's lineage gate has observed Identity.Epoch via // FenceCompleted. Otherwise stale old-epoch traffic could // still land while the projection already reads healthy. - if st.Identity.Epoch > st.Reachability.FencedEpoch { + if st.Identity.Epoch > st.Reachability.FencedEpoch || recoveredReplicaWaitingForPostCloseAck(st) { st.Publication.Healthy = false st.Publication.Degraded = false st.Publication.NeedsAttention = true diff --git a/seaweed-block/core/engine/apply_test.go b/seaweed-block/core/engine/apply_test.go index 39e656406b..49bff99ba4 100644 --- a/seaweed-block/core/engine/apply_test.go +++ b/seaweed-block/core/engine/apply_test.go @@ -340,11 +340,26 @@ func TestV3_Terminal_OnlySessionClosedCompletedGivesSuccess(t *testing.T) { if r.Projection.SessionPhase != PhaseCompleted { t.Fatalf("phase=%s, want completed", r.Projection.SessionPhase) } - // After completion + re-decision, should be caught up and healthy. + // After completion + re-decision, the recovery window is closed, + // but recovered-replica readiness still waits for post-close + // durable ack / live-feed continuity evidence. if r.Projection.RecoveryDecision != DecisionNone { t.Fatalf("decision=%s, want none after completion", r.Projection.RecoveryDecision) } - assertHasCommand(t, r, "PublishHealthy") + assertNoCommand(t, r, "PublishHealthy") + if r.Projection.Mode == ModeHealthy { + t.Fatalf("session close alone must not publish healthy") + } + + r2 := Apply(st, DurableAckObserved{ + ReplicaID: "r1", + EndpointVersion: 1, + TransportEpoch: 1, + DurableLSN: 100, + PrimaryTailLSN: 10, + PrimaryHeadLSN: 100, + }) + assertHasCommand(t, r2, "PublishHealthy") } func TestV3_Terminal_SessionCompletedDoesNotRegressRecoveryR(t *testing.T) { diff --git a/seaweed-block/core/engine/g5_5c_boundary_test.go b/seaweed-block/core/engine/g5_5c_boundary_test.go index de97418921..9dbce9d6da 100644 --- a/seaweed-block/core/engine/g5_5c_boundary_test.go +++ b/seaweed-block/core/engine/g5_5c_boundary_test.go @@ -46,26 +46,26 @@ func TestG5_5C_Dispatch_CatchUpVsRebuild_TableDriven(t *testing.T) { wantCmdKind string // "StartCatchUp" or "StartRebuild" or "" }{ { - name: "caught_up", - r: 100, s: 10, h: 100, + name: "caught_up", + r: 100, s: 10, h: 100, wantDec: DecisionNone, wantCmdKind: "", // none-decision emits FenceAtEpoch (covered elsewhere) but no recovery session }, { - name: "gap_within_wal_dispatches_catch_up", - r: 50, s: 10, h: 100, + name: "gap_within_wal_dispatches_catch_up", + r: 50, s: 10, h: 100, wantDec: DecisionCatchUp, wantCmdKind: "StartCatchUp", }, { - name: "gap_exceeds_wal_dispatches_rebuild", - r: 5, s: 10, h: 100, // R < S: replica is behind the recoverable start + name: "gap_exceeds_wal_dispatches_rebuild", + r: 5, s: 10, h: 100, // R < S: replica is behind the recoverable start wantDec: DecisionRebuild, wantCmdKind: "StartRebuild", }, { - name: "rebuild_pinned_overrides_catch_up", - r: 50, s: 10, h: 100, rebuildPin: true, + name: "rebuild_pinned_overrides_catch_up", + r: 50, s: 10, h: 100, rebuildPin: true, wantDec: DecisionRebuild, wantCmdKind: "StartRebuild", }, @@ -319,9 +319,9 @@ func TestG5_5C_StaleSessionAck_DoesNotPromoteHealth(t *testing.T) { // TestG5_5C_StaleSessionAck_FullAchievedDoesPromote is the // counterpart confirmation: a SessionCompleted with AchievedLSN == -// TargetLSN == H reaches DecisionNone and (after the implicit -// fence) promotes Healthy. Without this dual, the prior test could -// pass trivially (e.g., if Healthy never promotes for any input). +// TargetLSN == H reaches DecisionNone. G9C tightens the final +// publication gate: recovered replicas promote Healthy only after a +// post-close durable ack proves live-feed continuity. func TestG5_5C_StaleSessionAck_FullAchievedDoesPromote(t *testing.T) { st := &ReplicaState{} Apply(st, AssignmentObserved{ @@ -352,20 +352,21 @@ func TestG5_5C_StaleSessionAck_FullAchievedDoesPromote(t *testing.T) { if got := st.Recovery.Decision; got != DecisionNone { t.Errorf("Decision = %s, want None on full-achievement", got) } - // Implicit fence at SessionCompleted (apply.go:493-495) advances - // FencedEpoch to Identity.Epoch. Healthy gate may now flip true. + if st.Publication.Healthy { + t.Error("Publication.Healthy = true before post-close durable ack") + } + assertNoCommand(t, r, "PublishHealthy") + + r2 := Apply(st, DurableAckObserved{ + ReplicaID: "r1", + EndpointVersion: 1, + TransportEpoch: 1, + DurableLSN: 100, + PrimaryTailLSN: 0, + PrimaryHeadLSN: 100, + }) if !st.Publication.Healthy { - t.Error("Publication.Healthy = false despite full-achievement + implicit fence") - } - // PublishHealthy expected. - hasHealthy := false - for _, cmd := range r.Commands { - if CommandKind(cmd) == "PublishHealthy" { - hasHealthy = true - break - } - } - if !hasHealthy { - t.Error("PublishHealthy not emitted on full-achievement ack") + t.Error("Publication.Healthy = false after full achievement + post-close durable ack") } + assertHasCommand(t, r2, "PublishHealthy") } diff --git a/seaweed-block/core/engine/g9c_replica_ready_test.go b/seaweed-block/core/engine/g9c_replica_ready_test.go new file mode 100644 index 0000000000..8ca29a4c58 --- /dev/null +++ b/seaweed-block/core/engine/g9c_replica_ready_test.go @@ -0,0 +1,65 @@ +package engine + +import "testing" + +func TestG9C_RecoveredReplica_NotHealthyUntilPostCloseDurableAck(t *testing.T) { + st := g9cRecoveredReplicaBeforeClose() + + r := Apply(st, SessionClosedCompleted{ + ReplicaID: "r1", + SessionID: 11, + AchievedLSN: 100, + }) + + if st.Session.Phase != PhaseCompleted { + t.Fatalf("session phase=%s want completed", st.Session.Phase) + } + assertNoCommand(t, r, "PublishHealthy") + if r.Projection.Mode == ModeHealthy { + t.Fatalf("recovered replica became healthy before post-close durable ack") + } +} + +func TestG9C_RecoveredReplica_PostCloseDurableAckPublishesHealthy(t *testing.T) { + st := g9cRecoveredReplicaBeforeClose() + Apply(st, SessionClosedCompleted{ + ReplicaID: "r1", + SessionID: 11, + AchievedLSN: 100, + }) + + r := Apply(st, DurableAckObserved{ + ReplicaID: "r1", + EndpointVersion: 1, + TransportEpoch: 1, + DurableLSN: 100, + PrimaryTailLSN: 10, + PrimaryHeadLSN: 100, + }) + + assertHasCommand(t, r, "PublishHealthy") + if r.Projection.Mode != ModeHealthy { + t.Fatalf("after post-close durable ack mode=%s want healthy", r.Projection.Mode) + } +} + +func g9cRecoveredReplicaBeforeClose() *ReplicaState { + st := &ReplicaState{} + assignAndProbe(st) + Apply(st, RecoveryFactsObserved{ + ReplicaID: "r1", + EndpointVersion: 1, + TransportEpoch: 1, + R: 20, + S: 10, + H: 100, + }) + Apply(st, SessionPrepared{ + ReplicaID: "r1", + SessionID: 11, + Kind: SessionCatchUp, + FrontierHint: 100, + }) + Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 11}) + return st +} diff --git a/seaweed-block/core/engine/projection.go b/seaweed-block/core/engine/projection.go index 8c7b2fa391..b2df857375 100644 --- a/seaweed-block/core/engine/projection.go +++ b/seaweed-block/core/engine/projection.go @@ -49,11 +49,12 @@ func DeriveProjection(st *ReplicaState) ReplicaProjection { p.Mode = ModeHealthy case st.Recovery.Decision == DecisionNone && st.Reachability.Status == ProbeReachable && - st.Identity.Epoch > st.Reachability.FencedEpoch: + (st.Identity.Epoch > st.Reachability.FencedEpoch || + recoveredReplicaWaitingForPostCloseAck(st)): // P14 S1: caught-up but fence not yet acked. Transitional - // — not healthy yet, but nothing is wrong. Show as - // recovering rather than degraded so operators read the - // transition correctly. + // — not healthy yet, but nothing is wrong. G9C extends the + // same transitional shape to a recovered replica waiting for + // post-close durable ack / live-feed continuity evidence. p.Mode = ModeRecovering default: p.Mode = ModeDegraded diff --git a/seaweed-block/core/engine/state.go b/seaweed-block/core/engine/state.go index e174fc50d1..bd90e8847a 100644 --- a/seaweed-block/core/engine/state.go +++ b/seaweed-block/core/engine/state.go @@ -101,6 +101,19 @@ type RecoveryTruth struct { // comes from R/S/H facts and ClassifyProgress. LagDecision LagDecision + // RecoveryWindowClosed is set when a catch-up/rebuild session closes + // successfully. For rebuild, SessionClosedCompleted is the aggregate + // receiver proof that base + WAL + barrier closed; engine does not + // need a separate base-complete event in this slice. + RecoveryWindowClosed bool + + // PostCloseDurableAckKnown means the primary observed durable progress + // after the recovery window closed. A recovered replica is not ready + // for publication until this confirms live-feed continuity beyond the + // recovery close point. + PostCloseDurableAckKnown bool + PostCloseDurableAckR uint64 + // Attempts tracks how many StartCatchUp / StartRecovery commands // the engine has emitted for the current Decision. Engine // SessionFailed handler increments on close-with-non-recycled- diff --git a/seaweed-block/core/host/volume/status_server_test.go b/seaweed-block/core/host/volume/status_server_test.go index e9e5303267..1d764129c4 100644 --- a/seaweed-block/core/host/volume/status_server_test.go +++ b/seaweed-block/core/host/volume/status_server_test.go @@ -304,8 +304,20 @@ func TestG9B_StatusProjection_ComponentAdapterLifecycle_NotReadyRecoveringReady( Success: true, AchievedLSN: 10, }) body = s.statusProjection() + if body.ReplicationRole != ReplicationRoleRecovering { + t.Fatalf("after completed recovery before durable ack role=%q want %q", body.ReplicationRole, ReplicationRoleRecovering) + } + if body.FrontendPrimaryReady { + t.Fatalf("post-close recovered replica must not become frontend primary: %+v", body) + } + + exec.durableAck(adapter.DurableAckResult{ + ReplicaID: "r2", SessionID: exec.lastSessionID, + DurableLSN: 10, PrimaryTailLSN: 1, PrimaryHeadLSN: 10, + }) + body = s.statusProjection() if body.ReplicationRole != ReplicationRoleReady { - t.Fatalf("after completed recovery role=%q want %q", body.ReplicationRole, ReplicationRoleReady) + t.Fatalf("after post-close durable ack role=%q want %q", body.ReplicationRole, ReplicationRoleReady) } if body.FrontendPrimaryReady { t.Fatalf("supporting replica_ready must not become frontend primary: %+v", body) @@ -364,6 +376,7 @@ func TestIsLoopbackRemote(t *testing.T) { type g9bStatusExecutor struct { onSessionStart adapter.OnSessionStart onSessionClose adapter.OnSessionClose + onDurableAck adapter.OnDurableAck onFenceComplete adapter.OnFenceComplete lastSessionID uint64 probeCh chan struct{} @@ -381,6 +394,10 @@ func (e *g9bStatusExecutor) SetOnSessionClose(fn adapter.OnSessionClose) { e.onSessionClose = fn } +func (e *g9bStatusExecutor) SetOnDurableAck(fn adapter.OnDurableAck) { + e.onDurableAck = fn +} + func (e *g9bStatusExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { e.onFenceComplete = fn } @@ -448,6 +465,12 @@ func (e *g9bStatusExecutor) completeSession(result adapter.SessionCloseResult) { } } +func (e *g9bStatusExecutor) durableAck(result adapter.DurableAckResult) { + if e.onDurableAck != nil { + e.onDurableAck(result) + } +} + // TestStatusServer_RecoveryEndpoint_Disabled_Returns404 — G5-5 // regression: /status/recovery is OPT-IN. Default config (no // EnableRecoveryEndpoint call) must NOT route the path. From 152567f1a6fb4d790113501f6261dc8486f35197 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 19:53:19 -0700 Subject: [PATCH 2/4] G9C: emit post-close durable ack from dual-lane recovery --- seaweed-block/core/recovery/receiver.go | 13 +++-- .../core/transport/dual_lane_test.go | 54 +++++++++++++++---- seaweed-block/core/transport/executor.go | 23 ++++++-- 3 files changed, 72 insertions(+), 18 deletions(-) diff --git a/seaweed-block/core/recovery/receiver.go b/seaweed-block/core/recovery/receiver.go index 7fb6f26ee1..7598e25ab5 100644 --- a/seaweed-block/core/recovery/receiver.go +++ b/seaweed-block/core/recovery/receiver.go @@ -259,14 +259,17 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) { return 0, newFailure(FailureContract, PhaseRecvSync, fmt.Errorf("barrier req but layer-1 not done: %+v", st)) } - log.Printf("g7-debug: Receiver.Run TryComplete=true achieved=%d frontier=%d", achieved, frontier) - _ = achieved - if writeErr := writeFrame(r.conn, frameBarrierResp, encodeBarrierResp(frontier)); writeErr != nil { + durableAchieved := achieved + if frontier < durableAchieved { + durableAchieved = frontier + } + log.Printf("g7-debug: Receiver.Run TryComplete=true achieved=%d frontier=%d durableAchieved=%d", achieved, frontier, durableAchieved) + if writeErr := writeFrame(r.conn, frameBarrierResp, encodeBarrierResp(durableAchieved)); writeErr != nil { log.Printf("g7-debug: Receiver.Run BarrierResp write err err=%v", writeErr) return 0, newFailure(FailureWire, PhaseRecvSync, writeErr) } - log.Printf("g7-debug: Receiver.Run frameBarrierResp written, returning frontier=%d", frontier) - return frontier, nil + log.Printf("g7-debug: Receiver.Run frameBarrierResp written, returning durableAchieved=%d", durableAchieved) + return durableAchieved, nil case frameBarrierResp: return 0, newFailure(FailureProtocol, PhaseRecvDispatch, diff --git a/seaweed-block/core/transport/dual_lane_test.go b/seaweed-block/core/transport/dual_lane_test.go index 5a5c3233c3..a58ee9e559 100644 --- a/seaweed-block/core/transport/dual_lane_test.go +++ b/seaweed-block/core/transport/dual_lane_test.go @@ -89,9 +89,19 @@ func TestDualLane_BlockExecutor_StartRebuild(t *testing.T) { ) startCh := make(chan adapter.SessionStartResult, 1) - closeCh := make(chan adapter.SessionCloseResult, 1) + type recoveryEvent struct { + kind string + close adapter.SessionCloseResult + ack adapter.DurableAckResult + } + eventCh := make(chan recoveryEvent, 8) exec.SetOnSessionStart(func(r adapter.SessionStartResult) { startCh <- r }) - exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r }) + exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { + eventCh <- recoveryEvent{kind: "close", close: r} + }) + exec.SetOnDurableAck(func(r adapter.DurableAckResult) { + eventCh <- recoveryEvent{kind: "ack", ack: r} + }) _, _, primaryH := primary.Boundaries() if err := exec.StartRebuild("r1", 7, 1, 1, primaryH); err != nil { @@ -110,16 +120,42 @@ func TestDualLane_BlockExecutor_StartRebuild(t *testing.T) { } // OnSessionClose: success with achievedLSN == primary H. + var closeResult adapter.SessionCloseResult + closeDeadline := time.After(5 * time.Second) + for { + select { + case ev := <-eventCh: + if ev.kind != "close" { + continue + } + closeResult = ev.close + if !closeResult.Success { + t.Fatalf("OnSessionClose: not Success; FailReason=%q", closeResult.FailReason) + } + if closeResult.AchievedLSN != primaryH { + t.Errorf("OnSessionClose: achievedLSN=%d want %d", closeResult.AchievedLSN, primaryH) + } + goto closeObserved + case <-closeDeadline: + t.Fatal("OnSessionClose did not fire within 5s") + } + } +closeObserved: + + // G9C: the real dual-lane executor must emit a durable progress + // fact AFTER the recovery close, so engine readiness can distinguish + // recovery-window closure from live-feed continuity. select { - case got := <-closeCh: - if !got.Success { - t.Fatalf("OnSessionClose: not Success; FailReason=%q", got.FailReason) + case ev := <-eventCh: + if ev.kind != "ack" { + t.Fatalf("event after close=%s want ack", ev.kind) } - if got.AchievedLSN != primaryH { - t.Errorf("OnSessionClose: achievedLSN=%d want %d", got.AchievedLSN, primaryH) + if ev.ack.DurableLSN != closeResult.AchievedLSN { + t.Fatalf("post-close durable ack LSN=%d want close achieved %d", + ev.ack.DurableLSN, closeResult.AchievedLSN) } - case <-time.After(5 * time.Second): - t.Fatal("OnSessionClose did not fire within 5s") + case <-time.After(2 * time.Second): + t.Fatal("post-close durable ack did not fire within 2s") } // Replica matches primary on the rebuilt range. diff --git a/seaweed-block/core/transport/executor.go b/seaweed-block/core/transport/executor.go index b07b83c32b..32ed8a7080 100644 --- a/seaweed-block/core/transport/executor.go +++ b/seaweed-block/core/transport/executor.go @@ -236,10 +236,8 @@ func NewBlockExecutorWithDualLane( } e.mu.Lock() cb := e.onSessionClose + ackCb := e.onDurableAck e.mu.Unlock() - if cb == nil { - return - } // ReplicaID MUST be populated — see start lambda above for // the full failure mode (engine drops as wrong_replica; // session Phase stuck; hasActiveSession blocks future @@ -254,7 +252,24 @@ func NewBlockExecutorWithDualLane( } else { res.FailReason = err.Error() } - cb(res) + if cb != nil { + cb(res) + } + if err == nil && ackCb != nil { + // G9C: session close proves the recovery window closed; + // replica_ready needs a subsequent durable progress fact + // so the engine knows the live feed still owns this peer. + // `achieved` is the receiver's durable BarrierResp witness, + // not the primary's frontier intent. + _, primaryS, primaryH := e.primaryStore.Boundaries() + ackCb(adapter.DurableAckResult{ + ReplicaID: string(rid), + SessionID: sid, + DurableLSN: achieved, + PrimaryTailLSN: primaryS, + PrimaryHeadLSN: primaryH, + }) + } }, ) bridge.SetOnDurableAck(func(rid recovery.ReplicaID, sid, acknowledgedLSN, primaryS, primaryH uint64) { From f476817e3430465d2012417465bb23d5bcc50028 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 19:56:23 -0700 Subject: [PATCH 3/4] G9C: pin replica ready after post-close ack in dual-lane component path --- .../component/dual_lane_engine_test.go | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/seaweed-block/core/replication/component/dual_lane_engine_test.go b/seaweed-block/core/replication/component/dual_lane_engine_test.go index d49280dec8..279701f2fa 100644 --- a/seaweed-block/core/replication/component/dual_lane_engine_test.go +++ b/seaweed-block/core/replication/component/dual_lane_engine_test.go @@ -6,6 +6,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/engine" "github.com/seaweedfs/seaweed-block/core/recovery" "github.com/seaweedfs/seaweed-block/core/replication/component" ) @@ -136,6 +137,64 @@ func TestDualLane_EngineDrivenRebuild_HappyPath(t *testing.T) { }) } +// TestG9C_DualLaneRecoveredReplica_PublishesHealthyOnlyAfterPostCloseDurableAck +// pins the host-facing G9C contract on the real engine→adapter→dual-lane +// transport path: +// +// - SessionClosedCompleted closes the recovery window, but the engine +// must hold PublishHealthy. +// - The dual-lane executor must then report a durable ack derived from +// the receiver's BarrierResp witness. +// - Only that post-close durable ack may publish healthy / replica_ready. +func TestG9C_DualLaneRecoveredReplica_PublishesHealthyOnlyAfterPostCloseDurableAck(t *testing.T) { + component.RunSubstrate(t, "memorywal", component.MemoryWAL, func(t *testing.T, c *component.Cluster) { + c.WithReplicas(1). + WithEngineDrivenRecovery(). + WithDualLaneRecovery(). + Start() + + const seedN = 12 + c.PrimaryWriteN(seedN) + c.PrimarySync() + + a := c.Adapter(0) + c.DriveAssignment(0, adapter.AssignmentInfo{ + VolumeID: "v1", + ReplicaID: "replica-0", + Epoch: 1, + EndpointVersion: 1, + DataAddr: c.Replica(0).Addr, + CtrlAddr: c.Replica(0).Addr, + }) + c.DriveProbeResult(0, adapter.ProbeResult{ + ReplicaID: "replica-0", + Success: true, + EndpointVersion: 1, + TransportEpoch: 1, + ReplicaFlushedLSN: 0, + PrimaryTailLSN: 1, + PrimaryHeadLSN: seedN, + }) + + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + trace := a.Trace() + closeIdx := traceIndex(trace, 0, "event", "SessionClosedCompleted") + heldIdx := traceIndex(trace, closeIdx+1, "publish_healthy_held", "waiting for post-close durable ack") + ackIdx := traceIndex(trace, heldIdx+1, "event", "DurableAckObserved") + postAckIdx := traceIndex(trace, ackIdx+1, "post_close_durable_ack", "") + if closeIdx >= 0 && heldIdx >= 0 && ackIdx >= 0 && postAckIdx >= 0 && + commandLogContains(a.CommandLog(), "PublishHealthy") && + a.Projection().Mode == engine.ModeHealthy { + return + } + time.Sleep(20 * time.Millisecond) + } + t.Fatalf("post-close durable ack ordering not observed; trace=%v commands=%v projection=%+v", + a.Trace(), a.CommandLog(), a.Projection()) + }) +} + // TestDualLane_CoordReleasesPinFloorAfterSession — pins the // post-session lifecycle invariant: when a rebuild session ends // (success or failure), the coordinator's pin_floor for that @@ -515,3 +574,27 @@ func waitBridgeLiveReady(t *testing.T, bridge interface { } t.Fatalf("bridge session for %s did not become live-ready", replicaID) } + +func traceIndex(trace []engine.TraceEntry, start int, step, detail string) int { + if start < 0 { + return -1 + } + for i := start; i < len(trace); i++ { + if trace[i].Step != step { + continue + } + if detail == "" || trace[i].Detail == detail { + return i + } + } + return -1 +} + +func commandLogContains(log []string, want string) bool { + for _, got := range log { + if got == want { + return true + } + } + return false +} From 30bb0ca9f1e5bb4abae53074500236af2c3f00fb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 2 May 2026 19:58:47 -0700 Subject: [PATCH 4/4] G9C: expose replica ready transition through status projection --- .../host/volume/g9c_status_component_test.go | 112 ++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 seaweed-block/core/host/volume/g9c_status_component_test.go diff --git a/seaweed-block/core/host/volume/g9c_status_component_test.go b/seaweed-block/core/host/volume/g9c_status_component_test.go new file mode 100644 index 0000000000..9a38c5e9fc --- /dev/null +++ b/seaweed-block/core/host/volume/g9c_status_component_test.go @@ -0,0 +1,112 @@ +package volume + +import ( + "context" + "encoding/json" + "net/http" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/replication/component" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +func TestG9C_StatusProjection_DualLaneRecoveredReplicaReadyAfterPostCloseAck(t *testing.T) { + component.RunSubstrate(t, "memorywal", component.MemoryWAL, func(t *testing.T, c *component.Cluster) { + c.WithReplicas(1). + WithEngineDrivenRecovery(). + WithDualLaneRecovery(). + Start() + + const seedN = 24 + c.PrimaryWriteN(seedN) + c.PrimarySync() + // Keep the session visible long enough for HTTP status polling to + // observe the intermediate recovering state. + c.BlockExecutor(0).SetStepDelay(5 * time.Millisecond) + + a := c.Adapter(0) + h := &Host{cfg: Config{VolumeID: "v1", ReplicaID: "replica-0"}} + h.view = NewAdapterProjectionView(a, "v1", "replica-0", h) + // The current frontend authority line names another replica at the + // same lineage. This process can become a supporting replica_ready, + // but must never report frontend-primary-ready. + h.recordOtherLine(&control.AssignmentFact{ + VolumeId: "v1", + ReplicaId: "primary-r1", + Epoch: 1, + EndpointVersion: 1, + }) + s := NewStatusServer(h.view) + addr, err := s.Start("127.0.0.1:0") + if err != nil { + t.Fatalf("status start: %v", err) + } + defer func() { _ = s.Close(context.Background()) }() + + c.DriveAssignment(0, adapter.AssignmentInfo{ + VolumeID: "v1", + ReplicaID: "replica-0", + Epoch: 1, + EndpointVersion: 1, + DataAddr: c.Replica(0).Addr, + CtrlAddr: c.Replica(0).Addr, + }) + c.DriveProbeResult(0, adapter.ProbeResult{ + ReplicaID: "replica-0", + Success: true, + EndpointVersion: 1, + TransportEpoch: 1, + ReplicaFlushedLSN: 0, + PrimaryTailLSN: 1, + PrimaryHeadLSN: seedN, + }) + + recovering := waitG9CStatus(t, addr, 2*time.Second, func(p StatusProjection) bool { + return p.ReplicationRole == ReplicationRoleRecovering && !p.FrontendPrimaryReady + }) + if recovering.Healthy { + t.Fatalf("recovering supporting replica must not be Healthy yet: %+v", recovering) + } + + ready := waitG9CStatus(t, addr, 5*time.Second, func(p StatusProjection) bool { + return p.ReplicationRole == ReplicationRoleReady && !p.FrontendPrimaryReady + }) + if !ready.Healthy { + t.Fatalf("replica_ready should expose Healthy=true for support consumers: %+v", ready) + } + }) +} + +func waitG9CStatus(t *testing.T, addr string, timeout time.Duration, ok func(StatusProjection) bool) StatusProjection { + t.Helper() + deadline := time.Now().Add(timeout) + var last StatusProjection + for time.Now().Before(deadline) { + last = fetchG9CStatus(t, addr) + if ok(last) { + return last + } + time.Sleep(20 * time.Millisecond) + } + t.Fatalf("status condition not met within %v; last=%+v", timeout, last) + return StatusProjection{} +} + +func fetchG9CStatus(t *testing.T, addr string) StatusProjection { + t.Helper() + resp, err := http.Get("http://" + addr + "/status?volume=v1") + if err != nil { + t.Fatalf("status get: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("status code=%d want 200", resp.StatusCode) + } + var body StatusProjection + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + t.Fatalf("status decode: %v", err) + } + return body +}