From f8da58da3e2f69e44e213cd2cc794a031899a17e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 21:25:32 -0800 Subject: [PATCH] docs: restore block-design 1.4-1.7, cut with the smartwal section Replacing section 1.3 also deleted the sections after it (1.4 Durability and Sync, 1.5 Authority, 1.6 Replication and failover) and the 1.7 heading; they describe walstore and the shipped protocols, not the removed engines. Restored verbatim from main; only 1.3 changes. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/block-design.md | 124 ++++++++++++++++++++++ 1 file changed, 124 insertions(+) diff --git a/seaweed-block/docs/design/block-design.md b/seaweed-block/docs/design/block-design.md index 41232862de..eb8450ff61 100644 --- a/seaweed-block/docs/design/block-design.md +++ b/seaweed-block/docs/design/block-design.md @@ -189,6 +189,130 @@ stateDiagram-v2 v1.1 removes the two experimental engines, smartwal (in-place writes plus a metadata ring) and parallel-walstore. Their selector names are refused by blockvolume (`--durable-impl`), the provider and the Kubernetes launcher, and a volume either one created is refused at open under every selector, before any selector comparison, read-only and never modified, with the typed answer "created by a removed experimental engine; copy the data to a walstore volume with v1.0.x first" (`core/frontend/durable/provider.go` `verifyImplOnDisk`, `RemovedEngineName`; ledger `INV-OPEN-REMOVED-ENGINE-REFUSED-001`, `INV-OPEN-REMOVED-ENGINE-NAME-REFUSED-001`). Only their on-disk magics remain in the code: `SWAW`, and `SWPW` in either of parallel-walstore's two header slots. `blockvolume --durable-impl` defaults to auto, which creates new volumes as walstore and opens an existing walstore volume; auto refuses a root that carries chunk metadata (a `walstore-chunk` volume) instead of opening it as plain walstore; such a volume needs `--durable-impl=walstore-chunk` with its remote configuration (`core/frontend/durable/provider.go` `openOrCreate`). +## 1.4 Durability and Sync + +- **One durability point.** A write is durable only when a `Sync` covering its LSN returns nil. `Sync` returns the durable frontier. +- **Group commit.** Concurrent `Sync` callers share one `fsync`. The committer waits up to `MaxDelay` (1 ms) or until 64 waiters are queued (`core/storage/group_commit.go` `NewGroupCommitter`, `Run`). +- **Deduplication.** A sync that started after the last mutation covers later `Sync` requests with no new writes (`walstore.go` `walSyncCovered`). +- **A failed `fsync` is sticky.** The first failed `fsync` of the store's file (WAL, extent or superblock), or a failed WAL append, latches a typed `io_error` fault; the open store then refuses every later `Sync`, write and checkpoint until it is reopened and recovered (`walstore.go` `noteFsyncFailure`, `noteAppendFailure`, `syncFile`, `stickyIOFault`). Every `fsync` of the file is serialized with that latch, so no publication can pass the check and complete after another path's `fsync` failed (#172). +- **With replication.** `ReplicationVolume.Sync` queues a barrier behind every shipped write, runs the local `fsync` in parallel, and applies the volume's durability mode (§1.6). +- **Observability.** Per-stage power-of-two histograms (frontend receive, WAL append, group-commit wait, physical sync, return) are exposed under `/status/durable` (`docs/fsync-latency.md`). + +**Review directions.** +- `fsync` failure semantics: after a failed `fsync`, the kernel may have dropped the dirty pages, so a later successful `fsync` proves nothing about them. Any new path that `fsync`s the store's file must go through `syncFile`, so the fault latches. +- Do not add a stage's p99 to another's; the populations differ. + +## 1.5 Authority: blockmaster, assignments, epochs, leases + +**Algorithm.** +- blockmaster is the only component that mints epochs. A reassignment takes the maximum epoch published for the volume plus one (`core/authority/authority.go` `applyWithWorkspaceMove`, `IntentReassign` case). A workspace move reserves its epoch the same way and journals the move before the epoch is published (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). +- If a durable authority write fails, the publisher marks the volume uncertain and refuses further writes for it, so a later write cannot go backwards (`workspace.go` `persistWorkspaceLocked`). +- blockvolume never elects itself; it serves under the assignment it was given, and every I/O re-checks that assignment (§1.1). +- Workspace volumes add a lease ([agent workspace design §7](agent-workspace-design.md#7-lease-takeover-and-host-moves)). + +```mermaid +stateDiagram-v2 + [*] --> Unbound + Unbound --> Bound: IntentBind (epoch 1) + Bound --> Bound: same assignment republished + Bound --> Bound: IntentRefreshEndpoint (endpoint version + 1), only on the line it was decided against + Bound --> Reassigned: IntentReassign (max epoch + 1) + Reassigned --> Bound: new primary serves at the new epoch + Bound --> Deleting: deletion reservation (id never reused) + Deleting --> [*] +``` + +**Invariants.** + +| Invariant | Enforced in | Test | Model-checked | +|---|---|---|---| +| Epochs per volume are minted only by blockmaster and strictly increase | `authority.go`; `workspace.go` | `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`) | yes | +| A failed or uncertain authority write never lets the epoch go backwards | `workspace.go` `persistWorkspaceLocked` | covered by the authority store tests | yes (removing the guard produces a counterexample) | +| Each move request id gets exactly one epoch | `workspace.go` `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`) | yes | +| A deleted volume id is never created again | `core/host/master/services.go` (deletion reservations) | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`) | yes | + +**Review directions.** Any new way to publish an assignment must go through the publisher's epoch rule; nothing else may construct an epoch. The control plane has no authentication today (see Known issues), so every destructive RPC is reachable by anyone who can reach the port. + +## 1.6 Replication and failover + +This section is the replication engine as a core component. Kubernetes volumes use it when their StorageClass sets `replicationFactor` to 2 or 3 (the default is 1); agent workspaces do not use it (they run RF=1). The product view (StorageClass and Helm settings, failure detection, the promotion gate, multipath, readiness) is in the [Kubernetes block design](kubernetes-block-design.md). + +**Shipping.** The primary writes locally first, then ships each write to every replica in LSN order (`core/replication/volume.go` `OnLocalWrite`), through a per-peer FIFO. + +**Durable acknowledgement.** `ReplicationVolume.Sync` enqueues a barrier for the target LSN on every peer queue, runs the local `fsync` in parallel, and judges the result by mode (`core/replication/durability.go`): +- `best_effort`: the local `fsync` is enough; a failed peer barrier degrades that peer; +- `sync_quorum`: a majority of nodes (primary plus replicas) are durable; +- `sync_all`: every replica is durable. + +**Replica fencing.** The replica listener persists its epoch floor before acting on a higher epoch (`core/transport/replica.go` `raiseFloor`; `floor.go`). It refuses frames below the floor, frames that arrive while it is primary, and frames before its role is known (`acceptMutationLineage`, `EnterDualLane`). A failed `ApplyEntry` closes the connection, so no barrier can acknowledge past the gap. Replication listeners open only when the assignment has replica slots (`cmd/blockvolume/replication_ingress.go`). + +**Catch-up and rebuild.** The engine decides per peer (`core/engine/state.go` `RecoveryDecision`): +- **catch-up** when the gap is still in the primary's WAL: replay WAL entries; +- **rebuild** when it is not: a dual-lane session copies the base image while also feeding live WAL entries, and the receiver arbitrates per LBA with a bitmap ("WAL has won base") (`core/recovery/doc.go`). While a rebuild is active, the primary's checkpoint is clamped to the session's pin floor so the WAL it needs is retained (`walstore.go` `persistCheckpointReleasing`). + +**Promotion.** A replica is promotion-ready only if it is a member, reachable, caught up, has completed its fence at the current epoch, and has delivered the post-rebuild durable acknowledgement (`core/engine/promotion_ready.go` `BuildPromotionReadyFact`). + +```mermaid +stateDiagram-v2 + [*] --> Unknown + 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 and reconciled in sync by (epoch, LSN) + CatchingUp --> Degraded: catch-up fails + 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`. 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).) + +**Epoch table** (`core/transport/epoch_table.go`): each volume's durable record of the first LSN of every epoch it holds data from; an entry's identity is (epoch, LSN). A recovery ships history whose epochs arrive only at its end, so the table is invalid from before its first byte until that end, under a random token held by the newest recovery. + +```mermaid +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, rebuild's first base byte, or dual-lane SessionStart (Invalidate, new token) + Invalid --> Invalid: another recovery starts (new token takes the mark, marked "took over invalid"); a completion with another token, or a catch-up's that took over an invalid table, is refused + 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. Every recovery-data apply runs under the table's apply fence (shared) and only while its token owns the mark; a change of owner takes the fence exclusive, so it waits for in-flight applies to settle and later ones of the old owner are refused. A live apply holds the fence shared too and only while the table is valid, so a recovery's Invalidate drains it. A catch-up must state the LSN it starts after (a start without it is refused) and takes the mark only if the durable end is exactly that LSN; a live entry of a new epoch is accepted only at the store's next LSN. 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.** + +| Invariant | Enforced in | Test | Model-checked | +|---|---|---|---| +| A replica refuses traffic below its persisted epoch floor, while primary, or before its role is known | `transport/replica.go` `acceptMutationLineage`, `raiseFloor` | `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch` (`core/transport/g1_durable_floor_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | yes (RF=2 slice) | +| The rebuild port applies the same admission rules | `transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | +| A failed apply closes the connection; no barrier acknowledges past a gap | `transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | +| Replication ports are open only for assigned replica slots | `cmd/blockvolume/replication_ingress.go` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | +| Catch-up versus rebuild follows WAL retention | `core/engine/apply.go` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | +| Only a fenced, caught-up member is promotion-ready | `engine/promotion_ready.go` | `TestBuildPromotionReadyFact_RefusesPendingFence` (`core/engine/promotion_ready_test.go`) | yes (RF=2: acknowledged writes survive failover) | + +**Tests and coverage.** Unit and component tests with in-process replicas; binary tests for ingress. Not modelled: RF=3 quorum, catch-up and rebuild interleavings, startup grace after a primary restart. + +**Review directions.** +- Every inbound frame type must pass the same admission check. +- Any change to barrier accounting must state what "acknowledged" means for each durability mode. +- Rebuild and live WAL feeding must have a single emitter; a second path that ships WAL bypasses ordering. + +**Lessons.** +- #84: the dual-lane rebuild port had no epoch or role check, bypassing the replica fences. Fixed in #85; `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`. +- #89: a failed `ApplyEntry` was only logged, so a barrier could acknowledge past the gap. Fixed in #93; `TestReplicaApplyFailureStopsBarrierAtTheGap`. +- Epoch floor not persisted (G1) and a new primary not fencing its own listener (G2). Fixed in #83 and #82; `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch`, `TestG2_PromotedHostRefusesShipFromDeposedPrimary`. + +## 1.7 Recovery and typed fail-closed reasons + When local recovery fails, blockvolume reports a typed reason at once instead of waiting for a timeout (`cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason`): - `wal_corrupt`: a WAL integrity failure (bad bounds, a damaged committed record); - `io_error`: an I/O error from the substrate;