replication: the promotion seed reconciles a survivor by (last data epoch, end) against the primary's epoch table

The ingress owns the volume's epoch table: the listener notes shipped
entries, the primary's row (epoch, durable end + 1) is made durable before
a primary role is adopted, and the replication volume reads it at the seed
barrier. A survivor whose entries are not the primary's (an equal length at
another epoch, a tail above the frontier, data without a table) needs a
rebuild and is not counted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-24 22:26:48 -08:00
1 parent e4040e8a7b
commit e628a42896
5 files changed
+163 -7

No files matched your search

+10
View File
@@ -1046,6 +1046,7 @@ func runVolume(f flags, exits *processExit) int {
// No replication socket exists until a master assignment includes
// replica slots. The role gate starts/fences both lanes before admission.
replListen = newReplicationIngress(f, store)
replVolume.SetEpochTable(replListen.EpochTable())
if err := h.SetSelfFence(replListen); err != nil {
fmt.Fprintln(os.Stderr, "blockvolume: replica listener role:", err)
replListen.Stop()
@@ -1631,6 +1632,15 @@ func hostConfig(f flags, readyCh chan<- adapter.AssignmentInfo) volume.Config {
}
}
// epochTablePath is where the volume's epoch table lives, beside the floor
// record ("" for non-durable memback runs: in memory only).
func epochTablePath(f flags) string {
if f.durableRoot == "" {
return ""
}
return filepath.Join(f.durableRoot, f.volumeID+".epoch-table")
}
func replicaFloorPath(f flags) string {
if f.durableRoot == "" {
return ""
@@ -25,9 +25,13 @@ type replicationIngress struct {
// (walstore-chunk). The host latches the error: no role is adopted, not Healthy.
rf1Only string
listener *transport.ReplicaListener
dual net.Listener
cancel context.CancelFunc
closed bool
// epochs is the volume's epoch table, kept across roles; epochsErr a load
// failure, which refuses every role.
epochs *transport.EpochTable
epochsErr error
dual net.Listener
cancel context.CancelFunc
closed bool
}
// newReplicationIngress is the volume's ingress from its flags; an RF1-only
@@ -36,9 +40,26 @@ func newReplicationIngress(f flags, store storage.LogicalStorage) *replicationIn
r := &replicationIngress{addr: f.dataAddr, store: store, volumeID: f.volumeID,
floorPath: replicaFloorPath(f), dualLane: f.recoveryMode == "dual-lane"}
r.rf1Only = rf1Only(f)
r.epochs, r.epochsErr = transport.LoadEpochTable(epochTablePath(f), f.volumeID)
return r
}
// EpochTable is the volume's epoch table (nil when it failed to load).
func (r *replicationIngress) EpochTable() *transport.EpochTable { return r.epochs }
// notePrimaryEpoch makes the primary's row (epoch, durable end + 1) durable
// before the role is adopted, so no entry of the epoch can be durable first.
func (r *replicationIngress) notePrimaryEpoch(epoch uint64) error {
if r.epochsErr != nil {
return fmt.Errorf("volume %s epoch table: %w", r.volumeID, r.epochsErr)
}
head, err := r.store.Sync()
if err != nil {
return fmt.Errorf("volume %s epoch table: local sync: %w", r.volumeID, err)
}
return r.epochs.Note(epoch, head+1)
}
// rf1Only is the single-replica rule of this volume, "" when replication is
// allowed. The host refuses assignments with replica slots (installed at
// construction, before any fact is applied or replayed); the ingress gate
@@ -59,6 +80,9 @@ func (r *replicationIngress) FenceAsPrimaryWithPeers(epoch uint64, hasPeers bool
if r.closed {
return fmt.Errorf("replication ingress closed")
}
if err := r.notePrimaryEpoch(epoch); err != nil {
return err
}
if !hasPeers {
if r.listener != nil {
if err := r.listener.FenceAsPrimary(epoch); err != nil {
@@ -82,6 +106,9 @@ func (r *replicationIngress) AdmitAsReplica(epoch uint64) error {
if r.rf1Only != "" {
return fmt.Errorf("volume %s refuses a replica role at epoch %d: %s", r.volumeID, epoch, r.rf1Only)
}
if r.epochsErr != nil {
return fmt.Errorf("volume %s epoch table: %w", r.volumeID, r.epochsErr)
}
return r.roleLocked(epoch, false)
}
func (r *replicationIngress) roleLocked(epoch uint64, primary bool) error {
@@ -97,6 +124,7 @@ func (r *replicationIngress) roleLocked(epoch uint64, primary bool) error {
if err != nil {
return err
}
listener.SetEpochTable(r.epochs)
}
var err error
if primary {
@@ -0,0 +1,90 @@
package replication
import (
"testing"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
// seedWithTables installs one survivor whose store holds lsns 1..n and
// whose epoch table is replicaRows, behind a promoted primary whose table is
// primaryRows and whose frontier is also n, and returns the peer's state
// after the promotion seed barrier.
func seedWithTables(t *testing.T, n int, replicaRows, primaryRows []transport.EpochRow) ReplicaState {
t.Helper()
const blockSize = 4096
primary := storage.NewBlockStore(64, blockSize)
replica := storage.NewBlockStore(64, blockSize)
for i := 0; i < n; i++ {
p := make([]byte, blockSize)
p[0] = 0xA0
lsn, err := primary.Write(uint32(i), p)
if err != nil {
t.Fatal(err)
}
r := make([]byte, blockSize)
r[0] = 0xB0 // the survivor's bytes differ from the new primary's above the shared prefix
if err := replica.ApplyEntry(uint32(i), r, lsn); err != nil {
t.Fatal(err)
}
}
replicaTable, _ := transport.LoadEpochTable("", "vol-promoted")
if err := replicaTable.Replace(replicaRows); err != nil {
t.Fatal(err)
}
primaryTable, _ := transport.LoadEpochTable("", "vol-promoted")
if err := primaryTable.Replace(primaryRows); err != nil {
t.Fatal(err)
}
listener, err := transport.NewReplicaListener("127.0.0.1:0", replica)
if err != nil {
t.Fatal(err)
}
listener.SetEpochTable(replicaTable)
listener.Serve()
t.Cleanup(func() { listener.Stop() })
v := NewReplicationVolume("vol-promoted", primary)
v.SetDurabilityMode(DurabilitySyncQuorum)
v.SetEpochTable(primaryTable)
t.Cleanup(func() { _ = v.Close() })
if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("r3", listener.Addr(), 2, 1)}); err != nil {
t.Fatalf("UpdateReplicaSet: %v", err)
}
v.mu.Lock()
defer v.mu.Unlock()
return v.peers["r3"].State()
}
// Equal length, different history: the survivor's lsns 3..4 are epoch 1, the
// new primary's are epoch 2. A length check sees them in sync; the epoch
// table does not, and the survivor is taken out of every count to be rebuilt.
func TestPromotionSeed_EqualLengthDivergentEpochIsRebuilt(t *testing.T) {
got := seedWithTables(t, 4,
[]transport.EpochRow{{Epoch: 1, FirstLSN: 1}},
[]transport.EpochRow{{Epoch: 1, FirstLSN: 1}, {Epoch: 2, FirstLSN: 3}})
if got != ReplicaNeedsRebuild {
t.Fatalf("peer state %s; want needs_rebuild for an equal-length survivor of another epoch", got)
}
}
// The controls: the same history is in sync; a survivor without a table
// (data from before the table) is rebuilt; no table on the primary keeps the
// length checks.
func TestPromotionSeed_EpochTableControls(t *testing.T) {
for _, c := range []struct {
name string
replica, own []transport.EpochRow
want ReplicaState
}{
{"same history", []transport.EpochRow{{Epoch: 1, FirstLSN: 1}}, []transport.EpochRow{{Epoch: 1, FirstLSN: 1}, {Epoch: 2, FirstLSN: 5}}, ReplicaHealthy},
{"survivor without a table", nil, []transport.EpochRow{{Epoch: 1, FirstLSN: 1}, {Epoch: 2, FirstLSN: 5}}, ReplicaNeedsRebuild},
} {
t.Run(c.name, func(t *testing.T) {
if got := seedWithTables(t, 4, c.replica, c.own); got != c.want {
t.Fatalf("peer state %s; want %s", got, c.want)
}
})
}
}
@@ -12,7 +12,7 @@ import (
// A survivor that holds an entry above the promoted primary's frontier holds
// a tail written at the old epoch that the new primary never had: it was never
// acknowledged (an acknowledged write is on the promotion target). The seed
// barrier must not accept it as caught up on length: the peer is degraded,
// barrier must not accept it as caught up on length: the peer needs a rebuild,
// its live cursor is not seeded, and it does not satisfy sync-quorum.
func TestReplicationVolume_UpdateReplicaSet_DegradesPeerAboveLocalFrontier(t *testing.T) {
const blockSize = 4096
@@ -61,8 +61,8 @@ func TestReplicationVolume_UpdateReplicaSet_DegradesPeerAboveLocalFrontier(t *te
v.mu.Lock()
state := v.peers["r3"].State()
v.mu.Unlock()
if state != ReplicaDegraded {
t.Fatalf("peer state=%s want degraded for a survivor holding a divergent tail above the frontier", state)
if state != ReplicaNeedsRebuild {
t.Fatalf("peer state=%s want needs_rebuild for a survivor holding a divergent tail above the frontier", state)
}
// A flush must not count it either: its length covers the target, but it
// is not in sync.
+29 -1
View File
@@ -85,6 +85,10 @@ type ReplicationVolume struct {
store storage.LogicalStorage // borrowed, NEVER closed by us
newExec executorFactory // test seam; default dials real TCP
newDualExec dualLaneExecutorFactory // optional dual-lane override; nil = use newExec
// epochs is this volume's epoch table (nil = none: length checks only).
// A new peer is counted only when its barrier's (last data epoch, end)
// is in sync with this table; an entry's identity is (epoch, LSN).
epochs *transport.EpochTable
updateMu sync.Mutex // serializes membership replacement with Close
mu sync.Mutex // protects membership, lineage, and lifecycle snapshots
@@ -223,6 +227,21 @@ func (v *ReplicationVolume) SetDualLaneExecutorFactory(f func(store storage.Logi
// start, or on operator reconfiguration.
// Owns: durabilityMode field under v.mu.
// Borrows: nothing.
// SetEpochTable installs the volume's epoch table (the replica listener's).
// Call before the first UpdateReplicaSet.
func (v *ReplicationVolume) SetEpochTable(t *transport.EpochTable) {
v.mu.Lock()
v.epochs = t
v.mu.Unlock()
}
// markDiverged takes a peer whose entries are not this primary's out of
// every count: degraded, then NeedsRebuild, which nothing heals but a rebuild.
func markDiverged(peer *ReplicaPeer, reason string) {
peer.Invalidate(reason)
peer.SetState(ReplicaNeedsRebuild)
}
func (v *ReplicationVolume) SetDurabilityMode(mode DurabilityMode) {
v.mu.Lock()
v.durabilityMode = mode
@@ -539,6 +558,15 @@ func (v *ReplicationVolume) seedNewPeerLiveCursorsLocked(peers []*ReplicaPeer) {
v.volumeID, peer.Target().ReplicaID, frontier, err)
continue
}
if v.epochs != nil {
if shared, ok := v.epochs.SharedEnd(ack.LastDataEpoch, ack.AchievedLSN); !ok {
markDiverged(peer, fmt.Sprintf("promotion seed barrier: divergent entries (last data epoch %d, end %d; shared up to %d)",
ack.LastDataEpoch, ack.AchievedLSN, shared))
log.Printf("replication: volume %s live cursor seed rejected peer=%s: divergent (epoch %d, end %d) shared to %d",
v.volumeID, peer.Target().ReplicaID, ack.LastDataEpoch, ack.AchievedLSN, shared)
continue
}
}
if ack.AchievedLSN < frontier {
peer.Invalidate(fmt.Sprintf("promotion seed barrier below frontier: achieved=%d required=%d",
ack.AchievedLSN, frontier))
@@ -550,7 +578,7 @@ func (v *ReplicationVolume) seedNewPeerLiveCursorsLocked(peers []*ReplicaPeer) {
// Above this node's frontier the survivor holds entries this
// node never had: a tail of the old epoch that was never
// acknowledged. Length is not agreement; it needs a rebuild.
peer.Invalidate(fmt.Sprintf("promotion seed barrier above frontier: divergent tail achieved=%d frontier=%d",
markDiverged(peer, fmt.Sprintf("promotion seed barrier above frontier: divergent tail achieved=%d frontier=%d",
ack.AchievedLSN, frontier))
log.Printf("replication: volume %s live cursor seed rejected peer=%s: divergent tail achieved=%d above frontier=%d",
v.volumeID, peer.Target().ReplicaID, ack.AchievedLSN, frontier)