transport: a catch-up keeps its history's epochs; the writer census goes by type; the peer diagram names the reconciliation

A catch-up ships history under the session's epoch, and the replica noted
that epoch for it, so a byte-identical survivor of the older epoch later
reconciled as diverged. The recovery lane notes nothing; the catch-up's
final barrier carries the primary's rows and the replica takes them, cut at
its synced end, before the ack. The writer census type-checks the packages
and finds every call on an *EpochTable whatever the receiver is called
(alias and field controls). The block design's peer-state diagram shows
that every route to Healthy reconciles by (epoch, LSN) and that diverged
history goes to NeedsRebuild.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-24 22:45:11 -08:00
1 parent 61068fc9bf
commit 0c03f41fda
6 files changed
+212 -41

No files matched your search

+10 -1
View File
@@ -184,7 +184,16 @@ func (e *BlockExecutor) doCatchUp(replicaID string, session *activeSession, from
return lastSent, errSessionInvalidated
default:
}
if err := sendBarrierReq(conn, session.lineage, recoveryConnTimeout); err != nil {
// The final barrier carries this primary's epoch rows: the replica's
// entries up to its end are now this primary's history.
if err := conn.SetDeadline(time.Now().Add(recoveryConnTimeout)); err != nil {
return lastSent, fmt.Errorf("catch-up barrier: set deadline: %w", err)
}
req := EncodeLineage(session.lineage)
if e.epochs != nil {
req = append(req, EncodeEpochRows(e.epochs.Rows())...)
}
if err := WriteMsg(conn, MsgBarrierReq, req); err != nil {
return lastSent, fmt.Errorf("catch-up barrier: %w", err)
}
resp, err := recvBarrierResp(conn, recoveryConnTimeout)
@@ -0,0 +1,68 @@
package transport
import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
)
// A catch-up ships history under the session's epoch; the history's epochs
// are the primary's. Primary rows [(1,1),(2,11)], durable end 10, a replica
// holding the same first five entries: after a catch-up at epoch 2 the
// replica's rows are the primary's cut at 10, [(1,1)], not [(1,1),(2,6)],
// so after the next promotion it still reconciles with an identical survivor
// of epoch 1 ending at 10.
func TestCatchUpKeepsTheHistorysEpochs(t *testing.T) {
primary, replica, listener := setupPrimaryReplica(t)
theirs, _ := LoadEpochTable("", "v1")
_ = theirs.Replace([]EpochRow{{Epoch: 1, FirstLSN: 1}})
listener.SetEpochTable(theirs)
for i := 0; i < 10; i++ {
data := make([]byte, 4096)
data[0] = byte(i + 1)
lsn, err := primary.Write(uint32(i), data)
if err != nil {
t.Fatal(err)
}
if i < 5 {
if err := replica.ApplyEntry(uint32(i), data, lsn); err != nil {
t.Fatal(err)
}
}
}
if _, err := primary.Sync(); err != nil {
t.Fatal(err)
}
if _, err := replica.Sync(); err != nil {
t.Fatal(err)
}
own, _ := LoadEpochTable("", "v1")
_ = own.Replace([]EpochRow{{Epoch: 1, FirstLSN: 1}, {Epoch: 2, FirstLSN: 11}})
exec := NewBlockExecutor(primary, listener.Addr())
exec.SetEpochTable(own)
closeCh := make(chan adapter.SessionCloseResult, 1)
exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r })
if err := exec.StartCatchUp("r1", 5, 2, 1, 5, 10); err != nil {
t.Fatal(err)
}
select {
case r := <-closeCh:
if !r.Success {
t.Fatalf("catch-up failed: %+v", r)
}
case <-time.After(3 * time.Second):
t.Fatal("timeout waiting for the catch-up")
}
assertDataMatch(t, "after catch-up", primary, replica, 10)
if rows := theirs.Rows(); len(rows) != 1 || rows[0] != (EpochRow{Epoch: 1, FirstLSN: 1}) {
t.Fatalf("replica rows after catch-up %v; want the primary's cut at 10: [{1 1}]", rows)
}
// The next promotion: epoch 3 from 11 on this node; the former primary is
// byte-identical at epoch 1, end 10.
_ = theirs.Note(3, 11)
if _, shared := theirs.SharedEnd(1, 10); !shared {
t.Fatalf("an identical survivor (epoch 1, end 10) diverges from rows %v", theirs.Rows())
}
}
@@ -2,8 +2,10 @@ package transport
import (
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"io/fs"
"path/filepath"
"sort"
@@ -20,16 +22,18 @@ import (
var epochTableWriters = []string{
"cmd/blockvolume/replication_ingress.go: func newReplicationIngress .TrimAbove",
"cmd/blockvolume/replication_ingress.go: func notePrimaryEpoch .Note",
"core/transport/replica.go: func handleConn .Note",
"core/transport/replica.go: func handleConn .Replace",
"core/transport/replica.go: func handleConn .Note", // live-lane entry, before the apply
"core/transport/replica.go: func handleConn .Replace", // rebuild done
"core/transport/replica.go: func handleConn .Replace", // catch-up's final barrier
}
// epochWrites lists the non-test calls of Note or Replace on an expression
// naming an epoch table (an identifier or field whose name contains "epoch"),
// as "file: func F .Method".
// epochWrites lists the non-test calls of Note, Replace or TrimAbove whose
// receiver's TYPE is *EpochTable (any variable, field or alias name), as
// "file: func F .Method", type-checking every package that imports this one.
func epochWrites(t *testing.T, root string) []string {
t.Helper()
var out []string
const self = "github.com/seaweedfs/seaweed-block/core/transport"
dirs := map[string][]string{}
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
@@ -40,25 +44,59 @@ func epochWrites(t *testing.T, root string) []string {
}
return nil
}
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
if strings.HasSuffix(path, ".go") && !strings.HasSuffix(path, "_test.go") {
dirs[filepath.Dir(path)] = append(dirs[filepath.Dir(path)], path)
}
f, err := parser.ParseFile(token.NewFileSet(), path, nil, 0)
if err != nil {
return err
}
rel, _ := filepath.Rel(root, path)
out = append(out, writesIn(f, filepath.ToSlash(rel))...)
return nil
})
if err != nil {
t.Fatal(err)
}
fset := token.NewFileSet()
imp := importer.ForCompiler(fset, "source", nil)
var out []string
for dir, paths := range dirs {
var files []*ast.File
uses := false
for _, p := range paths {
f, err := parser.ParseFile(fset, p, nil, 0)
if err != nil {
t.Fatal(err)
}
files = append(files, f)
for _, im := range f.Imports {
if strings.Trim(im.Path.Value, `"`) == self {
uses = true
}
}
}
rel, _ := filepath.Rel(root, dir)
if !uses && filepath.ToSlash(rel) != "core/transport" {
continue
}
info := &types.Info{Selections: map[*ast.SelectorExpr]*types.Selection{}}
conf := types.Config{Importer: imp, Error: func(error) {}}
_, _ = conf.Check(dir, fset, files, info)
for _, f := range files {
name := filepath.ToSlash(mustRel(root, fset.Position(f.Pos()).Filename))
out = append(out, typedWritesIn(f, name, info)...)
}
}
sort.Strings(out)
return out
}
func writesIn(f *ast.File, rel string) []string {
func mustRel(root, p string) string {
r, err := filepath.Rel(root, p)
if err != nil {
return p
}
return r
}
// typedWritesIn: calls of the writer methods on a receiver of type
// *EpochTable (or EpochTable).
func typedWritesIn(f *ast.File, rel string, info *types.Info) []string {
var out []string
for _, decl := range f.Decls {
fn, ok := decl.(*ast.FuncDecl)
@@ -71,17 +109,18 @@ func writesIn(f *ast.File, rel string) []string {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok || (sel.Sel.Name != "Note" && sel.Sel.Name != "Replace" && sel.Sel.Name != "TrimAbove") {
if !ok || !epochWriter[sel.Sel.Name] {
return true
}
var recv string
switch x := sel.X.(type) {
case *ast.Ident:
recv = x.Name
case *ast.SelectorExpr:
recv = x.Sel.Name
s := info.Selections[sel]
if s == nil {
return true
}
if strings.Contains(strings.ToLower(recv), "epoch") {
recv := s.Recv()
if p, ok := recv.(*types.Pointer); ok {
recv = p.Elem()
}
if named, ok := recv.(*types.Named); ok && named.Obj().Name() == "EpochTable" {
out = append(out, rel+": func "+fn.Name.Name+" ."+sel.Sel.Name)
}
return true
@@ -90,6 +129,8 @@ func writesIn(f *ast.File, rel string) []string {
return out
}
var epochWriter = map[string]bool{"Note": true, "Replace": true, "TrimAbove": true}
func TestEpochTableHasExactlyItsListedWriters(t *testing.T) {
got := epochWrites(t, filepath.Join("..", ".."))
want := append([]string(nil), epochTableWriters...)
@@ -123,15 +164,41 @@ func TestEpochTableHasExactlyItsListedWriters(t *testing.T) {
}
}
// The census sees a fourth writer: a call in any function on any epoch-named
// receiver.
// The census sees a fourth writer whatever the receiver is called: an alias
// of the table, a field, a plain variable.
func TestEpochTableWriterCensusFindsAFourth(t *testing.T) {
src := "package p\nfunc sneak(epochs *T) { _ = epochs.Note(9, 9) }\nfunc ok(x *T) { _ = x.Note(1, 1) }\n"
f, err := parser.ParseFile(token.NewFileSet(), "sneak.go", src, 0)
src := `package p
type EpochTable struct{}
func (*EpochTable) Note(a, b uint64) error { return nil }
type holder struct{ h *EpochTable }
func sneak(epochs *EpochTable) {
history := epochs
_ = history.Note(9, 9)
x := holder{h: epochs}
_ = x.h.Note(1, 1)
}
type other struct{}
func (other) Note(a, b uint64) error { return nil }
func notATable(o other) { _ = o.Note(1, 1) }
`
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "sneak.go", src, 0)
if err != nil {
t.Fatal(err)
}
if got := writesIn(f, "sneak.go"); len(got) != 1 || got[0] != "sneak.go: func sneak .Note" {
t.Fatalf("census of a planted writer: %v", got)
info := &types.Info{Selections: map[*ast.SelectorExpr]*types.Selection{}}
if _, err := (&types.Config{}).Check("p", fset, []*ast.File{f}, info); err != nil {
t.Fatal(err)
}
got := typedWritesIn(f, "sneak.go", info)
if len(got) != 2 || got[0] != "sneak.go: func sneak .Note" || got[1] != "sneak.go: func sneak .Note" {
t.Fatalf("census of planted writers (alias, field; not another type): %v", got)
}
}
+31 -6
View File
@@ -427,11 +427,16 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
entry.Lineage.SessionID, entry.Lineage.Epoch, entry.Lineage.EndpointVersion)
return true
}
// The row first, then the entry: an entry whose epoch the
// table cannot name is never applied.
if err := r.epochs.Note(entry.Lineage.Epoch, entry.LSN); err != nil {
log.Printf("replica: epoch table lsn=%d epoch=%d: %v", entry.LSN, entry.Lineage.Epoch, err)
return true
// Live lane: the row first, then the entry, so an entry
// whose epoch the table cannot name is never applied. A
// recovery lane ships history: the session's epoch is not
// its entries' epoch, so nothing is noted here; the
// session's final barrier carries the primary's rows.
if lane != mutationLaneRecovery {
if err := r.epochs.Note(entry.Lineage.Epoch, entry.LSN); err != nil {
log.Printf("replica: epoch table lsn=%d epoch=%d: %v", entry.LSN, entry.Lineage.Epoch, err)
return true
}
}
// If the apply-gate is installed, route through it.
// Caller (this handler) decides lane; gate is lane-pure.
@@ -594,7 +599,27 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
lineage.SessionID, lineage.Epoch, lineage.EndpointVersion)
return true
}
frontier, _ := r.store.Sync()
frontier, syncErr := r.store.Sync()
// A catch-up's final barrier carries the primary's rows:
// the entries up to frontier are now the primary's history,
// so its rows cut there replace this table before the ack.
if len(payload) > 32 {
if syncErr != nil {
log.Printf("replica: catch-up barrier sync: %v", syncErr)
return true // no ack: the table is not replaced over an unknown end
}
rows, err := DecodeEpochRows(payload[32:])
if err != nil {
log.Printf("replica: catch-up barrier epoch rows: %v", err)
return true
}
if r.epochs != nil {
if err := r.epochs.Replace(RowsThrough(rows, frontier)); err != nil {
log.Printf("replica: catch-up barrier epoch table: %v", err)
return true
}
}
}
// Echo the request's full lineage in the barrier ack.
// The primary's DurabilityCoordinator validates this
// tuple against the session it is awaiting before
+6 -4
View File
@@ -294,22 +294,24 @@ This section is the replication engine as a core component. Kubernetes volumes u
```mermaid
stateDiagram-v2
[*] --> Unknown
Unknown --> Healthy: probe and barrier succeed
Unknown --> Healthy: probe, then a barrier whose (last data epoch, end) the primary's epoch table finds in sync
Healthy --> Degraded: barrier or ship failure
Healthy --> NeedsRebuild: seed barrier finds diverged history (another epoch at the same LSNs, or a tail above the frontier), via Degraded
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 --> Healthy: caught up to the target and reconciled in sync by (epoch, LSN)
CatchingUp --> Degraded: catch-up fails
Degraded --> Healthy: recovers
Degraded --> Healthy: recovers and reconciles in sync by (epoch, LSN), never by length
Degraded --> NeedsRebuild: a heal's reconciliation finds diverged history
Degraded --> NeedsRebuild: gap beyond WAL retention or retries exhausted
CatchingUp --> NeedsRebuild: WAL recycled
NeedsRebuild --> [*]: terminal for this peer
```
(Peer states and allowed transitions are in `core/replication/peer.go` `ReplicaState`, `replicaStateTransitionAllowed`. `NeedsRebuild` is terminal in this state machine; the rebuild itself runs as a separate dual-lane session, and the Kubernetes line drives it through an opt-in operator path, see the [Kubernetes block design](kubernetes-block-design.md#4-replication-and-failover).)
(Peer states and allowed transitions are in `core/replication/peer.go` `ReplicaState`, `replicaStateTransitionAllowed`. Every route to `Healthy` from a recovery verdict goes through `ReplicaPeer.HealIfInSync`: a barrier in this session whose (last data epoch, end) the primary's epoch table (`core/transport/epoch_table.go`, `SharedEnd`) finds in sync; diverged history goes to `NeedsRebuild` and is never counted. `NeedsRebuild` is terminal in this state machine; the rebuild itself runs as a separate dual-lane session, and the Kubernetes line drives it through an opt-in operator path, see the [Kubernetes block design](kubernetes-block-design.md#4-replication-and-failover).)
**Invariants.**
+1 -1
View File
@@ -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_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` | Each volume keeps a durable epoch -> first LSN table; a row is durable before any entry of its epoch (replica: before the apply; primary: at role adoption, at the next LSN); a rebuild takes the primary's rows cut at its end; a load drops rows above the recovered 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`, `TestEpochRowsWire` (`core/transport/epoch_rebuild_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` | Each volume keeps a durable epoch -> first LSN table; a row is durable before any entry of its epoch (replica: before the apply; primary: at role adoption, at the next LSN); a rebuild takes the primary's rows cut at its end; a load drops rows above the recovered 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`, `TestEpochRowsWire` (`core/transport/epoch_rebuild_test.go`); `TestCatchUpKeepsTheHistorysEpochs` (`core/transport/epoch_catchup_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 |