fix: prune replica versions only behind certified recovery prefixes

This commit is contained in:
pingqiu committed 2026-11-20 05:17:12 -08:00
1 parent 28d3054de5
commit 85bf19a8bb
11 files changed
+330 -8

No files matched your search

+5
View File
@@ -575,6 +575,11 @@ func (a *VolumeReplicaAdapter) executeCommand(q queuedCommand) {
a.executor.InvalidateSession(c.ReplicaID, c.SessionID, c.Reason)
case engine.PublishHealthy:
if c.CertifiedPrefix != 0 {
if publisher, ok := a.executor.(RecoveryPrefixPublisher); ok {
publisher.PublishRecoveryPrefix(c.ReplicaID, c.RecoverySessionID, c.Epoch, c.EndpointVersion, c.CertifiedPrefix)
}
}
a.executor.PublishHealthy(c.ReplicaID)
case engine.PublishDegraded:
+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)
}
+13 -1
View File
@@ -524,7 +524,19 @@ func decide(st *ReplicaState, r *ApplyResult, trace func(string, string)) {
} else if recoveredReplicaWaitingForPostCloseAck(st) {
trace("publish_healthy_held", "waiting for post-close durable ack")
} else {
r.Commands = append(r.Commands, PublishHealthy{ReplicaID: st.Identity.ReplicaID})
healthy := PublishHealthy{ReplicaID: st.Identity.ReplicaID}
target := st.Session.FrontierHint
if target == 0 {
target = st.Session.TargetLSN
}
if st.Recovery.RecoveryWindowClosed && st.Recovery.PostCloseDurableAckKnown &&
st.Session.Phase == PhaseCompleted && target > 0 && st.Session.AchievedLSN >= target {
healthy.RecoverySessionID = st.Session.SessionID
healthy.Epoch = st.Identity.Epoch
healthy.EndpointVersion = st.Identity.EndpointVersion
healthy.CertifiedPrefix = target
}
r.Commands = append(r.Commands, healthy)
}
}
+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" }
@@ -0,0 +1,25 @@
package engine
import "testing"
func TestHealthyPrefixRequiresCompletedRecoveryAndPostCloseAck(t *testing.T) {
st := helperPrime(t, 1, 1, 100)
Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 8, Kind: SessionCatchUp, FrontierHint: 100})
Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 8})
result := Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 8, AchievedLSN: 100})
for _, command := range result.Commands {
if _, ok := command.(PublishHealthy); ok {
t.Fatal("recovery close certified before post-close ack")
}
}
result = Apply(st, DurableAckObserved{ReplicaID: "r1", SessionID: 8, EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 120, PrimaryTailLSN: 1, PrimaryHeadLSN: 120})
for _, command := range result.Commands {
if healthy, ok := command.(PublishHealthy); ok {
if healthy.CertifiedPrefix != 100 || healthy.RecoverySessionID != 8 || healthy.Epoch != 1 || healthy.EndpointVersion != 1 {
t.Fatalf("healthy publication lost exact completed target: %+v", healthy)
}
return
}
}
t.Fatal("post-close ack did not publish certified recovery prefix")
}
+41 -3
View File
@@ -68,6 +68,7 @@ type ReplicaApplyGate struct {
mu sync.Mutex
sessions map[uint64]*applyGateSession // keyed by lineage.SessionID
appliedLSN map[uint32]uint64 // replica-wide, shared by every lane and session
floorLSN uint64 // certified contiguous prefix; never inferred from synced maximum R
}
// applyGateSession is the per-recovery-session state. Per round-44
@@ -165,7 +166,7 @@ func (g *ReplicaApplyGate) applyRecovery(sess *applyGateSession, lba uint32, dat
g.mu.Lock()
defer g.mu.Unlock()
if existing, ok := g.appliedLSN[lba]; ok && lsn <= existing {
if existing := max(g.appliedLSN[lba], g.floorLSN); lsn <= existing {
// Stale: skip data write but ADVANCE recoveryCovered.
sess.recoveryCovered[lba] = true
return nil
@@ -190,7 +191,7 @@ func (g *ReplicaApplyGate) applyLive(sess *applyGateSession, lba uint32, data []
g.mu.Lock()
defer g.mu.Unlock()
if existing, ok := g.appliedLSN[lba]; ok && lsn <= existing {
if existing := max(g.appliedLSN[lba], g.floorLSN); lsn <= existing {
// Stale: fail-loud. Caller logs + drops conn.
return fmt.Errorf("apply gate: live-lane stale entry lba=%d lsn=%d <= applied=%d (INV-REPL-LIVE-LANE-STALE-FAILS-LOUD)",
lba, lsn, existing)
@@ -224,7 +225,9 @@ func (g *ReplicaApplyGate) initSessionLocked(sessionID uint64) *applyGateSession
return sess
}
for lba, lsn := range seed {
g.appliedLSN[lba] = max(g.appliedLSN[lba], lsn)
if lsn > g.floorLSN {
g.appliedLSN[lba] = max(g.appliedLSN[lba], lsn)
}
}
return sess
}
@@ -288,3 +291,38 @@ func (g *ReplicaApplyGate) SessionAppliedLSN(sessionID uint64, lba uint32) (uint
lsn, present := g.appliedLSN[lba]
return lsn, present
}
// CertifyRecoveryPrefix accepts an explicit source-coverage certificate emitted
// only after a successful recovery close is published healthy. Sync/Boundaries
// alone cannot certify coverage: a high live LSN can be durable across a hole.
// The transport owns lineage admission. A missing/refused certificate retains
// history conservatively; ordinary live traffic does not advance this floor.
func (g *ReplicaApplyGate) CertifyRecoveryPrefix(lineage transport.RecoveryLineage) error {
prefix := lineage.EffectiveFrontierHint()
g.mu.Lock()
defer g.mu.Unlock()
r, _, _ := g.store.Boundaries()
if prefix == 0 || prefix > r {
return fmt.Errorf("apply gate: certified prefix %d exceeds durable boundary %d or is zero", prefix, r)
}
if prefix <= g.floorLSN {
return nil
}
// Rebuild rather than only deleting: release the old map's bucket capacity.
retained := make(map[uint32]uint64)
for lba, lsn := range g.appliedLSN {
if lsn > prefix {
retained[lba] = lsn
}
}
g.appliedLSN = retained
g.floorLSN = prefix
return nil
}
// CertifiedPrefix reports the source-certified coverage frontier, not R.
func (g *ReplicaApplyGate) CertifiedPrefix() uint64 {
g.mu.Lock()
defer g.mu.Unlock()
return g.floorLSN
}
@@ -26,9 +26,9 @@ func TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole(t *testing.T) {
}
}
// Each batch completes durability and closes coverage; retained version history
// should scale with the outstanding suffix, rather than all LBAs ever written.
func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) {
// Each batch has a successful recovery close and an explicit prefix certificate.
// Durability alone is insufficient; ordinary healthy traffic remains unbounded.
func TestApplyGate_CertifiedRecoveryClosesBoundVersionHistory(t *testing.T) {
const batch = 32
store := storage.NewBlockStore(1025, 1)
gate := NewReplicaApplyGate(store)
@@ -45,6 +45,9 @@ func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) {
if _, err := store.Sync(); err != nil {
t.Fatal(err)
}
if err := gate.CertifyRecoveryPrefix(recoveryLineage(session, lsn)); err != nil {
t.Fatal(err)
}
// A subsequent apply provides a lazy-pruning opportunity.
lsn++
if err := gate.ApplyLive(liveLineage(session), 1024, []byte{0xCC}, lsn); err != nil {
@@ -69,6 +72,9 @@ func TestApplyGate_PrunedDurableVersionsRemainStale(t *testing.T) {
if _, err := store.Sync(); err != nil {
t.Fatal(err)
}
if err := gate.CertifyRecoveryPrefix(recoveryLineage(1, 32)); err != nil {
t.Fatal(err)
}
gate.CloseSession(1)
if err := gate.ApplyRecovery(recoveryLineage(2, 32), 5, makeData(0xAA), 1); err != nil {
t.Fatal(err)
@@ -93,3 +99,43 @@ func TestApplyGate_PrunedDurableVersionsRemainStale(t *testing.T) {
t.Fatalf("durable versions were not pruned: tracked=%d want=0", tracked)
}
}
func TestApplyGate_CertifiedPrefixFreezesAcrossSessions(t *testing.T) {
gate, store := newGate(t)
if err := gate.ApplyRecovery(recoveryLineage(1, 1), 0, makeData(1), 1); err != nil {
t.Fatal(err)
}
if _, err := store.Sync(); err != nil {
t.Fatal(err)
}
if err := gate.CertifyRecoveryPrefix(recoveryLineage(1, 1)); err != nil {
t.Fatal(err)
}
gate.CloseSession(1)
if err := gate.ApplyLive(liveLineage(2), 5, makeData(0xBB), 120); err != nil {
t.Fatal(err)
}
if _, err := store.Sync(); err != nil {
t.Fatal(err)
}
if got := gate.CertifiedPrefix(); got != 1 {
t.Fatalf("new session or Sync extended certified floor: P=%d", got)
}
want := makeData(0xAA)
if err := gate.ApplyRecovery(recoveryLineage(3, 100), 6, want, 95); err != nil {
t.Fatal(err)
}
got, err := store.Read(6)
if err != nil || !bytes.Equal(got, want) {
t.Fatalf("frozen prefix swallowed missing recovery: err=%v", err)
}
if err := gate.CertifyRecoveryPrefix(recoveryLineage(3, 121)); err == nil {
t.Fatal("certificate above durable boundary accepted")
}
if err := gate.CertifyRecoveryPrefix(recoveryLineage(3, 1)); err != nil {
t.Fatal(err)
}
if gate.CertifiedPrefix() != 1 {
t.Fatal("failed/repeated certificate changed prefix")
}
}
@@ -0,0 +1,126 @@
package replication
import (
"net"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
type observedPrefixGate struct {
*ReplicaApplyGate
certified chan error
}
func (g *observedPrefixGate) CertifyRecoveryPrefix(l transport.RecoveryLineage) error {
err := g.ReplicaApplyGate.CertifyRecoveryPrefix(l)
g.certified <- err
return err
}
// Real primary engine/adapter/executor -> role-gated replica -> shared gate.
func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) {
primary := storage.NewBlockStore(64, blockSize)
for lba := uint32(0); lba < 32; lba++ {
if _, err := primary.Write(lba, makeData(byte(lba+1))); err != nil {
t.Fatal(err)
}
}
if _, err := primary.Sync(); err != nil {
t.Fatal(err)
}
store := storage.NewBlockStore(64, blockSize)
gate := &observedPrefixGate{ReplicaApplyGate: NewReplicaApplyGate(store), certified: make(chan error, 8)}
if err := gate.ApplyLive(liveLineage(1), 0, makeData(1), 1); err != nil {
t.Fatal(err)
}
if _, err := store.Sync(); err != nil {
t.Fatal(err)
}
listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate)
if err != nil {
t.Fatal(err)
}
if err := listener.AdmitAsReplica(1); err != nil {
listener.StopHard()
t.Fatal(err)
}
listener.Serve()
executor := transport.NewBlockExecutor(primary, listener.Addr())
t.Cleanup(func() { executor.Stop(); listener.StopHard() })
a := adapter.NewVolumeReplicaAdapter(executor)
a.OnAssignment(adapter.AssignmentInfo{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: listener.Addr()})
select {
case err := <-gate.certified:
if err != nil {
t.Fatal(err)
}
case <-time.After(5 * time.Second):
t.Fatal("healthy recovery did not publish wire prefix certificate")
}
if got := gate.CertifiedPrefix(); got != 32 {
t.Fatalf("wire certified prefix=%d want32", got)
}
tracked, _, _, found := gate.SessionState(2)
if !found || tracked != 0 {
t.Fatalf("wire recovery did not prune: found=%v tracked=%d", found, tracked)
}
}
func TestApplyGate_WirePrefixCannotIntroduceOrReviveSession(t *testing.T) {
gate, store := newGate(t)
if err := gate.ApplyRecovery(recoveryLineage(1, 1), 0, makeData(1), 1); err != nil {
t.Fatal(err)
}
if _, err := store.Sync(); err != nil {
t.Fatal(err)
}
listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate)
if err != nil {
t.Fatal(err)
}
if err := listener.AdmitAsReplica(1); err != nil {
listener.StopHard()
t.Fatal(err)
}
listener.Serve()
t.Cleanup(listener.StopHard)
send := func(l transport.RecoveryLineage, certificate bool) {
t.Helper()
c, err := net.DialTimeout("tcp", listener.Addr(), time.Second)
if err != nil {
t.Fatal(err)
}
defer c.Close()
if err := c.SetDeadline(time.Now().Add(2 * time.Second)); err != nil {
t.Fatal(err)
}
if certificate {
if err := transport.WriteMsg(c, transport.MsgCertifiedPrefix, transport.EncodeLineage(l)); err != nil {
t.Fatal(err)
}
}
if err := transport.WriteMsg(c, transport.MsgBarrierReq, transport.EncodeLineage(l)); err != nil {
if certificate {
return
}
t.Fatal(err)
}
kind, _, err := transport.ReadMsg(c)
if !certificate && (err != nil || kind != transport.MsgBarrierResp) {
t.Fatalf("setup barrier: kind=%d err=%v", kind, err)
}
}
send(recoveryLineage(1, 1), true) // unseen: rejected, must not introduce lineage
if gate.CertifiedPrefix() != 0 {
t.Fatal("unseen session certified prefix")
}
send(recoveryLineage(2, 1), false)
send(recoveryLineage(1, 1), true) // superseded: cannot certify even with valid R
if gate.CertifiedPrefix() != 0 {
t.Fatal("stale session certified prefix")
}
}
+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
+30 -1
View File
@@ -38,6 +38,12 @@ const (
// Returning a non-nil error → caller (handler) logs + closes conn.
// Per INV-REPL-LIVE-LANE-STALE-FAILS-LOUD: live-lane stale entries
// surface here as errors.
// RecoveryPrefixHook accepts explicit completed-prefix certificates. It does
// not derive source coverage from Sync. Admission is checked at the effect.
type RecoveryPrefixHook interface {
CertifyRecoveryPrefix(lineage RecoveryLineage) error
}
type ApplyHook interface {
// ApplyRecovery routes the entry through the recovery-lane apply
// path. Stale entries (LSN <= per-LBA applied) skip data + advance
@@ -512,6 +518,12 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
replyType, reply = MsgBarrierResp, resp
return true
case MsgCertifiedPrefix:
lineage, err := DecodeLineage(payload)
if err != nil || r.certifyRecoveryPrefix(lineage) != nil {
return true
}
case MsgBarrierReq:
lineage, err := DecodeLineage(payload)
if err != nil {
@@ -660,7 +672,7 @@ const defaultFenceDrainTimeout = 10 * time.Second
// isMutationMsg names the frames that pass acceptMutationLineage.
func isMutationMsg(msgType byte) bool {
switch msgType {
case MsgRecoveryLaneStart, MsgShipEntry, MsgRebuildBlock, MsgRebuildDone, MsgBarrierReq:
case MsgRecoveryLaneStart, MsgShipEntry, MsgRebuildBlock, MsgRebuildDone, MsgBarrierReq, MsgCertifiedPrefix:
return true
}
return false
@@ -782,3 +794,20 @@ func compareLineage(a, b RecoveryLineage) int {
return 0
}
}
// A certificate cannot introduce an unseen session or survive a later one.
// Lock order: listener.mu -> gate.mu -> store boundary read. There is no wire
// or physical I/O here; fencing/session admission cannot cross the effect.
func (r *ReplicaListener) certifyRecoveryPrefix(lineage RecoveryLineage) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.primary || (r.requireRole && !r.assigned) || lineage.Epoch < r.epochFloor ||
lineage.SessionID == 0 || lineage.EffectiveFrontierHint() == 0 || !r.activeLineage.Equivalent(lineage) {
return fmt.Errorf("replica: uncertified/stale recovery lineage")
}
hook, ok := r.applyHook.(RecoveryPrefixHook)
if !ok {
return fmt.Errorf("replica: no recovery prefix hook")
}
return hook.CertifyRecoveryPrefix(lineage)
}