diff --git a/seaweed-block/cmd/blockvolume/replication_ingress.go b/seaweed-block/cmd/blockvolume/replication_ingress.go index 9cdd43fe1c..5c7a4a4604 100644 --- a/seaweed-block/cmd/blockvolume/replication_ingress.go +++ b/seaweed-block/cmd/blockvolume/replication_ingress.go @@ -60,6 +60,15 @@ func (r *replicationIngress) notePrimaryEpoch(epoch uint64) error { if r.epochsErr != nil { return fmt.Errorf("volume %s epoch table: %w", r.volumeID, r.epochsErr) } + if r.epochs.Invalid() { + // Promoted (forced) over a store whose history is unknown: the table + // becomes exactly this epoch from the next LSN, so every survivor + // that rejoins holds an epoch this table never had and is rebuilt. + if err := r.epochs.Replace([]transport.EpochRow{{Epoch: epoch, FirstLSN: r.store.NextLSN()}}); err != nil { + return fmt.Errorf("volume %s epoch table: %w", r.volumeID, err) + } + return nil + } if err := r.epochs.Note(epoch, r.store.NextLSN()); err != nil { return fmt.Errorf("volume %s epoch table: %w", r.volumeID, err) } diff --git a/seaweed-block/cmd/blockvolume/replication_ingress_epoch_test.go b/seaweed-block/cmd/blockvolume/replication_ingress_epoch_test.go new file mode 100644 index 0000000000..fdd84c4797 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/replication_ingress_epoch_test.go @@ -0,0 +1,50 @@ +package main + +import ( + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +// Role adoption's table step, on the real ingress: a durable table is +// reloaded (trimmed above the recovered next LSN), a primary role notes its +// epoch at the next LSN, and a promotion over a table a recovery left +// invalid makes it exactly [(epoch, next LSN)]. +func TestIngressPrimaryAdoptionTableStep(t *testing.T) { + root := t.TempDir() + f := flags{dataAddr: "127.0.0.1:0", volumeID: "vol1", durableRoot: root} + store := storage.NewBlockStore(16, 4096) + for i := 0; i < 4; i++ { + if _, err := store.Write(uint32(i), make([]byte, 4096)); err != nil { + t.Fatal(err) + } + } + tb, err := transport.LoadEpochTable(epochTablePath(f), f.volumeID) + if err != nil { + t.Fatal(err) + } + _ = tb.Replace([]transport.EpochRow{{Epoch: 1, FirstLSN: 1}, {Epoch: 2, FirstLSN: 9}}) // 9: above the store's next LSN (5) + + r := newReplicationIngress(f, store) + t.Cleanup(r.Stop) + if rows := r.EpochTable().Rows(); len(rows) != 1 { + t.Fatalf("rows after the load trim %v; want [(1,1)] (the row at 9 names a lost tail)", rows) + } + if err := r.FenceAsPrimaryWithPeers(2, false); err != nil { + t.Fatal(err) + } + if rows := r.EpochTable().Rows(); len(rows) != 2 || rows[1] != (transport.EpochRow{Epoch: 2, FirstLSN: 5}) { + t.Fatalf("rows after adoption at epoch 2 %v; want [(1,1) (2,5)]", rows) + } + + if err := r.EpochTable().Invalidate(); err != nil { // a recovery left it without a history + t.Fatal(err) + } + if err := r.FenceAsPrimaryWithPeers(3, false); err != nil { + t.Fatalf("a forced promotion over an invalid table was refused: %v", err) + } + if rows := r.EpochTable().Rows(); len(rows) != 1 || rows[0] != (transport.EpochRow{Epoch: 3, FirstLSN: 5}) || r.EpochTable().Invalid() { + t.Fatalf("rows after a promotion over an invalid table %v (invalid %t); want exactly [(3,5)]", rows, r.EpochTable().Invalid()) + } +} diff --git a/seaweed-block/core/transport/epoch_invalid_test.go b/seaweed-block/core/transport/epoch_invalid_test.go new file mode 100644 index 0000000000..2f2858d18c --- /dev/null +++ b/seaweed-block/core/transport/epoch_invalid_test.go @@ -0,0 +1,155 @@ +package transport + +import ( + "errors" + "net" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" +) + +// promoteOver is the role adoption's table step: over an invalid table the +// table becomes exactly [(epoch, next)]; otherwise the epoch is noted. +func promoteOver(t *testing.T, tb *EpochTable, epoch, next uint64) { + t.Helper() + var err error + if tb.Invalid() { + err = tb.Replace([]EpochRow{{Epoch: epoch, FirstLSN: next}}) + } else { + err = tb.Note(epoch, next) + } + if err != nil { + t.Fatal(err) + } +} + +// codex03's schedule: a catch-up's data sync succeeds and its table replace +// fails. The data is durable; the table must not keep naming it epoch 1. After +// a reload and a forced promotion at epoch 3, an epoch-1 survivor whose 6..10 +// may differ must reconcile as diverged. +func TestCatchUpWithAFailedTableReplaceLeavesItInvalid(t *testing.T) { + primary, replica, listener := setupPrimaryReplica(t) + path := filepath.Join(t.TempDir(), "v1.epoch-table") + theirs, _ := LoadEpochTable(path, "v1") + _ = theirs.Replace([]EpochRow{{Epoch: 1, FirstLSN: 1}}) + listener.SetEpochTable(theirs) + for i := 0; i < 10; i++ { + lsn, err := primary.Write(uint32(i), makeData(byte(i+1))) + if err != nil { + t.Fatal(err) + } + if i < 5 { + if err := replica.ApplyEntry(uint32(i), makeData(byte(i+1)), lsn); err != nil { + t.Fatal(err) + } + } + } + _, _ = primary.Sync() + _, _ = replica.Sync() + own, _ := LoadEpochTable("", "v1") + _ = own.Replace([]EpochRow{{Epoch: 1, FirstLSN: 1}, {Epoch: 2, FirstLSN: 6}}) + + // The invalidation (first rename) succeeds; the final replace's fails. + saved := floorFS + t.Cleanup(func() { floorFS = saved }) + ops, renames := osFloorOps, 0 + ops.rename = func(from, to string) error { + renames++ + if renames >= 2 { + return errors.New("injected: the final table replace fails") + } + return osFloorOps.rename(from, to) + } + floorFS = ops + + 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("a catch-up whose table replace failed was acknowledged: %+v", r) + } + case <-time.After(3 * time.Second): + t.Fatal("timeout waiting for the catch-up") + } + floorFS = saved + + end, _ := replica.Sync() + if end != 10 { + t.Fatalf("replica end %d; want the catch-up's data durable at 10", end) + } + reloaded, err := LoadEpochTable(path, "v1") + if err != nil { + t.Fatal(err) + } + if !reloaded.Invalid() || reloaded.LastDataRowAt(end) != (EpochRow{}) { + t.Fatalf("reloaded table invalid=%t row=%v; want invalid with no last data row", reloaded.Invalid(), reloaded.LastDataRowAt(end)) + } + if err := reloaded.TrimAbove(end + 1); err != nil { + t.Fatal(err) + } + promoteOver(t, reloaded, 3, end+1) + if rows := reloaded.Rows(); len(rows) != 1 || rows[0] != (EpochRow{Epoch: 3, FirstLSN: 11}) || reloaded.Invalid() { + t.Fatalf("forced promotion over an invalid table: rows %v invalid %t; want exactly [(3, 11)]", rows, reloaded.Invalid()) + } + if _, shared := reloaded.SharedEnd(1, 1, 10); shared { + t.Fatal("an epoch-1 survivor ending at 10 reconciles as shared with the promoted node; want diverged") + } +} + +// A crash after a recovery lane started (its entries possibly synced) and +// before its final barrier: the table reloads invalid; the replica reports +// no data epoch, so it is diverged, and a live note is refused. +func TestRecoveryLaneCrashBeforeTheFinalBarrierLeavesTheTableInvalid(t *testing.T) { + _, replica, listener := setupPrimaryReplica(t) + path := filepath.Join(t.TempDir(), "v1.epoch-table") + theirs, _ := LoadEpochTable(path, "v1") + _ = theirs.Replace([]EpochRow{{Epoch: 1, FirstLSN: 1}}) + listener.SetEpochTable(theirs) + for i := 0; i < 5; i++ { + _ = replica.ApplyEntry(uint32(i), makeData(byte(i+1)), uint64(i+1)) + } + + lineage := RecoveryLineage{SessionID: 9, Epoch: 2, EndpointVersion: 1, TargetLSN: 10} + conn, err := net.Dial("tcp", listener.Addr()) + if err != nil { + t.Fatal(err) + } + if err := WriteMsg(conn, MsgRecoveryLaneStart, EncodeLineage(lineage)); err != nil { + t.Fatal(err) + } + for lsn := uint64(6); lsn <= 8; lsn++ { + if err := WriteMsg(conn, MsgShipEntry, EncodeShipEntry(ShipEntry{Lineage: lineage, LBA: uint32(lsn), LSN: lsn, Data: makeData(0xEE)})); err != nil { + t.Fatal(err) + } + } + deadline := time.Now().Add(2 * time.Second) + for !theirs.Invalid() && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + _ = conn.Close() // the primary dies before the final barrier + + reloaded, err := LoadEpochTable(path, "v1") + if err != nil { + t.Fatal(err) + } + end, _ := replica.Sync() + if !reloaded.Invalid() || reloaded.LastDataRowAt(end) != (EpochRow{}) { + t.Fatalf("after a crash mid-recovery: invalid=%t row=%v; want invalid, no last data row", reloaded.Invalid(), reloaded.LastDataRowAt(end)) + } + if err := reloaded.Note(2, end+1); err == nil { + t.Fatal("a live note on an invalid table was accepted") + } + own, _ := LoadEpochTable("", "v1") + _ = own.Replace([]EpochRow{{Epoch: 1, FirstLSN: 1}, {Epoch: 2, FirstLSN: 6}}) + if _, shared := own.SharedEnd(0, 0, end); shared { + t.Fatalf("an invalid replica with data to %d reconciles as shared; want diverged", end) + } +} diff --git a/seaweed-block/core/transport/epoch_table.go b/seaweed-block/core/transport/epoch_table.go index d6f959b854..3f217b6e7e 100644 --- a/seaweed-block/core/transport/epoch_table.go +++ b/seaweed-block/core/transport/epoch_table.go @@ -48,6 +48,11 @@ type epochTableRecord struct { Schema string `json:"schema"` VolumeID string `json:"volume_id"` Rows []EpochRow `json:"rows"` + // Invalid: a recovery (catch-up or rebuild) began applying history + // whose epochs arrive only at its end. Until that end replaces the + // table, the store's data has no known history: no last data row, no + // note; it reconciles as diverged at every crash point. + Invalid bool `json:"invalid,omitempty"` } // EpochTable is the durable table of one volume. The zero path keeps it in @@ -55,8 +60,9 @@ type epochTableRecord struct { type EpochTable struct { path, volumeID string - mu sync.Mutex - rows []EpochRow + mu sync.Mutex + rows []EpochRow + invalid bool } // LoadEpochTable reads the table at path; a missing record is an empty table. @@ -98,7 +104,7 @@ func LoadEpochTable(path, volumeID string) (*EpochTable, error) { if err := checkEpochRows(rec.Rows); err != nil { return nil, err } - t.rows = rec.Rows + t.rows, t.invalid = rec.Rows, rec.Invalid return t, nil } @@ -129,6 +135,9 @@ func (t *EpochTable) Note(epoch, firstLSN uint64) error { } t.mu.Lock() defer t.mu.Unlock() + if t.invalid { + return errors.New("epoch table: invalid until the recovery in progress replaces it") + } if n := len(t.rows); n > 0 { last := t.rows[n-1] switch { @@ -141,13 +150,33 @@ func (t *EpochTable) Note(epoch, firstLSN uint64) error { } } next := newestRows(append(append([]EpochRow(nil), t.rows...), EpochRow{Epoch: epoch, FirstLSN: firstLSN})) - if err := t.persistLocked(next); err != nil { + if err := t.persistLocked(next, false); err != nil { return err } t.rows = next return nil } +// Invalidate durably marks the table invalid, before a recovery applies +// any history (a catch-up's lane start, a rebuild's first base block): the +// history's epochs arrive only at the recovery's end, and until Replace +// installs them the data must read as diverged, whatever crashes between. +func (t *EpochTable) Invalidate() error { + if t == nil { + return nil + } + t.mu.Lock() + defer t.mu.Unlock() + if t.invalid { + return nil + } + if err := t.persistLocked(nil, true); err != nil { + return err + } + t.rows, t.invalid = nil, true + return nil +} + // Replace makes rows the table (after a rebuild from a primary's image). func (t *EpochTable) Replace(rows []EpochRow) error { if err := checkEpochRows(rows); err != nil { @@ -156,10 +185,10 @@ func (t *EpochTable) Replace(rows []EpochRow) error { t.mu.Lock() defer t.mu.Unlock() next := newestRows(append([]EpochRow(nil), rows...)) - if err := t.persistLocked(next); err != nil { + if err := t.persistLocked(next, false); err != nil { return err } - t.rows = next + t.rows, t.invalid = next, false return nil } @@ -175,21 +204,21 @@ func (t *EpochTable) TrimAbove(next uint64) error { t.mu.Lock() defer t.mu.Unlock() keep := RowsThrough(t.rows, next) - if len(keep) == len(t.rows) { + if t.invalid || len(keep) == len(t.rows) { return nil } - if err := t.persistLocked(keep); err != nil { + if err := t.persistLocked(keep, false); err != nil { return err } t.rows = keep return nil } -func (t *EpochTable) persistLocked(rows []EpochRow) error { +func (t *EpochTable) persistLocked(rows []EpochRow, invalid bool) error { if t.path == "" { return nil } - body, _ := json.Marshal(epochTableRecord{Schema: epochTableSchema, VolumeID: t.volumeID, Rows: rows}) + body, _ := json.Marshal(epochTableRecord{Schema: epochTableSchema, VolumeID: t.volumeID, Rows: rows, Invalid: invalid}) tmp := t.path + ".tmp" if err := floorFS.writeSynced(tmp, append(body, '\n')); err != nil { _ = floorFS.remove(tmp) @@ -213,6 +242,16 @@ func (r *ReplicaListener) SetEpochTable(t *EpochTable) { r.epochs = t } // rebuild-done frame then carries its rows. func (e *BlockExecutor) SetEpochTable(t *EpochTable) { e.epochs = t } +// Invalid reports whether a recovery left the table without a known history. +func (t *EpochTable) Invalid() bool { + if t == nil { + return false + } + t.mu.Lock() + defer t.mu.Unlock() + return t.invalid +} + // LastEpoch is the epoch of the last row; 0 = no rows. func (t *EpochTable) LastEpoch() uint64 { t.mu.Lock() @@ -238,6 +277,9 @@ func (t *EpochTable) LastDataRowAt(end uint64) EpochRow { } t.mu.Lock() defer t.mu.Unlock() + if t.invalid { + return EpochRow{} // history unknown: data without a table reconciles as diverged + } for i := len(t.rows) - 1; i >= 0; i-- { if t.rows[i].FirstLSN <= end { return t.rows[i] 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 4d7fe1fb73..8911af65cf 100644 --- a/seaweed-block/core/transport/epoch_table_writers_guard_test.go +++ b/seaweed-block/core/transport/epoch_table_writers_guard_test.go @@ -2,6 +2,7 @@ package transport import ( "go/ast" + "go/build" "go/importer" "go/parser" "go/token" @@ -22,9 +23,13 @@ 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", // 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 + "cmd/blockvolume/replication_ingress.go: func notePrimaryEpoch .Replace", // promoted over an invalid table: exactly [(e, next LSN)] + "core/transport/replica.go: func EnterDualLane .Invalidate", // dual-lane session: before its first byte + "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 + "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, Replace or TrimAbove whose @@ -45,6 +50,11 @@ func epochWrites(t *testing.T, root string) []string { return nil } if strings.HasSuffix(path, ".go") && !strings.HasSuffix(path, "_test.go") { + // Only the files of this build (GOOS, GOARCH, tags), as the + // compiler sees them. + if ok, err := build.Default.MatchFile(filepath.Dir(path), filepath.Base(path)); err != nil || !ok { + return err + } dirs[filepath.Dir(path)] = append(dirs[filepath.Dir(path)], path) } return nil @@ -75,8 +85,14 @@ func epochWrites(t *testing.T, root string) []string { continue } info := &types.Info{Selections: map[*ast.SelectorExpr]*types.Selection{}} - conf := types.Config{Importer: imp, Error: func(error) {}} + var typeErrs []error + conf := types.Config{Importer: imp, Error: func(err error) { typeErrs = append(typeErrs, err) }} _, _ = conf.Check(dir, fset, files, info) + // The census is authoritative only over fully type-checked code: an + // error could hide a selection, so it fails rather than undercounts. + if len(typeErrs) > 0 { + t.Fatalf("census cannot type-check %s: %v", rel, typeErrs[0]) + } for _, f := range files { name := filepath.ToSlash(mustRel(root, fset.Position(f.Pos()).Filename)) out = append(out, typedWritesIn(f, name, info)...) @@ -129,7 +145,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} +var epochWriter = map[string]bool{"Note": true, "Replace": true, "TrimAbove": true, "Invalidate": true} func TestEpochTableHasExactlyItsListedWriters(t *testing.T) { got := epochWrites(t, filepath.Join("..", "..")) @@ -159,8 +175,8 @@ func TestEpochTableHasExactlyItsListedWriters(t *testing.T) { }) } sort.Strings(persisters) - if strings.Join(persisters, ",") != "Note,Replace,TrimAbove" { - t.Fatalf("methods reaching persistLocked: %v; want Note, Replace, TrimAbove", persisters) + if strings.Join(persisters, ",") != "Invalidate,Note,Replace,TrimAbove" { + t.Fatalf("methods reaching persistLocked: %v; want Invalidate, Note, Replace, TrimAbove", persisters) } } diff --git a/seaweed-block/core/transport/peer_apply_paths_guard_test.go b/seaweed-block/core/transport/peer_apply_paths_guard_test.go new file mode 100644 index 0000000000..ed236dc28d --- /dev/null +++ b/seaweed-block/core/transport/peer_apply_paths_guard_test.go @@ -0,0 +1,96 @@ +package transport + +import ( + "go/ast" + "go/build" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "sort" + "strings" + "testing" +) + +// Every path that applies a primary's data to this store, with the epoch +// table rule that covers it. "row first": a live entry of the current epoch, +// noted before the apply. "invalid first": history from a recovery; the +// table is made invalid before its first byte and only the recovery's final +// replace makes it valid. A new apply path fails here until it is classified. +var peerApplyPaths = map[string]string{ + "core/transport/replica.go: func handleConn .ApplyEntry": "row first (live lane) / invalid first (recovery lane, MsgRecoveryLaneStart)", + "core/transport/replica.go: func handleConn .WriteBase": "invalid first (beginInstall invalidates before the first base byte)", + "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)", +} + +var peerApplyMethods = map[string]bool{"ApplyEntry": true, "WriteBase": true, "BeginInstall": true, "WriteExtentDirect": true} + +func peerApplyCalls(t *testing.T, root string, dirs []string) []string { + t.Helper() + var out []string + for _, d := range dirs { + err := filepath.WalkDir(filepath.Join(root, d), func(path string, e fs.DirEntry, err error) error { + if err != nil { + return err + } + if e.IsDir() { + if path != filepath.Join(root, d) { + return filepath.SkipDir // the listed package only, not its subpackages + } + return nil + } + if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + if ok, err := build.Default.MatchFile(filepath.Dir(path), filepath.Base(path)); err != nil || !ok { + return err + } + f, err := parser.ParseFile(token.NewFileSet(), path, nil, 0) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + rel = filepath.ToSlash(rel) + for _, decl := range f.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok { + continue + } + ast.Inspect(fn, func(n ast.Node) bool { + if c, ok := n.(*ast.CallExpr); ok { + if s, ok := c.Fun.(*ast.SelectorExpr); ok && peerApplyMethods[s.Sel.Name] { + out = append(out, rel+": func "+fn.Name.Name+" ."+s.Sel.Name) + } + } + return true + }) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + sort.Strings(out) + return out +} + +func TestEveryPeerApplyPathHasAnEpochTableRule(t *testing.T) { + got := peerApplyCalls(t, filepath.Join("..", ".."), []string{"core/transport", "core/replication", "core/recovery"}) + seen := map[string]bool{} + for _, c := range got { + seen[c] = true + if rule, ok := peerApplyPaths[c]; !ok || rule == "" { + t.Errorf("apply path %s has no epoch-table rule: classify it as row first or invalid first", c) + } + } + for c, rule := range peerApplyPaths { + if rule != "" && !seen[c] { + t.Errorf("classified apply path %s no longer exists: remove it", c) + } + } +} diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index b843376192..f4283340c8 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -361,6 +361,11 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { } return nil } + // The base's history arrives only with the done frame: the table is + // invalid from before the first base byte until that replace. + if err := r.epochs.Invalidate(); err != nil { + return err + } var id [16]byte for id == ([16]byte{}) { if _, err := rand.Read(id[:]); err != nil { @@ -413,6 +418,13 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true } + // The lane ships history whose epochs arrive only at its + // final barrier: invalid from before its first entry until + // that replace. + if err := r.epochs.Invalidate(); err != nil { + log.Printf("replica: recovery lane epoch table: %v", err) + return true + } lane = mutationLaneRecovery r.markPrefixEligibility(lineage, false) @@ -787,6 +799,14 @@ 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.Invalidate(); err != nil { + r.endMutationFrame() + return nil, fmt.Errorf("replica: dual-lane epoch %d: epoch table: %w", epoch, err) + } return r.endMutationFrame, nil } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 755264283d..bd725c8941 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` | 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`, `TestRebuildDoneWithoutTheTableReplaceIsNotAcked`, `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-REPL-EPOCH-TABLE-001` | A durable epoch -> first LSN table per volume: a live entry's row is durable before it; a recovery makes the table invalid before its first byte and valid only by its final replace (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`); `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 |