From 704eedac6730fac5499055087b73ca2ea96d92f5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:16:35 -0800 Subject: [PATCH] fix: guard promotion readiness and retire settled replica sessions --- .../core/adapter/recovery_dedup_test.go | 21 +++- seaweed-block/core/engine/apply.go | 1 + seaweed-block/core/engine/promotion_ready.go | 3 + .../apply_gate_wire_overlap_test.go | 24 ++++- seaweed-block/core/transport/replica.go | 98 ++++++++++++++++--- seaweed-block/docs/design/invariants.md | 10 +- 6 files changed, 137 insertions(+), 20 deletions(-) diff --git a/seaweed-block/core/adapter/recovery_dedup_test.go b/seaweed-block/core/adapter/recovery_dedup_test.go index 1fc3424f23..721c937c33 100644 --- a/seaweed-block/core/adapter/recovery_dedup_test.go +++ b/seaweed-block/core/adapter/recovery_dedup_test.go @@ -4,6 +4,7 @@ import ( "strconv" "sync" "testing" + "time" "github.com/seaweedfs/seaweed-block/core/engine" ) @@ -94,8 +95,24 @@ func TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery(t *testing.T) { wg.Add(1) go func() { defer wg.Done(); <-start; a.OnProbeResult(probe) }() } - close(start) - wg.Wait() + done := make(chan struct{}) + go func() { wg.Wait(); close(done) }() + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(start) }) } + t.Cleanup(func() { + release() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("concurrent probe workers did not settle during cleanup") + } + }) + release() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Fatal("concurrent probe workers did not settle") + } if got := countStarts(exec, "StartCatchUp"); got != 1 { t.Fatalf("identical delayed probes restarted healthy recovery: starts=%d path=%v", got, a.CommandLog()) } diff --git a/seaweed-block/core/engine/apply.go b/seaweed-block/core/engine/apply.go index 643f4dbbfe..f0ef93008f 100644 --- a/seaweed-block/core/engine/apply.go +++ b/seaweed-block/core/engine/apply.go @@ -313,6 +313,7 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra } fact := e.ProgressFact() if st.Recovery.FactsMissing { + st.Recovery.R = max(st.Recovery.R, fact.ReplicaR) st.Recovery.S, st.Recovery.H = fact.PrimaryS, fact.PrimaryH st.Recovery.FactsMissing = false } diff --git a/seaweed-block/core/engine/promotion_ready.go b/seaweed-block/core/engine/promotion_ready.go index 9f8f8f79e6..ef1426ee72 100644 --- a/seaweed-block/core/engine/promotion_ready.go +++ b/seaweed-block/core/engine/promotion_ready.go @@ -2,6 +2,7 @@ package engine const ( PromotionReadyReasonReady = "promotion_ready" + PromotionReadyReasonRecoveryActive = "recovery_active" PromotionReadyReasonNotMember = "not_member" PromotionReadyReasonNotReachable = "not_reachable" PromotionReadyReasonNotCaughtUp = "not_caught_up" @@ -35,6 +36,8 @@ func BuildPromotionReadyFact(st *ReplicaState) PromotionReadyFact { fact.Reason = PromotionReadyReasonNotMember case st.Reachability.Status != ProbeReachable: fact.Reason = PromotionReadyReasonNotReachable + case hasActiveSession(st): + fact.Reason = PromotionReadyReasonRecoveryActive case st.Recovery.Decision != DecisionNone: fact.Reason = PromotionReadyReasonNotCaughtUp case st.Identity.Epoch > st.Reachability.FencedEpoch: diff --git a/seaweed-block/core/replication/apply_gate_wire_overlap_test.go b/seaweed-block/core/replication/apply_gate_wire_overlap_test.go index e6a0040e50..f3f41a5e1c 100644 --- a/seaweed-block/core/replication/apply_gate_wire_overlap_test.go +++ b/seaweed-block/core/replication/apply_gate_wire_overlap_test.go @@ -15,6 +15,14 @@ type heldAdmittedRecovery struct { *ReplicaApplyGate entered, release chan struct{} done chan error + closed chan uint64 +} + +func (h *heldAdmittedRecovery) CloseSession(id uint64) { + h.ReplicaApplyGate.CloseSession(id) + if h.closed != nil { + h.closed <- id + } } func (h *heldAdmittedRecovery) ApplyRecovery(l transport.RecoveryLineage, lba uint32, data []byte, lsn uint64) error { @@ -32,7 +40,7 @@ func (h *heldAdmittedRecovery) ApplyRecovery(l transport.RecoveryLineage, lba ui // advances that check, then reach the apply gate after the newer write. func TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes(t *testing.T) { store := storage.NewBlockStore(64, blockSize) - h := &heldAdmittedRecovery{ReplicaApplyGate: NewReplicaApplyGate(store), entered: make(chan struct{}), release: make(chan struct{}), done: make(chan error, 1)} + h := &heldAdmittedRecovery{ReplicaApplyGate: NewReplicaApplyGate(store), entered: make(chan struct{}), release: make(chan struct{}), done: make(chan error, 1), closed: make(chan uint64, 8)} listener, err := transport.NewReplicaListenerWithApplyHook("127.0.0.1:0", store, h) if err != nil { t.Fatal(err) @@ -79,6 +87,9 @@ func TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes(t *testing.T) { want := bytes.Repeat([]byte{0xBB}, blockSize) send(c2, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: newer, LBA: 5, Data: want, LSN: 120})) barrier(c2, newer) + if _, _, _, found := h.SessionState(old.SessionID); !found { + t.Fatal("admitted old frame lost coverage before settlement") + } release() select { case err := <-h.done: @@ -88,6 +99,17 @@ func TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes(t *testing.T) { case <-time.After(3 * time.Second): t.Fatal("admitted old frame did not settle") } + select { + case id := <-h.closed: + if id != old.SessionID { + t.Fatalf("retired session=%d want old%d", id, old.SessionID) + } + case <-time.After(3 * time.Second): + t.Fatal("settled admitted old session was not retired") + } + if _, _, _, found := h.SessionState(old.SessionID); found { + t.Fatal("settled old coverage survived retirement") + } got, err := store.Read(5) if err != nil || !bytes.Equal(got, want) { t.Fatalf("admitted old wire session regressed bytes: err=%v", err) diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index a0ce27c2f4..9ac13c5017 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -40,6 +40,8 @@ const ( // surface here as errors. // RecoveryPrefixHook accepts explicit completed-prefix certificates. It does // not derive source coverage from Sync. Admission is checked at the effect. +type SessionRetirer interface{ CloseSession(sessionID uint64) } + type RecoveryPrefixHook interface { CertifyRecoveryPrefix(lineage RecoveryLineage) error CertifiedPrefix() uint64 @@ -65,9 +67,11 @@ type ReplicaListener struct { wg sync.WaitGroup applyHook ApplyHook // optional gate plug-in; nil = direct apply - mu sync.Mutex - activeLineage RecoveryLineage - prefixEligible RecoveryLineage // one active source-covered recovery certificate + mu sync.Mutex + activeLineage RecoveryLineage + prefixEligible RecoveryLineage // one active source-covered recovery certificate + sessionFrames map[uint64]int + retiringSessions map[uint64]bool // epochFloor is the highest epoch this host has taken a role at // (G2): mutating traffic below it is refused. primary is set while // this host is the primary: then every inbound replication mutation @@ -163,21 +167,31 @@ func (r *ReplicaListener) raiseFloor(epoch uint64) error { func (r *ReplicaListener) admitMutation(l RecoveryLineage) bool { r.mu.Lock() prev := r.activeLineage - r.mu.Unlock() - if !r.acceptMutationLineage(l) { + if !r.acceptMutationLineageLocked(l) { + r.mu.Unlock() return false } + if r.sessionFrames == nil { + r.sessionFrames = make(map[uint64]int) + } + r.sessionFrames[l.SessionID]++ // register before another lineage can retire it + r.mu.Unlock() if err := r.raiseFloor(l.Epoch); err != nil { - // Nothing changes on a refused frame: undo the lineage advance, - // unless another frame has moved it on since. r.mu.Lock() if r.activeLineage == l { r.activeLineage = prev } + r.markSessionRetiringLocked(l.SessionID) r.mu.Unlock() + r.endSessionFrame(l.SessionID) log.Printf("replica: refuse mutation at epoch %d: %v", l.Epoch, err) return false } + r.mu.Lock() + if prev.SessionID != l.SessionID { + r.markSessionRetiringLocked(prev.SessionID) + } + r.mu.Unlock() return true } @@ -245,6 +259,7 @@ func (r *ReplicaListener) Stop() { close(r.stopCh) r.listener.Close() r.wg.Wait() + r.closeSettledSessions() } // StopHard is like Stop but also forcibly closes all active handler @@ -280,6 +295,7 @@ func (r *ReplicaListener) StopHard() { _ = c.Close() } r.wg.Wait() + r.closeSettledSessions() } func (r *ReplicaListener) acceptLoop() { @@ -370,6 +386,14 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { // the fence waits for storage effects only, never for the network. var replyType byte var reply []byte + var admittedSession uint64 + admit := func(l RecoveryLineage) bool { + if !r.admitMutation(l) { + return false + } + admittedSession = l.SessionID + return true + } stop := func() bool { switch msgType { case MsgRecoveryLaneStart: @@ -378,7 +402,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode recovery lane start: %v", err) return true } - if !r.admitMutation(lineage) { + if !admit(lineage) { log.Printf("replica: reject stale recovery lane start session=%d epoch=%d endpointVersion=%d", lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true @@ -392,7 +416,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode ship entry: %v", err) return true } - if !r.admitMutation(entry.Lineage) { + if !admit(entry.Lineage) { log.Printf("replica: reject stale ship session=%d epoch=%d endpointVersion=%d", entry.Lineage.SessionID, entry.Lineage.Epoch, entry.Lineage.EndpointVersion) return true @@ -466,7 +490,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode rebuild block: %v", err) return true } - if !r.admitMutation(lineage) { + if !admit(lineage) { log.Printf("replica: reject stale rebuild block session=%d epoch=%d endpointVersion=%d", lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true @@ -489,7 +513,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode rebuild done: %v", err) return true } - if !r.admitMutation(lineage) { + if !admit(lineage) { log.Printf("replica: reject stale rebuild done session=%d epoch=%d endpointVersion=%d", lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true @@ -535,7 +559,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode barrier req: %v", err) return true } - if !r.admitMutation(lineage) { + if !admit(lineage) { log.Printf("replica: reject stale barrier session=%d epoch=%d endpointVersion=%d", lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true @@ -557,6 +581,9 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { } return false }() + if admittedSession != 0 { + r.endSessionFrame(admittedSession) + } if mutating { r.endMutationFrame() } @@ -749,6 +776,10 @@ func (r *ReplicaListener) AdmitAsReplica(epoch uint64) error { func (r *ReplicaListener) acceptMutationLineage(incoming RecoveryLineage) bool { r.mu.Lock() defer r.mu.Unlock() + return r.acceptMutationLineageLocked(incoming) +} + +func (r *ReplicaListener) acceptMutationLineageLocked(incoming RecoveryLineage) bool { if incoming.SessionID == 0 || incoming.Epoch == 0 || incoming.EndpointVersion == 0 { return false @@ -837,3 +868,46 @@ func (r *ReplicaListener) markPrefixEligibility(lineage RecoveryLineage, fullBas r.prefixEligible = lineage } } + +// Retirement tracks logical-session frames, not socket lifetimes. A newer +// session may run while an admitted older frame is parked before the hook. +// Lock order remains listener.mu -> gate.mu; versions and P are not released. +func (r *ReplicaListener) markSessionRetiringLocked(id uint64) { + if id == 0 { + return + } + if r.retiringSessions == nil { + r.retiringSessions = make(map[uint64]bool) + } + r.retiringSessions[id] = true + r.retireSessionIfSettledLocked(id) +} +func (r *ReplicaListener) retireSessionIfSettledLocked(id uint64) { + if !r.retiringSessions[id] || id == r.activeLineage.SessionID || r.sessionFrames[id] != 0 { + return + } + if hook, ok := r.applyHook.(SessionRetirer); ok { + hook.CloseSession(id) + } + delete(r.retiringSessions, id) +} +func (r *ReplicaListener) endSessionFrame(id uint64) { + r.mu.Lock() + defer r.mu.Unlock() + r.sessionFrames[id]-- + if r.sessionFrames[id] == 0 { + delete(r.sessionFrames, id) + } + r.retireSessionIfSettledLocked(id) +} +func (r *ReplicaListener) closeSettledSessions() { + r.mu.Lock() + defer r.mu.Unlock() + if hook, ok := r.applyHook.(SessionRetirer); ok { + hook.CloseSession(r.activeLineage.SessionID) + for id := range r.retiringSessions { + hook.CloseSession(id) + } + } + r.retiringSessions = nil +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index fabac920e5..6907808089 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -119,7 +119,7 @@ Completed recovery plus post-close healthy publication sends an explicit full-li certificate; current listener admission and the durable boundary guard it. A catch-up certificate also requires a covered starting image (local R at its lane marker no greater than P); a completed full BASE supplies its own image. A missing certificate retains history. Sync R, ordinary live traffic and session changes do not advance P. This implementation prunes at successful recovery certification only; healthy-run growth remains an -RF2 qualification limitation until ordered-live certification is wired (#297). Session coverage teardown is separate. +RF2 qualification limitation until ordered-live certification is wired (#297). Settled superseded logical sessions release coverage after their admitted frames finish; shared versions and P survive. Seed enumeration and healthy-run growth remain RF2 qualification limits. **Host role and listener admission.** @@ -141,9 +141,7 @@ RF2 qualification limitation until ordered-live certification is wired (#297). S | From | To | Event and guard | Enforced in | Protects | |---|---|---|---|---| | `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | -| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | Each runtime observation selects at most one recovery session; delayed same-identity facts cannot restart a completed prefix, while a higher primary head or replacement identity still permits new work. | M3 recovery observation / preparation | `core/adapter/adapter.go`, `normalize.go`; `core/engine/apply.go` | `TestAdapter_OneRecoveryFromPostCloseStalledAck`, `TestAdapter_OneRecoveryPreparedWithinProbeBatch`, `TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery`, `TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery`, `TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery | ACTIVE | -| `INV-REPL-NO-PER-LBA-DATA-REGRESSION` | Successful applies share a replica-wide per-LBA version across all sessions and lanes. Stale recovery advances only its own coverage; stale live entries fail. Closing a session or merging a lower seed cannot erase the applied version; failed physical writes do not publish it. Only an explicit completed-recovery prefix certificate advances P and prunes entries at/below P; the floor still rejects/skips old records. Synced R is not a certificate. Restart safety still requires substrate seeds. | M3 replica apply / session release | `core/replication/apply_gate.go`; blockvolume `replicationIngress` | `TestReplicationIngressSharesApplyVersionsAcrossSessions`, `TestApplyGate_OverlappingSessionsNeverRegressBytes`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes`, `TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion`, `TestApplyGate_FailedWriteDoesNotPublishReplicaVersion`, `TestApplyGate_CertifiedRecoveryClosesBoundVersionHistory`, `TestApplyGate_PrunedDurableVersionsRemainStale`, `TestApplyGate_CertifiedPrefixFreezesAcrossSessions`, `TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole`, `TestApplyGate_HealthyRecoveryPublishesWirePrefix`, `TestApplyGate_WirePrefixCannotIntroduceOrReviveSession` | `ReplicaApplyOrder` NoRegression; `ReplicaPrefixFloor` NoRegression/CertifiedCoverage/OnlySuffix | ACTIVE | -| `INV-REPL-CATCHUP-REBUILD-001` | +| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001`, `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | | `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | | any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | | `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | @@ -335,7 +333,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -81 rows: 70 ACTIVE, 11 STUB; 15 kept from the internal ledger, 66 new. +83 rows: 72 ACTIVE, 11 STUB; 15 kept from the internal ledger, 68 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -425,6 +423,8 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| +| `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | Each runtime observation selects at most one recovery session; delayed same-identity facts cannot restart a completed prefix, while a higher primary head or replacement identity still permits new work. | M3 recovery observation / preparation | `core/adapter/adapter.go`, `normalize.go`; `core/engine/apply.go` | `TestAdapter_OneRecoveryFromPostCloseStalledAck`, `TestAdapter_OneRecoveryPreparedWithinProbeBatch`, `TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery`, `TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery`, `TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery | ACTIVE | +| `INV-REPL-NO-PER-LBA-DATA-REGRESSION` | Successful applies share a replica-wide per-LBA version across all sessions and lanes. Stale recovery advances only its own coverage; stale live entries fail. Closing a session or merging a lower seed cannot erase the applied version; failed physical writes do not publish it. Only an explicit completed-recovery prefix certificate advances P and prunes entries at/below P; the floor still rejects/skips old records. Synced R is not a certificate. Restart safety still requires substrate seeds. | M3 replica apply / session release | `core/replication/apply_gate.go`; blockvolume `replicationIngress` | `TestReplicationIngressSharesApplyVersionsAcrossSessions`, `TestApplyGate_OverlappingSessionsNeverRegressBytes`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes`, `TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion`, `TestApplyGate_FailedWriteDoesNotPublishReplicaVersion`, `TestApplyGate_CertifiedRecoveryClosesBoundVersionHistory`, `TestApplyGate_PrunedDurableVersionsRemainStale`, `TestApplyGate_CertifiedPrefixFreezesAcrossSessions`, `TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole`, `TestApplyGate_HealthyRecoveryPublishesWirePrefix`, `TestApplyGate_WirePrefixCannotIntroduceOrReviveSession` | `ReplicaApplyOrder` NoRegression; `ReplicaPrefixFloor` NoRegression/CertifiedCoverage/OnlySuffix | ACTIVE | | `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | | `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | | `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE |