diff --git a/seaweed-block/cmd/blockvolume/replication_ingress.go b/seaweed-block/cmd/blockvolume/replication_ingress.go index e2d3febc4c..9cdd43fe1c 100644 --- a/seaweed-block/cmd/blockvolume/replication_ingress.go +++ b/seaweed-block/cmd/blockvolume/replication_ingress.go @@ -41,6 +41,10 @@ func newReplicationIngress(f flags, store storage.LogicalStorage) *replicationIn floorPath: replicaFloorPath(f), dualLane: f.recoveryMode == "dual-lane"} r.rf1Only = rf1Only(f) r.epochs, r.epochsErr = transport.LoadEpochTable(epochTablePath(f), f.volumeID) + if r.epochsErr == nil { + // Rows above the recovered store's next LSN name a lost tail. + r.epochsErr = r.epochs.TrimAbove(store.NextLSN()) + } return r } diff --git a/seaweed-block/core/transport/epoch_table.go b/seaweed-block/core/transport/epoch_table.go index 677d3627af..629e917074 100644 --- a/seaweed-block/core/transport/epoch_table.go +++ b/seaweed-block/core/transport/epoch_table.go @@ -21,9 +21,23 @@ import ( const epochTableSchema = "seaweed-block.epoch-table/v1" -// epochTableMaxBytes bounds the record read; a row is under 60 bytes. +// epochTableMaxBytes bounds the record read. const epochTableMaxBytes = 64 << 10 +// EpochTableMaxRows bounds the table: every write keeps the newest rows +// only, so the record always fits the read bound (a row is at most 62 +// bytes of JSON). An epoch whose row was dropped is unknown to SharedEnd, +// which reads as diverged: a rebuild, never a wrong count. +const EpochTableMaxRows = 512 + +// newestRows keeps the last EpochTableMaxRows rows. +func newestRows(rows []EpochRow) []EpochRow { + if len(rows) > EpochTableMaxRows { + return rows[len(rows)-EpochTableMaxRows:] + } + return rows +} + // EpochRow is one epoch's first LSN. type EpochRow struct { Epoch uint64 `json:"epoch"` @@ -126,7 +140,7 @@ func (t *EpochTable) Note(epoch, firstLSN uint64) error { return fmt.Errorf("epoch table: epoch %d starts at lsn %d, below epoch %d's %d", epoch, firstLSN, last.Epoch, last.FirstLSN) } } - next := append(append([]EpochRow(nil), t.rows...), EpochRow{Epoch: epoch, FirstLSN: firstLSN}) + next := newestRows(append(append([]EpochRow(nil), t.rows...), EpochRow{Epoch: epoch, FirstLSN: firstLSN})) if err := t.persistLocked(next); err != nil { return err } @@ -141,7 +155,7 @@ func (t *EpochTable) Replace(rows []EpochRow) error { } t.mu.Lock() defer t.mu.Unlock() - next := append([]EpochRow(nil), rows...) + next := newestRows(append([]EpochRow(nil), rows...)) if err := t.persistLocked(next); err != nil { return err } @@ -149,6 +163,28 @@ func (t *EpochTable) Replace(rows []EpochRow) error { return nil } +// TrimAbove drops the rows whose first LSN is above next, the store's next +// LSN after its recovery, durably. Such a row names entries the store does +// not hold (a tail lost before it was synced); kept, it would attribute the +// entries written later at those LSNs to the previous epoch. The next Note +// of that epoch appends it again at its real first LSN. +func (t *EpochTable) TrimAbove(next uint64) error { + if t == nil { + return nil + } + t.mu.Lock() + defer t.mu.Unlock() + keep := RowsThrough(t.rows, next) + if len(keep) == len(t.rows) { + return nil + } + if err := t.persistLocked(keep); err != nil { + return err + } + t.rows = keep + return nil +} + func (t *EpochTable) persistLocked(rows []EpochRow) error { if t.path == "" { return nil @@ -224,6 +260,9 @@ func DecodeEpochRows(buf []byte) ([]EpochRow, error) { return nil, errors.New("epoch rows: short") } n := binary.BigEndian.Uint32(buf[0:4]) + if n > EpochTableMaxRows { + return nil, fmt.Errorf("epoch rows: %d rows, at most %d", n, EpochTableMaxRows) + } if uint64(len(buf)) != 4+16*uint64(n) { return nil, fmt.Errorf("epoch rows: %d bytes for %d rows", len(buf), n) } diff --git a/seaweed-block/core/transport/epoch_table_trim_test.go b/seaweed-block/core/transport/epoch_table_trim_test.go new file mode 100644 index 0000000000..16d9fab80d --- /dev/null +++ b/seaweed-block/core/transport/epoch_table_trim_test.go @@ -0,0 +1,76 @@ +package transport + +import ( + "math" + "os" + "path/filepath" + "testing" +) + +// A primary adopted at epoch 2 at next LSN 10, holding an applied but +// unsynced tail 6..9 of epoch 1; it crashes, recovers to 5 (next LSN 6) and +// adopts epoch 2 again. Its new epoch-2 writes start at 6. Without the trim +// the row stays (2, 10) and the table calls 6..9 epoch 1, so an old primary's +// never-acknowledged epoch-1 tail ending at 8 would reconcile as shared. +func TestEpochTable_TrimAboveTheRecoveredEndKeepsTheNewWritesInTheirEpoch(t *testing.T) { + path := filepath.Join(t.TempDir(), "v1.epoch-table") + tb, _ := LoadEpochTable(path, "v1") + _ = tb.Note(1, 1) + _ = tb.Note(2, 10) + + // Restart: load, trim at the recovered store's next LSN, adopt again. + again, err := LoadEpochTable(path, "v1") + if err != nil { + t.Fatal(err) + } + if err := again.TrimAbove(6); err != nil { + t.Fatal(err) + } + if err := again.Note(2, 6); err != nil { + t.Fatal(err) + } + if _, shared := again.SharedEnd(1, 8); shared { + t.Fatalf("an epoch-1 tail ending at 8 reconciles as shared with rows %v; want diverged (6..8 are epoch 2 here)", again.Rows()) + } + if _, shared := again.SharedEnd(1, 5); !shared { + t.Fatalf("the shared epoch-1 prefix to 5 is not shared with rows %v", again.Rows()) + } + reloaded, _ := LoadEpochTable(path, "v1") + if rows := reloaded.Rows(); len(rows) != 2 || rows[1] != (EpochRow{Epoch: 2, FirstLSN: 6}) { + t.Fatalf("durable rows after the trim and the note: %v; want [{1 1} {2 6}]", rows) + } + // A row at exactly the next LSN (adopted, nothing written) is kept. + if err := reloaded.TrimAbove(6); err != nil || len(reloaded.Rows()) != 2 { + t.Fatalf("TrimAbove(next) dropped a row with no entry yet: %v %v", reloaded.Rows(), err) + } +} + +// Every write keeps the newest EpochTableMaxRows rows, so the record always +// reloads: the boundary is written with the widest values and read back. +func TestEpochTable_BoundedSoItAlwaysReloads(t *testing.T) { + path := filepath.Join(t.TempDir(), "v1.epoch-table") + tb, _ := LoadEpochTable(path, "v1") + wide := make([]EpochRow, EpochTableMaxRows+100) + for i := range wide { + wide[i] = EpochRow{Epoch: math.MaxUint64 - uint64(len(wide)-i), FirstLSN: math.MaxUint64 - uint64(len(wide)-i)} + } + if err := tb.Replace(wide); err != nil { + t.Fatal(err) + } + if n := len(tb.Rows()); n != EpochTableMaxRows { + t.Fatalf("%d rows kept; want the newest %d", n, EpochTableMaxRows) + } + if st, _ := os.Stat(path); st.Size() > epochTableMaxBytes { + t.Fatalf("record is %d bytes, over the %d read bound", st.Size(), epochTableMaxBytes) + } + back, err := LoadEpochTable(path, "v1") + if err != nil || len(back.Rows()) != EpochTableMaxRows || back.Rows()[EpochTableMaxRows-1] != wide[len(wide)-1] { + t.Fatalf("reload at the boundary: %d rows %v", len(back.Rows()), err) + } + if err := back.Note(math.MaxUint64, math.MaxUint64); err != nil || len(back.Rows()) != EpochTableMaxRows { + t.Fatalf("a note past the bound: %d rows %v", len(back.Rows()), err) + } + if _, err := DecodeEpochRows(EncodeEpochRows(wide)); err == nil { + t.Fatalf("a rebuild-done row list of %d rows was accepted", len(wide)) + } +} 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 5f90809893..fbd7ee2bb3 100644 --- a/seaweed-block/core/transport/epoch_table_writers_guard_test.go +++ b/seaweed-block/core/transport/epoch_table_writers_guard_test.go @@ -11,12 +11,14 @@ import ( "testing" ) -// The epoch table has exactly three writers: the replica's note of a shipped -// entry's epoch before the apply, the primary's note at role adoption, and -// the rebuild-done replacement. A fourth writer is a new way for the table to -// disagree with the data it describes; it fails here until it is reviewed -// and listed. +// The epoch table's writers: the replica's note of a shipped entry's epoch +// before the apply, the primary's note at role adoption, the rebuild-done +// replacement, and the trim at load of rows above the recovered store's next +// LSN (a lost tail; a node that truncates drops rows past its new end). Any +// other writer is a new way for the table to disagree with the data it +// describes; it fails here until it is reviewed and listed. 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", @@ -69,7 +71,7 @@ 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") { + if !ok || (sel.Sel.Name != "Note" && sel.Sel.Name != "Replace" && sel.Sel.Name != "TrimAbove") { return true } var recv string @@ -88,7 +90,7 @@ func writesIn(f *ast.File, rel string) []string { return out } -func TestEpochTableHasExactlyThreeWriters(t *testing.T) { +func TestEpochTableHasExactlyItsListedWriters(t *testing.T) { got := epochWrites(t, filepath.Join("..", "..")) want := append([]string(nil), epochTableWriters...) sort.Strings(want) @@ -116,8 +118,8 @@ func TestEpochTableHasExactlyThreeWriters(t *testing.T) { }) } sort.Strings(persisters) - if strings.Join(persisters, ",") != "Note,Replace" { - t.Fatalf("methods reaching persistLocked: %v; want Note, Replace", persisters) + if strings.Join(persisters, ",") != "Note,Replace,TrimAbove" { + t.Fatalf("methods reaching persistLocked: %v; want Note, Replace, TrimAbove", persisters) } } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index c8be3a9ed1..57b638849f 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_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 replaces it with the primary's rows cut at the rebuilt end; it has exactly three writers. | 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`); `TestEpochTableHasExactlyThreeWriters`, `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`); `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 |