From 3bd8e3302d699711753a75ddfeaaab6d95927d51 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 16:33:19 -0800 Subject: [PATCH 1/5] fix(blockvolume): a volume record not read in create mode is refused before any store exists INV-VOL-GEOMETRY-FLAGS-RECORD-001: in create mode a ReadVolume error was taken as an absent record, so a wrong --durable-blocks could still create a wrong-size store when the record could not be read. The error is now classified (one type check): the filer failed the read (remote unavailable, deadline) -> exit 75, retried: 'the volume record of V could not be read (); no local store was created; retrying'; the record is there but does not decode -> exit 78, not a retry loop: 'the volume record of V is unreadable (corrupt: ); no local store was created; restore or recreate the record'. An absent record (not found) keeps the create path. A first start with the filer down was already safe: it ends at the startup filer check (exit 1) before this one. Tests: unit, both classes (a failing LookupEntry -> 75 for a wrong and a right flag, the record read; a corrupt VOLUME entry -> 78); TestCorruptRecordIsRefusedBeforeTheStoreIsCreated (filer up, the VOLUME entry undecodable: 78 and no store for both flags; restored: 78 for the wrong flag, the right flag serves); TestFirstStartWithTheFilerDownCreatesNoStore (guard). The ledger row and the operator guide say so. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/chunk_remote.go | 30 ++++--- .../cmd/blockvolume/chunk_remote_test.go | 61 +++++++++++---- .../geometry_flag_record_integration_test.go | 78 +++++++++++++++++++ seaweed-block/cmd/blockvolume/main.go | 4 +- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/operator-guide.md | 6 ++ 6 files changed, 155 insertions(+), 26 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index 7be8c7b10c..c54a0f7cfd 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -223,21 +223,31 @@ const exitGeometryRefused = 78 // geometryFlagsRefusal compares the geometry flags with the volume record // before any local store is created, so a wrong flag never leaves a store of -// the wrong size behind. It returns the refusal line, or "" when the record -// agrees, does not exist yet (the attach check creates it from the flags), -// or cannot be read (the attach check still refuses a mismatch later), and -// when no store is being created (numBlocks 0: an existing store opens with -// its own geometry). -func geometryFlagsRefusal(ctx context.Context, cat *chunkstore.Catalog, volumeID string, numBlocks uint64, blockSize uint32) string { +// the wrong size behind. It returns the refusal line and its exit status: +// exitGeometryRefused (78) when the record disagrees or is there but does not +// decode; exitWorkspaceRetry (75) when the filer could not be read (an +// unknown, never taken as "absent"); ("", 0) when the record agrees, does +// not exist yet (the attach +// check creates it from the flags), or no store is being created (numBlocks +// 0: an existing store opens with its own geometry). +func geometryFlagsRefusal(ctx context.Context, cat *chunkstore.Catalog, volumeID string, numBlocks uint64, blockSize uint32) (string, int) { if numBlocks == 0 { - return "" // an existing store: the flags are not used + return "", 0 // an existing store: the flags are not used } v, ok, err := cat.ReadVolume(ctx, volumeID) - if err != nil || !ok || (v.NumBlocks == numBlocks && v.BlockSize == blockSize) { - return "" + if err != nil && chunkstore.CodeOf(err) == chunkstore.CodeRemoteUnavailable { + return fmt.Sprintf("blockvolume: the volume record of %s could not be read (%v); no local store was created; retrying", volumeID, err), exitWorkspaceRetry + } + if err != nil { + // A record that is there but does not decode stays that way: a + // permanent refusal, not a retry loop. + return fmt.Sprintf("blockvolume: the volume record of %s is unreadable (corrupt: %v); no local store was created; restore or recreate the record", volumeID, err), exitGeometryRefused + } + if !ok || (v.NumBlocks == numBlocks && v.BlockSize == blockSize) { + return "", 0 } return fmt.Sprintf("blockvolume: geometry_mismatch: --durable-blocks %d --durable-blocksize %d disagree with the volume record of %s (%d blocks of %d bytes); no local store was created; start it with the record's geometry", - numBlocks, blockSize, volumeID, v.NumBlocks, v.BlockSize) + numBlocks, blockSize, volumeID, v.NumBlocks, v.BlockSize), exitGeometryRefused } // chunkHolder is how this host names itself in HEAD: / diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index 9b8c1aa1ce..7a2f2cbe4a 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -3,6 +3,7 @@ package main import ( "context" "errors" + "path" "strings" "testing" "time" @@ -117,40 +118,46 @@ func TestChunkVolumeRootStaysInsideBase(t *testing.T) { } // Before any local store is created, a geometry flag that disagrees with the -// volume record is refused with a line naming both; a matching record, a -// missing record (the attach check creates it) and an unreadable one (the -// attach check still applies) do not refuse. +// volume record is refused with a line naming both (78); a record the filer +// could not deliver is refused as retryable (75), never taken as "absent"; +// a record that is there but does not decode is refused for good (78); a matching +// record, a missing record (the attach check creates it) and an existing +// store (no create geometry) are not refused. func TestGeometryFlagsRefusalComparesTheRecord(t *testing.T) { ctx := context.Background() cat, err := chunkstore.NewCatalog(chunkstore.NewMemFiler(), defaultChunkPath) if err != nil { t.Fatal(err) } - if got := geometryFlagsRefusal(ctx, cat, "v1", 32768, 4096); got != "" { - t.Fatalf("no record yet: %q", got) + if got, code := geometryFlagsRefusal(ctx, cat, "v1", 32768, 4096); got != "" || code != 0 { + t.Fatalf("no record yet: %q, %d", got, code) } if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 65536, BlockSize: 4096, ChunkBlocks: 1024}); err != nil { t.Fatal(err) } - if got := geometryFlagsRefusal(ctx, cat, "v1", 65536, 4096); got != "" { - t.Fatalf("matching flags refused: %q", got) + if got, code := geometryFlagsRefusal(ctx, cat, "v1", 65536, 4096); got != "" || code != 0 { + t.Fatalf("matching flags refused: %q, %d", got, code) } for _, c := range []struct { blocks uint64 size uint32 }{{32768, 4096}, {65536, 512}} { - got := geometryFlagsRefusal(ctx, cat, "v1", c.blocks, c.size) + got, code := geometryFlagsRefusal(ctx, cat, "v1", c.blocks, c.size) + if code != exitGeometryRefused { + t.Fatalf("flags %d x %d: exit %d, want %d", c.blocks, c.size, code, exitGeometryRefused) + } for _, want := range []string{"geometry_mismatch", "--durable-blocks", "65536 blocks of 4096 bytes"} { if !strings.Contains(got, want) { t.Fatalf("flags %d x %d: refusal %q lacks %q", c.blocks, c.size, got, want) } } } - if got := geometryFlagsRefusal(ctx, cat, "v1", 0, 0); got != "" { - t.Fatalf("an existing store (no create geometry) must not be refused: %q", got) + if got, code := geometryFlagsRefusal(ctx, cat, "v1", 0, 0); got != "" || code != 0 { + t.Fatalf("an existing store (no create geometry) must not be refused: %q, %d", got, code) } // An unreadable record: the same valid volume over a filer whose - // lookups fail. The record is read (and fails), and nothing is refused. + // lookups fail. The record is read, fails, and the start is refused as + // retryable before anything is created. failing := &lookupFailFiler{MemFiler: chunkstore.NewMemFiler()} failCat, err := chunkstore.NewCatalog(failing, defaultChunkPath) if err != nil { @@ -160,12 +167,40 @@ func TestGeometryFlagsRefusalComparesTheRecord(t *testing.T) { t.Fatal(err) } failing.fail, failing.reads = true, 0 - if got := geometryFlagsRefusal(ctx, failCat, "v1", 32768, 4096); got != "" { - t.Fatalf("an unreadable record must not refuse: %q", got) + for _, blocks := range []uint64{32768, 65536} { // a wrong and a right flag alike + got, code := geometryFlagsRefusal(ctx, failCat, "v1", blocks, 4096) + if code != exitWorkspaceRetry || !strings.Contains(got, "the volume record of v1 could not be read") || !strings.Contains(got, "no local store was created; retrying") { + t.Fatalf("--durable-blocks %d over an unreadable record: %q, exit %d; want a retryable refusal (%d)", blocks, got, code, exitWorkspaceRetry) + } } if failing.reads == 0 { t.Fatal("the unreadable-record case never read the record") } + // A record that is there but does not decode: a permanent refusal + // (78), not a retry loop, for a wrong and a right flag alike. + mem := chunkstore.NewMemFiler() + corruptCat, err := chunkstore.NewCatalog(mem, defaultChunkPath) + if err != nil { + t.Fatal(err) + } + if _, err := corruptCat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 65536, BlockSize: 4096, ChunkBlocks: 1024}); err != nil { + t.Fatal(err) + } + dir := path.Join(defaultChunkPath, "v1") + e, err := mem.LookupEntry(ctx, dir, "VOLUME") + if err != nil { + t.Fatal(err) + } + e.Content = []byte("{") + if err := mem.UpdateEntry(ctx, dir, e, nil); err != nil { + t.Fatal(err) + } + for _, blocks := range []uint64{32768, 65536} { + got, code := geometryFlagsRefusal(ctx, corruptCat, "v1", blocks, 4096) + if code != exitGeometryRefused || !strings.Contains(got, "the volume record of v1 is unreadable (corrupt:") || !strings.Contains(got, "no local store was created") { + t.Fatalf("--durable-blocks %d over a corrupt record: %q, exit %d; want a permanent refusal (%d)", blocks, got, code, exitGeometryRefused) + } + } } // lookupFailFiler is a MemFiler whose LookupEntry fails once fail is set; it diff --git a/seaweed-block/cmd/blockvolume/geometry_flag_record_integration_test.go b/seaweed-block/cmd/blockvolume/geometry_flag_record_integration_test.go index 4d7d545d8e..bdd1616177 100644 --- a/seaweed-block/cmd/blockvolume/geometry_flag_record_integration_test.go +++ b/seaweed-block/cmd/blockvolume/geometry_flag_record_integration_test.go @@ -3,7 +3,9 @@ package main_test import ( + "context" "os" + "path" "strings" "testing" "time" @@ -57,3 +59,79 @@ func TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated(t *testing.T) { t.Fatalf("1.0.1: %s", strings.Join(problems, "; ")) } } + +// INV-VOL-GEOMETRY-FLAGS-RECORD-001, the corrupt record: in create mode, a +// volume record that is there but does not decode is refused for good (exit +// 78) before any local store exists, never taken as "absent" and never +// retried. The filer stays up and answers the startup checks; v2's VOLUME +// entry is made undecodable. A wrong and a right --durable-blocks alike exit +// 78 and leave nothing under --durable-root. With the entry restored the wrong +// flag is refused (78, mismatch) and the right flag serves. (A filer that +// cannot deliver the record is the retryable case, 75: the unit test.) +func TestCorruptRecordIsRefusedBeforeTheStoreIsCreated(t *testing.T) { + env := startSourceWithSnapshot(t, "v2") + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + b := env.hosts["n-v2"] + right := append([]string{}, env.volArgsFor(b)...) + wrong := append([]string{}, right...) + for i := range wrong { + if wrong[i] == "--durable-blocks" { + wrong[i+1] = "32768" + } + } + ctx := context.Background() + cl := env.cluster.client(t, "") + dir := path.Join(env.chunkPath, "v2") + entry, err := cl.LookupEntry(ctx, dir, "VOLUME") + if err != nil { + t.Fatal(err) + } + record := append([]byte(nil), entry.Content...) + entry.Content = []byte("{") + if err := cl.UpdateEntry(ctx, dir, entry, nil); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + name string + args []string + }{{"wrong", wrong}, {"right", right}} { + d := env.h.start(t, "blockvolume-v2-"+c.name+"-corrupt", env.h.volume, c.args...) + err := d.wait(60 * time.Second) + line := d.line("is unreadable (corrupt:") + entries, _ := os.ReadDir(b.root) + t.Logf("%s flag over a corrupt record: exit %v; %q; files under --durable-root %d", c.name, err, line, len(entries)) + if exitCode(err) != 78 || !strings.Contains(line, "no local store was created") || len(entries) != 0 { + t.Fatalf("1.0.1: a %s-flag first start over a corrupt record must exit 78 before creating anything; exit %v, line %q, %d files", c.name, err, line, len(entries)) + } + } + entry.Content = record + if err := cl.UpdateEntry(ctx, dir, entry, nil); err != nil { + t.Fatal(err) + } + d := env.h.start(t, "blockvolume-v2-wrong-readable", env.h.volume, wrong...) + if err := d.wait(60 * time.Second); exitCode(err) != 78 { + t.Fatalf("with the record readable again, the wrong flag must be refused (78); exit %v", err) + } + served := env.startTarget(t, "v2", "blockvolume-v2-right-readable") + served.kill(t) +} + +// Guard: a first start with the filer stopped ends at the startup filer +// check (exit 1) before the record check and before any store exists. +func TestFirstStartWithTheFilerDownCreatesNoStore(t *testing.T) { + env := startSourceWithSnapshot(t, "v2") + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + b := env.hosts["n-v2"] + env.cluster.stopProc(t, "filer") + d := env.h.start(t, "blockvolume-v2-filer-down", env.h.volume, env.volArgsFor(b)...) + err := d.wait(120 * time.Second) + env.cluster.restartProc(t, "filer") + w4WaitTCP(t, env.cluster.filerGRPC, 30*time.Second) + entries, _ := os.ReadDir(b.root) + t.Logf("filer down: exit %v; %q; files under --durable-root %d", err, d.line("needs exactly one filer"), len(entries)) + if exitCode(err) != 1 || d.line("needs exactly one filer") == "" || len(entries) != 0 { + t.Fatalf("a first start with the filer down must end at the startup filer check without a store; exit %v, %d files", err, len(entries)) + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index cb475edb82..939191bdcc 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -737,7 +737,7 @@ func runVolume(f flags, exits *processExit) int { // between it and the record is the attach check's. if chunkErr == nil && geometryErr == nil && blocks != 0 && chunk.catalog != nil { readCtx, readCancel := context.WithTimeout(context.Background(), 10*time.Second) - refusal := geometryFlagsRefusal(readCtx, chunk.catalog, f.volumeID, uint64(blocks), uint32(blockSize)) + refusal, code := geometryFlagsRefusal(readCtx, chunk.catalog, f.volumeID, uint64(blocks), uint32(blockSize)) readCancel() if refusal != "" { fmt.Fprintln(os.Stderr, refusal) @@ -747,7 +747,7 @@ func runVolume(f flags, exits *processExit) int { shutCancel() } _ = h.Close() - return exitGeometryRefused + return code } } var dp *durable.DurableProvider diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 05b035cfd2..1fdacbf315 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -744,7 +744,7 @@ Notes: | `INV-WS-SEAL-REPLAY-001` | A repeated plain seal, also after restart, succeeds only from a fresh filer HEAD with exact owner/epoch and detachedBy proof. It returns that original HEAD/frontier without a CAS or new generation. An unreadable or mismatched proof cannot be answered from process memory. | M5 PlainStop -> RemoteProof -> SealedReply | `core/frontend/durable/provider_seal_replay.go` `replayPlainSeal`; `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`; `cmd/blockvolume/workspace_lease.go` `workspaceDetachedGeneration` | `TestWorkspaceRevocationUsesExactStoredSeal` (`cmd/blockvolume/workspace_proof_test.go`); `TestPlainSealLostAnswerRestartReplaysFilerProof`, `TestPlainSealReplayNeverUsesProcessMemory`, `TestPlainSealReplayDuringDeferredAuthorityStartup` (`core/frontend/durable/provider_plain_seal_replay_test.go`) | `PlainSealReplay` `SuccessNeedsFreshExactProof`, `ValidProofDoesNotNeedProcessMemory` | ACTIVE | | `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | | `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | -| `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | A create-mode start whose `--durable-blocks`/`--durable-blocksize` disagree with the volume record exits 78 before any local store exists; an existing store is checked only at attach; a missing record keeps the create path; an unreadable record falls to the attach check, never a refusal. | blockvolume startup (before the durable provider) | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `TestGeometryFlagsRefusalComparesTheRecord` (`cmd/blockvolume/chunk_remote_test.go`); `TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated`, `TestWrongGeometryCureAsWritten` (`cmd/blockvolume`, real binaries) | - | ACTIVE | +| `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | A create-mode start whose `--durable-blocks`/`--durable-blocksize` disagree with the volume record exits 78 before any local store exists; an existing store is checked only at attach; an absent record keeps the create path; an unread record exits 75 (filer failed) or 78 (corrupt). | blockvolume startup (before the durable provider) | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `TestGeometryFlagsRefusalComparesTheRecord` (`cmd/blockvolume/chunk_remote_test.go`); `TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated`, `TestCorruptRecordIsRefusedBeforeTheStoreIsCreated`, `TestWrongGeometryCureAsWritten` (`cmd/blockvolume`, real binaries) | - | ACTIVE | | `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published, or whose local durable LSN is below HEAD's `remote_lsn` (a rolled-back copy), is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`); `TestLocalReopenRejectsForeignClaimImage` (`core/frontend/durable/provider_reopen_belt_test.go`); `TestRolledBackCopyBelowHeadLSNIsRefused` (`core/frontend/durable/rolled_back_copy_test.go`); `TestCutPublishesOnlyLocallyDurableLSN` (`core/frontend/durable/cut_durable_before_cas_test.go`) | — | ACTIVE | | `INV-WS-ONE-PROCESS-PER-HOST-001` | One host runs at most one live blockvolume per volume: each takes the volume's exclusive host lock before its store opens and holds it until the store closes; a second is refused before it opens anything, whatever its `--durable-root`. | M4 (start) → Attaching, Refused | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` | `TestOneLiveProcessPerVolumePerHost`, `TestHostVolumeLockDirectoryCreatedOrRefused`, `TestHostVolumeLockRefusesNonDirectoryLockPath`, `TestHostVolumeLockTakesReadOnlyLockFile` (`core/frontend/durable/one_process_per_volume_test.go`); `TestHostVolumeLockCreatesParent0755AndLocks0700`, `TestHostVolumeLockKeepsExistingDirectoryModes` (`core/frontend/durable/volume_lock_parent_mode_test.go`); `TestVolumeLockDirTestOnlyRefusedUnderSystemd` (`cmd/blockvolume/volume_lock_flag_test.go`) | — | ACTIVE | | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index 17efd02f20..8adf89485c 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -55,6 +55,11 @@ one live blockvolume per volume ([one process per volume](releases/one-process-p A first start whose `--durable-blocks` or `--durable-blocksize` disagrees with the volume record is refused before any local store is created: it exits 78 (the unit does not restart it) with a line `geometry_mismatch: --durable-blocks ... disagree with the volume record`; correct the flag and start it again. + If that first start cannot read the volume record because the filer failed the read, it exits 75 with `the volume + record of could not be read ... no local store was created; retrying` and the unit starts it again. During a long + outage the unit can reach its start limit; once the filer answers, run `systemctl reset-failed ` and start it. + If the record is there but corrupt, it exits 78 with `the volume record of is unreadable (corrupt: ...)`: restore + or recreate the record, then start it. A wrong-size local store left by an earlier release's first start is different: its log repeats `chunk attach check: chunkstore: geometry_mismatch` and it exits; waiting or restarting with the right flags does not help. In one sitting: stop the unit first; then check that the volume never served: `sw-block ops chunk show --volume --chunk-filer --chunk-path ` prints `"epoch":0` and @@ -205,6 +210,7 @@ Every command on the pages above, and the test that runs it. | A snapshot refused with `host_slot_busy` / `no background slot` while every host slot is held, retried with the same request id | `TestSnapshotLadderF1VolumesOneHost` (`cmd/blockvolume`, `F1_RUN=1`, `F1_HOST_LIMIT_DIR` set, 3 slots; `F1_SLOT_RETRY_SECONDS=0` is its negative control) | binary | | Full local disk; full `--host-limit-dir` | `TestProcedureLocalDiskFull` (`cmd/blockvolume`, root, `testdata/diskfull.sh`); what a Linux guest sees: `TestProcedureLocalDiskFullKernelInitiator` (kernel NVMe/TCP host) | binary | | A first start with the wrong `--durable-blocks`: refused before any local store is created (exit 78) | `TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated` (`cmd/blockvolume`) | binary | +| A first start over a corrupt volume record: exit 78 before any local store is created; a start once the record is restored | `TestCorruptRecordIsRefusedBeforeTheStoreIsCreated` (`cmd/blockvolume`) | binary | | A wrong-size local store left by an earlier release (`geometry_mismatch` at attach): the guard (`sw-block ops chunk show`), removing the local files, a start with the right flags | `TestWrongGeometryCureAsWritten` (`cmd/blockvolume`; the store is planted from a capture of such a run) | binary | | SeaweedFS (filer or volume server) down during a cut | `TestProcedureStoreDownDuringACut` (`cmd/blockvolume`) | binary | | `blockmaster` refuses a `--workspace-max-clock-skew` whose half does not exceed its fence-exit budget (at or below 10.1 s) | `TestBlockmasterRefusesASkewBoundAtOrBelowTheFenceExit` (`cmd/blockvolume`, tag `subprocess`) | binary | From 880a8ba6f6e2f6179baefba3c17fe22c71928fcc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 16:44:38 -0800 Subject: [PATCH 2/5] test(blockvolume): the guide's reset-failed procedure after a filer outage, under real systemd Co-Authored-By: Claude Opus 5.5 --- ...tup_systemd_filer_down_integration_test.go | 107 ++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go new file mode 100644 index 0000000000..a76996f919 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go @@ -0,0 +1,107 @@ +//go:build linux && subprocess && chunkstore_integration && systemd_integration + +package main_test + +import ( + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// The operator guide's procedure for a first start during a long filer +// outage, run as written under real systemd (root): the blockvolume unit, +// with the shipped restart policy and a short start limit, starts while the +// filer is down; each start fails before any store exists until systemd +// stops retrying (start-limit-hit). The filer comes back; `systemctl +// reset-failed ` and `systemctl start ` then serve the volume. +// +// A runtime unit file (/run/systemd/system) stands for the installed unit: +// a transient systemd-run unit would be removed by reset-failed. +func TestSystemdFirstStartDuringAFilerOutageThenResetFailedServes(t *testing.T) { + if os.Getuid() != 0 { + t.Skip("real systemd units need root") + } + env := startSourceWithSnapshot(t, "v2") + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + b := env.hosts["n-v2"] + + shipped := gap1ShippedPolicy(t) + unit := fmt.Sprintf("swb-c04-filer-outage-%d.service", os.Getpid()) + unitPath := filepath.Join("/run/systemd/system", unit) + quoted := []string{fmt.Sprintf("%q", env.h.volume)} + for _, a := range env.volArgsFor(b) { + quoted = append(quoted, fmt.Sprintf("%q", a)) + } + spec := strings.Join([]string{ + "[Unit]", + "Description=sw-block test unit: first start during a filer outage", + "StartLimitIntervalSec=600", + "StartLimitBurst=2", + "[Service]", + "Type=exec", + "ExecStart=" + strings.Join(quoted, " "), + "Restart=on-failure", + "RestartSec=" + shipped["RestartSec"], + "RestartPreventExitStatus=" + shipped["RestartPreventExitStatus"], + "TimeoutStopSec=" + shipped["TimeoutStopSec"], + "", + }, "\n") + systemctl := func(args ...string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() + return string(out), err + } + t.Cleanup(func() { + gap1CleanupUnit(t, unit) + _ = os.Remove(unitPath) + _, _ = systemctl("daemon-reload") + }) + if err := os.WriteFile(unitPath, []byte(spec), 0o644); err != nil { + t.Fatal(err) + } + if out, err := systemctl("daemon-reload"); err != nil { + t.Fatalf("daemon-reload: %v %s", err, out) + } + + env.cluster.stopProc(t, "filer") + if out, err := systemctl("start", "--no-block", unit); err != nil { + t.Fatalf("start %s: %v %s", unit, err, out) + } + var state map[string]string + poll(t, 8*time.Minute, unit+" never reached start-limit-hit with the filer down", func() bool { + s, err := gap1ReadUnit(unit) + state = s + return err == nil && s["Result"] == "start-limit-hit" + }) + entries, _ := os.ReadDir(b.root) + t.Logf("filer down: %s gave up: Result %s, NRestarts %s, ExecMainStatus %s, ActiveState %s; files under --durable-root %d", + unit, state["Result"], state["NRestarts"], state["ExecMainStatus"], state["ActiveState"], len(entries)) + if len(entries) != 0 { + t.Fatalf("the failed starts created %d files under --durable-root", len(entries)) + } + + env.cluster.restartProc(t, "filer") + w4WaitTCP(t, env.cluster.filerGRPC, 30*time.Second) + // The guide, as written: reset-failed, then start. + if out, err := systemctl("reset-failed", unit); err != nil { + t.Fatalf("systemctl reset-failed %s: %v %s", unit, err, out) + } + if out, err := systemctl("start", unit); err != nil { + t.Fatalf("systemctl start %s: %v %s", unit, err, out) + } + poll(t, 2*time.Minute, "v2 never served after reset-failed and start", func() bool { + return volumeFrontendReady(b.status, "v2") + }) + head := env.headOf(t, "v2") + if strings.Contains(head, `"holder":""`) { + t.Fatalf("v2 serves but its HEAD is not claimed: %s", head) + } + t.Logf("after reset-failed + start: v2 serves; HEAD %s", head) +} From 6516a950ffa6ca1a212dd11c0ec3217e3af9ed1e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 16:51:21 -0800 Subject: [PATCH 3/5] review fold: the create-mode geometry check in M1 (diagram and row); the systemd test needs GAP1_SYSTEMD_AUTHORIZED=1 and root Co-Authored-By: Claude Opus 5.5 --- .../startup_systemd_filer_down_integration_test.go | 7 +++++-- seaweed-block/docs/design/invariants.md | 2 ++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go index a76996f919..1753751b68 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go @@ -23,8 +23,11 @@ import ( // A runtime unit file (/run/systemd/system) stands for the installed unit: // a transient systemd-run unit would be removed by reset-failed. func TestSystemdFirstStartDuringAFilerOutageThenResetFailedServes(t *testing.T) { - if os.Getuid() != 0 { - t.Skip("real systemd units need root") + if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" { + t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof") + } + if os.Geteuid() != 0 { + t.Fatal("systemd qualification needs root") } env := startSourceWithSnapshot(t, "v2") env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 1fdacbf315..73e2c3026c 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -46,6 +46,7 @@ The local storage engine and the durable backend in front of it. Diagrams in the stateDiagram-v2 [*] --> Opened: OpenWALStore / CreateWALStore [*] --> CreateRefused: CreateWALStore without local headroom (free < size + WAL) + [*] --> CreateRefused: chunk volume, create mode: geometry flags disagree with the volume record, or the record is not read Opened --> Recovering: RecoverVolume Recovering --> Serving: Recover ok, backend operational; workspace primary: lease held, then HEAD claim, then frontends listen, then ready Serving --> Closed: runtime HEAD fence, exit 78 head_fenced @@ -62,6 +63,7 @@ stateDiagram-v2 |---|---|---|---|---| | — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001`, `INV-WAL-V3-ACTIVATION-001`, `INV-WAL-V3-DESCRIPTOR-001`, `INV-WAL-V3-MAP-PUBLISH-001` | | — | CreateRefused | a new volume needs the durable root's free space >= its size + WAL, checked before the store, its WAL or its fresh marker is created (the replica floor, written when the assignment arrives, precedes the check and stays); the refusal ends the process with status 1; an existing volume opens and warns when its remaining data growth + WAL exceed the free space | `core/frontend/durable/headroom.go`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-LOCAL-HEADROOM-001` | +| — | CreateRefused | a chunk volume in create mode (no local store yet): before the provider is built, the geometry flags are compared with the volume record; they disagree, or the record is there but does not decode: exit 78; the filer failed the read: exit 75; nothing is created; an absent record keeps the create path; an existing store is never rechecked against the flags | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason); a workspace primary claims HEAD, listens and reports ready only while its lease guard permits now (`WorkspaceLeaseGuard.Held`; without a grant: `NotReadyReason=lease_not_held`, exit 75 after the start-time wait) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection`; `core/host/volume/workspace_lease.go` `Held` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001`, `INV-WAL-V3-W-RECOVERY-001` | From 32fb4b78fed40d0f2b19372af7878700c0a8b7c3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 16:54:08 -0800 Subject: [PATCH 4/5] test(blockvolume): the systemd outage test uses the real lock directory and the unit's failed state after its burst Under systemd blockvolume refuses --volume-lock-dir-test-only (exit 2), so the first run never reached the filer check. systemd 249 reports the start limit as a failed unit with Result=exit-code and 'Start request repeated too quickly', not Result=start-limit-hit. Co-Authored-By: Claude Opus 5.5 --- ...tup_systemd_filer_down_integration_test.go | 36 +++++++++++++++---- 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go index 1753751b68..5b0c0e86ad 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go @@ -16,8 +16,9 @@ import ( // The operator guide's procedure for a first start during a long filer // outage, run as written under real systemd (root): the blockvolume unit, // with the shipped restart policy and a short start limit, starts while the -// filer is down; each start fails before any store exists until systemd -// stops retrying (start-limit-hit). The filer comes back; `systemctl +// filer is down; each start fails at the startup filer check (exit 1, no +// store) until systemd stops retrying (its start limit). The filer comes +// back; `systemctl // reset-failed ` and `systemctl start ` then serve the volume. // // A runtime unit file (/run/systemd/system) stands for the installed unit: @@ -37,9 +38,23 @@ func TestSystemdFirstStartDuringAFilerOutageThenResetFailedServes(t *testing.T) shipped := gap1ShippedPolicy(t) unit := fmt.Sprintf("swb-c04-filer-outage-%d.service", os.Getpid()) unitPath := filepath.Join("/run/systemd/system", unit) + // Under systemd blockvolume refuses the test-only lock directory: the + // unit uses the real one, as an installed unit does. quoted := []string{fmt.Sprintf("%q", env.h.volume)} - for _, a := range env.volArgsFor(b) { - quoted = append(quoted, fmt.Sprintf("%q", a)) + args := env.volArgsFor(b) + for i := 0; i < len(args); i++ { + if args[i] == "--volume-lock-dir-test-only" { + i++ + continue + } + quoted = append(quoted, fmt.Sprintf("%q", args[i])) + } + const lockDir = "/run/sw-block/locks" + if _, err := os.Stat(lockDir); os.IsNotExist(err) { + if err := os.MkdirAll(lockDir, 0o755); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Remove(lockDir); _ = os.Remove(filepath.Dir(lockDir)) }) } spec := strings.Join([]string{ "[Unit]", @@ -77,15 +92,24 @@ func TestSystemdFirstStartDuringAFilerOutageThenResetFailedServes(t *testing.T) if out, err := systemctl("start", "--no-block", unit); err != nil { t.Fatalf("start %s: %v %s", unit, err, out) } + // systemd gives up when the start limit is hit: the unit stays failed + // after StartLimitBurst restarts, and the journal says "Start request + // repeated too quickly" (systemd 249 keeps Result=exit-code). var state map[string]string - poll(t, 8*time.Minute, unit+" never reached start-limit-hit with the filer down", func() bool { + poll(t, 8*time.Minute, unit+" never stopped retrying with the filer down", func() bool { s, err := gap1ReadUnit(unit) state = s - return err == nil && s["Result"] == "start-limit-hit" + return err == nil && s["ActiveState"] == "failed" && s["NRestarts"] == "2" }) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + journal, _ := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager").CombinedOutput() + cancel() entries, _ := os.ReadDir(b.root) t.Logf("filer down: %s gave up: Result %s, NRestarts %s, ExecMainStatus %s, ActiveState %s; files under --durable-root %d", unit, state["Result"], state["NRestarts"], state["ExecMainStatus"], state["ActiveState"], len(entries)) + if !strings.Contains(string(journal), "Start request repeated too quickly") || state["ExecMainStatus"] != "1" { + t.Fatalf("the unit did not stop on its start limit after failing at the startup filer check (status %s):\n%s", state["ExecMainStatus"], journal) + } if len(entries) != 0 { t.Fatalf("the failed starts created %d files under --durable-root", len(entries)) } From 162f914a3110adcd4c30252662db9b02dd26d0c2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 23 Nov 2026 17:03:03 -0800 Subject: [PATCH 5/5] test(blockvolume): the systemd test removes only the lock directories it created Co-Authored-By: Claude Opus 5.5 --- ...tup_systemd_filer_down_integration_test.go | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go index 5b0c0e86ad..28570b441d 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go @@ -49,13 +49,24 @@ func TestSystemdFirstStartDuringAFilerOutageThenResetFailedServes(t *testing.T) } quoted = append(quoted, fmt.Sprintf("%q", args[i])) } + // Create the lock directory and its parent only if missing, and remove + // only what this test created (child first); nothing pre-existing is + // touched. const lockDir = "/run/sw-block/locks" - if _, err := os.Stat(lockDir); os.IsNotExist(err) { - if err := os.MkdirAll(lockDir, 0o755); err != nil { - t.Fatal(err) + var created []string + for _, dir := range []string{filepath.Dir(lockDir), lockDir} { + if _, err := os.Stat(dir); os.IsNotExist(err) { + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + created = append(created, dir) } - t.Cleanup(func() { _ = os.Remove(lockDir); _ = os.Remove(filepath.Dir(lockDir)) }) } + t.Cleanup(func() { + for i := len(created) - 1; i >= 0; i-- { + _ = os.Remove(created[i]) + } + }) spec := strings.Join([]string{ "[Unit]", "Description=sw-block test unit: first start during a filer outage",