From c400b28f5fb1015fc80c50f75e1782aa46201326 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:31:51 -0800 Subject: [PATCH 01/20] test: reproduce cross-session replica byte regression --- .../apply_gate_cross_session_test.go | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 seaweed-block/core/replication/apply_gate_cross_session_test.go diff --git a/seaweed-block/core/replication/apply_gate_cross_session_test.go b/seaweed-block/core/replication/apply_gate_cross_session_test.go new file mode 100644 index 0000000000..15570d87e8 --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_cross_session_test.go @@ -0,0 +1,48 @@ +package replication + +import ( + "bytes" + "testing" +) + +// Both sessions are initialized before either writes the contested LBA. +// This fixes the ordering without relying on a probabilistic goroutine race. +func TestApplyGate_OverlappingSessionsNeverRegressBytes(t *testing.T) { + for _, live := range []bool{false, true} { + name := "recovery_then_older_recovery" + if live { + name = "live_then_older_recovery" + } + t.Run(name, func(t *testing.T) { + gate, store := newGate(t) + older, newer := recoveryLineage(10, 120), recoveryLineage(11, 120) + if err := gate.ApplyRecovery(older, 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if err := gate.ApplyRecovery(newer, 1, makeData(2), 2); err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{0xBB}, blockSize) + apply := gate.ApplyRecovery + if live { + apply = gate.ApplyLive + } + if err := apply(newer, 5, want, 120); err != nil { + t.Fatal(err) + } + if err := gate.ApplyRecovery(older, 5, bytes.Repeat([]byte{0xAA}, blockSize), 95); err != nil { + t.Fatal(err) + } + got, err := store.Read(5) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatalf("cross-session stale recovery regressed bytes: got %x want %x", got[:8], want[:8]) + } + if !gate.SessionRecoveryCoverage(older.SessionID, 5) { + t.Fatal("stale recovery did not advance its own coverage") + } + }) + } +} From 67e0cf0bbe7a7661134795c5a91d6748d4d7418e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:34:31 -0800 Subject: [PATCH 02/20] test: pin duplicate recovery preparation and delayed probe schedules --- .../core/adapter/recovery_dedup_test.go | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 seaweed-block/core/adapter/recovery_dedup_test.go diff --git a/seaweed-block/core/adapter/recovery_dedup_test.go b/seaweed-block/core/adapter/recovery_dedup_test.go new file mode 100644 index 0000000000..86ed57f6ed --- /dev/null +++ b/seaweed-block/core/adapter/recovery_dedup_test.go @@ -0,0 +1,65 @@ +package adapter + +import ( + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/engine" +) + +func dedupAdapter(t *testing.T) (*VolumeReplicaAdapter, *mockExecutor, ProbeResult) { + t.Helper() + exec := newMockExecutor() + exec.autoClose = false + // The automatic probe is irrelevant to this controlled delivery schedule. + // Its wrong-replica result is rejected regardless of when it returns. + exec.probeResults["r1"] = ProbeResult{ReplicaID: "other"} + a := NewVolumeReplicaAdapter(exec) + a.OnAssignment(AssignmentInfo{VolumeID: "vol1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}) + probe := ProbeResult{ReplicaID: "r1", Success: true, EndpointVersion: 1, TransportEpoch: 1, + ReplicaFlushedLSN: 50, PrimaryTailLSN: 10, PrimaryHeadLSN: 100} + a.OnProbeResult(probe) + t.Cleanup(func() { + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) + }) + return a, exec, probe +} + +func TestAdapter_OneRecoveryPreparedWithinProbeBatch(t *testing.T) { + a, exec, probe := dedupAdapter(t) + sid := exec.latestSessionID("StartCatchUp") + // A failed start permits a new probe to retry. Both reachability and facts + // in that one probe must see the first newly prepared recovery session. + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: sid, FailureKind: engine.RecoveryFailureStartTimeout}) + a.OnProbeResult(probe) + if got := countStarts(exec, "StartCatchUp"); got != 2 { + t.Fatalf("one probe batch emitted duplicate recovery: starts=%d want initial+one retry", got) + } +} + +func TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery(t *testing.T) { + for _, n := range []int{8, 5} { + t.Run(string(rune('0'+n)), func(t *testing.T) { + a, exec, probe := dedupAdapter(t) + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) + a.OnDurableAck(DurableAckResult{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100}) + if p := a.Projection(); p.Mode != engine.ModeHealthy { + t.Fatalf("precondition not healthy: %+v", p) + } + var wg sync.WaitGroup + start := make(chan struct{}) + for i := 0; i < n; i++ { + wg.Add(1) + go func() { defer wg.Done(); <-start; a.OnProbeResult(probe) }() + } + close(start) + wg.Wait() + if got := countStarts(exec, "StartCatchUp"); got != 1 { + t.Fatalf("identical delayed probes restarted healthy recovery: starts=%d path=%v", got, a.CommandLog()) + } + if p := a.Projection(); p.Mode != engine.ModeHealthy { + t.Fatalf("old facts regressed healthy replica: %+v", p) + } + }) + } +} From 14d724e3de7b23948390a3387411598d58bcd6be Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:39:56 -0800 Subject: [PATCH 03/20] test: witness an admitted old wire frame overtaken by a newer session --- .../apply_gate_wire_overlap_test.go | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 seaweed-block/core/replication/apply_gate_wire_overlap_test.go diff --git a/seaweed-block/core/replication/apply_gate_wire_overlap_test.go b/seaweed-block/core/replication/apply_gate_wire_overlap_test.go new file mode 100644 index 0000000000..e6a0040e50 --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_wire_overlap_test.go @@ -0,0 +1,95 @@ +package replication + +import ( + "bytes" + "net" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +type heldAdmittedRecovery struct { + *ReplicaApplyGate + entered, release chan struct{} + done chan error +} + +func (h *heldAdmittedRecovery) ApplyRecovery(l transport.RecoveryLineage, lba uint32, data []byte, lsn uint64) error { + if l.SessionID == 1 && lsn == 95 { + close(h.entered) + <-h.release + err := h.ReplicaApplyGate.ApplyRecovery(l, lba, data, lsn) + h.done <- err + return err + } + return h.ReplicaApplyGate.ApplyRecovery(l, lba, data, lsn) +} + +// An old frame can pass the listener's lineage check before a newer session +// 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)} + listener, err := transport.NewReplicaListenerWithApplyHook("127.0.0.1:0", store, h) + if err != nil { + t.Fatal(err) + } + listener.Serve() + var once sync.Once + release := func() { once.Do(func() { close(h.release) }) } + t.Cleanup(func() { release(); listener.Stop() }) + dial := func() net.Conn { + c, err := net.DialTimeout("tcp", listener.Addr(), 2*time.Second) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + if err := c.SetDeadline(time.Now().Add(3 * time.Second)); err != nil { + t.Fatal(err) + } + return c + } + send := func(c net.Conn, kind byte, payload []byte) { + if err := transport.WriteMsg(c, kind, payload); err != nil { + t.Fatal(err) + } + } + barrier := func(c net.Conn, l transport.RecoveryLineage) { + send(c, transport.MsgBarrierReq, transport.EncodeLineage(l)) + kind, _, err := transport.ReadMsg(c) + if err != nil || kind != transport.MsgBarrierResp { + t.Fatalf("barrier: kind=%d err=%v", kind, err) + } + } + old, newer := recoveryLineage(1, 120), recoveryLineage(2, 120) + c1, c2 := dial(), dial() + send(c1, transport.MsgRecoveryLaneStart, transport.EncodeLineage(old)) + send(c1, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: old, LBA: 0, Data: makeData(1), LSN: 1})) + barrier(c1, old) // initialize the old session before the competing apply + send(c1, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: old, LBA: 5, Data: makeData(0xAA), LSN: 95})) + select { + case <-h.entered: + case <-time.After(3 * time.Second): + t.Fatal("old frame never reached post-admission hook") + } + send(c2, transport.MsgRecoveryLaneStart, transport.EncodeLineage(newer)) + 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) + release() + select { + case err := <-h.done: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("admitted old frame did not settle") + } + got, err := store.Read(5) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("admitted old wire session regressed bytes: err=%v", err) + } +} From 056c80a957f143367d35a30e40f07528aa091fd8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:44:32 -0800 Subject: [PATCH 04/20] test: expose missing production replica apply-gate wiring --- .../replication_ingress_apply_test.go | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go diff --git a/seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go b/seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go new file mode 100644 index 0000000000..eb37cc413b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go @@ -0,0 +1,52 @@ +package main + +import ( + "bytes" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +func TestReplicationIngressSharesApplyVersionsAcrossSessions(t *testing.T) { + store := storage.NewBlockStore(64, 4096) + r := newReplicationIngress(flags{dataAddr: "127.0.0.1:0", volumeID: "vol1"}, store) + if err := r.AdmitAsReplica(1); err != nil { + t.Fatal(err) + } + t.Cleanup(r.Stop) + want := bytes.Repeat([]byte{0xBB}, 4096) + ship := func(session, lsn uint64, data []byte, recovery bool) { + c, err := net.DialTimeout("tcp", r.listener.Addr(), 2*time.Second) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if err := c.SetDeadline(time.Now().Add(3 * time.Second)); err != nil { + t.Fatal(err) + } + lineage := transport.RecoveryLineage{SessionID: session, Epoch: 1, EndpointVersion: 1, TargetLSN: 120} + send := func(kind byte, data []byte) { + if err := transport.WriteMsg(c, kind, data); err != nil { + t.Fatal(err) + } + } + if recovery { + send(transport.MsgRecoveryLaneStart, transport.EncodeLineage(lineage)) + } + send(transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: lineage, LBA: 5, Data: data, LSN: lsn})) + send(transport.MsgBarrierReq, transport.EncodeLineage(lineage)) + kind, _, err := transport.ReadMsg(c) + if err != nil || kind != transport.MsgBarrierResp { + t.Fatalf("barrier: kind=%d err=%v", kind, err) + } + } + ship(1, 120, want, false) + ship(2, 95, bytes.Repeat([]byte{0xAA}, 4096), true) + got, err := store.Read(5) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("production ingress allowed cross-session byte regression: err=%v", err) + } +} From 364118a28e77bd21f001bfc4b0c2c0796b5b8399 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:46:11 -0800 Subject: [PATCH 05/20] fix: deduplicate recovery observations and share replica apply versions --- .../cmd/blockvolume/replication_ingress.go | 8 ++- seaweed-block/core/adapter/adapter.go | 32 +++++----- seaweed-block/core/adapter/normalize.go | 22 +++---- .../core/adapter/recovery_dedup_test.go | 15 ++++- seaweed-block/core/calibration/scenarios.go | 32 +++++----- .../core/calibration/scenarios_test.go | 2 +- seaweed-block/core/engine/apply.go | 4 +- .../core/engine/recovery_probe_order_test.go | 28 +++++++++ seaweed-block/core/replication/apply_gate.go | 62 +++++++++---------- .../apply_gate_cross_session_test.go | 58 +++++++++++++++++ .../core/replication/apply_gate_test.go | 13 ++-- seaweed-block/core/transport/replica.go | 8 ++- seaweed-block/docs/design/block-design.md | 2 + seaweed-block/docs/design/invariants.md | 6 +- seaweed-block/docs/spec/README.md | 3 + seaweed-block/docs/spec/ReplicaApplyOrder.tla | 44 +++++++++++++ .../spec/cfg/R292_red_delayed_prepare.cfg | 5 ++ .../docs/spec/cfg/R292_red_probe_rollback.cfg | 5 ++ .../spec/cfg/R292_red_session_versions.cfg | 5 ++ seaweed-block/docs/spec/cfg/R292_safe.cfg | 5 ++ seaweed-block/docs/spec/run.sh | 1 + 21 files changed, 274 insertions(+), 86 deletions(-) create mode 100644 seaweed-block/core/engine/recovery_probe_order_test.go create mode 100644 seaweed-block/docs/spec/ReplicaApplyOrder.tla create mode 100644 seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg create mode 100644 seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg create mode 100644 seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg create mode 100644 seaweed-block/docs/spec/cfg/R292_safe.cfg diff --git a/seaweed-block/cmd/blockvolume/replication_ingress.go b/seaweed-block/cmd/blockvolume/replication_ingress.go index 89ab03da31..5ecd7a8eec 100644 --- a/seaweed-block/cmd/blockvolume/replication_ingress.go +++ b/seaweed-block/cmd/blockvolume/replication_ingress.go @@ -7,6 +7,7 @@ import ( "sync" "github.com/seaweedfs/seaweed-block/core/recovery" + "github.com/seaweedfs/seaweed-block/core/replication" "github.com/seaweedfs/seaweed-block/core/storage" "github.com/seaweedfs/seaweed-block/core/transport" ) @@ -18,6 +19,7 @@ type replicationIngress struct { mu sync.Mutex addr, volumeID, floorPath string store storage.LogicalStorage + applyGate *replication.ReplicaApplyGate dualLane bool // rf1Only, when set, refuses every role with replica slots with this reason // (walstore-chunk). The host latches the error: no role is adopted, not Healthy. @@ -86,8 +88,12 @@ func (r *replicationIngress) roleLocked(epoch uint64, primary bool) error { listener := r.listener fresh := listener == nil if fresh { + // One version map per replica store, surviving listener role transitions. + if r.applyGate == nil { + r.applyGate = replication.NewReplicaApplyGate(r.store) + } var err error - listener, err = transport.NewReplicaListenerWithFloor(r.addr, r.store, r.volumeID, r.floorPath) + listener, err = transport.NewReplicaListenerWithFloorAndApplyHook(r.addr, r.store, r.volumeID, r.floorPath, r.applyGate) if err != nil { return err } diff --git a/seaweed-block/core/adapter/adapter.go b/seaweed-block/core/adapter/adapter.go index bc79ef4505..9798315423 100644 --- a/seaweed-block/core/adapter/adapter.go +++ b/seaweed-block/core/adapter/adapter.go @@ -384,8 +384,9 @@ func (a *VolumeReplicaAdapter) applyBatchAndExecute(events []engine.Event, event log.EventKind = eventKind } - var cmds []engine.Command + var queued []queuedCommand for _, ev := range events { + var cmds []engine.Command result := engine.Apply(&a.state, ev) a.trace = append(a.trace, result.Trace...) log.Projection = result.Projection @@ -407,21 +408,22 @@ func (a *VolumeReplicaAdapter) applyBatchAndExecute(events []engine.Event, event log.Commands = append(log.Commands, kind) cmds = append(cmds, cmd) } - } - // Feed session lifecycle events back into engine while still under lock - // (these are synchronous, no external calls). - sessionEvents, queued := a.prepareQueuedCommands(cmds) - for _, sev := range sessionEvents { - sr := engine.Apply(&a.state, sev) - a.trace = append(a.trace, sr.Trace...) - log.Projection = sr.Projection - log.Trace = append(log.Trace, sr.Trace...) - for _, cmd := range sr.Commands { - kind := engine.CommandKind(cmd) - a.cmdLog = append(a.cmdLog, kind) - log.Commands = append(log.Commands, kind) - queued = append(queued, queuedCommand{cmd: cmd}) + // Reserve recovery before applying the next event in this observation. + // Otherwise both reachability and facts can emit a Start for an idle slot. + sessionEvents, prepared := a.prepareQueuedCommands(cmds) + queued = append(queued, prepared...) + for _, sev := range sessionEvents { + sr := engine.Apply(&a.state, sev) + a.trace = append(a.trace, sr.Trace...) + log.Projection = sr.Projection + log.Trace = append(log.Trace, sr.Trace...) + for _, cmd := range sr.Commands { + kind := engine.CommandKind(cmd) + a.cmdLog = append(a.cmdLog, kind) + log.Commands = append(log.Commands, kind) + queued = append(queued, queuedCommand{cmd: cmd}) + } } } a.mu.Unlock() diff --git a/seaweed-block/core/adapter/normalize.go b/seaweed-block/core/adapter/normalize.go index 341a2ce314..082ab4e768 100644 --- a/seaweed-block/core/adapter/normalize.go +++ b/seaweed-block/core/adapter/normalize.go @@ -111,8 +111,11 @@ func NormalizeAssignment(a AssignmentInfo) engine.Event { // NormalizeProbe converts a probe result into engine events. // A successful probe produces up to 2 events: -// 1. ProbeSucceeded (reachability) -// 2. RecoveryFactsObserved (R/S/H boundaries) +// 1. RecoveryFactsObserved (R/S/H boundaries) +// 2. ProbeSucceeded (reachability) +// +// Fresh boundaries precede reachability so its decision cannot reserve a +// recovery using the previous probe's retention window. // // A failed probe produces 1 event: // 1. ProbeFailed @@ -132,6 +135,12 @@ func NormalizeProbe(p ProbeResult) []engine.Event { } events := []engine.Event{ + engine.RecoveryFactsObserved{ + ReplicaID: p.ReplicaID, + EndpointVersion: p.EndpointVersion, + TransportEpoch: p.TransportEpoch, + R: p.ReplicaFlushedLSN, S: p.PrimaryTailLSN, H: p.PrimaryHeadLSN, + }, engine.ProbeSucceeded{ ReplicaID: p.ReplicaID, EndpointVersion: p.EndpointVersion, @@ -139,15 +148,6 @@ func NormalizeProbe(p ProbeResult) []engine.Event { }, } - events = append(events, engine.RecoveryFactsObserved{ - ReplicaID: p.ReplicaID, - EndpointVersion: p.EndpointVersion, - TransportEpoch: p.TransportEpoch, - R: p.ReplicaFlushedLSN, - S: p.PrimaryTailLSN, - H: p.PrimaryHeadLSN, - }) - return events } diff --git a/seaweed-block/core/adapter/recovery_dedup_test.go b/seaweed-block/core/adapter/recovery_dedup_test.go index 86ed57f6ed..f195941461 100644 --- a/seaweed-block/core/adapter/recovery_dedup_test.go +++ b/seaweed-block/core/adapter/recovery_dedup_test.go @@ -1,6 +1,7 @@ package adapter import ( + "strconv" "sync" "testing" @@ -20,7 +21,7 @@ func dedupAdapter(t *testing.T) (*VolumeReplicaAdapter, *mockExecutor, ProbeResu ReplicaFlushedLSN: 50, PrimaryTailLSN: 10, PrimaryHeadLSN: 100} a.OnProbeResult(probe) t.Cleanup(func() { - a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: max(exec.latestSessionID("StartCatchUp"), exec.latestSessionID("StartRebuild")), Success: true, AchievedLSN: 100}) }) return a, exec, probe } @@ -37,9 +38,19 @@ func TestAdapter_OneRecoveryPreparedWithinProbeBatch(t *testing.T) { } } +func TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery(t *testing.T) { + a, exec, probe := dedupAdapter(t) + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), FailureKind: engine.RecoveryFailureStartTimeout}) + probe.PrimaryTailLSN = 60 // the former catch-up prefix is now recycled + a.OnProbeResult(probe) + if catchup, rebuild := countStarts(exec, "StartCatchUp"), countStarts(exec, "StartRebuild"); catchup != 1 || rebuild != 1 { + t.Fatalf("probe reserved recovery from stale bounds: catchup=%d rebuild=%d", catchup, rebuild) + } +} + func TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery(t *testing.T) { for _, n := range []int{8, 5} { - t.Run(string(rune('0'+n)), func(t *testing.T) { + t.Run(strconv.Itoa(n), func(t *testing.T) { a, exec, probe := dedupAdapter(t) a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) a.OnDurableAck(DurableAckResult{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100}) diff --git a/seaweed-block/core/calibration/scenarios.go b/seaweed-block/core/calibration/scenarios.go index 1b69b5378f..94c364e74c 100644 --- a/seaweed-block/core/calibration/scenarios.go +++ b/seaweed-block/core/calibration/scenarios.go @@ -1,6 +1,7 @@ package calibration import ( + "fmt" "strings" "time" @@ -302,6 +303,7 @@ func (*scenarioC5OrderStable) Expect() Expected { DataIntegrityExpected: true, } } + // perturbation is one of the concrete interleaving patterns C5 runs. // Each produces the SAME underlying facts on the SAME replica (r1) // but delivers events to the adapter in a different order, timing, or @@ -324,11 +326,11 @@ func (*scenarioC5OrderStable) Expect() Expected { type perturbation int const ( - pertBaseline perturbation = iota // assign + wait - pertPreAssignProbe // one valid pre-assign probe, wiped when identity arrives - pertPreAssignStorm // 8 concurrent pre-assign probes, then assign - pertRepeatAssign // assign twice with identical epoch/endpointVersion (idempotent) - pertStaggeredAssign // 5 concurrent assigns with identical identity, then wait + pertBaseline perturbation = iota // assign + wait + pertPreAssignProbe // one valid pre-assign probe, wiped when identity arrives + pertPreAssignStorm // 8 concurrent pre-assign probes, then assign + pertRepeatAssign // assign twice with identical epoch/endpointVersion (idempotent) + pertStaggeredAssign // 5 concurrent assigns with identical identity, then wait ) func (*scenarioC5OrderStable) Run() (Observed, error) { @@ -345,6 +347,7 @@ func (*scenarioC5OrderStable) Run() (Observed, error) { sameDecision := true sameFinalMode := true sameRecoverySig := true + var divergentPath []string sameCloseCount := true dataOK := true @@ -381,6 +384,9 @@ func (*scenarioC5OrderStable) Run() (Observed, error) { } if sig != firstSig { sameRecoverySig = false + if divergentPath == nil { + divergentPath = append([]string{fmt.Sprintf("perturbation=%d baseline=%v", p, first.CommandPath)}, obs.CommandPath...) + } } if obs.CloseEventCount != first.CloseEventCount { sameCloseCount = false @@ -401,10 +407,9 @@ func (*scenarioC5OrderStable) Run() (Observed, error) { } if !sameRecoverySig { // Pollute the command path marker so the reader cannot miss - // that the recovery signature drifted. The baseline first-run - // path is preserved alongside the marker so divergence-log - // authors can still see what the first run looked like. - out.CommandPath = append([]string{"DIVERGED_ACROSS_RUNS_RECOVERY_SIG"}, first.CommandPath...) + // that the recovery signature drifted. Preserve the actual divergent + // perturbation and path alongside the baseline. + out.CommandPath = append([]string{"DIVERGED_ACROSS_RUNS_RECOVERY_SIG"}, divergentPath...) } if !sameCloseCount { // Set CloseEventCount to a negative sentinel so the JSON @@ -446,13 +451,8 @@ func extractRecoverySignature(path []string) recoverySignature { // R/S/H); only the delivery shape — timing, ordering, concurrency, // assignment idempotence — varies. // -// All post-assignment probe variations are deliberately omitted: a -// probe fired with pre-captured facts after the engine has converged -// would deliver STALE R to the engine and legitimately trigger -// re-recovery. Treating that as a C5 failure would conflate engine -// correctness with A1/A4. Treating it as a C5 success would require -// gating the engine's fact-processing, which is a route change that -// belongs outside Phase 06. +// Delayed same-identity probes cannot lower completed durable R; the +// concurrent variants exercise both pending and post-completion delivery. func applyPerturbation(h *harness, p perturbation) { _, _, pH := h.primaryStore.Boundaries() rR, rS, _ := h.replicaStore.Boundaries() diff --git a/seaweed-block/core/calibration/scenarios_test.go b/seaweed-block/core/calibration/scenarios_test.go index 6ea75164a2..0ad50a4fc9 100644 --- a/seaweed-block/core/calibration/scenarios_test.go +++ b/seaweed-block/core/calibration/scenarios_test.go @@ -124,7 +124,7 @@ func TestC5_OrderStableAcrossRuns(t *testing.T) { // Recovery-signature divergence is signaled by a sentinel element // prepended to CommandPath. The scenario run must not hit this. if len(obs.CommandPath) > 0 && obs.CommandPath[0] == "DIVERGED_ACROSS_RUNS_RECOVERY_SIG" { - t.Fatalf("C5: recovery signature drifted across runs; first-run path=%v", obs.CommandPath[1:]) + t.Fatalf("C5: recovery signature drifted across runs; divergent perturbation/path=%v", obs.CommandPath[1:]) } // CloseEventCount sentinel: negative is used to flag cross-run // drift in the number of SessionClosedCompleted events. A legit diff --git a/seaweed-block/core/engine/apply.go b/seaweed-block/core/engine/apply.go index 9616689808..161ff88729 100644 --- a/seaweed-block/core/engine/apply.go +++ b/seaweed-block/core/engine/apply.go @@ -295,7 +295,9 @@ func applyRecoveryFacts(st *ReplicaState, e RecoveryFactsObserved, r *ApplyResul trace("stale_recovery_facts", reason) return } - st.Recovery.R = e.R + // Within one identity, delayed probes cannot undo completed durable work. + // An identity-changing assignment resets the recovery facts. + st.Recovery.R = max(st.Recovery.R, e.R) st.Recovery.S = e.S st.Recovery.H = e.H diff --git a/seaweed-block/core/engine/recovery_probe_order_test.go b/seaweed-block/core/engine/recovery_probe_order_test.go new file mode 100644 index 0000000000..011329815b --- /dev/null +++ b/seaweed-block/core/engine/recovery_probe_order_test.go @@ -0,0 +1,28 @@ +package engine + +import "testing" + +func TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity(t *testing.T) { + st := &ReplicaState{} + assignAndProbe(st) + Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 100}) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, TargetLSN: 100}) + Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 1}) + Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 1, AchievedLSN: 100}) + r := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 100}) + assertNoCommand(t, r, "StartCatchUp") + if st.Recovery.R != 100 { + t.Fatalf("old probe lowered completed R: %d", st.Recovery.R) + } + // A higher primary head remains real new work, starting after durable R. + r = Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 150}) + start := findStartCatchUp(t, r.Commands) + if start.FromLSN != 101 || start.EffectiveFrontierHint() != 150 { + t.Fatalf("new work lost or replayed completed prefix: %+v", start) + } + // Replacement identity must not inherit the old replica's progress floor. + Apply(st, AssignmentObserved{VolumeID: "vol1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 2}) + Apply(st, ProbeSucceeded{ReplicaID: "r1", EndpointVersion: 2, TransportEpoch: 2}) + r = Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 2, TransportEpoch: 2, R: 0, S: 10, H: 150}) + assertHasCommand(t, r, "StartRebuild") +} diff --git a/seaweed-block/core/replication/apply_gate.go b/seaweed-block/core/replication/apply_gate.go index 368df4e62c..0adb09402c 100644 --- a/seaweed-block/core/replication/apply_gate.go +++ b/seaweed-block/core/replication/apply_gate.go @@ -52,8 +52,8 @@ import ( // Per-LBA applied LSN source (Option C hybrid, kickoff §2.5 #1): // at session init, query `store.AppliedLSNs()` for substrate- // reported per-LBA latest-applied-LSN seed; substrates returning -// `ErrAppliedLSNsNotTracked` (BlockStore) fall back to session-only -// tracking, seeded from live + recovery applies during the session. +// `ErrAppliedLSNsNotTracked` (BlockStore) fall back to replica-lifetime +// tracking, seeded from live + recovery applies across sessions. // // Pinned invariants (T4d mini-plan §4 #6): // - INV-REPL-NO-PER-LBA-DATA-REGRESSION (goal-level) @@ -65,20 +65,17 @@ import ( type ReplicaApplyGate struct { store storage.LogicalStorage - mu sync.Mutex - sessions map[uint64]*applyGateSession // keyed by lineage.SessionID + mu sync.Mutex + sessions map[uint64]*applyGateSession // keyed by lineage.SessionID + appliedLSN map[uint32]uint64 // replica-wide, shared by every lane and session } // applyGateSession is the per-recovery-session state. Per round-44 // 2-map split: liveTouched + recoveryCovered are distinct because // the same physical LBA can appear in both (live lane wrote it AND -// recovery lane saw it during the session). appliedLSN is the -// stale-skip discriminator. +// recovery lane saw it during the session). The stale-skip discriminator +// is replica-wide and survives CloseSession. type applyGateSession struct { - // appliedLSN: highest LSN successfully applied to each LBA - // (across both lanes). The stale-skip discriminator. - appliedLSN map[uint32]uint64 - // liveTouched: LBAs the live lane wrote during this session. // Recovery must yield to these (live-wins via per-LBA LSN check). liveTouched map[uint32]bool @@ -93,13 +90,14 @@ type applyGateSession struct { // // Called by: replica-side wiring code that constructs the // `transport.ReplicaListener` with an `ApplyHook` option. -// Owns: per-session state maps; substrate query at session init. +// Owns: per-session coverage, replica-wide applied LSNs; substrate seed queries. // Borrows: store handle (caller retains; gate calls ApplyEntry + // AppliedLSNs through the interface). func NewReplicaApplyGate(store storage.LogicalStorage) *ReplicaApplyGate { return &ReplicaApplyGate{ - store: store, - sessions: make(map[uint64]*applyGateSession), + store: store, + sessions: make(map[uint64]*applyGateSession), + appliedLSN: make(map[uint32]uint64), } } @@ -167,7 +165,7 @@ func (g *ReplicaApplyGate) applyRecovery(sess *applyGateSession, lba uint32, dat g.mu.Lock() defer g.mu.Unlock() - if existing, ok := sess.appliedLSN[lba]; ok && lsn <= existing { + if existing, ok := g.appliedLSN[lba]; ok && lsn <= existing { // Stale: skip data write but ADVANCE recoveryCovered. sess.recoveryCovered[lba] = true return nil @@ -176,7 +174,7 @@ func (g *ReplicaApplyGate) applyRecovery(sess *applyGateSession, lba uint32, dat if err := g.store.ApplyEntry(lba, data, lsn); err != nil { return fmt.Errorf("apply gate: recovery substrate.ApplyEntry lba=%d lsn=%d: %w", lba, lsn, err) } - sess.appliedLSN[lba] = lsn + g.appliedLSN[lba] = lsn sess.recoveryCovered[lba] = true return nil } @@ -192,7 +190,7 @@ func (g *ReplicaApplyGate) applyLive(sess *applyGateSession, lba uint32, data [] g.mu.Lock() defer g.mu.Unlock() - if existing, ok := sess.appliedLSN[lba]; ok && lsn <= existing { + if existing, ok := g.appliedLSN[lba]; ok && lsn <= existing { // Stale: fail-loud. Caller logs + drops conn. return fmt.Errorf("apply gate: live-lane stale entry lba=%d lsn=%d <= applied=%d (INV-REPL-LIVE-LANE-STALE-FAILS-LOUD)", lba, lsn, existing) @@ -202,17 +200,17 @@ func (g *ReplicaApplyGate) applyLive(sess *applyGateSession, lba uint32, data [] if err := g.store.ApplyEntry(lba, data, lsn); err != nil { return fmt.Errorf("apply gate: live substrate.ApplyEntry lba=%d lsn=%d: %w", lba, lsn, err) } - sess.appliedLSN[lba] = lsn + g.appliedLSN[lba] = lsn sess.liveTouched[lba] = true return nil } // initSessionLocked builds a fresh session state. Called with g.mu -// held. Seeds appliedLSN from substrate AppliedLSNs() (Option C -// hybrid); falls back to empty map on `ErrAppliedLSNsNotTracked`. +// held. Merge substrate seeds into the replica-wide map without lowering +// LSNs already applied by another lane or session. Untracked substrates +// retain the gate's replica-lifetime history. func (g *ReplicaApplyGate) initSessionLocked(sessionID uint64) *applyGateSession { sess := &applyGateSession{ - appliedLSN: make(map[uint32]uint64), liveTouched: make(map[uint32]bool), recoveryCovered: make(map[uint32]bool), } @@ -220,21 +218,21 @@ func (g *ReplicaApplyGate) initSessionLocked(sessionID uint64) *applyGateSession if err != nil { // ErrAppliedLSNsNotTracked is the documented sentinel (Option // C hybrid). Anything else is an unexpected substrate error; - // log and proceed with empty map (gate's session-only - // tracking will fill in via subsequent applies). - log.Printf("apply gate: session %d substrate AppliedLSNs unavailable (%v); falling back to session-only tracking", sessionID, err) + // log and retain the replica-lifetime map; subsequent applies + // extend it only after the physical write succeeds. + log.Printf("apply gate: session %d substrate AppliedLSNs unavailable (%v); retaining replica-lifetime tracking", sessionID, err) return sess } for lba, lsn := range seed { - sess.appliedLSN[lba] = lsn + g.appliedLSN[lba] = max(g.appliedLSN[lba], lsn) } return sess } // CloseSession clears per-session state. Called by replica-side // wiring on session teardown (lineage advance to a new session, -// peer disconnect, etc.). Optional — leaving stale sessions in the -// map costs memory but doesn't affect correctness for fresh sessions. +// peer disconnect, etc.). Only coverage is released: the replica-wide +// applied-LSN map must survive session teardown. // // Called by: replica-side session-lifecycle hook (post-T4d-2: the // existing acceptMutationLineage advance path is the natural close @@ -246,7 +244,7 @@ func (g *ReplicaApplyGate) CloseSession(sessionID uint64) { g.mu.Unlock() } -// SessionState exposes per-session state for assertion-only +// SessionState exposes replica-wide version count and per-session coverage for assertion-only // inspection in tests + diagnostics. Returns a snapshot; caller- // owned (mutation does not affect gate state). // @@ -258,7 +256,7 @@ func (g *ReplicaApplyGate) SessionState(sessionID uint64) (appliedLSN, liveTouch if !ok { return 0, 0, 0, false } - return len(sess.appliedLSN), len(sess.liveTouched), len(sess.recoveryCovered), true + return len(g.appliedLSN), len(sess.liveTouched), len(sess.recoveryCovered), true } // SessionRecoveryCoverage returns true iff the given LBA was @@ -276,17 +274,17 @@ func (g *ReplicaApplyGate) SessionRecoveryCoverage(sessionID uint64, lba uint32) return sess.recoveryCovered[lba] } -// SessionAppliedLSN returns the gate's tracked applied LSN for an -// LBA in this session. Returns 0 + false if not tracked. +// SessionAppliedLSN returns the replica-wide applied LSN visible to a +// registered session. Returns 0 + false if either is not tracked. // // Called by: tests pinning per-LBA stale-skip discrimination. func (g *ReplicaApplyGate) SessionAppliedLSN(sessionID uint64, lba uint32) (uint64, bool) { g.mu.Lock() defer g.mu.Unlock() - sess, ok := g.sessions[sessionID] + _, ok := g.sessions[sessionID] if !ok { return 0, false } - lsn, present := sess.appliedLSN[lba] + lsn, present := g.appliedLSN[lba] return lsn, present } diff --git a/seaweed-block/core/replication/apply_gate_cross_session_test.go b/seaweed-block/core/replication/apply_gate_cross_session_test.go index 15570d87e8..fdecae23d5 100644 --- a/seaweed-block/core/replication/apply_gate_cross_session_test.go +++ b/seaweed-block/core/replication/apply_gate_cross_session_test.go @@ -2,7 +2,10 @@ package replication import ( "bytes" + "errors" "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" ) // Both sessions are initialized before either writes the contested LBA. @@ -46,3 +49,58 @@ func TestApplyGate_OverlappingSessionsNeverRegressBytes(t *testing.T) { }) } } + +func TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion(t *testing.T) { + store := &fakeStoreWithSeed{BlockStore: storage.NewBlockStore(64, blockSize), seed: map[uint32]uint64{5: 1}} + gate := NewReplicaApplyGate(store) + want := bytes.Repeat([]byte{0xBB}, blockSize) + if err := gate.ApplyLive(liveLineage(1), 5, want, 120); err != nil { + t.Fatal(err) + } + gate.CloseSession(1) + if _, _, _, found := gate.SessionState(1); found { + t.Fatal("closed session coverage retained") + } + if err := gate.ApplyRecovery(recoveryLineage(2, 120), 5, makeData(0xAA), 95); err != nil { + t.Fatal(err) + } + if err := gate.ApplyLive(liveLineage(3), 5, makeData(0xCC), 100); err == nil { + t.Fatal("cross-session stale live write was accepted") + } + got, err := store.Read(5) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("teardown/reseed regressed replica bytes: err=%v", err) + } + if !gate.SessionRecoveryCoverage(2, 5) || gate.SessionRecoveryCoverage(3, 5) { + t.Fatal("stale skip/fail mixed lane coverage") + } +} + +type failOnceApplyStore struct { + *storage.BlockStore + fail bool +} + +func (s *failOnceApplyStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error { + if s.fail { + s.fail = false + return errSubstrateBoom + } + return s.BlockStore.ApplyEntry(lba, data, lsn) +} + +func TestApplyGate_FailedWriteDoesNotPublishReplicaVersion(t *testing.T) { + store := &failOnceApplyStore{BlockStore: storage.NewBlockStore(64, blockSize), fail: true} + gate := NewReplicaApplyGate(store) + if err := gate.ApplyLive(liveLineage(1), 5, makeData(0xBB), 120); !errors.Is(err, errSubstrateBoom) { + t.Fatalf("physical error lost: %v", err) + } + want := makeData(0xAA) + if err := gate.ApplyRecovery(recoveryLineage(2, 120), 5, want, 95); err != nil { + t.Fatal(err) + } + got, err := store.Read(5) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("failed write falsely blocked recovery: err=%v", err) + } +} diff --git a/seaweed-block/core/replication/apply_gate_test.go b/seaweed-block/core/replication/apply_gate_test.go index 7179d26bd9..b629eb0b68 100644 --- a/seaweed-block/core/replication/apply_gate_test.go +++ b/seaweed-block/core/replication/apply_gate_test.go @@ -230,18 +230,21 @@ func TestApplyGate_LiveLane_StaleEntry_DoesNotAdvanceRecoveryCovered(t *testing. // --- Lane independence: two sessions, different lanes --- -func TestApplyGate_LiveAndRecovery_DistinctSessions_Independent(t *testing.T) { +func TestApplyGate_LiveAndRecovery_DistinctCoverageSharedVersion(t *testing.T) { gate, _ := newGate(t) live := liveLineage(50) recov := recoveryLineage(7, 100) gate.ApplyLive(live, 5, makeData(0xBB), 100) - gate.ApplyRecovery(recov, 5, makeData(0xAA), 30) // recovery sees its own session + gate.ApplyRecovery(recov, 5, makeData(0xAA), 30) // stale across sessions - // Recovery session sees its own appliedLSN (just set: 30). + // Both sessions see the replica-wide version, with separate coverage. lsn, ok := gate.SessionAppliedLSN(7, 5) - if !ok || lsn != 30 { - t.Errorf("recovery session appliedLSN[5] = (%d, %v), want (30, true)", lsn, ok) + if !ok || lsn != 100 { + t.Errorf("recovery appliedLSN[5] = (%d, %v), want (100, true)", lsn, ok) + } + if !gate.SessionRecoveryCoverage(7, 5) || gate.SessionRecoveryCoverage(50, 5) { + t.Fatal("cross-session version sharing mixed recovery coverage") } // Live session sees its own appliedLSN (set: 100). diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 204709474a..13fec7a963 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -104,6 +104,12 @@ func NewReplicaListener(addr string, store storage.LogicalStorage) (*ReplicaList // it takes effect; a missing or invalid record refuses construction. An // empty floorPath (non-durable memback) keeps the floor in memory. func NewReplicaListenerWithFloor(addr string, store storage.LogicalStorage, volumeID, floorPath string) (*ReplicaListener, error) { + return NewReplicaListenerWithFloorAndApplyHook(addr, store, volumeID, floorPath, nil) +} + +// NewReplicaListenerWithFloorAndApplyHook preserves role and durable-floor +// admission while using the volume's shared apply ordering gate. +func NewReplicaListenerWithFloorAndApplyHook(addr string, store storage.LogicalStorage, volumeID, floorPath string, hook ApplyHook) (*ReplicaListener, error) { var floor uint64 if floorPath != "" { var err error @@ -111,7 +117,7 @@ func NewReplicaListenerWithFloor(addr string, store storage.LogicalStorage, volu return nil, err } } - r, err := NewReplicaListenerWithApplyHook(addr, store, nil) + r, err := NewReplicaListenerWithApplyHook(addr, store, hook) if err != nil { return nil, err } diff --git a/seaweed-block/docs/design/block-design.md b/seaweed-block/docs/design/block-design.md index dae9c48a72..41a572dd55 100644 --- a/seaweed-block/docs/design/block-design.md +++ b/seaweed-block/docs/design/block-design.md @@ -297,6 +297,8 @@ stateDiagram-v2 Unknown --> Healthy: probe and barrier succeed Healthy --> Degraded: barrier or ship failure Degraded --> CatchingUp: gap within the primary's WAL + CatchingUp --> CatchingUp: identical recovery facts retain the prepared session + Healthy --> Healthy: delayed probe retains completed durable R CatchingUp --> Healthy: caught up to the target CatchingUp --> Degraded: catch-up fails Degraded --> Healthy: recovers diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 244ff464cd..57d5a0fcb7 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -127,12 +127,16 @@ stateDiagram-v2 | (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | | Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | +**Recovery observation and apply ordering.** A probe publishes its fresh boundaries before reachability, and each emitted recovery is prepared under the adapter mutex before the next event. Same-identity delayed probes retain completed durable R. Every lane and session shares one replica-wide per-LBA applied-LSN map under the apply mutex; session close releases coverage only. Recovery skips stale data while advancing its own coverage; stale live data fails without advancing recovery coverage. + **Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). | 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-CATCHUP-REBUILD-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 probe observation reserves 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_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. 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` | `ReplicaApplyOrder` NoRegression | ACTIVE | +| `INV-REPL-CATCHUP-REBUILD-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` | diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 98c2c668f4..5e92eb1847 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -317,3 +317,6 @@ end-to-end wall-clock latency guarantee. Keep long model runs off tp04. `HostBudget.tla` abstracts cooperating process slots, COW reservation and joined release. Config `HostBudget.cfg` checks three owners/two slots; `HostBudget_early_release.cfg` must violate HeldUntilJoined. It excludes degraded static fallback and does not prove filesystem locks, rates or physical-I/O deadlines. Native subprocess tests cover lock lifetime. HostBudget also models guarded configuration initialization: staged bytes are invisible until atomic publication; an initializer crash permits a successor. `HostBudget_partial_config.cfg` must violate NoPartialConfig. The syscall-level crash boundary is covered by TestKilledInitializerDoesNotPublishPartialConfiguration. +## Replica apply ordering + +`ReplicaApplyOrder.tla` models two admitted sessions on one LBA with three versions, plus the two events of one probe and a delayed post-completion probe. `R292_safe` checks `NoRegression` and `NoDuplicateRecovery`; the three `R292_red_*` configurations remove one guard each. It abstracts successful physical applies only: it does not establish restart persistence, authority, byte-level framing, or I/O deadlines. diff --git a/seaweed-block/docs/spec/ReplicaApplyOrder.tla b/seaweed-block/docs/spec/ReplicaApplyOrder.tla new file mode 100644 index 0000000000..f277cbd544 --- /dev/null +++ b/seaweed-block/docs/spec/ReplicaApplyOrder.tla @@ -0,0 +1,44 @@ +------------------------- MODULE ReplicaApplyOrder ------------------------- +EXTENDS Integers, TLC + +\* Two admitted sessions, one LBA, three versions. Bytes are represented by +\* their LSN. Storage faults, restart persistence and authority are external +\* obligations; this model checks successful apply ordering and probe dedupe. +CONSTANTS SharedVersions, PrepareEachEvent, MonotoneFacts +VARIABLES applied, local, bytes, seen, stage, active, starts, replicaR +vars == <> +Max(a,b) == IF a > b THEN a ELSE b +Init == /\ applied = 0 /\ local = [s \in 1..2 |-> 0] + /\ bytes = 0 /\ seen = 0 /\ stage = 0 + /\ active = FALSE /\ starts = 0 /\ replicaR = 0 + +\* One shared mutex covers stale check, physical apply and version publication. +Apply(s,n) == LET floor == IF SharedVersions THEN applied ELSE local[s] + IN /\ bytes' = IF n > floor THEN n ELSE bytes + /\ applied' = Max(applied,n) + /\ local' = [local EXCEPT ![s] = Max(@,n)] + /\ seen' = Max(seen,n) + /\ UNCHANGED <> + +\* A probe's two semantic events must observe the same reserved session. +FirstEvent == /\ stage = 0 /\ stage' = 1 /\ starts' = 1 + /\ active' = PrepareEachEvent + /\ UNCHANGED <> +SecondEvent == /\ stage = 1 /\ stage' = 2 + /\ starts' = IF active THEN starts ELSE starts + 1 + /\ active' = TRUE + /\ UNCHANGED <> +Complete == /\ stage = 2 /\ stage' = 3 /\ replicaR' = 3 + /\ active' = FALSE + /\ UNCHANGED <> +DelayedProbe == /\ stage = 3 /\ stage' = 4 + /\ replicaR' = IF MonotoneFacts THEN replicaR ELSE 1 + /\ starts' = IF replicaR' < 3 THEN starts + 1 ELSE starts + /\ active' = (replicaR' < 3) + /\ UNCHANGED <> +Next == (\E s \in 1..2, n \in 1..3 : Apply(s,n)) + \/ FirstEvent \/ SecondEvent \/ Complete \/ DelayedProbe +Spec == Init /\ [][Next]_vars +NoRegression == bytes = seen +NoDuplicateRecovery == starts <= 1 +============================================================================= diff --git a/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg b/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg new file mode 100644 index 0000000000..a8d99dad2a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = TRUE + PrepareEachEvent = FALSE + MonotoneFacts = TRUE +INVARIANT NoDuplicateRecovery diff --git a/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg b/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg new file mode 100644 index 0000000000..b01f07b424 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = TRUE + PrepareEachEvent = TRUE + MonotoneFacts = FALSE +INVARIANT NoDuplicateRecovery diff --git a/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg b/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg new file mode 100644 index 0000000000..efc9f01d4c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = FALSE + PrepareEachEvent = TRUE + MonotoneFacts = TRUE +INVARIANT NoRegression diff --git a/seaweed-block/docs/spec/cfg/R292_safe.cfg b/seaweed-block/docs/spec/cfg/R292_safe.cfg new file mode 100644 index 0000000000..d631657e24 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_safe.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = TRUE + PrepareEachEvent = TRUE + MonotoneFacts = TRUE +INVARIANTS NoRegression NoDuplicateRecovery diff --git a/seaweed-block/docs/spec/run.sh b/seaweed-block/docs/spec/run.sh index 05391d8a5e..4bfc7d0b46 100755 --- a/seaweed-block/docs/spec/run.sh +++ b/seaweed-block/docs/spec/run.sh @@ -25,6 +25,7 @@ case $cfg in S4_*) spec=CutCapture ;; S5_*) spec=ControlPlane ;; S6_*) spec=ReplicationFailover ;; + R292_*) spec=ReplicaApplyOrder ;; S9b_*) spec=RetentionGCMulti ;; S9_*) spec=RetentionGCTiming ;; *) echo "run.sh: no spec for config '$cfg'" >&2; exit 2 ;; From 68da02fb5f019ec798fea030ba8f9f9a3356cd86 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:00:32 -0800 Subject: [PATCH 06/20] fix: preserve missing probe confidence with retained durable progress --- seaweed-block/core/engine/apply.go | 11 ++++++++ .../core/engine/recovery_probe_order_test.go | 15 ++++++++++ seaweed-block/core/engine/state.go | 3 ++ seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/spec/README.md | 2 +- seaweed-block/docs/spec/ReplicaApplyOrder.tla | 28 +++++++++++++------ .../spec/cfg/R292_red_delayed_prepare.cfg | 1 + .../docs/spec/cfg/R292_red_probe_rollback.cfg | 1 + .../spec/cfg/R292_red_session_versions.cfg | 1 + .../spec/cfg/R292_red_unknown_confidence.cfg | 6 ++++ seaweed-block/docs/spec/cfg/R292_safe.cfg | 3 +- 11 files changed, 61 insertions(+), 12 deletions(-) create mode 100644 seaweed-block/docs/spec/cfg/R292_red_unknown_confidence.cfg diff --git a/seaweed-block/core/engine/apply.go b/seaweed-block/core/engine/apply.go index 161ff88729..6d1af8d7ec 100644 --- a/seaweed-block/core/engine/apply.go +++ b/seaweed-block/core/engine/apply.go @@ -298,6 +298,7 @@ func applyRecoveryFacts(st *ReplicaState, e RecoveryFactsObserved, r *ApplyResul // Within one identity, delayed probes cannot undo completed durable work. // An identity-changing assignment resets the recovery facts. st.Recovery.R = max(st.Recovery.R, e.R) + st.Recovery.FactsMissing = !e.ProgressFact().PrimaryBoundsKnown st.Recovery.S = e.S st.Recovery.H = e.H @@ -311,6 +312,10 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra return } fact := e.ProgressFact() + if st.Recovery.FactsMissing { + st.Recovery.S, st.Recovery.H = fact.PrimaryS, fact.PrimaryH + st.Recovery.FactsMissing = false + } updateDurableAckLagState(st, fact) if fact.ReplicaR > st.Recovery.DurableAckR || !st.Recovery.DurableAckKnown { st.Recovery.DurableAckR = fact.ReplicaR @@ -443,6 +448,12 @@ func decide(st *ReplicaState, r *ApplyResult, trace func(string, string)) { trace("decision", "unknown (not reachable)") return } + if st.Recovery.FactsMissing { + st.Recovery.Decision = DecisionUnknown + st.Recovery.DecisionReason = "no_boundaries" + trace("decision", "unknown (missing probe facts)") + return + } fact := RecoveryFactsObserved{ ReplicaID: st.Identity.ReplicaID, diff --git a/seaweed-block/core/engine/recovery_probe_order_test.go b/seaweed-block/core/engine/recovery_probe_order_test.go index 011329815b..15908d0687 100644 --- a/seaweed-block/core/engine/recovery_probe_order_test.go +++ b/seaweed-block/core/engine/recovery_probe_order_test.go @@ -14,6 +14,21 @@ func TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity(t *testing.T) { if st.Recovery.R != 100 { t.Fatalf("old probe lowered completed R: %d", st.Recovery.R) } + // An unknown probe must not turn the retained R into invented primary + // boundaries or publish healthy. A later valid observation recovers it. + r = Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1}) + if r.Projection.RecoveryDecision != DecisionUnknown { + t.Fatalf("retained R fabricated known boundaries: %+v", r.Projection) + } + r = Apply(st, ProbeSucceeded{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1}) + if r.Projection.RecoveryDecision != DecisionUnknown { + t.Fatal("reachability fabricated missing recovery facts") + } + assertNoCommand(t, r, "PublishHealthy") + r = Apply(st, DurableAckObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100}) + if r.Projection.RecoveryDecision != DecisionNone || st.Recovery.FactsMissing { + t.Fatalf("valid ack did not restore known facts: %+v", r.Projection) + } // A higher primary head remains real new work, starting after durable R. r = Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 150}) start := findStartCatchUp(t, r.Commands) diff --git a/seaweed-block/core/engine/state.go b/seaweed-block/core/engine/state.go index bd90e8847a..c92f15734c 100644 --- a/seaweed-block/core/engine/state.go +++ b/seaweed-block/core/engine/state.go @@ -82,6 +82,9 @@ const ( // RecoveryTruth: what recovery is needed. Authority: primary. type RecoveryTruth struct { + // FactsMissing preserves an all-zero probe's unknown confidence even + // while R retains already-confirmed durable progress. + FactsMissing bool R uint64 // replica durable/achieved boundary S uint64 // primary recoverable start boundary (WAL tail) H uint64 // primary target boundary (head) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 57d5a0fcb7..da54e306fe 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -127,7 +127,7 @@ stateDiagram-v2 | (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | | Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | -**Recovery observation and apply ordering.** A probe publishes its fresh boundaries before reachability, and each emitted recovery is prepared under the adapter mutex before the next event. Same-identity delayed probes retain completed durable R. Every lane and session shares one replica-wide per-LBA applied-LSN map under the apply mutex; session close releases coverage only. Recovery skips stale data while advancing its own coverage; stale live data fails without advancing recovery coverage. +**Recovery observation and apply ordering.** A probe publishes its fresh boundaries before reachability, and each emitted recovery is prepared under the adapter mutex before the next event. Same-identity delayed probes retain completed durable R; missing probe boundaries remain unknown until a valid observation arrives. Every lane and session shares one replica-wide per-LBA applied-LSN map under the apply mutex; session close releases coverage only. Recovery skips stale data while advancing its own coverage; stale live data fails without advancing recovery coverage. **Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 5e92eb1847..8190995f3e 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -319,4 +319,4 @@ end-to-end wall-clock latency guarantee. Keep long model runs off tp04. HostBudget also models guarded configuration initialization: staged bytes are invisible until atomic publication; an initializer crash permits a successor. `HostBudget_partial_config.cfg` must violate NoPartialConfig. The syscall-level crash boundary is covered by TestKilledInitializerDoesNotPublishPartialConfiguration. ## Replica apply ordering -`ReplicaApplyOrder.tla` models two admitted sessions on one LBA with three versions, plus the two events of one probe and a delayed post-completion probe. `R292_safe` checks `NoRegression` and `NoDuplicateRecovery`; the three `R292_red_*` configurations remove one guard each. It abstracts successful physical applies only: it does not establish restart persistence, authority, byte-level framing, or I/O deadlines. +`ReplicaApplyOrder.tla` models two admitted sessions on one LBA with three versions, plus the two events of one probe and a delayed post-completion probe. `R292_safe` checks `NoRegression`, `NoDuplicateRecovery` and `NoFalseKnown`; the four `R292_red_*` configurations remove one guard each. It abstracts successful physical applies only: it does not establish restart persistence, authority, byte-level framing, or I/O deadlines. diff --git a/seaweed-block/docs/spec/ReplicaApplyOrder.tla b/seaweed-block/docs/spec/ReplicaApplyOrder.tla index f277cbd544..3ff2348cff 100644 --- a/seaweed-block/docs/spec/ReplicaApplyOrder.tla +++ b/seaweed-block/docs/spec/ReplicaApplyOrder.tla @@ -4,13 +4,14 @@ EXTENDS Integers, TLC \* Two admitted sessions, one LBA, three versions. Bytes are represented by \* their LSN. Storage faults, restart persistence and authority are external \* obligations; this model checks successful apply ordering and probe dedupe. -CONSTANTS SharedVersions, PrepareEachEvent, MonotoneFacts -VARIABLES applied, local, bytes, seen, stage, active, starts, replicaR -vars == <> +CONSTANTS SharedVersions, PrepareEachEvent, MonotoneFacts, PreserveUnknownConfidence +VARIABLES applied, local, bytes, seen, stage, active, starts, replicaR, factsKnown, knownDecision +vars == <> Max(a,b) == IF a > b THEN a ELSE b Init == /\ applied = 0 /\ local = [s \in 1..2 |-> 0] /\ bytes = 0 /\ seen = 0 /\ stage = 0 /\ active = FALSE /\ starts = 0 /\ replicaR = 0 + /\ factsKnown = TRUE /\ knownDecision = TRUE \* One shared mutex covers stale check, physical apply and version publication. Apply(s,n) == LET floor == IF SharedVersions THEN applied ELSE local[s] @@ -18,27 +19,36 @@ Apply(s,n) == LET floor == IF SharedVersions THEN applied ELSE local[s] /\ applied' = Max(applied,n) /\ local' = [local EXCEPT ![s] = Max(@,n)] /\ seen' = Max(seen,n) - /\ UNCHANGED <> + /\ UNCHANGED <> \* A probe's two semantic events must observe the same reserved session. FirstEvent == /\ stage = 0 /\ stage' = 1 /\ starts' = 1 /\ active' = PrepareEachEvent - /\ UNCHANGED <> + /\ UNCHANGED <> SecondEvent == /\ stage = 1 /\ stage' = 2 /\ starts' = IF active THEN starts ELSE starts + 1 /\ active' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> Complete == /\ stage = 2 /\ stage' = 3 /\ replicaR' = 3 /\ active' = FALSE - /\ UNCHANGED <> + /\ UNCHANGED <> DelayedProbe == /\ stage = 3 /\ stage' = 4 /\ replicaR' = IF MonotoneFacts THEN replicaR ELSE 1 /\ starts' = IF replicaR' < 3 THEN starts + 1 ELSE starts /\ active' = (replicaR' < 3) - /\ UNCHANGED <> + /\ UNCHANGED <> +\* Retaining durable R does not give an all-zero probe known confidence. +MissingProbe == /\ stage = 3 /\ stage' = 5 + /\ factsKnown' = FALSE + /\ knownDecision' = ~PreserveUnknownConfidence + /\ UNCHANGED <> +FreshAck == /\ stage = 5 /\ stage' = 3 + /\ factsKnown' = TRUE /\ knownDecision' = TRUE + /\ UNCHANGED <> Next == (\E s \in 1..2, n \in 1..3 : Apply(s,n)) - \/ FirstEvent \/ SecondEvent \/ Complete \/ DelayedProbe + \/ FirstEvent \/ SecondEvent \/ Complete \/ DelayedProbe \/ MissingProbe \/ FreshAck Spec == Init /\ [][Next]_vars NoRegression == bytes = seen NoDuplicateRecovery == starts <= 1 +NoFalseKnown == ~factsKnown => ~knownDecision ============================================================================= diff --git a/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg b/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg index a8d99dad2a..c2893f1af0 100644 --- a/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg +++ b/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg @@ -2,4 +2,5 @@ SPECIFICATION Spec CONSTANTS SharedVersions = TRUE PrepareEachEvent = FALSE MonotoneFacts = TRUE + PreserveUnknownConfidence = TRUE INVARIANT NoDuplicateRecovery diff --git a/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg b/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg index b01f07b424..662b75c378 100644 --- a/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg +++ b/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg @@ -2,4 +2,5 @@ SPECIFICATION Spec CONSTANTS SharedVersions = TRUE PrepareEachEvent = TRUE MonotoneFacts = FALSE + PreserveUnknownConfidence = TRUE INVARIANT NoDuplicateRecovery diff --git a/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg b/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg index efc9f01d4c..e457c7f536 100644 --- a/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg +++ b/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg @@ -2,4 +2,5 @@ SPECIFICATION Spec CONSTANTS SharedVersions = FALSE PrepareEachEvent = TRUE MonotoneFacts = TRUE + PreserveUnknownConfidence = TRUE INVARIANT NoRegression diff --git a/seaweed-block/docs/spec/cfg/R292_red_unknown_confidence.cfg b/seaweed-block/docs/spec/cfg/R292_red_unknown_confidence.cfg new file mode 100644 index 0000000000..762579b7e0 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_red_unknown_confidence.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = TRUE + PrepareEachEvent = TRUE + MonotoneFacts = TRUE + PreserveUnknownConfidence = FALSE +INVARIANT NoFalseKnown diff --git a/seaweed-block/docs/spec/cfg/R292_safe.cfg b/seaweed-block/docs/spec/cfg/R292_safe.cfg index d631657e24..47c0f9fd2f 100644 --- a/seaweed-block/docs/spec/cfg/R292_safe.cfg +++ b/seaweed-block/docs/spec/cfg/R292_safe.cfg @@ -2,4 +2,5 @@ SPECIFICATION Spec CONSTANTS SharedVersions = TRUE PrepareEachEvent = TRUE MonotoneFacts = TRUE -INVARIANTS NoRegression NoDuplicateRecovery + PreserveUnknownConfidence = TRUE +INVARIANTS NoRegression NoDuplicateRecovery NoFalseKnown From 4987a49d31114448acdcb10b426020fd8366024b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:22:08 -0800 Subject: [PATCH 07/20] fix: emit one recovery action per post-close durable acknowledgement --- seaweed-block/core/adapter/recovery_dedup_test.go | 15 +++++++++++++++ seaweed-block/core/engine/apply.go | 2 ++ seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/adapter/recovery_dedup_test.go b/seaweed-block/core/adapter/recovery_dedup_test.go index f195941461..6005fad58d 100644 --- a/seaweed-block/core/adapter/recovery_dedup_test.go +++ b/seaweed-block/core/adapter/recovery_dedup_test.go @@ -48,6 +48,21 @@ func TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery(t *testing.T) { } } +func TestAdapter_OneRecoveryFromPostCloseStalledAck(t *testing.T) { + a, exec, _ := dedupAdapter(t) + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) + for i := 0; i < 8; i++ { + a.OnDurableAck(DurableAckResult{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: uint64(200 + i)}) + if got := countStarts(exec, "StartCatchUp"); got > 1 { + if got != 2 { + t.Fatalf("one stalled ack emitted duplicate recovery: starts=%d", got) + } + return + } + } + t.Fatal("stalled ack never requested legitimate new recovery") +} + func TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery(t *testing.T) { for _, n := range []int{8, 5} { t.Run(strconv.Itoa(n), func(t *testing.T) { diff --git a/seaweed-block/core/engine/apply.go b/seaweed-block/core/engine/apply.go index 6d1af8d7ec..b15c1c520f 100644 --- a/seaweed-block/core/engine/apply.go +++ b/seaweed-block/core/engine/apply.go @@ -354,6 +354,7 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra TargetLSN: fact.PrimaryH, }) trace("command", "StartCatchUp (durable ack stalled)") + return // this observation already selected and emitted its recovery } if lag == LagDecisionStartRebuild && canEmitRecoveryFromDurableAck(st) { st.Recovery.R = st.Recovery.DurableAckR @@ -369,6 +370,7 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra TargetLSN: fact.PrimaryH, }) trace("command", "StartRebuild (durable ack below retention)") + return // do not emit a second recovery through post-close decide } if st.Recovery.PostCloseDurableAckKnown { decide(st, r, trace) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index da54e306fe..afe5586a3a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -134,7 +134,7 @@ stateDiagram-v2 | 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 probe observation reserves 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_OneRecoveryPreparedWithinProbeBatch`, `TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery`, `TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery`, `TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery | ACTIVE | +| `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. 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` | `ReplicaApplyOrder` NoRegression | ACTIVE | | `INV-REPL-CATCHUP-REBUILD-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` | From 54c1c61156adfd09472345e0bc0b2b173c7ac38b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:23:24 -0800 Subject: [PATCH 08/20] test: cover both post-close recovery decisions and settle the latest session --- .../core/adapter/recovery_dedup_test.go | 38 +++++++++++++------ 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/adapter/recovery_dedup_test.go b/seaweed-block/core/adapter/recovery_dedup_test.go index 6005fad58d..1fc3424f23 100644 --- a/seaweed-block/core/adapter/recovery_dedup_test.go +++ b/seaweed-block/core/adapter/recovery_dedup_test.go @@ -21,7 +21,15 @@ func dedupAdapter(t *testing.T) (*VolumeReplicaAdapter, *mockExecutor, ProbeResu ReplicaFlushedLSN: 50, PrimaryTailLSN: 10, PrimaryHeadLSN: 100} a.OnProbeResult(probe) t.Cleanup(func() { - a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: max(exec.latestSessionID("StartCatchUp"), exec.latestSessionID("StartRebuild")), Success: true, AchievedLSN: 100}) + exec.mu.Lock() + var sid, target uint64 + for _, start := range exec.starts { + if start.sessionID > sid { + sid, target = start.sessionID, start.targetLSN + } + } + exec.mu.Unlock() + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: sid, Success: true, AchievedLSN: target}) }) return a, exec, probe } @@ -49,18 +57,26 @@ func TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery(t *testing.T) { } func TestAdapter_OneRecoveryFromPostCloseStalledAck(t *testing.T) { - a, exec, _ := dedupAdapter(t) - a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) - for i := 0; i < 8; i++ { - a.OnDurableAck(DurableAckResult{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: uint64(200 + i)}) - if got := countStarts(exec, "StartCatchUp"); got > 1 { - if got != 2 { - t.Fatalf("one stalled ack emitted duplicate recovery: starts=%d", got) + for _, kind := range []string{"StartCatchUp", "StartRebuild"} { + t.Run(kind, func(t *testing.T) { + a, exec, _ := dedupAdapter(t) + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) + initial, tail := 1, uint64(10) + if kind == "StartRebuild" { + initial, tail = 0, 110 } - return - } + for i := 0; i < 8; i++ { + a.OnDurableAck(DurableAckResult{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: tail, PrimaryHeadLSN: uint64(200 + i)}) + if got := countStarts(exec, kind); got > initial { + if got != initial+1 { + t.Fatalf("one stalled ack emitted duplicate recovery: kind=%s starts=%d want=%d", kind, got, initial+1) + } + return + } + } + t.Fatal("stalled ack never requested legitimate new recovery") + }) } - t.Fatal("stalled ack never requested legitimate new recovery") } func TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery(t *testing.T) { From bc1b0fbaebee271adb99ac24e852d28c326ee68a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:42:38 -0800 Subject: [PATCH 09/20] test: expose replica version history growth and recovery holes --- .../core/replication/apply_gate_floor_test.go | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 seaweed-block/core/replication/apply_gate_floor_test.go diff --git a/seaweed-block/core/replication/apply_gate_floor_test.go b/seaweed-block/core/replication/apply_gate_floor_test.go new file mode 100644 index 0000000000..0ed7074e65 --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_floor_test.go @@ -0,0 +1,56 @@ +package replication + +import ( + "bytes" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A synced scalar maximum does not establish recovery coverage for other LBAs. +func TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole(t *testing.T) { + gate, store := newGate(t) + if err := gate.ApplyLive(liveLineage(1), 5, makeData(0xBB), 120); err != nil { + t.Fatal(err) + } + if r, err := store.Sync(); err != nil || r != 120 { + t.Fatalf("sync: R=%d err=%v", r, err) + } + want := makeData(0xAA) + if err := gate.ApplyRecovery(recoveryLineage(2, 100), 6, want, 95); err != nil { + t.Fatal(err) + } + got, err := store.Read(6) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("synced maximum swallowed an uncovered recovery LBA: err=%v got=%x", err, got[:8]) + } +} + +// Each batch completes durability and closes coverage; retained version history +// should scale with the outstanding suffix, rather than all LBAs ever written. +func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) { + const batch = 32 + store := storage.NewBlockStore(1025, 1) + gate := NewReplicaApplyGate(store) + for round := uint64(0); round < 32; round++ { + session := round + 1 + for j := uint64(0); j < batch; j++ { + lba := uint32(round*batch + j) + if err := gate.ApplyLive(liveLineage(session), lba, []byte{0xBB}, uint64(lba)+1); err != nil { + t.Fatal(err) + } + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + // A subsequent apply provides a lazy-pruning opportunity. + if err := gate.ApplyLive(liveLineage(session), 1024, []byte{0xCC}, 2048+round); err != nil { + t.Fatal(err) + } + tracked, _, _, _ := gate.SessionState(session) + if tracked > batch+1 { + t.Fatalf("durable version history grew with historical LBAs: round=%d tracked=%d bound=%d", round, tracked, batch+1) + } + gate.CloseSession(session) + } +} From 0a95b53940c70309a36f261cf5dfab886ca6ddb9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:43:03 -0800 Subject: [PATCH 10/20] test: keep long-run source versions monotone --- seaweed-block/core/replication/apply_gate_floor_test.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/replication/apply_gate_floor_test.go b/seaweed-block/core/replication/apply_gate_floor_test.go index 0ed7074e65..1ff083d333 100644 --- a/seaweed-block/core/replication/apply_gate_floor_test.go +++ b/seaweed-block/core/replication/apply_gate_floor_test.go @@ -32,11 +32,13 @@ func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) { const batch = 32 store := storage.NewBlockStore(1025, 1) gate := NewReplicaApplyGate(store) + var lsn uint64 for round := uint64(0); round < 32; round++ { session := round + 1 for j := uint64(0); j < batch; j++ { lba := uint32(round*batch + j) - if err := gate.ApplyLive(liveLineage(session), lba, []byte{0xBB}, uint64(lba)+1); err != nil { + lsn++ + if err := gate.ApplyLive(liveLineage(session), lba, []byte{0xBB}, lsn); err != nil { t.Fatal(err) } } @@ -44,7 +46,8 @@ func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) { t.Fatal(err) } // A subsequent apply provides a lazy-pruning opportunity. - if err := gate.ApplyLive(liveLineage(session), 1024, []byte{0xCC}, 2048+round); err != nil { + lsn++ + if err := gate.ApplyLive(liveLineage(session), 1024, []byte{0xCC}, lsn); err != nil { t.Fatal(err) } tracked, _, _, _ := gate.SessionState(session) From 28d3054de5ff7afa8b546a54746e4e1e7e5c6d88 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:44:54 -0800 Subject: [PATCH 11/20] test: preserve lane semantics after durable version pruning --- .../core/replication/apply_gate_floor_test.go | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/seaweed-block/core/replication/apply_gate_floor_test.go b/seaweed-block/core/replication/apply_gate_floor_test.go index 1ff083d333..a4f7d07a1f 100644 --- a/seaweed-block/core/replication/apply_gate_floor_test.go +++ b/seaweed-block/core/replication/apply_gate_floor_test.go @@ -57,3 +57,39 @@ func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) { gate.CloseSession(session) } } + +func TestApplyGate_PrunedDurableVersionsRemainStale(t *testing.T) { + gate, store := newGate(t) + want := makeData(0xBB) + for lba := uint32(0); lba < 32; lba++ { + if err := gate.ApplyLive(liveLineage(1), lba, want, uint64(lba)+1); err != nil { + t.Fatal(err) + } + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + gate.CloseSession(1) + if err := gate.ApplyRecovery(recoveryLineage(2, 32), 5, makeData(0xAA), 1); err != nil { + t.Fatal(err) + } + if !gate.SessionRecoveryCoverage(2, 5) { + t.Fatal("pruned stale recovery did not cover its own session") + } + if err := gate.ApplyLive(liveLineage(3), 6, makeData(0xCC), 2); err == nil { + t.Fatal("pruned stale live write was accepted") + } + if gate.SessionRecoveryCoverage(3, 6) { + t.Fatal("stale live write advanced recovery coverage") + } + for _, lba := range []uint32{5, 6} { + got, err := store.Read(lba) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("pruned stale record changed LBA %d: err=%v", lba, err) + } + } + tracked, _, _, _ := gate.SessionState(2) + if tracked != 0 { + t.Fatalf("durable versions were not pruned: tracked=%d want=0", tracked) + } +} From 85bf19a8bb6d951a44ebd7038bf118b8ba557acb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:53:34 -0800 Subject: [PATCH 12/20] fix: prune replica versions only behind certified recovery prefixes --- seaweed-block/core/adapter/adapter.go | 5 + seaweed-block/core/adapter/executor.go | 6 + seaweed-block/core/engine/apply.go | 14 +- seaweed-block/core/engine/commands.go | 2 + .../core/engine/recovery_prefix_test.go | 25 ++++ seaweed-block/core/replication/apply_gate.go | 44 +++++- .../core/replication/apply_gate_floor_test.go | 52 +++++++- .../apply_gate_prefix_wire_test.go | 126 ++++++++++++++++++ seaweed-block/core/transport/executor.go | 29 ++++ seaweed-block/core/transport/protocol.go | 4 + seaweed-block/core/transport/replica.go | 31 ++++- 11 files changed, 330 insertions(+), 8 deletions(-) create mode 100644 seaweed-block/core/engine/recovery_prefix_test.go create mode 100644 seaweed-block/core/replication/apply_gate_prefix_wire_test.go diff --git a/seaweed-block/core/adapter/adapter.go b/seaweed-block/core/adapter/adapter.go index 9798315423..8994bc89ab 100644 --- a/seaweed-block/core/adapter/adapter.go +++ b/seaweed-block/core/adapter/adapter.go @@ -575,6 +575,11 @@ func (a *VolumeReplicaAdapter) executeCommand(q queuedCommand) { a.executor.InvalidateSession(c.ReplicaID, c.SessionID, c.Reason) case engine.PublishHealthy: + if c.CertifiedPrefix != 0 { + if publisher, ok := a.executor.(RecoveryPrefixPublisher); ok { + publisher.PublishRecoveryPrefix(c.ReplicaID, c.RecoverySessionID, c.Epoch, c.EndpointVersion, c.CertifiedPrefix) + } + } a.executor.PublishHealthy(c.ReplicaID) case engine.PublishDegraded: diff --git a/seaweed-block/core/adapter/executor.go b/seaweed-block/core/adapter/executor.go index 8807399726..ba6e284fea 100644 --- a/seaweed-block/core/adapter/executor.go +++ b/seaweed-block/core/adapter/executor.go @@ -163,3 +163,9 @@ type DurableAckResult struct { type DurableAckCallbackSetter interface { SetOnDurableAck(fn OnDurableAck) } + +// RecoveryPrefixPublisher forwards the engine's explicit completed-prefix +// certificate. Plain healthy/probe or storage Sync facts carry no certificate. +type RecoveryPrefixPublisher interface { + PublishRecoveryPrefix(replicaID string, sessionID, epoch, endpointVersion, prefix uint64) +} diff --git a/seaweed-block/core/engine/apply.go b/seaweed-block/core/engine/apply.go index b15c1c520f..643f4dbbfe 100644 --- a/seaweed-block/core/engine/apply.go +++ b/seaweed-block/core/engine/apply.go @@ -524,7 +524,19 @@ func decide(st *ReplicaState, r *ApplyResult, trace func(string, string)) { } 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}) + healthy := PublishHealthy{ReplicaID: st.Identity.ReplicaID} + target := st.Session.FrontierHint + if target == 0 { + target = st.Session.TargetLSN + } + if st.Recovery.RecoveryWindowClosed && st.Recovery.PostCloseDurableAckKnown && + st.Session.Phase == PhaseCompleted && target > 0 && st.Session.AchievedLSN >= target { + healthy.RecoverySessionID = st.Session.SessionID + healthy.Epoch = st.Identity.Epoch + healthy.EndpointVersion = st.Identity.EndpointVersion + healthy.CertifiedPrefix = target + } + r.Commands = append(r.Commands, healthy) } } diff --git a/seaweed-block/core/engine/commands.go b/seaweed-block/core/engine/commands.go index 3d137a7a38..d8bcefcccc 100644 --- a/seaweed-block/core/engine/commands.go +++ b/seaweed-block/core/engine/commands.go @@ -106,6 +106,8 @@ func (FenceAtEpoch) commandKind() string { return "FenceAtEpoch" } // PublishHealthy: declare this replica healthy for external consumption. type PublishHealthy struct { ReplicaID string + // Zero unless this publication follows a successful recovery close at T. + RecoverySessionID, Epoch, EndpointVersion, CertifiedPrefix uint64 } func (PublishHealthy) commandKind() string { return "PublishHealthy" } diff --git a/seaweed-block/core/engine/recovery_prefix_test.go b/seaweed-block/core/engine/recovery_prefix_test.go new file mode 100644 index 0000000000..464b8ea878 --- /dev/null +++ b/seaweed-block/core/engine/recovery_prefix_test.go @@ -0,0 +1,25 @@ +package engine + +import "testing" + +func TestHealthyPrefixRequiresCompletedRecoveryAndPostCloseAck(t *testing.T) { + st := helperPrime(t, 1, 1, 100) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 8, Kind: SessionCatchUp, FrontierHint: 100}) + Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 8}) + result := Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 8, AchievedLSN: 100}) + for _, command := range result.Commands { + if _, ok := command.(PublishHealthy); ok { + t.Fatal("recovery close certified before post-close ack") + } + } + result = Apply(st, DurableAckObserved{ReplicaID: "r1", SessionID: 8, EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 120, PrimaryTailLSN: 1, PrimaryHeadLSN: 120}) + for _, command := range result.Commands { + if healthy, ok := command.(PublishHealthy); ok { + if healthy.CertifiedPrefix != 100 || healthy.RecoverySessionID != 8 || healthy.Epoch != 1 || healthy.EndpointVersion != 1 { + t.Fatalf("healthy publication lost exact completed target: %+v", healthy) + } + return + } + } + t.Fatal("post-close ack did not publish certified recovery prefix") +} diff --git a/seaweed-block/core/replication/apply_gate.go b/seaweed-block/core/replication/apply_gate.go index 0adb09402c..aa0fa64cd1 100644 --- a/seaweed-block/core/replication/apply_gate.go +++ b/seaweed-block/core/replication/apply_gate.go @@ -68,6 +68,7 @@ type ReplicaApplyGate struct { mu sync.Mutex sessions map[uint64]*applyGateSession // keyed by lineage.SessionID appliedLSN map[uint32]uint64 // replica-wide, shared by every lane and session + floorLSN uint64 // certified contiguous prefix; never inferred from synced maximum R } // applyGateSession is the per-recovery-session state. Per round-44 @@ -165,7 +166,7 @@ func (g *ReplicaApplyGate) applyRecovery(sess *applyGateSession, lba uint32, dat g.mu.Lock() defer g.mu.Unlock() - if existing, ok := g.appliedLSN[lba]; ok && lsn <= existing { + if existing := max(g.appliedLSN[lba], g.floorLSN); lsn <= existing { // Stale: skip data write but ADVANCE recoveryCovered. sess.recoveryCovered[lba] = true return nil @@ -190,7 +191,7 @@ func (g *ReplicaApplyGate) applyLive(sess *applyGateSession, lba uint32, data [] g.mu.Lock() defer g.mu.Unlock() - if existing, ok := g.appliedLSN[lba]; ok && lsn <= existing { + if existing := max(g.appliedLSN[lba], g.floorLSN); lsn <= existing { // Stale: fail-loud. Caller logs + drops conn. return fmt.Errorf("apply gate: live-lane stale entry lba=%d lsn=%d <= applied=%d (INV-REPL-LIVE-LANE-STALE-FAILS-LOUD)", lba, lsn, existing) @@ -224,7 +225,9 @@ func (g *ReplicaApplyGate) initSessionLocked(sessionID uint64) *applyGateSession return sess } for lba, lsn := range seed { - g.appliedLSN[lba] = max(g.appliedLSN[lba], lsn) + if lsn > g.floorLSN { + g.appliedLSN[lba] = max(g.appliedLSN[lba], lsn) + } } return sess } @@ -288,3 +291,38 @@ func (g *ReplicaApplyGate) SessionAppliedLSN(sessionID uint64, lba uint32) (uint lsn, present := g.appliedLSN[lba] return lsn, present } + +// CertifyRecoveryPrefix accepts an explicit source-coverage certificate emitted +// only after a successful recovery close is published healthy. Sync/Boundaries +// alone cannot certify coverage: a high live LSN can be durable across a hole. +// The transport owns lineage admission. A missing/refused certificate retains +// history conservatively; ordinary live traffic does not advance this floor. +func (g *ReplicaApplyGate) CertifyRecoveryPrefix(lineage transport.RecoveryLineage) error { + prefix := lineage.EffectiveFrontierHint() + g.mu.Lock() + defer g.mu.Unlock() + r, _, _ := g.store.Boundaries() + if prefix == 0 || prefix > r { + return fmt.Errorf("apply gate: certified prefix %d exceeds durable boundary %d or is zero", prefix, r) + } + if prefix <= g.floorLSN { + return nil + } + // Rebuild rather than only deleting: release the old map's bucket capacity. + retained := make(map[uint32]uint64) + for lba, lsn := range g.appliedLSN { + if lsn > prefix { + retained[lba] = lsn + } + } + g.appliedLSN = retained + g.floorLSN = prefix + return nil +} + +// CertifiedPrefix reports the source-certified coverage frontier, not R. +func (g *ReplicaApplyGate) CertifiedPrefix() uint64 { + g.mu.Lock() + defer g.mu.Unlock() + return g.floorLSN +} diff --git a/seaweed-block/core/replication/apply_gate_floor_test.go b/seaweed-block/core/replication/apply_gate_floor_test.go index a4f7d07a1f..68f1323176 100644 --- a/seaweed-block/core/replication/apply_gate_floor_test.go +++ b/seaweed-block/core/replication/apply_gate_floor_test.go @@ -26,9 +26,9 @@ func TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole(t *testing.T) { } } -// Each batch completes durability and closes coverage; retained version history -// should scale with the outstanding suffix, rather than all LBAs ever written. -func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) { +// Each batch has a successful recovery close and an explicit prefix certificate. +// Durability alone is insufficient; ordinary healthy traffic remains unbounded. +func TestApplyGate_CertifiedRecoveryClosesBoundVersionHistory(t *testing.T) { const batch = 32 store := storage.NewBlockStore(1025, 1) gate := NewReplicaApplyGate(store) @@ -45,6 +45,9 @@ func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) { if _, err := store.Sync(); err != nil { t.Fatal(err) } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(session, lsn)); err != nil { + t.Fatal(err) + } // A subsequent apply provides a lazy-pruning opportunity. lsn++ if err := gate.ApplyLive(liveLineage(session), 1024, []byte{0xCC}, lsn); err != nil { @@ -69,6 +72,9 @@ func TestApplyGate_PrunedDurableVersionsRemainStale(t *testing.T) { if _, err := store.Sync(); err != nil { t.Fatal(err) } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(1, 32)); err != nil { + t.Fatal(err) + } gate.CloseSession(1) if err := gate.ApplyRecovery(recoveryLineage(2, 32), 5, makeData(0xAA), 1); err != nil { t.Fatal(err) @@ -93,3 +99,43 @@ func TestApplyGate_PrunedDurableVersionsRemainStale(t *testing.T) { t.Fatalf("durable versions were not pruned: tracked=%d want=0", tracked) } } + +func TestApplyGate_CertifiedPrefixFreezesAcrossSessions(t *testing.T) { + gate, store := newGate(t) + if err := gate.ApplyRecovery(recoveryLineage(1, 1), 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(1, 1)); err != nil { + t.Fatal(err) + } + gate.CloseSession(1) + if err := gate.ApplyLive(liveLineage(2), 5, makeData(0xBB), 120); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + if got := gate.CertifiedPrefix(); got != 1 { + t.Fatalf("new session or Sync extended certified floor: P=%d", got) + } + want := makeData(0xAA) + if err := gate.ApplyRecovery(recoveryLineage(3, 100), 6, want, 95); err != nil { + t.Fatal(err) + } + got, err := store.Read(6) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("frozen prefix swallowed missing recovery: err=%v", err) + } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(3, 121)); err == nil { + t.Fatal("certificate above durable boundary accepted") + } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(3, 1)); err != nil { + t.Fatal(err) + } + if gate.CertifiedPrefix() != 1 { + t.Fatal("failed/repeated certificate changed prefix") + } +} diff --git a/seaweed-block/core/replication/apply_gate_prefix_wire_test.go b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go new file mode 100644 index 0000000000..3ffe7a8591 --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go @@ -0,0 +1,126 @@ +package replication + +import ( + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +type observedPrefixGate struct { + *ReplicaApplyGate + certified chan error +} + +func (g *observedPrefixGate) CertifyRecoveryPrefix(l transport.RecoveryLineage) error { + err := g.ReplicaApplyGate.CertifyRecoveryPrefix(l) + g.certified <- err + return err +} + +// Real primary engine/adapter/executor -> role-gated replica -> shared gate. +func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) { + primary := storage.NewBlockStore(64, blockSize) + for lba := uint32(0); lba < 32; lba++ { + if _, err := primary.Write(lba, makeData(byte(lba+1))); err != nil { + t.Fatal(err) + } + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + store := storage.NewBlockStore(64, blockSize) + gate := &observedPrefixGate{ReplicaApplyGate: NewReplicaApplyGate(store), certified: make(chan error, 8)} + if err := gate.ApplyLive(liveLineage(1), 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) + if err != nil { + t.Fatal(err) + } + if err := listener.AdmitAsReplica(1); err != nil { + listener.StopHard() + t.Fatal(err) + } + listener.Serve() + executor := transport.NewBlockExecutor(primary, listener.Addr()) + t.Cleanup(func() { executor.Stop(); listener.StopHard() }) + a := adapter.NewVolumeReplicaAdapter(executor) + a.OnAssignment(adapter.AssignmentInfo{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: listener.Addr()}) + select { + case err := <-gate.certified: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("healthy recovery did not publish wire prefix certificate") + } + if got := gate.CertifiedPrefix(); got != 32 { + t.Fatalf("wire certified prefix=%d want32", got) + } + tracked, _, _, found := gate.SessionState(2) + if !found || tracked != 0 { + t.Fatalf("wire recovery did not prune: found=%v tracked=%d", found, tracked) + } +} + +func TestApplyGate_WirePrefixCannotIntroduceOrReviveSession(t *testing.T) { + gate, store := newGate(t) + if err := gate.ApplyRecovery(recoveryLineage(1, 1), 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) + if err != nil { + t.Fatal(err) + } + if err := listener.AdmitAsReplica(1); err != nil { + listener.StopHard() + t.Fatal(err) + } + listener.Serve() + t.Cleanup(listener.StopHard) + send := func(l transport.RecoveryLineage, certificate bool) { + t.Helper() + c, err := net.DialTimeout("tcp", listener.Addr(), time.Second) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if err := c.SetDeadline(time.Now().Add(2 * time.Second)); err != nil { + t.Fatal(err) + } + if certificate { + if err := transport.WriteMsg(c, transport.MsgCertifiedPrefix, transport.EncodeLineage(l)); err != nil { + t.Fatal(err) + } + } + if err := transport.WriteMsg(c, transport.MsgBarrierReq, transport.EncodeLineage(l)); err != nil { + if certificate { + return + } + t.Fatal(err) + } + kind, _, err := transport.ReadMsg(c) + if !certificate && (err != nil || kind != transport.MsgBarrierResp) { + t.Fatalf("setup barrier: kind=%d err=%v", kind, err) + } + } + send(recoveryLineage(1, 1), true) // unseen: rejected, must not introduce lineage + if gate.CertifiedPrefix() != 0 { + t.Fatal("unseen session certified prefix") + } + send(recoveryLineage(2, 1), false) + send(recoveryLineage(1, 1), true) // superseded: cannot certify even with valid R + if gate.CertifiedPrefix() != 0 { + t.Fatal("stale session certified prefix") + } +} diff --git a/seaweed-block/core/transport/executor.go b/seaweed-block/core/transport/executor.go index e8eb0f44b7..26bd2f0419 100644 --- a/seaweed-block/core/transport/executor.go +++ b/seaweed-block/core/transport/executor.go @@ -1315,3 +1315,32 @@ func (e *BlockExecutor) recordSessionRunning(replicaID string, sessionID uint64) SessionID: sessionID, } } + +// PublishRecoveryPrefix forwards a completed-recovery certificate supplied by +// the engine's healthy publication. Failure conservatively retains the map. +// It does not certify subsequent live traffic or infer coverage from R. +func (e *BlockExecutor) PublishRecoveryPrefix(replicaID string, sessionID, epoch, endpointVersion, prefix uint64) { + if err := e.beginAsyncOperation(); err != nil { + return + } + go func() { + defer e.asyncWG.Done() + lineage := RecoveryLineage{SessionID: sessionID, Epoch: epoch, EndpointVersion: endpointVersion, FrontierHint: prefix} + conn, err := net.DialTimeout("tcp", e.replicaAddr, 2*time.Second) + if err != nil { + log.Printf("executor: prefix certificate %s: %v", replicaID, err) + return + } + defer conn.Close() + if err := e.trackTransientConn(conn); err != nil { + return + } + defer e.untrackTransientConn(conn) + if err := conn.SetDeadline(time.Now().Add(recoveryConnTimeout)); err != nil { + return + } + if err := WriteMsg(conn, MsgCertifiedPrefix, EncodeLineage(lineage)); err != nil { + log.Printf("executor: prefix certificate %s: %v", replicaID, err) + } + }() +} diff --git a/seaweed-block/core/transport/protocol.go b/seaweed-block/core/transport/protocol.go index c15344cfce..188974eed9 100644 --- a/seaweed-block/core/transport/protocol.go +++ b/seaweed-block/core/transport/protocol.go @@ -46,6 +46,10 @@ const ( // recovery-lane before any MsgShipEntry frames arrive. It replaces // payload-derived lane guessing from RecoveryLineage.TargetLSN. MsgRecoveryLaneStart byte = 0x08 + // MsgCertifiedPrefix carries a full lineage whose frontier is an explicit + // completed-recovery coverage certificate, never a scalar Sync maximum. + // No acknowledgement/old-peer fallback is needed: refusal retains history. + MsgCertifiedPrefix byte = 0x09 ) // RecoveryLineage binds a mutating recovery stream to one accepted recovery diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 13fec7a963..084b9aaefe 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -38,6 +38,12 @@ const ( // Returning a non-nil error → caller (handler) logs + closes conn. // Per INV-REPL-LIVE-LANE-STALE-FAILS-LOUD: live-lane stale entries // 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 RecoveryPrefixHook interface { + CertifyRecoveryPrefix(lineage RecoveryLineage) error +} + type ApplyHook interface { // ApplyRecovery routes the entry through the recovery-lane apply // path. Stale entries (LSN <= per-LBA applied) skip data + advance @@ -512,6 +518,12 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { replyType, reply = MsgBarrierResp, resp return true + case MsgCertifiedPrefix: + lineage, err := DecodeLineage(payload) + if err != nil || r.certifyRecoveryPrefix(lineage) != nil { + return true + } + case MsgBarrierReq: lineage, err := DecodeLineage(payload) if err != nil { @@ -660,7 +672,7 @@ const defaultFenceDrainTimeout = 10 * time.Second // isMutationMsg names the frames that pass acceptMutationLineage. func isMutationMsg(msgType byte) bool { switch msgType { - case MsgRecoveryLaneStart, MsgShipEntry, MsgRebuildBlock, MsgRebuildDone, MsgBarrierReq: + case MsgRecoveryLaneStart, MsgShipEntry, MsgRebuildBlock, MsgRebuildDone, MsgBarrierReq, MsgCertifiedPrefix: return true } return false @@ -782,3 +794,20 @@ func compareLineage(a, b RecoveryLineage) int { return 0 } } + +// A certificate cannot introduce an unseen session or survive a later one. +// Lock order: listener.mu -> gate.mu -> store boundary read. There is no wire +// or physical I/O here; fencing/session admission cannot cross the effect. +func (r *ReplicaListener) certifyRecoveryPrefix(lineage RecoveryLineage) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.primary || (r.requireRole && !r.assigned) || lineage.Epoch < r.epochFloor || + lineage.SessionID == 0 || lineage.EffectiveFrontierHint() == 0 || !r.activeLineage.Equivalent(lineage) { + return fmt.Errorf("replica: uncertified/stale recovery lineage") + } + hook, ok := r.applyHook.(RecoveryPrefixHook) + if !ok { + return fmt.Errorf("replica: no recovery prefix hook") + } + return hook.CertifyRecoveryPrefix(lineage) +} From ed08492b87d798eb875f05f66f38020dacdd67e2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:56:19 -0800 Subject: [PATCH 13/20] test: specify certified prefix pruning and recovery coverage guards --- .../core/engine/recovery_prefix_test.go | 2 +- seaweed-block/docs/design/block-design.md | 1 + seaweed-block/docs/design/invariants.md | 9 +++++- seaweed-block/docs/spec/README.md | 7 +++++ .../docs/spec/ReplicaPrefixFloor.tla | 31 +++++++++++++++++++ .../spec/cfg/R293_prefix_red_forgot_floor.cfg | 4 +++ .../spec/cfg/R293_prefix_red_synced_max.cfg | 4 +++ .../docs/spec/cfg/R293_prefix_safe.cfg | 4 +++ seaweed-block/docs/spec/run.sh | 1 + 9 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/docs/spec/ReplicaPrefixFloor.tla create mode 100644 seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg create mode 100644 seaweed-block/docs/spec/cfg/R293_prefix_red_synced_max.cfg create mode 100644 seaweed-block/docs/spec/cfg/R293_prefix_safe.cfg diff --git a/seaweed-block/core/engine/recovery_prefix_test.go b/seaweed-block/core/engine/recovery_prefix_test.go index 464b8ea878..d58b5367cc 100644 --- a/seaweed-block/core/engine/recovery_prefix_test.go +++ b/seaweed-block/core/engine/recovery_prefix_test.go @@ -12,7 +12,7 @@ func TestHealthyPrefixRequiresCompletedRecoveryAndPostCloseAck(t *testing.T) { t.Fatal("recovery close certified before post-close ack") } } - result = Apply(st, DurableAckObserved{ReplicaID: "r1", SessionID: 8, EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 120, PrimaryTailLSN: 1, PrimaryHeadLSN: 120}) + result = Apply(st, DurableAckObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 120, PrimaryTailLSN: 1, PrimaryHeadLSN: 120}) for _, command := range result.Commands { if healthy, ok := command.(PublishHealthy); ok { if healthy.CertifiedPrefix != 100 || healthy.RecoverySessionID != 8 || healthy.Epoch != 1 || healthy.EndpointVersion != 1 { diff --git a/seaweed-block/docs/design/block-design.md b/seaweed-block/docs/design/block-design.md index 41a572dd55..9061f000c4 100644 --- a/seaweed-block/docs/design/block-design.md +++ b/seaweed-block/docs/design/block-design.md @@ -299,6 +299,7 @@ stateDiagram-v2 Degraded --> CatchingUp: gap within the primary's WAL CatchingUp --> CatchingUp: identical recovery facts retain the prepared session Healthy --> Healthy: delayed probe retains completed durable R + Healthy --> Healthy: completed recovery certifies P, prune version suffix CatchingUp --> Healthy: caught up to the target CatchingUp --> Degraded: catch-up fails Degraded --> Healthy: recovers diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index afe5586a3a..e30a534706 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -114,6 +114,13 @@ stateDiagram-v2 Excluded --> Supporting: later fact lists self as a peer ``` +The apply gate retains versions only above its certified contiguous prefix P. +Completed recovery plus post-close healthy publication sends an explicit full-lineage +certificate; current listener admission and the durable boundary guard it. 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. + **Host role and listener admission.** | From | To | Event and guard | Enforced in | Protects | @@ -135,7 +142,7 @@ stateDiagram-v2 |---|---|---|---|---| | `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. 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` | `ReplicaApplyOrder` NoRegression | 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` | | `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` | diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 8190995f3e..a3586b8834 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -320,3 +320,10 @@ HostBudget also models guarded configuration initialization: staged bytes are in ## Replica apply ordering `ReplicaApplyOrder.tla` models two admitted sessions on one LBA with three versions, plus the two events of one probe and a delayed post-completion probe. `R292_safe` checks `NoRegression`, `NoDuplicateRecovery` and `NoFalseKnown`; the four `R292_red_*` configurations remove one guard each. It abstracts successful physical applies only: it does not establish restart persistence, authority, byte-level framing, or I/O deadlines. + +`ReplicaPrefixFloor.tla` checks two LBAs/three source versions with explicit +covered-prefix certification, suffix pruning and stale checks against the floor. +`R293_prefix_safe` checks `NoRegression`, `CertifiedCoverage`, and `OnlySuffix`; +its two negative controls infer a prefix from the synced maximum or omit the +floor after pruning. It does not establish the wire certificate's provenance, +restart persistence, live-prefix extension, or a fixed memory cap without closes. diff --git a/seaweed-block/docs/spec/ReplicaPrefixFloor.tla b/seaweed-block/docs/spec/ReplicaPrefixFloor.tla new file mode 100644 index 0000000000..70e419d693 --- /dev/null +++ b/seaweed-block/docs/spec/ReplicaPrefixFloor.tla @@ -0,0 +1,31 @@ +----------------------- MODULE ReplicaPrefixFloor ----------------------- +EXTENDS Integers, TLC +CONSTANTS UseFloor, CertifiedOnly +VARIABLES data, seen, versions, durable, prefix +vars == <> +Addr(n) == IF n = 2 THEN 2 ELSE 1 +Max(a,b) == IF a > b THEN a ELSE b +Covered(p) == \A n \in 1..p : data[Addr(n)] >= n +Init == /\ data = [i \in 1..2 |-> 0] /\ seen = data /\ versions = data + /\ durable = 0 /\ prefix = 0 +Apply(n) == LET i == Addr(n) + threshold == Max(versions[i], IF UseFloor THEN prefix ELSE 0) + IN /\ data' = IF n > threshold THEN [data EXCEPT ![i] = n] ELSE data + /\ seen' = [seen EXCEPT ![i] = Max(@,n)] + /\ versions' = IF n > threshold THEN [versions EXCEPT ![i] = n] ELSE versions + /\ UNCHANGED <> +Sync == /\ durable' = Max(durable, Max(data[1],data[2])) + /\ UNCHANGED <> +Certify(p) == /\ p > prefix /\ p <= durable + /\ (~CertifiedOnly \/ Covered(p)) + /\ prefix' = p + /\ versions' = [i \in 1..2 |-> IF versions[i] <= p THEN 0 ELSE versions[i]] + /\ UNCHANGED <> +\* Session changes, ordinary live writes, disconnects and Sync do not certify. +RestartSession == UNCHANGED vars +Next == (\E n \in 1..3 : Apply(n)) \/ Sync \/ (\E p \in 1..3 : Certify(p)) \/ RestartSession +Spec == Init /\ [][Next]_vars +NoRegression == data = seen +CertifiedCoverage == Covered(prefix) +OnlySuffix == \A i \in 1..2 : versions[i] = 0 \/ versions[i] > prefix +============================================================================= \ No newline at end of file diff --git a/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg b/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg new file mode 100644 index 0000000000..651a875730 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UseFloor = FALSE + CertifiedOnly = TRUE +INVARIANTS NoRegression CertifiedCoverage OnlySuffix diff --git a/seaweed-block/docs/spec/cfg/R293_prefix_red_synced_max.cfg b/seaweed-block/docs/spec/cfg/R293_prefix_red_synced_max.cfg new file mode 100644 index 0000000000..2e7b34a866 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_prefix_red_synced_max.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UseFloor = TRUE + CertifiedOnly = FALSE +INVARIANTS NoRegression CertifiedCoverage OnlySuffix diff --git a/seaweed-block/docs/spec/cfg/R293_prefix_safe.cfg b/seaweed-block/docs/spec/cfg/R293_prefix_safe.cfg new file mode 100644 index 0000000000..8fc29bed97 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_prefix_safe.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UseFloor = TRUE + CertifiedOnly = TRUE +INVARIANTS NoRegression CertifiedCoverage OnlySuffix diff --git a/seaweed-block/docs/spec/run.sh b/seaweed-block/docs/spec/run.sh index 4bfc7d0b46..06ed9184b8 100755 --- a/seaweed-block/docs/spec/run.sh +++ b/seaweed-block/docs/spec/run.sh @@ -25,6 +25,7 @@ case $cfg in S4_*) spec=CutCapture ;; S5_*) spec=ControlPlane ;; S6_*) spec=ReplicationFailover ;; + R293_prefix_*) spec=ReplicaPrefixFloor ;; R292_*) spec=ReplicaApplyOrder ;; S9b_*) spec=RetentionGCMulti ;; S9_*) spec=RetentionGCTiming ;; From 7b2522b4850c070f9acfaea538413398f4b75801 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:57:24 -0800 Subject: [PATCH 14/20] test: refuse prefix certification from plain healthy probes --- .../core/engine/recovery_prefix_test.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/seaweed-block/core/engine/recovery_prefix_test.go b/seaweed-block/core/engine/recovery_prefix_test.go index d58b5367cc..d8eeec7077 100644 --- a/seaweed-block/core/engine/recovery_prefix_test.go +++ b/seaweed-block/core/engine/recovery_prefix_test.go @@ -23,3 +23,20 @@ func TestHealthyPrefixRequiresCompletedRecoveryAndPostCloseAck(t *testing.T) { } t.Fatal("post-close ack did not publish certified recovery prefix") } + +func TestHealthyProbeDoesNotCertifyRecoveryPrefix(t *testing.T) { + st := helperPrime(t, 100, 1, 100) + result := Apply(st, FenceCompleted{ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}) + found := false + for _, command := range result.Commands { + if healthy, ok := command.(PublishHealthy); ok { + found = true + if healthy.CertifiedPrefix != 0 || healthy.RecoverySessionID != 0 { + t.Fatalf("plain healthy probe invented a prefix certificate: %+v", healthy) + } + } + } + if !found { + t.Fatal("control did not reach healthy publication") + } +} From 78781527ae91243bb4273d39770da3208b32415c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:58:38 -0800 Subject: [PATCH 15/20] test: bind wire pruning assertion to its actual recovery session --- .../apply_gate_prefix_wire_test.go | 21 ++++++++++++------- .../spec/cfg/R293_prefix_red_forgot_floor.cfg | 2 +- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/replication/apply_gate_prefix_wire_test.go b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go index 3ffe7a8591..9c194b13fa 100644 --- a/seaweed-block/core/replication/apply_gate_prefix_wire_test.go +++ b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go @@ -10,14 +10,19 @@ import ( "github.com/seaweedfs/seaweed-block/core/transport" ) +type prefixResult struct { + lineage transport.RecoveryLineage + err error +} + type observedPrefixGate struct { *ReplicaApplyGate - certified chan error + certified chan prefixResult } func (g *observedPrefixGate) CertifyRecoveryPrefix(l transport.RecoveryLineage) error { err := g.ReplicaApplyGate.CertifyRecoveryPrefix(l) - g.certified <- err + g.certified <- prefixResult{l, err} return err } @@ -33,7 +38,7 @@ func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) { t.Fatal(err) } store := storage.NewBlockStore(64, blockSize) - gate := &observedPrefixGate{ReplicaApplyGate: NewReplicaApplyGate(store), certified: make(chan error, 8)} + gate := &observedPrefixGate{ReplicaApplyGate: NewReplicaApplyGate(store), certified: make(chan prefixResult, 8)} if err := gate.ApplyLive(liveLineage(1), 0, makeData(1), 1); err != nil { t.Fatal(err) } @@ -53,18 +58,20 @@ func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) { t.Cleanup(func() { executor.Stop(); listener.StopHard() }) a := adapter.NewVolumeReplicaAdapter(executor) a.OnAssignment(adapter.AssignmentInfo{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: listener.Addr()}) + var certified transport.RecoveryLineage select { - case err := <-gate.certified: - if err != nil { - t.Fatal(err) + case result := <-gate.certified: + if result.err != nil { + t.Fatal(result.err) } + certified = result.lineage case <-time.After(5 * time.Second): t.Fatal("healthy recovery did not publish wire prefix certificate") } if got := gate.CertifiedPrefix(); got != 32 { t.Fatalf("wire certified prefix=%d want32", got) } - tracked, _, _, found := gate.SessionState(2) + tracked, _, _, found := gate.SessionState(certified.SessionID) if !found || tracked != 0 { t.Fatalf("wire recovery did not prune: found=%v tracked=%d", found, tracked) } diff --git a/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg b/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg index 651a875730..c877180acc 100644 --- a/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg +++ b/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec CONSTANTS UseFloor = FALSE CertifiedOnly = TRUE -INVARIANTS NoRegression CertifiedCoverage OnlySuffix +INVARIANTS NoRegression From 8bd459c24af06b7ef90dfb6beb34097da5a53928 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:02:39 -0800 Subject: [PATCH 16/20] fix: require a covered starting image before extending replica prefix --- .../apply_gate_prefix_wire_test.go | 93 +++++++++++++++++-- seaweed-block/core/transport/replica.go | 32 ++++++- 2 files changed, 116 insertions(+), 9 deletions(-) diff --git a/seaweed-block/core/replication/apply_gate_prefix_wire_test.go b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go index 9c194b13fa..83065c3ce1 100644 --- a/seaweed-block/core/replication/apply_gate_prefix_wire_test.go +++ b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go @@ -1,6 +1,7 @@ package replication import ( + "bytes" "net" "testing" "time" @@ -28,6 +29,10 @@ func (g *observedPrefixGate) CertifyRecoveryPrefix(l transport.RecoveryLineage) // Real primary engine/adapter/executor -> role-gated replica -> shared gate. func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) { + t.Run("catchup_from_certified_base", func(t *testing.T) { runHealthyRecoveryPrefix(t, true) }) + t.Run("full_base", func(t *testing.T) { runHealthyRecoveryPrefix(t, false) }) +} +func runHealthyRecoveryPrefix(t *testing.T, seeded bool) { primary := storage.NewBlockStore(64, blockSize) for lba := uint32(0); lba < 32; lba++ { if _, err := primary.Write(lba, makeData(byte(lba+1))); err != nil { @@ -39,11 +44,17 @@ func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) { } store := storage.NewBlockStore(64, blockSize) gate := &observedPrefixGate{ReplicaApplyGate: NewReplicaApplyGate(store), certified: make(chan prefixResult, 8)} - if err := gate.ApplyLive(liveLineage(1), 0, makeData(1), 1); err != nil { - t.Fatal(err) - } - if _, err := store.Sync(); err != nil { - t.Fatal(err) + if seeded { + if err := gate.ApplyLive(liveLineage(1), 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + // This initial BASE is known complete; Sync alone must not establish it. + if err := gate.ReplicaApplyGate.CertifyRecoveryPrefix(recoveryLineage(1, 1)); err != nil { + t.Fatal(err) + } } listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) if err != nil { @@ -72,7 +83,7 @@ func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) { t.Fatalf("wire certified prefix=%d want32", got) } tracked, _, _, found := gate.SessionState(certified.SessionID) - if !found || tracked != 0 { + if (seeded && !found) || tracked != 0 { t.Fatalf("wire recovery did not prune: found=%v tracked=%d", found, tracked) } } @@ -131,3 +142,73 @@ func TestApplyGate_WirePrefixCannotIntroduceOrReviveSession(t *testing.T) { t.Fatal("stale session certified prefix") } } + +// A clean recovery close cannot certify a pre-existing hole in its starting R. +func TestApplyGate_WirePrefixRequiresCoveredStartingImage(t *testing.T) { + gate, store := newGate(t) + if err := gate.ApplyLive(liveLineage(1), 5, makeData(0xBB), 120); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) + if err != nil { + t.Fatal(err) + } + if err := listener.AdmitAsReplica(1); err != nil { + listener.StopHard() + t.Fatal(err) + } + listener.Serve() + t.Cleanup(listener.StopHard) + lineage := recoveryLineage(2, 120) + dial := func() net.Conn { + t.Helper() + c, err := net.DialTimeout("tcp", listener.Addr(), time.Second) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + if err := c.SetDeadline(time.Now().Add(2 * time.Second)); err != nil { + t.Fatal(err) + } + return c + } + barrier := func(c net.Conn) error { + if err := transport.WriteMsg(c, transport.MsgBarrierReq, transport.EncodeLineage(lineage)); err != nil { + return err + } + _, _, err := transport.ReadMsg(c) + return err + } + c := dial() + if err := transport.WriteMsg(c, transport.MsgRecoveryLaneStart, transport.EncodeLineage(lineage)); err != nil { + t.Fatal(err) + } + if err := barrier(c); err != nil { + t.Fatal(err) + } + if err := transport.WriteMsg(c, transport.MsgCertifiedPrefix, transport.EncodeLineage(lineage)); err != nil { + t.Fatal(err) + } + _ = barrier(c) // certificate refusal closes this connection + if got := gate.CertifiedPrefix(); got != 0 { + t.Fatalf("uncertified starting R advanced P=%d", got) + } + c = dial() + if err := transport.WriteMsg(c, transport.MsgRecoveryLaneStart, transport.EncodeLineage(lineage)); err != nil { + t.Fatal(err) + } + want := makeData(0xAA) + if err := transport.WriteMsg(c, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: lineage, LBA: 6, LSN: 95, Data: want})); err != nil { + t.Fatal(err) + } + if err := barrier(c); err != nil { + t.Fatal(err) + } + got, err := store.Read(6) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("uncertified starting image swallowed recovery hole: err=%v", err) + } +} diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 084b9aaefe..a0ce27c2f4 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -42,6 +42,7 @@ const ( // not derive source coverage from Sync. Admission is checked at the effect. type RecoveryPrefixHook interface { CertifyRecoveryPrefix(lineage RecoveryLineage) error + CertifiedPrefix() uint64 } type ApplyHook interface { @@ -64,8 +65,9 @@ type ReplicaListener struct { wg sync.WaitGroup applyHook ApplyHook // optional gate plug-in; nil = direct apply - mu sync.Mutex - activeLineage RecoveryLineage + mu sync.Mutex + activeLineage RecoveryLineage + prefixEligible RecoveryLineage // one active source-covered recovery certificate // 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 @@ -382,6 +384,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { return true } lane = mutationLaneRecovery + r.markPrefixEligibility(lineage, false) case MsgShipEntry: entry, err := DecodeShipEntry(payload) @@ -509,6 +512,8 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: sync after rebuild done: %v", err) return true } + // A completed full BASE supplies the covered starting image. + r.markPrefixEligibility(lineage, true) // Echo the request's full lineage in the rebuild-done ack // so primary-side validators can consume it. resp := EncodeBarrierResp(BarrierResponse{ @@ -802,7 +807,7 @@ func (r *ReplicaListener) certifyRecoveryPrefix(lineage RecoveryLineage) error { r.mu.Lock() defer r.mu.Unlock() if r.primary || (r.requireRole && !r.assigned) || lineage.Epoch < r.epochFloor || - lineage.SessionID == 0 || lineage.EffectiveFrontierHint() == 0 || !r.activeLineage.Equivalent(lineage) { + lineage.SessionID == 0 || lineage.EffectiveFrontierHint() == 0 || !r.activeLineage.Equivalent(lineage) || !r.prefixEligible.Equivalent(lineage) { return fmt.Errorf("replica: uncertified/stale recovery lineage") } hook, ok := r.applyHook.(RecoveryPrefixHook) @@ -811,3 +816,24 @@ func (r *ReplicaListener) certifyRecoveryPrefix(lineage RecoveryLineage) error { } return hook.CertifyRecoveryPrefix(lineage) } + +// A successful scan can extend only an already-covered starting prefix. The +// engine starts catch-up at probed R+1; R is monotone, so observing local R<=P +// at the lane marker is a conservative bound on that starting R. A completed +// full BASE instead supplies its own prefix. A refusal only retains history. +func (r *ReplicaListener) markPrefixEligibility(lineage RecoveryLineage, fullBase bool) { + r.mu.Lock() + defer r.mu.Unlock() + if !r.activeLineage.Equivalent(lineage) || r.primary || (r.requireRole && !r.assigned) { + return + } + r.prefixEligible = RecoveryLineage{} + hook, ok := r.applyHook.(RecoveryPrefixHook) + if !ok { + return + } + synced, _, _ := r.store.Boundaries() + if fullBase || synced <= hook.CertifiedPrefix() { + r.prefixEligible = lineage + } +} From 7261411c467892aabb79395584c0f4c04090e926 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:04:01 -0800 Subject: [PATCH 17/20] docs: state prefix provenance and remaining healthy-run bound --- seaweed-block/docs/design/invariants.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e30a534706..fabac920e5 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -116,10 +116,10 @@ stateDiagram-v2 The apply gate retains versions only above its certified contiguous prefix P. Completed recovery plus post-close healthy publication sends an explicit full-lineage -certificate; current listener admission and the durable boundary guard it. Sync R, +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. +RF2 qualification limitation until ordered-live certification is wired (#297). Session coverage teardown is separate. **Host role and listener admission.** From 61274080b08b68178691cbb8d156cdde1c12ad4e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:12:09 -0800 Subject: [PATCH 18/20] test: reproduce false readiness and retained settled replica coverage --- .../engine/recovery_review_regression_test.go | 29 ++++++++++ .../replication/apply_gate_retirement_test.go | 54 +++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 seaweed-block/core/engine/recovery_review_regression_test.go create mode 100644 seaweed-block/core/replication/apply_gate_retirement_test.go diff --git a/seaweed-block/core/engine/recovery_review_regression_test.go b/seaweed-block/core/engine/recovery_review_regression_test.go new file mode 100644 index 0000000000..627be92efa --- /dev/null +++ b/seaweed-block/core/engine/recovery_review_regression_test.go @@ -0,0 +1,29 @@ +package engine + +import "testing" + +func TestPromotionReadyRefusesDelayedProbeDuringNewRecovery(t *testing.T) { + st := helperPrime(t, 50, 10, 100) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, FrontierHint: 100}) + Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 1, AchievedLSN: 100}) + Apply(st, DurableAckObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100}) + Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 100, S: 10, H: 150}) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 2, Kind: SessionCatchUp, FrontierHint: 150}) + Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 100}) + if fact := BuildPromotionReadyFact(st); fact.Ready { + t.Fatalf("active recovery became promotion ready after delayed probe: %+v", fact) + } +} + +func TestMissingProbeAckRestoresNewerDurableProgress(t *testing.T) { + st := helperPrime(t, 50, 10, 100) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, FrontierHint: 100}) + Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 1, AchievedLSN: 100}) + Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1}) + result := Apply(st, DurableAckObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 150, PrimaryTailLSN: 110, PrimaryHeadLSN: 150}) + if st.Recovery.R != 150 || st.Recovery.Decision != DecisionNone { + t.Fatalf("missing-probe ACK retained stale progress: R=%d decision=%s", st.Recovery.R, st.Recovery.Decision) + } + assertNoCommand(t, result, "StartRebuild") + assertNoCommand(t, result, "StartCatchUp") +} diff --git a/seaweed-block/core/replication/apply_gate_retirement_test.go b/seaweed-block/core/replication/apply_gate_retirement_test.go new file mode 100644 index 0000000000..64e506e94b --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_retirement_test.go @@ -0,0 +1,54 @@ +package replication + +import ( + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/transport" +) + +func TestApplyGate_WireSessionTurnoverRetiresSettledCoverage(t *testing.T) { + gate, store := newGate(t) + listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) + if err != nil { + t.Fatal(err) + } + if err := listener.AdmitAsReplica(1); err != nil { + listener.StopHard() + t.Fatal(err) + } + listener.Serve() + t.Cleanup(listener.StopHard) + for session := uint64(1); session <= 128; session++ { + c, err := net.DialTimeout("tcp", listener.Addr(), time.Second) + if err != nil { + t.Fatal(err) + } + if err := c.SetDeadline(time.Now().Add(2 * time.Second)); err != nil { + c.Close() + t.Fatal(err) + } + l := liveLineage(session) + err = transport.WriteMsg(c, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: l, LBA: 5, LSN: session, Data: makeData(byte(session))})) + if err == nil { + err = transport.WriteMsg(c, transport.MsgBarrierReq, transport.EncodeLineage(l)) + } + if err == nil { + _, _, err = transport.ReadMsg(c) + } + c.Close() + if err != nil { + t.Fatal(err) + } + if session > 1 { + if _, _, _, found := gate.SessionState(session - 1); found { + t.Fatalf("settled session coverage survived turnover: session=%d", session-1) + } + } + } + // Retirement must leave the shared suffix version intact. + if err := gate.ApplyLive(liveLineage(129), 5, makeData(0), 127); err == nil { + t.Fatal("coverage retirement erased shared version") + } +} From 704eedac6730fac5499055087b73ca2ea96d92f5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:16:35 -0800 Subject: [PATCH 19/20] 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 | From db07ef2c160a872ccd99f6bdbf778b00b55db1df Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:23:15 -0800 Subject: [PATCH 20/20] docs: align replica lifecycle and promotion guard models --- seaweed-block/core/transport/replica.go | 2 ++ seaweed-block/docs/design/block-design.md | 1 + seaweed-block/docs/design/invariants.md | 9 +++--- seaweed-block/docs/spec/README.md | 7 ++++ .../docs/spec/ReplicaReviewGuards.tla | 32 +++++++++++++++++++ .../docs/spec/cfg/R293_review_red_ack.cfg | 6 ++++ .../spec/cfg/R293_review_red_early_close.cfg | 6 ++++ .../spec/cfg/R293_review_red_readiness.cfg | 6 ++++ .../spec/cfg/R293_review_red_retention.cfg | 6 ++++ .../docs/spec/cfg/R293_review_safe.cfg | 6 ++++ seaweed-block/docs/spec/run.sh | 1 + 11 files changed, 78 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/docs/spec/ReplicaReviewGuards.tla create mode 100644 seaweed-block/docs/spec/cfg/R293_review_red_ack.cfg create mode 100644 seaweed-block/docs/spec/cfg/R293_review_red_early_close.cfg create mode 100644 seaweed-block/docs/spec/cfg/R293_review_red_readiness.cfg create mode 100644 seaweed-block/docs/spec/cfg/R293_review_red_retention.cfg create mode 100644 seaweed-block/docs/spec/cfg/R293_review_safe.cfg diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 9ac13c5017..b413222c7e 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -42,6 +42,8 @@ const ( // not derive source coverage from Sync. Admission is checked at the effect. type SessionRetirer interface{ CloseSession(sessionID uint64) } +// RecoveryPrefixHook accepts explicit completed-prefix certificates. It does +// not derive source coverage from Sync. Admission is checked at the effect. type RecoveryPrefixHook interface { CertifyRecoveryPrefix(lineage RecoveryLineage) error CertifiedPrefix() uint64 diff --git a/seaweed-block/docs/design/block-design.md b/seaweed-block/docs/design/block-design.md index 9061f000c4..f3f35d38e8 100644 --- a/seaweed-block/docs/design/block-design.md +++ b/seaweed-block/docs/design/block-design.md @@ -298,6 +298,7 @@ stateDiagram-v2 Healthy --> Degraded: barrier or ship failure Degraded --> CatchingUp: gap within the primary's WAL CatchingUp --> CatchingUp: identical recovery facts retain the prepared session + CatchingUp --> CatchingUp: active session refuses promotion readiness Healthy --> Healthy: delayed probe retains completed durable R Healthy --> Healthy: completed recovery certifies P, prune version suffix CatchingUp --> Healthy: caught up to the target diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6907808089..d2227ca9d4 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -132,7 +132,7 @@ RF2 qualification limitation until ordered-live certification is wired (#297). S | Primary, Supporting | Excluded | the fact names another primary and does not list this replica; ingress is closed, the other line is recorded and the frontend is unhealthy | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001` | | any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` | | (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | -| Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | +| Supporting | promotion candidate | no active recovery session; member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | **Recovery observation and apply ordering.** A probe publishes its fresh boundaries before reachability, and each emitted recovery is prepared under the adapter mutex before the next event. Same-identity delayed probes retain completed durable R; missing probe boundaries remain unknown until a valid observation arrives. Every lane and session shares one replica-wide per-LBA applied-LSN map under the apply mutex; session close releases coverage only. Recovery skips stale data while advancing its own coverage; stale live data fails without advancing recovery coverage. @@ -333,7 +333,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -83 rows: 72 ACTIVE, 11 STUB; 15 kept from the internal ledger, 68 new. +117 rows: 98 ACTIVE, 19 STUB; 15 kept from the internal ledger, 102 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. @@ -423,7 +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-SESSION-COVERAGE-RETIRE-001` | Superseded logical-session coverage is released only after every already-admitted frame for that session settles; newer sessions do not delay that release. Shared version history and P survive. | M3 replica admission / session retirement | `transport/replica.go` `admitMutation`, `endSessionFrame`; `ReplicaApplyGate.CloseSession` | `TestApplyGate_WireSessionTurnoverRetiresSettledCoverage`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes` | `ReplicaReviewGuards` NoEarlyRetirement/NoSettledHistory | ACTIVE | +| `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`, `TestMissingProbeAckRestoresNewerDurableProgress`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery; `ReplicaReviewGuards` AckRestoresProgress | 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 | @@ -431,7 +432,7 @@ Notes: | `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | | `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | | `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE | -| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | ACTIVE | +| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. An active recovery session always refuses readiness, even if delayed bounds select DecisionNone. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`), `TestPromotionReadyRefusesDelayedProbeDuringNewRecovery` | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive`; `ReplicaReviewGuards` ReadyRequiresIdle | ACTIVE | | `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | | `INV-ROLE-READINESS-BLOCK-001` | While local recovery blocks readiness, `applyFact` admits neither a primary nor a supporting role, and replays the stored fact once readiness clears. | M3 Unassigned → Primary \| Supporting (guard) | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter`, `TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter`, `TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirst` (`core/host/volume/apply_fact_test.go`) | — | ACTIVE | | `INV-ROLE-SUPERSEDED-001` | A fact naming another replica as primary, with this replica not among its peers, never reaches this host's adapter or replication, and is recorded as the other line. | M3 Primary \| Supporting → Excluded | `core/host/volume/host.go` `applyFact`, `recordOtherLine` | `TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication` (`core/host/volume/apply_fact_test.go`); `TestHost_BuildReport_SupersededReplicaNotReadyForPrimary` (`core/host/volume/frontend_targets_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index a3586b8834..7b0862480e 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -327,3 +327,10 @@ covered-prefix certification, suffix pruning and stale checks against the floor. its two negative controls infer a prefix from the synced maximum or omit the floor after pruning. It does not establish the wire certificate's provenance, restart persistence, live-prefix extension, or a fixed memory cap without closes. + +`ReplicaReviewGuards.tla` checks two logical sessions with one admitted frame +per session, settled-coverage retirement, active-recovery readiness refusal and +one missing-probe/newer-ACK schedule. `R293_review_safe` checks four invariants; +four negative controls separately remove retirement, the frame join, the +readiness guard or ACK progress restoration. This abstracts successful admitted +frames and does not prove physical-I/O, authority rollback or timing behavior. diff --git a/seaweed-block/docs/spec/ReplicaReviewGuards.tla b/seaweed-block/docs/spec/ReplicaReviewGuards.tla new file mode 100644 index 0000000000..82e179c078 --- /dev/null +++ b/seaweed-block/docs/spec/ReplicaReviewGuards.tla @@ -0,0 +1,32 @@ +---------------------- MODULE ReplicaReviewGuards ---------------------- +EXTENDS Integers, TLC +CONSTANTS RetireSettled, WaitForFrames, GuardActive, RestoreAck +VARIABLES current, refs, coverage, active, ready, missing, observedR +vars == <> +Init == /\ current = 1 /\ refs = [s \in 1..2 |-> 0] /\ coverage = {1} + /\ active = FALSE /\ ready = FALSE /\ missing = TRUE /\ observedR = 100 +Admit(s) == /\ s >= current /\ refs[s] = 0 + /\ current' = s /\ refs' = [refs EXCEPT ![s] = 1] + /\ coverage' = (coverage \cup {s}) \ ( + IF RetireSettled /\ s # current /\ (refs[current] = 0 \/ ~WaitForFrames) + THEN {current} ELSE {}) + /\ UNCHANGED <> +Release(s) == /\ refs[s] = 1 /\ refs' = [refs EXCEPT ![s] = 0] + /\ coverage' = IF RetireSettled /\ s # current THEN coverage \ {s} ELSE coverage + /\ UNCHANGED <> +Prepare == /\ ~active /\ active' = TRUE /\ ready' = FALSE + /\ UNCHANGED <> +DelayedProbe == /\ active /\ ready' = ~GuardActive + /\ UNCHANGED <> +Finish == /\ active /\ active' = FALSE /\ ready' = TRUE + /\ UNCHANGED <> +Ack == /\ missing /\ missing' = FALSE + /\ observedR' = IF RestoreAck THEN 150 ELSE 100 + /\ UNCHANGED <> +Next == (\E s \in 1..2 : Admit(s) \/ Release(s)) \/ Prepare \/ DelayedProbe \/ Finish \/ Ack +Spec == Init /\ [][Next]_vars +NoEarlyRetirement == \A s \in 1..2 : refs[s] = 1 => s \in coverage +NoSettledHistory == \A s \in coverage : s = current \/ refs[s] = 1 +ReadyRequiresIdle == ready => ~active +AckRestoresProgress == ~missing => observedR = 150 +============================================================================= \ No newline at end of file diff --git a/seaweed-block/docs/spec/cfg/R293_review_red_ack.cfg b/seaweed-block/docs/spec/cfg/R293_review_red_ack.cfg new file mode 100644 index 0000000000..8ff050bb89 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_red_ack.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = TRUE + WaitForFrames = TRUE + GuardActive = TRUE + RestoreAck = FALSE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/cfg/R293_review_red_early_close.cfg b/seaweed-block/docs/spec/cfg/R293_review_red_early_close.cfg new file mode 100644 index 0000000000..c9ebaae853 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_red_early_close.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = TRUE + WaitForFrames = FALSE + GuardActive = TRUE + RestoreAck = TRUE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/cfg/R293_review_red_readiness.cfg b/seaweed-block/docs/spec/cfg/R293_review_red_readiness.cfg new file mode 100644 index 0000000000..2ea4b4a0da --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_red_readiness.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = TRUE + WaitForFrames = TRUE + GuardActive = FALSE + RestoreAck = TRUE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/cfg/R293_review_red_retention.cfg b/seaweed-block/docs/spec/cfg/R293_review_red_retention.cfg new file mode 100644 index 0000000000..d67850d71a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_red_retention.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = FALSE + WaitForFrames = TRUE + GuardActive = TRUE + RestoreAck = TRUE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/cfg/R293_review_safe.cfg b/seaweed-block/docs/spec/cfg/R293_review_safe.cfg new file mode 100644 index 0000000000..ba56fd7d5f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_safe.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = TRUE + WaitForFrames = TRUE + GuardActive = TRUE + RestoreAck = TRUE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/run.sh b/seaweed-block/docs/spec/run.sh index 06ed9184b8..06c7e844f3 100755 --- a/seaweed-block/docs/spec/run.sh +++ b/seaweed-block/docs/spec/run.sh @@ -25,6 +25,7 @@ case $cfg in S4_*) spec=CutCapture ;; S5_*) spec=ControlPlane ;; S6_*) spec=ReplicationFailover ;; + R293_review_*) spec=ReplicaReviewGuards ;; R293_prefix_*) spec=ReplicaPrefixFloor ;; R292_*) spec=ReplicaApplyOrder ;; S9b_*) spec=RetentionGCMulti ;;