From a5f0501f8bf3ca3ab7dcb64e17fd13622660ed9c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 00:08:08 -0800 Subject: [PATCH] recovery: a dual-lane recovery takes the epoch table's mark under a token and its final barrier makes it valid The dual-lane path held the invalid mark under a sentinel no completion presented, so a replica recovered through it reported no history for ever and was rebuilt again. Its session now takes a tokened mark at SessionStart, before any data frame (the per-frame invalidation is gone), the primary's sender carries its epoch rows on the final barrier, and the receiver completes under its token once the data is synced, before the barrier is answered. Replace, the one unconditional writer, is pinned to the primary role's adoption, after which the listener refuses every inbound recovery frame. Co-Authored-By: Claude Opus 5.5 --- .../core/recovery/integration_stub.go | 11 +++ seaweed-block/core/recovery/receiver.go | 29 +++++++ seaweed-block/core/recovery/sender.go | 10 ++- .../core/transport/epoch_dual_lane_test.go | 81 +++++++++++++++++++ .../core/transport/epoch_owner_test.go | 9 ++- .../transport/epoch_primary_refuses_test.go | 38 +++++++++ seaweed-block/core/transport/epoch_table.go | 27 +------ .../epoch_table_writers_guard_test.go | 26 +++++- .../transport/peer_apply_paths_guard_test.go | 4 +- .../core/transport/rebuild_sender.go | 6 ++ seaweed-block/core/transport/replica.go | 24 ++++-- seaweed-block/docs/design/block-design.md | 6 +- seaweed-block/docs/design/invariants.md | 2 +- 13 files changed, 226 insertions(+), 47 deletions(-) create mode 100644 seaweed-block/core/transport/epoch_dual_lane_test.go create mode 100644 seaweed-block/core/transport/epoch_primary_refuses_test.go diff --git a/seaweed-block/core/recovery/integration_stub.go b/seaweed-block/core/recovery/integration_stub.go index af7734d511..e44d8baa75 100644 --- a/seaweed-block/core/recovery/integration_stub.go +++ b/seaweed-block/core/recovery/integration_stub.go @@ -63,6 +63,8 @@ type BridgeDurableAckCallback func(replicaID ReplicaID, sessionID, acknowledgedL // session converges autonomously: sender.Run barriers as soon as // sink.DrainBacklog returns (P2c-slice B-2 lifecycle). type PrimaryBridge struct { + epochRows func() []byte // see SetEpochRows + store storage.LogicalStorage coord *PeerShipCoordinator @@ -125,6 +127,14 @@ func NewPrimaryBridge(store storage.LogicalStorage, coord *PeerShipCoordinator, // SetOnDurableAck installs an optional progress callback. Safe to call // after construction; senders snapshot the bridge callback at ack time. +// SetEpochRows installs the primary's epoch rows (wire form) that every +// session's final barrier carries. +func (b *PrimaryBridge) SetEpochRows(fn func() []byte) { + b.mu.Lock() + b.epochRows = fn + b.mu.Unlock() +} + func (b *PrimaryBridge) SetOnDurableAck(fn BridgeDurableAckCallback) { b.mu.Lock() defer b.mu.Unlock() @@ -222,6 +232,7 @@ func (b *PrimaryBridge) startRebuildSessionLocked(ctx context.Context, conn net. sender = NewSenderWithSink(b.store, b.coord, conn, replicaID, sink) } sender.epoch = epoch + sender.epochRows = b.epochRows sender.SetOnDurableAck(func(rid ReplicaID, sid, acknowledgedLSN, primaryS, primaryH uint64) { b.mu.Lock() cb := b.onAck diff --git a/seaweed-block/core/recovery/receiver.go b/seaweed-block/core/recovery/receiver.go index f9002a330d..a6ba5cb228 100644 --- a/seaweed-block/core/recovery/receiver.go +++ b/seaweed-block/core/recovery/receiver.go @@ -32,6 +32,8 @@ const ( // it in its own goroutine; Run blocks until barrier ack is sent or // the connection errors. type Receiver struct { + epochToken uint64 // this session's hold on the epoch table's invalid mark (0 = none) + store storage.LogicalStorage conn io.ReadWriter @@ -65,6 +67,16 @@ type DualLaneGate interface { EnterDualLane(epoch uint64) (release func(), err error) } +// EpochRecoveryGate is the replica's epoch table seen from a dual-lane +// session (optional on the gate): the session takes the table's invalid +// mark under a fresh token before its first data frame, and makes it valid +// with the primary's rows (wire form) cut at its durable end only under that +// token, after the data is synced and before the barrier is answered. +type EpochRecoveryGate interface { + BeginEpochRecovery() (token uint64, err error) + CompleteEpochRecovery(token uint64, rows []byte, end uint64) error +} + func (r *Receiver) enterFrame() (func(), error) { if r.gate == nil { return func() {}, nil @@ -172,6 +184,15 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) { if gateErr != nil { return 0, gateErr } + // The epoch table is invalid from before the first data frame. + if eg, ok := r.gate.(EpochRecoveryGate); ok { + tok, err := eg.BeginEpochRecovery() + if err != nil { + release() + return 0, newFailure(FailureSubstrate, PhaseRecvApply, fmt.Errorf("epoch table: %w", err)) + } + r.epochToken = tok + } // The BASE install begins here, before any BASE block or WAL // entry, at the session's BASE frontier under a fresh random ID // (DESIGN r17.3.1 section 8.7). The begin is a mutation, so it @@ -335,6 +356,14 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) { if frontier < durableAchieved { durableAchieved = frontier } + // The data is synced: the primary's rows cut at the durable end + // make the table valid, only under this session's token; any + // failure leaves it invalid and the barrier unanswered. + if eg, ok := r.gate.(EpochRecoveryGate); ok && r.epochToken != 0 && len(payload) > 0 { + if err := eg.CompleteEpochRecovery(r.epochToken, payload, durableAchieved); err != nil { + return 0, newFailure(FailureSubstrate, PhaseRecvSync, fmt.Errorf("epoch table: %w", err)) + } + } log.Printf("g7-debug: Receiver.Run TryComplete=true achieved=%d frontier=%d durableAchieved=%d", achieved, frontier, durableAchieved) if writeErr := writeFrame(r.conn, frameBarrierResp, encodeBarrierResp(durableAchieved)); writeErr != nil { log.Printf("g7-debug: Receiver.Run BarrierResp write err err=%v", writeErr) diff --git a/seaweed-block/core/recovery/sender.go b/seaweed-block/core/recovery/sender.go index 431df16172..08df1fc7f7 100644 --- a/seaweed-block/core/recovery/sender.go +++ b/seaweed-block/core/recovery/sender.go @@ -77,6 +77,10 @@ type DurableAckCallback func(replicaID ReplicaID, sessionID, acknowledgedLSN, pr // Sender does NOT own: receiver-side state, retry policy, lineage // minting, session lifecycle decisions, or any live-write buffer. type Sender struct { + // epochRows is the primary's epoch table (wire form), sent on the final + // barrier so the replica's table names the history it now holds. + epochRows func() []byte + primaryStore storage.LogicalStorage coordinator *PeerShipCoordinator conn io.ReadWriter @@ -620,7 +624,11 @@ func (s *Sender) Run(ctx context.Context, sessionID, fromLSN, frontierHint uint6 probeCursor, probeHead) } - if err := s.writeFrame(frameBarrierReq, nil); err != nil { + var barrierPayload []byte + if s.epochRows != nil { + barrierPayload = s.epochRows() + } + if err := s.writeFrame(frameBarrierReq, barrierPayload); err != nil { return 0, newFailure(FailureWire, PhaseBarrierReq, err) } var achieved uint64 diff --git a/seaweed-block/core/transport/epoch_dual_lane_test.go b/seaweed-block/core/transport/epoch_dual_lane_test.go new file mode 100644 index 0000000000..c5eda7053a --- /dev/null +++ b/seaweed-block/core/transport/epoch_dual_lane_test.go @@ -0,0 +1,81 @@ +package transport + +import ( + "context" + "net" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/recovery" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A replica recovered through the dual lane becomes ack-eligible: its session +// takes the table's invalid mark under a token at SessionStart, and the final +// barrier carries the primary's rows, which make the table valid under that +// token once the data is synced. Before the barrier it reconciles as diverged. +func TestDualLaneRecoveryMakesTheEpochTableValid(t *testing.T) { + const numBlocks, blockSize = 64, 4096 + primary := storage.NewBlockStore(numBlocks, blockSize) + replica := storage.NewBlockStore(numBlocks, blockSize) + for lba := uint32(0); lba < 20; lba++ { + data := make([]byte, blockSize) + data[0] = byte(0x80 | lba) + _, _ = primary.Write(lba, data) + } + _, _ = primary.Sync() + + gate, err := NewReplicaListener("127.0.0.1:0", replica) + if err != nil { + t.Fatal(err) + } + theirs, _ := LoadEpochTable(filepath.Join(t.TempDir(), "v1.epoch-table"), "v1") + _ = theirs.Replace([]EpochRow{{Epoch: 1, FirstLSN: 1}}) + gate.SetEpochTable(theirs) + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + bridge := recovery.NewReplicaBridgeWithGate(replica, gate) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { defer close(done); bridge.AcceptDualLaneLoop(ctx, ln) }() + t.Cleanup(func() { cancel(); _ = ln.Close(); <-done }) + + own, _ := LoadEpochTable("", "v1") + _ = own.Replace([]EpochRow{{Epoch: 1, FirstLSN: 1}, {Epoch: 2, FirstLSN: 3}}) + coord := recovery.NewPeerShipCoordinator() + exec := NewBlockExecutorWithDualLane(primary, "127.0.0.1:0", ln.Addr().String(), coord, recovery.ReplicaID("r1")) + exec.SetEpochTable(own) + closeCh := make(chan adapter.SessionCloseResult, 1) + exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r }) + + _, _, h := primary.Boundaries() + if err := exec.StartRebuild("r1", 7, 2, 1, h); err != nil { + t.Fatal(err) + } + var end uint64 + select { + case r := <-closeCh: + if !r.Success { + t.Fatalf("dual-lane rebuild failed: %+v", r) + } + end = r.AchievedLSN + case <-time.After(5 * time.Second): + t.Fatal("timeout waiting for the dual-lane rebuild") + } + if theirs.Invalid() { + t.Fatal("after a completed dual-lane recovery the table is still invalid: the replica would be rebuilt for ever") + } + want := RowsThrough(own.Rows(), end) + if got := theirs.Rows(); len(got) != len(want) || got[len(got)-1] != want[len(want)-1] { + t.Fatalf("replica rows %v after a dual-lane recovery to %d; want the primary's cut there %v", got, end, want) + } + row := theirs.LastDataRowAt(end) + if _, ok := own.SharedEnd(row.Epoch, row.FirstLSN, end); !ok { + t.Fatalf("the dual-lane-recovered replica (epoch %d from %d, end %d) does not reconcile in sync", row.Epoch, row.FirstLSN, end) + } +} diff --git a/seaweed-block/core/transport/epoch_owner_test.go b/seaweed-block/core/transport/epoch_owner_test.go index b575a1dd69..adb309fc5f 100644 --- a/seaweed-block/core/transport/epoch_owner_test.go +++ b/seaweed-block/core/transport/epoch_owner_test.go @@ -20,7 +20,7 @@ func TestEpochTable_OnlyTheMarksOwnerCompletes(t *testing.T) { t.Fatal(err) } b, err := tb.Invalidate() // recovery B takes the mark over - if err != nil || b == a || b == 0 || b == DualLaneOwner { + if err != nil || b == a || b == 0 { t.Fatalf("tokens a=%d b=%d err=%v; want two distinct random tokens", a, b, err) } if err := tb.CompleteRecovery([]EpochRow{{Epoch: 1, FirstLSN: 1}}, a); !errors.Is(err, ErrNotRecoveryOwner) { @@ -45,12 +45,13 @@ func TestEpochTable_OnlyTheMarksOwnerCompletes(t *testing.T) { if err := reloaded.CompleteRecovery(nil, b); !errors.Is(err, ErrNotRecoveryOwner) { t.Fatal("a second completion of a valid table was accepted") } - if err := reloaded.InvalidateDualLane(); err != nil { + c, err := reloaded.Invalidate() + if err != nil { t.Fatal(err) } - for _, tok := range []uint64{0, DualLaneOwner, b} { + for _, tok := range []uint64{0, b} { if err := reloaded.CompleteRecovery(nil, tok); !errors.Is(err, ErrNotRecoveryOwner) { - t.Fatalf("completion with token %d cleared a dual-lane mark", tok) + t.Fatalf("completion with token %d cleared recovery %d's mark", tok, c) } } if err := reloaded.Note(3, 20); err == nil { diff --git a/seaweed-block/core/transport/epoch_primary_refuses_test.go b/seaweed-block/core/transport/epoch_primary_refuses_test.go new file mode 100644 index 0000000000..a14bd911e5 --- /dev/null +++ b/seaweed-block/core/transport/epoch_primary_refuses_test.go @@ -0,0 +1,38 @@ +package transport + +import ( + "net" + "path/filepath" + "testing" + "time" +) + +// After the node takes the primary role, inbound recovery frames are refused: +// a catch-up's lane start does not reach the epoch table (no invalidation), +// and a dual-lane session cannot enter. The table the adoption wrote stays. +func TestPrimaryRefusesInboundRecoveryFramesOverItsTable(t *testing.T) { + _, _, listener := setupPrimaryReplica(t) + tb, _ := LoadEpochTable(filepath.Join(t.TempDir(), "v1.epoch-table"), "v1") + _ = tb.Replace([]EpochRow{{Epoch: 3, FirstLSN: 11}}) + listener.SetEpochTable(tb) + if err := listener.FenceAsPrimary(3); err != nil { + t.Fatal(err) + } + + conn, err := net.Dial("tcp", listener.Addr()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + if err := WriteMsg(conn, MsgRecoveryLaneStart, EncodeLineage(RecoveryLineage{SessionID: 9, Epoch: 3, EndpointVersion: 1, TargetLSN: 20})); err != nil { + t.Fatal(err) + } + _ = conn.SetReadDeadline(time.Now().Add(time.Second)) + _, _, _ = ReadMsg(conn) // the replica closes the connection + if tb.Invalid() || len(tb.Rows()) != 1 { + t.Fatalf("a recovery frame reached a primary's table: invalid %t rows %v", tb.Invalid(), tb.Rows()) + } + if _, err := listener.EnterDualLane(3); err == nil { + t.Fatal("a dual-lane session entered a primary") + } +} diff --git a/seaweed-block/core/transport/epoch_table.go b/seaweed-block/core/transport/epoch_table.go index a4051c7f56..e51d4f1318 100644 --- a/seaweed-block/core/transport/epoch_table.go +++ b/seaweed-block/core/transport/epoch_table.go @@ -59,11 +59,6 @@ type epochTableRecord struct { Owner uint64 `json:"owner,omitempty"` } -// DualLaneOwner holds the invalid mark for dual-lane sessions, whose -// completion carries no rows: no completion presents it, so none clears it. -// A recovery token is never this value (nor 0). -const DualLaneOwner = ^uint64(0) - // ErrNotRecoveryOwner: a recovery's completion found the invalid mark held // by a newer recovery; it must not make the table valid over that one's data. var ErrNotRecoveryOwner = errors.New("epoch table: a newer recovery holds the invalid mark") @@ -184,7 +179,7 @@ func (t *EpochTable) Invalidate() (token uint64, err error) { return 0, nil } var b [8]byte - for token == 0 || token == DualLaneOwner { + for token == 0 { if _, err := rand.Read(b[:]); err != nil { return 0, fmt.Errorf("epoch table: recovery token: %w", err) } @@ -199,23 +194,7 @@ func (t *EpochTable) Invalidate() (token uint64, err error) { return token, nil } -// InvalidateDualLane marks the table invalid for dual-lane sessions (it runs -// for each of their frames: one write, then none while the mark is theirs). -func (t *EpochTable) InvalidateDualLane() error { - if t == nil { - return nil - } - t.mu.Lock() - defer t.mu.Unlock() - if t.invalid && t.owner == DualLaneOwner { - return nil - } - if err := t.persistLocked(nil, true, DualLaneOwner); err != nil { - return err - } - t.rows, t.invalid, t.owner = nil, true, DualLaneOwner - return nil -} + // CompleteRecovery makes rows the table and the table valid, at the end of // the recovery that holds token once its data is synced: only while the @@ -225,7 +204,7 @@ func (t *EpochTable) CompleteRecovery(rows []EpochRow, owner uint64) error { if t == nil { return nil } - if owner == 0 || owner == DualLaneOwner { + if owner == 0 { return fmt.Errorf("%w (no recovery token)", ErrNotRecoveryOwner) } if err := checkEpochRows(rows); err != nil { diff --git a/seaweed-block/core/transport/epoch_table_writers_guard_test.go b/seaweed-block/core/transport/epoch_table_writers_guard_test.go index a90906ce7b..0ccaf46ade 100644 --- a/seaweed-block/core/transport/epoch_table_writers_guard_test.go +++ b/seaweed-block/core/transport/epoch_table_writers_guard_test.go @@ -24,7 +24,8 @@ var epochTableWriters = []string{ "cmd/blockvolume/replication_ingress.go: func newReplicationIngress .TrimAbove", "cmd/blockvolume/replication_ingress.go: func notePrimaryEpoch .Note", "cmd/blockvolume/replication_ingress.go: func notePrimaryEpoch .Replace", // promoted over an invalid table: exactly [(e, next LSN)] - "core/transport/replica.go: func EnterDualLane .InvalidateDualLane", // dual-lane session: before its first byte + "core/transport/replica.go: func BeginEpochRecovery .Invalidate", // dual-lane session start: before its first data frame + "core/transport/replica.go: func CompleteEpochRecovery .CompleteRecovery", // dual-lane final barrier, only under its token "core/transport/replica.go: func handleConn .Invalidate", // rebuild: before the first base byte "core/transport/replica.go: func handleConn .Invalidate", // catch-up: at the recovery lane start "core/transport/replica.go: func handleConn .Note", // live-lane entry, before the apply @@ -145,7 +146,7 @@ func typedWritesIn(f *ast.File, rel string, info *types.Info) []string { return out } -var epochWriter = map[string]bool{"Note": true, "Replace": true, "TrimAbove": true, "Invalidate": true, "InvalidateDualLane": true, "CompleteRecovery": true} +var epochWriter = map[string]bool{"Note": true, "Replace": true, "TrimAbove": true, "Invalidate": true, "CompleteRecovery": true} func TestEpochTableHasExactlyItsListedWriters(t *testing.T) { got := epochWrites(t, filepath.Join("..", "..")) @@ -175,8 +176,8 @@ func TestEpochTableHasExactlyItsListedWriters(t *testing.T) { }) } sort.Strings(persisters) - if strings.Join(persisters, ",") != "CompleteRecovery,Invalidate,InvalidateDualLane,Note,Replace,TrimAbove" { - t.Fatalf("methods reaching persistLocked: %v; want CompleteRecovery, Invalidate, InvalidateDualLane, Note, Replace, TrimAbove", persisters) + if strings.Join(persisters, ",") != "CompleteRecovery,Invalidate,Note,Replace,TrimAbove" { + t.Fatalf("methods reaching persistLocked: %v; want CompleteRecovery, Invalidate, Note, Replace, TrimAbove", persisters) } } @@ -218,3 +219,20 @@ func notATable(o other) { _ = o.Note(1, 1) } t.Fatalf("census of planted writers (alias, field; not another type): %v", got) } } + +// Replace is the one unconditional writer: it ignores the recovery token. Its +// only caller is the primary role's adoption (a promotion over an invalid +// table), and after FenceAsPrimary the listener refuses every inbound +// recovery frame (the r.primary checks in admitMutation and EnterDualLane), +// so no recovery's data can land under the table it writes. +func TestEpochTableReplaceOnlyAtPrimaryAdoption(t *testing.T) { + var replaces []string + for _, w := range epochWrites(t, filepath.Join("..", "..")) { + if strings.HasSuffix(w, " .Replace") { + replaces = append(replaces, w) + } + } + if len(replaces) != 1 || replaces[0] != "cmd/blockvolume/replication_ingress.go: func notePrimaryEpoch .Replace" { + t.Fatalf("unconditional Replace callers: %v; want only the primary adoption (notePrimaryEpoch)", replaces) + } +} diff --git a/seaweed-block/core/transport/peer_apply_paths_guard_test.go b/seaweed-block/core/transport/peer_apply_paths_guard_test.go index ed236dc28d..f5c42cd88d 100644 --- a/seaweed-block/core/transport/peer_apply_paths_guard_test.go +++ b/seaweed-block/core/transport/peer_apply_paths_guard_test.go @@ -23,8 +23,8 @@ var peerApplyPaths = map[string]string{ "core/transport/replica.go: func handleConn .BeginInstall": "invalid first (beginInstall invalidates before BeginInstall)", "core/replication/apply_gate.go: func applyRecovery .ApplyEntry": "invalid first (reached only from handleConn's recovery lane)", "core/replication/apply_gate.go: func applyLive .ApplyEntry": "row first (reached only from handleConn's live lane, after the note)", - "core/recovery/receiver.go: func beginInstall .BeginInstall": "invalid first (dual-lane: EnterDualLane invalidates before any frame)", - "core/recovery/rebuild_session.go: func ApplyBaseBlock .WriteBase": "invalid first (dual-lane: EnterDualLane invalidates before any frame)", + "core/recovery/receiver.go: func beginInstall .BeginInstall": "invalid first (dual-lane: SessionStart takes the tokened mark before any data frame)", + "core/recovery/rebuild_session.go: func ApplyBaseBlock .WriteBase": "invalid first (dual-lane: SessionStart takes the tokened mark before any data frame)", } var peerApplyMethods = map[string]bool{"ApplyEntry": true, "WriteBase": true, "BeginInstall": true, "WriteExtentDirect": true} diff --git a/seaweed-block/core/transport/rebuild_sender.go b/seaweed-block/core/transport/rebuild_sender.go index 9f74733f9b..597e36aea7 100644 --- a/seaweed-block/core/transport/rebuild_sender.go +++ b/seaweed-block/core/transport/rebuild_sender.go @@ -253,6 +253,12 @@ func (e *BlockExecutor) startRebuildDualLane(replicaID string, sessionID, epoch, // sessionFromLSN := basePinLSN log.Printf("g7-debug: startRebuildDualLane calling Bridge.StartRebuildSessionWithSink replica=%s sessionID=%d basePinLSN=%d frontierHint=%d", replicaID, sessionID, sessionFromLSN, frontierHint) + // The session's final barrier carries this primary's epoch rows, so the + // rebuilt replica's table names the history it now holds. + if e.epochs != nil { + epochs := e.epochs + dl.Bridge.SetEpochRows(func() []byte { return EncodeEpochRows(epochs.Rows()) }) + } if err := dl.Bridge.StartRebuildSessionAtEpoch( context.Background(), conn, argRID, sessionID, epoch, sessionFromLSN, frontierHint, sink, ); err != nil { diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 94d33c0491..8830fd7bb5 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -806,17 +806,25 @@ func (r *ReplicaListener) EnterDualLane(epoch uint64) (func(), error) { r.endMutationFrame() return nil, fmt.Errorf("replica: dual-lane epoch %d: %w", epoch, err) } - // A dual-lane session applies history (base and WAL) whose epochs the - // table cannot name: invalid before its first byte. Its completion does - // not carry rows yet, so the table stays invalid: the replica reconciles - // as diverged and is rebuilt, never counted. - if err := r.epochs.InvalidateDualLane(); err != nil { - r.endMutationFrame() - return nil, fmt.Errorf("replica: dual-lane epoch %d: epoch table: %w", epoch, err) - } return r.endMutationFrame, nil } +// BeginEpochRecovery (recovery.EpochRecoveryGate): a dual-lane session +// takes the epoch table's invalid mark under a fresh token at its start, +// before its first data frame. +func (r *ReplicaListener) BeginEpochRecovery() (uint64, error) { return r.epochs.Invalidate() } + +// CompleteEpochRecovery (recovery.EpochRecoveryGate): after the session's +// data is synced, the primary's rows cut at end make the table valid, only +// under the session's token. +func (r *ReplicaListener) CompleteEpochRecovery(token uint64, rows []byte, end uint64) error { + decoded, err := DecodeEpochRows(rows) + if err != nil { + return err + } + return r.epochs.CompleteRecovery(RowsThrough(decoded, end), token) +} + func (r *ReplicaListener) beginMutationFrame() { r.mu.Lock() r.inFlight++ diff --git a/seaweed-block/docs/design/block-design.md b/seaweed-block/docs/design/block-design.md index 6f84f4b295..001244f697 100644 --- a/seaweed-block/docs/design/block-design.md +++ b/seaweed-block/docs/design/block-design.md @@ -319,13 +319,13 @@ stateDiagram-v2 stateDiagram-v2 [*] --> Valid Valid --> Valid: live entry of a new epoch, row noted before the apply; primary role adopted at the next LSN; load drops rows above the next LSN - Valid --> Invalid: catch-up lane start or rebuild's first base byte (Invalidate, new token); dual-lane session + Valid --> Invalid: catch-up lane start, rebuild's first base byte, or dual-lane SessionStart (Invalidate, new token) Invalid --> Invalid: another recovery starts (new token takes the mark); a completion with another token is refused - Invalid --> Valid: the token's recovery synced its data, then CompleteRecovery installs the primary's rows cut at its end + Invalid --> Valid: the token's recovery synced its data, then its final barrier or rebuild-done (dual-lane too) installs the primary's rows cut at its end Invalid --> Valid: primary role adopted over it: exactly [(epoch, next LSN)] ``` -While invalid the volume reports no last data epoch: it reconciles as diverged, is never counted and is rebuilt, and no live entry is noted. +While invalid the volume reports no last data epoch: it reconciles as diverged, is never counted and is rebuilt, and no live entry is noted. The unconditional reset happens only at primary adoption, after the fence: a primary refuses every inbound recovery frame (`admitMutation`, `EnterDualLane`), so no recovery's data lands under it. **Invariants.** diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7ae6f8cc4e..1337fe634b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -783,7 +783,7 @@ Notes: | `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. 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-REPL-DIVERGENT-TAIL-001` | A peer is counted only after a reconciliation in this session finds its (last data epoch, end) in sync with the primary's epoch table; an equal length of another epoch, a tail above the frontier or data without a table is diverged: NeedsRebuild, never healed by length. | M3 Healthy → Degraded → NeedsRebuild (seed, heal) | `core/replication/volume.go` `seedNewPeerLiveCursorsLocked`, `reconcilePeer`, `markDiverged`; `core/replication/peer.go` `HealIfInSync`; `core/replication/peer_work_queue.go` (barrier); `core/host/volume/peer_command_executor.go` `PublishHealthy`; `core/engine/apply.go` `decide` | `TestPromotionSeed_EqualLengthDivergentEpochIsRebuilt`, `TestPromotionSeed_SameEpochStartingElsewhereIsRebuilt`, `TestPromotionSeed_EpochTableControls` (`core/replication/divergent_epoch_seed_test.go`); `TestReplicationVolume_UpdateReplicaSet_DegradesPeerAboveLocalFrontier` (`core/replication/divergent_tail_seed_test.go`); `TestPublishHealthyNeverHealsAnEqualLengthDivergentPeer` (`core/host/volume/peer_heal_reconcile_test.go`); `TestDivergentTailBeforeTheEpochIsAcceptedIsRebuilt` (`core/engine/divergent_tail_test.go`); `TestPeerAdapterRegistry_DivergentTailAboveTheFrontierAtAddIsRebuilt` (`core/host/volume/peer_adapter_divergent_tail_test.go`) | `Promo` rule 7 (G4), row `mut_g4_no_truncate` | ACTIVE | -| `INV-REPL-EPOCH-TABLE-001` | A durable epoch -> first LSN table per volume: a live entry's row is durable before it; a recovery makes it invalid (random token) before its first byte and only that token's final replace makes it valid (invalid = diverged); a load drops rows above the next LSN; at most 512 rows. | M3 replica apply, Primary adoption, rebuild done | `core/transport/epoch_table.go` `EpochTable.Note`, `Replace`, `SharedEnd`, `LastDataEpochAt`; `core/transport/replica.go` (ship entry, rebuild done, barrier reply); `core/transport/rebuild_sender.go`; `cmd/blockvolume/replication_ingress.go` `notePrimaryEpoch` | `TestEpochTable_NoteIsDurableAndOrdered`, `TestEpochTable_InterruptEveryPersistStep`, `TestEpochTable_LastDataEpochAtTheDurableEnd`, `TestEpochTable_SharedEnd` (`core/transport/epoch_table_test.go`); `TestRebuildDoneReplacesTheEpochTableWithThePrimarysRows`, `TestRebuildDoneWithoutTheTableReplaceIsNotAcked`, `TestEpochRowsWire` (`core/transport/epoch_rebuild_test.go`); `TestCatchUpKeepsTheHistorysEpochs` (`core/transport/epoch_catchup_test.go`); `TestCatchUpWithAFailedTableReplaceLeavesItInvalid`, `TestRecoveryLaneCrashBeforeTheFinalBarrierLeavesTheTableInvalid` (`core/transport/epoch_invalid_test.go`); `TestEveryPeerApplyPathHasAnEpochTableRule` (`core/transport/peer_apply_paths_guard_test.go`); `TestEpochTable_OnlyTheMarksOwnerCompletes`, `TestOverlappingRecoveriesAStaleCompletionLeavesTheTableInvalid` (`core/transport/epoch_owner_test.go`); `TestIngressPrimaryAdoptionTableStep` (`cmd/blockvolume/replication_ingress_epoch_test.go`); `TestEpochTable_TrimAboveTheRecoveredEndKeepsTheNewWritesInTheirEpoch`, `TestEpochTable_BoundedSoItAlwaysReloads` (`core/transport/epoch_table_trim_test.go`); `TestEpochTableHasExactlyItsListedWriters`, `TestEpochTableWriterCensusFindsAFourth` (`core/transport/epoch_table_writers_guard_test.go`) | `Promo` Truncate (common prefix by (epoch, LSN)) | ACTIVE | +| `INV-REPL-EPOCH-TABLE-001` | A durable epoch -> first LSN table per volume: a live entry's row is durable before it; a recovery makes it invalid (random token) before its first byte and only that token's final replace makes it valid (invalid = diverged); a load drops rows above the next LSN; at most 512 rows. | M3 replica apply, Primary adoption, rebuild done | `core/transport/epoch_table.go` `EpochTable.Note`, `Replace`, `SharedEnd`, `LastDataEpochAt`; `core/transport/replica.go` (ship entry, rebuild done, barrier reply); `core/transport/rebuild_sender.go`; `cmd/blockvolume/replication_ingress.go` `notePrimaryEpoch` | `TestEpochTable_NoteIsDurableAndOrdered`, `TestEpochTable_InterruptEveryPersistStep`, `TestEpochTable_LastDataEpochAtTheDurableEnd`, `TestEpochTable_SharedEnd` (`core/transport/epoch_table_test.go`); `TestRebuildDoneReplacesTheEpochTableWithThePrimarysRows`, `TestRebuildDoneWithoutTheTableReplaceIsNotAcked`, `TestEpochRowsWire` (`core/transport/epoch_rebuild_test.go`); `TestCatchUpKeepsTheHistorysEpochs` (`core/transport/epoch_catchup_test.go`); `TestCatchUpWithAFailedTableReplaceLeavesItInvalid`, `TestRecoveryLaneCrashBeforeTheFinalBarrierLeavesTheTableInvalid` (`core/transport/epoch_invalid_test.go`); `TestEveryPeerApplyPathHasAnEpochTableRule` (`core/transport/peer_apply_paths_guard_test.go`); `TestEpochTable_OnlyTheMarksOwnerCompletes`, `TestOverlappingRecoveriesAStaleCompletionLeavesTheTableInvalid` (`core/transport/epoch_owner_test.go`); `TestDualLaneRecoveryMakesTheEpochTableValid` (`core/transport/epoch_dual_lane_test.go`); `TestEpochTableReplaceOnlyAtPrimaryAdoption` (`core/transport/epoch_table_writers_guard_test.go`); `TestPrimaryRefusesInboundRecoveryFramesOverItsTable` (`core/transport/epoch_primary_refuses_test.go`); `TestIngressPrimaryAdoptionTableStep` (`cmd/blockvolume/replication_ingress_epoch_test.go`); `TestEpochTable_TrimAboveTheRecoveredEndKeepsTheNewWritesInTheirEpoch`, `TestEpochTable_BoundedSoItAlwaysReloads` (`core/transport/epoch_table_trim_test.go`); `TestEpochTableHasExactlyItsListedWriters`, `TestEpochTableWriterCensusFindsAFourth` (`core/transport/epoch_table_writers_guard_test.go`) | `Promo` Truncate (common prefix by (epoch, LSN)) | 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 |