Merge pull request #293 from seaweedfs/fix/recovery-event-dedup

fix: deduplicate recovery observations and reject cross-session stale writes
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-20 08:09:25 -08:00
commit f2f22bb8ce
45 files changed
+1511 -100

No files matched your search

@@ -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
}
@@ -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)
}
}
+22 -15
View File
@@ -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()
@@ -573,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:
+6
View File
@@ -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)
}
+11 -11
View File
@@ -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
}
@@ -0,0 +1,124 @@
package adapter
import (
"strconv"
"sync"
"testing"
"time"
"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() {
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
}
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_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_OneRecoveryFromPostCloseStalledAck(t *testing.T) {
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
}
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")
})
}
}
func TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery(t *testing.T) {
for _, n := range []int{8, 5} {
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})
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) }()
}
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())
}
if p := a.Projection(); p.Mode != engine.ModeHealthy {
t.Fatalf("old facts regressed healthy replica: %+v", p)
}
})
}
}
+16 -16
View File
@@ -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()
@@ -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
+30 -2
View File
@@ -295,7 +295,10 @@ 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.FactsMissing = !e.ProgressFact().PrimaryBoundsKnown
st.Recovery.S = e.S
st.Recovery.H = e.H
@@ -309,6 +312,11 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra
return
}
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
}
updateDurableAckLagState(st, fact)
if fact.ReplicaR > st.Recovery.DurableAckR || !st.Recovery.DurableAckKnown {
st.Recovery.DurableAckR = fact.ReplicaR
@@ -347,6 +355,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
@@ -362,6 +371,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)
@@ -441,6 +451,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,
@@ -509,7 +525,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)
}
}
+2
View File
@@ -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" }
@@ -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:
@@ -0,0 +1,42 @@
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", 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")
}
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")
}
}
@@ -0,0 +1,43 @@
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)
}
// 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)
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")
}
@@ -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")
}
+3
View File
@@ -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)
+68 -32
View File
@@ -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,18 @@ 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
floorLSN uint64 // certified contiguous prefix; never inferred from synced maximum R
}
// 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 +91,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 +166,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 := max(g.appliedLSN[lba], g.floorLSN); lsn <= existing {
// Stale: skip data write but ADVANCE recoveryCovered.
sess.recoveryCovered[lba] = true
return nil
@@ -176,7 +175,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 +191,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 := 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)
@@ -202,17 +201,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 +219,23 @@ 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
if lsn > g.floorLSN {
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 +247,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 +259,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 +277,52 @@ 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
}
// 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
}
@@ -0,0 +1,106 @@
package replication
import (
"bytes"
"errors"
"testing"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// 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")
}
})
}
}
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)
}
}
@@ -0,0 +1,141 @@
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 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)
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)
lsn++
if err := gate.ApplyLive(liveLineage(session), lba, []byte{0xBB}, lsn); err != nil {
t.Fatal(err)
}
}
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 {
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)
}
}
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)
}
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)
}
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)
}
}
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")
}
}
@@ -0,0 +1,214 @@
package replication
import (
"bytes"
"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 prefixResult struct {
lineage transport.RecoveryLineage
err error
}
type observedPrefixGate struct {
*ReplicaApplyGate
certified chan prefixResult
}
func (g *observedPrefixGate) CertifyRecoveryPrefix(l transport.RecoveryLineage) error {
err := g.ReplicaApplyGate.CertifyRecoveryPrefix(l)
g.certified <- prefixResult{l, err}
return err
}
// 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 {
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 prefixResult, 8)}
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 {
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()})
var certified transport.RecoveryLineage
select {
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(certified.SessionID)
if (seeded && !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")
}
}
// 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)
}
}
@@ -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")
}
}
@@ -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).
@@ -0,0 +1,117 @@
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
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 {
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), closed: make(chan uint64, 8)}
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)
if _, _, _, found := h.SessionState(old.SessionID); !found {
t.Fatal("admitted old frame lost coverage before settlement")
}
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")
}
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)
}
}
+29
View File
@@ -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)
}
}()
}
+4
View File
@@ -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
+150 -13
View File
@@ -38,6 +38,17 @@ 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 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
}
type ApplyHook interface {
// ApplyRecovery routes the entry through the recovery-lane apply
// path. Stale entries (LSN <= per-LBA applied) skip data + advance
@@ -58,8 +69,11 @@ 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
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
@@ -104,6 +118,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 +131,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
}
@@ -149,21 +169,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
}
@@ -231,6 +261,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
@@ -266,6 +297,7 @@ func (r *ReplicaListener) StopHard() {
_ = c.Close()
}
r.wg.Wait()
r.closeSettledSessions()
}
func (r *ReplicaListener) acceptLoop() {
@@ -356,6 +388,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:
@@ -364,12 +404,13 @@ 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
}
lane = mutationLaneRecovery
r.markPrefixEligibility(lineage, false)
case MsgShipEntry:
entry, err := DecodeShipEntry(payload)
@@ -377,7 +418,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
@@ -451,7 +492,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
@@ -474,7 +515,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
@@ -497,6 +538,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{
@@ -506,13 +549,19 @@ 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 {
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
@@ -534,6 +583,9 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
}
return false
}()
if admittedSession != 0 {
r.endSessionFrame(admittedSession)
}
if mutating {
r.endMutationFrame()
}
@@ -654,7 +706,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
@@ -726,6 +778,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
@@ -776,3 +832,84 @@ 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) || !r.prefixEligible.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)
}
// 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
}
}
// 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
}
@@ -297,6 +297,10 @@ 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
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
CatchingUp --> Degraded: catch-up fails
Degraded --> Healthy: recovers
+16 -4
View File
@@ -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. 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). 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.**
| From | To | Event and guard | Enforced in | Protects |
@@ -125,14 +132,16 @@ stateDiagram-v2
| 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.
**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 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` |
@@ -324,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.
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.
@@ -414,13 +423,16 @@ Notes:
| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status |
|---|---|---|---|---|---|---|
| `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 |
| `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 |
| `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 |
+17
View File
@@ -317,3 +317,20 @@ 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`, `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.
`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.
@@ -0,0 +1,54 @@
------------------------- 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, PreserveUnknownConfidence
VARIABLES applied, local, bytes, seen, stage, active, starts, replicaR, factsKnown, knownDecision
vars == <<applied, local, bytes, seen, stage, active, starts, replicaR, factsKnown, knownDecision>>
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]
IN /\ bytes' = IF n > floor THEN n ELSE bytes
/\ applied' = Max(applied,n)
/\ local' = [local EXCEPT ![s] = Max(@,n)]
/\ seen' = Max(seen,n)
/\ UNCHANGED <<stage, active, starts, replicaR, factsKnown, knownDecision>>
\* A probe's two semantic events must observe the same reserved session.
FirstEvent == /\ stage = 0 /\ stage' = 1 /\ starts' = 1
/\ active' = PrepareEachEvent
/\ UNCHANGED <<applied, local, bytes, seen, replicaR, factsKnown, knownDecision>>
SecondEvent == /\ stage = 1 /\ stage' = 2
/\ starts' = IF active THEN starts ELSE starts + 1
/\ active' = TRUE
/\ UNCHANGED <<applied, local, bytes, seen, replicaR, factsKnown, knownDecision>>
Complete == /\ stage = 2 /\ stage' = 3 /\ replicaR' = 3
/\ active' = FALSE
/\ UNCHANGED <<applied, local, bytes, seen, starts, factsKnown, knownDecision>>
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 <<applied, local, bytes, seen, factsKnown, knownDecision>>
\* Retaining durable R does not give an all-zero probe known confidence.
MissingProbe == /\ stage = 3 /\ stage' = 5
/\ factsKnown' = FALSE
/\ knownDecision' = ~PreserveUnknownConfidence
/\ UNCHANGED <<applied, local, bytes, seen, active, starts, replicaR>>
FreshAck == /\ stage = 5 /\ stage' = 3
/\ factsKnown' = TRUE /\ knownDecision' = TRUE
/\ UNCHANGED <<applied, local, bytes, seen, active, starts, replicaR>>
Next == (\E s \in 1..2, n \in 1..3 : Apply(s,n))
\/ FirstEvent \/ SecondEvent \/ Complete \/ DelayedProbe \/ MissingProbe \/ FreshAck
Spec == Init /\ [][Next]_vars
NoRegression == bytes = seen
NoDuplicateRecovery == starts <= 1
NoFalseKnown == ~factsKnown => ~knownDecision
=============================================================================
@@ -0,0 +1,31 @@
----------------------- MODULE ReplicaPrefixFloor -----------------------
EXTENDS Integers, TLC
CONSTANTS UseFloor, CertifiedOnly
VARIABLES data, seen, versions, durable, prefix
vars == <<data, seen, versions, durable, prefix>>
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 <<durable,prefix>>
Sync == /\ durable' = Max(durable, Max(data[1],data[2]))
/\ UNCHANGED <<data,seen,versions,prefix>>
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 <<data,seen,durable>>
\* 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
=============================================================================
@@ -0,0 +1,32 @@
---------------------- MODULE ReplicaReviewGuards ----------------------
EXTENDS Integers, TLC
CONSTANTS RetireSettled, WaitForFrames, GuardActive, RestoreAck
VARIABLES current, refs, coverage, active, ready, missing, observedR
vars == <<current, refs, coverage, active, ready, missing, observedR>>
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 <<active,ready,missing,observedR>>
Release(s) == /\ refs[s] = 1 /\ refs' = [refs EXCEPT ![s] = 0]
/\ coverage' = IF RetireSettled /\ s # current THEN coverage \ {s} ELSE coverage
/\ UNCHANGED <<current,active,ready,missing,observedR>>
Prepare == /\ ~active /\ active' = TRUE /\ ready' = FALSE
/\ UNCHANGED <<current,refs,coverage,missing,observedR>>
DelayedProbe == /\ active /\ ready' = ~GuardActive
/\ UNCHANGED <<current,refs,coverage,active,missing,observedR>>
Finish == /\ active /\ active' = FALSE /\ ready' = TRUE
/\ UNCHANGED <<current,refs,coverage,missing,observedR>>
Ack == /\ missing /\ missing' = FALSE
/\ observedR' = IF RestoreAck THEN 150 ELSE 100
/\ UNCHANGED <<current,refs,coverage,active,ready>>
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
=============================================================================
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS SharedVersions = TRUE
PrepareEachEvent = FALSE
MonotoneFacts = TRUE
PreserveUnknownConfidence = TRUE
INVARIANT NoDuplicateRecovery
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS SharedVersions = TRUE
PrepareEachEvent = TRUE
MonotoneFacts = FALSE
PreserveUnknownConfidence = TRUE
INVARIANT NoDuplicateRecovery
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS SharedVersions = FALSE
PrepareEachEvent = TRUE
MonotoneFacts = TRUE
PreserveUnknownConfidence = TRUE
INVARIANT NoRegression
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS SharedVersions = TRUE
PrepareEachEvent = TRUE
MonotoneFacts = TRUE
PreserveUnknownConfidence = FALSE
INVARIANT NoFalseKnown
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS SharedVersions = TRUE
PrepareEachEvent = TRUE
MonotoneFacts = TRUE
PreserveUnknownConfidence = TRUE
INVARIANTS NoRegression NoDuplicateRecovery NoFalseKnown
@@ -0,0 +1,4 @@
SPECIFICATION Spec
CONSTANTS UseFloor = FALSE
CertifiedOnly = TRUE
INVARIANTS NoRegression
@@ -0,0 +1,4 @@
SPECIFICATION Spec
CONSTANTS UseFloor = TRUE
CertifiedOnly = FALSE
INVARIANTS NoRegression CertifiedCoverage OnlySuffix
@@ -0,0 +1,4 @@
SPECIFICATION Spec
CONSTANTS UseFloor = TRUE
CertifiedOnly = TRUE
INVARIANTS NoRegression CertifiedCoverage OnlySuffix
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS RetireSettled = TRUE
WaitForFrames = TRUE
GuardActive = TRUE
RestoreAck = FALSE
INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS RetireSettled = TRUE
WaitForFrames = FALSE
GuardActive = TRUE
RestoreAck = TRUE
INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS RetireSettled = TRUE
WaitForFrames = TRUE
GuardActive = FALSE
RestoreAck = TRUE
INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS RetireSettled = FALSE
WaitForFrames = TRUE
GuardActive = TRUE
RestoreAck = TRUE
INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS RetireSettled = TRUE
WaitForFrames = TRUE
GuardActive = TRUE
RestoreAck = TRUE
INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress
+3
View File
@@ -25,6 +25,9 @@ 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 ;;
S9_*) spec=RetentionGCTiming ;;
*) echo "run.sh: no spec for config '$cfg'" >&2; exit 2 ;;