diff --git a/seaweed-block/.github/workflows/test.yml b/seaweed-block/.github/workflows/test.yml index d936cb7be4..df5114a0a4 100644 --- a/seaweed-block/.github/workflows/test.yml +++ b/seaweed-block/.github/workflows/test.yml @@ -18,7 +18,10 @@ concurrency: jobs: test: name: go test (linux) - runs-on: ubuntu-latest + # Pushes and same-repo PRs run on the team's tp04 runner (seaweed.slice, + # capped at 8 cores / 8 GiB). Fork PRs never reach it: they stay on a + # GitHub-hosted runner. + runs-on: ${{ (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && 'tp04-seaweed-block' || 'ubuntu-latest' }} timeout-minutes: 25 env: # Pure-Go build: no package in the default build needs cgo, and the @@ -34,7 +37,11 @@ jobs: uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 with: go-version-file: go.mod - cache: true + # The self-hosted runner keeps GOCACHE/GOMODCACHE on its own disk; + # uploading them as an Actions cache (~4 GB) in the post step + # outlasted the job timeout after every test had passed. Only the + # GitHub-hosted (fork PR) runner uses the Actions cache. + cache: ${{ runner.environment == 'github-hosted' }} cache-dependency-path: go.sum - name: Go version @@ -46,5 +53,11 @@ jobs: - name: Vet run: go vet ./... - - name: Test - run: go test -short -count=1 -timeout 10m ./... + - name: Test default configuration + run: go test -p=1 -short -count=1 -timeout 10m ./... + + - name: Test legacy-fixture configuration + # Legacy-input fixtures and native caller controls stay executable after + # their constructors move behind the explicit test-only build tag. + # Bound package concurrency for existing short wall-clock assertions. + run: go test -p=1 -short -tags=swblock_format_v3_test -count=1 -timeout 10m ./... diff --git a/seaweed-block/AGENTS.md b/seaweed-block/AGENTS.md index 030b04dd7b..dd02471cb0 100644 --- a/seaweed-block/AGENTS.md +++ b/seaweed-block/AGENTS.md @@ -71,3 +71,19 @@ Strong success criteria let agents loop independently. Weak criteria such as These guidelines are working if there are fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes. + +## Protocol contract + +Seaweed Block's state machines and invariants are in +[`docs/design/invariants.md`](docs/design/invariants.md). Read it before +changing a protocol path: the storage engines, durability and `Sync`, +authority and epochs, replication and replica roles, the chunk layer and the +cut, the catalog, GC and volume delete, or the workspace lease. + +- Find the machine and transition (Part A) and the invariant IDs (Part B) + your change touches, and name them in the PR. +- Follow the change rules (Part C): a new or changed state or transition + updates Part A, the design-doc diagram, the ledger and the TLA+ spec that + covers it; an ACTIVE row never loses its test; a bug found by tests, soak + or TLA+ becomes a regression test plus a ledger row. +- Do not weaken a guard listed under "Enforced in" without updating its row. diff --git a/seaweed-block/README.md b/seaweed-block/README.md index 17b80fd8b3..d5f6be76d4 100644 --- a/seaweed-block/README.md +++ b/seaweed-block/README.md @@ -62,21 +62,26 @@ read-only status (stale evidence is `Ready=Unknown`, never a false ready). Lab runs, median of 3; not SLOs. Workloads: Firecracker microVMs (4 vCPU, 4 GiB) on one bare-metal host over NVMe/TCP loopback, against a local -file-backed disk. Snapshot and fork: a host-side proxy without network -latency, guest `fsync` or the block frontend. +file-backed disk. The two `fsync` rows marked "ublk" come from a later run on +the same host with the ublk frontend, after the group-commit fix +([#173](https://github.com/seaweedfs/seaweed-block/pull/173)). Snapshot and +fork: a host-side proxy without network latency, guest `fsync` or the block +frontend. | Measurement | Seaweed Block | Local disk | |---|---|---| | `npm ci` (617 packages, offline) / `git clone` (Go 1.23, local) | 2.14 s / 7.10 s | 2.14 s / 6.99 s | | Untar 100,000 files / cold `find` + `stat` over them | 1.10 s / 0.32 s | 1.06 s / 0.33 s | -| 2,000 × create + write + `fsync` | 14.33 s | 6.09 s | +| 2,000 × create + write + `fsync` (ublk) | 8.48 s | 6.11 s | +| Guest `fsync` median, fio 4 KiB random write, one at a time (ublk) | 3.23 ms | 2.74 ms | | Snapshot / fork of a 10 GiB volume (2,560 chunks) | 0.18 ms / 0.29 ms | | | Two-host lifecycle: create, snapshot, fork, move, stale holder, delete, GC | 35 of 35 checks | | -Metadata-heavy workloads run at local-disk speed. The cost in these runs is -`fsync` latency, about 7 ms against 3 ms local, measured with the NVMe/TCP -loopback frontend. The ublk frontend and per-stage `fsync` histograms are on -`main` now; latency improvement is in progress. +Metadata-heavy workloads run at local-disk speed. The remaining cost is +`fsync`: a median of 3.23 ms against 2.74 ms local with the ublk frontend +(3.59 ms over NVMe/TCP loopback), down from about 7 ms before the group-commit +fix. Every guest `fsync` still reaches the backend sync; no write cache is +turned off to get there. [Workspace measurements](docs/workspace-measurements.md) has every number and how each was measured. @@ -180,7 +185,8 @@ run evidence: [release notes](docs/releases/README.md). ### Not claimed yet - Production readiness, SLOs, or a published performance, RTO or RPO claim. -- `fsync` parity with local disk (in progress, see Measured results). +- `fsync` parity with local disk. Today it is about 1.2× local (see Measured + results). - ublk at high density. Unprivileged per-volume servers need a privileged control broker, which is not done. - Crash-restart recovery of a ublk server. A crashed server fails closed. @@ -209,7 +215,8 @@ run evidence: [release notes](docs/releases/README.md). ## Documentation - Design: [core](docs/design/block-design.md), [agent workspace](docs/design/agent-workspace-design.md), - [Kubernetes block](docs/design/kubernetes-block-design.md), [TLA+ specifications](docs/spec/README.md), + [Kubernetes block](docs/design/kubernetes-block-design.md), [invariants and state machines](docs/design/invariants.md), + [TLA+ specifications](docs/spec/README.md), [workspace measurements](docs/workspace-measurements.md) - Operations: [standalone deployment](docs/standalone-deployment.md), [Kubernetes quickstart](docs/quickstart-kubernetes.md), [user capabilities](docs/user-capabilities.md) diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index b4f60cfa2b..c8b7ce0c1c 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -29,13 +29,15 @@ const ( ) type chunkFlags struct { - filer string - path string - collection string - replication string - captureInterval time.Duration - dirtyThreshold int - uploadConcurrency int + filer string + path string + collection string + replication string + captureInterval time.Duration + dirtyThreshold int + uploadConcurrency int + hydrationWorkers int + hydrationQueueDepth int // controlEndpoint mounts the /chunk/* routes on the status listener. controlEndpoint bool } @@ -45,7 +47,7 @@ func validateChunkFlags(f flags) error { if f.durableImpl != "walstore-chunk" { if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath || c.captureInterval != defaultChunkCaptureInterval || c.dirtyThreshold != defaultChunkDirtyThreshold || - c.uploadConcurrency != 8 || c.controlEndpoint { + c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint { return errors.New("--chunk-* flags require --durable-impl=walstore-chunk") } return nil @@ -53,6 +55,9 @@ func validateChunkFlags(f flags) error { if c.controlEndpoint && f.statusAddr == "" { return errors.New("--chunk-control-endpoint requires --status-addr") } + if f.replicationAck != "" && f.replicationAck != "best-effort" { + return fmt.Errorf("--durable-impl=walstore-chunk is single-replica: --replication-ack=%q needs replica peers (%s)", f.replicationAck, chunkRF1Reason) + } if f.durableRoot == "" { return errors.New("--durable-impl=walstore-chunk requires --durable-root") } @@ -68,12 +73,25 @@ func validateChunkFlags(f flags) error { if c.uploadConcurrency < 1 || c.uploadConcurrency > 64 { return errors.New("--chunk-upload-concurrency must be between 1 and 64") } + if c.hydrationWorkers < 1 || c.hydrationWorkers > 64 { + return errors.New("--chunk-hydration-workers must be between 1 and 64") + } + if c.hydrationQueueDepth < 1 || c.hydrationQueueDepth > 65536 { + return errors.New("--chunk-hydration-queue-depth must be between 1 and 65536") + } if c.dirtyThreshold < 0 { return fmt.Errorf("--chunk-dirty-threshold=%d must not be negative", c.dirtyThreshold) } return nil } +// chunkRF1Reason is why a walstore-chunk volume refuses replication, at start +// and on every assignment with replica slots: a chunk cut takes its LSN from the +// local WAL head, which no replica is guaranteed to hold, so a published HEAD +// could be ahead of every replica. The master's workspace RPCs enforce RF1; this +// is the same rule on the volume server, for a direct start. +const chunkRF1Reason = "chunk snapshots take the cut LSN from the local WAL, which replicas may not hold; walstore-chunk is RF1 only" + // chunkWiring is what --durable-impl=walstore-chunk dials once: the // provider's per-volume remotes, the catalog under the same base (VOLUME // entries, snapshots) and the client's closer. diff --git a/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go b/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go new file mode 100644 index 0000000000..0d0fd71741 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A walstore-chunk volume is RF1 only: a chunk cut takes its LSN from the local +// WAL head, which replicas may not hold. A direct start must refuse replication +// (the master's workspace RPCs already do). +func TestChunkVolumeRefusesReplicationAckAtStart(t *testing.T) { + base := []string{"--master", "127.0.0.1:1", "--server-id", "node-a", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:9100", "--ctrl-addr", "127.0.0.1:9101"} + chunk := append(append([]string{}, base...), "--durable-root", t.TempDir(), "--durable-impl", "walstore-chunk", "--chunk-filer", "127.0.0.1:18888") + for _, ack := range []string{"sync-quorum", "sync-all"} { + _, err := parseFlags(append(append([]string{}, chunk...), "--replication-ack", ack)) + if err == nil || !strings.Contains(err.Error(), "single-replica") || !strings.Contains(err.Error(), "RF1 only") { + t.Fatalf("walstore-chunk with --replication-ack=%s: %v", ack, err) + } + } + if _, err := parseFlags(append(append([]string{}, chunk...), "--replication-ack", "best-effort")); err != nil { + t.Fatalf("walstore-chunk best-effort refused: %v", err) + } + if _, err := parseFlags(append(append([]string{}, base...), "--durable-root", t.TempDir(), "--durable-impl", "walstore", "--replication-ack", "sync-quorum")); err != nil { + t.Fatalf("walstore sync-quorum refused: %v", err) + } +} + +// The replication factor arrives with the master's assignment. The host refuses +// roles with replica slots (core/host/volume RF1Only, from hostConfig); the +// ingress gate refuses them again and opens neither inbound lane (legacy and +// dual-lane ports). A primary role without peers (RF1) is admitted. +func TestChunkVolumeIngressRefusesReplicaSlots(t *testing.T) { + for _, row := range []struct{ impl, mode string }{{"walstore", "legacy"}, {"walstore", "dual-lane"}, {"walstore-chunk", "legacy"}, {"walstore-chunk", "dual-lane"}} { + impl, dualLane := row.impl, row.mode == "dual-lane" + t.Run(row.impl+"/"+row.mode, func(t *testing.T) { + addr, dual := ingressPair(t) + f := flags{dataAddr: addr, volumeID: "v1", durableImpl: impl, recoveryMode: row.mode} + if got, want := hostConfig(f, nil).RF1Only, map[string]string{"walstore": "", "walstore-chunk": chunkRF1Reason}[impl]; got != want { + t.Fatalf("host config RF1Only = %q, want %q", got, want) + } + r := newReplicationIngress(f, storage.NewBlockStore(4, 4096)) + defer r.Stop() + admitErr := r.AdmitAsReplica(1) + if impl == "walstore" { + if admitErr != nil || r.listener == nil || (r.dual != nil) != dualLane { + t.Fatalf("walstore replica role (%s): %v", row.mode, admitErr) + } + return + } + if admitErr == nil || !strings.Contains(admitErr.Error(), "refuses a replica role") || !strings.Contains(admitErr.Error(), "RF1 only") { + t.Fatalf("replica role admitted: %v", admitErr) + } + if err := r.FenceAsPrimaryWithPeers(2, true); err == nil || !strings.Contains(err.Error(), "refuses a primary role with replica peers") { + t.Fatalf("primary with peers admitted: %v", err) + } + if err := r.FenceAsPrimary(3); err == nil { + t.Fatal("legacy primary fence (peers assumed) admitted") + } + if r.listener != nil || r.dual != nil { + t.Fatal("an inbound listener was created") + } + for _, a := range []string{addr, dual} { + if err := ingressPortReleased(a); err != nil { + t.Fatal(err) + } + } + if err := r.FenceAsPrimaryWithPeers(4, false); err != nil { + t.Fatalf("RF1 primary refused: %v", err) + } + if r.listener != nil || r.dual != nil { + t.Fatal("the RF1 primary role opened an inbound listener") + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go b/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go index e355245935..bf0e7a71f7 100644 --- a/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go +++ b/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go @@ -1,7 +1,9 @@ package main import ( + "context" "os" + "os/exec" "path/filepath" "strings" "testing" @@ -148,60 +150,54 @@ func TestDurableStartup_Issue51_SmartWALTornTailRecovers(t *testing.T) { } } -// walstore interim: the same mid-history -// corruption on a walstore volume does not become an outage: startup is -// ready, and the durable status carries the typed warning. -func TestDurableStartup_Issue51_WALStoreHoleIsAWarningNotAnOutage(t *testing.T) { - root := t.TempDir() - cfg := durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root, BlockSize: 4096, NumBlocks: 16} - path := filepath.Join(root, "v1.bin") - // A crashed walstore: entries synced, nothing checkpointed (the file - // as it is right after Sync; a clean close would checkpoint). - s, err := storage.CreateWALStore(path, 16, 4096) - if err != nil { - t.Fatal(err) - } - s.DisableAutoFlushForRecoveryTest() - for i := uint32(0); i < 4; i++ { - data := make([]byte, 4096) - data[0] = byte(0xD0 + i) - if _, err := s.Write(i, data); err != nil { +// V3 replaces the legacy warning-only recovery policy with nonce-bound, +// contiguous WAL recovery. Corruption below strict W must block readiness. +// The old v2 warning control is retained in walstore_midhistory_hole_test.go. +func TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness(t *testing.T) { + const childEnv = "SWBLOCK_V3_STARTUP_CRASH_PATH" + if path := os.Getenv(childEnv); path != "" { + s, err := storage.CreateWALStoreWithOptions(path, 16, 4096, storage.WALStoreOptions{WMode: storage.WModeStrict}) + if err != nil { t.Fatal(err) } - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - crashed, err := os.ReadFile(path) - if err != nil { - t.Fatal(err) - } - _ = s.Close() - // Corrupt a payload byte of the second entry (walstore's WAL starts at - // 4096; a one-block entry is 38+4096 bytes). - crashed[4096+(38+4096)+38+100] ^= 0xFF - if err := os.WriteFile(path, crashed, 0o644); err != nil { - t.Fatal(err) - } - dp, err := durable.NewDurableProvider(cfg, healthyView{}) - if err != nil { - t.Fatal(err) - } - defer dp.Close() - h := &spyHost{} - outcome, evidence, err := openAndRecoverDurable(dp, h, "v1", 5*time.Second) - if outcome != durableStartupReady || len(h.reported) != 0 { - t.Fatalf("walstore hole: outcome=%v reported=%v evidence=%q err=%v; want ready (no outage)", outcome, h.reported, evidence, err) - } - warned := false - for _, st := range dp.DurableStatuses() { - for _, w := range st.Warnings { - if strings.HasPrefix(w, storage.WarningWALHoleSuspected+":") { - warned = st.HolesSuspected == 1 + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 4; i++ { + data := make([]byte, 4096) + data[0] = byte(0xd0 + i) + if _, err := s.Write(i, data); err != nil { + t.Fatal(err) } } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + os.Exit(0) // deliberately no Close/checkpoint; OS releases the owner lock } - if !warned { - t.Fatalf("durable statuses %+v; want the %s warning, counted once", dp.DurableStatuses(), storage.WarningWALHoleSuspected) + root := t.TempDir() + path := filepath.Join(root, "v1.bin") + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness$") + cmd.Env = append(os.Environ(), childEnv+"="+path) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("crash fixture: %v\n%s", err, out) + } + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + at := int64(8192 + (70 + 4096) + 62 + 100) // v3 second record payload + b := make([]byte, 1) + _, re := f.ReadAt(b, at) + b[0] ^= 0xff + _, we := f.WriteAt(b, at) + ce := f.Close() + if re != nil || we != nil || ce != nil { + t.Fatal(re, we, ce) + } + cfg := durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root, BlockSize: 4096, NumBlocks: 16} + outcome, h := startAfterCorruption(t, cfg) + if outcome != durableStartupFaulted || len(h.reported) != 1 || h.reported[0] != volume.UnhealthyWALCorrupt || len(h.blocked) == 0 { + t.Fatalf("committed hole: outcome=%v reported=%v blocked=%v; want wal_corrupt and blocked", outcome, h.reported, h.blocked) } } diff --git a/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go b/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go new file mode 100644 index 0000000000..332bb0b8ff --- /dev/null +++ b/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go @@ -0,0 +1,130 @@ +package main + +import ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "strconv" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestExistingDurableVolumeIgnoresCreateGeometry(t *testing.T) { + root := t.TempDir() + s, err := storage.CreateWALStore(filepath.Join(root, "v1.bin"), 16, 4096) + if err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{0x73}, 4096) + if _, err = s.Write(0, want); err != nil { + s.Close() + t.Fatal(err) + } + if _, err = s.Sync(); err != nil { + s.Close() + t.Fatal(err) + } + if err = s.Close(); err != nil { + t.Fatal(err) + } + args := append(phase150RequiredBlockvolumeArgs(), "--volume-id=v1", "--durable-root="+root, "--durable-impl=walstore", "--durable-blocks=4294967295", "--durable-blocksize=8192") + f, err := parseFlags(args) + if err != nil { + t.Fatalf("existing storage must ignore create-only geometry: %v", err) + } + blocks, blockSize, err := durableCreateGeometry(f) + if err != nil { + t.Fatal(err) + } + if blocks != 0 { + t.Fatal("existing file must select open-only mode") + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplName(f.durableImpl), StorageRoot: f.durableRoot, NumBlocks: blocks, BlockSize: blockSize}, healthyView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + result, _, err := openAndRecoverDurable(p, &spyHost{}, "v1", 5*time.Second) + if err != nil || result != durableStartupReady { + t.Fatalf("existing recovery: %v %v", result, err) + } + st, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if st.NumBlocks() != 16 || st.BlockSize() != 4096 { + t.Fatalf("existing geometry changed: %d x %d", st.NumBlocks(), st.BlockSize()) + } + got := make([]byte, 4096) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err = b.Read(context.Background(), 0, got); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatal("existing bytes changed") + } +} + +func TestExistingDurableVolumeDisappearsDoesNotCreateFromIgnoredFlags(t *testing.T) { + if strconv.IntSize < 64 { + t.Skip("64-bit CLI uint overflow case") + } + for _, impl := range []durable.ImplName{durable.ImplWALStore, durable.ImplWALStoreChunk} { + t.Run(string(impl), func(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "v1.bin") + s, err := storage.CreateWALStore(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + if err = s.Close(); err != nil { + t.Fatal(err) + } + args := append(phase150RequiredBlockvolumeArgs(), "--volume-id=v1", "--durable-root="+root, "--durable-impl="+string(impl), "--durable-blocks=4294967297") + if impl == durable.ImplWALStoreChunk { + args = append(args, "--chunk-filer=127.0.0.1:18888") + } + f, err := parseFlags(args) + if err != nil { + t.Fatal(err) + } + blocks, bs, err := durableCreateGeometry(f) + if err != nil { + t.Fatal(err) + } + if blocks != 0 { + t.Fatal("not open-only") + } + if err = os.Remove(path); err != nil { + t.Fatal(err) + } + if _, _, err = durableCreateGeometry(f); err == nil { + t.Fatal("fresh recheck accepted original overflowing count") + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: impl, StorageRoot: root, NumBlocks: blocks, BlockSize: bs, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { + return nil, errors.New("unexpected remote access for missing open-only volume") + }}, healthyView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + if _, err = p.EnsureStorage("v1"); err == nil { + t.Fatal("created replacement from ignored flags") + } + if _, err = os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("replacement file exists: %v", err) + } + if _, err = os.Stat(path + ".chunkfresh"); !os.IsNotExist(err) { + t.Fatalf("open-only refusal left a fresh marker: %v", err) + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/hydration_flags_test.go b/seaweed-block/cmd/blockvolume/hydration_flags_test.go new file mode 100644 index 0000000000..6d37a85eb7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/hydration_flags_test.go @@ -0,0 +1,16 @@ +package main + +import "testing" + +func TestChunkHydrationFlagsAreConfigurable(t *testing.T) { + base := append(phase150RequiredBlockvolumeArgs(), "--durable-root=hydration-test", "--durable-impl=walstore-chunk", "--chunk-filer=x:1") + f, err := parseFlags(append(base, "--chunk-hydration-workers=3", "--chunk-hydration-queue-depth=17")) + if err != nil || f.chunk.hydrationWorkers != 3 || f.chunk.hydrationQueueDepth != 17 { + t.Fatalf("hydration limits: %+v err=%v", f.chunk, err) + } + for _, flag := range []string{"--chunk-hydration-workers=0", "--chunk-hydration-workers=65", "--chunk-hydration-queue-depth=0", "--chunk-hydration-queue-depth=65537"} { + if _, err := parseFlags(append(base, flag)); err == nil { + t.Fatalf("invalid hydration limit accepted: %s", flag) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index e1fefb3756..2516140cb2 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -27,6 +27,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/nvme" "github.com/seaweedfs/seaweed-block/core/frontend/nvmerdma" "github.com/seaweedfs/seaweed-block/core/frontend/ublk" + "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/host/volume" "github.com/seaweedfs/seaweed-block/core/recovery" "github.com/seaweedfs/seaweed-block/core/replication" @@ -193,7 +194,9 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)") fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: automatic cut once this long has passed since the last successful cut; 0 (default) disables the timer, e.g. 15m as a host-loss safety net") fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)") - fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", defaultChunkDirtyThreshold, "walstore-chunk: bound on one cut's barrier copy, in chunks; never triggers a cut; 0 = unbounded") + fs.IntVar(&f.chunk.hydrationWorkers, "chunk-hydration-workers", 2, "walstore-chunk: concurrent lazy chunk fetches per volume (1..64)") + fs.IntVar(&f.chunk.hydrationQueueDepth, "chunk-hydration-queue-depth", 64, "walstore-chunk: distinct queued/in-flight hydration chunks per volume (1..65536)") + fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", defaultChunkDirtyThreshold, "walstore-chunk: number of candidate chunks above which a cut pre-copies (stages) chunks before its barrier, in rounds of this size; copy-before-write copies the rest outside the barrier; never triggers a cut; 0 = no pre-copy") fs.BoolVar(&f.chunk.controlEndpoint, "chunk-control-endpoint", false, "walstore-chunk: expose the /chunk/* control routes (cut, snapshot, snapshots, snapshot/delete, detach) on the status HTTP listener; off by default; loopback-only like the listener") fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)") fs.UintVar(&f.durableBlockSize, "durable-blocksize", 4096, "block size in bytes on first create") @@ -270,6 +273,11 @@ func parseFlags(args []string) (flags, error) { return flags{}, fmt.Errorf("--durable-wal-recovery-test-disable-flusher requires --durable-impl=walstore") } } + if f.durableRoot != "" { + if _, _, err := durableCreateGeometry(f); err != nil { + return flags{}, err + } + } if f.iscsiCHAPUser == "" { f.iscsiCHAPUser = os.Getenv("SW_BLOCK_ISCSI_CHAP_USERNAME") } @@ -523,22 +531,26 @@ type nvmeReadyLine struct { SubsysNQN string `json:"subsys_nqn"` } +// durableCreateGeometry leaves existing volumes in open-only mode. If the +// observed file disappears before Open, NumBlocks=0 prevents a replacement +// from being created using narrowed or otherwise ignored CLI values. +func durableCreateGeometry(f flags) (uint32, int, error) { + path := filepath.Join(f.durableRoot, f.volumeID+".bin") + if _, err := os.Stat(path); err == nil { + return 0, 0, nil + } else if !os.IsNotExist(err) { + return 0, 0, fmt.Errorf("durable volume geometry: %w", err) + } + if err := geometry.ValidateBlockGeometry(uint64(f.durableBlocks), uint64(f.durableBlockSize)); err != nil { + return 0, 0, fmt.Errorf("--durable-blocks/--durable-blocksize: %w", err) + } + return uint32(f.durableBlocks), int(f.durableBlockSize), nil +} + func run(f flags) int { readyCh := make(chan adapter.AssignmentInfo, 16) - h, err := volume.New(volume.Config{ - MasterAddr: f.masterAddr, - ServerID: f.serverID, - VolumeID: f.volumeID, - ReplicaID: f.replicaID, - DataAddr: f.dataAddr, - CtrlAddr: f.ctrlAddr, - HeartbeatInterval: f.hbInterval, - RecoverTimeout: f.recoverTimeout, - ReadyMarker: readyCh, - EnableT1Readiness: f.enableT1Readiness, - WorkspaceLease: f.workspaceLease, - }) + h, err := volume.New(hostConfig(f, readyCh)) if err != nil { fmt.Fprintln(os.Stderr, "blockvolume:", err) return 1 @@ -591,11 +603,12 @@ func run(f flags) int { var durableProv *durable.DurableProvider var workspaceRemoteFor func(string) (storage.ChunkRemote, error) if f.durableRoot != "" { + blocks, blockSize, geometryErr := durableCreateGeometry(f) cfg := durable.ProviderConfig{ Impl: durable.ImplName(f.durableImpl), StorageRoot: f.durableRoot, - BlockSize: int(f.durableBlockSize), - NumBlocks: uint32(f.durableBlocks), + BlockSize: blockSize, + NumBlocks: blocks, WALRetentionLSNs: f.walRetentionLSNs, WALMultiBlockRecords: f.durableWALMultiBlockRecords, WALRecoveryTestDisableFlusher: f.durableWALRecoveryTestDisableFlusher, @@ -607,6 +620,8 @@ func run(f flags) int { cfg.ChunkCaptureInterval = f.chunk.captureInterval cfg.ChunkDirtyThreshold = f.chunk.dirtyThreshold cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency + cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers + cfg.ChunkHydrationQueueDepth = f.chunk.hydrationQueueDepth cfg.ChunkHolder = chunkHolder(f) if chunkErr == nil { cfg.ChunkRemoteFor = chunk.remoteFor @@ -615,7 +630,11 @@ func run(f flags) int { defer chunk.close() } } - dp, err := durable.NewDurableProvider(cfg, h.ProjectionView()) + var dp *durable.DurableProvider + err := geometryErr + if err == nil { + dp, err = durable.NewDurableProvider(cfg, h.ProjectionView()) + } if chunkErr != nil { err = chunkErr } @@ -871,8 +890,7 @@ func run(f flags) int { // No replication socket exists until a master assignment includes // replica slots. The role gate starts/fences both lanes before admission. - replListen = &replicationIngress{addr: f.dataAddr, store: store, - volumeID: f.volumeID, floorPath: replicaFloorPath(f), dualLane: f.recoveryMode == "dual-lane"} + replListen = newReplicationIngress(f, store) if err := h.SetSelfFence(replListen); err != nil { fmt.Fprintln(os.Stderr, "blockvolume: replica listener role:", err) replListen.Stop() @@ -1168,6 +1186,9 @@ func run(f flags) int { select { case <-shutdownCtx.Done(): case request := <-leaseRequests: + // The lease guard fenced and asks for the drain; it logs its cause as + // "workspace lease: fenced ...". Say here that this is why we stop (#205). + fmt.Fprintln(os.Stderr, "blockvolume: stopping: the workspace lease guard fenced and requested the drain") leaseStop = &request case err := <-leaseDone: fmt.Fprintln(os.Stderr, "blockvolume: workspace lease stopped:", err) @@ -1430,6 +1451,24 @@ func deriveDualLaneAddr(addr string) (string, error) { // replicaFloorPath is where the replica's epoch floor record lives (G1): // beside the volume's durable files, or "" for non-durable memback runs. +// hostConfig is the volume host's configuration from the flags. +func hostConfig(f flags, readyCh chan<- adapter.AssignmentInfo) volume.Config { + return volume.Config{ + MasterAddr: f.masterAddr, + ServerID: f.serverID, + VolumeID: f.volumeID, + ReplicaID: f.replicaID, + DataAddr: f.dataAddr, + CtrlAddr: f.ctrlAddr, + HeartbeatInterval: f.hbInterval, + RecoverTimeout: f.recoverTimeout, + ReadyMarker: readyCh, + EnableT1Readiness: f.enableT1Readiness, + WorkspaceLease: f.workspaceLease, + RF1Only: rf1Only(f), + } +} + func replicaFloorPath(f flags) string { if f.durableRoot == "" { return "" diff --git a/seaweed-block/cmd/blockvolume/replication_ingress.go b/seaweed-block/cmd/blockvolume/replication_ingress.go index 4117fbad45..89ab03da31 100644 --- a/seaweed-block/cmd/blockvolume/replication_ingress.go +++ b/seaweed-block/cmd/blockvolume/replication_ingress.go @@ -19,10 +19,33 @@ type replicationIngress struct { addr, volumeID, floorPath string store storage.LogicalStorage dualLane bool - listener *transport.ReplicaListener - dual net.Listener - cancel context.CancelFunc - closed bool + // rf1Only, when set, refuses every role with replica slots with this reason + // (walstore-chunk). The host latches the error: no role is adopted, not Healthy. + rf1Only string + listener *transport.ReplicaListener + dual net.Listener + cancel context.CancelFunc + closed bool +} + +// newReplicationIngress is the volume's ingress from its flags; an RF1-only +// volume (walstore-chunk) refuses every role with replica slots. +func newReplicationIngress(f flags, store storage.LogicalStorage) *replicationIngress { + r := &replicationIngress{addr: f.dataAddr, store: store, volumeID: f.volumeID, + floorPath: replicaFloorPath(f), dualLane: f.recoveryMode == "dual-lane"} + r.rf1Only = rf1Only(f) + return r +} + +// rf1Only is the single-replica rule of this volume, "" when replication is +// allowed. The host refuses assignments with replica slots (installed at +// construction, before any fact is applied or replayed); the ingress gate +// refuses the same roles again. +func rf1Only(f flags) string { + if f.durableImpl == "walstore-chunk" { + return chunkRF1Reason + } + return "" } func (r *replicationIngress) FenceAsPrimary(epoch uint64) error { @@ -43,6 +66,9 @@ func (r *replicationIngress) FenceAsPrimaryWithPeers(epoch uint64, hasPeers bool r.stopLocked(true) return nil } + if r.rf1Only != "" { + return fmt.Errorf("volume %s refuses a primary role with replica peers at epoch %d: %s", r.volumeID, epoch, r.rf1Only) + } return r.roleLocked(epoch, true) } func (r *replicationIngress) AdmitAsReplica(epoch uint64) error { @@ -51,6 +77,9 @@ func (r *replicationIngress) AdmitAsReplica(epoch uint64) error { if r.closed { return fmt.Errorf("replication ingress closed") } + if r.rf1Only != "" { + return fmt.Errorf("volume %s refuses a replica role at epoch %d: %s", r.volumeID, epoch, r.rf1Only) + } return r.roleLocked(epoch, false) } func (r *replicationIngress) roleLocked(epoch uint64, primary bool) error { diff --git a/seaweed-block/cmd/blockvolume/volume_size_admission_test.go b/seaweed-block/cmd/blockvolume/volume_size_admission_test.go new file mode 100644 index 0000000000..495e326770 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/volume_size_admission_test.go @@ -0,0 +1,27 @@ +package main + +import ( + "strconv" + "strings" + "testing" +) + +func TestDurableCreateFlagsValidateOriginalGeometry(t *testing.T) { + if strconv.IntSize < 64 { + t.Skip("64-bit CLI uint overflow case") + } + for _, blocks := range []string{"4294967297", "18446744073709551615"} { + args := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-blocks="+blocks) + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "durable-blocks") { + t.Fatalf("blocks %s: %v", blocks, err) + } + } + args := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-blocks=4294967295", "--durable-blocksize=4096") + if _, err := parseFlags(args); err != nil { + t.Fatal(err) + } + args = append(args, "--durable-blocksize=8192") + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("oversize geometry: %v", err) + } +} diff --git a/seaweed-block/cmd/sparrow/bootstrap_test.go b/seaweed-block/cmd/sparrow/bootstrap_test.go index 5f226fbd33..84d855faaa 100644 --- a/seaweed-block/cmd/sparrow/bootstrap_test.go +++ b/seaweed-block/cmd/sparrow/bootstrap_test.go @@ -430,3 +430,10 @@ func TestBootstrap_Close_Idempotent(t *testing.T) { t.Fatalf("second Close must be idempotent: %v", err) } } + +func (s *indexFailingAuthorityStore) PutWorkspaceLostRanges(string, []authority.WorkspaceLostRange) error { + return nil +} +func (s *indexFailingAuthorityStore) LoadWorkspaceLostRanges() (map[string][]authority.WorkspaceLostRange, []error, error) { + return nil, nil, nil +} diff --git a/seaweed-block/cmd/sparrow/main.go b/seaweed-block/cmd/sparrow/main.go index cb1dc80d1d..bdcad2a099 100644 --- a/seaweed-block/cmd/sparrow/main.go +++ b/seaweed-block/cmd/sparrow/main.go @@ -26,15 +26,15 @@ type options struct { calibrate bool persistDemo bool persistDir string - authorityStore string - s5Bootstrap bool - s7RestartSmoke bool + authorityStore string + s5Bootstrap bool + s7RestartSmoke bool } type demoResult struct { - Demo string `json:"demo"` - Pass bool `json:"pass"` - Reason string `json:"reason,omitempty"` + Demo string `json:"demo"` + Pass bool `json:"pass"` + Reason string `json:"reason,omitempty"` Projection engine.ReplicaProjection `json:"projection"` } @@ -221,7 +221,10 @@ func runValidationPass(state *ops.State, volumeID string, pubOpts ...authority.P _, _ = primaryStore.Write(i, data) } _, _ = primaryStore.Sync() - blocks := primaryStore.AllBlocks() + blocks, err := primaryStore.AllBlocks() + if err != nil { + return nil, fmt.Errorf("snapshot primary: %w", err) + } _, _, pH := primaryStore.Boundaries() for lba, data := range blocks { _ = replicaStore.ApplyEntry(lba, data, pH) diff --git a/seaweed-block/cmd/sparrow/persist.go b/seaweed-block/cmd/sparrow/persist.go index 0bd7e648f8..c4e021c7b2 100644 --- a/seaweed-block/cmd/sparrow/persist.go +++ b/seaweed-block/cmd/sparrow/persist.go @@ -39,15 +39,34 @@ func runPersistDemo(opts options) int { } path := filepath.Join(dir, "sparrow-persist.dat") + // The owned COW map is a file. Refuse an unexpected directory before + // changing the prior demo; never recursively remove a caller's directory. + mapPath := path + ".chunkmap" + if st, err := os.Lstat(mapPath); err == nil && st.IsDir() { + fmt.Fprintln(os.Stderr, "sparrow: persist demo: unexpected directory at map file path") + return 3 + } else if err != nil && !os.IsNotExist(err) { + fmt.Fprintf(os.Stderr, "sparrow: persist demo: inspect map: %v\n", err) + return 3 + } + // Demo is meant to be reproducible: every invocation creates a // fresh file. If a previous demo left bytes behind, remove them // before Round 1 so CreateWALStore's O_EXCL doesn't collide. - // We only remove the demo file we know we own — never the dir. + // Only the named demo file and its owned map sidecar are retired; the + // supplied parent directory and unrelated siblings are preserved. if err := os.Remove(path); err != nil && !os.IsNotExist(err) { fmt.Fprintf(os.Stderr, "sparrow: persist demo: cannot remove prior file %s: %v\n", path, err) return 3 } + // V3 owns a COW map file at this exact sibling path. + // Removing only the volume would leave the next O_EXCL map create blocked. + if err := os.Remove(mapPath); err != nil && !os.IsNotExist(err) { + fmt.Fprintf(os.Stderr, "sparrow: persist demo: cannot remove prior map: %v\n", err) + return 3 + } + const ( numBlocks = 16 blockSize = 4096 diff --git a/seaweed-block/cmd/sparrow/persist_sidecar_test.go b/seaweed-block/cmd/sparrow/persist_sidecar_test.go new file mode 100644 index 0000000000..08b305adfc --- /dev/null +++ b/seaweed-block/cmd/sparrow/persist_sidecar_test.go @@ -0,0 +1,52 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +func TestRunPersistDemoRetiresOnlyItsOwnedMap(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "sparrow-persist.dat") + if err := os.WriteFile(path, []byte("prior demo"), 0600); err != nil { + t.Fatal(err) + } + stale := path + ".chunkmap" + if err := os.WriteFile(stale, []byte("stale map"), 0600); err != nil { + t.Fatal(err) + } + other := path + ".unrelated" + if err := os.WriteFile(other, []byte("keep"), 0600); err != nil { + t.Fatal(err) + } + if code := runPersistDemo(options{json: true, persistDemo: true, persistDir: dir}); code != 0 { + t.Fatalf("demo exit=%d", code) + } + if got, err := os.ReadFile(stale); err == nil && string(got) == "stale map" { + t.Fatal("prior map file survives") + } else if err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + if got, err := os.ReadFile(other); err != nil || string(got) != "keep" { + t.Fatalf("unrelated sibling changed: %q %v", got, err) + } +} + +func TestRunPersistDemoRefusesUnexpectedMapDirectory(t *testing.T) { + dir := t.TempDir() + mapPath := filepath.Join(dir, "sparrow-persist.dat.chunkmap") + if err := os.Mkdir(mapPath, 0700); err != nil { + t.Fatal(err) + } + keep := filepath.Join(mapPath, "keep") + if err := os.WriteFile(keep, []byte("unrecognized directory"), 0600); err != nil { + t.Fatal(err) + } + if code := runPersistDemo(options{json: true, persistDemo: true, persistDir: dir}); code != 3 { + t.Fatalf("unexpected map directory exit=%d want3", code) + } + if got, err := os.ReadFile(keep); err != nil || string(got) != "unrecognized directory" { + t.Fatalf("unexpected directory changed: %q %v", got, err) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go new file mode 100644 index 0000000000..e9e52d078c --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go @@ -0,0 +1,60 @@ +package main + +import ( + "context" + "fmt" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type manifestFixtureFiler struct { + chunkstore.Filer + mu sync.Mutex + blobs map[string][]byte +} + +func newManifestFixtureFiler(f chunkstore.Filer) *manifestFixtureFiler { + return &manifestFixtureFiler{Filer: f, blobs: map[string][]byte{}} +} + +func (f *manifestFixtureFiler) Put(_ context.Context, b []byte) (string, error) { + f.mu.Lock() + defer f.mu.Unlock() + id := fmt.Sprintf("fixture-%d", len(f.blobs)) + f.blobs[id] = append([]byte(nil), b...) + return id, nil +} + +func (f *manifestFixtureFiler) Get(_ context.Context, id string) ([]byte, error) { + f.mu.Lock() + defer f.mu.Unlock() + b, ok := f.blobs[id] + if !ok { + return nil, chunkstore.ErrNotFound + } + return append([]byte(nil), b...), nil +} + +func prepareFixtureHead(t *testing.T, f *manifestFixtureFiler, h storage.ChunkHead) storage.ChunkHead { + t.Helper() + ctx := context.Background() + r, err := chunkstore.NewChunkRemote(f, f, defaultChunkPathCLI+"/v1") + if err != nil { + t.Fatal(err) + } + h, intents, err := r.PrepareManifest(ctx, storage.ChunkHead{}, h, 8*4096) + if err != nil { + t.Fatal(err) + } + // These fixtures hand the completed cut directly to the catalog; the + // snapshot/fork operations establish their own reachability intents. + for _, id := range intents { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + return h +} diff --git a/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go b/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go index 705e2ca9d5..b40b03134e 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go +++ b/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go @@ -41,10 +41,11 @@ func (f *failingFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.E func TestOpsChunk_RetainReportsPartialProgress(t *testing.T) { ctx := context.Background() ff := &failingFiler{MemFiler: chunkstore.NewMemFiler()} + fm := newManifestFixtureFiler(ff) prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return ff, func() error { return nil }, nil } + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return fm, func() error { return nil }, nil } t.Cleanup(func() { dialChunkFiler = prev }) - cat, err := chunkstore.NewCatalog(ff, defaultChunkPathCLI) + cat, err := chunkstore.NewCatalog(fm, defaultChunkPathCLI) if err != nil { t.Fatal(err) } @@ -54,6 +55,7 @@ func TestOpsChunk_RetainReportsPartialProgress(t *testing.T) { base := time.Now().Add(-48 * time.Hour) head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + head = prepareFixtureHead(t, fm, head) for i := 0; i < 4; i++ { at := base.Add(time.Duration(i) * time.Minute) cat.SetClock(func() time.Time { return at }) diff --git a/seaweed-block/cmd/sw-block/chunk_retain_test.go b/seaweed-block/cmd/sw-block/chunk_retain_test.go index 3623088e6c..0dd4633cfd 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain_test.go +++ b/seaweed-block/cmd/sw-block/chunk_retain_test.go @@ -44,7 +44,7 @@ func TestOpsChunk_SnapshotPinAndExpires(t *testing.T) { // dry-run, apply, and see the accounting follow. func TestOpsChunk_UsageAndRetain(t *testing.T) { ctx := context.Background() - mem := chunkstore.NewMemFiler() + mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) prev := dialChunkFiler dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } t.Cleanup(func() { dialChunkFiler = prev }) @@ -59,6 +59,7 @@ func TestOpsChunk_UsageAndRetain(t *testing.T) { cat.SetClock(func() time.Time { return old }) head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + head = prepareFixtureHead(t, mem, head) for i := 0; i < 5; i++ { if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: fmt.Sprintf("s%d", i), RequestID: fmt.Sprintf("r%d", i), Class: chunkstore.SnapshotClassSemantic}, head); err != nil { t.Fatal(err) diff --git a/seaweed-block/cmd/sw-block/chunk_show_test.go b/seaweed-block/cmd/sw-block/chunk_show_test.go index 22b3eaa32a..6a36ac02a5 100644 --- a/seaweed-block/cmd/sw-block/chunk_show_test.go +++ b/seaweed-block/cmd/sw-block/chunk_show_test.go @@ -13,7 +13,7 @@ import ( // either is null when it does not exist (B9 W2 appendix). func TestOpsChunk_Show(t *testing.T) { ctx := context.Background() - mem := chunkstore.NewMemFiler() + mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) prev := dialChunkFiler dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } t.Cleanup(func() { dialChunkFiler = prev }) @@ -27,6 +27,7 @@ func TestOpsChunk_Show(t *testing.T) { } head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + head = prepareFixtureHead(t, mem, head) if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, head); err != nil { t.Fatal(err) } diff --git a/seaweed-block/cmd/sw-block/chunk_test.go b/seaweed-block/cmd/sw-block/chunk_test.go index 9b96c7f623..39347d09fa 100644 --- a/seaweed-block/cmd/sw-block/chunk_test.go +++ b/seaweed-block/cmd/sw-block/chunk_test.go @@ -157,6 +157,15 @@ func TestOpsChunk_FilerCommands(t *testing.T) { } head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "r1", RemoteLSN: 42, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + manifestMem := newManifestFixtureFiler(mem) + cat, err = chunkstore.NewCatalog(manifestMem, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return manifestMem, func() error { return nil }, nil + } + head = prepareFixtureHead(t, manifestMem, head) if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, head); err != nil { t.Fatal(err) } diff --git a/seaweed-block/cmd/sw-block/internal/v2legacy/real_store_legacy_test.go b/seaweed-block/cmd/sw-block/internal/v2legacy/real_store_legacy_test.go new file mode 100644 index 0000000000..b5f4388b8f --- /dev/null +++ b/seaweed-block/cmd/sw-block/internal/v2legacy/real_store_legacy_test.go @@ -0,0 +1,103 @@ +//go:build swblock_format_v3_test + +package v2legacy + +import ( + "encoding/binary" + "errors" + "github.com/seaweedfs/seaweed-block/core/storage" + "os" + "path/filepath" + "testing" +) + +// TODO(format-v3 row 14a): retain raw-codec controls in the default suite; +// these real v2-engine fixtures remain explicit in the tagged migration suite. +func TestReadSuperblockRefusesOtherFormats(t *testing.T) { + path := filepath.Join(t.TempDir(), "v2") + s, err := storage.CreateLegacyWALStoreTest(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + sb, err := ReadSuperblock(raw[:SuperblockSize]) + if err != nil || sb.WALOffset != SuperblockSize || sb.BlockSize != 4096 { + t.Fatalf("real v2 superblock: %+v, %v", sb, err) + } + impl2 := append([]byte(nil), raw[:SuperblockSize]...) + binary.LittleEndian.PutUint32(impl2[92:], 2) + if _, err := ReadSuperblock(impl2); !errors.Is(err, ErrImplUnsupported) { + t.Fatalf("impl version 2: err = %v, want ErrImplUnsupported", err) + } + v3 := append([]byte(nil), raw[:SuperblockSize]...) + binary.LittleEndian.PutUint16(v3[4:], 3) + if _, err := ReadSuperblock(v3); !errors.Is(err, ErrNotV2) { + t.Fatalf("version 3: err = %v, want ErrNotV2", err) + } +} + +// Real v2 stores: a cleanly closed, flushed store scans clean; a store with +// synced records that were never flushed (a crash) refuses, even though +// its superblock may say head = tail (the #156 shape: bounds not persisted +// by an ordinary Sync). +func TestScanCleanOnRealV2Stores(t *testing.T) { + scan := func(t *testing.T, path string) []Finding { + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + sb, err := ReadSuperblock(raw[:SuperblockSize]) + if err != nil { + t.Fatal(err) + } + return ScanClean(raw[SuperblockSize:SuperblockSize+sb.WALSize], sb.WALCheckpointLSN) + } + blk := make([]byte, 4096) + t.Run("cleanly closed", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "clean") + s, err := storage.CreateLegacyWALStoreTest(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + for lba := uint32(0); lba < 4; lba++ { + if _, err := s.Write(lba, blk); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + if f := scan(t, path); len(f) != 0 { + t.Fatalf("a cleanly closed v2 store refused: %+v", f[0]) + } + }) + t.Run("synced, never flushed", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "dirty") + s, err := storage.CreateLegacyWALStoreTest(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + for lba := uint32(0); lba < 2; lba++ { + if _, err := s.Write(lba, blk); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if f := scan(t, path); len(f) == 0 { + t.Fatal("synced unflushed v2 records scanned clean") + } + _ = s.Close() + }) +} diff --git a/seaweed-block/cmd/sw-block/internal/v2legacy/v2legacy.go b/seaweed-block/cmd/sw-block/internal/v2legacy/v2legacy.go new file mode 100644 index 0000000000..794a053022 --- /dev/null +++ b/seaweed-block/cmd/sw-block/internal/v2legacy/v2legacy.go @@ -0,0 +1,188 @@ +// Package v2legacy is the frozen v2/impl1 reader used only by the offline +// migration tool (`sw-block migrate-v3`, format bump v3, DESIGN r17.4 +// section 10.1; plan row 13). It is a copy of the v2 superblock layout and +// the v2 WAL entry framing as they stand before the format bump, kept here +// so that the v3 open code holds no legacy reader and row 14 can delete the +// legacy production code. Nothing here writes, recovers or replays: the +// scan only decides whether the tool must refuse. +package v2legacy + +import ( + "encoding/binary" + "errors" + "fmt" + "hash/crc32" +) + +// SuperblockSize is the v2 superblock region at offset 0; the v2 WAL starts +// right after it. +const SuperblockSize = 4096 + +const ( + magic = "SWBK" + version = 2 + implWALStore = 1 + implVersion1 = 1 +) + +var ( + // ErrNotV2 is any offset-0 content that is not a v2 superblock. + ErrNotV2 = errors.New("v2legacy: offset 0 is not a v2 superblock") + // ErrImplUnsupported is a v2 superblock of another impl or impl version + // (impl 2, C12, is refused by the tool, DESIGN 10). + ErrImplUnsupported = errors.New("v2legacy: not walstore impl version 1") +) + +// Superblock is the frozen v2 superblock (core/storage/superblock.go at +// format version 2). +type Superblock struct { + Version uint16 + Flags uint16 + UUID [16]byte + VolumeSize uint64 + ExtentSize uint32 + BlockSize uint32 + WALOffset uint64 + WALSize uint64 + WALHead uint64 + WALTail uint64 + WALCheckpointLSN uint64 + CreatedAt uint64 + ImplKind uint8 + ImplVersion uint32 +} + +// ReadSuperblock decodes and validates a v2/impl1 superblock (precondition +// 2: magic, version 2, ImplKind walstore, ImplVersion 1). +func ReadSuperblock(buf []byte) (Superblock, error) { + if len(buf) < SuperblockSize { + return Superblock{}, fmt.Errorf("%w: short header (%d bytes)", ErrNotV2, len(buf)) + } + le := binary.LittleEndian + if string(buf[0:4]) != magic { + return Superblock{}, fmt.Errorf("%w: bad magic", ErrNotV2) + } + var sb Superblock + sb.Version = le.Uint16(buf[4:]) + if sb.Version != version { + return Superblock{}, fmt.Errorf("%w: version %d", ErrNotV2, sb.Version) + } + sb.Flags = le.Uint16(buf[6:]) + copy(sb.UUID[:], buf[8:24]) + sb.VolumeSize = le.Uint64(buf[24:]) + sb.ExtentSize = le.Uint32(buf[32:]) + sb.BlockSize = le.Uint32(buf[36:]) + sb.WALOffset = le.Uint64(buf[40:]) + sb.WALSize = le.Uint64(buf[48:]) + sb.WALHead = le.Uint64(buf[56:]) + sb.WALTail = le.Uint64(buf[64:]) + sb.WALCheckpointLSN = le.Uint64(buf[72:]) + sb.CreatedAt = le.Uint64(buf[80:]) + sb.ImplKind = buf[88] + sb.ImplVersion = le.Uint32(buf[92:]) + switch { + case sb.VolumeSize == 0, sb.BlockSize == 0, sb.ExtentSize == 0, sb.WALSize == 0: + return Superblock{}, fmt.Errorf("%w: zero geometry field", ErrNotV2) + case sb.WALOffset != SuperblockSize: + return Superblock{}, fmt.Errorf("%w: WALOffset %d", ErrNotV2, sb.WALOffset) + case sb.VolumeSize%uint64(sb.BlockSize) != 0: + return Superblock{}, fmt.Errorf("%w: VolumeSize not block aligned", ErrNotV2) + } + if sb.ImplKind != implWALStore || sb.ImplVersion != implVersion1 { + return Superblock{}, fmt.Errorf("%w: ImplKind %d ImplVersion %d", ErrImplUnsupported, sb.ImplKind, sb.ImplVersion) + } + return sb, nil +} + +// The frozen v2 WAL entry framing (core/storage/wal_entry.go): a 30-byte +// prefix LSN(8) Reserved(8) Type(1) Flags(1) LBA(8) Length(4), then the +// payload (write, batch and padding only), then CRC32-IEEE(4) over prefix +// and payload, and EntrySize(4). +const ( + entryPrefix = 30 + entryHeader = 38 + + typeWrite = 0x01 + typeTrim = 0x02 + typeBarrier = 0x03 + typeBatch = 0x04 + typePadding = 0xFF +) + +// Finding is one offset of the WAL region that refuses the migration. +type Finding struct { + Offset uint64 // relative to the WAL region start + Type uint8 + LSN uint64 // the record's last LSN (a batch counts by its last) + Reason string + Covered bool // LSN <= checkpoint: not a refusal (reported for tests only) +} + +// ScanClean is precondition 3 of DESIGN 10.1: an exhaustive, +// refusal-biased scan of the whole v2 WAL region. It tries the frozen +// decoder at every byte offset, reading circularly so a record crossing the +// region end is tried too. An offset refuses when it decodes as a known +// type whose type-derived footprint (38 + Length for write, batch and +// padding; 38 for trim and barrier) fits in the region, whose CRC and +// EntrySize are valid, and whose last LSN is above checkpoint; or when a +// CRC-valid candidate of a known type cannot be classified (a zero or +// overflowing batch count). A CRC-valid record at or below the checkpoint +// is already in the extent and is ignored. It never runs recovery or +// replay. It returns the refusing findings, in offset order. +func ScanClean(wal []byte, checkpoint uint64) []Finding { + n := uint64(len(wal)) + var out []Finding + at := func(i uint64) byte { return wal[i%n] } + read := func(off, length uint64) []byte { + b := make([]byte, length) + for i := range b { + b[i] = at(off + uint64(i)) + } + return b + } + for off := uint64(0); off < n && n >= entryHeader; off++ { + typ := at(off + 16) + var payload bool + switch typ { + case typeWrite, typeBatch, typePadding: + payload = true + case typeTrim, typeBarrier: + default: + continue + } + prefix := read(off, entryPrefix) + length := uint64(binary.LittleEndian.Uint32(prefix[26:])) + footprint := uint64(entryHeader) + if payload { + footprint += length + } + if footprint > n { + continue // cannot be a record of this region + } + body := read(off, footprint) + dataEnd := footprint - 8 + if binary.LittleEndian.Uint32(body[dataEnd:]) != crc32.ChecksumIEEE(body[:dataEnd]) || + uint64(binary.LittleEndian.Uint32(body[dataEnd+4:])) != footprint { + continue + } + lsn := binary.LittleEndian.Uint64(body[0:]) + last := lsn + f := Finding{Offset: off, Type: typ} + if typ == typeBatch { + count := binary.LittleEndian.Uint64(body[8:]) + if count == 0 || lsn+count-1 < lsn { + f.LSN, f.Reason = lsn, "CRC-valid batch with an unclassifiable block count" + out = append(out, f) + continue + } + last = lsn + count - 1 + } + f.LSN = last + if last <= checkpoint { + continue // already in the extent + } + f.Reason = fmt.Sprintf("CRC-valid v2 record type %#x with LSN %d above the checkpoint %d", typ, last, checkpoint) + out = append(out, f) + } + return out +} diff --git a/seaweed-block/cmd/sw-block/internal/v2legacy/v2legacy_test.go b/seaweed-block/cmd/sw-block/internal/v2legacy/v2legacy_test.go new file mode 100644 index 0000000000..fd7871d803 --- /dev/null +++ b/seaweed-block/cmd/sw-block/internal/v2legacy/v2legacy_test.go @@ -0,0 +1,69 @@ +package v2legacy + +import ( + "encoding/binary" + "hash/crc32" + "testing" +) + +// Plan row 13a controls (DESIGN r17.4 section 10.1 precondition 3; owner +// claude03): the frozen v2 decoder and the exhaustive, refusal-biased scan. + +// encode is a test-only encoder of the frozen v2 framing. +func encode(lsn, reserved uint64, typ uint8, lba uint64, length uint32, data []byte) []byte { + b := make([]byte, entryPrefix+len(data)+8) + le := binary.LittleEndian + le.PutUint64(b[0:], lsn) + le.PutUint64(b[8:], reserved) + b[16] = typ + le.PutUint64(b[18:], lba) + le.PutUint32(b[26:], length) + copy(b[entryPrefix:], data) + end := entryPrefix + len(data) + le.PutUint32(b[end:], crc32.ChecksumIEEE(b[:end])) + le.PutUint32(b[end+4:], uint32(entryHeader+len(data))) + return b +} + +func region(n int, at int, recs ...[]byte) []byte { + w := make([]byte, n) + for _, r := range recs { + for i := range r { + w[(at+i)%n] = r[i] + } + at += len(r) + } + return w +} + +func write(lsn uint64) []byte { return encode(lsn, 0, typeWrite, 1, 64, make([]byte, 64)) } + +func TestScanCleanFindsEveryUnflushedV2RecordShape(t *testing.T) { + cases := []struct { + name string + wal []byte + checkpoint uint64 + refuse bool + }{ + {"an empty region", make([]byte, 4096), 0, false}, + {"a write above the checkpoint", region(4096, 100, write(5)), 4, true}, + {"a write at the checkpoint is in the extent", region(4096, 100, write(5)), 5, false}, + {"a record wrapping across the region end", region(4096, 4096-50, write(9)), 0, true}, + {"a trim whose affected range exceeds the region (footprint 38)", region(4096, 0, encode(7, 0, typeTrim, 0, 1<<30, nil)), 6, true}, + {"a barrier above the checkpoint", region(4096, 0, encode(7, 0, typeBarrier, 0, 0, nil)), 6, true}, + {"a batch counts by its last LSN", region(4096, 0, encode(3, 3, typeBatch, 0, 64, make([]byte, 64))), 4, true}, + {"a batch fully below the checkpoint", region(4096, 0, encode(3, 3, typeBatch, 0, 64, make([]byte, 64))), 5, false}, + {"a CRC-valid batch with a zero count is unclassifiable", region(4096, 0, encode(3, 0, typeBatch, 0, 64, make([]byte, 64))), 9, true}, + {"a record embedded in another record's payload", region(4096, 0, encode(2, 0, typeWrite, 1, uint32(len(write(9))), write(9))), 5, true}, + {"a corrupt CRC is no record", func() []byte { w := region(4096, 0, write(9)); w[40] ^= 0xFF; return w }(), 0, false}, + {"a record larger than the region cannot be one", encode(9, 0, typeWrite, 1, 100, make([]byte, 100))[:64], 0, false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := ScanClean(c.wal, c.checkpoint) + if (len(got) > 0) != c.refuse { + t.Fatalf("findings %+v, want refuse = %v", got, c.refuse) + } + }) + } +} diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index 2c2bd65dea..249ead1fac 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -77,13 +77,16 @@ func run(args []string, stdout, stderr io.Writer) int { fmt.Fprintln(stdout, buildinfo.Version("sw-block")) return ops.VolumeStatusExitOK } + if args[0] == "migrate-v3" { + return runMigrateV3(args[1:], stdout, stderr) + } if args[0] != "ops" { fmt.Fprintf(stderr, "sw-block: unknown command %q\n", args[0]) usage(stderr) return ops.VolumeStatusExitInvalid } if len(args) < 2 { - fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk") + fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk|volume-unheld") usage(stderr) return ops.VolumeStatusExitInvalid } @@ -126,6 +129,8 @@ func run(args []string, stdout, stderr io.Writer) int { return runOpsFrontendPublicationExecutor(args[2:], stdout, stderr) case "chunk": return runOpsChunk(args[2:], stdout, stderr) + case "volume-unheld": + return runOpsVolumeUnheld(args[2:], stdout, stderr) default: fmt.Fprintf(stderr, "sw-block: unknown ops subcommand %q\n", args[1]) usage(stderr) @@ -2293,6 +2298,7 @@ func usage(w io.Writer) { fmt.Fprintln(w, " sw-block ops chunk fork --chunk-filer [--chunk-path /swblock/chunks] --source --snapshot --target [--request-id ] [--label k=v]...") fmt.Fprintln(w, " sw-block ops chunk show --volume --chunk-filer [--chunk-path /swblock/chunks]") fmt.Fprintln(w, " sw-block ops chunk gc --chunk-filer --master [--chunk-path /swblock/chunks] [--apply] [--grace 1h] [--intent-ttl 1h] [--timeout 1m]") + fmt.Fprintln(w, " sw-block ops volume-unheld --path (exit 0: no process on this host holds it; local filesystems only)") } func emptyCLI(value string) string { diff --git a/seaweed-block/cmd/sw-block/migrate.go b/seaweed-block/cmd/sw-block/migrate.go new file mode 100644 index 0000000000..78a6c16e1d --- /dev/null +++ b/seaweed-block/cmd/sw-block/migrate.go @@ -0,0 +1,269 @@ +package main + +import ( + "encoding/hex" + "errors" + "flag" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + + "github.com/seaweedfs/seaweed-block/cmd/sw-block/internal/v2legacy" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// `sw-block migrate-v3` (format bump v3, DESIGN r17.4 section 10.1; plan row +// 13b): the offline, in-place v2/impl1 -> v3/impl3 descriptor rewrite of a +// cleanly closed volume whose WAL is fully flushed. No record is converted +// and no extent byte is touched. Every step is durable before the next. + +// errMigrateNotClean is DESIGN 10.1's ErrMigrateNotClean. +var errMigrateNotClean = errors.New("migrate-v3: the volume is not cleanly flushed: open with the old binary, flush, close cleanly, retry") + +// errMigrateNeitherSlot: neither offset 0 nor offset 4096 holds a valid +// slot or v2 superblock; nothing is changed. +var errMigrateNeitherSlot = errors.New("migrate-v3: no valid v2 superblock or v3 descriptor slot; nothing changed") + +// migrateStepHook, when set by a test, runs after each durable step with +// its name; returning an error stops the tool there (a simulated crash). +var migrateStepHook func(step string) error + +// syncDirHook, when set by a test, runs at every directory fsync; an error +// fails that fsync. +var syncDirHook func(path string) error + +func runMigrateV3(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("migrate-v3", flag.ContinueOnError) + fs.SetOutput(stderr) + chunkBlocks := fs.Uint64("chunk-blocks", 0, "the provider's chunk size in blocks (the map geometry); required") + if err := fs.Parse(args); err != nil { + return 2 + } + if fs.NArg() != 1 || *chunkBlocks == 0 { + fmt.Fprintln(stderr, "usage: sw-block migrate-v3 --chunk-blocks N ") + return 2 + } + if err := migrateV3(fs.Arg(0), *chunkBlocks, stdout); err != nil { + fmt.Fprintln(stderr, err) + return 1 + } + return 0 +} + +func migrateV3(path string, chunkBlocks uint64, out io.Writer) error { + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + return err + } + defer f.Close() + if err := storage.LockWALStoreFile(f); err != nil { + return err + } + head := make([]byte, 2*storage.MigrationSlotSize) + if _, err := f.ReadAt(head, 0); err != nil { + return fmt.Errorf("migrate-v3: read the descriptor region: %w", err) + } + a, b := head[:storage.MigrationSlotSize], head[storage.MigrationSlotSize:] + sb, v2err := v2legacy.ReadSuperblock(a) + switch { + case v2err == nil: + // Not committed: restart from step 1 with a full rescan (the old + // binary may have run since; nothing earlier is trusted). + return migrateFromV2(f, path, sb, chunkBlocks, out) + case errors.Is(v2err, v2legacy.ErrImplUnsupported): + return fmt.Errorf("migrate-v3: %w (an impl-2 volume stays on its old binary)", v2err) + } + stA, genA := storage.ClassifyMigrationSlotV3(a) + stB, _ := storage.ClassifyMigrationSlotV3(b) + switch { + case stA == storage.MigrationSlotCommitted: + // Committed. Finish step 6 if B was never rewritten, then step 7. + if genA == 2 && stB != storage.MigrationSlotCommitted { + rb, err := storage.RolloverSlotV3(a) + if err != nil { + return err + } + if err := pwriteSync(f, rb, storage.MigrationSlotBOffset); err != nil { + return err + } + } + return retireC11(path) + case stB == storage.MigrationSlotCommitted: + // Committed and possibly in use: only step 7. + return retireC11(path) + case stB == storage.MigrationSlotPrepared: + // A torn step 5 or an old-binary run after preparation followed by + // damage to A: the bytes cannot tell; never guess. + return fmt.Errorf("migrate-v3: %w; nothing changed (an operator decision, using the backup)", storage.ErrMigrationIncomplete) + default: + return errMigrateNeitherSlot + } +} + +func migrateFromV2(f *os.File, path string, sb v2legacy.Superblock, chunkBlocks uint64, out io.Writer) error { + src := storage.MigrationSourceV3{ + UUID: sb.UUID, VolumeSize: sb.VolumeSize, ExtentSize: sb.ExtentSize, BlockSize: sb.BlockSize, + OldWALOffset: sb.WALOffset, OldWALSize: sb.WALSize, CreatedAt: sb.CreatedAt, + CheckpointLSN: sb.WALCheckpointLSN, ChunkBlocks: chunkBlocks, + } + // Precondition 4 first (read-only): the geometry, including the checked + // extent end, refuses before the WAL is read or anything is written. + if err := storage.ValidateMigrationV3(src); err != nil { + return err + } + fi, err := f.Stat() + if err != nil { + return err + } + if size := uint64(fi.Size()); sb.WALOffset > size || sb.WALSize > size-sb.WALOffset { // no wrapping sum + return fmt.Errorf("%w: the v2 WAL [%d, %d) extends past the file end %d", storage.ErrMigrateGeometry, sb.WALOffset, sb.WALOffset+sb.WALSize, fi.Size()) + } + // Step 1: precondition 3, read-only and before any write. + if sb.WALHead != sb.WALTail { + return fmt.Errorf("%w (WALHead %d != WALTail %d)", errMigrateNotClean, sb.WALHead, sb.WALTail) + } + wal := make([]byte, sb.WALSize) + if _, err := f.ReadAt(wal, int64(sb.WALOffset)); err != nil { + return fmt.Errorf("migrate-v3: read the v2 WAL: %w", err) + } + if found := v2legacy.ScanClean(wal, sb.WALCheckpointLSN); len(found) > 0 { + return fmt.Errorf("%w (%d unflushed record(s); first at WAL offset %d: %s)", errMigrateNotClean, len(found), found[0].Offset, found[0].Reason) + } + if err := step("scanned"); err != nil { + return err + } + // Step 2: the atomic operator backup of the v2 superblock. + raw := make([]byte, v2legacy.SuperblockSize) + if _, err := f.ReadAt(raw, 0); err != nil { + return err + } + if err := writeFileAtomic(path+".v2-superblock.bak", raw); err != nil { + return fmt.Errorf("migrate-v3: backup: %w", err) + } + if err := step("backup"); err != nil { + return err + } + // Step 3: the initial map sidecar (all UNKNOWN), durable. + plan, err := storage.PrepareMigrationV3(path+".chunkmap", src) + if err != nil { + return fmt.Errorf("migrate-v3: initial map: %w", err) + } + if err := syncDirOf(path); err != nil { + return err + } + if err := step("map"); err != nil { + return err + } + // Step 4: the prepared slot B, over the old WAL's first 4 KiB. + if err := pwriteSync(f, plan.PreparedB, storage.MigrationSlotBOffset); err != nil { + return err + } + if err := step("prepared"); err != nil { + return err + } + // Step 5: slot A, phase 0: the commit point. + if err := pwriteSync(f, plan.CommittedA, storage.MigrationSlotAOffset); err != nil { + return err + } + if err := step("committed"); err != nil { + return err + } + // Step 6: slot B rewritten at phase 0 (two-slot redundancy). + if err := pwriteSync(f, plan.RolloverB, storage.MigrationSlotBOffset); err != nil { + return err + } + if err := step("rollover"); err != nil { + return err + } + // Step 7: retire the v2 C11 bitmap, only after the commit. + if err := retireC11(path); err != nil { + return err + } + // Step 8. + fmt.Fprintf(out, "migrated %s to v3: descriptor sha256 %s; backups left in place\n", path, hex.EncodeToString(plan.DescriptorHash[:])) + return nil +} + +func step(name string) error { + if h := migrateStepHook; h != nil { + return h(name) + } + return nil +} + +func pwriteSync(f *os.File, b []byte, off int64) error { + if _, err := f.WriteAt(b, off); err != nil { + return fmt.Errorf("migrate-v3: write at %d: %w", off, err) + } + if err := f.Sync(); err != nil { + return fmt.Errorf("migrate-v3: fsync: %w", err) + } + return nil +} + +// writeFileAtomic writes b to name via name.tmp, fsync, rename and a +// directory fsync; a leftover .tmp from an earlier run is replaced. +func writeFileAtomic(name string, b []byte) error { + tmp := name + ".tmp" + if err := os.Remove(tmp); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + t, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) + if err != nil { + return err + } + if _, err := t.Write(b); err != nil { + t.Close() + return err + } + if err := t.Sync(); err != nil { + t.Close() + return err + } + if err := t.Close(); err != nil { + return err + } + if err := os.Rename(tmp, name); err != nil { + return err + } + return syncDirOf(name) +} + +// retireC11 is step 7: rename a v2 .chunkbitmap sidecar to +// .v2-chunkbitmap.bak and fsync the directory. Absent is done. +func retireC11(path string) error { + err := os.Rename(path+".chunkbitmap", path+".v2-chunkbitmap.bak") + if errors.Is(err, os.ErrNotExist) { + if _, serr := os.Stat(path + ".v2-chunkbitmap.bak"); serr != nil { + return nil // there was no v2 bitmap + } + // An earlier run renamed it; its directory fsync may have failed, so + // make the rename durable now (codex01 row 13b P2). + return syncDirOf(path) + } + if err != nil { + return fmt.Errorf("migrate-v3: retire the v2 chunk bitmap: %w", err) + } + return syncDirOf(path) +} + +// syncDirOf fsyncs the directory holding path. A directory cannot be +// fsynced on Windows; there it is a no-op, as in the provider. +func syncDirOf(path string) error { + if h := syncDirHook; h != nil { + if err := h(path); err != nil { + return err + } + } + if runtime.GOOS == "windows" { + return nil + } + d, err := os.Open(filepath.Dir(path)) + if err != nil { + return err + } + defer d.Close() + return d.Sync() +} diff --git a/seaweed-block/cmd/sw-block/migrate_format_v3_test.go b/seaweed-block/cmd/sw-block/migrate_format_v3_test.go new file mode 100644 index 0000000000..c87acf727b --- /dev/null +++ b/seaweed-block/cmd/sw-block/migrate_format_v3_test.go @@ -0,0 +1,176 @@ +//go:build swblock_format_v3_test + +package main + +import ( + "bytes" + "errors" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestMigrateV3ExcludesOpenUntilCommitFinishes(t *testing.T) { + path := v2Volume(t, true) + parked, resume := make(chan struct{}), make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(resume) }) } + defer release() + migrateStepHook = func(step string) error { + if step == "committed" { + close(parked) + <-resume + } + return nil + } + finished := make(chan error, 1) + done := make(chan struct{}) + go func() { + defer close(done) + finished <- migrateV3(path, 4, &bytes.Buffer{}) + }() + t.Cleanup(func() { + release() + select { + case <-done: + migrateStepHook = nil + case <-time.After(10 * time.Second): + t.Error("migration worker did not stop during cleanup") + } + }) + select { + case <-parked: + case err := <-finished: + t.Fatalf("migration stopped before the held commit: %v", err) + case <-time.After(10 * time.Second): + t.Fatal("migration did not reach the held commit") + } + if s, err := storage.OpenMappedWALStoreV3Test(path); !errors.Is(err, storage.ErrWALStoreLocked) { + if s != nil { + _ = s.Close() + } + t.Fatalf("open during migration: %v, want volume locked", err) + } + release() + select { + case err := <-finished: + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("migration did not release its lock") + } + s, err := storage.OpenMappedWALStoreV3Test(path) + if err != nil { + t.Fatalf("open after migration: %v", err) + } + _ = s.Close() +} + +func TestMigrateV3RefusesAnOpenV3Volume(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + s, err := storage.CreateMappedWALStoreV3Test(path, 64, migBlock, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + // Windows byte-range locks reject reads through a second handle. Snapshot + // only while no owner is open, then hold the real owner for the CLI call. + if err := s.Close(); err != nil { + t.Fatal(err) + } + before := snapshotFiles(t, path) + s, err = storage.OpenMappedWALStoreV3Test(path) + if err != nil { + t.Fatal(err) + } + code, msg := migrate(t, path) + if code != 1 || !strings.Contains(msg, "locked") { + t.Fatalf("migration must refuse an open v3 volume: exit=%d message=%s", code, msg) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + if !sameFiles(before, snapshotFiles(t, path)) { + t.Fatal("refused migration modified the open volume") + } + if code, msg := migrate(t, path); code != 0 { + t.Fatalf("migration after owner close: exit=%d message=%s", code, msg) + } +} + +// Row 13b through the actual v3 open (tag swblock_format_v3_test). + +// A migrated volume opens as v3 and serves the v2 blocks unchanged; its +// map is the initial one (all UNKNOWN, covered = the v2 checkpoint); a +// v3 write and a reopen work. Mutant: an initial map with clean entries +// fails here. +func TestMigrateV3VolumeOpensAsV3(t *testing.T) { + path := v2Volume(t, true) + if code, msg := migrate(t, path); code != 0 { + t.Fatalf("migrate: %s", msg) + } + s, err := storage.OpenMappedWALStoreV3Test(path) + if err != nil { + t.Fatalf("v3 open of a migrated volume: %v", err) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + covered, allUnknown := storage.MapCoverageV3Test(s) + if !allUnknown || covered != s.CheckpointLSN() { + t.Fatalf("initial map: covered %d (checkpoint %d), all UNKNOWN %v", covered, s.CheckpointLSN(), allUnknown) + } + for lba := uint32(0); lba < 4; lba++ { + got, err := s.Read(lba) + if err != nil || !bytes.Equal(got, migBlk(0x10+byte(lba))) { + t.Fatalf("LBA %d after migration: err %v", lba, err) + } + } + if _, err := s.Write(7, migBlk(0x77)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + r, err := storage.OpenMappedWALStoreV3Test(path) + if err != nil { + t.Fatal(err) + } + defer r.Close() + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if got, _ := r.Read(7); !bytes.Equal(got, migBlk(0x77)) { + t.Fatal("a v3 write after migration did not survive a reopen") + } +} + +// A prepared-only volume (stopped before the commit, A then damaged) is +// refused by v3 open with ErrMigrationIncomplete, as by the tool. +func TestMigrateV3PreparedOnlyRefusedByV3Open(t *testing.T) { + path := v2Volume(t, true) + migrateStepHook = func(s string) error { + if s == "prepared" { + return errors.New("stop") + } + return nil + } + migrate(t, path) + migrateStepHook = nil + damageSlotA(t, path) + if s, err := storage.OpenMappedWALStoreV3Test(path); !errors.Is(err, storage.ErrMigrationIncomplete) { + if s != nil { + _ = s.Close() + } + t.Fatalf("v3 open of a prepared-only volume: err = %v, want ErrMigrationIncomplete", err) + } +} diff --git a/seaweed-block/cmd/sw-block/migrate_test.go b/seaweed-block/cmd/sw-block/migrate_test.go new file mode 100644 index 0000000000..fd8386c5e1 --- /dev/null +++ b/seaweed-block/cmd/sw-block/migrate_test.go @@ -0,0 +1,467 @@ +//go:build swblock_format_v3_test + +package main + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/cmd/sw-block/internal/v2legacy" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Plan row 13b controls (DESIGN r17.4 section 10.1; owner claude03), all +// through the actual CLI entry (run). + +const migBlock = 4096 + +func migBlk(b byte) []byte { return bytes.Repeat([]byte{b}, migBlock) } + +// v2Volume creates a real v2/impl1 volume with 4 written blocks; clean +// closes it (flushing), otherwise it is left synced but unflushed. +func v2Volume(t *testing.T, clean bool) string { + t.Helper() + path := filepath.Join(t.TempDir(), "vol") + s, err := storage.CreateLegacyWALStoreTest(path, 64, migBlock) + if err != nil { + t.Fatal(err) + } + if !clean { + s.DisableAutoFlushForRecoveryTest() + } + for lba := uint32(0); lba < 4; lba++ { + if _, err := s.Write(lba, migBlk(0x10+byte(lba))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if clean { + if err := s.Close(); err != nil { + t.Fatal(err) + } + } else { + t.Cleanup(func() { _ = s.Close() }) + } + return path +} + +func migrate(t *testing.T, path string) (int, string) { + t.Helper() + var out, errb bytes.Buffer + code := run([]string{"migrate-v3", "--chunk-blocks", "4", path}, &out, &errb) + return code, out.String() + errb.String() +} + +// snapshotFiles reads the volume and every sidecar next to it. +func snapshotFiles(t *testing.T, path string) map[string][]byte { + t.Helper() + got := map[string][]byte{} + matches, _ := filepath.Glob(path + "*") + for _, m := range matches { + b, err := os.ReadFile(m) + if err != nil { + t.Fatal(err) + } + got[filepath.Base(m)] = b + } + return got +} + +func sameFiles(a, b map[string][]byte) bool { + if len(a) != len(b) { + return false + } + for k, v := range a { + if !bytes.Equal(v, b[k]) { + return false + } + } + return true +} + +// A clean v2 volume migrates: slot A committed (slotGen 2), slot B rolled +// over (slotGen 3), every extent byte unchanged, the backup holds the old +// superblock, a v2 chunk bitmap is retired, the old binary now refuses the +// file, and a rerun changes no byte. +func TestMigrateV3CleanVolume(t *testing.T) { + path := v2Volume(t, true) + if err := os.WriteFile(path+".chunkbitmap", []byte("c11"), 0o644); err != nil { + t.Fatal(err) + } + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + sb, err := v2legacy.ReadSuperblock(before) + if err != nil { + t.Fatal(err) + } + extentBase := sb.WALOffset + sb.WALSize + if code, msg := migrate(t, path); code != 0 || !strings.Contains(msg, "descriptor sha256") { + t.Fatalf("migrate: exit %d: %s", code, msg) + } + after, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(after[extentBase:], before[extentBase:]) { + t.Fatal("the migration changed extent bytes") + } + if st, gen := storage.ClassifyMigrationSlotV3(after[:4096]); st != storage.MigrationSlotCommitted || gen != 2 { + t.Fatalf("slot A: state %d gen %d, want committed gen 2", st, gen) + } + if st, gen := storage.ClassifyMigrationSlotV3(after[4096:8192]); st != storage.MigrationSlotCommitted || gen != 3 { + t.Fatalf("slot B: state %d gen %d, want committed gen 3", st, gen) + } + if bak, err := os.ReadFile(path + ".v2-superblock.bak"); err != nil || !bytes.Equal(bak, before[:4096]) { + t.Fatalf("backup: %v", err) + } + if _, err := os.Stat(path + ".chunkbitmap"); !errors.Is(err, os.ErrNotExist) { + t.Fatal("the v2 chunk bitmap was not retired") + } + if _, err := os.Stat(path + ".v2-chunkbitmap.bak"); err != nil { + t.Fatalf("retired bitmap: %v", err) + } + if s, err := storage.OpenLegacyWALStoreTest(path); err == nil { + _ = s.Close() + t.Fatal("the old binary opened a migrated volume") + } + snap := snapshotFiles(t, path) + if code, msg := migrate(t, path); code != 0 { + t.Fatalf("rerun: exit %d: %s", code, msg) + } + if !sameFiles(snap, snapshotFiles(t, path)) { + t.Fatal("a rerun on a committed volume changed bytes") + } +} + +// Refusals change no byte of the volume or any sidecar: an unflushed WAL +// (ErrMigrateNotClean with the operator remedy), an impl-2 volume, and a +// file with neither a v2 superblock nor a valid v3 slot. Mutant: skipping +// the clean scan migrates the unflushed volume and fails here. +func TestMigrateV3RefusalsChangeNothing(t *testing.T) { + t.Run("unflushed WAL", func(t *testing.T) { + path := v2Volume(t, false) + snap := snapshotFiles(t, path) + code, msg := migrate(t, path) + if code == 0 || !strings.Contains(msg, "open with the old binary, flush, close cleanly, retry") { + t.Fatalf("exit %d: %s", code, msg) + } + if !sameFiles(snap, snapshotFiles(t, path)) { + t.Fatal("a refused migration changed bytes") + } + }) + t.Run("impl 2", func(t *testing.T) { + path := v2Volume(t, true) + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + if _, err := f.WriteAt([]byte{2, 0, 0, 0}, 92); err != nil { + t.Fatal(err) + } + f.Close() + snap := snapshotFiles(t, path) + if code, _ := migrate(t, path); code == 0 || !sameFiles(snap, snapshotFiles(t, path)) { + t.Fatal("an impl-2 volume was not refused unchanged") + } + }) + t.Run("neither valid", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "junk") + if err := os.WriteFile(path, bytes.Repeat([]byte{0xEE}, 3*4096), 0o644); err != nil { + t.Fatal(err) + } + snap := snapshotFiles(t, path) + if code, _ := migrate(t, path); code == 0 || !sameFiles(snap, snapshotFiles(t, path)) { + t.Fatal("neither-valid was not refused unchanged") + } + }) +} + +// A crash after each step is resumable from the slot bytes alone: before +// the commit the rerun restarts with a full rescan; after it, the rerun +// only finishes the rollover and the bitmap retirement. +func TestMigrateV3CrashAfterEachStepIsResumable(t *testing.T) { + for _, stop := range []string{"scanned", "backup", "map", "prepared", "committed", "rollover"} { + t.Run(stop, func(t *testing.T) { + path := v2Volume(t, true) + if err := os.WriteFile(path+".chunkbitmap", []byte("c11"), 0o644); err != nil { + t.Fatal(err) + } + migrateStepHook = func(s string) error { + if s == stop { + return errors.New("simulated crash after " + s) + } + return nil + } + code, _ := migrate(t, path) + migrateStepHook = nil + if code == 0 { + t.Fatal("the simulated crash did not stop the tool") + } + // Before the commit point (step 5) slot A is still the v2 + // superblock and the v2 bitmap is not retired; after it A is a + // committed v3 slot. + crashed, _ := os.ReadFile(path) + _, v2err := v2legacy.ReadSuperblock(crashed[:4096]) + _, bitmapErr := os.Stat(path + ".chunkbitmap") + if committed := stop == "committed" || stop == "rollover"; committed { + if st, _ := storage.ClassifyMigrationSlotV3(crashed[:4096]); st != storage.MigrationSlotCommitted { + t.Fatalf("crash after %s: slot A state %d, want committed", stop, st) + } + } else if v2err != nil || bitmapErr != nil { + t.Fatalf("crash after %s: A still v2 = %v, bitmap present = %v; want both before the commit", stop, v2err == nil, bitmapErr == nil) + } + if code, msg := migrate(t, path); code != 0 { + t.Fatalf("rerun after a crash at %s: exit %d: %s", stop, code, msg) + } + raw, _ := os.ReadFile(path) + if st, _ := storage.ClassifyMigrationSlotV3(raw[:4096]); st != storage.MigrationSlotCommitted { + t.Fatalf("after the rerun slot A state %d, want committed", st) + } + if st, _ := storage.ClassifyMigrationSlotV3(raw[4096:8192]); st != storage.MigrationSlotCommitted { + t.Fatalf("after the rerun slot B state %d, want committed", st) + } + }) + } +} + +// The old binary runs after preparation (A is still v2, so it opens): the +// rerun finds A still v2 and restarts with a full rescan; it refuses while +// the old binary's writes are unflushed and migrates once it flushed and +// closed. A prepared B with a damaged A is ambiguous and refused with +// ErrMigrationIncomplete, writing nothing. +func TestMigrateV3OldBinaryAfterPreparation(t *testing.T) { + path := v2Volume(t, true) + migrateStepHook = func(s string) error { + if s == "prepared" { + return errors.New("stop after preparation") + } + return nil + } + migrate(t, path) + migrateStepHook = nil + s, err := storage.OpenLegacyWALStoreTest(path) + if err != nil { + t.Fatalf("the old binary refused a prepared-only volume: %v", err) + } + s.DisableAutoFlushForRecoveryTest() + if _, err := s.Write(9, migBlk(0x99)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + snap := snapshotFiles(t, path) + if code, msg := migrate(t, path); code == 0 || !strings.Contains(msg, "not cleanly flushed") { + t.Fatalf("rerun over the old binary's unflushed write: exit %d: %s", code, msg) + } + if !sameFiles(snap, snapshotFiles(t, path)) { + t.Fatal("a refused rerun changed bytes") + } + _ = s.Close() // stopped without a flush: still not clean + if code, _ := migrate(t, path); code == 0 { + t.Fatal("the rerun migrated a volume the old binary left unflushed") + } + // The operator remedy: open with the old binary, flush, close cleanly. + s2, err := storage.OpenLegacyWALStoreTest(path) + if err != nil { + t.Fatal(err) + } + if _, err := s2.Recover(); err != nil { + t.Fatal(err) + } + if err := s2.Close(); err != nil { + t.Fatal(err) + } + if code, msg := migrate(t, path); code != 0 { + t.Fatalf("rerun after the old binary closed cleanly: exit %d: %s", code, msg) + } + + t.Run("prepared B with a damaged A", func(t *testing.T) { + path := v2Volume(t, true) + migrateStepHook = func(s string) error { + if s == "prepared" { + return errors.New("stop after preparation") + } + return nil + } + migrate(t, path) + migrateStepHook = nil + f, _ := os.OpenFile(path, os.O_RDWR, 0) + _, _ = f.WriteAt(bytes.Repeat([]byte{0xEE}, 4096), 0) + f.Close() + snap := snapshotFiles(t, path) + code, msg := migrate(t, path) + if code == 0 || !strings.Contains(msg, storage.ErrMigrationIncomplete.Error()) || !sameFiles(snap, snapshotFiles(t, path)) { + t.Fatalf("exit %d: %s", code, msg) + } + }) +} + +// The tool never reads or restores its backup: a committed volume reruns +// to success with the backup damaged and its slots untouched. +func TestMigrateV3NeverRestoresTheBackup(t *testing.T) { + path := v2Volume(t, true) + if code, msg := migrate(t, path); code != 0 { + t.Fatalf("migrate: %s", msg) + } + if err := os.WriteFile(path+".v2-superblock.bak", []byte("damaged"), 0o644); err != nil { + t.Fatal(err) + } + raw, _ := os.ReadFile(path) + if code, msg := migrate(t, path); code != 0 { + t.Fatalf("rerun: %s", msg) + } + now, _ := os.ReadFile(path) + if !bytes.Equal(raw, now) { + t.Fatal("a rerun changed the committed volume") + } +} + +// The old v2 WAL starts at offset 4096, over the prepared slot B, so an +// old-binary run can overwrite B partly or wholly (codex03 r8). Either way B +// is an invalid slot, never prepared or committed: with A still v2 the rerun +// restarts and migrates; with A damaged too, neither slot is valid and the +// rerun refuses with no byte changed. +func TestMigrateV3OldWALOverwritesThePreparedSlot(t *testing.T) { + for _, n := range []int{100, 4096} { + for _, damageA := range []bool{false, true} { + name := map[int]string{100: "partial", 4096: "full"}[n] + if damageA { + name += " with A damaged" + } + t.Run(name, func(t *testing.T) { + path := v2Volume(t, true) + migrateStepHook = func(s string) error { + if s == "prepared" { + return errors.New("stop after preparation") + } + return nil + } + migrate(t, path) + migrateStepHook = nil + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + if _, err := f.WriteAt(bytes.Repeat([]byte{0xA5}, n), 4096); err != nil { + t.Fatal(err) + } + if damageA { + if _, err := f.WriteAt(bytes.Repeat([]byte{0xEE}, 4096), 0); err != nil { + t.Fatal(err) + } + } + f.Close() + raw, _ := os.ReadFile(path) + if st, _ := storage.ClassifyMigrationSlotV3(raw[4096:8192]); st != storage.MigrationSlotInvalid { + t.Fatalf("an overwritten B classifies as %d, want invalid", st) + } + snap := snapshotFiles(t, path) + code, msg := migrate(t, path) + if damageA { + if code == 0 || !sameFiles(snap, snapshotFiles(t, path)) { + t.Fatalf("neither valid: exit %d, bytes changed: %s", code, msg) + } + return + } + if code != 0 { + t.Fatalf("rerun with A still v2: exit %d: %s", code, msg) + } + }) + } + } +} + +func damageSlotA(t *testing.T, path string) { + t.Helper() + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + defer f.Close() + if _, err := f.WriteAt(bytes.Repeat([]byte{0xEE}, 4096), 0); err != nil { + t.Fatal(err) + } +} + +func patchSuperblock(t *testing.T, path string, off int64, v uint64) { + t.Helper() + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + defer f.Close() + var b [8]byte + for i := range b { + b[i] = byte(v >> (8 * i)) + } + if _, err := f.WriteAt(b[:], off); err != nil { + t.Fatal(err) + } +} + +// codex01 row 13b P1 and P2: geometry the v3 slot validation would refuse +// is refused before ANY write (no backup, no map, the volume unchanged): +// an aligned VolumeSize whose extent end overflows, and a v2 WAL size that +// extends past the file end (refused before the scan allocates it). +// Mutants: no checked extent end in ValidateMigrationV3, no file-size +// bound before the WAL read. +func TestMigrateV3BadGeometryRefusedBeforeAnyWrite(t *testing.T) { + for name, patch := range map[string][2]uint64{ + "extent end overflows": {24, 1 << 63}, // VolumeSize, block aligned + "WAL past the file end": {48, 1<<45 + 4096}, // WALSize, v3 size aligned + "WAL region wraps": {48, ^uint64(0) - 4095}, // WALSize 2^64-4096: every sum wraps + } { + t.Run(name, func(t *testing.T) { + path := v2Volume(t, true) + patchSuperblock(t, path, int64(patch[0]), patch[1]) + snap := snapshotFiles(t, path) + code, msg := migrate(t, path) + if code == 0 || !strings.Contains(msg, "cannot be migrated in place") { + t.Fatalf("exit %d: %s", code, msg) + } + if !sameFiles(snap, snapshotFiles(t, path)) { + t.Fatal("a geometry refusal wrote a backup, a map or volume bytes") + } + }) + } +} + +// codex01 row 13b P2: an earlier run renamed the v2 chunk bitmap but its +// directory fsync failed; the rerun (source gone) still fsyncs the +// directory so the rename is durable. Mutant: treating the missing source +// as done without the fsync fails here. +func TestMigrateV3RetirementRerunFsyncsTheDirectory(t *testing.T) { + path := v2Volume(t, true) + if err := os.WriteFile(path+".chunkbitmap", []byte("c11"), 0o644); err != nil { + t.Fatal(err) + } + failed := false + syncDirHook = func(string) error { + if _, err := os.Stat(path + ".v2-chunkbitmap.bak"); err == nil && !failed { + failed = true + return errors.New("injected directory fsync failure") + } + return nil + } + defer func() { syncDirHook = nil }() + if code, _ := migrate(t, path); code == 0 { + t.Fatal("the injected retirement fsync failure did not fail the tool") + } + calls := 0 + syncDirHook = func(string) error { calls++; return nil } + if code, msg := migrate(t, path); code != 0 { + t.Fatalf("rerun: exit %d: %s", code, msg) + } + if calls == 0 { + t.Fatal("the rerun did not fsync the directory of the earlier rename") + } +} diff --git a/seaweed-block/cmd/sw-block/volume_unheld.go b/seaweed-block/cmd/sw-block/volume_unheld.go new file mode 100644 index 0000000000..81d2c12d0e --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_unheld.go @@ -0,0 +1,54 @@ +package main + +import ( + "errors" + "flag" + "fmt" + "io" + + "github.com/seaweedfs/seaweed-block/core/ops" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const volumeUnheldUsage = `usage: sw-block ops volume-unheld --path + +Exit 0 only when no process on THIS host holds the v3 volume file's lock +(the lock every v3 owner holds while its store is open; the kernel releases +it when the owner process exits). Exit 1: held. Exit 2: unknown (missing +file, not a v3 volume, lock error) or bad usage. + +This proof is per host and for local filesystems only. It says nothing about +another host, and nothing on a network or shared mount. It does not prove the +owner process is dead: host cleanup must require BOTH this command's exit 0 +AND the host tooling's own check that the recorded owner process is gone. + +The probe holds the lock only for an instant and reserves nothing: it does not +keep a new owner out after it returns, and an owner opening the volume at that +instant is refused. Run it only when the owner is believed gone. +` + +// runOpsVolumeUnheld is `sw-block ops volume-unheld`. +func runOpsVolumeUnheld(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops volume-unheld", flag.ContinueOnError) + fs.SetOutput(stderr) + fs.Usage = func() { fmt.Fprint(stderr, volumeUnheldUsage) } + path := fs.String("path", "", "the volume file") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if *path == "" || fs.NArg() != 0 { + fmt.Fprint(stderr, volumeUnheldUsage) + return ops.VolumeStatusExitInvalid + } + switch err := storage.ProbeVolumeUnheld(*path); { + case err == nil: + fmt.Fprintf(stdout, "unheld: no process on this host holds %s (local proof only; also check the owner process is gone)\n", *path) + return ops.VolumeStatusExitOK + case errors.Is(err, storage.ErrVolumeHeld): + fmt.Fprintf(stdout, "held: a live process on this host holds %s\n", *path) + return ops.VolumeStatusExitUnhealthy + default: + fmt.Fprintf(stderr, "unknown: %v\n", err) + return ops.VolumeStatusExitInvalid + } +} diff --git a/seaweed-block/cmd/sw-block/volume_unheld_test.go b/seaweed-block/cmd/sw-block/volume_unheld_test.go new file mode 100644 index 0000000000..868f276778 --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_unheld_test.go @@ -0,0 +1,63 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// `sw-block ops volume-unheld` exits 0 only for an unheld v3 volume: 1 while +// a store holds it, 2 for unknown (missing, not v3) and bad usage. The +// usage states the per-host, local-only limit and the second check. +func TestOpsVolumeUnheldExitCodes(t *testing.T) { + path := filepath.Join(t.TempDir(), "v.bin") + s, err := storage.CreateWALStore(path, 64, 4096) + if err != nil { + t.Fatal(err) + } + closed := false + t.Cleanup(func() { + if !closed { + _ = s.Close() + } + }) + junk := filepath.Join(t.TempDir(), "junk.bin") + if err := os.WriteFile(junk, make([]byte, 64<<10), 0o644); err != nil { + t.Fatal(err) + } + runIt := func(args ...string) (int, string, string) { + var out, errOut bytes.Buffer + code := run(append([]string{"ops", "volume-unheld"}, args...), &out, &errOut) + return code, out.String(), errOut.String() + } + if code, out, _ := runIt("--path", path); code != 1 || !strings.HasPrefix(out, "held:") { + t.Fatalf("open store: exit %d %q; want 1 held", code, out) + } + closed = true + if err := s.Close(); err != nil { + t.Fatal(err) + } + if code, out, _ := runIt("--path", path); code != 0 || !strings.HasPrefix(out, "unheld:") { + t.Fatalf("closed store: exit %d %q; want 0 unheld", code, out) + } + for name, args := range map[string][]string{ + "missing": {"--path", filepath.Join(t.TempDir(), "missing.bin")}, + "not v3": {"--path", junk}, + "no path": nil, + "extra arg": {"--path", path, "x"}, + } { + if code, out, _ := runIt(args...); code != 2 || strings.HasPrefix(out, "unheld") { + t.Fatalf("%s: exit %d %q; want 2", name, code, out) + } + } + _, _, usage := runIt() + for _, want := range []string{"per host", "local filesystems only", "network or shared mount", "BOTH", "reserves nothing", "is refused"} { + if !strings.Contains(usage, want) { + t.Fatalf("usage lacks %q:\n%s", want, usage) + } + } +} diff --git a/seaweed-block/core/adapter/handoff_test.go b/seaweed-block/core/adapter/handoff_test.go index 83bd09acc3..f7f8187fc5 100644 --- a/seaweed-block/core/adapter/handoff_test.go +++ b/seaweed-block/core/adapter/handoff_test.go @@ -263,7 +263,10 @@ func TestHandoff_RejoinAfterNewPrimary_DataConsistent(t *testing.T) { waitRecoveredHealthy(t, adapterB, "r1", 3*time.Second) // Every LBA that B wrote must match on the replica. - allB := primaryB.AllBlocks() + allB, snapshotErr := primaryB.AllBlocks() + if snapshotErr != nil { + t.Fatal(snapshotErr) + } for lba, expected := range allB { got, err := replica.Read(lba) if err != nil { diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 88e5a2c2b4..52f8d7fe1f 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -157,12 +157,21 @@ type Publisher struct { // Workspace state is serialized with assignment minting under mu. Remote // HEAD reads and subscriber delivery never run under this lock. - workspace map[string]*WorkspaceState - workspaceUncertain map[string]bool - workspaceNow func() time.Time - workspaceTTL time.Duration - workspaceMaxClockSkew time.Duration - workspaceLeaseDeadline map[string]time.Time + workspace map[string]*WorkspaceState + lostRanges map[string][]WorkspaceLostRange // forced moves' abandoned ranges (side files) + workspaceUncertain map[string]bool + workspaceNow func() time.Time + workspaceTTL time.Duration + workspaceMaxClockSkew time.Duration + + // Lease renewal state (workspace_lease_view.go). leaseMu is a memory-only + // leaf: lock order p.mu -> leaseMu, never the reverse, and nothing is + // acquired, waited on or written while it is held. + leaseMu sync.Mutex + leaseViews map[string]*leaseView + leaseClosing bool + extWG sync.WaitGroup + extendFailures map[string]int // guarded by mu } // PublicationAdmission surrounds an ordinary mint with local ownership/lifetime @@ -221,15 +230,17 @@ func WithPublishObserver(observer PublishObserver) PublisherOption { // the pieces. func NewPublisher(dir Directive, opts ...PublisherOption) *Publisher { p := &Publisher{ - dir: dir, - state: make(map[subKey]assignmentState), - subs: make(map[subKey][]*subscription), - writeSeqByVolume: map[string]uint64{}, - workspace: map[string]*WorkspaceState{}, - workspaceUncertain: map[string]bool{}, - workspaceNow: time.Now, - workspaceTTL: 30 * time.Second, - workspaceLeaseDeadline: map[string]time.Time{}, + dir: dir, + state: make(map[subKey]assignmentState), + subs: make(map[subKey][]*subscription), + writeSeqByVolume: map[string]uint64{}, + workspace: map[string]*WorkspaceState{}, + lostRanges: map[string][]WorkspaceLostRange{}, + workspaceUncertain: map[string]bool{}, + workspaceNow: time.Now, + workspaceTTL: 30 * time.Second, + leaseViews: map[string]*leaseView{}, + extendFailures: map[string]int{}, } for _, opt := range opts { if opt != nil { @@ -256,9 +267,6 @@ func (p *Publisher) reloadFromStore() { for _, rec := range records { if rec.Workspace != nil { p.workspace[rec.VolumeID] = cloneWorkspace(rec.Workspace) - // Conservatively cover every previously granted TTL after restart. - // Persisted wall time alone must never shorten a live host's lease. - p.workspaceLeaseDeadline[rec.VolumeID] = p.workspaceNow().Add(p.workspaceTTL) } key := subKey{volumeID: rec.VolumeID, replicaID: rec.ReplicaID} p.state[key] = assignmentState{ @@ -277,6 +285,20 @@ func (p *Publisher) reloadFromStore() { } } p.loadErrs = append(p.loadErrs, skips...) + ranges, lskips, lerr := p.store.LoadWorkspaceLostRanges() + if lerr != nil { + panic(fmt.Sprintf("authority: lost range load failure: %v", lerr)) + } + p.lostRanges = ranges + p.loadErrs = append(p.loadErrs, lskips...) + for _, rec := range records { + p.refreshLeaseViewLocked(rec.VolumeID) + if rec.Workspace != nil { + // Conservatively cover every previously granted TTL after restart. + // Persisted wall time alone must never shorten a live host's lease. + p.setLeaseDeadlineLocked(rec.VolumeID, p.workspaceNow().Add(p.workspaceTTL), false) + } + } } // LoadErrors returns the per-record skip errors observed during @@ -474,6 +496,15 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr p.mu.Unlock() return ErrBindAlreadyBound } + // Bind is genesis for the VOLUME, not only for this slot: once + // any slot of the volume holds an authority line, a Bind for + // another slot would mint a second epoch-1 line beside it. + // Moving authority to another slot is IntentReassign. + if bound, ok := boundReplicaForVolume(p.state, ask.VolumeID); ok { + p.mu.Unlock() + return fmt.Errorf("%w: volume %s is already bound to replica %s; use Reassign", + ErrBindAlreadyBound, ask.VolumeID, bound) + } next = adapter.AssignmentInfo{ VolumeID: ask.VolumeID, ReplicaID: ask.ReplicaID, @@ -566,6 +597,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr // unwind. Just report the failure. if record.Workspace != nil { p.workspaceUncertain[ask.VolumeID] = true + p.refreshLeaseViewLocked(ask.VolumeID) } p.mu.Unlock() return fmt.Errorf("authority: durable Put failed, rolling back mint: %w", err) @@ -574,10 +606,13 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr } if issuedWorkspace != nil { p.workspace[ask.VolumeID] = issuedWorkspace - delete(p.workspaceLeaseDeadline, ask.VolumeID) } p.state[k] = assignmentState{info: next, present: true} + p.refreshLeaseViewLocked(ask.VolumeID) + if issuedWorkspace != nil { + p.setLeaseDeadlineLocked(ask.VolumeID, time.Time{}, false) // the issued move clears the lease + } // Snapshot subscribers under lock, release the lock BEFORE // delivering. This prevents a slow consumer goroutine from @@ -610,6 +645,22 @@ func safeInvokePublishObserver(observer func(PublishEvent), event PublishEvent) // treat that as "no per-volume authority line to advance". // // Must be called with p.mu held; reads p.state. +// boundReplicaForVolume reports whether any slot of volumeID holds a +// published authority line, and names one (the lowest replica id, so the +// error text is deterministic). Presence, not the epoch value, decides. +func boundReplicaForVolume(state map[subKey]assignmentState, volumeID string) (string, bool) { + bound, found := "", false + for k, st := range state { + if !st.present || k.volumeID != volumeID { + continue + } + if !found || k.replicaID < bound { + bound, found = k.replicaID, true + } + } + return bound, found +} + func maxPublishedEpochForVolume(state map[subKey]assignmentState, volumeID string) uint64 { var max uint64 for k, st := range state { diff --git a/seaweed-block/core/authority/authority_restart_test.go b/seaweed-block/core/authority/authority_restart_test.go index eb0cf7e578..8a152c4e24 100644 --- a/seaweed-block/core/authority/authority_restart_test.go +++ b/seaweed-block/core/authority/authority_restart_test.go @@ -369,3 +369,8 @@ func (f *failingStore) Close() error { return nil } // Silence unused import warning if adapter is not referenced // directly in this file's test bodies. var _ = adapter.AssignmentInfo{} + +func (f *failingStore) PutWorkspaceLostRanges(string, []WorkspaceLostRange) error { return nil } +func (f *failingStore) LoadWorkspaceLostRanges() (map[string][]WorkspaceLostRange, []error, error) { + return nil, nil, nil +} diff --git a/seaweed-block/core/authority/authority_store.go b/seaweed-block/core/authority/authority_store.go index 680fb2a087..8a3864ac62 100644 --- a/seaweed-block/core/authority/authority_store.go +++ b/seaweed-block/core/authority/authority_store.go @@ -80,6 +80,16 @@ type AuthorityStore interface { // Publisher.apply). Put(record DurableRecord) error + // PutWorkspaceLostRanges replaces a volume's forced-move lost ranges + // atomically, beside (never inside) its authority record, so the record + // stays readable by binaries that predate them. Every store must record + // them: a forced move does not issue without its range. + PutWorkspaceLostRanges(volumeID string, ranges []WorkspaceLostRange) error + + // LoadWorkspaceLostRanges returns every volume's lost ranges, with + // per-file skip errors; only an index-level failure returns err. + LoadWorkspaceLostRanges() (map[string][]WorkspaceLostRange, []error, error) + // Close releases store resources. Idempotent. Close() error } diff --git a/seaweed-block/core/authority/authority_store_test.go b/seaweed-block/core/authority/authority_store_test.go index 99674cf04b..3a270db010 100644 --- a/seaweed-block/core/authority/authority_store_test.go +++ b/seaweed-block/core/authority/authority_store_test.go @@ -362,6 +362,12 @@ func TestDurableAuthority_StoreWriteCallerAllowlist_BoundaryGuard(t *testing.T) if !strings.HasSuffix(path, ".go") { return nil } + // Test doubles outside the package (for example a slow-store wrapper + // that delays and then delegates Put) are not production write + // callers; the guard is about the production tree. + if strings.HasSuffix(path, "_test.go") { + return nil + } // The authority package itself is the only legitimate // write caller. if strings.Contains(path, string(filepath.Separator)+"core"+string(filepath.Separator)+"authority"+string(filepath.Separator)) { diff --git a/seaweed-block/core/authority/bind_volume_genesis_test.go b/seaweed-block/core/authority/bind_volume_genesis_test.go new file mode 100644 index 0000000000..0e80e42f6e --- /dev/null +++ b/seaweed-block/core/authority/bind_volume_genesis_test.go @@ -0,0 +1,104 @@ +package authority + +import ( + "errors" + "testing" +) + +// #183: Bind is genesis for the volume. These cover the branches around +// the per-volume check; the Run-path reproducer is +// TestPublisher_RunRejectsSecondSlotGenesisBind. + +func bindAsk(volumeID, replicaID string) AssignmentAsk { + return AssignmentAsk{VolumeID: volumeID, ReplicaID: replicaID, DataAddr: "d-" + replicaID, CtrlAddr: "c-" + replicaID, Intent: IntentBind} +} + +func reassignAsk(volumeID, replicaID string) AssignmentAsk { + ask := bindAsk(volumeID, replicaID) + ask.Intent = IntentReassign + return ask +} + +func TestPublisher_BindSecondSlotOfBoundVolumeRejected(t *testing.T) { + pub := NewPublisher(NewStaticDirective(nil)) + if err := pub.apply(bindAsk("v1", "r1")); err != nil { + t.Fatalf("first Bind: %v", err) + } + if err := pub.apply(bindAsk("v1", "r2")); !errors.Is(err, ErrBindAlreadyBound) { + t.Fatalf("second-slot Bind: want ErrBindAlreadyBound, got %v", err) + } + if got, ok := pub.LastPublished("v1", "r2"); ok { + t.Fatalf("second slot was published: %+v", got) + } + if got, ok := pub.LastPublished("v1", "r1"); !ok || got.Epoch != 1 || got.EndpointVersion != 1 { + t.Fatalf("first slot line changed: %+v ok=%t", got, ok) + } +} + +func TestPublisher_BindOtherVolumeUnaffected(t *testing.T) { + pub := NewPublisher(NewStaticDirective(nil)) + if err := pub.apply(bindAsk("v1", "r1")); err != nil { + t.Fatalf("Bind v1: %v", err) + } + if err := pub.apply(bindAsk("v2", "r2")); err != nil { + t.Fatalf("Bind of a fresh volume rejected: %v", err) + } + if got, ok := pub.LastPublished("v2", "r2"); !ok || got.Epoch != 1 { + t.Fatalf("fresh volume line=%+v ok=%t want epoch 1", got, ok) + } +} + +func TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected(t *testing.T) { + pub := NewPublisher(NewStaticDirective(nil)) + if err := pub.apply(bindAsk("v1", "r1")); err != nil { + t.Fatalf("Bind: %v", err) + } + if err := pub.apply(reassignAsk("v1", "r2")); err != nil { + t.Fatalf("Reassign to another slot: %v", err) + } + if got, ok := pub.LastPublished("v1", "r2"); !ok || got.Epoch != 2 { + t.Fatalf("reassigned line=%+v ok=%t want epoch 2", got, ok) + } + for _, r := range []string{"r1", "r2", "r3"} { + if err := pub.apply(bindAsk("v1", r)); !errors.Is(err, ErrBindAlreadyBound) { + t.Fatalf("Bind %s after Reassign: want ErrBindAlreadyBound, got %v", r, err) + } + } + if _, ok := pub.LastPublished("v1", "r3"); ok { + t.Fatal("r3 was published by a Bind") + } +} + +// The file store keeps one record per volume, so after a restart only the +// current slot is in memory. A Bind for the earlier slot must still be +// refused: the volume, not the key, is bound. +func TestPublisher_BindAfterRestartRejectedForAnySlot(t *testing.T) { + dir := t.TempDir() + storeA, err := NewFileAuthorityStore(dir) + if err != nil { + t.Fatal(err) + } + pubA := NewPublisher(NewStaticDirective(nil), WithStore(storeA)) + if err := pubA.apply(bindAsk("v1", "r1")); err != nil { + t.Fatalf("Bind: %v", err) + } + if err := pubA.apply(reassignAsk("v1", "r2")); err != nil { + t.Fatalf("Reassign: %v", err) + } + _ = storeA.Close() + + storeB, err := NewFileAuthorityStore(dir) + if err != nil { + t.Fatal(err) + } + defer storeB.Close() + pubB := NewPublisher(NewStaticDirective(nil), WithStore(storeB)) + for _, r := range []string{"r1", "r2", "r3"} { + if err := pubB.apply(bindAsk("v1", r)); !errors.Is(err, ErrBindAlreadyBound) { + t.Fatalf("Bind %s after restart: want ErrBindAlreadyBound, got %v", r, err) + } + } + if got, ok := pubB.LastPublished("v1", "r2"); !ok || got.Epoch != 2 { + t.Fatalf("reloaded line=%+v ok=%t want r2 epoch 2", got, ok) + } +} diff --git a/seaweed-block/core/authority/bind_volume_regression_test.go b/seaweed-block/core/authority/bind_volume_regression_test.go new file mode 100644 index 0000000000..fed669071d --- /dev/null +++ b/seaweed-block/core/authority/bind_volume_regression_test.go @@ -0,0 +1,62 @@ +package authority + +import ( + "context" + "testing" + "time" +) + +type bindRegressionDirective struct { + asks *StaticDirective + processed chan struct{} + calls int +} + +func (d *bindRegressionDirective) Next(ctx context.Context) (AssignmentAsk, error) { + d.calls++ + if d.calls == 3 { + // Run requests another ask only after it settles the preceding apply. + close(d.processed) + <-ctx.Done() + return AssignmentAsk{}, ctx.Err() + } + return d.asks.Next(ctx) +} + +func TestPublisher_RunRejectsSecondSlotGenesisBind(t *testing.T) { + d := &bindRegressionDirective{processed: make(chan struct{}), asks: NewStaticDirective([]AssignmentAsk{ + {VolumeID: "v", ReplicaID: "r1", DataAddr: "d1", CtrlAddr: "c1", Intent: IntentBind}, + {VolumeID: "v", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", Intent: IntentBind}, + })} + pub := NewPublisher(d) + first, cancelFirst := pub.Subscribe("v", "r1") + defer cancelFirst() + second, cancelSecond := pub.Subscribe("v", "r2") + defer cancelSecond() + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- pub.Run(ctx) }() + t.Cleanup(func() { + cancel() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Error("publisher did not stop") + } + }) + select { + case <-first: + case <-time.After(2 * time.Second): + t.Fatal("first Bind did not publish") + } + select { + case <-d.processed: + case <-time.After(2 * time.Second): + t.Fatal("publisher did not settle both asks") + } + select { + case got := <-second: + t.Fatalf("second slot received genesis authority: %+v; first volume Bind must exclude a second genesis", got) + default: + } +} diff --git a/seaweed-block/core/authority/directive.go b/seaweed-block/core/authority/directive.go index 958f10e3d2..f65349d76b 100644 --- a/seaweed-block/core/authority/directive.go +++ b/seaweed-block/core/authority/directive.go @@ -26,8 +26,10 @@ type AskIntent int const ( // IntentBind: first-time binding for (VolumeID, ReplicaID). - // Publisher mints Epoch=1, EndpointVersion=1. Rejected if a - // prior publish already exists for the key. + // Publisher mints Epoch=1, EndpointVersion=1. Rejected + // (ErrBindAlreadyBound) if a prior publish already exists for the + // key or for any other slot of the same volume: Bind is genesis + // for the volume; another slot is reached by IntentReassign. IntentBind AskIntent = iota + 1 // IntentRefreshEndpoint: same volume/replica, new transport diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index ea4f05b7fa..6d6301e1b3 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -92,41 +92,6 @@ func (p *Publisher) workspaceSkew(lease *WorkspaceLease) time.Duration { return skew } -func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { - if err := ctx.Err(); err != nil { - return WorkspaceLease{}, err - } - p.mu.Lock() - defer p.mu.Unlock() - _, line, ok := p.workspaceLineLocked(volume) - if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch { - return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority") - } - s := cloneWorkspace(p.workspace[volume]) - if s == nil { - s = &WorkspaceState{} - } - if len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued { - return WorkspaceLease{}, fmt.Errorf("workspace lease: move pending") - } - now := p.workspaceNow() - if s.Lease != nil { - if s.Lease.Revoking { - return *s.Lease, nil - } // tell the host to drain; never extend - if now.UnixNano() >= s.Lease.ExpiresAtNS || !now.Before(p.workspaceLeaseDeadline[volume]) { - return WorkspaceLease{}, fmt.Errorf("workspace lease expired or revoking") - } - } - lease := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(s.Lease))} - s.Lease = &lease - if err := p.persistWorkspaceLocked(volume, s); err != nil { - return WorkspaceLease{}, err - } - p.workspaceLeaseDeadline[volume] = now.Add(p.workspaceTTL) - return lease, nil -} - // Replica IDs are logical assignment identities; HEAD.Holder is qualified // as / and is checked separately against ExpectedHost. type WorkspaceMoveRequest struct { @@ -246,7 +211,7 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a return fmt.Errorf("workspace revoke ACK: stale or unsolicited") } now := p.workspaceNow() - if now.UnixNano() >= s.Lease.ExpiresAtNS || !now.Before(p.workspaceLeaseDeadline[volume]) { + if now.UnixNano() >= s.Lease.ExpiresAtNS || !now.Before(p.leaseDeadlineLocked(volume)) { return fmt.Errorf("workspace revoke ACK: lease expired; forced move required") } if s.Ack != nil && *s.Ack != ack { @@ -286,10 +251,12 @@ func (p *Publisher) persistWorkspaceLocked(volume string, s *WorkspaceState) err WriteSeq: p.writeSeqByVolume[volume] + 1, Workspace: cloneWorkspace(s)} if err := p.store.Put(record); err != nil { p.workspaceUncertain[volume] = true + p.refreshLeaseViewLocked(volume) return err } p.writeSeqByVolume[volume] = record.WriteSeq p.workspace[volume] = cloneWorkspace(s) + p.refreshLeaseViewLocked(volume) return nil } @@ -313,12 +280,20 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra if !ok || line.info.Epoch != q.ExpectedEpoch || line.info.ReplicaID != q.ExpectedReplicaID || s == nil || s.Lease == nil { return nil, 0, fmt.Errorf("workspace move: missing or changed authority/lease") } + var lostUntil int64 if q.Kind == "forced" { now := p.workspaceNow() skew := p.workspaceSkew(s.Lease) - if now.Before(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew)) || now.Before(p.workspaceLeaseDeadline[q.VolumeID].Add(skew)) { + deadline := p.leaseDeadlineLocked(q.VolumeID) + if now.Before(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) { return nil, 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") } + // The audit bound only, in wall time: the admission above keeps both + // predicates (the deadline's monotonic reading included). + lostUntil = time.Unix(0, s.Lease.ExpiresAtNS).Add(skew).UnixNano() + if d := deadline.Add(skew).UnixNano(); d > lostUntil { + lostUntil = d + } } // A restart may resume the identical durable reservation; it never grants // a different request the reserved epoch. @@ -327,6 +302,15 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra if r.Issued || !sameWorkspaceRequest(r, q) { return nil, 0, fmt.Errorf("workspace move reservation differs") } + // A forced reservation issues only with the exact range recorded + // before it; a missing one (a reservation older than lost ranges, + // or a skipped side file) is refused, never recomputed: a new + // request records a fresh range. + if r.Kind == "forced" { + if _, ok := p.lostRangeLocked(q.VolumeID, r.RequestID, r.NewEpoch); !ok { + return nil, 0, fmt.Errorf("workspace forced move reservation %s has no recorded lost range; retry with a new request id", r.RequestID) + } + } s.Moves[idx].Issued = true s.Lease = nil s.Ack = nil @@ -352,6 +336,12 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra } r := WorkspaceMoveRecord{RequestID: q.RequestID, VolumeID: q.VolumeID, OldHost: q.ExpectedHost, NewHost: q.TargetHost, OldReplicaID: q.ExpectedReplicaID, NewReplicaID: q.TargetReplicaID, Kind: q.Kind, OldEpoch: q.ExpectedEpoch, NewEpoch: max + 1, HeadGen: h.Gen, RemoteLSN: h.RemoteLSN, TargetDataAddr: q.TargetDataAddr, TargetCtrlAddr: q.TargetCtrlAddr} + if q.Kind == "forced" { + lost := WorkspaceLostRange{RequestID: r.RequestID, NewEpoch: r.NewEpoch, OldReplicaID: r.OldReplicaID, OldEpoch: r.OldEpoch, LostAfterLSN: r.RemoteLSN, LostUntilNS: lostUntil} + if err := p.recordLostRangeLocked(q.VolumeID, lost); err != nil { + return nil, 0, err + } + } s.Moves = append(s.Moves, r) if err := p.persistWorkspaceLocked(q.VolumeID, s); err != nil { return nil, 0, err diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go new file mode 100644 index 0000000000..2a43a9c5b9 --- /dev/null +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -0,0 +1,1215 @@ +package authority + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// GREEN-gating controls for the #205 fix (design r1 section 8). + +// hookStore runs before (an error is a known no-write) and after (an error +// after the real Put is an unknown outcome: the record landed) hooks. +type hookStore struct { + AuthorityStore + before atomic.Pointer[func(DurableRecord) error] + after atomic.Pointer[func(DurableRecord) error] +} + +func (s *hookStore) Put(r DurableRecord) error { + if f := s.before.Load(); f != nil { + if err := (*f)(r); err != nil { + return err + } + } + if err := s.AuthorityStore.Put(r); err != nil { + return err + } + if f := s.after.Load(); f != nil { + return (*f)(r) + } + return nil +} + +func (s *hookStore) setBefore(f func(DurableRecord) error) { s.before.Store(&f) } +func (s *hookStore) setAfter(f func(DurableRecord) error) { s.after.Store(&f) } + +// isExtension reports a lease write that raises the horizon above firstH and +// is not a revocation: the extender's write. +func isExtension(r DurableRecord, volume string, firstH int64) bool { + return r.VolumeID == volume && r.Workspace != nil && r.Workspace.Lease != nil && !r.Workspace.Lease.Revoking && r.Workspace.Lease.ExpiresAtNS > firstH +} + +type testClock struct{ ns atomic.Int64 } + +func newTestClock() *testClock { + c := &testClock{} + c.ns.Store(time.Unix(1000, 0).UnixNano()) + return c +} +func (c *testClock) now() time.Time { return time.Unix(0, c.ns.Load()) } +func (c *testClock) at(sec float64) { + c.ns.Store(time.Unix(1000, 0).Add(time.Duration(sec * float64(time.Second))).UnixNano()) +} +func (c *testClock) sec(sec float64) time.Time { + return time.Unix(1000, 0).Add(time.Duration(sec * float64(time.Second))) +} + +// newLeasePublisher joins extenders on cleanup, before the store closes +// (newTempStore registers its Close first, so it runs later). +func newLeasePublisher(t *testing.T, store AuthorityStore, ttl time.Duration, c *testClock) *Publisher { + t.Helper() + p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(ttl, c.now)) + t.Cleanup(p.CloseWorkspaceExtenders) + return p +} + +func bindAndGrant(t *testing.T, p *Publisher, volume, replica string) WorkspaceLease { + t.Helper() + if err := p.apply(AssignmentAsk{VolumeID: volume, ReplicaID: replica, DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + l, err := p.RenewWorkspaceLease(context.Background(), volume, replica, 1) + if err != nil { + t.Fatal(err) + } + return l +} + +// waitExtenders joins every admitted extender (tests only; no concurrent +// admission while waiting). +// waitExtenders joins every admitted extender. No wall-clock bound (#227): +// extenders are finite (each makes at most one store write), so the join is +// the progress condition; a hang is reported by the go test timeout. +func waitExtenders(t *testing.T, p *Publisher) { + t.Helper() + p.extWG.Wait() +} + +// assertLeaseViewMatches checks INV-LEASE-VIEW-001: with p.mu held, every +// volume's view equals derive(published state). +func assertLeaseViewMatches(t *testing.T, p *Publisher, what string) { + t.Helper() + p.mu.Lock() + defer p.mu.Unlock() + vols := map[string]bool{} + for k := range p.state { + vols[k.volumeID] = true + } + for v := range p.workspace { + vols[v] = true + } + for v := range p.workspaceUncertain { + vols[v] = true + } + p.leaseMu.Lock() + for v := range p.leaseViews { + vols[v] = true + } + p.leaseMu.Unlock() + for v := range vols { + want := p.deriveLeaseLocked(v) + p.leaseMu.Lock() + var got leaseDerived + if lv := p.leaseViews[v]; lv != nil { + got = lv.d + } + p.leaseMu.Unlock() + if got != want { + t.Fatalf("%s: INV-LEASE-VIEW-001 broken for %s:\n view %+v\n derive %+v", what, v, got, want) + } + } +} + +func forcedMove(volume, id string) (WorkspaceMoveRequest, WorkspaceHead) { + return WorkspaceMoveRequest{RequestID: id, VolumeID: volume, ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}, + WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42} +} + +// The view equals derive(published) after every writer kind: bind, first +// grant, extension, endpoint refresh, revocation, ACK, clean move issue, a +// move reservation whose issue write fails (uncertain via apply), a failed +// extension (uncertain via persistWorkspaceLocked), reload and close. +func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + check := func(what string) { t.Helper(); assertLeaseViewMatches(t, p, what) } + ctx := context.Background() + check("empty") + for _, v := range []string{"v", "w", "x"} { + if err := p.apply(AssignmentAsk{VolumeID: v, ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + } + check("bind") + if err := p.apply(AssignmentAsk{VolumeID: "x", ReplicaID: "r", DataAddr: "d1", CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err != nil { + t.Fatal(err) + } + check("endpoint refresh, not enrolled") + for _, v := range []string{"v", "w", "x"} { + if _, err := p.RenewWorkspaceLease(ctx, v, "r", 1); err != nil { + t.Fatal(err) + } + } + check("first grants") + firstH := p.WorkspaceState("v").Lease.ExpiresAtNS + c.at(10) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + waitExtenders(t, p) + if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != c.sec(55).UnixNano() || got <= firstH { + t.Fatalf("extension did not publish trigger+1.5*TTL: %d", got) + } + check("extension") + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d2", CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err != nil { + t.Fatal(err) + } + check("endpoint refresh, enrolled") + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + check("revocation") + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil { + t.Fatal(err) + } + check("ack") + clean := WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} + if _, err := p.MoveWorkspace(ctx, clean, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42, Detached: true}); err != nil { + t.Fatal(err) + } + check("clean move issued") + if p.leaseDeadlineLockedForTest("v") != (time.Time{}) { + t.Fatal("move issue kept the old deadline") + } + // w: forced move whose issue write fails after the reservation persisted. + c.at(30 + 15 + 20 + 1) // past w's horizon (45) + skew (20) + hs.setBefore(func(r DurableRecord) error { + if r.VolumeID == "w" && r.Workspace != nil && len(r.Workspace.Moves) > 0 && r.Workspace.Moves[len(r.Workspace.Moves)-1].Issued { + return errors.New("injected issue write failure") + } + return nil + }) + q, h := forcedMove("w", "forced-w") + if _, err := p.MoveWorkspace(ctx, q, h); err == nil { + t.Fatal("injected issue failure ignored") + } + check("move reservation, failed issue (uncertain via apply)") + if st := p.WorkspaceState("w"); len(st.Moves) != 1 || st.Moves[0].Issued { + t.Fatalf("reservation not published: %+v", st) + } + // x: a failed extension latches uncertainty. + c.at(0) + p2Disk, _ := newTempStore(t) + hs2 := &hookStore{AuthorityStore: p2Disk} + p2 := newLeasePublisher(t, hs2, 30*time.Second, c) + bindAndGrant(t, p2, "x", "r") + firstX := p2.WorkspaceState("x").Lease.ExpiresAtNS + hs2.setBefore(func(r DurableRecord) error { + if isExtension(r, "x", firstX) { + return errors.New("injected extension write failure") + } + return nil + }) + c.at(10) + if _, err := p2.RenewWorkspaceLease(ctx, "x", "r", 1); err != nil { + t.Fatal(err) + } + waitExtenders(t, p2) + assertLeaseViewMatches(t, p2, "failed extension (uncertain via persistWorkspaceLocked)") + if !p2.workspaceUncertainForTest("x") { + t.Fatal("failed extension did not latch uncertainty") + } + p.CloseWorkspaceExtenders() + check("close") + reloaded := newLeasePublisher(t, disk, 30*time.Second, c) + assertLeaseViewMatches(t, reloaded, "reload") +} + +func (p *Publisher) leaseDeadlineLockedForTest(v string) time.Time { + p.mu.Lock() + defer p.mu.Unlock() + return p.leaseDeadlineLocked(v) +} + +func (p *Publisher) workspaceUncertainForTest(v string) bool { + p.mu.Lock() + defer p.mu.Unlock() + return p.workspaceUncertain[v] +} + +// Control 1: with the store stalled for good, grants shrink to the durable +// horizon, a renewal that would leave no host validity is refused, and a +// renewal at the horizon is refused. The stall is exercised by the extender +// (puts > 0), so a green cannot bypass it. +func TestWorkspaceLeaseClampsToHorizonUnderStalledStore(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + horizon := p.WorkspaceState("v").Lease.ExpiresAtNS // 1045 + var puts atomic.Int64 + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + hs.setBefore(func(r DurableRecord) error { + if isExtension(r, "v", horizon) { + puts.Add(1) + enterOnce.Do(func() { close(entered) }) + <-release + } + return nil + }) + t.Cleanup(func() { releaseOnce.Do(func() { close(release) }) }) // before Close joins + ctx := context.Background() + c.at(10) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("extender never reached the store") + } + c.at(20) + start := time.Now() + l, err := p.RenewWorkspaceLease(ctx, "v", "r", 1) + if err != nil { + t.Fatal(err) + } + if took := time.Since(start); took > time.Second { + t.Fatalf("renewal waited %s behind the stalled extender", took) + } + if l.ExpiresAtNS > horizon { + t.Fatalf("grant %s beyond the durable horizon %s", time.Unix(0, l.ExpiresAtNS), time.Unix(0, horizon)) + } + if l.ExpiresAtNS != horizon { + t.Fatalf("grant not clamped to the horizon: %s", time.Unix(0, l.ExpiresAtNS)) + } + c.at(35) // horizon - skew/2 = 1035: no positive host validity + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil || !strings.Contains(err.Error(), "no host validity") { + t.Fatalf("renewal without host validity: %v", err) + } + c.at(45) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil { + t.Fatal("renewal at the durable horizon accepted") + } + if puts.Load() == 0 { + t.Fatal("the stall was never exercised by an extender write") + } +} + +// Control 2: a restarted master honours the persisted (extended) horizon in +// the forced barrier: max(horizon, restart+TTL) + skew. +func TestWorkspaceRestartForcedBarrierHonoursHorizon(t *testing.T) { + disk, _ := newTempStore(t) + c := newTestClock() + p := newLeasePublisher(t, disk, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + c.at(10) + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { + t.Fatal(err) + } + waitExtenders(t, p) + if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != c.sec(55).UnixNano() { + t.Fatalf("extension not durable: %s", time.Unix(0, got)) + } + p.CloseWorkspaceExtenders() + c.at(12) + r := newLeasePublisher(t, disk, 30*time.Second, c) // reload deadline 1042 < horizon 1055 + q, h := forcedMove("v", "forced") + c.ns.Store(c.sec(75).UnixNano() - 1) + if _, err := r.MoveWorkspace(context.Background(), q, h); err == nil { + t.Fatal("forced move before persisted horizon + skew after restart") + } + c.at(75) + if _, err := r.MoveWorkspace(context.Background(), q, h); err != nil { + t.Fatal("forced move at horizon + skew refused:", err) + } +} + +// Control 3: an extension whose rename landed but whose directory sync +// failed is an unknown write: the volume is uncertain, the next renewal is +// refused (INV-AUTH-UNCERTAIN-001), and a reload finds the landed horizon and +// bars a forced move until that horizon + skew. +func TestWorkspaceAmbiguousExtensionLatchesUncertainty(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + first := p.WorkspaceState("v").Lease.ExpiresAtNS + hs.setAfter(func(r DurableRecord) error { + if isExtension(r, "v", first) { + return errors.New("injected: directory sync failed after rename") + } + return nil + }) + c.at(10) + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { + t.Fatal(err) + } + waitExtenders(t, p) + if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != first { + t.Fatalf("an unknown write was published: %s", time.Unix(0, got)) + } + c.at(11) + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil || !strings.Contains(err.Error(), "uncertain") { + t.Fatalf("renewal after an unknown write: %v; want refused as uncertain", err) + } + // INV-AUTH-UNCERTAIN-001: every further authority change of the volume + // is refused until a restart. + if err := p.BeginWorkspaceRevocation(context.Background(), "v", "r", 1); err == nil { + t.Fatal("revocation accepted on an uncertain volume") + } + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d2", CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err == nil { + t.Fatal("authority change accepted on an uncertain volume") + } + p.CloseWorkspaceExtenders() + c.at(12) + r := newLeasePublisher(t, disk, 30*time.Second, c) + landed := r.WorkspaceState("v").Lease.ExpiresAtNS + if landed != c.sec(55).UnixNano() { + t.Fatalf("reload did not find the landed horizon: %s", time.Unix(0, landed)) + } + q, h := forcedMove("v", "forced") + c.ns.Store(time.Unix(0, landed).Add(20*time.Second).UnixNano() - 1) + if _, err := r.MoveWorkspace(context.Background(), q, h); err == nil { + t.Fatal("forced move before the landed horizon + skew") + } + c.ns.Store(time.Unix(0, landed).Add(20 * time.Second).UnixNano()) + if _, err := r.MoveWorkspace(context.Background(), q, h); err != nil { + t.Fatal(err) + } +} + +// Control 4: an extender held inside its Put holds p.mu; a revocation or a +// forced move of the same volume waits, then runs after the extension is +// published, so its record carries the extended horizon (ordered). +func TestWorkspaceExtenderHeldOrdersSameVolumeWriters(t *testing.T) { + for _, op := range []string{"revocation", "forced-move"} { + t.Run(op, func(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + first := p.WorkspaceState("v").Lease.ExpiresAtNS + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + releaseFn := func() { releaseOnce.Do(func() { close(release) }) } + hs.setBefore(func(r DurableRecord) error { + if isExtension(r, "v", first) { + enterOnce.Do(func() { close(entered) }) + <-release + } + return nil + }) + done := make(chan error, 1) + started := false + // Installed before the extender is triggered: on any failure the + // held write is released and the writer settled (bounded) before + // the publisher joins its extenders and the store closes. + t.Cleanup(func() { + releaseFn() + if started { + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("writer did not settle") + } + } + }) + c.at(10) + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { + t.Fatal(err) + } + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("extender never reached the store") + } + started = true + if op == "revocation" { + go func() { done <- p.BeginWorkspaceRevocation(context.Background(), "v", "r", 1) }() + } else { + c.at(66) // past the OLD barrier max(1045, 1040) + 20 + q, h := forcedMove("v", "forced") + go func() { _, err := p.MoveWorkspace(context.Background(), q, h); done <- err }() + } + select { + case err := <-done: + done <- err // keep it for the cleanup join + t.Fatalf("%s ran while the extender held p.mu: %v", op, err) + case <-time.After(200 * time.Millisecond): + } + releaseFn() + var err error + select { + case err = <-done: + done <- err + case <-time.After(5 * time.Second): + t.Fatalf("%s did not finish after the extender", op) + } + want := c.sec(55).UnixNano() + st := p.WorkspaceState("v") + if op == "revocation" { + if err != nil || st.Lease == nil || !st.Lease.Revoking || st.Lease.ExpiresAtNS != want { + t.Fatalf("revocation not ordered after the extension: %v %+v", err, st.Lease) + } + } else if err == nil || len(st.Moves) != 0 || st.Lease.ExpiresAtNS != want { + t.Fatalf("forced move did not see the extended horizon: %v %+v", err, st) + } + p.CloseWorkspaceExtenders() + r := newLeasePublisher(t, disk, 30*time.Second, c) + if got := r.WorkspaceState("v").Lease; got.ExpiresAtNS != want || got.Revoking != (op == "revocation") { + t.Fatalf("reload: %+v", got) + } + }) + } +} + +// Control 5: a renewal of the same volume during a held revocation write sees +// the last published state (a grant under the horizon), then the revoking +// lease with the granted expiry and no extension. During a held forced-move +// write (barrier passed) a renewal is refused. +func TestWorkspaceSameVolumeRenewalDuringHeldWrite(t *testing.T) { + t.Run("revocation", func(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + horizon := p.WorkspaceState("v").Lease.ExpiresAtNS + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + releaseFn := func() { releaseOnce.Do(func() { close(release) }) } + hs.setBefore(func(r DurableRecord) error { + if r.VolumeID == "v" && r.Workspace != nil && r.Workspace.Lease != nil && r.Workspace.Lease.Revoking { + enterOnce.Do(func() { close(entered) }) + <-release + } + return nil + }) + done := make(chan error, 1) + go func() { done <- p.BeginWorkspaceRevocation(context.Background(), "v", "r", 1) }() + t.Cleanup(func() { + releaseFn() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("revocation did not settle") + } + }) + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("revocation write never reached the store") + } + c.at(5) + l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1) + if err != nil || l.Revoking || l.ExpiresAtNS != c.sec(35).UnixNano() || l.ExpiresAtNS > horizon { + t.Fatalf("renewal during the held revocation write: %+v %v", l, err) + } + releaseFn() + select { + case err := <-done: + done <- err + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("revocation did not finish after the release") + } + for _, at := range []float64{6, 7} { + c.at(at) + l, err = p.RenewWorkspaceLease(context.Background(), "v", "r", 1) + if err != nil || !l.Revoking || l.ExpiresAtNS != c.sec(35).UnixNano() { + t.Fatalf("revoking renewal at %v: %+v %v; want the granted expiry, never extended", at, l, err) + } + } + }) + t.Run("forced-move", func(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + releaseFn := func() { releaseOnce.Do(func() { close(release) }) } + hs.setBefore(func(r DurableRecord) error { + if r.VolumeID == "v" && r.Workspace != nil && len(r.Workspace.Moves) > 0 && !r.Workspace.Moves[len(r.Workspace.Moves)-1].Issued { + enterOnce.Do(func() { close(entered) }) + <-release + } + return nil + }) + c.at(66) // past horizon 1045 + skew 20 + q, h := forcedMove("v", "forced") + done := make(chan error, 1) + go func() { _, err := p.MoveWorkspace(context.Background(), q, h); done <- err }() + t.Cleanup(func() { + releaseFn() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("forced move did not settle") + } + }) + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("move reservation write never reached the store") + } + start := time.Now() + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil { + t.Fatal("renewal granted during a forced move past the barrier") + } + if took := time.Since(start); took > time.Second { + t.Fatalf("renewal waited %s on the held move", took) + } + releaseFn() + select { + case err := <-done: + done <- err + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("forced move did not finish after the release") + } + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil { + t.Fatal("old-epoch renewal after the move") + } + }) +} + +// Control 7 (run with -race): N volumes renew while apply, revocation, ACK, +// a clean move, a forced move, extenders and Close run. A bounded handshake +// holds the first horizon-extension write inside the store while renewals +// keep succeeding and the writers and Close are in flight (queued on the +// publisher lock behind it); then it is released. Required afterwards: every +// eligible volume had successful grants, at least one extension write was +// observed (classified by content: a raised horizon at the same epoch, not +// an ordinary writer's record), no renewal waited 2 s, nothing deadlocked, +// every live lease keeps disk >= published horizon >= every grant (S1), and +// the view equals derive. +func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { + const n = 8 + vol := func(i int) string { return fmt.Sprintf("v%d", i) } + const forcedVol, cleanVol = 2, 1 + eligible := []int{0, 3, 4, 5, 6, 7} // stay leased throughout; v0 also takes endpoint refreshes + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + + // Extension classification and the overlap hold. + var classMu sync.Mutex + lastH := map[string]int64{} + lastEpoch := map[string]uint64{} + var extensions atomic.Int64 + heldEntered, heldRelease := make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + // The publisher clock is frozen while the extension write is held (#247 + // hang): the held write holds p.mu, so every other volume's extender queues + // and no horizon can move. With a running clock a late test goroutine could + // let horizons expire before each volume got a grant under the hold (the + // progress condition never holds), or before the writers run after the + // release (a revoke ACK finds the lease expired). This test is about lock + // and store ordering, not about lease expiry. + // The clock stays frozen after the release until the clean volume's revoke + // ACK: the endpoint refreshes, the revocation and the ACK queue on p.mu + // behind every volume's extension write (fsync), which on a loaded machine + // can outlast the clean volume's grant, and a revoking lease is never + // extended (in-time ACK has its own tests). The writer then resumes the + // clock from the frozen instant, so it neither jumps over a horizon nor runs + // backwards; extensions run in real time alongside the moves and Close. + // Now/Freeze/Resume are one transaction each. + clock := &leaseTestClock{} + releaseHold := func() { + releaseOnce.Do(func() { close(heldRelease) }) + } + var classifying atomic.Bool + var holding atomic.Bool // set when the extension write is held, before it blocks + var heldVol atomic.Value // string: the volume whose extension write is held + var holdTaken atomic.Bool + var holdMu sync.Mutex + var skippedHolds atomic.Int64 // extension writes not held: some eligible volume lacked headroom + var p *Publisher + // headroom witnesses, at the frozen instant and from each volume's own + // renewal view (the fields RenewWorkspaceLease reads, under the leaf + // leaseMu), that a renewal of every eligible volume and of the clean volume + // grants positive host validity: lease present and live, durable horizon + // minus half the skew after now, and now before the granted deadline. The + // frozen clock and the queued extenders keep it so for the whole hold and, + // for the clean volume, through its revocation and ACK. + var noHeadroom atomic.Value // string: the last volume found without headroom, and why + headroom := func() bool { + now := clock.Now().UnixNano() + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + for _, i := range append(append([]int{}, eligible...), cleanVol) { // the clean volume is revoked and ACKed frozen + lv := p.leaseViews[vol(i)] + if lv == nil || !lv.d.bound || !lv.d.leasePresent || lv.d.revoking || lv.d.movePending || + lv.d.uncertain || lv.d.storeless || lv.d.horizon-lv.d.maxSkewNS/2 <= now || now >= lv.deadline.UnixNano() { + why := "no view" + if lv != nil { + why = fmt.Sprintf("bound=%v present=%v revoking=%v pending=%v uncertain=%v validity=%v deadline-now=%v", + lv.d.bound, lv.d.leasePresent, lv.d.revoking, lv.d.movePending, lv.d.uncertain, + time.Duration(lv.d.horizon-lv.d.maxSkewNS/2-now), time.Duration(lv.deadline.UnixNano()-now)) + } + noHeadroom.Store(vol(i) + ": " + why) + return false + } + } + return true + } + hs.setBefore(func(r DurableRecord) error { + time.Sleep(5 * time.Millisecond) // a slow store + if !classifying.Load() || r.Workspace == nil || r.Workspace.Lease == nil { + return nil + } + l := r.Workspace.Lease + pending := len(r.Workspace.Moves) > 0 && !r.Workspace.Moves[len(r.Workspace.Moves)-1].Issued + classMu.Lock() + ext := !l.Revoking && !pending && l.Epoch == lastEpoch[r.VolumeID] && l.ExpiresAtNS > lastH[r.VolumeID] + if ext { + lastH[r.VolumeID] = l.ExpiresAtNS + } + classMu.Unlock() + if ext { + extensions.Add(1) + first := false + if !holdTaken.Load() { + holdMu.Lock() + if !holdTaken.Load() { + clock.Freeze() + if headroom() { + holdTaken.Store(true) + first = true + } else { + clock.Resume() // try again at a later extension write + skippedHolds.Add(1) + } + } + holdMu.Unlock() + } + if first { + heldVol.Store(r.VolumeID) // the volume whose extension write is held + holding.Store(true) // before the hold: a renewal started after this saw it + close(heldEntered) + <-heldRelease + } + } + return nil + }) + // The publisher clock is real time plus an offset. The forced-move volume + // is granted at offset -10 s, so by offset 0 its horizon + skew barrier has + // passed; the clock only moves forward. + clock.SetOffset(-10 * time.Second) + p = NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, clock.Now)) + t.Cleanup(p.CloseWorkspaceExtenders) + ctx := context.Background() + bindAndGrant(t, p, vol(forcedVol), "r") // never renewed again + clock.SetOffset(0) + // Set-up writes are real store writes (fsync): on a loaded machine binding + // the volumes can take longer than a TTL, and the first-bound volume would + // expire before its renewer starts (by design it never recovers). The clock + // stays frozen through the set-up and resumes just before the renewers. + clock.Freeze() + for i := 0; i < n; i++ { + if i != forcedVol { + bindAndGrant(t, p, vol(i), "r") + } + } + for i := 0; i < n; i++ { + st := p.WorkspaceState(vol(i)) + lastH[vol(i)], lastEpoch[vol(i)] = st.Lease.ExpiresAtNS, st.Lease.Epoch + } + clock.Resume() + classifying.Store(true) + + var grants [n]atomic.Int64 + var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held + var returnedUnderHold [n]atomic.Int64 // calls (any outcome) that started while the extension write was held + var refusedUnderHold atomic.Value // string: a refusal of a call started under the hold, before the writers + var writersGo atomic.Bool // set before the writers start + var maxGrant [n]atomic.Int64 + var slowest atomic.Int64 + stop := make(chan struct{}) + var stopOnce sync.Once + stopRenewers := func() { stopOnce.Do(func() { close(stop) }) } + var wg sync.WaitGroup + writersDone := make(chan error, 1) + closed := make(chan struct{}) + writersStarted, closeStarted := false, false + // Bounded cleanup on every path: release the hold, stop renewers, settle + // every worker, and only then let the fixtures close. + t.Cleanup(func() { + releaseHold() + clock.Resume() + stopRenewers() + settled := make(chan struct{}) + go func() { wg.Wait(); close(settled) }() + select { + case <-settled: + case <-time.After(10 * time.Second): + t.Error("renewers did not settle") + } + if writersStarted { + select { + case <-writersDone: + case <-time.After(10 * time.Second): + t.Error("writers did not settle") + } + } + if closeStarted { + select { + case <-closed: + case <-time.After(10 * time.Second): + t.Error("Close did not settle") + } + } + }) + for _, i := range append(append([]int{}, eligible...), cleanVol) { + wg.Add(1) + go func(i int) { + defer wg.Done() + for { + select { + case <-stop: + return + default: + } + fresh := holding.Load() // the call starts while the extension write is held + beforeWriters := !writersGo.Load() + start := time.Now() + l, err := p.RenewWorkspaceLease(ctx, vol(i), "r", 1) + if d := int64(time.Since(start)); d > slowest.Load() { + slowest.Store(d) + } + if fresh { + returnedUnderHold[i].Add(1) + // Headroom was witnessed at the frozen instant: until the + // writers start, every such renewal must grant (any refusal, + // a horizon error included, fails). + if beforeWriters && (err != nil || l.Revoking) { + refusedUnderHold.CompareAndSwap(nil, fmt.Sprintf("%s: %+v %v", vol(i), l, err)) + } + } + if err == nil && !l.Revoking { + grants[i].Add(1) + if fresh { + underHold[i].Add(1) + } + if l.ExpiresAtNS > maxGrant[i].Load() { + maxGrant[i].Store(l.ExpiresAtNS) + } + } + time.Sleep(5 * time.Millisecond) + } + }(i) + } + + // Handshake 1: the first extension write is held inside the store. + // Progress handshakes (#227) with a real-time failure exit (never a pass): + // the cleanup releases the hold and joins every worker. + select { + case <-heldEntered: // renewers keep triggering extensions + case <-time.After(30 * time.Second): + nh, _ := noHeadroom.Load().(string) + t.Fatalf("no extension write was held within 30 s (%d extension writes, %d not held for lack of headroom; last: %s)", + extensions.Load(), skippedHolds.Load(), nh) + } + // A late test goroutine (machine load), longer than a horizon (1.5 x TTL): + // with the clock frozen under the hold, no volume can lose its lease here. + time.Sleep(3500 * time.Millisecond) + // Handshake 2: renewals keep succeeding while it is held. + // Progress, no timer (#227): every eligible volume gains a grant from a call + // that STARTED while the extension write was held (a reply computed before + // the hold does not count); renewals that waited for it would never return. + // The hold was taken only with headroom witnessed for every eligible volume + // at the frozen instant, so no refusal is allowed here. + held, _ := heldVol.Load().(string) + for give := time.Now().Add(30 * time.Second); ; time.Sleep(5 * time.Millisecond) { + if r, _ := refusedUnderHold.Load().(string); r != "" { + t.Fatalf("under the held extension of %s, with headroom witnessed: refused %s", held, r) + } + all := true + for _, i := range eligible { + if underHold[i].Load() == 0 { + all = false + } + } + if all { + break + } + if time.Now().After(give) { + t.Fatalf("under the held extension of %s within 30 s: grants %v, returned calls %v", held, + underHoldCounts(&underHold, eligible), underHoldCounts(&returnedUnderHold, eligible)) + } + } + t.Logf("under the held extension of %s (%d extension writes not held for lack of headroom): grants %v", held, + skippedHolds.Load(), underHoldCounts(&underHold, eligible)) + // Writers and Close start while the extension write is held. + writersGo.Store(true) + writersStarted = true + go func() { + for k := 0; k < 5; k++ { + if err := p.apply(AssignmentAsk{VolumeID: vol(0), ReplicaID: "r", DataAddr: fmt.Sprintf("d%d", k), CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err != nil { + writersDone <- fmt.Errorf("endpoint refresh: %w", err) + return + } + } + // Still frozen since the hold (the refreshes above needed p.mu, which the + // held write owned); the clean volume's headroom was witnessed then. + if err := p.BeginWorkspaceRevocation(ctx, vol(cleanVol), "r", 1); err != nil { + clock.Resume() + writersDone <- fmt.Errorf("revocation: %w", err) + return + } + err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}) + clock.Resume() + if err != nil { + writersDone <- fmt.Errorf("ack: %w", err) + return + } + clean := WorkspaceMoveRequest{RequestID: "clean", VolumeID: vol(cleanVol), ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} + if _, err := p.MoveWorkspace(ctx, clean, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42, Detached: true}); err != nil { + writersDone <- fmt.Errorf("clean move: %w", err) + return + } + q, h := forcedMove(vol(forcedVol), "forced") + if _, err := p.MoveWorkspace(ctx, q, h); err != nil { + writersDone <- fmt.Errorf("forced move: %w", err) + return + } + writersDone <- nil + }() + closeStarted = true + go func() { p.CloseWorkspaceExtenders(); close(closed) }() + select { + case err := <-writersDone: + writersDone <- err // keep it for the cleanup join + t.Fatalf("writers finished while the extension write held the publisher lock: %v", err) + case <-closed: + t.Fatal("Close finished while an extension write was held") + case <-time.After(150 * time.Millisecond): + } + releaseHold() + var werr error + select { + case werr = <-writersDone: + writersDone <- werr // keep it for the cleanup join + case <-time.After(20 * time.Second): + t.Fatal("deadlock: writers did not finish after the release") + } + if werr != nil { + t.Fatal("writer:", werr) + } + select { + case <-closed: + case <-time.After(20 * time.Second): + t.Fatal("deadlock: Close did not finish after the release") + } + time.Sleep(50 * time.Millisecond) // renewals continue after Close + stopRenewers() + settled := make(chan struct{}) + go func() { wg.Wait(); close(settled) }() + select { + case <-settled: + case <-time.After(20 * time.Second): + t.Fatal("deadlock: renewers did not finish") + } + + if s := time.Duration(slowest.Load()); s >= 2*time.Second { + t.Fatalf("slowest renewal %s", s) + } + for _, i := range eligible { + if grants[i].Load() == 0 { + t.Fatalf("%s had no successful grant", vol(i)) + } + } + if extensions.Load() == 0 { + t.Fatal("no horizon-extension write was observed") + } + if st := p.WorkspaceState(vol(forcedVol)); st == nil || st.Lease != nil || len(st.Moves) != 1 || !st.Moves[0].Issued || st.Moves[0].Kind != "forced" { + t.Fatalf("forced move not issued: %+v", st) + } + if st := p.WorkspaceState(vol(cleanVol)); st == nil || st.Lease != nil || len(st.Moves) != 1 || st.Moves[0].Kind != "clean" { + t.Fatalf("clean move not issued: %+v", st) + } + assertLeaseViewMatches(t, p, "after concurrency") + recs, err := disk.Load() + if err != nil { + t.Fatal(err) + } + onDisk := map[string]int64{} + for _, r := range recs { + if r.Workspace != nil && r.Workspace.Lease != nil { + onDisk[r.VolumeID] = r.Workspace.Lease.ExpiresAtNS + } + } + for i := 0; i < n; i++ { + st := p.WorkspaceState(vol(i)) + if st == nil || st.Lease == nil { + continue // a completed move cleared the lease (out of S1's scope) + } + if onDisk[vol(i)] < st.Lease.ExpiresAtNS || st.Lease.ExpiresAtNS < maxGrant[i].Load() { + t.Fatalf("%s: S1 broken: disk %d, published horizon %d, max grant %d", vol(i), onDisk[vol(i)], st.Lease.ExpiresAtNS, maxGrant[i].Load()) + } + } + t.Logf("extension writes %d; grants per eligible volume %v", extensions.Load(), func() []int64 { + out := []int64{} + for _, i := range eligible { + out = append(out, grants[i].Load()) + } + return out + }()) +} + +// Control 10a: Close waits for an extender held inside its Put; after Close +// no extension is admitted or written. +func TestWorkspaceCloseJoinsHeldExtender(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + first := p.WorkspaceState("v").Lease.ExpiresAtNS + var puts atomic.Int64 + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + releaseFn := func() { releaseOnce.Do(func() { close(release) }) } + hs.setBefore(func(r DurableRecord) error { + if isExtension(r, "v", first) { + puts.Add(1) + enterOnce.Do(func() { close(entered) }) + <-release + } + return nil + }) + closed := make(chan struct{}) + closeStarted := false + t.Cleanup(func() { // bounded: release, then settle Close before the store closes + releaseFn() + if closeStarted { + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Error("Close did not settle") + } + } + }) + c.at(10) + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { + t.Fatal(err) + } + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("extender never reached the store") + } + closeStarted = true + go func() { p.CloseWorkspaceExtenders(); close(closed) }() + select { + case <-closed: + t.Fatal("Close returned while an extender was inside its write") + case <-time.After(200 * time.Millisecond): + } + releaseFn() + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Fatal("Close did not return after the extender finished") + } + before := puts.Load() + c.at(20) // would trigger an extension (horizon 1055 < 1020 + 37.5) + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { + t.Fatal(err) + } + waitExtenders(t, p) + if puts.Load() != before { + t.Fatal("an extension was written after Close") + } +} + +// Control 10b: an extender admitted before Close that reaches p.mu after +// closing is set aborts with a known no-write. The test holds p.mu itself, so +// the renewal also shows it never needs p.mu. +func TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite(t *testing.T) { + disk, _ := newTempStore(t) + hs := &hookStore{AuthorityStore: disk} + c := newTestClock() + p := newLeasePublisher(t, hs, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + first := p.WorkspaceState("v").Lease.ExpiresAtNS + var puts atomic.Int64 + hs.setBefore(func(r DurableRecord) error { + if isExtension(r, "v", first) { + puts.Add(1) + } + return nil + }) + c.at(10) + p.mu.Lock() + renewed := make(chan error, 1) + go func() { _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); renewed <- err }() + select { + case err := <-renewed: + if err != nil { + p.mu.Unlock() + t.Fatal(err) + } + case <-time.After(2 * time.Second): + p.mu.Unlock() + t.Fatal("renewal waited on p.mu") + } + p.leaseMu.Lock() + admitted := p.leaseViews["v"].extending + p.leaseClosing = true // Close's first step, while the extender waits for p.mu + p.leaseMu.Unlock() + p.mu.Unlock() + if !admitted { + t.Fatal("no extender was admitted") + } + waitExtenders(t, p) + if puts.Load() != 0 || p.WorkspaceState("v").Lease.ExpiresAtNS != first { + t.Fatal("an extender admitted before closing wrote after closing") + } + p.leaseMu.Lock() + extending := p.leaseViews["v"].extending + p.leaseMu.Unlock() + if extending { + t.Fatal("aborted extender left the single-flight flag set") + } +} + +// leaseTestClock is a test publisher clock: real time plus an offset, or a +// frozen instant. Now, Freeze, Resume and SetOffset are each one transaction +// under mu, and Now never returns an earlier time than a previous Now. +type leaseTestClock struct { + mu sync.Mutex + off time.Duration + frozen time.Time // zero = running + last time.Time +} + +func (c *leaseTestClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + t := c.frozen + if t.IsZero() { + t = time.Now().Add(c.off) + } + if t.Before(c.last) { + t = c.last + } + c.last = t + return t +} + +// Freeze stops the clock at its current reading. +func (c *leaseTestClock) Freeze() { + c.mu.Lock() + defer c.mu.Unlock() + if c.frozen.IsZero() { + c.frozen = time.Now().Add(c.off) + if c.frozen.Before(c.last) { + c.frozen = c.last + } + } +} + +// Resume restarts a frozen clock from its frozen instant. +func (c *leaseTestClock) Resume() { + c.mu.Lock() + defer c.mu.Unlock() + if !c.frozen.IsZero() { + c.off = c.frozen.Sub(time.Now()) + c.frozen = time.Time{} + } +} + +func (c *leaseTestClock) SetOffset(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.off = d +} + +func underHoldCounts(u *[8]atomic.Int64, eligible []int) []int64 { + out := make([]int64, 0, len(eligible)) + for _, i := range eligible { + out = append(out, u[i].Load()) + } + return out +} + +// Readers running across freeze/resume transitions never see the test clock +// go backwards, and a resume does not jump forward over the frozen interval. +func TestLeaseTestClockMonotonicAcrossFreezeResume(t *testing.T) { + c := &leaseTestClock{} + var stop atomic.Bool + var wg sync.WaitGroup + errs := make(chan string, 8) + // Registered before launch: every exit, a Fatal included, stops and joins + // the readers (bounded). + t.Cleanup(func() { + stop.Store(true) + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(10 * time.Second): + t.Error("clock readers did not settle") + } + }) + for r := 0; r < 4; r++ { + wg.Add(1) + go func() { + defer wg.Done() + prev := c.Now() + for !stop.Load() { + now := c.Now() + if now.Before(prev) { + select { + case errs <- fmt.Sprintf("clock went backwards: %v after %v", now, prev): + default: + } + return + } + prev = now + } + }() + } + for k := 0; k < 50; k++ { + c.Freeze() + at := c.Now() + time.Sleep(2 * time.Millisecond) + if got := c.Now(); !got.Equal(at) { + t.Fatalf("frozen clock moved: %v -> %v", at, got) + } + r0 := time.Now() + c.Resume() + got := c.Now() + // After a resume the clock advances by at most the real time since the + // resume began (no jump over the frozen interval), and never backwards. + if got.Before(at) || got.Sub(at) > time.Since(r0) { + t.Fatalf("resume moved the clock by %v (real time since resume %v)", got.Sub(at), time.Since(r0)) + } + time.Sleep(time.Millisecond) + } + stop.Store(true) + wg.Wait() + close(errs) + for e := range errs { + t.Fatal(e) + } +} diff --git a/seaweed-block/core/authority/workspace_lease_refusal_race_test.go b/seaweed-block/core/authority/workspace_lease_refusal_race_test.go new file mode 100644 index 0000000000..295989d9cd --- /dev/null +++ b/seaweed-block/core/authority/workspace_lease_refusal_race_test.go @@ -0,0 +1,61 @@ +package authority + +import ( + "context" + "strings" + "sync" + "testing" + "time" +) + +// #242: a renewal refused for lack of host validity formats its error from +// the lease view; that read must happen under leaseMu, because the extender +// (refreshLeaseViewLocked) rewrites the view under leaseMu at any time. +// Run with -race: renewals that take the refusal run while another goroutine +// rewrites the view, as the extender does. +func TestWorkspaceLeaseRefusalReadsTheViewUnderTheLock(t *testing.T) { + disk, _ := newTempStore(t) + c := newTestClock() + p := newLeasePublisher(t, disk, 3*time.Second, c) + bindAndGrant(t, p, "v", "r") + // Force the no-host-validity refusal: the horizon just ahead, a skew + // bound far larger than what is left of it; the granted deadline later. + p.leaseMu.Lock() + lv := p.leaseViews["v"] + lv.d.horizon = c.now().Add(time.Millisecond).UnixNano() + lv.d.maxSkewNS = int64(time.Hour) + lv.deadline = c.now().Add(time.Hour) + p.leaseMu.Unlock() + + const rounds = 200 + var wg sync.WaitGroup + wg.Add(2) + go func() { // the extender's republish: a write of the view under leaseMu + defer wg.Done() + for i := 0; i < rounds; i++ { + p.leaseMu.Lock() + d := lv.d + lv.d = d + p.leaseMu.Unlock() + } + }() + errs := make(chan error, 1) + go func() { + defer wg.Done() + for i := 0; i < rounds; i++ { + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil || !strings.Contains(err.Error(), "leaves no host validity") { + select { + case errs <- err: + default: + } + return + } + } + }() + wg.Wait() + select { + case err := <-errs: + t.Fatalf("renewal with no host validity: %v; want the refusal", err) + default: + } +} diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go new file mode 100644 index 0000000000..6cfc82d8a5 --- /dev/null +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -0,0 +1,311 @@ +package authority + +import ( + "context" + "fmt" + "log" + "time" +) + +// leaseDerived is the part of a volume's lease view that is a pure function +// of published publisher state (derive). Writers recompute it under +// p.mu -> leaseMu at every point where an input changes, so that whenever +// p.mu is released the view equals derive(published) (INV-LEASE-VIEW-001). +type leaseDerived struct { + bound bool // an authority line exists for the volume + replica string + epoch uint64 + leasePresent bool + revoking bool + movePending bool // the last workspace move is reserved, not issued + uncertain bool // a workspace write of the volume failed (INV-AUTH-UNCERTAIN-001) + storeless bool + horizon int64 // published Lease.ExpiresAtNS: durable upper bound of every grant + maxSkewNS int64 + lease WorkspaceLease // the published (durable) lease +} + +// leaseView is one volume's renewal state. Guarded by Publisher.leaseMu. +// deadline (the latest grant, or the restart rule's now+TTL) and extending +// are owned by the view; d is derived. +type leaseView struct { + d leaseDerived + deadline time.Time + extending bool + clamped bool // a renewal was clamped below now+TTL; logged once per streak +} + +// deriveLeaseLocked computes the derived lease view from published state. +// Caller holds p.mu. +func (p *Publisher) deriveLeaseLocked(volume string) leaseDerived { + d := leaseDerived{uncertain: p.workspaceUncertain[volume], storeless: p.store == nil, maxSkewNS: int64(p.workspaceSkew(nil))} + if _, line, ok := p.workspaceLineLocked(volume); ok { + d.bound, d.replica, d.epoch = true, line.info.ReplicaID, line.info.Epoch + } + if s := p.workspace[volume]; s != nil { + d.movePending = len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued + if s.Lease != nil { + d.leasePresent, d.revoking, d.horizon, d.lease = true, s.Lease.Revoking, s.Lease.ExpiresAtNS, *s.Lease + d.maxSkewNS = int64(p.workspaceSkew(s.Lease)) + } + } + return d +} + +// refreshLeaseViewLocked republishes the derived view of volume. Caller holds +// p.mu; this takes leaseMu (the only p.mu -> leaseMu edge besides deadline +// reads). Called at every mutation of a derive input: the authority line, the +// published workspace state, uncertainty, and closing. +func (p *Publisher) refreshLeaseViewLocked(volume string) { + d := p.deriveLeaseLocked(volume) + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + lv := p.leaseViews[volume] + if lv == nil { + lv = &leaseView{} + p.leaseViews[volume] = lv + } + lv.d = d +} + +// leaseDeadlineLocked reads the granted deadline. Caller holds p.mu. +func (p *Publisher) leaseDeadlineLocked(volume string) time.Time { + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + if lv := p.leaseViews[volume]; lv != nil { + return lv.deadline + } + return time.Time{} +} + +// setLeaseDeadlineLocked replaces the deadline (restart rule, move issue) or, +// with raise, raises it to at least t (a grant). Caller holds p.mu. +func (p *Publisher) setLeaseDeadlineLocked(volume string, t time.Time, raise bool) { + d := p.deriveLeaseLocked(volume) + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + lv := p.leaseViews[volume] + if lv == nil { + lv = &leaseView{d: d} + p.leaseViews[volume] = lv + } + if !raise || t.After(lv.deadline) { + lv.deadline = t + } +} + +// replyExpiryNS is the expiry reported to a host: never the raw durable +// horizon, only what was granted (min(horizon, deadline)). +func (lv *leaseView) replyExpiryNS() int64 { + if lv.deadline.IsZero() { + return lv.d.horizon // unreachable: a published lease always has a deadline + } + if dl := lv.deadline.UnixNano(); dl < lv.d.horizon { + return dl + } + return lv.d.horizon +} + +// WorkspaceLeaseReply returns the published lease with its expiry clamped to +// what was granted (min(durable horizon, granted deadline)), for replies that +// report a lease to a host or operator. ok is false without a lease. +func (p *Publisher) WorkspaceLeaseReply(volume string) (WorkspaceLease, bool) { + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + lv := p.leaseViews[volume] + if lv == nil || !lv.d.leasePresent { + return WorkspaceLease{}, false + } + l := lv.d.lease + l.ExpiresAtNS = lv.replyExpiryNS() + return l, true +} + +// RenewWorkspaceLease answers a live holder from memory: it takes only the +// leaf leaseMu, does no I/O and never waits on p.mu or the store. The grant +// is min(now+TTL, durable horizon); a background extender (an ordinary p.mu +// writer) pushes the horizon ahead. Only the first grant of a lease writes +// synchronously (firstWorkspaceGrant). +func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { + if err := ctx.Err(); err != nil { + return WorkspaceLease{}, err + } + p.leaseMu.Lock() + now := p.workspaceNow() // read under leaseMu: the forced-barrier argument needs it + lv := p.leaseViews[volume] + if lv == nil || !lv.d.bound || lv.d.replica != holder || lv.d.epoch != epoch { + p.leaseMu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority") + } + if lv.d.movePending { + p.leaseMu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease: move pending") + } + if !lv.d.leasePresent { + p.leaseMu.Unlock() // never re-enter p.mu while holding the leaf + return p.firstWorkspaceGrant(ctx, volume, holder, epoch) + } + if lv.d.revoking { // tell the host to drain; never extend + l := lv.d.lease + l.ExpiresAtNS = lv.replyExpiryNS() + p.leaseMu.Unlock() + return l, nil + } + if now.UnixNano() >= lv.d.horizon || !now.Before(lv.deadline) { + p.leaseMu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease expired or revoking") + } + // Where the synchronous write used to refuse (persistWorkspaceLocked): + // a renewal never bypasses uncertainty (INV-AUTH-UNCERTAIN-001). + if lv.d.storeless || lv.d.uncertain { + p.leaseMu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain") + } + grant := now.Add(p.workspaceTTL).UnixNano() + clamped := grant > lv.d.horizon + if clamped { + grant = lv.d.horizon + } + // A grant without positive host validity (expiry minus half the skew + // bound, leaseFact) would make the host fence on an invalid reply and lose + // its remaining validity; refuse with an error instead. + if grant-lv.d.maxSkewNS/2 <= now.UnixNano() { + horizon := lv.d.horizon // the view is leaseMu's: read it before the unlock (#242) + p.leaseMu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease: durable horizon %s leaves no host validity", time.Unix(0, horizon).UTC().Format(time.RFC3339Nano)) + } + if g := time.Unix(0, grant); g.After(lv.deadline) { + lv.deadline = g + } + var note string + switch { + case clamped && !lv.clamped: + lv.clamped = true + note = fmt.Sprintf("workspace lease: grants of volume=%s are clamped to the durable horizon %s (%s remaining); extensions are behind", + volume, time.Unix(0, lv.d.horizon).UTC().Format(time.RFC3339Nano), time.Duration(lv.d.horizon-now.UnixNano()).Round(time.Millisecond)) + case !clamped && lv.clamped: + lv.clamped = false + note = fmt.Sprintf("workspace lease: grants of volume=%s are no longer clamped (horizon %s)", volume, time.Unix(0, lv.d.horizon).UTC().Format(time.RFC3339Nano)) + } + if lv.d.horizon < now.Add(p.workspaceTTL+p.workspaceTTL/4).UnixNano() && !lv.extending && !p.leaseClosing { + lv.extending = true + p.extWG.Add(1) // under leaseMu with !closing: no Add can follow CloseWorkspaceExtenders + go p.extendWorkspaceLease(volume, holder, epoch, now) + } + l := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS} + p.leaseMu.Unlock() + if note != "" { + log.Print(note) + } + return l, nil +} + +// firstWorkspaceGrant creates a lease synchronously under p.mu (one write per +// assignment epoch). A host whose first renewal fails does not fence: it has +// no deadline yet and retries. The durable horizon starts at now+1.5*TTL. +func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { + p.mu.Lock() + _, line, ok := p.workspaceLineLocked(volume) + if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch { + p.mu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority") + } + s := cloneWorkspace(p.workspace[volume]) + if s == nil { + s = &WorkspaceState{} + } + if len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued { + p.mu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease: move pending") + } + if s.Lease != nil { + // Another writer created the lease after the view was read. Do not + // re-enter the memory path from here (no mutual recursion): the host has + // no deadline yet, so a failed first renewal does not fence it, and its + // retry takes the memory path. + p.mu.Unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease: created concurrently; retry") + } + now := p.workspaceNow() + skew := int64(p.workspaceSkew(nil)) + grant := now.Add(p.workspaceTTL) + s.Lease = &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: skew} + if err := p.persistWorkspaceLocked(volume, s); err != nil { + p.mu.Unlock() + return WorkspaceLease{}, err + } + p.setLeaseDeadlineLocked(volume, grant, true) + p.mu.Unlock() + return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: skew}, nil +} + +// extendWorkspaceLease is an ordinary writer: under p.mu it rechecks the +// lease and writes horizon H = trigger + 1.5*TTL through +// persistWorkspaceLocked, so its write and its publication are one p.mu +// section. Any write error is an unknown write and latches uncertainty +// (INV-AUTH-UNCERTAIN-001); a failed recheck is a known no-write. +func (p *Publisher) extendWorkspaceLease(volume, holder string, epoch uint64, trigger time.Time) { + defer p.extWG.Done() + var note string + defer func() { + if note != "" { + log.Print(note) + } + }() + p.mu.Lock() + defer p.mu.Unlock() + defer func() { + p.leaseMu.Lock() + if lv := p.leaseViews[volume]; lv != nil { + lv.extending = false + } + p.leaseMu.Unlock() + }() + p.leaseMu.Lock() + closing := p.leaseClosing + p.leaseMu.Unlock() + if closing { + return + } + _, line, ok := p.workspaceLineLocked(volume) + s := cloneWorkspace(p.workspace[volume]) + if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch || s == nil || s.Lease == nil || s.Lease.Revoking || + s.Lease.ReplicaID != holder || s.Lease.Epoch != epoch || (len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued) || + p.workspaceUncertain[volume] || p.store == nil { + return + } + h := trigger.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano() + old := s.Lease.ExpiresAtNS + if h <= old { + return + } + s.Lease.ExpiresAtNS = h + start := time.Now() + err := p.persistWorkspaceLocked(volume, s) + took := time.Since(start).Round(time.Millisecond) + if err != nil { + if p.extendFailures[volume] == 0 { + note = fmt.Sprintf("workspace lease: extension of volume=%s failed after %s (horizon %s, %s remaining); the volume is now uncertain and its renewals are refused: %v", + volume, took, time.Unix(0, old).UTC().Format(time.RFC3339Nano), time.Until(time.Unix(0, old)).Round(time.Millisecond), err) + } + p.extendFailures[volume]++ + return + } + if n := p.extendFailures[volume]; n > 0 { + note = fmt.Sprintf("workspace lease: extension of volume=%s recovered after %d failures, took %s, horizon now %s", volume, n, took, time.Unix(0, h).UTC().Format(time.RFC3339Nano)) + delete(p.extendFailures, volume) + } +} + +// CloseWorkspaceExtenders stops admitting lease extensions and joins every +// admitted extender. Owners call it before closing the authority store: +// closing is set under p.mu -> leaseMu, so an extender either finished its +// write before or sees closing and does not write. +func (p *Publisher) CloseWorkspaceExtenders() { + p.mu.Lock() + p.leaseMu.Lock() + p.leaseClosing = true + p.leaseMu.Unlock() + p.mu.Unlock() + p.extWG.Wait() +} diff --git a/seaweed-block/core/authority/workspace_lost_range.go b/seaweed-block/core/authority/workspace_lost_range.go new file mode 100644 index 0000000000..40d26cd5ae --- /dev/null +++ b/seaweed-block/core/authority/workspace_lost_range.go @@ -0,0 +1,211 @@ +package authority + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" +) + +// WorkspaceLostRange records what a forced move abandoned: the old holder's +// writes after LostAfterLSN (the HEAD frontier the move keeps) are lost, and +// none of them was acknowledged later than LostUntilNS (master time: the +// forced barrier, the lease horizon or restart deadline plus skew). The +// lease carries no write frontier, so the upper bound is a time. +type WorkspaceLostRange struct { + RequestID string + NewEpoch uint64 + OldReplicaID string + OldEpoch uint64 + LostAfterLSN uint64 + LostUntilNS int64 +} + +// lostRangeFileExtension does not end in storeFileExtension: authority +// loaders, old and new, never read these files. +const lostRangeFileExtension = ".lostrange.json" + +type lostRangeEnvelope struct { + Version int `json:"v"` + VolumeID string `json:"volume"` + Ranges []WorkspaceLostRange `json:"ranges"` + Checksum string `json:"checksum"` +} + +func lostRangeChecksum(volumeID string, ranges []WorkspaceLostRange) string { + body, err := json.Marshal(struct { + VolumeID string + Ranges []WorkspaceLostRange + }{volumeID, ranges}) + if err != nil { + return "" + } + sum := sha256.Sum256(body) + return hex.EncodeToString(sum[:]) +} + +// PutWorkspaceLostRanges replaces volumeID's lost ranges atomically (temp +// file, fsync, rename, directory fsync). +func (s *FileAuthorityStore) PutWorkspaceLostRanges(volumeID string, ranges []WorkspaceLostRange) error { + if volumeID == "" { + return fmt.Errorf("authority_store: lost range with empty VolumeID") + } + payload, err := json.Marshal(lostRangeEnvelope{Version: 1, VolumeID: volumeID, Ranges: ranges, Checksum: lostRangeChecksum(volumeID, ranges)}) + if err != nil { + return fmt.Errorf("authority_store: encode lost range: %w", err) + } + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return fmt.Errorf("authority_store: lost range Put on closed store") + } + final := filepath.Join(s.dir, encodeVolumeIDForFilename(volumeID)+lostRangeFileExtension) + temp := final + tempSuffix + f, err := os.OpenFile(temp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) + if err != nil { + return fmt.Errorf("authority_store: open lost range temp: %w", err) + } + _, werr := f.Write(payload) + if werr == nil { + werr = f.Sync() + } + if werr == nil { + werr = testLostRangeFault("before-rename") + } + if cerr := f.Close(); werr == nil { + werr = cerr + } + if werr != nil { + _ = os.Remove(temp) + return fmt.Errorf("authority_store: write lost range temp: %w", werr) + } + if err := renameWithRetry(temp, final); err != nil { + _ = os.Remove(temp) + return fmt.Errorf("authority_store: rename lost range: %w", err) + } + d, err := os.Open(s.dir) + if err != nil { + return fmt.Errorf("authority_store: lost range directory open: %w", err) + } + serr := d.Sync() + if serr == nil { + serr = testLostRangeFault("directory-sync") + } + if cerr := d.Close(); serr == nil { + serr = cerr + } + if serr != nil { + return fmt.Errorf("authority_store: lost range directory fsync: %w", serr) + } + return nil +} + +// LoadWorkspaceLostRanges returns every volume's lost ranges. A file that +// fails its checks is skipped with an error (these are records of loss, not +// authority); only an unreadable directory fails the load. +func (s *FileAuthorityStore) LoadWorkspaceLostRanges() (map[string][]WorkspaceLostRange, []error, error) { + s.mu.Lock() + defer s.mu.Unlock() + entries, err := os.ReadDir(s.dir) + if err != nil { + return nil, nil, fmt.Errorf("authority_store: readdir: %w", err) + } + out := map[string][]WorkspaceLostRange{} + var skips []error + for _, e := range entries { + name := e.Name() + if e.IsDir() || !strings.HasSuffix(name, lostRangeFileExtension) { + continue + } + raw, err := os.ReadFile(filepath.Join(s.dir, name)) + if err != nil { + skips = append(skips, fmt.Errorf("%s: read: %w", name, err)) + continue + } + var env lostRangeEnvelope + switch { + case json.Unmarshal(raw, &env) != nil: + err = errors.New("decode") + case env.Version != 1: + err = fmt.Errorf("version %d unsupported", env.Version) + case env.Checksum != lostRangeChecksum(env.VolumeID, env.Ranges): + err = errors.New("checksum mismatch") + case encodeVolumeIDForFilename(env.VolumeID)+lostRangeFileExtension != name: + err = fmt.Errorf("filename does not match VolumeID %q", env.VolumeID) + } + if err != nil { + skips = append(skips, fmt.Errorf("%s: %w: lost range %v", name, ErrCorruptRecord, err)) + continue + } + out[env.VolumeID] = env.Ranges + } + return out, skips, nil +} + +// testLostRangeFaultHook, test-only, fails PutWorkspaceLostRanges at a named +// step ("before-rename", "directory-sync") when it returns an error. +var testLostRangeFaultHook func(step string) error + +func testLostRangeFault(step string) error { + if h := testLostRangeFaultHook; h != nil { + return h(step) + } + return nil +} + +// lostRangeLocked returns volume's recorded range for (requestID, newEpoch). +// Called under p.mu. +func (p *Publisher) lostRangeLocked(volume, requestID string, newEpoch uint64) (WorkspaceLostRange, bool) { + for _, e := range p.lostRanges[volume] { + if e.RequestID == requestID && e.NewEpoch == newEpoch { + return e, true + } + } + return WorkspaceLostRange{}, false +} + +// recordLostRangeLocked durably records r for volume before the move record +// that issues it is written. An entry whose move never issues is an orphan, +// ignored on read. Called under p.mu. +func (p *Publisher) recordLostRangeLocked(volume string, r WorkspaceLostRange) error { + if p.store == nil { + return fmt.Errorf("workspace forced move: no store to record the lost range") + } + next := make([]WorkspaceLostRange, 0, len(p.lostRanges[volume])+1) + for _, e := range p.lostRanges[volume] { + if e.RequestID != r.RequestID || e.NewEpoch != r.NewEpoch { + next = append(next, e) + } + } + next = append(next, r) + if err := p.store.PutWorkspaceLostRanges(volume, next); err != nil { + return fmt.Errorf("workspace forced move: record lost range: %w", err) + } + p.lostRanges[volume] = next + return nil +} + +// WorkspaceLostRanges returns the lost ranges of volume's issued forced +// moves (an entry with no matching issued move is ignored). +func (p *Publisher) WorkspaceLostRanges(volume string) []WorkspaceLostRange { + p.mu.Lock() + defer p.mu.Unlock() + s := p.workspace[volume] + if s == nil { + return nil + } + var out []WorkspaceLostRange + for _, e := range p.lostRanges[volume] { + for _, m := range s.Moves { + if m.Issued && m.Kind == "forced" && m.RequestID == e.RequestID && m.NewEpoch == e.NewEpoch { + out = append(out, e) + break + } + } + } + return out +} diff --git a/seaweed-block/core/authority/workspace_lost_range_test.go b/seaweed-block/core/authority/workspace_lost_range_test.go new file mode 100644 index 0000000000..4be162bd56 --- /dev/null +++ b/seaweed-block/core/authority/workspace_lost_range_test.go @@ -0,0 +1,339 @@ +package authority + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func forcedLostRangeFixture(t *testing.T, store AuthorityStore, restart bool) (p *Publisher, now *time.Time, barrier time.Time) { + t.Helper() + ctx := context.Background() + at := time.Unix(1000, 0) + now = &at + clock := func() time.Time { return *now } + p = NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(time.Second, clock)) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "old", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "old", 1); err != nil { + t.Fatal(err) + } + if restart { + *now = now.Add(time.Second) + p = NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(time.Second, clock)) + } + lease := p.WorkspaceState("v").Lease + if restart && !p.leaseDeadlineLockedForTest("v").After(time.Unix(0, lease.ExpiresAtNS)) { + t.Fatal("fixture: the restart deadline is not the later barrier term") + } + barrier = time.Unix(0, lease.ExpiresAtNS) + if d := p.leaseDeadlineLockedForTest("v"); d.After(barrier) { + barrier = d + } + return p, now, barrier.Add(p.workspaceSkew(lease)) +} + +var forcedLostRangeReq = WorkspaceMoveRequest{RequestID: "f", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, + TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} +var forcedLostRangeHead = WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42} + +// A forced move records the abandoned range beside its record: the kept HEAD +// frontier and the forced barrier (lease horizon, or after a restart the +// later restart deadline, plus skew) as the latest master time an old-holder +// write can have been acknowledged. A reload returns it; the move record's +// own encoding is unchanged, so older binaries still verify and load it. +func TestWorkspaceForcedMoveRecordsTheLostRange(t *testing.T) { + for _, restart := range []bool{false, true} { + t.Run(map[bool]string{false: "running", true: "after restart"}[restart], func(t *testing.T) { + disk, _ := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, restart) + *now = barrier.Add(-time.Nanosecond) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err == nil { + t.Fatal("forced move admitted before its barrier") + } + if got := p.WorkspaceLostRanges("v"); len(got) != 0 { + t.Fatalf("a refused move recorded a lost range: %+v", got) + } + *now = barrier.Add(5 * time.Second) // the bound is the barrier, not the time of the move + r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead) + if err != nil { + t.Fatal(err) + } + want := WorkspaceLostRange{RequestID: "f", NewEpoch: r.NewEpoch, OldReplicaID: "old", OldEpoch: 1, LostAfterLSN: 42, LostUntilNS: barrier.UnixNano()} + if got := p.WorkspaceLostRanges("v"); len(got) != 1 || got[0] != want { + t.Fatalf("lost range %+v; want [%+v]", got, want) + } + reloaded := NewPublisher(nil, WithStore(disk)) + if got := reloaded.WorkspaceLostRanges("v"); len(got) != 1 || got[0] != want { + t.Fatalf("reloaded lost range %+v; want [%+v]", got, want) + } + raw, err := json.Marshal(reloaded.WorkspaceState("v").Moves[0]) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(raw), "Lost") { + t.Fatalf("the move record's encoding changed: %s", raw) + } + }) + } +} + +// A clean move abandons nothing and records no lost range. +func TestWorkspaceCleanMoveRecordsNoLostRange(t *testing.T) { + ctx := context.Background() + disk, dir := newTempStore(t) + p := NewPublisher(nil, WithStore(disk)) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "old", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "old", 1); err != nil { + t.Fatal(err) + } + if err := p.BeginWorkspaceRevocation(ctx, "v", "old", 1); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "old", 1); err != nil { + t.Fatal(err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7}); err != nil { + t.Fatal(err) + } + req := WorkspaceMoveRequest{RequestID: "c", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, + TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} + if _, err := p.MoveWorkspace(ctx, req, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42, Detached: true}); err != nil { + t.Fatal(err) + } + if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 0 { + t.Fatalf("clean move recorded a lost range: %+v", got) + } + if m, _ := filepath.Glob(filepath.Join(dir, "*"+lostRangeFileExtension)); len(m) != 0 { + t.Fatalf("clean move wrote a lost range file: %v", m) + } +} + +// lostRangeFaultStore is the file store with injectable failures. +type lostRangeFaultStore struct { + *FileAuthorityStore + failPut, failLostRange bool +} + +var errInjected = errors.New("injected store failure") + +func (s *lostRangeFaultStore) Put(r DurableRecord) error { + if s.failPut && r.Workspace != nil && len(r.Workspace.Moves) > 0 { + return errInjected + } + return s.FileAuthorityStore.Put(r) +} + +func (s *lostRangeFaultStore) PutWorkspaceLostRanges(v string, rs []WorkspaceLostRange) error { + if s.failLostRange { + return errInjected + } + return s.FileAuthorityStore.PutWorkspaceLostRanges(v, rs) +} + +// The lost range is written before the move record: a failed range write +// refuses the move (no epoch issued); a range whose move record then fails +// is an orphan, on disk but never reported. +func TestWorkspaceForcedMoveLostRangeOrdering(t *testing.T) { + t.Run("range write fails", func(t *testing.T) { + disk, _ := newTempStore(t) + store := &lostRangeFaultStore{FileAuthorityStore: disk, failLostRange: true} + p, now, barrier := forcedLostRangeFixture(t, store, false) + *now = barrier.Add(time.Second) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); !errors.Is(err, errInjected) { + t.Fatalf("move with a failed range write: %v; want refused", err) + } + if line, _ := NewPublisher(nil, WithStore(disk)).VolumeAuthorityLine("v"); line.Epoch != 1 { + t.Fatalf("epoch issued without its lost range: %+v", line) + } + }) + t.Run("move record fails", func(t *testing.T) { + disk, dir := newTempStore(t) + store := &lostRangeFaultStore{FileAuthorityStore: disk, failPut: true} + p, now, barrier := forcedLostRangeFixture(t, store, false) + *now = barrier.Add(time.Second) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err == nil { + t.Fatal("move issued although its record failed") + } + raw, err := os.ReadFile(filepath.Join(dir, "v"+lostRangeFileExtension)) + if err != nil || !strings.Contains(string(raw), `"RequestID":"f"`) { + t.Fatalf("fixture: no orphan range on disk: %v %s", err, raw) + } + if got := p.WorkspaceLostRanges("v"); len(got) != 0 { + t.Fatalf("orphan reported: %+v", got) + } + if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 0 { + t.Fatalf("orphan reported after reload: %+v", got) + } + }) +} + +// issueFailStore fails the authority write that would issue a move, leaving +// its reservation pending on disk (a crash between reservation and issue). +type issueFailStore struct { + *FileAuthorityStore + failIssue bool +} + +func (s *issueFailStore) Put(r DurableRecord) error { + if s.failIssue && r.Workspace != nil { + for _, m := range r.Workspace.Moves { + if m.Issued { + return errInjected + } + } + } + return s.FileAuthorityStore.Put(r) +} + +// A pending forced reservation resumes only with the exact range recorded +// before it: after a reload the retry issues it with that range (not one +// recomputed at the retry); without it the retry is refused, and a new +// request records a fresh range. +func TestWorkspaceForcedReservationResumeNeedsItsRange(t *testing.T) { + for _, missing := range []bool{false, true} { + t.Run(map[bool]string{false: "range kept", true: "range missing"}[missing], func(t *testing.T) { + disk, dir := newTempStore(t) + store := &issueFailStore{FileAuthorityStore: disk, failIssue: true} + p, now, barrier := forcedLostRangeFixture(t, store, false) + *now = barrier.Add(time.Second) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err == nil { + t.Fatal("fixture: the issue write did not fail") + } + st := NewPublisher(nil, WithStore(disk)).WorkspaceState("v") + if st == nil || len(st.Moves) != 1 || st.Moves[0].Issued { + t.Fatalf("fixture: no pending reservation on disk: %+v", st) + } + want := WorkspaceLostRange{RequestID: "f", NewEpoch: st.Moves[0].NewEpoch, OldReplicaID: "old", OldEpoch: 1, LostAfterLSN: 42, LostUntilNS: barrier.UnixNano()} + if missing { + if err := os.Remove(filepath.Join(dir, "v"+lostRangeFileExtension)); err != nil { + t.Fatal(err) + } + } + later := barrier.Add(time.Hour) // a recomputed bound would differ + q := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, func() time.Time { return later })) + later = later.Add(time.Minute) // past the reload's own restart deadline + r, err := q.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead) + if missing { + if err == nil || !strings.Contains(err.Error(), "no recorded lost range") { + t.Fatalf("resume without its range: %v; want refused", err) + } + if line, _ := q.VolumeAuthorityLine("v"); line.Epoch != 1 { + t.Fatalf("epoch issued without a range: %+v", line) + } + fresh := forcedLostRangeReq + fresh.RequestID = "f2" + r2, err := q.MoveWorkspace(context.Background(), fresh, forcedLostRangeHead) + if err != nil { + t.Fatalf("a new request after the refused resume: %v", err) + } + if got := q.WorkspaceLostRanges("v"); len(got) != 1 || got[0].RequestID != "f2" || got[0].NewEpoch != r2.NewEpoch { + t.Fatalf("new request range %+v", got) + } + return + } + if err != nil || !r.Issued || r.NewEpoch != want.NewEpoch { + t.Fatalf("resume: %+v %v", r, err) + } + if got := q.WorkspaceLostRanges("v"); len(got) != 1 || got[0] != want { + t.Fatalf("resumed range %+v; want the recorded [%+v]", got, want) + } + }) + } +} + +// Failures inside the file store: before the rename nothing is published +// and no temp file is left; after the rename (directory sync) the range may +// be on disk as an orphan. Either way the move is refused with no epoch, the +// orphan is not reported, and a retry issues with exactly one range. +func TestWorkspaceLostRangeFileFaults(t *testing.T) { + for _, step := range []string{"before-rename", "directory-sync"} { + t.Run(step, func(t *testing.T) { + disk, dir := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, false) + *now = barrier.Add(time.Second) + testLostRangeFaultHook = func(s string) error { + if s == step { + return errInjected + } + return nil + } + t.Cleanup(func() { testLostRangeFaultHook = nil }) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); !errors.Is(err, errInjected) { + t.Fatalf("move with a failed range write: %v; want refused", err) + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 1 { + t.Fatalf("epoch issued: %+v", line) + } + _, statErr := os.Stat(filepath.Join(dir, "v"+lostRangeFileExtension)) + temps, _ := filepath.Glob(filepath.Join(dir, "*"+lostRangeFileExtension+tempSuffix)) + if len(temps) != 0 { + t.Fatalf("temp file left: %v", temps) + } + if step == "before-rename" && statErr == nil { + t.Fatal("range published although the write failed before the rename") + } + if step == "directory-sync" && statErr != nil { + t.Fatalf("fixture: the rename did not land: %v", statErr) + } + if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 0 { + t.Fatalf("orphan reported: %+v", got) + } + testLostRangeFaultHook = nil + r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead) + if err != nil { + t.Fatal("retry:", err) + } + if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 1 || got[0].NewEpoch != r.NewEpoch { + t.Fatalf("after the retry: %+v; want one range", got) + } + }) + } +} + +// A store wrapper that embeds AuthorityStore forwards the lost ranges: a +// forced move through it records its range. +func TestWorkspaceLostRangeThroughAStoreWrapper(t *testing.T) { + disk, _ := newTempStore(t) + wrapped := &workspaceFailStore{AuthorityStore: disk} + p, now, barrier := forcedLostRangeFixture(t, wrapped, false) + *now = barrier.Add(time.Second) + if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err != nil { + t.Fatal(err) + } + if got := NewPublisher(nil, WithStore(disk)).WorkspaceLostRanges("v"); len(got) != 1 { + t.Fatalf("range through a wrapper: %+v", got) + } +} + +// Budget evidence (logged, not asserted): the added critical-section write, +// one file of the volume's whole range history plus two fsyncs, for a short +// and a long history. +func TestWorkspaceLostRangeWriteCost(t *testing.T) { + disk, _ := newTempStore(t) + for _, n := range []int{1, 1000} { + ranges := make([]WorkspaceLostRange, n) + for i := range ranges { + ranges[i] = WorkspaceLostRange{RequestID: "request-" + strings.Repeat("x", 24), NewEpoch: uint64(i + 2), OldReplicaID: "r1", OldEpoch: uint64(i + 1), LostAfterLSN: 1 << 40, LostUntilNS: 1 << 60} + } + var worst time.Duration + for i := 0; i < 5; i++ { + start := time.Now() + if err := disk.PutWorkspaceLostRanges("v", ranges); err != nil { + t.Fatal(err) + } + if d := time.Since(start); d > worst { + worst = d + } + } + t.Logf("lost range write: %d entries, worst of 5 = %v", n, worst) + } +} diff --git a/seaweed-block/core/authority/workspace_renewal_slowstore_test.go b/seaweed-block/core/authority/workspace_renewal_slowstore_test.go new file mode 100644 index 0000000000..6d7ddf652e --- /dev/null +++ b/seaweed-block/core/authority/workspace_renewal_slowstore_test.go @@ -0,0 +1,209 @@ +package authority + +import ( + "context" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" +) + +// slowLeaseStore delays every workspace-lease Put once armed, standing in for +// a master disk whose fsync stalls under heavy I/O (issue #205). +type slowLeaseStore struct { + AuthorityStore + delayNS atomic.Int64 + puts atomic.Int64 // delayed (armed) lease writes: proves the stall was exercised +} + +func (s *slowLeaseStore) Put(r DurableRecord) error { + if d := time.Duration(s.delayNS.Load()); d > 0 && r.Workspace != nil && r.Workspace.Lease != nil { + s.puts.Add(1) + time.Sleep(d) + } + return s.AuthorityStore.Put(r) +} + +// A renewal of a live lease must not wait for the authority store's fsync: +// the host's renewal RPC times out after 2 s, so a slower store write on the +// renewal path turns into a host fence and a volume shutdown (issue #205). +func TestWorkspaceRenewalDoesNotWaitForSlowStore(t *testing.T) { + disk, _ := newTempStore(t) + slow := &slowLeaseStore{AuthorityStore: disk} + var nowNS atomic.Int64 + nowNS.Store(time.Unix(1000, 0).UnixNano()) + p := NewPublisher(nil, WithStore(slow), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })) + t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "old", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + first, err := p.RenewWorkspaceLease(context.Background(), "v", "old", 1) + if err != nil { + t.Fatal(err) + } + slow.delayNS.Store(int64(2500 * time.Millisecond)) + t.Cleanup(func() { slow.delayNS.Store(0) }) + nowNS.Add(int64(10 * time.Second)) + start := time.Now() + second, err := p.RenewWorkspaceLease(context.Background(), "v", "old", 1) + took := time.Since(start) + if err != nil { + t.Fatal(err) + } + if second.ExpiresAtNS <= first.ExpiresAtNS { + t.Fatalf("renewal did not extend the grant: first=%d second=%d", first.ExpiresAtNS, second.ExpiresAtNS) + } + if took >= 2*time.Second { + t.Fatalf("renewal of a live lease took %s behind a 2.5 s store write; the host's renewal RPC times out at 2 s", took.Round(time.Millisecond)) + } + t.Logf("renewal took %s", took) + waitExtenders(t, p) + if slow.puts.Load() == 0 { + t.Fatal("no lease write went through the 2.5 s stall: the test did not exercise it") + } +} + +// Renewals of different volumes must not queue behind each other's store +// writes: with six volumes and a 0.5 s write each, serializing them makes the +// last renewal wait about 3 s, past the host's 2 s renewal timeout. +func TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore(t *testing.T) { + disk, _ := newTempStore(t) + slow := &slowLeaseStore{AuthorityStore: disk} + var nowNS atomic.Int64 + nowNS.Store(time.Unix(1000, 0).UnixNano()) + p := NewPublisher(nil, WithStore(slow), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })) + t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes + const n = 6 + for i := 0; i < n; i++ { + v := fmt.Sprintf("v%d", i) + if err := p.apply(AssignmentAsk{VolumeID: v, ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(context.Background(), v, "r", 1); err != nil { + t.Fatal(err) + } + } + slow.delayNS.Store(int64(500 * time.Millisecond)) + t.Cleanup(func() { slow.delayNS.Store(0) }) + nowNS.Add(int64(10 * time.Second)) + var wg sync.WaitGroup + took := make([]time.Duration, n) + errs := make([]error, n) + gate := make(chan struct{}) + for i := 0; i < n; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + <-gate + start := time.Now() + _, errs[i] = p.RenewWorkspaceLease(context.Background(), fmt.Sprintf("v%d", i), "r", 1) + took[i] = time.Since(start) + }(i) + } + close(gate) + wg.Wait() + var slowest time.Duration + for i := 0; i < n; i++ { + if errs[i] != nil { + t.Fatalf("v%d: %v", i, errs[i]) + } + if took[i] > slowest { + slowest = took[i] + } + } + if slowest >= 2*time.Second { + t.Fatalf("slowest of %d concurrent renewals took %s (all: %v); renewals serialize behind each other's store writes", n, slowest.Round(time.Millisecond), took) + } + t.Logf("slowest of %d concurrent renewals took %s", n, slowest) + waitExtenders(t, p) + if slow.puts.Load() == 0 { + t.Fatal("no lease write went through the 0.5 s stall: the test did not exercise it") + } +} + +// heldWriteStore blocks the first Put that matches hold until release closes, +// standing in for one slow synchronous authority write. +type heldWriteStore struct { + AuthorityStore + hold func(DurableRecord) bool + once sync.Once + entered chan struct{} + release chan struct{} +} + +func (s *heldWriteStore) Put(r DurableRecord) error { + if s.hold != nil && s.hold(r) { + held := false + s.once.Do(func() { held = true }) + if held { + close(s.entered) + <-s.release + } + } + return s.AuthorityStore.Put(r) +} + +// A slow synchronous write of one volume (here the revocation of a) must not +// block the renewal of an unrelated volume b: renewal needs no write of its +// own, so it must not wait on a's store I/O (issue #205). +func TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite(t *testing.T) { + disk, _ := newTempStore(t) + held := &heldWriteStore{AuthorityStore: disk, entered: make(chan struct{}), release: make(chan struct{}), + hold: func(r DurableRecord) bool { + return r.VolumeID == "a" && r.Workspace != nil && r.Workspace.Lease != nil && r.Workspace.Lease.Revoking + }} + var nowNS atomic.Int64 + nowNS.Store(time.Unix(1000, 0).UnixNano()) + p := NewPublisher(nil, WithStore(held), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })) + t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes + for _, v := range []string{"a", "b"} { + if err := p.apply(AssignmentAsk{VolumeID: v, ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(context.Background(), v, "r", 1); err != nil { + t.Fatal(err) + } + } + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(held.release) }) } + revoked := make(chan error, 1) + go func() { revoked <- p.BeginWorkspaceRevocation(context.Background(), "a", "r", 1) }() + // Bounded cleanup: release the held write first, then settle the worker. + t.Cleanup(func() { + release() + select { + case <-revoked: + case <-time.After(5 * time.Second): + t.Error("held revocation of a did not settle within 5 s after release") + } + }) + select { + case <-held.entered: + case <-time.After(3 * time.Second): + t.Fatal("revocation of a never reached the store") + } + nowNS.Add(int64(10 * time.Second)) + renewed := make(chan error, 1) + start := time.Now() + go func() { + _, err := p.RenewWorkspaceLease(context.Background(), "b", "r", 1) + renewed <- err + }() + select { + case err := <-renewed: + if err != nil { + t.Fatalf("renewal of b: %v", err) + } + t.Logf("renewal of b took %s while a's write was held", time.Since(start)) + case <-time.After(2 * time.Second): + blocked := time.Since(start).Round(time.Millisecond) + release() + select { + case err := <-renewed: + t.Fatalf("renewal of b was still blocked %s behind the held store write of a (it returned only after a was released, err=%v)", blocked, err) + case <-time.After(5 * time.Second): + t.Fatalf("renewal of b was still blocked %s behind the held store write of a, and did not settle within 5 s after release", blocked) + } + } +} diff --git a/seaweed-block/core/authority/workspace_skew_test.go b/seaweed-block/core/authority/workspace_skew_test.go index 320d43eba8..69b4c733c6 100644 --- a/seaweed-block/core/authority/workspace_skew_test.go +++ b/seaweed-block/core/authority/workspace_skew_test.go @@ -23,7 +23,10 @@ func TestWorkspaceClockSkewPersistsAndProtectsRestart(t *testing.T) { if lease.MaxClockSkewNS != int64(4*time.Second) { t.Fatal("configured margin not in durable grant", lease) } - boundary := start.Add(10 * time.Second) + // The first grant persists the durable horizon start+1.5*TTL (9 s), + // the upper bound of every later grant; the forced barrier is + // horizon + skew, TTL/2 later than the grant itself (#205). + boundary := start.Add(9*time.Second + 4*time.Second) if restart { now = start.Add(7 * time.Second) p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(6*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(time.Second)) diff --git a/seaweed-block/core/authority/workspace_test.go b/seaweed-block/core/authority/workspace_test.go index 4873446164..39473fec1f 100644 --- a/seaweed-block/core/authority/workspace_test.go +++ b/seaweed-block/core/authority/workspace_test.go @@ -35,7 +35,8 @@ func TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant(t *testing.T) { if _, err := p.RenewWorkspaceLease(context.Background(), "v", "old", 1); err != nil { t.Fatal(err) } - now = now.Add(2 * time.Second) + // Past the durable horizon (1.5*TTL) plus skew, not only the grant (#205). + now = now.Add(3 * time.Second) req := WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42} fault.failIssue = true @@ -224,7 +225,8 @@ func TestWorkspaceMoveUsesQualifiedHEADHolder(t *testing.T) { if _, err := p.RenewWorkspaceLease(ctx, "v", "same", 1); err != nil { t.Fatal(err) } - now = now.Add(2 * time.Second) + // Past the durable horizon (1.5*TTL) plus skew, not only the grant (#205). + now = now.Add(3 * time.Second) q := WorkspaceMoveRequest{RequestID: "qualified", VolumeID: "v", ExpectedReplicaID: "same", TargetReplicaID: "same", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} for _, holder := range []string{"same", "other-node/same", "old-node/other"} { if _, err := p.MoveWorkspace(ctx, q, WorkspaceHead{Gen: 7, Epoch: 1, Holder: holder, RemoteLSN: 42}); err == nil { diff --git a/seaweed-block/core/calibration/harness.go b/seaweed-block/core/calibration/harness.go index 500fdada44..b7b2e8d4af 100644 --- a/seaweed-block/core/calibration/harness.go +++ b/seaweed-block/core/calibration/harness.go @@ -67,7 +67,10 @@ func (h *harness) writeBlocks(n uint32) { // and marks the replica's synced frontier at the primary's head. Used // by C1 setup where the replica is already caught up. func (h *harness) mirrorToReplica() { - blocks := h.primaryStore.AllBlocks() + blocks, err := h.primaryStore.AllBlocks() + if err != nil { + panic(fmt.Errorf("calibration snapshot: %w", err)) + } _, _, pH := h.primaryStore.Boundaries() for lba, data := range blocks { _ = h.replicaStore.ApplyEntry(lba, data, pH) @@ -120,7 +123,10 @@ func (h *harness) commandLog() []string { // dataMatches returns true iff every LBA that exists on the primary is // byte-identical on the replica. Used for C2/C3 data-integrity evidence. func (h *harness) dataMatches() bool { - primary := h.primaryStore.AllBlocks() + primary, err := h.primaryStore.AllBlocks() + if err != nil { + return false + } for lba, want := range primary { got, err := h.replicaStore.Read(lba) if err != nil { diff --git a/seaweed-block/core/csi/controller.go b/seaweed-block/core/csi/controller.go index c4471f4bd9..4e9f41ff26 100644 --- a/seaweed-block/core/csi/controller.go +++ b/seaweed-block/core/csi/controller.go @@ -8,6 +8,7 @@ import ( "time" csipb "github.com/container-storage-interface/spec/lib/go/csi" + "github.com/seaweedfs/seaweed-block/core/geometry" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -248,6 +249,9 @@ func volumeSpecFromCreateRequest(req *csipb.CreateVolumeRequest) (VolumeSpec, er if size <= 0 { return VolumeSpec{}, status.Error(codes.InvalidArgument, "capacity is required") } + if err := geometry.ValidateVolumeSize(uint64(size)); err != nil { + return VolumeSpec{}, status.Error(codes.InvalidArgument, err.Error()) + } if len(req.GetVolumeCapabilities()) == 0 { return VolumeSpec{}, status.Error(codes.InvalidArgument, "volume capabilities are required") } diff --git a/seaweed-block/core/csi/volume_size_limit_test.go b/seaweed-block/core/csi/volume_size_limit_test.go new file mode 100644 index 0000000000..49570c143c --- /dev/null +++ b/seaweed-block/core/csi/volume_size_limit_test.go @@ -0,0 +1,29 @@ +package csi + +import ( + "context" + csipb "github.com/container-storage-interface/spec/lib/go/csi" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "strings" + "testing" +) + +func TestCSICreateVolumeCapacityCapBeforeProvision(t *testing.T) { + const capBytes = int64(17592186040320) + p := &stubProvisioner{} + s := NewControllerServerWithProvisioner(&stubLookup{}, p) + req := &csipb.CreateVolumeRequest{Name: "v", CapacityRange: &csipb.CapacityRange{RequiredBytes: capBytes}, VolumeCapabilities: []*csipb.VolumeCapability{testVolumeCapability()}} + if _, err := s.CreateVolume(context.Background(), req); err != nil { + t.Fatal(err) + } + p.calls = nil + req.CapacityRange.RequiredBytes = capBytes + 4096 + _, err := s.CreateVolume(context.Background(), req) + if status.Code(err) != codes.InvalidArgument || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("want clear InvalidArgument, got %v", err) + } + if len(p.calls) != 0 { + t.Fatal("oversized request reached provisioner") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/api.go b/seaweed-block/core/frontend/chunkstore/api.go index 469ca3295f..eae7dd0fd8 100644 --- a/seaweed-block/core/frontend/chunkstore/api.go +++ b/seaweed-block/core/frontend/chunkstore/api.go @@ -94,7 +94,7 @@ func NewVolumeShowBody(vol string, v *VolumeInfo, h *storage.ChunkHead) VolumeSh if state == "" { state = storage.ChunkHeadActive } - body.Head = &HeadShow{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: state, ChunkCount: len(h.Chunks)} + body.Head = &HeadShow{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: state, ChunkCount: manifestCount(*h)} if d := h.DetachedBy; d != nil { body.Head.DetachedBy = &DetachedByShow{Holder: d.Holder, Epoch: d.Epoch, Gen: d.Gen} } diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 1e1889e3d0..eb6fd6f4eb 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -35,6 +35,7 @@ import ( "strings" "time" + "github.com/seaweedfs/seaweed-block/core/geometry" "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" @@ -227,8 +228,9 @@ type SnapshotInfo struct { attempt string // the attempt the name resolved to, when read by name - head storage.ChunkHead - geo Geometry + head storage.ChunkHead + geo Geometry + digest string // identity uses the embedded writer version, not today's serializer } // Head returns the HEAD the snapshot copied. @@ -487,6 +489,9 @@ func (c *Catalog) EnsureVolume(ctx context.Context, vol string, g Geometry) (Vol return VolumeInfo{}, err } if !ok { + if g.BlockSize != 0 && g.NumBlocks > geometry.MaxVolumeBytes/uint64(g.BlockSize) { + return VolumeInfo{}, catErr(CodeGeometryMismatch, false, nil, "volume size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) + } v = VolumeInfo{Format: volumeFormat, VolumeID: vol, Geometry: g, Origin: OriginCreate, CreatedNs: c.now().UnixNano()} e, err := volumeEntry(v, "") if err != nil { @@ -669,6 +674,10 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) { if err != nil { return fail("%v", err) } + digest, err := snapshotHeadDigest(head, doc.Head) + if err != nil { + return fail("HEAD identity: %v", err) + } state := string(e.Extended[extSnapState]) if state != SnapActive && state != SnapDeleting { return fail("state %q", state) @@ -680,7 +689,7 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) { VolumeID: doc.VolumeID, Name: doc.Name, HeadGen: head.Gen, HeadEpoch: head.Epoch, CutLSN: head.RemoteLSN, CreatedNs: doc.CreatedNs, State: state, ChunkCount: manifestCount(head), ManifestBytes: len(e.GetContent()), Consistency: doc.Consistency, Labels: doc.Labels, Parent: doc.Parent, ExpiresAtNs: doc.ExpiresAtNs, - Class: doc.Class, head: head, geo: doc.Geometry, + Class: doc.Class, head: head, geo: doc.Geometry, digest: digest, }, doc.RequestID, nil } @@ -866,6 +875,11 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe return SnapshotInfo{}, refuseDeleted(vol, "it cannot be snapshotted") } + head, upgradeIDs, err := c.prepareLegacyHead(ctx, root, head, head, v.Geometry) + defer c.dropManifestIntents(ctx, root, upgradeIDs) + if err != nil { + return SnapshotInfo{}, err + } headEnt, err := headEntry(head) if err != nil { return SnapshotInfo{}, err @@ -1227,10 +1241,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, fmt.Errorf("chunkstore: snapshot %s/%s has no geometry", req.Source, req.Snapshot) } src := snap.Head() - digest, err := headDigest(src) - if err != nil { - return ForkResult{}, err - } + digest := snap.digest head := storage.ChunkHead{Gen: 1, Epoch: 0, Holder: "", RemoteLSN: src.RemoteLSN, Chunks: make(map[uint64]storage.ChunkRef, len(src.Chunks)), State: storage.ChunkHeadActive} qualified := 0 if src.Segments != nil { @@ -1281,6 +1292,11 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) existing = vol } + head, upgradeIDs, err := c.prepareLegacyHead(ctx, dstRoot, storage.ChunkHead{}, head, snap.geo) + defer c.dropManifestIntents(ctx, dstRoot, upgradeIDs) + if err != nil { + return ForkResult{}, err + } he, err := headEntry(head) if err != nil { return ForkResult{}, err @@ -1352,6 +1368,9 @@ func (c *Catalog) claimForkParent(ctx context.Context, req ForkRequest) (Snapsho if ref.info.State == SnapDeleting { return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot) } + if ref.info.geo.BlockSize != 0 && ref.info.geo.NumBlocks > geometry.MaxVolumeBytes/uint64(ref.info.geo.BlockSize) { + return SnapshotInfo{}, catErr(CodeGeometryMismatch, false, nil, "fork size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) + } claims := decodeClaims(ref.entry) for _, cl := range claims { if cl == token { diff --git a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go index 7d7290c26f..44b67dffaa 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go @@ -28,8 +28,7 @@ func intentsOf(t *testing.T, f *fakeFiler, vol string) []storage.ChunkIntent { func sortedKeysOf(h storage.ChunkHead, qualify string) []string { var out []string - for _, ref := range h.Chunks { - k := ref.Key + for _, k := range headKeys(h) { if qualify != "" && !strings.HasPrefix(k, "@") { k = "@" + qualify + "/" + k } @@ -196,11 +195,20 @@ func TestFork_IncompleteRetryBoundToOriginalImage(t *testing.T) { next.Chunks[k] = v } next.Chunks[5] = storage.ChunkRef{Key: "chunks/e1/c5/new", SHA256: sha256Of(chunkBytes(0x55))} + next, ids, err := r1.PrepareManifest(ctx, h, next, h.ChunkBytes) + if err != nil { + t.Fatal(err) + } gen, err := r1.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: 1}, next) if err != nil { t.Fatal(err) } next.Gen = gen + for _, id := range ids { + if err := r1.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-new"}, next); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/chunkstore/catalog_test.go b/seaweed-block/core/frontend/chunkstore/catalog_test.go index 533b82f2ba..33ade710d3 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_test.go @@ -41,11 +41,20 @@ func publishSource(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string, chunks if err != nil { t.Fatal(err) } + h, intents, err := r.PrepareManifest(ctx, cur, h, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h) if err != nil { t.Fatal(err) } h.Gen = gen + for _, id := range intents { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } return h } @@ -80,7 +89,10 @@ func chunkBytes(fill byte) []byte { func catalogFixture(t *testing.T) (*fakeFiler, *fakeBlobs, *Catalog, storage.ChunkHead) { t.Helper() f, b := newFakeFiler(), newFakeBlobs() - c := newCat(t, f) + c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) + if err != nil { + t.Fatal(err) + } if _, err := c.EnsureVolume(context.Background(), "v1", catGeo); err != nil { t.Fatal(err) } @@ -233,7 +245,7 @@ func TestCatalog_DeleteMarksThenIdempotent(t *testing.T) { } func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) { - f, _, c, h := catalogFixture(t) + f, b, c, h := catalogFixture(t) ctx := context.Background() if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { t.Fatal(err) @@ -259,7 +271,7 @@ func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) { if got, _ := f.ListEntries(ctx, catBase+"/v2/intents", "", "", 0); len(got) != 0 { t.Fatalf("fork left %d intents", len(got)) } - r2, _ := NewChunkRemote(f, newFakeBlobs(), catBase+"/v2") + r2, _ := NewChunkRemote(f, b, catBase+"/v2") head, err := r2.GetHead(ctx) if err != nil { t.Fatal(err) @@ -269,11 +281,11 @@ func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) { } for idx, ref := range head.Chunks { src := h.Chunks[idx] - if ref.Key != "@v1/"+src.Key || ref.SHA256 != src.SHA256 { + if ref.Key != qualifyManifestKey("v1", src.Key) || ref.SHA256 != src.SHA256 { t.Fatalf("chunk %d ref %+v, want @v1/%s with the same hash", idx, ref, src.Key) } } - if res.HeadGen != 1 || res.HeadEpoch != 0 || res.QualifiedRefs != 2 || res.SourceGen != h.Gen || res.RemoteLSN != 42 || res.Replayed { + if res.HeadGen != 1 || res.HeadEpoch != 0 || res.QualifiedRefs != 1 || res.ChunkCount != 2 || res.SourceGen != h.Gen || res.RemoteLSN != 42 || res.Replayed { t.Fatalf("result %+v", res) } v, ok, err := c.ReadVolume(ctx, "v2") @@ -310,7 +322,7 @@ func TestFork_ForkOfForkKeepsOriginalOwner(t *testing.T) { r3, _ := NewChunkRemote(f, b, catBase+"/v3") h3, _ := r3.GetHead(ctx) for idx, ref := range h3.Chunks { - if ref.Key != "@v1/"+h.Chunks[idx].Key { + if ref.Key != qualifyManifestKey("v1", h.Chunks[idx].Key) { t.Fatalf("second-level fork chunk %d names %q, want the original owner @v1/%s", idx, ref.Key, h.Chunks[idx].Key) } if got, err := r3.Get(ctx, ref.Key); err != nil || sha256.Sum256(got) != ref.SHA256 { @@ -403,7 +415,7 @@ func TestFork_ThenFreshHostReadsSnapshotImage(t *testing.T) { t.Fatal(err) } p := filepath.Join(dir, vol) - s, err := storage.CreateWALStore(p, blocks, 4096) + s, err := storage.CreateWALStoreWithOptions(p, blocks, 4096, storage.WALStoreOptions{ChunkBlocks: chunkBlocks}) if err != nil { t.Fatal(err) } @@ -411,8 +423,7 @@ func TestFork_ThenFreshHostReadsSnapshotImage(t *testing.T) { t.Fatal(err) } r, _ := NewChunkRemote(f, b, path.Join(catBase, vol)) - cfg := storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: epoch, Holder: vol, FreshFromHead: fresh, - Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap")} + cfg := storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: epoch, Holder: vol, FreshFromHead: fresh} if fresh { // This low-level fixture bypasses the provider: perform the same // takeover and durable frontier seed before attaching its layer. @@ -577,7 +588,7 @@ func TestDetach_ProductionSerializedHead(t *testing.T) { ctx := context.Background() f, b := newFakeFiler(), newFakeBlobs() p := filepath.Join(t.TempDir(), "v1") - s, err := storage.CreateWALStore(p, 64, 4096) + s, err := storage.CreateWALStoreWithOptions(p, 64, 4096, storage.WALStoreOptions{ChunkBlocks: 8}) if err != nil { t.Fatal(err) } @@ -586,8 +597,7 @@ func TestDetach_ProductionSerializedHead(t *testing.T) { t.Fatal(err) } r, _ := NewChunkRemote(f, b, catBase+"/v1") - l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 3, Holder: "host-a", - Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap")}) + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 3, Holder: "host-a"}) if err != nil { t.Fatal(err) } @@ -650,7 +660,7 @@ func TestCatalog_EnsureVolumeCreatesTheInitialHead(t *testing.T) { if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil { t.Fatal(err) } - if kept, _, _ := c.ReadHead(ctx, "v2"); kept.Gen != pub.Gen || len(kept.Chunks) != 1 { + if kept, _, _ := c.ReadHead(ctx, "v2"); kept.Gen != pub.Gen || manifestCount(kept) != 1 || kept.Segments[0] != pub.Segments[0] { t.Fatalf("an existing HEAD was replaced by the initial one: %+v, published %+v", kept, pub) } diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 3fbfde5f9d..aff708783b 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -339,6 +339,7 @@ func decodeIntent(p string, e *filerpb.Entry) (storage.ChunkIntent, error) { } type headDoc struct { + Levels int `json:"levels,omitempty"` Segments map[uint64]storage.ChunkSegment `json:"segments,omitempty"` ChunkBytes uint64 `json:"chunk_bytes,omitempty"` ChunkCount int `json:"chunk_count,omitempty"` @@ -370,6 +371,16 @@ type refDoc struct { // was ever published. An entry that exists but does not decode is an // error, never the zero HEAD. func (r *ChunkRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + h, err := r.getHeadRoot(ctx) + if err != nil { + return h, err + } + return r.resolveManifest(ctx, h) +} + +// getHeadRoot validates the root and its CAS attributes without reading any +// immutable segment. CASHead only needs authority and lineage from this root. +func (r *ChunkRemote) getHeadRoot(ctx context.Context) (storage.ChunkHead, error) { e, err := r.f.LookupEntry(ctx, r.root, headName) if errors.Is(err, ErrNotFound) { return storage.ChunkHead{}, nil @@ -377,11 +388,7 @@ func (r *ChunkRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { if err != nil { return storage.ChunkHead{}, err } - h, err := decodeHead(path.Join(r.root, headName), e) - if err != nil { - return h, err - } - return r.resolveManifest(ctx, h) + return decodeHead(path.Join(r.root, headName), e) } // CASHead installs next, at generation expected.Gen+1, only if the stored @@ -397,7 +404,7 @@ func (r *ChunkRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVer // Read the LSN under the same generation/epoch guard used by UpdateEntry. // A competing write after this read makes the conditional update fail; // no successful CAS can lower the committed lineage frontier. - current, err := r.GetHead(ctx) + current, err := r.getHeadRoot(ctx) if err != nil { return 0, err } @@ -439,19 +446,17 @@ func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) { doc.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen} } if h.Segments == nil { - doc.Chunks = make(map[uint64]refDoc, len(h.Chunks)) - for idx, ref := range h.Chunks { - if ref.Key == "" { - return nil, fmt.Errorf("chunkstore: HEAD chunk %d has no key", idx) - } - doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} + if len(h.Chunks) != 0 { + return nil, errors.New("chunkstore: data HEAD requires a segmented manifest and geometry") } + doc.Chunks = map[uint64]refDoc{} } if h.Segments != nil { if err := validateRoot(h); err != nil { return nil, err } - doc.Format = 2 + doc.Format = 3 + doc.Levels = 1 doc.Chunks = nil doc.Segments = h.Segments doc.ChunkBytes = h.ChunkBytes @@ -555,11 +560,11 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) { if err != nil || len(sum) != 32 || ref.Key == "" { return fail("chunk %d ref invalid", idx) } - cr := storage.ChunkRef{Key: ref.Key} + cr := storage.ChunkRef{Key: ref.Key, Encoding: "full", BirthLSN: doc.RemoteLSN} copy(cr.SHA256[:], sum) h.Chunks[idx] = cr } - if doc.Format == 2 { + if doc.Format == 2 || doc.Format == 3 { if len(doc.Chunks) != 0 { return fail("segmented root contains flat chunks") } diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go index 5115efb612..5250c781b3 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go @@ -219,7 +219,7 @@ func TestIntegration_ChunkLayerCaptureThenFreshHost(t *testing.T) { dir := t.TempDir() attach := func(name string, fresh bool) (*storage.WALStore, storage.ChunkLayer) { p := filepath.Join(dir, name) - s, err := storage.CreateWALStore(p, blocks, 4096) + s, err := storage.CreateWALStoreWithOptions(p, blocks, 4096, storage.WALStoreOptions{ChunkBlocks: chunkBlocks}) if err != nil { t.Fatal(err) } @@ -228,7 +228,6 @@ func TestIntegration_ChunkLayerCaptureThenFreshHost(t *testing.T) { } l, err := storage.AttachChunkLayer(s, c.remote(t, root), storage.ChunkLayerConfig{ ChunkBlocks: chunkBlocks, Epoch: 1, Holder: name, FreshFromHead: fresh, - Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap"), }) if err != nil { t.Fatal(err) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go index 5e545e0a0a..70a1f172ff 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go @@ -55,10 +55,22 @@ func TestChunkRemote_HeadRoundTripAndCAS(t *testing.T) { t.Fatal(err) } want := head(1, "a", 42, map[uint64]storage.ChunkRef{3: ref("chunks/e1/c3/n-1", d)}) + legacy := want.Chunks[3] + legacy.Encoding, legacy.BirthLSN = "full", want.RemoteLSN + want.Chunks[3] = legacy + want, intents, err := r.PrepareManifest(ctx, storage.ChunkHead{}, want, 4096) + if err != nil { + t.Fatal(err) + } gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, want) if err != nil || gen != 1 { t.Fatalf("first CAS = %d, %v; want gen 1", gen, err) } + for _, id := range intents { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } got, err := r.GetHead(ctx) if err != nil { t.Fatal(err) @@ -228,7 +240,8 @@ func TestChunkRemote_UntrustedHeadIsAnError(t *testing.T) { f := newFakeFiler() r := newTestRemote(t, f, newFakeBlobs()) h := head(1, "a", 1, map[uint64]storage.ChunkRef{0: ref("k", []byte("x"))}) - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, h); err != nil { + h.Gen = 1 + if err := f.CreateEntry(ctx, testRoot, legacyHeadFixture(t, h), true); err != nil { t.Fatal(err) } f.mu.Lock() @@ -252,7 +265,7 @@ func TestChunkRemote_ChunkLayerCaptureThenFreshHost(t *testing.T) { attach := func(name string, fresh bool) (*storage.WALStore, storage.ChunkLayer) { p := filepath.Join(dir, name) - s, err := storage.CreateWALStore(p, blocks, 4096) + s, err := storage.CreateWALStoreWithOptions(p, blocks, 4096, storage.WALStoreOptions{ChunkBlocks: chunkBlocks}) if err != nil { t.Fatal(err) } @@ -262,7 +275,6 @@ func TestChunkRemote_ChunkLayerCaptureThenFreshHost(t *testing.T) { r := newTestRemote(t, f, b) l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ ChunkBlocks: chunkBlocks, Epoch: 1, Holder: name, FreshFromHead: fresh, - Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap"), }) if err != nil { t.Fatal(err) diff --git a/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go b/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go index 5dce4f7ad3..ea28bc0c35 100644 --- a/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go +++ b/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go @@ -21,10 +21,14 @@ func fuzzHeadSeeds(tb testing.TB) [][]byte { {Gen: 3, Epoch: 4, Holder: "r2", RemoteLSN: 9, State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Holder: "r2", Epoch: 4, Gen: 3}, Chunks: map[uint64]storage.ChunkRef{}}, {Gen: 2, Epoch: 1, Holder: "r1", RemoteLSN: 3, ChunkBytes: 4 << 20, ManifestChunkCount: 2, - Segments: map[uint64]storage.ChunkSegment{0: {Key: "@v1/seg/00", SHA256: sum, Owner: "v1", Count: 2}}}, + Segments: map[uint64]storage.ChunkSegment{0: {Key: "@v1/seg/00", SHA256: sum, Owner: "v1", Count: 2, SegFormat: 2, MaxBirthLSN: 3}}}, } var out [][]byte for _, h := range heads { + if h.Segments == nil && len(h.Chunks) > 0 { + out = append(out, legacyHeadFixture(tb, h).Content) + continue + } e, err := headEntry(h) if err != nil { tb.Fatalf("seed %+v: %v", h, err) @@ -90,6 +94,12 @@ func FuzzDecodeHeadDocument(f *testing.F) { return } e, err := headEntry(h) + if h.Segments == nil && len(h.Chunks) > 0 { + if err == nil { + t.Fatal("read-only legacy data was writable as flat HEAD") + } + return + } if err != nil { if gap := knownHeadEncodeGap(h); gap != "" { return diff --git a/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go b/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go new file mode 100644 index 0000000000..237f018820 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go @@ -0,0 +1,61 @@ +package chunkstore + +import ( + "context" + "path" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +// A legacy catalog may already contain oversized geometry. A new fork is +// still a new volume: it must not bypass the creation cap by inheritance. +func TestForkRejectsLegacyOversizedGeometry(t *testing.T) { + for _, blocks := range []uint64{4294967295, 4294967296} { + f, b, c, _, _ := gcFixture(t) + ctx := context.Background() + v, ok, err := c.ReadVolume(ctx, "v1") + if err != nil || !ok { + t.Fatal(err) + } + v.NumBlocks = blocks + e, err := volumeEntry(v, "") + if err != nil { + t.Fatal(err) + } + if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { + t.Fatal(err) + } + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41)}) + _, err = c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h) + if err != nil { + t.Fatal(err) + } + if err = f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "fork", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + _, err = c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "fork", RequestID: "f"}) + if blocks == 4294967295 { + if err != nil { + t.Fatalf("at-cap fork: %v", err) + } + got, ok, e := c.ReadVolume(ctx, "fork") + if e != nil || !ok || got.NumBlocks != blocks { + t.Fatalf("at-cap geometry not inherited: %+v %v", got, e) + } + continue + } + if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("oversized fork must refuse: %v", err) + } + if _, ok, e := c.ReadVolume(ctx, "fork"); e != nil || ok { + t.Fatalf("oversized fork persisted target: %v %v", ok, e) + } + // Observe claim cleanup through the public retention operation: an + // uncompleted fork claim would make this snapshot undeletable. + if _, deleteErr := c.DeleteSnapshot(ctx, "v1", "s1"); deleteErr != nil { + t.Fatalf("capacity refusal blocked snapshot deletion: %v", deleteErr) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go b/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go new file mode 100644 index 0000000000..ee4a1779e2 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go @@ -0,0 +1,222 @@ +package chunkstore + +import ( + "bytes" + "context" + "encoding/json" + "os" + "path" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Frozen output of the pre-format-3 CreateSnapshot/Fork producers at 3401cc60. +func preF4ForkFixture(t *testing.T, segmented bool) (*fakeFiler, *Catalog, *ChunkRemote) { + t.Helper() + suffix := "false" + if segmented { + suffix = "true" + } + data, err := os.ReadFile("testdata/pre_f4_fork_" + suffix + ".json") + if err != nil { + t.Fatal(err) + } + var frozen struct { + Entries map[string]*filerpb.Entry + Objects map[string][]byte + } + if err := json.Unmarshal(data, &frozen); err != nil { + t.Fatal(err) + } + f, b := newFakeFiler(), newFakeBlobs() + f.entries = frozen.Entries + c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) + if err != nil { + t.Fatal(err) + } + c.now = func() time.Time { return time.Unix(1000, 0) } + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + if err := r.Put(context.Background(), "legacy-data", bytes.Repeat([]byte{0x41}, 8*4096)); err != nil { + t.Fatal(err) + } + for key, body := range frozen.Objects { + if err := r.Put(context.Background(), key, body); err != nil { + t.Fatal(err) + } + } + return f, c, r +} +func assertLegacyImage(t *testing.T, r *ChunkRemote) { + t.Helper() + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if h.RemoteLSN != 7 || len(h.Chunks) != 1 { + t.Fatalf("legacy image/frontier lost: %+v", h) + } + data, err := r.Get(context.Background(), h.Chunks[0].Key) + if err != nil || !bytes.Equal(data, bytes.Repeat([]byte{0x41}, 8*4096)) { + t.Fatalf("legacy bytes changed: %v", err) + } +} +func TestFormatUpgradeLegacyIncompleteFork(t *testing.T) { + for _, segmented := range []bool{false, true} { + name := "flat" + if segmented { + name = "segmented" + } + t.Run(name, func(t *testing.T) { + f, c, r := preF4ForkFixture(t, segmented) + _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}) + if err != nil { + t.Fatalf("old incomplete fork retry: %v", err) + } + dst, err := NewChunkRemote(f, r.b, path.Join(catBase, "v2")) + if err != nil { + t.Fatal(err) + } + assertLegacyImage(t, dst) + e, err := f.LookupEntry(context.Background(), path.Join(catBase, "v2"), headName) + if err != nil { + t.Fatal(err) + } + var doc struct{ Format int } + if json.Unmarshal(e.Content, &doc) != nil || doc.Format != 3 { + t.Fatal("fork data must be format3") + } + }) + } +} +func TestFormatUpgradeLegacyForkIdentityStillRefusesChangedImage(t *testing.T) { + for _, segmented := range []bool{false, true} { + t.Run(map[bool]string{false: "flat", true: "segmented"}[segmented], func(t *testing.T) { + f, c, _ := preF4ForkFixture(t, segmented) + p := snapPath(t, f, "v1", "s1") + var s snapDoc + if err := json.Unmarshal(f.entries[p].Content, &s); err != nil { + t.Fatal(err) + } + var h map[string]any + if err := json.Unmarshal(s.Head, &h); err != nil { + t.Fatal(err) + } + // Preserve generation/frontier: only immutable content identity changes. + if segmented { + ref := h["segments"].(map[string]any)["0"].(map[string]any) + sum := ref["sha256"].([]any) + sum[0] = float64((int(sum[0].(float64)) + 1) % 256) + } else { + ref := h["chunks"].(map[string]any)["0"].(map[string]any) + ref["sha256"] = strings.Repeat("0", 64) + } + s.Head, _ = json.Marshal(h) + f.entries[p].Content, _ = json.Marshal(s) + if _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}); CodeOf(err) != CodeTargetExists { + t.Fatalf("changed image admitted or identity not reached: %v", err) + } + }) + } +} +func TestFormatUpgradeLegacySnapshotAndDelete(t *testing.T) { + t.Run("snapshot", func(t *testing.T) { + f, c, r := preF4ForkFixture(t, false) + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "upgraded", RequestID: "new-snapshot"}, h); err != nil { + t.Fatalf("legacy snapshot: %v", err) + } + e := f.entries[snapPath(t, f, "v1", "upgraded")] + var s snapDoc + if err := json.Unmarshal(e.Content, &s); err != nil { + t.Fatal(err) + } + var doc struct{ Format int } + json.Unmarshal(s.Head, &doc) + if doc.Format != 3 { + t.Fatal("snapshot contains flat data") + } + assertLegacyImage(t, r) + }) + t.Run("delete", func(t *testing.T) { + f, c, r := preF4ForkFixture(t, false) + for p := range f.entries { + if p != path.Join(catBase, "v1", headName) && p != path.Join(catBase, "v1", volumeName) && !bytes.Contains([]byte(p), []byte("/keys/")) { + delete(f.entries, p) + } + } + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + h.Holder = "" + h.Epoch = 0 + f.entries[path.Join(catBase, "v1", headName)] = legacyHeadFixture(t, h) + c.retainHook = func(stage, _ string) { + if stage == hookHeadMarked { + assertLegacyImage(t, r) + e := f.entries[path.Join(catBase, "v1", headName)] + var d struct{ Format int } + json.Unmarshal(e.Content, &d) + if d.Format != 3 { + t.Fatal("delete mark contains flat data") + } + } + } + res, err := c.DeleteVolume(context.Background(), "v1", nil) + if err != nil || !res.Completed { + t.Fatalf("legacy delete: %+v %v", res, err) + } + }) +} + +type legacyUpgradeView struct{} + +func (legacyUpgradeView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, Healthy: true} +} +func TestFormatUpgradeLegacyProviderTakeover(t *testing.T) { + f, _, r := preF4ForkFixture(t, false) + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-new/r1", ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, legacyUpgradeView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("legacy provider takeover: %v", err) + } + h, err := r.GetHead(ctx) + if err != nil || h.Holder != "node-new/r1" || h.Epoch != 2 { + t.Fatalf("takeover not installed: %+v %v", h, err) + } + e := f.entries[path.Join(catBase, "v1", headName)] + var d struct{ Format int } + json.Unmarshal(e.Content, &d) + if d.Format != 3 { + t.Fatal("takeover wrote flat data") + } + for i := uint32(0); i < 8; i++ { + got, err := s.Read(i) + if err != nil || !bytes.Equal(got, bytes.Repeat([]byte{0x41}, 4096)) { + t.Fatalf("takeover bytes %d: %v", i, err) + } + } + assertLegacyImage(t, r) +} diff --git a/seaweed-block/core/frontend/chunkstore/format_refusal_test.go b/seaweed-block/core/frontend/chunkstore/format_refusal_test.go new file mode 100644 index 0000000000..1fc6471d0a --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_refusal_test.go @@ -0,0 +1,105 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "encoding/json" + "path" + "testing" +) + +func TestManifestFormatUpgradeRejectsUnsupportedOrInconsistentObjects(t *testing.T) { + type mutation func(map[string]any) + for _, tc := range []struct { + name string + segment bool + change mutation + }{ + {"levels", false, func(v map[string]any) { v["levels"] = 2 }}, + {"missing-levels", false, func(v map[string]any) { delete(v, "levels") }}, + {"head-version", false, func(v map[string]any) { v["format"] = 4 }}, + {"head-unknown", false, func(v map[string]any) { v["future"] = true }}, + {"segment-version-ref", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["seg_format"] = 3 }}, + {"root-max", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["max_birth_lsn"] = 41 }}, + {"root-max-future", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["max_birth_lsn"] = 43 }}, + {"segment-version", true, func(v map[string]any) { v["format"] = 3 }}, + {"segment-unknown", true, func(v map[string]any) { v["future"] = true }}, + {"segment-max", true, func(v map[string]any) { v["max_birth_lsn"] = 41 }}, + {"segment-max-missing", true, func(v map[string]any) { delete(v, "max_birth_lsn") }}, + {"computed-max", true, func(v map[string]any) { + for _, entry := range v["chunks"].(map[string]any) { + entry.(map[string]any)["birth_lsn"] = 41 + } + }}, + {"encoding", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["enc"] = "zstd" }}, + {"birth-future", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["birth_lsn"] = 43 }}, + {"birth-missing", true, func(v map[string]any) { delete(v["chunks"].(map[string]any)["0"].(map[string]any), "birth_lsn") }}, + {"hash-shape", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["sha256"] = "bad" }}, + } { + t.Run(tc.name, func(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + r, h := publishSegmented(t, f, b) + ctx := context.Background() + e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) + if err != nil { + t.Fatal(err) + } + var root map[string]any + if err := json.Unmarshal(e.Content, &root); err != nil { + t.Fatal(err) + } + if tc.segment { + body, err := r.Get(ctx, h.Segments[0].Key) + if err != nil { + t.Fatal(err) + } + var object map[string]any + if err := json.Unmarshal(body, &object); err != nil { + t.Fatal(err) + } + tc.change(object) + body, err = json.Marshal(object) + if err != nil { + t.Fatal(err) + } + if err := r.Put(ctx, "malformed-segment", body); err != nil { + t.Fatal(err) + } + ref := root["segments"].(map[string]any)["0"].(map[string]any) + ref["key"] = qualifyManifestKey("v1", "malformed-segment") + ref["sha256"] = sha256.Sum256(body) + } else { + tc.change(root) + } + e.Content, err = json.Marshal(root) + if err != nil { + t.Fatal(err) + } + if err := f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { + t.Fatal(err) + } + if _, err := r.GetHead(ctx); err == nil { + t.Fatal("invalid persisted schema accepted") + } + }) + } +} + +func TestManifestFormatUpgradeReadsLegacyRootGoldens(t *testing.T) { + for _, body := range []string{ + `{"format":1,"gen":1,"epoch":1,"holder":"old","remote_lsn":7,"chunks":{"0":{"key":"old","sha256":"0000000000000000000000000000000000000000000000000000000000000000"}}}`, + `{"format":2,"gen":1,"epoch":1,"holder":"old","remote_lsn":7,"chunk_bytes":4096,"chunk_count":1,"segments":{"0":{"key":"@v1/old","sha256":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"owner":"v1","count":1}}}`, + } { + h, err := DecodeHeadDocument("legacy", []byte(body)) + if err != nil { + t.Fatal(err) + } + if h.Segments == nil { + if h.Chunks[0].Encoding != "full" || h.Chunks[0].BirthLSN != 7 { + t.Fatal("legacy flat frontier not inherited") + } + } else if h.Segments[0].SegFormat != 1 || h.Segments[0].MaxBirthLSN != 7 { + t.Fatal("legacy segment maximum not inherited") + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/format_reuse_test.go b/seaweed-block/core/frontend/chunkstore/format_reuse_test.go new file mode 100644 index 0000000000..7b738b075d --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_reuse_test.go @@ -0,0 +1,185 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "path" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func legacySegmentedFixture(t *testing.T) (*ChunkRemote, *fakeBlobs, storage.ChunkHead) { + t.Helper() + f, b, _, _, _ := gcFixture(t) + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + doc := segmentedHeadDoc{headIdentityDoc: headIdentityDoc{Format: 2, Gen: 1, Epoch: 1, Holder: "old", RemoteLSN: 42}, Segments: map[uint64]legacySegmentRefDoc{}, ChunkBytes: 4096, ChunkCount: 2} + for group := uint64(0); group < 2; group++ { + key := fmt.Sprintf("legacy-data-%d", group) + data := []byte{byte(0x41 + group)} + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + idx := group * (manifestSegmentBytes / 4096) + segment := legacySegmentDoc{Format: 1, Range: group, ChunkBytes: 4096, Owner: "v1", Chunks: map[uint64]legacyChunkRefDoc{idx: {Key: qualifyManifestKey("v1", key), SHA256: sha256.Sum256(data)}}} + body, err := json.Marshal(segment) + if err != nil { + t.Fatal(err) + } + segmentKey := fmt.Sprintf("legacy-segment-%d", group) + if err := r.Put(ctx, segmentKey, body); err != nil { + t.Fatal(err) + } + doc.Segments[group] = legacySegmentRefDoc{Key: qualifyManifestKey("v1", segmentKey), SHA256: sha256.Sum256(body), Owner: "v1", Count: 1} + } + e := legacyHeadFixture(t, storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "old", RemoteLSN: 42}) + e.Content, err = json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + if err := f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { + t.Fatal(err) + } + h, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + return r, b.fakeBlobs, h +} + +func TestManifestFormatUpgradeReusesColdSegmentsWithoutUploads(t *testing.T) { + r, b, base := legacySegmentedFixture(t) + ctx := context.Background() + before, _, _ := b.counts() + unchanged, ids, err := r.PrepareManifest(ctx, base, base, base.ChunkBytes) + if err != nil { + t.Fatal(err) + } + after, _, _ := b.counts() + if before != after || len(ids) != 0 || unchanged.Segments[0] != base.Segments[0] || unchanged.Segments[1] != base.Segments[1] { + t.Fatal("zero changed groups uploaded a segment or intent") + } + next := base + next.RemoteLSN = 43 + next.Chunks = map[uint64]storage.ChunkRef{} + for idx, ref := range base.Chunks { + next.Chunks[idx] = ref + } + data := []byte{0x53} + if err := r.Put(ctx, "changed-data", data); err != nil { + t.Fatal(err) + } + idx := manifestSegmentBytes / base.ChunkBytes + next.Chunks[idx] = storage.ChunkRef{Key: qualifyManifestKey("v1", "changed-data"), SHA256: sha256.Sum256(data), Encoding: "full", BirthLSN: 43} + before, _, _ = b.counts() + updated, ids, err := r.PrepareManifest(ctx, base, next, base.ChunkBytes) + if err != nil { + t.Fatal(err) + } + after, _, _ = b.counts() + if after-before != 1 || len(ids) != 1 || updated.Segments[0] != base.Segments[0] || updated.Segments[1].SegFormat != 2 || updated.Segments[1].MaxBirthLSN != 43 { + t.Fatal("one changed group rewrote cold segments or lost the new format") + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, updated); err != nil { + t.Fatal(err) + } + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + h, err := r.GetHead(ctx) + if err != nil || h.Segments[0].SegFormat != 1 || h.Chunks[0].BirthLSN != 42 || h.Chunks[idx].BirthLSN != 43 { + t.Fatalf("mixed legacy/new image did not resolve: %+v %v", h, err) + } + got, err := r.Get(ctx, h.Chunks[idx].Key) + if err != nil || len(got) != 1 || got[0] != 0x53 { + t.Fatal("mixed root changed bytes") + } +} + +func TestManifestFormatUpgradeAllowsInheritedZeroBirth(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + base, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + data := []byte{0x57} + if err := r.Put(ctx, "zero-birth", data); err != nil { + t.Fatal(err) + } + next := storage.ChunkHead{Epoch: 1, Holder: "base", Chunks: map[uint64]storage.ChunkRef{0: {Key: "zero-birth", SHA256: sha256.Sum256(data), Encoding: "full", BirthLSN: 0}}} + next, ids, err := r.PrepareManifest(ctx, base, next, 4096) + if err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, next); err != nil { + t.Fatal(err) + } + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + h, err := r.GetHead(ctx) + if err != nil || h.Chunks[0].BirthLSN != 0 || h.Segments[0].MaxBirthLSN != 0 { + t.Fatalf("fresh base zero birth refused: %+v %v", h, err) + } +} + +func TestManifestFormatUpgradeSnapshotAndForkPreserveMetadata(t *testing.T) { + f, b, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "format3", RequestID: "format3"}, h); err != nil { + t.Fatal(err) + } + snapshotPath := snapPath(t, f, "v1", "format3") + e, err := f.LookupEntry(ctx, path.Dir(snapshotPath), path.Base(snapshotPath)) + if err != nil { + t.Fatal(err) + } + var snapshot struct { + Head struct { + Format int `json:"format"` + Levels int `json:"levels"` + } `json:"head"` + } + if err := json.Unmarshal(e.Content, &snapshot); err != nil || snapshot.Head.Format != 3 || snapshot.Head.Levels != 1 { + t.Fatalf("data snapshot embedded flat HEAD: %s %v", e.Content, err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "format3", Target: "v2", RequestID: "format3-fork"}); err != nil { + t.Fatal(err) + } + r, err := NewChunkRemote(f, b, path.Join(catBase, "v2")) + if err != nil { + t.Fatal(err) + } + fork, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if fork.RemoteLSN != h.RemoteLSN || len(fork.Chunks) != len(h.Chunks) { + t.Fatal("fork lost inherited frontier or chunk count") + } + for idx, ref := range h.Chunks { + if fork.Chunks[idx] != ref { + t.Fatal("fork changed owner, encoding, birth or stored-byte hash") + } + } + for group, ref := range h.Segments { + if fork.Segments[group] != ref { + t.Fatal("fork changed segment version or maximum") + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/format_sustained_test.go b/seaweed-block/core/frontend/chunkstore/format_sustained_test.go new file mode 100644 index 0000000000..3d514e261b --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_sustained_test.go @@ -0,0 +1,113 @@ +package chunkstore + +import ( + "bytes" + "context" + "encoding/json" + "path" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestManifestFormatUpgradeSustainedWritesPastWALWithPeriodicFlush(t *testing.T) { + const blocks, blockSize, chunkBlocks = 1024, 4096, 64 + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + f, b := newFakeFiler(), newFakeBlobs() + r, err := NewChunkRemote(f, b, path.Join(catBase, "sustained")) + if err != nil { + t.Fatal(err) + } + s, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "source"), blocks, blockSize, storage.WALStoreOptions{ChunkBlocks: chunkBlocks, WMode: storage.WModeStrict}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { s.Close() }) + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: 1, Holder: "source", FreshFromHead: true, BarrierBound: 2, UploadConcurrency: 2}) + if err != nil { + t.Fatal(err) + } + walBytes := s.WALCapacityBytes() + if walBytes == 0 || walBytes > 128<<20 { + t.Fatalf("smoke WAL capacity outside bounded fixture: %d", walBytes) + } + batchBytes := uint64(blocks * blockSize) + rounds := int(walBytes/batchBytes) + 1 + var payload, last uint64 + var finalByte byte + for round := 0; round < rounds; round++ { + finalByte = byte(round%251 + 1) + data := bytes.Repeat([]byte{finalByte}, blocks*blockSize) + batch := make([][]byte, blocks) + for i := range batch { + batch[i] = data[i*blockSize : (i+1)*blockSize] + } + if _, err := s.WriteBatch(0, batch); err != nil { + t.Fatal(err) + } + last, err = s.Sync() + if err != nil { + t.Fatal(err) + } + payload += batchBytes + // Use the production periodic flusher, not a second checkpoint path. + for s.CheckpointLSN() < last { + select { + case <-ctx.Done(): + t.Fatalf("periodic Flush did not cover batch %d: %v", round, ctx.Err()) + case <-time.After(10 * time.Millisecond): + } + } + if (round+1)%4 == 0 || round+1 == rounds { + if _, err := l.Cut(ctx); err != nil { + t.Fatal(err) + } + } + } + if payload <= walBytes || s.FlushCount() == 0 { + t.Fatal("sustained fixture did not exceed WAL with periodic Flush") + } + h, err := r.GetHead(ctx) + if err != nil || h.RemoteLSN != last { + t.Fatalf("final frontier: %+v %v", h, err) + } + e, err := f.LookupEntry(ctx, path.Join(catBase, "sustained"), headName) + if err != nil { + t.Fatal(err) + } + var shape struct { + Format int `json:"format"` + Levels int `json:"levels"` + } + if err := json.Unmarshal(e.Content, &shape); err != nil || shape.Format != 3 || shape.Levels != 1 { + t.Fatal("sustained cut did not publish format3") + } + fresh, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "fresh"), blocks, blockSize, storage.WALStoreOptions{ChunkBlocks: chunkBlocks, WMode: storage.WModeStrict}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { fresh.Close() }) + if _, err := fresh.Recover(); err != nil { + t.Fatal(err) + } + if err := fresh.SeedChunkFrontier(last); err != nil { + t.Fatal(err) + } + if _, err := storage.AttachChunkLayer(fresh, r, storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: 2, Holder: "fresh", FreshFromHead: true}); err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{finalByte}, blockSize) + for lba := uint32(0); lba < blocks; lba++ { + got, err := fresh.Read(lba) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("fresh read block%d: %v", lba, err) + } + } + t.Logf("payload=%d > WAL=%d, checkpoint drains=%d, FlushCount=%d; full fresh lazy read exact", payload, walBytes, rounds, s.FlushCount()) +} diff --git a/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go b/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go new file mode 100644 index 0000000000..f758d1f4d0 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go @@ -0,0 +1,125 @@ +package chunkstore + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "path" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestManifestFormatUpgradeFlatWriterNeverStoresData(t *testing.T) { + dataHead := storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "h1", RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{0: {Key: "k"}}} + if _, err := headEntry(dataHead); err == nil { + t.Fatal("flat writer accepted chunk-bearing HEAD without a manifest") + } + f, b, _, _, _ := gcFixture(t) + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + cur, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(context.Background(), storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, dataHead); err == nil { + t.Fatal("direct CAS accepted geometry-free data") + } + after, err := r.GetHead(context.Background()) + if err != nil || after.Gen != cur.Gen { + t.Fatal("refused flat CAS changed HEAD") + } + empty, err := headEntry(storage.ChunkHead{Gen: 1, State: storage.ChunkHeadActive}) + if err != nil { + t.Fatal(err) + } + var shape struct { + Format int `json:"format"` + } + if err := json.Unmarshal(empty.Content, &shape); err != nil || shape.Format != 1 { + t.Fatal("empty flat root must remain writable") + } +} + +func TestManifestFormatUpgradeWritesVersionedStoredByteReferences(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + r, h := publishSegmented(t, f, b) + ctx := context.Background() + entry, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) + if err != nil { + t.Fatal(err) + } + var root struct { + Format int `json:"format"` + Levels int `json:"levels"` + Segments map[string]struct { + Format int `json:"seg_format"` + Max uint64 `json:"max_birth_lsn"` + } `json:"segments"` + } + if err := json.Unmarshal(entry.Content, &root); err != nil { + t.Fatal(err) + } + if root.Format != 3 || root.Levels != 1 || root.Segments["0"].Format != 2 || root.Segments["0"].Max != h.RemoteLSN { + t.Fatalf("missing format3/levels/segment2 metadata: %s", entry.Content) + } + body, err := r.Get(ctx, h.Segments[0].Key) + if err != nil { + t.Fatal(err) + } + var segment struct { + Format int `json:"format"` + Max uint64 `json:"max_birth_lsn"` + Chunks map[string]struct { + Encoding string `json:"enc"` + Birth uint64 `json:"birth_lsn"` + Hash string `json:"sha256"` + } `json:"chunks"` + } + if err := json.Unmarshal(body, &segment); err != nil { + t.Fatal(err) + } + if segment.Format != 2 || segment.Max != h.RemoteLSN || len(segment.Chunks) != 2 { + t.Fatalf("missing segment format/max: %s", body) + } + for _, ref := range segment.Chunks { + if ref.Encoding != "full" || ref.Birth != h.RemoteLSN || len(ref.Hash) != 64 { + t.Fatalf("invalid inherited chunk reference: %+v", ref) + } + } + resolved, err := r.GetHead(ctx) + if err != nil || len(resolved.Chunks) != 2 { + t.Fatalf("format3 roundtrip: %+v %v", resolved, err) + } +} + +func TestManifestFormatUpgradeRefusesUnknownSegmentField(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + r, h := publishSegmented(t, f, b) + ctx := context.Background() + if _, err := r.GetHead(ctx); err != nil { + t.Fatalf("valid legacy segment refused: %v", err) + } + ref := h.Segments[0] + body, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + // Keep the object hash valid: the refusal must come from the segment schema. + body = append(bytes.TrimSuffix(body, []byte("}")), []byte(",\"future_encoding\":\"unsupported\"}")...) + if err := r.Put(ctx, "format-upgrade-unknown-field", body); err != nil { + t.Fatal(err) + } + ref.Key = qualifyManifestKey(ref.Owner, "format-upgrade-unknown-field") + ref.SHA256 = sha256.Sum256(body) + h.Segments[0] = ref + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, h); err != nil { + t.Fatal(err) + } + if _, err := r.GetHead(ctx); err == nil { + t.Fatal("published segment with unknown field accepted") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index 5d524d0c13..7e8bf522f5 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -230,6 +230,15 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e } if in.Segments != nil { h := storage.ChunkHead{Segments: in.Segments, ChunkBytes: in.ChunkBytes} + // Intents protect keys without carrying a published frontier. + // Validate segment maxima against the reference maxima here. + for group, ref := range h.Segments { + if ref.SegFormat == 0 { + ref.SegFormat = 1 + h.Segments[group] = ref + } + h.RemoteLSN = max(h.RemoteLSN, ref.MaxBirthLSN) + } for _, ref := range in.Segments { h.ManifestChunkCount += ref.Count } diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go index 3a296d2d37..00789d6bf4 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go @@ -164,7 +164,7 @@ func TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace(t *testing.T) { t.Fatalf("first unrooted mark: %+v %v", result, e) } *now = now.Add(time.Hour) - if result, e := g.Run(ctx); e != nil || result.Reclaimed != 1 { + if result, e := g.Run(ctx); e != nil || result.Reclaimed != 2 { t.Fatalf("deleted attempt retained chunks forever: %+v %v", result, e) } if _, e := f.LookupEntry(ctx, path.Dir(oldPath), path.Base(oldPath)); e != nil { diff --git a/seaweed-block/core/frontend/chunkstore/gc_test.go b/seaweed-block/core/frontend/chunkstore/gc_test.go index 6ba7eca47b..498a7f667f 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_test.go @@ -69,7 +69,7 @@ func TestGC_StalledCutRemainsReadableAfterTwoMarks(t *testing.T) { } held := &heldGCRemote{remote, make(chan struct{}), make(chan struct{})} p := filepath.Join(t.TempDir(), "volume") - s, e := storage.CreateWALStore(p, 64, 4096) + s, e := storage.CreateWALStoreWithOptions(p, 64, 4096, storage.WALStoreOptions{ChunkBlocks: 8}) if e != nil { t.Fatal(e) } @@ -77,8 +77,7 @@ func TestGC_StalledCutRemainsReadableAfterTwoMarks(t *testing.T) { if _, e = s.Recover(); e != nil { t.Fatal(e) } - layer, e := storage.AttachChunkLayer(s, held, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", Bitmap: storage.NewFileChunkBitmapStore(p + ".bitmap"), - FreshFromHead: true}) // a new, empty store: its dirty set is known (empty) + layer, e := storage.AttachChunkLayer(s, held, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true}) // a new, empty store: its dirty set is known (empty) if e != nil { t.Fatal(e) } diff --git a/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go b/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go new file mode 100644 index 0000000000..d65183c90e --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go @@ -0,0 +1,62 @@ +package chunkstore + +import ( + "context" + "errors" + "path" + "reflect" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type rootCASFiler struct { + Filer + roots, children int + refuseChildren bool +} + +func (f *rootCASFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if name == headName { + f.roots++ + } else { + f.children++ + if f.refuseChildren { + return nil, errors.New("segment service unavailable") + } + } + return f.Filer.LookupEntry(ctx, dir, name) +} + +// A HEAD CAS validates root authority, not the availability of every immutable +// segment. Ordinary GetHead still resolves and verifies all segment contents. +func TestManifest_CASReadsOnlyRoot(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + _, h := publishSegmented(t, f, b) + tracked := &rootCASFiler{Filer: f, refuseChildren: true} + r, err := NewChunkRemote(tracked, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + next := h + next.RemoteLSN++ + gen, err := r.CASHead(context.Background(), storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next) + if err != nil { + t.Fatalf("root-only CAS must not depend on segments: %v", err) + } + if gen != h.Gen+1 || tracked.roots != 1 || tracked.children != 0 { + t.Fatalf("CAS gen=%d root reads=%d child reads=%d", gen, tracked.roots, tracked.children) + } + if _, err := r.GetHead(context.Background()); err == nil { + t.Fatal("GetHead skipped segment resolution") + } + tracked.refuseChildren = false + got, err := r.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if got.Gen != gen || got.RemoteLSN != next.RemoteLSN || !reflect.DeepEqual(got.Chunks, h.Chunks) || !reflect.DeepEqual(got.Segments, h.Segments) { + t.Fatalf("CAS changed content or lost frontier: %+v", got) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/head_decode.go b/seaweed-block/core/frontend/chunkstore/head_decode.go index fca0c37eff..699259088b 100644 --- a/seaweed-block/core/frontend/chunkstore/head_decode.go +++ b/seaweed-block/core/frontend/chunkstore/head_decode.go @@ -26,9 +26,30 @@ type flatHeadDoc struct { } type segmentedHeadDoc struct { headIdentityDoc - Segments map[uint64]storage.ChunkSegment `json:"segments"` - ChunkBytes uint64 `json:"chunk_bytes"` - ChunkCount int `json:"chunk_count"` + Segments map[uint64]legacySegmentRefDoc `json:"segments"` + ChunkBytes uint64 `json:"chunk_bytes"` + ChunkCount int `json:"chunk_count"` +} + +type legacySegmentRefDoc struct { + Key string `json:"key"` + SHA256 [32]byte `json:"sha256"` + Owner string `json:"owner"` + Count int `json:"count"` +} + +type segmentRefV3Doc struct { + legacySegmentRefDoc + MaxBirthLSN *uint64 `json:"max_birth_lsn"` + SegFormat int `json:"seg_format"` +} + +type levelHeadDoc struct { + headIdentityDoc + Levels int `json:"levels"` + Segments map[uint64]segmentRefV3Doc `json:"segments"` + ChunkBytes uint64 `json:"chunk_bytes"` + ChunkCount int `json:"chunk_count"` } func (d headIdentityDoc) document() headDoc { @@ -61,7 +82,29 @@ func decodeFormatHead(content []byte) (headDoc, error) { return headDoc{}, err } doc := segmented.headIdentityDoc.document() - doc.Segments, doc.ChunkBytes, doc.ChunkCount = segmented.Segments, segmented.ChunkBytes, segmented.ChunkCount + doc.Segments = make(map[uint64]storage.ChunkSegment, len(segmented.Segments)) + for group, ref := range segmented.Segments { + doc.Segments[group] = storage.ChunkSegment{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count, SegFormat: 1, MaxBirthLSN: doc.RemoteLSN} + } + doc.ChunkBytes, doc.ChunkCount = segmented.ChunkBytes, segmented.ChunkCount + return doc, nil + case 3: + var root levelHeadDoc + if err := decoder.Decode(&root); err != nil { + return headDoc{}, err + } + if root.Levels != 1 { + return headDoc{}, fmt.Errorf("chunkstore: unsupported levels %d", root.Levels) + } + doc := root.headIdentityDoc.document() + doc.Levels, doc.ChunkBytes, doc.ChunkCount = root.Levels, root.ChunkBytes, root.ChunkCount + doc.Segments = make(map[uint64]storage.ChunkSegment, len(root.Segments)) + for group, ref := range root.Segments { + if ref.MaxBirthLSN == nil || (ref.SegFormat != 1 && ref.SegFormat != 2) || *ref.MaxBirthLSN > root.RemoteLSN { + return headDoc{}, fmt.Errorf("chunkstore: invalid segment version/birth maximum") + } + doc.Segments[group] = storage.ChunkSegment{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count, SegFormat: ref.SegFormat, MaxBirthLSN: *ref.MaxBirthLSN} + } return doc, nil default: return headDoc{}, fmt.Errorf("chunkstore: unsupported HEAD format %d", discriminator.Format) diff --git a/seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go b/seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go new file mode 100644 index 0000000000..5df831bae3 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go @@ -0,0 +1,25 @@ +package chunkstore + +import ( + "encoding/hex" + "encoding/json" + "strconv" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Only old-reader fixtures bypass the production format-1 data-write refusal. +func legacyHeadFixture(t testing.TB, h storage.ChunkHead) *filerpb.Entry { + t.Helper() + doc := headDoc{Format: 1, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: h.State, Chunks: map[uint64]refDoc{}} + for idx, ref := range h.Chunks { + doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} + } + body, err := json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + return &filerpb.Entry{Name: headName, Content: body, Extended: map[string][]byte{extKind: []byte(kindChunkHead), extGen: []byte(strconv.FormatUint(h.Gen, 10)), extEpoch: []byte(strconv.FormatUint(h.Epoch, 10)), extHolder: []byte(h.Holder)}} +} diff --git a/seaweed-block/core/frontend/chunkstore/manifest.go b/seaweed-block/core/frontend/chunkstore/manifest.go index 01781b4b06..ee525f2213 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest.go +++ b/seaweed-block/core/frontend/chunkstore/manifest.go @@ -48,6 +48,9 @@ func validateRoot(h storage.ChunkHead) error { } count := 0 for group, ref := range h.Segments { + if (ref.SegFormat != 1 && ref.SegFormat != 2) || ref.MaxBirthLSN > h.RemoteLSN { + return errors.New("chunkstore: invalid segment version/birth maximum") + } if CheckVolumeID(ref.Owner) != nil || storage.ValidChunkKey(ref.Key) != nil || ref.Count <= 0 || uint64(ref.Count) > manifestSegmentBytes/h.ChunkBytes || group > ^uint64(0)/(manifestSegmentBytes/h.ChunkBytes) { return errors.New("chunkstore: invalid segment reference") } @@ -76,6 +79,12 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch groups := map[uint64]map[uint64]storage.ChunkRef{} canonical := make(map[uint64]storage.ChunkRef, len(next.Chunks)) for idx, ref := range next.Chunks { + if ref.Encoding == "" { + ref.Encoding, ref.BirthLSN = "full", next.RemoteLSN + } + if ref.Encoding != "full" || ref.BirthLSN > next.RemoteLSN { + return next, nil, errors.New("chunkstore: invalid chunk encoding/birth") + } ref.Key = qualifyManifestKey(owner, ref.Key) canonical[idx] = ref group := idx / per @@ -90,19 +99,31 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch data []byte } var uploads []upload - for group, chunks := range groups { - old := map[uint64]storage.ChunkRef{} - for idx, ref := range base.Chunks { - if idx/per == group { - ref.Key = qualifyManifestKey(owner, ref.Key) - old[idx] = ref - } + // Partition the base once, rather than scanning every base chunk for each + // segment group. Keep the same qualified-key comparison for segment reuse. + baseGroups := map[uint64]map[uint64]storage.ChunkRef{} + for idx, ref := range base.Chunks { + if ref.Encoding == "" { + ref.Encoding, ref.BirthLSN = "full", base.RemoteLSN } + group := idx / per + if baseGroups[group] == nil { + baseGroups[group] = map[uint64]storage.ChunkRef{} + } + ref.Key = qualifyManifestKey(owner, ref.Key) + baseGroups[group][idx] = ref + } + for group, chunks := range groups { + old := baseGroups[group] if previous, ok := base.Segments[group]; ok && base.ChunkBytes == chunkBytes && reflect.DeepEqual(chunks, old) { + // Legacy groups keep a conservative upper bound until rewritten. + if previous.SegFormat == 0 { + previous.SegFormat, previous.MaxBirthLSN = 1, base.RemoteLSN + } next.Segments[group] = previous continue } - body, err := json.Marshal(segmentDoc{1, group, chunkBytes, owner, chunks}) + body, maxBirth, err := encodeSegmentV2(group, chunkBytes, owner, chunks) if err != nil { return next, nil, err } @@ -114,7 +135,7 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch return next, nil, err } key := fmt.Sprintf("seg/%x", nonce) - next.Segments[group] = storage.ChunkSegment{Key: qualifyManifestKey(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks)} + next.Segments[group] = storage.ChunkSegment{Key: qualifyManifestKey(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks), SegFormat: 2, MaxBirthLSN: maxBirth} uploads = append(uploads, upload{key, body}) } if err := validateRoot(next); err != nil { @@ -156,11 +177,11 @@ func (r *ChunkRemote) resolveManifest(ctx context.Context, h storage.ChunkHead) if len(body) > maxManifestBytes || sha256.Sum256(body) != ref.SHA256 { return h, errors.New("chunkstore: segment hash/size mismatch") } - var doc segmentDoc - if err := decodeManifestJSON(body, &doc); err != nil { + doc, err := decodeSegment(body, ref, h.RemoteLSN) + if err != nil { return h, err } - if doc.Format != 1 || doc.Range != group || doc.ChunkBytes != h.ChunkBytes || doc.Owner != ref.Owner || len(doc.Chunks) != ref.Count { + if doc.Range != group || doc.ChunkBytes != h.ChunkBytes || doc.Owner != ref.Owner || len(doc.Chunks) != ref.Count { return h, errors.New("chunkstore: invalid segment contents") } for idx, cr := range doc.Chunks { diff --git a/seaweed-block/core/frontend/chunkstore/manifest_format.go b/seaweed-block/core/frontend/chunkstore/manifest_format.go new file mode 100644 index 0000000000..bd5f852035 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/manifest_format.go @@ -0,0 +1,105 @@ +package chunkstore + +import ( + "bytes" + "encoding/hex" + "encoding/json" + "errors" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type segmentChunkV2Doc struct { + Key string `json:"key"` + // SHA256 covers stored object bytes, before any encoding is decoded. + SHA256 string `json:"sha256"` + Encoding string `json:"enc"` + BirthLSN *uint64 `json:"birth_lsn"` +} + +type segmentV2Doc struct { + Format int `json:"format"` + Range uint64 `json:"range"` + ChunkBytes uint64 `json:"chunk_bytes"` + Owner string `json:"owner"` + MaxBirthLSN *uint64 `json:"max_birth_lsn"` + Chunks map[uint64]segmentChunkV2Doc `json:"chunks"` +} + +type legacyChunkRefDoc struct { + Key string + SHA256 [32]byte +} + +type legacySegmentDoc struct { + Format int `json:"format"` + Range uint64 `json:"range"` + ChunkBytes uint64 `json:"chunk_bytes"` + Owner string `json:"owner"` + Chunks map[uint64]legacyChunkRefDoc `json:"chunks"` +} + +func encodeSegmentV2(group, chunkBytes uint64, owner string, chunks map[uint64]storage.ChunkRef) ([]byte, uint64, error) { + doc := segmentV2Doc{Format: 2, Range: group, ChunkBytes: chunkBytes, Owner: owner, Chunks: map[uint64]segmentChunkV2Doc{}} + var maxBirth uint64 + for idx, ref := range chunks { + birth := ref.BirthLSN + doc.Chunks[idx] = segmentChunkV2Doc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:]), Encoding: ref.Encoding, BirthLSN: &birth} + maxBirth = max(maxBirth, birth) + } + doc.MaxBirthLSN = &maxBirth + body, err := json.Marshal(doc) + return body, maxBirth, err +} + +func decodeSegment(body []byte, ref storage.ChunkSegment, remoteLSN uint64) (segmentDoc, error) { + var discriminator struct { + Format int `json:"format"` + } + if err := decodeManifestJSON(body, &discriminator); err != nil { + return segmentDoc{}, err + } + if discriminator.Format != ref.SegFormat { + return segmentDoc{}, errors.New("chunkstore: segment format/reference mismatch") + } + d := json.NewDecoder(bytes.NewReader(body)) + d.DisallowUnknownFields() + result := segmentDoc{Chunks: map[uint64]storage.ChunkRef{}} + switch discriminator.Format { + case 1: + var doc legacySegmentDoc + if err := d.Decode(&doc); err != nil { + return result, err + } + result.Format, result.Range, result.ChunkBytes, result.Owner = doc.Format, doc.Range, doc.ChunkBytes, doc.Owner + for idx, cr := range doc.Chunks { + result.Chunks[idx] = storage.ChunkRef{Key: cr.Key, SHA256: cr.SHA256, Encoding: "full", BirthLSN: ref.MaxBirthLSN} + } + case 2: + var doc segmentV2Doc + if err := d.Decode(&doc); err != nil { + return result, err + } + if doc.MaxBirthLSN == nil || *doc.MaxBirthLSN != ref.MaxBirthLSN || *doc.MaxBirthLSN > remoteLSN { + return result, errors.New("chunkstore: segment birth maximum mismatch") + } + result.Format, result.Range, result.ChunkBytes, result.Owner = doc.Format, doc.Range, doc.ChunkBytes, doc.Owner + var maxBirth uint64 + for idx, cr := range doc.Chunks { + sum, err := hex.DecodeString(cr.SHA256) + if err != nil || len(sum) != 32 || cr.Encoding != "full" || cr.BirthLSN == nil || *cr.BirthLSN > remoteLSN { + return result, errors.New("chunkstore: invalid segment chunk encoding/hash/birth") + } + v := storage.ChunkRef{Key: cr.Key, Encoding: cr.Encoding, BirthLSN: *cr.BirthLSN} + copy(v.SHA256[:], sum) + result.Chunks[idx] = v + maxBirth = max(maxBirth, v.BirthLSN) + } + if maxBirth != *doc.MaxBirthLSN { + return result, errors.New("chunkstore: incorrect segment birth maximum") + } + default: + return result, errors.New("chunkstore: unsupported segment format") + } + return result, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go b/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go index efa205cb31..a7fa099313 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go @@ -67,7 +67,7 @@ func TestManifestPerf_64DirtyChunks(t *testing.T) { if _, err = s.Recover(); err != nil { t.Fatal(err) } - l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 1024, Epoch: 1, Holder: "h1", FreshFromHead: true, UploadConcurrency: parallel, Bitmap: storage.NewFileChunkBitmapStore(filepath.Join(dir, "bitmap"))}) + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 1024, Epoch: 1, Holder: "h1", FreshFromHead: true, UploadConcurrency: parallel}) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/chunkstore/manifest_scaling_test.go b/seaweed-block/core/frontend/chunkstore/manifest_scaling_test.go new file mode 100644 index 0000000000..dd093d6c84 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/manifest_scaling_test.go @@ -0,0 +1,36 @@ +package chunkstore + +import ( + "context" + "fmt" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Metadata-only scaling probe: one chunk per 1-GiB segment, all unchanged. +// No volume data allocation or remote I/O is included. Report ns/op and allocs; +// the old per-group scan visits groups*groups base references. +func BenchmarkPrepareManifestUnchangedGroups(b *testing.B) { + for _, n := range []int{256, 1024, 4096} { + b.Run(fmt.Sprint(n), func(b *testing.B) { + r, err := NewChunkRemote(newFakeFiler(), newFakeBlobs(), "/chunks/v1") + if err != nil { + b.Fatal(err) + } + base := storage.ChunkHead{Chunks: map[uint64]storage.ChunkRef{}, Segments: map[uint64]storage.ChunkSegment{}, ChunkBytes: 1 << 30, ManifestChunkCount: n} + for i := 0; i < n; i++ { + base.Chunks[uint64(i)] = storage.ChunkRef{Key: fmt.Sprintf("@v1/chunk/%d", i)} + base.Segments[uint64(i)] = storage.ChunkSegment{Key: fmt.Sprintf("@v1/seg/%d", i), Owner: "v1", Count: 1} + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + next, ids, err := r.PrepareManifest(context.Background(), base, base, 1<<30) + if err != nil || len(ids) != 0 || len(next.Segments) != n { + b.Fatalf("unchanged segment reuse: %v, intents=%v", err, ids) + } + } + }) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/manifest_test.go b/seaweed-block/core/frontend/chunkstore/manifest_test.go index 58d39ea59c..fa0309f434 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_test.go @@ -23,7 +23,7 @@ func TestManifest_CapturePublishesSegmentRoot(t *testing.T) { t.Fatal(err) } p := filepath.Join(t.TempDir(), "volume") - s, err := storage.CreateWALStore(p, 64, 4096) + s, err := storage.CreateWALStoreWithOptions(p, 64, 4096, storage.WALStoreOptions{ChunkBlocks: 8}) if err != nil { t.Fatal(err) } @@ -31,7 +31,7 @@ func TestManifest_CapturePublishesSegmentRoot(t *testing.T) { if _, err = s.Recover(); err != nil { t.Fatal(err) } - l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true, Bitmap: storage.NewFileChunkBitmapStore(p + ".bitmap")}) + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true}) if err != nil { t.Fatal(err) } @@ -54,7 +54,7 @@ func TestManifest_CapturePublishesSegmentRoot(t *testing.T) { if err = json.Unmarshal(e.Content, &doc); err != nil { t.Fatal(err) } - if doc.Format != 2 || len(doc.Chunks) != 0 || len(doc.Segments) != 1 { + if doc.Format != 3 || len(doc.Chunks) != 0 || len(doc.Segments) != 1 { t.Fatalf("cut did not publish a small segmented root: %s", e.Content) } h, err := r.GetHead(ctx) @@ -281,7 +281,7 @@ func TestManifest_NoopFlatUpgradeUsesOneNormalGeneration(t *testing.T) { t.Fatal(err) } p := filepath.Join(t.TempDir(), "store") - s, err := storage.CreateWALStore(p, 64, 4096) + s, err := storage.CreateWALStoreWithOptions(p, 64, 4096, storage.WALStoreOptions{ChunkBlocks: 8}) if err != nil { t.Fatal(err) } @@ -289,7 +289,7 @@ func TestManifest_NoopFlatUpgradeUsesOneNormalGeneration(t *testing.T) { if _, err = s.Recover(); err != nil { t.Fatal(err) } - l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true, Bitmap: storage.NewFileChunkBitmapStore(p + ".bitmap")}) + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true}) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/chunkstore/manifest_upgrade.go b/seaweed-block/core/frontend/chunkstore/manifest_upgrade.go new file mode 100644 index 0000000000..8a9887873b --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/manifest_upgrade.go @@ -0,0 +1,80 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func (c *Catalog) prepareLegacyHead(ctx context.Context, root string, base, next storage.ChunkHead, geo Geometry) (storage.ChunkHead, []string, error) { + if next.Segments != nil || len(next.Chunks) == 0 { + return next, nil, nil + } + if c.blobs == nil { + return next, nil, errors.New("chunkstore: legacy data upgrade needs blob storage") + } + r, err := NewChunkRemote(c.f, c.blobs, root) + if err != nil { + return next, nil, err + } + return r.PrepareManifest(ctx, base, next, uint64(geo.BlockSize)*uint64(geo.ChunkBlocks)) +} +func (c *Catalog) dropManifestIntents(ctx context.Context, root string, ids []string) { + for _, id := range ids { + c.dropIntent(ctx, root, id) + } +} + +// Fork identity is a persisted protocol. Old snapshots keep the pre-format-3 +// canonical encoding even when their next publication upgrades the manifest. +func snapshotHeadDigest(h storage.ChunkHead, embedded json.RawMessage) (string, error) { + var version struct { + Format int `json:"format"` + } + if err := json.Unmarshal(embedded, &version); err != nil { + return "", err + } + if version.Format == 3 { + return headDigest(h) + } + type oldHead struct { + Segments map[uint64]legacySegmentRefDoc `json:"segments,omitempty"` + ChunkBytes uint64 `json:"chunk_bytes,omitempty"` + ChunkCount int `json:"chunk_count,omitempty"` + Format int `json:"format"` + Gen uint64 `json:"gen"` + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + RemoteLSN uint64 `json:"remote_lsn"` + Chunks map[uint64]refDoc `json:"chunks,omitempty"` + State string `json:"state,omitempty"` + DetachedBy *detachedByDoc `json:"detachedBy,omitempty"` + } + d := oldHead{Format: version.Format, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: h.State} + if h.DetachedBy != nil { + d.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen} + } + if version.Format == 2 { + d.Segments = map[uint64]legacySegmentRefDoc{} + d.ChunkBytes = h.ChunkBytes + d.ChunkCount = h.ManifestChunkCount + for idx, ref := range h.Segments { + d.Segments[idx] = legacySegmentRefDoc{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count} + } + } else { + d.Chunks = map[uint64]refDoc{} + for idx, ref := range h.Chunks { + d.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} + } + } + body, err := json.Marshal(d) + if err != nil { + return "", err + } + sum := sha256.Sum256(body) + return hex.EncodeToString(sum[:]), nil +} diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go index 79e8eed28b..10109d3916 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_test.go @@ -338,11 +338,20 @@ func publishTagged(t *testing.T, f *fakeFiler, b *fakeBlobs, vol, tag string, ch if err != nil { t.Fatal(err) } + h, ids, err := r.PrepareManifest(ctx, cur, h, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h) if err != nil { t.Fatal(err) } h.Gen = gen + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } return h } @@ -353,6 +362,19 @@ func TestCatalog_UsageFromManifests(t *testing.T) { f, b, c, h := catalogFixture(t) // HEAD: chunks 0 and 3 ctx := context.Background() full := uint64(catGeo.ChunkBlocks) * uint64(catGeo.BlockSize) + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + manifestBytes := func(head storage.ChunkHead) uint64 { + var total uint64 + for _, ref := range head.Segments { + body, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + total += uint64(len(body)) + } + return total + } + expectedManifestBytes := manifestBytes(h) if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { t.Fatal(err) } @@ -363,12 +385,13 @@ func TestCatalog_UsageFromManifests(t *testing.T) { if u.LiveChunks != 2 || u.LiveBytes != 2*full || len(u.Snapshots) != 1 || u.Snapshots[0].ExclusiveBytes != 0 { t.Fatalf("shared chunks: %+v", u) } - if u.StoredBindings != 2 || u.StoredBytes != 2*full || u.StoredUpperBound { + if u.StoredBindings != 3 || u.ManifestBindings != 1 || expectedManifestBytes == 0 || u.ManifestBytes != expectedManifestBytes || u.StoredBytes != 2*full+expectedManifestBytes || u.StoredUpperBound { t.Fatalf("stored: %+v; want 2 bindings, exact", u) } // HEAD moves on: chunk 0 is rewritten, so s1 alone holds the old one. - publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)}) + newHead := publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)}) + expectedManifestBytes += manifestBytes(newHead) u, err = c.Usage(ctx, "v1") if err != nil { t.Fatal(err) @@ -377,7 +400,7 @@ func TestCatalog_UsageFromManifests(t *testing.T) { // both of s1's chunks are now exclusive: the new HEAD uses e2 keys t.Fatalf("after HEAD moved: s1 exclusive %d, want %d", u.Snapshots[0].ExclusiveBytes, 2*full) } - if u.StoredBindings != 4 || u.StoredBytes != 4*full || u.StoredUpperBound { + if u.StoredBindings != 6 || u.ManifestBindings != 2 || u.ManifestBytes != expectedManifestBytes || u.StoredBytes != 4*full+expectedManifestBytes || u.StoredUpperBound { t.Fatalf("stored after HEAD moved: %+v; want 4 bindings, exact", u) } @@ -390,7 +413,7 @@ func TestCatalog_UsageFromManifests(t *testing.T) { if err != nil { t.Fatal(err) } - if len(u.Snapshots) != 0 || u.StoredBindings != 4 || !u.StoredUpperBound { + if len(u.Snapshots) != 0 || u.StoredBindings != 6 || !u.StoredUpperBound { t.Fatalf("after delete: %+v; want no snapshots, 4 bindings, upper bound", u) } } diff --git a/seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go b/seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go new file mode 100644 index 0000000000..a70a44babb --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go @@ -0,0 +1,53 @@ +package chunkstore + +import ( + "crypto/sha256" + "encoding/json" + "reflect" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func FuzzDecodeVersionedSegment(f *testing.F) { + sum := sha256.Sum256([]byte("stored bytes")) + refs := map[uint64]storage.ChunkRef{0: {Key: "@v1/k", SHA256: sum, Encoding: "full", BirthLSN: 7}} + body, _, err := encodeSegmentV2(0, 4096, "v1", refs) + if err != nil { + f.Fatal(err) + } + f.Add(body, uint8(2)) + legacy, err := json.Marshal(legacySegmentDoc{Format: 1, Range: 0, ChunkBytes: 4096, Owner: "v1", Chunks: map[uint64]legacyChunkRefDoc{0: {Key: "@v1/k", SHA256: sum}}}) + if err != nil { + f.Fatal(err) + } + f.Add(legacy, uint8(1)) + f.Add([]byte(`{"format":2,"format":1}`), uint8(2)) + f.Add([]byte(`{"format":3}`), uint8(3)) + f.Fuzz(func(t *testing.T, body []byte, version uint8) { + ref := storage.ChunkSegment{SegFormat: int(version), MaxBirthLSN: 7} + got, err := decodeSegment(body, ref, 7) + if err != nil { + return + } + if got.Format != 1 && got.Format != 2 { + t.Fatalf("accepted format %d", got.Format) + } + for _, cr := range got.Chunks { + if cr.Encoding != "full" || cr.BirthLSN > 7 { + t.Fatalf("accepted unsupported chunk metadata: %+v", cr) + } + } + if got.Format == 2 { + encoded, maxBirth, err := encodeSegmentV2(got.Range, got.ChunkBytes, got.Owner, got.Chunks) + if err != nil { + t.Fatal(err) + } + ref.MaxBirthLSN = maxBirth + again, err := decodeSegment(encoded, ref, 7) + if err != nil || !reflect.DeepEqual(got, again) { + t.Fatalf("round trip: %+v / %+v: %v", got, again, err) + } + } + }) +} diff --git a/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_false.json b/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_false.json new file mode 100644 index 0000000000..a544d45c09 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_false.json @@ -0,0 +1 @@ +{"Entries":{"/swblock/chunks/v1/HEAD":{"name":"HEAD","attributes":{"file_size":190,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.epoch":"MQ==","swb.gen":"Mg==","swb.holder":"b2xk","swb.kind":"Y2h1bmtoZWFk"},"content":"eyJmb3JtYXQiOjEsImdlbiI6MiwiZXBvY2giOjEsImhvbGRlciI6Im9sZCIsInJlbW90ZV9sc24iOjcsImNodW5rcyI6eyIwIjp7ImtleSI6ImxlZ2FjeS1kYXRhIiwic2hhMjU2IjoiNWZmMDc0ZGRhZDg4YjdmY2I0MzM5Y2I3YTNlNjgzNDEwNjE3OTI4NjllNDM2NzNiMmRlODUyNWE3NTQ3NmJkOCJ9fSwic3RhdGUiOiJhY3RpdmUifQ=="},"/swblock/chunks/v1/VOLUME":{"name":"VOLUME","attributes":{"file_size":139,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiY3JlYXRlIiwiY3JlYXRlZF9ucyI6MTAwMDAwMDAwMDAwMCwicGFyZW50IjpudWxsfQ=="},"/swblock/chunks/v1/snapnames/s1":{"name":"s1","attributes":{"file_size":127,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi01NTJjZmRhNGU0YzI3YzA1","swb.kind":"Y2h1bmtzbmFwbmFtZQ==","swb.req":"b2xkLXNuYXBzaG90"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImF0dGVtcHQiOiIyLTU1MmNmZGE0ZTRjMjdjMDUiLCJjcmVhdGVkX25zIjoxMDAwMDAwMDAwMDAwfQ=="},"/swblock/chunks/v1/snaps/s1/2-552cfda4e4c27c05":{"name":"2-552cfda4e4c27c05","attributes":{"file_size":442,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi01NTJjZmRhNGU0YzI3YzA1","swb.kind":"Y2h1bmtzbmFw","swb.req":"b2xkLXNuYXBzaG90","swb.snap.claims":"WyJ2Mi9vbGQtZm9yayJd","swb.snap.epoch":"MQ==","swb.snap.gen":"Mg==","swb.snap.lsn":"Nw==","swb.snap.state":"YWN0aXZl"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsImNyZWF0ZWRfYnkiOiIiLCJjb25zaXN0ZW5jeSI6ImNyYXNoIiwiaGVhZCI6eyJmb3JtYXQiOjEsImdlbiI6MiwiZXBvY2giOjEsImhvbGRlciI6Im9sZCIsInJlbW90ZV9sc24iOjcsImNodW5rcyI6eyIwIjp7ImtleSI6ImxlZ2FjeS1kYXRhIiwic2hhMjU2IjoiNWZmMDc0ZGRhZDg4YjdmY2I0MzM5Y2I3YTNlNjgzNDEwNjE3OTI4NjllNDM2NzNiMmRlODUyNWE3NTQ3NmJkOCJ9fSwic3RhdGUiOiJhY3RpdmUifSwiZ2VvbWV0cnkiOnsibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OH0sInBhcmVudCI6bnVsbCwibGFiZWxzIjpudWxsLCJleHBpcmVzX2F0X25zIjowfQ=="},"/swblock/chunks/v2/VOLUME":{"name":"VOLUME","attributes":{"file_size":384,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU=","swb.req":"b2xkLWZvcms="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYyIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiZm9yayIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsInBhcmVudCI6eyJ2b2x1bWVfaWQiOiJ2MSIsInNuYXBzaG90IjoiczEiLCJnZW4iOjJ9LCJmb3JrIjp7InJlcXVlc3RfaWQiOiJvbGQtZm9yayIsInNvdXJjZSI6InYxIiwic25hcHNob3QiOiJzMSIsInNvdXJjZV9nZW4iOjIsImhlYWRfc2hhMjU2IjoiNGZlZGEwZWY2ZTA1OGRjNzNmYmFlMWUyZWEwOGU3ZTdlMGVjZWE0OTk2NjY0Y2ViYTFjYTNmODA5ZGFiYTk3MiIsInJlbW90ZV9sc24iOjcsImNodW5rX2NvdW50IjoxLCJxdWFsaWZpZWRfcmVmcyI6MX19"}},"Objects":{}} diff --git a/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_true.json b/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_true.json new file mode 100644 index 0000000000..43bcb01966 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/testdata/pre_f4_fork_true.json @@ -0,0 +1 @@ +{"Entries":{"/swblock/chunks/v1/HEAD":{"name":"HEAD","attributes":{"file_size":331,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.epoch":"MQ==","swb.gen":"Mg==","swb.holder":"b2xk","swb.kind":"Y2h1bmtoZWFk"},"content":"eyJzZWdtZW50cyI6eyIwIjp7ImtleSI6IkB2MS9zZWcvZTdiM2VkZGUwNTYwYTM3MjQxZTkxMDJkNjA3ZWJjMTQiLCJzaGEyNTYiOls3NSwyMTgsMTMyLDExMywxNTgsMTcxLDQ1LDIxNCwyMjUsMjE5LDEwNywxNzYsMTczLDQ4LDI0MiwxNTMsMTIsMjMwLDExOCwyMjcsOTAsMTQxLDI0Nyw0LDExMSw1Nyw0OSwyMzcsOTQsMTg0LDg0LDk0XSwib3duZXIiOiJ2MSIsImNvdW50IjoxfX0sImNodW5rX2J5dGVzIjozMjc2OCwiY2h1bmtfY291bnQiOjEsImZvcm1hdCI6MiwiZ2VuIjoyLCJlcG9jaCI6MSwiaG9sZGVyIjoib2xkIiwicmVtb3RlX2xzbiI6Nywic3RhdGUiOiJhY3RpdmUifQ=="},"/swblock/chunks/v1/VOLUME":{"name":"VOLUME","attributes":{"file_size":139,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiY3JlYXRlIiwiY3JlYXRlZF9ucyI6MTAwMDAwMDAwMDAwMCwicGFyZW50IjpudWxsfQ=="},"/swblock/chunks/v1/snapnames/s1":{"name":"s1","attributes":{"file_size":127,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi03ZDc0ZTg5MWU0MTZhMmI5","swb.kind":"Y2h1bmtzbmFwbmFtZQ==","swb.req":"b2xkLXNuYXBzaG90"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImF0dGVtcHQiOiIyLTdkNzRlODkxZTQxNmEyYjkiLCJjcmVhdGVkX25zIjoxMDAwMDAwMDAwMDAwfQ=="},"/swblock/chunks/v1/snaps/s1/2-7d74e891e416a2b9":{"name":"2-7d74e891e416a2b9","attributes":{"file_size":583,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.attempt":"Mi03ZDc0ZTg5MWU0MTZhMmI5","swb.kind":"Y2h1bmtzbmFw","swb.req":"b2xkLXNuYXBzaG90","swb.snap.claims":"WyJ2Mi9vbGQtZm9yayJd","swb.snap.epoch":"MQ==","swb.snap.gen":"Mg==","swb.snap.lsn":"Nw==","swb.snap.state":"YWN0aXZl"},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYxIiwibmFtZSI6InMxIiwicmVxdWVzdF9pZCI6Im9sZC1zbmFwc2hvdCIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsImNyZWF0ZWRfYnkiOiIiLCJjb25zaXN0ZW5jeSI6ImNyYXNoIiwiaGVhZCI6eyJzZWdtZW50cyI6eyIwIjp7ImtleSI6IkB2MS9zZWcvZTdiM2VkZGUwNTYwYTM3MjQxZTkxMDJkNjA3ZWJjMTQiLCJzaGEyNTYiOls3NSwyMTgsMTMyLDExMywxNTgsMTcxLDQ1LDIxNCwyMjUsMjE5LDEwNywxNzYsMTczLDQ4LDI0MiwxNTMsMTIsMjMwLDExOCwyMjcsOTAsMTQxLDI0Nyw0LDExMSw1Nyw0OSwyMzcsOTQsMTg0LDg0LDk0XSwib3duZXIiOiJ2MSIsImNvdW50IjoxfX0sImNodW5rX2J5dGVzIjozMjc2OCwiY2h1bmtfY291bnQiOjEsImZvcm1hdCI6MiwiZ2VuIjoyLCJlcG9jaCI6MSwiaG9sZGVyIjoib2xkIiwicmVtb3RlX2xzbiI6Nywic3RhdGUiOiJhY3RpdmUifSwiZ2VvbWV0cnkiOnsibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OH0sInBhcmVudCI6bnVsbCwibGFiZWxzIjpudWxsLCJleHBpcmVzX2F0X25zIjowfQ=="},"/swblock/chunks/v2/VOLUME":{"name":"VOLUME","attributes":{"file_size":384,"mtime":1795084724,"file_mode":420,"crtime":1795084724,"mime":"application/json"},"extended":{"swb.kind":"Y2h1bmt2b2x1bWU=","swb.req":"b2xkLWZvcms="},"content":"eyJmb3JtYXQiOjEsInZvbHVtZV9pZCI6InYyIiwibnVtX2Jsb2NrcyI6NjQsImJsb2NrX3NpemUiOjQwOTYsImNodW5rX2Jsb2NrcyI6OCwib3JpZ2luIjoiZm9yayIsImNyZWF0ZWRfbnMiOjEwMDAwMDAwMDAwMDAsInBhcmVudCI6eyJ2b2x1bWVfaWQiOiJ2MSIsInNuYXBzaG90IjoiczEiLCJnZW4iOjJ9LCJmb3JrIjp7InJlcXVlc3RfaWQiOiJvbGQtZm9yayIsInNvdXJjZSI6InYxIiwic25hcHNob3QiOiJzMSIsInNvdXJjZV9nZW4iOjIsImhlYWRfc2hhMjU2IjoiY2U3OTJiODQ3NWQ2OGY3OTcwNzNlMTA0Nzc1NTFlYmUzYzBlMTQ2NzdmNTNmYjIxMzZkYmM2MDQ4YmVlODU1MSIsInJlbW90ZV9sc24iOjcsImNodW5rX2NvdW50IjoxLCJxdWFsaWZpZWRfcmVmcyI6MX19"}},"Objects":{"seg/e7b3edde0560a37241e9102d607ebc14":"eyJmb3JtYXQiOjEsInJhbmdlIjowLCJjaHVua19ieXRlcyI6MzI3NjgsIm93bmVyIjoidjEiLCJjaHVua3MiOnsiMCI6eyJLZXkiOiJAdjEvbGVnYWN5LWRhdGEiLCJTSEEyNTYiOls5NSwyNDAsMTE2LDIyMSwxNzMsMTM2LDE4MywyNTIsMTgwLDUxLDE1NiwxODMsMTYzLDIzMCwxMzEsNjUsNiwyMywxNDYsMTM0LDE1OCw2NywxMDMsNTksNDUsMjMyLDgyLDkwLDExNyw3MSwxMDcsMjE2XX19fQ=="}} diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete.go b/seaweed-block/core/frontend/chunkstore/volume_delete.go index 0526990ae7..bfa4b8d787 100644 --- a/seaweed-block/core/frontend/chunkstore/volume_delete.go +++ b/seaweed-block/core/frontend/chunkstore/volume_delete.go @@ -244,17 +244,38 @@ func headDeletingOrDeleted(h storage.ChunkHead) bool { // refuses to anyone else. func (c *Catalog) writeHead(ctx context.Context, root string, cur, next storage.ChunkHead) error { next.Gen = cur.Gen + 1 + var ids []string + if next.Segments == nil && len(next.Chunks) != 0 { + v, ok, err := c.ReadVolume(ctx, path.Base(root)) + if err != nil { + return err + } + if !ok { + return errors.New("chunkstore: legacy delete needs VOLUME geometry") + } + next, ids, err = c.prepareLegacyHead(ctx, root, cur, next, v.Geometry) + if err != nil { + c.dropManifestIntents(ctx, root, ids) + return err + } + } e, err := headEntry(next) if err != nil { + c.dropManifestIntents(ctx, root, ids) return err } if cur.Gen == 0 { - return c.f.CreateEntry(ctx, root, e, true) + err = c.f.CreateEntry(ctx, root, e, true) + } else { + err = c.f.UpdateEntry(ctx, root, e, map[string][]byte{ + extGen: []byte(strconv.FormatUint(cur.Gen, 10)), extEpoch: []byte(strconv.FormatUint(cur.Epoch, 10)), + }) } - return c.f.UpdateEntry(ctx, root, e, map[string][]byte{ - extGen: []byte(strconv.FormatUint(cur.Gen, 10)), - extEpoch: []byte(strconv.FormatUint(cur.Epoch, 10)), - }) + // Unknown publication retains protection; a later sweep can settle it. + if err == nil || lostCondition(err) { + c.dropManifestIntents(ctx, root, ids) + } + return err } func lostCondition(err error) bool { diff --git a/seaweed-block/core/frontend/chunkstore/volume_size_limit_test.go b/seaweed-block/core/frontend/chunkstore/volume_size_limit_test.go new file mode 100644 index 0000000000..debc3434e1 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/volume_size_limit_test.go @@ -0,0 +1,28 @@ +package chunkstore + +import ( + "context" + "strings" + "testing" +) + +func TestEnsureVolumeRejectsBeyondUint32LBACap(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + c, err := NewCatalog(manifestFilerBlobs{f, b}, catBase) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if _, err = c.EnsureVolume(ctx, "at-cap", Geometry{NumBlocks: 4294967295, BlockSize: 4096, ChunkBlocks: 1024}); err != nil { + t.Fatal(err) + } + for _, blocks := range []uint64{4294967296, ^uint64(0)} { + _, err = c.EnsureVolume(ctx, "too-large", Geometry{NumBlocks: blocks, BlockSize: 4096, ChunkBlocks: 1024}) + if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("blocks %d: want capacity refusal, got %v", blocks, err) + } + if _, ok, e := c.ReadVolume(ctx, "too-large"); e != nil || ok { + t.Fatalf("refusal changed catalog: exists=%v err=%v", ok, e) + } + } +} diff --git a/seaweed-block/core/frontend/durable/attach_hydration_composed_test.go b/seaweed-block/core/frontend/durable/attach_hydration_composed_test.go new file mode 100644 index 0000000000..7f56987580 --- /dev/null +++ b/seaweed-block/core/frontend/durable/attach_hydration_composed_test.go @@ -0,0 +1,161 @@ +package durable + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" + "sync" + "sync/atomic" + "testing" + "time" +) + +type cumulativeReadStorage struct { + storage.LogicalStorage + remaining time.Duration +} + +func (s *cumulativeReadStorage) Read(uint32) ([]byte, error) { + time.Sleep(2750 * time.Millisecond) + return make([]byte, 4096), nil +} +func (s *cumulativeReadStorage) ReadContext(ctx context.Context, _ uint32) ([]byte, error) { + deadline, _ := ctx.Deadline() + s.remaining = time.Until(deadline) + timer := time.NewTimer(2750 * time.Millisecond) + defer timer.Stop() + select { + case <-timer.C: + return make([]byte, 4096), nil + case <-ctx.Done(): + return nil, errors.Join(storage.ErrChunkHydrationPending, ctx.Err()) + } +} +func TestAttachAndHydrationUseOneArrivalDeadline(t *testing.T) { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + store := &cumulativeReadStorage{} + b := &StorageBackend{storage: store, blockSize: 4096, id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}} + b.setChunkAttachPending("pending") + var once sync.Once + var timer *time.Timer + fired := make(chan struct{}) + b.testBeforeReadReadyWait = func() { + once.Do(func() { + timer = time.AfterFunc(2500*time.Millisecond, func() { defer close(fired); b.SetOperational(true, "attached") }) + }) + } + defer func() { + if timer != nil && !timer.Stop() { + <-fired + } + }() + start := time.Now() + n, err := b.Read(context.Background(), 0, make([]byte, 4096)) + elapsed := time.Since(start) + if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) || elapsed >= 5*time.Second || store.remaining > 2*time.Second { + t.Fatalf("n=%d err=%v elapsed=%s hydration remaining=%s", n, err, elapsed, store.remaining) + } + t.Logf("combined attach+hydration: %s; remaining at hydration: %s", elapsed, store.remaining) +} + +// Both the command context and the capped attach context use this same +// absolute deadline. Hold the registered wait until it has expired so +// notification selection cannot accidentally make the oracle pass. +type combinedReadProbe struct { + storage.LogicalStorage + calls atomic.Int32 +} + +func (s *combinedReadProbe) Read(uint32) ([]byte, error) { + s.calls.Add(1) + return make([]byte, 4096), nil +} +func (s *combinedReadProbe) ReadContext(context.Context, uint32) ([]byte, error) { + s.calls.Add(1) + return make([]byte, 4096), nil +} +func TestCombinedRead_TiedAttachAndCommandDeadline(t *testing.T) { + for _, state := range []string{"pending", "published", "fenced"} { + t.Run(state, func(t *testing.T) { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + probe := &combinedReadProbe{} + b := &StorageBackend{storage: probe, blockSize: 4096, id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}} + b.setChunkAttachPending("pending") + // Queue residence consumes three seconds of the original four-second + // allowance. The attach child's three-second limit is capped by it. + ctx, cancel := frontend.WithReadBudget(context.Background(), time.Now().Add(-3*time.Second)) + defer cancel() + registered, resume, joined := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once, releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(resume) }) } + b.testBeforeReadReadyWait = func() { once.Do(func() { close(registered) }); <-resume } + result := make(chan error, 1) + t.Cleanup(func() { + cancel() + release() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("combined read did not settle") + } + }) + start := time.Now() + go func() { + defer close(joined) + n, err := b.Read(ctx, 0, make([]byte, 4096)) + if n != 0 { + t.Errorf("expired read returned %d bytes", n) + } + result <- err + }() + select { + case <-registered: + case <-ctx.Done(): + t.Fatal("attach waiter not registered before deadline") + } + <-ctx.Done() + switch state { + case "published": + b.SetOperational(true, "attached at expiry") + case "fenced": + b.mu.Lock() + b.chunkFenced = func() bool { return true } + b.mu.Unlock() + b.SetOperational(false, "fenced at expiry") + } + release() + select { + case err := <-result: + if state == "fenced" { + if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("deadline hid fence: %v", err) + } + } else if !errors.Is(err, frontend.ErrNotReady) || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) || errors.Is(err, storage.ErrChunkHydrationPending) { + t.Fatalf("attach classification must win before hydration: %v", err) + } + case <-time.After(time.Second): + t.Fatal("expired combined read did not return") + } + if probe.calls.Load() != 0 { + t.Fatal("expired command entered storage") + } + if time.Since(start) >= 5*time.Second { + t.Fatal("cooperative combined deadline exceeded command budget") + } + }) + } +} +func TestCombinedRead_ExpiryAfterAdmissionKeepsAttachClassification(t *testing.T) { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + probe := &combinedReadProbe{} + b := &StorageBackend{storage: probe, blockSize: 4096, id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}} + b.SetOperational(true, "attached") + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + b.testBeforeIOLock = func() { <-ctx.Done() } + n, err := b.Read(ctx, 0, make([]byte, 4096)) + if n != 0 || probe.calls.Load() != 0 || !errors.Is(err, frontend.ErrNotReady) || !errors.Is(err, frontend.ErrBackendBusy) || errors.Is(err, storage.ErrChunkHydrationPending) { + t.Fatalf("post-admission expiry: n=%d calls=%d err=%v", n, probe.calls.Load(), err) + } +} diff --git a/seaweed-block/core/frontend/durable/checkpoint_status_test.go b/seaweed-block/core/frontend/durable/checkpoint_status_test.go new file mode 100644 index 0000000000..e3eed2d4f2 --- /dev/null +++ b/seaweed-block/core/frontend/durable/checkpoint_status_test.go @@ -0,0 +1,70 @@ +package durable_test + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestDurableProvider_CheckpointPersistenceStatus(t *testing.T) { + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: 64, ChunkBlocks: 4, ChunkCaptureInterval: 0, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + be, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := be.Write(context.Background(), 0, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + if err := be.Sync(context.Background()); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for { + statuses := p.DurableStatuses() + raw, err := json.Marshal(statuses) + if err != nil { + t.Fatal(err) + } + var wire []struct { + CheckpointPersistence *struct { + Successes uint64 + Refusals uint64 + Failures uint64 + CheckpointLSN uint64 + Advances uint64 + LastAdvance time.Time + } + } + if err := json.Unmarshal(raw, &wire); err != nil { + t.Fatal(err) + } + if len(wire) == 1 && wire[0].CheckpointPersistence != nil && wire[0].CheckpointPersistence.Successes > 0 && + wire[0].CheckpointPersistence.CheckpointLSN > 0 && wire[0].CheckpointPersistence.Advances > 0 && + !wire[0].CheckpointPersistence.LastAdvance.IsZero() { + return + } + if time.Now().After(deadline) { + t.Fatalf("no checkpoint persist status in durable response: %s", raw) + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/seaweed-block/core/frontend/durable/export_chunk_test.go b/seaweed-block/core/frontend/durable/export_chunk_test.go index 83300439e8..7c74e579b7 100644 --- a/seaweed-block/core/frontend/durable/export_chunk_test.go +++ b/seaweed-block/core/frontend/durable/export_chunk_test.go @@ -1,5 +1,31 @@ package durable +import ( + "context" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + // SetTestAfterChunkResolve installs the test-only hook CutVolume runs right // after it resolves the volume's handle and layer. func SetTestAfterChunkResolve(p *DurableProvider, f func()) { p.testAfterChunkResolve = f } + +// SetTestDetachStopIO replaces DetachVolume's StopIO call (test-only). +func SetTestDetachStopIO(p *DurableProvider, f func(ctx context.Context) error) { + p.testDetachStopIO = f +} + +// SetTestDetachTrace observes DetachVolume's stages and deadlines (test-only). +func SetTestDetachTrace(p *DurableProvider, f func(stage string, deadline time.Time)) { + p.testDetachTrace = f +} + +// SetTestBeforeIOLock runs f in the backend's admission, right before the I/O +// lock (test-only). +func SetTestBeforeIOLock(b frontend.Backend, f func()) { b.(*StorageBackend).testBeforeIOLock = f } + +// SetTestBeforeAttachWait observes the first registered readiness wait. +func SetTestBeforeAttachWait(b frontend.Backend, f func()) { + b.(*StorageBackend).testBeforeReadReadyWait = f +} diff --git a/seaweed-block/core/frontend/durable/hydration_budget_test.go b/seaweed-block/core/frontend/durable/hydration_budget_test.go new file mode 100644 index 0000000000..f19d4f49c6 --- /dev/null +++ b/seaweed-block/core/frontend/durable/hydration_budget_test.go @@ -0,0 +1,426 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestDurableHydration_ConfiguredLimitsReachStatus(t *testing.T) { + for _, configured := range []bool{false, true} { + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks} + r := storage.NewMemChunkRemote() + cfg.ChunkRemoteFor = func(string) (storage.ChunkRemote, error) { return r, nil } + wantWorkers, wantDepth := 2, 64 + if configured { + cfg.ChunkHydrationWorkers, cfg.ChunkHydrationQueueDepth = 3, 17 + wantWorkers, wantDepth = 3, 17 + } + p, err := durable.NewDurableProvider(cfg, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + openRecovered(t, p) + st := p.DurableStatuses() + if len(st) != 1 || st[0].Chunk == nil { + t.Fatalf("missing chunk status: %+v", st) + } + h := st[0].Chunk.Stats.Hydration + if h.WorkerLimit != wantWorkers || h.QueueDepth != wantDepth { + t.Fatalf("configured=%t hydration=%+v", configured, h) + } + } +} + +type faultyHydrationRemote struct { + storage.ChunkRemote + fault error + corrupt bool +} + +func (r *faultyHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) { + if r.fault != nil { + return nil, r.fault + } + b, err := r.ChunkRemote.Get(ctx, key) + if err == nil && r.corrupt && len(b) > 0 { + b = append([]byte(nil), b...) + b[0] ^= 0xff + } + return b, err +} + +func TestDurableHydration_NVMePreservesPhysicalAndHashErrors(t *testing.T) { + for _, corrupt := range []bool{false, true} { + t.Run(map[bool]string{false: "joined physical", true: "hash"}[corrupt], func(t *testing.T) { + r := &faultyHydrationRemote{ChunkRemote: seededRemote(t), corrupt: corrupt} + if !corrupt { + r.fault = errors.Join(context.DeadlineExceeded, errors.New("physical remote read failure")) + } + p := chunkProvider(t, t.TempDir(), r, v1View(), 0) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: b, BlockSize: 4096, VolumeSize: pcBlocks * 4096}) + res := h.Handle(context.Background(), nvme.IOCommand{Opcode: 2, NSID: 1, SLBA: 33, NLB: 1}) + if res.SC != nvme.SCInternalError || len(res.Data) != 0 { + t.Fatalf("terminal hydration failure: %+v", res) + } + }) + } +} + +type pacedHydrationRemote struct { + storage.ChunkRemote + gets atomic.Int64 + second chan struct{} + once sync.Once +} + +func (r *pacedHydrationRemote) release() { r.once.Do(func() { close(r.second) }) } +func (r *pacedHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) { + if r.gets.Add(1) == 1 { + timer := time.NewTimer(120 * time.Millisecond) + defer timer.Stop() + select { + case <-timer.C: + case <-ctx.Done(): + return nil, ctx.Err() + } + } else { + select { + case <-r.second: + case <-ctx.Done(): + return nil, ctx.Err() + } + } + return r.ChunkRemote.Get(ctx, key) +} + +func TestDurableHydration_MultipleChunksShareOneDeadline(t *testing.T) { + r := &pacedHydrationRemote{ChunkRemote: seededRemote(t), second: make(chan struct{})} + p := chunkProvider(t, t.TempDir(), r, v1View(), 0) + t.Cleanup(r.release) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 220*time.Millisecond) + defer cancel() + start := time.Now() + buf := make([]byte, (101-33)*4096) + n, err := b.Read(ctx, 33*4096, buf) + if !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) || n != (96-33)*4096 { + t.Fatalf("shared deadline n=%d err=%v gets=%d", n, err, r.gets.Load()) + } + if elapsed := time.Since(start); elapsed >= 450*time.Millisecond { + t.Fatalf("read budget renewed: %s", elapsed) + } + if !bytes.Equal(buf[:4096], block(0x33)) { + t.Fatal("first chunk prefix changed") + } + r.release() + ctx2, cancel2 := context.WithTimeout(context.Background(), time.Second) + defer cancel2() + last := make([]byte, 4096) + if n, err := b.Read(ctx2, 100*4096, last); n != 4096 || err != nil || !bytes.Equal(last, block(0x64)) { + t.Fatalf("shared work after timeout: n=%d err=%v", n, err) + } + if r.gets.Load() != 2 { + t.Fatalf("retry restarted shared fetch: %d", r.gets.Load()) + } +} + +type heldHydrationRemote struct { + storage.ChunkRemote + gate chan struct{} + once sync.Once + gets atomic.Int64 + entered chan struct{} +} + +func (r *heldHydrationRemote) release() { r.once.Do(func() { close(r.gate) }) } +func (r *heldHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) { + r.gets.Add(1) + if r.entered != nil { + select { + case r.entered <- struct{}{}: + default: + } + } + select { + case <-r.gate: + return r.ChunkRemote.Get(ctx, key) + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func TestDurableHydration_HostRetriesJoinOwnedFetch(t *testing.T) { + r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)} + p := chunkProvider(t, t.TempDir(), r, v1View(), 0) + t.Cleanup(r.release) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: b, BlockSize: 4096, VolumeSize: pcBlocks * 4096}) + // Start the hold only after the first actual Get. No setup time counts + // toward the delay that the host's retry sequence must bridge. + joined := make(chan struct{}) + stop := make(chan struct{}) + t.Cleanup(func() { close(stop); r.release(); <-joined }) + go func() { + defer close(joined) + select { + case <-r.entered: + case <-stop: + return + } + timer := time.NewTimer(120 * time.Millisecond) + defer timer.Stop() + select { + case <-timer.C: + r.release() + case <-stop: + } + }() + busy := 0 + for attempt := 0; attempt < 6; attempt++ { + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + res := h.Handle(ctx, nvme.IOCommand{Opcode: 2, NSID: 1, SLBA: 33, NLB: 1}) + cancel() + if res.SC == nvme.SCSuccess { + if busy == 0 || !bytes.Equal(res.Data, block(0x33)) || r.gets.Load() != 1 { + t.Fatalf("busy=%d Gets=%d bytes=%d", busy, r.gets.Load(), len(res.Data)) + } + return + } + if res.SC != nvme.SCNamespaceNotReady || len(res.Data) != 0 { + t.Fatalf("attempt %d: %+v", attempt, res) + } + busy++ + } + t.Fatal("six immediate host attempts exhausted despite surviving shared fill") +} + +func TestDurableHydration_FenceWinsCallerExpiry(t *testing.T) { + r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)} + view := v1View() + p := chunkProvider(t, t.TempDir(), r, view, 0) + t.Cleanup(r.release) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + joined := make(chan struct{}) + result := make(chan error, 1) + t.Cleanup(func() { + cancel() + r.release() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("fenced hydration waiter not joined") + } + }) + go func() { + defer close(joined) + _, err := b.Read(ctx, 33*4096, make([]byte, 4096)) + result <- err + }() + select { + case <-r.entered: + case <-time.After(time.Second): + t.Fatal("cold read never reached Get") + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 1})) + cancel() + select { + case err := <-result: + if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("expiry hid fencing: %v", err) + } + case <-time.After(time.Second): + t.Fatal("fenced waiter did not detach") + } +} + +func TestDurableHydration_ReadAndRMWPreserveCallerBudget(t *testing.T) { + for _, rmw := range []bool{false, true} { + name := "read" + if rmw { + name = "rmw" + } + t.Run(name, func(t *testing.T) { + r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{})} + p := chunkProvider(t, t.TempDir(), r, v1View(), 0) + t.Cleanup(r.release) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + before := s.NextLSN() + fired := make(chan struct{}) + timer := time.AfterFunc(500*time.Millisecond, func() { defer close(fired); r.release() }) + t.Cleanup(func() { + r.release() + if !timer.Stop() { + <-fired + } + }) + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + start := time.Now() + var n int + if rmw { + n, err = b.Write(ctx, 33*4096+1, []byte{0x74}) + } else { + n, err = b.Read(ctx, 33*4096, make([]byte, 4096)) + } + if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("request deadline: n=%d err=%v elapsed=%s", n, err, time.Since(start)) + } + if time.Since(start) >= 350*time.Millisecond { + t.Fatal("read/RMW did not share caller budget") + } + if s.NextLSN() != before { + t.Fatal("refused RMW appended data") + } + }) + } +} + +func TestDurableHydration_RMWFenceWinsCallerExpiry(t *testing.T) { + r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)} + view := v1View() + p := chunkProvider(t, t.TempDir(), r, view, 0) + t.Cleanup(r.release) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + store, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + before := store.NextLSN() + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + joined := make(chan struct{}) + result := make(chan error, 1) + t.Cleanup(func() { + cancel() + r.release() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("fenced hydration waiter not joined") + } + }) + go func() { + defer close(joined) + n, err := b.Write(ctx, 33*4096+1, []byte{0x74}) + if n != 0 { + t.Errorf("unexpected RMW prefix %d: %v", n, err) + } + result <- err + }() + select { + case <-r.entered: + case <-time.After(time.Second): + t.Fatal("cold read never reached Get") + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 1})) + select { + case err := <-result: + if store.NextLSN() != before { + t.Fatal("fenced RMW appended data") + } + if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("expiry hid fencing: %v", err) + } + case <-time.After(time.Second): + t.Fatal("fenced waiter did not detach") + } +} + +func TestDurableHydration_RMWFenceKeepsCommittedPrefix(t *testing.T) { + r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)} + view := v1View() + p := chunkProvider(t, t.TempDir(), r, view, 0) + t.Cleanup(r.release) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + store, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + before := store.NextLSN() + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + joined := make(chan struct{}) + result := make(chan error, 1) + t.Cleanup(func() { + cancel() + r.release() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("fenced hydration waiter not joined") + } + }) + go func() { + defer close(joined) + n, err := b.Write(ctx, 32*4096, bytes.Repeat([]byte{0x74}, 4097)) + if n != 4096 { + t.Errorf("unexpected RMW prefix %d: %v", n, err) + } + result <- err + }() + select { + case <-r.entered: + case <-time.After(time.Second): + t.Fatal("cold read never reached Get") + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 1})) + select { + case err := <-result: + if store.NextLSN() != before+1 { + t.Fatal("fenced RMW lost its exact committed prefix") + } + if !errors.Is(err, frontend.ErrStalePrimary) || errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("expiry hid fencing: %v", err) + } + case <-time.After(time.Second): + t.Fatal("fenced waiter did not detach") + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index eedba71cc7..6174905117 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -38,6 +38,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/storage" "github.com/seaweedfs/seaweed-block/core/storage/parallelwal" "github.com/seaweedfs/seaweed-block/core/storage/smartwal" @@ -81,6 +82,14 @@ var ErrImplKindMismatch = errors.New("durable: impl kind mismatch between select // volumeID has not been Open'd. var ErrVolumeNotOpen = errors.New("durable: volume not opened") +// ErrDetachAborted: the detach did not happen (its final cut provably did not +// publish), so the volume resumed serving on this host (MIGRATION E4). +var ErrDetachAborted = errors.New("durable: detach aborted; the volume keeps serving on this host") + +// ErrDetachOutcomeUnknown: whether the detach landed cannot be decided yet; +// I/O stays stopped (never resumed on a possibly detached HEAD). +var ErrDetachOutcomeUnknown = errors.New("durable: detach outcome unknown; I/O stays stopped") + // ProviderConfig configures a DurableProvider. type ProviderConfig struct { // Impl selects which LogicalStorage implementation to open or @@ -153,14 +162,26 @@ type ProviderConfig struct { // ChunkReadMissTimeout bounds one remote fetch of an absent block. // Zero: the storage default. ChunkReadMissTimeout time.Duration + // Per-volume hydration bounds; zero selects 2 workers and 64 distinct chunks. + ChunkHydrationWorkers int + ChunkHydrationQueueDepth int // ChunkCaptureInterval: an automatic cut is due once this long has // passed since the volume's last successful cut (of any kind). Zero // disables the timer. ChunkCaptureInterval time.Duration - // ChunkDirtyThreshold is the bound on one cut's barrier copy, in - // chunks. It never triggers a cut: the remote holds snapshots, and - // cuts are published only by CaptureVolume, MakeVolumeRemoteDurable - // (snapshot, detach) and the timer. Zero: unbounded. + // DetachFreezeTimeout bounds how long a failing DetachVolume keeps guest + // I/O stopped before it resumes or settles: the drain and final cut get + // three quarters of it, the settlement of a failed cut the rest (the + // caller's context can only shorten the cut part). Zero: 20 s, below the + // host's 30 s I/O timeout; a freeze past the 5 s target is logged as an + // alarm. Cooperative: a syscall that never returns is not bounded. + DetachFreezeTimeout time.Duration + // ChunkDirtyThreshold is the number of candidate chunks above which + // a cut pre-copies (stages) chunks before its barrier, in rounds of + // this size; copy-before-write copies the rest outside the barrier. + // It never triggers a cut: the remote holds snapshots, and cuts are + // published only by CaptureVolume, MakeVolumeRemoteDurable + // (snapshot, detach) and the timer. Zero: no pre-copy. ChunkDirtyThreshold int // ChunkUploadConcurrency bounds remote uploads; zero defaults to 8. ChunkUploadConcurrency int @@ -179,6 +200,18 @@ type DurableProvider struct { // testAfterChunkResolve, test-only, runs in CutVolume right after the // volume's handle and layer are resolved. testAfterChunkResolve func() + // testDetachStopIO, test-only, replaces DetachVolume's StopIO call (so a + // test can force the failed-drain branch); testDetachTrace, test-only, + // observes the detach's stages and their deadlines ("cut", "settle"). + testDetachStopIO func(ctx context.Context) error + testDetachTrace func(stage string, deadline time.Time) + + // testBeforeChunkFreshRetire holds the real post-presence/pre-marker boundary. + testBeforeChunkFreshRetire func() error + + // testWALStoreFactory selects a dark store only in provider caller controls. + // No production option, flag or environment variable installs it. + testWALStoreFactory func(path string, create bool) (*storage.WALStore, error) // walstore-chunk: closeCtx ends with Close and cancels in-flight // remote attachment; inflight counts RecoverVolume calls admitted @@ -209,6 +242,8 @@ type volHandle struct { recoverGen uint64 waitGen uint64 chunk storage.ChunkLayer // after RecoverVolume + // Private until the owner commit succeeds; retained for attach retry. + chunkPending storage.ChunkLayer // chunkDetach is set (under attachMu) when DetachVolume starts and // never cleared in this process: frontend I/O stays stopped, through // any later RecoverVolume, until a new lifetime attaches the volume. @@ -221,21 +256,22 @@ type volHandle struct { // handle. It intentionally exposes lineage and readiness facts without giving // callers a control surface. type VolumeStatus struct { - VolumeID string - Path string - Impl string - ReplicaID string - Epoch uint64 - EndpointVersion uint64 - Latched bool - Operational bool - FrontierKnown bool - DurableLSN uint64 - RetainedLSN uint64 - HeadLSN uint64 - Evidence string - Closed bool - WriteProfile WriteProfileStatus + VolumeID string + Path string + Impl string + ReplicaID string + Epoch uint64 + EndpointVersion uint64 + Latched bool + Operational bool + FrontierKnown bool + DurableLSN uint64 + RetainedLSN uint64 + HeadLSN uint64 + Evidence string + Closed bool + WriteProfile WriteProfileStatus + CheckpointPersistence *storage.CheckpointPersistenceStatus `json:",omitempty"` // Chunk is the chunk layer's state and cut counters; walstore-chunk // volumes only. Chunk *ChunkStatus @@ -587,6 +623,13 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) { } return h, nil } + // Existing storage ignores create geometry; admission precedes all fresh sidecars. + if p.cfg.NumBlocks == 0 { + return nil, fmt.Errorf("durable: NumBlocks=0; cannot create storage for %s (use open-existing mode)", volumeID) + } + if err := geometry.ValidateBlockGeometry(uint64(p.cfg.NumBlocks), uint64(p.cfg.BlockSize)); err != nil { + return nil, err + } if p.cfg.Impl == ImplWALStoreChunk { // Durable before the volume file exists: a crash anywhere between // here and the first successful attach leaves a fresh volume. @@ -627,6 +670,8 @@ func (p *DurableProvider) verifyImplOnDisk(path string) (ImplName, error) { // the format's real header selector instead of rejecting on byte 0. if err := parallelwal.ProbeStore(path); err == nil { diskImpl, ok = ImplParallelWALStore, true + } else if err := storage.ProbeWALStoreV3(path); err == nil { + diskImpl, ok = ImplWALStore, true } } if !ok { @@ -668,13 +713,23 @@ func (p *DurableProvider) openExisting(volumeID, path string, impl ImplName) (*v var s storage.LogicalStorage switch impl { case ImplWALStore, ImplWALStoreChunk: - ws, err := storage.OpenWALStore(path) + var ws *storage.WALStore + var err error + if p.testWALStoreFactory != nil { + ws, err = p.testWALStoreFactory(path, false) + } else { + ws, err = storage.OpenWALStore(path) + } if err != nil { return nil, fmt.Errorf("durable: OpenWALStore %s: %w", path, err) } // G6 §1.A α: plumb operator-tunable retention into walstore. // Zero (pre-G6 default) preserves strict checkpoint-driven // recycle. + // Defer before Recover can publish a completed BASE away. + if impl == ImplWALStoreChunk && p.cfg.ChunkRemoteFor != nil { + ws.DeferBaseRetirementV3() + } if p.cfg.WALRetentionLSNs > 0 { ws.SetRecoveryRetentionLSNs(p.cfg.WALRetentionLSNs) } @@ -714,11 +769,21 @@ func (p *DurableProvider) createFresh(volumeID, path string, impl ImplName) (*vo var s storage.LogicalStorage switch impl { case ImplWALStore, ImplWALStoreChunk: - ws, err := storage.CreateWALStore(path, p.cfg.NumBlocks, p.cfg.BlockSize) + var ws *storage.WALStore + var err error + if p.testWALStoreFactory != nil { + ws, err = p.testWALStoreFactory(path, true) + } else { + ws, err = storage.CreateWALStoreWithOptions(path, p.cfg.NumBlocks, p.cfg.BlockSize, storage.WALStoreOptions{ChunkBlocks: p.cfg.ChunkBlocks}) + } if err != nil { return nil, fmt.Errorf("durable: CreateWALStore %s: %w", path, err) } // G6 §1.A α (see openExisting comment for semantics). + // Defer before Recover can publish a completed BASE away. + if impl == ImplWALStoreChunk && p.cfg.ChunkRemoteFor != nil { + ws.DeferBaseRetirementV3() + } if p.cfg.WALRetentionLSNs > 0 { ws.SetRecoveryRetentionLSNs(p.cfg.WALRetentionLSNs) } @@ -816,7 +881,7 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R // Recovered; I/O stays refused until the layer attaches under // the master's assignment (the authority wait flips it). report.Evidence += "; chunk layer awaiting master authority" - h.backend.SetOperational(false, report.Evidence) + h.backend.setChunkAttachPending(report.Evidence) return report, nil } if err := chunkFenced(volumeID, h); err != nil { @@ -889,6 +954,11 @@ func chunkSidecars(path string) ([]string, error) { } var out []string for _, e := range entries { + // The owned v3 LSN map belongs to plain walstore as well. Remote + // chunk identity still has its own presence/fresh/HEAD sidecars. + if e.Name() == base+".chunkmap" { + continue + } if !e.IsDir() && strings.HasPrefix(e.Name(), base+".chunk") { out = append(out, e.Name()) } diff --git a/seaweed-block/core/frontend/durable/provider_auto_impl_test.go b/seaweed-block/core/frontend/durable/provider_auto_impl_test.go index 229997d61f..0d60aa8a75 100644 --- a/seaweed-block/core/frontend/durable/provider_auto_impl_test.go +++ b/seaweed-block/core/frontend/durable/provider_auto_impl_test.go @@ -1,6 +1,7 @@ package durable_test import ( + "bytes" "context" "errors" "io" @@ -75,6 +76,41 @@ func TestDurableProvider_AutoCreatesWALStore(t *testing.T) { } } +func TestDurableProvider_AutoOpensV3FallbackSlot(t *testing.T) { + root := t.TempDir() + p := autoProvider(t, root, durable.ImplWALStore) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err := s.Write(3, bytes.Repeat([]byte{0x73}, 4096)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + path := filepath.Join(root, "v1.bin") + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + _, err = f.WriteAt([]byte{0xff}, 0) + ce := f.Close() + if err != nil || ce != nil { + t.Fatal(err, ce) + } + auto := autoProvider(t, root, durable.ImplAuto) + if _, err := auto.EnsureStorage("v1"); err != nil { + t.Fatalf("valid v3 fallback must pass the auto probe: %v", err) + } + if _, err := auto.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } +} + func TestDurableProvider_AutoOpensExistingVolumeByOnDiskFormat(t *testing.T) { for _, impl := range []durable.ImplName{durable.ImplSmartWAL, durable.ImplWALStore, durable.ImplParallelWALStore} { t.Run(string(impl), func(t *testing.T) { diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 3d0f8f45fd..4af44da113 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -10,6 +10,7 @@ import ( "os" "path/filepath" "runtime" + "strings" "sync" "time" @@ -84,6 +85,25 @@ func chunkAuthority(proj frontend.Projection, volumeID string) bool { return proj.VolumeID == volumeID && proj.Healthy && proj.Epoch > 0 && proj.ReplicaID != "" } +// chunkAuthorityGap names the projection fields that fail chunkAuthority, +// for the logs ("" when none fails). +func chunkAuthorityGap(proj frontend.Projection, volumeID string) string { + var gap []string + if proj.VolumeID != volumeID { + gap = append(gap, fmt.Sprintf("volume=%q", proj.VolumeID)) + } + if !proj.Healthy { + gap = append(gap, "healthy=false") + } + if proj.Epoch == 0 { + gap = append(gap, "epoch=0") + } + if proj.ReplicaID == "" { + gap = append(gap, `replica=""`) + } + return strings.Join(gap, " ") +} + // recoverChunk runs after a successful local Recover, generation gen. It // attaches the layer when the projection already carries master authority // and reports true. Otherwise it starts an authority wait bound to gen @@ -126,6 +146,13 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen if limit <= 0 { limit = 30 * time.Second } + start := time.Now() + log.Printf("durable: chunk layer for volume=%s waits for master authority (up to %s): projection lacks %s", + volumeID, limit, chunkAuthorityGap(p.view.Projection(), volumeID)) + ended := "superseded by a later recovery" + defer func() { + log.Printf("durable: chunk authority wait for volume=%s ended after %s: %s", volumeID, time.Since(start), ended) + }() waitCtx, endWait := context.WithTimeout(p.closeCtx, limit) defer endWait() defer func() { @@ -136,6 +163,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen h.attachMu.Lock() defer h.attachMu.Unlock() if p.current(h, gen) && h.chunk == nil { + ended = fmt.Sprintf("assignment unavailable, not serving (projection lacks %s)", chunkAuthorityGap(p.view.Projection(), volumeID)) h.backend.SetOperational(false, "chunk assignment unavailable: "+waitCtx.Err().Error()) } }() @@ -148,18 +176,28 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen }() t := time.NewTicker(chunkAuthorityPoll) defer t.Stop() + attempts := 0 for { select { case <-waitCtx.Done(): + ended = "provider closed" + if errors.Is(waitCtx.Err(), context.DeadlineExceeded) { + ended = "deadline" + } return case <-t.C: } if !p.current(h, gen) { return // a later recovery (successful or failed) owns the volume } - if !chunkAuthority(p.view.Projection(), volumeID) { + proj := p.view.Projection() + if !chunkAuthority(proj, volumeID) { continue } + if attempts++; attempts == 1 { + log.Printf("durable: chunk layer for volume=%s: master authority after %s (replica=%q epoch=%d endpoint=%d); first attach attempt", + volumeID, time.Since(start), proj.ReplicaID, proj.Epoch, proj.EndpointVersion) + } h.attachMu.Lock() if !p.current(h, gen) { // re-checked under the per-volume serialization h.attachMu.Unlock() @@ -176,9 +214,14 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen } h.attachMu.Unlock() switch { - case err == nil, errors.Is(err, errProviderClosed): + case err == nil: + ended = fmt.Sprintf("attached after %d attempt(s)", attempts) + return + case errors.Is(err, errProviderClosed): + ended = "provider closed" return case errors.Is(err, storage.ErrChunkLayerFenced): + ended = "fenced, not serving" log.Printf("durable: chunk layer for volume=%s: %v (not serving)", volumeID, err) if errors.Is(err, ErrChunkStaleLocalRoot) { h.attachMu.Lock() @@ -189,11 +232,17 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen } return case errors.Is(err, errChunkNoAuthority): + log.Printf("durable: chunk layer attach for volume=%s: authority lost before attempt %d (projection lacks %s); waiting", + volumeID, attempts, chunkAuthorityGap(p.view.Projection(), volumeID)) continue } log.Printf("durable: chunk layer attach for volume=%s: %v (retrying)", volumeID, err) select { case <-waitCtx.Done(): + ended = "provider closed during the retry backoff" + if errors.Is(waitCtx.Err(), context.DeadlineExceeded) { + ended = "deadline during the retry backoff" + } return case <-time.After(chunkAttachRetry): } @@ -207,6 +256,9 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *volHandle) error { p.mu.Lock() layer := h.chunk + if layer == nil { + layer = h.chunkPending + } p.mu.Unlock() if layer == nil { var err error @@ -215,33 +267,66 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v } p.mu.Lock() if p.closed { - // Not published: the store still owns the layer and closes it - // in WALStore.Close, which Close runs after this call settles. + // The store owns this unpublished layer and closes it after + // the admitted attach settles. p.mu.Unlock() return errProviderClosed } + h.chunkPending = layer + p.mu.Unlock() + } + // The owner commit is serialized with a later BASE begin. The callback + // does marker I/O only: no store/layer reentry while installMu is held. + commit := func() error { + if h.fresh { + return removeChunkFreshMarker(h.path) + } + return nil + } + if h.fresh { + if hook := p.testBeforeChunkFreshRetire; hook != nil { + if err := hook(); err != nil { + return err + } + } + } + if ws, ok := h.storage.(*storage.WALStore); ok { + if err := ws.CommitChunkAttachV3(commit); err != nil { + return err + } + } else if err := commit(); err != nil { + return err + } + p.mu.Lock() + defer p.mu.Unlock() + if p.closed { + return errProviderClosed + } + h.fresh = false + if h.chunk == nil { + // No explicit operation can resolve the layer, and no scheduler + // can publish, until marker retirement is durably committed. h.chunk = layer + h.chunkPending = nil h.backend.mu.Lock() h.backend.chunkFenced = layer.Fenced h.backend.mu.Unlock() - if p.cfg.ChunkCaptureInterval > 0 { - ctx, cancel := context.WithCancel(context.Background()) - h.chunkStop, h.chunkDone = cancel, make(chan struct{}) - go p.chunkLoop(ctx, volumeID, layer, h.chunkDone) - } - p.mu.Unlock() - } - if h.fresh { - // The attach persisted the absence of every HEAD chunk; only now - // may a restart treat the local volume as authoritative. - if err := removeChunkFreshMarker(h.path); err != nil { - return err - } - h.fresh = false + p.startChunkLoop(volumeID, h, layer) } return nil } +// startChunkLoop starts the periodic cuts of an attached layer, if configured +// and not already running. The caller holds h.attachMu and p.mu. +func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer storage.ChunkLayer) { + if p.cfg.ChunkCaptureInterval <= 0 || h.chunkStop != nil { + return + } + loopCtx, cancel := context.WithCancel(context.Background()) + h.chunkStop, h.chunkDone = cancel, make(chan struct{}) + go p.chunkLoop(loopCtx, volumeID, layer, h.chunkDone) +} + func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) { ws, ok := h.storage.(*storage.WALStore) if !ok { @@ -279,14 +364,16 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h remote = &manifestBoundRemote{closeBoundRemote: bound, builder: builder} } cfg := storage.ChunkLayerConfig{ - ChunkBlocks: p.cfg.ChunkBlocks, - Epoch: lin.epoch, - Holder: holder, - FreshFromHead: h.fresh, - ReadMissTimeout: p.cfg.ChunkReadMissTimeout, - Bitmap: storage.NewFileChunkBitmapStore(h.path + ".chunkbitmap"), - BarrierBound: p.cfg.ChunkDirtyThreshold, - UploadConcurrency: p.cfg.ChunkUploadConcurrency, + ChunkBlocks: p.cfg.ChunkBlocks, + RestoreChunkBytes: uint64(ws.BlockSize()) * uint64(p.cfg.ChunkBlocks), + Epoch: lin.epoch, + Holder: holder, + FreshFromHead: h.fresh, + ReadMissTimeout: p.cfg.ChunkReadMissTimeout, + HydrationWorkers: p.cfg.ChunkHydrationWorkers, + HydrationQueueDepth: p.cfg.ChunkHydrationQueueDepth, + BarrierBound: p.cfg.ChunkDirtyThreshold, + UploadConcurrency: p.cfg.ChunkUploadConcurrency, CaptureAllowed: func() error { cur := p.view.Projection() if !cur.Healthy || cur.VolumeID != volumeID || lin.volumeID != volumeID { @@ -320,6 +407,17 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h // Attach preparation is gated. Seed the exact observed HEAD before // its takeover CAS; only then finalize lazy attachment and expose I/O. cfg.PrepareRestore = func(head storage.ChunkHead) error { + log.Printf("durable: HEAD claim for volume=%s observed HEAD gen=%d epoch=%d holder=%q state=%v remote_lsn=%d; preparing", + volumeID, head.Gen, head.Epoch, head.Holder, head.State, head.RemoteLSN) + if baseLSN, complete := ws.InstalledBaseLSN(); complete { + // The fresh marker can outlive a full local BASE. It is not + // permission to seed backwards or to fill from an older HEAD. + if head.RemoteLSN > baseLSN { + return fmt.Errorf("durable: completed BASE frontier %d is behind HEAD %d", baseLSN, head.RemoteLSN) + } + cfg.FreshFromHead = false + return nil + } // No HEAD is a new lineage; preserve any pre-assignment local // writes instead of replacing their frontier with zero. if head.Gen == 0 { @@ -339,10 +437,18 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h // restore here, so HEAD is never claimed for a mis-ordered ship. return h.backend.seedAndRebase(func() error { return ws.SeedChunkFrontier(head.RemoteLSN) }) } + claimStart := time.Now() + log.Printf("durable: HEAD claim for volume=%s starting: target epoch=%d holder=%q", volumeID, cfg.Epoch, cfg.Holder) head, err := storage.ClaimChunkHead(ctx, remote, cfg) if err != nil { + log.Printf("durable: HEAD claim for volume=%s failed after %s: %v", volumeID, time.Since(claimStart), err) return nil, fmt.Errorf("durable: restore HEAD claim: %w", err) } + claimed := "claimed" + if head.Gen == 0 { + claimed = "no HEAD to claim (new lineage)" + } + log.Printf("durable: HEAD claim for volume=%s done in %s: gen=%d epoch=%d holder=%q, %s", volumeID, time.Since(claimStart), head.Gen, head.Epoch, head.Holder, claimed) cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch} } @@ -706,12 +812,19 @@ func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN } // DetachVolume is a clean stop's final cut (B9 W2 §3.6): it stops the -// volume's frontend I/O and waits (bounded by ctx) for the I/O already -// admitted to finish, stops the periodic cuts, then publishes one cut with -// HEAD state detached. It also returns the last LSN written. From its -// start, the volume stays stopped for this process, through any later -// RecoverVolume, even when the detach fails; a retry settles it and a -// repeated call returns the first result. +// volume's frontend I/O and waits for the I/O already admitted to finish, +// stops the periodic cuts, then publishes one cut with HEAD state detached. +// It also returns the last LSN written. The freeze (drain + final cut) is +// bounded by DetachFreezeTimeout and ctx. After a successful detach the +// volume stays stopped for this process, through any later RecoverVolume, +// and a repeated call returns the first result. A failed detach never leaves +// the guest frozen by a detach that did not happen (MIGRATION E4): +// - nothing published (the drain or the cut failed before its CAS, or the +// CAS was refused, or an unresolved detach CAS was cancelled): serving +// resumes and ErrDetachAborted is returned; +// - the detach CAS applied (its reply was lost): the detached result; +// - HEAD belongs to another holder: stays stopped (fenced); +// - undecidable (HEAD unreadable): stays stopped, ErrDetachOutcomeUnknown. func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) { p.mu.Lock() h, ok := p.volumes[volumeID] @@ -725,16 +838,83 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st if err != nil { return storage.ChunkCutResult{}, 0, err } + freeze := p.cfg.DetachFreezeTimeout + if freeze <= 0 { + freeze = defaultDetachFreezeTimeout + } + // One freeze budget covers the drain, the final cut AND the settlement: + // the cut gets three quarters, the settlement what is left. The bound is + // cooperative (contexts): a syscall that never returns is not bounded here. + start := time.Now() + cutCtx, cancel := context.WithDeadline(ctx, start.Add(freeze*3/4)) + defer cancel() + defer func() { + if d := time.Since(start); d > detachFreezeTarget { + log.Printf("durable: ALARM detach of volume=%s held guest I/O for %s (target %s, bound %s)", volumeID, d.Round(time.Millisecond), detachFreezeTarget, freeze) + } + }() + if trace := p.testDetachTrace; trace != nil { + dl, _ := cutCtx.Deadline() + trace("cut", dl) + } h.chunkDetach = true - if err := h.backend.StopIO(ctx, "chunk detach: I/O stopped until a new attach"); err != nil { - return storage.ChunkCutResult{}, 0, err + if stop := p.testDetachStopIO; stop != nil { + err = stop(cutCtx) + } else { + err = h.backend.StopIO(cutCtx, "chunk detach: I/O stopped until a new attach") } - p.stopChunkLoop(h) - r, err := layer.Detach(ctx) - if err != nil { - return storage.ChunkCutResult{}, 0, err + if err == nil { + p.stopChunkLoop(h) + var r storage.ChunkCutResult + if r, err = layer.Detach(cutCtx); err == nil { + return r, h.storage.NextLSN() - 1, nil + } } - return r, h.storage.NextLSN() - 1, nil + // Every failure, a failed drain included, is settled before anything + // resumes: an earlier detach that applied, an unresolved detach CAS or a + // fenced layer must never resume serving. The settlement keeps the rest + // of the freeze budget even when the caller's context is gone. + sctx, scancel := context.WithDeadline(context.WithoutCancel(ctx), start.Add(freeze)) + defer scancel() + if trace := p.testDetachTrace; trace != nil { + dl, _ := sctx.Deadline() + trace("settle", dl) + } + how, dr, serr := layer.SettleDetach(sctx) + switch { + case serr != nil: + return storage.ChunkCutResult{}, 0, fmt.Errorf("%w: %w (settle: %w)", ErrDetachOutcomeUnknown, err, serr) + case how == storage.DetachApplied: + return dr, h.storage.NextLSN() - 1, nil + case how == storage.DetachFenced: + return storage.ChunkCutResult{}, 0, fmt.Errorf("durable: detach of %s: HEAD belongs to a newer epoch or another holder; I/O stays stopped: %w: %w", volumeID, storage.ErrChunkLayerFenced, err) + default: + return storage.ChunkCutResult{}, 0, p.resumeAfterDetach(volumeID, h, layer, err) + } +} + +const ( + defaultDetachFreezeTimeout = 20 * time.Second + detachFreezeTarget = 5 * time.Second +) + +// resumeAfterDetach undoes a detach that provably did not happen: the +// periodic cuts restart, the stop is lifted, and the volume serves again. +// The caller holds h.attachMu. +func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer storage.ChunkLayer, cause error) error { + p.mu.Lock() + closed := p.closed || h.chunk != layer + if !closed { + p.startChunkLoop(volumeID, h, layer) + } + p.mu.Unlock() + if closed { // a concurrent Close or detach of the layer owns the volume now + return fmt.Errorf("durable: detach of %s aborted while the provider closed: %w", volumeID, cause) + } + h.chunkDetach = false + h.backend.SetOperational(true, "chunk detach aborted: serving resumed") + log.Printf("durable: detach of volume=%s aborted, nothing published; serving resumed: %v", volumeID, cause) + return fmt.Errorf("%w: %w", ErrDetachAborted, cause) } // Preserve the optional manifest capability only when the inner remote has it; diff --git a/seaweed-block/core/frontend/durable/provider_chunk_authority_log_test.go b/seaweed-block/core/frontend/durable/provider_chunk_authority_log_test.go new file mode 100644 index 0000000000..9d3b9a2c4e --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_authority_log_test.go @@ -0,0 +1,225 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type lockedLog struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (l *lockedLog) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.buf.Write(p) +} + +func (l *lockedLog) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.buf.String() +} + +// waitLog waits until the log holds want, then returns the log. +func waitLog(t *testing.T, l *lockedLog, want string) string { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for !strings.Contains(l.String(), want) { + if time.Now().After(deadline) { + t.Fatalf("log never held %q:\n%s", want, l.String()) + } + time.Sleep(time.Millisecond) + } + return l.String() +} + +// inOrder checks that every line holding a want[i] fragment set appears, +// each after the previous one. +func inOrder(t *testing.T, logs string, want ...[]string) { + t.Helper() + lines := strings.Split(logs, "\n") + at := 0 +next: + for _, frags := range want { + for ; at < len(lines); at++ { + ok := true + for _, f := range frags { + ok = ok && strings.Contains(lines[at], f) + } + if ok { + at++ + continue next + } + } + t.Fatalf("no line with %q after the previous expected line:\n%s", frags, logs) + } +} + +// The deferred attach logs its wait (with the projection fields that +// fail), the first attach attempt, the HEAD claim and how the wait ended. +func TestChunkAuthorityWaitLogsTheWaitTheClaimAndTheEnd(t *testing.T) { + logs := &lockedLog{} + captureWriteLogs(t, logs) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} + p := chunkProviderForAssignment(t, v) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + v.active.Store(true) + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + waitLog(t, logs, "waits for master authority") + close(v.assigned) + got := waitLog(t, logs, "chunk authority wait for volume=v1 ended after") + inOrder(t, got, + []string{"volume=v1 waits for master authority (up to 30s): projection lacks healthy=false epoch=0"}, + []string{"volume=v1: master authority after", `replica="r1" epoch=3 endpoint=1`, "first attach attempt"}, + []string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`}, + []string{`HEAD claim for volume=v1 observed HEAD gen=0 epoch=0 holder=""`, "; preparing"}, + []string{"HEAD claim for volume=v1 done in ", `gen=0 epoch=0 holder="", no HEAD to claim (new lineage)`}, + []string{"chunk authority wait for volume=v1 ended after", ": attached after 1 attempt(s)"}, + ) + if strings.Count(got, "first attach attempt") != 1 { + t.Fatalf("first attach attempt logged more than once:\n%s", got) + } +} + +// A wait that reaches its bound logs the assignment-unavailable transition +// with the fields still missing; a wait ended by Close says so. +func TestChunkAuthorityWaitLogsDeadlineAndClose(t *testing.T) { + for _, mode := range []string{"limit", "close"} { + t.Run(mode, func(t *testing.T) { + logs := &lockedLog{} + captureWriteLogs(t, logs) + v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} + limit := 40 * time.Millisecond + if mode == "close" { + limit = time.Minute + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, + ChunkAssignmentTimeout: limit, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, + }, v) + if err != nil { + t.Fatal(err) + } + defer p.Close() + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + v.active.Store(true) + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + want := "ended after" + if mode == "close" { + waitLog(t, logs, "waits for master authority") + if err := p.Close(); err != nil { + t.Fatal(err) + } + } + got := waitLog(t, logs, want) + end := ": assignment unavailable, not serving (projection lacks healthy=false epoch=0)" + if mode == "close" { + end = ": provider closed" + } + inOrder(t, got, + []string{"volume=v1 waits for master authority (up to " + limit.String() + "): projection lacks healthy=false epoch=0"}, + []string{"chunk authority wait for volume=v1 ended after", end}, + ) + if strings.Contains(got, "first attach attempt") || strings.Contains(got, "HEAD claim for") { + t.Fatalf("attach logged without authority:\n%s", got) + } + }) + } +} + +// headFailRemote fails GetHead while fails > 0 (forever when < 0). +type headFailRemote struct { + *storage.MemChunkRemote + fails atomic.Int32 +} + +var errHeadRead = errors.New("injected HEAD read failure") + +func (r *headFailRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + if n := r.fails.Load(); n != 0 { + if n > 0 { + r.fails.Add(-1) + } + return storage.ChunkHead{}, errHeadRead + } + return r.MemChunkRemote.GetHead(ctx) +} + +// A claim whose first HEAD read fails logs its start and its failure with +// the elapsed time; the retry then claims. Close during the retry backoff +// ends the wait as closed, not superseded. +func TestChunkAuthorityWaitLogsAFailedClaim(t *testing.T) { + for _, mode := range []string{"retried", "closed in backoff"} { + t.Run(mode, func(t *testing.T) { + logs := &lockedLog{} + captureWriteLogs(t, logs) + remote := &headFailRemote{MemChunkRemote: storage.NewMemChunkRemote()} + remote.fails.Store(1) + if mode != "retried" { + remote.fails.Store(-1) + } + v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v) + if err != nil { + t.Fatal(err) + } + defer p.Close() + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + v.active.Store(true) + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + waitLog(t, logs, "waits for master authority") + close(v.assigned) + if mode == "retried" { + got := waitLog(t, logs, "chunk authority wait for volume=v1 ended after") + inOrder(t, got, + []string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`}, + []string{"HEAD claim for volume=v1 failed after ", errHeadRead.Error()}, + []string{"chunk layer attach for volume=v1:", "(retrying)"}, + []string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`}, + []string{"HEAD claim for volume=v1 observed HEAD gen=0"}, + []string{"HEAD claim for volume=v1 done in "}, + []string{"chunk authority wait for volume=v1 ended after", ": attached after 2 attempt(s)"}, + ) + return + } + waitLog(t, logs, "(retrying)") + if err := p.Close(); err != nil { + t.Fatal(err) + } + got := waitLog(t, logs, "chunk authority wait for volume=v1 ended after") + inOrder(t, got, + []string{"HEAD claim for volume=v1 failed after ", errHeadRead.Error()}, + []string{"chunk authority wait for volume=v1 ended after", ": provider closed during the retry backoff"}, + ) + }) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_burst_test.go b/seaweed-block/core/frontend/durable/provider_chunk_burst_test.go new file mode 100644 index 0000000000..903d2242a8 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_burst_test.go @@ -0,0 +1,105 @@ +package durable_test + +import ( + "bytes" + "context" + "encoding/binary" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" + "time" +) + +// Public provider + actual NVMe handler, file-backed v3 with the default +// 64 MiB WAL. No injected I/O failures, private selector, or flusher control. +func TestWALStoreChunkV3_SequentialBurstFlush(t *testing.T) { + const total = 320 * 1024 * 1024 + const transfer = 128 * 1024 + const flushEvery = 48 * 1024 * 1024 + ctx := context.Background() + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: total / 4096, ChunkBlocks: 1024, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := p.Close(); err != nil { + t.Logf("close: %v", err) + } + }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + be, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: be, BlockSize: 4096, VolumeSize: total}) + data := make([]byte, transfer) + start := time.Now() + for off := 0; off < total; off += transfer { + fillBurstTransfer(data, off) + r := h.Handle(ctx, nvme.IOCommand{Opcode: 0x01, NSID: 1, SLBA: uint64(off / 4096), NLB: transfer / 4096, Data: data}) + if r.AsError() != nil { + _, syncErr := s.Sync() + t.Fatalf("write bytes=%d elapsed=%v result=%+v exact Sync=%T %v", off, time.Since(start), r, syncErr, syncErr) + } + if (off+transfer)%flushEvery == 0 || off+transfer == total { + r = h.Handle(ctx, nvme.IOCommand{Opcode: 0x00, NSID: 1}) + if r.AsError() != nil { + _, syncErr := s.Sync() + t.Fatalf("flush bytes=%d elapsed=%v result=%+v exact Sync=%T %v", off+transfer, time.Since(start), r, syncErr, syncErr) + } + t.Logf("flush bytes=%d elapsed=%v", off+transfer, time.Since(start)) + } + } + // The expected bytes come from the submitted pattern, not another reader. + for off := 0; off < total; off += transfer { + got := make([]byte, transfer) + n, err := be.Read(ctx, int64(off), got) + if err != nil { + t.Fatalf("readback at%d: %v", off, err) + } + if n != transfer { + t.Fatalf("short readback at%d: %d", off, n) + } + for i := 0; i < len(got); i += 8 { + if word := binary.LittleEndian.Uint64(got[i : i+8]); word != uint64(off+i) { + t.Fatalf("readback word at byte%d=%d want%d", off+i, word, off+i) + } + } + } + +} + +func fillBurstTransfer(data []byte, off int) { + for i := 0; i < len(data); i += 8 { + binary.LittleEndian.PutUint64(data[i:i+8], uint64(off+i)) + } +} + +func TestWALStoreChunkV3_BurstPatternBindsFullLBA(t *testing.T) { + const transfer = 128 * 1024 + zero, later := make([]byte, transfer), make([]byte, transfer) + fillBurstTransfer(zero, 0) + for _, off := range []int{32 * 1024 * 1024, 64 * 1024 * 1024, 256 * 1024 * 1024} { + fillBurstTransfer(later, off) + if bytes.Equal(zero, later) { + t.Fatalf("pattern aliases LBA0 and LBA%d", off/4096) + } + for _, i := range []int{0, 4096, len(later) - 8} { + if got := binary.LittleEndian.Uint64(later[i : i+8]); got != uint64(off+i) { + t.Fatalf("word at byte%d=%d want%d", off+i, got, off+i) + } + } + } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go new file mode 100644 index 0000000000..4584662a70 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go @@ -0,0 +1,423 @@ +package durable_test + +// A failed detach (design MIGRATION E4, review S6): the guest is never left +// frozen by a detach that did not happen. When the final cut provably did not +// publish (a failed upload, a refused CAS, an unresolved detach CAS that a +// cancel at the same base settles), serving resumes on this host. When the +// detach landed, the volume stays stopped with the detached result. When the +// outcome cannot be decided (HEAD unreadable), it stays stopped: never resume +// on top of a possibly detached HEAD. + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// faultRemote injects one fault into the next detach's remote calls. +type faultRemote struct { + *storage.MemChunkRemote + mu sync.Mutex + putErr error // returned by every Put while set + casMode string // "", "precondition", "lost" (not applied, error), "applied-lost" (applied, error), "hold" + getHeadErr error // returned by every GetHead while set + getHeadFail int // the next N GetHead calls fail + getHeadHold bool // every GetHead blocks until its caller gives up + // "delayed": the CAS's reply is lost now, the CAS itself reaches the + // remote only when release closes; its own result goes to delayedErr. + release chan struct{} + delayedErr chan error +} + +var errInjected = errors.New("injected remote fault") + +func (r *faultRemote) set(f func(r *faultRemote)) { r.mu.Lock(); f(r); r.mu.Unlock() } + +func (r *faultRemote) Put(ctx context.Context, key string, data []byte) error { + r.mu.Lock() + err := r.putErr + r.mu.Unlock() + if err != nil { + return err + } + return r.MemChunkRemote.Put(ctx, key, data) +} + +func (r *faultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + r.mu.Lock() + hold := r.getHeadHold + err := r.getHeadErr + if err == nil && r.getHeadFail > 0 { + r.getHeadFail-- + err = errInjected + } + r.mu.Unlock() + if hold { + <-ctx.Done() + return storage.ChunkHead{}, ctx.Err() + } + if err != nil { + return storage.ChunkHead{}, err + } + return r.MemChunkRemote.GetHead(ctx) +} + +func (r *faultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + r.mu.Lock() + mode := r.casMode + r.casMode = "" // one fault, on the next CAS only + r.mu.Unlock() + switch mode { + case "precondition": + return 0, storage.ErrChunkHeadPrecondition + case "lost": + return 0, errInjected + case "hold": // held until the caller gives up: not applied + <-ctx.Done() + return 0, ctx.Err() + case "delayed": + r.mu.Lock() + release, out := r.release, r.delayedErr + r.mu.Unlock() + go func() { + <-release + _, err := r.MemChunkRemote.CASHead(context.Background(), expected, next) + out <- err + }() + return 0, errInjected + case "applied-lost": + if _, err := r.MemChunkRemote.CASHead(ctx, expected, next); err != nil { + return 0, err + } + return 0, errInjected + } + return r.MemChunkRemote.CASHead(ctx, expected, next) +} + +// detachFixture: a chunk volume with one cut published and one more write +// (dirty), so the detach's final cut has something to upload. +func detachFixture(t *testing.T) (*faultRemote, *durable.DurableProvider, frontend.Backend) { + t.Helper() + remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} + p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 4096, block(1)); err != nil { + t.Fatal(err) + } + if _, err := p.CutVolume(context.Background(), "v1", 0); err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 8192, block(2)); err != nil { + t.Fatal(err) + } + return remote, p, b +} + +// assertServing: the volume accepts writes and a cut publishes them, with a +// HEAD that is not detached. +func assertServing(t *testing.T, p *durable.DurableProvider, b frontend.Backend, remote *faultRemote) { + t.Helper() + ctx := context.Background() + if _, err := b.Write(ctx, 12288, block(3)); err != nil { + t.Fatalf("write after an aborted detach: %v; want the volume serving again", err) + } + r, err := p.CutVolume(ctx, "v1", 0) + if err != nil { + t.Fatalf("cut after an aborted detach: %v", err) + } + if r.Head.State == storage.ChunkHeadDetached { + t.Fatal("HEAD is detached after a detach that was reported aborted") + } + if !bytesEqual(headBlock(t, remote.MemChunkRemote, 2), block(2)) || !bytesEqual(headBlock(t, remote.MemChunkRemote, 3), block(3)) { + t.Fatal("the cut after an aborted detach lost the dirty blocks") + } +} + +func TestWALStoreChunk_FailedDetachUploadResumes(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.putErr = errInjected }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with failing uploads: %v; want ErrDetachAborted", err) + } + remote.set(func(r *faultRemote) { r.putErr = nil }) + assertServing(t, p, b, remote) +} + +func TestWALStoreChunk_RefusedDetachCASResumes(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "precondition" }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with a refused CAS: %v; want ErrDetachAborted", err) + } + assertServing(t, p, b, remote) +} + +// The detach CAS's reply is lost and it did not apply: the settle cancels it +// with a CAS at the same base, so it can never land, and serving resumes. +func TestWALStoreChunk_LostDetachCASNotAppliedIsCancelledAndResumes(t *testing.T) { + remote, p, b := detachFixture(t) + base, _ := remote.MemChunkRemote.GetHead(context.Background()) + remote.set(func(r *faultRemote) { r.casMode = "lost" }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with a lost, unapplied CAS: %v; want ErrDetachAborted after the cancel", err) + } + // The cancel is a real CAS at the detach's base: HEAD moved one generation + // and is not detached, so the lost detach CAS can never land afterwards. + if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached || head.Gen != base.Gen+1 { + t.Fatalf("HEAD after the cancel: gen %d state %q; want gen %d, not detached", head.Gen, head.State, base.Gen+1) + } + assertServing(t, p, b, remote) +} + +// The detach CAS's reply is lost but it applied: the detach succeeded, the +// volume stays stopped and DetachVolume returns the detached result. +func TestWALStoreChunk_LostDetachCASAppliedStaysDetached(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "applied-lost" }) + r, _, err := p.DetachVolume(context.Background(), "v1") + if err != nil || r.Head.State != storage.ChunkHeadDetached { + t.Fatalf("detach whose CAS applied but lost its reply: %+v %v; want the detached result", r, err) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after an applied detach: %v; want ErrNotReady", err) + } +} + +// The detach CAS applied but its reply was lost AND the cut's own HEAD re-read +// failed: only the settle can tell. It reads HEAD, finds the detach, and the +// detach succeeds (stays stopped) instead of resuming on a detached HEAD. +func TestWALStoreChunk_LostDetachCASAppliedFoundBySettle(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "applied-lost"; r.getHeadFail = 1 }) + r, _, err := p.DetachVolume(context.Background(), "v1") + if err != nil || r.Head.State != storage.ChunkHeadDetached { + t.Fatalf("detach whose applied CAS only the settle can see: %+v %v; want the detached result", r, err) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after a settled, applied detach: %v; want ErrNotReady", err) + } +} + +// The detach CAS's reply is lost and HEAD cannot be read: the outcome is +// unknown, so the volume stays stopped (also through a recovery). +func TestWALStoreChunk_UndecidableDetachStaysStopped(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "lost"; r.getHeadErr = errInjected }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) { + t.Fatalf("detach with an undecidable outcome: %v; want ErrDetachOutcomeUnknown", err) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after an undecidable detach: %v; want ErrNotReady", err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) { + t.Fatalf("recovery after an undecidable detach: %v; want the volume to stay stopped", err) + } +} + +// The freeze is bounded by DetachFreezeTimeout: a CAS that hangs ends there, +// the outcome is settled (HEAD still at base: cancelled) and serving resumes, +// all well inside bound + settle. +func TestWALStoreChunk_DetachFreezeIsBoundedThenResumes(t *testing.T) { + remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, + StorageRoot: t.TempDir(), + BlockSize: 4096, + NumBlocks: pcBlocks, + ChunkBlocks: pcChunkBlocks, + DetachFreezeTimeout: 300 * time.Millisecond, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 4096, block(1)); err != nil { + t.Fatal(err) + } + if _, err := p.CutVolume(context.Background(), "v1", 0); err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 8192, block(2)); err != nil { + t.Fatal(err) + } + remote.set(func(r *faultRemote) { r.casMode = "hold" }) + start := time.Now() + _, _, err = p.DetachVolume(context.Background(), "v1") + took := time.Since(start) + if !errors.Is(err, durable.ErrDetachAborted) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("detach with a hung CAS: %v; want an aborted detach at the freeze bound", err) + } + // The cut gets three quarters of the bound, the settlement the rest. + if took < 225*time.Millisecond || took > 300*time.Millisecond+200*time.Millisecond { + t.Fatalf("detach with a hung CAS took %v; want the cut ended at 3/4 of the 300 ms freeze bound and the total within it", took) + } + assertServing(t, p, b, remote) +} + +// HEAD belongs to a newer epoch: the detach's CAS is refused and the volume +// is fenced; it stays stopped (never resumes against another holder). +func TestWALStoreChunk_DetachAgainstNewerEpochStaysStopped(t *testing.T) { + remote, p, b := detachFixture(t) + ctx := context.Background() + cur, err := remote.MemChunkRemote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + newer := cur + newer.Epoch, newer.Holder = cur.Epoch+1, "another-holder" + if _, err := remote.MemChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, newer); err != nil { + t.Fatal(err) + } + if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) || errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach against a newer epoch: %v; want fenced, not aborted", err) + } + if _, err := b.Write(ctx, 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) && !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("write after a fenced detach: %v; want it refused (not ready / stale primary)", err) + } +} + +// P1 (review): a repeated detach after a successful one, with a cancelled +// context (its StopIO fails at once), returns the first result and never +// resumes serving. +func TestWALStoreChunk_RepeatDetachWithCancelledContextNeverResumes(t *testing.T) { + _, p, b := detachFixture(t) + r1, _, err := p.DetachVolume(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + forced := false + durable.SetTestDetachStopIO(p, func(context.Context) error { forced = true; return context.Canceled }) // the drain fails + r2, _, err := p.DetachVolume(context.Background(), "v1") + if !forced { + t.Fatal("the failed-drain branch was not taken") + } + if err != nil || r2.Head.Gen != r1.Head.Gen || r2.Head.State != storage.ChunkHeadDetached { + t.Fatalf("repeated detach with a cancelled context: %+v %v; want the first result %+v", r2, err, r1) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after a repeated detach: %v; want ErrNotReady (never resumed)", err) + } +} + +// P1 (review): after an undecidable detach, a retry whose StopIO fails (a +// cancelled context) settles first and stays stopped while the outcome is +// still unknown. +func TestWALStoreChunk_RetryAfterUndecidableDetachNeverResumes(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "lost"; r.getHeadErr = errInjected }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) { + t.Fatalf("first detach: %v; want ErrDetachOutcomeUnknown", err) + } + forced := false + durable.SetTestDetachStopIO(p, func(context.Context) error { forced = true; return context.Canceled }) // the drain fails + _, _, err := p.DetachVolume(context.Background(), "v1") + if !forced { + t.Fatal("the failed-drain branch was not taken") + } + if !errors.Is(err, durable.ErrDetachOutcomeUnknown) || errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("retry over an unresolved detach CAS: %v; want still unknown, never aborted", err) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after a retry over an unknown detach: %v; want ErrNotReady", err) + } +} + +// P1 (review): one freeze budget covers the cut AND the settlement: with the +// CAS and every HEAD read hung, DetachVolume returns within the bound (here +// undecided, so the volume stays stopped). +func TestWALStoreChunk_DetachFreezeBoundCoversTheSettle(t *testing.T) { + const freeze = 400 * time.Millisecond + remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + DetachFreezeTimeout: freeze, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 4096, block(1)); err != nil { + t.Fatal(err) + } + remote.set(func(r *faultRemote) { r.casMode = "hold"; r.getHeadHold = true }) + deadlines := map[string]time.Time{} + durable.SetTestDetachTrace(p, func(stage string, d time.Time) { deadlines[stage] = d }) + start := time.Now() + _, _, err = p.DetachVolume(context.Background(), "v1") + took := time.Since(start) + cutAt, settleAt := deadlines["cut"].Sub(start), deadlines["settle"].Sub(start) + if cutAt < freeze*3/4-50*time.Millisecond || cutAt > freeze*3/4+50*time.Millisecond || settleAt < freeze-50*time.Millisecond || settleAt > freeze+50*time.Millisecond { + t.Fatalf("deadlines: cut %v, settle %v after the start; want three quarters of the %v freeze, then the bound", cutAt, settleAt, freeze) + } + if !errors.Is(err, durable.ErrDetachOutcomeUnknown) { + t.Fatalf("detach with a hung CAS and hung HEAD reads: %v; want the outcome unknown", err) + } + if took > freeze+200*time.Millisecond { + t.Fatalf("detach took %v; the %v freeze bound must cover the settlement too", took, freeze) + } + if _, err := b.Write(context.Background(), 8192, block(2)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after an undecided detach: %v; want ErrNotReady", err) + } +} + +// P2 (review): the lost detach CAS really is in flight. It reaches the remote +// only after the cancel landed, and then fails its precondition: HEAD stays +// active. +func TestWALStoreChunk_DelayedDetachCASCannotLandAfterTheCancel(t *testing.T) { + remote, p, b := detachFixture(t) + release, delayed := make(chan struct{}), make(chan error, 1) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + joined := false + t.Cleanup(func() { // join the delayed CAS worker, bounded + unblock() + if !joined { + select { + case <-delayed: + case <-time.After(5 * time.Second): + t.Error("delayed CAS worker not joined") + } + } + }) + remote.set(func(r *faultRemote) { r.casMode = "delayed"; r.release, r.delayedErr = release, delayed }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with a delayed CAS: %v; want ErrDetachAborted after the cancel", err) + } + unblock() + var derr error + select { + case derr = <-delayed: + joined = true + case <-time.After(5 * time.Second): + t.Fatal("the delayed detach CAS did not complete after its release") + } + if !errors.Is(derr, storage.ErrChunkHeadPrecondition) { + t.Fatalf("the delayed detach CAS after the cancel: %v; want a precondition failure", derr) + } + if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached { + t.Fatal("the delayed detach CAS landed after the cancel") + } + assertServing(t, p, b, remote) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go index 368b60d143..0dda1b07f1 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go @@ -118,10 +118,11 @@ func TestWALStoreChunk_DetachDrainsAdmittedWrite(t *testing.T) { } } -// The drain is bounded by the caller's context: a detach that cannot drain -// fails, publishes nothing and keeps I/O stopped, also through a recovery; -// once the admitted write finishes, a retry settles the detach with it. -func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) { +// The drain is bounded (the caller's context or the freeze bound): a detach +// that cannot drain publishes nothing, so it aborts and the volume serves +// again (MIGRATION E4; it used to stay stopped, review S6); once the admitted +// write finishes, a retry detaches with every acknowledged write. +func TestWALStoreChunk_DetachDrainTimeoutAbortsAndResumes(t *testing.T) { ctx := context.Background() remote := storage.NewMemChunkRemote() p, view := parkedProvider(t, remote) @@ -139,21 +140,54 @@ func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) { dctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) _, _, err = p.DetachVolume(dctx, "v1") cancel() - if !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("detach that cannot drain: %v; want the context's deadline", err) + if !errors.Is(err, context.DeadlineExceeded) || !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach that cannot drain: %v; want an aborted detach on the context's deadline", err) } if head, _ := remote.GetHead(ctx); head.State == storage.ChunkHeadDetached { t.Fatalf("a detach that did not drain published a detached HEAD: %+v", head) } - if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) { - t.Fatalf("recovery after a failed detach: %v; want the volume to stay stopped", err) + // Serving resumes: a new write is accepted. The drain still pending from + // the aborted stop orders new I/O after the I/O admitted before it, so + // this write completes once that admitted write does (never on the + // detach itself). + arrived := make(chan struct{}) + var arriveOnce sync.Once + durable.SetTestBeforeIOLock(b, func() { arriveOnce.Do(func() { close(arrived) }) }) + nerr := make(chan error, 1) + go func() { _, err := b.Write(ctx, 8192, block(6)); nerr <- err }() + bounded := func(what string, ch <-chan struct{}) { + t.Helper() + select { + case <-ch: + case <-time.After(5 * time.Second): + t.Fatalf("%s did not happen within 5s", what) + } } - if _, err := b.Write(ctx, 8192, block(6)); !errors.Is(err, frontend.ErrNotReady) { - t.Fatalf("new write after a failed detach and a recovery: %v; want ErrNotReady", err) + bounded("the new write passing the operational gate (serving resumed)", arrived) + select { + case err := <-nerr: + t.Fatalf("new write completed (%v) ahead of the write admitted before the stop", err) + default: // queued behind the admitted write at the I/O lock, as the drain orders it } view.unpark() - acked := <-werr == nil + recv := func(what string, ch <-chan error) error { + t.Helper() + select { + case err := <-ch: + return err + case <-time.After(5 * time.Second): + t.Fatalf("%s did not complete within 5s", what) + return nil + } + } + acked := recv("the admitted write", werr) == nil + if err := recv("the new write", nerr); err != nil { + t.Fatalf("new write after an aborted detach: %v; want it accepted", err) + } + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("recovery after an aborted detach: %v; want it to succeed", err) + } o := detachOutcome{} o.r, o.last, o.err = p.DetachVolume(ctx, "v1") if o.err != nil || o.r.Head.State != storage.ChunkHeadDetached { @@ -162,6 +196,9 @@ func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) { if acked && !bytesEqual(headBlock(t, remote, 1), block(5)) { t.Fatal("the write admitted before the stop was acknowledged but is not in the detached HEAD") } + if !bytesEqual(headBlock(t, remote, 2), block(6)) { + t.Fatal("the write accepted after the aborted detach is not in the detached HEAD") + } } // After a successful detach, RecoverVolume keeps I/O stopped and a repeated diff --git a/seaweed-block/core/frontend/durable/provider_chunk_lifetime_test.go b/seaweed-block/core/frontend/durable/provider_chunk_lifetime_test.go index 4cc8a19612..21d1d73f72 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_lifetime_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_lifetime_test.go @@ -401,9 +401,52 @@ func TestWALStoreChunk_ConcurrentRecoverAttachesOnce(t *testing.T) { } } -// The caller's recovery deadline governs the attach's first remote call, -// with no Close and no hold release. +// A caller deadline can expire during local recovery, before the first +// remote call, or while that call is held. Both must return the deadline +// error without Close or releasing the remote hold. func TestWALStoreChunk_RecoverHonoursCallerDeadline(t *testing.T) { + for _, tc := range []struct { + name string + timeout time.Duration + }{ + {"during_recovery_or_attach", 300 * time.Millisecond}, + {"before_recovery", -time.Millisecond}, + } { + t.Run(tc.name, func(t *testing.T) { + g := newGated(storage.NewMemChunkRemote()) + g.holdGetHead = make(chan struct{}) + g.honourCtx = true + t.Cleanup(g.release) + p := chunkProvider(t, t.TempDir(), g, v1View(), 0) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), tc.timeout) + defer cancel() + recErr := make(chan error, 1) + go func() { _, err := p.RecoverVolume(ctx, "v1"); recErr <- err }() + var err error + select { + case what := <-g.entered: + if what != "gethead" { + t.Fatalf("held call %q, want gethead", what) + } + err = recvErr(t, recErr, "RecoverVolume past its caller deadline") + case err = <-recErr: + // Local recovery may consume the deadline before attach starts. + case <-time.After(10 * time.Second): + t.Fatal("RecoverVolume neither returned nor reached the held remote") + } + if !errors.Is(err, context.DeadlineExceeded) || ctx.Err() != context.DeadlineExceeded { + t.Fatalf("RecoverVolume=%v caller=%v, want deadline exceeded", err, ctx.Err()) + } + }) + } +} + +// This handshake separately guarantees that the caller's cancellation is +// tested with a remote call already in flight, independent of local I/O speed. +func TestWALStoreChunk_RecoverHonoursCallerCancellationAfterRemoteEntry(t *testing.T) { g := newGated(storage.NewMemChunkRemote()) g.holdGetHead = make(chan struct{}) g.honourCtx = true @@ -412,13 +455,14 @@ func TestWALStoreChunk_RecoverHonoursCallerDeadline(t *testing.T) { if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) } - ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + ctx, cancel := context.WithCancel(context.Background()) defer cancel() recErr := make(chan error, 1) go func() { _, err := p.RecoverVolume(ctx, "v1"); recErr <- err }() waitEntered(t, g, "gethead") - if err := recvErr(t, recErr, "RecoverVolume past its caller deadline"); err == nil { - t.Fatal("RecoverVolume succeeded although its deadline expired during attach") + cancel() + if err := recvErr(t, recErr, "RecoverVolume after caller cancellation"); !errors.Is(err, context.Canceled) { + t.Fatalf("RecoverVolume=%v, want caller cancellation", err) } } @@ -542,24 +586,65 @@ func TestWALStoreChunk_CloseSettlesDeferredAttach(t *testing.T) { // recovery refuses as a WAL integrity fault. It returns a restore func. func corruptWALWrite(t *testing.T, path string, fill byte) func() { t.Helper() - raw, err := os.ReadFile(path) + // Read the known fixture geometry without touching the owner's locked + // byte zero, and search only the WAL (the extent may contain a copy). + source, err := os.Open(path) if err != nil { t.Fatal(err) } - payload := bytes.Repeat([]byte{fill}, 4096) - at := bytes.Index(raw, payload) - if at < 30 || bytes.Index(raw[at+1:], payload) >= 0 { - t.Fatalf("WAL record for fill %#x not found exactly once", fill) + defer source.Close() + var geometry [16]byte + if _, err := source.ReadAt(geometry[:], 48); err != nil { + t.Fatal(err) } - const hdr = 30 // LSN 8, Reserved 8, Type 1, Flags 1, LBA 8, Length 4 - start := at - hdr - rec := append([]byte(nil), raw[start:at+4096+8]...) + walStart := binary.LittleEndian.Uint64(geometry[:8]) + walSize := binary.LittleEndian.Uint64(geometry[8:]) + if walStart != 8192 || walSize > 64*1024*1024 || walSize < 4096+70 { + t.Fatalf("unexpected v3 fixture geometry %d/%d", walStart, walSize) + } + wal := make([]byte, int(walSize)) + if _, err := source.ReadAt(wal, int64(walStart)); err != nil { + t.Fatal(err) + } + payload := bytes.Repeat([]byte{fill}, 4096) + // Search every overlapping payload occurrence, accepting only a complete, + // CRC-valid single-write record. A nonce/trailer byte may equal fill, so + // the first bytes.Index match is not necessarily the payload boundary. + const hdr, recordSize = 62, 62 + 4096 + 8 + table := crc32.MakeTable(crc32.Castagnoli) + at, matches := -1, 0 + for search := 0; search <= len(wal)-len(payload); { + relative := bytes.Index(wal[search:], payload) + if relative < 0 { + break + } + candidate := search + relative + search = candidate + 1 + if candidate < hdr || candidate+4096+8 > len(wal) { + continue + } + record := wal[candidate-hdr : candidate+4096+8] + if record[16] != 0x01 || record[17] != 0 || + binary.LittleEndian.Uint64(record[8:16]) != 0 || + binary.LittleEndian.Uint32(record[26:30]) != 4096 || + binary.LittleEndian.Uint64(record[38:46])%walSize != uint64(candidate-hdr) || + binary.LittleEndian.Uint32(record[hdr+4096:]) != crc32.Checksum(record[:hdr+4096], table) || + binary.LittleEndian.Uint32(record[hdr+4096+4:]) != recordSize { + continue + } + at, matches = candidate, matches+1 + } + if matches != 1 { + t.Fatalf("CRC-valid WAL write payload %#x matched %d records; want exactly one", fill, matches) + } + start := int64(walStart) + int64(at-hdr) + rec := append([]byte(nil), wal[at-hdr:at+4096+8]...) orig := append([]byte(nil), rec...) if rec[16] != 0x01 || binary.LittleEndian.Uint64(rec[8:]) != 0 { t.Fatalf("unexpected WAL record header % x", rec[:hdr]) } - rec[16] = 0x04 // write batch, Reserved stays 0: invalid - binary.LittleEndian.PutUint32(rec[hdr+4096:], crc32.ChecksumIEEE(rec[:hdr+4096])) + rec[16] = 0x04 // invalid native batch: BatchCount remains zero + binary.LittleEndian.PutUint32(rec[hdr+4096:], crc32.Checksum(rec[:hdr+4096], crc32.MakeTable(crc32.Castagnoli))) f, err := os.OpenFile(path, os.O_WRONLY, 0) if err != nil { t.Fatal(err) @@ -580,6 +665,47 @@ func corruptWALWrite(t *testing.T, path string, fill byte) func() { } } +// The nonce ends immediately before the payload. A matching last nonce byte +// must not shift the corruption target one byte into the header. +func TestCorruptWALWrite_NoncePayloadOverlap(t *testing.T) { + const prefix, payloadSize, walStart, walSize = 62, 4096, 8192, 16384 + path := filepath.Join(t.TempDir(), "overlap.bin") + image := make([]byte, walStart+walSize) + binary.LittleEndian.PutUint64(image[48:56], walStart) + binary.LittleEndian.PutUint64(image[56:64], walSize) + rec := image[walStart : walStart+prefix+payloadSize+8] + binary.LittleEndian.PutUint64(rec[:8], 1) + rec[16] = 0x01 + binary.LittleEndian.PutUint64(rec[18:26], 5) + binary.LittleEndian.PutUint32(rec[26:30], payloadSize) + rec[61] = 0xa7 // legal nonce: old bytes.Index reports 61, not payload offset 62 + copy(rec[prefix:], bytes.Repeat([]byte{0xa7}, payloadSize)) + binary.LittleEndian.PutUint32(rec[prefix+payloadSize:], crc32.Checksum(rec[:prefix+payloadSize], crc32.MakeTable(crc32.Castagnoli))) + binary.LittleEndian.PutUint32(rec[prefix+payloadSize+4:], uint32(len(rec))) + if err := os.WriteFile(path, image, 0600); err != nil { + t.Fatal(err) + } + restore := corruptWALWrite(t, path, 0xa7) + changed, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + want := append([]byte(nil), image...) + want[walStart+16] = 0x04 + binary.LittleEndian.PutUint32(want[walStart+prefix+payloadSize:], crc32.Checksum(want[walStart:walStart+prefix+payloadSize], crc32.MakeTable(crc32.Castagnoli))) + if !bytes.Equal(changed, want) { + t.Fatal("corruption changed bytes outside the intended type/CRC") + } + restore() + repaired, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(repaired, image) { + t.Fatal("restore did not recover the exact original image") + } +} + // A deferred attach belongs to the recovery that registered it. Recovery // A succeeds before authority; recovery B then fails on a real WAL // integrity fault; when authority arrives, A's wait must neither attach @@ -609,6 +735,15 @@ func TestWALStoreChunk_StaleWaiterCannotOverrideFailedRecovery(t *testing.T) { if _, err := s.Write(5, block(0xA7)); err != nil { t.Fatal(err) } + // This oracle requires corruption below a persisted W. Default mode C + // intentionally permits losing its newest uncheckpointed batch instead. + ws, ok := s.(*storage.WALStore) + if !ok { + t.Fatalf("unexpected native store %T", s) + } + if err := ws.SetWMode(storage.WModeStrict); err != nil { + t.Fatal(err) + } if _, err := s.Sync(); err != nil { t.Fatal(err) } @@ -683,6 +818,15 @@ func TestWALStoreChunk_FailedRecoveryRetiresAuthorityWait(t *testing.T) { if _, err := s.Write(5, block(0xA7)); err != nil { t.Fatal(err) } + // This oracle requires corruption below a persisted W. Default mode C + // intentionally permits losing its newest uncheckpointed batch instead. + ws, ok := s.(*storage.WALStore) + if !ok { + t.Fatalf("unexpected native store %T", s) + } + if err := ws.SetWMode(storage.WModeStrict); err != nil { + t.Fatal(err) + } if _, err := s.Sync(); err != nil { t.Fatal(err) } @@ -774,6 +918,15 @@ func TestWALStoreChunk_StaleWaiterPastTickCheckCannotAttach(t *testing.T) { if _, err := s.Write(5, block(0xA7)); err != nil { t.Fatal(err) } + // This oracle requires corruption below a persisted W. Default mode C + // intentionally permits losing its newest uncheckpointed batch instead. + ws, ok := s.(*storage.WALStore) + if !ok { + t.Fatalf("unexpected native store %T", s) + } + if err := ws.SetWMode(storage.WModeStrict); err != nil { + t.Fatal(err) + } if _, err := s.Sync(); err != nil { t.Fatal(err) } @@ -781,6 +934,7 @@ func TestWALStoreChunk_StaleWaiterPastTickCheckCannotAttach(t *testing.T) { // Park A's wait inside its projection read, after its tick check. view.arm() + t.Cleanup(func() { close(view.release) }) select { case <-view.parked: case <-time.After(10 * time.Second): diff --git a/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go b/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go new file mode 100644 index 0000000000..1e3e2a9734 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go @@ -0,0 +1,265 @@ +package durable_test + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/recovery" + "github.com/seaweedfs/seaweed-block/core/storage" + "runtime" + "sort" + "testing" + "time" +) + +// Preserve the typed backend cause alongside the actual NVMe handler result. +// This test submits writes synchronously, so lastError has one caller. +type noFlushBackend struct { + frontend.Backend + lastError error +} + +func (b *noFlushBackend) Write(ctx context.Context, offset int64, data []byte) (int, error) { + n, err := b.Backend.Write(ctx, offset, data) + b.lastError = err + return n, err +} + +// Public provider + actual NVMe handler, file-backed v3 with the default +// 64 MiB WAL. No injected I/O failures, private selector, or flusher control. +func TestWALStoreChunkV3_NoClientFlushBurst(t *testing.T) { + for _, mode := range []storage.WMode{storage.WModeLagged, storage.WModeStrict} { + t.Run(fmt.Sprintf("mode-%d", mode), func(t *testing.T) { + runNoClientFlushBurst(t, mode) + }) + } +} +func runNoClientFlushBurst(t *testing.T, mode storage.WMode) { + const total = 400 * 1024 * 1024 + const transfer = 128 * 1024 + ctx := context.Background() + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: (1 << 30) / 4096, ChunkBlocks: 1024, ChunkCaptureInterval: 0, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := p.Close(); err != nil { + t.Logf("close: %v", err) + } + }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + be, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + before, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + ws := s.(*storage.WALStore) + if err := ws.SetWMode(mode); err != nil { + t.Fatal(err) + } + syncsBefore := ws.WALSyncCount() + var durations []time.Duration + busyCount := 0 + t.Logf("before HEAD gen=%d remoteLSN=%d cp=%d next=%d retention=%d", before.Gen, before.RemoteLSN, ws.CheckpointLSN(), ws.NextLSN(), ws.RecoveryRetentionLSNs()) + recorded := &noFlushBackend{Backend: be} + h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: recorded, BlockSize: 4096, VolumeSize: 1 << 30}) + data := make([]byte, transfer) + start := time.Now() + for off := 0; off < total; off += transfer { + for i := range data { + if i%8 == 0 { + binary.LittleEndian.PutUint64(data[i:i+8], uint64(off+i)) + } + } + retryDeadline := time.Now().Add(30 * time.Second) + cpBefore := ws.CheckpointLSN() + retried := false + for { + writeStart := time.Now() + r := h.Handle(ctx, nvme.IOCommand{Opcode: 0x01, NSID: 1, SLBA: uint64(off / 4096), NLB: transfer / 4096, Data: data}) + elapsed := time.Since(writeStart) + durations = append(durations, elapsed) + if elapsed >= 5*time.Second || time.Since(start) >= 2*time.Minute || time.Now().After(retryDeadline) { + dump := make([]byte, 2<<20) + n := runtime.Stack(dump, true) + t.Logf("TIMEOUT STACKS\n%s", dump[:n]) + t.Fatalf("NO FLUSH exceeded wait bound bytes=%d attempt=%v total=%v busy=%d result=%+v cp=%d next=%d", off, elapsed, time.Since(start), busyCount, r, ws.CheckpointLSN(), ws.NextLSN()) + } + if r.AsError() == nil { + if retried { + t.Logf("NO FLUSH resumed bytes=%d cp=%d->%d next=%d syncs=%d busy=%d", off, cpBefore, ws.CheckpointLSN(), ws.NextLSN(), ws.WALSyncCount(), busyCount) + } + break + } + if !errors.Is(recorded.lastError, frontend.ErrBackendBusy) || r.SCT != nvme.SCTGeneric || r.SC != nvme.SCNamespaceNotReady { + t.Fatalf("NO FLUSH non-retryable write bytes=%d result=%+v cause=%v", off, r, recorded.lastError) + } + busyCount++ + retried = true + t.Logf("NO FLUSH retry bytes=%d busy=%d attempt=%v cp=%d next=%d syncs=%d", off, busyCount, elapsed, ws.CheckpointLSN(), ws.NextLSN(), ws.WALSyncCount()) + if busyCount == 1 { + passiveStart := time.Now() + cpAtBusy := ws.CheckpointLSN() + target := ws.NextLSN() - 1 + cpObserved := cpAtBusy + // Getters only: no Write, Sync, NotifyUrgent or Close may + // drive progress before the first retry. + for cpAtBusy < target && cpObserved <= cpAtBusy && time.Since(passiveStart) < 10*time.Second { + time.Sleep(25 * time.Millisecond) + cpObserved = ws.CheckpointLSN() + } + t.Logf("NO FLUSH passive bytes=%d wait=%v cpBefore=%d cpAtBusy=%d cpObserved=%d target=%d", off, time.Since(passiveStart), cpBefore, cpAtBusy, cpObserved, target) + if time.Since(passiveStart) >= 10*time.Second || (cpAtBusy < target && cpObserved <= cpAtBusy) { + t.Fatalf("NO FLUSH passive checkpoint did not advance without another write: bytes=%d cp=%d busy=%d", off, cpObserved, busyCount) + } + } + // Retry the identical command; no caller Flush drives reclamation. + time.Sleep(25 * time.Millisecond) + } + if (off+transfer)%(16*1024*1024) == 0 { + t.Logf("NO FLUSH progress bytes=%d elapsed=%v cp=%d next=%d", off+transfer, time.Since(start), ws.CheckpointLSN(), ws.NextLSN()) + } + } + // The expected bytes come from the submitted pattern, not another reader. + for off := 0; off < total; off += transfer { + got := make([]byte, transfer) + n, err := be.Read(ctx, int64(off), got) + if err != nil { + t.Fatalf("readback at%d: %v", off, err) + } + if n != transfer { + t.Fatalf("short readback at%d: %d", off, n) + } + for i := 0; i < len(got); i += 8 { + if value := binary.LittleEndian.Uint64(got[i : i+8]); value != uint64(off+i) { + t.Fatalf("readback offset%d got%d", off+i, value) + } + } + } + + sort.Slice(durations, func(i, j int) bool { return durations[i] < durations[j] }) + batches := ws.WALSyncCount() - syncsBefore + fsyncs := batches + if mode == storage.WModeStrict { + fsyncs *= 2 + } + t.Logf("COST mode=%d bytes=%d busy=%d pressureBatches=%d internalFsyncsPerGiB=%.2f attemptP99=%v maxAttempt=%v", mode, total, busyCount, batches, float64(fsyncs)/(float64(total)/(1<<30)), durations[(len(durations)-1)*99/100], durations[len(durations)-1]) + after, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + st := p.DurableStatuses() + if after.Gen != before.Gen || after.RemoteLSN != before.RemoteLSN { + t.Fatalf("remote moved without explicit cut: before=%+v after=%+v", before, after) + } + if len(st) != 1 || st[0].Chunk == nil || st[0].Chunk.Stats.CutsOK != 0 { + t.Fatalf("unexpected cuts: %+v", st) + } + if ws.CheckpointLSN() == 0 || st[0].WriteProfile.WALAppendWrapCount == 0 { + t.Fatal("no checkpoint or physical wrap observed") + } + t.Logf("after HEAD gen=%d remoteLSN=%d cp=%d next=%d wraps=%d cuts=%d", after.Gen, after.RemoteLSN, ws.CheckpointLSN(), ws.NextLSN(), st[0].WriteProfile.WALAppendWrapCount, st[0].Chunk.Stats.CutsOK) + +} + +// Actual RF2 coordinator pins retained history even after an internal fsync. +// Expiry is retryable; ending the session restores local no-Flush progress. +func TestWALStoreChunkV3NoFlushWithActiveRF2CatchupPin(t *testing.T) { + ctx := context.Background() + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + be, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + ws := s.(*storage.WALStore) + c := recovery.NewPeerShipCoordinator() + if err := c.StartSession("r2", 1, 0, 0); err != nil { + t.Fatal(err) + } + ws.SetRecycleFloorSource(c) + recorded := &noFlushBackend{Backend: be} + h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: recorded, BlockSize: 4096, VolumeSize: 1 << 30}) + data := bytes.Repeat([]byte{0x5a}, 128*1024) + var stalled bool + for off := 0; off < 80*1024*1024; off += len(data) { + start := time.Now() + r := h.Handle(ctx, nvme.IOCommand{Opcode: 1, NSID: 1, SLBA: uint64(off / 4096), NLB: 32, Data: data}) + if r.AsError() != nil { + if r.SCT != nvme.SCTGeneric || r.SC != nvme.SCNamespaceNotReady || time.Since(start) >= 5*time.Second { + t.Fatalf("pin wait status=%+v elapsed=%v", r, time.Since(start)) + } + stalled = true + break + } + } + if !stalled || ws.CheckpointLSN() != 0 { + t.Fatalf("pin did not constrain checkpoint: stalled=%v cp=%d", stalled, ws.CheckpointLSN()) + } + count := 0 + if err := ws.ScanLBAs(1, func(e storage.RecoveryEntry) error { + count++ + if !bytes.Equal(e.Data, bytes.Repeat([]byte{0x5a}, 4096)) { + return fmt.Errorf("pinned catch-up bytes changed") + } + return nil + }); err != nil || count == 0 { + t.Fatalf("retained catch-up records=%d err=%v", count, err) + } + c.EndSession("r2") + retryDeadline := time.Now().Add(30 * time.Second) + busy := 0 + for { + start := time.Now() + r := h.Handle(ctx, nvme.IOCommand{Opcode: 1, NSID: 1, SLBA: 20000, NLB: 32, Data: data}) + if time.Since(start) >= 5*time.Second || time.Now().After(retryDeadline) { + t.Fatalf("released pin exceeded bound: attempt=%v busy=%d result=%+v", time.Since(start), busy, r) + } + if r.AsError() == nil { + break + } + if !errors.Is(recorded.lastError, frontend.ErrBackendBusy) || r.SCT != nvme.SCTGeneric || r.SC != nvme.SCNamespaceNotReady { + t.Fatalf("non-retryable released-pin write: %+v cause=%v", r, recorded.lastError) + } + busy++ + time.Sleep(25 * time.Millisecond) + } + got := make([]byte, len(data)) + if n, err := be.Read(ctx, 20000*4096, got); err != nil || n != len(got) || !bytes.Equal(got, data) { + t.Fatalf("released-pin readback n=%d err=%v", n, err) + } + if ws.CheckpointLSN() == 0 { + t.Fatal("released pin did not permit checkpoint progress") + } + t.Logf("released pin completed: busy=%d checkpoint=%d", busy, ws.CheckpointLSN()) +} diff --git a/seaweed-block/core/frontend/durable/provider_format_v3_base_test.go b/seaweed-block/core/frontend/durable/provider_format_v3_base_test.go new file mode 100644 index 0000000000..96ea3a6d40 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_format_v3_base_test.go @@ -0,0 +1,270 @@ +//go:build swblock_format_v3_test + +package durable + +import ( + "bytes" + "context" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" + "time" +) + +func TestDurableProviderV3_AttachedChunkBASEInstallAndCapture(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + p := mappedProviderV3(t, t.TempDir(), remote) + st, e := p.EnsureStorage("v1") + if e != nil { + t.Fatal(e) + } + if _, e = p.RecoverVolume(ctx, "v1"); e != nil { + t.Fatal(e) + } + var id [16]byte + id[0] = 1 + h, e := storage.BeginInstall(st, 0, id) + if e != nil { + t.Fatalf("real provider attached BASE begin refused: %v", e) + } + want := bytes.Repeat([]byte{0x69}, 4096) + if e = h.WriteBase(5, want); e != nil { + t.Fatal(e) + } + if _, e = p.CaptureVolume(ctx, "v1"); e == nil { + t.Fatal("partial BASE was captured") + } + if e = h.MarkBaseComplete(); e != nil { + t.Fatal(e) + } + if _, e = p.CaptureVolume(ctx, "v1"); e != nil { + t.Fatalf("completed BASE capture refused: %v", e) + } + head, e := remote.GetHead(ctx) + if e != nil { + t.Fatal(e) + } + ref, ok := head.Chunks[1] + if !ok { + t.Fatal("completed BASE chunk omitted") + } + chunk, e := remote.Get(ctx, ref.Key) + if e != nil || len(chunk) < 8192 || !bytes.Equal(chunk[4096:8192], want) { + t.Fatalf("captured BASE mismatch: %v", e) + } +} + +func TestDurableProviderV3_AttachesCompletedChunkBASE(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + p := mappedProviderV3(t, t.TempDir(), storage.NewMemChunkRemote()) + st, e := p.EnsureStorage("v1") + if e != nil { + t.Fatal(e) + } + if _, e = st.Recover(); e != nil { + t.Fatal(e) + } + var id [16]byte + id[0] = 2 + h, e := storage.BeginInstall(st, 7, id) + if e != nil { + t.Fatal(e) + } + if e = h.WriteBase(5, bytes.Repeat([]byte{0x37}, 4096)); e != nil { + t.Fatal(e) + } + if e = h.MarkBaseComplete(); e != nil { + t.Fatal(e) + } + if _, e = p.RecoverVolume(ctx, "v1"); e != nil { + t.Fatalf("real provider completed BASE attach refused: %v", e) + } + got := make([]byte, 4096) + if n, e := p.Backend("v1").Read(ctx, 5*4096, got); e != nil || n != 4096 || !bytes.Equal(got, bytes.Repeat([]byte{0x37}, 4096)) { + t.Fatalf("completed BASE read n=%d err=%v", n, e) + } +} + +// A complete local BASE is not an empty fresh restore, even while the +// provider's first-attach marker exists and HEAD still names an older image. +func TestDurableProviderV3_CompletedBASEDoesNotRestoreOlderHEAD(t *testing.T) { + completedBASEDoesNotRestoreOlderHEAD(t, false) +} + +func TestDurableProviderV3_DefersBASERetirementUntilLocalPresence(t *testing.T) { + completedBASEDoesNotRestoreOlderHEAD(t, true) +} + +func completedBASEDoesNotRestoreOlderHEAD(t *testing.T, retire bool) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + source := mappedProviderV3(t, t.TempDir(), remote) + if _, e := source.EnsureStorage("v1"); e != nil { + t.Fatal(e) + } + if _, e := source.RecoverVolume(ctx, "v1"); e != nil { + t.Fatal(e) + } + for _, lba := range []int64{5, 9} { + if n, e := source.Backend("v1").Write(ctx, lba*4096, bytes.Repeat([]byte{0x11}, 4096)); e != nil || n != 4096 { + t.Fatal(n, e) + } + } + if e := source.Backend("v1").Sync(ctx); e != nil { + t.Fatal(e) + } + if _, e := source.CaptureVolume(ctx, "v1"); e != nil { + t.Fatal(e) + } + if e := source.Close(); e != nil { + t.Fatal(e) + } + root := t.TempDir() + target := mappedProviderV3(t, root, remote) + st, e := target.EnsureStorage("v1") + if e != nil { + t.Fatal(e) + } + if _, e = st.Recover(); e != nil { + t.Fatal(e) + } + var id [16]byte + id[0] = 3 + h, e := storage.BeginInstall(st, 7, id) + if e != nil { + t.Fatal(e) + } + want := bytes.Repeat([]byte{0x78}, 4096) + if e = h.WriteBase(5, want); e != nil { + t.Fatal(e) + } + if e = h.WriteBase(9, make([]byte, 4096)); e != nil { + t.Fatal(e) + } + if retire { + if e = h.ApplyInstallEntry(5, want, 8); e != nil { + t.Fatal(e) + } + } + if e = h.MarkBaseComplete(); e != nil { + t.Fatal(e) + } + if retire { + if _, e = st.Sync(); e != nil { + t.Fatal(e) + } + if e = storage.FlushMappedWALStoreV3Test(st.(*storage.WALStore)); e != nil { + t.Fatal(e) + } + state, _ := storage.BaseStateV3Test(st.(*storage.WALStore)) + if _, ok := st.(*storage.WALStore).InstalledBaseLSN(); !ok || state != storage.BaseInstalled || st.(*storage.WALStore).CheckpointLSN() < 8 { + t.Fatalf("BASE retired before durable local presence: state=%v checkpoint=%d", state, st.(*storage.WALStore).CheckpointLSN()) + } + // The provider must restore the opt-in gate before recovery can + // publish a descriptor on a reopened store. + if e = target.Close(); e != nil { + t.Fatal(e) + } + target = mappedProviderV3(t, root, remote) + st, e = target.EnsureStorage("v1") + if e != nil { + t.Fatal(e) + } + } + if _, e = target.RecoverVolume(ctx, "v1"); e != nil { + t.Fatalf("completed local BASE was treated as empty remote restore: %v", e) + } + check := func() { + t.Helper() + for lba, expected := range map[int64][]byte{5: want, 9: make([]byte, 4096)} { + got := make([]byte, 4096) + if n, e := target.Backend("v1").Read(ctx, lba*4096, got); e != nil || n != 4096 || !bytes.Equal(got, expected) { + t.Fatalf("local BASE lba%d bytes lost: n%d err%v", lba, n, e) + } + } + + } + check() + if retire { + if _, e = st.Sync(); e != nil { + t.Fatal(e) + } + if e = storage.FlushMappedWALStoreV3Test(st.(*storage.WALStore)); e != nil { + t.Fatal(e) + } + state, _ := storage.BaseStateV3Test(st.(*storage.WALStore)) + if state != storage.BaseNone { + t.Fatalf("durable local presence did not release retirement: %v", state) + } + } + if e = target.Close(); e != nil { + t.Fatal(e) + } + target = mappedProviderV3(t, root, remote) + if _, e = target.EnsureStorage("v1"); e != nil { + t.Fatal(e) + } + if _, e = target.RecoverVolume(ctx, "v1"); e != nil { + t.Fatal(e) + } + check() +} + +// A seeded checkpoint is not proof that any extent data was materialized. +func TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + source := mappedProviderV3(t, t.TempDir(), remote) + if _, err := source.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := source.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{0x4d}, 4096) + if n, err := source.Backend("v1").Write(ctx, 5*4096, want); err != nil || n != len(want) { + t.Fatal(n, err) + } + if err := source.Backend("v1").Sync(ctx); err != nil { + t.Fatal(err) + } + if _, err := source.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if err := source.Close(); err != nil { + t.Fatal(err) + } + head, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + target := mappedProviderV3(t, t.TempDir(), remote) + st, err := target.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err = st.Recover(); err != nil { + t.Fatal(err) + } + if err = st.(*storage.WALStore).SeedChunkFrontier(head.RemoteLSN); err != nil { + t.Fatal(err) + } + if st.(*storage.WALStore).CheckpointLSN() == 0 || st.NextLSN() <= 1 { + t.Fatal("seed did not establish the ambiguous frontier") + } + if _, ok := st.(*storage.WALStore).InstalledBaseLSN(); ok { + t.Fatal("seed became a completed BASE") + } + if _, err = target.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + got := make([]byte, 4096) + if n, err := target.Backend("v1").Read(ctx, 5*4096, got); err != nil || n != len(got) || !bytes.Equal(got, want) { + t.Fatalf("seed-only restore lost remote bytes: n=%d err=%v equal=%v", n, err, bytes.Equal(got, want)) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_format_v3_fresh_crash_test.go b/seaweed-block/core/frontend/durable/provider_format_v3_fresh_crash_test.go new file mode 100644 index 0000000000..f450ad17e2 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_format_v3_fresh_crash_test.go @@ -0,0 +1,300 @@ +//go:build swblock_format_v3_test + +package durable + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type freshCrashImage struct { + Head storage.ChunkHead + Objects map[string][]byte +} + +func freshCrashRemote(t *testing.T, path string) *storage.MemChunkRemote { + t.Helper() + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var img freshCrashImage + if err = json.Unmarshal(raw, &img); err != nil { + t.Fatal(err) + } + remote := storage.NewMemChunkRemote() + ctx := context.Background() + for key, data := range img.Objects { + if err = remote.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + } + for gen := uint64(0); gen < img.Head.Gen; gen++ { + current, e := remote.GetHead(ctx) + if e != nil { + t.Fatal(e) + } + if _, e = remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: current.Gen, Epoch: current.Epoch}, img.Head); e != nil { + t.Fatal(e) + } + } + return remote +} + +// The child exits after presence is durable but before the fresh marker is +// removed. No Close or provider cleanup runs on the successful crash path. +func TestDurableProviderV3_FreshMarkerCrashKeepsCompletedBASE(t *testing.T) { + freshMarkerCrashKeepsCompletedBASE(t, "attach") +} + +func TestDurableProviderV3_FreshMarkerCompletionCrashKeepsCompletedBASE(t *testing.T) { + freshMarkerCrashKeepsCompletedBASE(t, "complete") +} + +func TestDurableProviderV3_FreshMarkerCaptureCrashKeepsCompletedBASE(t *testing.T) { + freshMarkerCrashKeepsCompletedBASE(t, "capture") +} + +func freshMarkerCrashKeepsCompletedBASE(t *testing.T, mode string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if root := os.Getenv("SWBLOCK_V3_FRESH_CRASH_ROOT"); root != "" { + remote := freshCrashRemote(t, filepath.Join(root, "remote.json")) + p := mappedProviderV3(t, root, remote) + if os.Getenv("SWBLOCK_V3_FRESH_CRASH_MODE") == "capture" { + p.cfg.ChunkCaptureInterval = time.Hour + } + st, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ws := st.(*storage.WALStore) + if _, err = ws.Recover(); err != nil { + t.Fatal(err) + } + var h storage.InstallHandle + install := func() { + var id [16]byte + id[0] = 23 + h, err = storage.BeginInstall(ws, 7, id) + if err != nil { + t.Fatal(err) + } + data := bytes.Repeat([]byte{0x78}, 4096) + if err = h.WriteBase(5, data); err != nil { + t.Fatal(err) + } + if err = h.WriteBase(9, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + if err = h.ApplyInstallEntry(5, data, 8); err != nil { + t.Fatal(err) + } + if err = h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + if _, err = ws.Sync(); err != nil { + t.Fatal(err) + } + if err = storage.FlushMappedWALStoreV3Test(ws); err != nil { + t.Fatal(err) + } + } + mode = os.Getenv("SWBLOCK_V3_FRESH_CRASH_MODE") + if mode != "complete" { + install() + } + p.testBeforeChunkFreshRetire = func() error { + if mode == "complete" { + install() + } + if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil { + t.Fatal(err) + } + if err := h.ApplyInstallEntry(5, bytes.Repeat([]byte{0x79}, 4096), 9); err != nil { + t.Fatal(err) + } + if _, err := ws.Sync(); err != nil { + t.Fatal(err) + } + if mode == "capture" { + before, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + beforeBytes, err := json.Marshal(before) + if err != nil { + t.Fatal(err) + } + puts := remote.Puts() + if _, err := p.CaptureVolume(ctx, "v1"); !errors.Is(err, ErrNotChunkVolume) { + t.Fatal("precommit CaptureVolume published before durable owner commit") + } + if _, err := p.CutVolume(ctx, "v1", 9); !errors.Is(err, ErrNotChunkVolume) { + t.Fatal("precommit CutVolume was admitted") + } + if err := p.MakeVolumeRemoteDurable(ctx, "v1", 9); !errors.Is(err, ErrNotChunkVolume) { + t.Fatal("precommit MakeVolumeRemoteDurable was admitted") + } + after, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + afterBytes, err := json.Marshal(after) + if err != nil { + t.Fatal(err) + } + intents, err := remote.ListIntents(ctx) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(beforeBytes, afterBytes) || remote.Puts() != puts || len(intents) != 0 { + t.Fatal("refused precommit publication changed remote state") + } + p.mu.Lock() + handle := p.volumes["v1"] + exposed := handle.chunk != nil || handle.chunkStop != nil || handle.chunkDone != nil + p.mu.Unlock() + if exposed { + t.Fatal("precommit layer or scheduler was exposed") + } + fmt.Println("FRESH_CAPTURE_REFUSED no_remote_effect=true scheduler_hidden=true") + } + fmt.Println("FRESH_CRASH_READY presence_saved=true marker_present=true ack=9 no_Close=true") + os.Exit(0) + return nil + } + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + t.Fatal("crash boundary not reached") + } + root := t.TempDir() + remote := storage.NewMemChunkRemote() + source := mappedProviderV3(t, t.TempDir(), remote) + if _, err := source.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := source.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + for _, lba := range []int64{5, 9} { + if n, err := source.Backend("v1").Write(ctx, lba*4096, bytes.Repeat([]byte{0x11}, 4096)); err != nil || n != 4096 { + t.Fatal(n, err) + } + } + if err := source.Backend("v1").Sync(ctx); err != nil { + t.Fatal(err) + } + if _, err := source.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if err := source.Close(); err != nil { + t.Fatal(err) + } + head, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + img := freshCrashImage{Head: head, Objects: map[string][]byte{}} + for _, ref := range head.Chunks { + data, e := remote.Get(ctx, ref.Key) + if e != nil { + t.Fatal(e) + } + img.Objects[ref.Key] = data + } + raw, err := json.Marshal(img) + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(filepath.Join(root, "remote.json"), raw, 0600); err != nil { + t.Fatal(err) + } + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDurableProviderV3_FreshMarkerCrashKeepsCompletedBASE$", "-test.v") + cmd.WaitDelay = 2 * time.Second + cmd.Env = append(os.Environ(), "SWBLOCK_V3_FRESH_CRASH_ROOT="+root, "SWBLOCK_V3_FRESH_CRASH_MODE="+mode) + out, err := cmd.CombinedOutput() + t.Logf("%s", out) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(out, []byte("FRESH_CRASH_READY presence_saved=true marker_present=true ack=9 no_Close=true")) { + t.Fatal("child missed crash boundary") + } + p := mappedProviderV3(t, root, freshCrashRemote(t, filepath.Join(root, "remote.json"))) + if _, err = os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil { + t.Fatal("crash marker missing", err) + } + if _, err = p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("post-presence/pre-marker crash lost completed BASE recovery: %v", err) + } + for lba, want := range map[int64][]byte{5: bytes.Repeat([]byte{0x79}, 4096), 9: make([]byte, 4096)} { + got := make([]byte, 4096) + if n, err := p.Backend("v1").Read(ctx, lba*4096, got); err != nil || n != 4096 || !bytes.Equal(got, want) { + t.Fatalf("crash BASE bytes lba=%d n=%d err=%v equal=%v", lba, n, err, bytes.Equal(got, want)) + } + } +} + +// A failed owner commit keeps the layer private without leaking or trying +// to attach it twice. Success publishes it and starts its scheduler once. +func TestDurableProviderV3_AttachCommitRetryKeepsLayerPrivate(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + p := mappedProviderV3(t, t.TempDir(), remote) + p.cfg.ChunkCaptureInterval = time.Hour + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + injected := errors.New("hold durable owner commit") + p.testBeforeChunkFreshRetire = func() error { return injected } + if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, injected) { + t.Fatal(err) + } + p.mu.Lock() + h := p.volumes["v1"] + pending := h.chunkPending + exposed := h.chunk != nil || h.chunkStop != nil || h.chunkDone != nil + p.mu.Unlock() + if pending == nil || exposed { + t.Fatal("failed commit exposed or lost pending layer") + } + if _, err := p.CaptureVolume(ctx, "v1"); !errors.Is(err, ErrNotChunkVolume) { + t.Fatal("failed commit capture", err) + } + if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil { + t.Fatal(err) + } + p.testBeforeChunkFreshRetire = nil + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal("commit retry", err) + } + p.mu.Lock() + correct := h.chunk == pending && h.chunkPending == nil && h.chunkStop != nil && h.chunkDone != nil + p.mu.Unlock() + if !correct { + t.Fatal("commit did not publish the same pending layer and scheduler") + } + if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); !os.IsNotExist(err) { + t.Fatal("committed marker remains", err) + } + if _, err := p.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal("postcommit capture", err) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_format_v3_test.go b/seaweed-block/core/frontend/durable/provider_format_v3_test.go new file mode 100644 index 0000000000..f9602b79f0 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_format_v3_test.go @@ -0,0 +1,459 @@ +//go:build swblock_format_v3_test + +package durable + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "os" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type formatV3View struct{} + +func (formatV3View) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, Healthy: true} +} + +func mappedProviderV3(t *testing.T, root string, remote storage.ChunkRemote) *DurableProvider { + t.Helper() + p, err := NewDurableProvider(ProviderConfig{ + Impl: ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, + WALRecoveryTestDisableFlusher: true, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, formatV3View{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + // Activation closure: use the production selector and provider geometry. + return p +} + +func TestDurableProviderV3_MappedCheckpointCaptureAndReopen(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + root := t.TempDir() + remote := storage.NewMemChunkRemote() + p := mappedProviderV3(t, root, remote) + st, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + b := p.Backend("v1") + data := bytes.Repeat([]byte{0x57}, 4096) + if n, err := b.Write(ctx, 5*4096, data); err != nil || n != len(data) { + t.Fatalf("Write: %d %v", n, err) + } + if err = b.Sync(ctx); err != nil { + t.Fatal(err) + } + if err = storage.FlushMappedWALStoreV3Test(st.(*storage.WALStore)); err != nil { + t.Fatal(err) + } + if _, err = p.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + check := func(want []byte) { + t.Helper() + head, e := remote.GetHead(ctx) + if e != nil { + t.Fatal(e) + } + ref, ok := head.Chunks[1] + if !ok { + t.Fatal("capture omitted checkpointed chunk") + } + chunk, e := remote.Get(ctx, ref.Key) + if e != nil { + t.Fatal(e) + } + if !bytes.Equal(chunk[4096:8192], want) { + t.Fatal("published chunk bytes differ") + } + } + check(data) + raw, err := os.ReadFile(p.volumePath("v1")) + if err != nil { + t.Fatal(err) + } + if binary.LittleEndian.Uint32(raw[12:16]) != 3 { + t.Fatal("provider did not open impl3") + } + if _, err = os.Stat(p.volumePath("v1") + ".chunkbitmap"); !os.IsNotExist(err) { + t.Fatalf("legacy bitmap exists: %v", err) + } + if err = p.Close(); err != nil { + t.Fatal(err) + } + p2 := mappedProviderV3(t, root, remote) + st2, err := p2.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err = p2.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + b2 := p2.Backend("v1") + got := make([]byte, 4096) + if n, err := b2.Read(ctx, 5*4096, got); err != nil || n != len(got) || !bytes.Equal(got, data) { + t.Fatalf("reopen read %d %v equal=%v", n, err, bytes.Equal(got, data)) + } + next := bytes.Repeat([]byte{0x93}, 4096) + if _, err = b2.Write(ctx, 5*4096, next); err != nil { + t.Fatal(err) + } + if err = b2.Sync(ctx); err != nil { + t.Fatal(err) + } + if err = storage.FlushMappedWALStoreV3Test(st2.(*storage.WALStore)); err != nil { + t.Fatal(err) + } + before := remote.Puts() + if _, err = p2.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if remote.Puts()-before != 1 { + t.Fatalf("incremental capture uploaded %d chunks", remote.Puts()-before) + } + check(next) +} + +// The selector must not turn a missing owned map into a legacy bitmap path. +func TestDurableProviderV3_MissingMapRefusesBeforeBackend(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + root := t.TempDir() + remote := storage.NewMemChunkRemote() + p := mappedProviderV3(t, root, remote) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + path := p.volumePath("v1") + if err := p.Close(); err != nil { + t.Fatal(err) + } + if err := os.Remove(path + ".chunkmap"); err != nil { + t.Fatal(err) + } + p2 := mappedProviderV3(t, root, remote) + if st, err := p2.EnsureStorage("v1"); err == nil || st != nil { + t.Fatalf("accepted missing map: store=%v err=%v", st, err) + } + if p2.Backend("v1") != nil { + t.Fatal("failed open cached a backend") + } + if _, err := os.Stat(path + ".chunkbitmap"); !os.IsNotExist(err) { + t.Fatalf("legacy fallback created a bitmap: %v", err) + } +} + +func TestDurableProviderV3_DefaultSelectorCreatesV3(t *testing.T) { + p, err := NewDurableProvider(ProviderConfig{Impl: ImplWALStore, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096}, formatV3View{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err = p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + f, err := os.Open(p.volumePath("v1")) + if err != nil { + t.Fatal(err) + } + defer f.Close() + var hdr [16]byte + if _, err = f.ReadAt(hdr[:], 0); err != nil { + t.Fatal(err) + } + if binary.LittleEndian.Uint16(hdr[4:6]) != 3 || binary.LittleEndian.Uint32(hdr[12:16]) != 3 { + t.Fatal("default provider did not select v3/impl3") + } +} + +// An invalid inherited frontier must fail preparation without claiming HEAD. +func TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 2, Holder: "old", RemoteLSN: ^uint64(0)}); err != nil { + t.Fatal(err) + } + before, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + p := mappedProviderV3(t, t.TempDir(), remote) + if _, err = p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(p.volumePath("v1")) + if err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(ctx, "v1"); err == nil { + t.Fatal("invalid HEAD frontier accepted") + } + after, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if after.Gen != before.Gen || after.Epoch != before.Epoch || after.Holder != before.Holder { + t.Fatal("failed seed claimed HEAD") + } + now, err := os.ReadFile(p.volumePath("v1")) + if err != nil { + t.Fatal(err) + } + // Recover may publish the serving scan's descriptor. It must never serialize + // a legacy header or advance the inherited logical frontier. + if binary.LittleEndian.Uint16(now[4:6]) != 3 || binary.LittleEndian.Uint16(raw[4:6]) != 3 { + t.Fatal("restore serialized a legacy header") + } + var buf [4096]byte + if _, err := p.Backend("v1").Read(ctx, 0, buf[:]); err == nil { + t.Fatal("failed restore left backend operational") + } +} + +// This exercises the row7 caller seam without enabling production v3. The +// owner seed/install transaction must make this pass before restore is claimed. +type formatV3TakeoverView struct{} + +func (formatV3TakeoverView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v1", ReplicaID: "r2", Epoch: 4, EndpointVersion: 1, Healthy: true} +} + +type formatV3RestoreRemote struct { + storage.ChunkRemote + beforeClaim func() error + loseClaimResponse bool +} + +func (r *formatV3RestoreRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + if expected.Epoch == 3 { + if err := r.beforeClaim(); err != nil { + return 0, err + } + } + gen, err := r.ChunkRemote.CASHead(ctx, expected, next) + if err == nil && expected.Epoch == 3 && r.loseClaimResponse { + return 0, errors.New("claim response lost after commit") + } + return gen, err +} +func TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN(t *testing.T) { + exerciseMappedHEADRestoreV3(t, false) +} +func TestDurableProviderV3_HEADRestoreAfterLostClaimResponse(t *testing.T) { + exerciseMappedHEADRestoreV3(t, true) +} +func exerciseMappedHEADRestoreV3(t *testing.T, loseClaimResponse bool) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + source := mappedProviderV3(t, t.TempDir(), remote) + st, err := source.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err = source.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + first, second := bytes.Repeat([]byte{0x51}, 4096), bytes.Repeat([]byte{0xC2}, 4096) + for lba, data := range map[int64][]byte{5: first, 12: second} { + if _, err = source.Backend("v1").Write(ctx, lba*4096, data); err != nil { + t.Fatal(err) + } + } + if err = source.Backend("v1").Sync(ctx); err != nil { + t.Fatal(err) + } + if err = storage.FlushMappedWALStoreV3Test(st.(*storage.WALStore)); err != nil { + t.Fatal(err) + } + if h, err := source.CaptureVolume(ctx, "v1"); err != nil || h != 2 { + t.Fatalf("source capture H=%d err=%v", h, err) + } + if err = source.Close(); err != nil { + t.Fatal(err) + } + root := t.TempDir() + probe := &formatV3RestoreRemote{ChunkRemote: remote, loseClaimResponse: loseClaimResponse} + target := mappedProviderV3(t, root, probe) + target.view = formatV3TakeoverView{} + restored, err := target.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + probe.beforeClaim = func() error { + if restored.NextLSN() != 3 { + return errors.New("HEAD takeover attempted before durable seed/rebase") + } + return nil + } + if _, err = target.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("actual mapped HEAD restore refused: %v", err) + } + if restored.NextLSN() != 3 { + t.Fatalf("restored nextLSN=%d want3", restored.NextLSN()) + } + head, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if head.RemoteLSN != 2 || head.Epoch != 4 || head.Holder != "r2" { + t.Fatalf("takeover changed image/frontier: %+v", head) + } + before := remote.Puts() + check := func(p *DurableProvider, lba int64, want []byte) { + t.Helper() + got := make([]byte, 4096) + if n, e := p.Backend("v1").Read(ctx, lba*4096, got); e != nil || n != len(got) || !bytes.Equal(got, want) { + t.Fatalf("LBA%d n=%d err=%v equal=%v", lba, n, e, bytes.Equal(got, want)) + } + } + check(target, 5, first) + check(target, 12, second) + check(target, 0, make([]byte, 4096)) + if remote.Puts() != before { + t.Fatal("lazy read uploaded remote chunks") + } + next := bytes.Repeat([]byte{0x83}, 4096) + if _, err = target.Backend("v1").Write(ctx, 5*4096, next); err != nil { + t.Fatal(err) + } + if restored.NextLSN() != 4 { + t.Fatalf("restored write reused inherited LSN: next=%d", restored.NextLSN()) + } + if err = target.Backend("v1").Sync(ctx); err != nil { + t.Fatal(err) + } + if err = storage.FlushMappedWALStoreV3Test(restored.(*storage.WALStore)); err != nil { + t.Fatal(err) + } + if h, err := target.CaptureVolume(ctx, "v1"); err != nil || h != 3 { + t.Fatalf("restored capture H=%d err=%v", h, err) + } + if _, err = os.Stat(target.volumePath("v1") + ".chunkbitmap"); !os.IsNotExist(err) { + t.Fatalf("restore used legacy bitmap: %v", err) + } + if err = target.Close(); err != nil { + t.Fatal(err) + } + reopened := mappedProviderV3(t, root, remote) + reopened.view = formatV3TakeoverView{} + if _, err = reopened.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err = reopened.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + check(reopened, 5, next) + check(reopened, 12, second) +} + +// Exercise the same snapshots consumed by the host status endpoint, not a +// separately constructed status object. +func TestDurableProviderV3_StatusTracksRecoverSyncAndCapture(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + p := mappedProviderV3(t, t.TempDir(), storage.NewMemChunkRemote()) + st, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + status := func() VolumeStatus { + t.Helper() + all := p.DurableStatuses() + if len(all) != 1 { + t.Fatalf("statuses=%+v", all) + } + v := all[0] + if v.VolumeID != "v1" || v.ReplicaID != "r1" || v.Epoch != 3 || !v.Latched || !v.FrontierKnown { + t.Fatalf("lineage/frontier=%+v", v) + } + return v + } + if v := status(); v.Operational || v.Chunk == nil || v.Chunk.Attached { + t.Fatalf("before recover=%+v", v) + } + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if v := status(); !v.Operational || v.Chunk == nil || !v.Chunk.Attached || v.Chunk.Fenced { + t.Fatalf("after recover=%+v", v) + } + if n, e := p.Backend("v1").Write(ctx, 5*4096, bytes.Repeat([]byte{0x77}, 4096)); e != nil || n != 4096 { + t.Fatal(n, e) + } + if err = p.Backend("v1").Sync(ctx); err != nil { + t.Fatal(err) + } + if v := status(); v.DurableLSN != 1 || v.HeadLSN != 1 || v.Chunk.RemoteLSN != 0 { + t.Fatalf("after Sync=%+v", v) + } + if err = storage.FlushMappedWALStoreV3Test(st.(*storage.WALStore)); err != nil { + t.Fatal(err) + } + if _, err = p.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if v := status(); v.DurableLSN != 1 || v.Chunk.RemoteLSN != 1 || !v.Operational { + t.Fatalf("after capture=%+v", v) + } +} + +func TestDurableProviderV3_ContiguousWriteSurvivesCheckpointAndReopen(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + root := t.TempDir() + remote := storage.NewMemChunkRemote() + p := mappedProviderV3(t, root, remote) + st, e := p.EnsureStorage("v1") + if e != nil { + t.Fatal(e) + } + if _, e = p.RecoverVolume(ctx, "v1"); e != nil { + t.Fatal(e) + } + want := append(bytes.Repeat([]byte{0x31}, 4096), bytes.Repeat([]byte{0x72}, 4096)...) + if n, e := p.Backend("v1").Write(ctx, 4*4096, want); e != nil || n != len(want) { + t.Fatalf("actual provider contiguous Write: n=%d err=%v", n, e) + } + if e = p.Backend("v1").Sync(ctx); e != nil { + t.Fatal(e) + } + if e = storage.FlushMappedWALStoreV3Test(st.(*storage.WALStore)); e != nil { + t.Fatal(e) + } + if _, e = p.CaptureVolume(ctx, "v1"); e != nil { + t.Fatal(e) + } + if e = p.Close(); e != nil { + t.Fatal(e) + } + q := mappedProviderV3(t, root, remote) + if _, e = q.EnsureStorage("v1"); e != nil { + t.Fatal(e) + } + if _, e = q.RecoverVolume(ctx, "v1"); e != nil { + t.Fatal(e) + } + got := make([]byte, len(want)) + if n, e := q.Backend("v1").Read(ctx, 4*4096, got); e != nil || n != len(want) || !bytes.Equal(got, want) { + t.Fatalf("reopen n=%d err=%v equal=%v", n, e, bytes.Equal(got, want)) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_seed_linux_test.go b/seaweed-block/core/frontend/durable/provider_seed_linux_test.go index 477abdabdf..65c5007223 100644 --- a/seaweed-block/core/frontend/durable/provider_seed_linux_test.go +++ b/seaweed-block/core/frontend/durable/provider_seed_linux_test.go @@ -10,7 +10,6 @@ import ( "os" "path/filepath" "strconv" - "strings" "sync" "syscall" "testing" @@ -47,7 +46,7 @@ func failSeedFD(t *testing.T, root string) func() { fd := -1 for _, e := range entries { name, err := os.Readlink("/proc/self/fd/" + e.Name()) - if err == nil && strings.HasPrefix(name, root+string(os.PathSeparator)) { + if err == nil && name == filepath.Join(root, "v1.bin") { if fd != -1 { t.Fatal("more than one fixture WAL descriptor") } diff --git a/seaweed-block/core/frontend/durable/provider_test.go b/seaweed-block/core/frontend/durable/provider_test.go index 6b70ff437e..310c0afd1c 100644 --- a/seaweed-block/core/frontend/durable/provider_test.go +++ b/seaweed-block/core/frontend/durable/provider_test.go @@ -71,8 +71,8 @@ func TestPhase150_DurableProviderWALMultiBlockOptIn(t *testing.T) { single := run(t, false) multi := run(t, true) - if single != 16 { - t.Fatalf("single encode ops=%d want 16", single) + if single != 4 { + t.Fatalf("native v3 batch encode ops=%d want 4 regardless of legacy option", single) } if multi != 4 { t.Fatalf("multi encode ops=%d want 4", multi) diff --git a/seaweed-block/core/frontend/durable/read_ready_wait_test.go b/seaweed-block/core/frontend/durable/read_ready_wait_test.go new file mode 100644 index 0000000000..c19c8c1373 --- /dev/null +++ b/seaweed-block/core/frontend/durable/read_ready_wait_test.go @@ -0,0 +1,112 @@ +package durable + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { + for _, mode := range []string{"close", "drain-then-close", "fence", "write-close"} { + name := mode + t.Run(name, func(t *testing.T) { + // No storage is needed: this read must never pass the operational gate. + b := &StorageBackend{waitAttachReady: true} + b.opEvidence.Store("attachment pending") + registered := make(chan struct{}, 1) + resume := make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(resume) }) } + b.testBeforeReadReadyWait = func() { + select { + case registered <- struct{}{}: + default: + } + <-resume + } + done := make(chan error, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + release() + _ = b.Close() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("pending read did not settle after release and Close") + } + }) + go func() { + defer close(joined) + var err error + if mode == "write-close" { + _, err = b.Write(context.Background(), 0, make([]byte, 4096)) + } else { + _, err = b.Read(context.Background(), 0, make([]byte, 4096)) + } + done <- err + }() + select { + case <-registered: + case <-time.After(time.Second): + t.Fatal("read did not register a readiness notification") + } + if mode == "drain-then-close" { + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + if err := b.StopIO(ctx, "attachment still pending"); err != nil { + t.Fatalf("waiting read held I/O admission: %v", err) + } + } + want := frontend.ErrBackendClosed + if mode == "fence" { + b.mu.Lock() + b.chunkFenced = func() bool { return true } + b.mu.Unlock() + b.SetOperational(false, "fenced") + want = frontend.ErrStalePrimary + } else if err := b.Close(); err != nil { + t.Fatal(err) + } + release() + select { + case err := <-done: + if !errors.Is(err, want) { + t.Fatalf("Close wake error=%v", err) + } + case <-time.After(time.Second): + t.Fatal("Close did not wake registered read") + } + }) + } +} + +type readinessProjection frontend.Projection + +func (p readinessProjection) Projection() frontend.Projection { return frontend.Projection(p) } + +func TestAttachReadinessTimeoutPreservesStaleLineage(t *testing.T) { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + b := &StorageBackend{id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 2, EndpointVersion: 1, Healthy: true}} + b.setChunkAttachPending("pending") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + b.testBeforeReadReadyWait = func() { b.SetOperational(true, "attached under another epoch"); cancel() } + _, err := b.Read(ctx, 0, make([]byte, 4096)) + if !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("timeout lost stale lineage: %v", err) + } +} + +func TestAttachReadinessPublicationRetriesAdmission(t *testing.T) { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + b := &StorageBackend{id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}} + b.setChunkAttachPending("pending") + b.testAfterAttachRefusal = func() { b.SetOperational(true, "attached") } + if _, err := b.Read(context.Background(), 0, nil); err != nil { + t.Fatalf("readiness publication returned the old refusal: %v", err) + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 30e3c05bbd..83545e2a54 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -146,6 +146,13 @@ const maxFullBlockBatchBlocks = 64 // StorageBackend adapts a LogicalStorage into frontend.Backend. type StorageBackend struct { + // testBeforeIOLock, test-only, runs in admit after the readiness check, + // right before the I/O lock (an arrival handshake for queued I/O). + testBeforeIOLock func() + // Runs outside locks after a read registers its readiness notification. + testBeforeReadReadyWait func() + testAfterAttachRefusal func() + storage storage.LogicalStorage view frontend.ProjectionView id frontend.Identity @@ -155,8 +162,12 @@ type StorageBackend struct { // false; provider flips true after Recover() succeeds (T3b). // opEvidence is the reason reported when operational=false // (e.g., "awaiting recovery", "local epoch ahead of assignment"). - operational atomic.Bool - opEvidence atomic.Value // string + // Only a successfully recovered chunk volume awaiting attachment may wait. + // waitAttachReady and readyChanged are protected by mu. + waitAttachReady bool + readyChanged chan struct{} + operational atomic.Bool + opEvidence atomic.Value // string // ioMu is the I/O admission boundary: every Read, Write and Sync holds // its read side for the whole operation, gate included, so StopIO can @@ -284,6 +295,13 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus if c, ok := b.storage.(interface{ HolesSuspected() uint64 }); ok { holes = c.HolesSuspected() } + var checkpoint *storage.CheckpointPersistenceStatus + if reporter, ok := b.storage.(interface { + CheckpointPersistence() storage.CheckpointPersistenceStatus + }); ok { + snapshot := reporter.CheckpointPersistence() + checkpoint = &snapshot + } writeProfile := b.WriteProfile() if instrumented, ok := b.storage.(storage.WriteInstrumented); ok { storageProfile := instrumented.WriteInstrumentation() @@ -312,23 +330,24 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus writeProfile.DirtyMapUpdateDurationNanos = storageProfile.DirtyMapUpdateDurationNanos } return VolumeStatus{ - Warnings: warnings, - HolesSuspected: holes, - VolumeID: volumeID, - Path: path, - Impl: impl, - ReplicaID: id.ReplicaID, - Epoch: id.Epoch, - EndpointVersion: id.EndpointVersion, - Latched: id.Epoch > 0 && id.EndpointVersion > 0, - Operational: b.operational.Load(), - FrontierKnown: true, - DurableLSN: durableLSN, - RetainedLSN: retainedLSN, - HeadLSN: headLSN, - Evidence: evidence, - Closed: closed, - WriteProfile: writeProfile, + Warnings: warnings, + HolesSuspected: holes, + VolumeID: volumeID, + Path: path, + Impl: impl, + ReplicaID: id.ReplicaID, + Epoch: id.Epoch, + EndpointVersion: id.EndpointVersion, + Latched: id.Epoch > 0 && id.EndpointVersion > 0, + Operational: b.operational.Load(), + FrontierKnown: true, + DurableLSN: durableLSN, + RetainedLSN: retainedLSN, + HeadLSN: headLSN, + Evidence: evidence, + Closed: closed, + WriteProfile: writeProfile, + CheckpointPersistence: checkpoint, } } @@ -339,6 +358,7 @@ func (b *StorageBackend) Close() error { b.mu.Lock() defer b.mu.Unlock() b.closed = true + b.notifyReadReadyLocked() return nil } @@ -367,12 +387,14 @@ func (b *StorageBackend) SetWriteObserver(obs WriteObserver) error { err = fmt.Errorf("durable: write observer not installed: ship LSN: %w", err) b.mu.Lock() b.observerErr = err + b.notifyReadReadyLocked() b.mu.Unlock() return err } } b.mu.Lock() b.observer, b.observerErr = obs, nil + b.notifyReadReadyLocked() b.mu.Unlock() return nil } @@ -397,6 +419,7 @@ func (b *StorageBackend) seedAndRebase(seed func() error) error { err = fmt.Errorf("durable: write observer ship LSN after the frontier seed: %w", err) b.mu.Lock() b.observerErr = err + b.notifyReadReadyLocked() b.mu.Unlock() return err } @@ -440,8 +463,12 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) { evidence = "not operational" } } + b.mu.Lock() b.opEvidence.Store(evidence) b.operational.Store(ok) + b.waitAttachReady = false + b.notifyReadReadyLocked() + b.mu.Unlock() } // StopIO makes the backend refuse every new Read, Write and Sync with @@ -527,7 +554,9 @@ func (b *StorageBackend) Sync(ctx context.Context) error { // Read copies up to len(p) bytes starting at offset. Reads past // end-of-volume return zero bytes (no error). Every read is gated. func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, error) { - release, err := b.admit() + ctx, cancel := frontend.WithReadBudget(ctx, time.Time{}) + defer cancel() + release, err := b.admitAfterAttach(ctx) if err != nil { return 0, err } @@ -535,7 +564,104 @@ func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, if len(p) == 0 { return 0, nil } - return b.readBytes(offset, p) + if ctx.Err() != nil { + return 0, b.attachReadyTimeout(ctx.Err()) + } + n, err := b.readBytes(ctx, offset, p) + if hydrationPendingOnly(err) { + if gateErr := b.gate(); gateErr != nil { + return 0, gateErr + } + return n, fmt.Errorf("%w: %w", frontend.ErrBackendBusy, err) + } + return n, err +} + +// setChunkAttachPending is used only after successful local recovery. +func (b *StorageBackend) setChunkAttachPending(evidence string) { + b.mu.Lock() + b.opEvidence.Store(evidence) + b.operational.Store(false) + b.waitAttachReady = true + b.notifyReadReadyLocked() + b.mu.Unlock() +} + +func (b *StorageBackend) admitAfterAttach(ctx context.Context) (func(), error) { + release, err := b.admit() + if !errors.Is(err, frontend.ErrNotReady) { + return release, err + } + if hook := b.testAfterAttachRefusal; hook != nil { + hook() + } + b.mu.Lock() + pending := b.waitAttachReady + b.mu.Unlock() + if !pending { + // Readiness may have published after the initial refusal. + return b.admit() + } + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + return b.awaitAttachAdmission(ctx) +} + +// notifyReadReadyLocked wakes waiting I/O without making them hold ioMu while +// the provider is attaching or draining the backend. Caller holds mu. +func (b *StorageBackend) notifyReadReadyLocked() { + if b.readyChanged != nil { + close(b.readyChanged) + b.readyChanged = nil + } +} + +// awaitAttachAdmission waits only after a gate refusal, before any storage I/O. +// The three-second readiness allowance is capped by an earlier caller deadline. +func (b *StorageBackend) awaitAttachAdmission(ctx context.Context) (func(), error) { + for { + b.mu.Lock() + if b.readyChanged == nil { + b.readyChanged = make(chan struct{}) + } + changed := b.readyChanged + terminal := b.closed || b.observerErr != nil || !b.waitAttachReady + b.mu.Unlock() + if err := ctx.Err(); err != nil { + return nil, b.attachReadyTimeout(err) + } + release, err := b.admit() + if err == nil { + if cause := ctx.Err(); cause != nil { + release() + return nil, b.attachReadyTimeout(cause) + } + return release, nil + } + if !errors.Is(err, frontend.ErrNotReady) || terminal || b.operational.Load() { + return release, err + } + if hook := b.testBeforeReadReadyWait; hook != nil { + hook() + } + select { + case <-changed: + case <-ctx.Done(): + return nil, b.attachReadyTimeout(ctx.Err()) + } + } +} + +func (b *StorageBackend) attachReadyTimeout(cause error) error { + // A concurrent Close, fence or observer failure must retain its gate error. + err := b.gate() + b.mu.Lock() + observerFailed := b.observerErr != nil + b.mu.Unlock() + if err != nil && (!errors.Is(err, frontend.ErrNotReady) || observerFailed) { + return err + } + return fmt.Errorf("%w: %w: chunk attachment readiness: %w", frontend.ErrNotReady, frontend.ErrBackendBusy, cause) } // Write persists up to len(p) bytes at offset. Partial-block @@ -543,9 +669,11 @@ func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, // overlay the partial range, write the full block back. // Every write is gated. func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int, error) { + ctx, cancel := frontend.WithWriteBudget(ctx, time.Time{}) + defer cancel() iolatency.BackendEnter(ctx) defer iolatency.BackendExit(ctx) - release, err := b.admit() + release, err := b.admitAfterAttach(ctx) if err != nil { log.Printf("durable: StorageBackend.Write gate-rejected offset=%d: %v", offset, err) return 0, err @@ -554,9 +682,20 @@ func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int if len(p) == 0 { return 0, nil } + if ctx.Err() != nil { + return 0, b.attachReadyTimeout(ctx.Err()) + } b.profile.recordBackendWriteRequest(len(p)) start := time.Now() n, err := b.writeBytes(ctx, offset, p) + if hydrationPendingOnly(err) { + if gateErr := b.gate(); gateErr != nil { + err = gateErr + } + } + if errors.Is(err, storage.ErrWALPressureTimeout) || hydrationPendingOnly(err) { + err = fmt.Errorf("%w: %w", frontend.ErrBackendBusy, err) + } if n > 0 { b.profile.recordBackendWrite(n, time.Since(start)) } @@ -582,6 +721,9 @@ func (b *StorageBackend) admit() (func(), error) { if err := b.readyCheck(); err != nil { return nil, err } + if hook := b.testBeforeIOLock; hook != nil { + hook() + } b.ioMu.RLock() if err := b.gate(); err != nil { b.ioMu.RUnlock() @@ -644,6 +786,54 @@ func (b *StorageBackend) lineageCheck() error { return nil } +// readStorageBlock shares the request deadline across blocks and partial-write +// RMW. Legacy engines may still perform contextless local I/O (#221). +func (b *StorageBackend) readStorageBlock(ctx context.Context, lba uint32) ([]byte, error) { + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("%w: %w", storage.ErrChunkHydrationPending, err) + } + var data []byte + var err error + if r, ok := b.storage.(storage.ContextReader); ok { + data, err = r.ReadContext(ctx, lba) + } else { + data, err = b.storage.Read(lba) + } + if err != nil { + return nil, err + } // a known substrate failure wins expiry + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("%w: %w", storage.ErrChunkHydrationPending, err) + } + return data, nil +} + +func hydrationPendingOnly(err error) bool { + return errors.Is(err, storage.ErrChunkHydrationPending) && hydrationPendingCauseOnly(err) +} + +func hydrationPendingCauseOnly(err error) bool { + if err == storage.ErrChunkHydrationPending || err == context.DeadlineExceeded || err == context.Canceled { + return true + } + if err == nil { + return false + } + if j, ok := err.(interface{ Unwrap() []error }); ok { + causes := j.Unwrap() + if len(causes) == 0 { + return false + } + for _, cause := range causes { + if !hydrationPendingCauseOnly(cause) { + return false + } + } + return true + } + return hydrationPendingCauseOnly(errors.Unwrap(err)) +} + // readBytes performs the byte-range → LBA-range fanout for Read. // Reads block-at-a-time, copying the sub-slice covered by the // current byte range. Handles three cases: @@ -651,7 +841,7 @@ func (b *StorageBackend) lineageCheck() error { // - offset aligned, len >= block: copy full block, advance. // - offset misaligned: copy tail of first block only. // - final block, len < available: copy prefix only. -func (b *StorageBackend) readBytes(offset int64, p []byte) (int, error) { +func (b *StorageBackend) readBytes(ctx context.Context, offset int64, p []byte) (int, error) { if offset < 0 { return 0, errInvalidOffset } @@ -661,7 +851,7 @@ func (b *StorageBackend) readBytes(offset int64, p []byte) (int, error) { pos := offset for len(buf) > 0 { lba := uint32(pos / bs) - block, err := b.storage.Read(lba) + block, err := b.readStorageBlock(ctx, lba) if err != nil { return total, fmt.Errorf("durable: read lba=%d: %w", lba, err) } @@ -738,7 +928,7 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte) block = buf[:chunkLen] } else { // Partial-block: RMW. - existing, err := b.storage.Read(lba) + existing, err := b.readStorageBlock(ctx, lba) if err != nil { writeLock.Unlock() return total, fmt.Errorf("durable: RMW read lba=%d: %w", lba, err) @@ -752,7 +942,13 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte) return total, fmt.Errorf("%w: no write observer installed", ErrReplicationAckUnavailable) } - lsn, err := b.storage.Write(lba, block) + var lsn uint64 + var err error + if writer, ok := b.storage.(storage.ContextWriter); ok { + lsn, err = writer.WriteContext(ctx, lba, block) + } else if err = expiredCommand(ctx); err == nil { + lsn, err = b.storage.Write(lba, block) + } writeLock.Unlock() if err != nil { return total, fmt.Errorf("durable: write lba=%d: %w", lba, err) @@ -788,7 +984,13 @@ func (b *StorageBackend) writeFullBlockBatch(ctx context.Context, startLBA uint3 blocks[i] = p[i*bs : (i+1)*bs] } unlock := b.lockLBARange(startLBA, blockCount) - lsns, err := batcher.WriteBatch(startLBA, blocks) + var lsns []uint64 + var err error + if writer, ok := batcher.(storage.ContextWriteBatcher); ok { + lsns, err = writer.WriteBatchContext(ctx, startLBA, blocks) + } else if err = expiredCommand(ctx); err == nil { + lsns, err = batcher.WriteBatch(startLBA, blocks) + } unlock() if len(lsns) > 0 { b.profile.recordBackendStorageWrite(len(lsns), true) @@ -799,14 +1001,14 @@ func (b *StorageBackend) writeFullBlockBatch(ctx context.Context, startLBA uint3 log.Printf("durable: replication batch fan-out failed lba=%d blocks=%d: %v", startLBA, len(lsns), obsErr) if policy == WriteAckRequireObserverAck { - return len(lsns) * bs, fmt.Errorf("%w: %w", ErrReplicationAckUnavailable, obsErr) + return len(lsns) * bs, replicationWriteError(ctx, withStorageCause(startLBA, blockCount, err, obsErr)) } } } else { for i, lsn := range lsns { block := blocks[i] lba := startLBA + uint32(i) - if obsErr := b.observeWrite(ctx, lba, lsn, block, obs, policy); obsErr != nil { + if obsErr := b.observeWriteCause(ctx, lba, lsn, block, obs, policy, withStorageCause(startLBA, blockCount, err, nil)); obsErr != nil { return (i + 1) * bs, obsErr } } @@ -842,6 +1044,13 @@ func (b *StorageBackend) lockLBARange(startLBA uint32, blockCount int) func() { } func (b *StorageBackend) observeWrite(ctx context.Context, lba uint32, lsn uint64, block []byte, obs WriteObserver, policy WriteAckPolicy) error { + return b.observeWriteCause(ctx, lba, lsn, block, obs, policy, nil) +} + +// observeWriteCause is observeWrite with the storage failure of the same +// command (nil if none): a required observer's error is classified together +// with it, so a physical storage fault is never reclassified as retryable. +func (b *StorageBackend) observeWriteCause(ctx context.Context, lba uint32, lsn uint64, block []byte, obs WriteObserver, policy WriteAckPolicy, storageErr error) error { // Replication fan-out (T4a-6 hook). Error is logged best-effort // unless the ack policy requires observer acknowledgement. if obs == nil { @@ -851,12 +1060,53 @@ func (b *StorageBackend) observeWrite(ctx context.Context, lba uint32, lsn uint6 log.Printf("durable: replication fan-out failed lba=%d lsn=%d: %v", lba, lsn, werr) if policy == WriteAckRequireObserverAck { - return fmt.Errorf("%w: %w", ErrReplicationAckUnavailable, werr) + if storageErr != nil { + werr = errors.Join(storageErr, werr) + } + return replicationWriteError(ctx, werr) } } return nil } +// withStorageCause joins a batch's storage error (nil if none) with an +// observer error, so the classifier sees the complete error set (#252): +// a committed prefix may come back together with a physical failure. +func withStorageCause(startLBA uint32, blockCount int, storageErr, obsErr error) error { + if storageErr == nil { + return obsErr + } + se := fmt.Errorf("durable: write batch lba=%d blocks=%d: %w", startLBA, blockCount, storageErr) + if obsErr == nil { + return se + } + return errors.Join(se, obsErr) +} + +// Classify the observer cause before adding the acknowledgement sentinel; +// otherwise that sentinel would obscure a pure caller deadline at the target. +func replicationWriteError(ctx context.Context, err error) error { + wrapped := fmt.Errorf("%w: %w", ErrReplicationAckUnavailable, err) + if frontend.IsWriteDeadline(ctx, err) { + return fmt.Errorf("%w: %w", frontend.ErrBackendBusy, wrapped) + } + return wrapped +} + // Compile-time check that StorageBackend satisfies frontend.Backend. // Catches interface drift at build time rather than runtime. var _ frontend.Backend = (*StorageBackend)(nil) + +// expiredCommand refuses a fresh mutation through a contextless storage +// fallback once the command is already expired or cancelled (#252); a pure +// deadline is retryable busy, as on the context-aware path. +func expiredCommand(ctx context.Context) error { + err := ctx.Err() + if err == nil { + return nil + } + if frontend.IsWriteDeadline(ctx, err) { + return fmt.Errorf("%w: %w", frontend.ErrBackendBusy, err) + } + return err +} diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go new file mode 100644 index 0000000000..e2278f7b30 --- /dev/null +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -0,0 +1,183 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// External observers see the committed takeover HEAD while attachment is +// held in the provider-owned worker, without a separate test goroutine. +type heldTakeoverClaim struct { + storage.ChunkRemote + claimed chan struct{} + release chan struct{} + once, releaseOnce sync.Once + holdFor time.Duration + readRegistered chan struct{} +} + +func (r *heldTakeoverClaim) unblock() { r.releaseOnce.Do(func() { close(r.release) }) } +func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + gen, err := r.ChunkRemote.CASHead(ctx, expected, next) + if err != nil || next.Epoch != 4 { + return gen, err + } + r.once.Do(func() { close(r.claimed) }) + var expired <-chan time.Time + if r.holdFor > 0 { + select { + case <-r.readRegistered: + case <-r.release: + return gen, nil + case <-ctx.Done(): + return gen, ctx.Err() + } + timer := time.NewTimer(r.holdFor) + defer timer.Stop() + expired = timer.C + } + select { + case <-r.release: + return gen, nil + case <-expired: + return gen, nil + case <-ctx.Done(): + return gen, ctx.Err() + } +} + +func pendingTakeoverRead(t *testing.T, hold time.Duration) (*durable.DurableProvider, frontend.Backend, *nvme.IOHandler) { + t.Helper() + remote := &heldTakeoverClaim{ChunkRemote: seededRemote(t), claimed: make(chan struct{}), release: make(chan struct{}), holdFor: hold, readRegistered: make(chan struct{})} + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + p := chunkProvider(t, t.TempDir(), remote, view, 0) + // Registered after provider cleanup, so release precedes its worker join. + t.Cleanup(remote.unblock) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) + select { + case <-remote.claimed: + case <-time.After(10 * time.Second): + t.Fatal("takeover CAS never became visible") + } + head, err := remote.GetHead(context.Background()) + if err != nil || head.Epoch != 4 || head.Holder != "r1" { + t.Fatalf("takeover HEAD: %+v, %v", head, err) + } + backend, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + var firstWait sync.Once + durable.SetTestBeforeAttachWait(backend, func() { firstWait.Do(func() { close(remote.readRegistered) }) }) + handler := nvme.NewIOHandler(nvme.HandlerConfig{Backend: backend, BlockSize: 4096, VolumeSize: pcBlocks * 4096, NSID: 1}) + return p, backend, handler +} + +// Model Linux max_retries=5 and CRD=0: at most six attempts, no sleeps. +// A status-only fix exhausts them during attachment and becomes guest EIO. +func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { + _, _, handler := pendingTakeoverRead(t, 2500*time.Millisecond) + command := nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1} + start := time.Now() + for attempt := 0; attempt <= 5; attempt++ { + result := handler.Handle(context.Background(), command) + if result.AsError() == nil { + if !bytes.Equal(result.Data, block(0x33)) { + t.Fatal("guest read returned incorrect HEAD bytes") + } + if elapsed := time.Since(start); elapsed >= 5*time.Second { + t.Fatalf("guest read took %s", elapsed) + } + t.Logf("guest read succeeded on attempt%d after%s (max5 immediate retries)", attempt+1, time.Since(start)) + return + } + if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady { + t.Fatalf("guest read terminal status: %v", result.AsError()) + } + } + t.Fatal("guest EIO: all six immediate attempts exhausted before chunk attach") +} + +func TestWALStoreChunk_PendingReadWaitIsBounded(t *testing.T) { + _, _, handler := pendingTakeoverRead(t, 0) + start := time.Now() + result := handler.Handle(context.Background(), nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1}) + elapsed := time.Since(start) + if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { + t.Fatalf("pending read result: %+v", result) + } + if elapsed < 2500*time.Millisecond || elapsed >= 5*time.Second { + t.Fatalf("pending read wait=%s; want bounded readiness wait below5s", elapsed) + } +} + +func TestWALStoreChunk_PendingReadHonoursEarlierDeadline(t *testing.T) { + _, backend, _ := pendingTakeoverRead(t, 0) + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) + defer cancel() + start := time.Now() + n, err := backend.Read(ctx, 33*4096, make([]byte, 4096)) + if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("deadline read: n=%d err=%v", n, err) + } + if time.Since(start) >= time.Second { + t.Fatal("read ignored earlier deadline") + } +} + +func TestWALStoreChunk_TakeoverWriteWaitsForAttach(t *testing.T) { + _, backend, _ := pendingTakeoverRead(t, 2500*time.Millisecond) + start := time.Now() + n, err := backend.Write(context.Background(), 33*4096, block(0x74)) + if err != nil || n != 4096 { + t.Fatalf("pending write: n=%d err=%v", n, err) + } + if elapsed := time.Since(start); elapsed >= 5*time.Second { + t.Fatalf("write waited %s", elapsed) + } + got := make([]byte, 4096) + if n, err := backend.Read(context.Background(), 33*4096, got); err != nil || n != 4096 || !bytes.Equal(got, block(0x74)) { + t.Fatalf("attached write readback: n=%d err=%v", n, err) + } +} + +func TestWALStoreChunk_PendingWriteHonoursEarlierDeadline(t *testing.T) { + _, backend, _ := pendingTakeoverRead(t, 0) + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) + defer cancel() + n, err := backend.Write(ctx, 33*4096, block(0x74)) + if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("pending write deadline: n=%d err=%v", n, err) + } +} + +func TestWALStoreChunk_PendingAttachBeyondHostRetryBudget(t *testing.T) { + _, _, handler := pendingTakeoverRead(t, 0) + for attempt := 0; attempt <= 5; attempt++ { + start := time.Now() + result := handler.Handle(context.Background(), nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1}) + if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { + t.Fatalf("attempt%d exposed data or terminal status: %+v", attempt, result) + } + if elapsed := time.Since(start); elapsed < 2500*time.Millisecond || elapsed >= 5*time.Second { + t.Fatalf("attempt%d wait=%s", attempt, elapsed) + } + } + // A permanently unavailable backend still exhausts a finite host retry policy; + // this control promises retryable completions and no bytes, not infinite availability. +} diff --git a/seaweed-block/core/frontend/durable/volume_size_admission_test.go b/seaweed-block/core/frontend/durable/volume_size_admission_test.go new file mode 100644 index 0000000000..5120e2951b --- /dev/null +++ b/seaweed-block/core/frontend/durable/volume_size_admission_test.go @@ -0,0 +1,39 @@ +package durable_test + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestProviderCreateCapacityPrecedesFreshMarker(t *testing.T) { + root := t.TempDir() + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: ^uint32(0), BlockSize: 8192, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }}, newStubView(healthyProj(id))) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + // A blocked marker path prevents a giant allocation even without admission. + parent := filepath.Join(root, "v1.bin.chunkfresh") + if err := os.Mkdir(parent, 0700); err != nil { + t.Fatal(err) + } + _, err = p.Open(context.Background(), "v1") + if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("want capacity before marker, got %v", err) + } + entries, err := os.ReadDir(root) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Name() != "v1.bin.chunkfresh" { + t.Fatalf("refused create wrote files: %v", entries) + } +} diff --git a/seaweed-block/core/frontend/durable/write_command_budget_p1_test.go b/seaweed-block/core/frontend/durable/write_command_budget_p1_test.go new file mode 100644 index 0000000000..e529b86102 --- /dev/null +++ b/seaweed-block/core/frontend/durable/write_command_budget_p1_test.go @@ -0,0 +1,76 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// partialFaultStore commits the first block of a batch and returns that prefix +// together with a physical error (the shape parallelwal and smartwal return), +// after the command's deadline has passed. +type partialFaultStore struct { + storage.LogicalStorage + fault error +} + +func (s *partialFaultStore) WriteBatch(lba uint32, blocks [][]byte) ([]uint64, error) { + lsn, err := s.LogicalStorage.Write(lba, blocks[0]) + if err != nil { + return nil, err + } + return []uint64{lsn}, s.fault +} +func (s *partialFaultStore) WriteBatchContext(ctx context.Context, lba uint32, blocks [][]byte) ([]uint64, error) { + <-ctx.Done() + return s.WriteBatch(lba, blocks) +} + +// #252 P1-3: a committed prefix plus a physical storage error, then a required +// batch observer that reports a pure expired deadline: the physical fault must +// stay in the error (terminal), never be reclassified as retryable busy. +func TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline(t *testing.T) { + for _, batchObserver := range []bool{true, false} { + name := map[bool]string{true: "batch-observer", false: "per-block-observer"}[batchObserver] + t.Run(name, func(t *testing.T) { + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} + physical := errors.New("injected physical WAL append failure") + s := &partialFaultStore{LogicalStorage: storage.NewBlockStore(8, 4096), fault: physical} + b := durable.NewStorageBackend(s, newStubView(healthyProj(id)), id) + b.SetOperational(true, "test") + deadlineOnly := func(ctx context.Context) error { return ctx.Err() } + obs := writeObserverFunc{observe: func(ctx context.Context, _ uint32, _ uint64, _ []byte) error { return deadlineOnly(ctx) }} + if batchObserver { + b.SetWriteObserver(batchWriteObserverFunc{writeObserverFunc: obs, observeBatch: func(ctx context.Context, _ uint32, _ []uint64, _ [][]byte) error { return deadlineOnly(ctx) }}) + } else { + b.SetWriteObserver(obs) + b.SetWriteAckPolicy(durable.WriteAckBestEffort) // the per-block path is taken without a batch observer only off the required policy + } + if batchObserver { + b.SetWriteAckPolicy(durable.WriteAckRequireObserverAck) + } + ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) + defer cancel() + data := append(bytes.Repeat([]byte{0xA1}, 4096), bytes.Repeat([]byte{0xB2}, 4096)...) + n, err := b.Write(ctx, 0, data) + if n != 4096 { + t.Fatalf("committed bytes %d, want exactly the 4096-byte prefix (err %v)", n, err) + } + if !errors.Is(err, physical) { + t.Fatalf("physical storage fault lost: %v", err) + } + if errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("physical storage fault reclassified as retryable busy: %v", err) + } + if batchObserver && !errors.Is(err, durable.ErrReplicationAckUnavailable) { + t.Fatalf("required observer failure lost its ACK identity: %v", err) + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/write_command_budget_test.go b/seaweed-block/core/frontend/durable/write_command_budget_test.go new file mode 100644 index 0000000000..2f41b94c62 --- /dev/null +++ b/seaweed-block/core/frontend/durable/write_command_budget_test.go @@ -0,0 +1,143 @@ +package durable_test + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type deadlineStorage struct { + storage.LogicalStorage + deadlines []time.Time + legacyCalls int +} + +func (s *deadlineStorage) Write(lba uint32, p []byte) (uint64, error) { + s.legacyCalls++ + return s.LogicalStorage.Write(lba, p) +} +func (s *deadlineStorage) WriteBatch(lba uint32, blocks [][]byte) ([]uint64, error) { + s.legacyCalls++ + return nil, errors.New("contextless batch called") +} +func (s *deadlineStorage) WriteContext(ctx context.Context, lba uint32, p []byte) (uint64, error) { + deadline, _ := ctx.Deadline() + s.deadlines = append(s.deadlines, deadline) + return s.LogicalStorage.Write(lba, p) +} +func (s *deadlineStorage) WriteBatchContext(ctx context.Context, lba uint32, blocks [][]byte) ([]uint64, error) { + deadline, _ := ctx.Deadline() + s.deadlines = append(s.deadlines, deadline) + var lsns []uint64 + for i, p := range blocks { + lsn, err := s.LogicalStorage.Write(lba+uint32(i), p) + if err != nil { + return lsns, err + } + lsns = append(lsns, lsn) + } + return lsns, nil +} +func TestStorageBackendWriteKeepsOneDeadlineAcrossBatches(t *testing.T) { + _, view, base := newTestBackend(t, logicalStorageFactories()[0], 160, 4096) + wrapped := &deadlineStorage{LogicalStorage: base} + b := durable.NewStorageBackend(wrapped, view, frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}) + b.SetOperational(true, "test") + want := time.Now().Add(2 * time.Second) + ctx, cancel := context.WithDeadline(context.Background(), want) + defer cancel() + if n, err := b.Write(ctx, 0, make([]byte, 130*4096)); err != nil || n != 130*4096 { + t.Fatalf("write %d %v", n, err) + } + if _, err := b.Write(ctx, 130*4096, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + if wrapped.legacyCalls != 0 || len(wrapped.deadlines) != 4 { + t.Fatalf("dispatch legacy=%d deadlines=%v", wrapped.legacyCalls, wrapped.deadlines) + } + for _, got := range wrapped.deadlines { + if !got.Equal(want) { + t.Fatalf("deadline reset %v want%v", got, want) + } + } +} +func TestStorageBackendExpiredWriteDoesNotAppend(t *testing.T) { + b, _, s := newTestBackend(t, logicalStorageFactories()[0], 16, 4096) + before := s.NextLSN() + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + for _, size := range []int{4096, 8192} { + n, err := b.Write(ctx, 0, make([]byte, size)) + if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || s.NextLSN() != before { + t.Fatalf("expired write n=%d err=%v next=%d", n, err, s.NextLSN()) + } + } +} + +type deadlineAckStore struct{ storage.LogicalStorage } + +func (s *deadlineAckStore) WriteContext(ctx context.Context, lba uint32, p []byte) (uint64, error) { + <-ctx.Done() + return s.LogicalStorage.Write(lba, p) +} +func (s *deadlineAckStore) WriteBatch(lba uint32, blocks [][]byte) ([]uint64, error) { + var lsns []uint64 + for i, p := range blocks { + lsn, err := s.LogicalStorage.Write(lba+uint32(i), p) + if err != nil { + return lsns, err + } + lsns = append(lsns, lsn) + } + return lsns, nil +} +func (s *deadlineAckStore) WriteBatchContext(ctx context.Context, lba uint32, blocks [][]byte) ([]uint64, error) { + <-ctx.Done() + return s.WriteBatch(lba, blocks) +} +func TestStorageBackendRequiredObserverDeadlineStaysRetryable(t *testing.T) { + for _, batch := range []bool{false, true} { + for _, physical := range []bool{false, true} { + t.Run(fmt.Sprintf("batch=%t/physical=%t", batch, physical), func(t *testing.T) { + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} + s := &deadlineAckStore{storage.NewBlockStore(8, 4096)} + b := durable.NewStorageBackend(s, newStubView(healthyProj(id)), id) + b.SetOperational(true, "test") + injected := errors.New("physical observer failure") + outcome := func(ctx context.Context) error { + if physical { + return errors.Join(injected, ctx.Err()) + } + return fmt.Errorf("ack wait: %w", ctx.Err()) + } + b.SetWriteObserver(batchWriteObserverFunc{writeObserverFunc: writeObserverFunc{observe: func(ctx context.Context, _ uint32, _ uint64, _ []byte) error { return outcome(ctx) }}, observeBatch: func(ctx context.Context, _ uint32, _ []uint64, _ [][]byte) error { return outcome(ctx) }}) + b.SetWriteAckPolicy(durable.WriteAckRequireObserverAck) + ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) + defer cancel() + size := 4096 + if batch { + size *= 2 + } + n, err := b.Write(ctx, 0, make([]byte, size)) + if n != size || !errors.Is(err, durable.ErrReplicationAckUnavailable) { + t.Fatalf("committed error n=%d err=%v", n, err) + } + if physical { + if !errors.Is(err, injected) || errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("physical fault masked: %v", err) + } + } else { + if !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("observer deadline lost retryability: %v", err) + } + } + }) + } + } +} diff --git a/seaweed-block/core/frontend/errors.go b/seaweed-block/core/frontend/errors.go index a3d390ca2f..84691012a8 100644 --- a/seaweed-block/core/frontend/errors.go +++ b/seaweed-block/core/frontend/errors.go @@ -9,9 +9,14 @@ import "errors" var ErrStalePrimary = errors.New("frontend: stale primary lineage") // ErrNotReady is returned by Provider.Open when the projection -// never reports healthy before the context deadline. +// never reports healthy before the context deadline, and by a Backend +// while local recovery or chunk attachment is not yet operational. var ErrNotReady = errors.New("frontend: volume not ready") // ErrBackendClosed is returned by Backend.Read / Backend.Write // after Backend.Close has been invoked. var ErrBackendClosed = errors.New("frontend: backend closed") + +// ErrBackendBusy is a transient local admission timeout. Retry may succeed; +// it must not be used for a sticky persistence or integrity fault. +var ErrBackendBusy = errors.New("frontend: backend temporarily busy") diff --git a/seaweed-block/core/frontend/nvme/flush_error_log_test.go b/seaweed-block/core/frontend/nvme/flush_error_log_test.go new file mode 100644 index 0000000000..a83c59a90b --- /dev/null +++ b/seaweed-block/core/frontend/nvme/flush_error_log_test.go @@ -0,0 +1,51 @@ +package nvme + +import ( + "bytes" + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" + "log" + "strings" + "testing" +) + +type flushErrorBackend struct { + frontend.Backend + syncErr error +} + +func (b *flushErrorBackend) Sync(context.Context) error { return b.syncErr } + +func TestSessionFlushLogsBackendReason(t *testing.T) { + var logs bytes.Buffer + b := &flushErrorBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), syncErr: errors.New("injected Sync failure: extent EIO")} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), logger: log.New(&logs, "", 0), qid: 7, respCh: make(chan *response, 1), done: make(chan struct{})} + req := &Request{} + req.capsule.OpCode = ioFlush + req.capsule.NSID = 1 + s.dispatchIO(context.Background(), req) + resp := <-s.respCh + if resp.resp.Status != MakeStatusField(SCTGeneric, SCInternalError, true) { + t.Fatalf("status=%#x", resp.resp.Status) + } + for _, want := range []string{"Flush failed", "qid=7", "nsid=1", "backend error on flush: injected Sync failure: extent EIO"} { + if !strings.Contains(logs.String(), want) { + t.Fatalf("log %q missing %q", logs.String(), want) + } + } + if strings.Count(logs.String(), "Flush failed") != 1 { + t.Fatalf("duplicate failure log: %q", logs.String()) + } + logs.Reset() + b.syncErr = nil + s.dispatchIO(context.Background(), &Request{capsule: req.capsule}) + resp = <-s.respCh + if resp.resp.Status != 0 { + t.Fatalf("success status=%#x", resp.resp.Status) + } + if logs.Len() != 0 { + t.Fatalf("successful Flush logged a failure: %q", logs.String()) + } +} diff --git a/seaweed-block/core/frontend/nvme/h2c_bounds_test.go b/seaweed-block/core/frontend/nvme/h2c_bounds_test.go new file mode 100644 index 0000000000..136723b53b --- /dev/null +++ b/seaweed-block/core/frontend/nvme/h2c_bounds_test.go @@ -0,0 +1,46 @@ +package nvme + +import ( + "bytes" + "math" + "strings" + "testing" +) + +// Exercise the real TCP framing and receive path, without a socket or backend. +func TestRecvH2CDataRangeBounds(t *testing.T) { + for _, tc := range []struct { + name string + offset uint32 + payload []byte + reject bool + }{ + {"uint32-wrap", math.MaxUint32, []byte{1, 2}, true}, + {"exact-bound", 0, []byte{1, 2, 3, 4}, false}, + {"bound-plus-one", 1, []byte{1, 2, 3, 4}, true}, + } { + t.Run(tc.name, func(t *testing.T) { + var stream bytes.Buffer + w := NewWriter(&stream) + h := H2CDataHeader{DATAO: tc.offset, DATAL: uint32(len(tc.payload))} + if err := w.SendWithData(pduH2CData, 0, &h, h2cDataHdrSize, tc.payload); err != nil { + t.Fatal(err) + } + s := &Session{wire: newTCPPDUTransport(&stream)} + // A panic is a test failure, never an acceptable malformed-input outcome. + defer func() { + if p := recover(); p != nil { + t.Fatalf("invalid range panicked instead of refusing: %v", p) + } + }() + data, err := s.recvH2CData(4) + if tc.reject { + if err == nil || !strings.Contains(err.Error(), "data exceeds expected size") || data != nil { + t.Fatalf("range not refused: data=%v err=%v", data, err) + } + } else if err != nil || !bytes.Equal(data, tc.payload) { + t.Fatalf("exact-bound payload changed: %v %v", data, err) + } + }) + } +} diff --git a/seaweed-block/core/frontend/nvme/io.go b/seaweed-block/core/frontend/nvme/io.go index 929d761db1..437737aa49 100644 --- a/seaweed-block/core/frontend/nvme/io.go +++ b/seaweed-block/core/frontend/nvme/io.go @@ -72,12 +72,15 @@ type IOCommand struct { // idiomatic error use AsError() — nil return means Status // was Success. type IOResult struct { - SCT uint8 - SC uint8 - Data []byte // read payload (nil for writes / errors) - Reason string + SCT uint8 + SC uint8 + Data []byte // read payload (nil for writes / errors) + Reason string + retryable bool // transient pressure or readiness refusal clears wire DNR } +func (r IOResult) completionStatus() uint16 { return MakeStatusField(r.SCT, r.SC, !r.retryable) } + // AsError returns a non-nil *StatusError iff Status != Success. func (r IOResult) AsError() *StatusError { if r.SCT == SCTGeneric && r.SC == SCSuccess { @@ -260,6 +263,8 @@ func (h *IOHandler) read(ctx context.Context, cmd IOCommand) IOResult { } func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult { + ctx, cancel := frontend.WithWriteBudget(ctx, time.Time{}) + defer cancel() if cmd.NLB == 0 { return IOResult{SCT: SCTGeneric, SC: SCInvalidField, Reason: "NLB=0"} } @@ -278,25 +283,38 @@ func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult { start := time.Now() n, err := h.backend.Write(ctx, int64(cmd.SLBA)*int64(h.blockSize), cmd.Data[:expectedBytes]) if err != nil { - return mapBackendError(err, "write") + return mapWriteBudgetError(ctx, err, "write") } if rec, ok := h.backend.(targetWriteRecorder); ok { rec.RecordTargetWrite(n, time.Since(start)) } if cmd.FUA { if err := h.backend.Sync(ctx); err != nil { - return mapBackendError(err, "FUA sync") + return mapWriteBudgetError(ctx, err, "FUA sync") } } return IOResult{SCT: SCTGeneric, SC: SCSuccess} } +// Only a pure command-deadline cause is transient. A joined physical error +// must retain its terminal mapping even when the command deadline also passed. +func mapWriteBudgetError(ctx context.Context, err error, op string) IOResult { + if frontend.IsWriteDeadline(ctx, err) { + return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, retryable: true, Reason: "command deadline on " + op + ": " + err.Error()} + } + return mapBackendError(err, op) +} + // mapBackendError translates frontend errors into NVMe CQE // status tuples. ErrStalePrimary → ANA Transition; -// ErrBackendClosed → ANA Inaccessible; anything else → Internal +// ErrBackendClosed → ANA Inaccessible; ErrNotReady → retryable Namespace +// Not Ready; anything else → Internal // Error (fail-closed; real-backend-specific mapping lands with // T3). func mapBackendError(err error, op string) IOResult { + if errors.Is(err, frontend.ErrBackendBusy) { + return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, Reason: "local admission pressure on " + op + ": " + err.Error(), retryable: true} + } if errors.Is(err, frontend.ErrStalePrimary) { return IOResult{ SCT: SCTPathRelated, @@ -311,6 +329,9 @@ func mapBackendError(err error, op string) IOResult { Reason: "backend closed on " + op, } } + if errors.Is(err, frontend.ErrNotReady) { + return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, Reason: "backend not ready on " + op + ": " + err.Error(), retryable: true} + } return IOResult{ SCT: SCTGeneric, SC: SCInternalError, diff --git a/seaweed-block/core/frontend/nvme/pressure_retry_test.go b/seaweed-block/core/frontend/nvme/pressure_retry_test.go new file mode 100644 index 0000000000..094c26274e --- /dev/null +++ b/seaweed-block/core/frontend/nvme/pressure_retry_test.go @@ -0,0 +1,37 @@ +package nvme + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" + "testing" +) + +type pressureWriteBackend struct { + frontend.Backend + err error +} + +func (b *pressureWriteBackend) Write(context.Context, int64, []byte) (int, error) { return 0, b.err } +func TestSessionPressureTimeoutIsRetryableNamespaceNotReady(t *testing.T) { + b := &pressureWriteBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: frontend.ErrBackendBusy} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), respCh: make(chan *response, 1), done: make(chan struct{})} + for _, busy := range []bool{true, false} { + if !busy { + b.err = errors.New("sticky physical I/O fault") + } + req := &Request{payload: make([]byte, 512)} + req.capsule.OpCode = ioWrite + req.capsule.NSID = 1 + s.handleWrite(context.Background(), req) + resp := <-s.respCh + want := MakeStatusField(SCTGeneric, SCInternalError, true) + if busy { + want = MakeStatusField(SCTGeneric, SCNamespaceNotReady, false) + } + if resp.resp.Status != want { + t.Fatalf("busy=%v wire status=%#x want%#x", busy, resp.resp.Status, want) + } + } +} diff --git a/seaweed-block/core/frontend/nvme/read_command_budget_test.go b/seaweed-block/core/frontend/nvme/read_command_budget_test.go new file mode 100644 index 0000000000..5ff7456770 --- /dev/null +++ b/seaweed-block/core/frontend/nvme/read_command_budget_test.go @@ -0,0 +1,45 @@ +package nvme + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" +) + +type budgetReadBackend struct { + frontend.Backend + deadline time.Time + physical bool +} + +func (b *budgetReadBackend) Read(ctx context.Context, _ int64, p []byte) (int, error) { + b.deadline, _ = ctx.Deadline() + <-ctx.Done() + if b.physical { + return 0, errors.Join(ctx.Err(), errors.New("physical read failure")) + } + return 0, frontend.ErrBackendBusy +} + +func TestSessionReadBudgetIncludesQueueResidence(t *testing.T) { + for _, physical := range []bool{false, true} { + b := &budgetReadBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), physical: physical} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), respCh: make(chan *response, 1), done: make(chan struct{})} + arrival := time.Now().Add(-5 * time.Second) + req := &Request{receivedAt: arrival, dispatchReadyAt: time.Now()} + req.capsule.OpCode, req.capsule.NSID = ioRead, 1 + s.handleRead(context.Background(), req) + resp := <-s.respCh + want := MakeStatusField(SCTGeneric, SCNamespaceNotReady, false) + if physical { + want = MakeStatusField(SCTGeneric, SCInternalError, true) + } + if !b.deadline.Equal(arrival.Add(frontend.ReadCommandBudget)) || resp.resp.Status != want || len(resp.c2hData) != 0 { + t.Fatalf("physical=%t deadline=%v status=%#x data=%d", physical, b.deadline, resp.resp.Status, len(resp.c2hData)) + } + } +} diff --git a/seaweed-block/core/frontend/nvme/read_ready_retry_test.go b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go new file mode 100644 index 0000000000..0b89d1dfad --- /dev/null +++ b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go @@ -0,0 +1,65 @@ +package nvme + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" +) + +type readyReadBackend struct { + frontend.Backend + err error +} + +func (b *readyReadBackend) Read(context.Context, int64, []byte) (int, error) { return 0, b.err } + +func TestSessionReadNotReadyIsRetryable(t *testing.T) { + for _, tc := range []struct { + name string + err error + sct, sc uint8 + dnr bool + }{ + {"attach-pending", fmt.Errorf("awaiting HEAD attach: %w", frontend.ErrNotReady), SCTGeneric, SCNamespaceNotReady, false}, + {"not-ready-closed", errors.Join(frontend.ErrNotReady, frontend.ErrBackendClosed), SCTPathRelated, SCPathAsymAccessInaccessible, true}, + {"not-ready-stale", errors.Join(frontend.ErrNotReady, frontend.ErrStalePrimary), SCTPathRelated, SCPathAsymAccessTransition, true}, + {"physical-fault", errors.New("physical read failure"), SCTGeneric, SCInternalError, true}, + {"closed", frontend.ErrBackendClosed, SCTPathRelated, SCPathAsymAccessInaccessible, true}, + {"stale", frontend.ErrStalePrimary, SCTPathRelated, SCPathAsymAccessTransition, true}, + } { + t.Run(tc.name, func(t *testing.T) { + backend := &readyReadBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: tc.err} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: backend}), respCh: make(chan *response, 1), done: make(chan struct{})} + req := &Request{} + req.capsule.OpCode = ioRead + req.capsule.NSID = 1 + s.handleRead(context.Background(), req) + resp := <-s.respCh + if want := MakeStatusField(tc.sct, tc.sc, tc.dnr); resp.resp.Status != want { + t.Fatalf("wire status=%#x want=%#x", resp.resp.Status, want) + } + }) + } +} + +func TestReadinessRetryDelayIsNotAdvertised(t *testing.T) { + s := &Session{target: &Target{cfg: TargetConfig{VolumeID: "v1"}}, handler: &IOHandler{}, ctrl: &adminController{}, respCh: make(chan *response, 1), done: make(chan struct{})} + controller := s.buildIdentifyController() + for offset := 128; offset < 134; offset++ { + if controller[offset] != 0 { + t.Fatalf("CRDT byte%d=%d; host-policy control assumes no retry delay", offset, controller[offset]) + } + } + req := &Request{} + req.capsule.D10 = 0x16 // Host Behavior Support, including ACRE. + if err := s.handleSetFeatures(req); err != nil { + t.Fatal(err) + } + if got := (<-s.respCh).resp.Status; got != MakeStatusField(SCTGeneric, SCInvalidField, true) { + t.Fatalf("unsupported Host Behavior status=%#x", got) + } +} diff --git a/seaweed-block/core/frontend/nvme/session.go b/seaweed-block/core/frontend/nvme/session.go index 5eb97d4aca..48f76d5210 100644 --- a/seaweed-block/core/frontend/nvme/session.go +++ b/seaweed-block/core/frontend/nvme/session.go @@ -63,6 +63,7 @@ import ( "context" "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend" "io" "net" "sync" @@ -80,7 +81,8 @@ type Request struct { capsule CapsuleCommand payload []byte // inline/R2T-collected data for Write resp CapsuleResponse - c2hData []byte // non-nil for Read/Identify responses + c2hData []byte // non-nil for Read/Identify responses + receivedAt time.Time // capsule arrival, including queued/R2T time dispatchReadyAt time.Time } @@ -266,7 +268,7 @@ func (s *Session) parseCapsule() (*Request, error) { return nil, err } } - req := &Request{capsule: capsule, payload: payload} + req := &Request{capsule: capsule, payload: payload, receivedAt: start} req.resp.CID = capsule.CID if s.qid > 0 && capsule.OpCode == ioWrite { s.recordWriteCapsuleReceiveParse(time.Since(start)) @@ -402,11 +404,12 @@ func (s *Session) recvH2CData(totalBytes uint32) ([]byte, error) { if dataLen == 0 { return nil, fmt.Errorf("recvH2CData: H2CData PDU has no payload") } - if h2c.DATAO+dataLen > totalBytes { + end := uint64(h2c.DATAO) + uint64(dataLen) + if end > uint64(totalBytes) { return nil, fmt.Errorf("recvH2CData: data exceeds expected size (%d+%d > %d)", h2c.DATAO, dataLen, totalBytes) } - if err := s.wire.ReceiveData(buf[h2c.DATAO : h2c.DATAO+dataLen]); err != nil { + if err := s.wire.ReceiveData(buf[uint64(h2c.DATAO):end]); err != nil { return nil, fmt.Errorf("recvH2CData: receive data: %w", err) } s.recordH2CData(dataLen) @@ -469,7 +472,12 @@ func (s *Session) dispatchIO(ctx context.Context, req *Request) { NSID: req.capsule.NSID, }) if res.AsError() != nil { - req.resp.Status = MakeStatusField(res.SCT, res.SC, true) + // CQEs carry status, not the backend's diagnostic. Keep the reason + // at the real session boundary so host fsync EIO can be attributed. + if s.logger != nil { + s.logger.Printf("nvme: Flush failed qid=%d nsid=%d sct=%#x sc=%#x reason=%s", s.qid, req.capsule.NSID, res.SCT, res.SC, res.Reason) + } + req.resp.Status = res.completionStatus() } s.enqueueResponse(&response{resp: req.resp}) default: @@ -566,6 +574,12 @@ func (s *Session) enqueueResponse(resp *response) { // ---------- IO handlers (run in goroutines) ---------- func (s *Session) handleRead(ctx context.Context, req *Request) { + arrival := req.receivedAt + if arrival.IsZero() { + arrival = req.dispatchReadyAt + } + ctx, cancel := frontend.WithReadBudget(ctx, arrival) + defer cancel() s.recordReadCommand() res := s.handler.Handle(ctx, IOCommand{ Opcode: req.capsule.OpCode, @@ -574,7 +588,7 @@ func (s *Session) handleRead(ctx context.Context, req *Request) { NLB: req.capsule.LbaLength(), }) if res.AsError() != nil { - req.resp.Status = MakeStatusField(res.SCT, res.SC, true) + req.resp.Status = res.completionStatus() s.enqueueResponse(&response{resp: req.resp}) return } @@ -582,6 +596,12 @@ func (s *Session) handleRead(ctx context.Context, req *Request) { } func (s *Session) handleWrite(ctx context.Context, req *Request) { + arrival := req.receivedAt + if arrival.IsZero() { + arrival = req.dispatchReadyAt + } + ctx, cancel := frontend.WithWriteBudget(ctx, arrival) + defer cancel() s.recordWriteCommand() s.recordWriteDispatchWait(time.Since(req.dispatchReadyAt)) handlerStart := time.Now() @@ -595,7 +615,7 @@ func (s *Session) handleWrite(ctx context.Context, req *Request) { }) s.recordWriteHandler(time.Since(handlerStart)) if res.AsError() != nil { - req.resp.Status = MakeStatusField(res.SCT, res.SC, true) + req.resp.Status = res.completionStatus() } s.enqueueResponse(&response{resp: req.resp, writeCompletion: true, queuedAt: time.Now()}) } diff --git a/seaweed-block/core/frontend/nvme/write_command_budget_test.go b/seaweed-block/core/frontend/nvme/write_command_budget_test.go new file mode 100644 index 0000000000..71910cc639 --- /dev/null +++ b/seaweed-block/core/frontend/nvme/write_command_budget_test.go @@ -0,0 +1,90 @@ +package nvme + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" +) + +type expiredDispatchBackend struct { + frontend.Backend + deadline time.Time + calls int +} + +func (b *expiredDispatchBackend) Write(ctx context.Context, _ int64, _ []byte) (int, error) { + b.calls++ + b.deadline, _ = ctx.Deadline() + if ctx.Err() == context.DeadlineExceeded { + return 0, frontend.ErrBackendBusy + } + return 512, nil +} +func TestSessionWriteBudgetIncludesDispatchQueue(t *testing.T) { + b := &expiredDispatchBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"})} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), respCh: make(chan *response, 1), done: make(chan struct{})} + arrived := time.Now().Add(-5 * time.Second) + req := &Request{payload: make([]byte, 512), receivedAt: arrived, dispatchReadyAt: time.Now()} + req.capsule.OpCode = ioWrite + req.capsule.NSID = 1 + s.handleWrite(context.Background(), req) + resp := <-s.respCh + if b.calls != 1 || !b.deadline.Equal(arrived.Add(frontend.WriteCommandBudget)) || resp.resp.Status != MakeStatusField(SCTGeneric, SCNamespaceNotReady, false) { + t.Fatalf("deadline=%v status=%#x calls=%d", b.deadline, resp.resp.Status, b.calls) + } +} + +// An already-issued write is joined even if its deadline passes. A subsequent +// FUA wait may return deadline exceeded, but must not turn transient expiry +// into a permanent device error. Physical failures still win. +type joinedBudgetBackend struct { + frontend.Backend + fua, physical bool +} + +func (b *joinedBudgetBackend) result(ctx context.Context) error { + if b.physical { + return errors.Join(errors.New("physical fsync failure"), ctx.Err()) + } + return fmt.Errorf("durability wait: %w", ctx.Err()) +} +func (b *joinedBudgetBackend) Write(ctx context.Context, _ int64, p []byte) (int, error) { + <-ctx.Done() + if b.fua { + return len(p), nil + } + return 0, b.result(ctx) +} +func (b *joinedBudgetBackend) Sync(ctx context.Context) error { return b.result(ctx) } +func TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA(t *testing.T) { + for _, fua := range []bool{false, true} { + for _, physical := range []bool{false, true} { + t.Run(fmt.Sprintf("fua=%t/physical=%t", fua, physical), func(t *testing.T) { + b := &joinedBudgetBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), fua: fua, physical: physical} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), respCh: make(chan *response, 1), done: make(chan struct{})} + ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) + defer cancel() + req := &Request{payload: make([]byte, 512)} + req.capsule.OpCode = ioWrite + req.capsule.NSID = 1 + if fua { + req.capsule.D12 |= 1 << 30 + } + s.handleWrite(ctx, req) + got := (<-s.respCh).resp.Status + want := MakeStatusField(SCTGeneric, SCNamespaceNotReady, false) + if physical { + want = MakeStatusField(SCTGeneric, SCInternalError, true) + } + if got != want { + t.Fatalf("completion=%#x want%#x", got, want) + } + }) + } + } +} diff --git a/seaweed-block/core/frontend/read_budget.go b/seaweed-block/core/frontend/read_budget.go new file mode 100644 index 0000000000..38685a03c4 --- /dev/null +++ b/seaweed-block/core/frontend/read_budget.go @@ -0,0 +1,14 @@ +package frontend + +import ( + "context" + "time" +) + +const ReadCommandBudget = WriteCommandBudget + +// WithReadBudget includes queue residence and all cooperative attachment and +// hydration waits. A previously established, earlier deadline is never reset. +func WithReadBudget(ctx context.Context, arrival time.Time) (context.Context, context.CancelFunc) { + return WithWriteBudget(ctx, arrival) +} diff --git a/seaweed-block/core/frontend/write_budget.go b/seaweed-block/core/frontend/write_budget.go new file mode 100644 index 0000000000..f2c447f5b4 --- /dev/null +++ b/seaweed-block/core/frontend/write_budget.go @@ -0,0 +1,49 @@ +package frontend + +import ( + "context" + "errors" + "time" +) + +const WriteCommandBudget = 4 * time.Second + +// WithWriteBudget preserves an earlier caller deadline, including time spent +// queued before dispatch. A zero arrival denotes a direct backend call. +func WithWriteBudget(ctx context.Context, arrival time.Time) (context.Context, context.CancelFunc) { + if arrival.IsZero() { + arrival = time.Now() + } + deadline := arrival.Add(WriteCommandBudget) + if prior, ok := ctx.Deadline(); ok && !deadline.Before(prior) { + return ctx, func() {} + } + return context.WithDeadline(ctx, deadline) +} + +// IsWriteDeadline recognizes only an expired caller's pure deadline cause. +// Joined physical/unknown errors retain their terminal classification. +func IsWriteDeadline(ctx context.Context, err error) bool { + return ctx.Err() == context.DeadlineExceeded && deadlineCausesOnly(err) +} +func deadlineCausesOnly(err error) bool { + if err == context.DeadlineExceeded { + return true + } + if err == nil { + return false + } + if joined, ok := err.(interface{ Unwrap() []error }); ok { + causes := joined.Unwrap() + if len(causes) == 0 { + return false + } + for _, cause := range causes { + if !deadlineCausesOnly(cause) { + return false + } + } + return true + } + return deadlineCausesOnly(errors.Unwrap(err)) +} diff --git a/seaweed-block/core/geometry/volume_size.go b/seaweed-block/core/geometry/volume_size.go new file mode 100644 index 0000000000..a1e941e327 --- /dev/null +++ b/seaweed-block/core/geometry/volume_size.go @@ -0,0 +1,33 @@ +// Package geometry defines shared volume capacity limits at creation boundaries. +package geometry + +import "fmt" + +// MaxVolumeBytes is the uint32-LBA limit with the supported 4-KiB IO unit. +// This byte cap assumes that IO unit: support for another block size must +// enforce min(MaxVolumeBytes, (2^32-1)*blockSize) at creation as well. +const MaxVolumeBytes uint64 = (16 << 40) - 4096 + +// ValidateVolumeSize rejects an unsupported capacity before any allocation or +// durable create. Division also makes block geometry checks overflow-safe. +func ValidateVolumeSize(size uint64) error { + if size > MaxVolumeBytes { + return fmt.Errorf("volume size %d exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", size, MaxVolumeBytes) + } + return nil +} + +// ValidateBlockGeometry checks the original values before narrowing or I/O. +func ValidateBlockGeometry(blocks, blockSize uint64) error { + if blocks > uint64(^uint32(0)) { + return fmt.Errorf("block count %d exceeds uint32", blocks) + } + if blockSize == 0 || blockSize > uint64(^uint32(0)) { + return fmt.Errorf("invalid block size %d", blockSize) + } + // Division prevents an oversized product from wrapping before admission. + if blocks > MaxVolumeBytes/blockSize { + return fmt.Errorf("volume geometry %d x %d exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", blocks, blockSize, MaxVolumeBytes) + } + return nil +} diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index f74dbfae99..76c8e1eb4f 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -480,5 +480,9 @@ func (h *Host) Close(ctx context.Context) error { } h.wg.Wait() + // Join lease extenders (authority writers) before the store closes. + if h.boot != nil && h.boot.Publisher != nil { + h.boot.Publisher.CloseWorkspaceExtenders() + } return h.boot.Close() } diff --git a/seaweed-block/core/host/master/primary_boot_grace_gate_test.go b/seaweed-block/core/host/master/primary_boot_grace_gate_test.go index f5c9f5c2fe..7c2721ce3b 100644 --- a/seaweed-block/core/host/master/primary_boot_grace_gate_test.go +++ b/seaweed-block/core/host/master/primary_boot_grace_gate_test.go @@ -95,7 +95,10 @@ func (p *switchProbe) ProbePromotionCandidates(volumeID string, current authorit } defer p.mu.Unlock() return PromotionProbeResult{ - AckProfile: "sync-quorum", + AckProfile: "sync-quorum", + // Only r2 is seen, so its promotion needs a known frontier + // it covers (#181); r3 is silent in these tests. + SyncAckLSN: 70, CurrentKnown: true, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: p.currentReady, DurableLSN: 70}, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 70}}, diff --git a/seaweed-block/core/host/master/primary_boot_grace_probe_test.go b/seaweed-block/core/host/master/primary_boot_grace_probe_test.go index 87a6186a5b..34e6042fdd 100644 --- a/seaweed-block/core/host/master/primary_boot_grace_probe_test.go +++ b/seaweed-block/core/host/master/primary_boot_grace_probe_test.go @@ -93,7 +93,12 @@ func useProductionProbe(t *testing.T, h *Host) (r1, r2 *fakeStatus) { {ServerID: "node-c", ReplicaID: "r3"}, }, }} - h.SetPromotionEvidenceProvider(NewWorkloadPlanPromotionEvidenceProvider(plans, WorkloadPlanPromotionProbeConfig{AckProfile: "sync-quorum"})) + // r3 has no status server, so r2's promotion needs a known frontier + // it covers (#181): r2 reports durable 70. + h.SetPromotionEvidenceProvider(NewWorkloadPlanPromotionEvidenceProvider(plans, WorkloadPlanPromotionProbeConfig{ + AckProfile: "sync-quorum", + RequiredLSNByVolume: map[string]uint64{"vol-rf3": 70}, + })) return r1, r2 } diff --git a/seaweed-block/core/host/master/product_loop.go b/seaweed-block/core/host/master/product_loop.go index ae62d1aa6d..fe86039969 100644 --- a/seaweed-block/core/host/master/product_loop.go +++ b/seaweed-block/core/host/master/product_loop.go @@ -29,8 +29,13 @@ type PromotionCandidateEvidence struct { } type PromotionProbeResult struct { - AckProfile string - SyncAckLSN uint64 + AckProfile string + SyncAckLSN uint64 + // SyncAckKnown reports that SyncAckLSN is a known required + // acknowledgement frontier, which may be zero. A nonzero SyncAckLSN + // is always a known frontier; a zero SyncAckLSN without SyncAckKnown + // is unknown and is never read as "nothing was acknowledged". + SyncAckKnown bool CurrentKnown bool Current PromotionCandidateEvidence Candidates []PromotionCandidateEvidence @@ -220,7 +225,7 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, } probeCount++ result, ok := h.probePromotionCandidatesCurrent(vol.VolumeID, vol.Authority, candidates) - allowed := promotionAllowedReplicas(result, ok) + allowed := promotionAllowedReplicas(result, ok, len(candidates), h.freshPromotionPeers(vol.VolumeID, candidates)) if ok { h.log.Printf("blockmaster: promotion gate volume=%s current=%s current_known=%t current_ready=%t ack_profile=%s required_lsn=%d candidates=%v allowed=%v", vol.VolumeID, vol.Authority.ReplicaID, result.CurrentKnown, result.Current.Ready, result.AckProfile, result.SyncAckLSN, result.Candidates, allowed) @@ -313,7 +318,7 @@ func (h *Host) applyUnsupportedPromotionEvidenceGate(placements []lifecycle.Plac } probeCount++ result, probeOK := h.probePromotionCandidatesCurrent(vol.VolumeID, current, candidates) - allowed := promotionAllowedReplicas(result, probeOK) + allowed := promotionAllowedReplicas(result, probeOK, len(candidates), h.freshPromotionPeers(vol.VolumeID, candidates)) if probeOK { h.log.Printf("blockmaster: promotion gate unsupported volume=%s current=%s reasons=%v current_known=%t current_ready=%t ack_profile=%s required_lsn=%d candidates=%v allowed=%v", vol.VolumeID, current.ReplicaID, evidence.Reasons, result.CurrentKnown, result.Current.Ready, result.AckProfile, result.SyncAckLSN, result.Candidates, allowed) @@ -565,7 +570,54 @@ func (h *Host) probePromotionCandidatesCurrent(volumeID string, current authorit return h.probePromotionCandidates(volumeID, current, candidates) } -func promotionAllowedReplicas(result PromotionProbeResult, ok bool) map[string]bool { +// freshPromotionPeers returns the peers that have a fresh heartbeat slot +// now, by the observation store's own freshness rule (FreshSlotCandidate), +// and report themselves reachable. Only these may count toward the +// unknown-frontier survivor rule in promotionAllowedReplicas. +func (h *Host) freshPromotionPeers(volumeID string, peers []authority.ReplicaCandidate) map[string]bool { + fresh := make(map[string]bool, len(peers)) + for _, peer := range peers { + if slot, ok := h.freshCurrentSlot(volumeID, peer.ReplicaID); ok && slot.Reachable { + fresh[peer.ReplicaID] = true + } + } + return fresh +} + +// unknownFrontierSurvivorsNeeded is how many of peerCount peers must be +// probed ready, with a known durable frontier, before the highest durable +// candidate may be promoted while the required acknowledgement frontier is +// unknown. It mirrors replication.waitForSyncAcks +// (core/replication/async_ack.go): a write is acknowledged only after the +// primary's local sync and K peer acks, K = peerCount for sync_all and +// K = (peerCount+1)/2 for sync_quorum. An acknowledged write therefore lives +// on at least K of the peerCount peers, so any peerCount-K+1 peers include at +// least one of them, and the highest durable frontier among those peers +// covers every acknowledged write. With fewer, an acknowledged write may +// live only on the peers that were not seen. RF3 sync_quorum: 2 of 2; +// RF3 sync_all: 1 of 2. +func unknownFrontierSurvivorsNeeded(ackProfile string, peerCount int) int { + required := peerCount + if strings.ToLower(strings.ReplaceAll(ackProfile, "-", "_")) == "sync_quorum" { + required = (peerCount + 1) / 2 + } + return peerCount - required + 1 +} + +// promotionAllowedReplicas returns the candidates that may be promoted. +// peerCount is the number of replicas other than the current primary, and +// freshPeers holds those of them with a fresh heartbeat now. +// +// With a quorum ack profile and a known required frontier (SyncAckKnown or +// a nonzero SyncAckLSN), a candidate must cover it: durable >= required. +// With a quorum ack profile and an unknown frontier, coverage must be +// proven from the survivors instead: at least +// unknownFrontierSurvivorsNeeded peers must be probed ready in this probe +// (ready implies a known durable frontier) and be fresh; otherwise nothing +// is allowed. An unknown frontier is never read as zero. best_effort keeps +// its rule: no required frontier can be covered, so a nonzero one refuses, +// and otherwise the highest durable ready candidate is allowed. +func promotionAllowedReplicas(result PromotionProbeResult, ok bool, peerCount int, freshPeers map[string]bool) map[string]bool { allowed := map[string]bool{} if !ok || !isKnownAckProfile(result.AckProfile) { return allowed @@ -573,6 +625,22 @@ func promotionAllowedReplicas(result PromotionProbeResult, ok bool) map[string]b if result.SyncAckLSN > 0 && !isQuorumAckProfile(result.AckProfile) { return allowed } + frontierKnown := result.SyncAckKnown || result.SyncAckLSN > 0 + if isQuorumAckProfile(result.AckProfile) && !frontierKnown { + // Survivors are counted only from result, the probe run for this + // tick, and freshPeers, read for this tick. Nothing from an + // earlier tick is kept: a survivor seen ready last tick and not + // seen now does not count. + seen := map[string]bool{} + for _, candidate := range result.Candidates { + if candidate.ReplicaID != "" && candidate.Ready && freshPeers[candidate.ReplicaID] { + seen[candidate.ReplicaID] = true + } + } + if len(seen) < unknownFrontierSurvivorsNeeded(result.AckProfile, peerCount) { + return allowed + } + } var bestLSN uint64 for _, candidate := range result.Candidates { if candidate.ReplicaID == "" || !candidate.Ready { diff --git a/seaweed-block/core/host/master/promotion_frontier_coverage_test.go b/seaweed-block/core/host/master/promotion_frontier_coverage_test.go new file mode 100644 index 0000000000..41bf39f282 --- /dev/null +++ b/seaweed-block/core/host/master/promotion_frontier_coverage_test.go @@ -0,0 +1,267 @@ +package master + +import ( + "reflect" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" +) + +// #181: an RF3 promotion must prove it covers the required acknowledgement +// frontier, either from a known frontier or, when the frontier is unknown, +// from enough fresh ready survivors to intersect every ack quorum. + +func TestUnknownFrontierSurvivorsNeeded(t *testing.T) { + for _, tc := range []struct { + profile string + peerCount int + want int + }{ + {"sync-quorum", 2, 2}, // RF3: K=1, every acked write is on >=1 of 2 peers + {"sync_quorum", 2, 2}, + {"sync-all", 2, 1}, // RF3: K=2, every acked write is on both peers + {"sync-quorum", 4, 3}, // RF5: K=2 + {"sync-all", 4, 1}, + } { + if got := unknownFrontierSurvivorsNeeded(tc.profile, tc.peerCount); got != tc.want { + t.Errorf("unknownFrontierSurvivorsNeeded(%q, %d)=%d want %d", tc.profile, tc.peerCount, got, tc.want) + } + } +} + +func TestPromotionAllowedReplicas_RequiredFrontierCoverage(t *testing.T) { + ready := func(id string, lsn uint64) PromotionCandidateEvidence { + return PromotionCandidateEvidence{ReplicaID: id, Ready: true, DurableLSN: lsn} + } + missing := func(id string) PromotionCandidateEvidence { + return PromotionCandidateEvidence{ReplicaID: id, ProbeAddr: "missing"} + } + bothFresh := map[string]bool{"r2": true, "r3": true} + for _, tc := range []struct { + name string + result PromotionProbeResult + ok bool + fresh map[string]bool + want map[string]bool + }{ + { + name: "known frontier covered is allowed with one survivor", + result: PromotionProbeResult{AckProfile: "sync-quorum", SyncAckLSN: 52, Candidates: []PromotionCandidateEvidence{ready("r2", 60), missing("r3")}}, + ok: true, fresh: bothFresh, want: map[string]bool{"r2": true}, + }, + { + name: "known frontier not covered is refused", + result: PromotionProbeResult{AckProfile: "sync-quorum", SyncAckLSN: 52, Candidates: []PromotionCandidateEvidence{ready("r2", 51), missing("r3")}}, + ok: true, fresh: bothFresh, want: map[string]bool{}, + }, + { + name: "known zero frontier is known, not unknown", + result: PromotionProbeResult{AckProfile: "sync-quorum", SyncAckKnown: true, Candidates: []PromotionCandidateEvidence{ready("r2", 10), missing("r3")}}, + ok: true, fresh: bothFresh, want: map[string]bool{"r2": true}, + }, + { + name: "unknown frontier with every survivor fresh and ready picks the highest", + result: PromotionProbeResult{AckProfile: "sync-quorum", Candidates: []PromotionCandidateEvidence{ready("r2", 70), ready("r3", 90)}}, + ok: true, fresh: bothFresh, want: map[string]bool{"r3": true}, + }, + { + name: "unknown frontier with one survivor unseen is refused", + result: PromotionProbeResult{AckProfile: "sync-quorum", Candidates: []PromotionCandidateEvidence{ready("r2", 51), missing("r3")}}, + ok: true, fresh: bothFresh, want: map[string]bool{}, + }, + { + name: "unknown frontier with one survivor not ready is refused", + result: PromotionProbeResult{AckProfile: "sync-quorum", Candidates: []PromotionCandidateEvidence{ready("r2", 51), {ReplicaID: "r3", DurableLSN: 90}}}, + ok: true, fresh: bothFresh, want: map[string]bool{}, + }, + { + name: "a ready probe without a fresh heartbeat does not count", + result: PromotionProbeResult{AckProfile: "sync-quorum", Candidates: []PromotionCandidateEvidence{ready("r2", 70), ready("r3", 90)}}, + ok: true, fresh: map[string]bool{"r2": true}, want: map[string]bool{}, + }, + { + name: "a survivor reported twice counts once", + result: PromotionProbeResult{AckProfile: "sync-quorum", Candidates: []PromotionCandidateEvidence{ready("r2", 70), ready("r2", 70)}}, + ok: true, fresh: bothFresh, want: map[string]bool{}, + }, + { + name: "sync_all unknown frontier needs one fresh ready survivor", + result: PromotionProbeResult{AckProfile: "sync-all", Candidates: []PromotionCandidateEvidence{ready("r2", 51), missing("r3")}}, + ok: true, fresh: bothFresh, want: map[string]bool{"r2": true}, + }, + { + name: "best_effort unknown frontier is unchanged", + result: PromotionProbeResult{AckProfile: "best-effort", Candidates: []PromotionCandidateEvidence{ready("r2", 51), missing("r3")}}, + ok: true, fresh: map[string]bool{}, want: map[string]bool{"r2": true}, + }, + { + name: "best_effort with a required frontier is unchanged (refused)", + result: PromotionProbeResult{AckProfile: "best-effort", SyncAckLSN: 52, Candidates: []PromotionCandidateEvidence{ready("r2", 60), ready("r3", 60)}}, + ok: true, fresh: bothFresh, want: map[string]bool{}, + }, + { + name: "probe unavailable is refused", + result: PromotionProbeResult{AckProfile: "sync-quorum", SyncAckLSN: 52, Candidates: []PromotionCandidateEvidence{ready("r2", 60), ready("r3", 60)}}, + ok: false, fresh: bothFresh, want: map[string]bool{}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + got := promotionAllowedReplicas(tc.result, tc.ok, 2, tc.fresh) + if !reflect.DeepEqual(got, tc.want) { + t.Fatalf("allowed=%v want %v", got, tc.want) + } + }) + } +} + +// A volume absent from RequiredLSNByVolume has an unknown frontier; one +// present with zero has a known zero frontier. +func TestWorkloadPlanProvider_RequiredFrontierKnownness(t *testing.T) { + for _, tc := range []struct { + name string + required map[string]uint64 + want bool + }{ + {"absent map", nil, false}, + {"other volume only", map[string]uint64{"vol-other": 9}, false}, + {"present zero", map[string]uint64{"vol-rf3": 0}, true}, + {"present nonzero", map[string]uint64{"vol-rf3": 52}, true}, + } { + provider := NewWorkloadPlanPromotionEvidenceProvider(nil, WorkloadPlanPromotionProbeConfig{AckProfile: "sync-quorum", RequiredLSNByVolume: tc.required}) + result, err := provider.ProbePromotionCandidates("vol-rf3", authority.AuthorityBasis{}, nil) + if err != nil { + t.Fatalf("%s: %v", tc.name, err) + } + if result.SyncAckKnown != tc.want || result.SyncAckLSN != tc.required["vol-rf3"] { + t.Fatalf("%s: known=%t lsn=%d want known=%t lsn=%d", tc.name, result.SyncAckKnown, result.SyncAckLSN, tc.want, tc.required["vol-rf3"]) + } + } +} + +// Only peers with a fresh heartbeat slot count toward the survivor rule. +func TestFreshPromotionPeers_UsesObservationFreshness(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3}) + defer closeTestMaster(t, h) + for _, s := range []struct{ server, replica string }{{"node-a", "r1"}, {"node-b", "r2"}} { + if err := h.ObservationHost().Ingest(authority.Observation{ + ServerID: s.server, + ObservedAt: time.Now().UTC(), + Server: authority.ServerFact{Reachable: true, Eligible: true}, + Slots: []authority.SlotFact{{ + VolumeID: "vol-rf3", ReplicaID: s.replica, + DataAddr: "127.0.0.1:1", CtrlAddr: "127.0.0.1:2", + Reachable: true, ReadyForPrimary: true, Eligible: true, + }}, + }); err != nil { + t.Fatalf("ingest %s: %v", s.server, err) + } + } + got := h.freshPromotionPeers("vol-rf3", []authority.ReplicaCandidate{{ReplicaID: "r2"}, {ReplicaID: "r3"}}) + if !reflect.DeepEqual(got, map[string]bool{"r2": true}) { + t.Fatalf("fresh peers=%v want only r2 (r3 never observed)", got) + } +} + +type swapPromotionProbe struct { + mu sync.Mutex + result PromotionProbeResult +} + +func (p *swapPromotionProbe) set(r PromotionProbeResult) { + p.mu.Lock() + defer p.mu.Unlock() + p.result = r +} + +func (p *swapPromotionProbe) ProbePromotionCandidates(string, authority.AuthorityBasis, []authority.ReplicaCandidate) (PromotionProbeResult, error) { + p.mu.Lock() + defer p.mu.Unlock() + return p.result, nil +} + +// Survivors count only from this tick's probe: r3 was probed ready on the +// previous tick, but this tick its probe is missing, so with an unknown +// frontier r2 alone cannot be promoted. +func TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3}) + defer closeTestMaster(t, h) + probe := &swapPromotionProbe{} + h.SetPromotionEvidenceProvider(probe) + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + if initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3"); initial.ReplicaID != "r1" { + t.Fatalf("initial line=%+v want r1", initial) + } + + // Previous tick: both survivors probed ready, current primary ready. + probe.set(PromotionProbeResult{ + AckProfile: "sync-quorum", + CurrentKnown: true, + Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: true, DurableLSN: 90}, + Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r2", Ready: true, DurableLSN: 90}, + {ReplicaID: "r3", Ready: true, DurableLSN: 90}, + }, + }) + ingestRF3Observation(t, h, true, true, true) + prev, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatal(err) + } + if prev.PromotionProbes != 1 || prev.PromotionBlocked != 0 { + t.Fatalf("previous tick=%+v want one probe that admits both survivors", prev) + } + + // This tick: the primary is lost and r3's probe is missing. + probe.set(PromotionProbeResult{ + AckProfile: "sync-quorum", + Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r2", Ready: true, DurableLSN: 90}, + {ReplicaID: "r3", ProbeAddr: "missing"}, + }, + }) + ingestRF3Observation(t, h, false, true, true) + now, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatal(err) + } + if now.PromotionProbes != 1 || now.PromotionBlocked != 1 { + t.Fatalf("this tick=%+v want the promotion blocked: r3 is not seen this tick", now) + } + time.Sleep(200 * time.Millisecond) + if line, _ := h.Publisher().VolumeAuthorityLine("vol-rf3"); line.ReplicaID != "r1" { + t.Fatalf("authority moved to %+v on a partial view", line) + } +} + +// RF2 never consults the RF3 promotion gate: a probe that would refuse every +// candidate (unknown frontier, no survivors) does not stop RF2 failover. +func TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 2}) + defer closeTestMaster(t, h) + h.SetPromotionEvidenceProvider(staticPromotionProbe{result: PromotionProbeResult{AckProfile: "sync-quorum"}}) + seedRF2Placement(t, h) + ingestRF2Observation(t, h, true, true) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + if initial := waitAuthorityLine(t, h.Publisher(), "vol-rf2"); initial.ReplicaID != "r1" { + t.Fatalf("initial line=%+v want r1", initial) + } + ingestRF2Observation(t, h, false, true) + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("failover product tick: %v", err) + } + if result.PromotionProbes != 0 { + t.Fatalf("result=%+v want no RF3 promotion probe for RF2", result) + } + if failover := waitAuthorityReplica(t, h.Publisher(), "vol-rf2", "r2"); failover.Epoch != 2 { + t.Fatalf("failover line=%+v want r2@2", failover) + } +} diff --git a/seaweed-block/core/host/master/promotion_missing_frontier_regression_test.go b/seaweed-block/core/host/master/promotion_missing_frontier_regression_test.go new file mode 100644 index 0000000000..2ae248a535 --- /dev/null +++ b/seaweed-block/core/host/master/promotion_missing_frontier_regression_test.go @@ -0,0 +1,50 @@ +package master + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +func TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3}) + defer closeTestMaster(t, h) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/status": + _ = json.NewEncoder(w).Encode(volume.StatusProjection{Projection: frontend.Projection{VolumeID: "vol-rf3", ReplicaID: "r2"}, ReplicationRole: "replica_ready"}) + case "/status/durable": + _ = json.NewEncoder(w).Encode(struct{ Volumes []durable.VolumeStatus }{Volumes: []durable.VolumeStatus{{VolumeID: "vol-rf3", ReplicaID: "r2", FrontierKnown: true, DurableLSN: 51}}}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + // Mirrors cmd/blockmaster.runLifecycleLauncherTick: no RequiredLSNByVolume. + // A candidate reporting a local frontier is not proof of covering prior ACKs. + h.SetPromotionEvidenceProvider(NewWorkloadPlanPromotionEvidenceProvider([]lifecycle.BlockVolumeWorkloadPlan{{VolumeID: "vol-rf3", Protocol: "iscsi", Replicas: []lifecycle.BlockVolumeReplicaWorkload{{ReplicaID: "r2", ISCSIListenPort: 3260}}}}, WorkloadPlanPromotionProbeConfig{AckProfile: "sync-quorum", HTTPClient: rewriteHTTPClient(server.URL, "127.0.0.1:23260")})) + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if initial.ReplicaID != "r1" { + t.Fatalf("initial line=%+v", initial) + } + ingestRF3Observation(t, h, false, true, true) + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatal(err) + } + if result.PromotionBlocked != 1 { + t.Fatalf("unknown required frontier admitted promotion: %+v; candidate durable=51, required coverage unknown", result) + } +} diff --git a/seaweed-block/core/host/master/promotion_probe.go b/seaweed-block/core/host/master/promotion_probe.go index f0f7e66439..1cb98f7b87 100644 --- a/seaweed-block/core/host/master/promotion_probe.go +++ b/seaweed-block/core/host/master/promotion_probe.go @@ -69,10 +69,14 @@ type workloadPlanPromotionEvidenceProvider struct { } func (p *workloadPlanPromotionEvidenceProvider) ProbePromotionCandidates(volumeID string, current authority.AuthorityBasis, candidates []authority.ReplicaCandidate) (PromotionProbeResult, error) { + // A volume absent from RequiredLSNByVolume has an unknown required + // frontier, not a zero one. + required, requiredKnown := p.required[volumeID] result := PromotionProbeResult{ - AckProfile: p.ackProfile, - SyncAckLSN: p.required[volumeID], - Candidates: make([]PromotionCandidateEvidence, 0, len(candidates)), + AckProfile: p.ackProfile, + SyncAckLSN: required, + SyncAckKnown: requiredKnown, + Candidates: make([]PromotionCandidateEvidence, 0, len(candidates)), } if current.ReplicaID != "" { statusAddr := p.status[volumeID][current.ReplicaID] diff --git a/seaweed-block/core/host/master/workspace_binding_test.go b/seaweed-block/core/host/master/workspace_binding_test.go index 87f73e1b1d..07b3a67767 100644 --- a/seaweed-block/core/host/master/workspace_binding_test.go +++ b/seaweed-block/core/host/master/workspace_binding_test.go @@ -126,8 +126,14 @@ func workspaceBindingsMove(t *testing.T, forced bool) { t.Fatal(e) } if forced { + // The forced barrier is the durable horizon (>= every grant) plus + // skew, not the reply's grant (#205). + horizon := lease.ExpiresAtNs + if st := h.Publisher().WorkspaceState(vol); st != nil && st.Lease != nil && st.Lease.ExpiresAtNS > horizon { + horizon = st.Lease.ExpiresAtNS + } select { - case <-time.After(time.Until(time.Unix(0, lease.ExpiresAtNs)) + 100*time.Millisecond + 20*time.Millisecond): + case <-time.After(time.Until(time.Unix(0, horizon)) + 100*time.Millisecond + 20*time.Millisecond): case <-ctx.Done(): t.Fatal(ctx.Err()) } diff --git a/seaweed-block/core/host/master/workspace_exited_holder_test.go b/seaweed-block/core/host/master/workspace_exited_holder_test.go new file mode 100644 index 0000000000..7e066b6f6b --- /dev/null +++ b/seaweed-block/core/host/master/workspace_exited_holder_test.go @@ -0,0 +1,217 @@ +package master + +import ( + "bytes" + "context" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// A holder that exited never detaches or ACKs, so its live authority blocks +// a volume delete. The existing path recovers the volume: after the lease +// horizon plus skew a forced move grants epoch+1 on another host, that +// host claims HEAD and serves the last cut, then detaches with a clean ACK, +// and the delete is admitted. Real master runtime, real providers, the +// in-memory ChunkRemote (read by the master through a HEAD reader). +func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) { + // The real lease horizon (1.5 x the 30 s TTL) plus skew takes ~45 s of + // this budget; the rest must cover the work after it under load and -race. + ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + reader := func(ctx context.Context, _ string) (authority.WorkspaceHead, error) { + h, err := remote.GetHead(ctx) + if err != nil { + return authority.WorkspaceHead{}, err + } + return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached}, nil + } + const skew = 100 * time.Millisecond + m, err := New(Config{WorkspaceMaxClockSkew: skew, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: reader}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn) + + // vol-a placed on node-a as r1; node-b is a prepared target. + for _, server := range []string{"node-a", "node-b"} { + if _, err = m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + } + if _, err = lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + src := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-a", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"} + dst := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-b", DataAddr: "127.0.0.1:29200", CtrlAddr: "127.0.0.1:29100"} + for _, b := range []*control.WorkspaceBinding{src, dst} { + if _, err = ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err = ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "vol-a", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + if _, err = control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "vol-a", ReplicaId: "r1", DataAddr: src.DataAddr, CtrlAddr: src.CtrlAddr}}}); err != nil { + t.Fatal(err) + } + if _, err = m.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + oldLine := waitAuthorityLine(t, m.Publisher(), "vol-a") + oldID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: oldLine.ReplicaID, Epoch: oldLine.Epoch} + if _, err = ws.RenewWorkspaceLease(ctx, oldID); err != nil { + t.Fatal(err) + } + + open := func(host string, line authority.AuthorityBasis) (*durable.DurableProvider, frontend.Backend) { + t.Helper() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, + ChunkHolder: host + "/" + line.ReplicaID, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, restoreProjection{frontend.Projection{VolumeID: "vol-a", ReplicaID: line.ReplicaID, Epoch: line.Epoch, EndpointVersion: line.EndpointVersion, Healthy: true}}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("vol-a"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(ctx, "vol-a"); err != nil { + t.Fatalf("%s recovery: %v", host, err) + } + b, err := p.Open(ctx, "vol-a") + if err != nil { + t.Fatal(err) + } + return p, b + } + + // The holder writes, cuts, then exits without detaching or ACKing. + oldProvider, oldBackend := open("node-a", oldLine) + want := bytes.Repeat([]byte{0xE1}, 4096) + if n, err := oldBackend.Write(ctx, 8*4096, want); err != nil || n != len(want) { + t.Fatal(n, err) + } + if err := oldBackend.Sync(ctx); err != nil { + t.Fatal(err) + } + cut, err := oldProvider.CaptureVolume(ctx, "vol-a") + if err != nil { + t.Fatal(err) + } + if err := oldProvider.Close(); err != nil { + t.Fatal(err) + } + head, err := remote.GetHead(ctx) + if err != nil || head.RemoteLSN != cut || head.State == storage.ChunkHeadDetached { + t.Fatalf("HEAD after the holder exited: %+v %v", head, err) + } + + // The exited holder's live authority blocks the delete and a clean move. + if _, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "vol-a", Token: "del-early"}); err == nil || !strings.Contains(err.Error(), "live authority requires clean revocation ACK") { + t.Fatalf("delete under the exited holder's live authority: %v; want the clean revocation ACK refusal", err) + } + move := &control.WorkspaceMove{RequestId: "clean-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: oldLine.Epoch, TargetReplicaId: "r1", + TargetServerId: "node-b", TargetDataAddr: dst.DataAddr, TargetCtrlAddr: dst.CtrlAddr, Kind: "clean"} + if _, err := ws.MoveWorkspace(ctx, move); err == nil { + t.Fatal("clean move granted without the holder's detach and ACK") + } + move.RequestId, move.Kind, move.Force = "forced-1", "forced", true + if _, err := ws.MoveWorkspace(ctx, move); err == nil { + t.Fatal("forced move granted before the lease horizon plus skew") + } + + // After the durable lease horizon plus skew, the forced move is granted. + horizon := int64(0) + if st := m.Publisher().WorkspaceState("vol-a"); st != nil && st.Lease != nil { + horizon = st.Lease.ExpiresAtNS + } + if horizon == 0 { + t.Fatal("no lease horizon recorded") + } + select { + case <-time.After(time.Until(time.Unix(0, horizon)) + skew + 20*time.Millisecond): + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + grant, err := ws.MoveWorkspace(ctx, move) + if err != nil { + t.Fatal("forced move after the horizon:", err) + } + newLine, ok := m.Publisher().VolumeAuthorityLine("vol-a") + if !grant.Issued || grant.NewEpoch != oldLine.Epoch+1 || !ok || newLine.Epoch != grant.NewEpoch || grant.HeadGen != head.Gen || grant.RemoteLsn != cut { + t.Fatalf("forced grant %+v line %+v; want epoch %d bound to HEAD gen %d lsn %d", grant, newLine, oldLine.Epoch+1, head.Gen, cut) + } + if _, err := ws.RenewWorkspaceLease(ctx, oldID); err == nil { + t.Fatal("the exited holder's authority renewed after the forced move") + } + + // The new host claims HEAD, serves the last cut and continues past it. + newProvider, newBackend := open("node-b", newLine) + claimed, err := remote.GetHead(ctx) + if err != nil || claimed.Epoch != newLine.Epoch || claimed.Holder != "node-b/r1" || claimed.RemoteLSN != cut || claimed.State == storage.ChunkHeadDetached { + t.Fatalf("HEAD after the new host's recovery: %+v %v", claimed, err) + } + got := make([]byte, len(want)) + if n, err := newBackend.Read(ctx, 8*4096, got); err != nil || n != len(got) || !bytes.Equal(got, want) { + t.Fatalf("new host read of the last cut: n=%d err=%v", n, err) + } + if n, err := newBackend.Write(ctx, 0, bytes.Repeat([]byte{0xE2}, 4096)); err != nil || n != 4096 { + t.Fatal(n, err) + } + if err := newBackend.Sync(ctx); err != nil { + t.Fatal(err) + } + if newCut, err := newProvider.CaptureVolume(ctx, "vol-a"); err != nil || newCut <= cut { + t.Fatalf("new host cut %d err %v; want past %d", newCut, err, cut) + } + + // The new holder detaches cleanly and ACKs; the delete is then admitted. + newID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: newLine.ReplicaID, Epoch: newLine.Epoch} + if _, err := ws.RenewWorkspaceLease(ctx, newID); err != nil { + t.Fatal(err) + } + if _, err := ws.RevokeWorkspace(ctx, newID); err != nil { + t.Fatal(err) + } + detached, _, err := newProvider.DetachVolume(ctx, "vol-a") + if err != nil || detached.Head.State != storage.ChunkHeadDetached { + t.Fatalf("detach: %+v %v", detached.Head, err) + } + if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: newID, HeadGen: detached.Head.Gen}); err != nil { + t.Fatal(err) + } + res, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "vol-a", Token: "del-1"}) + if err != nil || !res.GetKnown() || res.GetState() != lifecycle.ReservationAdmitted { + t.Fatalf("delete after the clean ACK: %+v %v", res, err) + } + if _, err := ws.RenewWorkspaceLease(ctx, newID); err == nil { + t.Fatal("authority renewed after the delete was admitted") + } + move.RequestId, move.ExpectedEpoch = "forced-2", newLine.Epoch + // The RPC refuses first; publication admission refuses it again behind it. + if _, err := ws.MoveWorkspace(ctx, move); err == nil || !strings.Contains(err.Error(), "workspace: volume is being deleted") { + t.Fatalf("move after the delete was admitted: %v; want the RPC's deletion refusal", err) + } +} diff --git a/seaweed-block/core/host/master/workspace_head.go b/seaweed-block/core/host/master/workspace_head.go index ef51030272..0c5dd7f544 100644 --- a/seaweed-block/core/host/master/workspace_head.go +++ b/seaweed-block/core/host/master/workspace_head.go @@ -48,7 +48,6 @@ func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authori return authority.WorkspaceHead{}, fmt.Errorf("HEAD too large") } var doc struct { - Format int `json:"format"` Gen uint64 `json:"gen"` Epoch uint64 `json:"epoch"` Holder string `json:"holder"` @@ -67,7 +66,8 @@ func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authori if _, err := chunkstore.DecodeHeadDocument("workspace/"+volume, raw); err != nil { return authority.WorkspaceHead{}, err } - if (doc.Format != 1 && doc.Format != 2) || doc.Gen == 0 || doc.Epoch == 0 || doc.Holder == "" || doc.LegacyDetached != nil || (doc.State != "" && doc.State != "active" && doc.State != "detached") { + // DecodeHeadDocument above owns the supported-format checks. + if doc.Gen == 0 || doc.Epoch == 0 || doc.Holder == "" || doc.LegacyDetached != nil || (doc.State != "" && doc.State != "active" && doc.State != "detached") { return authority.WorkspaceHead{}, fmt.Errorf("invalid HEAD identity/state") } // Missing state is the legacy active representation. Only a final-cut diff --git a/seaweed-block/core/host/master/workspace_head_format3_test.go b/seaweed-block/core/host/master/workspace_head_format3_test.go new file mode 100644 index 0000000000..7a07fbf073 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_head_format3_test.go @@ -0,0 +1,98 @@ +package master + +import ( + "context" + "crypto/sha256" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type workspaceManifestBlobs struct{ chunkstore.Blobs } + +func (workspaceManifestBlobs) Put(context.Context, []byte) (string, error) { + return "1,0000000100000001", nil +} + +// Exercise the F4 writer and HTTP reader together, not a hand-written schema. +func TestWorkspaceHEADReadsProductionFormat3Detach(t *testing.T) { + ctx := context.Background() + filer := chunkstore.NewMemFiler() + remote, err := chunkstore.NewChunkRemote(filer, workspaceManifestBlobs{}, "/vol-a") + if err != nil { + t.Fatal(err) + } + head := storage.ChunkHead{Epoch: 3, Holder: "node-a/r1", RemoteLSN: 42, + State: storage.ChunkHeadDetached, + DetachedBy: &storage.ChunkDetachedBy{Holder: "node-a/r1", Epoch: 3, Gen: 1}, + Chunks: map[uint64]storage.ChunkRef{0: {Key: "data-1", SHA256: sha256.Sum256([]byte("cut-image")), Encoding: "full", BirthLSN: 42}}} + head, _, err = remote.PrepareManifest(ctx, storage.ChunkHead{}, head, 4096) + if err != nil { + t.Fatal(err) + } + if _, err = remote.CASHead(ctx, storage.ChunkHeadVersion{}, head); err != nil { + t.Fatal(err) + } + stored, err := filer.LookupEntry(ctx, "/vol-a", "HEAD") + if err != nil { + t.Fatal(err) + } + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write(stored.Content) + })) + defer s.Close() + read, err := NewWorkspaceHEADReader(s.URL) + if err != nil { + t.Fatal(err) + } + got, err := read(ctx, "vol-a") + if err != nil || !got.Detached || got.Gen != 1 || got.Epoch != 3 || got.Holder != "node-a/r1" || got.RemoteLSN != 42 { + t.Fatalf("production detached HEAD not usable as move evidence: %+v, %v; body=%s", got, err, stored.Content) + } +} + +func TestWorkspaceHEADFormat3DetachedProof(t *testing.T) { + for _, tc := range []struct { + name, state string + format, levels int + valid, detached bool + }{ + {"detached", `,"state":"detached","detachedBy":{"holder":"node-a/r1","epoch":3,"gen":9}`, 3, 1, true, true}, + {"active", `,"state":"active"`, 3, 1, true, false}, + {"missing-proof", `,"state":"detached"`, 3, 1, false, false}, + {"wrong-proof", `,"state":"detached","detachedBy":{"holder":"node-b/r1","epoch":3,"gen":9}`, 3, 1, false, false}, + {"stale-active-proof", `,"state":"active","detachedBy":{"holder":"node-a/r1","epoch":3,"gen":9}`, 3, 1, false, false}, + {"unknown-format", `,"state":"active"`, 4, 1, false, false}, + {"unknown-levels", `,"state":"active"`, 3, 2, false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + // A data-bearing F4 root: the control-plane reader validates the + // root and detach proof without fetching immutable segment payloads. + body := fmt.Sprintf(`{"format":%d,"levels":%d,"gen":9,"epoch":3,"holder":"node-a/r1","remote_lsn":42,"chunk_bytes":4096,"chunk_count":1,"segments":{"0":{"key":"segment-1","sha256":[],"owner":"vol-a","count":1,"seg_format":2,"max_birth_lsn":42}}%s}`, tc.format, tc.levels, tc.state) + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/vol-a/HEAD" { + t.Errorf("unexpected path %s", r.URL.Path) + http.NotFound(w, r) + return + } + _, _ = w.Write([]byte(body)) + })) + defer s.Close() + read, err := NewWorkspaceHEADReader(s.URL) + if err != nil { + t.Fatal(err) + } + h, err := read(context.Background(), "vol-a") + if (err == nil) != tc.valid { + t.Fatalf("valid=%v, HEAD=%+v, error=%v", tc.valid, h, err) + } + if err == nil && (h.Gen != 9 || h.Epoch != 3 || h.Holder != "node-a/r1" || h.RemoteLSN != 42 || h.Detached != tc.detached) { + t.Fatalf("incorrect HEAD evidence: %+v", h) + } + }) + } +} diff --git a/seaweed-block/core/host/master/workspace_lease_horizon_test.go b/seaweed-block/core/host/master/workspace_lease_horizon_test.go new file mode 100644 index 0000000000..c0ae355df8 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_lease_horizon_test.go @@ -0,0 +1,207 @@ +package master + +import ( + "context" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// stalledGuardStore blocks every lease write once armed until release +// closes: a store that never comes back (issue #205, control 1). +type stalledGuardStore struct { + authority.AuthorityStore + armed atomic.Bool + puts atomic.Int64 + release chan struct{} +} + +func (s *stalledGuardStore) Put(r authority.DurableRecord) error { + if s.armed.Load() && r.Workspace != nil && r.Workspace.Lease != nil { + s.puts.Add(1) + <-s.release + } + return s.AuthorityStore.Put(r) +} + +// Control 1 (host side): with the master's store stalled for good, a real +// guard keeps serving on clamped grants and fences by the durable horizon +// minus half the skew bound, not earlier and not later than the horizon. +func TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore(t *testing.T) { + disk, err := authority.NewFileAuthorityStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + stall := &stalledGuardStore{AuthorityStore: disk, release: make(chan struct{})} + var inflight sync.WaitGroup + t.Cleanup(func() { + inflight.Wait() + if err := disk.Close(); err != nil { + t.Error(err) + } + }) + dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)} + p := authority.NewPublisher(dir, authority.WithStore(stall), authority.WithWorkspaceLeaseConfig(3*time.Second, nil)) + seedSkewPublisher(t, p, dir) + t.Cleanup(p.CloseWorkspaceExtenders) + var releaseOnce sync.Once + t.Cleanup(func() { releaseOnce.Do(func() { close(stall.release) }) }) // runs first: unblock the extender + var stops atomic.Int32 + g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, + deadlineLeaseClient{p: p, inflight: &inflight}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, + func(context.Context) (uint64, error) { stops.Add(1); return 7, nil }, nil) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + runDone := make(chan error, 1) + go func() { runDone <- g.Run(ctx) }() + t.Cleanup(func() { + cancel() + select { + case <-runDone: + case <-time.After(10 * time.Second): + t.Error("guard did not settle") + } + }) + for wait := time.Now().Add(3 * time.Second); !g.Projection().Healthy; time.Sleep(10 * time.Millisecond) { + if time.Now().After(wait) { + t.Fatal("first grant did not arrive") + } + } + lease := p.WorkspaceState("v").Lease + horizon := time.Unix(0, lease.ExpiresAtNS) + halfSkew := time.Duration(lease.MaxClockSkewNS) / 2 + stall.armed.Store(true) + var fencedAt time.Time + for deadline := horizon.Add(2 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { + if !g.Projection().Healthy { + fencedAt = time.Now() + break + } + } + if fencedAt.IsZero() { + t.Fatalf("guard still serving 2 s past the durable horizon %s", horizon.Format(time.RFC3339Nano)) + } + if fencedAt.After(horizon.Add(300 * time.Millisecond)) { + t.Fatalf("guard fenced %s after the durable horizon", fencedAt.Sub(horizon)) + } + if early := horizon.Add(-halfSkew - 500*time.Millisecond); fencedAt.Before(early) { + t.Fatalf("guard fenced %s before horizon - skew/2: grants did not clamp to the horizon", early.Sub(fencedAt)) + } + if stall.puts.Load() == 0 { + t.Fatal("no extender write reached the stalled store") + } + t.Logf("guard fenced %s before the durable horizon (half skew %s)", horizon.Sub(fencedAt).Round(time.Millisecond), halfSkew) +} + +// Control 6a and the reply clamp: through the services layer, QueryWorkspace +// and RevokeWorkspace report the granted expiry, not the durable horizon; a +// renewal during a held reservation write of the SAME volume (revoked and +// ACKed, so deletion is admitted) returns the revoking lease without waiting, +// and once the reservation is published renewals are refused. +func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) { + h, c, ctx := reviewBindingHost(t) + reviewLegacyBind(t, h, c, ctx, "vol-b") + line := waitAuthorityLine(t, h.Publisher(), "vol-b") + svc := &services{host: h} + id := &control.WorkspaceIdentity{VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch} + first, err := svc.RenewWorkspaceLease(ctx, id) + if err != nil { + t.Fatal(err) + } + durable := h.Publisher().WorkspaceState("vol-b").Lease.ExpiresAtNS + if first.ExpiresAtNs >= durable { + t.Fatalf("fixture: grant %d not below the durable horizon %d", first.ExpiresAtNs, durable) + } + q, err := svc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-b"}) + if err != nil || q.Lease == nil || q.Lease.ExpiresAtNs != first.ExpiresAtNs { + t.Fatalf("QueryWorkspace must report the grant %d, got %+v %v", first.ExpiresAtNs, q.GetLease(), err) + } + rv, err := svc.RevokeWorkspace(ctx, id) + if err != nil || !rv.Revoking || rv.ExpiresAtNs != first.ExpiresAtNs { + t.Fatalf("RevokeWorkspace must report the grant %d, got %+v %v", first.ExpiresAtNs, rv, err) + } + if _, err := svc.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil { + t.Fatal(err) + } + deletions := h.Lifecycle().Deletions + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + releaseHook := func() { releaseOnce.Do(func() { close(release) }) } + deletions.SetPersistHookForTest(func() error { + enterOnce.Do(func() { close(entered) }) + <-release + return nil + }) + marked := make(chan error, 1) + go func() { + _, err := svc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "vol-b", Token: "tok"}) + marked <- err + }() + renewed := make(chan *control.WorkspaceLeaseFact, 1) + renewErr := make(chan error, 1) + renewStarted := false + t.Cleanup(func() { // bounded: release, settle both workers, then clear the hook + releaseHook() + settled := true + select { + case <-marked: + case <-time.After(5 * time.Second): + settled = false + t.Error("held reservation write did not settle") + } + if renewStarted { + select { + case <-renewErr: + case <-time.After(5 * time.Second): + settled = false + t.Error("renewal did not settle") + } + } + if settled { + deletions.SetPersistHookForTest(nil) + } + }) + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("reservation write of vol-b never reached the store") + } + renewStarted = true + go func() { + f, err := svc.RenewWorkspaceLease(ctx, id) + renewed <- f + renewErr <- err + }() + select { + case f := <-renewed: + err := <-renewErr + renewErr <- err + if err != nil || !f.Revoking || f.ExpiresAtNs != first.ExpiresAtNs { + t.Fatalf("renewal during the held same-volume reservation: %+v %v; want the revoking lease with the granted expiry", f, err) + } + case <-time.After(2 * time.Second): + t.Fatal("renewal waited on the held reservation write") + } + releaseHook() + select { + case err := <-marked: + marked <- err + if err != nil { + t.Fatal("mark deleting:", err) + } + case <-time.After(5 * time.Second): + t.Fatal("mark deleting did not finish") + } + if _, err := svc.RenewWorkspaceLease(ctx, id); err == nil || !strings.Contains(err.Error(), "being deleted") { + t.Fatalf("renewal after the reservation was published: %v; want refused as being deleted", err) + } +} diff --git a/seaweed-block/core/host/master/workspace_move_refusal_test.go b/seaweed-block/core/host/master/workspace_move_refusal_test.go new file mode 100644 index 0000000000..9a7e113705 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_move_refusal_test.go @@ -0,0 +1,202 @@ +package master + +import ( + "bytes" + "context" + "log" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +type syncBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuffer) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} + +func (s *syncBuffer) String() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.String() +} + +// A refused move names the precondition that failed, in the gRPC status and +// in the master log: an unknown source, an unregistered target node, a +// target that is the source, or target endpoints that are not registered +// (with what is registered: the node's pair, or the volume's live bindings +// on that node). +func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { + logs := &syncBuffer{} + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + Logger: log.New(logs, "", 0), + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil + }}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn) + for _, n := range []lifecycle.NodeRegistration{ + {ServerID: "node-a", DataAddr: "127.0.0.1:19101", CtrlAddr: "127.0.0.1:19102"}, + {ServerID: "node-b", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"}, + } { + if _, err := m.Lifecycle().Nodes.RegisterNode(n); err != nil { + t.Fatal(err) + } + } + for _, v := range []string{"placed", "unplaced", "bound"} { + if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: v, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + } + if _, err := m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "placed", DesiredRF: 1, + Candidates: []lifecycle.PlacementCandidate{{VolumeID: "placed", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { + t.Fatal(err) + } + // "bound" has explicit per-volume bindings: its source on node-a and a + // prepared target on node-b at slot 2. + for _, b := range []*control.WorkspaceBinding{ + {VolumeId: "bound", ServerId: "node-a", DataAddr: "127.0.0.1:19121", CtrlAddr: "127.0.0.1:19122"}, + {VolumeId: "bound", ServerId: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"}, + } { + if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "bound", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + + move := func(vol, server, data, ctrl string) *control.WorkspaceMove { + return &control.WorkspaceMove{RequestId: vol + "-" + server + "-" + data, VolumeId: vol, ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", + TargetServerId: server, TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"} + } + for _, c := range []struct { + name string + q *control.WorkspaceMove + want string + }{ + {"unknown source", move("unplaced", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), `move source unknown: no issued move or placement names replica "r1" at epoch 1`}, + {"unknown target node", move("placed", "node-z", "127.0.0.1:19301", "127.0.0.1:19302"), `move target node "node-z" is not registered`}, + {"target is the source", move("placed", "node-a", "127.0.0.1:19101", "127.0.0.1:19102"), `move target "node-a" is the current source host`}, + {"target on another host", move("placed", "node-b", "10.9.9.9:19311", "127.0.0.1:19312"), + `move target endpoints 10.9.9.9:19311/127.0.0.1:19312 on "node-b" are not registered (not on the node's hosts: it registers 127.0.0.1:19301/127.0.0.1:19302; no per-volume binding is prepared)`}, + {"explicit binding elsewhere", move("bound", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), + `move target endpoints 127.0.0.1:19301/127.0.0.1:19302 on "node-b" are not registered (live bindings on that node: 127.0.0.1:19321/127.0.0.1:19322)`}, + } { + t.Run(c.name, func(t *testing.T) { + _, err := ws.MoveWorkspace(ctx, c.q) + if status.Code(err) != codes.FailedPrecondition || status.Convert(err).Message() != c.want { + t.Fatalf("refusal %v; want FailedPrecondition %q", err, c.want) + } + if line := `MoveWorkspace refused volume="` + c.q.VolumeId + `" request="` + c.q.RequestId + `": ` + c.want; !strings.Contains(logs.String(), line) { + t.Fatalf("log lacks %q:\n%s", line, logs.String()) + } + }) + } + // Slot-0 and slot-1 targets on the node's host pass these preconditions + // (they fail later, at the clean-move ACK check, for a different reason). + for _, data := range []string{"127.0.0.1:19301", "127.0.0.1:19311"} { + _, err = ws.MoveWorkspace(ctx, move("placed", "node-b", data, "127.0.0.1:19312")) + if err == nil || strings.Contains(err.Error(), "move target") || strings.Contains(err.Error(), "move source") { + t.Fatalf("target %s on the node's host: %v; want past the endpoint preconditions", data, err) + } + } +} + +// blockingWriter blocks the first write that contains marker until +// released; other writes pass. +type blockingWriter struct { + marker string + entered, release chan struct{} + once sync.Once +} + +func (b *blockingWriter) Write(p []byte) (int, error) { + if !strings.Contains(string(p), b.marker) { + return len(p), nil + } + first := false + b.once.Do(func() { first = true }) + if first { + close(b.entered) + <-b.release + } + return len(p), nil +} + +// A refused move is logged after workspaceMu is released: while the log +// writer is blocked, another workspace RPC still gets the lock. +func TestWorkspaceMoveRefusalLogsOutsideTheWorkspaceLock(t *testing.T) { + w := &blockingWriter{marker: "MoveWorkspace refused", entered: make(chan struct{}), release: make(chan struct{})} + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, Logger: log.New(w, "", 0), + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(w.release) }) } + defer release() + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + ws := control.NewWorkspaceServiceClient(conn) + if _, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { + _, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "r", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", + TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"}) + done <- err + }() + select { + case <-w.entered: + case <-time.After(10 * time.Second): + t.Fatal("the refusal was never logged") + } + qctx, qcancel := context.WithTimeout(ctx, 5*time.Second) + defer qcancel() + if _, err := ws.QueryWorkspace(qctx, &control.WorkspaceVolume{VolumeId: "v"}); err != nil { + t.Fatalf("workspace RPC while the refusal log is blocked: %v; want workspaceMu free", err) + } + release() + select { + case err := <-done: + if status.Code(err) != codes.FailedPrecondition { + t.Fatalf("move: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("the move did not return after the log was released") + } +} diff --git a/seaweed-block/core/host/master/workspace_move_slot_test.go b/seaweed-block/core/host/master/workspace_move_slot_test.go new file mode 100644 index 0000000000..f6a31dbac6 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_move_slot_test.go @@ -0,0 +1,133 @@ +package master + +import ( + "context" + "strconv" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// The T08 shape: two volumes without per-volume bindings, nodes registered +// at slot 0 of their host. "a1" holds slot 0 on node-a; "a2" lives on +// node-b and moves back to node-a. Its target lands on slot 1 (slot 0 is +// held) and is granted; a target on a1's live slot-0 endpoints is refused by +// the collision check, and one on another host's address by the ownership +// check. The grant routes a2 to the slot-1 endpoints it asked for. +func TestWorkspaceMoveToAnotherSlotOnTheTargetHost(t *testing.T) { + heads := map[string]authority.WorkspaceHead{"a2": {Gen: 9, Epoch: 1, Holder: "node-b/r1", RemoteLSN: 42, Detached: true}} + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + WorkspaceHeadReader: func(_ context.Context, v string) (authority.WorkspaceHead, error) { return heads[v], nil }}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn) + slot := func(base, n int) (string, string) { + return "127.0.0.1:" + strconv.Itoa(base+10*n+1), "127.0.0.1:" + strconv.Itoa(base+10*n+2) + } + for _, n := range []struct { + id string + base int + }{{"node-a", 19100}, {"node-b", 19300}} { + d, c := slot(n.base, 0) + if _, err := m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: n.id, DataAddr: d, CtrlAddr: c}); err != nil { + t.Fatal(err) + } + } + place := func(vol, server string, base int) authority.AuthorityBasis { + t.Helper() + if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: vol, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + if _, err := m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: vol, DesiredRF: 1, + Candidates: []lifecycle.PlacementCandidate{{VolumeID: vol, ServerID: server, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { + t.Fatal(err) + } + d, c := slot(base, 0) + if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: vol, ReplicaId: "r1", DataAddr: d, CtrlAddr: c}}}); err != nil { + t.Fatal(err) + } + if _, err := m.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + return waitAuthorityLine(t, m.Publisher(), vol) + } + a1 := place("a1", "node-a", 19100) // holds node-a slot 0 + a2 := place("a2", "node-b", 19300) + if a1.DataAddr != "127.0.0.1:19101" || a2.DataAddr != "127.0.0.1:19301" { + t.Fatalf("fixture lines a1=%+v a2=%+v", a1, a2) + } + // a2 stops cleanly on node-b: lease, revocation, ACK of its detached HEAD. + id := &control.WorkspaceIdentity{VolumeId: "a2", ReplicaId: "r1", Epoch: a2.Epoch} + if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil { + t.Fatal(err) + } + if _, err := ws.RevokeWorkspace(ctx, id); err != nil { + t.Fatal(err) + } + if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil { + t.Fatal(err) + } + move := func(req, data, ctrl string) *control.WorkspaceMove { + return &control.WorkspaceMove{RequestId: req, VolumeId: "a2", ExpectedReplicaId: "r1", ExpectedEpoch: a2.Epoch, TargetReplicaId: "r1", + TargetServerId: "node-a", TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"} + } + d0, c0 := slot(19100, 0) + if _, err := ws.MoveWorkspace(ctx, move("onto-a1", d0, c0)); err == nil || !strings.Contains(err.Error(), "endpoint belongs to live assignment") { + t.Fatalf("move onto a1's live slot-0 endpoints: %v; want the collision refusal", err) + } + if _, err := ws.MoveWorkspace(ctx, move("other-host", "10.9.9.9:19111", "10.9.9.9:19112")); err == nil || !strings.Contains(err.Error(), `endpoints 10.9.9.9:19111/10.9.9.9:19112 on "node-a" are not registered`) { + t.Fatalf("move to another host's address: %v; want the ownership refusal", err) + } + d1, c1 := slot(19100, 1) + if _, err := ws.MoveWorkspace(ctx, move("ctrl-other-host", d1, "10.9.9.9:19112")); err == nil || !strings.Contains(err.Error(), `on "node-a" are not registered`) { + t.Fatalf("move with its ctrl endpoint on another host: %v; want the ownership refusal", err) + } + // Invalid endpoints on the right host are refused before anything is + // written: the epoch, the journal, the lease and the ACK stay as they were. + before := m.Publisher().WorkspaceState("a2") + for _, bad := range []struct{ name, data, ctrl string }{ + {"non-numeric port", "127.0.0.1:bad", c1}, + {"port 0", "127.0.0.1:0", c1}, + {"port 65536", d1, "127.0.0.1:65536"}, + {"empty port", "127.0.0.1:", c1}, + {"data equals ctrl", d1, d1}, + } { + if _, err := ws.MoveWorkspace(ctx, move("bad-"+bad.name, bad.data, bad.ctrl)); err == nil || !strings.Contains(err.Error(), "move target endpoints invalid") { + t.Fatalf("%s: %v; want the invalid-endpoint refusal", bad.name, err) + } + after := m.Publisher().WorkspaceState("a2") + line, _ := m.Publisher().VolumeAuthorityLine("a2") + if line.Epoch != a2.Epoch || after == nil || len(after.Moves) != 0 || after.Ack == nil || before.Ack == nil || *after.Ack != *before.Ack || after.Lease == nil || !after.Lease.Revoking { + t.Fatalf("%s: state changed by a refused move: line %+v state %+v", bad.name, line, after) + } + } + g, err := ws.MoveWorkspace(ctx, move("slot-1", d1, c1)) + if err != nil { + t.Fatalf("move to node-a slot 1 while slot 0 is held: %v", err) + } + line, ok := m.Publisher().VolumeAuthorityLine("a2") + if !g.Issued || g.NewHost != "node-a" || g.OldHost != "node-b" || !ok || line.Epoch != g.NewEpoch || line.DataAddr != d1 || line.CtrlAddr != c1 { + t.Fatalf("grant %+v line %+v; want a2 issued on node-a at %s/%s", g, line, d1, c1) + } + if l1, _ := m.Publisher().VolumeAuthorityLine("a1"); l1.DataAddr != d0 || l1.Epoch != a1.Epoch { + t.Fatalf("a1 changed: %+v", l1) + } +} diff --git a/seaweed-block/core/host/master/workspace_renewal_boundary_test.go b/seaweed-block/core/host/master/workspace_renewal_boundary_test.go index afab27803b..4cf6c385c3 100644 --- a/seaweed-block/core/host/master/workspace_renewal_boundary_test.go +++ b/seaweed-block/core/host/master/workspace_renewal_boundary_test.go @@ -69,7 +69,9 @@ func TestWorkspaceHeldRenewalBoundary(t *testing.T) { if err != nil { t.Fatal(err) } - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + // No wall-clock bound on the test context (#227): the held client + // is released by the test; only the guard's own RPC timeout remains. + ctx, cancel := context.WithCancel(context.Background()) defer cancel() if err := g.Refresh(ctx); err != nil { t.Fatal(err) @@ -99,10 +101,13 @@ func TestWorkspaceHeldRenewalBoundary(t *testing.T) { case <-ctx.Done(): t.Fatal("renewal did not enter", ctx.Err()) } + // A renewal is answered from memory: the grant is in the reply, and + // the durable lease holds the horizon (>= every grant), so the + // persisted expiry is not the grant any more (#205). renewed := *p.WorkspaceState("v").Lease freshEarly := requestStart.Add(time.Duration(reply.ValidForNs)) - if freshEarly.Sub(oldEarly) < time.Second || renewed.ExpiresAtNS <= oldLease.ExpiresAtNS || renewed.MaxClockSkewNS != int64(4*time.Second) { - t.Fatal("fixture did not extend the real persisted grant", oldLease, renewed) + if freshEarly.Sub(oldEarly) < time.Second || reply.ExpiresAtNs <= client.initial.ExpiresAtNs || renewed.ExpiresAtNS < reply.ExpiresAtNs || renewed.MaxClockSkewNS != int64(4*time.Second) { + t.Fatal("fixture did not extend the grant under the durable horizon", client.initial, reply, oldLease, renewed) } arrival := oldEarly.Add(-time.Second) if late { @@ -135,8 +140,14 @@ func TestWorkspaceHeldRenewalBoundary(t *testing.T) { } q := authority.WorkspaceMoveRequest{RequestID: "renewed-forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} head := authority.WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42} - boundary := time.Unix(0, renewed.ExpiresAtNS).Add(time.Duration(renewed.MaxClockSkewNS)) - for _, when := range []time.Time{time.Unix(0, oldLease.ExpiresAtNS).Add(4 * time.Second), boundary.Add(-time.Nanosecond)} { + // The barrier is max(durable horizon, renewed grant) + skew; the old + // grant's expiry plus skew is still too early. + barrierBase := renewed.ExpiresAtNS + if reply.ExpiresAtNs > barrierBase { + barrierBase = reply.ExpiresAtNs + } + boundary := time.Unix(0, barrierBase).Add(time.Duration(renewed.MaxClockSkewNS)) + for _, when := range []time.Time{time.Unix(0, client.initial.ExpiresAtNs).Add(4 * time.Second), time.Unix(0, reply.ExpiresAtNs).Add(4 * time.Second), boundary.Add(-time.Nanosecond)} { masterNS.Store(when.UnixNano()) if _, err := p.MoveWorkspace(ctx, q, head); err == nil { t.Fatal("forced move ignored renewed expiry plus persisted margin") diff --git a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go new file mode 100644 index 0000000000..a00a3d48ca --- /dev/null +++ b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go @@ -0,0 +1,261 @@ +package master + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" +) + +// slowGuardStore holds every workspace-lease Put, once armed, until a lease +// renewal that STARTED after the Put entered has succeeded (issue #205): a slow +// store write, with the slowness defined by progress instead of a fixed sleep. +// Each held Put takes a generation; a renewal is credited with the generation +// it observed before its call, so a reply computed before the hold never +// releases it. +type slowGuardStore struct { + authority.AuthorityStore + armed atomic.Bool + gen atomic.Int64 // generation of the latest held Put + credited atomic.Int64 // highest generation a fresh renewal was started under + renewals atomic.Int64 // successful renewals seen by the client + kick chan struct{} // a renewal succeeded (buffered 1) + stop chan struct{} // closed by release(): frees any held Put + stopOnce sync.Once + held atomic.Int64 // lease writes that were held and then completed +} + +func newSlowGuardStore(s authority.AuthorityStore) *slowGuardStore { + return &slowGuardStore{AuthorityStore: s, kick: make(chan struct{}, 1), stop: make(chan struct{})} +} + +// release disarms and frees every held Put; idempotent. +func (s *slowGuardStore) release() { + s.armed.Store(false) + s.stopOnce.Do(func() { close(s.stop) }) +} + +// renewed credits a successful renewal that started under generation g. +func (s *slowGuardStore) renewed(g int64) { + s.renewals.Add(1) + for { + c := s.credited.Load() + if g <= c || s.credited.CompareAndSwap(c, g) { + break + } + } + select { + case s.kick <- struct{}{}: + default: + } +} + +func (s *slowGuardStore) Put(r authority.DurableRecord) error { + if s.armed.Load() && r.Workspace != nil && r.Workspace.Lease != nil { + g := s.gen.Add(1) + for s.credited.Load() < g { + select { + case <-s.kick: + case <-s.stop: + return s.AuthorityStore.Put(r) + } + } + defer s.held.Add(1) + } + return s.AuthorityStore.Put(r) +} + +// deadlineLeaseClient calls the publisher through the master's leaseFact and, +// like a gRPC client, returns at the caller's deadline even when the master +// call is still blocked. In-flight calls are joined before the store closes. +type deadlineLeaseClient struct { + p *authority.Publisher + inflight *sync.WaitGroup + slow *slowGuardStore // optional: told about each successful renewal +} + +func (c deadlineLeaseClient) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity, _ ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + type result struct { + fact *control.WorkspaceLeaseFact + err error + } + var g int64 + if c.slow != nil { + g = c.slow.gen.Load() // a reply can only release holds that entered before this call + } + done := make(chan result, 1) + c.inflight.Add(1) + go func() { + defer c.inflight.Done() + l, err := c.p.RenewWorkspaceLease(context.Background(), id.VolumeId, id.ReplicaId, id.Epoch) + if err != nil { + done <- result{err: err} + return + } + done <- result{fact: leaseFact(id.VolumeId, l)} + }() + select { + case r := <-done: + if r.err == nil && c.slow != nil { + c.slow.renewed(g) + } + return r.fact, r.err + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func (deadlineLeaseClient) AckWorkspaceRevoked(context.Context, *control.WorkspaceRevocationAck, ...grpc.CallOption) (*control.WorkspaceEmpty, error) { + panic("a slow store must not lead to a clean ACK") +} + +// A live host must keep its lease while the master's authority store is slow: +// a store write longer than the host's 2 s renewal timeout must not fence the +// guard and shut the volume down (issue #205). TTL 6 s gives the guard 4 s of +// validity (6 s minus half the default 4 s skew), renewed every ~1.3 s. +func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) { + disk, err := authority.NewFileAuthorityStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + slow := newSlowGuardStore(disk) + var inflight sync.WaitGroup + t.Cleanup(func() { + slow.release() + inflight.Wait() + if err := disk.Close(); err != nil { + t.Error(err) + } + }) + dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)} + p := authority.NewPublisher(dir, authority.WithStore(slow), authority.WithWorkspaceLeaseConfig(6*time.Second, nil)) + t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes + t.Cleanup(slow.release) // runs before the join above: frees a held Put first + seedSkewPublisher(t, p, dir) + var stops atomic.Int32 + g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, + deadlineLeaseClient{p: p, inflight: &inflight, slow: slow}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, + func(context.Context) (uint64, error) { stops.Add(1); return 7, nil }, nil) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + runDone := make(chan error, 1) + go func() { runDone <- g.Run(ctx) }() + t.Cleanup(func() { + cancel() + <-runDone // Run returns on cancel; the go test timeout bounds a hang + }) + t.Cleanup(slow.release) // first of all cleanups: a held Put never blocks the joins + for !g.Projection().Healthy { // progress: the first grant + time.Sleep(20 * time.Millisecond) + } + + // Every lease write is now held until a renewal succeeded during its hold, + // so a renewal that waited for the store would deadlock this test. The + // sampler records any fence while armed; three held writes must complete. + var fenced atomic.Bool + sampled := make(chan struct{}) + slow.armed.Store(true) + go func() { + defer close(sampled) + for slow.armed.Load() { + if !g.Projection().Healthy || stops.Load() != 0 { + fenced.Store(true) + } + time.Sleep(20 * time.Millisecond) + } + }() + for slow.held.Load() < 3 { + if fenced.Load() { + break + } + time.Sleep(20 * time.Millisecond) + } + slow.armed.Store(false) + <-sampled + if fenced.Load() || !g.Projection().Healthy || stops.Load() != 0 { + t.Fatalf("guard fenced while lease writes were held behind renewals (held=%d renewals=%d stops=%d)", slow.held.Load(), slow.renewals.Load(), stops.Load()) + } + t.Logf("guard stayed healthy through %d held lease writes (%d renewals)", slow.held.Load(), slow.renewals.Load()) +} + +// A durable deletion-reservation write of an unrelated volume must not block +// a lease renewal: the renewal RPC checks Deletions.Reserved and the volume +// record, and both lifecycle stores hold their mutex across file I/O +// (issue #205). +func TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite(t *testing.T) { + h, c, ctx := reviewBindingHost(t) + reviewLegacyBind(t, h, c, ctx, "vol-b") + line := waitAuthorityLine(t, h.Publisher(), "vol-b") + svc := &services{host: h} + id := &control.WorkspaceIdentity{VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch} + if _, err := svc.RenewWorkspaceLease(ctx, id); err != nil { + t.Fatal(err) // first grant + } + deletions := h.Lifecycle().Deletions + entered, release := make(chan struct{}), make(chan struct{}) + var enterOnce, releaseOnce sync.Once + releaseHook := func() { releaseOnce.Do(func() { close(release) }) } + deletions.SetPersistHookForTest(func() error { + enterOnce.Do(func() { close(entered) }) + <-release + return nil + }) + admitted := make(chan error, 1) + go func() { + _, err := deletions.Admit("vol-x", "tok") // an unrelated volume, a real durable write + admitted <- err + }() + renewed := make(chan error, 1) + renewStarted := false + // Bounded cleanup: release the hook first, settle BOTH workers, and only + // then clear the hook. Never call the setter after a timed-out join: the + // store mutex may still be held. + t.Cleanup(func() { + releaseHook() + settled := true + select { + case <-admitted: + case <-time.After(5 * time.Second): + settled = false + t.Error("held reservation write did not settle within 5 s after release") + } + if renewStarted { + select { + case <-renewed: + case <-time.After(5 * time.Second): + settled = false + t.Error("renewal did not settle within 5 s after release") + } + } + if settled { + deletions.SetPersistHookForTest(nil) + } + }) + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("reservation write never reached the store") + } + start := time.Now() + renewStarted = true + go func() { _, err := svc.RenewWorkspaceLease(ctx, id); renewed <- err }() + select { + case err := <-renewed: + renewed <- err // keep it for the cleanup join + if err != nil { + t.Fatalf("renewal of vol-b: %v", err) + } + t.Logf("renewal RPC of vol-b took %s while vol-x's reservation write was held", time.Since(start)) + case <-time.After(2 * time.Second): + t.Fatalf("renewal RPC of vol-b was still blocked %s behind the held reservation write of vol-x", time.Since(start).Round(time.Millisecond)) + } +} diff --git a/seaweed-block/core/host/master/workspace_restore_test.go b/seaweed-block/core/host/master/workspace_restore_test.go index ac7ddbd188..95282bf1c2 100644 --- a/seaweed-block/core/host/master/workspace_restore_test.go +++ b/seaweed-block/core/host/master/workspace_restore_test.go @@ -6,7 +6,6 @@ import ( "reflect" "sync/atomic" "testing" - "time" "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/frontend" @@ -33,7 +32,9 @@ func (r *restoreRemote) Get(ctx context.Context, key string) ([]byte, error) { // Keep the old projection stale to model delayed assignment delivery; a HEAD // takeover must independently refuse its cut and then stop its frontend I/O. func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + // No wall-clock bound (#227): each step completes or the go test timeout + // reports the hang; a 10 s context failed the HEAD claim under load. + ctx, cancel := context.WithCancel(context.Background()) defer cancel() m := newTestMaster(t, t.TempDir()) defer closeTestMaster(t, m) diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 0a4da5644a..fabe00514c 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -2,6 +2,8 @@ package master import ( "context" + "fmt" + "strings" "time" "github.com/seaweedfs/seaweed-block/core/authority" @@ -28,6 +30,29 @@ func (s *services) workspaceVolume(volume string) error { return nil } +// workspaceVolumeForRenewal is workspaceVolume for lease renewal: it reads +// the published snapshots of the lifecycle stores instead of taking their +// mutexes, which writers hold across file I/O. A renewal during an in-flight +// lifecycle write sees the last published state; deletion admission itself +// stays in the publisher (RecordWorkspaceDeletion needs a clean revocation +// ACK for a live authority line). +func (s *services) workspaceVolumeForRenewal(volume string) error { + if !s.host.cfg.WorkspaceRPC { + return status.Error(codes.FailedPrecondition, "workspace RPC disabled") + } + if s.host.lifecycle == nil { + return status.Error(codes.FailedPrecondition, "lifecycle store unavailable") + } + r, ok := s.host.lifecycle.Volumes.GetVolumeSnapshot(volume) + if !ok || r.Spec.ReplicationFactor != 1 { + return status.Error(codes.FailedPrecondition, "workspace move requires an existing RF1 volume") + } + if s.host.lifecycle.Deletions.ReservedSnapshot(volume) { + return status.Error(codes.FailedPrecondition, "workspace: volume is being deleted") + } + return nil +} + func workspaceError(err error) error { if err == nil { return nil @@ -61,7 +86,7 @@ func leaseFact(volume string, l authority.WorkspaceLease) *control.WorkspaceLeas } func (s *services) RenewWorkspaceLease(ctx context.Context, q *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) { - if err := s.workspaceVolume(q.GetVolumeId()); err != nil { + if err := s.workspaceVolumeForRenewal(q.GetVolumeId()); err != nil { return nil, err } l, err := s.host.Publisher().RenewWorkspaceLease(ctx, q.GetVolumeId(), q.GetReplicaId(), q.GetEpoch()) @@ -78,11 +103,12 @@ func (s *services) RevokeWorkspace(ctx context.Context, q *control.WorkspaceIden if err := s.host.Publisher().BeginWorkspaceRevocation(ctx, q.GetVolumeId(), q.GetReplicaId(), q.GetEpoch()); err != nil { return nil, workspaceError(err) } - state := s.host.Publisher().WorkspaceState(q.GetVolumeId()) - if state == nil || state.Lease == nil { + // Report what was granted, never the durable horizon. + lease, ok := s.host.Publisher().WorkspaceLeaseReply(q.GetVolumeId()) + if !ok { return nil, status.Error(codes.FailedPrecondition, "workspace moved during revocation") } - return leaseFact(q.GetVolumeId(), *state.Lease), nil + return leaseFact(q.GetVolumeId(), lease), nil } func (s *services) AckWorkspaceRevoked(ctx context.Context, q *control.WorkspaceRevocationAck) (*control.WorkspaceEmpty, error) { @@ -119,6 +145,14 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) } // Remote reads never hold the workspace mutation lock. Re-read every // local precondition below; Publisher checks the expected epoch atomically. + // A refusal is logged after the lock is released (deferred first, so it + // runs last): a slow log writer never holds workspaceMu. + var refusal string + defer func() { + if refusal != "" { + s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal) + } + }() s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() if err := ctx.Err(); err != nil { @@ -133,14 +167,32 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if err != nil { return nil, workspaceError(err) } - matched := !explicit && target.DataAddr == q.GetTargetDataAddr() && target.CtrlAddr == q.GetTargetCtrlAddr() + // A volume without per-volume bindings may move to any port on the + // target node's registered hosts (a host runs several slots): the host + // match ties the endpoints to that node's registration (it trusts the + // registration; it is not an identity proof). The collision check below + // still refuses endpoints another assignment or binding owns. + matched := !explicit && sameHost(q.GetTargetDataAddr(), target.DataAddr) && sameHost(q.GetTargetCtrlAddr(), target.CtrlAddr) + endpointErr := lifecycle.ValidateWorkspaceEndpoints(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: q.GetTargetServerId(), DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}) for _, b := range bindings { if !b.Retired && b.ServerID == q.GetTargetServerId() && b.DataAddr == q.GetTargetDataAddr() && b.CtrlAddr == q.GetTargetCtrlAddr() { matched = true } } - if oldHost == "" || !ok || target.ServerID == oldHost || !matched { - return nil, status.Error(codes.FailedPrecondition, "move needs known source slot and registered target endpoints") + switch { + case endpointErr != nil: + refusal = fmt.Sprintf("move target endpoints invalid: %v", endpointErr) + case oldHost == "": + refusal = fmt.Sprintf("move source unknown: no issued move or placement names replica %q at epoch %d", q.GetExpectedReplicaId(), q.GetExpectedEpoch()) + case !ok: + refusal = fmt.Sprintf("move target node %q is not registered", q.GetTargetServerId()) + case target.ServerID == oldHost: + refusal = fmt.Sprintf("move target %q is the current source host", target.ServerID) + case !matched: + refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit)) + } + if refusal != "" { + return nil, status.Error(codes.FailedPrecondition, refusal) } if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { return nil, workspaceError(err) @@ -156,6 +208,32 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) return grantFact(r), nil } +// sameHost reports whether two host:port addresses name the same host: +// canonical host parts (equivalent IP spellings equal), no name resolution. +func sameHost(a, b string) bool { + ha := lifecycle.WorkspaceEndpointHost(a) + return ha != "" && ha == lifecycle.WorkspaceEndpointHost(b) +} + +// registeredTargetEndpoints describes what a move to target may name: the +// node's own pair for a volume without explicit bindings, else its live +// bindings on that node. +func registeredTargetEndpoints(target lifecycle.NodeRegistration, bindings []lifecycle.WorkspaceBinding, explicit bool) string { + if !explicit { + return fmt.Sprintf("not on the node's hosts: it registers %s/%s; no per-volume binding is prepared", target.DataAddr, target.CtrlAddr) + } + var live []string + for _, b := range bindings { + if !b.Retired && b.ServerID == target.ServerID { + live = append(live, b.DataAddr+"/"+b.CtrlAddr) + } + } + if len(live) == 0 { + return "the volume has explicit bindings but none live on that node" + } + return "live bindings on that node: " + strings.Join(live, ", ") +} + func (s *services) QueryWorkspace(ctx context.Context, q *control.WorkspaceVolume) (*control.WorkspaceStatus, error) { s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() @@ -174,8 +252,8 @@ func (s *services) QueryWorkspace(ctx context.Context, q *control.WorkspaceVolum if state == nil { return out, nil } - if state.Lease != nil { - out.Lease = leaseFact(q.GetVolumeId(), *state.Lease) + if lease, ok := s.host.Publisher().WorkspaceLeaseReply(q.GetVolumeId()); ok { + out.Lease = leaseFact(q.GetVolumeId(), lease) // granted expiry, not the durable horizon } if state.Ack != nil { out.RevocationAck = &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: q.GetVolumeId(), ReplicaId: state.Ack.ReplicaID, Epoch: state.Ack.Epoch}, HeadGen: state.Ack.HeadGen} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index afb8cd99cb..a0053962cb 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -45,8 +45,63 @@ type ChunkCutResponse struct { Holder string `json:"holder"` Noop bool `json:"noop"` FullHash bool `json:"fullHash"` - // The cut statistics (§3.1) are added when W3 fills them; until then - // the body omits them rather than report zeros (B9 W2 appendix). + // Stats are the statistics the chunk layer measured for this cut + // (§3.1). A zero field is "not measured" or "none" (a Noop cut + // uploads nothing). + Stats ChunkCutStatsBody `json:"stats"` +} + +// ChunkCutStatsBody is one cut's statistics in the /chunk/cut body. It +// mirrors storage.ChunkCutStats field for field (a test keeps the two in +// step); every duration is in nanoseconds. +type ChunkCutStatsBody struct { + COWSavedChunks int `json:"cowSavedChunks"` + COWSaveNs int64 `json:"cowSaveNs"` + COWWaitNs int64 `json:"cowWaitNs"` + BarrierPauseNs int64 `json:"barrierPauseNs"` + LockWaitNs int64 `json:"lockWaitNs"` + SyncNs int64 `json:"syncNs"` + CopyNs int64 `json:"copyNs"` + CandidateChunks int `json:"candidateChunks"` + UploadedChunks int `json:"uploadedChunks"` + UploadedBytes int64 `json:"uploadedBytes"` + ZeroedChunks int `json:"zeroedChunks"` + UnchangedChunks int `json:"unchangedChunks"` + UploadNs int64 `json:"uploadNs"` + CASNs int64 `json:"casNs"` + CASResult string `json:"casResult"` + TotalNs int64 `json:"totalNs"` + StageRounds int `json:"stageRounds"` + StagedChunks int `json:"stagedChunks"` + StagedChunksUsed int `json:"stagedChunksUsed"` + BarrierCopyChunks int `json:"barrierCopyChunks"` + BarrierOverBound bool `json:"barrierOverBound"` +} + +func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { + return ChunkCutStatsBody{ + BarrierPauseNs: s.BarrierPauseNs, + LockWaitNs: s.LockWaitNs, + SyncNs: s.SyncNs, + CopyNs: s.CopyNs, + COWSavedChunks: s.COWSavedChunks, + COWSaveNs: s.COWSaveNs, + COWWaitNs: s.COWWaitNs, + CandidateChunks: s.CandidateChunks, + UploadedChunks: s.UploadedChunks, + UploadedBytes: s.UploadedBytes, + ZeroedChunks: s.ZeroedChunks, + UnchangedChunks: s.UnchangedChunks, + UploadNs: s.UploadNs, + CASNs: s.CASNs, + CASResult: s.CASResult, + TotalNs: s.TotalNs, + StageRounds: s.StageRounds, + StagedChunks: s.StagedChunks, + StagedChunksUsed: s.StagedChunksUsed, + BarrierCopyChunks: s.BarrierCopyChunks, + BarrierOverBound: s.BarrierOverBound, + } } // ChunkSnapshotRequest is POST /chunk/snapshot's request (§3.2), without @@ -104,6 +159,7 @@ const ( codeFenced = "fenced" codeHeadConflict = "head_conflict" codeClosing = "closing" + codeDetachAborted = "detach_aborted" // the detach did not happen; the volume keeps serving here codeLSNBehind = "lsn_behind" codeInternal = "internal" codeBadRequest = "bad_request" @@ -174,6 +230,13 @@ func writeChunkFailure(w http.ResponseWriter, err error) { func chunkErrorCode(err error) (int, string, bool) { var ce *chunkstore.CatalogError switch { + case errors.Is(err, durable.ErrDetachAborted): + // Before any cause (a catalog error included): nothing was + // published and serving resumed here. + return http.StatusConflict, codeDetachAborted, true + case errors.Is(err, durable.ErrDetachOutcomeUnknown): + // Before any cause: the detach may still have landed; I/O stays stopped. + return http.StatusServiceUnavailable, chunkstore.CodeOutcomeUnknown, true case errors.As(err, &ce): return catalogStatus(ce.Code), ce.Code, ce.Retryable case errors.Is(err, storage.ErrChunkLayerFenced): @@ -207,6 +270,8 @@ func chunkErrorCode(err error) (int, string, bool) { return http.StatusConflict, chunkstore.CodeNotChunkVolume, false case errors.Is(err, context.DeadlineExceeded): return http.StatusServiceUnavailable, chunkstore.CodeDeadlineExceeded, true + case errors.Is(err, storage.ErrCutCOWAborted): + return http.StatusServiceUnavailable, "cut_aborted", true default: return http.StatusInternalServerError, codeInternal, false } @@ -455,7 +520,7 @@ func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64) return ChunkCutResponse{}, err } return ChunkCutResponse{VolumeID: volumeID, CutLSN: r.H, HeadGen: r.Head.Gen, HeadEpoch: r.Head.Epoch, Holder: r.Head.Holder, - Noop: r.Noop, FullHash: r.FullHash}, nil + Noop: r.Noop, FullHash: r.FullHash, Stats: cutStatsBody(r.Stats)}, nil } // Snapshot resolves the request against the catalog first (§3.2 step 1): diff --git a/seaweed-block/core/host/volume/chunk_control_adapter_test.go b/seaweed-block/core/host/volume/chunk_control_adapter_test.go index e2e933f955..c84cfb7877 100644 --- a/seaweed-block/core/host/volume/chunk_control_adapter_test.go +++ b/seaweed-block/core/host/volume/chunk_control_adapter_test.go @@ -2,6 +2,10 @@ package volume import ( "context" + "encoding/json" + "fmt" + "reflect" + "sync" "testing" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" @@ -17,6 +21,30 @@ type fakeChunkProvider struct { lastMin uint64 } +type adapterManifestFiler struct { + chunkstore.Filer + mu sync.Mutex + blobs map[string][]byte +} + +func (f *adapterManifestFiler) Put(_ context.Context, b []byte) (string, error) { + f.mu.Lock() + defer f.mu.Unlock() + id := fmt.Sprintf("fixture-%d", len(f.blobs)) + f.blobs[id] = append([]byte(nil), b...) + return id, nil +} + +func (f *adapterManifestFiler) Get(_ context.Context, id string) ([]byte, error) { + f.mu.Lock() + defer f.mu.Unlock() + b, ok := f.blobs[id] + if !ok { + return nil, chunkstore.ErrNotFound + } + return append([]byte(nil), b...), nil +} + func (f *fakeChunkProvider) CutVolume(_ context.Context, _ string, minLSN uint64) (storage.ChunkCutResult, error) { f.cuts++ f.lastMin = minLSN @@ -34,8 +62,17 @@ func adapterFixture(t *testing.T) (*fakeChunkProvider, ChunkControl) { t.Helper() head := storage.ChunkHead{Gen: 3, Epoch: 2, Holder: "r1", RemoteLSN: 9, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e2/c0/k1"}, 5: {Key: "chunks/e2/c5/k2"}}} + f := &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}} + r, err := chunkstore.NewChunkRemote(f, f, "/swblock/chunks/v1") + if err != nil { + t.Fatal(err) + } + head, _, err = r.PrepareManifest(context.Background(), storage.ChunkHead{}, head, 8*4096) + if err != nil { + t.Fatal(err) + } fp := &fakeChunkProvider{cut: storage.ChunkCutResult{H: 9, Head: head}} - cat, err := chunkstore.NewCatalog(chunkstore.NewMemFiler(), "/swblock/chunks") + cat, err := chunkstore.NewCatalog(f, "/swblock/chunks") if err != nil { t.Fatal(err) } @@ -79,6 +116,75 @@ func TestChunkControl_SnapshotStoresTheCutHead(t *testing.T) { } } +// The cut body carries the statistics the chunk layer measured for that +// cut (§3.1), so a caller can see what one cut cost: the barrier pause, +// the chunks and bytes it uploaded, the chunks it found unchanged. +func TestChunkControl_CutReturnsTheLayerStats(t *testing.T) { + ctx := context.Background() + fp, ctl := adapterFixture(t) + fp.cut.Stats = storage.ChunkCutStats{BarrierPauseNs: 1500, SyncNs: 700, CandidateChunks: 4, UploadedChunks: 3, + UploadedBytes: 3 << 22, UnchangedChunks: 1, CASResult: "ok", TotalNs: 9000, BarrierCopyChunks: 2} + r, err := ctl.Cut(ctx, "v1", 0) + if err != nil { + t.Fatal(err) + } + raw, err := json.Marshal(r) + if err != nil { + t.Fatal(err) + } + var body struct { + Stats map[string]any `json:"stats"` + } + if err := json.Unmarshal(raw, &body); err != nil { + t.Fatal(err) + } + want := map[string]any{"barrierPauseNs": float64(1500), "syncNs": float64(700), "candidateChunks": float64(4), + "uploadedChunks": float64(3), "uploadedBytes": float64(3 << 22), "unchangedChunks": float64(1), "casResult": "ok", + "totalNs": float64(9000), "barrierCopyChunks": float64(2), "barrierOverBound": false} + for k, v := range want { + if body.Stats[k] != v { + t.Fatalf("cut body stats[%q] = %v, want %v (body %s)", k, body.Stats[k], v, raw) + } + } +} + +// ChunkCutStatsBody mirrors storage.ChunkCutStats: a field added to the +// layer's statistics must also reach the body. +func TestChunkCutStatsBody_MirrorsTheLayerStats(t *testing.T) { + layer, body := reflect.TypeOf(storage.ChunkCutStats{}), reflect.TypeOf(ChunkCutStatsBody{}) + if layer.NumField() != body.NumField() { + t.Fatalf("storage.ChunkCutStats has %d fields, ChunkCutStatsBody %d", layer.NumField(), body.NumField()) + } + for i := 0; i < layer.NumField(); i++ { + lf, ok := body.FieldByName(layer.Field(i).Name) + if !ok || lf.Type != layer.Field(i).Type { + t.Fatalf("ChunkCutStatsBody lacks %s %s", layer.Field(i).Name, layer.Field(i).Type) + } + } + // Every field is copied: set each one to a distinct value and compare. + var s storage.ChunkCutStats + v := reflect.ValueOf(&s).Elem() + for i := 0; i < v.NumField(); i++ { + switch f := v.Field(i); f.Kind() { + case reflect.Int, reflect.Int64: + f.SetInt(int64(i + 1)) + case reflect.String: + f.SetString("s") + case reflect.Bool: + f.SetBool(true) + default: + t.Fatalf("field %s: unhandled kind %s", v.Type().Field(i).Name, f.Kind()) + } + } + got := reflect.ValueOf(cutStatsBody(s)) + for i := 0; i < v.NumField(); i++ { + name := v.Type().Field(i).Name + if !reflect.DeepEqual(got.FieldByName(name).Interface(), v.Field(i).Interface()) { + t.Fatalf("cutStatsBody drops %s: got %v, want %v", name, got.FieldByName(name).Interface(), v.Field(i).Interface()) + } + } +} + func TestChunkControl_CutMinLSNAndDetach(t *testing.T) { ctx := context.Background() fp, ctl := adapterFixture(t) diff --git a/seaweed-block/core/host/volume/chunk_control_test.go b/seaweed-block/core/host/volume/chunk_control_test.go index aff00be7f8..6c8c76722d 100644 --- a/seaweed-block/core/host/volume/chunk_control_test.go +++ b/seaweed-block/core/host/volume/chunk_control_test.go @@ -159,8 +159,8 @@ func TestStatusServer_ChunkSuccessBodiesUseSpecFields(t *testing.T) { ctl.deadline < chunkstore.DefaultOpDeadline-time.Minute || ctl.deadline > chunkstore.DefaultOpDeadline { t.Fatalf("cut with a huge timeoutMs: %d (deadline %v), want OpDeadline", w.Code, ctl.deadline) } - // The cut statistics are omitted until W3 fills them (B9 W2 appendix). - wantKeys(t, "cut", jsonKeys(t, w.Body.Bytes()), "volumeID", "cutLSN", "headGen", "headEpoch", "holder", "noop", "fullHash") + // The chunk layer fills the cut statistics (§3.1), so the body carries them. + wantKeys(t, "cut", jsonKeys(t, w.Body.Bytes()), "volumeID", "cutLSN", "headGen", "headEpoch", "holder", "noop", "fullHash", "stats") w = serve(t, s, http.MethodPost, "/chunk/snapshot", `{"volumeID":"v1","name":"s1","requestID":"r","labels":{"agent.step":"x"},"consistency":"app","expiresAtNs":9}`, "") if w.Code != 200 || ctl.lastSnap.Name != "s1" || ctl.lastSnap.RequestID != "r" || ctl.lastSnap.Consistency != "app" || ctl.lastSnap.Labels["agent.step"] != "x" || ctl.lastSnap.ExpiresAtNs != 9 { @@ -218,9 +218,15 @@ func TestStatusServer_ChunkErrorBodyIsTyped(t *testing.T) { {fmt.Errorf("%w: %w", storage.ErrChunkReconciling, context.DeadlineExceeded), "reconciling", 409, true}, {fmt.Errorf("x: %w", storage.ErrChunkCASOutcomeUnknown), "outcome_unknown", 503, true}, {fmt.Errorf("x: %w", storage.ErrChunkHeadPrecondition), "head_conflict", 409, true}, + {fmt.Errorf("save: %w", storage.ErrCutCOWAborted), "cut_aborted", 503, true}, {fmt.Errorf("x: %w", storage.ErrChunkRemoteUnavailable), "remote_unavailable", 503, true}, {fmt.Errorf("x: %w", storage.ErrChunkLayerClosed), "closing", 503, false}, {fmt.Errorf("x: %w", storage.ErrChunkLayerDetached), "closing", 409, false}, + {fmt.Errorf("%w: %w", durable.ErrDetachAborted, storage.ErrChunkRemoteUnavailable), "detach_aborted", 409, true}, + // The detach sentinels decide even over a catalog-error cause (which + // alone maps to its own code), and without the storage CAS sentinel. + {fmt.Errorf("%w: %w", durable.ErrDetachAborted, &chunkstore.CatalogError{Code: chunkstore.CodeSnapshotExists, Message: "m"}), "detach_aborted", 409, true}, + {fmt.Errorf("%w: %w", durable.ErrDetachOutcomeUnknown, &chunkstore.CatalogError{Code: chunkstore.CodeSnapshotExists, Message: "m"}), "outcome_unknown", 503, true}, {fmt.Errorf("%w: %w: cut LSN 1, HEAD remote_lsn 10", storage.ErrChunkCaptureRefused, storage.ErrChunkLSNBehind), "lsn_behind", 409, false}, {&chunkstore.CatalogError{Code: chunkstore.CodeInvalidLabel, Message: "m"}, "invalid_label", 400, false}, {fmt.Errorf("x: %w", durable.ErrNotChunkVolume), "not_chunk_volume", 409, false}, diff --git a/seaweed-block/core/host/volume/chunk_cow_stats_red_test.go b/seaweed-block/core/host/volume/chunk_cow_stats_red_test.go new file mode 100644 index 0000000000..405ad36bcf --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_cow_stats_red_test.go @@ -0,0 +1,60 @@ +package volume + +import ( + "encoding/json" + "reflect" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Keep the new cut-body counters as a caller-visible contract. Reflection +// lets this RED compile on main before the COW fields are implemented. +func TestChunkCutStatsBody_ExposesCOWCounters(t *testing.T) { + var stats storage.ChunkCutStats + fields := []struct { + goName, jsonName string + value int64 + }{ + {"COWSavedChunks", "cowSavedChunks", 31}, + {"COWSaveNs", "cowSaveNs", 47}, + {"COWWaitNs", "cowWaitNs", 59}, + } + value := reflect.ValueOf(&stats).Elem() + for _, field := range fields { + target := value.FieldByName(field.goName) + if !target.IsValid() { + t.Errorf("RED: storage cut stats lack %s", field.goName) + continue + } + if target.Kind() != reflect.Int && target.Kind() != reflect.Int64 { + t.Errorf("counter %s has unexpected kind %s", field.goName, target.Kind()) + continue + } + target.SetInt(field.value) + } + raw, err := json.Marshal(cutStatsBody(stats)) + if err != nil { + t.Fatal(err) + } + // Other cut-body fields include strings/bools, so decode only the named + // integer counters from RawMessage rather than accepting a partial decode. + var members map[string]json.RawMessage + if err = json.Unmarshal(raw, &members); err != nil { + t.Fatal(err) + } + for _, field := range fields { + member, exists := members[field.jsonName] + if !exists { + t.Errorf("RED: cut response lacks %s", field.jsonName) + continue + } + var number int64 + if err = json.Unmarshal(member, &number); err != nil { + t.Fatalf("counter %s: %v", field.jsonName, err) + } + if number != field.value { + t.Errorf("counter %s=%d want %d", field.jsonName, number, field.value) + } + } +} diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 1bea934d13..bd077186d4 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -66,6 +66,11 @@ type Config struct { // their documented non-healthy projection). EnableT1Readiness bool WorkspaceLease bool // Opt-in: require a workspace lease before I/O or capture. + // RF1Only, when set, is why this volume serves single-replica only + // (walstore-chunk): every assignment with replica slots, primary with + // peers or supporting replica, is refused before any peer set, role or + // readiness is installed, and latched like a failed role admission. + RF1Only string // ReplicationVolume, when non-nil, receives peer-set updates on // every self-replica AssignmentFact. The Host calls @@ -143,6 +148,15 @@ type Host struct { // even on a host that was healthy at its prior epoch; only a later // successful role call for the current role and epoch clears it. roleAdmissionFailed atomic.Value // string reason; "" = not failed + // RF1Only admission state, one unit under rf1Mu (field access only, no + // calls): the highest refused epoch with its reason ("" = cleared), and the + // highest epoch an RF1 fact was admitted at. A clear removes only the + // refusal it can still see as not newer than its own fact. + rf1Mu sync.Mutex + rf1Reason string + rf1Refused uint64 + rf1Admitted uint64 + rf1BeforeAdmit func() // test hook: between the stale check and the admit conn *grpc.ClientConn obsCli control.ObservationServiceClient @@ -428,6 +442,12 @@ func (h *Host) latchRoleAdmission(role selfRole, epoch uint64, err error) { // call on this host's replica listener failed, and why. The projection view // treats a failure as not Healthy. func (h *Host) RoleAdmissionFailure() (bool, string) { + h.rf1Mu.Lock() + rf1 := h.rf1Reason + h.rf1Mu.Unlock() + if rf1 != "" { + return true, rf1 + } reason, _ := h.roleAdmissionFailed.Load().(string) return reason != "", reason } @@ -780,6 +800,10 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { h.cfg.VolumeID, reason, info.ReplicaID, info.Epoch, info.EndpointVersion) return } + if h.cfg.RF1Only != "" { + h.refuseRF1("a supporting replica role", info.Epoch) + return + } if err := h.fenceSelf(selfRoleReplica, info.Epoch); err != nil { // G1: fail closed, as for the primary path; stream replay // redelivers the fact and a later success clears the latch. @@ -817,6 +841,23 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { return } + // An RF1-only volume refuses replica peers before anything is installed, + // and a fact below a refused epoch is stale: it neither adopts nor clears. + if h.cfg.RF1Only != "" { + if len(fact.Peers) > 0 { + h.refuseRF1(fmt.Sprintf("a primary role with %d replica peers", len(fact.Peers)), fact.Epoch) + return + } + h.rf1Mu.Lock() + refused := h.rf1Refused + h.rf1Mu.Unlock() + if fact.Epoch < refused { + h.log.Printf("blockvolume: volume %s stale RF1 assignment at epoch %d below refused epoch %d — NOT applying to adapter", + h.cfg.VolumeID, fact.Epoch, refused) + return + } + } + // Step (2a): install replication peer set first. Decoded via // the separate host-only decodeReplicaTargets path (not through // AssignmentInfo), so the TestNoOtherAssignmentInfoConstruction @@ -855,6 +896,11 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { h.cfg.VolumeID, info.Epoch, err) return } + if h.cfg.RF1Only != "" && !h.admitRF1(fact.Epoch) { + h.log.Printf("blockvolume: volume %s RF1 assignment at epoch %d overtaken by a newer refusal — NOT applying to adapter", + h.cfg.VolumeID, fact.Epoch) + return + } h.adpt.OnAssignment(info) h.log.Printf("blockvolume: volume %s adopted as PRIMARY at %s@%d (EV=%d)", h.cfg.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion) @@ -866,6 +912,42 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { } } +// refuseRF1 latches the refusal of a role with replica slots on an RF1-only +// volume (Config.RF1Only): no peer set, role or readiness was installed. +func (h *Host) refuseRF1(what string, epoch uint64) { + reason := fmt.Sprintf("volume %s refuses %s at epoch %d: %s", h.cfg.VolumeID, what, epoch, h.cfg.RF1Only) + h.rf1Mu.Lock() + stale := epoch < h.rf1Admitted // older than an admitted RF1 fact: does not re-latch + if !stale && epoch >= h.rf1Refused { + h.rf1Refused, h.rf1Reason = epoch, reason + } + h.rf1Mu.Unlock() + if stale { + h.log.Printf("blockvolume: stale %s (admitted RF1 epoch is newer) — NOT applying to adapter", reason) + return + } + h.log.Printf("blockvolume: %s — NOT applying to adapter (fail-closed)", reason) +} + +// admitRF1 clears the RF1 refusal for an RF1 fact whose role was admitted, +// unless a refusal at a newer epoch was latched meanwhile (then it reports +// false and the fact must not be adopted). +func (h *Host) admitRF1(epoch uint64) bool { + if hook := h.rf1BeforeAdmit; hook != nil { + hook() + } + h.rf1Mu.Lock() + defer h.rf1Mu.Unlock() + if epoch < h.rf1Refused { + return false + } + h.rf1Reason = "" + if epoch > h.rf1Admitted { + h.rf1Admitted = epoch + } + return true +} + func (h *Host) emitSupportingReadyMarker(info adapter.AssignmentInfo) { if h.cfg.ReadyMarker == nil || info.Epoch == 0 { return diff --git a/seaweed-block/core/host/volume/rf1_only_test.go b/seaweed-block/core/host/volume/rf1_only_test.go new file mode 100644 index 0000000000..fd9b0b3b16 --- /dev/null +++ b/seaweed-block/core/host/volume/rf1_only_test.go @@ -0,0 +1,324 @@ +package volume + +import ( + "bytes" + "context" + "errors" + "fmt" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/engine" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/replication" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage/memorywal" +) + +func rf2PrimaryFact(epoch uint64) *control.AssignmentFact { + return &control.AssignmentFact{ + VolumeId: "vol1", ReplicaId: "r1", Epoch: epoch, EndpointVersion: 1, + DataAddr: "127.0.0.1:1000", CtrlAddr: "127.0.0.1:1001", PeerSetGeneration: epoch, + Peers: []*control.ReplicaDescriptor{{ReplicaId: "r2", Epoch: epoch, EndpointVersion: 1, DataAddr: "127.0.0.1:2000", CtrlAddr: "127.0.0.1:2001"}}, + } +} + +// The production start schedule of an RF1-only (walstore-chunk) volume: the +// host starts with local readiness blocked, a retained RF2 fact arrives and is +// stored, and installing the replication volume replays it with no self fence +// installed yet. The host must refuse it before any peer set, adoption or +// readiness marker, and latch the refusal; a later RF1 fact is adopted. +func TestRF1Only_RetainedReplicatedFactReplayedBeforeSelfFence(t *testing.T) { + rec := &orderingRecorder{} + h, a, r := newStubbedHost(t, "vol1", "r1", rec) + ready := make(chan adapter.AssignmentInfo, 4) + h.cfg.ReadyMarker, h.cfg.RF1Only = ready, "chunk snapshots need RF1" + rv := h.replication + h.replication = nil + h.BlockLocalReadiness("awaiting durable recovery") + + h.applyFact(rf2PrimaryFact(3)) // stored for replay + h.ClearLocalReadinessBlock() + h.replicationMu.Lock() + h.setReplicationLocked(rv) // what SetReplicationVolume does, then it replays + h.replicationMu.Unlock() + h.replayLocalReadinessFactIfReady() + + if h.selfFence != nil { + t.Fatal("fixture: a self fence is installed") + } + if r.callCount.Load() != 0 || a.callCount.Load() != 0 || len(ready) != 0 { + t.Fatalf("replayed RF2 fact installed something: peers=%d adopt=%d ready=%d %v", r.callCount.Load(), a.callCount.Load(), len(ready), rec.snapshot()) + } + failed, reason := h.RoleAdmissionFailure() + if !failed || !strings.Contains(reason, "refuses a primary role with 1 replica peers at epoch 3") || !strings.Contains(reason, "chunk snapshots need RF1") { + t.Fatalf("no refusal latch: %v %q", failed, reason) + } + + // A supporting-replica fact (another primary lists this replica) is refused too. + sup := rf2PrimaryFact(4) + sup.ReplicaId, sup.Peers[0].ReplicaId = "r2", "r1" + h.applyFact(sup) + if r.callCount.Load() != 0 || a.callCount.Load() != 0 || len(ready) != 0 { + t.Fatal("supporting replica admitted on an RF1-only volume") + } + if _, reason := h.RoleAdmissionFailure(); !strings.Contains(reason, "refuses a supporting replica role at epoch 4") { + t.Fatalf("supporting refusal not latched: %q", reason) + } + + // The master moves the volume to RF1: adopted, latch cleared, ready emitted. + rf1 := rf2PrimaryFact(5) + rf1.Peers = nil + h.applyFact(rf1) + if a.callCount.Load() != 1 || len(ready) != 1 { + t.Fatalf("RF1 primary not adopted: adopt=%d ready=%d", a.callCount.Load(), len(ready)) + } + if failed, reason := h.RoleAdmissionFailure(); failed { + t.Fatalf("latch not cleared by an RF1 fact: %q", reason) + } +} + +// Control: without the rule the same replayed RF2 fact installs its peer set +// and is adopted (today's behaviour for replicated volumes). +func TestRF1Only_UnsetKeepsReplicatedAdoption(t *testing.T) { + h, a, r := newStubbedHost(t, "vol1", "r1", &orderingRecorder{}) + h.applyFact(rf2PrimaryFact(3)) + if r.callCount.Load() != 1 || a.callCount.Load() != 1 { + t.Fatalf("replicated fact not applied: peers=%d adopt=%d", r.callCount.Load(), a.callCount.Load()) + } + if failed, _ := h.RoleAdmissionFailure(); failed { + t.Fatal("latched without the rule") + } +} + +// A refusal is bound to its epoch: RF1@2 healthy and writing, RF2@3 refused +// (writes stop), then a stale RF1@2 replay must neither adopt nor clear the +// refusal (writes stay refused, no peers installed); only RF1 at the refused +// epoch or newer, once its role is admitted, clears it. +func TestRF1Only_StaleRF1FactDoesNotClearANewerRefusal(t *testing.T) { + f := newRF1BackendHost(t) + f.h.applyFact(rf1Fact(2)) + if f.a.callCount.Load() != 1 { + t.Fatal("fixture: RF1@2 not adopted") + } + f.mustWrite(t, 2, 0xD2) + f.h.applyFact(rf2PrimaryFact(3)) + f.assertRefusedAt(t, 3) + f.h.applyFact(rf1Fact(2)) // stale replay below the refused epoch + f.assertRefusedAt(t, 3) + if f.a.callCount.Load() != 1 || f.r.callCount.Load() != 1 { + t.Fatalf("stale RF1@2 adopted or RF2 peers installed: adopt=%d peerSets=%d", f.a.callCount.Load(), f.r.callCount.Load()) + } + f.fencer.fail.Store(true) // RF1@3 whose role fence fails: a failed attempt does not clear the refusal + f.h.applyFact(rf1Fact(3)) + if _, reason := f.h.RoleAdmissionFailure(); !strings.Contains(reason, "refuses a primary role") || f.a.callCount.Load() != 1 { + t.Fatalf("failed RF1@3 attempt cleared the refusal: %q adopt=%d", reason, f.a.callCount.Load()) + } + f.fencer.fail.Store(false) + f.h.applyFact(rf1Fact(3)) + if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 { + t.Fatalf("RF1@3 did not reconcile: %v %q adopt=%d", failed, reason, f.a.callCount.Load()) + } + f.mustWrite(t, 3, 0xD3) +} + +type rf1Fixture struct { + fencer *switchFencer + h *Host + a *stubAdapter + r *stubReplication + proj *mutableProjector + store *memorywal.Store +} + +func newRF1BackendHost(t *testing.T) *rf1Fixture { + t.Helper() + h, a, r := newStubbedHost(t, "vol1", "r1", &orderingRecorder{}) + h.cfg.RF1Only = "chunk snapshots need RF1" + proj := &mutableProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 2, EndpointVersion: 1}} + h.view = NewAdapterProjectionView(proj, "vol1", "r1", h) + fencer := &switchFencer{} + if err := h.SetSelfFence(fencer); err != nil { + t.Fatal(err) + } + store := memorywal.NewStore(8, 4096) + t.Cleanup(func() { _ = store.Close() }) + return &rf1Fixture{fencer: fencer, h: h, a: a, r: r, proj: proj, store: store} +} + +// backend is a frontend at this epoch's identity, with the engine projection +// at that epoch (only called while no applyFact runs). +func (f *rf1Fixture) backend(epoch uint64) *durable.StorageBackend { + f.proj.p = engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: epoch, EndpointVersion: 1} + b := durable.NewStorageBackend(f.store, f.h.view, frontend.Identity{VolumeID: "vol1", ReplicaID: "r1", Epoch: epoch, EndpointVersion: 1}) + b.SetOperational(true, "rf1 fixture") + return b +} + +// mustWrite writes one block at the epoch's identity and reads it back. +func (f *rf1Fixture) mustWrite(t *testing.T, epoch uint64, fill byte) { + t.Helper() + ctx := context.Background() + b := f.backend(epoch) + data := bytes.Repeat([]byte{fill}, 4096) + if n, err := b.Write(ctx, 0, data); n != len(data) || err != nil { + t.Fatalf("write at epoch %d: n=%d err=%v", epoch, n, err) + } + got := make([]byte, len(data)) + if n, err := b.Read(ctx, 0, got); n != len(got) || err != nil || !bytes.Equal(got, data) { + t.Fatalf("readback at epoch %d: n=%d err=%v equal=%v", epoch, n, err, bytes.Equal(got, data)) + } +} + +func rf1Fact(epoch uint64) *control.AssignmentFact { + f := rf2PrimaryFact(epoch) + f.Peers = nil + return f +} + +func (f *rf1Fixture) assertRefusedAt(t *testing.T, epoch uint64) { + t.Helper() + if failed, reason := f.h.RoleAdmissionFailure(); !failed || !strings.Contains(reason, fmt.Sprintf("at epoch %d", epoch)) { + t.Fatalf("want the refusal at epoch %d latched: %v %q", epoch, failed, reason) + } + if _, err := f.backend(epoch-1).Write(context.Background(), 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("write at the old identity after the refusal: %v", err) + } + if len(f.r.lastTargetIDs) != 0 { + t.Fatalf("forbidden peers installed: %v", f.r.lastTargetIDs) + } +} + +// Serial interleaving: an allowed RF1@2 replay passes the stale check, and +// before it admits, the stream latches an RF2@3 refusal. The replay must not +// clear that newer refusal nor adopt. RF1@3 then admits and serves at epoch 3. +func TestRF1Only_HeldRF1ReplayDoesNotClearANewerRefusal(t *testing.T) { + f := newRF1BackendHost(t) + f.h.applyFact(rf1Fact(2)) + f.mustWrite(t, 2, 0xA2) + fired := false + f.h.rf1BeforeAdmit = func() { + if !fired { + fired = true + f.h.applyFact(rf2PrimaryFact(3)) + } + } + f.h.applyFact(rf1Fact(2)) + f.h.rf1BeforeAdmit = nil + if !fired || f.a.callCount.Load() != 1 { + t.Fatalf("fixture fired=%v; held RF1@2 adopted=%d", fired, f.a.callCount.Load()) + } + f.assertRefusedAt(t, 3) + f.h.applyFact(rf1Fact(3)) + if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 || f.a.lastInfo.Epoch != 3 { + t.Fatalf("current RF1@3 not admitted: %v %q adopt=%d", failed, reason, f.a.callCount.Load()) + } + f.mustWrite(t, 3, 0xA3) +} + +// holdingUpdater parks the first armed UpdateReplicaSet until released. +type holdingUpdater struct { + inner replicaSetUpdater + armed atomic.Bool + entered, release chan struct{} +} + +func (u *holdingUpdater) UpdateReplicaSet(gen uint64, targets []replication.ReplicaTarget) error { + if u.armed.CompareAndSwap(true, false) { + close(u.entered) + <-u.release + } + return u.inner.UpdateReplicaSet(gen, targets) +} + +// Two workers: the replay worker's RF1@2 passes the stale check and parks in +// the peer-set update; the stream worker's RF2@3 is refused meanwhile; the +// replay then resumes. Bounded by timeouts. +func TestRF1Only_ParallelHeldReplayAndNewerRefusal(t *testing.T) { + f := newRF1BackendHost(t) + f.h.applyFact(rf1Fact(2)) + f.mustWrite(t, 2, 0xB2) + u := &holdingUpdater{inner: f.r, entered: make(chan struct{}), release: make(chan struct{})} + u.armed.Store(true) + f.h.replicationMu.Lock() + f.h.setReplicationLocked(u) + f.h.replicationMu.Unlock() + + // Registered before any worker starts: every exit path (including a Fatal + // below) releases the parked replay and joins both workers, bounded. + var once sync.Once + release := func() { once.Do(func() { close(u.release) }) } + replay, stream := make(chan struct{}), make(chan struct{}) + replayStarted, streamStarted := false, false + t.Cleanup(func() { + release() + for _, w := range []struct { + started bool + done chan struct{} + name string + }{{replayStarted, replay, "replay"}, {streamStarted, stream, "stream"}} { + if !w.started { + continue + } + select { + case <-w.done: + case <-time.After(5 * time.Second): + t.Errorf("%s worker did not finish after release", w.name) + } + } + }) + replayStarted = true + go func() { defer close(replay); f.h.applyFact(rf1Fact(2)) }() + select { + case <-u.entered: + case <-time.After(5 * time.Second): + t.Fatal("replay worker did not reach the peer-set update") + } + streamStarted = true + go func() { defer close(stream); f.h.applyFact(rf2PrimaryFact(3)) }() + select { + case <-stream: + case <-time.After(5 * time.Second): + t.Fatal("stream worker blocked behind the parked replay") + } + release() + select { + case <-replay: + case <-time.After(5 * time.Second): + t.Fatal("replay worker did not finish") + } + if f.a.callCount.Load() != 1 { + t.Fatalf("parked RF1@2 adopted after the newer refusal: adopt=%d", f.a.callCount.Load()) + } + f.assertRefusedAt(t, 3) + f.h.applyFact(rf1Fact(3)) + if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 { + t.Fatalf("current RF1@3 not admitted: %v %q", failed, reason) + } + f.mustWrite(t, 3, 0xB3) +} + +// A stale RF2 below an admitted RF1 epoch does not re-latch the refusal. +func TestRF1Only_StaleRF2AfterNewerRF1DoesNotRelatch(t *testing.T) { + f := newRF1BackendHost(t) + f.h.applyFact(rf1Fact(2)) + f.h.applyFact(rf2PrimaryFact(3)) + f.h.applyFact(rf1Fact(4)) + if failed, reason := f.h.RoleAdmissionFailure(); failed || f.a.callCount.Load() != 2 { + t.Fatalf("RF1@4 not admitted: %v %q adopt=%d", failed, reason, f.a.callCount.Load()) + } + f.h.applyFact(rf2PrimaryFact(3)) // stale replay + if failed, reason := f.h.RoleAdmissionFailure(); failed { + t.Fatalf("stale RF2@3 re-latched after RF1@4: %q", reason) + } + f.mustWrite(t, 4, 0xC4) + f.h.applyFact(rf2PrimaryFact(4)) // same epoch, peers added: refused + if failed, _ := f.h.RoleAdmissionFailure(); !failed { + t.Fatal("RF2 at the admitted epoch not refused") + } +} diff --git a/seaweed-block/core/host/volume/status_server_test.go b/seaweed-block/core/host/volume/status_server_test.go index 50fffb65d1..cbdf18d3eb 100644 --- a/seaweed-block/core/host/volume/status_server_test.go +++ b/seaweed-block/core/host/volume/status_server_test.go @@ -7,6 +7,7 @@ import ( "bytes" "context" "encoding/json" + "github.com/seaweedfs/seaweed-block/core/storage" "net/http" "net/http/httptest" "strings" @@ -981,15 +982,16 @@ func TestStatusServer_DurableStatusEndpoint_EnabledAfterStart_ReturnsLineage(t * } defer func() { _ = s.Close(context.Background()) }() s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{ - VolumeID: "v1", - Path: "/tmp/v1.bin", - Impl: "smartwal", - ReplicaID: "r1", - Epoch: 1, - EndpointVersion: 1, - Latched: true, - Operational: true, - Evidence: "recovered LSN=0", + VolumeID: "v1", + Path: "/tmp/v1.bin", + Impl: "smartwal", + ReplicaID: "r1", + Epoch: 1, + EndpointVersion: 1, + Latched: true, + Operational: true, + Evidence: "recovered LSN=0", + CheckpointPersistence: &storage.CheckpointPersistenceStatus{Successes: 3, Refusals: 2, Failures: 1}, }}}) resp, err := http.Get("http://" + addr + "/status/durable?volume=v1") @@ -1015,6 +1017,10 @@ func TestStatusServer_DurableStatusEndpoint_EnabledAfterStart_ReturnsLineage(t * if len(body.Volumes) != 1 || !body.Volumes[0].Latched || !body.Volumes[0].Operational || body.Volumes[0].Epoch != 1 { t.Fatalf("unexpected durable volume body: %+v", body.Volumes) } + checkpoint := body.Volumes[0].CheckpointPersistence + if checkpoint == nil || checkpoint.Successes != 3 || checkpoint.Refusals != 2 || checkpoint.Failures != 1 { + t.Fatalf("checkpoint counters missing from HTTP response: %+v", checkpoint) + } } func TestG9B_StatusProjection_ReturnedReplicaCanBeDurableReadyButFrontendNotReady(t *testing.T) { diff --git a/seaweed-block/core/host/volume/workspace_lease.go b/seaweed-block/core/host/volume/workspace_lease.go index dad21b65fb..cf99b03c73 100644 --- a/seaweed-block/core/host/volume/workspace_lease.go +++ b/seaweed-block/core/host/volume/workspace_lease.go @@ -3,6 +3,7 @@ package volume import ( "context" "fmt" + "log" "sync" "time" @@ -34,6 +35,38 @@ type WorkspaceLeaseGuard struct { stopped bool headGen uint64 revoked bool + // cause says why the guard fenced (the first reason wins); logged once, + // because the shutdown it triggers is otherwise silent (issue #205). + cause string + logged bool +} + +// fenceLocked latches the fence and records its first cause. Caller holds mu. +func (g *WorkspaceLeaseGuard) fenceLocked(cause string) { + g.fenced = true + if g.cause == "" { + g.cause = cause + } +} + +// FenceCause is why the guard fenced, or "" while it has not. +func (g *WorkspaceLeaseGuard) FenceCause() string { + g.mu.Lock() + defer g.mu.Unlock() + return g.cause +} + +// logFence logs the fence and its cause once. Never called with mu held. +func (g *WorkspaceLeaseGuard) logFence() { + g.mu.Lock() + if !g.fenced || g.logged { + g.mu.Unlock() + return + } + g.logged = true + cause := g.cause + g.mu.Unlock() + log.Printf("workspace lease: fenced volume=%s replica=%s epoch=%d: %s", g.id.VolumeId, g.id.ReplicaId, g.id.Epoch, cause) } func NewWorkspaceLeaseGuard(base frontend.ProjectionView, client WorkspaceLeaseClient, id *control.WorkspaceIdentity, stop func(context.Context) (uint64, error), now func() time.Time) (*WorkspaceLeaseGuard, error) { @@ -58,7 +91,7 @@ func (g *WorkspaceLeaseGuard) permits(p frontend.Projection) bool { g.mu.Lock() defer g.mu.Unlock() if !g.until.IsZero() && !g.now().Before(g.until) { - g.fenced = true + g.fenceLocked(fmt.Sprintf("lease expired at %s without a successful renewal", g.until.UTC().Format(time.RFC3339Nano))) } return !g.fenced && !g.until.IsZero() && p.VolumeID == g.id.VolumeId && p.ReplicaID == g.id.ReplicaId && p.Epoch == g.id.Epoch } @@ -73,14 +106,15 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { start := g.now() g.mu.Lock() if !g.until.IsZero() && !start.Before(g.until) { - g.fenced = true + g.fenceLocked(fmt.Sprintf("lease expired at %s without a successful renewal", g.until.UTC().Format(time.RFC3339Nano))) } fenced, until := g.fenced, g.until g.mu.Unlock() if fenced { + g.logFence() return g.drain(ctx, g.revoked) } - rpcCtx, cancel := context.WithTimeout(ctx, 2*time.Second) + rpcCtx, cancel := context.WithTimeout(ctx, renewalRPCTimeout) if !until.IsZero() { var c context.CancelFunc rpcCtx, c = context.WithDeadline(rpcCtx, until) @@ -89,52 +123,105 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { defer cancel() reply, err := g.client.RenewWorkspaceLease(rpcCtx, &g.id) if err != nil { + end := g.now() + elapsed := end.Sub(start).Round(time.Millisecond) + hit := renewalLimitHit(start, end, until) g.mu.Lock() - expired := !g.until.IsZero() && !g.now().Before(g.until) + expired := !g.until.IsZero() && !end.Before(g.until) if expired { - g.fenced = true + g.fenceLocked(fmt.Sprintf("lease expired after a failed renewal (renewal failed after %s, %s: %v)", elapsed, hit, err)) } g.mu.Unlock() + // Every failed renewal is visible with its latency and with which limit, + // if any, the call reached: a run of them is the warning before an expiry + // fence (issue #205). + log.Printf("workspace lease: renewal failed after %s volume=%s epoch=%d (%s; lease valid until %s): %v", + elapsed, g.id.VolumeId, g.id.Epoch, hit, until.UTC().Format(time.RFC3339Nano), err) if expired { - _ = g.drain(ctx, false) + g.logFence() + return g.drainAfterFence(ctx, fmt.Errorf("workspace lease expired: renewal failed after %s (%s): %w", elapsed, hit, err)) } return err } if reply.GetVolumeId() != g.id.VolumeId || reply.GetReplicaId() != g.id.ReplicaId || reply.GetEpoch() != g.id.Epoch || reply.GetValidForNs() <= 0 || reply.GetValidForNs() > int64(30*time.Second) { g.mu.Lock() - g.fenced = true + g.fenceLocked(fmt.Sprintf("invalid lease reply (volume=%q replica=%q epoch=%d validForNs=%d)", reply.GetVolumeId(), reply.GetReplicaId(), reply.GetEpoch(), reply.GetValidForNs())) g.mu.Unlock() - _ = g.drain(ctx, false) - return fmt.Errorf("invalid workspace lease reply") + g.logFence() + return g.drainAfterFence(ctx, fmt.Errorf("invalid workspace lease reply")) } g.mu.Lock() // Check the OLD deadline before accepting a newer grant. In particular a // reply received after expiry cannot undo a fence latched by a frontend. - if ctx.Err() != nil || rpcCtx.Err() != nil || (!g.until.IsZero() && !g.now().Before(g.until)) || !g.now().Before(start.Add(time.Duration(reply.ValidForNs))) { - g.fenced = true + switch { + case ctx.Err() != nil: + g.fenceLocked("shutdown while a renewal was in flight") + // A late reply is refused in all three cases; the cause names which limit + // it missed, so a valid lease is not reported as an expired one. + case !g.until.IsZero() && !g.now().Before(g.until): + g.fenceLocked(fmt.Sprintf("renewal reply arrived after the lease deadline (renewal took %s)", g.now().Sub(start).Round(time.Millisecond))) + case !g.now().Before(start.Add(time.Duration(reply.ValidForNs))): + g.fenceLocked(fmt.Sprintf("renewal reply arrived after its own grant ended (renewal took %s)", g.now().Sub(start).Round(time.Millisecond))) + case rpcCtx.Err() != nil: + g.fenceLocked(fmt.Sprintf("renewal reply arrived after the renewal call's context ended (renewal took %s; lease still valid until %s)", g.now().Sub(start).Round(time.Millisecond), g.until.UTC().Format(time.RFC3339Nano))) } if !g.fenced { g.until = start.Add(time.Duration(reply.ValidForNs)) } if reply.Revoking { - g.fenced = true + g.fenceLocked("revoked by the master") g.revoked = true } closed := g.fenced g.mu.Unlock() if closed { + g.logFence() return g.drain(ctx, reply.Revoking) } return nil } +// renewalRPCTimeout bounds one renewal call; the lease deadline may bound it +// sooner (Refresh). +const renewalRPCTimeout = 2 * time.Second + +// renewalLimitHit says which limit a failed renewal call had reached when it +// returned, on the guard's clock: the lease deadline (when it came before the +// per-call timeout), the 2 s per-call timeout, or neither (the call failed +// for another reason). It separates a slow master from a dead lease. +func renewalLimitHit(start, end, until time.Time) string { + callLimit := start.Add(renewalRPCTimeout) + switch { + case !until.IsZero() && until.Before(callLimit) && !end.Before(until): + return "the call reached the lease deadline" + case !end.Before(callLimit): + return "the call reached the 2s renewal timeout" + default: + return "the call failed before any deadline" + } +} + +// drainAfterFence drains after a fence and returns err. If the stop itself +// failed, its error (which names the fence cause) is kept next to err. +// Caller holds operation. +func (g *WorkspaceLeaseGuard) drainAfterFence(ctx context.Context, err error) error { + derr := g.drain(ctx, false) + if !g.stopped { + return fmt.Errorf("%w; %w", err, derr) + } + return err +} + func (g *WorkspaceLeaseGuard) drain(parent context.Context, ack bool) error { if !g.stopped { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) gen, err := g.stop(ctx) cancel() if err != nil { - return err + g.mu.Lock() + cause := g.cause + g.mu.Unlock() + return fmt.Errorf("workspace lease fenced (%s): stop failed: %w", cause, err) } g.headGen, g.stopped = gen, true } @@ -159,7 +246,10 @@ func (g *WorkspaceLeaseGuard) drain(parent context.Context, ack bool) error { _, err := g.client.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: &g.id, HeadGen: g.headGen}) return err } - return fmt.Errorf("workspace lease fenced") + g.mu.Lock() + cause := g.cause + g.mu.Unlock() + return fmt.Errorf("workspace lease fenced: %s", cause) } // Run owns renewal and physical close. Projection independently checks expiry, @@ -189,8 +279,9 @@ func (g *WorkspaceLeaseGuard) Run(ctx context.Context) error { case <-ctx.Done(): g.operation.Lock() g.mu.Lock() - g.fenced = true + g.fenceLocked("shutdown requested (context cancelled)") g.mu.Unlock() + g.logFence() err := g.drain(ctx, false) g.operation.Unlock() return err diff --git a/seaweed-block/core/host/volume/workspace_lease_cause_test.go b/seaweed-block/core/host/volume/workspace_lease_cause_test.go new file mode 100644 index 0000000000..59f3e27714 --- /dev/null +++ b/seaweed-block/core/host/volume/workspace_lease_cause_test.go @@ -0,0 +1,312 @@ +package volume + +import ( + "bytes" + "context" + "errors" + "log" + "strings" + "sync" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" +) + +// lockedBuffer collects log output from the guard (log.Printf may be called +// from more than one goroutine in other tests of this package). +type lockedBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (l *lockedBuffer) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.Write(p) +} + +func (l *lockedBuffer) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.String() +} + +func captureLog(t *testing.T) *lockedBuffer { + t.Helper() + buf := &lockedBuffer{} + prevOut, prevFlags := log.Writer(), log.Flags() + log.SetOutput(buf) + t.Cleanup(func() { log.SetOutput(prevOut); log.SetFlags(prevFlags) }) + return buf +} + +// Issue #205: under sustained write load a volume stopped and nothing said +// why: the shutdown path logged nothing and the only trace was a raw +// DeadlineExceeded at closeout. Renewals failing until the lease expired is a +// hypothesis that matches the code path, not something the logs proved. A +// fence must name its cause so the next occurrence settles it. +func TestWorkspaceLeaseRenewalTimeoutFenceNamesItsCause(t *testing.T) { + logs := captureLog(t) + now := time.Unix(1000, 0) + calls, stops := 0, 0 + client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) { + calls++ + if calls == 1 { + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(time.Second)}, nil + } + // A slow master: the renewal RPC runs past the lease deadline and times out. + now = now.Add(3 * time.Second) + return nil, context.DeadlineExceeded + }} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { stops++; return 7, nil }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + err = g.Refresh(context.Background()) + if err == nil { + t.Fatal("a renewal that failed past the deadline did not fence") + } + if stops != 1 { + t.Fatalf("fence did not stop the volume: stops=%d", stops) + } + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("the renewal error was lost: %v", err) + } + if !strings.Contains(err.Error(), "workspace lease expired") { + t.Fatalf("the returned error does not name the cause: %q", err) + } + out := logs.String() + if !strings.Contains(out, "workspace lease: fenced") || !strings.Contains(out, "renewal failed") { + t.Fatalf("the fence and its cause were not logged; log=%q", out) + } + // The lease (1s) ended before the 2s per-call timeout: the log must say the + // call ran into the lease deadline, not that the RPC timed out on its own. + if !strings.Contains(out, "reached the lease deadline") || strings.Contains(out, "2s renewal timeout") { + t.Fatalf("the log does not say which limit the call reached; log=%q", out) + } + if !strings.Contains(g.FenceCause(), "lease expired after a failed renewal") { + t.Fatalf("FenceCause = %q", g.FenceCause()) + } +} + +// A renewal that fails while the lease is still valid does not fence, but it +// must be visible with its latency: a run of these is the early warning. +func TestWorkspaceLeaseRenewalFailureIsLoggedWithLatency(t *testing.T) { + logs := captureLog(t) + now := time.Unix(1000, 0) + calls := 0 + client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) { + calls++ + if calls == 1 { + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(10 * time.Second)}, nil + } + now = now.Add(2 * time.Second) + return nil, context.DeadlineExceeded + }} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err == nil { + t.Fatal("the failed renewal was not reported to the caller") + } + if !g.Projection().Healthy { + t.Fatal("a failed renewal inside the lease fenced the volume") + } + out := logs.String() + if !strings.Contains(out, "renewal failed after 2s") { + t.Fatalf("the failed renewal and its latency were not logged; log=%q", out) + } + // The lease (10s) outlives the call: this failure is the 2s per-call + // timeout, a slow master, not a lease that ran out. + if !strings.Contains(out, "reached the 2s renewal timeout") || strings.Contains(out, "lease deadline") { + t.Fatalf("the log does not say the 2s call timeout was reached; log=%q", out) + } + if g.FenceCause() != "" { + t.Fatalf("a failure inside the lease recorded a fence cause: %q", g.FenceCause()) + } +} + +// The first cause wins and is logged once: a frontend that notices expiry +// latches the cause with the exact deadline; the later drain, and a second +// Refresh, keep it and do not log the fence again. +func TestWorkspaceLeaseFirstFenceCauseWinsAndIsLoggedOnce(t *testing.T) { + logs := captureLog(t) + now := time.Unix(1000, 0) + renewals, stops := 0, 0 + client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) { + renewals++ + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(time.Second)}, nil + }} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { stops++; return 7, nil }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + now = now.Add(2 * time.Second) + if g.Projection().Healthy { + t.Fatal("expired lease served") + } + const first = "lease expired at 1970-01-01T00:16:41Z without a successful renewal" + if got := g.FenceCause(); got != first { + t.Fatalf("FenceCause = %q, want %q", got, first) + } + err = g.Refresh(context.Background()) + if err == nil || !strings.Contains(err.Error(), first) { + t.Fatalf("drain error does not carry the first cause: %v", err) + } + if err := g.Refresh(context.Background()); err == nil { + t.Fatal("fenced guard reopened") + } + if got := g.FenceCause(); got != first { + t.Fatalf("the first cause was replaced: %q", got) + } + if renewals != 1 || stops != 1 { + t.Fatalf("renewals=%d stops=%d, want 1 and 1", renewals, stops) + } + if n := strings.Count(logs.String(), "workspace lease: fenced"); n != 1 { + t.Fatalf("fence logged %d times, want once; log=%q", n, logs.String()) + } +} + +// A late reply that also carries a revocation keeps the first cause (the late +// reply), not the revocation that arrived with it. +func TestWorkspaceLeaseLateRevokingReplyKeepsTheFirstCause(t *testing.T) { + captureLog(t) + now := time.Unix(1000, 0) + renewals := 0 + client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) { + renewals++ + if renewals > 1 { + now = now.Add(3 * time.Second) // the reply arrives after the 1s lease ended + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(time.Second), Revoking: true}, nil + } + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(time.Second)}, nil + }, ack: func() error { t.Fatal("an expired lease must not ACK"); return nil }} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err == nil { + t.Fatal("a late reply did not fence") + } + if got := g.FenceCause(); !strings.HasPrefix(got, "renewal reply arrived after the lease deadline") { + t.Fatalf("FenceCause = %q, want the late reply", got) + } +} + +// A stop that fails after a fence must not hide the cause: the returned error +// names the cause and keeps both the stop error and the renewal error. +func TestWorkspaceLeaseFailedStopKeepsTheCause(t *testing.T) { + captureLog(t) + errStop := errors.New("frontend close failed") + now := time.Unix(1000, 0) + calls := 0 + client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) { + calls++ + if calls == 1 { + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(time.Second)}, nil + } + now = now.Add(3 * time.Second) + return nil, context.DeadlineExceeded + }} + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 0, errStop }, func() time.Time { return now }) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + err = g.Refresh(context.Background()) + if !errors.Is(err, errStop) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("the stop or renewal error was lost: %v", err) + } + if !strings.Contains(err.Error(), "stop failed") || !strings.Contains(err.Error(), "lease expired after a failed renewal") { + t.Fatalf("the error does not name the cause and the failed stop: %q", err) + } + // The next Refresh retries the stop through the fenced path: same cause. + err = g.Refresh(context.Background()) + if !errors.Is(err, errStop) || !strings.Contains(err.Error(), "lease expired after a failed renewal") { + t.Fatalf("the retried stop lost the cause: %v", err) + } +} + +// ctxLeaseClient answers a renewal only once the call's context has ended, +// like a reply that lands just after the 2s per-call timeout. +type ctxLeaseClient struct{ validFor time.Duration } + +func (c ctxLeaseClient) RenewWorkspaceLease(ctx context.Context, _ *control.WorkspaceIdentity, _ ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + if ctx.Err() == nil { + select { + case <-ctx.Done(): + case <-time.After(5 * time.Second): // bound: the 2s call timeout ends it first + } + } + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(c.validFor)}, nil +} + +func (ctxLeaseClient) AckWorkspaceRevoked(context.Context, *control.WorkspaceRevocationAck, ...grpc.CallOption) (*control.WorkspaceEmpty, error) { + return &control.WorkspaceEmpty{}, nil +} + +// A valid reply that arrives after the renewal call's 2s context ended, while +// the old lease and the new grant are both still valid, is still refused, but +// its cause must say the call's context ended, not that the lease expired. +func TestWorkspaceLeaseReplyAfterCallTimeoutIsNotCalledAnExpiry(t *testing.T) { + captureLog(t) + first := true + slow := ctxLeaseClient{validFor: 20 * time.Second} + renew := func(ctx context.Context, id *control.WorkspaceIdentity, o ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + if first { + first = false + return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(20 * time.Second)}, nil + } + return slow.RenewWorkspaceLease(ctx, id, o...) + } + stops := 0 + g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, funcLeaseClient(renew), &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { stops++; return 7, nil }, nil) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + began := time.Now() + if err := g.Refresh(context.Background()); err == nil { + t.Fatal("a reply after the call's context ended was accepted") + } + if took := time.Since(began); took > 4*time.Second { + t.Fatalf("the late call was not bounded by the 2s timeout: %s", took) + } + if stops != 1 { + t.Fatalf("stops=%d, want 1 (the refusal is unchanged)", stops) + } + cause := g.FenceCause() + if !strings.HasPrefix(cause, "renewal reply arrived after the renewal call's context ended") || strings.Contains(cause, "lease deadline") { + t.Fatalf("FenceCause = %q, want the call-context cause, not an expiry", cause) + } +} + +// funcLeaseClient adapts a function to WorkspaceLeaseClient (renewals only). +type funcLeaseClient func(context.Context, *control.WorkspaceIdentity, ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) + +func (f funcLeaseClient) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity, o ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + return f(ctx, id, o...) +} + +func (funcLeaseClient) AckWorkspaceRevoked(context.Context, *control.WorkspaceRevocationAck, ...grpc.CallOption) (*control.WorkspaceEmpty, error) { + return &control.WorkspaceEmpty{}, nil +} diff --git a/seaweed-block/core/lifecycle/deletion_reservations.go b/seaweed-block/core/lifecycle/deletion_reservations.go index 75cd4f381d..a27cda7245 100644 --- a/seaweed-block/core/lifecycle/deletion_reservations.go +++ b/seaweed-block/core/lifecycle/deletion_reservations.go @@ -8,6 +8,7 @@ import ( "path/filepath" "sort" "sync" + "sync/atomic" ) // Deletion reservations (review of #152 r2): the master-side exclusion of a @@ -51,11 +52,26 @@ type DeletionReservationStore struct { mu sync.Mutex dir string records map[string]DeletionReservation + // snap mirrors records as an immutable copy, republished at every + // assignment of records, for lock-free renewal-path reads. + snap atomic.Pointer[map[string]DeletionReservation] // Test seams for persistence faults (nil in production). failWrite, failRename, failDirSync func() error } +// SetPersistHookForTest installs (nil clears) a callback that each later +// reservation write of this store runs under the store mutex, after its +// temporary file is created and before the write. A non-nil error fails that +// write with nothing replaced. Tests only: install it before any concurrent +// writer starts; the callback must not call back into the store or into this +// setter. Never call it while a write may still be held by the callback. +func (s *DeletionReservationStore) SetPersistHookForTest(hook func() error) { + s.mu.Lock() + defer s.mu.Unlock() + s.failWrite = hook +} + // OpenDeletionReservationStore opens or creates the store in dir. func OpenDeletionReservationStore(dir string) (*DeletionReservationStore, error) { return openDeletionReservationStore(dir, syncBindingParent) @@ -77,6 +93,7 @@ func openDeletionReservationStore(dir string, syncParent func(string) error) (*D b, err := os.ReadFile(filepath.Join(dir, reservationsFile)) switch { case errors.Is(err, os.ErrNotExist): + s.publishLocked() return s, nil case err != nil: return nil, fmt.Errorf("lifecycle: read deletion reservations: %w", err) @@ -89,9 +106,34 @@ func openDeletionReservationStore(dir string, syncParent func(string) error) (*D return nil, fmt.Errorf("lifecycle: deletion reservation %q is invalid", v) } } + s.publishLocked() return s, nil } +// publishLocked republishes the immutable snapshot of records (token slices +// copied). Called wherever records is assigned; caller holds mu or owns s. +func (s *DeletionReservationStore) publishLocked() { + m := make(map[string]DeletionReservation, len(s.records)) + for k, r := range s.records { + r.Tokens = append([]string(nil), r.Tokens...) + m[k] = r + } + s.snap.Store(&m) +} + +// ReservedSnapshot is Reserved without the store mutex, for the lease +// renewal path: it reads the last published records (after a durable write, +// or a protective change kept in memory on an unknown outcome), never waiting +// on a write in flight. +func (s *DeletionReservationStore) ReservedSnapshot(vol string) bool { + m := s.snap.Load() + if m == nil { + return false + } + _, ok := (*m)[vol] + return ok +} + // Get returns vol's reservation. func (s *DeletionReservationStore) Get(vol string) (DeletionReservation, bool) { s.mu.Lock() @@ -194,6 +236,7 @@ func (s *DeletionReservationStore) update(vol string, protective bool, change fu return r, err } s.records = next + s.publishLocked() return r, nil } @@ -225,6 +268,7 @@ func (s *DeletionReservationStore) persist(next map[string]DeletionReservation, unknown := func(err error) error { if protective { s.records = next // may be on disk: keep the exclusion + s.publishLocked() } return fmt.Errorf("lifecycle: deletion reservation outcome unknown: %w", err) } diff --git a/seaweed-block/core/lifecycle/legacy_size_retry_test.go b/seaweed-block/core/lifecycle/legacy_size_retry_test.go new file mode 100644 index 0000000000..133310042d --- /dev/null +++ b/seaweed-block/core/lifecycle/legacy_size_retry_test.go @@ -0,0 +1,35 @@ +package lifecycle + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +func TestLegacyOversizeIdenticalCreateRetry(t *testing.T) { + dir := t.TempDir() + spec := VolumeSpec{VolumeID: "legacy", SizeBytes: 17592186044416, ReplicationFactor: 1} + data, err := json.Marshal(VolumeRecord{Spec: spec}) + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(filepath.Join(dir, "legacy.json"), data, 0600); err != nil { + t.Fatal(err) + } + s, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + got, err := s.CreateVolume(spec) + if err != nil { + t.Fatalf("existing identical intent must remain retryable: %v", err) + } + if got.Spec.SizeBytes != spec.SizeBytes { + t.Fatal("existing size changed") + } + spec.VolumeID = "new-oversize" + if _, err = s.CreateVolume(spec); err == nil { + t.Fatal("new oversize admitted") + } +} diff --git a/seaweed-block/core/lifecycle/renewal_snapshot_test.go b/seaweed-block/core/lifecycle/renewal_snapshot_test.go new file mode 100644 index 0000000000..7ae59cdda1 --- /dev/null +++ b/seaweed-block/core/lifecycle/renewal_snapshot_test.go @@ -0,0 +1,217 @@ +package lifecycle + +import ( + "errors" + "fmt" + "sync" + "testing" + "time" +) + +// The reservation snapshot mirrors records at every assignment: after a +// durable write, on a protective change kept in memory on an unknown outcome +// (fail closed), never on a known no-write, and at load. Snapshots are +// immutable, token slices included (issue #205). +func TestDeletionReservationSnapshotFollowsRecords(t *testing.T) { + fail := errors.New("injected") + dir := t.TempDir() + s := reopen(t, dir) + same := func(what string, st *DeletionReservationStore, vols ...string) { + t.Helper() + for _, v := range vols { + if st.ReservedSnapshot(v) != st.Reserved(v) { + t.Fatalf("%s: snapshot of %q = %t, records = %t", what, v, st.ReservedSnapshot(v), st.Reserved(v)) + } + } + } + if s.ReservedSnapshot("v") { + t.Fatal("empty store reports a reservation") + } + if _, err := s.Admit("v", "d1"); err != nil { + t.Fatal(err) + } + if !s.ReservedSnapshot("v") { + t.Fatal("durable admission not visible to the snapshot") + } + s.failWrite = func() error { return fail } + if _, err := s.Admit("w", "d1"); !errors.Is(err, fail) || s.ReservedSnapshot("w") { + t.Fatalf("known no-write: %v; snapshot must not show it", err) + } + s.failWrite = nil + s.failRename = func() error { return fail } + if _, err := s.Admit("r", "d1"); !errors.Is(err, fail) || !s.ReservedSnapshot("r") { + t.Fatalf("unknown outcome of a protective change: %v; the snapshot must keep the exclusion (fail closed)", err) + } + s.failRename = nil + s.failDirSync = func() error { return fail } + if _, err := s.Admit("y", "d1"); !errors.Is(err, fail) || !s.ReservedSnapshot("y") { + t.Fatalf("unknown outcome (directory sync): %v; the snapshot must keep the exclusion", err) + } + s.failDirSync = nil + same("after faults", s, "v", "w", "r", "y") + + // Immutability: a published snapshot does not change when records do. + before := s.snap.Load() + tokens := append([]string(nil), (*before)["v"].Tokens...) + if _, err := s.Admit("v", "d2"); err != nil { + t.Fatal(err) + } + if got := (*before)["v"].Tokens; fmt.Sprint(got) != fmt.Sprint(tokens) { + t.Fatalf("an earlier snapshot changed: %v, was %v", got, tokens) + } + after := s.snap.Load() + (*after)["v"].Tokens[0] = "mutated" + if got, _ := s.Get("v"); got.Tokens[0] == "mutated" { + t.Fatal("snapshot token slice aliases the records") + } + if _, err := s.Abort("v", "d1"); err != nil { + t.Fatal(err) + } + if _, err := s.Abort("v", "d2"); err != nil || s.ReservedSnapshot("v") { + t.Fatalf("release of the last token: %v; snapshot must drop the reservation", err) + } + same("after release", s, "v", "w", "r", "y") + r := reopen(t, dir) // load publishes too + same("after reopen", r, "v", "w", "r", "y") +} + +// The Volumes snapshot follows every change of records, including load and +// the memory-first delete. +func TestFileStoreSnapshotFollowsRecords(t *testing.T) { + dir := t.TempDir() + s, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + if _, ok := s.GetVolumeSnapshot("a"); ok { + t.Fatal("empty store reports a volume") + } + if _, err := s.CreateVolume(VolumeSpec{VolumeID: "a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + if rec, ok := s.GetVolumeSnapshot("a"); !ok || rec.Spec.ReplicationFactor != 1 { + t.Fatalf("create not visible: %+v %t", rec, ok) + } + if _, err := s.AttachVolume("a", "n1"); err != nil { + t.Fatal(err) + } + if rec, _ := s.GetVolumeSnapshot("a"); rec.AttachedTo != "n1" { + t.Fatalf("attach not visible: %+v", rec) + } + if _, err := s.DetachVolume("a", "n1"); err != nil { + t.Fatal(err) + } + if rec, _ := s.GetVolumeSnapshot("a"); rec.AttachedTo != "" { + t.Fatalf("detach not visible: %+v", rec) + } + r, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + if _, ok := r.GetVolumeSnapshot("a"); !ok { + t.Fatal("load did not publish") + } + if err := s.DeleteVolume("a"); err != nil { + t.Fatal(err) + } + if _, ok := s.GetVolumeSnapshot("a"); ok { + t.Fatal("delete not visible") + } +} + +// Snapshot reads never take the store mutex that writers hold across file +// I/O: they return while the mutex is held. +func TestLifecycleSnapshotReadsDoNotTakeStoreMutex(t *testing.T) { + vols, err := OpenFileStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if _, err := vols.CreateVolume(VolumeSpec{VolumeID: "a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + res := reopen(t, t.TempDir()) + if _, err := res.Admit("x", "d"); err != nil { + t.Fatal(err) + } + vols.mu.Lock() + res.mu.Lock() + done := make(chan bool, 1) + go func() { + _, okV := vols.GetVolumeSnapshot("a") + done <- okV && res.ReservedSnapshot("x") + }() + select { + case ok := <-done: + res.mu.Unlock() + vols.mu.Unlock() + if !ok { + t.Fatal("snapshot read returned the wrong state") + } + case <-time.After(2 * time.Second): + res.mu.Unlock() + vols.mu.Unlock() + <-done + t.Fatal("snapshot read waited on the store mutex") + } +} + +// Snapshot readers run concurrently with every writer kind (run with -race). +func TestLifecycleSnapshotConcurrentWriters(t *testing.T) { + vols, err := OpenFileStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + res := reopen(t, t.TempDir()) + stop := make(chan struct{}) + var wg sync.WaitGroup + wg.Add(3) + go func() { + defer wg.Done() + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + v := fmt.Sprintf("v%d", i%4) + _, _ = vols.CreateVolume(VolumeSpec{VolumeID: v, SizeBytes: 1 << 20, ReplicationFactor: 1}) + _ = vols.DeleteVolume(v) + } + }() + go func() { + defer wg.Done() + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + v := fmt.Sprintf("r%d", i%4) + _, _ = res.Admit(v, "d1") + _, _ = res.Admit(v, "d2") + _, _ = res.Abort(v, "d1") + if i%3 == 0 { + _, _ = res.Commit(v, "d2") + } else { + _, _ = res.Abort(v, "d2") + } + } + }() + go func() { + defer wg.Done() + for { + select { + case <-stop: + return + default: + } + for i := 0; i < 4; i++ { + _, _ = vols.GetVolumeSnapshot(fmt.Sprintf("v%d", i)) + _ = res.ReservedSnapshot(fmt.Sprintf("r%d", i)) + } + } + }() + time.Sleep(300 * time.Millisecond) + close(stop) + wg.Wait() +} diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index 1de3e090e2..89b1e6ae66 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -15,6 +15,9 @@ import ( "regexp" "sort" "sync" + "sync/atomic" + + "github.com/seaweedfs/seaweed-block/core/geometry" ) var ( @@ -52,6 +55,31 @@ type FileStore struct { mu sync.Mutex dir string records map[string]VolumeRecord + // snap mirrors records as an immutable copy, republished at every change + // of records, for lock-free renewal-path reads. + snap atomic.Pointer[map[string]VolumeRecord] +} + +// publishLocked republishes the immutable snapshot of records. Caller holds +// mu or owns s. +func (s *FileStore) publishLocked() { + m := make(map[string]VolumeRecord, len(s.records)) + for k, r := range s.records { + m[k] = r + } + s.snap.Store(&m) +} + +// GetVolumeSnapshot is GetVolume without the store mutex, for the lease +// renewal path: it reads the last published records, never waiting on a +// write in flight. +func (s *FileStore) GetVolumeSnapshot(volumeID string) (VolumeRecord, bool) { + m := s.snap.Load() + if m == nil { + return VolumeRecord{}, false + } + rec, ok := (*m)[volumeID] + return rec, ok } // OpenFileStore opens or creates a lifecycle intent store. @@ -69,6 +97,7 @@ func OpenFileStore(dir string) (*FileStore, error) { if err := s.load(); err != nil { return nil, err } + s.publishLocked() return s, nil } @@ -92,15 +121,20 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { return VolumeRecord{}, err } s.records[spec.VolumeID] = merged + s.publishLocked() return merged, nil } return existing, nil } + if err := geometry.ValidateVolumeSize(spec.SizeBytes); err != nil { + return VolumeRecord{}, fmt.Errorf("%w: %w", ErrInvalidVolumeSpec, err) + } rec := VolumeRecord{Spec: spec} if err := s.putLocked(rec); err != nil { return VolumeRecord{}, err } s.records[spec.VolumeID] = rec + s.publishLocked() return rec, nil } @@ -140,6 +174,7 @@ func (s *FileStore) DeleteVolume(volumeID string) error { s.mu.Lock() defer s.mu.Unlock() delete(s.records, volumeID) + s.publishLocked() if err := os.Remove(s.path(volumeID)); err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("lifecycle: remove %s: %w", volumeID, err) } @@ -169,6 +204,7 @@ func (s *FileStore) AttachVolume(volumeID, nodeID string) (VolumeRecord, error) return VolumeRecord{}, err } s.records[volumeID] = rec + s.publishLocked() return rec, nil } @@ -192,6 +228,7 @@ func (s *FileStore) DetachVolume(volumeID, nodeID string) (VolumeRecord, error) return VolumeRecord{}, err } s.records[volumeID] = rec + s.publishLocked() return rec, nil } diff --git a/seaweed-block/core/lifecycle/volume_size_limit_test.go b/seaweed-block/core/lifecycle/volume_size_limit_test.go new file mode 100644 index 0000000000..7aa7627f55 --- /dev/null +++ b/seaweed-block/core/lifecycle/volume_size_limit_test.go @@ -0,0 +1,27 @@ +package lifecycle + +import ( + "errors" + "strings" + "testing" +) + +func TestCreateVolumeRejectsBeyondUint32LBACap(t *testing.T) { + s, err := OpenFileStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + const capBytes = uint64(17592186040320) // 16 TiB - 4 KiB + if _, err = s.CreateVolume(VolumeSpec{VolumeID: "at-cap", SizeBytes: capBytes, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + for _, size := range []uint64{capBytes + 1, capBytes + 4096, ^uint64(0)} { + _, err = s.CreateVolume(VolumeSpec{VolumeID: "too-large", SizeBytes: size, ReplicationFactor: 1}) + if !errors.Is(err, ErrInvalidVolumeSpec) || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("size %d: want clear capacity refusal, got %v", size, err) + } + if _, ok := s.GetVolumeSnapshot("too-large"); ok { + t.Fatal("refusal persisted oversized volume") + } + } +} diff --git a/seaweed-block/core/lifecycle/workspace_bindings.go b/seaweed-block/core/lifecycle/workspace_bindings.go index 5d51a472ba..d3fbefd8e9 100644 --- a/seaweed-block/core/lifecycle/workspace_bindings.go +++ b/seaweed-block/core/lifecycle/workspace_bindings.go @@ -119,6 +119,25 @@ func validateWorkspaceBinding(b WorkspaceBinding) error { return nil } +// ValidateWorkspaceEndpoints applies a binding's endpoint rules (host:port +// with a numeric port 1..65535, data and ctrl distinct) without registering +// anything. +func ValidateWorkspaceEndpoints(b WorkspaceBinding) error { return validateWorkspaceBinding(b) } + +// WorkspaceEndpointHost returns addr's host in canonical form (equivalent IP +// spellings compare equal; names lower-cased; no DNS), or "" if addr is not +// host:port. +func WorkspaceEndpointHost(addr string) string { + h, _, err := net.SplitHostPort(addr) + if err != nil || h == "" { + return "" + } + if ip := net.ParseIP(h); ip != nil { + return ip.String() + } + return strings.ToLower(h) +} + // Compare numeric ports and equivalent IP spellings without DNS/network I/O. func workspaceEndpointKey(addr string) string { h, p, err := net.SplitHostPort(addr) diff --git a/seaweed-block/core/recovery/install_log_boundary_test.go b/seaweed-block/core/recovery/install_log_boundary_test.go new file mode 100644 index 0000000000..df1176ffc2 --- /dev/null +++ b/seaweed-block/core/recovery/install_log_boundary_test.go @@ -0,0 +1,53 @@ +package recovery + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// DESIGN 7 and section 11 item 6 (plan row 10a): the install-log ack is not +// callable from the frontend. LogicalStorage has no SyncInstallLog, and no +// package outside core/storage (which defines it) and core/recovery (the +// receiver) names InstallLogSyncer. Mutant: adding SyncInstallLog to +// LogicalStorage, or using the interface elsewhere, fails here. +func TestInstallLogSyncerIsReceiverOnly(t *testing.T) { + if _, ok := reflect.TypeOf((*storage.LogicalStorage)(nil)).Elem().MethodByName("SyncInstallLog"); ok { + t.Fatal("LogicalStorage exposes SyncInstallLog to every caller") + } + root := filepath.Join("..", "..") + err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() && (d.Name() == ".git" || d.Name() == "vendor") { + return filepath.SkipDir + } + if d.IsDir() || !strings.HasSuffix(path, ".go") { + return nil + } + rel, err := filepath.Rel(root, path) + if err != nil { + return err + } + rel = filepath.ToSlash(rel) + if dir := filepath.ToSlash(filepath.Dir(rel)); dir == "core/storage" || dir == "core/recovery" { + return nil // the defining package and the receiver + } + b, err := os.ReadFile(path) + if err != nil { + return err + } + if strings.Contains(string(b), "InstallLogSyncer") { + t.Errorf("%s names InstallLogSyncer outside core/storage and core/recovery", rel) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/recovery/rebuild_session.go b/seaweed-block/core/recovery/rebuild_session.go index 94220f6735..bb3a67c680 100644 --- a/seaweed-block/core/recovery/rebuild_session.go +++ b/seaweed-block/core/recovery/rebuild_session.go @@ -27,7 +27,11 @@ import ( // This type knows nothing about pin_floor, primary recycle, wire // protocol, or barrier ack. Those live in layer 2. type RebuildSession struct { - store storage.LogicalStorage + store storage.LogicalStorage + // install is the BASE install handle (DESIGN r17.3.1 section 8.7): every + // BASE write, install-lane apply and the completion go through it. The + // receiver begins the install and sets it; otherwise the legacy handle. + install storage.InstallHandle baseFrontierHint uint64 // snapshot pin/frontier hint for BASE lane; not a completion predicate mu sync.Mutex @@ -75,6 +79,7 @@ type RebuildSession struct { func NewRebuildSession(store storage.LogicalStorage, baseFrontierHint uint64) *RebuildSession { return &RebuildSession{ store: store, + install: storage.NewLegacyInstallHandle(store, baseFrontierHint), baseFrontierHint: baseFrontierHint, bitmap: NewRebuildBitmap(store.NumBlocks()), } @@ -107,7 +112,7 @@ func (s *RebuildSession) ApplyBaseBlock(lba uint32, data []byte) (skipped bool, if s.bitmap.IsApplied(lba) { return true, nil } - if err := s.store.WriteExtentDirect(lba, data); err != nil { + if err := s.install.WriteBase(lba, data); err != nil { return false, fmt.Errorf("recovery: base extent-direct lba=%d: %w", lba, err) } return false, nil @@ -136,7 +141,7 @@ func (s *RebuildSession) ApplyWALEntry(kind WALEntryKind, lba uint32, data []byt if s.completed { return errors.New("recovery: ApplyWALEntry after session completed") } - if err := s.store.ApplyEntry(lba, data, lsn); err != nil { + if err := s.install.ApplyInstallEntry(lba, data, lsn); err != nil { return fmt.Errorf("recovery: wal apply lba=%d lsn=%d: %w", lba, lsn, err) } s.bitmap.MarkApplied(lba) @@ -178,15 +183,32 @@ func (s *RebuildSession) BaseBatchAcked(lbaUpper uint32) { // is installed" without needing a competing WAL apply at // that hint. Subsequent WAL frames above that hint advance // further via `ApplyEntry`'s normal side effects. -func (s *RebuildSession) MarkBaseComplete() { +// +// Since the v3 seam the completion goes through the install handle and +// returns its error (DESIGN 8.2 step 4): on an error the install stays +// incomplete and baseDone stays false. +func (s *RebuildSession) MarkBaseComplete() error { s.mu.Lock() defer s.mu.Unlock() - s.baseDone = true // §6.10 frontier reconciliation: BASE bytes are now installed // to extent; declare frontier at baseFrontierHint so post-rebuild // Sync()/Boundaries() report a non-degenerate value even on - // BASE-only sessions (no WAL frames in this session). - s.store.AdvanceFrontier(s.baseFrontierHint) + // BASE-only sessions (no WAL frames in this session). The legacy + // handle does exactly that (AdvanceFrontier); a v3 handle publishes + // installed and moves the frontier itself. + if err := s.install.MarkBaseComplete(); err != nil { + return fmt.Errorf("recovery: mark BASE complete: %w", err) + } + s.baseDone = true + return nil +} + +// SetInstallHandle binds the session to the install the receiver began. +// It is called before any BASE block or WAL entry. +func (s *RebuildSession) SetInstallHandle(h storage.InstallHandle) { + s.mu.Lock() + defer s.mu.Unlock() + s.install = h } // SeedWalApplied seeds walApplied at session start with the receiver's @@ -274,7 +296,7 @@ type Status struct { WALApplied uint64 BaseDone bool Completed bool - BarrierWitnessed bool // §IV.2.1 A-class: latched on frameBarrierReq arrival + BarrierWitnessed bool // §IV.2.1 A-class: latched on frameBarrierReq arrival BaseAckedPrefix uint32 BitmapApplied int // count of LBAs the WAL lane has marked BacklogApplied uint64 // count of WALKindBacklog entries applied diff --git a/seaweed-block/core/recovery/receiver.go b/seaweed-block/core/recovery/receiver.go index cecf42e07d..f9002a330d 100644 --- a/seaweed-block/core/recovery/receiver.go +++ b/seaweed-block/core/recovery/receiver.go @@ -1,6 +1,7 @@ package recovery import ( + "crypto/rand" "errors" "fmt" "io" @@ -49,8 +50,8 @@ type Receiver struct { cadenceT time.Duration blocksSinceLastAck uint32 lastAckTime time.Time - baseInstalledUpper uint32 // highest base LBA installed; advisory only in BaseBatchAck - basePrepared bool + baseInstalledUpper uint32 // highest base LBA installed; advisory only in BaseBatchAck + installID [16]byte // this session's BASE install ID (DESIGN 7, 8.7) gate DualLaneGate // nil only in tests that exercise the protocol alone epoch uint64 // from SessionStart; checked by gate on every mutating frame @@ -171,7 +172,15 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) { if gateErr != nil { return 0, gateErr } + // The BASE install begins here, before any BASE block or WAL + // entry, at the session's BASE frontier under a fresh random ID + // (DESIGN r17.3.1 section 8.7). The begin is a mutation, so it + // stays inside the counted section. + install, beginErr := r.beginInstall(s.FromLSN) release() + if beginErr != nil { + return 0, newFailure(FailureSubstrate, PhaseRecvApply, beginErr) + } r.sessionID = s.SessionID // Wire compat: sessionStart still carries TargetLSN in // the legacy fourth slot, but BASE frontier comes from @@ -181,6 +190,7 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) { // as a compat/frontier-hint band and MUST NOT drive BASE // AdvanceFrontier. r.session = NewRebuildSession(r.store, s.FromLSN) + r.session.SetInstallHandle(install) // Seed walApplied with fromLSN so AchievedLSN remains a // monotonic observation even when no WAL frames arrive. // Completion itself is baseDone + BarrierReq witness; the @@ -188,7 +198,6 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) { r.session.SeedWalApplied(s.FromLSN) r.recvFromLSN = s.FromLSN r.appliedWalLSN = s.FromLSN - r.basePrepared = false log.Printf("g7-debug: Receiver.Run frameSessionStart sessionID=%d fromLSN=%d targetLSN=%d numBlocks=%d", s.SessionID, s.FromLSN, s.TargetLSN, s.NumBlocks) case frameBaseBlock: @@ -204,15 +213,8 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) { if gateErr != nil { return 0, gateErr } - prepErr := r.prepareBaseInstall() - var applyErr error - if prepErr == nil { - _, applyErr = r.session.ApplyBaseBlock(lba, data) - } + _, applyErr := r.session.ApplyBaseBlock(lba, data) release() - if prepErr != nil { - return 0, newFailure(FailureSubstrate, PhaseRecvApply, prepErr) - } if applyErr != nil { log.Printf("g7-debug: Receiver.Run ApplyBaseBlock err lba=%d err=%v", lba, applyErr) return 0, newFailure(FailureSubstrate, PhaseRecvApply, @@ -274,16 +276,15 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) { if gateErr != nil { return 0, gateErr } - prepErr := r.prepareBaseInstall() - if prepErr != nil { - release() - return 0, newFailure(FailureSubstrate, PhaseRecvApply, prepErr) - } log.Printf("g7-debug: Receiver.Run frameBaseDone baseCount=%d walCount=%d", baseCount, walCount) - // The frontier advance is a mutation too: it stays inside the - // counted section, so a fence cannot return while it is pending. - r.session.MarkBaseComplete() + // The completion (and the frontier advance) is a mutation too: it + // stays inside the counted section, so a fence cannot return while + // it is pending. Its error propagates (DESIGN 8.2 step 4). + doneErr := r.session.MarkBaseComplete() release() + if doneErr != nil { + return 0, newFailure(FailureSubstrate, PhaseRecvApply, doneErr) + } // Mandatory final base-lane ack — base done means primary // expects to know our base-installed cursor before drain // even if cadence wouldn't have triggered yet. @@ -353,17 +354,21 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) { } } -func (r *Receiver) prepareBaseInstall() error { - if r.basePrepared { - return nil - } - if preparer, ok := r.store.(storage.BaseInstallPreparer); ok { - if err := preparer.BeginBaseInstall(); err != nil { - return fmt.Errorf("prepare BASE install: %w", err) +// beginInstall begins this session's BASE install at baseLSN under a fresh +// random, nonzero install ID (DESIGN 8.1, 8.7). +func (r *Receiver) beginInstall(baseLSN uint64) (storage.InstallHandle, error) { + var id [16]byte + for id == ([16]byte{}) { + if _, err := rand.Read(id[:]); err != nil { + return nil, fmt.Errorf("BASE install ID: %w", err) } } - r.basePrepared = true - return nil + h, err := storage.BeginInstall(r.store, baseLSN, id) + if err != nil { + return nil, fmt.Errorf("begin BASE install: %w", err) + } + r.installID = id + return h, nil } // shouldAck evaluates the cadence rule per docs/recovery-pin-floor-wire.md §3. @@ -410,7 +415,17 @@ func (r *Receiver) sendAck() error { errors.New("sendAck before SessionStart")) } st := r.session.Status() - syncedLSN, err := r.store.Sync() + // While installing, the durable claim is the install log's + // (SyncInstallLog, DESIGN 7); the logical Sync is gated there. After this + // session's own completion the logical Sync is ordinary again (8.7 done + // path), and the WAL lane may still be sending. + var syncedLSN uint64 + var err error + if syncer, ok := r.store.(storage.InstallLogSyncer); ok && !st.BaseDone { + syncedLSN, err = syncer.SyncInstallLog(r.installID) + } else { + syncedLSN, err = r.store.Sync() + } if err != nil { return newFailure(FailureSubstrate, PhaseRecvAckWrite, err) } diff --git a/seaweed-block/core/recovery/receiver_base_pin_test.go b/seaweed-block/core/recovery/receiver_base_pin_test.go index 88feb115c4..0a305db5f5 100644 --- a/seaweed-block/core/recovery/receiver_base_pin_test.go +++ b/seaweed-block/core/recovery/receiver_base_pin_test.go @@ -90,7 +90,7 @@ type basePreparingStore struct { prepareCalls int } -func (s *basePreparingStore) BeginBaseInstall() error { +func (s *basePreparingStore) BeginBaseStage() error { s.prepareCalls++ return nil } @@ -196,7 +196,7 @@ func (s *receiverAckStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error func (s *receiverAckStore) WriteExtentDirect(lba uint32, data []byte) error { return nil } -func (s *receiverAckStore) AllBlocks() map[uint32][]byte { return nil } +func (s *receiverAckStore) AllBlocks() (map[uint32][]byte, error) { return nil, nil } func (s *receiverAckStore) ScanLBAs(fromLSN uint64, fn func(storage.RecoveryEntry) error) error { return nil diff --git a/seaweed-block/core/recovery/receiver_install_format_v3_test.go b/seaweed-block/core/recovery/receiver_install_format_v3_test.go new file mode 100644 index 0000000000..907aaf6fbd --- /dev/null +++ b/seaweed-block/core/recovery/receiver_install_format_v3_test.go @@ -0,0 +1,395 @@ +//go:build swblock_format_v3_test + +package recovery + +import ( + "bytes" + "errors" + "net" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Plan row 9b controls (DESIGN r17.3.1 section 8.7): the dual-lane Receiver +// on a dark v3 store. Every BASE block and WAL entry goes through the +// session's install handle; both admission schedules run through the real +// receiver (WriteBase through frameBaseBlock, ApplyInstallEntry through +// RebuildSession.ApplyWALEntry from frameWALEntry). Owner: claude03. +// Mutants are the row 9a store mutants (shared-begin, no-id-check, +// premature-check) plus the row 9b caller mutants named per control. + +const v3RecvBlock = 4096 + +func v3RecvStore(t *testing.T) *storage.WALStore { + t.Helper() + s, _ := v3RecvStoreAt(t) + t.Cleanup(func() { _ = s.Close() }) + return s +} + +func v3RecvStoreAt(t *testing.T) (*storage.WALStore, string) { + t.Helper() + path := filepath.Join(t.TempDir(), "recv.v3") + s, err := storage.CreateWALStoreV3Test(path, 64, v3RecvBlock) + if err != nil { + t.Fatal(err) + } + return s, path +} + +func v3Blk(b byte) []byte { return bytes.Repeat([]byte{b}, v3RecvBlock) } + +// v3Peer is the primary side of one receiver connection. Every frame the +// receiver writes is read into frames, so the receiver never blocks on the +// synchronous pipe. +type v3Peer struct { + conn net.Conn + frames chan frameType + acks chan uint64 // AcknowledgedLSN of every BaseBatchAck, in order + done chan error +} + +func startV3Receiver(t *testing.T, store storage.LogicalStorage) *v3Peer { + t.Helper() + primary, replica := net.Pipe() + t.Cleanup(func() { primary.Close(); replica.Close() }) + p := &v3Peer{conn: primary, frames: make(chan frameType, 64), acks: make(chan uint64, 64), done: make(chan error, 1)} + r := NewReceiverWithCadence(store, replica, 1, time.Hour) // an ack after every BASE block + go func() { _, err := r.Run(); p.done <- err; replica.Close() }() + go func() { + for { + ft, payload, err := readFrame(primary) + if err != nil { + close(p.frames) + return + } + if ft == frameBaseBatchAck { + if a, err := decodeBaseBatchAck(payload); err == nil { + p.acks <- a.AcknowledgedLSN + } + } + p.frames <- ft + } + }() + return p +} + +func (p *v3Peer) send(t *testing.T, ft frameType, payload []byte) { + t.Helper() + if err := writeFrame(p.conn, ft, payload); err != nil { + t.Fatalf("write frame %v: %v", ft, err) + } +} + +func (p *v3Peer) start(t *testing.T, fromLSN uint64) { + t.Helper() + p.send(t, frameSessionStart, encodeSessionStart(sessionStartPayload{SessionID: 1, FromLSN: fromLSN, NumBlocks: 64})) +} + +func (p *v3Peer) want(t *testing.T, ft frameType) { + t.Helper() + select { + case got, ok := <-p.frames: + if !ok || got != ft { + t.Fatalf("frame %v (open %v), want %v", got, ok, ft) + } + case <-time.After(10 * time.Second): + t.Fatalf("no %v frame", ft) + } +} + +func (p *v3Peer) runErr(t *testing.T) error { + t.Helper() + select { + case err := <-p.done: + return err + case <-time.After(10 * time.Second): + t.Fatal("receiver did not end") + return nil + } +} + +// holdFirst returns a hook that parks the first call until release runs. +// The rendezvous is bounded (a hook that never fires fails the test instead +// of hanging it) and cleanup always releases. +func holdFirst(t *testing.T) (hook func(), waitParked func(), release func()) { + parked, gate := make(chan struct{}), make(chan struct{}) + var once sync.Once + release = func() { once.Do(func() { close(gate) }) } + t.Cleanup(release) + var armed atomic.Bool + armed.Store(true) + waitParked = func() { + t.Helper() + select { + case <-parked: + case <-time.After(10 * time.Second): + t.Fatal("the held frame never reached the install hook") + } + } + return func() { + if armed.CompareAndSwap(true, false) { + close(parked) + <-gate + } + }, waitParked, release +} + +func readV3Recv(t *testing.T, s *storage.WALStore, lba uint32) []byte { + t.Helper() + b, err := s.Read(lba) + if err != nil { + t.Fatal(err) + } + return b +} + +// The positive receiver rebuild: SessionStart begins the install, a BASE +// block and a WAL entry go through the handle, BaseDone completes it +// (installed) and the barrier completes the session. BaseLSN 5 is above +// the checkpoint, so installed is not retired yet (8.4). +// Mutant: a receiver that skips the begin (the legacy handle on v3) is +// refused by the v3 store (errV3NotYet) and fails here. +func TestReceiverV3InstallThroughTheHandle(t *testing.T) { + s := v3RecvStore(t) + p := startV3Receiver(t, s) + p.start(t, 5) + p.send(t, frameBaseBlock, encodeBaseBlock(3, v3Blk(0x33))) + p.want(t, frameBaseBatchAck) + if st, _ := storage.BaseStateV3Test(s); st != storage.BaseInstalling { + t.Fatalf("state %d during the session, want installing", st) + } + p.send(t, frameWALEntry, encodeWALEntry(WALKindBacklog, 4, 6, v3Blk(0x44))) + p.send(t, frameBaseDone, nil) + p.want(t, frameBaseBatchAck) + p.send(t, frameBarrierReq, nil) + p.want(t, frameBarrierResp) + if err := p.runErr(t); err != nil { + t.Fatalf("receiver: %v", err) + } + if st, _ := storage.BaseStateV3Test(s); st != storage.BaseInstalled { + t.Fatalf("state %d after BaseDone, want installed", st) + } + for lba, want := range map[uint32]byte{3: 0x33, 4: 0x44} { + if got := readV3Recv(t, s, lba); !bytes.Equal(got, v3Blk(want)) { + t.Fatalf("LBA %d = %x..., want %x", lba, got[0], want) + } + } +} + +// Drain setup through the receiver (codex01 r12 P2): A's admitted BASE +// write is held; B's SessionStart begin waits for it; B writes the target +// block and stays installing; a further A frame fails A's session with +// ErrInstallSuperseded and B's block is byte-identical. +func TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession(t *testing.T) { + s := v3RecvStore(t) + a := startV3Receiver(t, s) + a.start(t, 0) + hook, waitParked, release := holdFirst(t) + storage.SetInstallHooksV3Test(s, nil, hook) + a.send(t, frameBaseBlock, encodeBaseBlock(7, v3Blk(0xAA))) + waitParked() + _, idA := storage.BaseStateV3Test(s) + b := startV3Receiver(t, s) + bSent := make(chan struct{}) + go func() { + b.start(t, 0) + b.send(t, frameBaseBlock, encodeBaseBlock(7, v3Blk(0xBB))) + close(bSent) + }() + // B must not get past its begin while A's write is held; give a wrong + // (shared) begin time to write first. The oracle is the bytes below. + select { + case ft := <-b.frames: + if ft != frameBaseBatchAck { + t.Fatalf("B frame %v", ft) + } + b.frames <- ft + case <-time.After(300 * time.Millisecond): + } + release() + // A's write finishes; its progress ack (SyncInstallLog, row 10) either + // runs before B's begin, or queues behind B's exclusive begin and fails + // with ErrInstallIDMismatch. Either way A cannot write again. + aAcked := false + select { + case ft, ok := <-a.frames: + if !ok || ft != frameBaseBatchAck { + if err := a.runErr(t); !errors.Is(err, storage.ErrInstallIDMismatch) { + t.Fatalf("A's ack after the drain: %v, want ErrInstallIDMismatch", err) + } + } else { + aAcked = true + } + case <-time.After(10 * time.Second): + t.Fatal("A neither acked nor ended") + } + <-bSent + b.want(t, frameBaseBatchAck) + if got := readV3Recv(t, s, 7); !bytes.Equal(got, v3Blk(0xBB)) { + t.Fatalf("LBA 7 = %x..., want B's bytes", got[0]) + } + if aAcked { + a.send(t, frameBaseBlock, encodeBaseBlock(7, v3Blk(0xAA))) + if err := a.runErr(t); !errors.Is(err, storage.ErrInstallSuperseded) { + t.Fatalf("A after the supersession: %v, want ErrInstallSuperseded", err) + } + } + if got := readV3Recv(t, s, 7); !bytes.Equal(got, v3Blk(0xBB)) { + t.Fatalf("LBA 7 = %x... after A's stale frame, want B's bytes", got[0]) + } + if st, id := storage.BaseStateV3Test(s); st != storage.BaseInstalling || id == idA { + t.Fatalf("state %d id unchanged %v, want installing under B", st, id == idA) + } +} + +// Premature-check setup through the receiver (codex03 r11): A's frame parks +// before acquiring installMu; B supersedes, writes the target block and +// stays installing; A resumes and its session fails with +// ErrInstallSuperseded, B's block byte-identical. WriteBase runs through +// frameBaseBlock, ApplyInstallEntry through frameWALEntry. +func TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession(t *testing.T) { + for _, lane := range []string{"base", "wal"} { + t.Run(lane, func(t *testing.T) { + s := v3RecvStore(t) + a := startV3Receiver(t, s) + a.start(t, 0) + hook, waitParked, release := holdFirst(t) + storage.SetInstallHooksV3Test(s, hook, nil) + if lane == "base" { + a.send(t, frameBaseBlock, encodeBaseBlock(7, v3Blk(0xAA))) + } else { + a.send(t, frameWALEntry, encodeWALEntry(WALKindBacklog, 7, 1, v3Blk(0xAA))) + } + waitParked() + b := startV3Receiver(t, s) + b.start(t, 0) + b.send(t, frameBaseBlock, encodeBaseBlock(7, v3Blk(0xBB))) + b.want(t, frameBaseBatchAck) + release() + if err := a.runErr(t); !errors.Is(err, storage.ErrInstallSuperseded) { + t.Fatalf("parked A (%s): %v, want ErrInstallSuperseded", lane, err) + } + if got := readV3Recv(t, s, 7); !bytes.Equal(got, v3Blk(0xBB)) { + t.Fatalf("LBA 7 = %x..., want B's bytes", got[0]) + } + if st, _ := storage.BaseStateV3Test(s); st != storage.BaseInstalling { + t.Fatalf("state %d, want installing under B", st) + } + }) + } +} + +// A superseded session's BaseDone fails (DESIGN 8.2 step 4): the +// completion error propagates, no BaseBatchAck is sent and the volume stays +// installing under the newer ID. Mutant: a receiver that discards the +// MarkBaseComplete error acks and fails here. +func TestReceiverV3SupersededBaseDoneFailsWithoutAnAck(t *testing.T) { + s := v3RecvStore(t) + a := startV3Receiver(t, s) + a.start(t, 0) + a.send(t, frameBaseBlock, encodeBaseBlock(2, v3Blk(0x22))) + a.want(t, frameBaseBatchAck) + b := startV3Receiver(t, s) + b.start(t, 0) + b.send(t, frameBaseBlock, encodeBaseBlock(3, v3Blk(0x33))) + b.want(t, frameBaseBatchAck) + a.send(t, frameBaseDone, nil) + if err := a.runErr(t); !errors.Is(err, storage.ErrInstallSuperseded) { + t.Fatalf("A BaseDone: %v, want ErrInstallSuperseded", err) + } + if ft, ok := <-a.frames; ok { + t.Fatalf("A sent %v after a failed completion", ft) + } + if st, _ := storage.BaseStateV3Test(s); st != storage.BaseInstalling { + t.Fatalf("state %d, want installing", st) + } +} + +// codex01 row 9b P1: the real Sender sends BaseDone from its base lane while +// its WAL lane is still sending (sender.go base goroutine). A WAL entry of +// the same session after BaseDone must still apply, and the barrier then +// completes with both lanes' bytes. Mutant: admitting install-lane WAL +// only while installing fails here (the entry after BaseDone is refused). +func TestReceiverV3WALAfterBaseDoneStillApplies(t *testing.T) { + s := v3RecvStore(t) + p := startV3Receiver(t, s) + p.start(t, 5) + p.send(t, frameBaseBlock, encodeBaseBlock(3, v3Blk(0x33))) + p.want(t, frameBaseBatchAck) + p.send(t, frameWALEntry, encodeWALEntry(WALKindBacklog, 4, 6, v3Blk(0x44))) + p.send(t, frameBaseDone, nil) + p.want(t, frameBaseBatchAck) + p.send(t, frameWALEntry, encodeWALEntry(WALKindSessionLive, 5, 7, v3Blk(0x55))) + p.send(t, frameBarrierReq, nil) + p.want(t, frameBarrierResp) + if err := p.runErr(t); err != nil { + t.Fatalf("receiver: %v", err) + } + for lba, want := range map[uint32]byte{3: 0x33, 4: 0x44, 5: 0x55} { + if got := readV3Recv(t, s, lba); !bytes.Equal(got, v3Blk(want)) { + t.Fatalf("LBA %d = %x..., want %x", lba, got[0], want) + } + } +} + +// The same Sender order with a crash after the barrier: every byte of both +// lanes, including the WAL entry sent after BaseDone, survives a crash and +// a reopen (DESIGN r17.4, section 11). +func TestReceiverV3WALAfterBaseDoneSurvivesACrash(t *testing.T) { + s, path := v3RecvStoreAt(t) + p := startV3Receiver(t, s) + p.start(t, 5) + p.send(t, frameBaseBlock, encodeBaseBlock(3, v3Blk(0x33))) + p.want(t, frameBaseBatchAck) + p.send(t, frameWALEntry, encodeWALEntry(WALKindBacklog, 4, 6, v3Blk(0x44))) + p.send(t, frameBaseDone, nil) + p.want(t, frameBaseBatchAck) + p.send(t, frameWALEntry, encodeWALEntry(WALKindSessionLive, 5, 7, v3Blk(0x55))) + p.send(t, frameBarrierReq, nil) + p.want(t, frameBarrierResp) + if err := p.runErr(t); err != nil { + t.Fatalf("receiver: %v", err) + } + r, err := storage.CrashReopenV3Test(s, path) + if err != nil { + t.Fatalf("crash and reopen: %v", err) + } + t.Cleanup(func() { _ = r.Close() }) + for lba, want := range map[uint32]byte{3: 0x33, 4: 0x44, 5: 0x55} { + if got := readV3Recv(t, r, lba); !bytes.Equal(got, v3Blk(want)) { + t.Fatalf("after reopen LBA %d = %x..., want %x", lba, got[0], want) + } + } +} + +// Row 10a: a progress ack during the install is the install log's durable +// claim (SyncInstallLog, DESIGN 7): it reports min(WALApplied, H) and the +// slot carries W = H with the volume still installing; the logical Sync +// stays gated. Mutant: sendAck through the gated logical Sync fails the +// session at its first ack. +func TestReceiverV3ProgressAckIsTheInstallLog(t *testing.T) { + s := v3RecvStore(t) + p := startV3Receiver(t, s) + p.start(t, 5) + p.send(t, frameBaseBlock, encodeBaseBlock(3, v3Blk(0x33))) + p.want(t, frameBaseBatchAck) + p.send(t, frameWALEntry, encodeWALEntry(WALKindBacklog, 4, 6, v3Blk(0x44))) + p.send(t, frameBaseBlock, encodeBaseBlock(2, v3Blk(0x22))) + p.want(t, frameBaseBatchAck) + <-p.acks // the first ack, before the WAL entry + if got := <-p.acks; got != 6 { + t.Fatalf("progress ack AcknowledgedLSN %d, want 6", got) + } + if st, _ := storage.BaseStateV3Test(s); st != storage.BaseInstalling { + t.Fatalf("state %d after a progress ack, want installing", st) + } + if f, err := s.Sync(); f != 0 || !errors.Is(err, storage.ErrBaseInstalling) { + t.Fatalf("logical Sync during the install = (%d, %v), want (0, ErrBaseInstalling)", f, err) + } +} diff --git a/seaweed-block/core/replication/apply_gate_format_v3_test.go b/seaweed-block/core/replication/apply_gate_format_v3_test.go new file mode 100644 index 0000000000..503461a067 --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_format_v3_test.go @@ -0,0 +1,44 @@ +//go:build swblock_format_v3_test + +package replication + +import ( + "bytes" + "path/filepath" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +// The real ReplicaApplyGate over a dark v3 store: the recovery lane applies +// fresh entries and stale-skips without touching the store; the live lane +// applies the next LSNs. Mutant: ApplyEntry refused on v3 fails here. +func TestApplyGateOverV3Store(t *testing.T) { + s, err := storage.CreateWALStoreV3Test(filepath.Join(t.TempDir(), "gate.v3"), 64, blockSize) + if err != nil { + t.Fatal(err) + } + defer s.Close() + gate := NewReplicaApplyGate(s) + rec := transport.RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 1} + live := transport.RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 100} + blk := func(b byte) []byte { return bytes.Repeat([]byte{b}, blockSize) } + for lsn := uint64(1); lsn <= 2; lsn++ { + if err := gate.ApplyRecovery(rec, uint32(lsn), blk(byte(lsn)), lsn); err != nil { + t.Fatalf("recovery apply %d: %v", lsn, err) + } + } + if err := gate.ApplyRecovery(rec, 2, blk(0xEE), 1); err != nil { + t.Fatalf("recovery stale-skip: %v", err) + } + if err := gate.ApplyLive(live, 3, blk(3), 3); err != nil { + t.Fatalf("live apply: %v", err) + } + for lba := uint32(1); lba <= 3; lba++ { + got, err := s.Read(lba) + if err != nil || !bytes.Equal(got, blk(byte(lba))) { + t.Fatalf("LBA %d: err %v", lba, err) + } + } +} diff --git a/seaweed-block/core/replication/component/apply_gate_scenarios_test.go b/seaweed-block/core/replication/component/apply_gate_scenarios_test.go index 58db25f466..858dbf7bb3 100644 --- a/seaweed-block/core/replication/component/apply_gate_scenarios_test.go +++ b/seaweed-block/core/replication/component/apply_gate_scenarios_test.go @@ -25,6 +25,7 @@ import ( func TestComponent_RecoveryStaleSkip_CoverageStillAdvances(t *testing.T) { component.RunSubstrate(t, "walstore", component.Walstore, func(t *testing.T, c *component.Cluster) { c.WithReplicas(1).WithApplyGate().Start() + primeReplicaZeroBase(t, c, 49) gate := c.ApplyGate(0) if gate == nil { @@ -67,6 +68,7 @@ func TestComponent_RecoveryStaleSkip_CoverageStillAdvances(t *testing.T) { func TestComponent_LiveLaneStaleEntry_FailsLoud(t *testing.T) { component.RunSubstrate(t, "walstore", component.Walstore, func(t *testing.T, c *component.Cluster) { c.WithReplicas(1).WithApplyGate().Start() + primeReplicaZeroBase(t, c, 49) gate := c.ApplyGate(0) // Live-lane lineage (TargetLSN == liveShipTargetLSN == 1). @@ -114,6 +116,7 @@ func TestComponent_LiveLaneStaleEntry_FailsLoud(t *testing.T) { func TestComponent_LanePurity_CallerControlsDispatch(t *testing.T) { component.RunSubstrate(t, "walstore", component.Walstore, func(t *testing.T, c *component.Cluster) { c.WithReplicas(1).WithApplyGate().Start() + primeReplicaZeroBase(t, c, 49) gate := c.ApplyGate(0) @@ -156,6 +159,7 @@ func TestComponent_LanePurity_CallerControlsDispatch(t *testing.T) { func TestComponent_OptionCHybrid_WalstoreSeed(t *testing.T) { component.RunSubstrate(t, "walstore", component.Walstore, func(t *testing.T, c *component.Cluster) { c.WithReplicas(1).WithApplyGate().Start() + primeReplicaZeroBase(t, c, 49) // Pre-apply on the replica's substrate directly to populate // dirty map (which walstore's AppliedLSNs() reads). @@ -170,7 +174,7 @@ func TestComponent_OptionCHybrid_WalstoreSeed(t *testing.T) { } // Trigger session init (any apply does it). Use unrelated LBA. - gate.ApplyRecovery(recov, 99, makeData(0xCC), 60) + gate.ApplyRecovery(recov, 99, makeData(0xCC), 51) // Now LBA=5's seed should be visible. seedLSN, ok := gate.SessionAppliedLSN(7, 5) diff --git a/seaweed-block/core/replication/component/cluster.go b/seaweed-block/core/replication/component/cluster.go index 9310f8eb69..d1ce45f6d8 100644 --- a/seaweed-block/core/replication/component/cluster.go +++ b/seaweed-block/core/replication/component/cluster.go @@ -793,7 +793,10 @@ func (c *Cluster) allConverged() bool { } func (c *Cluster) replicaConverged(r *ReplicaNode) bool { - pBlocks := c.primary.Store.AllBlocks() + pBlocks, err := c.primary.Store.AllBlocks() + if err != nil { + return false + } for lba, pData := range pBlocks { rData, _ := r.Store.Read(lba) if !bytes.Equal(pData, rData) { @@ -816,7 +819,10 @@ func (c *Cluster) divergenceReport() string { func (c *Cluster) divergenceReportFor(r *ReplicaNode) string { var diffs []string - pBlocks := c.primary.Store.AllBlocks() + pBlocks, err := c.primary.Store.AllBlocks() + if err != nil { + return fmt.Sprintf("primary snapshot failed: %v", err) + } for lba, pData := range pBlocks { rData, _ := r.Store.Read(lba) if !bytes.Equal(pData, rData) { diff --git a/seaweed-block/core/replication/component/cluster_test.go b/seaweed-block/core/replication/component/cluster_test.go index d9853bbc0d..3d49ea5369 100644 --- a/seaweed-block/core/replication/component/cluster_test.go +++ b/seaweed-block/core/replication/component/cluster_test.go @@ -110,14 +110,43 @@ func TestComponent_ProbeHappy(t *testing.T) { }) } +// Pin the genesis replay window across both sessions. Unlike a logical +// retention setting, this prevents the old impl1 checkpoint releasing it. +type twoReplicaWALPin struct{} + +func (twoReplicaWALPin) MinPinAcrossActiveSessions() (uint64, bool) { return 0, true } + // TestComponent_TwoReplicas_BothConverge — multi-replica scenario. // Demonstrates WithReplicas(N) + per-replica catch-up. func TestComponent_TwoReplicas_BothConverge(t *testing.T) { component.RunMatrix(t, func(t *testing.T, c *component.Cluster) { c.WithReplicas(2).Start() + var ws *storage.WALStore + var priorFlushes uint64 + if s, ok := c.Primary().Store.(*storage.WALStore); ok { + ws, priorFlushes = s, s.FlushCount() + s.SetRecycleFloorSource(twoReplicaWALPin{}) + defer s.SetRecycleFloorSource(nil) + } + c.PrimaryWriteN(10) c.PrimarySync() + // Let the real flusher complete work before catch-up, so the pin + // (rather than winning a race with the timer) keeps WAL available. + if ws != nil { + deadline := time.Now().Add(10 * time.Second) + for ws.FlushCount() == priorFlushes && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) + } + if ws.FlushCount() == priorFlushes { + t.Fatal("primary did not complete a flush") + } + if cp := ws.CheckpointLSN(); cp != 0 { + t.Fatalf("active replay pin allowed checkpoint%d, want0", cp) + } + } + for i := 0; i < c.ReplicaCount(); i++ { r := c.CatchUpReplica(i) if !r.Success { @@ -134,7 +163,7 @@ func TestComponent_TwoReplicas_BothConverge(t *testing.T) { // pre-existing replica state. func TestComponent_PartialReplicaThenCatchUp(t *testing.T) { component.RunMatrix(t, func(t *testing.T, c *component.Cluster) { - c.WithReplicas(1).Start() + c.WithReplicas(1).WithApplyGate().Start() // Stage 1: primary + replica both have LBAs 0..4. for i := 0; i < 5; i++ { data := make([]byte, component.DefaultBlockSize) diff --git a/seaweed-block/core/replication/component/format_v3_fixture_test.go b/seaweed-block/core/replication/component/format_v3_fixture_test.go new file mode 100644 index 0000000000..a05d7f239b --- /dev/null +++ b/seaweed-block/core/replication/component/format_v3_fixture_test.go @@ -0,0 +1,24 @@ +package component_test + +import ( + "github.com/seaweedfs/seaweed-block/core/replication/component" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" +) + +// These scenarios prime an otherwise zero replica at a chosen historical +// floor. V3 requires a complete BASE anchor before any later sparse LSN. +func primeReplicaZeroBase(t *testing.T, c *component.Cluster, floor uint64) { + t.Helper() + s, ok := c.Replica(0).Store.(*storage.WALStore) + if !ok || !s.FormatV3() { + return + } + h, err := s.BeginBaseInstall(floor, [16]byte{0x61}) + if err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/replication/component/frontier_regression_test.go b/seaweed-block/core/replication/component/frontier_regression_test.go index 51b70d2630..fa7d1386e5 100644 --- a/seaweed-block/core/replication/component/frontier_regression_test.go +++ b/seaweed-block/core/replication/component/frontier_regression_test.go @@ -35,7 +35,7 @@ import ( // INV-REPL-CATCHUP-FRONTIER-MONOTONIC-UNDER-OVER-SCAN. func TestComponent_CatchupFromBelowReplicaLSN_NoFrontierRegression(t *testing.T) { component.RunMatrix(t, func(t *testing.T, c *component.Cluster) { - c.WithReplicas(1).Start() + c.WithReplicas(1).WithApplyGate().Start() // Stage 1: prime replica with LBAs 0..4 at LSNs 1..5. // (Use ReplicaApply to install state directly — bypasses diff --git a/seaweed-block/core/replication/component/qa_g5_scenarios_test.go b/seaweed-block/core/replication/component/qa_g5_scenarios_test.go index 421bf2a2f6..a12f2f7e1e 100644 --- a/seaweed-block/core/replication/component/qa_g5_scenarios_test.go +++ b/seaweed-block/core/replication/component/qa_g5_scenarios_test.go @@ -43,6 +43,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/replication/component" + "github.com/seaweedfs/seaweed-block/core/storage" ) // TestG5_QA_LaneDiscipline_LiveAndRecoveryConcurrent_MultiReplica was @@ -125,10 +126,28 @@ func TestG5_QA_RF2_BothReplicasReachByteEqual(t *testing.T) { component.RunMatrix(t, func(t *testing.T, c *component.Cluster) { c.WithReplicas(2).WithApplyGate().Start() + // This scenario requires WAL replay from genesis for both replicas. + // Retain those 30 records even when checkpointing wins the race. + if s, ok := c.Primary().Store.(*storage.WALStore); ok { + s.SetRecoveryRetentionLSNs(30) + } + // Write 30 LBAs on primary. c.PrimaryWriteN(30) c.PrimarySync() + // Exercise both WAL catch-ups after the real checkpoint, rather than + // depending on completion before the background flusher runs. + if s, ok := c.Primary().Store.(*storage.WALStore); ok { + deadline := time.Now().Add(5 * time.Second) + for s.CheckpointLSN() < 30 && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) + } + if s.CheckpointLSN() < 30 { + t.Fatal("primary did not checkpoint the test writes") + } + } + // Both replicas catch up independently (single catch-up per // replica avoids sessionID=1 collision per known carry). for i := 0; i < 2; i++ { diff --git a/seaweed-block/core/replication/component/stale_entry_adversarial_test.go b/seaweed-block/core/replication/component/stale_entry_adversarial_test.go index f583a03c24..d9bf8652df 100644 --- a/seaweed-block/core/replication/component/stale_entry_adversarial_test.go +++ b/seaweed-block/core/replication/component/stale_entry_adversarial_test.go @@ -69,6 +69,7 @@ func TestComponent_Adversarial_StaleEntryDoesNotRegress(t *testing.T) { // Stage 2: replica is primed with the LATEST state (LSN=2, // value B). Simulates "replica caught up via prior live // ship before our catch-up session." + primeReplicaZeroBase(t, c, 1) c.ReplicaApply(0, 7, dataB, 2) c.Replica(0).Store.Sync() diff --git a/seaweed-block/core/replication/component/t4d3_scenarios_test.go b/seaweed-block/core/replication/component/t4d3_scenarios_test.go index bc306baea2..37a41242d4 100644 --- a/seaweed-block/core/replication/component/t4d3_scenarios_test.go +++ b/seaweed-block/core/replication/component/t4d3_scenarios_test.go @@ -215,6 +215,7 @@ func TestT4d3_RecoveryTargetLSN1_RoutesByConnectionContext(t *testing.T) { // the catch-up session fails. Recovery lane must stale-skip. replicaData := make([]byte, component.DefaultBlockSize) replicaData[0] = 0x22 + primeReplicaZeroBase(t, c, 1) c.ReplicaApply(0, 0, replicaData, 2) result := c.CatchUpReplica(0) diff --git a/seaweed-block/core/replication/invalidate_terminal_regression_test.go b/seaweed-block/core/replication/invalidate_terminal_regression_test.go new file mode 100644 index 0000000000..24044917a7 --- /dev/null +++ b/seaweed-block/core/replication/invalidate_terminal_regression_test.go @@ -0,0 +1,18 @@ +package replication + +import "testing" + +func TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState(t *testing.T) { + peer, _, _ := setupPeerWithRealReplica(t) + peer.SetState(ReplicaDegraded) + peer.SetState(ReplicaNeedsRebuild) + if got := peer.State(); got != ReplicaNeedsRebuild { + t.Fatalf("setup state=%s", got) + } + peer.Invalidate("authority peer-down observation") + invalidated := peer.State() + peer.SetState(ReplicaHealthy) + if invalidated != ReplicaNeedsRebuild || peer.State() != ReplicaNeedsRebuild { + t.Fatalf("terminal state escaped: after Invalidate=%s after SetState(Healthy)=%s; want NeedsRebuild throughout", invalidated, peer.State()) + } +} diff --git a/seaweed-block/core/replication/invalidate_transition_test.go b/seaweed-block/core/replication/invalidate_transition_test.go new file mode 100644 index 0000000000..9b0a698638 --- /dev/null +++ b/seaweed-block/core/replication/invalidate_transition_test.go @@ -0,0 +1,60 @@ +package replication + +import ( + "bytes" + "log" + "strings" + "testing" +) + +// #182: Invalidate still moves every non-terminal state to Degraded. A new +// peer starts Healthy; Unknown is only set by Close, after which Invalidate +// returns early, so it is not a reachable starting state here. +func TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded(t *testing.T) { + for _, tc := range []struct { + name string + setup []ReplicaState + want ReplicaState // state before Invalidate + }{ + {"healthy", []ReplicaState{ReplicaHealthy}, ReplicaHealthy}, + {"degraded", []ReplicaState{ReplicaHealthy, ReplicaDegraded}, ReplicaDegraded}, + {"catching_up", []ReplicaState{ReplicaHealthy, ReplicaCatchingUp}, ReplicaCatchingUp}, + } { + t.Run(tc.name, func(t *testing.T) { + peer, _, _ := setupPeerWithRealReplica(t) + for _, s := range tc.setup { + peer.SetState(s) + } + if got := peer.State(); got != tc.want { + t.Fatalf("setup state=%s want %s", got, tc.want) + } + peer.Invalidate("test invalidation") + if got := peer.State(); got != ReplicaDegraded { + t.Fatalf("after Invalidate from %s: state=%s want degraded", tc.want, got) + } + }) + } +} + +// #182: on a NeedsRebuild peer, Invalidate keeps the state but still logs +// the reason, its only other effect. +func TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason(t *testing.T) { + peer, _, _ := setupPeerWithRealReplica(t) + peer.SetState(ReplicaHealthy) + peer.SetState(ReplicaDegraded) + peer.SetState(ReplicaNeedsRebuild) + if got := peer.State(); got != ReplicaNeedsRebuild { + t.Fatalf("setup state=%s", got) + } + var buf bytes.Buffer + prev := log.Writer() + log.SetOutput(&buf) + peer.Invalidate("reason-182-marker") + log.SetOutput(prev) + if got := peer.State(); got != ReplicaNeedsRebuild { + t.Fatalf("state=%s want needs_rebuild kept", got) + } + if !strings.Contains(buf.String(), "reason-182-marker") { + t.Fatalf("invalidation reason not logged; log=%q", buf.String()) + } +} diff --git a/seaweed-block/core/replication/peer.go b/seaweed-block/core/replication/peer.go index ffe01ab003..6280721502 100644 --- a/seaweed-block/core/replication/peer.go +++ b/seaweed-block/core/replication/peer.go @@ -804,6 +804,9 @@ func replicaStateTransitionAllowed(prev, next ReplicaState) bool { // transitions (CatchingUp, NeedsRebuild) flow through SetState. // Calling Invalidate on an already-Degraded peer is a no-op (beyond // the log line — still useful because the reason string may be new). +// Calling it on a NeedsRebuild peer keeps NeedsRebuild: Invalidate obeys +// replicaStateTransitionAllowed like SetState, and NeedsRebuild is +// terminal. // // Called by: ShipEntry on transport error; ReplicationVolume on // explicit peer-down from authority updates. @@ -816,6 +819,17 @@ func (p *ReplicaPeer) Invalidate(reason string) { return } prev := p.state + // Invalidate goes through the same transition gate as SetState, so + // it can never move a peer out of a terminal state (NeedsRebuild). + // Every other state may move to Degraded, so their behaviour is + // unchanged. The log line is Invalidate's only other effect and is + // kept either way: the reason may be new. + if !replicaStateTransitionAllowed(prev, ReplicaDegraded) { + p.mu.Unlock() + log.Printf("replication: peer %s invalidated, state kept (prev=%s is terminal, reason=%s)", + p.target.ReplicaID, prev, reason) + return + } p.state = ReplicaDegraded p.mu.Unlock() log.Printf("replication: peer %s invalidated (prev=%s, reason=%s)", diff --git a/seaweed-block/core/replication/volume.go b/seaweed-block/core/replication/volume.go index 3fe1433363..5964fa7554 100644 --- a/seaweed-block/core/replication/volume.go +++ b/seaweed-block/core/replication/volume.go @@ -798,9 +798,8 @@ func (v *ReplicationVolume) dispatchLocalWrite(w LocalWrite) writeAckSet { } v.mu.Unlock() - log.Printf("replication: OnLocalWrite volume=%s lba=%d lsn=%d peers=%d", - v.volumeID, w.LBA, w.LSN, peerCount) - + // No per-write log line here (#204): at RF=1 it filled the volume log under + // sustained writes. Per-write evidence is in the counters (Stats). v.writeFanout.Add(replicationDurationNanos(time.Since(start))) return writeAckSet{ mode: mode, diff --git a/seaweed-block/core/replication/volume_write_log_test.go b/seaweed-block/core/replication/volume_write_log_test.go new file mode 100644 index 0000000000..0c842ba103 --- /dev/null +++ b/seaweed-block/core/replication/volume_write_log_test.go @@ -0,0 +1,70 @@ +package replication + +import ( + "bytes" + "context" + "log" + "strings" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type writeLogBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (w *writeLogBuffer) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + return w.b.Write(p) +} + +func (w *writeLogBuffer) String() string { + w.mu.Lock() + defer w.mu.Unlock() + return w.b.String() +} + +// Issue #204: at RF=1 every local write logged one INFO line on the write +// path ("replication: OnLocalWrite volume=... lba=... lsn=... peers=0"). Under +// sustained writes that filled the volume's log (162 MB in 13 minutes) and +// buried the useful lines. Per-write detail belongs in the counters (Stats), +// not the log. +func TestReplicationVolume_LocalWritesDoNotLogPerWrite(t *testing.T) { + buf := &writeLogBuffer{} + prev, flags := log.Writer(), log.Flags() + log.SetOutput(buf) + t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) }) + + store := storage.NewBlockStore(8, 4096) + v := NewReplicationVolume("rf1", store) + t.Cleanup(func() { _ = v.Close() }) + + const writes = 100 + data := make([]byte, 4096) + for i := 0; i < writes; i++ { + lsn, err := store.Write(uint32(i%8), data) + if err != nil { + t.Fatal(err) + } + if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: uint32(i % 8), LSN: lsn, Data: data}); err != nil { + t.Fatal(err) + } + } + if n := strings.Count(buf.String(), "OnLocalWrite"); n != 0 { + t.Fatalf("%d local writes produced %d per-write log lines; first: %q", writes, n, firstLine(buf.String())) + } + if got := v.Stats().WriteOps; got != writes { + t.Fatalf("Stats().WriteOps = %d, want %d (the counters keep per-write evidence)", got, writes) + } +} + +func firstLine(s string) string { + if i := strings.IndexByte(s, '\n'); i >= 0 { + return s[:i] + } + return s +} diff --git a/seaweed-block/core/storage/activation_recycle_v3_test.go b/seaweed-block/core/storage/activation_recycle_v3_test.go new file mode 100644 index 0000000000..6a22f353e8 --- /dev/null +++ b/seaweed-block/core/storage/activation_recycle_v3_test.go @@ -0,0 +1,67 @@ +package storage + +import "testing" + +// Public recycle knobs retain their meaning; setup uses actual acknowledged +// writes and complete checkpoints rather than fabricating legacy fields. +func TestWALStoreV3RecycleFloorCompatibilityMatrix(t *testing.T) { + for _, tc := range []struct { + name string + floor uint64 + active, install, disable, prior bool + want uint64 + }{ + {name: "nil", want: 5}, + {name: "inactive", floor: 2, install: true, want: 5}, + {name: "active", floor: 2, active: true, install: true, want: 2}, + {name: "above", floor: 9, active: true, install: true, want: 5}, + {name: "disable", floor: 2, active: true, install: true, disable: true, want: 5}, + {name: "no_regression", floor: 1, active: true, install: true, prior: true, want: 3}, + } { + t.Run(tc.name, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + for i := 1; i <= 5; i++ { + writeSynced(t, s, uint32(i), uint32(i)) + if tc.prior && i == 3 { + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + } + } + if tc.install { + s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: tc.floor, anyActive: tc.active}) + } + if tc.disable { + s.SetRecycleFloorSource(nil) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if cp := s.CheckpointLSN(); cp != tc.want { + t.Fatalf("checkpoint=%d want %d", cp, tc.want) + } + for i := 1; i <= 5; i++ { + got, err := s.Read(uint32(i)) + if err != nil || got[0] != byte(i) { + t.Fatalf("LBA%d: %v", i, err) + } + } + }) + } +} + +func TestWALStoreV3RetentionCompatibilityMatrix(t *testing.T) { + for _, tc := range []struct{ retain, tail uint64 }{{0, 20830}, {1, 16664}, {10, 0}} { + s, _ := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(tc.retain) + for i := 1; i <= 5; i++ { + writeSynced(t, s, uint32(i), uint32(i)) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if got := s.v3.pub.current().RetainedTail; got != tc.tail { + t.Fatalf("retention%d: tail=%d want %d", tc.retain, got, tc.tail) + } + } +} diff --git a/seaweed-block/core/storage/base_install_reopen_v3_test.go b/seaweed-block/core/storage/base_install_reopen_v3_test.go new file mode 100644 index 0000000000..d2db295dc8 --- /dev/null +++ b/seaweed-block/core/storage/base_install_reopen_v3_test.go @@ -0,0 +1,122 @@ +package storage + +import ( + "bytes" + "errors" + "testing" +) + +// Plan row 11a controls (DESIGN r17.4 sections 6.6 and 8.3; owner claude03): +// a covering superseding begin after an installing reopen. + +// installThenCrashV3 begins install A at BaseLSN 10 over two acknowledged +// guest writes, applies install-lane LSNs 11, 12, 13 at LBAs 1, 2, 3 +// (one block each), optionally acknowledges them through the install log, +// crashes, damages record 12 and reopens. Recover reports the installing +// outcome. +func installThenCrashV3(t *testing.T, ackLane bool) (*WALStore, string, error) { + t.Helper() + s, path := newStoreV3(t, WModeStrict) + writeSynced(t, s, 1, 2) + h := beginV3(t, s, 10, idA) + for lsn := uint64(11); lsn <= 13; lsn++ { + if err := h.ApplyInstallEntry(uint32(lsn-10), blk(byte(lsn)), lsn); err != nil { + t.Fatal(err) + } + } + if ackLane { + if H, err := s.SyncInstallLog(idA); err != nil || H != 13 { + t.Fatalf("SyncInstallLog = (%d, %v)", H, err) + } + } + crashRecoveryHardeningStore(t, s) + damageRecord(t, path, 12) + r, err := openUnmappedWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + _, rerr := r.Recover() + return r, path, rerr +} + +func reopenServingV3(t *testing.T, s *WALStore, path string) *WALStore { + t.Helper() + crashRecoveryHardeningStore(t, s) + r := mustReopenV3(t, path) + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + return r +} + +// G3 (DESIGN 6.6): the reopen keeps LSN 11 (E is past it) and drops 12; +// record 13 survives beyond the gap. Superseding B at BaseLSN 11 writes its +// LSN 12 exactly where A's 12 was, so without the fence A's 13 would chain +// on after it and be served after B completes. The fence zeroes [E, ...) +// before B's installing publication. Mutant: a supersession without the +// fence serves A's LBA 3 bytes and fails here. +func TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix(t *testing.T) { + r, path, err := installThenCrashV3(t, false) + if !errors.Is(err, ErrBaseIncomplete) || errors.Is(err, ErrInstallSuffixDamaged) { + t.Fatalf("reopen: err = %v, want an intact ErrBaseIncomplete (W 2 <= R 11)", err) + } + hB := beginV3(t, r, 11, idB) + if err := hB.WriteBase(1, blk(0xB1)); err != nil { + t.Fatal(err) + } + if err := hB.ApplyInstallEntry(2, blk(0xB2), 12); err != nil { + t.Fatal(err) + } + if err := hB.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + q := reopenServingV3(t, r, path) + if got := readV3(t, q, 3); bytes.Equal(got, blk(13)) { + t.Fatal("A's LSN 13 resurrected after the supersession (no fence)") + } + for lba, want := range map[uint32]byte{1: 0xB1, 2: 0xB2} { + if got := readV3(t, q, lba); !bytes.Equal(got, blk(want)) { + t.Fatalf("LBA %d = %x..., want B's %x", lba, got[0], want) + } + } +} + +// A covering supersession over a DAMAGED suffix (DESIGN 8.3, r15): A's lane +// was acknowledged through 13 (W 13), record 12 is damaged, so R 11 < W* 13 +// and resume is refused. A supersession below W is refused writing +// nothing; one at BaseLSN >= W fences, publishes installing into both +// slots, completes and serves. Mutant: applying the trusted-through-W check +// to the supersession leaves the volume stuck and fails here. +func TestBaseInstallV3CoveringSupersessionOverADamagedSuffix(t *testing.T) { + r, path, err := installThenCrashV3(t, true) + if !errors.Is(err, ErrInstallSuffixDamaged) { + t.Fatalf("reopen: err = %v, want ErrInstallSuffixDamaged (R 11 < W* 13)", err) + } + a0, b0 := slotsV3(t, path) + if _, err := r.beginBaseInstallV3(12, idB); !errors.Is(err, ErrInstallSupersedeUncovered) { + t.Fatalf("supersession below W: err = %v, want ErrInstallSupersedeUncovered", err) + } + if a, b := slotsV3(t, path); a != a0 || b != b0 { + t.Fatal("a refused supersession wrote a slot") + } + hB := beginV3(t, r, 13, idB) + a, b := slotsV3(t, path) + for i, d := range []descriptorV3{a, b} { + if d.BaseState != BaseInstalling || d.BaseInstallID != idB || d.BaseLSN != 13 { + t.Fatalf("slot %d after the supersession: state %d BaseLSN %d", i, d.BaseState, d.BaseLSN) + } + } + for lba := uint32(1); lba <= 3; lba++ { + if err := hB.WriteBase(lba, blk(0xB0+byte(lba))); err != nil { + t.Fatal(err) + } + } + if err := hB.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + q := reopenServingV3(t, r, path) + for lba := uint32(1); lba <= 3; lba++ { + if got := readV3(t, q, lba); !bytes.Equal(got, blk(0xB0+byte(lba))) { + t.Fatalf("LBA %d = %x..., want B's BASE", lba, got[0]) + } + } +} diff --git a/seaweed-block/core/storage/base_install_resume_v3_test.go b/seaweed-block/core/storage/base_install_resume_v3_test.go new file mode 100644 index 0000000000..8c21abac9d --- /dev/null +++ b/seaweed-block/core/storage/base_install_resume_v3_test.go @@ -0,0 +1,255 @@ +package storage + +import ( + "bytes" + "errors" + "os" + "testing" +) + +// Plan row 11b controls (DESIGN r17.4 sections 6.6 and 8.3; owner claude03): +// the same-ID resume after an installing reopen. + +// An intact reopen (W 2 <= R 11; record 12 damaged, 13 beyond the gap) +// resumes the same ID: the recovered LSN 11 is kept and served after +// completion, the resumed session's LSN 12 lands at E, and the old 13 does +// not re-chain behind it (the fence). Mutant: a resume without the fence +// serves the old LSN 13 at LBA 3 and fails here. +func TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix(t *testing.T) { + r, path, err := installThenCrashV3(t, false) + if !errors.Is(err, ErrBaseIncomplete) || errors.Is(err, ErrInstallSuffixDamaged) { + t.Fatalf("reopen: err = %v, want an intact ErrBaseIncomplete", err) + } + h, err := r.resumeBaseInstallV3(idA) + if err != nil { + t.Fatalf("resume: %v", err) + } + if d := r.v3.pub.current(); d.BaseState != BaseInstalling || d.BaseInstallID != idA { + t.Fatalf("after resume: state %d", d.BaseState) + } + if err := h.ApplyInstallEntry(2, blk(0x99), 12); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + q := reopenServingV3(t, r, path) + if got := readV3(t, q, 3); bytes.Equal(got, blk(13)) { + t.Fatal("the dropped LSN 13 resurrected after the resume (no fence)") + } + for lba, want := range map[uint32]byte{1: 11, 2: 0x99} { + if got := readV3(t, q, lba); !bytes.Equal(got, blk(want)) { + t.Fatalf("LBA %d = %x..., want %x", lba, got[0], want) + } + } +} + +// A damaged suffix (W* 13 > R 11) refuses the resume with +// ErrInstallSuffixDamaged, writing nothing; the volume stays installing. +// Mutant: a resume that ignores the damage fails here. +func TestBaseInstallV3ResumeRefusesADamagedSuffix(t *testing.T) { + r, path, err := installThenCrashV3(t, true) + if !errors.Is(err, ErrInstallSuffixDamaged) { + t.Fatalf("reopen: err = %v, want ErrInstallSuffixDamaged", err) + } + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + a0, b0 := slotsV3(t, path) + if _, err := r.resumeBaseInstallV3(idA); !errors.Is(err, ErrInstallSuffixDamaged) { + t.Fatalf("resume over a damaged suffix: err = %v, want ErrInstallSuffixDamaged", err) + } + if a, b := slotsV3(t, path); a != a0 || b != b0 { + t.Fatal("a refused resume wrote a slot") + } + if st := r.v3.pub.current().BaseState; st != BaseInstalling { + t.Fatalf("state %d, want installing", st) + } +} + +// E below the persisted retainedHead (codex03 r17 check): the head was +// published past LSN 13 (white-box, as an earlier same-open recovery +// would), then 13 is damaged, so the reopen's E ends after 12, below the +// head. The resume is refused (E >= head is part of trusted-through-W). A +// covering supersession anchors at P = the persisted head; a crash right +// after it reopens with E = P = head and resumes. Mutants: a resume +// without the E >= head check, and a supersession anchored at P = E (its +// reopen then has E below the head and cannot resume), fail here. +func TestBaseInstallV3EBelowThePersistedHead(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + writeSynced(t, s, 1, 2) + h := beginV3(t, s, 10, idA) + for lsn := uint64(11); lsn <= 13; lsn++ { + if err := h.ApplyInstallEntry(uint32(lsn-10), blk(byte(lsn)), lsn); err != nil { + t.Fatal(err) + } + } + head := s.v3.w.logicalHeadV3() + if _, err := s.v3.pub.publish(&s.mu, nil, func(n *descriptorV3) error { n.RetainedHead = head; return nil }); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + damageRecord(t, path, 13) + r, err := openUnmappedWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + if _, err := r.Recover(); !errors.Is(err, ErrBaseIncomplete) || errors.Is(err, ErrInstallSuffixDamaged) { + t.Fatalf("reopen: err = %v, want an intact ErrBaseIncomplete (R 12 >= W* 2)", err) + } + if ro := r.v3.installReopen; ro == nil || ro.E >= head { + t.Fatalf("setup: E %v not below the persisted head %d", ro, head) + } + if _, err := r.resumeBaseInstallV3(idA); !errors.Is(err, ErrInstallSuffixDamaged) { + t.Fatalf("resume with E below the persisted head: err = %v, want ErrInstallSuffixDamaged", err) + } + beginV3(t, r, 12, idB) + if d := r.v3.pub.current(); d.BaseCursor != head || d.RetainedHead != head { + t.Fatalf("supersession anchored at %d (head %d), want P = the persisted head %d", d.BaseCursor, d.RetainedHead, head) + } + crashRecoveryHardeningStore(t, r) + q, err := openUnmappedWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + q.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { crashRecoveryHardeningStore(t, q) }) + if _, err := q.Recover(); !errors.Is(err, ErrBaseIncomplete) || errors.Is(err, ErrInstallSuffixDamaged) { + t.Fatalf("reopen after the supersession: err = %v, want an intact ErrBaseIncomplete", err) + } + if _, err := q.resumeBaseInstallV3(idB); err != nil { + t.Fatalf("resume of the covering install: %v", err) + } +} + +// codex01 row 11b P1: a same-open Recover while this open's install is live +// must not leave a resumable cut behind. The old handle stays valid +// (r17.4) and applies and acknowledges LSN 12 after the Recover; a resume +// then refuses before any I/O, so the acknowledged record's bytes are +// unchanged, and a crash and a physical reopen still resume the same ID and +// serve LSN 12. Mutant: recording the recovered bounds on a same-open +// Recover lets the resume fence from the stale E and erase the acknowledged +// LSN 12, failing here. +func TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + writeSynced(t, s, 1, 2) + h := beginV3(t, s, 10, idA) + if err := h.ApplyInstallEntry(1, blk(11), 11); err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); !errors.Is(err, ErrBaseIncomplete) { + t.Fatalf("same-open Recover while installing: err = %v, want ErrBaseIncomplete", err) + } + if err := h.ApplyInstallEntry(2, blk(12), 12); err != nil { + t.Fatalf("the live handle after a same-open Recover: %v", err) + } + if H, err := s.SyncInstallLog(idA); err != nil || H != 12 { + t.Fatalf("ack of LSN 12 = (%d, %v)", H, err) + } + off := recordOffset(t, path, 12) + before := readRawV3(t, path, off, walEntryHeaderSizeV3+v3TestBlock) + if _, err := s.resumeBaseInstallV3(idA); err == nil { + t.Fatal("a resume after a same-open Recover proceeded") + } + if got := readRawV3(t, path, off, walEntryHeaderSizeV3+v3TestBlock); !bytes.Equal(got, before) { + t.Fatal("the refused resume changed the acknowledged LSN 12 record") + } + crashRecoveryHardeningStore(t, s) + r, err := openUnmappedWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + if _, err := r.Recover(); !errors.Is(err, ErrBaseIncomplete) || errors.Is(err, ErrInstallSuffixDamaged) { + t.Fatalf("physical reopen: err = %v, want an intact ErrBaseIncomplete", err) + } + hr, err := r.resumeBaseInstallV3(idA) + if err != nil { + t.Fatalf("resume after the physical reopen: %v", err) + } + if err := hr.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + q := reopenServingV3(t, r, path) + for lba, want := range map[uint32]byte{1: 11, 2: 12} { + if got := readV3(t, q, lba); !bytes.Equal(got, blk(want)) { + t.Fatalf("LBA %d = %x..., want %x", lba, got[0], want) + } + } +} + +func readRawV3(t *testing.T, path string, off int64, n int) []byte { + t.Helper() + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + b := make([]byte, n) + if _, err := f.ReadAt(b, off); err != nil { + t.Fatal(err) + } + return b +} + +// codex01 04180c33 P1 (live continuation): BASE writes LBA 1 = B0, then the +// install lane applies and acknowledges LSN 11 at LBA 1; a same-open +// Recover clears the dirty map; the ORIGINAL handle then applies and +// acknowledges LSN 12 at LBA 2 and completes; reads in the same open must +// serve LSN 11 at LBA 1, not the older BASE bytes. Mutant: a same-open +// Recover that does not replay the live install's records serves B0. +func TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + h := beginV3(t, s, 0, idA) + if err := h.WriteBase(1, blk(0xB0)); err != nil { + t.Fatal(err) + } + if err := h.ApplyInstallEntry(1, blk(11), 1); err != nil { + t.Fatal(err) + } + if _, err := s.SyncInstallLog(idA); err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); !errors.Is(err, ErrBaseIncomplete) { + t.Fatalf("same-open Recover: err = %v", err) + } + if err := h.ApplyInstallEntry(2, blk(12), 2); err != nil { + t.Fatal(err) + } + if _, err := s.SyncInstallLog(idA); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + for lba, want := range map[uint32]byte{1: 11, 2: 12} { + if got := readV3(t, s, lba); !bytes.Equal(got, blk(want)) { + t.Fatalf("same-open read LBA %d = %x..., want %x", lba, got[0], want) + } + } +} + +// A same-open Recover that finds the live install's WAL cut short of the +// writer (a record damaged under the live install) fails closed: the store +// latches and the handle cannot append past the damage. Mutant: without +// the latch the handle appends behind the gap and fails here. +func TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + h := beginV3(t, s, 0, idA) + for lsn := uint64(1); lsn <= 2; lsn++ { + if err := h.ApplyInstallEntry(uint32(lsn), blk(byte(lsn)), lsn); err != nil { + t.Fatal(err) + } + } + if err := s.syncFile(nil, s.fd.Sync); err != nil { + t.Fatal(err) + } + damageRecord(t, path, 2) + if _, err := s.Recover(); !errors.Is(err, ErrBaseIncomplete) { + t.Fatalf("same-open Recover: err = %v", err) + } + if err := h.ApplyInstallEntry(3, blk(3), 3); err == nil { + t.Fatal("the live handle appended behind a damaged record after a same-open Recover") + } +} diff --git a/seaweed-block/core/storage/base_install_v3.go b/seaweed-block/core/storage/base_install_v3.go new file mode 100644 index 0000000000..dba6fb0aaa --- /dev/null +++ b/seaweed-block/core/storage/base_install_v3.go @@ -0,0 +1,668 @@ +package storage + +import ( + "errors" + "fmt" + "sync/atomic" +) + +// The v3 BASE install protocol, store part (format bump v3, DESIGN r17.3.1 +// sections 8.1, 8.2, 8.4, 8.5 and 8.7; plan row 9). It is dark: only tests +// reach it until the seam and the callers move onto it (row 9b) and the +// format is activated (row 12b). +// +// installMu is the topmost lock (DESIGN 4, 8.7). Begin and complete take it +// exclusive, which drains every already-admitted mutation of the old ID; a +// handle mutation takes it shared and checks, under it, that the volume is +// still installing under the handle's ID. Below it the order is the store's +// optional chunk capMu -> captureMu -> lifecycleMu -> syncMu -> s.mu -> descMu -> fileSyncMu, +// and nothing below ever waits for installMu. + +var ( + // ErrInstallBaseUncovered: a begin from none whose BaseLSN is below the + // acknowledged W or the checkpoint (DESIGN 8.1, r17.2). + ErrInstallBaseUncovered = errors.New("storage: v3 BASE install refused: BaseLSN below W or CheckpointLSN") + // ErrInstallSupersedeUncovered: a superseding begin whose BaseLSN is + // below the acknowledged W or the checkpoint (DESIGN 8.1, 8.5). + ErrInstallSupersedeUncovered = errors.New("storage: v3 superseding BASE install refused: BaseLSN below W or CheckpointLSN") + // ErrInstallSuperseded: a mutation or completion through a handle whose + // ID is no longer the installing ID (DESIGN 8.7). + ErrInstallSuperseded = errors.New("storage: v3 install handle superseded") + // ErrBaseInstallNoSpace: an install-lane append found no WAL space; the + // session fails and is retried, nothing waits (DESIGN 8.4). + ErrBaseInstallNoSpace = errors.New("storage: v3 install-lane append found no WAL space") + // ErrInstallLSNGap: a replicated or install-lane entry would leave an + // unanchored LSN gap (DESIGN 8.1, ApplyEntry gap rule). + ErrInstallLSNGap = errors.New("storage: v3 replicated entry leaves an unanchored LSN gap") +) + +// installReopenV3 is an installing reopen's recovered bounds (DESIGN 8.3). +type installReopenV3 struct { + id [16]byte + E, R uint64 + damaged bool + walSize uint64 + records []walScannedRecordV3 // the trusted write records <= R, for a resume +} + +// resumeBaseInstallV3 resumes the installing ID after a reopen (DESIGN +// 8.3, "Resume (same ID)"). Under installMu exclusive it appends nothing +// until all three hold: the trusted-through-W check (the recovered suffix +// is intact, R >= W*, and E >= the persisted retainedHead), the 6.6 fence +// of [E, floor + WALSize) with fsync, and a publication of retainedHead = E +// (G3). Otherwise it refuses with ErrInstallSuffixDamaged, writing nothing; +// the volume stays installing and not ready. The writer continues at E, +// the live position after this open's recovery; the recovered install-lane +// records are replayed so the completed image serves them. +func (s *WALStore) resumeBaseInstallV3(id [16]byte) (*installHandleV3, error) { + v := s.v3 + if v == nil { + return nil, errors.New("storage: v3 BASE resume on a non-v3 store") + } + v.installMu.Lock() + defer v.installMu.Unlock() + s.captureMu.Lock() + defer s.captureMu.Unlock() + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + v.syncMu.Lock() + defer v.syncMu.Unlock() + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return nil, errors.New("storage: BASE resume after Close") + } + if err := s.stickyIOFault(); err != nil { + return nil, err + } + d := v.pub.current() + ro := v.installReopen + if d.BaseState != BaseInstalling || d.BaseInstallID != id { + return nil, ErrInstallSuperseded + } + if ro == nil || ro.id != id || v.w == nil { + return nil, fmt.Errorf("%w: resume without this open's recovered bounds", errV3NotYet) + } + if ro.damaged || ro.E < d.RetainedHead { + return nil, fmt.Errorf("%w: R %d, E %d, persisted retainedHead %d", ErrInstallSuffixDamaged, ro.R, ro.E, d.RetainedHead) + } + v.recoverGen.Add(1) + defer v.recoverGen.Add(1) + floor, sameNonce := v.pub.reuseFloor() + if err := s.fenceV3(ro.E, floor, d.WALSize, sameNonce, d.WALOffset); err != nil { + return nil, err + } + if _, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { + if n.BaseState != BaseInstalling || n.BaseInstallID != id { + return ErrInstallSuperseded + } + n.RetainedHead = ro.E + return nil + }); err != nil { + return nil, err + } + if err := v.w.advanceHeadV3(ro.E); err != nil { + return nil, err + } + for _, r := range ro.records { + s.replayRecordV3(r, ro.walSize, d.BlockSize) + e := r.Entry + count := uint64(1) + if e.Type == walEntryWriteBatch { + count = e.BatchCount + } + for i := uint64(0); i < count; i++ { + s.recordMapWriteV3(e.LBA+i, e.LSN+i) + } + } + v.installReopen = nil + v.liveInstallID = id + v.installEpoch++ + v.preBaseHighest = 0 // every recovered record is of this install + if err := v.pub.invalidateMapProofV3(); err != nil { + return nil, err + } + return &installHandleV3{s: s, id: id, epoch: v.installEpoch}, nil +} + +// installHandleV3 is the only path for BASE extent writes and install-lane +// WAL applies on a v3 store (DESIGN 8.7). +type installHandleV3 struct { + s *WALStore + id [16]byte + epoch uint64 // the store's install epoch at this handle's begin + // completed is set once this handle's own MarkBaseComplete succeeded: + // the session's WAL lane may still be sending (the Sender sends BaseDone + // from its base lane), so install-lane applies stay admitted until the + // next begin (codex01 row 9b P1). + completed atomic.Bool +} + +// beginBaseInstallV3 is the DESIGN 8.1 begin. It refuses, before any +// descriptor or extent write, unless BaseLSN covers both the acknowledged W +// and the checkpoint. It then freezes P (the writer's head, a record +// boundary), publishes installing (BaseLSN, BaseCursor = P, the new ID) and +// republishes it into the other slot, so both fallback choices are +// installing before the first BASE mutation is admitted. +func (s *WALStore) beginBaseInstallV3(baseLSN uint64, id [16]byte) (*installHandleV3, error) { + v := s.v3 + if v == nil { + return nil, errors.New("storage: v3 BASE install on a non-v3 store") + } + if id == ([16]byte{}) { + return nil, fmt.Errorf("%w: zero BaseInstallID", errDescriptorTransition) + } + v.installMu.Lock() // exclusive: drains the old ID's admitted mutations + defer v.installMu.Unlock() + hooks := s.chunk.Load() + release, err := holdChunkBaseTransitionV3(hooks) + if err != nil { + return nil, err + } + defer release() + s.captureMu.Lock() // quiesce the install/capture boundary (8.1 step 1) + defer s.captureMu.Unlock() + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + v.syncMu.Lock() + defer v.syncMu.Unlock() + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return nil, errors.New("storage: BASE install after Close") + } + if err := s.stickyIOFault(); err != nil { + return nil, err + } + if v.w == nil { + return nil, errWALBindingV3 // a half-published reset before its Recover + } + // Attachment takes captureMu too. A layer installed after the outer + // snapshot was not drained by this transition: retry without mutation. + if s.chunk.Load() != hooks { + return nil, ErrMapCoverageStale + } + d := v.pub.current() + switch d.BaseState { + case BaseInstalled: + // installed -> installing is not an 8.5 edge: retire first. + return nil, fmt.Errorf("%w: begin while installed (retire first)", errDescriptorTransition) + case BaseInstalling: + if d.BaseInstallID == id { + return nil, fmt.Errorf("%w: begin with the installing ID", errDescriptorTransition) + } + if d.BaseInstallID != v.liveInstallID { + // A superseding begin after an installing reopen (DESIGN 8.3) + // needs that reopen's recovered bounds. + if ro := v.installReopen; ro == nil || ro.id != d.BaseInstallID { + return nil, fmt.Errorf("%w: superseding begin without the installing reopen's recovered bounds", errV3NotYet) + } + } + } + // W includes every acknowledged LSN, published or not yet (mode C). + // BaseLSN must also cover every appended LSN: an unacknowledged record + // above BaseLSN would lie behind BaseCursor, so recovery from + // max(CheckpointLSN, BaseLSN) would meet a hole where the allocator + // continued (codex01 row 9a P1-1). Such a begin is refused, writing + // nothing; the records are never rewound or dropped to make room. + w := max(d.W, v.wack.Load()) + appended := v.appended.Load() + if baseLSN < w || baseLSN < d.CheckpointLSN || baseLSN < appended { + refusal := ErrInstallBaseUncovered + if d.BaseState == BaseInstalling { + refusal = ErrInstallSupersedeUncovered + } + return nil, fmt.Errorf("%w: BaseLSN %d, W %d, CheckpointLSN %d, appended %d", + refusal, baseLSN, w, d.CheckpointLSN, appended) + } + P := v.w.logicalHeadV3() // 8.1 step 2: the serialized writer's head + if ro := v.installReopen; ro != nil && d.BaseState == BaseInstalling && ro.id == d.BaseInstallID { + // Covering supersession after an installing reopen (DESIGN 8.3, 6.6, + // G3): fence [E, floor + WALSize) and fsync before the installing + // publication, so no record of the old install beyond E re-chains; + // anchor at P = max(E, the persisted retainedHead), never lowering + // retainedHead; the writer restarts at P. Reads and the flusher see + // a recovery-like boundary. + v.recoverGen.Add(1) + defer v.recoverGen.Add(1) + floor, sameNonce := v.pub.reuseFloor() + if err := s.fenceV3(ro.E, floor, d.WALSize, sameNonce, d.WALOffset); err != nil { + return nil, err + } + P = max(ro.E, d.RetainedHead) + if err := v.w.advanceHeadV3(P); err != nil { + return nil, err + } + s.dm.clear() + } + // Step 3: installing into the fallback slot. + if _, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { + n.BaseState, n.BaseLSN, n.BaseCursor, n.BaseInstallID = BaseInstalling, baseLSN, P, id + n.RetainedHead = max(n.RetainedHead, P) + return nil + }); err != nil { + return nil, err + } + // Step 4: republish it, metadata-only, into the other slot. + if _, err := v.pub.publish(nil, nil, nil); err != nil { + return nil, err + } + v.liveInstallID = id + v.installEpoch++ + v.installReopen = nil + // A new install re-arms a lifted retirement deferral: its own image + // needs its own durable local presence before it may retire. + v.pub.retireGate.CompareAndSwap(retireAllowedV3, retireDeferredV3) + v.preBaseHighest = appended + if err := v.pub.invalidateMapProofV3(); err != nil { // an install transition (9.1) + return nil, err + } + return &installHandleV3{s: s, id: id, epoch: v.installEpoch}, nil +} + +// BeginBaseInstall is the BASE install seam (DESIGN 8.7). A v3 store runs +// the section 8.1 begin; a v2 store keeps its pre-seam behaviour behind the +// legacy handle (it had no begin step). +func (s *WALStore) BeginBaseInstall(baseLSN uint64, installID [16]byte) (InstallHandle, error) { + if s.v3 == nil { + return NewLegacyInstallHandle(s, baseLSN), nil + } + h, err := s.beginBaseInstallV3(baseLSN, installID) + if err != nil { + return nil, err + } + return h, nil +} + +// MarkBaseComplete completes this handle's install (DESIGN 8.2). +func (h *installHandleV3) MarkBaseComplete() error { + if err := h.s.markBaseCompleteV3(h.id); err != nil { + return err + } + h.completed.Store(true) + return nil +} + +var _ BaseInstallPreparer = (*WALStore)(nil) + +// admitV3 takes installMu shared and checks, under it, that the volume is +// installing under h's ID (DESIGN 8.7). The caller releases it only after +// its whole mutation. +func (h *installHandleV3) admitV3(baseWrite bool) (release func(), err error) { + v := h.s.v3 + if hook := v.testInstallBeforeAdmit; hook != nil { + hook() + } + v.installMu.RLock() + if !h.admissibleV3(baseWrite) { + v.installMu.RUnlock() + return nil, ErrInstallSuperseded + } + if hook := v.testInstallAdmitted; hook != nil { + hook() + } + return v.installMu.RUnlock, nil +} + +// admissibleV3 is the admission predicate, under installMu shared: no begin +// has run since this handle's own, and either the volume is installing +// under the handle's ID, or (install-lane applies only) the handle has +// completed and the volume is installed under its ID or retired since. +func (h *installHandleV3) admissibleV3(baseWrite bool) bool { + v := h.s.v3 + if v.installEpoch != h.epoch { + return false + } + d := v.pub.current() + if d.BaseState == BaseInstalling && d.BaseInstallID == h.id { + return true + } + if baseWrite || !h.completed.Load() { + return false + } + return (d.BaseState == BaseInstalled && d.BaseInstallID == h.id) || d.BaseState == BaseNone +} + +// WriteBase installs one BASE block into the extent (the v3 replacement of +// WriteExtentDirect). No LSN is recorded; the chunk's map coverage becomes +// UNKNOWN, and a dirty entry for the LBA no longer flushes over it. +func (h *installHandleV3) WriteBase(lba uint32, data []byte) error { + release, err := h.admitV3(true) + if err != nil { + return err + } + defer release() + s := h.s + s.captureMu.RLock() + defer s.captureMu.RUnlock() + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + if err := s.checkInstallBlockV3(lba, data); err != nil { + return err + } + // Proof invalidation and UNKNOWN precede the mutation (s.mu is released + // before the extent lock, as in the legacy direct write). + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return errors.New("storage: WriteBase after Close") + } + if p := s.v3.mapProof; p != nil { + if err := p.mutatedV3(); err != nil { + s.mu.Unlock() + return err + } + } + s.markMapUnknownV3(uint64(lba)) + s.mu.Unlock() + lock := &s.extentMu[uint64(lba)%uint64(len(s.extentMu))] + lock.Lock() + defer lock.Unlock() + _, _, previousLSN, _, hadDirty := s.dm.get(uint64(lba)) + if err := s.writeExtentUnlocked(lba, data); err != nil { + return err + } + if c := s.chunk.Load(); c != nil { + c.sink.OnExtentWrite(uint64(lba), 0) + } + if hadDirty { + s.dm.compareAndDelete(uint64(lba), previousLSN) + } + return nil +} + +// ApplyInstallEntry appends one install-lane record with the source's LSN +// (DESIGN 8.1 order and gap rules, 8.4 no space). +func (h *installHandleV3) ApplyInstallEntry(lba uint32, data []byte, lsn uint64) error { + release, err := h.admitV3(false) + if err != nil { + return err + } + defer release() + return h.s.applyEntryV3(lba, data, lsn, true) +} + +// applyEntryV3 appends one replicated entry with the source's LSN on a v3 +// store (DESIGN 8.1 and 6.7, r16/r16.1): through the v3 writer in LSN +// order; an LSN at or below the highest appended is a superseded no-op when +// the LBA already holds a higher LSN and ErrWALLSNOrder otherwise; an LSN +// that would leave an unanchored gap above max(CheckpointLSN, BaseLSN, +// highest) is refused (recovery needs a contiguous prefix). installLane is +// the install handle's apply (its admission ran already); an ordinary +// replicated apply is refused while installing (that lane is the handle's). +func (s *WALStore) applyEntryV3(lba uint32, data []byte, lsn uint64, installLane bool) error { + v := s.v3 + s.captureMu.RLock() + defer s.captureMu.RUnlock() + if err := s.checkInstallBlockV3(lba, data); err != nil { + return err + } + s.beforeChunkMutation(uint64(lba), 1) + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return errors.New("storage: ApplyEntry after Close") + } + if err := s.stickyIOFault(); err != nil { + return err + } + d := v.pub.current() + if !installLane && d.BaseState == BaseInstalling { + return fmt.Errorf("%w: an ordinary replicated apply while installing", ErrBaseInstalling) + } + highest := v.appended.Load() + if lsn <= highest { + if _, _, held, _, ok := s.dm.get(uint64(lba)); ok && held > lsn { + return nil // superseded no-op: the LBA already holds a higher LSN + } + return fmt.Errorf("%w: replicated %d at or below %d", ErrWALLSNOrder, lsn, highest) + } + if anchor := max(d.CheckpointLSN, d.BaseLSN, highest); lsn > anchor+1 { + return fmt.Errorf("%w: %d above %d", ErrInstallLSNGap, lsn, anchor) + } + dataCopy := append([]byte(nil), data...) + phys, err := s.appendWriteV3(lba, dataCopy, lsn, nil) + s.walMutation.Add(1) + if err != nil { + if installLane && errors.Is(err, errWALFull) { + return fmt.Errorf("%w: %w", ErrBaseInstallNoSpace, err) + } + return err + } + s.dm.put(uint64(lba), phys, lsn, uint32(len(dataCopy))) + s.noteChunkMutation(uint64(lba)) + if lsn >= s.nextLSN { + s.nextLSN = lsn + 1 + } + s.walHead = max(s.walHead, lsn) + if s.walTail == 0 { + s.walTail = lsn + } + return nil +} + +// markBaseCompleteV3 is DESIGN 8.2. Under installMu exclusive (no handle +// mutation is admitted) it validates the ID, then settles step 2 exactly as +// a checkpoint does: one fsync for the BASE extent bytes and the +// install-lane suffix (they share the file), the optional metadata and +// chunk barriers, and a fresh owned-map candidate that carries the UNKNOWN +// coverage the BASE writes set (codex01 row 9a P1-2). It then publishes +// installed with the same ID and that candidate in one publication +// (retainedTail = max(retainedTail, P), 8.4), stops serving the superseded +// pre-BASE records and moves the frontier to BaseLSN. A guest write that +// changes the map meanwhile makes the candidate stale and the completion +// fails. On any error the volume stays installing and the error propagates. +func (s *WALStore) markBaseCompleteV3(id [16]byte) error { + v := s.v3 + if v == nil { + return errors.New("storage: v3 BASE complete on a non-v3 store") + } + v.installMu.Lock() + defer v.installMu.Unlock() + hooks := s.chunk.Load() + release, err := holdChunkBaseTransitionV3(hooks) + if err != nil { + return err + } + defer release() + s.captureMu.Lock() + defer s.captureMu.Unlock() + if s.chunk.Load() != hooks { + return ErrMapCoverageStale + } + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + s.mu.RLock() + closed := s.closed + gen := v.recoverGen.Load() + s.mu.RUnlock() + if closed { + return errors.New("storage: MarkBaseComplete after Close") + } + d := v.pub.current() + if d.BaseState != BaseInstalling || d.BaseInstallID != id { + return ErrInstallSuperseded + } + // Step 2. + if err := s.syncFile(nil, s.fd.Sync); err != nil { + return err + } + cp := d.CheckpointLSN // the checkpoint does not move here + if s.metadata != nil { + if err := s.metadata.BeforeCheckpointAdvance(cp); err != nil { + return err + } + } + if h := s.chunk.Load(); h != nil { + if err := h.sink.BeforeCheckpointAdvance(cp); err != nil { + return err + } + } + var prepared *preparedMapPublicationV3 + var mutateMap func(*descriptorV3) error + if v.ownedMap != nil { + var err error + if prepared, err = s.prepareOwnedMapCheckpointV3(cp); err != nil { + return err + } + } else if v.mapCandidate != nil { + var err error + if mutateMap, err = v.mapCandidate(cp); err != nil { + return err + } + } + // Step 3: installed, same ID, with the candidate, under the leader role. + v.syncMu.Lock() + defer v.syncMu.Unlock() + if !v.flushLifetimeValidV3(gen) { + prepared.abandonV3() + return ErrMapCoverageStale // a recovery or reset ran meanwhile + } + installed := func(n *descriptorV3) error { + if n.BaseState != BaseInstalling || n.BaseInstallID != id { + return ErrInstallSuperseded + } + n.BaseState = BaseInstalled + n.RetainedTail = max(n.RetainedTail, d.BaseCursor) + if mutateMap != nil { + return mutateMap(n) + } + return nil + } + if prepared != nil { + _, err = v.pub.publishMapV3(&s.mu, nil, prepared, installed) + } else { + _, err = v.pub.publish(&s.mu, nil, installed) + } + if err != nil { + return err + } + s.mu.Lock() + defer s.mu.Unlock() + if err := v.pub.invalidateMapProofV3(); err != nil { + return err + } + // Records before P (LSN <= the highest appended at begin, which the + // begin bounded by BaseLSN) are behind the installed BaseCursor and + // superseded by the BASE image: recovery never scans them, so the open + // store stops serving or flushing them too. + for _, e := range s.dm.snapshot() { + if e.LSN <= v.preBaseHighest { + s.dm.compareAndDelete(e.LBA, e.LSN) + } + } + // The frontier move (8.7): the BASE image is durable through BaseLSN. + if d.BaseLSN >= s.nextLSN { + s.nextLSN = d.BaseLSN + 1 + } + s.walHead = max(s.walHead, d.BaseLSN) + if d.BaseLSN > v.appended.Load() { + v.appended.Store(d.BaseLSN) + } + return nil +} + +func (s *WALStore) checkInstallBlockV3(lba uint32, data []byte) error { + if err := s.stickyIOFault(); err != nil { + return err + } + if lba >= uint32(s.sb.VolumeSize/uint64(s.sb.BlockSize)) { + return fmt.Errorf("storage: install LBA %d out of range", lba) + } + if len(data) != int(s.sb.BlockSize) { + return fmt.Errorf("storage: install data size %d != block size %d", len(data), s.sb.BlockSize) + } + return nil +} + +// DeferBaseRetirementV3 keeps a completed BASE installed (no retirement to +// none) until AllowBaseRetirementV3. A chunk-managed provider calls it at +// open, before Recover and before any publication. Not a v3 store: no-op. +func (s *WALStore) DeferBaseRetirementV3() { + if s.v3 != nil { + s.v3.ownerAttachDurable.Store(false) + s.v3.pub.retireGate.CompareAndSwap(retireNoGateV3, retireDeferredV3) + } +} + +// CommitChunkAttachV3 is the provider's durable attach commit (row 12a +// retirement timing): under installMu exclusive it runs commit (the +// provider removes its fresh-from-HEAD marker and fsyncs the directory; it +// must not re-enter the store), and only when commit succeeds it records +// that this open's chunk attach is durable and, if the volume is installed, +// lifts the retirement deferral. On a commit error nothing changes. So a +// completed BASE never retires while the provider could still read the +// volume as fresh from HEAD. Not a v3 store: commit only. +func (s *WALStore) CommitChunkAttachV3(commit func() error) error { + v := s.v3 + if v == nil { + return commit() + } + v.installMu.Lock() + defer v.installMu.Unlock() + if err := commit(); err != nil { + return err + } + v.ownerAttachDurable.Store(true) + if v.pub.current().BaseState == BaseInstalled { + v.pub.retireGate.Store(retireAllowedV3) + } + return nil +} + +// OwnerChunkAttachDurableV3 reports whether this open's chunk attach was +// durably committed (CommitChunkAttachV3); it resets at every open. +func (s *WALStore) OwnerChunkAttachDurableV3() bool { + return s.v3 != nil && s.v3.ownerAttachDurable.Load() +} + +// AllowBaseRetirementV3 lifts the deferral once the chunk layer has durably +// recorded local presence for the installed image; retirement then happens +// on the next ordinary publication whose 8.4 conditions hold. +func (s *WALStore) AllowBaseRetirementV3() { + if s.v3 != nil { + s.v3.pub.retireGate.Store(retireAllowedV3) + } +} + +// markMapUnknownV3: an effective direct extent/BASE mutation makes its +// chunk's coverage UNKNOWN (DESIGN 9, r16.1). Caller holds WALStore.mu. +func (s *WALStore) markMapUnknownV3(lba uint64) { + v := s.v3 + if v.ownedMap == nil { + return + } + e := &v.mapEntries[lba/v.ownedMap.chunkBlocks] + e.Unknown = true + // A BASE byte has no WAL record: inherit its image frontier, not an + // unrelated later write. Keep UNKNOWN conservative as before. + birth := s.nextLSN - 1 + if d := v.pub.current(); d.BaseState == BaseInstalling { + birth = d.BaseLSN + } + e.LSN = max(e.LSN, birth) +} + +// InstalledBaseLSN reports a completed local BASE obligation, not a normal +// checkpoint. A caller must still revalidate under its attachment admission. +func (s *WALStore) InstalledBaseLSN() (uint64, bool) { + if s.v3 == nil { + return 0, false + } + d := s.v3.pub.current() + return d.BaseLSN, d.BaseState == BaseInstalled +} + +// Caller holds installMu exclusively and no lower lock. The returned release +// must be deferred before acquiring captureMu, so it runs after lower unlocks. +func holdChunkBaseTransitionV3(h *chunkHooks) (func(), error) { + if h == nil { + return func() {}, nil + } + if h.baseTransitionV3 == nil { + return nil, fmt.Errorf("%w: BASE transition with an unsupported attached chunk layer", errV3NotYet) + } + return h.baseTransitionV3() +} diff --git a/seaweed-block/core/storage/base_install_v3_test.go b/seaweed-block/core/storage/base_install_v3_test.go new file mode 100644 index 0000000000..5e1c9311a5 --- /dev/null +++ b/seaweed-block/core/storage/base_install_v3_test.go @@ -0,0 +1,683 @@ +package storage + +import ( + "bytes" + "errors" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" +) + +// Plan row 9a controls (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7): +// the v3 BASE begin, the install handle, complete, no abort and retirement. +// Owner: claude03. Each control names the mutant it qualifies. + +var ( + idA = [16]byte{0xA} + idB = [16]byte{0xB} +) + +func beginV3(t *testing.T, s *WALStore, baseLSN uint64, id [16]byte) *installHandleV3 { + t.Helper() + h, err := s.beginBaseInstallV3(baseLSN, id) + if err != nil { + t.Fatalf("begin BaseLSN %d: %v", baseLSN, err) + } + return h +} + +// Begin publishes installing (BaseLSN, BaseCursor = the writer head, the +// ID) into BOTH slots before it returns the handle (8.1 steps 3 and 4). +// Mutant: a one-slot begin (no step 4) fails here. +func TestBaseInstallV3BeginPublishesInstallingIntoBothSlots(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 3) + P := s.v3.w.logicalHeadV3() + beginV3(t, s, 3, idA) + a, b := slotsV3(t, path) + for i, d := range []descriptorV3{a, b} { + if d.BaseState != BaseInstalling || d.BaseInstallID != idA || d.BaseLSN != 3 || d.BaseCursor != P { + t.Fatalf("slot %d: state %d id %x BaseLSN %d BaseCursor %d, want installing %x 3 %d", + i, d.BaseState, d.BaseInstallID[0], d.BaseLSN, d.BaseCursor, idA[0], P) + } + } +} + +// The coverage rule (8.1): a begin from none or a superseding begin with +// BaseLSN below the acknowledged W is refused before any descriptor write, +// with the begin-specific error. Mutant: dropping the W check fails here. +func TestBaseInstallV3BeginRefusesBelowW(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 3) + writes := countSlotWritesV3(s) + a0, b0 := slotsV3(t, path) + if _, err := s.beginBaseInstallV3(2, idA); !errors.Is(err, ErrInstallBaseUncovered) { + t.Fatalf("begin from none below W: err = %v, want ErrInstallBaseUncovered", err) + } + if a, b := slotsV3(t, path); writes.Load() != 0 || a != a0 || b != b0 { + t.Fatal("a refused begin wrote a descriptor slot") + } + s.v3.testBeforeSlotWrite = nil + beginV3(t, s, 3, idA) + writes = countSlotWritesV3(s) + a0, b0 = slotsV3(t, path) + if _, err := s.beginBaseInstallV3(2, idB); !errors.Is(err, ErrInstallSupersedeUncovered) { + t.Fatalf("superseding begin below W: err = %v, want ErrInstallSupersedeUncovered", err) + } + if a, b := slotsV3(t, path); writes.Load() != 0 || a != a0 || b != b0 { + t.Fatal("a refused superseding begin wrote a descriptor slot") + } +} + +// Mode C: W includes an acknowledged LSN the lagged slot W does not show +// yet. A begin at the published W but below the acknowledged one is +// refused. Mutant: checking only the published W fails here. +func TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW(t *testing.T) { + s, _ := newStoreV3(t, WModeLagged) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 3) + d := s.v3.pub.current() + if ack := s.v3.wack.Load(); d.W >= ack { + t.Fatalf("setup: published W %d is not below the acknowledged %d", d.W, ack) + } + if _, err := s.beginBaseInstallV3(d.W, idA); !errors.Is(err, ErrInstallBaseUncovered) { + t.Fatalf("begin at the lagged W %d: err = %v, want ErrInstallBaseUncovered", d.W, err) + } +} + +func TestBaseInstallV3BeginRefusals(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + if _, err := s.beginBaseInstallV3(0, [16]byte{}); !errors.Is(err, errDescriptorTransition) { + t.Fatalf("zero ID: err = %v", err) + } + beginV3(t, s, 0, idA) + if _, err := s.beginBaseInstallV3(0, idA); !errors.Is(err, errDescriptorTransition) { + t.Fatalf("begin with the installing ID: err = %v", err) + } +} + +// Complete (8.2): a stale ID is refused with no slot write; the real ID +// makes BASE bytes and the install-lane suffix durable, publishes installed +// with retainedTail >= BaseCursor, and moves the frontier to BaseLSN. A +// crash and reopen serve the installed image and the suffix. The pre-BASE +// guest records (LSN 1, 2 at LBA 1, 2, behind BaseCursor) are superseded +// by the BASE image: the open store and the recovered one both stop +// serving them (the BASE here does not ship LBA 1 or 2). Mutant: keeping +// the pre-BASE dirty entries at complete serves LBA 1 before the crash and +// not after it. +func TestBaseInstallV3CompleteServesTheImageAcrossACrash(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + writeSynced(t, s, 1, 2) + h := beginV3(t, s, 10, idA) + if err := h.WriteBase(5, blk(0x55)); err != nil { + t.Fatal(err) + } + if err := h.ApplyInstallEntry(6, blk(0x66), 11); err != nil { + t.Fatal(err) + } + writes := countSlotWritesV3(s) + if err := s.markBaseCompleteV3(idB); !errors.Is(err, ErrInstallSuperseded) || writes.Load() != 0 { + t.Fatalf("stale-ID complete: err = %v, slot writes %d", err, writes.Load()) + } + s.v3.testBeforeSlotWrite = nil + if err := s.markBaseCompleteV3(idA); err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + if d.BaseState != BaseInstalled || d.BaseInstallID != idA || d.RetainedTail < d.BaseCursor { + t.Fatalf("after complete: state %d id %x tail %d cursor %d", d.BaseState, d.BaseInstallID[0], d.RetainedTail, d.BaseCursor) + } + if err := h.WriteBase(5, blk(0x77)); !errors.Is(err, ErrInstallSuperseded) { + t.Fatalf("WriteBase after complete: err = %v, want ErrInstallSuperseded", err) + } + served := map[uint32]byte{1: 0, 2: 0, 5: 0x55, 6: 0x66} + for lba, want := range served { + if got := readV3(t, s, lba); !bytes.Equal(got, blk(want)) { + t.Fatalf("after complete LBA %d = %x..., want %x", lba, got[0], want) + } + } + lsn, err := s.Write(7, blk(0x70)) + if err != nil || lsn != 12 { + t.Fatalf("first guest write after complete: LSN %d err %v, want 12", lsn, err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + r := mustReopenV3(t, path) + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + served[7] = 0x70 + for lba, want := range served { + if got := readV3(t, r, lba); !bytes.Equal(got, blk(want)) { + t.Fatalf("after reopen LBA %d = %x..., want %x", lba, got[0], want) + } + } +} + +// No abort (r17, 8.5): installing -> none is refused at the publisher with +// no slot write. Mutant: allowing the edge fails here. +func TestBaseInstallV3InstallingToNoneIsRefused(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + beginV3(t, s, 0, idA) + writes := countSlotWritesV3(s) + a0, b0 := slotsV3(t, path) + _, err := s.v3.pub.publish(&s.mu, nil, func(n *descriptorV3) error { + n.BaseState, n.BaseLSN, n.BaseCursor, n.BaseInstallID = BaseNone, 0, 0, [16]byte{} + return nil + }) + if !errors.Is(err, errDescriptorTransition) { + t.Fatalf("installing -> none: err = %v, want errDescriptorTransition", err) + } + if a, b := slotsV3(t, path); writes.Load() != 0 || a != a0 || b != b0 { + t.Fatal("a refused abort wrote a descriptor slot") + } +} + +// Retirement (8.4, 8.5): installed stays installed through publications +// until the checkpoint covers BaseLSN; then a normal publication zeroes the +// BASE fields. Mutant: retiring without the checkpoint check fails here. +func TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN(t *testing.T) { + s, _, _ := checkpointedStoreV3(t, 2) + h := beginV3(t, s, 4, idA) + if err := h.WriteBase(3, blk(3)); err != nil { + t.Fatal(err) + } + if err := h.ApplyInstallEntry(5, blk(5), 5); err != nil { + t.Fatal(err) + } + if err := s.markBaseCompleteV3(idA); err != nil { + t.Fatal(err) + } + if _, err := s.v3.pub.publish(&s.mu, nil, nil); err != nil { + t.Fatal(err) + } + if d := s.v3.pub.current(); d.BaseState != BaseInstalled { + t.Fatalf("retired with checkpoint %d below BaseLSN %d", d.CheckpointLSN, d.BaseLSN) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + if _, err := s.v3.pub.publish(&s.mu, nil, nil); err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + if d.CheckpointLSN < 4 || d.BaseState != BaseNone || d.BaseCursor != 0 || d.BaseInstallID != ([16]byte{}) { + t.Fatalf("checkpoint %d: state %d cursor %d id %x, want retired", d.CheckpointLSN, d.BaseState, d.BaseCursor, d.BaseInstallID[0]) + } + readAllV3(t, s, 1, 3) + readAllV3(t, s, 5, 5) +} + +// The order and gap rules (8.1, 6.7) for the install lane. +func TestBaseInstallV3ApplyInstallEntryOrderAndGap(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + h := beginV3(t, s, 4, idA) + if err := h.ApplyInstallEntry(1, blk(1), 7); !errors.Is(err, ErrInstallLSNGap) { + t.Fatalf("gap above BaseLSN 4: err = %v, want ErrInstallLSNGap", err) + } + if err := h.ApplyInstallEntry(1, blk(1), 5); err != nil { + t.Fatal(err) + } + if err := h.ApplyInstallEntry(2, blk(2), 5); !errors.Is(err, ErrWALLSNOrder) { + t.Fatalf("repeated LSN on another LBA: err = %v, want ErrWALLSNOrder", err) + } + if err := h.ApplyInstallEntry(1, blk(9), 6); err != nil { + t.Fatal(err) + } + if err := h.ApplyInstallEntry(1, blk(8), 5); err != nil { + t.Fatalf("a superseded lower LSN for an LBA that holds 6: err = %v, want a no-op", err) + } + if got := readV3(t, s, 1); !bytes.Equal(got, blk(9)) { + t.Fatalf("LBA 1 = %x..., want the LSN 6 bytes", got[0]) + } +} + +// holdOnce returns a hook that parks the first call until release runs, +// and reports through parked when it has parked. The test's cleanup always +// releases, so a failing test never leaves a parked goroutine behind +// (codex01 row 9a P2). +func holdOnce(t *testing.T) (hook func(), parked chan struct{}, release func()) { + parked = make(chan struct{}) + gate := make(chan struct{}) + var once sync.Once + release = func() { once.Do(func() { close(gate) }) } + t.Cleanup(release) + var armed atomic.Bool + armed.Store(true) + return func() { + if armed.CompareAndSwap(true, false) { + close(parked) + <-gate + } + }, parked, release +} + +// Drain setup, held inside the mutation (plan row 9, codex01 r12 P2): +// A's admitted write is held; B's begin waits for it; B then writes the +// target block and stays installing; a further A attempt is refused with +// B's block byte-identical. Mutants: begin taking installMu shared (A's +// held write lands over B's) and no ID check (the further A write lands). +func TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + hA := beginV3(t, s, 0, idA) + hook, parked, release := holdOnce(t) + s.v3.testInstallAdmitted = hook + aDone := make(chan error, 1) + go func() { aDone <- hA.WriteBase(7, blk(0xAA)) }() + <-parked + var hB *installHandleV3 + bDone := make(chan error, 1) + go func() { + var err error + if hB, err = s.beginBaseInstallV3(0, idB); err == nil { + err = hB.WriteBase(7, blk(0xBB)) + } + bDone <- err + }() + // B must not get past its begin while A's write is held; give a wrong + // (shared) begin time to finish first. The oracle is the bytes below. + select { + case err := <-bDone: + bDone <- err + case <-time.After(300 * time.Millisecond): + } + release() + if err := <-aDone; err != nil { + t.Fatalf("A's admitted write: %v", err) + } + if err := <-bDone; err != nil { + t.Fatalf("B: %v", err) + } + if got := readV3(t, s, 7); !bytes.Equal(got, blk(0xBB)) { + t.Fatalf("LBA 7 = %x..., want B's bytes", got[0]) + } + if err := hA.WriteBase(7, blk(0xAA)); !errors.Is(err, ErrInstallSuperseded) { + t.Fatalf("further A write: err = %v, want ErrInstallSuperseded", err) + } + if err := hA.ApplyInstallEntry(7, blk(0xAA), 1); !errors.Is(err, ErrInstallSuperseded) { + t.Fatalf("further A apply: err = %v, want ErrInstallSuperseded", err) + } + if got := readV3(t, s, 7); !bytes.Equal(got, blk(0xBB)) { + t.Fatalf("LBA 7 = %x... after the stale attempts, want B's bytes", got[0]) + } + if d := s.v3.pub.current(); d.BaseState != BaseInstalling || d.BaseInstallID != idB { + t.Fatalf("state %d id %x, want installing under B", d.BaseState, d.BaseInstallID[0]) + } +} + +// Premature-check setup, parked before admission (codex03 r11, plan row +// 9): A parks before acquiring installMu; B supersedes, writes the target +// block and stays installing; A resumes and is refused under the lock. +// Mutants: checking the ID before acquiring installMu, and no ID check. +func TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession(t *testing.T) { + for _, op := range []string{"WriteBase", "ApplyInstallEntry"} { + t.Run(op, func(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + hA := beginV3(t, s, 0, idA) + hook, parked, release := holdOnce(t) + s.v3.testInstallBeforeAdmit = hook + aDone := make(chan error, 1) + go func() { + if op == "WriteBase" { + aDone <- hA.WriteBase(7, blk(0xAA)) + } else { + aDone <- hA.ApplyInstallEntry(7, blk(0xAA), 1) + } + }() + <-parked + hB := beginV3(t, s, 0, idB) + if err := hB.WriteBase(7, blk(0xBB)); err != nil { + t.Fatal(err) + } + release() + if err := <-aDone; !errors.Is(err, ErrInstallSuperseded) { + t.Fatalf("parked A %s: err = %v, want ErrInstallSuperseded", op, err) + } + if got := readV3(t, s, 7); !bytes.Equal(got, blk(0xBB)) { + t.Fatalf("LBA 7 = %x..., want B's bytes", got[0]) + } + if d := s.v3.pub.current(); d.BaseState != BaseInstalling || d.BaseInstallID != idB { + t.Fatalf("state %d id %x, want installing under B", d.BaseState, d.BaseInstallID[0]) + } + }) + } +} + +// codex01 row 9a P1-1: W 1 with unacknowledged LSNs 2 and 3 appended. A +// begin at BaseLSN 1 would put 2 and 3 behind BaseCursor while the +// allocator continues at 4: after complete, an acknowledged write 4 and a +// reopen from F = 1 meet the hole (strict: R 1 < W 4; lagged: 4 dropped). +// The begin is refused, writing nothing; a begin covering the appended +// LSNs installs, and the acknowledged write after it survives a crash. +// Mutant: bounding BaseLSN by W and the checkpoint only fails here. +func TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + writeSynced(t, s, 1, 1) + for lba := uint32(2); lba <= 3; lba++ { + if _, err := s.Write(lba, blk(byte(lba))); err != nil { + t.Fatal(err) + } + } + if w, a := s.v3.wack.Load(), s.v3.appended.Load(); w != 1 || a != 3 { + t.Fatalf("setup: acknowledged %d appended %d, want 1 and 3", w, a) + } + writes := countSlotWritesV3(s) + if _, err := s.beginBaseInstallV3(1, idA); !errors.Is(err, ErrInstallBaseUncovered) { + t.Fatalf("begin at BaseLSN 1 below appended 3: err = %v, want ErrInstallBaseUncovered", err) + } + if writes.Load() != 0 { + t.Fatal("a refused begin wrote a descriptor slot") + } + s.v3.testBeforeSlotWrite = nil + h := beginV3(t, s, 3, idA) + for lba := uint32(1); lba <= 3; lba++ { + if err := h.WriteBase(lba, blk(0x10+byte(lba))); err != nil { + t.Fatal(err) + } + } + if err := s.markBaseCompleteV3(idA); err != nil { + t.Fatal(err) + } + lsn, err := s.Write(4, blk(4)) + if err != nil || lsn != 4 { + t.Fatalf("write after complete: LSN %d err %v, want 4", lsn, err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + r := mustReopenV3(t, path) + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + for lba, want := range map[uint32]byte{1: 0x11, 2: 0x12, 3: 0x13, 4: 4} { + if got := readV3(t, r, lba); !bytes.Equal(got, blk(want)) { + t.Fatalf("after reopen LBA %d = %x..., want %x", lba, got[0], want) + } + } +} + +// codex01 row 9a P1-2: a BASE write makes its chunk's coverage UNKNOWN only +// in memory. Complete settles the map like a checkpoint: the installed +// publication carries a fresh root with that UNKNOWN, so a crash and a +// mapped reopen keep it. Setup: chunk 2 is clean in the durable root (as a +// capture would leave it; set white-box, then checkpointed). Mutant: a +// complete that publishes installed without the map candidate reopens with +// chunk 2 clean and fails here. +func TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites(t *testing.T) { + path := filepath.Join(t.TempDir(), "mapped.v3") + s, err := createMappedWALStoreV3ForTest(path, 64, v3TestBlock, v3TestWAL, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + writeSynced(t, s, 1, 1) + s.mu.Lock() + s.v3.mapEntries[2] = chunkLSNEntryV3{} + s.mu.Unlock() + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + if e := s.v3.pub.mapCurrent.entries[2]; e.Unknown { + t.Fatal("setup: chunk 2 is not clean in the durable root") + } + h := beginV3(t, s, 1, idA) + if err := h.WriteBase(9, blk(9)); err != nil { // LBA 9 is in chunk 2 + t.Fatal(err) + } + if err := s.markBaseCompleteV3(idA); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + if st := r.v3.pub.current().BaseState; st != BaseInstalled { + t.Fatalf("reopen state %d, want installed", st) + } + if e := r.v3.pub.mapCurrent.entries[2]; !e.Unknown { + t.Fatal("chunk 2 reopened clean: the BASE write's UNKNOWN was lost at complete") + } +} + +// An attached layer without the transition protocol still refuses, writing +// nothing. Actual supported layers are covered by the chunk/provider controls. +func TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + cfg := ctConfig(1) + cfg.Bitmap = nil + cfg.BarrierBound = 1 + mustAttach(t, s, newFakeChunkRemote(), cfg) + hooks := *s.chunk.Load() + hooks.baseTransitionV3 = nil + s.chunk.Store(&hooks) + a0, b0 := slotsV3(t, path) + if _, err := s.beginBaseInstallV3(0, idA); !errors.Is(err, errV3NotYet) { + t.Fatalf("begin with a chunk layer attached: err = %v, want errV3NotYet", err) + } + if a, b := slotsV3(t, path); a != a0 || b != b0 { + t.Fatal("a refused begin wrote a descriptor slot") + } +} + +// codex01 row 9b P1, store part: a completed handle keeps admitting +// install-lane applies (the session's WAL lane outlives its BaseDone) while +// installed and after its retirement, until the next begin; a BASE write +// after complete is refused; once a later begin has run (here after the +// retirement, so the ID check alone cannot tell), the old handle is +// refused with ErrInstallSuperseded. Mutants: admitting only while +// installing (the apply after complete fails) and dropping the epoch check +// (the stale apply lands in the new install). +func TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin(t *testing.T) { + s, _, _ := checkpointedStoreV3(t, 2) + h := beginV3(t, s, 4, idA) + if err := h.WriteBase(3, blk(3)); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + if err := h.ApplyInstallEntry(5, blk(5), 5); err != nil { + t.Fatalf("apply after complete (installed): %v", err) + } + if err := h.WriteBase(6, blk(6)); !errors.Is(err, ErrInstallSuperseded) { + t.Fatalf("WriteBase after complete: err = %v, want ErrInstallSuperseded", err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + if _, err := s.v3.pub.publish(&s.mu, nil, nil); err != nil { + t.Fatal(err) + } + if st := s.v3.pub.current().BaseState; st != BaseNone { + t.Fatalf("setup: state %d, want retired", st) + } + if err := h.ApplyInstallEntry(6, blk(6), 6); err != nil { + t.Fatalf("apply after retirement: %v", err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + hB := beginV3(t, s, 6, idB) + if err := h.ApplyInstallEntry(7, blk(0xAA), 7); !errors.Is(err, ErrInstallSuperseded) { + t.Fatalf("old handle after a later begin: err = %v, want ErrInstallSuperseded", err) + } + for lba := uint32(5); lba <= 6; lba++ { // B's BASE image at 6 + if err := hB.WriteBase(lba, blk(byte(lba))); err != nil { + t.Fatal(err) + } + } + if err := hB.ApplyInstallEntry(7, blk(7), 7); err != nil { + t.Fatal(err) + } + // B completes and retires too: the state is none again, which the old + // completed handle would accept without the epoch check. + if err := hB.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + if _, err := s.v3.pub.publish(&s.mu, nil, nil); err != nil { + t.Fatal(err) + } + if st := s.v3.pub.current().BaseState; st != BaseNone { + t.Fatalf("setup: state %d after B, want retired", st) + } + if err := h.ApplyInstallEntry(8, blk(0xAA), 8); !errors.Is(err, ErrInstallSuperseded) { + t.Fatalf("old handle after a later install retired: err = %v, want ErrInstallSuperseded", err) + } + readAllV3(t, s, 5, 7) +} + +// The retirement gate (row 12a retired-BASE ruling): a deferred store keeps +// a completed BASE installed through publications whose 8.4 conditions hold, +// and retires on the first publication after AllowBaseRetirementV3. A store +// that never set the gate retires as before (TestBaseInstallV3Retires...). +// Mutant: a publisher that ignores the gate retires early and fails here. +func TestBaseInstallV3RetirementWaitsForTheGate(t *testing.T) { + s, _, _ := checkpointedStoreV3(t, 2) + s.DeferBaseRetirementV3() + h := beginV3(t, s, 4, idA) + if err := h.WriteBase(3, blk(3)); err != nil { + t.Fatal(err) + } + if err := h.ApplyInstallEntry(5, blk(5), 5); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if _, err := s.v3.pub.publish(&s.mu, nil, nil); err != nil { + t.Fatal(err) + } + } + if d := s.v3.pub.current(); d.CheckpointLSN < 4 || d.BaseState != BaseInstalled { + t.Fatalf("deferred: checkpoint %d state %d, want installed with the 8.4 conditions holding", d.CheckpointLSN, d.BaseState) + } + s.AllowBaseRetirementV3() + if _, err := s.v3.pub.publish(&s.mu, nil, nil); err != nil { + t.Fatal(err) + } + if d := s.v3.pub.current(); d.BaseState != BaseNone { + t.Fatalf("after Allow: state %d, want retired", d.BaseState) + } + // A second install in the same open is deferred again: the earlier + // Allow covered the first image only. Mutant: a begin that does not + // re-arm the gate retires the second install early and fails here. + h2 := beginV3(t, s, 6, idB) + if err := h2.WriteBase(3, blk(0x33)); err != nil { + t.Fatal(err) + } + if err := h2.ApplyInstallEntry(5, blk(0x55), 7); err != nil { + t.Fatal(err) + } + if err := h2.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if _, err := s.v3.pub.publish(&s.mu, nil, nil); err != nil { + t.Fatal(err) + } + } + if d := s.v3.pub.current(); d.CheckpointLSN < 6 || d.BaseState != BaseInstalled || d.BaseInstallID != idB { + t.Fatalf("second install: checkpoint %d state %d, want installed under B (re-armed)", d.CheckpointLSN, d.BaseState) + } +} + +// CommitChunkAttachV3 (row 12a retirement timing): the provider's commit +// runs under installMu exclusive; a failing commit changes nothing (no +// durable flag, the deferral holds, the volume stays installed); a +// successful one records the durable attach and lifts the deferral of an +// installed volume, which then retires on the next publication; Defer +// resets the flag at the next open. Mutants: lifting on a failed commit, +// not recording the flag, running the commit outside installMu. +func TestBaseInstallV3CommitChunkAttach(t *testing.T) { + s, _, _ := checkpointedStoreV3(t, 2) + s.DeferBaseRetirementV3() + h := beginV3(t, s, 4, idA) + if err := h.WriteBase(3, blk(3)); err != nil { + t.Fatal(err) + } + if err := h.ApplyInstallEntry(5, blk(5), 5); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + exclusive := false + err := s.CommitChunkAttachV3(func() error { + if s.v3.installMu.TryRLock() { + s.v3.installMu.RUnlock() + } else { + exclusive = true + } + return errors.New("injected marker fsync failure") + }) + if err == nil || !exclusive { + t.Fatalf("failing commit: err %v, ran under installMu exclusive %v", err, exclusive) + } + if s.OwnerChunkAttachDurableV3() { + t.Fatal("a failed commit recorded a durable attach") + } + if _, err := s.v3.pub.publish(&s.mu, nil, nil); err != nil { + t.Fatal(err) + } + if st := s.v3.pub.current().BaseState; st != BaseInstalled { + t.Fatalf("state %d after a failed commit, want installed", st) + } + if err := s.CommitChunkAttachV3(func() error { return nil }); err != nil { + t.Fatal(err) + } + if !s.OwnerChunkAttachDurableV3() { + t.Fatal("a successful commit did not record the durable attach") + } + if _, err := s.v3.pub.publish(&s.mu, nil, nil); err != nil { + t.Fatal(err) + } + if st := s.v3.pub.current().BaseState; st != BaseNone { + t.Fatalf("state %d after the commit, want retired", st) + } + s.DeferBaseRetirementV3() + if s.OwnerChunkAttachDurableV3() { + t.Fatal("Defer (the next open) did not reset the durable attach flag") + } +} diff --git a/seaweed-block/core/storage/block_metadata.go b/seaweed-block/core/storage/block_metadata.go index 29e8092aac..120ae6d4a6 100644 --- a/seaweed-block/core/storage/block_metadata.go +++ b/seaweed-block/core/storage/block_metadata.go @@ -45,14 +45,24 @@ type BlockMetadataBinding struct { // or recovery begins. On create it declares a layout without writing bytes; // on open it must accept exactly the stored version. No registry or hook chain. type BlockMetadataFactory func(BlockMetadataFile, BlockMetadataLayout) (BlockMetadataBinding, error) -type WALStoreOptions struct{ MetadataFactory BlockMetadataFactory } +type WALStoreOptions struct { + MetadataFactory BlockMetadataFactory + // ChunkBlocks fixes the owned map geometry at create. Zero uses 1024. + ChunkBlocks uint32 + // WMode is C (lagged) by default; A (strict) is an opt-in per volume. + WMode WMode +} func bindBlockMetadata(f *os.File, sb *superblock, opts WALStoreOptions, creating, readonly bool) (BlockMetadata, int64, error) { if sb.WALOffset > math.MaxInt64 || sb.WALSize > math.MaxInt64-sb.WALOffset || sb.VolumeSize > math.MaxInt64-sb.WALOffset-sb.WALSize { return nil, 0, fmt.Errorf("storage: extent size overflow") } base := sb.WALOffset + sb.WALSize + sb.VolumeSize - binding := BlockMetadataBinding{ImplVersion: WALStoreImplVersion} + nativeVersion := uint32(1) // frozen v2 metadata seam + if sb.Version == superblockVersionV3 { + nativeVersion = walStoreImplVersion3 + } + binding := BlockMetadataBinding{ImplVersion: nativeVersion} if opts.MetadataFactory != nil { var err error binding, err = opts.MetadataFactory(f, BlockMetadataLayout{ImplVersion: sb.ImplVersion, BlockSize: sb.BlockSize, NumBlocks: uint32(sb.VolumeSize / uint64(sb.BlockSize)), ExtentEnd: int64(base), Creating: creating, ReadOnly: readonly}) @@ -60,7 +70,7 @@ func bindBlockMetadata(f *os.File, sb *superblock, opts WALStoreOptions, creatin return nil, 0, fmt.Errorf("storage: bind block metadata: %w", err) } } - if binding.ImplVersion == 0 || (!creating && binding.ImplVersion != sb.ImplVersion) || (binding.ImplVersion != WALStoreImplVersion && binding.Hook == nil) { + if binding.ImplVersion == 0 || (!creating && binding.ImplVersion != sb.ImplVersion) || (binding.ImplVersion != nativeVersion && binding.Hook == nil) { return nil, 0, fmt.Errorf("storage: unsupported walstore implementation version %d without accepting metadata factory", sb.ImplVersion) } if binding.AppendedBytes > math.MaxInt64-base { diff --git a/seaweed-block/core/storage/block_metadata_test.go b/seaweed-block/core/storage/block_metadata_test.go index 9aab488a5a..6324d9beb7 100644 --- a/seaweed-block/core/storage/block_metadata_test.go +++ b/seaweed-block/core/storage/block_metadata_test.go @@ -2,7 +2,6 @@ package storage import ( "bytes" - "encoding/binary" "errors" "os" "path/filepath" @@ -83,11 +82,16 @@ func TestBlockMetadata_BarrierErrorBlocksCheckpointAndDirectFrontier(t *testing. h := &recordingMetadata{barrierErr: sentinel} s, _ := metadataStore(t, h) cp, tail := s.CheckpointLSN(), walLogicalTail(s) + var install InstallHandle if direct { - if err := s.WriteExtentDirect(3, makeBlock(4096, 0x32)); err != nil { + var err error + install, err = s.BeginBaseInstall(7, [16]byte{1}) + if err != nil { + t.Fatal(err) + } + if err := install.WriteBase(3, makeBlock(4096, 0x32)); err != nil { t.Fatal(err) } - s.AdvanceFrontier(7) } else { if _, err := s.Write(3, makeBlock(4096, 0x32)); err != nil { t.Fatal(err) @@ -98,7 +102,7 @@ func TestBlockMetadata_BarrierErrorBlocksCheckpointAndDirectFrontier(t *testing. } var err error if direct { - _, err = s.Sync() + err = install.MarkBaseComplete() } else { err = s.flusher.flushOnce() } @@ -112,12 +116,19 @@ func TestBlockMetadata_WriteAndVerifyRouting(t *testing.T) { h := &recordingMetadata{} s, p := metadataStore(t, h) sentinel := errors.New("metadata refusal") + install, err := s.BeginBaseInstall(0, [16]byte{1}) + if err != nil { + t.Fatal(err) + } h.writeErr = sentinel - if err := s.WriteExtentDirect(3, makeBlock(4096, 0x33)); !errors.Is(err, sentinel) { + if err := install.WriteBase(3, makeBlock(4096, 0x33)); !errors.Is(err, sentinel) { t.Fatalf("write hook bypassed: %v", err) } h.writeErr = nil - if err := s.WriteExtentDirect(3, makeBlock(4096, 0x33)); err != nil { + if err := install.WriteBase(3, makeBlock(4096, 0x33)); err != nil { + t.Fatal(err) + } + if err := install.MarkBaseComplete(); err != nil { t.Fatal(err) } h.readErr = sentinel @@ -182,11 +193,12 @@ func TestBlockMetadata_SeedFailureRetry(t *testing.T) { sentinel := errors.New("deferred metadata not durable") hook := &recordingMetadata{barrierErr: sentinel} s, path := metadataStore(t, hook) - if err := s.WriteExtentDirect(3, makeBlock(4096, 0x45)); err != nil { + // Quiescent pre-seed image bytes, not an admitted direct-BASE mutation. + if err := s.writeExtentUnlocked(3, makeBlock(4096, 0x45)); err != nil { t.Fatal(err) } - persist := s.syncDirectFrontierMetadata - s.syncDirectFrontierMetadata = func(data []byte) error { + persist := s.v3.pub.io.writeSlot + s.v3.pub.io.writeSlot = func(off int64, data []byte) error { if hook.barriers != 2 { t.Errorf("seed persistence before retry barrier: %d", hook.barriers) } @@ -194,7 +206,7 @@ func TestBlockMetadata_SeedFailureRetry(t *testing.T) { if _, err := s.fd.ReadAt(marker, hook.end); err != nil || marker[0] != 1 { t.Errorf("seed persisted before deferred marker: %v %v", marker, err) } - return persist(data) + return persist(off, data) } if err := s.SeedChunkFrontier(7); !errors.Is(err, sentinel) { t.Fatalf("seed bypassed deferred metadata error: %v", err) @@ -205,11 +217,7 @@ func TestBlockMetadata_SeedFailureRetry(t *testing.T) { if r, _, h := s.Boundaries(); r != 0 || h != 0 { t.Fatalf("failed seed published boundaries: %d %d", r, h) } - header := make([]byte, 4096) - if _, err := s.fd.ReadAt(header, 0); err != nil { - t.Fatal(err) - } - if binary.LittleEndian.Uint64(header[72:80]) != 0 { + if s.v3.pub.current().CheckpointLSN != 0 { t.Fatal("failed seed persisted checkpoint") } hook.barrierErr = nil diff --git a/seaweed-block/core/storage/c11_production_removal_test.go b/seaweed-block/core/storage/c11_production_removal_test.go new file mode 100644 index 0000000000..d678d1b43d --- /dev/null +++ b/seaweed-block/core/storage/c11_production_removal_test.go @@ -0,0 +1,45 @@ +package storage + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "strings" + "testing" +) + +// The retained C11 file codec is historical fixture evidence, not a store +// option. Inspect uses as well as declarations (including function aliases). +func TestProductionExcludesC11FileStore(t *testing.T) { + for _, dir := range []string{".", filepath.Join("..", "frontend", "durable")} { + files, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + inspected := 0 + for _, entry := range files { + name := entry.Name() + if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + inspected++ + file := filepath.Join(dir, name) + f, err := parser.ParseFile(token.NewFileSet(), file, nil, 0) + if err != nil { + t.Fatal(err) + } + ast.Inspect(f, func(n ast.Node) bool { + id, ok := n.(*ast.Ident) + if ok && (strings.Contains(id.Name, "FileChunkBitmapStore") || id.Name == "legacyC11FileStore" || id.Name == "newLegacyC11FileStore") { + t.Errorf("production source %s retains C11 file store %s", file, id.Name) + } + return true + }) + } + if inspected == 0 { + t.Fatalf("no production source inspected in %s", dir) + } + } +} diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go new file mode 100644 index 0000000000..4ddf562718 --- /dev/null +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -0,0 +1,705 @@ +package storage + +import ( + "bytes" + "encoding/binary" + "errors" + "path/filepath" + "testing" + "time" +) + +func TestChunkLayerV3_CheckpointProgressUnderContinuousAppends(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + remote := newFakeChunkRemote() + mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(0, blk(1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + realSync := s.v3.ownedMap.syncFile + t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync }) + refusals := 0 + previousCP := uint64(0) + for round := uint32(0); round < 8; round++ { + injected := false + s.v3.ownedMap.syncFile = func() error { + if !injected { + injected = true + if _, err := s.Write(round+1, blk(byte(round+2))); err != nil { + return err + } + } + return realSync() + } + err := s.flusher.flushOnce() + s.v3.ownedMap.syncFile = realSync + if err != nil && !errors.Is(err, ErrMapCoverageStale) { + t.Fatal(err) + } + if errors.Is(err, ErrMapCoverageStale) { + refusals++ + } + if !injected { + t.Fatal("cycle did not overlap a write") + } + if cp := s.CheckpointLSN(); cp <= previousCP { + t.Fatalf("cycle %d: checkpoint %d did not advance beyond %d", round, cp, previousCP) + } else { + previousCP = cp + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + cp := s.CheckpointLSN() + t.Logf("continuous writes: cycles8 refusals%d cp%d wack%d dirty%d", refusals, cp, s.v3.wack.Load(), s.dm.len()) + if cp == 0 { + t.Fatal("checkpoint made no progress across eight completed extent/map persistence cycles while newer appends continued") + } +} + +func TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + remote := newFakeChunkRemote() + layer := mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(1, blk(0x11)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.v3.testMapPrepared = func() { + if _, err := s.WriteBatch(1, [][]byte{blk(0xB2), blk(0xC3)}); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + s.v3.testMapPrepared = nil + d := s.v3.pub.current() + if d.CheckpointLSN != 1 || d.MapCoveredCheckpoint != 1 || s.dm.len() != 2 { + t.Fatalf("prefix cp=%d C=%d dirty=%d", d.CheckpointLSN, d.MapCoveredCheckpoint, s.dm.len()) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err = r.Recover(); err != nil { + t.Fatal(err) + } + for lba, want := range map[uint32][]byte{1: blk(0xB2), 2: blk(0xC3)} { + if !bytes.Equal(readV3(t, r, lba), want) { + t.Fatalf("replayed LBA%d lost", lba) + } + } + restored := mustAttach(t, r, remote, ctConfig(1)) + cut, err := restored.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + image := remote.imageOf(t, cut.Head) + if !bytes.Equal(image[4096:8192], blk(0xB2)) || !bytes.Equal(image[8192:12288], blk(0xC3)) { + t.Fatal("capture omitted newer replayed batch") + } +} + +func TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + h := beginV3(t, s, 0, idA) + cp := s.CheckpointLSN() + prepared, err := s.prepareOwnedMapCheckpointV3(cp) + if err != nil { + t.Fatal(err) + } + before := s.v3.pub.current() + if err = h.WriteBase(1, blk(0xA7)); err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("effective BASE mutation proof accepted: %v", err) + } + if s.v3.pub.current() != before { + t.Fatal("stale BASE candidate changed slots") + } +} + +// Removing append-driven increments must not bypass terminal exhaustion. +func TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend(t *testing.T) { + for _, batch := range []bool{false, true} { + s, _ := newMappedCheckpointStoreV3(t) + before := s.NextLSN() + s.v3.mapProof.mutation.Store(counterMaxV3) + var err error + if batch { + _, err = s.WriteBatch(1, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.Write(1, blk(1)) + } + if !errors.Is(err, ErrCounterExhausted) || s.NextLSN() != before || s.dm.len() != 0 { + t.Fatalf("exhaustion bypassed: batch=%t err=%v next=%d dirty=%d", batch, err, s.NextLSN(), s.dm.len()) + } + } +} + +// A write's real fallback rollover can run after a map candidate was prepared. +// It preserves the older prefix and the later append remains available to replay. +func TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(1) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(2) + if err != nil { + t.Fatal(err) + } + tail := s.v3.w.reclaimThroughV3(2) + before := s.v3.pub.current() + if tail <= before.RetainedTail { + t.Fatal("setup: no releasable retained record") + } + // One real slot publication advances the current tail only. The next Write + // must bring the fallback forward before it can reuse that released range. + if _, err := s.v3.pub.publish(nil, nil, func(d *descriptorV3) error { + d.RetainedTail = tail + d.RetainedHead = max(d.RetainedHead, tail) + return nil + }); err != nil { + t.Fatal(err) + } + current, floor, ok := s.v3.pub.walSnapshotV3() + if !ok || floor >= tail { + t.Fatal("setup: fallback did not pin rollover") + } + if lsn, err := s.Write(3, blk(0xD3)); err != nil || lsn != 3 { + t.Fatalf("write: lsn %d err %v", lsn, err) + } + after := s.v3.pub.current() + if after.SlotGen != current.SlotGen+1 { + t.Fatal("Write did not execute the fallback rollover") + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatalf("prefix publication after rollover: %v", err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + d, floor, ok := s.v3.pub.walSnapshotV3() + if !ok || d.CheckpointLSN != 2 || d.MapCoveredCheckpoint != 2 || d.W < 3 || floor != tail || d.RetainedTail != tail { + t.Fatalf("prefix/suffix boundary: cp%d C%d W%d floor%d tail%d want%d", d.CheckpointLSN, d.MapCoveredCheckpoint, d.W, floor, d.RetainedTail, tail) + } + s.SetRecoveryRetentionLSNs(1) + var scanned []RecoveryEntry + if err := s.ScanLBAs(3, func(e RecoveryEntry) error { scanned = append(scanned, e); return nil }); err != nil || len(scanned) != 1 || scanned[0].LSN != 3 || !bytes.Equal(scanned[0].Data, blk(0xD3)) { + t.Fatalf("retained suffix: %+v err %v", scanned, err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if !bytes.Equal(readV3(t, r, 3), blk(0xD3)) { + t.Fatal("retained suffix lost after reopen") + } +} + +func TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix(t *testing.T) { + path := filepath.Join(t.TempDir(), "hydrating") + s, err := createMappedWALStoreV3ForTest(path, ctNumBlocks, ctBlockSize, v3TestWAL, WModeStrict, ctChunkBlocks) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + image := make([]byte, ctNumBlocks*ctBlockSize) + copy(image[9*ctBlockSize:], blk(0xA9)) + remote := newFakeChunkRemote() + remote.seedHead(t, image, 10, 1) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + layer := mustAttach(t, s, remote, cfg).(*chunkLayerImpl) + prepared, err := s.prepareOwnedMapCheckpointV3(10) + if err != nil { + t.Fatal(err) + } + layer.stMu.Lock() + absent := layer.absent[2] + layer.stMu.Unlock() + if !absent { + t.Fatal("setup: chunk is not absent") + } + if got, err := s.Read(9); err != nil || !bytes.Equal(got, blk(0xA9)) { + t.Fatalf("lazy read: %v", err) + } + layer.stMu.Lock() + absent = layer.absent[2] + layer.stMu.Unlock() + if absent { + t.Fatal("read did not hydrate chunk") + } + if !prepared.proof.validV3(s.v3.mapProof) { + t.Fatal("lazy fill invalidated the checkpoint prefix") + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatalf("publish after lazy fill: %v", err) + } +} + +// At every cycle the ring reaches the real admission soft-pressure range. +// An append overlaps map persistence, yet each completed cycle must reclaim; +// none may require a cut or new remote HEAD to escape repeated proof refusal. +func TestChunkLayerV3_CheckpointProgressAtWALPressure(t *testing.T) { + for _, mode := range []WMode{WModeStrict, WModeLagged} { + t.Run(map[WMode]string{WModeStrict: "A", WModeLagged: "C"}[mode], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "pressure") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 64*1024, mode, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + realSync := s.v3.ownedMap.syncFile + t.Cleanup(func() { s.v3.ownedMap.syncFile = realSync }) + previousCP := uint64(0) + expected := make(map[uint32][]byte) + write := func() error { + lsn := s.NextLSN() + lba := uint32(lsn % 64) + data := checkpointProgressBlock(lsn) + if _, err := s.Write(lba, data); err != nil { + return err + } + expected[lba] = data + return nil + } + for cycle := 0; cycle < 8; cycle++ { + for s.walUsedFraction() < 0.72 { + if err := write(); err != nil { + t.Fatal(err) + } + } + injected := false + s.v3.ownedMap.syncFile = func() error { + if !injected { + injected = true + if err := write(); err != nil { + return err + } + } + return realSync() + } + err := s.flusher.flushOnce() + s.v3.ownedMap.syncFile = realSync + if err != nil { + t.Fatalf("pressure cycle%d: %v", cycle, err) + } + cp := s.CheckpointLSN() + if !injected || cp <= previousCP { + t.Fatalf("no progress cycle%d cp%d previous%d", cycle, cp, previousCP) + } + previousCP = cp + } + floor, ok := s.v3.pub.reuseFloor() + if !ok || floor < 5*64*1024 { + t.Fatalf("no sustained ring reuse: floor%d", floor) + } + for lba, want := range expected { + if got, err := s.Read(lba); err != nil || !bytes.Equal(got, want) { + t.Fatalf("no-Flush readback LBA%d: %v", lba, err) + } + } + t.Logf("no client Sync: cycles8 checkpoint%d floor%d busy0", previousCP, floor) + }) + } +} + +func checkpointProgressBlock(lsn uint64) []byte { + data := make([]byte, 4096) + for i := 0; i < len(data); i += 8 { + binary.LittleEndian.PutUint64(data[i:i+8], lsn*4096+uint64(i)) + } + return data +} + +// An active history pin gives one bounded, typed refusal; local flusher work +// after releasing it restores progress without a client Sync or new remote cut. +func TestCheckpointV3_NoFlushPressureWithRealPin(t *testing.T) { + path := filepath.Join(t.TempDir(), "pinned") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 64*1024, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 0, anyActive: true}) + expected := make(map[uint32][]byte) + for s.walUsedFraction() < 0.90 { + lsn := s.NextLSN() + lba := uint32(lsn) + data := checkpointProgressBlock(lsn) + if _, err := s.Write(lba, data); err != nil { + t.Fatal(err) + } + expected[lba] = data + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if s.CheckpointLSN() != 0 || s.v3.wack.Load() == 0 { + t.Fatal("real retention pin did not constrain an internally synced checkpoint") + } + next := s.NextLSN() + start := time.Now() + _, err = s.Write(uint32(next), checkpointProgressBlock(next)) + elapsed := time.Since(start) + if !errors.Is(err, ErrWALPressureTimeout) || elapsed >= 5*time.Second || s.NextLSN() != next { + t.Fatalf("pinned busy: err%v elapsed%v next%d want%d", err, elapsed, s.NextLSN(), next) + } + count := 0 + if err := s.ScanLBAs(1, func(e RecoveryEntry) error { + count++ + if e.LSN != uint64(count) || !bytes.Equal(e.Data, expected[e.LBA]) { + return errors.New("pinned retained prefix differs from submitted bytes") + } + return nil + }); err != nil || count != len(expected) { + t.Fatalf("pinned exact prefix count%d want%d: %v", count, len(expected), err) + } + s.SetRecycleFloorSource(nil) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } // no Write/Sync wakes it + if s.CheckpointLSN() != next-1 { + t.Fatal("released pin did not permit passive local checkpoint progress") + } + if lsn, err := s.Write(uint32(next), checkpointProgressBlock(next)); err != nil || lsn != next { + t.Fatalf("retry: %d %v", lsn, err) + } + expected[uint32(next)] = checkpointProgressBlock(next) + for lba, want := range expected { + if got, err := s.Read(lba); err != nil || !bytes.Equal(got, want) { + t.Fatalf("pinned readback LBA%d: %v", lba, err) + } + } + t.Logf("busy1 elapsed%v retained%d checkpoint%d", elapsed, count, s.CheckpointLSN()) +} + +func TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(1) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(2) + if err != nil { + t.Fatal(err) + } + tail := s.v3.w.reclaimThroughV3(2) + if _, err := s.v3.pub.publish(nil, nil, func(d *descriptorV3) error { + d.RetainedTail = tail + d.RetainedHead = max(d.RetainedHead, tail) + return nil + }); err != nil { + t.Fatal(err) + } + before := s.v3.pub.current() + _, floor, ok := s.v3.pub.walSnapshotV3() + if !ok || floor >= tail { + t.Fatal("setup: no pinned fallback") + } + injected := errors.New("append rollover slot fault") + s.v3.testBeforeSlotWrite = func() error { return injected } + _, err = s.Write(3, blk(0xD3)) + s.v3.testBeforeSlotWrite = nil + if !errors.Is(err, injected) || s.stickyIOFault() == nil || s.NextLSN() != 3 || s.dm.len() != 0 { + t.Fatalf("rollover fault: %v next%d dirty%d", err, s.NextLSN(), s.dm.len()) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil { + t.Fatal("held candidate published through sticky rollover failure") + } + if s.v3.pub.current() != before { + t.Fatal("rollover fault changed authoritative tuple") + } + if nextFloor, valid := s.v3.pub.reuseFloor(); valid || nextFloor != 0 { + t.Fatal("uncertain rollover must disable reuse until reopen") + } +} + +// Max-LSN map entries may include unsynced writes above both cp and W. A +// reused LSN can then set UNKNOWN without changing the prefix proof token. +func TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + remote := newFakeChunkRemote() + layer := mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(1, blk(0xA1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if s.v3.mapEntries[0].Unknown { + t.Fatal("setup: initial definite cut did not clear UNKNOWN") + } + if _, err := s.Write(1, blk(0xA2)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, blk(0xA3)); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + e := prepared.candidate.entries[0] + if e.LSN != 3 || e.Unknown || d.CheckpointLSN != 1 || d.W != 1 { + t.Fatalf("speculative maximum: entry%+v cp%d W%d", e, d.CheckpointLSN, d.W) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatal(err) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + damageRecord(t, path, 2) // unacknowledged record2 tears; the following3 is dropped + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if r.NextLSN() != 2 || r.v3.mapEntries[0].LSN != 3 { + t.Fatal("dropped suffix did not leave the conservative persisted maximum") + } + held, err := r.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + if held.candidate.entries[0].Unknown { + t.Fatal("setup: held candidate already UNKNOWN") + } + if lsn, err := r.Write(1, blk(0xB2)); err != nil || lsn != 2 { + t.Fatalf("reused LSN: %d %v", lsn, err) + } + if !r.v3.mapEntries[0].Unknown || r.v3.mapEntries[0].LSN != 3 { + t.Fatal("reused LSN did not conservatively set UNKNOWN beneath the high maximum") + } + if !held.proof.validV3(r.v3.mapProof) { + t.Fatal("reused ordered append invalidated the older prefix") + } + if _, err := r.v3.pub.publishMapV3(&r.mu, nil, held, nil); err != nil { + t.Fatal(err) + } + if _, err := r.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, r) + r.mu.Lock() + r.closed = true + r.mu.Unlock() + r2, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r2.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r2.Close() }) + if _, err := r2.Recover(); err != nil { + t.Fatal(err) + } + if !r2.v3.mapEntries[0].Unknown || !bytes.Equal(readV3(t, r2, 1), blk(0xB2)) { + t.Fatal("replay did not restore UNKNOWN and exact reused-LSN bytes") + } + restored := mustAttach(t, r2, remote, ctConfig(2)) + cut, err := restored.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + image := remote.imageOf(t, cut.Head) + if !bytes.Equal(image[4096:8192], blk(0xB2)) { + t.Fatal("capture treated the speculative maximum as remotely clean") + } +} + +func TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush(t *testing.T) { + for _, flush := range []bool{false, true} { + t.Run(map[bool]string{false: "wal", true: "extent"}[flush], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "hydrating") + s, err := createMappedWALStoreV3ForTest(path, ctNumBlocks, ctBlockSize, v3TestWAL, WModeStrict, ctChunkBlocks) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + image := make([]byte, ctNumBlocks*ctBlockSize) + copy(image[8*ctBlockSize:], blk(0xA8)) + copy(image[9*ctBlockSize:], blk(0xA9)) + remote := newFakeChunkRemote() + remote.seedHead(t, image, 10, 1) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + layer := mustAttach(t, s, remote, cfg) + held, err := s.prepareOwnedMapCheckpointV3(10) + if err != nil { + t.Fatal(err) + } + entered, release := holdNextGet(t, remote) + done := make(chan error, 1) + joined := make(chan struct{}) + // Release the fetch before joining, including failures before release(). + // Register before launch so store/layer cleanup never precedes the join. + t.Cleanup(func() { + release() + select { + case <-joined: + case <-time.After(ctLocalBound): + t.Errorf("held hydration reader did not settle within %v after release", ctLocalBound) + } + }) + go func() { + defer close(joined) + got, err := s.Read(9) + if err == nil && !bytes.Equal(got, blk(0xB9)) { + err = errors.New("held read did not return newer local bytes") + } + done <- err + }() + waitKey(t, entered, "cold fill before a competing local write") + within(t, "local write and optional flush while hydration is held", func() error { + if _, err := s.Write(9, blk(0xB9)); err != nil { + return err + } + if flush { + if _, err := s.Sync(); err != nil { + return err + } + return s.flusher.flushOnce() + } + return nil + }) + dirty := s.dm.len() + release() + if err := waitErr(t, done, "fill and post-miss WAL recheck"); err != nil { + t.Fatal(err) + } + if s.dm.len() != dirty || !held.proof.validV3(s.v3.mapProof) { + t.Fatal("hydration manufactured logical dirt or invalidated the prefix proof") + } + before := s.v3.pub.current() + _, err = s.v3.pub.publishMapV3(&s.mu, nil, held, nil) + if flush { + if !errors.Is(err, ErrMapCoverageStale) || s.v3.pub.current() != before { + t.Fatalf("superseded candidate after flush: %v", err) + } + } else if err != nil { + t.Fatal(err) + } + // Cover the hydrated extent bytes too before the reopen oracle. + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if !bytes.Equal(readV3(t, s, 8), blk(0xA8)) || !bytes.Equal(readV3(t, s, 9), blk(0xB9)) { + t.Fatal("HEAD fill or local write was overwritten") + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if !bytes.Equal(readV3(t, r, 8), blk(0xA8)) || !bytes.Equal(readV3(t, r, 9), blk(0xB9)) { + t.Fatal("reopen lost exact hydrated/local bytes") + } + }) + } +} + +func TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + layer := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + writeSynced(t, s, 1, 1) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + held, err := s.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + if !s.v3.mapEntries[0].Unknown { + t.Fatal("setup: no UNKNOWN to clear") + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if s.v3.mapEntries[0].Unknown { + t.Fatal("definite cut did not clear UNKNOWN") + } + // Inspect the proof itself so the newer map generation cannot mask a missing + // clear-invalidation guard in the publication refusal below. + if held.proof.validV3(s.v3.mapProof) { + t.Fatal("capture UNKNOWN clearing left the old proof valid") + } + before := s.v3.pub.current() + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, held, nil); !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("old capture proof: %v", err) + } + if s.v3.pub.current() != before { + t.Fatal("capture-stale candidate changed a slot") + } +} diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go new file mode 100644 index 0000000000..68303be17a --- /dev/null +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -0,0 +1,87 @@ +package storage + +import ( + "errors" + "log" + "time" +) + +// CheckpointPersistenceStatus counts flusher checkpoint calls in this open. +// Success includes a safely clamped/unchanged checkpoint; it is not a slot-write +// count. Advances counts only the successes that moved the persisted +// CheckpointLSN, and LastAdvance is when the latest one did (zero: none in +// this open), so a starved checkpoint shows Successes rising while +// LastAdvance stays frozen. Fields are cumulative atomic observations, not a +// coherent frontier. +type CheckpointPersistenceStatus struct { + Successes uint64 + Refusals uint64 + Failures uint64 + CheckpointLSN uint64 + Advances uint64 + LastAdvance time.Time +} + +func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus { + if s.flusher == nil { + return CheckpointPersistenceStatus{CheckpointLSN: s.CheckpointLSN()} + } + i := &s.flusher.instr + st := CheckpointPersistenceStatus{ + Successes: i.checkpointSuccesses.Load(), + Refusals: i.checkpointRefusals.Load(), + Failures: i.checkpointFailures.Load(), + CheckpointLSN: s.CheckpointLSN(), + Advances: i.checkpointAdvances.Load(), + } + if ns := i.checkpointLastAdvanceNanos.Load(); ns != 0 { + st.LastAdvance = time.Unix(0, ns) + } + return st +} + +// recordCheckpoint classifies one flusher checkpoint call; before and after +// are the persisted CheckpointLSN around it. +func (i *flusherInstrumentation) recordCheckpoint(err error, before, after uint64, now time.Time) { + switch { + case err == nil: + i.checkpointSuccesses.Add(1) + if after > before { + i.checkpointAdvances.Add(1) + i.checkpointLastAdvanceNanos.Store(now.UnixNano()) + } + case errors.Is(err, ErrMapCoverageStale): + i.checkpointRefusals.Add(1) + default: + i.checkpointFailures.Add(1) + } +} + +type mapCoverageRefusal string + +func (r mapCoverageRefusal) Error() string { return ErrMapCoverageStale.Error() + ": " + string(r) } +func (r mapCoverageRefusal) Unwrap() error { return ErrMapCoverageStale } + +// Owned exclusively by the flusher run loop; no storage lock or I/O ordering +// changes. Terminal errors are never rate limited. +type checkpointLogLimiter struct { + last time.Time + suppressed uint64 +} + +func (l *checkpointLogLimiter) report(err error, now time.Time) { + if !errors.Is(err, ErrMapCoverageStale) { + log.Printf("storage: flusher: %v", err) + return + } + if !l.last.IsZero() && now.Sub(l.last) < 30*time.Second { + l.suppressed++ + return + } + var reason mapCoverageRefusal + if !errors.As(err, &reason) { + reason = "unspecified" + } + log.Printf("storage: flusher: checkpoint deferred reason=%s suppressed=%d: %v", string(reason), l.suppressed, err) + l.last, l.suppressed = now, 0 +} diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go new file mode 100644 index 0000000000..3834cecd57 --- /dev/null +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -0,0 +1,193 @@ +package storage + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "log" + "strings" + "testing" + "time" +) + +func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + writeSynced(t, s, 1, 1) + s.v3.testMapPrepared = func() { + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + // Simulate the effective-mutation class; newer WAL appends alone are safe. + if err := s.v3.mapProof.mutatedV3(); err != nil { + t.Fatal(err) + } + } + before := s.v3.pub.current() + err := s.flusher.flushOnce() + if !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("refusal: %v", err) + } + if !strings.Contains(err.Error(), "proof_changed") { + t.Errorf("missing refusal reason: %v", err) + } + if s.v3.pub.current() != before || s.dm.len() != 2 || s.stickyIOFault() != nil { + t.Fatal("refusal changed publication/retry/fault state") + } + raw, _ := json.Marshal(s.FlusherInstrumentation()) + var counts map[string]uint64 + if err := json.Unmarshal(raw, &counts); err != nil { + t.Fatal(err) + } + if counts["CheckpointRefusals"] != 1 || counts["CheckpointSuccesses"] != 0 { + t.Fatalf("refusal counters: %s", raw) + } + s.v3.testMapPrepared = nil + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + raw, _ = json.Marshal(s.FlusherInstrumentation()) + if err := json.Unmarshal(raw, &counts); err != nil { + t.Fatal(err) + } + if counts["CheckpointRefusals"] != 1 || counts["CheckpointSuccesses"] != 1 || s.CheckpointLSN() != 2 || s.dm.len() != 0 { + t.Fatalf("retry counters/state: %s cp=%d", raw, s.CheckpointLSN()) + } +} + +func TestCheckpointDiagnostics_PrepareRefusalAndIOFailure(t *testing.T) { + for _, fault := range []bool{false, true} { + t.Run(fmt.Sprint(fault), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + writeSynced(t, s, 1, 1) + realSync := s.v3.ownedMap.syncFile + injected := errors.New("checkpoint map fsync fault") + once := false + s.v3.ownedMap.syncFile = func() error { + if fault { + return injected + } + if !once { + once = true + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + if err := s.v3.mapProof.mutatedV3(); err != nil { + t.Fatal(err) + } + } + return realSync() + } + err := s.flusher.flushOnce() + got := s.CheckpointPersistence() + if fault { + if !errors.Is(err, injected) || got.Failures != 1 || got.Refusals != 0 || s.stickyIOFault() == nil { + t.Fatalf("fault %v counts=%+v", err, got) + } + } else { + if !errors.Is(err, ErrMapCoverageStale) || !strings.Contains(err.Error(), "proof_changed_during_prepare") || got.Refusals != 1 || got.Failures != 0 || s.stickyIOFault() != nil { + t.Fatalf("refusal %v counts=%+v", err, got) + } + } + if got.Successes != 0 || s.CheckpointLSN() != 0 || s.dm.len() == 0 { + t.Fatal("failed checkpoint advanced or lost retry ownership") + } + }) + } +} + +func TestCheckpointDiagnostics_LogRateLimit(t *testing.T) { + var out bytes.Buffer + old := log.Writer() + log.SetOutput(&out) + t.Cleanup(func() { log.SetOutput(old) }) + var limiter checkpointLogLimiter + now := time.Unix(100, 0) + stale := fmt.Errorf("persist checkpoint: %w", mapCoverageRefusal("proof_changed")) + limiter.report(stale, now) + for i := 0; i < 5; i++ { + limiter.report(stale, now.Add(time.Second)) + } + // A terminal failure must remain visible while refusals are suppressed. + terminal := errors.New("real fsync fault") + limiter.report(terminal, now.Add(2*time.Second)) + limiter.report(terminal, now.Add(3*time.Second)) + limiter.report(stale, now.Add(30*time.Second)) + got := out.String() + if strings.Count(got, "checkpoint deferred") != 2 || strings.Count(got, "real fsync fault") != 2 || !strings.Contains(got, "reason=proof_changed suppressed=5") { + t.Fatalf("logs: %s", got) + } +} + +// A starved checkpoint: flush cycles keep succeeding (clamped to the +// acknowledged frontier, nothing persisted moves) while the persisted +// CheckpointLSN and the last advance stay frozen. Only a real move of the +// persisted checkpoint counts as an advance. +func TestCheckpointDiagnostics_StarvedCheckpointIsVisible(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + writeSynced(t, s, 1, 1) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + first := s.CheckpointPersistence() + if first.CheckpointLSN != 1 || first.Advances != 1 || first.LastAdvance.IsZero() || first.Successes != 1 { + t.Fatalf("first checkpoint: %+v", first) + } + for i := uint32(0); i < 3; i++ { // written, never synced: the checkpoint is clamped at 1 + if _, err := s.Write(2+i, blk(byte(2+i))); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + } + starved := s.CheckpointPersistence() + if starved.Successes <= first.Successes { + t.Fatalf("flush cycles did not keep succeeding: %+v", starved) + } + if starved.CheckpointLSN != 1 || starved.Advances != 1 || !starved.LastAdvance.Equal(first.LastAdvance) { + t.Fatalf("a clamped success counted as an advance: first %+v starved %+v", first, starved) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + moved := s.CheckpointPersistence() + if moved.CheckpointLSN != s.CheckpointLSN() || moved.CheckpointLSN <= 1 || moved.Advances != 2 || !moved.LastAdvance.After(first.LastAdvance) { + t.Fatalf("after sync the checkpoint advance was not recorded: %+v", moved) + } +} + +// Only an advancing success moves LastAdvance; an unchanged success, a +// refusal and a failure leave the latest advance time as it was. +func TestCheckpointDiagnostics_LastAdvanceFollowsOnlyAdvances(t *testing.T) { + var i flusherInstrumentation + t0 := time.Unix(1000, 0) + at := func() time.Time { return time.Unix(0, i.checkpointLastAdvanceNanos.Load()) } + i.recordCheckpoint(nil, 0, 5, t0) + if !at().Equal(t0) || i.checkpointAdvances.Load() != 1 { + t.Fatalf("first advance: %v %d", at(), i.checkpointAdvances.Load()) + } + i.recordCheckpoint(nil, 5, 5, t0.Add(time.Second)) + i.recordCheckpoint(mapCoverageRefusal("proof_changed"), 5, 5, t0.Add(2*time.Second)) + i.recordCheckpoint(errors.New("fsync fault"), 5, 5, t0.Add(3*time.Second)) + if !at().Equal(t0) || i.checkpointAdvances.Load() != 1 { + t.Fatalf("a non-advance moved LastAdvance: %v advances=%d", at(), i.checkpointAdvances.Load()) + } + t1 := t0.Add(4 * time.Second) + i.recordCheckpoint(nil, 5, 9, t1) + if !at().Equal(t1) || i.checkpointAdvances.Load() != 2 { + t.Fatalf("second advance: %v %d", at(), i.checkpointAdvances.Load()) + } + if i.checkpointSuccesses.Load() != 3 || i.checkpointRefusals.Load() != 1 || i.checkpointFailures.Load() != 1 { + t.Fatalf("classification: s=%d r=%d f=%d", i.checkpointSuccesses.Load(), i.checkpointRefusals.Load(), i.checkpointFailures.Load()) + } +} diff --git a/seaweed-block/core/storage/chunk_base_v3.go b/seaweed-block/core/storage/chunk_base_v3.go new file mode 100644 index 0000000000..c9a7aa2a6f --- /dev/null +++ b/seaweed-block/core/storage/chunk_base_v3.go @@ -0,0 +1,69 @@ +package storage + +import "fmt" + +// holdBaseTransitionV3 drains a whole cut, including pre-copy, remote CAS, +// ambiguous-outcome bookkeeping and map settlement. It runs under installMu +// exclusive, before captureMu or any lower store lock; no remote call or +// persistent bitmap I/O occurs here. Close joins the transition registration. +func (l *chunkLayerImpl) holdBaseTransitionV3() (func(), error) { + done, err := l.register() + if err != nil { + return nil, err + } + if hook := l.testBaseTransitionBeforeLock; hook != nil { + hook() + } + l.capMu.Lock() + l.stMu.Lock() + var refusal error + switch { + case l.closed: + refusal = errChunkLayerClosed + case l.fenced: + refusal = errChunkLayerFenced + case l.detached != nil: + refusal = errChunkLayerDetached + case l.pending != nil: + refusal = errChunkCASOutcomeUnknown + } + l.stMu.Unlock() + if refusal != nil { + l.capMu.Unlock() + done() + return nil, fmt.Errorf("storage: BASE transition refused: %w", refusal) + } + return func() { + // All lower store locks have been released. Descriptor truth wins even + // after a refused or partly published transition; never infer completion. + d := l.s.v3.pub.current() + l.noteAllMutated() + l.stMu.Lock() + l.reconcileGen++ + if l.reconciled != nil { + close(l.reconciled) + l.reconciled = nil + } + l.reconcile = map[uint64]bool{} + l.hashMode = false + l.allDirty = true + l.dirtyVer++ + switch d.BaseState { + case BaseInstalling: + l.hdr.Base = chunkBaseInstalling + case BaseInstalled: + l.hdr.Base = chunkBaseInstalledAwaitingCut + default: + l.hdr.Base = chunkBaseNone + } + // The barrier saved presence while installing; release sees the + // installed publication only after all lower locks were released. + presenceDurable := l.presenceVer == l.savedPresVer && len(l.absent) == 0 && len(l.localBlocks) == 0 + l.stMu.Unlock() + if d.BaseState == BaseInstalled && presenceDurable && l.s.OwnerChunkAttachDurableV3() { + l.s.AllowBaseRetirementV3() + } + l.capMu.Unlock() + done() + }, nil +} diff --git a/seaweed-block/core/storage/chunk_base_v3_test.go b/seaweed-block/core/storage/chunk_base_v3_test.go new file mode 100644 index 0000000000..853c5aae41 --- /dev/null +++ b/seaweed-block/core/storage/chunk_base_v3_test.go @@ -0,0 +1,254 @@ +package storage + +import ( + "bytes" + "errors" + "testing" + "time" +) + +func mappedBASELayerV3(t *testing.T) (*WALStore, *fakeChunkRemote, *chunkLayerImpl) { + t.Helper() + s, _ := newMappedCheckpointStoreV3(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.Bitmap = nil + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + return s, f, l +} + +func TestChunkLayerV3_BASEIncompleteCaptureGuard(t *testing.T) { + s, f, l := mappedBASELayerV3(t) + h, e := s.BeginBaseInstall(7, idA) + if e != nil { + t.Fatal(e) + } + if e = h.WriteBase(5, blk(0x55)); e != nil { + t.Fatal(e) + } + before := f.stats() + if _, e = l.Cut(ctTimeout(t)); !errors.Is(e, errChunkBaseInstalling) || !errors.Is(e, errChunkCaptureRefused) { + t.Fatalf("missing early typed incomplete capture guard: %v", e) + } + after := f.stats() + if after.puts != before.puts || after.cas != before.cas { + t.Fatal("incomplete capture performed remote writes") + } + if e = h.MarkBaseComplete(); e != nil { + t.Fatal(e) + } + if _, e = l.Cut(ctTimeout(t)); e != nil { + t.Fatal(e) + } +} + +func TestChunkLayerV3_BASEBeginDrainsWholeCut(t *testing.T) { + s, f, l := mappedBASELayerV3(t) + if _, e := s.Write(5, blk(0x11)); e != nil { + t.Fatal(e) + } + if _, e := s.Sync(); e != nil { + t.Fatal(e) + } + entered, release := holdPuts(t, f) + cutDone := startCapture(t, l) + waitKey(t, entered, "held cut upload after barrier") + attempted := make(chan struct{}) + l.testBaseTransitionBeforeLock = func() { close(attempted) } + type result struct { + h InstallHandle + err error + } + finished := make(chan result, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + release() + select { + case <-joined: + case <-time.After(ctLocalBound): + t.Error("BASE begin worker not joined") + } + }) + go func() { defer close(joined); h, e := s.BeginBaseInstall(7, idA); finished <- result{h, e} }() + select { + case <-attempted: + case <-time.After(ctLocalBound): + t.Fatal("BASE did not reach outer drain") + } + select { + case r := <-finished: + t.Fatalf("BASE begin completed before the captured upload/CAS drained: %v", r.err) + case <-time.After(200 * time.Millisecond): + } + release() + if e := waitErr(t, cutDone, "old cut settlement"); e != nil { + t.Fatal(e) + } + var r result + select { + case r = <-finished: + case <-time.After(ctLocalBound): + t.Fatal("BASE begin failed to resume after cut settled") + } + if r.err != nil { + t.Fatal(r.err) + } + l.testBaseTransitionBeforeLock = nil + old := f.stats().head + if old.RemoteLSN != 1 || !bytes.Equal(f.imageOf(t, old)[5*ctBlockSize:6*ctBlockSize], blk(0x11)) { + t.Fatal("old cut was not settled before installing") + } + if e := r.h.WriteBase(5, blk(0x77)); e != nil { + t.Fatal(e) + } + if _, e := l.Cut(ctTimeout(t)); !errors.Is(e, errChunkBaseInstalling) { + t.Fatal("partial BASE capture", e) + } + if !sameHead(f.stats().head, old) { + t.Fatal("HEAD advanced during partial BASE") + } + if e := r.h.MarkBaseComplete(); e != nil { + t.Fatal(e) + } + next, e := l.Cut(ctTimeout(t)) + if e != nil { + t.Fatal(e) + } + if next.H < 7 || !bytes.Equal(f.imageOf(t, next.Head)[5*ctBlockSize:6*ctBlockSize], blk(0x77)) { + t.Fatal("completed BASE did not replace the old cut") + } +} + +func TestChunkLayerV3_BASEBeginRefusesUnsettledCAS(t *testing.T) { + s, f, l := mappedBASELayerV3(t) + if _, e := s.Write(5, blk(0x11)); e != nil { + t.Fatal(e) + } + if _, e := s.Sync(); e != nil { + t.Fatal(e) + } + f.mu.Lock() + f.casModes = []fakeCASMode{casDeferred} + f.mu.Unlock() + if _, e := l.Cut(ctTimeout(t)); !errors.Is(e, errChunkCASOutcomeUnknown) { + t.Fatal("setup did not retain ambiguous CAS", e) + } + before := s.v3.pub.current() + if _, e := s.BeginBaseInstall(7, idA); !errors.Is(e, errChunkCASOutcomeUnknown) { + t.Fatalf("BASE admitted while old CAS could still land: %v", e) + } + if after := s.v3.pub.current(); after != before { + t.Fatal("unsettled CAS refusal changed descriptor") + } + f.releaseDeferredCAS() + if _, e := l.Cut(ctTimeout(t)); e != nil { + t.Fatal("old publication settlement", e) + } + h, e := s.BeginBaseInstall(7, idA) + if e != nil { + t.Fatal("settled cut did not allow begin", e) + } + if e = h.MarkBaseComplete(); e != nil { + t.Fatal(e) + } +} + +func TestChunkLayerV3_BASEDrainJoinsClose(t *testing.T) { + s, f, l := mappedBASELayerV3(t) + if _, e := s.Write(5, blk(0x11)); e != nil { + t.Fatal(e) + } + if _, e := s.Sync(); e != nil { + t.Fatal(e) + } + entered, release := holdPuts(t, f) + cutDone := startCapture(t, l) + waitKey(t, entered, "upload before Close") + attempted := make(chan struct{}) + l.testBaseTransitionBeforeLock = func() { close(attempted) } + beginDone := make(chan error, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + release() + select { + case <-joined: + case <-time.After(ctLocalBound): + t.Error("BASE worker not joined after Close") + } + }) + go func() { defer close(joined); _, e := s.BeginBaseInstall(7, idA); beginDone <- e }() + select { + case <-attempted: + case <-time.After(ctLocalBound): + t.Fatal("BASE never registered for drain") + } + within(t, "store Close cancels cut and joins BASE drain", s.Close) + if e := waitErr(t, beginDone, "BASE after Close"); !errors.Is(e, errChunkLayerClosed) { + t.Fatalf("BASE ignored closing layer: %v", e) + } + if e := waitErr(t, cutDone, "cancelled cut after Close"); e == nil { + t.Fatal("cancelled upload cut succeeded") + } +} + +func TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling(t *testing.T) { + s, f, l := mappedBASELayerV3(t) + s.DeferBaseRetirementV3() + // Model an already committed provider owner before a later BASE. + if err := s.CommitChunkAttachV3(func() error { return nil }); err != nil { + t.Fatal(err) + } + if _, e := s.Write(5, blk(0x11)); e != nil { + t.Fatal(e) + } + if _, e := s.Sync(); e != nil { + t.Fatal(e) + } + if e := s.flusher.flushOnce(); e != nil { + t.Fatal(e) + } + if _, e := l.Cut(ctTimeout(t)); e != nil { + t.Fatal(e) + } + if e := l.EvictChunk(1); e != nil { + t.Fatal(e) + } + h, e := s.BeginBaseInstall(7, idA) + if e != nil { + t.Fatal(e) + } + if e = h.WriteBase(5, blk(0x77)); e != nil { + t.Fatal(e) + } + before := s.v3.pub.current() + injected := errors.New("injected BASE presence directory barrier") + realSync := l.syncDirFn + l.syncDirFn = func(string) error { return injected } + t.Cleanup(func() { l.syncDirFn = realSync }) + if e = h.MarkBaseComplete(); !errors.Is(e, injected) { + t.Fatalf("missing presence barrier error: %v", e) + } + if after := s.v3.pub.current(); after != before || after.BaseState != BaseInstalling { + t.Fatal("failed presence barrier published installed") + } + if _, e = l.Cut(ctTimeout(t)); !errors.Is(e, errChunkBaseInstalling) { + t.Fatal("failed BASE became capturable", e) + } + if gate := s.v3.pub.retireGate.Load(); gate != retireDeferredV3 { + t.Fatalf("failed presence barrier released gate: %d", gate) + } + l.syncDirFn = realSync + if e = h.MarkBaseComplete(); e != nil { + t.Fatal("completion retry", e) + } + if gate := s.v3.pub.retireGate.Load(); gate != retireAllowedV3 { + t.Fatalf("durable completion did not release gate: %d", gate) + } + r, e := l.Cut(ctTimeout(t)) + if e != nil { + t.Fatal(e) + } + if !bytes.Equal(f.imageOf(t, r.Head)[5*ctBlockSize:6*ctBlockSize], blk(0x77)) { + t.Fatal("retry installed an older remote block") + } +} diff --git a/seaweed-block/core/storage/chunk_birth.go b/seaweed-block/core/storage/chunk_birth.go new file mode 100644 index 0000000000..c6862223a8 --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth.go @@ -0,0 +1,19 @@ +package storage + +// The caller holds captureMu exclusive, with no layer state lock held. +// An owned-map max is conservative: recovery can drop an unacked suffix +// while retaining its maximum. Bound it by the same-barrier cut frontier; +// the captured image has no later writes. Preserve lower inherited births. +func (l *chunkLayerImpl) captureBirths(candidates map[uint64]bool, frontier uint64) map[uint64]uint64 { + out := make(map[uint64]uint64, len(candidates)) + l.s.mu.RLock() + defer l.s.mu.RUnlock() + for idx := range candidates { + birth := frontier + if l.usesOwnedMapV3() { + birth = min(l.s.v3.mapEntries[idx].LSN, frontier) + } + out[idx] = birth + } + return out +} diff --git a/seaweed-block/core/storage/chunk_birth_budget_test.go b/seaweed-block/core/storage/chunk_birth_budget_test.go new file mode 100644 index 0000000000..5535c69edf --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_budget_test.go @@ -0,0 +1,65 @@ +package storage + +import ( + "testing" + "time" +) + +// Metadata-only maximum-volume/default-chunk shape; no volume-sized image or +// device is allocated. This measures the added sampler, not a complete cut. +func BenchmarkCaptureBirthsMaxVolumeDefaultChunk(b *testing.B) { + const count = 1 << 22 // ceil((16 TiB - 4 KiB) / 4 MiB) + candidates := make(map[uint64]bool, count) + s := &WALStore{v3: &walStoreV3State{mapEntries: make([]chunkLSNEntryV3, count), mapProof: newMapProofEpochV3()}} + for i := uint64(0); i < count; i++ { + candidates[i] = true + s.v3.mapEntries[i].LSN = i + 1 + } + l := &chunkLayerImpl{s: s} + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.captureMu.Lock() + out := l.captureBirths(candidates, count) + s.captureMu.Unlock() + if len(out) != count || out[0] != 1 || out[count-1] != count { + b.Fatal("worst-shape birth mismatch") + } + } +} +func TestCaptureBirthsIncludesStoreLockWait(t *testing.T) { + s := &WALStore{} + l := &chunkLayerImpl{s: s} + candidates := map[uint64]bool{0: true} + s.mu.Lock() + locked := true + done := make(chan map[uint64]uint64, 1) + t.Cleanup(func() { + if locked { + s.mu.Unlock() + } + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("sampler did not join") + } + }) + go func() { s.captureMu.Lock(); out := l.captureBirths(candidates, 7); s.captureMu.Unlock(); done <- out }() + select { + case out := <-done: + done <- out + t.Fatal("sampler bypassed store lock") + case <-time.After(25 * time.Millisecond): + } + s.mu.Unlock() + locked = false + select { + case out := <-done: + done <- out + if out[0] != 7 { + t.Fatal("legacy frontier changed") + } + case <-time.After(5 * time.Second): + t.Fatal("sampler did not finish after lock release") + } +} diff --git a/seaweed-block/core/storage/chunk_birth_export_test.go b/seaweed-block/core/storage/chunk_birth_export_test.go new file mode 100644 index 0000000000..08795edc5e --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_export_test.go @@ -0,0 +1,82 @@ +package storage + +import ( + "bytes" + "testing" +) + +// DroppedSuffixBirthStoreForTest exposes only the recovery fixture to the +// external-package regression, which uses chunkstore's real manifest builder. +func DroppedSuffixBirthStoreForTest(t *testing.T, remote ChunkRemote) *WALStore { + t.Helper() + s, path := newMappedCheckpointStoreV3(t) + layer := mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(1, blk(0xA1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, blk(0xA2)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, blk(0xA3)); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(1) + if err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + if e := prepared.candidate.entries[0]; e.LSN != 3 || d.CheckpointLSN != 1 || d.W != 1 { + t.Fatalf("setup entry%+v cp%d W%d", e, d.CheckpointLSN, d.W) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatal(err) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + damageRecord(t, path, 2) + reopen := func() *WALStore { + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + return r + } + r := reopen() + if r.NextLSN() != 2 || r.v3.mapEntries[0].LSN != 3 { + t.Fatal("missing conservative maximum after dropped suffix") + } + if n, err := r.Write(1, blk(0xB2)); err != nil || n != 2 { + t.Fatalf("reused LSN %d: %v", n, err) + } + if _, err := r.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, r) + r.mu.Lock() + r.closed = true + r.mu.Unlock() + r2 := reopen() + if e := r2.v3.mapEntries[0]; e.LSN != 3 || !e.Unknown || r2.NextLSN() != 3 || !bytes.Equal(readV3(t, r2, 1), blk(0xB2)) { + t.Fatalf("recovered reused image: entry%+v next%d", e, r2.NextLSN()) + } + return r2 +} diff --git a/seaweed-block/core/storage/chunk_birth_manifest_test.go b/seaweed-block/core/storage/chunk_birth_manifest_test.go new file mode 100644 index 0000000000..062f36e959 --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_manifest_test.go @@ -0,0 +1,156 @@ +package storage_test + +import ( + "bytes" + "context" + "fmt" + "path" + "sort" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/protobuf/proto" +) + +// Only the metadata/blob transports are in memory; capture, recovery, +// PrepareManifest, segment encoding, CAS and resolved reads are production. +type birthFiler struct { + mu sync.Mutex + entries map[string]*filerpb.Entry +} + +func (f *birthFiler) LookupEntry(_ context.Context, d, n string) (*filerpb.Entry, error) { + f.mu.Lock() + defer f.mu.Unlock() + e := f.entries[path.Join(d, n)] + if e == nil { + return nil, chunkstore.ErrNotFound + } + return proto.Clone(e).(*filerpb.Entry), nil +} +func (f *birthFiler) CreateEntry(_ context.Context, d string, e *filerpb.Entry, excl bool) error { + f.mu.Lock() + defer f.mu.Unlock() + k := path.Join(d, e.Name) + if excl && f.entries[k] != nil { + return chunkstore.ErrExists + } + f.entries[k] = proto.Clone(e).(*filerpb.Entry) + return nil +} +func (f *birthFiler) UpdateEntry(_ context.Context, d string, e *filerpb.Entry, expected map[string][]byte) error { + f.mu.Lock() + defer f.mu.Unlock() + k := path.Join(d, e.Name) + old := f.entries[k] + if old == nil { + return chunkstore.ErrNotFound + } + for k, v := range expected { + if !bytes.Equal(old.Extended[k], v) { + return chunkstore.ErrPrecondition + } + } + f.entries[k] = proto.Clone(e).(*filerpb.Entry) + return nil +} +func (f *birthFiler) DeleteEntry(_ context.Context, d, n string, expected map[string][]byte) error { + f.mu.Lock() + defer f.mu.Unlock() + k := path.Join(d, n) + for key, v := range expected { + if f.entries[k] == nil || !bytes.Equal(f.entries[k].Extended[key], v) { + return chunkstore.ErrPrecondition + } + } + delete(f.entries, k) + return nil +} +func (f *birthFiler) ListEntries(_ context.Context, d, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { + f.mu.Lock() + defer f.mu.Unlock() + var out []*filerpb.Entry + for k, e := range f.entries { + if path.Dir(k) == d && strings.HasPrefix(e.Name, prefix) && e.Name > after { + out = append(out, proto.Clone(e).(*filerpb.Entry)) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + if limit > 0 && len(out) > int(limit) { + out = out[:limit] + } + return out, nil +} + +type birthBlobs struct { + mu sync.Mutex + data map[string][]byte +} + +func (b *birthBlobs) Put(_ context.Context, d []byte) (string, error) { + b.mu.Lock() + defer b.mu.Unlock() + id := fmt.Sprint(len(b.data) + 1) + b.data[id] = bytes.Clone(d) + return id, nil +} +func (b *birthBlobs) Get(_ context.Context, id string) ([]byte, error) { + b.mu.Lock() + defer b.mu.Unlock() + d, ok := b.data[id] + if !ok { + return nil, chunkstore.ErrNotFound + } + return bytes.Clone(d), nil +} + +func TestChunkBirthDroppedSuffixPublishesWithRealManifest(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + f := &birthFiler{entries: map[string]*filerpb.Entry{}} + b := &birthBlobs{data: map[string][]byte{}} + remote, err := chunkstore.NewChunkRemote(f, b, "/birth/v1") + if err != nil { + t.Fatal(err) + } + s := storage.DroppedSuffixBirthStoreForTest(t, remote) + layer, err := storage.AttachChunkLayer(s, remote, storage.ChunkLayerConfig{ChunkBlocks: 4, Epoch: 2, Holder: "host-a"}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = layer.Close() }) + cut, err := layer.Cut(ctx) + if err != nil { + t.Fatalf("reused-LSN cut must publish without another write: %v", err) + } + h, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if cut.Head.RemoteLSN != 2 || h.RemoteLSN != 2 || h.Chunks[0].BirthLSN != 2 || h.Segments[0].MaxBirthLSN != 2 { + t.Fatalf("cut-image frontier/birth: %+v", h) + } + data, err := remote.Get(ctx, h.Chunks[0].Key) + if err != nil { + t.Fatal(err) + } + want := make([]byte, 4*4096) + copy(want[4096:], bytes.Repeat([]byte{0xB2}, 4096)) + if !bytes.Equal(data, want) { + t.Fatal("published cut differs from recovered B2 image") + } + // The real builder's future-birth guard must still reject corrupt proposals. + invalid := h + invalid.Chunks = map[uint64]storage.ChunkRef{0: h.Chunks[0]} + ref := invalid.Chunks[0] + ref.BirthLSN = 3 + invalid.Chunks[0] = ref + if _, _, err := remote.PrepareManifest(ctx, h, invalid, 4*4096); err == nil { + t.Fatal("future birth was accepted") + } +} diff --git a/seaweed-block/core/storage/chunk_birth_migration_test.go b/seaweed-block/core/storage/chunk_birth_migration_test.go new file mode 100644 index 0000000000..987c7bab07 --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_migration_test.go @@ -0,0 +1,99 @@ +package storage + +import ( + "bytes" + "os" + "testing" +) + +func TestChunkBirthMigrationCarriesImageFrontier(t *testing.T) { + s, path := newChunkTestStore(t) + d := s.v3.pub.current() + mapPath := s.v3.ownedMap.fd.Name() + if err := s.Close(); err != nil { + t.Fatal(err) + } + src := MigrationSourceV3{UUID: d.UUID, VolumeSize: d.VolumeSize, ExtentSize: d.ExtentSize, BlockSize: d.BlockSize, OldWALOffset: 4096, OldWALSize: d.WALSize + 4096, CreatedAt: d.CreatedAt, CheckpointLSN: 7, ChunkBlocks: ctChunkBlocks} + plan, err := PrepareMigrationV3(mapPath, src) + if err != nil { + t.Fatal(err) + } + fd, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { fd.Close() }) + // Actual offline migration's map and slot encoder, on a small flushed + // image. No legacy engine or fabricated in-memory owned-map entries. + for _, part := range []struct { + offset int64 + data []byte + }{{MigrationSlotBOffset, plan.PreparedB}, {MigrationSlotAOffset, plan.CommittedA}, {MigrationSlotBOffset, plan.RolloverB}} { + if _, err := fd.WriteAt(part.data, part.offset); err != nil { + t.Fatal(err) + } + if err := fd.Sync(); err != nil { + t.Fatal(err) + } + } + want := makeBlock(ctBlockSize, 0x57) + if _, err := fd.WriteAt(want, int64(d.WALOffset+d.WALSize)); err != nil { + t.Fatal(err) + } + if err := fd.Sync(); err != nil { + t.Fatal(err) + } + if err := fd.Close(); err != nil { + t.Fatal(err) + } + r, err := OpenWALStoreWithOptions(path, WALStoreOptions{ChunkBlocks: ctChunkBlocks}) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { closeBounded(t, r) }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + l := mustAttach(t, r, f, ctConfig(1)) + newest, err := r.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x41)) + if err != nil { + t.Fatal(err) + } + cut, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if cut.Head.Chunks[0].BirthLSN != 7 || cut.Head.Chunks[1].BirthLSN != newest { + t.Fatalf("migrated image birth lost: %+v", cut.Head) + } + if !bytes.Equal(f.imageOf(t, cut.Head)[:ctBlockSize], want) { + t.Fatal("migration cut changed inherited bytes") + } +} + +func TestChunkBirthSeededFrontierPreservesInheritedImage(t *testing.T) { + s, _ := newChunkTestStore(t) + if err := s.SeedChunkFrontier(7); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + image := make([]byte, ctNumBlocks*ctBlockSize) + copy(image[ctChunkBlocks*ctBlockSize:], makeBlock(ctBlockSize, 0x57)) + f.seedHead(t, image, 7, 1) + cfg := ctConfig(2) + cfg.FreshFromHead = true + l := mustAttach(t, s, f, cfg) + newest, err := s.Write(0, makeBlock(ctBlockSize, 0x41)) + if err != nil { + t.Fatal(err) + } + cut, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if cut.Head.Chunks[1].BirthLSN != 7 || cut.Head.Chunks[0].BirthLSN != newest { + t.Fatalf("seeded image birth lost: %+v", cut.Head) + } +} diff --git a/seaweed-block/core/storage/chunk_birth_test.go b/seaweed-block/core/storage/chunk_birth_test.go new file mode 100644 index 0000000000..c442156f43 --- /dev/null +++ b/seaweed-block/core/storage/chunk_birth_test.go @@ -0,0 +1,177 @@ +package storage + +import ( + "bytes" + "context" + "sync" + "testing" + "time" +) + +func TestChunkBirthLegacyEngineUsesCutFrontierUpperBound(t *testing.T) { + s, _ := newLegacyChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + l := mustAttach(t, s, f, cfg) + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)); err != nil { + t.Fatal(err) + } + last, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42)) + if err != nil { + t.Fatal(err) + } + cut, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + for _, idx := range []uint64{0, 1} { + if cr := cut.Head.Chunks[idx]; cr.Encoding != "full" || cr.BirthLSN != last { + t.Fatalf("legacy chunk %d metadata %+v, want frontier %d", idx, cr, last) + } + } + want := make([]byte, ctNumBlocks*ctBlockSize) + copy(want, makeBlock(ctBlockSize, 0x41)) + copy(want[ctChunkBlocks*ctBlockSize:], makeBlock(ctBlockSize, 0x42)) + assertImage(t, "legacy inherited image", f.imageOf(t, cut.Head), want) +} + +func TestChunkBirthBASEUsesInheritedFrontierIncludingZero(t *testing.T) { + for _, frontier := range []uint64{0, 7} { + t.Run(string(rune('0'+frontier)), func(t *testing.T) { + s, _, l := mappedBASELayerV3(t) + h, err := s.BeginBaseInstall(frontier, idA) + if err != nil { + t.Fatal(err) + } + if err := h.WriteBase(5, blk(0x55)); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + newest, err := s.Write(0, blk(0x41)) + if err != nil { + t.Fatal(err) + } + cut, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if cut.Head.Chunks[1].BirthLSN != frontier || cut.Head.Chunks[0].BirthLSN != newest { + t.Fatalf("BASE birth drifted with unrelated WAL writes: %+v, inherited %d", cut.Head, frontier) + } + }) + } +} + +func TestChunkBirthCOWDoesNotObservePostBarrierWrite(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.FreshFromHead = true + cfg.BarrierBound = 0 + cfg.UploadConcurrency = 1 + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)); err != nil { + t.Fatal(err) + } + before, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42)) + if err != nil { + t.Fatal(err) + } + entered, release := make(chan struct{}), make(chan struct{}) + var once, releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + l.testCOWRead = func(idx uint64, _ bool) { + if idx == 0 { + once.Do(func() { close(entered) }) + <-release + } + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + done := make(chan error, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + cancel() + unblock() + select { + case <-joined: + case <-time.After(ctLocalBound): + t.Error("birth COW worker not joined") + } + }) + go func() { defer close(joined); _, err := l.Cut(ctx); done <- err }() + cowWaitSignal(t, entered, "copy after the birth barrier") + after, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x43)) + if err != nil { + t.Fatal(err) + } + unblock() + if err := waitErr(t, done, "birth COW cut"); err != nil { + t.Fatal(err) + } + cowWaitSignal(t, joined, "birth COW join") + first := f.installedHeads()[0] + if first.Chunks[1].BirthLSN != before || !bytes.Equal(f.imageOf(t, first)[ctChunkBlocks*ctBlockSize:(ctChunkBlocks+1)*ctBlockSize], makeBlock(ctBlockSize, 0x42)) { + t.Fatal("post-barrier write changed the saved image or its birth") + } + l.testCOWRead = nil + second, err := l.Cut(ctTimeout(t)) + if err != nil || second.Head.Chunks[1].BirthLSN != after { + t.Fatalf("next version lost post-barrier birth: %+v %v", second, err) + } +} + +func TestChunkBirthTracksNewestLocalWriteAtCut(t *testing.T) { + for _, bound := range []int{0, 1} { + t.Run(string(rune('0'+bound)), func(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.FreshFromHead = true + cfg.BarrierBound = bound + l := mustAttach(t, s, f, cfg) + x, err := s.Write(0, makeBlock(ctBlockSize, 0x41)) + if err != nil { + t.Fatal(err) + } + if _, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42)); err != nil { + t.Fatal(err) + } + y, err := s.Write(ctChunkBlocks+1, makeBlock(ctBlockSize, 0x43)) + if err != nil { + t.Fatal(err) + } + first, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if first.Head.Chunks[0].BirthLSN != x || first.Head.Chunks[1].BirthLSN != y || first.Head.Chunks[0].Encoding != "full" || first.Head.RemoteLSN != y { + t.Fatalf("births did not preserve distinct local write frontiers: %+v, want %d/%d", first.Head, x, y) + } + z, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x44)) + if err != nil { + t.Fatal(err) + } + second, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if second.Head.Chunks[0] != first.Head.Chunks[0] || second.Head.Chunks[1].BirthLSN != z { + t.Fatal("rewrite changed a cold chunk birth or failed to advance the changed version") + } + for _, lba := range []uint32{ctChunkBlocks, ctChunkBlocks + 1} { + if _, err := s.Write(lba, makeBlock(ctBlockSize, 0)); err != nil { + t.Fatal(err) + } + } + third, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if _, exists := third.Head.Chunks[1]; exists || third.Head.Chunks[0] != first.Head.Chunks[0] { + t.Fatal("zero-chunk deletion retained a reference or changed the cold birth") + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_bitmap_file_test.go b/seaweed-block/core/storage/chunk_bitmap_file_test.go index 829a5e6fa0..3b940ee422 100644 --- a/seaweed-block/core/storage/chunk_bitmap_file_test.go +++ b/seaweed-block/core/storage/chunk_bitmap_file_test.go @@ -8,9 +8,9 @@ import ( "testing" ) -func TestFileChunkBitmapStore_RoundTripAndReopen(t *testing.T) { +func TestLegacyC11FileCodec_RoundTripAndReopen(t *testing.T) { path := filepath.Join(t.TempDir(), "vol.chunkbitmap") - b := NewFileChunkBitmapStore(path) + b := newLegacyC11FileStore(path) if _, _, ok, err := b.Load(); ok || err != nil { t.Fatalf("empty store: ok %v err %v", ok, err) } @@ -30,7 +30,7 @@ func TestFileChunkBitmapStore_RoundTripAndReopen(t *testing.T) { t.Fatal(err) } // A new instance reads exactly the durable state. - b2 := NewFileChunkBitmapStore(path) + b2 := newLegacyC11FileStore(path) hdr, dirty, ok, err = b2.Load() if !ok || err != nil || hdr != want || !reflect.DeepEqual(dirty, []uint64{7}) { t.Fatalf("reopened: ok %v err %v hdr %+v dirty %v", ok, err, hdr, dirty) @@ -41,9 +41,9 @@ func TestFileChunkBitmapStore_RoundTripAndReopen(t *testing.T) { } } -func TestFileChunkBitmapStore_CorruptStateIsLost(t *testing.T) { +func TestLegacyC11FileCodec_CorruptStateIsLost(t *testing.T) { path := filepath.Join(t.TempDir(), "vol.chunkbitmap") - b := NewFileChunkBitmapStore(path) + b := newLegacyC11FileStore(path) if err := b.Save([]uint64{1}); err != nil { t.Fatal(err) } @@ -55,17 +55,17 @@ func TestFileChunkBitmapStore_CorruptStateIsLost(t *testing.T) { if err := os.WriteFile(path, raw, 0o600); err != nil { t.Fatal(err) } - if _, _, ok, err := NewFileChunkBitmapStore(path).Load(); ok || err != nil { + if _, _, ok, err := newLegacyC11FileStore(path).Load(); ok || err != nil { t.Fatalf("corrupt state: ok %v err %v, want ok=false (hash-compare fallback) and no error", ok, err) } } -// The layer with the production file bitmap and the in-memory remote: -// after a crash the first cut is incremental and exact. -func TestChunkLayer_FileBitmapIncrementalAfterRestart(t *testing.T) { +// The mapped layer and the in-memory remote: after a crash the owned map +// makes the first cut incremental and exact, without a C11 file sidecar. +func TestChunkLayer_OwnedMapIncrementalAfterRestart(t *testing.T) { s, path, crash := crashableStore(t) remote := NewMemChunkRemote() - cfg := chunkLayerConfig{ChunkBlocks: ctChunkBlocks, Epoch: 1, Holder: "h", Bitmap: NewFileChunkBitmapStore(path + ".chunkbitmap")} + cfg := chunkLayerConfig{ChunkBlocks: ctChunkBlocks, Epoch: 1, Holder: "h"} layer := mustAttach(t, s, remote, cfg) w := newWriteLog() w.write(t, s, 1, 0x01) // chunk 0 @@ -73,15 +73,15 @@ func TestChunkLayer_FileBitmapIncrementalAfterRestart(t *testing.T) { if _, err := layer.Capture(context.Background()); err != nil { t.Fatal(err) } - w.write(t, s, 24, 0x24) // chunk 6, flushed: only the bitmap remembers it + w.write(t, s, 24, 0x24) // chunk 6, flushed: the owned map remembers it mustSyncFlush(t, s) w.write(t, s, 28, 0x28) // chunk 7, WAL only if _, err := s.Sync(); err != nil { t.Fatal(err) } + assertNoC11Sidecars(t, path) crash() s2, _ := reopen(t, path) - cfg.Bitmap = NewFileChunkBitmapStore(path + ".chunkbitmap") // a fresh instance reads the file layer2 := mustAttach(t, s2, remote, cfg) before := remote.Puts() h, err := layer2.Capture(context.Background()) @@ -104,4 +104,14 @@ func TestChunkLayer_FileBitmapIncrementalAfterRestart(t *testing.T) { copy(img[int(idx)*ctChunkBytes:], b) } assertImage(t, "HEAD image after restart", img, w.imageAt(h)) + assertNoC11Sidecars(t, path) +} + +func assertNoC11Sidecars(t *testing.T, path string) { + t.Helper() + for _, suffix := range []string{".chunkbitmap", ".chunkbitmap.deltas"} { + if _, err := os.Stat(path + suffix); !os.IsNotExist(err) { + t.Fatalf("C11 sidecar %s: got %v, want absent", suffix, err) + } + } } diff --git a/seaweed-block/core/storage/chunk_candidates_v3_test.go b/seaweed-block/core/storage/chunk_candidates_v3_test.go new file mode 100644 index 0000000000..206e5b5590 --- /dev/null +++ b/seaweed-block/core/storage/chunk_candidates_v3_test.go @@ -0,0 +1,37 @@ +package storage + +import "testing" + +func TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + f := newFakeChunkRemote() + l := mustAttach(t, s, f, ctConfig(1)) + if _, err := s.Write(1, blk(1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if s.dm.len() != 1 { + t.Fatal("control requires the captured WAL entry still retained in dirty map") + } + if d := l.Stats().DirtyChunks; d != 0 { + t.Fatalf("already captured WAL counts as dirty: %d", d) + } + if _, err := s.Write(1, blk(2)); err != nil { + t.Fatal(err) + } + if d := l.Stats().DirtyChunks; d != 1 { + t.Fatalf("post-HEAD write missing: %d", d) + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if got := f.imageOf(t, r.Head)[ctBlockSize]; got != 2 { + t.Fatalf("post-HEAD write lost: %d", got) + } +} diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go new file mode 100644 index 0000000000..96cc435bc5 --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -0,0 +1,598 @@ +package storage + +// Cut-window ownership. Lock order: layer.cowMu -> window.mu -> entry.mu. +// None of these locks spans a read, side-store I/O, wait, or store lock. +// captureMu shared covers the write hook, but lifecycleMu is acquired AFTER it. +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "math" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "time" +) + +const cutCOWMemoryLimit = 64 << 20 + +// defaultCOWSpillLimit caps a copy window's side-file bytes by default. +const defaultCOWSpillLimit = 1 << 30 +const ( + cowPending uint8 = iota + cowCopying + cowSaving + cowSaved + cowDone +) + +var errCutCOWAborted = errors.New("storage: cut copy window aborted; retry cut") + +type cutCOWEntry struct { + mu sync.Mutex + state uint8 + ready chan struct{} + data []byte + slot int64 + spilled bool + readingSaved bool + // missing lists the block offsets that were lazily absent when the bytes + // were captured: their image at H is HEAD's, filled by the copier from the + // cut's base HEAD after it released the entry (never under a guest write). + missing []uint64 +} +type cutCOWWindow struct { + layer *chunkLayerImpl + mu sync.Mutex + terminal bool + err error + ended chan struct{} + refs sync.WaitGroup // Add under mu, only while OPEN; Wait only after terminal + sideReady chan struct{} + cleanupErr error + entries map[uint64]*cutCOWEntry + head map[uint64]chunkRef // the cut's base HEAD: the source of missing blocks + memory int64 + spillBytes int64 // bytes written to the side file; at most spillLimit + spillLimit int64 + chunkBytes int64 + side *os.File + sideErr error + cleanup sync.Once + saved atomic.Int64 + saveNs atomic.Int64 + waitNs atomic.Int64 + // Scheduling/fault controls are nil in production and set before installation. +} + +func (s *WALStore) beforeChunkMutation(first, count uint64) { + if h := s.chunk.Load(); h != nil && h.beforeMutation != nil { + h.beforeMutation(first, count) + } +} + +// Return with the requested capture barrier held. A first attach that races the +// optimistic hook snapshot forces admission/drain to be repeated with its hooks. +func (s *WALStore) holdChunkDestructive(exclusive bool) func() { + for { + h := s.chunk.Load() + if hook := s.testDestructiveSnapshot; hook != nil { + hook() + } + var release func() + if h != nil && h.beforeDestructive != nil { + release = h.beforeDestructive() + } + if exclusive { + s.captureMu.Lock() + } else { + s.captureMu.RLock() + } + if s.chunk.Load() == h { + return func() { + if exclusive { + s.captureMu.Unlock() + } else { + s.captureMu.RUnlock() + } + if release != nil { + release() + } + } + } + if exclusive { + s.captureMu.Unlock() + } else { + s.captureMu.RUnlock() + } + if release != nil { + release() + } + } +} + +func (l *chunkLayerImpl) holdCOWDestructive() func() { + l.cowMu.Lock() + l.cowTransitions++ + w := l.cow + if w != nil { + w.abort(errCutCOWAborted) + } + l.cowMu.Unlock() + if w != nil { + w.join() + } + return func() { l.cowMu.Lock(); l.cowTransitions--; l.cowMu.Unlock() } +} + +// The caller owns captureMu exclusive, so no writer can miss this publication. +func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef) (*cutCOWWindow, error) { + size := uint64(l.blockSize) * l.chunkBlocks + if size == 0 || size > math.MaxInt64 || uint64(len(candidates)) > math.MaxInt64/size { + return nil, fmt.Errorf("%w: side-store geometry", errCutCOWAborted) + } + w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: l.cfg.COWSpillLimit, chunkBytes: int64(size)} + var slot int64 + for _, idx := range sortedKeys(candidates) { + state := cowPending + if staged[idx] { + state = cowDone + } + w.entries[idx] = &cutCOWEntry{state: state, ready: make(chan struct{}), slot: slot} + slot++ + } + l.cowMu.Lock() + defer l.cowMu.Unlock() + if l.cowClosed || l.cowTransitions != 0 { + return nil, errCutCOWAborted + } + l.cow = w + l.cowActive.Store(w) + return w, nil +} + +func (w *cutCOWWindow) abort(err error) { + w.mu.Lock() + if !w.terminal { + w.terminal, w.err = true, fmt.Errorf("%w: %w", errCutCOWAborted, err) + close(w.ended) + } + w.mu.Unlock() +} +func (w *cutCOWWindow) join() error { + w.refs.Wait() + // Only terminal windows are joined. Saved readers never outlive their ref. + w.cleanup.Do(func() { + if w.side != nil { + name := w.side.Name() + w.cleanupErr = errors.Join(w.side.Close(), os.Remove(name)) + } + for _, e := range w.entries { + e.data = nil + } + }) + return w.cleanupErr +} +func (w *cutCOWWindow) status() error { w.mu.Lock(); defer w.mu.Unlock(); return w.err } + +// A nil result without a notification means done/terminal. Waiters own a +// lifetime reference through wakeup/accounting, never an entry or I/O lock. +func (w *cutCOWWindow) claim(idx uint64, saving bool) (*cutCOWEntry, uint8, <-chan struct{}) { + w.mu.Lock() + defer w.mu.Unlock() + if w.terminal { + return nil, cowDone, nil + } + e := w.entries[idx] + if e == nil { + return nil, cowDone, nil + } + e.mu.Lock() + defer e.mu.Unlock() + state := e.state + switch state { + case cowPending: + if saving { + e.state = cowSaving + } else { + e.state = cowCopying + } + w.refs.Add(1) + return e, state, nil + case cowSaved: + if saving { + return nil, cowDone, nil + } // live bytes are already saved + if e.readingSaved { + w.refs.Add(1) + return nil, state, e.ready + } + e.readingSaved = true + w.refs.Add(1) + return e, state, nil + case cowSaving, cowCopying: + // Waiters acquire while OPEN too: drain includes their accounting + // before the coordinator snapshots aggregate wait time. + w.refs.Add(1) + return nil, state, e.ready + default: + return nil, cowDone, nil + } +} +func (w *cutCOWWindow) finish(e *cutCOWEntry, state uint8) bool { + w.mu.Lock() + defer w.mu.Unlock() + e.mu.Lock() + defer e.mu.Unlock() + if w.terminal { + return false + } + e.state = state + e.readingSaved = false + close(e.ready) + e.ready = make(chan struct{}) + return true +} +func (w *cutCOWWindow) wait(ch <-chan struct{}) { + defer w.refs.Done() + start := time.Now() + if hook := w.layer.testCOWWait; hook != nil { + hook() + } + select { + case <-ch: + case <-w.ended: + } + w.waitNs.Add(time.Since(start).Nanoseconds()) +} + +func (l *chunkLayerImpl) beforeCOWMutation(first, count uint64) { + w := l.cowActive.Load() + if w == nil || count == 0 { + return + } + last := (first + count - 1) / l.chunkBlocks + for idx := first / l.chunkBlocks; idx <= last; idx++ { + for { + e, _, wait := w.claim(idx, true) + if wait != nil { + w.wait(wait) + continue + } + if e == nil { + break + } + start := time.Now() + // Local blocks only: a guest write never waits on SeaweedFS. + data, missing, err := l.readCOWChunk(w, idx) + if err == nil { + err = w.save(e, data, missing) + } + if err != nil { + w.abort(err) + } else if w.finish(e, cowSaved) { + w.saved.Add(1) + } + w.saveNs.Add(time.Since(start).Nanoseconds()) + // In particular an aborting saver releases itself BEFORE anyone joins. + w.refs.Done() + break + } + } +} + +func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte, missing []uint64) error { + if hook := w.layer.testCOWSave; hook != nil { + if err := hook(); err != nil { + return err + } + } + w.mu.Lock() + if w.terminal { + w.mu.Unlock() + return errCutCOWAborted + } + inMemory := w.memory+w.chunkBytes <= cutCOWMemoryLimit + if inMemory { + w.memory += w.chunkBytes + } else if w.spillBytes+w.chunkBytes > w.spillLimit { + // The side file is sparse but its saved chunks are real bytes on the + // volume's filesystem: abort the cut (retried) instead of filling it. + w.mu.Unlock() + return fmt.Errorf("%w: COW spill would exceed its cap of %d bytes", errCutCOWAborted, w.spillLimit) + } else { + w.spillBytes += w.chunkBytes + } + w.mu.Unlock() + // e.missing (and e.data / the spilled bytes) are published to readers by + // w.finish(e, cowSaved), which takes w.mu and e.mu after these writes: a + // copier reads them only after claiming the entry in state cowSaved. + e.missing = missing + if inMemory { + e.data = data + return nil + } + if err := w.openSide(); err != nil { + return err + } + if w.sideErr != nil { + return w.sideErr + } + n, err := w.side.WriteAt(data, e.slot*w.chunkBytes) + if err == nil && n != len(data) { + err = fmt.Errorf("short COW side write: %d/%d", n, len(data)) + } + e.spilled = true + return err +} + +// readCOWChunk reads chunk idx's LOCAL blocks and never fetches: a block that +// is lazily absent (no local version, HEAD names the chunk) is left zero and +// listed in missing; its image at H is HEAD's by definition. +func (l *chunkLayerImpl) readCOWChunk(w *cutCOWWindow, idx uint64) ([]byte, []uint64, error) { + buf := make([]byte, int(w.chunkBytes)) + var missing []uint64 + for i := uint64(0); i < l.chunkBlocks; i++ { + select { + case <-w.ended: + return nil, nil, errCutCOWAborted + default: + } + lba := idx*l.chunkBlocks + i + if lba >= uint64(l.s.NumBlocks()) { + break + } + b, local, err := l.readLocalBlock(lba) + if err != nil { + return nil, nil, err + } + if !local { + missing = append(missing, i) + continue + } + copy(buf[int(i)*l.blockSize:], b) + } + return buf, missing, nil +} + +// readLocalBlock reads lba unless it is lazily absent (local=false): the dirty +// map/WAL first, then the extent of a present block (or of a block written +// since its chunk became absent), zeros for an absent chunk HEAD stores as +// ZERO. It never calls the miss hook. The order is safe against a concurrent +// flush (dirty map before presence) and fill (HEAD's bytes either way); a new +// write of the block waits for the caller's COW entry. +func (l *chunkLayerImpl) readLocalBlock(lba uint64) ([]byte, bool, error) { + s := l.s + if s.v3 != nil { + if data, handled, err := s.readDirtyV3(uint32(lba)); handled { + return data, err == nil, err + } + } else if walRelOff, dataOffset, _, _, ok := s.dm.get(lba); ok { + data, err := s.readFromWAL(walRelOff, dataOffset) + return data, err == nil, err + } + idx := l.chunkOf(lba) + l.stMu.Lock() + absent := l.absent[idx] && !l.localBlocks[lba] + _, inHead := l.head.Chunks[idx] + l.stMu.Unlock() + if absent && inHead { + return nil, false, nil + } + if absent { + return make([]byte, l.blockSize), true, nil + } + data, err := s.readExtentBlock(uint32(lba)) + return data, err == nil, err +} + +// fillMissing completes a COW capture: the blocks listed missing get the cut's +// base HEAD bytes. It runs with no entry held (no guest waits on it), bounded +// by ReadMissTimeout and the window's end. +func (l *chunkLayerImpl) fillMissing(w *cutCOWWindow, idx uint64, data []byte, missing []uint64) ([]byte, error) { + ref, ok := w.head[idx] + if !ok { + return nil, fmt.Errorf("storage: cut chunk %d: %d lazily absent block(s) but HEAD has no chunk", idx, len(missing)) + } + ctx, cancel := context.WithTimeout(l.ctx, l.cfg.ReadMissTimeout) + defer cancel() + go func() { + select { + case <-w.ended: + cancel() + case <-ctx.Done(): + } + }() + head, err := l.remote.Get(ctx, ref.Key) + if err != nil { + return nil, fmt.Errorf("storage: cut chunk %d HEAD fetch: %w", idx, err) + } + if sha256.Sum256(head) != ref.SHA256 || len(head) != int(l.chunkBlocks)*l.blockSize { + return nil, fmt.Errorf("storage: cut chunk %d HEAD fetch: content does not match HEAD", idx) + } + out := append([]byte(nil), data...) + for _, i := range missing { + copy(out[int(i)*l.blockSize:int(i+1)*l.blockSize], head[int(i)*l.blockSize:int(i+1)*l.blockSize]) + } + return out, nil +} + +func (l *chunkLayerImpl) copyCOWEntry(w *cutCOWWindow, idx uint64) (capturedChunk, bool, error) { + for { + if err := l.admit(); err != nil { + w.abort(err) + return capturedChunk{}, false, err + } + e, state, wait := w.claim(idx, false) + if wait != nil { + w.wait(wait) + continue + } + if e == nil { + return capturedChunk{}, false, w.status() + } + var data []byte + var missing []uint64 + var err error + if state == cowSaved { + missing = e.missing + if e.spilled { + data = make([]byte, int(w.chunkBytes)) + _, err = w.side.ReadAt(data, e.slot*w.chunkBytes) + } else { + data = e.data + } + } else { + data, missing, err = l.readCOWChunk(w, idx) + } + if hook := l.testCOWRead; hook != nil { + hook(idx, state == cowSaved) + } + if err == nil { + err = l.admit() + } + if err != nil { + w.abort(err) + } + kept := false + if err == nil { + kept = w.finish(e, cowDone) + } + if kept && len(missing) > 0 { + // The entry is released: guests no longer wait on this chunk. + if data, err = l.fillMissing(w, idx, data, missing); err != nil { + w.abort(err) + kept = false + } + } + w.refs.Done() + if !kept { + return capturedChunk{}, false, w.status() + } + return capturedChunk{idx: idx, data: data, sum: sha256.Sum256(data), zero: isAllZero(data)}, true, nil + } +} + +func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow) ([]capturedChunk, error) { + stop := context.AfterFunc(ctx, func() { w.abort(ctx.Err()) }) + defer stop() + defer func() { + w.abort(errCutCOWAborted) + w.join() + l.cowMu.Lock() + if l.cow == w { + l.cow = nil + l.cowActive.Store(nil) + } + l.cowMu.Unlock() + }() + indices := make(map[uint64]bool, len(w.entries)) + for idx := range w.entries { + indices[idx] = true + } + keys := sortedKeys(indices) + out := make([]capturedChunk, len(keys)) + kept := make([]bool, len(keys)) + var next atomic.Int64 + var workers sync.WaitGroup + for n := 0; n < min(l.cfg.UploadConcurrency, len(keys)); n++ { + workers.Add(1) + go func() { + defer workers.Done() + for { + i := int(next.Add(1) - 1) + if i >= len(keys) { + return + } + c, ok, err := l.copyCOWEntry(w, keys[i]) + if err != nil { + return + } + out[i], kept[i] = c, ok + } + }() + } + workers.Wait() + w.mu.Lock() + if !w.terminal { + w.terminal = true + close(w.ended) + } + err := w.err + w.mu.Unlock() + cleanupErr := w.join() + if cleanupErr != nil { + err = errors.Join(err, errCutCOWAborted, cleanupErr) + } + if err != nil { + return nil, err + } + var result []capturedChunk + for i, c := range out { + if kept[i] { + result = append(result, c) + } + } + return result, nil +} + +// Creation is single-owner, but no allocation/lifetime lock spans filesystem I/O. +func (w *cutCOWWindow) openSide() error { + w.mu.Lock() + if w.sideReady != nil { + ready := w.sideReady + w.mu.Unlock() + select { + case <-ready: + return w.sideErr + case <-w.ended: + return errCutCOWAborted + } + } + w.sideReady = make(chan struct{}) + w.mu.Unlock() + side, err := os.CreateTemp(filepath.Dir(w.layer.s.path), filepath.Base(w.layer.s.path)+".cut-cow-") + w.mu.Lock() + w.side, w.sideErr = side, err + close(w.sideReady) + w.mu.Unlock() + return err +} + +// Called only by an exclusive, locked RW open. Side payloads are never decoded +// or imported, and directories/symlinks/other volume prefixes are untouched. +func discardCutCOWFiles(path string) error { + dir := filepath.Dir(path) + entries, err := os.ReadDir(dir) + if err != nil { + return err + } + prefix := filepath.Base(path) + ".cut-cow-" + for _, e := range entries { + if !strings.HasPrefix(e.Name(), prefix) || !e.Type().IsRegular() { + continue + } + // Type zero includes regular files only; Info also protects unknown dir types. + info, err := e.Info() + if err != nil { + return err + } + if !info.Mode().IsRegular() { + continue + } + if err := os.Remove(filepath.Join(dir, e.Name())); err != nil { + return err + } + } + return nil +} + +// Called only after releasing stMu; it invalidates without joining its caller. +func (l *chunkLayerImpl) abortCOW(err error) { + if w := l.cowActive.Load(); w != nil { + w.abort(err) + } +} diff --git a/seaweed-block/core/storage/chunk_cut_cow_bench_test.go b/seaweed-block/core/storage/chunk_cut_cow_bench_test.go new file mode 100644 index 0000000000..e659de4425 --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_cow_bench_test.go @@ -0,0 +1,135 @@ +package storage + +import ( + "context" + "fmt" + "path/filepath" + "runtime" + "sort" + "sync" + "testing" + "time" +) + +// File-backed backend proxy, not a guest/mount benchmark. Writers are released +// by the actual Sync/H handshake and issue one 4K write+Sync each per cut. +// This file is intentionally source-identical on the parent comparison ref. +func BenchmarkCutCOWProxy(b *testing.B) { + for _, chunks := range []int{8, 64} { + for _, qd := range []int{1, 8} { + b.Run(fmt.Sprintf("chunks%d/QD%d", chunks, qd), func(b *testing.B) { + const blocksPerChunk = 1024 + s, err := CreateWALStoreWithOptions(filepath.Join(b.TempDir(), "volume"), uint32(chunks*blocksPerChunk), 4096, WALStoreOptions{ChunkBlocks: blocksPerChunk}) + if err != nil { + b.Fatal(err) + } + b.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + if _, err = s.Recover(); err != nil { + b.Fatal(err) + } + remote := NewMemChunkRemote() + layer, err := AttachChunkLayer(s, remote, ChunkLayerConfig{ChunkBlocks: blocksPerChunk, Epoch: 1, Holder: "proxy", UploadConcurrency: 8, FreshFromHead: true}) + if err != nil { + b.Fatal(err) + } + l := layer.(*chunkLayerImpl) + if _, err = l.Cut(context.Background()); err != nil { + b.Fatal(err) + } + var latencies []int64 + var barrier, copyNs, syncNs, total, uploads, bytes int64 + b.ResetTimer() + b.StopTimer() + for n := 0; n < b.N; n++ { + data := makeBlock(4096, byte(1+n%100)) + for c := 0; c < chunks; c++ { + if _, err = s.Write(uint32(c*blocksPerChunk), data); err != nil { + b.Fatal(err) + } + } + if _, err = s.Sync(); err != nil { + b.Fatal(err) + } + if err = s.flusher.flushOnce(); err != nil { + b.Fatal(err) + } + start := make(chan struct{}) + done := make(chan struct{}) + durations := make([]int64, qd) + errs := make([]error, qd) + l.testAfterBarrierSyncHook = func(uint64) { close(start) } + var wg sync.WaitGroup + for writer := 0; writer < qd; writer++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + <-start + t := time.Now() + _, e := s.Write(uint32((chunks-1-i%chunks)*blocksPerChunk+1), makeBlock(4096, byte(0xa0+i))) + if e == nil { + _, e = s.Sync() + } + durations[i] = time.Since(t).Nanoseconds() + errs[i] = e + }(writer) + } + go func() { wg.Wait(); close(done) }() + b.StartTimer() + r, e := l.Cut(context.Background()) + b.StopTimer() + select { + case <-done: + case <-time.After(30 * time.Second): + stack := make([]byte, 1<<20) + nn := runtime.Stack(stack, true) + b.Fatalf("proxy writers stalled\n%s", stack[:nn]) + } + if e != nil { + b.Fatal(e) + } + for _, e := range errs { + if e != nil { + b.Fatal(e) + } + } + l.testAfterBarrierSyncHook = nil + latencies = append(latencies, durations...) + barrier += r.Stats.BarrierPauseNs + copyNs += r.Stats.CopyNs + syncNs += r.Stats.SyncNs + total += r.Stats.TotalNs + uploads += int64(r.Stats.UploadedChunks) + bytes += r.Stats.UploadedBytes + // The proxy is not measuring retained old remote versions. Retain only + // current HEAD objects between iterations, identically in both arms. + remote.mu.Lock() + live := map[string]bool{} + for _, ref := range remote.head.Chunks { + live[ref.Key] = true + } + for key := range remote.objs { + if !live[key] { + delete(remote.objs, key) + } + } + remote.mu.Unlock() + } + sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] }) + percentile := func(p int) float64 { + i := (len(latencies)*p+99)/100 - 1 + if i < 0 { + i = 0 + } + return float64(latencies[i]) + } + b.ReportMetric(percentile(50), "writer-p50-ns") + b.ReportMetric(percentile(99), "writer-p99-ns") + b.ReportMetric(float64(latencies[len(latencies)-1]), "writer-max-ns") + for name, value := range map[string]int64{"barrier-ns": barrier, "copy-ns": copyNs, "sync-ns": syncNs, "cut-ns": total, "uploaded-chunks": uploads, "uploaded-bytes": bytes} { + b.ReportMetric(float64(value)/float64(b.N), name) + } + }) + } + } +} diff --git a/seaweed-block/core/storage/chunk_cut_cow_fill_test.go b/seaweed-block/core/storage/chunk_cut_cow_fill_test.go new file mode 100644 index 0000000000..194f9a4e09 --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_cow_fill_test.go @@ -0,0 +1,149 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "strings" + "sync" + "testing" + "time" +) + +// lazyChunk2Fixture: HEAD holds chunk 2 (LBA 8-11); the volume is fresh from +// HEAD (every chunk absent) and LBA 8 is written locally, so chunk 2 is a +// partly absent cut candidate. +func lazyChunk2Fixture(t *testing.T, readMiss time.Duration) (*WALStore, *chunkLayerImpl, *fakeChunkRemote, []byte, []byte) { + t.Helper() + src := make([]byte, ctNumBlocks*ctBlockSize) + for lba := uint32(8); lba < 12; lba++ { + copy(src[int(lba)*ctBlockSize:], makeBlock(ctBlockSize, byte(0x80+lba))) + } + f := newFakeChunkRemote() + f.seedHead(t, src, 10, 1) + s, _ := newChunkTestStore(t) + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + cfg.ReadMissTimeout = readMiss + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + local := makeBlock(ctBlockSize, 0xD8) + if _, err := s.Write(8, local); err != nil { + t.Fatal(err) + } + return s, l, f, src, local +} + +// The copier's HEAD fill (after it released the entry) is cancelled by an +// aborted cut: the cut returns promptly, the window is drained, and the next +// cut publishes the right image. +func TestCutCOWV3_HeldFillIsCancelledByAbortAndDrained(t *testing.T) { + _, l, f, src, local := lazyChunk2Fixture(t, time.Minute) + gEntered, gRelease := holdGets(t, f) + t.Cleanup(gRelease) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { _, err := l.Cut(ctx); done <- err }() + waitKey(t, gEntered, "the copier's HEAD fill of chunk 2") + cancel() + err := waitErr(t, done, "aborted cut with a held fill") + if err == nil || !(errors.Is(err, context.Canceled) || errors.Is(err, errCutCOWAborted)) { + t.Fatalf("cut aborted during a held fill: %v, want cancellation", err) + } + if w := l.cowActive.Load(); w != nil { + t.Fatal("copy window not drained after the abort") + } + gRelease() + r, err := l.Cut(context.Background()) + if err != nil { + t.Fatal("next cut:", err) + } + img := f.imageOf(t, r.Head) + if !bytes.Equal(blockOf(img, 8), local) || !bytes.Equal(blockOf(img, 9), blockOf(src, 9)) { + t.Fatal("next cut lost the local block or HEAD's bytes for the absent ones") + } +} + +// A held fill is bounded by ReadMissTimeout: the cut aborts (retryable) instead +// of waiting, and the window is drained. +func TestCutCOWV3_HeldFillTimesOutAndAborts(t *testing.T) { + _, l, f, _, _ := lazyChunk2Fixture(t, 200*time.Millisecond) + _, gRelease := holdGets(t, f) + t.Cleanup(gRelease) + done := make(chan error, 1) + go func() { _, err := l.Cut(context.Background()); done <- err }() + err := waitErr(t, done, "cut with a held fill past ReadMissTimeout") + if !errors.Is(err, errCutCOWAborted) || !errors.Is(err, context.DeadlineExceeded) || !strings.Contains(err.Error(), "HEAD fetch") { + t.Fatalf("cut with a timed-out fill: %v, want an aborted cut naming the HEAD fetch deadline", err) + } + if w := l.cowActive.Load(); w != nil { + t.Fatal("copy window not drained after the fill timeout") + } +} + +// Image control for the spill path: a saved chunk with lazily-absent blocks +// spills its local bytes and its missing list; the copier fills the missing +// blocks from HEAD, and the image is exact. +func TestCutCOWV3_LazySaverSpillImageIsExact(t *testing.T) { + s, _ := newChunkTestStore(t) + source := make([]byte, ctNumBlocks*ctBlockSize) + for lba := 0; lba < 8; lba++ { + copy(source[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x30+lba))) + } + f := newFakeChunkRemote() + f.seedHead(t, source, 0, 1) + cfg := ctConfig(2) + cfg.Bitmap = nil + cfg.FreshFromHead = true + cfg.BarrierBound = 0 + cfg.UploadConcurrency = 1 + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + if _, err := s.Write(1, makeBlock(ctBlockSize, 0x51)); err != nil { + t.Fatal(err) + } + if _, err := s.WriteBatch(4, [][]byte{makeBlock(ctBlockSize, 0x54), makeBlock(ctBlockSize, 0x55)}); err != nil { + t.Fatal(err) + } + live, releaseLive := make(chan struct{}), make(chan struct{}) + var once, relOnce sync.Once + unblock := func() { relOnce.Do(func() { close(releaseLive) }) } + var w *cutCOWWindow + l.testCOWRead = func(idx uint64, _ bool) { + if idx == 0 { + once.Do(func() { + w = l.cowActive.Load() + w.mu.Lock() + w.memory = cutCOWMemoryLimit // the next save spills + w.mu.Unlock() + close(live) + }) + <-releaseLive + } + } + cutDone := make(chan error, 1) + t.Cleanup(unblock) + go func() { _, err := l.Cut(context.Background()); cutDone <- err }() + cowWaitSignal(t, live, "the window open, chunk 0 held") + if _, err := s.Write(6, makeBlock(ctBlockSize, 0x96)); err != nil { + t.Fatal(err) + } + w.mu.Lock() + spilled := w.side != nil + w.mu.Unlock() + if !spilled { + t.Fatal("the save did not spill") + } + unblock() + if err := waitErr(t, cutDone, "spilled lazy cut"); err != nil { + t.Fatal(err) + } + want := append([]byte(nil), source...) + for lba, value := range map[int]byte{1: 0x51, 4: 0x54, 5: 0x55} { + copy(want[lba*ctBlockSize:], makeBlock(ctBlockSize, value)) + } + if !bytes.Equal(f.imageOf(t, f.stats().head), want) { + t.Fatal("spilled COW save lost local bytes or HEAD's bytes for its missing blocks") + } +} diff --git a/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go b/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go new file mode 100644 index 0000000000..a6f9473ea1 --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go @@ -0,0 +1,861 @@ +package storage + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" +) + +// These fixtures use the public v3 factory, real reads/WAL/flusher, and actual +// cut/write/recovery/close callers. Hooks only hold an identified I/O boundary. +func cowFixture(t *testing.T) (*WALStore, *chunkLayerImpl, *fakeChunkRemote, *cowReadGate) { + t.Helper() + gate := &cowReadGate{entered: make(chan struct{}), release: make(chan struct{})} + s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), ctNumBlocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks, MetadataFactory: func(_ BlockMetadataFile, layout BlockMetadataLayout) (BlockMetadataBinding, error) { + return BlockMetadataBinding{ImplVersion: layout.ImplVersion, Hook: gate}, nil + }}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { gate.unblock(); _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + if _, err = s.Recover(); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.Bitmap = nil + cfg.BarrierBound = 0 + cfg.UploadConcurrency = 1 + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + if _, err = l.Cut(context.Background()); err != nil { + t.Fatal(err) + } + for _, lba := range []uint32{1, 5} { + if _, err = s.Write(lba, makeBlock(ctBlockSize, byte(lba))); err != nil { + t.Fatal(err) + } + } + if _, err = s.Sync(); err != nil { + t.Fatal(err) + } + if err = s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + gate.mu.Lock() + gate.armed = true + gate.mu.Unlock() + return s, l, f, gate +} +func cowStartCut(t *testing.T, l *chunkLayerImpl, gate *cowReadGate) (<-chan struct{}, <-chan error) { + t.Helper() + done := make(chan struct{}) + errs := make(chan error, 1) + t.Cleanup(func() { gate.unblock(); cowWaitSignal(t, done, "cut cleanup") }) + go func() { defer close(done); _, err := l.Cut(context.Background()); errs <- err }() + cowWaitSignal(t, gate.entered, "live copier") + return done, errs +} + +func TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves(t *testing.T) { + s, l, f, gate := cowFixture(t) + waiting := make(chan struct{}) + var once sync.Once + l.testCOWWait = func() { once.Do(func() { close(waiting) }) } + cutDone, cutErr := cowStartCut(t, l, gate) + writeDone := make(chan struct{}) + var writeErr error + t.Cleanup(func() { gate.unblock(); cowWaitSignal(t, writeDone, "writer cleanup") }) + go func() { defer close(writeDone); _, writeErr = s.Write(1, makeBlock(ctBlockSize, 0xa1)) }() + cowWaitSignal(t, waiting, "same-chunk wait admission") + select { + case <-writeDone: + t.Fatal("copying chunk changed before old image finished") + default: + } + if _, err := s.Write(5, makeBlock(ctBlockSize, 0xa5)); err != nil { + t.Fatal(err) + } + gate.unblock() + cowWaitSignal(t, writeDone, "same-chunk write") + cowWaitSignal(t, cutDone, "cut") + if writeErr != nil { + t.Fatal(writeErr) + } + if err := <-cutErr; err != nil { + t.Fatal(err) + } + if l.Stats().LastCut.COWWaitNs <= 0 { + t.Fatal("drained window omitted its real wait time") + } + image := f.imageOf(t, f.stats().head) + if !bytes.Equal(image[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 1)) || !bytes.Equal(image[5*ctBlockSize:6*ctBlockSize], makeBlock(ctBlockSize, 5)) { + t.Fatal("torn or post-H cut image") + } +} + +func TestCutCOWV3_SaveFailureAbortsOnlyCut(t *testing.T) { + s, l, f, gate := cowFixture(t) + var calls atomic.Int32 + l.testCOWSave = func() error { calls.Add(1); return errors.New("injected side ENOSPC") } + before := f.stats().head + cutDone, cutErr := cowStartCut(t, l, gate) + if _, err := s.Write(5, makeBlock(ctBlockSize, 0xb5)); err != nil { + t.Fatalf("COW failure escaped into guest write: %v", err) + } + gate.unblock() + cowWaitSignal(t, cutDone, "aborted cut") + if err := <-cutErr; !errors.Is(err, errCutCOWAborted) { + t.Fatalf("cut error=%v", err) + } + if f.stats().head.Gen != before.Gen || calls.Load() != 1 { + t.Fatal("failed cut published or save not exercised") + } + l.testCOWSave = nil + r, err := l.Cut(context.Background()) + if err != nil { + t.Fatal(err) + } + image := f.imageOf(t, r.Head) + if !bytes.Equal(image[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 1)) || !bytes.Equal(image[5*ctBlockSize:6*ctBlockSize], makeBlock(ctBlockSize, 0xb5)) { + t.Fatal("retry lost original candidates or new dirt") + } +} + +func TestCutCOWV3_RecoveryAndCloseDrainSavingOwner(t *testing.T) { + for _, action := range []string{"Recover", "Reset", "LayerClose", "StoreClose", "Cancel"} { + t.Run(action, func(t *testing.T) { + s, l, _, gate := cowFixture(t) + saveEntered, saveRelease := make(chan struct{}), make(chan struct{}) + var once sync.Once + releaseSave := func() { once.Do(func() { close(saveRelease) }) } + l.testCOWSave = func() error { close(saveEntered); <-saveRelease; return nil } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + cutDone, writeDone, actionDone := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var writeErr, actionErr, cutErr error + actionStarted := false + t.Cleanup(func() { + releaseSave() + gate.unblock() + cowWaitSignal(t, writeDone, "save writer cleanup") + cowWaitSignal(t, cutDone, "cut cleanup") + if actionStarted { + cowWaitSignal(t, actionDone, "transition cleanup") + } + }) + go func() { defer close(cutDone); _, cutErr = l.Cut(ctx) }() + cowWaitSignal(t, gate.entered, "held copier") + w := l.cowActive.Load() + if w == nil { + t.Fatal("window not installed") + } + go func() { defer close(writeDone); _, writeErr = s.Write(5, makeBlock(ctBlockSize, 0xc5)) }() + cowWaitSignal(t, saveEntered, "saving owner") + actionStarted = true + go func() { + defer close(actionDone) + switch action { + case "Recover": + _, actionErr = s.Recover() + case "Reset": + actionErr = s.resetIncarnationV3() + case "LayerClose": + actionErr = l.Close() + case "StoreClose": + actionErr = s.Close() + case "Cancel": + cancel() + <-cutDone + } + }() + // Store Close first takes capture exclusive, held by the saver; release + // the actual saver for that arm before expecting layer/window cancellation. + if action == "StoreClose" { + releaseSave() + } + cowWaitSignal(t, w.ended, "terminal notification") + if action != "StoreClose" { + // ended is the real abort handshake, not a scheduling guess. + // Keep actual I/O held for this bounded non-completion check; + // an immediate default select could miss a no-join mutant. + select { + case <-actionDone: + t.Fatal("transition returned with saver/live copy still held") + case <-time.After(100 * time.Millisecond): + } + } + releaseSave() + gate.unblock() + cowWaitSignal(t, writeDone, "saving writer") + cowWaitSignal(t, cutDone, "aborted cut") + cowWaitSignal(t, actionDone, "transition") + if writeErr != nil { + t.Fatal(writeErr) + } + if cutErr == nil { + t.Fatal("terminal window published") + } + if actionErr != nil && action != "Reset" { + t.Fatal(actionErr) + } + if action == "Recover" || action == "Reset" || action == "Cancel" { + l.testCOWSave = nil + if _, err := l.Cut(context.Background()); err != nil { + t.Fatal(err) + } + } + }) + } +} + +func TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion(t *testing.T) { + s, _ := newChunkTestStore(t) + entered, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + s.testCloseSnapshot = func() { close(entered); <-release } + first, second := make(chan struct{}), make(chan struct{}) + t.Cleanup(func() { + unblock() + cowWaitSignal(t, first, "first close cleanup") + cowWaitSignal(t, second, "second close cleanup") + }) + go func() { defer close(first); _ = s.Close() }() + cowWaitSignal(t, entered, "Close stable snapshot") + go func() { defer close(second); _ = s.Close() }() + cfg := ctConfig(1) + cfg.Bitmap = nil + layer, err := attachChunkLayer(s, newFakeChunkRemote(), cfg) + if err == nil { + // Isolated missing-gate negative: the real first layer installs an + // OPEN window while Close is parked after its nil snapshot. No fake + // sentinel hook stands in for that snapshot. + l := layer.(*chunkLayerImpl) + live, releaseLive := make(chan struct{}), make(chan struct{}) + var liveOnce sync.Once + unblockLive := func() { liveOnce.Do(func() { close(releaseLive) }) } + l.testCOWRead = func(idx uint64, _ bool) { + if idx == 0 { + close(live) + <-releaseLive + } + } + cutDone := make(chan struct{}) + t.Cleanup(func() { unblockLive(); cowWaitSignal(t, cutDone, "missed first-attach cut"); _ = l.Close() }) + go func() { defer close(cutDone); _, _ = l.Cut(context.Background()) }() + cowWaitSignal(t, live, "missed first-attach live owner") + unblock() + cowWaitSignal(t, first, "Close after missing first attach") + select { + case <-cutDone: + default: + t.Error("Close returned before newly admitted live owner drained") + } + unblockLive() + t.Error("first attach admitted after permanent shutdown") + } else if !errors.Is(err, errChunkLayerClosed) { + t.Fatal(err) + } + select { + case <-second: + t.Fatal("second Close skipped the first drain") + default: + } + unblock() + cowWaitSignal(t, first, "first close") + cowWaitSignal(t, second, "second close") +} + +func TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped(t *testing.T) { + s, l, _, gate := cowFixture(t) + cutDone, cutErr := cowStartCut(t, l, gate) + w := l.cowActive.Load() + w.mu.Lock() + w.memory = cutCOWMemoryLimit + w.mu.Unlock() // force real file spill without a large volume + if _, err := s.Write(5, makeBlock(ctBlockSize, 0xd5)); err != nil { + t.Fatal(err) + } + w.mu.Lock() + side := w.side + w.mu.Unlock() + if side == nil { + t.Fatal("spill not exercised") + } + name := side.Name() + gate.unblock() + cowWaitSignal(t, cutDone, "spilled cut") + if err := <-cutErr; err != nil { + t.Fatal(err) + } + if _, err := os.Stat(name); !os.IsNotExist(err) { + t.Fatalf("side store survives terminal drain: %v", err) + } + path := s.path + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + stale := path + ".cut-cow-stale" + other := path + "-other.cut-cow-stale" + directory := path + ".cut-cow-dir" + if err := os.WriteFile(stale, []byte("corrupt side, not recovery input"), 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(other, []byte("other owner"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(directory, 0700); err != nil { + t.Fatal(err) + } + reopened, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + defer reopened.Close() + reopened.DisableAutoFlushForRecoveryTest() + if _, err = reopened.Recover(); err != nil { + t.Fatal(err) + } + if _, err = os.Stat(stale); !os.IsNotExist(err) { + t.Fatal("stale own side payload retained") + } + for _, p := range []string{other, directory} { + if _, err = os.Stat(p); err != nil { + t.Fatal("cleanup touched other data", err) + } + } + got, err := reopened.Read(5) + if err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, 0xd5)) { + t.Fatal("reopen trusted side payload or lost synced bytes", err) + } +} + +func TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader(t *testing.T) { + s, l, f, gate := cowFixture(t) + saved, releaseSave := make(chan struct{}), make(chan struct{}) + reader, releaseReader := make(chan struct{}), make(chan struct{}) + waiting := make(chan struct{}) + var waitOnce, saveOnce, readerOnce sync.Once + var saves atomic.Int32 + unblockSave := func() { saveOnce.Do(func() { close(releaseSave) }) } + unblockReader := func() { readerOnce.Do(func() { close(releaseReader) }) } + l.testCOWSave = func() error { saves.Add(1); close(saved); <-releaseSave; return nil } + l.testCOWWait = func() { waitOnce.Do(func() { close(waiting) }) } + l.testCOWRead = func(idx uint64, side bool) { + if idx == 1 && side { + close(reader) + <-releaseReader + } + } + cutDone, cutErr := cowStartCut(t, l, gate) + w := l.cowActive.Load() + w.mu.Lock() + w.memory = cutCOWMemoryLimit + w.mu.Unlock() + first, second, closeDone := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var err1, err2, closeErr error + closeStarted := false + t.Cleanup(func() { + unblockSave() + unblockReader() + gate.unblock() + cowWaitSignal(t, first, "first writer") + cowWaitSignal(t, second, "second writer") + if closeStarted { + cowWaitSignal(t, closeDone, "saved reader close") + } + }) + go func() { defer close(first); _, err1 = s.Write(5, makeBlock(ctBlockSize, 0xe1)) }() + cowWaitSignal(t, saved, "single saving owner") + go func() { defer close(second); _, err2 = s.Write(6, makeBlock(ctBlockSize, 0xe2)) }() + cowWaitSignal(t, waiting, "second writer waits on same chunk") + select { + case <-second: + t.Fatal("second writer bypassed saving owner") + default: + } + unblockSave() + cowWaitSignal(t, first, "first write") + cowWaitSignal(t, second, "second write") + if err1 != nil || err2 != nil || saves.Load() != 1 { + t.Fatalf("single owner: %v %v saves=%d", err1, err2, saves.Load()) + } + w.mu.Lock() + side := w.side + w.mu.Unlock() + if side == nil { + t.Fatal("saved read must use real spill file") + } + name := side.Name() + gate.unblock() + cowWaitSignal(t, reader, "actual saved-file read completed, reference held") + thirdDone := make(chan struct{}) + var thirdErr error + t.Cleanup(func() { unblockReader(); cowWaitSignal(t, thirdDone, "writer during saved-file read") }) + go func() { defer close(thirdDone); _, thirdErr = s.Write(7, makeBlock(ctBlockSize, 0xe3)) }() + cowWaitSignal(t, thirdDone, "saved chunk remains writable during saved-file read") + if thirdErr != nil { + t.Fatal(thirdErr) + } + closeStarted = true + go func() { defer close(closeDone); closeErr = l.Close() }() + cowWaitSignal(t, w.ended, "close aborts saved-reader window") + select { + case <-closeDone: + t.Fatal("Close returned before saved reader released") + case <-time.After(100 * time.Millisecond): + } + if _, err := os.Stat(name); err != nil { + t.Fatal("side removed before reader reference drained", err) + } + unblockReader() + cowWaitSignal(t, closeDone, "saved reader drain") + cowWaitSignal(t, cutDone, "aborted saved-read cut") + if closeErr != nil || <-cutErr == nil { + t.Fatal("Close/cut result", closeErr) + } + if _, err := os.Stat(name); !os.IsNotExist(err) { + t.Fatal("side survived saved-reader drain", err) + } + if f.stats().head.RemoteLSN >= s.NextLSN()-1 { + t.Fatal("aborted cut published post-H mutations") + } +} + +func TestCutCOWV3_ObservedFenceAbortsAndWakesWriters(t *testing.T) { + s, l, f, gate := cowFixture(t) + var fenced atomic.Bool + l.cfg.CaptureAllowed = func() error { + if fenced.Load() { + return errChunkLayerFenced + } + return nil + } + l.cfg.UploadConcurrency = 2 + other, releaseOther := make(chan struct{}), make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(releaseOther) }) } + l.testCOWRead = func(idx uint64, _ bool) { + if idx == 1 { + close(other) + <-releaseOther + } + } + cutDone, cutErr := cowStartCut(t, l, gate) + t.Cleanup(unblock) + cowWaitSignal(t, other, "second copier before ordinary authority recheck") + w := l.cowActive.Load() + before := f.stats().head.Gen + fenced.Store(true) + unblock() + cowWaitSignal(t, w.ended, "ordinary capture gate observes fence") + if _, err := s.Write(1, makeBlock(ctBlockSize, 0xf1)); err != nil { + t.Fatalf("COW fence refused ordinary write: %v", err) + } + select { + case <-cutDone: + t.Fatal("cut returned while live read reference held") + default: + } + gate.unblock() + cowWaitSignal(t, cutDone, "fenced cut drain") + if !errors.Is(<-cutErr, errCutCOWAborted) || f.stats().head.Gen != before { + t.Fatal("fenced window published") + } +} + +func TestCutCOWV3_InvalidInputsDoNotSaveOrAbortWindow(t *testing.T) { + s, l, _, gate := cowFixture(t) + var saves atomic.Int32 + l.testCOWSave = func() error { saves.Add(1); return errors.New("invalid input touched COW") } + cutDone, cutErr := cowStartCut(t, l, gate) + w := l.cowActive.Load() + if _, err := s.Write(ctNumBlocks, makeBlock(ctBlockSize, 1)); err == nil { + t.Fatal("invalid Write accepted") + } + if _, err := s.Write(5, []byte{1}); err == nil { + t.Fatal("short Write accepted") + } + if _, err := s.WriteBatch(ctNumBlocks-1, [][]byte{makeBlock(ctBlockSize, 1), makeBlock(ctBlockSize, 2)}); err == nil { + t.Fatal("invalid batch accepted") + } + if _, err := s.WriteBatch(5, nil); err != nil { + t.Fatal(err) + } + if err := s.ApplyEntry(5, []byte{1}, s.NextLSN()); err == nil { + t.Fatal("short Apply accepted") + } + if saves.Load() != 0 { + t.Fatal("invalid caller performed COW I/O") + } + select { + case <-w.ended: + t.Fatal("invalid input aborted cut") + default: + } + gate.unblock() + cowWaitSignal(t, cutDone, "valid cut after invalid requests") + if err := <-cutErr; err != nil { + t.Fatal(err) + } +} + +func TestCutCOWV3_OverlappingRealBatchesPreserveCut(t *testing.T) { + s, l, f, gate := cowFixture(t) + for _, lba := range []uint32{9, 13} { + if _, err := s.Write(lba, makeBlock(ctBlockSize, byte(lba))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + cutDone, cutErr := cowStartCut(t, l, gate) + var wg sync.WaitGroup + errs := make(chan error, 2) + done := make(chan struct{}) + t.Cleanup(func() { gate.unblock(); cowWaitSignal(t, done, "batch cleanup") }) + for _, start := range []uint32{5, 9} { + wg.Add(1) + go func(start uint32) { + defer wg.Done() + blocks := make([][]byte, 5) + for i := range blocks { + blocks[i] = makeBlock(ctBlockSize, byte(start)+0x80+byte(i)) + } + _, err := s.WriteBatch(start, blocks) + errs <- err + }(start) + } + go func() { wg.Wait(); close(done) }() + cowWaitSignal(t, done, "overlapping batches while earlier copy held") + for i := 0; i < 2; i++ { + if err := <-errs; err != nil { + t.Fatal(err) + } + } + gate.unblock() + cowWaitSignal(t, cutDone, "batch cut") + if err := <-cutErr; err != nil { + t.Fatal(err) + } + want := make([]byte, ctNumBlocks*ctBlockSize) + for _, lba := range []int{1, 5, 9, 13} { + copy(want[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(lba))) + } + if !bytes.Equal(f.imageOf(t, f.stats().head), want) { + t.Fatal("batch published into the pre-H cut") + } + // Both submitted batches assign the same literal bytes to overlapping + // LBAs (9). Derive the next HEAD oracle from those inputs, never local Read. + for lba := 5; lba <= 13; lba++ { + copy(want[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(lba)+0x80)) + } + r, err := l.Cut(context.Background()) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(f.imageOf(t, r.Head), want) { + t.Fatal("following cut lost overlapping batch writes") + } +} + +func TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment(t *testing.T) { + for _, reset := range []bool{false, true} { + t.Run(map[bool]string{false: "Recover", true: "Reset"}[reset], func(t *testing.T) { + s, _ := newChunkTestStore(t) + snapshot, release := make(chan struct{}), make(chan struct{}) + var once, releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + s.testDestructiveSnapshot = func() { once.Do(func() { close(snapshot); <-release }) } + done := make(chan struct{}) + var transitionErr error + t.Cleanup(func() { unblock(); cowWaitSignal(t, done, "first-attach transition cleanup") }) + go func() { + defer close(done) + if reset { + transitionErr = s.resetIncarnationV3() + } else { + _, transitionErr = s.Recover() + } + }() + cowWaitSignal(t, snapshot, "nil hook snapshot before barrier") + cfg := ctConfig(1) + cfg.Bitmap = nil + cfg.BarrierBound = 0 + cfg.UploadConcurrency = 1 + l := mustAttach(t, s, newFakeChunkRemote(), cfg).(*chunkLayerImpl) + live, releaseLive := make(chan struct{}), make(chan struct{}) + var liveOnce sync.Once + unblockLive := func() { liveOnce.Do(func() { close(releaseLive) }) } + l.testCOWRead = func(idx uint64, _ bool) { + if idx == 0 { + close(live) + <-releaseLive + } + } + cutDone := make(chan struct{}) + var cutErr error + t.Cleanup(func() { unblockLive(); cowWaitSignal(t, cutDone, "first attach cut cleanup") }) + go func() { defer close(cutDone); _, cutErr = l.Cut(context.Background()) }() + cowWaitSignal(t, live, "newly attached OPEN live-copy owner") + w := l.cowActive.Load() + unblock() + cowWaitSignal(t, w.ended, "hook snapshot retry aborts new window") + select { + case <-done: + t.Fatal("destructive path missed first attach's owner") + default: + } + unblockLive() + cowWaitSignal(t, cutDone, "first attach cut drain") + cowWaitSignal(t, done, "destructive retry") + if cutErr == nil { + t.Fatal("first-attach window survived destructive transition") + } + if transitionErr != nil { + t.Fatal(transitionErr) + } + }) + } +} + +// A process stop while OPEN deliberately bypasses all Close/abort cleanups. +// The parent gets the actual last remote HEAD, not a reconstructed proposal. +func TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage(t *testing.T) { + if path := os.Getenv("SWBLOCK_COW_CRASH_PATH"); path != "" { + gate := &cowReadGate{entered: make(chan struct{}), release: make(chan struct{})} + s, err := CreateWALStoreWithOptions(path, ctNumBlocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks, MetadataFactory: func(_ BlockMetadataFile, layout BlockMetadataLayout) (BlockMetadataBinding, error) { + return BlockMetadataBinding{ImplVersion: layout.ImplVersion, Hook: gate}, nil + }}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { gate.unblock(); _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + if _, err = s.Recover(); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.Bitmap = nil + cfg.BarrierBound = 0 + cfg.UploadConcurrency = 1 + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + baseline, err := l.Cut(context.Background()) + if err != nil { + t.Fatal(err) + } + for _, lba := range []uint32{1, 5} { + if _, err = s.Write(lba, makeBlock(ctBlockSize, byte(lba))); err != nil { + t.Fatal(err) + } + } + if _, err = s.Sync(); err != nil { + t.Fatal(err) + } + if err = s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + gate.mu.Lock() + gate.armed = true + gate.mu.Unlock() + cutDone, _ := cowStartCut(t, l, gate) + w := l.cowActive.Load() + w.mu.Lock() + w.memory = cutCOWMemoryLimit + w.mu.Unlock() + if _, err = s.Write(5, makeBlock(ctBlockSize, 0x77)); err != nil { + t.Fatal(err) + } + if _, err = s.Sync(); err != nil { + t.Fatal(err) + } + if w.side == nil { + t.Fatal("child has no live side file") + } + head := f.stats().head + if head.Gen != baseline.Head.Gen { + t.Fatal("OPEN cut already moved HEAD") + } + raw, err := json.Marshal(head) + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(path+".remote-head.json", raw, 0600); err != nil { + t.Fatal(err) + } + select { + case <-cutDone: + t.Fatal("cut not OPEN at crash") + default: + } + os.Exit(0) // intentional process crash: no cleanup runs + } + path := filepath.Join(t.TempDir(), "volume") + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage$", "-test.timeout=20s") + cmd.Env = append(os.Environ(), "SWBLOCK_COW_CRASH_PATH="+path) + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("crash child: %v: %s", err, output) + } + stale, err := filepath.Glob(path + ".cut-cow-*") + if err != nil || len(stale) != 1 { + t.Fatalf("OPEN crash did not leave one spill: %v %v", stale, err) + } + raw, err := os.ReadFile(path + ".remote-head.json") + if err != nil { + t.Fatal(err) + } + var head chunkHead + if err = json.Unmarshal(raw, &head); err != nil { + t.Fatal(err) + } + if head.RemoteLSN != 0 || len(head.Chunks) != 0 { + t.Fatal("OPEN crash changed old HEAD") + } + s, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + if _, err = s.Recover(); err != nil { + t.Fatal(err) + } + if got, err := s.Read(5); err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, 0x77)) { + t.Fatal("synced post-H write lost on reopen", err) + } + for _, name := range stale { + if _, err = os.Stat(name); !os.IsNotExist(err) { + t.Fatal("crash side not discarded", err) + } + } + f := newFakeChunkRemote() + f.head = head + cfg := ctConfig(1) + cfg.Bitmap = nil + cfg.BarrierBound = 0 + l := mustAttach(t, s, f, cfg) + r, err := l.Cut(context.Background()) + if err != nil { + t.Fatal(err) + } + want := make([]byte, ctNumBlocks*ctBlockSize) + copy(want[ctBlockSize:], makeBlock(ctBlockSize, 1)) + copy(want[5*ctBlockSize:], makeBlock(ctBlockSize, 0x77)) + if !bytes.Equal(f.imageOf(t, r.Head), want) { + t.Fatal("next cut imported stale side bytes") + } +} + +func TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD(t *testing.T) { + for _, flushed := range []bool{false, true} { + t.Run(map[bool]string{false: "WAL-only-batch", true: "flushed-batch"}[flushed], func(t *testing.T) { + s, _ := newChunkTestStore(t) + source := make([]byte, ctNumBlocks*ctBlockSize) + for lba := 0; lba < 8; lba++ { + copy(source[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x30+lba))) + } + f := newFakeChunkRemote() + f.seedHead(t, source, 0, 1) + cfg := ctConfig(2) + cfg.Bitmap = nil + cfg.FreshFromHead = true + cfg.BarrierBound = 0 + cfg.UploadConcurrency = 1 + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + if _, err := s.Write(1, makeBlock(ctBlockSize, 0x51)); err != nil { + t.Fatal(err) + } + if _, err := s.WriteBatch(4, [][]byte{makeBlock(ctBlockSize, 0x54), makeBlock(ctBlockSize, 0x55)}); err != nil { + t.Fatal(err) + } + if flushed { + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + } + live, releaseLive := make(chan struct{}), make(chan struct{}) + var once sync.Once + unblockLive := func() { once.Do(func() { close(releaseLive) }) } + l.testCOWRead = func(idx uint64, _ bool) { + if idx == 0 { + close(live) + <-releaseLive + } + } + cutDone, writeDone := make(chan struct{}), make(chan struct{}) + var cutErr, writeErr error + writeStarted := false + t.Cleanup(func() { + unblockLive() + cowWaitSignal(t, cutDone, "lazy cut cleanup") + if writeStarted { + cowWaitSignal(t, writeDone, "lazy saver cleanup") + } + }) + go func() { defer close(cutDone); _, cutErr = l.Cut(context.Background()) }() + cowWaitSignal(t, live, "first actual copied chunk") + // The window is open. No guest write may wait on SeaweedFS (design + // rules 1/2): the saver captures only the chunk's LOCAL blocks and + // lists the lazily-absent ones as missing (the copier fills them from + // HEAD later, off the write path), so with every HEAD fetch held the + // saving write must finish without one. + gets, releaseGet := holdGets(t, f) + t.Cleanup(releaseGet) + writeStarted = true + go func() { defer close(writeDone); _, writeErr = s.Write(6, makeBlock(ctBlockSize, 0x96)) }() + cowWaitSignal(t, writeDone, "lazy saving write without a remote fetch") + select { + case k := <-gets: + t.Fatalf("a guest write fetched %s from the remote inside the cut window", k) + default: + } + releaseGet() + if writeErr != nil { + t.Fatal(writeErr) + } + unblockLive() + cowWaitSignal(t, cutDone, "lazy cut") + if cutErr != nil { + t.Fatal(cutErr) + } + want := append([]byte(nil), source...) + for lba, value := range map[int]byte{1: 0x51, 4: 0x54, 5: 0x55} { + copy(want[lba*ctBlockSize:], makeBlock(ctBlockSize, value)) + } + if !bytes.Equal(f.imageOf(t, f.stats().head), want) { + t.Fatal("COW saver lost WAL/batch bytes or lazy HEAD backing") + } + l.testCOWRead = nil + next, err := l.Cut(context.Background()) + if err != nil { + t.Fatal(err) + } + copy(want[6*ctBlockSize:], makeBlock(ctBlockSize, 0x96)) + if !bytes.Equal(f.imageOf(t, next.Head), want) { + t.Fatal("post-save mutation omitted by next cut") + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_cut_cow_red_test.go b/seaweed-block/core/storage/chunk_cut_cow_red_test.go new file mode 100644 index 0000000000..3acb72f52d --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_cow_red_test.go @@ -0,0 +1,378 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "path/filepath" + "runtime" + "sync" + "testing" + "time" +) + +// This test-only metadata adapter parks a real extent read after ReadAt. +// It changes no bytes and does not replace the v3 reader, WAL or flusher. +type cowReadGate struct { + mu sync.Mutex + armed bool + entered chan struct{} + release chan struct{} + once sync.Once +} + +func (g *cowReadGate) OnExtentWrite(uint32, []byte) error { return nil } +func (g *cowReadGate) BeforeCheckpointAdvance(uint64) error { return nil } +func (g *cowReadGate) VerifyExtent(lba uint32, _ []byte) error { + g.mu.Lock() + hold := g.armed && lba == 0 + if hold { + g.armed = false + } + g.mu.Unlock() + if hold { + close(g.entered) + <-g.release + } + return nil +} +func (g *cowReadGate) unblock() { g.once.Do(func() { close(g.release) }) } +func cowWaitSignal(t *testing.T, ch <-chan struct{}, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(ctLocalBound): + stacks := make([]byte, 1<<20) + n := runtime.Stack(stacks, true) + t.Fatalf("%s did not finish within %v\n%s", what, ctLocalBound, stacks[:n]) + } +} + +// R1/R11: a cut copying chunk 0 must allow an at-H image of pending chunk 1 +// to be saved and a new mutation published there. With one copy worker, the +// second chunk is still pending. The first HEAD stays at H; the next cut +// publishes the post-H mutation. Main's full-copy barrier fails progress. +func TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld(t *testing.T) { + for _, method := range []string{"Write", "WriteBatch", "ApplyEntry", "ApplyInstallEntry", "WriteOutsideD"} { + t.Run(method, func(t *testing.T) { + gate := &cowReadGate{entered: make(chan struct{}), release: make(chan struct{})} + opts := WALStoreOptions{ChunkBlocks: ctChunkBlocks, MetadataFactory: func(_ BlockMetadataFile, layout BlockMetadataLayout) (BlockMetadataBinding, error) { + return BlockMetadataBinding{ImplVersion: layout.ImplVersion, Hook: gate}, nil + }} + s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), ctNumBlocks, ctBlockSize, opts) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := s.Close(); err != nil { + t.Error(err) + } + }) + s.DisableAutoFlushForRecoveryTest() + if _, err = s.Recover(); err != nil { + t.Fatal(err) + } + var completed InstallHandle + if method == "ApplyInstallEntry" { + completed, err = s.BeginBaseInstall(7, [16]byte{0xc1}) + if err != nil { + t.Fatal(err) + } + if err = completed.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + } + remote := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.Bitmap = nil + cfg.BarrierBound = 0 + cfg.UploadConcurrency = 1 + layer := mustAttach(t, s, remote, cfg) + // Certify initially UNKNOWN chunks through the real capture, so the + // measured cut has precisely chunks 0 and 1 as its candidates. + if _, err = layer.Cut(context.Background()); err != nil { + t.Fatal(err) + } + for lba, value := range map[uint32]byte{1: 0x21, 5: 0x65} { + if _, err = s.Write(lba, makeBlock(ctBlockSize, value)); err != nil { + t.Fatal(err) + } + } + if _, err = s.Sync(); err != nil { + t.Fatal(err) + } + if err = s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + nextLSN := s.NextLSN() + gate.mu.Lock() + gate.armed = true + gate.mu.Unlock() + type cutResult struct { + cut chunkCutResult + err error + } + cutResultCh := make(chan cutResult, 1) + cutDone, writeDone := make(chan struct{}), make(chan struct{}) + writeErr := make(chan error, 1) + writerStarted := false + // Register release and actual joins before starting either worker. + t.Cleanup(func() { + gate.unblock() + cowWaitSignal(t, cutDone, "cut cleanup") + if writerStarted { + cowWaitSignal(t, writeDone, "mutation cleanup") + } + }) + go func() { + defer close(cutDone) + result, e := layer.Cut(context.Background()) + cutResultCh <- cutResult{result, e} + }() + cowWaitSignal(t, gate.entered, "actual chunk 0 extent-read admission") + writerStarted = true + go func() { + defer close(writeDone) + var e error + switch method { + case "Write": + _, e = s.Write(5, makeBlock(ctBlockSize, 0xa5)) + case "WriteBatch": + _, e = s.WriteBatch(5, [][]byte{makeBlock(ctBlockSize, 0xa5), makeBlock(ctBlockSize, 0xa6), makeBlock(ctBlockSize, 0xa7), makeBlock(ctBlockSize, 0xa8)}) + case "ApplyEntry": + e = s.ApplyEntry(5, makeBlock(ctBlockSize, 0xa5), nextLSN) + case "ApplyInstallEntry": + e = completed.ApplyInstallEntry(5, makeBlock(ctBlockSize, 0xa5), nextLSN) + case "WriteOutsideD": + _, e = s.Write(21, makeBlock(ctBlockSize, 0xa5)) + } + writeErr <- e + }() + // Require positive completion while the extent-read handshake is held. + // The deadline bounds a liveness requirement, not a sleep proving entry. + writeResultRead := false + select { + case e := <-writeErr: + writeResultRead = true + if e != nil { + t.Fatalf("post-H mutation: %v", e) + } + case <-time.After(ctLocalBound): + t.Error("RED: mutation blocked behind another chunk's held copy; capture barrier still covers chunk I/O") + } + if writeResultRead { + // Post-H bytes may checkpoint before this cut settles. Captured + // versions must not certify that newer owned-map state as clean. + if _, e := s.Sync(); e != nil { + t.Fatal(e) + } + if e := s.flusher.flushOnce(); e != nil { + t.Fatal(e) + } + } + gate.unblock() + cowWaitSignal(t, cutDone, "cut after read release") + cowWaitSignal(t, writeDone, "mutation after read release") + if !writeResultRead { + if e := <-writeErr; e != nil { + t.Fatalf("post-release mutation: %v", e) + } + } + result := <-cutResultCh + if result.err != nil { + t.Fatal(result.err) + } + if method != "WriteOutsideD" && (result.cut.Stats.COWSavedChunks != 1 || result.cut.Stats.COWSaveNs <= 0) { + t.Fatalf("real cut did not report its save: %+v", result.cut.Stats) + } + if result.cut.Stats.BarrierCopyChunks != 0 { + t.Fatal("native cut reports data copied under barrier") + } + if result.cut.H != nextLSN-1 { + t.Fatalf("cut H=%d want %d", result.cut.H, nextLSN-1) + } + image := remote.imageOf(t, result.cut.Head) + want := make([]byte, ctNumBlocks*ctBlockSize) + copy(want[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 0x21)) + copy(want[5*ctBlockSize:6*ctBlockSize], makeBlock(ctBlockSize, 0x65)) + if !bytes.Equal(image, want) { + t.Fatal("first HEAD is not the literal pre-H image") + } + changedLBA := 5 + if method == "WriteOutsideD" { + changedLBA = 21 + } + if got, e := s.Read(uint32(changedLBA)); e != nil || !bytes.Equal(got, makeBlock(ctBlockSize, 0xa5)) { + t.Fatalf("local post-H image: %v", e) + } + second, e := layer.Cut(context.Background()) + if e != nil { + t.Fatal(e) + } + copy(want[changedLBA*ctBlockSize:(changedLBA+1)*ctBlockSize], makeBlock(ctBlockSize, 0xa5)) + if method == "WriteBatch" { + for i, value := range []byte{0xa6, 0xa7, 0xa8} { + copy(want[(6+i)*ctBlockSize:(7+i)*ctBlockSize], makeBlock(ctBlockSize, value)) + } + } + if second.H <= result.cut.H || !bytes.Equal(remote.imageOf(t, second.Head), want) { + t.Fatal("next cut omitted post-H mutation") + } + assertNoRemoteMisuse(t, remote) + t.Logf("image controls passed: first H=%d has pre-H bytes, second H=%d has %s bytes", result.cut.H, second.H, method) + }) + } +} + +// R8 first-attachment race through the real Close/Attach callers. Holding +// lifecycle shared lets us observe Close queued at lifecycle exclusive: +// its initial nil hook snapshot has already happened on the parent. This +// arm does not claim a live copier can start after that writer is queued. +func TestCutCOWV3_CloseCannotMissFirstAttachment(t *testing.T) { + s, _ := newChunkTestStore(t) + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if s.chunk.Load() != nil { + t.Fatal("fixture must start unattached") + } + s.lifecycleMu.RLock() + var unlockOnce sync.Once + unlock := func() { unlockOnce.Do(s.lifecycleMu.RUnlock) } + closeDone := make(chan struct{}) + closeErr := make(chan error, 1) + t.Cleanup(func() { unlock(); cowWaitSignal(t, closeDone, "Close cleanup") }) + go func() { defer close(closeDone); closeErr <- s.Close() }() + deadline := time.NewTimer(ctLocalBound) + defer deadline.Stop() + for { + if !s.lifecycleMu.TryRLock() { + break + } + s.lifecycleMu.RUnlock() + select { + case <-deadline.C: + t.Fatal("Close did not reach actual lifecycle-exclusive admission") + case <-closeDone: + t.Fatal("Close returned through a held lifecycle reader") + default: + runtime.Gosched() + } + } + cfg := ctConfig(1) + cfg.Bitmap = nil + layer, err := attachChunkLayer(s, newFakeChunkRemote(), cfg) + if err != nil && !errors.Is(err, errChunkLayerClosed) { + t.Fatalf("unexpected first-attach refusal: %v", err) + } + if err == nil { + t.Cleanup(func() { _ = layer.Close() }) + } + unlock() + cowWaitSignal(t, closeDone, "Close after lifecycle release") + if err = <-closeErr; err != nil { + t.Fatal(err) + } + if layer != nil { + impl := layer.(*chunkLayerImpl) + impl.stMu.Lock() + drained := impl.closed + impl.stMu.Unlock() + if !drained { + t.Error("RED: first attach succeeded after Close's nil snapshot and Close returned without closing that layer") + } + } +} + +// R8 live-copy arm: unlike the first-attach test, the real copier is already +// inside its validated extent read. Close must not complete while it is held. +// This is a preservation control on the barrier parent, not a claimed COW RED. +func TestCutCOWV3_CloseJoinsHeldLiveCopy(t *testing.T) { + for _, which := range []string{"Layer", "Store"} { + t.Run(which, func(t *testing.T) { + gate := &cowReadGate{entered: make(chan struct{}), release: make(chan struct{})} + opts := WALStoreOptions{ChunkBlocks: ctChunkBlocks, MetadataFactory: func(_ BlockMetadataFile, layout BlockMetadataLayout) (BlockMetadataBinding, error) { + return BlockMetadataBinding{ImplVersion: layout.ImplVersion, Hook: gate}, nil + }} + s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), ctNumBlocks, ctBlockSize, opts) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + if _, err = s.Recover(); err != nil { + t.Fatal(err) + } + cfg := ctConfig(1) + cfg.Bitmap = nil + cfg.BarrierBound = 0 + cfg.UploadConcurrency = 1 + layer := mustAttach(t, s, newFakeChunkRemote(), cfg) + gate.mu.Lock() + gate.armed = true + gate.mu.Unlock() + cutDone, closeDone := make(chan struct{}), make(chan struct{}) + cutErr := make(chan error, 1) + closeErr := make(chan error, 1) + early := make(chan bool, 1) + closeStarted := false + t.Cleanup(func() { + gate.unblock() + cowWaitSignal(t, cutDone, "live-copy cut cleanup") + if closeStarted { + cowWaitSignal(t, closeDone, "live-copy Close cleanup") + } + }) + go func() { defer close(cutDone); _, e := layer.Cut(context.Background()); cutErr <- e }() + cowWaitSignal(t, gate.entered, "actual held live-copy read") + closeStarted = true + go func() { + defer close(closeDone) + var e error + if which == "Layer" { + e = layer.Close() + } else { + e = s.Close() + } + // Check actual event order rather than assuming an attempted call + // reached Close based only on goroutine scheduling or a sleep. + select { + case <-gate.release: + early <- false + default: + early <- true + } + closeErr <- e + }() + impl := layer.(*chunkLayerImpl) + deadline := time.NewTimer(ctLocalBound) + defer deadline.Stop() + for { + impl.stMu.Lock() + closing := impl.closed + impl.stMu.Unlock() + if closing { + break + } + select { + case <-deadline.C: + t.Fatal("Close did not enter actual layer shutdown") + default: + runtime.Gosched() + } + } + gate.unblock() + cowWaitSignal(t, cutDone, "cut after live read release") + cowWaitSignal(t, closeDone, "Close after live read release") + if <-early { + t.Error("Close returned before the live-copy read completed") + } + if e := <-closeErr; e != nil { + t.Fatal(e) + } + if e := <-cutErr; e == nil { + t.Error("closed layer's cut unexpectedly published") + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go b/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go new file mode 100644 index 0000000000..9edf4fb498 --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go @@ -0,0 +1,87 @@ +package storage + +import ( + "context" + "errors" + "strings" + "testing" + "time" +) + +// P3: once the in-memory budget is used, a save that would take the side file +// past its byte cap aborts the cut (retried) instead of growing the file; the +// guest write still completes and no side file is left. +func TestCutCOWV3_SpillCapAbortsTheCut(t *testing.T) { + s, l, _, gate := cowFixture(t) + cutDone, cutErr := cowStartCut(t, l, gate) + w := l.cowActive.Load() + w.mu.Lock() + w.memory = cutCOWMemoryLimit // the in-memory budget is used + w.spillLimit = w.chunkBytes - 1 // the cap leaves no room for one chunk + w.mu.Unlock() + writeDone := make(chan error, 1) + go func() { _, err := s.Write(5, makeBlock(ctBlockSize, 0xd5)); writeDone <- err }() + select { + case err := <-writeDone: + if err != nil { + t.Fatal("guest write refused by the spill cap:", err) + } + case <-time.After(ctLocalBound): + t.Fatal("guest write did not complete when the spill cap aborted the cut") + } + w.mu.Lock() + side, spilled := w.side, w.spillBytes + w.mu.Unlock() + if side != nil || spilled != 0 { + t.Fatalf("side file %v / %d spilled bytes past the cap", side != nil, spilled) + } + gate.unblock() + cowWaitSignal(t, cutDone, "capped cut") + if err := <-cutErr; !errors.Is(err, errCutCOWAborted) || !strings.Contains(err.Error(), "spill would exceed its cap") { + t.Fatalf("cut past the spill cap: %v, want the cap abort", err) + } + if _, err := l.Cut(context.Background()); err != nil { + t.Fatal("retried cut:", err) + } +} + +// The default cap applies at attach (0), and a negative cap is refused. +func TestChunkLayer_COWSpillLimitDefaultAndRefusal(t *testing.T) { + s, _ := newChunkTestStore(t) + cfg := ctConfig(1) + cfg.COWSpillLimit = -1 + if _, err := attachChunkLayer(s, newFakeChunkRemote(), cfg); err == nil || !strings.Contains(err.Error(), "spill limit") { + t.Fatalf("negative COW spill limit: %v, want a refusal", err) + } + cfg.COWSpillLimit = 0 + l := mustAttach(t, s, newFakeChunkRemote(), cfg).(*chunkLayerImpl) + if l.cfg.COWSpillLimit != defaultCOWSpillLimit { + t.Fatalf("COW spill limit %d, want the default %d", l.cfg.COWSpillLimit, defaultCOWSpillLimit) + } +} + +// A spill within the cap is accounted: with room for exactly one chunk the +// save spills, the window counts that chunk, and the cut completes. +func TestCutCOWV3_SpillWithinCapIsAccounted(t *testing.T) { + s, l, _, gate := cowFixture(t) + cutDone, cutErr := cowStartCut(t, l, gate) + w := l.cowActive.Load() + w.mu.Lock() + w.memory = cutCOWMemoryLimit + w.spillLimit = w.chunkBytes + w.mu.Unlock() + if _, err := s.Write(5, makeBlock(ctBlockSize, 0xd5)); err != nil { + t.Fatal(err) + } + w.mu.Lock() + side, spilled := w.side, w.spillBytes + w.mu.Unlock() + if side == nil || spilled != w.chunkBytes { + t.Fatalf("spill within the cap: side file %v, %d bytes accounted, want one chunk (%d)", side != nil, spilled, w.chunkBytes) + } + gate.unblock() + cowWaitSignal(t, cutDone, "cut within the spill cap") + if err := <-cutErr; err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/storage/chunk_cut_pause_test.go b/seaweed-block/core/storage/chunk_cut_pause_test.go new file mode 100644 index 0000000000..deef363de6 --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_pause_test.go @@ -0,0 +1,79 @@ +package storage + +import ( + "sync" + "testing" + "time" +) + +// cutWithBarrierHeld runs one cut while a writer holds the capture barrier +// shared (as a writer parked in WAL admission does). The hold ends hold after +// the cut's barrier Lock REQUEST (a handshake, not a guess at the cut's +// progress), so the cut waited at least hold at its Lock. The shared hold is +// released on every path, and the cut is joined within a bound. +func cutWithBarrierHeld(t *testing.T, hold time.Duration) chunkCutStats { + t.Helper() + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + l := layer.(*chunkLayerImpl) + w := newWriteLog() + w.write(t, s, 2, 0x22) + requested := make(chan struct{}) + var reqOnce sync.Once + l.testBeforeBarrierLockHook = func() { reqOnce.Do(func() { close(requested) }) } + s.captureMu.RLock() + var unlockOnce sync.Once + release := func() { unlockOnce.Do(s.captureMu.RUnlock) } + type result struct { + r chunkCutResult + err error + } + done := make(chan result, 1) + t.Cleanup(func() { + release() + select { + case <-done: + case <-time.After(ctLocalBound): + t.Errorf("cut not joined within %v", ctLocalBound) + } + }) + go func() { + r, err := layer.Cut(ctTimeout(t)) + done <- result{r, err} + }() + cowWaitSignal(t, requested, "the cut's barrier Lock request") + time.Sleep(hold) // the cut is waiting at captureMu.Lock for the shared holder + release() + var got result + select { + case got = <-done: + case <-time.After(ctLocalBound): + t.Fatalf("cut did not finish within %v after the shared holder released the barrier", ctLocalBound) + } + done <- got // for the cleanup's join + if got.err != nil { + t.Fatal(got.err) + } + return got.r.Stats +} + +// P2: the guest pause starts at the barrier's Lock request (a pending writer +// blocks new readers), so the wait for writers already holding the barrier is +// part of BarrierPauseNs. +func TestCutStats_BarrierPauseIncludesTheLockWait(t *testing.T) { + const hold = 300 * time.Millisecond + st := cutWithBarrierHeld(t, hold) + if st.BarrierPauseNs < hold.Nanoseconds() { + t.Fatalf("BarrierPauseNs %v does not include the >= %v wait for a writer holding the barrier", time.Duration(st.BarrierPauseNs), hold) + } +} + +// P2: LockWaitNs reports that wait on its own, as the first part of the pause. +func TestCutStats_LockWaitNsReportsTheWait(t *testing.T) { + const hold = 300 * time.Millisecond + st := cutWithBarrierHeld(t, hold) + if st.LockWaitNs < hold.Nanoseconds() || st.BarrierPauseNs < st.LockWaitNs+st.SyncNs { + t.Fatalf("LockWaitNs %v (pause %v, sync %v): want >= %v and inside the pause before the sync", time.Duration(st.LockWaitNs), time.Duration(st.BarrierPauseNs), time.Duration(st.SyncNs), hold) + } +} diff --git a/seaweed-block/core/storage/chunk_fake_remote_test.go b/seaweed-block/core/storage/chunk_fake_remote_test.go index 7eec202e29..ea6d6da91f 100644 --- a/seaweed-block/core/storage/chunk_fake_remote_test.go +++ b/seaweed-block/core/storage/chunk_fake_remote_test.go @@ -386,7 +386,7 @@ func (f *fakeChunkRemote) seedHead(t *testing.T, image []byte, remoteLSN, epoch key := fmt.Sprintf("seed/%d", idx) f.objs[key] = append([]byte(nil), c...) f.everStored[key] = true - head.Chunks[uint64(idx)] = chunkRef{Key: key, SHA256: sha256.Sum256(c)} + head.Chunks[uint64(idx)] = chunkRef{Key: key, SHA256: sha256.Sum256(c), Encoding: "full", BirthLSN: remoteLSN} } f.installLocked(head) } @@ -696,7 +696,7 @@ func closeBounded(t *testing.T, s *WALStore) { func newChunkTestStore(t *testing.T) (*WALStore, string) { t.Helper() path := filepath.Join(t.TempDir(), "vol.bin") - s, err := CreateWALStore(path, ctNumBlocks, ctBlockSize) + s, err := CreateWALStoreWithOptions(path, ctNumBlocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks}) if err != nil { t.Fatal(err) } @@ -710,7 +710,7 @@ func newChunkTestStore(t *testing.T) (*WALStore, string) { func crashableStore(t *testing.T) (*WALStore, string, func()) { t.Helper() path := filepath.Join(t.TempDir(), "vol.bin") - s, err := CreateWALStore(path, ctNumBlocks, ctBlockSize) + s, err := CreateWALStoreWithOptions(path, ctNumBlocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks}) if err != nil { t.Fatal(err) } @@ -1133,3 +1133,67 @@ func waitReconciledForTest(t *testing.T, layer chunkLayer) { time.Sleep(time.Millisecond) } } + +// TODO(format-v3 row 14a): explicit C11 bitmap-engine fixtures only. +func newLegacyChunkTestStore(t *testing.T) (*WALStore, string) { + t.Helper() + path := filepath.Join(t.TempDir(), "vol.bin") + s, err := createLegacyWALStoreWithOptions(path, ctNumBlocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks}) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { closeBounded(t, s) }) + return s, path +} + +// crashableStore is a store a test may crash; it is closed at cleanup only +// if it was not crashed. +func legacyCrashableStore(t *testing.T) (*WALStore, string, func()) { + t.Helper() + path := filepath.Join(t.TempDir(), "vol.bin") + s, err := createLegacyWALStoreWithOptions(path, ctNumBlocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks}) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + crashed := false + t.Cleanup(func() { + if !crashed { + closeBounded(t, s) + } + }) + return s, path, func() { + crashed = true + s.committer.Stop() + if err := s.fd.Close(); err != nil { + t.Fatal(err) + } + } +} + +// reopen opens and recovers a crashed store; it may be crashed again. +func legacyReopen(t *testing.T, path string) (*WALStore, func()) { + t.Helper() + s, err := openLegacyWALStoreForTest(path) + if err != nil { + t.Fatal(err) + } + crashed := false + t.Cleanup(func() { + if !crashed { + closeBounded(t, s) + } + }) + s.DisableAutoFlushForRecoveryTest() + if _, err := s.Recover(); err != nil { + t.Fatalf("local recovery: %v", err) + } + return s, func() { + crashed = true + s.committer.Stop() + if err := s.fd.Close(); err != nil { + t.Fatal(err) + } + } +} diff --git a/seaweed-block/core/storage/chunk_frontier.go b/seaweed-block/core/storage/chunk_frontier.go index c1c0eebee0..46b0bdf94e 100644 --- a/seaweed-block/core/storage/chunk_frontier.go +++ b/seaweed-block/core/storage/chunk_frontier.go @@ -3,6 +3,8 @@ package storage import ( "errors" "fmt" + "log" + "time" ) // SeedChunkFrontier installs an empty fresh host's inherited remote frontier. @@ -11,6 +13,9 @@ import ( // attaching the chunk layer or admitting writes. Repeating after failure is safe. // Order: captureMu -> lifecycleMu -> mu; no remote call or layer callback. func (s *WALStore) SeedChunkFrontier(lsn uint64) error { + if s.v3 != nil { + return s.seedChunkFrontierV3(lsn) + } s.captureMu.Lock() defer s.captureMu.Unlock() s.lifecycleMu.RLock() @@ -52,3 +57,84 @@ func (s *WALStore) SeedChunkFrontier(lsn uint64) error { s.pendingDirectFrontierLSN = 0 return nil } + +// seedChunkFrontierV3 is SeedChunkFrontier on a dark v3 store (plan row 9): +// the same preconditions (an open, unattached store with no local writes +// beyond its checkpoint), a data fsync, and then the one checkpoint +// publication (publishCheckpointV3): the metadata barrier, the owned-map +// candidate at lsn and the sole slot publisher, which raises W and the +// checkpoint to lsn together. The volatile frontier moves only after that +// publication succeeded; any failure publishes nothing and may be retried. +// An unmapped v3 store has no map candidate for the new checkpoint and is +// refused. Order: captureMu -> lifecycleMu -> (syncMu ->) mu. +func (s *WALStore) seedChunkFrontierV3(lsn uint64) error { + var t seedTimes + err := s.seedChunkFrontierV3Locked(lsn, &t) + // Logged after the capture and lifecycle locks are released: a slow log + // writer never extends them. A refused or no-op seed did no I/O. + if !t.validated.IsZero() { + stage := func(from, to time.Time) string { + if to.IsZero() { + return "-" + } + return to.Sub(from).String() + } + log.Printf("storage: seed frontier %d: capture+lifecycle lock wait %s, store mutex+validation %s, data sync (incl. sync serialization) %s, checkpoint publish %s, err=%v", + lsn, t.locked.Sub(t.start), t.validated.Sub(t.locked), stage(t.validated, t.synced), stage(t.synced, t.published), err) + } + return err +} + +// seedTimes are the stage boundaries of one v3 seed (zero: not reached). +type seedTimes struct{ start, locked, validated, synced, published time.Time } + +func (s *WALStore) seedChunkFrontierV3Locked(lsn uint64, t *seedTimes) (err error) { + v := s.v3 + t.start = time.Now() + s.captureMu.Lock() + defer s.captureMu.Unlock() + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + t.locked = time.Now() + s.mu.Lock() + if s.closed || s.chunk.Load() != nil { + s.mu.Unlock() + return errors.New("storage: seed frontier requires an open, unattached store") + } + if err := s.stickyIOFault(); err != nil { + s.mu.Unlock() + return err + } + d := v.pub.current() + if lsn == ^uint64(0) || lsn < d.CheckpointLSN || v.appended.Load() > d.CheckpointLSN || + s.walHead > s.checkpointLSN || s.nextLSN > lsn+1 || d.BaseState != BaseNone { + s.mu.Unlock() + return errors.New("storage: seed frontier cannot replace local writes, an install or wrap LSN") + } + if v.ownedMap == nil { + s.mu.Unlock() + return fmt.Errorf("%w: a v3 seed needs the owned map for its checkpoint coverage", errV3NotYet) + } + if d.CheckpointLSN == lsn && d.W >= lsn && s.nextLSN == lsn+1 { + s.mu.Unlock() + return nil + } + gen := v.recoverGen.Load() + s.mu.Unlock() + t.validated = time.Now() + err = s.syncFile(nil, s.fd.Sync) + t.synced = time.Now() + if err != nil { + return fmt.Errorf("storage: seed data sync: %w", err) + } + _, err = s.publishCheckpointV3(lsn, true, gen) + t.published = time.Now() + if err != nil { + return fmt.Errorf("storage: seed frontier %d: %w", lsn, err) + } + s.mu.Lock() + defer s.mu.Unlock() + s.checkpointLSN, s.syncedLSN, s.walHead, s.nextLSN = lsn, lsn, lsn, lsn+1 + s.pendingDirectFrontierLSN = 0 + return nil +} diff --git a/seaweed-block/core/storage/chunk_frontier_test.go b/seaweed-block/core/storage/chunk_frontier_test.go index f92846b4f6..c4d2ecc613 100644 --- a/seaweed-block/core/storage/chunk_frontier_test.go +++ b/seaweed-block/core/storage/chunk_frontier_test.go @@ -6,7 +6,7 @@ import ( ) func TestSeedChunkFrontierMetadataFailureRetry(t *testing.T) { - s, path := newChunkTestStore(t) + s, path := newLegacyChunkTestStore(t) s.DisableAutoFlushForRecoveryTest() syncMetadata := s.syncDirectFrontierMetadata s.syncDirectFrontierMetadata = func([]byte) error { return errors.New("injected metadata fsync failure") } @@ -29,7 +29,7 @@ func TestSeedChunkFrontierMetadataFailureRetry(t *testing.T) { t.Fatalf("same-store seed retry after a failed fsync: %v; want ErrFsyncFailed", err) } _ = s.Close() - reopened, err := OpenWALStore(path) + reopened, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -51,7 +51,7 @@ func TestSeedChunkFrontierMetadataFailureRetry(t *testing.T) { reopened.committer.Stop() _ = reopened.fd.Close() // crash reopenedOpen = false - again, err := OpenWALStore(path) + again, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/chunk_frontier_v3_log_test.go b/seaweed-block/core/storage/chunk_frontier_v3_log_test.go new file mode 100644 index 0000000000..3d74b0dffb --- /dev/null +++ b/seaweed-block/core/storage/chunk_frontier_v3_log_test.go @@ -0,0 +1,160 @@ +package storage + +import ( + "bytes" + "log" + "regexp" + "strings" + "sync" + "testing" + "time" +) + +type seedLog struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (l *seedLog) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.buf.Write(p) +} + +func (l *seedLog) lines() []string { + l.mu.Lock() + defer l.mu.Unlock() + var out []string + for _, line := range strings.Split(l.buf.String(), "\n") { + if strings.Contains(line, "storage: seed frontier") { + out = append(out, line) + } + } + return out +} + +// Nonparallel: the standard logger is global. +func captureSeedLog(t *testing.T) *seedLog { + t.Helper() + l := &seedLog{} + old := log.Writer() + log.SetOutput(l) + t.Cleanup(func() { log.SetOutput(old) }) + return l +} + +var seedTimesLine = regexp.MustCompile(`storage: seed frontier 7: capture\+lifecycle lock wait [0-9.]+[a-zµ]+s, store mutex\+validation [0-9.]+[a-zµ]+s, data sync \(incl\. sync serialization\) [0-9.]+[a-zµ]+s, checkpoint publish [0-9.]+[a-zµ]+s, err=`) + +// A v3 seed logs its lock wait, data fsync and checkpoint publication +// times once per seed that did I/O, with its outcome; a no-op repeat and a +// refusal log nothing. +func TestWALStoreV3SeedLogsItsStageTimes(t *testing.T) { + t.Run("seeded", func(t *testing.T) { + logs := captureSeedLog(t) + s, _ := newMappedCheckpointStoreV3(t) + if err := s.SeedChunkFrontier(7); err != nil { + t.Fatal(err) + } + if err := s.SeedChunkFrontier(7); err != nil { // already seeded: no I/O + t.Fatal(err) + } + got := logs.lines() + if len(got) != 1 || !seedTimesLine.MatchString(got[0]) || !strings.HasSuffix(got[0], "err=") { + t.Fatalf("seed log lines %q; want one line with the three stage times and err=", got) + } + }) + t.Run("publish failed", func(t *testing.T) { + logs := captureSeedLog(t) + s, _ := newMappedCheckpointStoreV3(t) + fired := false + s.v3.testMapPrepared = func() { + if !fired { + fired = true + s.v3.recoverGen.Add(2) + } + } + if err := s.SeedChunkFrontier(7); err == nil { + t.Fatal("seed across a lifetime change succeeded") + } + got := logs.lines() + if len(got) != 1 || !seedTimesLine.MatchString(got[0]) || !strings.Contains(got[0], ErrMapCoverageStale.Error()) { + t.Fatalf("seed log lines %q; want one line with the stage times and the coverage error", got) + } + }) + t.Run("refused", func(t *testing.T) { + logs := captureSeedLog(t) + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + if err := s.SeedChunkFrontier(7); err == nil { + t.Fatal("seed over local writes succeeded") + } + if got := logs.lines(); len(got) != 0 { + t.Fatalf("a refused seed logged %q", got) + } + }) +} + +// blockingLog blocks its first write until released. +type blockingLog struct { + entered, release chan struct{} + once sync.Once +} + +func (b *blockingLog) Write(p []byte) (int, error) { + first := false + b.once.Do(func() { first = true }) + if first { + close(b.entered) + <-b.release + } + return len(p), nil +} + +// The seed's log line is written after the capture and lifecycle locks are +// released: while the log output is blocked, both are free. +func TestWALStoreV3SeedLogsOutsideTheStoreLocks(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + b := &blockingLog{entered: make(chan struct{}), release: make(chan struct{})} + old := log.Writer() + log.SetOutput(b) + t.Cleanup(func() { log.SetOutput(old) }) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(b.release) }) } + done := make(chan error, 1) + joined := false + t.Cleanup(func() { // release the blocked writer, then join the seed, bounded + release() + if joined { + return + } + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("seed not joined") + } + }) + go func() { done <- s.SeedChunkFrontier(7) }() + select { + case <-b.entered: + case <-time.After(5 * time.Second): + t.Fatal("the seed never logged") + } + if !s.captureMu.TryLock() { + t.Fatal("captureMu held while the seed log output is blocked") + } + s.captureMu.Unlock() + if !s.lifecycleMu.TryLock() { + t.Fatal("lifecycleMu held while the seed log output is blocked") + } + s.lifecycleMu.Unlock() + release() + select { + case err := <-done: + joined = true + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("the seed did not finish after the log output was released") + } +} diff --git a/seaweed-block/core/storage/chunk_frontier_v3_test.go b/seaweed-block/core/storage/chunk_frontier_v3_test.go new file mode 100644 index 0000000000..c965d17fc0 --- /dev/null +++ b/seaweed-block/core/storage/chunk_frontier_v3_test.go @@ -0,0 +1,125 @@ +package storage + +import ( + "errors" + "testing" +) + +// Plan row 9c controls (owner claude03): SeedChunkFrontier on a dark v3 +// store uses the checkpoint's map/metadata barrier and the sole descriptor +// publication (publishCheckpointV3), never the legacy superblock writer. + +// A seed publishes CheckpointLSN = W = map coverage = lsn in exactly one +// slot publication with a fresh map root; the allocator continues at lsn+1 +// and a crash and mapped reopen keep the frontier and a later write. +// Mutant: a seed that does not raise W refuses (no candidate above W) and +// fails here. +func TestWALStoreV3SeedPublishesTheCheckpointThroughTheMap(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + before := s.v3.pub.current() + writes := countSlotWritesV3(s) + if err := s.SeedChunkFrontier(7); err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + if writes.Load() != 1 { + t.Fatalf("seed wrote %d slots, want one publication", writes.Load()) + } + if d.CheckpointLSN != 7 || d.W != 7 || d.MapCoveredCheckpoint != 7 || d.MapGeneration <= before.MapGeneration { + t.Fatalf("seed published checkpoint %d W %d coverage %d map gen %d (was %d)", + d.CheckpointLSN, d.W, d.MapCoveredCheckpoint, d.MapGeneration, before.MapGeneration) + } + if s.NextLSN() != 8 { + t.Fatalf("NextLSN %d, want 8", s.NextLSN()) + } + if err := s.SeedChunkFrontier(7); err != nil || writes.Load() != 1 { + t.Fatalf("repeated seed: err %v, slot writes %d, want an idempotent no-op", err, writes.Load()) + } + s.v3.testBeforeSlotWrite = nil + if lsn, err := s.Write(3, blk(3)); err != nil || lsn != 8 { + t.Fatalf("write after seed: LSN %d err %v, want 8", lsn, err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if got := r.v3.pub.current(); got.CheckpointLSN != 7 || got.W < 8 { + t.Fatalf("reopen: checkpoint %d W %d, want 7 and >= 8", got.CheckpointLSN, got.W) + } + readAllV3(t, r, 3, 3) +} + +// The barrier precedes the publication: when the map candidate is +// persisted, no slot has been published yet. A failure after it (here a +// recovery lifetime change) publishes nothing and moves no volatile +// frontier; a retry then succeeds. Mutant: moving the volatile frontier +// before the publication fails here. +func TestWALStoreV3SeedFailurePublishesNothingAndRetries(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + before := s.v3.pub.current() + fired := false + s.v3.testMapPrepared = func() { + if fired { + return + } + fired = true + if s.v3.pub.current() != before { + t.Error("a slot was published before the map candidate was persisted") + } + s.v3.recoverGen.Add(2) // a recovery ran between preparation and publication + } + if err := s.SeedChunkFrontier(7); !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("seed across a lifetime change: err = %v, want ErrMapCoverageStale", err) + } + if s.v3.pub.current() != before || s.NextLSN() != 1 || s.v3.wack.Load() != 0 { + t.Fatal("a failed seed published or moved the volatile frontier") + } + if err := s.SeedChunkFrontier(7); err != nil { + t.Fatalf("retry: %v", err) + } + if d := s.v3.pub.current(); d.CheckpointLSN != 7 || s.NextLSN() != 8 { + t.Fatalf("retry: checkpoint %d NextLSN %d", d.CheckpointLSN, s.NextLSN()) + } +} + +// Refusals, writing nothing: local writes beyond the checkpoint, an +// unmapped store (no map candidate for the new checkpoint) and an attached +// chunk layer. +func TestWALStoreV3SeedRefusals(t *testing.T) { + t.Run("local writes", func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + before := s.v3.pub.current() + if err := s.SeedChunkFrontier(7); err == nil || s.v3.pub.current() != before { + t.Fatalf("seed over a local write: err %v", err) + } + }) + t.Run("unmapped", func(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + before := s.v3.pub.current() + if err := s.SeedChunkFrontier(7); !errors.Is(err, errV3NotYet) || s.v3.pub.current() != before { + t.Fatalf("unmapped seed: err %v", err) + } + }) + t.Run("attached chunk layer", func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + cfg := ctConfig(1) + cfg.Bitmap = nil + cfg.BarrierBound = 1 + mustAttach(t, s, newFakeChunkRemote(), cfg) + before := s.v3.pub.current() + if err := s.SeedChunkFrontier(7); err == nil || s.v3.pub.current() != before { + t.Fatalf("seed with a layer attached: err %v", err) + } + }) +} diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go new file mode 100644 index 0000000000..2291ea22cc --- /dev/null +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -0,0 +1,254 @@ +package storage + +import ( + "context" + "errors" + "fmt" +) + +// ErrChunkHydrationPending means no guest bytes were admitted: hydration +// is queued/in flight or the caller's wait expired. Owned work may continue. +var ErrChunkHydrationPending = errors.New("storage: chunk hydration pending") + +const defaultHydrationWorkers = 2 +const defaultHydrationQueueDepth = 64 + +// ChunkHydrationStats separates wait refusals from owned fetch outcomes. +// A wait refusal is not necessarily a wire completion (a caller may cancel). +type ChunkHydrationStats struct { + WorkerLimit int + QueueDepth int + Active int + Queued int + WaitCalls uint64 + Joined uint64 + WaitRefusals uint64 + Fetches uint64 + Completed uint64 + FetchErrors uint64 +} + +type chunkHydrationFlight struct { + idx, gen uint64 + ref chunkRef + ctx context.Context + cancel context.CancelFunc + done chan struct{} + running bool + waiters int + err error +} + +func hydrationPending(cause error) error { + if cause == nil { + return ErrChunkHydrationPending + } + return fmt.Errorf("%w: %w", ErrChunkHydrationPending, cause) +} + +// The promise and worker lifetime belong to the layer, not any one caller. +// stMu protects admission, queue membership and waiter counts. Nobody holds +// it (or a store/capture/lifecycle lock) while awaiting or fetching bytes. +func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]byte, error) { + idx := l.chunkOf(lba) + counted := false + for { + l.stMu.Lock() + if l.closed { + l.stMu.Unlock() + return nil, errChunkLayerClosed + } + if !l.absent[idx] || l.localBlocks[lba] { + l.stMu.Unlock() + return nil, nil + } + ref, ok := l.head.Chunks[idx] + if !ok { + l.stMu.Unlock() + return make([]byte, l.blockSize), nil + } + if !counted { + l.stats.Hydration.WaitCalls++ + counted = true + } + if err := ctx.Err(); err != nil { + l.stats.Hydration.WaitRefusals++ + l.stMu.Unlock() + return nil, hydrationPending(err) + } + gen := l.absentGen[idx] + f := l.hydration[idx] + stale := f != nil && (f.gen != gen || f.ref != ref) + if stale { + f.cancel() + // The old worker remains owned and joined, but cannot delay a + // new generation or remove its replacement when it finishes. + delete(l.hydration, idx) + close(f.done) + f = nil + } + if f != nil && !stale { + l.stats.Hydration.Joined++ + } + if f == nil { + if len(l.hydration) >= l.cfg.HydrationQueueDepth { + l.stats.Hydration.WaitRefusals++ + l.stMu.Unlock() + return nil, hydrationPending(nil) + } + if !l.hydrationStarted { + l.hydration = make(map[uint64]*chunkHydrationFlight) + l.hydrationWake = make(chan struct{}, 1) + l.hydrationStarted = true + l.wg.Add(l.cfg.HydrationWorkers) + for i := 0; i < l.cfg.HydrationWorkers; i++ { + go l.hydrationWorker() + } + } + work, cancel := context.WithCancel(l.ctx) + f = &chunkHydrationFlight{idx: idx, gen: gen, ref: ref, ctx: work, cancel: cancel, done: make(chan struct{})} + l.hydration[idx] = f + } + f.waiters++ + l.wakeHydrationLocked() + l.stMu.Unlock() + if hook := l.testHydrationWait; hook != nil { + hook(idx) + } + select { + case <-l.ctx.Done(): + l.stMu.Lock() + f.waiters-- + l.stMu.Unlock() + return nil, errChunkLayerClosed + case <-f.done: + case <-ctx.Done(): + // A completed fault wins a simultaneous caller deadline. + select { + case <-f.done: + default: + l.stMu.Lock() + f.waiters-- + l.stats.Hydration.WaitRefusals++ + l.stMu.Unlock() + return nil, hydrationPending(ctx.Err()) + } + } + l.stMu.Lock() + f.waiters-- + closed := l.closed + changed := l.absentGen[idx] != f.gen || l.head.Chunks[idx] != f.ref + err := f.err + if !closed && !changed && errors.Is(err, ErrChunkHydrationPending) { + l.stats.Hydration.WaitRefusals++ + } + l.stMu.Unlock() + if closed { + return nil, errChunkLayerClosed + } + if changed { + continue + } + if err != nil { + return nil, err + } + // A local override or an intervening HEAD/absence change is resolved + // through the normal path, under the same original caller deadline. + } +} + +func (l *chunkLayerImpl) wakeHydrationLocked() { + select { + case l.hydrationWake <- struct{}{}: + default: + } +} + +func (l *chunkLayerImpl) hydrationWorker() { + defer l.wg.Done() + for { + l.stMu.Lock() + if l.closed { + l.stMu.Unlock() + return + } + var next *chunkHydrationFlight + for _, f := range l.hydration { + if !f.running && (next == nil || (f.waiters > 0 && next.waiters == 0)) { + next = f + } + } + if next == nil { + l.stMu.Unlock() + select { + case <-l.hydrationWake: + continue + case <-l.ctx.Done(): + return + } + } + next.running = true + l.stats.Hydration.Active++ + l.stats.Hydration.Fetches++ + l.wakeHydrationLocked() + l.stMu.Unlock() + fetch, cancel := context.WithTimeout(next.ctx, l.cfg.ReadMissTimeout) + resolved, err := l.fillOnce(fetch, next.idx, next.gen, next.ref) + cancel() + next.cancel() + l.stMu.Lock() + if hydrationContextCauseOnly(err) { + err = hydrationPending(err) + } + if err != nil { + l.stats.Hydration.FetchErrors++ + } else if resolved { + l.stats.Hydration.Completed++ + } + l.stats.Hydration.Active-- + next.err = err + if l.hydration[next.idx] == next { + delete(l.hydration, next.idx) + close(next.done) + } + l.wakeHydrationLocked() + l.stMu.Unlock() + } +} + +// Caller holds stMu, before Close begins joining wg. Running fills remain +// owned until their worker finishes; queued promises settle without I/O. +func (l *chunkLayerImpl) closeHydrationLocked() { + for idx, f := range l.hydration { + f.cancel() + if !f.running { + f.err = errChunkLayerClosed + delete(l.hydration, idx) + close(f.done) + } + } +} + +// Joined physical/unknown errors must not become retryable just because they +// also contain a context cause. +func hydrationContextCauseOnly(err error) bool { + if err == context.DeadlineExceeded || err == context.Canceled { + return true + } + if err == nil { + return false + } + if j, ok := err.(interface{ Unwrap() []error }); ok { + causes := j.Unwrap() + if len(causes) == 0 { + return false + } + for _, cause := range causes { + if !hydrationContextCauseOnly(cause) { + return false + } + } + return true + } + return hydrationContextCauseOnly(errors.Unwrap(err)) +} diff --git a/seaweed-block/core/storage/chunk_hydration_budget_test.go b/seaweed-block/core/storage/chunk_hydration_budget_test.go new file mode 100644 index 0000000000..1f224970e3 --- /dev/null +++ b/seaweed-block/core/storage/chunk_hydration_budget_test.go @@ -0,0 +1,96 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "testing" + "time" +) + +func hydrationReadContext(s *WALStore, ctx context.Context, lba uint32) ([]byte, error) { + if r, ok := any(s).(interface { + ReadContext(context.Context, uint32) ([]byte, error) + }); ok { + return r.ReadContext(ctx, lba) + } + return s.Read(lba) +} + +func TestChunkHydration_DeadlineDetachesWithoutCancellingFill(t *testing.T) { + src := make([]byte, ctNumBlocks*ctBlockSize) + copy(src[8*ctBlockSize:], makeBlock(ctBlockSize, 0x88)) + remote := newFakeChunkRemote() + remote.seedHead(t, src, 50, 1) + s, _ := newChunkTestStore(t) + cfg := ctConfig(2) + cfg.FreshFromHead = true + mustAttach(t, s, remote, cfg) + _, release := holdNextGet(t, remote) + fired := make(chan struct{}) + timer := time.AfterFunc(500*time.Millisecond, func() { defer close(fired); release() }) + t.Cleanup(func() { + release() + if !timer.Stop() { + <-fired + } + }) + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + start := time.Now() + got, err := hydrationReadContext(s, ctx, 8) + elapsed := time.Since(start) + if len(got) != 0 || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("deadline must detach before fill: bytes=%d err=%v elapsed=%s", len(got), err, elapsed) + } + if elapsed >= 350*time.Millisecond { + t.Fatalf("hydration ignored caller budget: %s", elapsed) + } + retry, cancelRetry := context.WithTimeout(context.Background(), 2*time.Second) + defer cancelRetry() + got, err = hydrationReadContext(s, retry, 8) + if err != nil || !bytes.Equal(got, makeBlock(ctBlockSize, 0x88)) { + t.Fatalf("retry did not get exact bytes: %v", err) + } + if n := remote.stats().gets; n != 1 { + t.Fatalf("retry cancelled/restarted shared fetch: Gets=%d want1", n) + } +} + +// Internal readers have no frontend command budget: the remote fill owns its timeout. +func TestChunkHydration_ContextlessReadAllowsSlowFill(t *testing.T) { + s, layer, remote, _ := hydrationFixture(t, 2, 64) + layer.cfg.ReadMissTimeout = 30 * time.Second + entered, release := holdGets(t, remote) + defer release() + result := make(chan hydrationResult, 1) + go func() { data, err := s.Read(8); result <- hydrationResult{data, err} }() + waitKey(t, entered, "contextless slow fill") + timer := time.NewTimer(6 * time.Second) + defer timer.Stop() + <-timer.C + release() + select { + case got := <-result: + if got.err != nil || !bytes.Equal(got.data, makeBlock(ctBlockSize, 0x48)) { + t.Fatalf("contextless reader lost slow fill: %v", got.err) + } + case <-time.After(ctLocalBound): + t.Fatal("contextless reader did not settle after release") + } +} + +func TestChunkHydration_SnapshotFailsOnReadError(t *testing.T) { + s, _, remote, _ := hydrationFixture(t, 2, 64) + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x77)); err != nil { + t.Fatal(err) + } + fault := errors.New("remote snapshot read fault") + remote.mu.Lock() + remote.failGet = fault + remote.mu.Unlock() + got, err := s.AllBlocks() + if !errors.Is(err, fault) || got != nil { + t.Fatalf("snapshot silently lost unreadable blocks: entries=%d err=%v", len(got), err) + } +} diff --git a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go new file mode 100644 index 0000000000..575e90b035 --- /dev/null +++ b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go @@ -0,0 +1,407 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "strings" + "sync" + "testing" + "time" +) + +type hydrationResult struct { + data []byte + err error +} + +func hydrationFixture(t *testing.T, workers, depth int) (*WALStore, *chunkLayerImpl, *fakeChunkRemote, <-chan uint64) { + t.Helper() + image := make([]byte, ctNumBlocks*ctBlockSize) + for i := uint32(0); i < ctNumBlocks; i++ { + copy(image[int(i)*ctBlockSize:], makeBlock(ctBlockSize, byte(0x40+i))) + } + remote := newFakeChunkRemote() + remote.seedHead(t, image, 50, 1) + s, _ := newChunkTestStore(t) + if err := s.SeedChunkFrontier(50); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + cfg.HydrationWorkers = workers + cfg.HydrationQueueDepth = depth + layer := mustAttach(t, s, remote, cfg).(*chunkLayerImpl) + registered := make(chan uint64, 128) + layer.testHydrationWait = func(idx uint64) { registered <- idx } + return s, layer, remote, registered +} + +func startHydrationRead(t *testing.T, s *WALStore, parent context.Context, lba uint32) <-chan hydrationResult { + t.Helper() + ctx, cancel := context.WithCancel(parent) + result := make(chan hydrationResult, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + cancel() + select { + case <-joined: + case <-time.After(ctLocalBound): + t.Error("hydration reader failed to settle") + } + }) + go func() { + defer close(joined) + data, err := hydrationReadContext(s, ctx, lba) + result <- hydrationResult{data, err} + }() + return result +} +func waitHydrationRegistration(t *testing.T, c <-chan uint64, n int) { + t.Helper() + for i := 0; i < n; i++ { + select { + case <-c: + case <-time.After(ctLocalBound): + t.Fatal("hydration waiter was not registered") + } + } +} +func hydrationOutcome(t *testing.T, c <-chan hydrationResult) hydrationResult { + t.Helper() + select { + case r := <-c: + return r + case <-time.After(ctLocalBound): + t.Fatal("hydration read did not finish") + return hydrationResult{} + } +} + +func TestChunkHydration_ConcurrentReadersShareOneGet(t *testing.T) { + s, _, remote, registered := hydrationFixture(t, 2, 64) + entered, release := holdGets(t, remote) + defer release() + const readers = 12 + results := make([]<-chan hydrationResult, readers) + for i := range results { + results[i] = startHydrationRead(t, s, context.Background(), 8) + } + waitHydrationRegistration(t, registered, readers) + waitKey(t, entered, "shared hydration") + if got := remote.stats().gets; got != 1 { + t.Fatalf("same-chunk readers started %d Gets", got) + } + release() + for _, c := range results { + r := hydrationOutcome(t, c) + if r.err != nil || !bytes.Equal(r.data, makeBlock(ctBlockSize, 0x48)) { + t.Fatalf("shared fill bytes: %v", r.err) + } + } + if got := remote.stats().gets; got != 1 { + t.Fatalf("shared fill restarted: Gets=%d", got) + } +} + +func TestChunkHydration_QueueAndWorkerLimitsAreBounded(t *testing.T) { + s, layer, remote, registered := hydrationFixture(t, 1, 2) + entered, release := holdGets(t, remote) + defer release() + first := startHydrationRead(t, s, context.Background(), 8) + waitKey(t, entered, "first worker") + waitHydrationRegistration(t, registered, 1) + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) + defer cancel() + second := startHydrationRead(t, s, ctx, 12) + waitHydrationRegistration(t, registered, 1) + if r := hydrationOutcome(t, second); !errors.Is(r.err, ErrChunkHydrationPending) { + t.Fatalf("queued timeout: %v", r.err) + } + _, err := hydrationReadContext(s, context.Background(), 16) + if !errors.Is(err, ErrChunkHydrationPending) { + t.Fatalf("full queue did not refuse: %v", err) + } + if got := remote.stats().gets; got != 1 { + t.Fatalf("worker bound exceeded: Gets=%d", got) + } + stats := layer.Stats().Hydration + if stats.WorkerLimit != 1 || stats.QueueDepth != 2 || stats.Active != 1 || stats.Queued != 1 || stats.WaitRefusals != 2 || stats.Fetches != 1 { + t.Fatalf("hydration status does not reflect bounded pressure: %+v", stats) + } + release() + if r := hydrationOutcome(t, first); r.err != nil { + t.Fatal(r.err) + } +} + +func TestChunkHydration_ActiveDemandPrecedesExpiredWaiter(t *testing.T) { + s, _, remote, registered := hydrationFixture(t, 1, 3) + entered, release := holdGets(t, remote) + defer release() + first := startHydrationRead(t, s, context.Background(), 8) + waitKey(t, entered, "occupied worker") + waitHydrationRegistration(t, registered, 1) + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) + defer cancel() + expired := startHydrationRead(t, s, ctx, 12) + waitHydrationRegistration(t, registered, 1) + if r := hydrationOutcome(t, expired); !errors.Is(r.err, ErrChunkHydrationPending) { + t.Fatalf("expired queued read: %v", r.err) + } + demand := startHydrationRead(t, s, context.Background(), 16) + waitHydrationRegistration(t, registered, 1) + release() + if r := hydrationOutcome(t, first); r.err != nil { + t.Fatal(r.err) + } + if r := hydrationOutcome(t, demand); r.err != nil || !bytes.Equal(r.data, makeBlock(ctBlockSize, 0x50)) { + t.Fatalf("demand: %v", r.err) + } + var gets []string + for _, op := range remote.stats().ops { + if strings.HasPrefix(op, "get:") { + gets = append(gets, strings.TrimPrefix(op, "get:")) + } + } + if want := remote.stats().head.Chunks[4].Key; len(gets) < 2 || gets[1] != want { + t.Fatalf("fetch order %v, want demand %q second", gets, want) + } +} + +func TestChunkHydration_CloseSettlesQueuedAndRunningReaders(t *testing.T) { + s, layer, remote, registered := hydrationFixture(t, 1, 2) + entered, release := holdGets(t, remote) + defer release() + first := startHydrationRead(t, s, context.Background(), 8) + waitKey(t, entered, "running Get") + second := startHydrationRead(t, s, context.Background(), 12) + waitHydrationRegistration(t, registered, 2) + if err := layer.Close(); err != nil { + t.Fatal(err) + } + for _, c := range []<-chan hydrationResult{first, second} { + if r := hydrationOutcome(t, c); !errors.Is(r.err, errChunkLayerClosed) { + t.Fatalf("close outcome: %v", r.err) + } + } + if got := remote.stats().gets; got != 1 { + t.Fatalf("queued work started after Close: Gets=%d", got) + } +} + +func TestChunkHydration_ConfiguredWorkersBoundConcurrentGets(t *testing.T) { + s, _, remote, registered := hydrationFixture(t, 2, 3) + entered, release := holdGets(t, remote) + defer release() + a := startHydrationRead(t, s, context.Background(), 8) + b := startHydrationRead(t, s, context.Background(), 12) + waitKey(t, entered, "worker1") + waitKey(t, entered, "worker2") + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + c := startHydrationRead(t, s, ctx, 16) + waitHydrationRegistration(t, registered, 3) + if r := hydrationOutcome(t, c); !errors.Is(r.err, ErrChunkHydrationPending) { + t.Fatalf("queued read: %v", r.err) + } + if got := remote.stats().gets; got != 2 { + t.Fatalf("configured2 workers started%d Gets", got) + } + release() + if r := hydrationOutcome(t, a); r.err != nil { + t.Fatal(r.err) + } + if r := hydrationOutcome(t, b); r.err != nil { + t.Fatal(r.err) + } +} + +type uninterruptibleHydrationRemote struct { + *fakeChunkRemote + entered, release chan struct{} + once sync.Once +} + +func (r *uninterruptibleHydrationRemote) Get(_ context.Context, key string) ([]byte, error) { + r.once.Do(func() { close(r.entered) }) + <-r.release + return r.fakeChunkRemote.Get(context.Background(), key) +} + +func TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet(t *testing.T) { + image := make([]byte, ctNumBlocks*ctBlockSize) + copy(image[8*ctBlockSize:], makeBlock(ctBlockSize, 0x88)) + f := newFakeChunkRemote() + f.seedHead(t, image, 50, 1) + r := &uninterruptibleHydrationRemote{fakeChunkRemote: f, entered: make(chan struct{}), release: make(chan struct{})} + var once sync.Once + release := func() { once.Do(func() { close(r.release) }) } + s, _ := newChunkTestStore(t) + cfg := ctConfig(2) + cfg.FreshFromHead = true + layer := mustAttach(t, s, r, cfg) + t.Cleanup(release) + result := startHydrationRead(t, s, context.Background(), 8) + select { + case <-r.entered: + case <-time.After(ctLocalBound): + t.Fatal("Get not entered") + } + closed := make(chan struct{}) + t.Cleanup(func() { + release() + select { + case <-closed: + case <-time.After(ctLocalBound): + t.Error("Close did not join Get") + } + }) + go func() { _ = layer.Close(); close(closed) }() + select { + case got := <-result: + if !errors.Is(got.err, errChunkLayerClosed) { + t.Fatalf("Close lost closed cause: %v", got.err) + } + case <-time.After(500 * time.Millisecond): + t.Fatal("Close did not wake hydration caller") + } + select { + case <-closed: + t.Fatal("Close abandoned uninterruptible Get") + case <-time.After(50 * time.Millisecond): + } + release() + select { + case <-closed: + case <-time.After(ctLocalBound): + t.Fatal("Close did not settle after Get release") + } +} + +// Only the old generation ignores cancellation; a spare worker can serve the new one. +type staleHydrationRemote struct { + *fakeChunkRemote + oldKey string + newEntered, newRelease chan struct{} + entered, release chan struct{} + once sync.Once +} + +func (r *staleHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) { + if key == r.oldKey { + r.once.Do(func() { close(r.entered) }) + <-r.release + return r.fakeChunkRemote.Get(context.Background(), key) + } + if r.newRelease != nil { + select { + case r.newEntered <- struct{}{}: + default: + } + select { + case <-r.newRelease: + case <-ctx.Done(): + return nil, ctx.Err() + } + } + return r.fakeChunkRemote.Get(ctx, key) +} +func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) { + s, layer, remote, registered := hydrationFixture(t, 2, 64) + layer.stMu.Lock() + oldRef, newRef := layer.head.Chunks[2], layer.head.Chunks[3] + layer.stMu.Unlock() + r := &staleHydrationRemote{fakeChunkRemote: remote, oldKey: oldRef.Key, entered: make(chan struct{}), release: make(chan struct{})} + layer.remote = r + var once sync.Once + release := func() { once.Do(func() { close(r.release) }) } + t.Cleanup(release) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + old := startHydrationRead(t, s, ctx, 8) + waitHydrationRegistration(t, registered, 1) + select { + case <-r.entered: + case <-time.After(ctLocalBound): + t.Fatal("old Get not entered") + } + layer.stMu.Lock() + layer.head.Chunks[2] = newRef + layer.absentGen[2]++ + layer.stMu.Unlock() + newer := startHydrationRead(t, s, ctx, 8) + waitHydrationRegistration(t, registered, 1) + select { + case got := <-newer: + if got.err != nil || !bytes.Equal(got.data, makeBlock(ctBlockSize, 0x4c)) { + t.Fatalf("new generation blocked by stale Get or wrong bytes: %v", got.err) + } + case <-time.After(500 * time.Millisecond): + release() + t.Fatal("new generation joined cancellation-ignoring old Get") + } + release() + if got := hydrationOutcome(t, old); got.err != nil || !bytes.Equal(got.data, makeBlock(ctBlockSize, 0x4c)) { + t.Fatalf("old waiter failed to follow new generation: %v", got.err) + } +} + +func TestChunkHydration_StaleCompletionKeepsReplacement(t *testing.T) { + s, layer, remote, registered := hydrationFixture(t, 2, 64) + layer.stMu.Lock() + oldRef, newRef := layer.head.Chunks[2], layer.head.Chunks[3] + layer.stMu.Unlock() + r := &staleHydrationRemote{fakeChunkRemote: remote, oldKey: oldRef.Key, entered: make(chan struct{}), release: make(chan struct{}), newEntered: make(chan struct{}, 1), newRelease: make(chan struct{})} + layer.remote = r + var oldOnce, newOnce sync.Once + releaseOld := func() { oldOnce.Do(func() { close(r.release) }) } + releaseNew := func() { newOnce.Do(func() { close(r.newRelease) }) } + t.Cleanup(func() { releaseOld(); releaseNew() }) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + old := startHydrationRead(t, s, ctx, 8) + waitHydrationRegistration(t, registered, 1) + select { + case <-r.entered: + case <-time.After(ctLocalBound): + t.Fatal("old Get not entered") + } + layer.stMu.Lock() + layer.head.Chunks[2] = newRef + layer.absentGen[2]++ + layer.stMu.Unlock() + newer := startHydrationRead(t, s, ctx, 8) + select { + case <-r.newEntered: + case <-time.After(ctLocalBound): + t.Fatal("replacement Get not entered") + } + layer.stMu.Lock() + replacement := layer.hydration[2] + layer.stMu.Unlock() + releaseOld() + deadline := time.NewTimer(time.Second) + defer deadline.Stop() + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for layer.Stats().Hydration.Active != 1 { + select { + case <-tick.C: + case <-deadline.C: + t.Fatal("stale worker did not settle") + } + } + layer.stMu.Lock() + kept := layer.hydration[2] == replacement + layer.stMu.Unlock() + if !kept { + t.Fatal("stale completion removed replacement promise") + } + releaseNew() + for _, result := range []<-chan hydrationResult{old, newer} { + if got := hydrationOutcome(t, result); got.err != nil || !bytes.Equal(got.data, makeBlock(ctBlockSize, 0x4c)) { + t.Fatalf("replacement data: %v", got.err) + } + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 4c10814263..a2e6c10709 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -4,7 +4,7 @@ package storage // // Lock order (never reversed): // -// capMu -> WALStore.captureMu -> WALStore.lifecycleMu -> WALStore.mu +// installMu (BASE transitions only) -> capMu -> WALStore.captureMu -> WALStore.lifecycleMu -> WALStore.mu // extentMu[i] -> stMu // WALStore.mu -> bmMu -> stMu (BeforeCheckpointAdvance runs under mu) // @@ -33,6 +33,9 @@ import ( // chunkHooks is what the WALStore holds for an attached layer. type chunkHooks struct { + beforeMutation func(first, count uint64) + beforeDestructive func() func() + sink chunkSink closer func() error // mutated runs after every dirty-map insert (a write, a batch write, @@ -41,6 +44,8 @@ type chunkHooks struct { // recovered runs when Recover republished the dirty map (any chunk // may have changed), before reads resume. recovered func() + // Acquired only under installMu exclusive, before every lower store lock. + baseTransitionV3 func() (release func(), err error) } const defaultReadMissTimeout = 30 * time.Second @@ -59,11 +64,20 @@ type chunkLayerImpl struct { cancel context.CancelFunc wg sync.WaitGroup // captures and fills in flight + cowMu sync.Mutex // window admission only; never held during reads or joins + cow *cutCOWWindow + cowActive atomic.Pointer[cutCOWWindow] + cowTransitions int + cowClosed bool + capMu sync.Mutex // serializes Capture, Evict, Begin/EndBaseInstall bmMu sync.Mutex // serializes bitmap store calls presMu sync.Mutex // serializes a whole presence save: snapshot, fsync, replace, version - closeDone chan struct{} // closed when Close has finished + hydration map[uint64]*chunkHydrationFlight // under stMu + hydrationWake chan struct{} + hydrationStarted bool + closeDone chan struct{} // closed when Close has finished stMu sync.Mutex closed bool @@ -112,12 +126,18 @@ type chunkLayerImpl struct { keySeq uint64 // Test-only scheduling hooks; nil in production. - testPresenceSnapshotHook func() // after a presence snapshot, before it is written - testAfterAdmitHook func() // right after a capture is admitted - testAfterStageHook func(round int) // after each pre-copy staging round - testAfterStageReadHook func(idx uint64) // after a staging read, before its result is kept - testAfterBarrierSyncHook func(h uint64) // under the capture barrier, right after Sync fixed H - syncDirFn func(dir string) error // directory fsync after a rename; syncDir in production + testHydrationWait func(uint64) // after promise registration, outside locks + testCOWWait func() + testCOWRead func(idx uint64, saved bool) + testCOWSave func() error + testPresenceSnapshotHook func() // after a presence snapshot, before it is written + testBaseTransitionBeforeLock func() // test handshake before capMu drain + testAfterAdmitHook func() // right after a capture is admitted + testAfterStageHook func(round int) // after each pre-copy staging round + testAfterStageReadHook func(idx uint64) // after a staging read, before its result is kept + testAfterBarrierSyncHook func(h uint64) // under the capture barrier, right after Sync fixed H + testBeforeBarrierLockHook func() // right before the capture barrier's Lock request + syncDirFn func(dir string) error // directory fsync after a rename; syncDir in production // Absence: chunks whose local bytes are not authoritative (fresh host, // evicted), and blocks written locally inside such chunks since. @@ -131,8 +151,30 @@ type chunkLayerImpl struct { } func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) (chunkLayer, error) { - if remote == nil || cfg.Bitmap == nil || cfg.ChunkBlocks == 0 { - return nil, errors.New("storage: chunk layer needs a remote, a bitmap store and ChunkBlocks > 0") + mapped := s.v3 != nil && s.v3.mapProof != nil + if remote == nil || cfg.ChunkBlocks == 0 || (!mapped && cfg.Bitmap == nil) { + return nil, errors.New("storage: chunk layer needs a remote, ChunkBlocks > 0 and a legacy bitmap unless the store owns an impl3 map") + } + var localBase bool + s.captureMu.Lock() + defer s.captureMu.Unlock() + if s.attachClosed { + return nil, errChunkLayerClosed + } + if mapped { + // Serialize hook publication with begin/complete. Their outer hook + // snapshot is rechecked after taking this same barrier. + d := s.v3.pub.current() + if d.BaseState == BaseInstalling { + return nil, ErrBaseIncomplete + } + localBase = d.BaseState == BaseInstalled + if localBase { + cfg.FreshFromHead = false + } + } + if s.v3 != nil && s.v3.ownedMap != nil && uint64(cfg.ChunkBlocks) != s.v3.ownedMap.chunkBlocks { + return nil, fmt.Errorf("%w: chunk layer geometry differs from owned map", ErrMapInvalid) } if cfg.UploadConcurrency < 0 || cfg.UploadConcurrency > 64 { return nil, errors.New("storage: upload concurrency must be between 1 and 64 (0 defaults to 8)") @@ -140,9 +182,24 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) if cfg.UploadConcurrency == 0 { cfg.UploadConcurrency = 8 } + if cfg.HydrationWorkers < 0 || cfg.HydrationWorkers > 64 || cfg.HydrationQueueDepth < 0 || cfg.HydrationQueueDepth > 65536 { + return nil, errors.New("storage: hydration workers must be 1..64 and queue depth 1..65536 (0 uses defaults)") + } + if cfg.HydrationWorkers == 0 { + cfg.HydrationWorkers = defaultHydrationWorkers + } + if cfg.HydrationQueueDepth == 0 { + cfg.HydrationQueueDepth = defaultHydrationQueueDepth + } if cfg.ReadMissTimeout <= 0 { cfg.ReadMissTimeout = defaultReadMissTimeout } + if cfg.COWSpillLimit < 0 { + return nil, errors.New("storage: COW spill limit must not be negative (0 defaults to 1 GiB)") + } + if cfg.COWSpillLimit == 0 { + cfg.COWSpillLimit = defaultCOWSpillLimit + } nb := uint64(s.NumBlocks()) l := &chunkLayerImpl{ s: s, @@ -183,40 +240,53 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) // never used as this holder's publication guard. l.fenced = l.supersededBy(head) - hdr, saved, ok, err := cfg.Bitmap.Load() - if err != nil { - l.cancel() - return nil, fmt.Errorf("storage: chunk layer attach: load bitmap: %w", err) - } - switch { - case ok && hdr.Base == chunkBaseInstalling: - l.hdr = hdr // an interrupted BASE install: cuts stay refused - case ok && hdr.Base == chunkBaseInstalledAwaitingCut: - l.hdr, l.hashMode = hdr, true - case ok && hdr.BaseLSN == head.RemoteLSN && hdr.HeadGen == head.Gen && hdr.Epoch == head.Epoch: - l.hdr = hdr - for _, idx := range saved { - l.dirty[idx] = true + if mapped { + // Dirt is derived from the owned LSN map against the actual remote HEAD; + // no local HEAD-period bitmap header is loaded or created for impl3. + l.hdr = chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: head.Epoch} + } else { + hdr, saved, ok, err := cfg.Bitmap.Load() + if err != nil { + l.cancel() + return nil, fmt.Errorf("storage: chunk layer attach: load bitmap: %w", err) } - case !ok && cfg.FreshFromHead: - // A fresh local volume has taken no write yet (I/O waits for its - // first attach): its image is HEAD's, so nothing is dirty. Start with - // an empty bitmap bound to HEAD instead of hash mode, which stays for - // an existing volume whose bitmap is lost (integration ruling F1). - fresh := chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: head.Epoch, Base: chunkBaseNone} - if err := cfg.Bitmap.WriteHeader(fresh); err != nil { - l.hashMode = true // safe: compare every chunk on the first cut - } else { - l.hdr = fresh - } - default: - if ok { + switch { + case ok && hdr.Base == chunkBaseInstalling: + l.hdr = hdr // an interrupted BASE install: cuts stay refused + case ok && hdr.Base == chunkBaseInstalledAwaitingCut: + l.hdr, l.hashMode = hdr, true + case ok && hdr.BaseLSN == head.RemoteLSN && hdr.HeadGen == head.Gen && hdr.Epoch == head.Epoch: l.hdr = hdr + for _, idx := range saved { + l.dirty[idx] = true + } + case !ok && cfg.FreshFromHead: + // A fresh local volume has taken no write yet (I/O waits for its + // first attach): its image is HEAD's, so nothing is dirty. Start with + // an empty bitmap bound to HEAD instead of hash mode, which stays for + // an existing volume whose bitmap is lost (integration ruling F1). + fresh := chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: head.Epoch, Base: chunkBaseNone} + if err := cfg.Bitmap.WriteHeader(fresh); err != nil { + l.hashMode = true // safe: compare every chunk on the first cut + } else { + l.hdr = fresh + } + default: + if ok { + l.hdr = hdr + } + l.hashMode = true } - l.hashMode = true + } - if cfg.FreshFromHead { + if localBase { + // The completed BASE image is local authority, including ZERO blocks. + // Never revive old HEAD absence after a crash before its first cut. + l.hdr.Base = chunkBaseInstalledAwaitingCut + l.allDirty = true + l.presenceVer++ + } else if cfg.FreshFromHead { // An existing HEAD defines the fresh host's lazy image. With no HEAD, // local writes may already have checkpointed out of the WAL dirty map: // preserve ALL chunks as candidates for the first hash-comparing cut. @@ -224,16 +294,18 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.hdr = chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: cfg.Epoch} var initialDirty []uint64 l.dirty = map[uint64]bool{} - l.hashMode = head.Gen == 0 && s.NextLSN() > 1 + l.hashMode = !mapped && head.Gen == 0 && s.NextLSN() > 1 if l.hashMode { for idx := uint64(0); idx < l.numChunks; idx++ { l.dirty[idx] = true initialDirty = append(initialDirty, idx) } } - if err := cfg.Bitmap.Reset(l.hdr, initialDirty, chunkDelta{}); err != nil { - l.cancel() - return nil, fmt.Errorf("storage: fresh bitmap reset: %w", err) + if !mapped { + if err := cfg.Bitmap.Reset(l.hdr, initialDirty, chunkDelta{}); err != nil { + l.cancel() + return nil, fmt.Errorf("storage: fresh bitmap reset: %w", err) + } } for idx := range head.Chunks { l.absent[idx] = true @@ -245,6 +317,11 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) return nil, err } hooks := &chunkHooks{sink: l, closer: l.Close, mutated: l.noteMutation, recovered: l.noteAllMutated} + if mapped { + hooks.baseTransitionV3 = l.holdBaseTransitionV3 + hooks.beforeMutation = l.beforeCOWMutation + hooks.beforeDestructive = l.holdCOWDestructive + } if !s.chunk.CompareAndSwap(nil, hooks) { l.cancel() return nil, errors.New("storage: a chunk layer is already attached") @@ -336,11 +413,42 @@ func (l *chunkLayerImpl) noteAllMutated() { } } -// walChunks returns the chunks with entries in the WAL dirty map. -func (l *chunkLayerImpl) walChunks() map[uint64]bool { +// captureCandidates includes current WAL entries and impl3 owned-map dirt. +// UNKNOWN never certifies clean; a max LSN beyond HEAD must be captured even +// after the WAL entry has checkpointed and the legacy bitmap says clean. +func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { out := map[uint64]bool{} + mapped := l.usesOwnedMapV3() + var base uint64 + if mapped { + l.stMu.Lock() + base = l.remoteLSN + l.stMu.Unlock() + } for _, e := range l.s.dm.snapshot() { - out[l.chunkOf(e.LBA)] = true + // Retention in the local WAL is not dirt since HEAD. Lower-LSN + // BASE/direct changes remain conservative through UNKNOWN below. + if !mapped || e.LSN > base { + out[l.chunkOf(e.LBA)] = true + } + } + if mapped { + l.stMu.Lock() + absent := map[uint64]bool{} + for idx := range l.absent { + if !l.chunkHasLocalLocked(idx) { + absent[idx] = true + } + } + l.stMu.Unlock() + l.s.mu.RLock() + for idx, e := range l.s.v3.mapEntries { + i := uint64(idx) + if !absent[i] && (e.Unknown || e.LSN > base) { + out[i] = true + } + } + l.s.mu.RUnlock() } return out } @@ -354,6 +462,16 @@ func (l *chunkLayerImpl) chunkVersion(idx uint64) uint64 { // frontier path, under WALStore.mu: it makes the dirty set (and any changed // absence state) durable before the checkpoint can pass the entries. func (l *chunkLayerImpl) BeforeCheckpointAdvance(lsn uint64) error { + if l.usesOwnedMapV3() && l.s.v3.pub.current().BaseState == BaseInstalling { + // Serving/capture remain blocked by the installing descriptor. Settle + // local BASE authority before the installed descriptor can publish; + // a failure leaves the volume installing, never serving a partial image. + l.stMu.Lock() + l.absent = map[uint64]bool{} + l.localBlocks = map[uint64]bool{} + l.presenceVer++ + l.stMu.Unlock() + } if err := l.saveDirty(); err != nil { return err } @@ -363,6 +481,12 @@ func (l *chunkLayerImpl) BeforeCheckpointAdvance(lsn uint64) error { // saveDirty persists dirty ∪ inflight ∪ the chunks of WAL entries still in // the dirty map (all chunks when a BASE block landed or the set is unknown). func (l *chunkLayerImpl) saveDirty() error { + // Impl3's actual checkpoint caller persists its owned map after this + // callback. It already tracks WAL mutations independently of this layer; + // making a second persistent C11 bitmap would add no coverage authority. + if l.usesOwnedMapV3() { + return nil + } l.bmMu.Lock() defer l.bmMu.Unlock() set := l.dirtySetLocked(nil) @@ -423,45 +547,7 @@ func sortedKeys(m map[uint64]bool) []uint64 { // block that has no newer local version, then lets the store read its // extent. It runs with no walstore lock held. func (l *chunkLayerImpl) OnReadMiss(lba uint64) ([]byte, error) { - idx := l.chunkOf(lba) - l.stMu.Lock() - if l.closed || !l.absent[idx] || l.localBlocks[lba] { - l.stMu.Unlock() - return nil, nil - } - l.wg.Add(1) - l.stMu.Unlock() - defer l.wg.Done() - // One deadline covers every attempt. Each attempt fetches the chunk as - // the current HEAD names it; a fill that went stale (eviction generation - // or HEAD ref changed meanwhile) installs nothing and the read retries, - // so the extent is read only once the block is resolved: the chunk is no - // longer absent, or the block has a local version. - ctx, cancel := context.WithTimeout(l.ctx, l.cfg.ReadMissTimeout) - defer cancel() - for { - l.stMu.Lock() - if !l.absent[idx] || l.localBlocks[lba] { - l.stMu.Unlock() - return nil, nil - } - ref, ok := l.head.Chunks[idx] - gen := l.absentGen[idx] - l.stMu.Unlock() - if !ok { // ZERO in the current HEAD - return make([]byte, l.blockSize), nil - } - resolved, err := l.fillOnce(ctx, idx, gen, ref) - if err != nil { - return nil, err - } - if resolved { - return nil, nil - } - if err := ctx.Err(); err != nil { - return nil, fmt.Errorf("storage: chunk %d fetch: fill kept going stale: %w", idx, err) - } - } + return l.OnReadMissContext(context.Background(), lba) } // fillOnce fetches one chunk version and installs every block that has no @@ -559,6 +645,9 @@ func (l *chunkLayerImpl) EndBaseInstall(frontier uint64) error { } func (l *chunkLayerImpl) writeBaseState(state chunkBaseState, apply func()) error { + if l.usesOwnedMapV3() { + return fmt.Errorf("%w: BASE state must be published by the descriptor install protocol", errV3NotYet) + } l.bmMu.Lock() defer l.bmMu.Unlock() l.stMu.Lock() @@ -596,7 +685,15 @@ func (l *chunkLayerImpl) register() (done func(), err error) { return l.wg.Done, nil } -func (l *chunkLayerImpl) admit() error { +func (l *chunkLayerImpl) admit() (err error) { + defer func() { + if err != nil { + l.abortCOW(err) + } + }() + if l.usesOwnedMapV3() && l.s.v3.pub.current().BaseState == BaseInstalling { + return fmt.Errorf("%w: %w", errChunkCaptureRefused, errChunkBaseInstalling) + } l.stMu.Lock() closed, fenced, base, detached := l.closed, l.fenced, l.hdr.Base, l.detached != nil l.stMu.Unlock() @@ -607,7 +704,7 @@ func (l *chunkLayerImpl) admit() error { return errChunkLayerFenced case detached: return errChunkLayerDetached - case base == chunkBaseInstalling: + case base == chunkBaseInstalling && !l.usesOwnedMapV3(): return fmt.Errorf("%w: %w", errChunkCaptureRefused, errChunkBaseInstalling) } if gate := l.cfg.CaptureAllowed; gate != nil { @@ -658,11 +755,12 @@ func (l *chunkLayerImpl) MakeRemoteDurable(ctx context.Context, t uint64) error } type capturedChunk struct { - idx uint64 - data []byte - sum [32]byte - zero bool - key string // staged: already uploaded under this key (data is nil) + idx uint64 + data []byte + sum [32]byte + zero bool + key string // staged: already uploaded under this key (data is nil) + birth uint64 } // stagedChunk is a chunk pre-copied outside the barrier at chunk version @@ -720,9 +818,17 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch return chunkCutResult{}, err } - // Quiesced cut. + // Quiesced cut. The guest pause starts at the Lock REQUEST: a pending + // writer blocks new readers of captureMu, so a write arriving while the cut + // waits for writers already holding it (e.g. parked in WAL admission) is + // paused too. LockWaitNs reports that wait on its own. + pauseStart := time.Now() + if hook := l.testBeforeBarrierLockHook; hook != nil { + hook() + } l.s.captureMu.Lock() barrier := time.Now() + st.LockWaitNs = barrier.Sub(pauseStart).Nanoseconds() h, err := l.s.Sync() st.SyncNs = time.Since(barrier).Nanoseconds() if hook := l.testAfterBarrierSyncHook; hook != nil && err == nil { @@ -730,12 +836,12 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } if err != nil { l.s.captureMu.Unlock() - st.BarrierPauseNs = time.Since(barrier).Nanoseconds() + st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() l.dropIntents(ctx, intents) // a clean abort: staged keys are released return chunkCutResult{}, fmt.Errorf("storage: capture sync: %w", err) } candidates := map[uint64]bool{} - for idx := range l.walChunks() { + for idx := range l.captureCandidates() { candidates[idx] = true } l.stMu.Lock() @@ -757,8 +863,15 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // it since staging (its version is unchanged) and HEAD is the one it // was compared against. var captured []capturedChunk + var capturedVersions map[uint64]uint64 + if l.usesOwnedMapV3() { + capturedVersions = make(map[uint64]uint64, len(candidates)) + } useStaged := map[uint64]bool{} for idx := range candidates { + if capturedVersions != nil { + capturedVersions[idx] = l.chunkVersion(idx) + } if sc, ok := staged[idx]; ok && sc.ver == l.chunkVersion(idx) && sc.headGen == l.head.Gen { useStaged[idx] = true captured = append(captured, sc.capturedChunk) @@ -770,25 +883,43 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.cutLSN = h baseHead := copyHead(l.head) l.stMu.Unlock() + // Candidates, mutation versions and births belong to the same barrier. + // Do not sample the owned map after COW writers are admitted again. + births := l.captureBirths(candidates, h) st.CandidateChunks = len(candidates) - st.BarrierCopyChunks = len(candidates) - len(useStaged) var copyErr error copyStart := time.Now() - for _, idx := range sortedKeys(candidates) { - if useStaged[idx] { - continue + if l.usesOwnedMapV3() { + var w *cutCOWWindow + w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks) + l.s.captureMu.Unlock() + st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() + copyStart = time.Now() + if copyErr == nil { + var copied []capturedChunk + copied, copyErr = l.copyCOWWindow(ctx, w) + captured = append(captured, copied...) + st.COWSavedChunks = int(w.saved.Load()) + st.COWSaveNs, st.COWWaitNs = w.saveNs.Load(), w.waitNs.Load() } - buf, err := l.readChunk(idx) - if err != nil { - copyErr = err - break + } else { + st.BarrierCopyChunks = len(candidates) - len(useStaged) + for _, idx := range sortedKeys(candidates) { + if useStaged[idx] { + continue + } + buf, err := l.readChunk(idx) + if err != nil { + copyErr = err + break + } + captured = append(captured, capturedChunk{idx: idx, data: buf, sum: sha256.Sum256(buf), zero: isAllZero(buf)}) } - captured = append(captured, capturedChunk{idx: idx, data: buf, sum: sha256.Sum256(buf), zero: isAllZero(buf)}) + l.s.captureMu.Unlock() + st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() } st.CopyNs = time.Since(copyStart).Nanoseconds() - l.s.captureMu.Unlock() - st.BarrierPauseNs = time.Since(barrier).Nanoseconds() if copyErr != nil { l.abortCut(all) l.dropIntents(ctx, intents) @@ -822,6 +953,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } var uploads []upload for _, c := range captured { + c.birth = births[c.idx] ref, had := baseHead.Chunks[c.idx] switch { case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum: @@ -834,7 +966,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch continue } if c.key != "" { // staged: uploaded before the barrier - next.Chunks[c.idx] = chunkRef{Key: c.key, SHA256: c.sum} + next.Chunks[c.idx] = chunkRef{Key: c.key, SHA256: c.sum, Encoding: "full", BirthLSN: c.birth} newKeys[c.idx] = c.key changed = append(changed, c.idx) st.StagedChunksUsed++ @@ -860,14 +992,14 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error { u := uploads[i] - return l.remote.Put(ctx, u.key, u.c.data) + return l.putCaptured(ctx, u.key, u.c.data) }); err != nil { l.abortCut(all) l.dropIntents(ctx, intents) return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w: %w", errChunkRemoteUnavailable, err) } for _, u := range uploads { - next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum} + next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum, Encoding: "full", BirthLSN: u.c.birth} newKeys[u.c.idx] = u.key changed = append(changed, u.c.idx) st.UploadedChunks++ @@ -902,10 +1034,12 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.stMu.Lock() l.fenced, l.head = true, copyHead(cur) l.stMu.Unlock() + l.abortCOW(errChunkLayerFenced) return chunkCutResult{}, errChunkLayerFenced } l.finishCut(baseHead, h, nil, nil) // nothing new: no CAS - l.dropIntents(ctx, intents) // superseded staged uploads only + l.persistCapturedMapV3(capturedVersions) + l.dropIntents(ctx, intents) // superseded staged uploads only return chunkCutResult{H: h, Head: copyHead(baseHead), Noop: true, FullHash: all}, nil } if err := l.admit(); err != nil { // admission re-checked right before the CAS @@ -919,6 +1053,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.stMu.Lock() l.fenced = true l.stMu.Unlock() + l.abortCOW(errChunkLayerFenced) return chunkCutResult{}, errChunkLayerFenced } expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch} @@ -934,6 +1069,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if casErr == nil { next.Gen = gen l.finishCut(next, h, changed, newKeys) + l.persistCapturedMapV3(capturedVersions) l.dropIntents(ctx, intents) return l.cutDone(chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, detach), nil } @@ -963,6 +1099,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if sameProposal(cur, next) { st.CASResult = "resolved-by-reread" l.finishCut(cur, h, changed, newKeys) + l.persistCapturedMapV3(capturedVersions) l.dropIntents(ctx, intents) return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil } @@ -974,6 +1111,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.fenced = true l.head = copyHead(cur) l.stMu.Unlock() + l.abortCOW(errChunkLayerFenced) return chunkCutResult{}, errors.Join(errChunkLayerFenced, casErr) } l.stMu.Lock() @@ -1005,6 +1143,75 @@ func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { return r, err } +// SettleDetach: see chunkLayer. Only an unresolved DETACH proposal needs a +// remote decision: if HEAD is still that CAS's base, it is cancelled by a CAS +// at the same base to the non-detached base image (this holder, this epoch), +// so whichever lands first decides and the detach can never land after a +// successful cancel. resolvePending would re-propose the detach instead. +func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (detachSettlement, chunkCutResult, error) { + l.capMu.Lock() + defer l.capMu.Unlock() + if r, ok := l.storedDetach(); ok { + return detachApplied, r, nil + } + l.stMu.Lock() + fenced, pending, isDetach, base, intents := l.fenced, l.pending, l.pendingDetach, l.pendingBase, l.pendingIntents + baseHead := copyHead(l.head) + l.stMu.Unlock() + if fenced { + return detachFenced, chunkCutResult{}, nil + } + if pending == nil || !isDetach { + // Nothing of this detach can land: it failed before its CAS or was + // definitely refused (an unresolved ordinary cut settles as usual). + return detachNotPublished, chunkCutResult{}, nil + } + cur, err := l.remote.GetHead(ctx) + if err != nil { + return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved: %w: %w", errChunkCASOutcomeUnknown, err) + } + if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + if err := l.admit(); err != nil { + return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (%w); cancel refused: %w", errChunkCASOutcomeUnknown, err) + } + cancel := copyHead(baseHead) + cancel.Epoch, cancel.Holder = l.cfg.Epoch, l.cfg.Holder + cancel.State, cancel.DetachedBy = chunkHeadActive, nil + gen, casErr := l.remote.CASHead(ctx, base, cancel) + if casErr == nil { + cancel.Gen = gen + cur = cancel + } else if cur, err = l.remote.GetHead(ctx); err != nil { + return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): %w: %w", casErr, errChunkCASOutcomeUnknown, err) + } else if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown) + } + } + // Settled: the detach landed, or it can never land. + l.dropIntents(ctx, intents) + l.stMu.Lock() + defer l.stMu.Unlock() + cut := l.pendingCut + l.pending, l.pendingIntents = nil, nil + l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} + switch { + case sameProposal(cur, *pending): + l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN + cut.Head = copyHead(cur) + l.detached = &cut + r := cut + r.Head = copyHead(cur) + return detachApplied, r, nil + case l.supersededBy(cur): + l.fenced = true + l.head = copyHead(cur) + return detachFenced, chunkCutResult{}, nil + default: + l.head = copyHead(cur) + return detachNotPublished, chunkCutResult{}, nil + } +} + func (l *chunkLayerImpl) storedDetach() (chunkCutResult, bool) { l.stMu.Lock() defer l.stMu.Unlock() @@ -1059,7 +1266,13 @@ func sameProposal(cur, next chunkHead) bool { } // resolvePending re-reads HEAD when an earlier CAS outcome is unresolved. -func (l *chunkLayerImpl) resolvePending(ctx context.Context) error { +func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { + // Registered before the state unlock, so invalidation runs without stMu. + defer func() { + if errors.Is(err, errChunkLayerFenced) { + l.abortCOW(err) + } + }() l.stMu.Lock() pending, base, intents := l.pending, l.pendingBase, l.pendingIntents l.stMu.Unlock() @@ -1163,8 +1376,14 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error func (l *chunkLayerImpl) Stats() chunkLayerStats { l.stMu.Lock() - defer l.stMu.Unlock() out := l.stats + out.Hydration.WorkerLimit = l.cfg.HydrationWorkers + out.Hydration.QueueDepth = l.cfg.HydrationQueueDepth + for _, f := range l.hydration { + if !f.running { + out.Hydration.Queued++ + } + } out.CutsRefused = make(map[string]uint64, len(l.stats.CutsRefused)) for k, v := range l.stats.CutsRefused { out.CutsRefused[k] = v @@ -1174,6 +1393,10 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats { out.Reconciling = l.hashMode out.ReconcileTotal = l.reconcileTotal out.ReconcileDone = l.reconcileTotal - len(l.reconcile) + l.stMu.Unlock() + if l.usesOwnedMapV3() { + out.DirtyChunks = len(l.captureCandidates()) + } return out } @@ -1317,11 +1540,13 @@ func (l *chunkLayerImpl) finishReconcile(gen uint64) bool { // The dirty set first, then the header naming HEAD: a crash between // the two leaves the old header, which mismatches HEAD, so the next // attach reconciles again instead of trusting an incomplete bitmap. - if err := l.cfg.Bitmap.Save(sortedKeys(still)); err != nil { - return false - } - if err := l.cfg.Bitmap.WriteHeader(hdr); err != nil { - return false + if !l.usesOwnedMapV3() { + if err := l.cfg.Bitmap.Save(sortedKeys(still)); err != nil { + return false + } + if err := l.cfg.Bitmap.WriteHeader(hdr); err != nil { + return false + } } l.stMu.Lock() defer l.stMu.Unlock() @@ -1428,7 +1653,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint staged := map[uint64]stagedChunk{} var intents []string for round := 0; round < chunkStageRounds; round++ { - wal := l.walChunks() + wal := l.captureCandidates() l.stMu.Lock() need := map[uint64]bool{} consider := func(idx uint64) { @@ -1493,7 +1718,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint intents = append(intents, id) if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error { u := uploads[i] - return l.remote.Put(ctx, u.key, u.data) + return l.putCaptured(ctx, u.key, u.data) }); err != nil { return nil, intents, fmt.Errorf("storage: capture stage upload: %w: %w", errChunkRemoteUnavailable, err) } @@ -1570,12 +1795,14 @@ func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, n delta := chunkDelta{FromLSN: prevBase, ToLSN: h, Gen: head.Gen, Dirty: changed, NewKeys: newKeys} // HEAD is published; a failed Reset only leaves a stale header, which a // restart treats as a mismatch (hash compare): safe. - if err := l.cfg.Bitmap.Reset(hdr, sortedKeys(still), delta); err == nil { - l.stMu.Lock() - if ver > l.savedDirtyVer { - l.savedDirtyVer = ver + if !l.usesOwnedMapV3() { + if err := l.cfg.Bitmap.Reset(hdr, sortedKeys(still), delta); err == nil { + l.stMu.Lock() + if ver > l.savedDirtyVer { + l.savedDirtyVer = ver + } + l.stMu.Unlock() } - l.stMu.Unlock() } } @@ -1604,16 +1831,12 @@ func (l *chunkLayerImpl) EvictChunk(idx uint64) error { if idx >= l.numChunks { return fmt.Errorf("%w: chunk %d out of range", errChunkEvictRefused, idx) } - walDirty := false - for _, e := range l.s.dm.snapshot() { - if l.chunkOf(e.LBA) == idx { - walDirty = true - break - } - } + // The same owned-map/WAL dirt that capture must publish also forbids + // eviction: a later fill from the older HEAD must not overwrite it. + dirtyCandidate := l.captureCandidates()[idx] l.stMu.Lock() switch { - case l.head.Gen == 0, l.hashMode, l.allDirty, l.hdr.Base != chunkBaseNone, l.dirty[idx], l.inflight[idx], walDirty: + case l.head.Gen == 0, l.hashMode, l.allDirty, l.hdr.Base != chunkBaseNone, l.dirty[idx], l.inflight[idx], dirtyCandidate: l.stMu.Unlock() return fmt.Errorf("%w: chunk %d is dirty since HEAD or HEAD is unknown", errChunkEvictRefused, idx) } @@ -1770,8 +1993,19 @@ func (l *chunkLayerImpl) Close() error { return nil } l.closed = true + l.closeHydrationLocked() l.stMu.Unlock() + l.cowMu.Lock() + l.cowClosed = true + w := l.cow + if w != nil { + w.abort(errChunkLayerClosed) + } + l.cowMu.Unlock() l.cancel() + if w != nil { + w.join() + } l.wg.Wait() close(l.closeDone) return nil diff --git a/seaweed-block/core/storage/chunk_layer_c11_test.go b/seaweed-block/core/storage/chunk_layer_c11_test.go index acb0259f0f..4e1177a46b 100644 --- a/seaweed-block/core/storage/chunk_layer_c11_test.go +++ b/seaweed-block/core/storage/chunk_layer_c11_test.go @@ -28,6 +28,9 @@ func extentBytes(t *testing.T, s *WALStore, lba uint32) []byte { // walLogicalTail is the WAL writer's physical recycling position. func walLogicalTail(s *WALStore) uint64 { + if s.v3 != nil { + return s.v3.pub.current().RetainedTail + } s.wal.mu.Lock() defer s.wal.mu.Unlock() return s.wal.logicalTail @@ -96,7 +99,7 @@ func flushWithin(t *testing.T, s *WALStore, what string) error { // no WALStore re-entry. (A BASE mark must also be a constant-time flag; that // cost bound is measured in the implementation PR, not proven here.) func TestChunkLayer_C11_ExtentCallbackIsPureInMemory(t *testing.T) { - s, _ := newChunkTestStore(t) + s, _ := newLegacyChunkTestStore(t) f := newFakeChunkRemote() cfg := ctConfig(1) bm := cfg.Bitmap.(*fakeBitmapStore) @@ -141,7 +144,7 @@ func TestChunkLayer_C11_ExtentCallbackIsPureInMemory(t *testing.T) { // refuses the advance (checkpoint and WAL tail unchanged), and a restart // still captures the chunk from the WAL. func TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle(t *testing.T) { - s, path, crash := crashableStore(t) + s, path, crash := legacyCrashableStore(t) f := newFakeChunkRemote() cfg := ctConfig(1) bm := cfg.Bitmap.(*fakeBitmapStore) @@ -216,7 +219,7 @@ func TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle(t *testing.T) { bm.failSave = nil bm.mu.Unlock() crash() - s2, _ := reopen(t, path) + s2, _ := legacyReopen(t, path) layer2 := mustAttach(t, s2, f, cfg) before := f.stats() if _, err := layer2.Capture(ctTimeout(t)); err != nil { @@ -232,7 +235,7 @@ func TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle(t *testing.T) { // and its WAL recycled (so only the bitmap remembers it). The cut's Reset // must keep that chunk dirty, and after a crash the next capture uploads it. func TestChunkLayer_C11_RolloverKeepsPostCutDirt(t *testing.T) { - s, path, crash := crashableStore(t) + s, path, crash := legacyCrashableStore(t) f := newFakeChunkRemote() cfg := ctConfig(1) bm := cfg.Bitmap.(*fakeBitmapStore) @@ -266,7 +269,7 @@ func TestChunkLayer_C11_RolloverKeepsPostCutDirt(t *testing.T) { t.Fatal("the cut's Reset kept chunk 1, which the cut captured") } crash() - s2, _ := reopen(t, path) + s2, _ := legacyReopen(t, path) layer2 := mustAttach(t, s2, f, cfg) before := f.stats() if _, err := layer2.Capture(ctTimeout(t)); err != nil { @@ -291,7 +294,7 @@ func TestChunkLayer_C11_RolloverKeepsPostCutDirt(t *testing.T) { // Then the host crashes. func c11BaseFixture(t *testing.T, failSave, complete bool) (path string, f *fakeChunkRemote, cfg chunkLayerConfig, frontier uint64) { t.Helper() - s, path, crash := crashableStore(t) + s, path, crash := legacyCrashableStore(t) f = newFakeChunkRemote() cfg = ctConfig(1) bm := cfg.Bitmap.(*fakeBitmapStore) @@ -425,7 +428,7 @@ func rerunBase(t *testing.T, s *WALStore, layer chunkLayer, frontier uint64) { func TestChunkLayer_C11_BaseRebuildRecovery(t *testing.T) { t.Run("interrupted install", func(t *testing.T) { path, f, cfg, frontier := c11BaseFixture(t, false, false) - s2, _ := reopen(t, path) + s2, _ := legacyReopen(t, path) layer2 := mustAttach(t, s2, f, cfg) before := f.stats() if _, err := layer2.Capture(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) { @@ -439,13 +442,13 @@ func TestChunkLayer_C11_BaseRebuildRecovery(t *testing.T) { }) t.Run("completed install", func(t *testing.T) { path, f, cfg, _ := c11BaseFixture(t, false, true) - s2, _ := reopen(t, path) + s2, _ := legacyReopen(t, path) layer2 := mustAttach(t, s2, f, cfg) assertBaseCutUploadsChangedChunks(t, layer2, f, cfg) }) t.Run("bitmap save fails on the direct-frontier path", func(t *testing.T) { path, f, cfg, frontier := c11BaseFixture(t, true, false) - s2, _ := reopen(t, path) + s2, _ := legacyReopen(t, path) layer2 := mustAttach(t, s2, f, cfg) if _, err := layer2.Capture(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) { t.Fatalf("cut after an install whose frontier never became durable: got %v, want errChunkCaptureRefused", err) @@ -459,7 +462,7 @@ func TestChunkLayer_C11_BaseRebuildRecovery(t *testing.T) { // then fails; after a crash the next capture may over-report, but its image // is exact and nothing is missed. func TestChunkLayer_C11_SaveThenCheckpointFailureOverReportsOnly(t *testing.T) { - s, path, crash := crashableStore(t) + s, path, crash := legacyCrashableStore(t) f := newFakeChunkRemote() cfg := ctConfig(1) layer := mustAttach(t, s, f, cfg) @@ -477,7 +480,7 @@ func TestChunkLayer_C11_SaveThenCheckpointFailureOverReportsOnly(t *testing.T) { t.Fatal("the flush succeeded although its checkpoint publish failed") } crash() - s2, _ := reopen(t, path) + s2, _ := legacyReopen(t, path) layer2 := mustAttach(t, s2, f, cfg) if _, err := layer2.Capture(ctTimeout(t)); err != nil { t.Fatalf("capture after restart: %v", err) @@ -493,7 +496,7 @@ func TestChunkLayer_C11_SaveThenCheckpointFailureOverReportsOnly(t *testing.T) { // and keep the refs of the unchanged chunks. func c11RestartFixture(t *testing.T, beforeReattach func(bm *fakeBitmapStore)) { t.Helper() - s, path, crash := crashableStore(t) + s, path, crash := legacyCrashableStore(t) f := newFakeChunkRemote() cfg := ctConfig(1) bm := cfg.Bitmap.(*fakeBitmapStore) @@ -511,7 +514,7 @@ func c11RestartFixture(t *testing.T, beforeReattach func(bm *fakeBitmapStore)) { t.Fatal(err) } crash() - s2, _ := reopen(t, path) + s2, _ := legacyReopen(t, path) if beforeReattach != nil { bm.mu.Lock() beforeReattach(bm) @@ -567,7 +570,7 @@ func TestChunkLayer_C11_LostOrMismatchedBitmapFallsBackToHashCompare(t *testing. // promoted replica's bitmap covers its applied chunks before their WAL // entries are recycled. func TestChunkLayer_C11_ReplicaApplyKeepsBitmap(t *testing.T) { - s, _ := newChunkTestStore(t) + s, _ := newLegacyChunkTestStore(t) f := newFakeChunkRemote() cfg := ctConfig(1) bm := cfg.Bitmap.(*fakeBitmapStore) diff --git a/seaweed-block/core/storage/chunk_layer_contract_test.go b/seaweed-block/core/storage/chunk_layer_contract_test.go index d4f7d83a15..86dd77f065 100644 --- a/seaweed-block/core/storage/chunk_layer_contract_test.go +++ b/seaweed-block/core/storage/chunk_layer_contract_test.go @@ -214,6 +214,11 @@ func TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites(t *testing.T) { } if err == nil { err = s.flusher.flushOnce() + // A concurrent cut can invalidate a prepared checkpoint map; + // the production worker retries this explicit stale-proof outcome. + if errors.Is(err, ErrMapCoverageStale) { + err = nil + } } if err != nil { werr <- err @@ -268,6 +273,10 @@ func TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites(t *testing.T) { // C3 barrier: a write issued while a cut is still copying its chunks does // not land until the copy is done, so it can never tear the captured image. +// It waits for the LOCAL copy only, never for SeaweedFS (design rules 1/2): +// the copy reads chunk 2's local blocks and releases the chunk; it fetches the +// absent blocks from HEAD afterwards, so the write completes with every remote +// fetch held. // The copy is held deterministically: on a fresh host the cut's copy of a // dirty chunk must fetch that chunk's absent blocks, and the fetch is held. func TestChunkLayer_C3_WriteDuringCopyWaitsForTheCut(t *testing.T) { @@ -278,7 +287,11 @@ func TestChunkLayer_C3_WriteDuringCopyWaitsForTheCut(t *testing.T) { f := newFakeChunkRemote() f.seedHead(t, src, 10, 1) s, _ := newChunkTestStore(t) - s.AdvanceFrontier(10) // the log continues from HEAD's remote_lsn (W4b's job in production) + func() { + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + }() // the log continues from HEAD's remote_lsn (W4b's job in production) cfg := ctConfig(2) cfg.FreshFromHead = true layer := mustAttach(t, s, f, cfg) @@ -287,12 +300,28 @@ func TestChunkLayer_C3_WriteDuringCopyWaitsForTheCut(t *testing.T) { t.Fatal(err) } - gEntered, gRelease := holdGets(t, f) + l := layer.(*chunkLayerImpl) + writerParked := make(chan struct{}) + var parkOnce sync.Once + l.testCOWWait = func() { parkOnce.Do(func() { close(writerParked) }) } // a writer is waiting on a COW entry + inCopy, releaseCopy := make(chan struct{}), make(chan struct{}) + var copyOnce, releaseOnce sync.Once + unblockCopy := func() { releaseOnce.Do(func() { close(releaseCopy) }) } + l.testCOWRead = func(idx uint64, _ bool) { + if idx == 2 { + copyOnce.Do(func() { close(inCopy) }) + <-releaseCopy + } + } late := makeBlock(ctBlockSize, 0xDA) wrote := make(chan error, 1) joined := make(chan struct{}) + var gRelease func() t.Cleanup(func() { - gRelease() + unblockCopy() + if gRelease != nil { + gRelease() + } select { case <-joined: case <-time.After(ctLocalBound): @@ -300,24 +329,31 @@ func TestChunkLayer_C3_WriteDuringCopyWaitsForTheCut(t *testing.T) { } }) done := startCapture(t, layer) - waitKey(t, gEntered, "the cut's fetch of an absent block in chunk 2") + cowWaitSignal(t, inCopy, "the cut copying chunk 2 inside its window") + var gEntered chan string + gEntered, gRelease = holdGets(t, f) // from here any remote fetch blocks go func() { defer close(joined) _, err := s.Write(10, late) wrote <- err }() + cowWaitSignal(t, writerParked, "the write parked on chunk 2's copy entry") select { case err := <-wrote: t.Fatalf("a write landed while the cut was still copying (err %v); the barrier was released before the copy", err) - case <-time.After(200 * time.Millisecond): // the copy is held indefinitely; the write must wait + default: // parked on the held copy's entry, as it must be } + unblockCopy() // the remote stays held: the write may wait only for the local copy + if err := waitErr(t, wrote, "write after the local copy, with the remote held"); err != nil { + t.Fatal(err) + } + // The copier fetches chunk 2's absent blocks from HEAD only now, after it + // released the entry: the write above completed with that fetch held. + waitKey(t, gEntered, "the copier's HEAD fetch of chunk 2's absent blocks, off the write path") gRelease() if err := waitErr(t, done, "held cut"); err != nil { t.Fatalf("held cut: %v", err) } - if err := waitErr(t, wrote, "write after the cut"); err != nil { - t.Fatal(err) - } img := f.imageOf(t, f.stats().head) if !bytes.Equal(blockOf(img, 8), local) { t.Fatal("the cut's image lacks the write made before its barrier") @@ -382,29 +418,38 @@ func TestChunkLayer_C4_WritesDuringUploadAndBaseAreCapturedNext(t *testing.T) { t.Fatalf("second HEAD remote_lsn %d still misses the mid-upload write %d", h.RemoteLSN, during) } - // Rebuild BASE, bracketed: no cut runs between Begin and End. - if err := layer.BeginBaseInstall(); err != nil { - t.Fatalf("BeginBaseInstall: %v", err) - } + // Rebuild through the v3 store handle. The admitted BASE is the full + // image at the last cut, plus the replacement block, at a new floor. + image := f.imageOf(t, f.stats().head) base := makeBlock(ctBlockSize, 0xBA) - if err := s.WriteExtentDirect(20, base); err != nil { + copy(image[20*ctBlockSize:21*ctBlockSize], base) + frontier := during + 10 + handle, err := s.BeginBaseInstall(frontier, [16]byte{0x44}) + if err != nil { t.Fatal(err) } - frontier := during + 10 - s.AdvanceFrontier(frontier) + for lba := uint32(0); lba < ctNumBlocks; lba++ { + data := image[int(lba)*ctBlockSize : int(lba+1)*ctBlockSize] + if err := handle.WriteBase(lba, data); err != nil { + t.Fatal(err) + } + } w.record(frontier, 20, base) - if _, err := s.Sync(); err != nil { - t.Fatal(err) + if _, err := s.Sync(); !errors.Is(err, ErrBaseInstalling) { + t.Fatalf("logical Sync during install: %v", err) } before := f.stats() if _, err := layer.Capture(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) { - t.Fatalf("Capture during a BASE install: got %v, want errChunkCaptureRefused", err) + t.Fatalf("capture while installing: %v", err) } if after := f.stats(); after.puts != before.puts || after.cas != before.cas { - t.Fatalf("capture during a BASE install made %d puts and %d CAS calls", after.puts-before.puts, after.cas-before.cas) + t.Fatal("capture during install made remote effects") } - if err := layer.EndBaseInstall(frontier); err != nil { - t.Fatalf("EndBaseInstall after the durable frontier: %v", err) + if err := handle.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) } waitReconciledForTest(t, layer) // the BASE is reconciled against HEAD first if _, err := layer.Capture(ctTimeout(t)); err != nil { diff --git a/seaweed-block/core/storage/chunk_layer_detach_test.go b/seaweed-block/core/storage/chunk_layer_detach_test.go index 4561a815a7..027492f0fa 100644 --- a/seaweed-block/core/storage/chunk_layer_detach_test.go +++ b/seaweed-block/core/storage/chunk_layer_detach_test.go @@ -111,7 +111,11 @@ func TestChunkCut_NewHolderClearsDetachedState(t *testing.T) { f.mu.Unlock() s, _ := newChunkTestStore(t) - s.AdvanceFrontier(10) // the log continues from HEAD's remote_lsn (W4b's job in production) + func() { + if err := s.SeedChunkFrontier(10); err != nil { + t.Fatal(err) + } + }() // the log continues from HEAD's remote_lsn (W4b's job in production) cfg := ctConfig(2) cfg.FreshFromHead = true layer := mustAttach(t, s, f, cfg) diff --git a/seaweed-block/core/storage/chunk_layer_fresh_bitmap_test.go b/seaweed-block/core/storage/chunk_layer_fresh_bitmap_test.go index aabc2f8c9d..f0a06ffbdc 100644 --- a/seaweed-block/core/storage/chunk_layer_fresh_bitmap_test.go +++ b/seaweed-block/core/storage/chunk_layer_fresh_bitmap_test.go @@ -53,7 +53,7 @@ func TestChunkLayer_LostBitmapReconciles(t *testing.T) { copy(src, makeBlock(ctBlockSize, 0x44)) // HEAD's block 0 differs from the local image f := newFakeChunkRemote() f.seedHead(t, src, 0, 0) // an older epoch: this holder may publish over it - s, _ := newChunkTestStore(t) + s, _ := newLegacyChunkTestStore(t) layer := mustAttach(t, s, f, ctConfig(1)) // waits for reconciliation if st := layer.Stats(); st.Reconciling || st.ReconcileTotal == 0 || st.ReconcileDone != st.ReconcileTotal { t.Fatalf("an existing volume without a bitmap did not reconcile: reconciling=%v done=%d/%d", st.Reconciling, st.ReconcileDone, st.ReconcileTotal) diff --git a/seaweed-block/core/storage/chunk_layer_intent_test.go b/seaweed-block/core/storage/chunk_layer_intent_test.go index 1517f2cf30..858e15bf80 100644 --- a/seaweed-block/core/storage/chunk_layer_intent_test.go +++ b/seaweed-block/core/storage/chunk_layer_intent_test.go @@ -286,10 +286,10 @@ func TestChunkIntent_AdmissionRefusedBeforeCASDeletesIntent(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() cfg := ctConfig(1) - calls := 0 cfg.CaptureAllowed = func() error { - calls++ - if calls >= 2 { // the cut's start passes; the check before the CAS refuses + // The gate is checked concurrently between COW claims as well. Bind + // demotion to the real upload event, not a call count/schedule. + if f.stats().puts > 0 { // uploaded under an intent, before the CAS return errors.New("demoted") } return nil @@ -300,6 +300,9 @@ func TestChunkIntent_AdmissionRefusedBeforeCASDeletesIntent(t *testing.T) { if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) { t.Fatalf("cut refused before its CAS: %v", err) } + if f.stats().puts == 0 { + t.Fatal("control did not reach the intent-protected upload") + } if n := f.stats().cas; n != 0 { t.Fatalf("refused cut issued %d CAS", n) } diff --git a/seaweed-block/core/storage/chunk_layer_lsn_order_test.go b/seaweed-block/core/storage/chunk_layer_lsn_order_test.go index 467ef39780..988c9b6805 100644 --- a/seaweed-block/core/storage/chunk_layer_lsn_order_test.go +++ b/seaweed-block/core/storage/chunk_layer_lsn_order_test.go @@ -15,7 +15,7 @@ func TestChunkCut_RemoteLSNNeverDecreases(t *testing.T) { copy(src, makeBlock(ctBlockSize, 0x44)) f := newFakeChunkRemote() f.seedHead(t, src, 10, 1) - s, _ := newChunkTestStore(t) + s, _ := newLegacyChunkTestStore(t) cfg := ctConfig(2) cfg.FreshFromHead = true layer := mustAttach(t, s, f, cfg) diff --git a/seaweed-block/core/storage/chunk_layer_map_only_v3_test.go b/seaweed-block/core/storage/chunk_layer_map_only_v3_test.go new file mode 100644 index 0000000000..afc0c65e53 --- /dev/null +++ b/seaweed-block/core/storage/chunk_layer_map_only_v3_test.go @@ -0,0 +1,151 @@ +package storage + +import ( + "bytes" + "errors" + "os" + "testing" + "time" +) + +func TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 5, 5) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.Bitmap = nil + cfg.BarrierBound = 1 + layer := mustAttach(t, s, f, cfg) + first, err := layer.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(f.imageOf(t, first.Head)[5*ctBlockSize:6*ctBlockSize], blk(5)) { + t.Fatal("map-only capture omitted checkpointed bytes") + } + if _, err = s.Write(5, blk(8)); err != nil { + t.Fatal(err) + } + if _, err = s.Sync(); err != nil { + t.Fatal(err) + } + if err = s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + second, err := layer.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(f.imageOf(t, second.Head)[5*ctBlockSize:6*ctBlockSize], blk(8)) { + t.Fatal("map-only checkpoint/capture omitted later bytes") + } + if _, err = os.Stat(path + ".chunkbitmap"); !os.IsNotExist(err) { + t.Fatalf("impl3 created or used a legacy bitmap: %v", err) + } + if layer.Stats().DirtyChunks != 0 { + t.Error("verified map-only capture remains dirty") + } +} + +func TestChunkLayerV3_IgnoresProvidedLegacyBitmap(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + b := newFakeBitmap() + b.failSave = errors.New("legacy bitmap must not be used") + cfg.Bitmap = b + layer := mustAttach(t, s, f, cfg) + if layer.Stats().DirtyChunks == 0 { + t.Error("owned-map UNKNOWN missing from status") + } + writeSynced(t, s, 5, 5) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + b.mu.Lock() + calls := b.calls + b.mu.Unlock() + if calls != 0 { + t.Errorf("impl3 invoked legacy bitmap %d times", calls) + } +} +func TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 5, 5) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.Bitmap = nil + cfg.FreshFromHead = true + layer := mustAttach(t, s, f, cfg) + result, err := layer.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(f.imageOf(t, result.Head)[5*ctBlockSize:6*ctBlockSize], blk(5)) { + t.Fatal("fresh zero HEAD discarded checkpointed local bytes") + } +} +func TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + cfg := ctConfig(1) + cfg.Bitmap = nil + layer := mustAttach(t, s, newFakeChunkRemote(), cfg).(*chunkLayerImpl) + before := s.v3.pub.current() + if err := layer.BeginBaseInstall(); !errors.Is(err, errV3NotYet) { + t.Fatalf("legacy begin mutated impl3 BASE: %v", err) + } + if err := layer.EndBaseInstall(0); !errors.Is(err, errV3NotYet) { + t.Fatalf("legacy end mutated impl3 BASE: %v", err) + } + if s.v3.pub.current() != before { + t.Error("legacy BASE callback published a descriptor") + } + if _, err := os.Stat(path + ".chunkbitmap"); !os.IsNotExist(err) { + t.Fatalf("BASE refusal created a legacy bitmap: %v", err) + } +} +func TestChunkLayerV3_MapStatusConcurrentClose(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + cfg := ctConfig(1) + cfg.Bitmap = nil + layer := mustAttach(t, s, newFakeChunkRemote(), cfg) + begun, done := make(chan struct{}), make(chan struct{}) + t.Cleanup(func() { + select { + case <-done: + case <-time.After(ctLocalBound): + t.Error("status worker not joined") + } + }) + go func() { + defer close(done) + for i := 0; i < 1000; i++ { + layer.Stats() + if i == 0 { + close(begun) + } + } + }() + select { + case <-begun: + case <-time.After(ctLocalBound): + t.Fatal("status worker did not begin") + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + select { + case <-done: + case <-time.After(ctLocalBound): + t.Fatal("status during Close did not settle") + } +} diff --git a/seaweed-block/core/storage/chunk_layer_map_v3.go b/seaweed-block/core/storage/chunk_layer_map_v3.go new file mode 100644 index 0000000000..28b62756b0 --- /dev/null +++ b/seaweed-block/core/storage/chunk_layer_map_v3.go @@ -0,0 +1,71 @@ +package storage + +// mapProof is an immutable discriminator for this open store. ownedMap may +// be cleared by Close, so callers such as Stats must not use that cleanup +// pointer to decide which metadata format this layer implements. +func (l *chunkLayerImpl) usesOwnedMapV3() bool { return l.s.v3 != nil && l.s.v3.mapProof != nil } + +// persistCapturedMapV3 is called only after HEAD's publication is definite +// (or an authority-checked no-op), outside bmMu/stMu and the capture barrier. +// The capture's mutation versions were sampled under the quiesced barrier. +// Store.mu prevents a WAL append from slipping between the version check and +// the UNKNOWN update. A later WAL append updates max LSN and stays retained; +// an effective UNKNOWN change or lifecycle transition invalidates proofs. +// A failed map publication leaves the old disk UNKNOWN conservative; a map +// persistence failure also latches the store, while the remote HEAD remains +// the successfully captured image. No remote durability claim is undone. +func (l *chunkLayerImpl) persistCapturedMapV3(versions map[uint64]uint64) { + s := l.s + v := s.v3 + if v == nil || v.ownedMap == nil { + return + } + s.mu.Lock() + if s.stickyIOFault() != nil { + s.mu.Unlock() + return + } + var clear []uint64 + for idx, version := range versions { + if idx < uint64(len(v.mapEntries)) && v.mapEntries[idx].Unknown && l.chunkVersion(idx) == version { + clear = append(clear, idx) + } + } + if len(clear) > 0 { + if err := v.mapProof.mutatedV3(); err != nil { + s.mu.Unlock() + return + } + for _, idx := range clear { + v.mapEntries[idx].Unknown = false + } + } + v.pub.descMu.Lock() + cp := v.pub.cur.CheckpointLSN + need := false + for i, e := range v.mapEntries { + if e != v.pub.mapCurrent.entries[i] { + need = true + break + } + } + v.pub.descMu.Unlock() + s.mu.Unlock() + if !need { + return + } + prepared, err := s.prepareOwnedMapCheckpointV3(cp) + if err != nil { + return + } + v.syncMu.Lock() + defer v.syncMu.Unlock() + // The ordinary merged-coverage and proof checks handle a concurrent + // checkpoint/Recover/append. Failure retires no root or page. A later cut + // retries a cache/disk difference even if UNKNOWN was already cleared in + // memory by this verified publication. + _, _ = v.pub.publishMapV3(&s.mu, nil, prepared, func(n *descriptorV3) error { + n.W = max(n.W, v.wack.Load()) + return nil + }) +} diff --git a/seaweed-block/core/storage/chunk_layer_map_v3_test.go b/seaweed-block/core/storage/chunk_layer_map_v3_test.go new file mode 100644 index 0000000000..b3ad2be3c6 --- /dev/null +++ b/seaweed-block/core/storage/chunk_layer_map_v3_test.go @@ -0,0 +1,208 @@ +package storage + +import ( + "bytes" + "errors" + "testing" +) + +func TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 5, 5) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if s.dm.len() != 0 { + t.Fatal("setup requires checkpointed data with no WAL dirty entry") + } + f := newFakeChunkRemote() + cfg := ctConfig(1) + // The legacy bitmap deliberately reports clean in the current HEAD period. + // The owned impl3 map, not this stale fixture, must still select local data. + if err := cfg.Bitmap.WriteHeader(chunkBitmapHeader{}); err != nil { + t.Fatal(err) + } + layer := mustAttach(t, s, f, cfg) + cut, err := layer.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + image := f.imageOf(t, cut.Head) + if !bytes.Equal(image[5*ctBlockSize:6*ctBlockSize], blk(5)) { + t.Error("capture omitted checkpointed data named by the owned map") + } + es, _, err := readChunkLSNMapV3(s.v3.ownedMap.fd, s.v3.pub.current(), 4) + if err != nil { + t.Fatal(err) + } + for i, e := range es { + if e.Unknown { + t.Errorf("verified captured chunk%d still UNKNOWN", i) + } + } + again, err := layer.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if !again.Noop || again.Stats.CandidateChunks != 0 { + t.Errorf("verified clean cut reread chunks: noop=%v candidates=%d", again.Noop, again.Stats.CandidateChunks) + } + assertNoRemoteMisuse(t, f) +} + +func attachCleanMapFixtureV3(t *testing.T, s *WALStore, f *fakeChunkRemote, head chunkHead) chunkLayer { + t.Helper() + cfg := ctConfig(1) + if err := cfg.Bitmap.WriteHeader(chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: head.Epoch}); err != nil { + t.Fatal(err) + } + return mustAttach(t, s, f, cfg) +} +func TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 5, 5) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + layer := attachCleanMapFixtureV3(t, s, f, chunkHead{}) + first, err := layer.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if err = s.Close(); err != nil { + t.Fatal(err) + } + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { r.Close() }) + if _, err = r.Recover(); err != nil { + t.Fatal(err) + } + if _, err = r.Write(5, blk(7)); err != nil { + t.Fatal(err) + } + if _, err = r.Sync(); err != nil { + t.Fatal(err) + } + if err = r.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + es, _, err := readChunkLSNMapV3(r.v3.ownedMap.fd, r.v3.pub.current(), 4) + if err != nil { + t.Fatal(err) + } + if es[1].Unknown || es[1].LSN != 2 || r.dm.len() != 0 { + t.Fatalf("setup needs known map maxLSN2 and no WAL dirt: %+v", es[1]) + } + secondLayer := attachCleanMapFixtureV3(t, r, f, first.Head) + if err := secondLayer.EvictChunk(1); !errors.Is(err, errChunkEvictRefused) { + t.Errorf("eviction ignored owned-map dirt: %v", err) + } + + second, err := secondLayer.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if second.Stats.CandidateChunks != 1 { + t.Errorf("max-LSN incremental selection candidates=%d want1", second.Stats.CandidateChunks) + } + image := f.imageOf(t, second.Head) + if !bytes.Equal(image[5*ctBlockSize:6*ctBlockSize], blk(7)) { + t.Error("max-LSN map entry omitted checkpointed update") + } +} +func TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 5, 5) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + layer := attachCleanMapFixtureV3(t, s, f, chunkHead{}) + entered, release := holdPuts(t, f) + done := startCapture(t, layer) + waitKey(t, entered, "map capture upload") + if _, err := s.Write(5, blk(9)); err != nil { + t.Fatal(err) + } + release() + if err := waitErr(t, done, "map capture after concurrent write"); err != nil { + t.Fatal(err) + } + head := f.stats().head + if head.RemoteLSN != 1 || !bytes.Equal(f.imageOf(t, head)[5*ctBlockSize:6*ctBlockSize], blk(5)) { + t.Error("published capture is not its barrier image") + } + es, _, err := readChunkLSNMapV3(s.v3.ownedMap.fd, s.v3.pub.current(), 4) + if err != nil { + t.Fatal(err) + } + if !es[1].Unknown || es[1].LSN != 2 { + t.Fatalf("changed chunk token was cleared: %+v", es[1]) + } + next, err := layer.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(f.imageOf(t, next.Head)[5*ctBlockSize:6*ctBlockSize], blk(9)) { + t.Error("next cut missed post-barrier write") + } + es, _, err = readChunkLSNMapV3(s.v3.ownedMap.fd, s.v3.pub.current(), 4) + if err != nil { + t.Fatal(err) + } + if es[1].Unknown { + t.Error("fresh verified version did not clear UNKNOWN") + } +} +func TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN(t *testing.T) { + for _, mode := range []string{"intent_failure", "cas_unknown"} { + t.Run(mode, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 5, 5) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + layer := attachCleanMapFixtureV3(t, s, f, chunkHead{}) + if mode == "intent_failure" { + f.failPutIntent = errors.New("intent unavailable") + } else { + f.casModes = []fakeCASMode{casUnknownNotApplied} + } + before := s.v3.pub.current() + if _, err := layer.Cut(ctTimeout(t)); err == nil { + t.Fatal("unsettled cut returned success") + } + after := s.v3.pub.current() + if after.MapRootHash != before.MapRootHash || after.MapGeneration != before.MapGeneration { + t.Error("unsettled capture published a clean map root") + } + es, _, err := readChunkLSNMapV3(s.v3.ownedMap.fd, after, 4) + if err != nil { + t.Fatal(err) + } + for i, e := range es { + if !e.Unknown { + t.Errorf("unsettled chunk%d lost UNKNOWN", i) + } + } + }) + } +} +func TestChunkLayerV3_RefusesMapGeometryBeforeRemote(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.ChunkBlocks = 8 + if _, err := attachChunkLayer(s, f, cfg); !errors.Is(err, ErrMapInvalid) { + t.Fatalf("mismatched map geometry=%v", err) + } + if f.stats().getHeads != 0 { + t.Error("geometry refusal contacted the remote") + } +} diff --git a/seaweed-block/core/storage/chunk_layer_precopy_test.go b/seaweed-block/core/storage/chunk_layer_precopy_test.go index d9d92f5a42..7d6077e704 100644 --- a/seaweed-block/core/storage/chunk_layer_precopy_test.go +++ b/seaweed-block/core/storage/chunk_layer_precopy_test.go @@ -24,6 +24,11 @@ func precopyLayer(t *testing.T, bound, n int) (*WALStore, *fakeChunkRemote, *chu cfg.FreshFromHead = true cfg.BarrierBound = bound l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + // A new v3 map is conservatively UNKNOWN. Publish the zero baseline + // first so this control isolates subsequent pre-copy redirty behavior. + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } w := newWriteLog() for c := 0; c < n; c++ { w.write(t, s, uint32(c*ctChunkBlocks+1), byte(0x10+c)) @@ -39,8 +44,8 @@ func assertNoIntentsLeft(t *testing.T, f *fakeChunkRemote) { } } -// A chunk re-dirtied between staging and the barrier is copied again under -// the barrier: HEAD has the newer bytes, never the stale stage. Both ways a +// A chunk re-dirtied between staging and the barrier is copied again in +// the COW window: HEAD has the newer bytes, never the stale stage. Both ways a // write can reach a staged chunk are covered: flushed to the extent (its // chunk version moves) and still in the WAL. func TestChunkPrecopy_RedirtiedStagedChunkIsRecopied(t *testing.T) { @@ -63,8 +68,8 @@ func TestChunkPrecopy_RedirtiedStagedChunkIsRecopied(t *testing.T) { if r.Stats.StageRounds != 1 || r.Stats.StagedChunks != 2 { t.Fatalf("staging: %d rounds, %d chunks; want 1 round of 2", r.Stats.StageRounds, r.Stats.StagedChunks) } - if r.Stats.StagedChunksUsed != 1 || r.Stats.BarrierCopyChunks != 2 || r.Stats.BarrierOverBound { - t.Fatalf("barrier: %d staged used, %d copied, over bound %v; want chunk 1 from staging, chunks 0 and 2 copied, within the bound", + if r.Stats.StagedChunksUsed != 1 || r.Stats.BarrierCopyChunks != 0 || r.Stats.CandidateChunks != 3 || r.Stats.BarrierOverBound { + t.Fatalf("barrier: %d staged used, %d copied, over bound %v; want chunk 1 from staging, chunks 0 and 2 copied outside the barrier", r.Stats.StagedChunksUsed, r.Stats.BarrierCopyChunks, r.Stats.BarrierOverBound) } assertEveryHeadIsPrefixImage(t, f, w) @@ -73,8 +78,8 @@ func TestChunkPrecopy_RedirtiedStagedChunkIsRecopied(t *testing.T) { } } -// Writes that outpace the staging: after three rounds the barrier copies -// the rest even above the bound, counts it, and the image is still exact. +// Writes that outpace staging: after three rounds the COW window copies +// all remaining chunks outside the barrier, keeping the image exact. func TestChunkPrecopy_WritesOutpacingStagingGoOverBound(t *testing.T) { s, f, l, w := precopyLayer(t, 2, 4) l.testAfterStageHook = func(round int) { @@ -89,11 +94,11 @@ func TestChunkPrecopy_WritesOutpacingStagingGoOverBound(t *testing.T) { if r.Stats.StageRounds != 3 { // the ruling: at most three rounds t.Fatalf("%d staging rounds, want 3", r.Stats.StageRounds) } - if !r.Stats.BarrierOverBound || r.Stats.BarrierCopyChunks != 4 { - t.Fatalf("barrier copied %d chunks, over bound %v; want all 4, over the bound of 2", r.Stats.BarrierCopyChunks, r.Stats.BarrierOverBound) + if r.Stats.BarrierOverBound || r.Stats.BarrierCopyChunks != 0 || r.Stats.CandidateChunks != 4 { + t.Fatalf("barrier copied %d chunks, over bound %v; want all 4 candidates copied outside the barrier", r.Stats.BarrierCopyChunks, r.Stats.BarrierOverBound) } - if got := l.Stats().BarrierOverBound; got != 1 { - t.Fatalf("BarrierOverBound counter %d, want 1", got) + if got := l.Stats().BarrierOverBound; got != 0 { + t.Fatalf("BarrierOverBound counter %d, want 0 for COW", got) } assertEveryHeadIsPrefixImage(t, f, w) assertNoIntentsLeft(t, f) @@ -107,8 +112,8 @@ func TestChunkPrecopy_NoStagingWithoutNeed(t *testing.T) { if err != nil { t.Fatal(err) } - if r.Stats.StageRounds != 0 || r.Stats.BarrierCopyChunks != tc.n || r.Stats.BarrierOverBound { - t.Fatalf("bound %d, %d dirty: %d rounds, %d copied, over %v; want no staging, all copied under the barrier", + if r.Stats.StageRounds != 0 || r.Stats.BarrierCopyChunks != 0 || r.Stats.CandidateChunks != tc.n || r.Stats.BarrierOverBound { + t.Fatalf("bound %d, %d dirty: %d rounds, %d copied, over %v; want no staging, all copied outside the barrier", tc.bound, tc.n, r.Stats.StageRounds, r.Stats.BarrierCopyChunks, r.Stats.BarrierOverBound) } assertEveryHeadIsPrefixImage(t, f, w) @@ -203,7 +208,7 @@ func TestChunkPrecopy_LowerLSNApplyAfterStagingIsNotLost(t *testing.T) { for _, flushed := range []bool{false, true} { name := map[bool]string{true: "flushed", false: "in the WAL"}[flushed] t.Run(name, func(t *testing.T) { - s, _ := newChunkTestStore(t) + s, _ := newLegacyChunkTestStore(t) f := newFakeChunkRemote() cfg := ctConfig(1) cfg.FreshFromHead = true @@ -302,7 +307,7 @@ func TestChunkPrecopy_BarrierSyncFailureSettlesStagedIntents(t *testing.T) { // same-open Recover. A chunk staged before it must not be reused: // HEAD at the recovered H has the recovered bytes. func TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage(t *testing.T) { - s, f, l, _ := precopyLayer(t, 1, 3) // chunk 0 staged in round 0; bound 1 + s, f, l, _ := legacyPrecopyLayer(t, 1, 3) // chunk 0 staged in round 0; bound 1 want := makeBlock(ctBlockSize, 0xa7) recovered := false l.testAfterStageHook = func(round int) { @@ -363,7 +368,7 @@ func plantRecordPastHead(t *testing.T, s *WALStore, lba uint64, data []byte) { // barrier, so the cut's HEAD at H never holds post-H bytes; the recovered // bytes are published by the next cut. func TestChunkCut_RecoverWaitsForTheCaptureBarrier(t *testing.T) { - s, f, l, w := precopyLayer(t, 0, 2) // no bound: the barrier copies all + s, f, l, w := legacyPrecopyLayer(t, 0, 2) // no bound: the barrier copies all newer := makeBlock(ctBlockSize, 0xa7) partialBatchPrefix(t, s, newer) recovered := make(chan error, 1) @@ -405,3 +410,19 @@ func TestChunkCut_RecoverWaitsForTheCaptureBarrier(t *testing.T) { t.Fatalf("next cut H=%d (prev %d): LBA 0 %#x..., want the recovered %#x...", r2.H, r.H, got[0], newer[0]) } } + +// TODO(format-v3 row 14a): raw v2 surgery/nonmonotone fixture only. +func legacyPrecopyLayer(t *testing.T, bound, n int) (*WALStore, *fakeChunkRemote, *chunkLayerImpl, *writeLog) { + t.Helper() + s, _ := newLegacyChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.FreshFromHead = true + cfg.BarrierBound = bound + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + w := newWriteLog() + for c := 0; c < n; c++ { + w.write(t, s, uint32(c*ctChunkBlocks+1), byte(0x10+c)) + } + return s, f, l, w +} diff --git a/seaweed-block/core/storage/chunk_layer_races_test.go b/seaweed-block/core/storage/chunk_layer_races_test.go index b7ab868156..f85348c581 100644 --- a/seaweed-block/core/storage/chunk_layer_races_test.go +++ b/seaweed-block/core/storage/chunk_layer_races_test.go @@ -129,6 +129,12 @@ func TestChunkLayer_StaleFillCannotInstallAfterReEviction(t *testing.T) { } held, releaseA := holdNextGet(t, f) + // Schedule an old-generation physical fill directly. Guest readers now + // share one flight, so two guest reads cannot create this overlap. + impl := layer.(*chunkLayerImpl) + impl.stMu.Lock() + oldGen, oldRef := impl.absentGen[2], impl.head.Chunks[2] + impl.stMu.Unlock() readA := make(chan error, 1) joinedA := make(chan struct{}) t.Cleanup(func() { @@ -141,7 +147,7 @@ func TestChunkLayer_StaleFillCannotInstallAfterReEviction(t *testing.T) { }) go func() { defer close(joinedA) - _, err := s.Read(8) + _, err := impl.fillOnce(ctTimeout(t), 2, oldGen, oldRef) readA <- err }() waitKey(t, held, "fetch A") @@ -193,7 +199,11 @@ func TestChunkLayer_StaleAttachDoesNotPublishOverNewerHolder(t *testing.T) { f.heads[len(f.heads)-1].Holder = tc.headHolder f.mu.Unlock() s, _ := newChunkTestStore(t) - s.AdvanceFrontier(5) // the log continues from HEAD's remote_lsn (W4b's job in production) + func() { + if err := s.SeedChunkFrontier(5); err != nil { + t.Fatal(err) + } + }() // the log continues from HEAD's remote_lsn (W4b's job in production) if _, err := s.Write(3, makeBlock(ctBlockSize, 0x33)); err != nil { // stale local change t.Fatal(err) } @@ -328,7 +338,11 @@ func TestChunkLayer_StaleFillNeverAuthorizesUnresolvedExtentRead(t *testing.T) { f := newFakeChunkRemote() f.seedHead(t, src, 5, 1) s, _ := newChunkTestStore(t) - s.AdvanceFrontier(5) // the log continues from HEAD's remote_lsn (W4b's job in production) + func() { + if err := s.SeedChunkFrontier(5); err != nil { + t.Fatal(err) + } + }() // the log continues from HEAD's remote_lsn (W4b's job in production) cfg := ctConfig(2) cfg.FreshFromHead = true layer := mustAttach(t, s, f, cfg) @@ -409,7 +423,11 @@ func TestChunkLayer_FreshHostHashCutFetchesNoUntouchedChunk(t *testing.T) { f := newFakeChunkRemote() f.seedHead(t, src, 5, 1) s, _ := newChunkTestStore(t) - s.AdvanceFrontier(5) // the log continues from HEAD's remote_lsn (W4b's job in production) + func() { + if err := s.SeedChunkFrontier(5); err != nil { + t.Fatal(err) + } + }() // the log continues from HEAD's remote_lsn (W4b's job in production) cfg := ctConfig(2) cfg.FreshFromHead = true layer := mustAttach(t, s, f, cfg) diff --git a/seaweed-block/core/storage/chunk_layer_reconcile_test.go b/seaweed-block/core/storage/chunk_layer_reconcile_test.go index 727019a83c..583df12e83 100644 --- a/seaweed-block/core/storage/chunk_layer_reconcile_test.go +++ b/seaweed-block/core/storage/chunk_layer_reconcile_test.go @@ -39,7 +39,7 @@ func newReconcileFixtureWith(t *testing.T, hold bool, mutate func(bm *fakeBitmap // newReconcileFixtureOpts also lets mutateCfg adjust the reattach config. func newReconcileFixtureOpts(t *testing.T, hold bool, mutate func(bm *fakeBitmapStore), mutateCfg func(cfg *chunkLayerConfig)) *reconcileFixture { t.Helper() - s, path, crash := crashableStore(t) + s, path, crash := legacyCrashableStore(t) f := newFakeChunkRemote() cfg := ctConfig(1) bm := cfg.Bitmap.(*fakeBitmapStore) @@ -57,7 +57,7 @@ func newReconcileFixtureOpts(t *testing.T, hold bool, mutate func(bm *fakeBitmap t.Fatal(err) } crash() - s2, _ := reopen(t, path) + s2, _ := legacyReopen(t, path) bm.mu.Lock() mutate(bm) bm.mu.Unlock() @@ -220,7 +220,7 @@ func TestChunkReconcile_ResultPersisted(t *testing.T) { if err := fx.s.Close(); err != nil { // closes the layer too t.Fatal(err) } - s3, _ := reopen(t, fx.path) + s3, _ := legacyReopen(t, fx.path) l2, err := attachChunkLayer(s3, fx.f, fx.cfg) if err != nil { t.Fatal(err) @@ -290,7 +290,7 @@ func TestChunkReconcile_BaseInstallSupersedesRunningReconciliation(t *testing.T) if err := fx.s.Close(); err != nil { // closes the layer too t.Fatal(err) } - s3, _ := reopen(t, fx.path) + s3, _ := legacyReopen(t, fx.path) defer s3.Close() cfg := fx.cfg cfg.testReconcileHold = nil diff --git a/seaweed-block/core/storage/chunk_layer_stats_test.go b/seaweed-block/core/storage/chunk_layer_stats_test.go index 9782a303d4..c2c1d1755e 100644 --- a/seaweed-block/core/storage/chunk_layer_stats_test.go +++ b/seaweed-block/core/storage/chunk_layer_stats_test.go @@ -17,8 +17,8 @@ func TestChunkCutStats_PublishedZeroedUnchangedAndNoop(t *testing.T) { if err := flushWithin(t, s, "flush before the cut"); err != nil { // the bitmap counts flushed writes t.Fatal(err) } - if d := layer.Stats().DirtyChunks; d != 2 { - t.Fatalf("dirty chunks before the cut: %d, want 2", d) + if d := layer.Stats().DirtyChunks; d != ctNumBlocks/ctChunkBlocks { + t.Fatalf("dirty chunks before the first cut: %d, want all UNKNOWN chunks", d) } r, err := layer.Cut(ctTimeout(t)) @@ -26,14 +26,14 @@ func TestChunkCutStats_PublishedZeroedUnchangedAndNoop(t *testing.T) { t.Fatal(err) } st := r.Stats - if st.UploadedChunks != 2 || st.UploadedBytes != 2*ctChunkBytes || st.ZeroedChunks != 0 || st.CandidateChunks < 2 { - t.Fatalf("first cut stats %+v: want 2 uploaded chunks (%d bytes), 0 zeroed, >=2 candidates", st, 2*ctChunkBytes) + if st.UploadedChunks != 2 || st.UploadedBytes != 2*ctChunkBytes || st.ZeroedChunks != 0 || st.UnchangedChunks != ctNumBlocks/ctChunkBlocks-2 || st.CandidateChunks != ctNumBlocks/ctChunkBlocks { + t.Fatalf("first cut stats %+v: want 2 uploaded chunks (%d bytes), remaining UNKNOWN zero chunks unchanged, all chunks candidates", st, 2*ctChunkBytes) } if st.CASResult != "ok" || st.CASNs < 0 || st.UploadNs < 0 || st.TotalNs <= 0 { t.Fatalf("first cut timings/result %+v", st) } - if st.BarrierPauseNs <= 0 || st.BarrierPauseNs < st.SyncNs || st.BarrierPauseNs < st.CopyNs { - t.Fatalf("barrier %d ns must cover sync %d and copy %d", st.BarrierPauseNs, st.SyncNs, st.CopyNs) + if st.BarrierPauseNs <= 0 || st.BarrierPauseNs < st.SyncNs { + t.Fatalf("barrier %d ns must cover sync %d; copy %d is outside it", st.BarrierPauseNs, st.SyncNs, st.CopyNs) } if st.TotalNs < st.BarrierPauseNs+st.UploadNs+st.CASNs { t.Fatalf("total %d ns shorter than barrier %d + upload %d + CAS %d", st.TotalNs, st.BarrierPauseNs, st.UploadNs, st.CASNs) diff --git a/seaweed-block/core/storage/chunk_layer_typed_cause_test.go b/seaweed-block/core/storage/chunk_layer_typed_cause_test.go index 56ed95f4f1..1df9f40661 100644 --- a/seaweed-block/core/storage/chunk_layer_typed_cause_test.go +++ b/seaweed-block/core/storage/chunk_layer_typed_cause_test.go @@ -9,7 +9,7 @@ import ( // reachable with errors.Is through the layer's errors. func TestChunkCut_BaseInstallRefusalIsTyped(t *testing.T) { - s, _ := newChunkTestStore(t) + s, _ := newLegacyChunkTestStore(t) layer := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) newWriteLog().write(t, s, 2, 0x22) if err := layer.BeginBaseInstall(); err != nil { @@ -21,7 +21,7 @@ func TestChunkCut_BaseInstallRefusalIsTyped(t *testing.T) { } func TestChunkCut_UploadFailureIsRemoteUnavailable(t *testing.T) { - s, _ := newChunkTestStore(t) + s, _ := newMappedCheckpointStoreV3(t) f := newFakeChunkRemote() layer := mustAttach(t, s, f, ctConfig(1)) newWriteLog().write(t, s, 2, 0x22) @@ -34,7 +34,7 @@ func TestChunkCut_UploadFailureIsRemoteUnavailable(t *testing.T) { } func TestChunkCut_ClosedLayerIsTyped(t *testing.T) { - s, _ := newChunkTestStore(t) + s, _ := newMappedCheckpointStoreV3(t) layer := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) if err := layer.Close(); err != nil { t.Fatal(err) @@ -47,7 +47,7 @@ func TestChunkCut_ClosedLayerIsTyped(t *testing.T) { // A CAS that returned no definite answer, after which HEAD reads a newer // generation from the same holder, did not apply: a head conflict. func TestChunkCut_CASLostToMovedHeadIsHeadConflict(t *testing.T) { - s, _ := newChunkTestStore(t) + s, _ := newMappedCheckpointStoreV3(t) f := newFakeChunkRemote() layer := mustAttach(t, s, f, ctConfig(1)) w := newWriteLog() diff --git a/seaweed-block/core/storage/chunk_lsn_map_v3.go b/seaweed-block/core/storage/chunk_lsn_map_v3.go new file mode 100644 index 0000000000..caac02dcb7 --- /dev/null +++ b/seaweed-block/core/storage/chunk_lsn_map_v3.go @@ -0,0 +1,479 @@ +package storage + +// Impl-3 COW map. Pages and roots are immutable once written; their extents +// are reused only after no live root references them +// (chunk_map_extents_v3.go), so neither slot root nor a pending candidate can +// lose a dependency. +import ( + "bytes" + "crypto/sha256" + "encoding/binary" + "errors" + "fmt" + "io" + "math" + "os" + "path/filepath" + "sync" +) + +const mapPageDomainV3 = "swblock:chunk-map:page:v1\x00" +const mapRootDomainV3 = "swblock:chunk-map:root:v1\x00" + +var ErrMapInvalid = errors.New("storage: v3 chunk map invalid") + +type chunkLSNEntryV3 struct { + LSN uint64 + Unknown bool +} +type mapPageRefV3 struct { + Offset uint64 + Hash [32]byte +} +type mapShapeV3 struct{ chunks, pages, raw, aligned uint64 } + +func mapShapeForV3(d descriptorV3, cb uint64) (mapShapeV3, error) { + var s mapShapeV3 + if d.BlockSize == 0 || d.VolumeSize == 0 || d.VolumeSize%uint64(d.BlockSize) != 0 || cb == 0 { + return s, ErrMapInvalid + } + nb := d.VolumeSize / uint64(d.BlockSize) + s.chunks = nb / cb + if nb%cb != 0 { + s.chunks++ + } + s.pages = s.chunks / 250 + if s.chunks%250 != 0 { + s.pages++ + } + if s.pages == 0 || s.pages > (counterMaxV3-120)/40 { + return s, ErrCounterExhausted + } + s.raw = 120 + 40*s.pages + if s.raw > uint64(math.MaxInt64)-4095 { + return s, ErrCounterExhausted + } + s.aligned = (s.raw + 4095) &^ uint64(4095) + if s.aligned > uint64(int(^uint(0)>>1)) { + return s, ErrCounterExhausted + } + return s, nil +} +func mapZeroV3(b []byte) bool { return firstNonZero(b) < 0 } + +func mapDigestV3(domain string, b []byte) [32]byte { + h := sha256.New() + h.Write([]byte(domain)) + h.Write(b) + var out [32]byte + copy(out[:], h.Sum(nil)) + return out +} +func encodeMapPageV3(d descriptorV3, g, index uint64, es []chunkLSNEntryV3) ([]byte, error) { + if g > counterMaxV3 { + return nil, ErrCounterExhausted + } + if g == 0 || len(es) == 0 || len(es) > 250 { + return nil, ErrMapInvalid + } + b := make([]byte, 4096) + copy(b, "CLM3") + le := binary.LittleEndian + le.PutUint16(b[4:], 1) + copy(b[8:], d.UUID[:]) + copy(b[24:], d.MapLineage[:]) + le.PutUint64(b[40:], g) + le.PutUint64(b[48:], index) + le.PutUint32(b[56:], uint32(len(es))) + for i, e := range es { + if e.LSN > counterMaxV3 { + return nil, ErrCounterExhausted + } + le.PutUint64(b[64+16*i:], e.LSN) + if e.Unknown { + b[72+16*i] = 1 + } + } + hash := mapDigestV3(mapPageDomainV3, b[:4064]) + copy(b[4064:], hash[:]) + return b, nil +} +func encodeMapRootV3(d descriptorV3, g, cb, C uint64, refs []mapPageRefV3) ([]byte, error) { + s, e := mapShapeForV3(d, cb) + if e != nil { + return nil, e + } + if g > counterMaxV3 || C > counterMaxV3 { + return nil, ErrCounterExhausted + } + if g == 0 || uint64(len(refs)) != s.pages { + return nil, ErrMapInvalid + } + b := make([]byte, int(s.aligned)) + copy(b, "CLR3") + le := binary.LittleEndian + le.PutUint16(b[4:], 1) + copy(b[8:], d.UUID[:]) + copy(b[24:], d.MapLineage[:]) + le.PutUint64(b[40:], g) + le.PutUint64(b[48:], s.chunks) + le.PutUint64(b[56:], cb) + le.PutUint64(b[64:], C) + le.PutUint64(b[72:], s.pages) + le.PutUint64(b[80:], s.raw) + for i, r := range refs { + if r.Offset%4096 != 0 { + return nil, ErrMapInvalid + } + off := 88 + 40*i + le.PutUint64(b[off:], r.Offset) + copy(b[off+8:], r.Hash[:]) + } + h := mapDigestV3(mapRootDomainV3, b[:s.raw-32]) + copy(b[s.raw-32:], h[:]) + return b, nil +} +func mapReadAtV3(f *os.File, off, n, size uint64) ([]byte, error) { + if off%4096 != 0 || off > size || n > size-off || off > math.MaxInt64 || n > uint64(int(^uint(0)>>1)) { + return nil, ErrMapInvalid + } + b := make([]byte, int(n)) + if _, e := f.ReadAt(b, int64(off)); e != nil { + return nil, e + } + return b, nil +} + +// readChunkLSNMapV3 checks the descriptor tuple and every immutable dependency +// before returning any entries. No corrupt root is treated as an empty map. +func readChunkLSNMapV3(f *os.File, d descriptorV3, cb uint64) ([]chunkLSNEntryV3, []mapPageRefV3, error) { + s, e := mapShapeForV3(d, cb) + if e != nil { + return nil, nil, e + } + if d.MapGeneration == 0 || d.MapGeneration > counterMaxV3 || d.MapCoveredCheckpoint > counterMaxV3 || d.UUID == [16]byte{} || d.MapLineage == [16]byte{} { + return nil, nil, ErrMapInvalid + } + // Reject an impossible entry allocation before root allocation or file I/O. + if s.chunks > uint64(int(^uint(0)>>1))/16 { + return nil, nil, ErrMapInvalid + } + info, e := f.Stat() + if e != nil { + return nil, nil, e + } + if info.Size() < 0 { + return nil, nil, ErrMapInvalid + } + size := uint64(info.Size()) + b, e := mapReadAtV3(f, d.MapRootLocator, s.aligned, size) + if e != nil { + return nil, nil, e + } + le := binary.LittleEndian + if string(b[:4]) != "CLR3" || le.Uint16(b[4:]) != 1 || le.Uint16(b[6:]) != 0 || !bytes.Equal(b[8:24], d.UUID[:]) || !bytes.Equal(b[24:40], d.MapLineage[:]) || le.Uint64(b[40:]) != d.MapGeneration || d.MapGeneration == 0 || le.Uint64(b[48:]) != s.chunks || le.Uint64(b[56:]) != cb || le.Uint64(b[64:]) != d.MapCoveredCheckpoint || le.Uint64(b[72:]) != s.pages || le.Uint64(b[80:]) != s.raw || d.MapFormatID != 1 { + return nil, nil, ErrMapInvalid + } + hash := mapDigestV3(mapRootDomainV3, b[:s.raw-32]) + if hash != d.MapRootHash || !bytes.Equal(hash[:], b[s.raw-32:s.raw]) || !mapZeroV3(b[s.raw:]) { + return nil, nil, ErrMapInvalid + } + // Root is file-bounded before page and entry allocations; every page needs + // 4096 distinct bytes. Reject impossible geometry before allocating entries. + if s.pages > size/4096 { + return nil, nil, ErrMapInvalid + } + entries := make([]chunkLSNEntryV3, 0, int(s.chunks)) + refs := make([]mapPageRefV3, 0, int(s.pages)) + seen := make(map[uint64]bool) + for j := uint64(0); j < s.pages; j++ { + pos := 88 + 40*j + r := mapPageRefV3{Offset: le.Uint64(b[pos:])} + copy(r.Hash[:], b[pos+8:pos+40]) + if seen[r.Offset] || (r.Offset < d.MapRootLocator+s.aligned && r.Offset+4096 > d.MapRootLocator) { + return nil, nil, ErrMapInvalid + } + seen[r.Offset] = true + p, e := mapReadAtV3(f, r.Offset, 4096, size) + if e != nil { + return nil, nil, e + } + count := min(uint64(250), s.chunks-j*250) + pg := le.Uint64(p[40:]) + ph := mapDigestV3(mapPageDomainV3, p[:4064]) + if string(p[:4]) != "CLM3" || le.Uint16(p[4:]) != 1 || le.Uint16(p[6:]) != 0 || !bytes.Equal(p[8:24], d.UUID[:]) || !bytes.Equal(p[24:40], d.MapLineage[:]) || pg == 0 || pg > d.MapGeneration || le.Uint64(p[48:]) != j || uint64(le.Uint32(p[56:])) != count || !mapZeroV3(p[60:64]) || ph != r.Hash || !bytes.Equal(ph[:], p[4064:]) || !mapZeroV3(p[64+16*count:4064]) { + return nil, nil, ErrMapInvalid + } + for i := uint64(0); i < count; i++ { + q := p[64+16*i : 80+16*i] + lsn := le.Uint64(q) + if lsn > counterMaxV3 || q[8]&^byte(1) != 0 || !mapZeroV3(q[9:]) { + return nil, nil, ErrMapInvalid + } + entries = append(entries, chunkLSNEntryV3{LSN: lsn, Unknown: q[8] == 1}) + } + refs = append(refs, r) + } + return entries, refs, nil +} + +type chunkMapCandidateV3 struct { + owner *chunkLSNMapV3 + generation, covered, rootOffset uint64 + hash [32]byte + refs []mapPageRefV3 + entries []chunkLSNEntryV3 +} + +func (c *chunkMapCandidateV3) descriptor(d descriptorV3) descriptorV3 { + d.MapFormatID = 1 + d.MapGeneration = c.generation + d.MapCoveredCheckpoint = c.covered + d.MapRootLocator = c.rootOffset + d.MapRootHash = c.hash + return d +} + +type chunkLSNMapV3 struct { + mu sync.Mutex + fd *os.File + identity descriptorV3 + chunkBlocks uint64 + failed error + lastGeneration uint64 + syncFile func() error + syncDirectory func() error + latchPersistence func(error) + // liveMu guards live (chunk_map_extents_v3.go); never held across I/O. + liveMu sync.Mutex + live chunkMapLiveV3 +} + +func (m *chunkLSNMapV3) initLiveV3() { + m.live.roots = map[mapRootKeyV3]mapRootExtentsV3{} + m.live.inflight = map[mapRootKeyV3]bool{} +} + +func createChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3, error) { + if _, e := mapShapeForV3(d, cb); e != nil { + return nil, e + } + if d.UUID == [16]byte{} || d.MapLineage == [16]byte{} { + return nil, ErrMapInvalid + } + f, e := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) + if e != nil { + return nil, e + } + m := &chunkLSNMapV3{fd: f, identity: d, chunkBlocks: cb} + m.initLiveV3() + m.syncFile = f.Sync + m.syncDirectory = func() error { return syncDir(filepath.Dir(path)) } + if e = m.syncFile(); e == nil { + e = m.syncDirectory() + } + if e != nil { + f.Close() + return nil, e + } + return m, nil +} + +// Open validates the selected generation before permitting any append. The +// caller must also validate the fallback descriptor before serving/retiring. +func openChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3, *chunkMapCandidateV3, error) { + f, e := os.OpenFile(path, os.O_RDWR, 0) + if e != nil { + return nil, nil, e + } + es, refs, e := readChunkLSNMapV3(f, d, cb) + if e != nil { + f.Close() + return nil, nil, e + } + m := &chunkLSNMapV3{fd: f, identity: d, chunkBlocks: cb, lastGeneration: d.MapGeneration} + m.initLiveV3() + if s, e := mapShapeForV3(d, cb); e == nil { + m.registerRootV3(d.MapGeneration, d.MapRootLocator, s.aligned, refs) + } + if info, e := f.Stat(); e == nil && info.Size() > 0 { + m.live.fileBytes.Store(uint64(info.Size())) + } + m.syncFile = f.Sync + m.syncDirectory = func() error { return syncDir(filepath.Dir(path)) } + c := &chunkMapCandidateV3{owner: m, generation: d.MapGeneration, covered: d.MapCoveredCheckpoint, rootOffset: d.MapRootLocator, hash: d.MapRootHash, refs: refs, entries: es} + return m, c, nil +} + +// Prepare persists pages -> page fsync -> root -> root fsync -> directory fsync. +// It returns a pinned tuple, never a descriptor publication or reuse authority. +// Preflight and Stat errors do not latch. Once the append transaction starts, +// an error latches and refuses subsequent persistence I/O until reopen. +// New pages and the root go into extents no live root references +// (chunk_map_extents_v3.go); the candidate stays live until a publication +// names it or supersedes it. +func (m *chunkLSNMapV3) Prepare(g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (out *chunkMapCandidateV3, err error) { + m.mu.Lock() + defer m.mu.Unlock() + return m.prepareLockedV3(g, C, entries, prior) +} + +// Generation reservation and persistence share the existing sidecar mutex. +// Concurrent preparers cannot select the same generation; no new lock or +// scheduler is introduced. A candidate known never to reach a slot is +// released (abandonCandidateV3); an uncertain one stays pinned until reopen. +func (m *chunkLSNMapV3) prepareNextV3(C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (*chunkMapCandidateV3, error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.failed != nil { + return nil, m.failed + } + if m.lastGeneration >= counterMaxV3 { + return nil, ErrCounterExhausted + } + return m.prepareLockedV3(m.lastGeneration+1, C, entries, prior) +} +func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (out *chunkMapCandidateV3, err error) { + if m.failed != nil { + return nil, m.failed + } + s, e := mapShapeForV3(m.identity, m.chunkBlocks) + if e != nil { + return nil, e + } + if g > counterMaxV3 || C > counterMaxV3 { + return nil, ErrCounterExhausted + } + if uint64(len(entries)) != s.chunks || g == 0 || g <= m.lastGeneration { + return nil, ErrMapInvalid + } + if prior != nil && (prior.owner != m || prior.generation >= g) { + return nil, ErrMapInvalid + } + // Validate every entry before any I/O. + for _, v := range entries { + if v.LSN > counterMaxV3 { + return nil, ErrCounterExhausted + } + } + info, e := m.fd.Stat() + if e != nil { + return nil, e + } + if info.Size() < 0 { + return nil, ErrMapInvalid + } + fileBytes := uint64(info.Size()) + if fileBytes > math.MaxInt64-4095 { + return nil, ErrCounterExhausted + } + // The live set: every page and root extent a live root references. + // Roots are only added here (under m.mu); the publisher's report only + // removes them, so this snapshot is a superset for the whole prepare. + used, liveBytes := usedPagesV3(m.liveSnapshotV3()) + defer func() { + if err != nil { + m.failed = err + if m.latchPersistence != nil { + m.latchPersistence(err) + } + } + }() + // Bounded file: truncate the free tail once the file exceeds 4 x the + // live bytes. Nothing at or below the highest live page is touched, so + // a root the fallback slot names stays readable. + if liveBytes > 0 && fileBytes > 4*liveBytes { + keep := (used[len(used)-1] + 1) * 4096 + if keep < fileBytes { + if e := m.fd.Truncate(int64(keep)); e != nil { + return nil, e + } + fileBytes = keep + m.live.fileBytes.Store(keep) // the file is shorter even if the fsync fails + m.live.truncations.Add(1) + if e := m.syncFile(); e != nil { + return nil, e + } + } + } + alloc := newExtentAllocatorV3(used, fileBytes) + write := func(b []byte) (uint64, error) { + at := alloc.alloc(uint64(len(b)+4095) / 4096) + if uint64(len(b)) > math.MaxInt64-at { + return 0, ErrCounterExhausted + } + n, e := m.fd.WriteAt(b, int64(at)) + if end := at + uint64(n); end > m.live.fileBytes.Load() { + m.live.fileBytes.Store(end) // also on a failed or short write + } + if e == nil && n != len(b) { + e = io.ErrShortWrite + } + if e != nil { + return 0, e + } + return at, nil + } + refs := make([]mapPageRefV3, s.pages) + for j := uint64(0); j < s.pages; j++ { + start := j * 250 + end := min(start+250, s.chunks) + same := prior != nil && len(prior.entries) == len(entries) + if same { + for i := start; i < end; i++ { + if prior.entries[i] != entries[i] { + same = false + break + } + } + } + if same { + refs[j] = prior.refs[j] + continue + } + p, e := encodeMapPageV3(m.identity, g, j, entries[start:end]) + if e != nil { + return nil, e + } + at, e := write(p) + if e != nil { + return nil, e + } + refs[j] = mapPageRefV3{Offset: at, Hash: mapDigestV3(mapPageDomainV3, p[:4064])} + } + if e = m.syncFile(); e != nil { + return nil, e + } + root, e := encodeMapRootV3(m.identity, g, m.chunkBlocks, C, refs) + if e != nil { + return nil, e + } + at, e := write(root) + if e != nil { + return nil, e + } + if e = m.syncFile(); e != nil { + return nil, e + } + if e = m.syncDirectory(); e != nil { + return nil, e + } + m.lastGeneration = g + out = &chunkMapCandidateV3{owner: m, generation: g, covered: C, rootOffset: at, hash: mapDigestV3(mapRootDomainV3, root[:s.raw-32]), refs: refs, entries: append([]chunkLSNEntryV3(nil), entries...)} + // The candidate is live (in flight) until a publication names it or + // supersedes it. + x := rootExtentsV3(at, s.aligned, refs) + m.liveMu.Lock() + k := mapRootKeyV3{at, g} + m.live.roots[k] = x + m.live.inflight[k] = true + m.liveMu.Unlock() + m.live.fileBytes.Store(max(alloc.end*4096, fileBytes)) + return out, nil +} +func (m *chunkLSNMapV3) Close() error { + m.mu.Lock() + defer m.mu.Unlock() + m.failed = fmt.Errorf("%w: closed", ErrMapInvalid) + return m.fd.Close() +} diff --git a/seaweed-block/core/storage/chunk_lsn_map_v3_review_test.go b/seaweed-block/core/storage/chunk_lsn_map_v3_review_test.go new file mode 100644 index 0000000000..8048b45142 --- /dev/null +++ b/seaweed-block/core/storage/chunk_lsn_map_v3_review_test.go @@ -0,0 +1,82 @@ +package storage + +import ( + "crypto/sha256" + "errors" + "os" + "path/filepath" + "testing" +) + +func TestChunkLSNMapV3_EntryBoundBeforeRootIO(t *testing.T) { + d := mapDescriptorV3(t) + d.BlockSize = 1 + d.VolumeSize = uint64(int(^uint(0)>>1))/16 + 1 + f, err := os.Create(filepath.Join(t.TempDir(), "closed-map")) + if err != nil { + t.Fatal(err) + } + if err = f.Close(); err != nil { + t.Fatal(err) + } + // The geometry must be refused before even Stat, without allocating a root. + _, _, err = readChunkLSNMapV3(f, d, 1) + if !errors.Is(err, ErrMapInvalid) { + t.Fatalf("entry bound must precede file I/O: %v", err) + } +} + +func TestChunkLSNMapV3_WholePageHashIsNotBodyDigest(t *testing.T) { + d := mapDescriptorV3(t) + m, err := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 1) + if err != nil { + t.Fatal(err) + } + defer m.Close() + c, err := m.Prepare(1, 7, []chunkLSNEntryV3{{LSN: 7}}, nil) + if err != nil { + t.Fatal(err) + } + page := make([]byte, 4096) + if _, err = m.fd.ReadAt(page, int64(c.refs[0].Offset)); err != nil { + t.Fatal(err) + } + // Deliberately wrong: SHA-256 of all 4096 bytes, including the embedded hash, + // instead of the domain-separated 4064-byte body required by the byte contract. + whole := sha256.Sum256(page) + if whole == c.refs[0].Hash { + t.Fatal("whole-page digest unexpectedly matches body digest") + } + copy(page[4064:], whole[:]) + if _, err = m.fd.WriteAt(page, int64(c.refs[0].Offset)); err != nil { + t.Fatal(err) + } + root, err := encodeMapRootV3(d, 1, 1, 7, []mapPageRefV3{{Offset: c.refs[0].Offset, Hash: whole}}) + if err != nil { + t.Fatal(err) + } + if _, err = m.fd.WriteAt(root, int64(c.rootOffset)); err != nil { + t.Fatal(err) + } + d = c.descriptor(d) + // Root, reference and embedded digest agree. Only page-body validation rejects it. + d.MapRootHash = mapDigestV3(mapRootDomainV3, root[:128]) + if _, _, err = readChunkLSNMapV3(m.fd, d, 1); !errors.Is(err, ErrMapInvalid) { + t.Fatalf("whole-page hash accepted: %v", err) + } +} + +func TestChunkLSNMapV3_PreflightErrorDoesNotLatch(t *testing.T) { + d := mapDescriptorV3(t) + m, err := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 1) + if err != nil { + t.Fatal(err) + } + defer m.Close() + if c, err := m.Prepare(0, 7, []chunkLSNEntryV3{{LSN: 7}}, nil); c != nil || !errors.Is(err, ErrMapInvalid) { + t.Fatalf("invalid generation = %v, %v", c, err) + } + if c, err := m.Prepare(1, 7, []chunkLSNEntryV3{{LSN: 7}}, nil); err != nil || c == nil { + t.Fatalf("valid retry after preflight error = %v, %v", c, err) + } +} diff --git a/seaweed-block/core/storage/chunk_lsn_map_v3_test.go b/seaweed-block/core/storage/chunk_lsn_map_v3_test.go new file mode 100644 index 0000000000..37d3e62d63 --- /dev/null +++ b/seaweed-block/core/storage/chunk_lsn_map_v3_test.go @@ -0,0 +1,354 @@ +package storage + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "os" + "path/filepath" + "testing" +) + +func mapDescriptorV3(t *testing.T) descriptorV3 { + t.Helper() + d, e := decodeSlotV3(readSlotVector(t, "slot-ref"), nil) + if e != nil { + t.Fatal(e) + } + for i := range d.UUID { + d.UUID[i] = byte(i) + d.MapLineage[i] = byte(i + 16) + } + d.VolumeSize = 4096 + d.BlockSize = 4096 + d.MapGeneration = 1 + d.MapCoveredCheckpoint = 7 + d.W = 7 + d.CheckpointLSN = 7 + return d +} +func TestChunkLSNMapV3_CanonicalVectors(t *testing.T) { + d := mapDescriptorV3(t) + p, e := encodeMapPageV3(d, 1, 0, []chunkLSNEntryV3{{LSN: 7}}) + if e != nil { + t.Fatal(e) + } + want, e := os.ReadFile("testdata/format_v3/reference-page.bin") + if e != nil { + t.Fatal(e) + } + if !bytes.Equal(p, want) { + t.Fatal("page differs from independent vector") + } + root, e := encodeMapRootV3(d, 1, 1, 7, []mapPageRefV3{{Offset: 4096, Hash: mapDigestV3(mapPageDomainV3, p[:4064])}}) + if e != nil { + t.Fatal(e) + } + want, e = os.ReadFile("testdata/format_v3/reference-root.bin") + if e != nil { + t.Fatal(e) + } + if !bytes.Equal(root, want) { + t.Fatal("root differs from independent vector") + } + d.MapRootHash = mapDigestV3(mapRootDomainV3, root[:128]) + d.MapRootLocator = 0 + f, e := os.Create(filepath.Join(t.TempDir(), "map")) + if e != nil { + t.Fatal(e) + } + defer f.Close() + if _, e = f.WriteAt(root, 0); e != nil { + t.Fatal(e) + } + if _, e = f.WriteAt(p, 4096); e != nil { + t.Fatal(e) + } + entries, _, e := readChunkLSNMapV3(f, d, 1) + if e != nil || len(entries) != 1 || entries[0].LSN != 7 { + t.Fatalf("read=%v %v", entries, e) + } +} +func TestChunkLSNMapV3_PersistReloadAndReuse(t *testing.T) { + d := mapDescriptorV3(t) + d.VolumeSize = 251 * 4096 + path := filepath.Join(t.TempDir(), "map") + m, e := createChunkLSNMapV3(path, d, 1) + if e != nil { + t.Fatal(e) + } + defer m.Close() + entries := make([]chunkLSNEntryV3, 251) + entries[0].LSN = 7 + entries[250].Unknown = true + a, e := m.Prepare(1, 7, entries, nil) + if e != nil { + t.Fatal(e) + } + entries[250] = chunkLSNEntryV3{LSN: 8} + b, e := m.Prepare(2, 8, entries, a) + if e != nil { + t.Fatal(e) + } + if a.refs[0] != b.refs[0] || a.refs[1] == b.refs[1] { + t.Fatal("COW did not retain precisely the unchanged page") + } + next := b.descriptor(d) + next.W = 8 + got, _, e := readChunkLSNMapV3(m.fd, next, 1) + if e != nil || len(got) != 251 || got[250].LSN != 8 { + t.Fatalf("reload=%v %v", got, e) + } + old, _, e := readChunkLSNMapV3(m.fd, a.descriptor(d), 1) + if e != nil || !old[250].Unknown { + t.Fatalf("old generation lost: %v", e) + } + foreign := next + foreign.UUID[0] ^= 1 + if _, _, e := readChunkLSNMapV3(m.fd, foreign, 1); e == nil { + t.Fatal("foreign identity accepted") + } +} +func TestChunkLSNMapV3_CorruptionAndBounds(t *testing.T) { + for _, kind := range []string{"page", "coverage", "padding", "overlap", "count", "reserved"} { + t.Run(kind, func(t *testing.T) { + d := mapDescriptorV3(t) + m, e := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 1) + if e != nil { + t.Fatal(e) + } + defer m.Close() + c, e := m.Prepare(1, 7, []chunkLSNEntryV3{{LSN: 7}}, nil) + if e != nil { + t.Fatal(e) + } + d = c.descriptor(d) + switch kind { + case "page": + _, e = m.fd.WriteAt([]byte{9}, int64(c.refs[0].Offset+64)) + case "coverage": + d.MapCoveredCheckpoint = 6 + case "padding": + _, e = m.fd.WriteAt([]byte{1}, int64(c.rootOffset+200)) + case "overlap": + d.MapRootLocator = c.refs[0].Offset + case "count": + d.VolumeSize = 8192 + case "reserved": + _, e = m.fd.WriteAt([]byte{1}, int64(c.refs[0].Offset+60)) + } + if e != nil { + t.Fatal(e) + } + if _, _, e := readChunkLSNMapV3(m.fd, d, 1); e == nil { + t.Fatalf("%s accepted", kind) + } + }) + } +} +func TestChunkLSNMapV3_FailureDoesNotPublishOrReuse(t *testing.T) { + for _, stage := range []string{"page_sync", "root_sync", "directory"} { + t.Run(stage, func(t *testing.T) { + d := mapDescriptorV3(t) + m, e := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 1) + if e != nil { + t.Fatal(e) + } + defer m.Close() + boom := errors.New("injected durability failure") + calls := 0 + m.syncFile = func() error { + calls++ + if (stage == "page_sync" && calls == 1) || (stage == "root_sync" && calls == 2) { + return boom + } + return m.fd.Sync() + } + m.syncDirectory = func() error { + if stage == "directory" { + return boom + } + return nil + } + if c, e := m.Prepare(1, 7, []chunkLSNEntryV3{{Unknown: true}}, nil); !errors.Is(e, boom) || c != nil { + t.Fatalf("candidate escaped failed persistence: %v %v", c, e) + } + before, _ := m.fd.Stat() + if _, e := m.Prepare(2, 7, []chunkLSNEntryV3{{Unknown: true}}, nil); e == nil { + t.Fatal("failed sidecar reused") + } + after, _ := m.fd.Stat() + if before.Size() != after.Size() { + t.Fatal("retry wrote after failure") + } + }) + } +} + +func TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage(t *testing.T) { + d := mapDescriptorV3(t) + d.VolumeSize = 501 * 4096 + path := filepath.Join(t.TempDir(), "map") + m, e := createChunkLSNMapV3(path, d, 2) + if e != nil { + t.Fatal(e) + } + if other, e := createChunkLSNMapV3(path, d, 2); e == nil { + other.Close() + t.Fatal("overwrote owned sidecar") + } + var stages []string + m.syncFile = func() error { + info, err := m.fd.Stat() + if err != nil { + return err + } + want := int64(8192) + if len(stages) == 1 { + want = 12288 + } + if info.Size() != want { + t.Errorf("sync boundary file size=%d want %d", info.Size(), want) + } + stages = append(stages, "file") + return m.fd.Sync() + } + m.syncDirectory = func() error { stages = append(stages, "directory"); return nil } + es := make([]chunkLSNEntryV3, 251) + es[250] = chunkLSNEntryV3{LSN: 7, Unknown: true} + c, e := m.Prepare(1, 7, es, nil) + if e != nil { + t.Fatal(e) + } + if fmt.Sprint(stages) != "[file file directory]" { + t.Fatalf("durability order=%v", stages) + } + next := c.descriptor(d) + if e = m.Close(); e != nil { + t.Fatal(e) + } + reopened, loaded, e := openChunkLSNMapV3(path, next, 2) + if e != nil { + t.Fatal(e) + } + defer reopened.Close() + if len(loaded.entries) != 251 || !loaded.entries[250].Unknown { + t.Fatal("clipped final chunk lost") + } + // The last page has precisely one entry even though the last chunk is clipped. + if loaded.refs[1].Offset == loaded.refs[0].Offset { + t.Fatal("pages aliased") + } + if _, e := reopened.Prepare(1, 7, es, loaded); e == nil { + t.Fatal("generation reuse accepted") + } + foreign := next + foreign.MapLineage[0] ^= 1 + if f, _, e := openChunkLSNMapV3(path, foreign, 2); e == nil { + f.Close() + t.Fatal("foreign lineage opened") + } + if f, _, e := openChunkLSNMapV3(path+"missing", next, 2); e == nil { + f.Close() + t.Fatal("missing metadata became clean") + } +} +func TestChunkLSNMapV3_RejectsRehashedMalformedRecords(t *testing.T) { + for _, kind := range []string{"page_generation", "state", "reserved", "unused", "page_domain", "root_domain", "root_padding", "overlap", "duplicate", "huge_count"} { + t.Run(kind, func(t *testing.T) { + d := mapDescriptorV3(t) + d.VolumeSize = 251 * 4096 + m, e := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 1) + if e != nil { + t.Fatal(e) + } + defer m.Close() + c, e := m.Prepare(1, 7, make([]chunkLSNEntryV3, 251), nil) + if e != nil { + t.Fatal(e) + } + d = c.descriptor(d) + shape, _ := mapShapeForV3(d, 1) + root := make([]byte, shape.aligned) + if _, e = m.fd.ReadAt(root, int64(c.rootOffset)); e != nil { + t.Fatal(e) + } + le := binary.LittleEndian + page := make([]byte, 4096) + if _, e = m.fd.ReadAt(page, int64(c.refs[1].Offset)); e != nil { + t.Fatal(e) + } + switch kind { + case "page_generation": + le.PutUint64(page[40:], 2) + case "state": + page[72] = 2 + case "reserved": + page[60] = 1 + case "unused": + page[80] = 1 + case "page_domain": + case "root_domain": + case "root_padding": + root[shape.raw] = 1 + case "overlap": + le.PutUint64(root[88:], c.rootOffset) + case "duplicate": + copy(root[128:168], root[88:128]) + case "huge_count": + le.PutUint64(root[72:], ^uint64(0)) + } + ph := mapDigestV3(mapPageDomainV3, page[:4064]) + if kind == "page_domain" { + ph = mapDigestV3(mapRootDomainV3, page[:4064]) + } + copy(page[4064:], ph[:]) + copy(root[136:168], ph[:]) + if _, e = m.fd.WriteAt(page, int64(c.refs[1].Offset)); e != nil { + t.Fatal(e) + } + rh := mapDigestV3(mapRootDomainV3, root[:shape.raw-32]) + if kind == "root_domain" { + rh = mapDigestV3(mapPageDomainV3, root[:shape.raw-32]) + } + copy(root[shape.raw-32:], rh[:]) + d.MapRootHash = rh + if _, e = m.fd.WriteAt(root, int64(c.rootOffset)); e != nil { + t.Fatal(e) + } + if _, _, e := readChunkLSNMapV3(m.fd, d, 1); e == nil { + t.Fatalf("rehashed %s accepted", kind) + } + }) + } +} + +func TestChunkLSNMapV3_CounterAndGeometryRefusal(t *testing.T) { + d := mapDescriptorV3(t) + if _, e := encodeMapPageV3(d, ^uint64(0), 0, []chunkLSNEntryV3{{}}); !errors.Is(e, ErrCounterExhausted) { + t.Fatalf("page counter=%v", e) + } + if _, e := encodeMapRootV3(d, 1, 1, ^uint64(0), []mapPageRefV3{{}}); !errors.Is(e, ErrCounterExhausted) { + t.Fatalf("root counter=%v", e) + } + m, e := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 1) + if e != nil { + t.Fatal(e) + } + defer m.Close() + if _, e = m.Prepare(^uint64(0), 7, []chunkLSNEntryV3{{}}, nil); !errors.Is(e, ErrCounterExhausted) { + t.Fatalf("prepare counter=%v", e) + } + stat, _ := m.fd.Stat() + if stat.Size() != 0 { + t.Fatal("invalid counter wrote bytes") + } + if _, e = mapShapeForV3(d, 0); e == nil { + t.Fatal("zero chunk geometry accepted") + } + d.VolumeSize++ + if _, e = mapShapeForV3(d, 1); e == nil { + t.Fatal("nonintegral block geometry accepted") + } +} diff --git a/seaweed-block/core/storage/chunk_manifest.go b/seaweed-block/core/storage/chunk_manifest.go index 2125321931..c460c0fe99 100644 --- a/seaweed-block/core/storage/chunk_manifest.go +++ b/seaweed-block/core/storage/chunk_manifest.go @@ -5,14 +5,16 @@ import "context" // ChunkSegment names an immutable range manifest. Owner is the namespace in // which that manifest was encoded; forks preserve it without rewriting data. type ChunkSegment struct { - Key string `json:"key"` - SHA256 [32]byte `json:"sha256"` - Owner string `json:"owner"` - Count int `json:"count"` + Key string `json:"key"` + SHA256 [32]byte `json:"sha256"` + Owner string `json:"owner"` + Count int `json:"count"` + MaxBirthLSN uint64 `json:"max_birth_lsn"` + SegFormat int `json:"seg_format"` } // ChunkManifestBuilder prepares immutable segments before the existing root -// CAS. Returned intents belong to the cut and follow its settlement rules. +// CAS. Returned intents belong to the publishing caller and follow its settlement rules. type ChunkManifestBuilder interface { PrepareManifest(context.Context, ChunkHead, ChunkHead, uint64) (ChunkHead, []string, error) } diff --git a/seaweed-block/core/storage/chunk_map_bind_v3_test.go b/seaweed-block/core/storage/chunk_map_bind_v3_test.go new file mode 100644 index 0000000000..63743a0b7f --- /dev/null +++ b/seaweed-block/core/storage/chunk_map_bind_v3_test.go @@ -0,0 +1,63 @@ +package storage + +import ( + "bytes" + "testing" +) + +// Binding is the open/quiesced publication seam. The selected map alone is +// insufficient: the valid fallback slot still pins its own immutable pages. +func TestMapPublicationV3_BindValidatesBothSlotDependencies(t *testing.T) { + for _, corrupt := range []bool{false, true} { + name := "valid_fallback" + if corrupt { + name = "corrupt_fallback" + } + t.Run(name, func(t *testing.T) { + x := newMapPublicationHarnessV3(t, 11) + next := x.prepare(t, 12, 110) + if _, err := x.h.pub.publishMapV3(&x.h.storeMu, nil, next, func(n *descriptorV3) error { n.CheckpointLSN = 110; return nil }); err != nil { + t.Fatal(err) + } + if next.candidate.refs[0].Offset == x.initial.refs[0].Offset { + t.Fatal("control requires disjoint old/new pages") + } + if corrupt { + if _, err := x.m.fd.WriteAt([]byte{0xff}, int64(x.initial.refs[0].Offset)+64); err != nil { + t.Fatal(err) + } + if err := x.m.fd.Sync(); err != nil { + t.Fatal(err) + } + } + // The selected generation is intact in both cases, so only checking it + // would incorrectly accept the damaged fallback. + d := x.h.pub.current() + if _, _, err := readChunkLSNMapV3(x.m.fd, d, x.m.chunkBlocks); err != nil { + t.Fatalf("selected generation damaged: %v", err) + } + before := mapSlotsV3(t, x.h) + oldDomain := x.h.pub.mapDomain + freshDomain := newMapProofEpochV3() + err := x.h.pub.bindMapV3(next.candidate, freshDomain) + if corrupt { + if err == nil { + t.Error("bind accepted a valid fallback descriptor with corrupt map dependencies") + } + if x.h.pub.mapDomain != oldDomain { + t.Error("failed bind replaced the open proof domain") + } + } else { + if err != nil { + t.Fatal(err) + } + if x.h.pub.mapDomain != freshDomain { + t.Error("valid both-slot bind did not install its domain") + } + } + if !bytes.Equal(before, mapSlotsV3(t, x.h)) { + t.Error("bind wrote descriptor slots") + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_map_extents_v3.go b/seaweed-block/core/storage/chunk_map_extents_v3.go new file mode 100644 index 0000000000..85fe268188 --- /dev/null +++ b/seaweed-block/core/storage/chunk_map_extents_v3.go @@ -0,0 +1,221 @@ +package storage + +import ( + "sort" + "sync/atomic" +) + +// The owned-map file reuses space. A candidate's new pages and root go into +// 4 KiB extents that no live root references, and the file's free tail is +// truncated once the file exceeds 4x the live bytes. +// +// Live roots are the roots the two descriptor slots name and every prepared +// candidate not yet published or superseded (an uncertain candidate stays +// live, because a failed publication latches the publisher). An extent is +// released only after a publication leaves neither slot naming it. New +// pages and the root are fsynced before a publication names them, so a +// crash leaves every slot-named root intact. Roots and pages are addressed +// by offset and SHA-256, so the on-disk format is unchanged. +// +// Map pages are read by offset only at open, before any candidate exists; +// other openers take the same exclusive volume lock. +// +// Lock order: WALStore.mu -> descMu -> liveMu (the publisher's report and +// the definite-abandon path run under descMu), and chunkLSNMapV3.mu -> +// liveMu (a prepare snapshots and registers under it). liveMu is held only +// for map and slice bookkeeping (it may allocate a slice or a map entry), +// never across I/O, sorting or extent allocation, +// and nothing holding liveMu takes another lock. + +type mapRootKeyV3 struct{ off, gen uint64 } + +type mapRootExtentsV3 struct { + rootOff, rootLen uint64 // bytes, 4 KiB aligned + pages []uint64 // page offsets (every page the root references) +} + +// chunkMapLiveV3 is the live set of one owned map. +type chunkMapLiveV3 struct { + roots map[mapRootKeyV3]mapRootExtentsV3 + inflight map[mapRootKeyV3]bool + truncations atomic.Uint64 + fileBytes atomic.Uint64 // set at open, after each prepare and truncation +} + +// ChunkMapStats reports the owned map file's size, the bytes its live roots +// reference, and how many times its free tail was truncated. +type ChunkMapStats struct { + FileBytes, LiveBytes, Truncations uint64 +} + +// registerRootV3 records a slot-named root read at open. Caller holds no lock +// other than possibly m.mu. +func (m *chunkLSNMapV3) registerRootV3(gen, rootOff, rootLen uint64, refs []mapPageRefV3) { + m.liveMu.Lock() + defer m.liveMu.Unlock() + m.live.roots[mapRootKeyV3{rootOff, gen}] = rootExtentsV3(rootOff, rootLen, refs) +} + +func rootExtentsV3(rootOff, rootLen uint64, refs []mapPageRefV3) mapRootExtentsV3 { + x := mapRootExtentsV3{rootOff: rootOff, rootLen: rootLen, pages: make([]uint64, len(refs))} + for i, r := range refs { + x.pages[i] = r.Offset + } + return x +} + +// slotsPublishedV3 is the publisher's report after a successful publication +// (under descMu). Roots named by neither slot are released, and so is every +// in-flight candidate the new current generation supersedes (it can never +// be published: a publication needs a strictly higher generation). +func (m *chunkLSNMapV3) slotsPublishedV3(cur, other descriptorV3, otherValid bool) { + m.liveMu.Lock() + defer m.liveMu.Unlock() + keep := map[mapRootKeyV3]bool{{cur.MapRootLocator, cur.MapGeneration}: true} + if otherValid { + keep[mapRootKeyV3{other.MapRootLocator, other.MapGeneration}] = true + } + for k := range m.live.roots { + if keep[k] { + delete(m.live.inflight, k) + continue + } + if m.live.inflight[k] && k.gen > cur.MapGeneration { + continue // a newer candidate, still publishable + } + delete(m.live.roots, k) + delete(m.live.inflight, k) + } +} + +// abandonCandidateV3 releases a prepared candidate that is known never to +// have reached a descriptor slot: its publication was refused before any +// slot I/O (a stale proof, a validation refusal, a latched fault), or its +// caller gave up before publishing. A candidate whose publication I/O +// started stays pinned (uncertain) until reopen. +func (m *chunkLSNMapV3) abandonCandidateV3(c *chunkMapCandidateV3) { + m.liveMu.Lock() + defer m.liveMu.Unlock() + k := mapRootKeyV3{c.rootOffset, c.generation} + if m.live.inflight[k] { + delete(m.live.inflight, k) + delete(m.live.roots, k) + } +} + +// abandonV3 is the definite-abandon path for a prepared publication. +func (p *preparedMapPublicationV3) abandonV3() { + if p != nil && p.candidate != nil && p.candidate.owner != nil { + p.candidate.owner.abandonCandidateV3(p.candidate) + } +} + +// liveSnapshotV3 copies the live roots' extents under liveMu. +func (m *chunkLSNMapV3) liveSnapshotV3() []mapRootExtentsV3 { + m.liveMu.Lock() + defer m.liveMu.Unlock() + out := make([]mapRootExtentsV3, 0, len(m.live.roots)) + for _, x := range m.live.roots { + out = append(out, x) + } + return out +} + +// usedPagesV3 returns the sorted, distinct 4 KiB page indexes a live-set +// snapshot references, and the live byte count. It needs no lock. +func usedPagesV3(roots []mapRootExtentsV3) ([]uint64, uint64) { + set := map[uint64]bool{} + for _, x := range roots { + for p := x.rootOff / 4096; p < (x.rootOff+x.rootLen)/4096; p++ { + set[p] = true + } + for _, off := range x.pages { + set[off/4096] = true + } + } + used := make([]uint64, 0, len(set)) + for p := range set { + used = append(used, p) + } + sort.Slice(used, func(i, j int) bool { return used[i] < used[j] }) + return used, uint64(len(used)) * 4096 +} + +// extentAllocatorV3 hands out free 4 KiB-aligned runs, lowest first, given +// the pages in use; it grows the file only when no free run fits. +type extentAllocatorV3 struct { + used map[uint64]bool + end uint64 // page index just past the file's last page + next uint64 // scan start: pages below it were found used or allocated +} + +func newExtentAllocatorV3(used []uint64, fileBytes uint64) *extentAllocatorV3 { + a := &extentAllocatorV3{used: make(map[uint64]bool, len(used)), end: (fileBytes + 4095) / 4096} + for _, p := range used { + a.used[p] = true + } + return a +} + +// alloc reserves n contiguous pages and returns the byte offset. +func (a *extentAllocatorV3) alloc(n uint64) uint64 { + run, start := uint64(0), uint64(0) + for p := a.next; p < a.end; p++ { + if a.used[p] { + run = 0 + if p == a.next { + a.next++ + } + continue + } + if run == 0 { + start = p + } + run++ + if run == n { + for q := start; q < start+n; q++ { + a.used[q] = true + } + if start == a.next { + a.next = start + n + } + return start * 4096 + } + } + if run > 0 && start+run == a.end { // a free run at the end grows in place + for q := start; q < a.end; q++ { + a.used[q] = true + } + need := n - run + for q := a.end; q < a.end+need; q++ { + a.used[q] = true + } + a.end += need + return start * 4096 + } + off := a.end * 4096 + for q := a.end; q < a.end+n; q++ { + a.used[q] = true + } + a.end += n + return off +} + +// Stats reports the map file's size, live bytes and truncations. The live +// bytes are computed on demand from a snapshot. +func (m *chunkLSNMapV3) Stats() ChunkMapStats { + _, live := usedPagesV3(m.liveSnapshotV3()) + return ChunkMapStats{FileBytes: m.live.fileBytes.Load(), LiveBytes: live, Truncations: m.live.truncations.Load()} +} + +// ChunkMapStatsV3 reports the owned map file's bounded-growth counters, or +// the zero value when the store has no owned map. Close clears the map +// under lifecycleMu, so the read holds it shared. +func (s *WALStore) ChunkMapStatsV3() ChunkMapStats { + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + if s.v3 == nil || s.v3.ownedMap == nil { + return ChunkMapStats{} + } + return s.v3.ownedMap.Stats() +} diff --git a/seaweed-block/core/storage/chunk_map_extents_v3_test.go b/seaweed-block/core/storage/chunk_map_extents_v3_test.go new file mode 100644 index 0000000000..ed343e1a35 --- /dev/null +++ b/seaweed-block/core/storage/chunk_map_extents_v3_test.go @@ -0,0 +1,513 @@ +package storage + +import ( + "errors" + "os" + "path/filepath" + "testing" +) + +// Extent reuse in the owned-map file. +// Map-level schedules on a one-page map (mapDescriptorV3: one chunk), with +// the publisher's slot report driven directly so each schedule is exact. + +func extentsMapV3(t *testing.T) (*chunkLSNMapV3, descriptorV3, string) { + t.Helper() + d := mapDescriptorV3(t) + path := filepath.Join(t.TempDir(), "map") + m, err := createChunkLSNMapV3(path, d, 1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.Close() }) + return m, d, path +} + +func prepV3(t *testing.T, m *chunkLSNMapV3, g uint64, prior *chunkMapCandidateV3) *chunkMapCandidateV3 { + t.Helper() + c, err := m.Prepare(g, 7, []chunkLSNEntryV3{{LSN: 100 + g}}, prior) + if err != nil { + t.Fatalf("prepare gen %d: %v", g, err) + } + return c +} + +func readsV3(t *testing.T, m *chunkLSNMapV3, d descriptorV3, c *chunkMapCandidateV3, what string) { + t.Helper() + es, _, err := readChunkLSNMapV3(m.fd, c.descriptor(d), m.chunkBlocks) + if err != nil { + t.Fatalf("%s (gen %d at %d) unreadable: %v", what, c.generation, c.rootOffset, err) + } + if es[0].LSN != 100+c.generation { + t.Fatalf("%s (gen %d) reads LSN %d", what, c.generation, es[0].LSN) + } +} + +func publishV3(m *chunkLSNMapV3, d descriptorV3, cur, other *chunkMapCandidateV3) { + m.slotsPublishedV3(cur.descriptor(d), other.descriptor(d), true) +} + +func mapFileSizeV3(t *testing.T, path string) int64 { + t.Helper() + fi, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + return fi.Size() +} + +// Every publication leaves the previous generation in the fallback slot. Its +// root and page must stay readable after every later candidate, and the file +// stays within 8 one-page maps. Mutants: a live set without the fallback +// slot (a later candidate overwrites the fallback's extents) and an +// append-only allocator (the file grows by a page and a root per candidate). +func TestChunkMapExtentsV3FallbackRootIsNeverReused(t *testing.T) { + m, d, path := extentsMapV3(t) + prev := prepV3(t, m, 1, nil) + publishV3(m, d, prev, prev) + for g := uint64(2); g <= 60; g++ { + c := prepV3(t, m, g, prev) + publishV3(m, d, c, prev) + readsV3(t, m, d, c, "current") + readsV3(t, m, d, prev, "fallback") + prev = c + } + if size := mapFileSizeV3(t, path); size > 8*2*4096 { + t.Fatalf("map file %d B after 60 generations, bound %d B", size, 8*2*4096) + } +} + +// A candidate prepared after another one that is not yet published (two +// preparers) is newer than the generation the first publication makes +// current, so it stays live and the next candidate must not reuse its +// extents. Mutant: releasing every unpublished candidate at a publication +// overwrites it. +func TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused(t *testing.T) { + m, d, _ := extentsMapV3(t) + c1 := prepV3(t, m, 1, nil) + publishV3(m, d, c1, c1) + c2 := prepV3(t, m, 2, c1) + c3 := prepV3(t, m, 3, c1) // a second preparer, not yet published + publishV3(m, d, c2, c1) + c4 := prepV3(t, m, 4, c2) + readsV3(t, m, d, c3, "in-flight gen 3") + readsV3(t, m, d, c4, "gen 4") + readsV3(t, m, d, c1, "fallback") +} + +// A crash after a candidate was written into reused extents but before any +// publication named it: the reopen of the selected slot and its fallback +// reads both intact, because a candidate only ever takes extents no slot +// names. +func TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent(t *testing.T) { + m, d, path := extentsMapV3(t) + prev := prepV3(t, m, 1, nil) + publishV3(m, d, prev, prev) + var cur *chunkMapCandidateV3 + for g := uint64(2); g <= 10; g++ { + cur = prepV3(t, m, g, prev) + publishV3(m, d, cur, prev) + prev, cur = cur, prev + } + cur, prev = prev, cur // cur = gen 10, prev = gen 9 + orphan := prepV3(t, m, 11, cur) + if orphan.rootOffset+4096 >= uint64(mapFileSizeV3(t, path)) { + t.Fatalf("setup: gen 11's root at %d did not reuse a freed extent", orphan.rootOffset) + } + if err := m.Close(); err != nil { + t.Fatal(err) + } + r, rc, err := openChunkLSNMapV3(path, cur.descriptor(d), 1) + if err != nil { + t.Fatalf("reopen of the selected slot after the crash: %v", err) + } + defer r.Close() + if rc.entries[0].LSN != 100+cur.generation { + t.Fatalf("selected slot reads LSN %d", rc.entries[0].LSN) + } + if _, _, err := readChunkLSNMapV3(r.fd, prev.descriptor(d), 1); err != nil { + t.Fatalf("fallback after the crash: %v", err) + } +} + +// Truncation while the fallback slot's root lies at the file's tail: a burst +// of unpublished candidates raises the high-water mark; the fallback then is +// the highest of them and the current one lands low. The next candidate +// must not truncate below the fallback; once a later publication releases +// it, the free tail is truncated. Mutant: truncating above the lowest live +// page cuts the fallback's root away. +func TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail(t *testing.T) { + m, d, path := extentsMapV3(t) + c := prepV3(t, m, 1, nil) + publishV3(m, d, c, c) + var burst []*chunkMapCandidateV3 + for g := uint64(2); g <= 21; g++ { + burst = append(burst, prepV3(t, m, g, c)) // unpublished: the file grows + } + top := burst[len(burst)-1] // gen 21, the highest extents + publishV3(m, d, top, c) // releases gens 2..20 + low := prepV3(t, m, 22, top) + if low.rootOffset > top.rootOffset { + t.Fatalf("setup: gen 22 at %d did not land below gen 21 at %d", low.rootOffset, top.rootOffset) + } + publishV3(m, d, low, top) // fallback = gen 21 at the tail + next := prepV3(t, m, 23, low) + readsV3(t, m, d, top, "fallback at the tail") + publishV3(m, d, next, low) // releases gen 21 + before := mapFileSizeV3(t, path) + last := prepV3(t, m, 24, next) + readsV3(t, m, d, last, "gen 24") + readsV3(t, m, d, next, "gen 23") + if after := mapFileSizeV3(t, path); after >= before || m.Stats().Truncations == 0 { + t.Fatalf("free tail not truncated: %d B -> %d B, truncations %d", before, after, m.Stats().Truncations) + } +} + +// Repeated publications refused before any slot I/O (a stale proof) release +// their candidates at once, so the file and the live set stay bounded. +// Mutant: no definite-abandon path keeps every rejected candidate pinned +// until a later successful publication and the file grows by a root each. +func TestChunkMapExtentsV3RejectedPublicationsStayBounded(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + cp := s.v3.pub.current().CheckpointLSN + for i := 0; i < 300; i++ { + prepared, err := s.prepareOwnedMapCheckpointV3(cp) + if err != nil { + t.Fatalf("prepare %d: %v", i, err) + } + if err := s.v3.pub.invalidateMapProofV3(); err != nil { + t.Fatal(err) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil { + t.Fatal("a stale-proof publication succeeded") + } + } + st := s.ChunkMapStatsV3() + fi, err := os.Stat(path + ".chunkmap") + if err != nil { + t.Fatal(err) + } + if fi.Size() > 8*2*4096 || st.LiveBytes > 4*2*4096 { + t.Fatalf("after 300 rejected publications: file %d B, live %d B", fi.Size(), st.LiveBytes) + } +} + +// damageNewestSlotV3 corrupts the slot with the higher generation so the +// next open selects the fallback slot. +func damageNewestSlotV3(t *testing.T, path string) { + t.Helper() + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + defer f.Close() + var gens [2]uint64 + offs := [2]int64{slotAOffsetV3, slotBOffsetV3} + for i, off := range offs { + b := make([]byte, slotSizeV3) + if _, err := f.ReadAt(b, off); err != nil { + t.Fatal(err) + } + if d, err := decodeSlotV3(b, nil); err == nil { + gens[i] = d.SlotGen + } + } + off := offs[0] + if gens[1] > gens[0] { + off = offs[1] + } + if _, err := f.WriteAt([]byte{0xFF, 0xFF, 0xFF, 0xFF}, off+64); err != nil { + t.Fatal(err) + } + if err := f.Sync(); err != nil { + t.Fatal(err) + } +} + +// A real two-slot reopen registers BOTH slot roots read from disk, so a +// candidate prepared before the open's first publication (which would +// re-report both slots) cannot take the fallback root's extents. The +// candidates are prepared right after the open, none is published, and the +// store crashes; with the newest slot damaged, the reopen selects the +// fallback slot and its map must validate. Mutant: an open that does not +// register the fallback slot's root lets the candidates overwrite it. +func TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot(t *testing.T) { + path := filepath.Join(t.TempDir(), "mapped") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, v3TestWAL, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 10; i++ { + writeSynced(t, s, i, i) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + } + // One more map publication without the checkpoint's rollover, so the two + // slots name different map roots at the crash. + writeSynced(t, s, 12, 12) + prepared, err := s.prepareOwnedMapCheckpointV3(s.v3.pub.current().CheckpointLSN) + if err != nil { + t.Fatal(err) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + cp := r.v3.pub.current().CheckpointLSN + r.v3.pub.descMu.Lock() + cur, other, otherValid := r.v3.pub.cur, r.v3.pub.other, r.v3.pub.otherValid + r.v3.pub.descMu.Unlock() + if !otherValid || cur.MapGeneration == other.MapGeneration { + t.Fatalf("setup: slots name map generations %d and %d (fallback valid %v)", cur.MapGeneration, other.MapGeneration, otherValid) + } + for i := 0; i < 20; i++ { // unpublished candidates fill every free extent + if _, err := r.prepareOwnedMapCheckpointV3(cp); err != nil { + t.Fatal(err) + } + } + crashRecoveryHardeningStore(t, r) + damageNewestSlotV3(t, path) + q, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatalf("reopen from the fallback slot: %v", err) + } + q.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { crashRecoveryHardeningStore(t, q) }) + if _, err := q.Recover(); err != nil { + t.Fatalf("recover from the fallback slot: %v", err) + } +} + +// A failed fsync of the tail truncation itself (the first fsync of the +// prepare) latches the map: the prepare and every later one fail. The slot +// roots stay readable, because the truncation only removes extents above +// the highest live page. +func TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots(t *testing.T) { + m, d, path := extentsMapV3(t) + c := prepV3(t, m, 1, nil) + publishV3(m, d, c, c) + var top *chunkMapCandidateV3 + for g := uint64(2); g <= 21; g++ { + top = prepV3(t, m, g, c) + } + publishV3(m, d, top, c) + low := prepV3(t, m, 22, top) + publishV3(m, d, low, top) + next := prepV3(t, m, 23, low) + publishV3(m, d, next, low) // gen 21 released: the tail is free + before := mapFileSizeV3(t, path) + orig, calls := m.syncFile, 0 + m.syncFile = func() error { + calls++ + if calls == 1 { + return os.ErrInvalid // the truncation's fsync + } + return orig() + } + if _, err := m.Prepare(24, 7, []chunkLSNEntryV3{{LSN: 124}}, next); err == nil { + t.Fatal("prepare across a failed truncation fsync succeeded") + } + if calls != 1 || mapFileSizeV3(t, path) >= before { + t.Fatalf("setup: %d fsyncs, file %d B -> %d B; want the truncation's fsync to fail", calls, before, mapFileSizeV3(t, path)) + } + if got, want := m.Stats().FileBytes, uint64(mapFileSizeV3(t, path)); got != want { + t.Fatalf("stats after a truncation whose fsync failed: file bytes %d, file is %d B", got, want) + } + if _, err := m.Prepare(25, 7, []chunkLSNEntryV3{{LSN: 125}}, next); err == nil || calls != 1 { + t.Fatalf("the map did not latch: err %v, fsyncs %d", err, calls) + } + if err := m.Close(); err != nil { + t.Fatal(err) + } + r, rc, err := openChunkLSNMapV3(path, next.descriptor(d), 1) + if err != nil { + t.Fatalf("reopen after the truncation fault: %v", err) + } + defer r.Close() + if rc.entries[0].LSN != 100+next.generation { + t.Fatalf("selected root reads LSN %d", rc.entries[0].LSN) + } + if _, _, err := readChunkLSNMapV3(r.fd, low.descriptor(d), 1); err != nil { + t.Fatalf("fallback after the truncation fault: %v", err) + } +} + +// A publication whose slot I/O failed leaves an uncertain candidate: the +// publisher latches and the candidate stays pinned until reopen. A later +// admitted prepare must not reuse its extents, and both the uncertain +// candidate and the slot roots stay readable. Mutant: abandoning the +// uncertain candidate like a refused one lets the later prepare overwrite it. +func TestChunkMapExtentsV3UncertainCandidateStaysPinned(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + cp := s.v3.pub.current().CheckpointLSN + prepared, err := s.prepareOwnedMapCheckpointV3(cp) + if err != nil { + t.Fatal(err) + } + s.v3.testBeforeSlotWrite = func() error { return os.ErrInvalid } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil { + t.Fatal("a publication with a failed slot write succeeded") + } + s.v3.testBeforeSlotWrite = nil + m := s.v3.ownedMap + unc := prepared.candidate + for i := 0; i < 5; i++ { // admitted prepares after the failure + if _, err := m.prepareNextV3(cp, append([]chunkLSNEntryV3(nil), s.v3.mapEntries...), unc); err != nil { + t.Fatalf("admitted prepare %d: %v", i, err) + } + } + d := s.v3.pub.current() + if _, _, err := readChunkLSNMapV3(m.fd, unc.descriptor(d), m.chunkBlocks); err != nil { + t.Fatalf("uncertain candidate overwritten: %v", err) + } + if _, _, err := readChunkLSNMapV3(m.fd, d, m.chunkBlocks); err != nil { + t.Fatalf("selected slot root overwritten: %v", err) + } +} + +// ChunkMapStatsV3 is correct right after a reopen: the file size and the +// live bytes of the two slot roots read from disk, not zero. +func TestChunkMapExtentsV3StatsAfterReopen(t *testing.T) { + path := filepath.Join(t.TempDir(), "mapped") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, v3TestWAL, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 5; i++ { + writeSynced(t, s, i, i) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + } + crashRecoveryHardeningStore(t, s) + fi, err := os.Stat(path + ".chunkmap") + if err != nil { + t.Fatal(err) + } + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + st := r.ChunkMapStatsV3() + if st.FileBytes != uint64(fi.Size()) || st.LiveBytes == 0 || st.LiveBytes > st.FileBytes { + t.Fatalf("stats after reopen: %+v, file %d B", st, fi.Size()) + } +} + +// A candidate that is prepared successfully but whose proof went stale +// during its file I/O (a guest write changed the map meanwhile) is +// refused before publication and must be released at once, so a steady +// stream of such refusals keeps the file bounded. Both preparation paths +// are covered: the checkpoint's and prepareMapPublicationV3. Mutant: not +// abandoning after the proof check pins every refused candidate. +func TestChunkMapExtentsV3ProofStalePreparesStayBounded(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + m := s.v3.ownedMap + orig := m.syncFile + m.syncFile = func() error { // the proof goes stale during the prepare's I/O + if err := s.v3.mapProof.mutatedV3(); err != nil { + return err + } + return orig() + } + cp := s.v3.pub.current().CheckpointLSN + for i := 0; i < 150; i++ { + _, err := s.prepareOwnedMapCheckpointV3(cp) + var reason mapCoverageRefusal + if !errors.Is(err, ErrMapCoverageStale) || !errors.As(err, &reason) || reason != "proof_changed_during_prepare" { + t.Fatalf("checkpoint prepare %d: err = %v, want ErrMapCoverageStale", i, err) + } + } + g := s.v3.pub.current().MapGeneration + for i := 0; i < 150; i++ { + g += 1000 + entries := append([]chunkLSNEntryV3(nil), s.v3.mapEntries...) + _, err := prepareMapPublicationV3(m, s.v3.mapProof, g, cp, entries, nil) + var reason mapCoverageRefusal + if !errors.Is(err, ErrMapCoverageStale) || !errors.As(err, &reason) || reason != "proof_changed_during_prepare" { + t.Fatalf("publication prepare %d: err = %v, want ErrMapCoverageStale", i, err) + } + } + m.syncFile = orig + fi, err := os.Stat(path + ".chunkmap") + if err != nil { + t.Fatal(err) + } + if st := s.ChunkMapStatsV3(); fi.Size() > 8*2*4096 || st.LiveBytes > 4*2*4096 { + t.Fatalf("after 300 proof-stale prepares: file %d B, live %d B", fi.Size(), st.LiveBytes) + } +} + +// A publication whose slot write and fsync both happened, but which a fault +// latched meanwhile refuses at its success boundary, may be named by the +// slot on disk. Its candidate stays pinned: an already admitted preparer +// does not reuse its extents, and after a crash the reopen selects that +// slot and its map validates. Mutant: treating that refusal like one before +// slot I/O abandons the candidate and the preparer overwrites it. +func TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned(t *testing.T) { + path := filepath.Join(t.TempDir(), "mapped") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, v3TestWAL, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 4; i++ { + writeSynced(t, s, i, i) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + } + writeSynced(t, s, 9, 9) + cp := s.v3.pub.current().CheckpointLSN + prepared, err := s.prepareOwnedMapCheckpointV3(cp) + if err != nil { + t.Fatal(err) + } + orig := s.v3.pub.io.fsync + s.v3.pub.io.fsync = func() error { // the slot reaches disk, then a fault latches + err := orig() + s.latchV3(os.ErrInvalid) + return err + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err == nil { + t.Fatal("a publication refused at its success boundary returned no error") + } + s.v3.pub.io.fsync = orig + m := s.v3.ownedMap + for i := 0; i < 10; i++ { // an already admitted preparer keeps going + entries := append([]chunkLSNEntryV3(nil), s.v3.mapEntries...) + entries[0].LSN += uint64(i + 1) + if _, err := m.prepareNextV3(cp, entries, prepared.candidate); err != nil { + t.Fatalf("admitted prepare %d: %v", i, err) + } + } + crashRecoveryHardeningStore(t, s) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatalf("reopen of the durable slot: %v", err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + if g := r.v3.pub.current().MapGeneration; g != prepared.candidate.generation { + t.Fatalf("reopen selected map generation %d, want the durable one %d", g, prepared.candidate.generation) + } +} diff --git a/seaweed-block/core/storage/chunk_map_publication_v3.go b/seaweed-block/core/storage/chunk_map_publication_v3.go new file mode 100644 index 0000000000..2ef10237b2 --- /dev/null +++ b/seaweed-block/core/storage/chunk_map_publication_v3.go @@ -0,0 +1,216 @@ +package storage + +// Dark row-7 map publication/proof controls. These are NOT flusher/provider +// integration: the row-5b real WALStore must call the lifecycle invalidations +// and prepare from its permitted quiesced mutation snapshot before activation. +import ( + "encoding/binary" + "errors" + "math" + "os" + "sync" + "sync/atomic" +) + +var ErrMapCoverageStale = errors.New("storage: v3 chunk map coverage or proof stale") + +// Each open has a distinct domain pointer. Epochs never wrap. Recover must +// invalidate at START and at END (also on failure); reset and every install +// transition invalidate too. No store/map lock is taken by an invalidation. +// The owner must serialize these lifecycle transitions against descriptor +// publication using its existing lifecycle admission; this type adds no lock. +type mapProofEpochV3 struct{ epoch, mutation atomic.Uint64 } + +func newMapProofEpochV3() *mapProofEpochV3 { d := &mapProofEpochV3{}; d.epoch.Store(1); return d } +func advanceMapProofCounterV3(v *atomic.Uint64) error { + for { + n := v.Load() + if n >= counterMaxV3 { + return ErrCounterExhausted + } + if v.CompareAndSwap(n, n+1) { + return nil + } + } +} +func (d *mapProofEpochV3) invalidateV3() error { return advanceMapProofCounterV3(&d.epoch) } +func (d *mapProofEpochV3) mutatedV3() error { return advanceMapProofCounterV3(&d.mutation) } + +type mapPublicationProofV3 struct { + domain *mapProofEpochV3 + epoch, mutation uint64 +} + +func (d *mapProofEpochV3) snapshotV3() mapPublicationProofV3 { + return mapPublicationProofV3{domain: d, epoch: d.epoch.Load(), mutation: d.mutation.Load()} +} +func (p mapPublicationProofV3) validV3(d *mapProofEpochV3) bool { + return d != nil && p.domain == d && p.epoch < counterMaxV3 && p.mutation < counterMaxV3 && p.epoch == d.epoch.Load() && p.mutation == d.mutation.Load() +} + +type preparedMapPublicationV3 struct { + candidate *chunkMapCandidateV3 + proof mapPublicationProofV3 +} + +// The caller supplies entries from its permitted mutation/version boundary. +// Preparation takes the sidecar mutex and I/O only, before store/desc locks. +func prepareMapPublicationV3(m *chunkLSNMapV3, d *mapProofEpochV3, g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (*preparedMapPublicationV3, error) { + if m == nil || d == nil { + return nil, mapCoverageRefusal("map_binding_missing") + } + proof := d.snapshotV3() + c, e := m.Prepare(g, C, entries, prior) + if e != nil { + return nil, e + } + if !proof.validV3(d) { + m.abandonCandidateV3(c) // prepared but never publishable + return nil, mapCoverageRefusal("proof_changed_during_prepare") + } + return &preparedMapPublicationV3{candidate: c, proof: proof}, nil +} +func sameMapTupleV3(d descriptorV3, c *chunkMapCandidateV3) bool { + if c == nil || c.owner == nil { + return false + } + id := c.owner.identity + return d.UUID == id.UUID && sameGeometryV3(d, id) && d.MapLineage == id.MapLineage && d.MapFormatID == mapFormatIDV1 && d.MapGeneration == c.generation && d.MapCoveredCheckpoint == c.covered && d.MapRootLocator == c.rootOffset && d.MapRootHash == c.hash +} + +// bindMapV3 is used only while opening/quiesced. Snapshot both slots under +// descMu, validate all dependencies without store/desc locks, then recheck the +// snapshot before installing the open proof domain. A fallback remains a root +// even when none of its pages belong to the selected generation. +func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpochV3) error { + if c == nil || c.owner == nil || d == nil { + return mapCoverageRefusal("map_binding_missing") + } + p.descMu.Lock() + current, other, otherValid := p.cur, p.other, p.otherValid + p.descMu.Unlock() + if !sameMapTupleV3(current, c) { + return mapCoverageRefusal("map_tuple_changed") + } + if _, _, e := readChunkLSNMapV3(c.owner.fd, current, c.owner.chunkBlocks); e != nil { + return e + } + if otherValid { + if other.UUID != current.UUID || other.MapLineage != current.MapLineage || !sameGeometryV3(other, current) { + return ErrMapInvalid + } + if _, _, e := readChunkLSNMapV3(c.owner.fd, other, c.owner.chunkBlocks); e != nil { + return e + } + } + p.descMu.Lock() + defer p.descMu.Unlock() + if p.cur != current || p.otherValid != otherValid || (otherValid && p.other != other) { + return mapCoverageRefusal("descriptor_changed_during_bind") + } + p.mapCurrent = c + p.mapDomain = d + return nil +} +func (p *descriptorPublisherV3) validateMapPublicationV3(next descriptorV3, prepared *preparedMapPublicationV3) error { + if p.mapCurrent == nil { + if prepared != nil { + return mapCoverageRefusal("map_not_bound") + } + return nil + } // dark core not bound yet + c := p.mapCurrent + if prepared != nil { + c = prepared.candidate + if c == nil || c.owner != p.mapCurrent.owner || !prepared.proof.validV3(p.mapDomain) { + return mapCoverageRefusal("proof_changed") + } + if c.generation <= p.mapCurrent.generation || c.covered < p.mapCurrent.covered { + return mapCoverageRefusal("candidate_superseded") + } + } + if !sameMapTupleV3(next, c) || c.covered < next.CheckpointLSN || c.covered > next.W { + return mapCoverageRefusal("map_coverage_mismatch") + } + return nil +} +func (p *descriptorPublisherV3) publishMapV3(storeMu sync.Locker, snap func(), prepared *preparedMapPublicationV3, mutate func(*descriptorV3) error) (descriptorV3, error) { + if prepared == nil || prepared.candidate == nil { + return descriptorV3{}, mapCoverageRefusal("candidate_missing") + } + d, err := p.publishWithMapV3(storeMu, snap, func(d *descriptorV3) error { + if mutate != nil { + if e := mutate(d); e != nil { + return e + } + } + *d = prepared.candidate.descriptor(*d) + return nil + }, prepared) + if err != nil { + // Definite abandon: unless the slot I/O started (the candidate is + // the uncertain one, pinned until reopen), no slot can name it. + c := prepared.candidate + p.descMu.Lock() + unc := p.uncertain + if unc == nil || unc.MapRootLocator != c.rootOffset || unc.MapGeneration != c.generation { + prepared.abandonV3() + } + p.descMu.Unlock() + } + return d, err +} + +// invalidateMapProofV3 is called under WALStore.mu at a lifecycle boundary. +// Taking the existing descMu orders the epoch change after any publication +// already inside descriptor I/O. It performs no callback, allocation or I/O. +// A not-yet-bound dark store has no candidate domain to invalidate. +func (p *descriptorPublisherV3) invalidateMapProofV3() error { + p.descMu.Lock() + defer p.descMu.Unlock() + if p.mapDomain == nil { + return nil + } + return p.mapDomain.invalidateV3() +} + +// openDescriptorMapV3 validates geometry from the root and both valid slot +// dependencies before any store background worker is started. Geometry is +// subsequently checked by the chunk/provider caller against its configuration. +func openDescriptorMapV3(path string, selected descriptorV3, fallback *descriptorV3) (*chunkLSNMapV3, *chunkMapCandidateV3, error) { + if selected.MapRootLocator > math.MaxInt64-64 { + return nil, nil, ErrMapInvalid + } + f, err := os.Open(path) + if err != nil { + return nil, nil, err + } + var raw [8]byte + _, err = f.ReadAt(raw[:], int64(selected.MapRootLocator)+56) + err = errors.Join(err, f.Close()) + if err != nil { + return nil, nil, err + } + cb := binary.LittleEndian.Uint64(raw[:]) + m, c, err := openChunkLSNMapV3(path, selected, cb) + if err != nil { + return nil, nil, err + } + if fallback != nil { + if fallback.UUID != selected.UUID || fallback.MapLineage != selected.MapLineage || !sameGeometryV3(*fallback, selected) { + err = ErrMapInvalid + } else { + var refs []mapPageRefV3 + if _, refs, err = readChunkLSNMapV3(m.fd, *fallback, cb); err == nil { + if sh, e := mapShapeForV3(*fallback, cb); e == nil { + m.registerRootV3(fallback.MapGeneration, fallback.MapRootLocator, sh.aligned, refs) + } + } + } + if err != nil { + _ = m.Close() + return nil, nil, err + } + } + return m, c, nil +} diff --git a/seaweed-block/core/storage/chunk_map_publication_v3_test.go b/seaweed-block/core/storage/chunk_map_publication_v3_test.go new file mode 100644 index 0000000000..0325e87680 --- /dev/null +++ b/seaweed-block/core/storage/chunk_map_publication_v3_test.go @@ -0,0 +1,292 @@ +package storage + +import ( + "bytes" + "errors" + "path/filepath" + "testing" + "time" +) + +type mapPublicationHarnessV3 struct { + h *descHarnessV3 + m *chunkLSNMapV3 + domain *mapProofEpochV3 + initial *chunkMapCandidateV3 +} + +func newMapPublicationHarnessV3(t *testing.T, gen uint64) *mapPublicationHarnessV3 { + t.Helper() + h := newDescHarnessV3(t) + d := h.pub.current() + d.W = 200 + d.CheckpointLSN = 100 + d.MapCoveredCheckpoint = 100 + cb := d.VolumeSize / uint64(d.BlockSize) + m, e := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, cb) + if e != nil { + t.Fatal(e) + } + t.Cleanup(func() { m.Close() }) + c, e := m.Prepare(gen, 100, []chunkLSNEntryV3{{LSN: 100}}, nil) + if e != nil { + t.Fatal(e) + } + d = c.descriptor(d) + h.pub.cur = d + if _, e = h.f.WriteAt(d.encode(), 0); e != nil { + t.Fatal(e) + } + domain := newMapProofEpochV3() + if e = h.pub.bindMapV3(c, domain); e != nil { + t.Fatal(e) + } + return &mapPublicationHarnessV3{h, m, domain, c} +} +func (x *mapPublicationHarnessV3) prepare(t *testing.T, g, C uint64) *preparedMapPublicationV3 { + t.Helper() + c, e := prepareMapPublicationV3(x.m, x.domain, g, C, []chunkLSNEntryV3{{LSN: C}}, x.initial) + if e != nil { + t.Fatal(e) + } + return c +} +func mapSlotsV3(t *testing.T, h *descHarnessV3) []byte { + t.Helper() + b := make([]byte, 8192) + if _, e := h.f.ReadAt(b, 0); e != nil { + t.Fatal(e) + } + return b +} +func awaitMapPublishV3(t *testing.T, ch <-chan error) error { + t.Helper() + select { + case e := <-ch: + return e + case <-time.After(5 * time.Second): + t.Fatal("map publication did not settle") + return nil + } +} +func TestMapPublicationV3_HeldPublicationsBothOrders(t *testing.T) { + for _, reverse := range []bool{false, true} { + t.Run(map[bool]string{false: "A_then_B", true: "B_then_A"}[reverse], func(t *testing.T) { + x := newMapPublicationHarnessV3(t, 11) + a := x.prepare(t, 12, 120) + b := x.prepare(t, 13, 110) + releaseA := make(chan struct{}) + releaseB := make(chan struct{}) + aDone := make(chan error, 1) + bDone := make(chan error, 1) + joined := make(chan struct{}, 2) + t.Cleanup(func() { + select { + case <-releaseA: + default: + close(releaseA) + } + select { + case <-releaseB: + default: + close(releaseB) + } + timer := time.NewTimer(5 * time.Second) + defer timer.Stop() + for i := 0; i < 2; i++ { + select { + case <-joined: + case <-timer.C: + t.Error("publication workers did not join") + return + } + } + }) + go func() { + defer func() { joined <- struct{}{} }() + <-releaseA + _, e := x.h.pub.publishMapV3(&x.h.storeMu, nil, a, func(d *descriptorV3) error { d.CheckpointLSN = 120; return nil }) + aDone <- e + }() + go func() { + defer func() { joined <- struct{}{} }() + <-releaseB + _, e := x.h.pub.publishMapV3(&x.h.storeMu, nil, b, func(d *descriptorV3) error { d.CheckpointLSN = 110; return nil }) + bDone <- e + }() + if reverse { + close(releaseB) + if e := awaitMapPublishV3(t, bDone); e != nil { + t.Fatal(e) + } + before := mapSlotsV3(t, x.h) + close(releaseA) + if e := awaitMapPublishV3(t, aDone); !errors.Is(e, ErrMapCoverageStale) { + t.Fatalf("lower-generation A=%v", e) + } + if !bytes.Equal(before, mapSlotsV3(t, x.h)) { + t.Fatal("refused A wrote slots") + } + } else { + close(releaseA) + if e := awaitMapPublishV3(t, aDone); e != nil { + t.Fatal(e) + } + before := mapSlotsV3(t, x.h) + close(releaseB) + if e := awaitMapPublishV3(t, bDone); !errors.Is(e, ErrMapCoverageStale) { + t.Fatalf("stale-coverage B=%v", e) + } + if !bytes.Equal(before, mapSlotsV3(t, x.h)) { + t.Fatal("refused B wrote slots") + } + } + fresh := x.prepare(t, 14, 130) + if _, e := x.h.pub.publishMapV3(&x.h.storeMu, nil, fresh, func(d *descriptorV3) error { d.CheckpointLSN = 125; return nil }); e != nil { + t.Fatal(e) + } + d := x.h.pub.current() + if d.MapGeneration != 14 || d.MapCoveredCheckpoint != 130 || d.CheckpointLSN != 125 { + t.Fatalf("fresh tuple=%+v", d) + } + }) + } +} +func TestMapPublicationV3_IsolatedMergedCoverageAndWPositive(t *testing.T) { + x := newMapPublicationHarnessV3(t, 12) + c := x.prepare(t, 13, 110) + before := mapSlotsV3(t, x.h) + d0 := x.h.pub.current() + floor, ok := x.h.pub.reuseFloor() + if _, e := x.h.pub.publishMapV3(&x.h.storeMu, nil, c, func(d *descriptorV3) error { d.CheckpointLSN = 120; return nil }); !errors.Is(e, ErrMapCoverageStale) { + t.Fatalf("isolated merged coverage=%v", e) + } + f2, o2 := x.h.pub.reuseFloor() + if d0 != x.h.pub.current() || floor != f2 || ok != o2 || !bytes.Equal(before, mapSlotsV3(t, x.h)) { + t.Fatal("refused candidate changed descriptor/tail/floor/slots") + } + if _, e := x.h.pub.publish(&x.h.storeMu, nil, func(d *descriptorV3) error { d.W = 210; return nil }); e != nil { + t.Fatal(e) + } + if x.h.pub.current().MapRootHash != d0.MapRootHash { + t.Fatal("W-only changed root") + } +} +func TestMapPublicationV3_ProofEpochAndMutationRefusal(t *testing.T) { + for _, event := range []string{"recover_start", "recover_end_success", "recover_end_failure", "reset", "install_begin", "install_complete", "install_abort", "mutation", "domain_identity", "new_open"} { + t.Run(event, func(t *testing.T) { + x := newMapPublicationHarnessV3(t, 12) + if event == "recover_end_success" || event == "recover_end_failure" { + if e := x.domain.invalidateV3(); e != nil { + t.Fatal(e) + } + } + c := x.prepare(t, 13, 110) + if event == "mutation" { + if e := x.domain.mutatedV3(); e != nil { + t.Fatal(e) + } + } else if event == "domain_identity" { + x.domain = newMapProofEpochV3() + if e := x.h.pub.bindMapV3(x.initial, x.domain); e != nil { + t.Fatal(e) + } + } else if event == "new_open" { + if e := x.m.Close(); e != nil { + t.Fatal(e) + } + m, loaded, e := openChunkLSNMapV3(x.m.fd.Name(), x.h.pub.current(), x.m.chunkBlocks) + if e != nil { + t.Fatal(e) + } + x.m = m + t.Cleanup(func() { m.Close() }) + x.initial = loaded + x.domain = newMapProofEpochV3() + if e = x.h.pub.bindMapV3(loaded, x.domain); e != nil { + t.Fatal(e) + } + } else { + if e := x.domain.invalidateV3(); e != nil { + t.Fatal(e) + } + } + before := mapSlotsV3(t, x.h) + if _, e := x.h.pub.publishMapV3(&x.h.storeMu, nil, c, nil); !errors.Is(e, ErrMapCoverageStale) { + t.Fatalf("%s stale proof=%v", event, e) + } + if !bytes.Equal(before, mapSlotsV3(t, x.h)) { + t.Fatal("stale proof wrote slots") + } + // Reprepare with current epoch/open owner and a strictly higher generation. + fresh := x.prepare(t, 14, 110) + if _, e := x.h.pub.publishMapV3(&x.h.storeMu, nil, fresh, nil); e != nil { + t.Fatal(e) + } + }) + } +} +func TestMapPublicationV3_UncertainFinalResponsePinsCandidate(t *testing.T) { + x := newMapPublicationHarnessV3(t, 12) + c := x.prepare(t, 13, 110) + boom := errors.New("response lost after descriptor write") + x.h.writeHook = func(off int64, b []byte) error { + if _, e := x.h.f.WriteAt(b, off); e != nil { + return e + } + return boom + } + if _, e := x.h.pub.publishMapV3(&x.h.storeMu, nil, c, nil); !errors.Is(e, ErrDescriptorPublishUncertain) { + t.Fatalf("unknown final response=%v", e) + } + pending, ok := x.h.pub.uncertainCandidate() + if !ok || pending.MapRootHash != c.candidate.hash { + t.Fatal("uncertain map dependency unpinned") + } + if _, _, e := readChunkLSNMapV3(x.m.fd, pending, x.m.chunkBlocks); e != nil { + t.Fatalf("candidate pages lost: %v", e) + } + if _, ok := x.h.pub.reuseFloor(); ok { + t.Fatal("unknown publication allowed retirement") + } +} +func TestMapPublicationV3_CoverageWAndNoUnpreparedRoot(t *testing.T) { + x := newMapPublicationHarnessV3(t, 12) + c := x.prepare(t, 13, 201) + if _, e := x.h.pub.publishMapV3(&x.h.storeMu, nil, c, nil); !errors.Is(e, ErrMapCoverageStale) { + t.Fatalf("C>W=%v", e) + } + if _, e := x.h.pub.publish(&x.h.storeMu, nil, func(d *descriptorV3) error { *d = c.candidate.descriptor(*d); return nil }); !errors.Is(e, ErrMapCoverageStale) { + t.Fatalf("unprepared root bypass=%v", e) + } +} + +func TestMapPublicationV3_ProofChangedDuringPersistenceRefuses(t *testing.T) { + x := newMapPublicationHarnessV3(t, 12) + before := mapSlotsV3(t, x.h) + x.m.syncDirectory = func() error { return x.domain.invalidateV3() } + if c, e := prepareMapPublicationV3(x.m, x.domain, 13, 110, []chunkLSNEntryV3{{LSN: 110}}, x.initial); !errors.Is(e, ErrMapCoverageStale) || c != nil { + t.Fatalf("overlapping invalidation yielded candidate: %v %v", c, e) + } + if !bytes.Equal(before, mapSlotsV3(t, x.h)) { + t.Fatal("preparation changed slots") + } +} +func TestMapPublicationV3_ProofCountersNeverWrap(t *testing.T) { + d := newMapProofEpochV3() + d.epoch.Store(counterMaxV3) + if e := d.invalidateV3(); !errors.Is(e, ErrCounterExhausted) { + t.Fatal(e) + } + if d.snapshotV3().validV3(d) { + t.Fatal("exhausted epoch accepted") + } + d = newMapProofEpochV3() + d.mutation.Store(counterMaxV3) + if e := d.mutatedV3(); !errors.Is(e, ErrCounterExhausted) { + t.Fatal(e) + } + if d.snapshotV3().validV3(d) { + t.Fatal("exhausted mutation version accepted") + } +} diff --git a/seaweed-block/core/storage/chunk_public.go b/seaweed-block/core/storage/chunk_public.go index a81d157e2f..8dcfb337a7 100644 --- a/seaweed-block/core/storage/chunk_public.go +++ b/seaweed-block/core/storage/chunk_public.go @@ -20,6 +20,14 @@ type ( ChunkLayerStats = chunkLayerStats ChunkIntent = chunkIntent ChunkDetachedBy = chunkDetachedBy + DetachSettlement = detachSettlement +) + +// How a failed Detach ended (ChunkLayer.SettleDetach). +const ( + DetachNotPublished = detachNotPublished + DetachApplied = detachApplied + DetachFenced = detachFenced ) // HEAD states. @@ -45,6 +53,7 @@ const ( ) var ( + ErrCutCOWAborted = errCutCOWAborted ErrChunkKeyExists = errChunkKeyExists ErrChunkHeadPrecondition = errChunkHeadPrecondition ErrChunkHeadDeleted = errChunkHeadDeleted diff --git a/seaweed-block/core/storage/chunk_restore.go b/seaweed-block/core/storage/chunk_restore.go index c95f8a9d1f..e34a11251b 100644 --- a/seaweed-block/core/storage/chunk_restore.go +++ b/seaweed-block/core/storage/chunk_restore.go @@ -57,11 +57,31 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi // A new holder's takeover starts serving the same image as active. The // previous holder's final-cut proof belongs only to its detached HEAD. next.State, next.DetachedBy = chunkHeadActive, nil + var intents []string + settled := true // no root RPC sent yet + defer func() { + if settled { + for _, id := range intents { + _ = remote.DeleteIntent(ctx, id) + } + } + }() + if builder, ok := remote.(ChunkManifestBuilder); ok && next.Segments == nil && len(next.Chunks) != 0 { + if cfg.RestoreChunkBytes == 0 { + return ChunkHead{}, errors.New("storage: legacy HEAD claim needs validated chunk geometry") + } + next, intents, err = builder.PrepareManifest(ctx, head, next, cfg.RestoreChunkBytes) + if err != nil { + return ChunkHead{}, err + } + } if err := allowed(); err != nil { return ChunkHead{}, err } + settled = false // an ambiguous CAS keeps its segment intents gen, casErr := remote.CASHead(ctx, ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, next) if casErr == nil { + settled = true next.Gen = gen return next, allowed() } @@ -71,6 +91,7 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi if readErr != nil { return ChunkHead{}, fmt.Errorf("storage: HEAD claim unresolved: %w", errors.Join(casErr, readErr)) } + settled = errors.Is(casErr, ErrChunkHeadPrecondition) || current.Gen > head.Gen if current.Gen > head.Gen && sameProposal(current, next) { return current, allowed() } diff --git a/seaweed-block/core/storage/chunk_restore_test.go b/seaweed-block/core/storage/chunk_restore_test.go index 115f4e5818..6652121559 100644 --- a/seaweed-block/core/storage/chunk_restore_test.go +++ b/seaweed-block/core/storage/chunk_restore_test.go @@ -8,12 +8,12 @@ import ( ) func TestClaimChunkHeadClearsProductionDetachProof(t *testing.T) { - s, path := newChunkTestStore(t) + s, _ := newChunkTestStore(t) if _, err := s.Recover(); err != nil { t.Fatal(err) } remote := NewMemChunkRemote() - layer, err := AttachChunkLayer(s, remote, ChunkLayerConfig{ChunkBlocks: 4, Epoch: 1, Holder: "old", Bitmap: NewFileChunkBitmapStore(path + ".bitmap")}) + layer, err := AttachChunkLayer(s, remote, ChunkLayerConfig{ChunkBlocks: 4, Epoch: 1, Holder: "old"}) if err != nil { t.Fatal(err) } @@ -137,7 +137,7 @@ func TestClaimChunkHeadFencesNoopCut(t *testing.T) { } func TestFreshRestoreBitmapStartsAtClaimedHEAD(t *testing.T) { - s, _ := newChunkTestStore(t) + s, _ := newLegacyChunkTestStore(t) r := NewMemChunkRemote() if _, err := r.CASHead(ctTimeout(t), ChunkHeadVersion{}, ChunkHead{Epoch: 2, Holder: "host-a", RemoteLSN: 42}); err != nil { t.Fatal(err) diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 4367acd5e9..c1cc2888f2 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -15,12 +15,12 @@ package storage // 1. blocks new writes at the store and waits for in-flight ones; // 2. Syncs; H is then the synced LSN (nextLSN-1) and no data newer than H // exists in the WAL or the extent. The flusher is not drained; -// 3. under that barrier reads every chunk dirtied since the last HEAD -// through the store's normal read path (dirty map/WAL entry if present, -// else extent) into immutable buffers; that is exactly the image at H. -// A chunk counts as dirty since HEAD whether its newer blocks are still -// in the WAL or already in the extent; -// 4. releases the barrier (pause = Sync + copy of the dirty chunks); +// 3. fixes the candidate set and installs an owned-map v3 COW window under +// that barrier, then releases it (pause = Sync + window installation); +// 4. copies outside the barrier. Before publication, the first writer to a +// pending candidate saves its at-H chunk; writers wait for a copying or +// saving owner. Both paths use the validated store reader. Legacy test +// fixtures retain the full-copy barrier; // 5. uploads the buffers, outside every walstore lock; // 6. CASes HEAD {gen, epoch} with RemoteLSN = H. // @@ -151,10 +151,12 @@ type chunkBitmapStore interface { } // chunkRef names one published chunk: its immutable key and the SHA-256 of -// its ChunkBlocks*BlockSize bytes. +// its stored object bytes, verified before any encoding is decoded. type chunkRef struct { - Key string - SHA256 [32]byte + Key string + SHA256 [32]byte + Encoding string + BirthLSN uint64 } // chunkHeadVersion is the CAS guard of HEAD. @@ -331,6 +333,9 @@ type chunkLayerConfig struct { // while its frontend is gated. An error leaves remote ownership unchanged. // No store/layer/remote lock is held across the callback. PrepareRestore func(head chunkHead) error + // RestoreChunkBytes is the local, validated geometry for upgrading a flat + // legacy image during an ownership claim; it is never inferred from data. + RestoreChunkBytes uint64 // CaptureAllowed is supplied by the store owner. It is an admission // check, made when a capture starts and again right before its HEAD CAS: // it refuses a cut during a BASE install or rebuild, or when this node is @@ -338,10 +343,16 @@ type chunkLayerConfig struct { // that last check and the CAS. Publication safety across a demotion // rests on the epoch: a new primary's takeover raises the HEAD epoch, so // the old primary's CAS fails and it fences (C6). Nil allows capture. + // COW workers may call this concurrently, between chunk claims. CaptureAllowed func() error // ReadMissTimeout bounds one OnReadMiss remote fetch. ReadMissTimeout time.Duration - // Bitmap persists the dirty-since-HEAD bitmap. Required. + // HydrationWorkers bounds layer-owned fetches (0 defaults to 2). + HydrationWorkers int + // HydrationQueueDepth bounds distinct queued/in-flight chunks (0 defaults to 64). + HydrationQueueDepth int + // Bitmap persists the legacy dirty-since-HEAD bitmap. Required for v2; + // impl3 uses its owned LSN map and never calls this optional legacy object. Bitmap chunkBitmapStore // BarrierBound bounds how many chunks a cut copies under its barrier: @@ -353,6 +364,12 @@ type chunkLayerConfig struct { // UploadConcurrency bounds capture/pre-copy Put calls (0 defaults to 8). UploadConcurrency int + // COWSpillLimit caps the bytes a cut's copy window may spill to its side + // file once the in-memory budget is used: a save beyond it aborts the cut + // (the caller retries) instead of growing the file under the WAL/extent. + // 0 defaults to defaultCOWSpillLimit; negative is refused. + COWSpillLimit int64 + // testReconcileHold, set only by this package's tests, holds the // reconciler before each slice until a token is received or the // channel is closed. @@ -367,7 +384,14 @@ type chunkLayerConfig struct { // chunkCutStats describes one cut. The periodic-cut work fills it; a zero // value means "not measured". type chunkCutStats struct { + COWSavedChunks int + COWSaveNs int64 + COWWaitNs int64 + // BarrierPauseNs is the guest pause: from the capture barrier's Lock + // request until it is released. LockWaitNs is its first part, the wait for + // writers already holding the capture barrier shared. BarrierPauseNs int64 + LockWaitNs int64 SyncNs int64 CopyNs int64 CandidateChunks int @@ -411,6 +435,7 @@ type chunkCutStats struct { // - LastCut, LastCutH and LastCutNs (wall clock, Unix ns) describe the // last successful cut, whatever triggered it. type chunkLayerStats struct { + Hydration ChunkHydrationStats CutsOK uint64 CutsNoop uint64 CutsFailed uint64 @@ -448,6 +473,15 @@ type chunkCutResult struct { } // chunkLayer is what the store owner drives. +// detachSettlement is how a failed Detach ended (SettleDetach). +type detachSettlement int + +const ( + detachNotPublished detachSettlement = iota + detachApplied + detachFenced +) + type chunkLayer interface { chunkSink // Cut takes a quiesced cut at H (the last written LSN), uploads the @@ -466,6 +500,14 @@ type chunkLayer interface { // Detach returns the first result. An unresolved detach CAS is settled // like any other unresolved CAS, before the next capture or Detach. Detach(ctx context.Context) (chunkCutResult, error) + // SettleDetach decides how a failed Detach ended, with the caller's I/O + // still stopped: detachNotPublished (HEAD does not and can never carry + // this layer's detach: serving may resume; the dirty set stays dirty), + // detachApplied (HEAD carries it: the detached result is returned) or + // detachFenced (HEAD belongs to a newer epoch or another holder). An + // error wrapping errChunkCASOutcomeUnknown leaves it undecided: stay + // stopped. It never resumes on top of a possibly detached HEAD. + SettleDetach(ctx context.Context) (detachSettlement, chunkCutResult, error) // MakeRemoteDurable is the durability point for snapshot, detach and // migrate: a Capture whose H >= t. Only a nil return makes t remote // durable; it requires the local Sync to cover t first, and fails diff --git a/seaweed-block/core/storage/chunk_upload.go b/seaweed-block/core/storage/chunk_upload.go index b1e79b7b2f..ff71412b44 100644 --- a/seaweed-block/core/storage/chunk_upload.go +++ b/seaweed-block/core/storage/chunk_upload.go @@ -1,10 +1,52 @@ package storage import ( + "bytes" "context" + "errors" "sync" + "time" ) +// putCaptured retries one immutable object, never a whole batch or HEAD CAS. +// A lost binding reply can turn the next attempt into KeyExists: only exact +// bytes read from that binding prove completion; a collision is terminal. +// Bound attempts per object, without imposing a deadline on legitimate work +// across the whole cut. All attempts still obey the caller's context. +func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byte) error { + backoff := 100 * time.Millisecond + var lastErr error + for attempt := 1; ; attempt++ { + if err := ctx.Err(); err != nil { + return errors.Join(lastErr, err) + } + err := l.remote.Put(ctx, key, data) + if err == nil { + return nil + } + lastErr = err + // Resolve a possibly committed binding before replaying the Put. + got, readErr := l.remote.Get(ctx, key) + if readErr == nil { + if bytes.Equal(got, data) { + return nil + } + return errChunkKeyExists + } + if attempt == 3 { + return lastErr + } + timer := time.NewTimer(backoff) + select { + case <-ctx.Done(): + timer.Stop() + return errors.Join(lastErr, ctx.Err()) + case <-timer.C: + } + backoff = min(2*time.Second, 2*backoff) + } +} + // uploadBatch owns and joins all Put calls before its caller settles intents. // No storage/publication lock is acquired by workers. Cancellation stops new // admission; a remote ignoring cancellation remains joined, never declared done. diff --git a/seaweed-block/core/storage/chunk_upload_base_budget_test.go b/seaweed-block/core/storage/chunk_upload_base_budget_test.go new file mode 100644 index 0000000000..f52f4d8ea1 --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload_base_budget_test.go @@ -0,0 +1,88 @@ +package storage + +import ( + "context" + "errors" + "testing" + "time" +) + +func TestChunkUploadOutageSettlesBeforeQueuedBASE(t *testing.T) { + s, f, l := mappedBASELayerV3(t) + if _, err := s.Write(5, blk(0x31)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + entered, release := holdPuts(t, f) + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + cutDone := make(chan error, 1) + cutJoined := make(chan struct{}) + var baseJoined chan struct{} + t.Cleanup(func() { + cancel() + release() + select { + case <-cutJoined: + case <-time.After(5 * time.Second): + t.Error("cut not joined") + } + if baseJoined != nil { + select { + case <-baseJoined: + case <-time.After(5 * time.Second): + t.Error("BASE worker not joined") + } + } + }) + start := time.Now() + go func() { defer close(cutJoined); _, err := l.Cut(ctx); cutDone <- err }() + waitKey(t, entered, "cooperative cut upload") + attempted := make(chan struct{}) + l.testBaseTransitionBeforeLock = func() { close(attempted) } + baseJoined = make(chan struct{}) + type result struct { + h InstallHandle + err error + } + baseDone := make(chan result, 1) + go func() { defer close(baseJoined); h, err := s.BeginBaseInstall(7, idA); baseDone <- result{h, err} }() + select { + case <-attempted: + case <-time.After(5 * time.Second): + t.Fatal("BASE did not reach cut drain") + } + select { + case err := <-cutDone: + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("cut deadline: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("cooperative cut not settled") + } + var got result + select { + case got = <-baseDone: + case <-time.After(5 * time.Second): + t.Fatal("BASE did not proceed after cut settlement") + } + if got.err != nil { + t.Fatal(got.err) + } + if time.Since(start) >= 5*time.Second { + t.Fatal("single queued BASE exceeded sub-5s target") + } + if len(f.installedHeads()) != 0 { + t.Fatal("failed upload published HEAD") + } + select { + case <-baseJoined: + case <-time.After(5 * time.Second): + t.Fatal("BASE begin worker not joined") + } + l.testBaseTransitionBeforeLock = nil + if err := got.h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/storage/chunk_upload_budget_test.go b/seaweed-block/core/storage/chunk_upload_budget_test.go new file mode 100644 index 0000000000..836b7a9275 --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload_budget_test.go @@ -0,0 +1,150 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "sync" + "testing" + "time" +) + +type cutBudgetRemote struct { + *fakeChunkRemote + mu sync.Mutex + keys []string + deadlines []time.Time + held chan struct{} + once sync.Once + healthy bool +} + +func (r *cutBudgetRemote) Put(ctx context.Context, key string, data []byte) error { + r.mu.Lock() + if r.healthy { + r.mu.Unlock() + return r.fakeChunkRemote.Put(ctx, key, data) + } + r.keys = append(r.keys, key) + d, ok := ctx.Deadline() + if !ok { + d = time.Time{} + } + r.deadlines = append(r.deadlines, d) + n := len(r.keys) + r.mu.Unlock() + if n >= 3 { + r.once.Do(func() { close(r.held) }) + <-ctx.Done() + return ctx.Err() + } + return r.fakeChunkRemote.Put(ctx, key, data) +} + +func TestChunkCutCallerBudgetSharedAcrossStagesAndWritesProgress(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &cutBudgetRemote{fakeChunkRemote: f, held: make(chan struct{})} + cfg := ctConfig(1) + cfg.FreshFromHead = true + cfg.BarrierBound = 1 + cfg.UploadConcurrency = 2 + l := mustAttach(t, s, r, cfg).(*chunkLayerImpl) + for i := 0; i < 3; i++ { + if _, err := s.Write(uint32(i*ctChunkBlocks), makeBlock(ctBlockSize, byte(0x41+i))); err != nil { + t.Fatal(err) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + done := make(chan error, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + cancel() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("cut worker not joined") + } + }) + start := time.Now() + go func() { defer close(joined); _, err := l.Cut(ctx); done <- err }() + select { + case <-r.held: + case <-time.After(5 * time.Second): + t.Fatal("did not reach staged then final upload") + } + r.mu.Lock() + deadlines := append([]time.Time(nil), r.deadlines...) + r.mu.Unlock() + if len(deadlines) != 3 { + t.Fatalf("want two staged and one final upload: %v", deadlines) + } + wantDeadline, _ := ctx.Deadline() + if !deadlines[0].Equal(wantDeadline) { + t.Fatalf("cut replaced caller's deadline: %v, want %v", deadlines[0], wantDeadline) + } + for _, d := range deadlines { + if !d.Equal(deadlines[0]) { + t.Fatal("stage/worker received a reset budget") + } + } + writeDone := make(chan error, 1) + writeJoined := make(chan struct{}) + t.Cleanup(func() { + cancel() + select { + case <-writeJoined: + case <-time.After(5 * time.Second): + t.Error("ordinary write not joined") + } + }) + go func() { + defer close(writeJoined) + _, err := s.Write(3*ctChunkBlocks, makeBlock(ctBlockSize, 0x44)) + if err == nil { + _, err = s.Sync() + } + writeDone <- err + }() + select { + case err := <-writeDone: + if err != nil { + t.Fatal(err) + } + case err := <-done: + t.Fatalf("ordinary write waited for remote cut settlement: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("ordinary write blocked") + } + select { + case err := <-done: + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("lost caller deadline: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("cooperative cut did not settle") + } + if time.Since(start) >= 5*time.Second { + t.Fatal("cut exceeded sub-5s target") + } + if len(f.installedHeads()) != 0 { + t.Fatal("outage published HEAD") + } + r.mu.Lock() + r.healthy = true + r.mu.Unlock() + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + heads := f.installedHeads() + if len(heads) != 1 { + t.Fatal("retry did not publish exactly once") + } + want := make([]byte, ctNumBlocks*ctBlockSize) + for i := 0; i < 4; i++ { + copy(want[i*ctChunkBlocks*ctBlockSize:], makeBlock(ctBlockSize, byte(0x41+i))) + } + if !bytes.Equal(f.imageOf(t, heads[0]), want) { + t.Fatal("shared-budget abort lost pending/concurrent bytes") + } +} diff --git a/seaweed-block/core/storage/chunk_upload_parallel_test.go b/seaweed-block/core/storage/chunk_upload_parallel_test.go index f15df41ec5..7bb842c9f2 100644 --- a/seaweed-block/core/storage/chunk_upload_parallel_test.go +++ b/seaweed-block/core/storage/chunk_upload_parallel_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "sync" "sync/atomic" "testing" "time" @@ -11,6 +12,7 @@ import ( func TestChunkUploads_DefaultOverlapsBeforeCAS(t *testing.T) { _, f, l, w := precopyLayer(t, 0, 3) + baselineCAS := f.stats().cas f.mu.Lock() f.putGate = make(chan struct{}) gate := f.putGate @@ -33,7 +35,7 @@ func TestChunkUploads_DefaultOverlapsBeforeCAS(t *testing.T) { } } f.mu.Lock() - if len(f.intents) == 0 || f.casCalls != 0 { + if len(f.intents) == 0 || f.casCalls != baselineCAS { t.Error("overlapping uploads require a durable intent and no root CAS") } f.mu.Unlock() @@ -104,22 +106,32 @@ type unjoinedUploadRemote struct { second chan struct{} failed chan struct{} release chan struct{} + settled chan struct{} } func (r *unjoinedUploadRemote) Put(ctx context.Context, key string, data []byte) error { - if r.calls.Add(1) == 1 { - <-r.second + switch r.calls.Add(1) { + case 1: + select { + case <-r.second: + case <-ctx.Done(): + return ctx.Err() + } close(r.failed) return errFakeRemoteDown + case 2: + close(r.second) + defer close(r.settled) + default: + return errFakeRemoteDown } - close(r.second) <-r.release return r.fakeChunkRemote.Put(context.Background(), key, data) } func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() - r := &unjoinedUploadRemote{fakeChunkRemote: f, second: make(chan struct{}), failed: make(chan struct{}), release: make(chan struct{})} + r := &unjoinedUploadRemote{fakeChunkRemote: f, second: make(chan struct{}), failed: make(chan struct{}), release: make(chan struct{}), settled: make(chan struct{})} cfg := ctConfig(1) cfg.FreshFromHead = true cfg.UploadConcurrency = 2 @@ -127,29 +139,52 @@ func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) { w := newWriteLog() w.write(t, s, 0, 0x21) w.write(t, s, ctChunkBlocks, 0x22) + ctx, cancel := context.WithCancel(context.Background()) done := make(chan error, 1) - go func() { _, err := l.Cut(context.Background()); done <- err }() + joined := make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(r.release) }) } + t.Cleanup(func() { + cancel() + release() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("cut worker not joined") + } + select { + case <-r.second: + select { + case <-r.settled: + case <-time.After(5 * time.Second): + t.Error("owned upload not joined") + } + default: + } + }) + go func() { defer close(joined); _, err := l.Cut(ctx); done <- err }() select { case <-r.failed: + cancel() // retries are now allowed; terminate this cut explicitly case <-time.After(time.Second): - close(r.release) - <-done t.Fatal("uploads did not overlap") } select { case err := <-done: - close(r.release) t.Fatalf("returned with owned upload still active: %v", err) case <-time.After(20 * time.Millisecond): } if len(liveIntents(t, f)) == 0 { - close(r.release) - <-done t.Fatal("intent removed before join") } - close(r.release) - if err := <-done; !errors.Is(err, errFakeRemoteDown) { - t.Fatalf("lost upload failure: %v", err) + release() + select { + case err := <-done: + if !errors.Is(err, errFakeRemoteDown) { + t.Fatalf("lost upload failure: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("cut completion not joined") } if f.stats().cas != 0 { t.Fatal("failed batch published") diff --git a/seaweed-block/core/storage/chunk_upload_retry_test.go b/seaweed-block/core/storage/chunk_upload_retry_test.go new file mode 100644 index 0000000000..d8d2419af6 --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload_retry_test.go @@ -0,0 +1,227 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "path/filepath" + "sync" + "testing" + "time" +) + +// Faults sit at the remote seam; all captures, intents, hashes and HEADs use +// the real layer and the write-once fake remote. +type retryUploadRemote struct { + *fakeChunkRemote + mu sync.Mutex + mode string + calls map[string]int + values map[string]byte +} + +func (r *retryUploadRemote) Put(ctx context.Context, key string, data []byte) error { + r.mu.Lock() + r.calls[key]++ + if r.values == nil { + r.values = map[string]byte{} + } + if len(data) > 0 { + r.values[key] = data[0] + } + n, mode := r.calls[key], r.mode + r.mu.Unlock() + if mode == "down" || mode == "transient" && n == 1 || mode == "mixed" && n == 1 && len(data) > 0 && data[0] == 0x42 { + return errFakeRemoteDown + } + if mode == "lost" && n == 1 { + if err := r.fakeChunkRemote.Put(ctx, key, data); err != nil { + return err + } + return errFakeRemoteDown // binding committed, response lost + } + if mode == "collision" { + bad := bytes.Repeat([]byte{0xff}, len(data)) + if err := r.fakeChunkRemote.Put(ctx, key, bad); err != nil { + return err + } + return errChunkKeyExists + } + return r.fakeChunkRemote.Put(ctx, key, data) +} + +func TestChunkCutMixedSuccessDoesNotReplaySuccessfulKey(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &retryUploadRemote{fakeChunkRemote: f, mode: "mixed", calls: map[string]int{}} + l := mustAttach(t, s, r, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 0, 0x41) + w.write(t, s, ctChunkBlocks, 0x42) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if len(f.installedHeads()) != 1 { + t.Fatal("must publish once") + } + r.mu.Lock() + defer r.mu.Unlock() + if len(r.calls) != 2 { + t.Fatalf("changed immutable keys: %v", r.calls) + } + seen := map[byte]bool{} + for key, n := range r.calls { + value := r.values[key] + want := 1 + if value == 0x42 { + want = 2 + } + if value != 0x41 && value != 0x42 { + t.Fatalf("unexpected payload %x", value) + } + if n != want { + t.Fatalf("payload %x attempted %d times, want %d", value, n, want) + } + seen[value] = true + } + if len(seen) != 2 { + t.Fatal("did not exercise success and retry") + } + assertEveryHeadIsPrefixImage(t, f, w) +} + +func TestChunkCutRetriesOnlyTheFailedUpload(t *testing.T) { + for _, mode := range []string{"transient", "lost"} { + t.Run(mode, func(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &retryUploadRemote{fakeChunkRemote: f, mode: mode, calls: map[string]int{}} + layer := mustAttach(t, s, r, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 0, 0x41) + w.write(t, s, ctChunkBlocks, 0x42) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if len(f.installedHeads()) != 1 { + t.Fatal("cut did not publish exactly one HEAD") + } + assertEveryHeadIsPrefixImage(t, f, w) + r.mu.Lock() + defer r.mu.Unlock() + if len(r.calls) != 2 { + t.Fatalf("new key generated on retry: %v", r.calls) + } + for key, n := range r.calls { + want := 2 + if mode == "lost" { + want = 1 + } + if n != want { + t.Fatalf("key %s attempted %d times, want %d", key, n, want) + } + } + }) + } +} + +func TestChunkCutUploadCollisionNeverPublishes(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &retryUploadRemote{fakeChunkRemote: f, mode: "collision", calls: map[string]int{}} + layer := mustAttach(t, s, r, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 0, 0x41) + if _, err := layer.Cut(ctTimeout(t)); err == nil { + t.Fatal("published mismatching existing key") + } + if len(f.installedHeads()) != 0 { + t.Fatal("HEAD moved after collision") + } +} + +func TestChunkCutUploadRetryHonorsDeadlineAndRetainsDirt(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &retryUploadRemote{fakeChunkRemote: f, mode: "down", calls: map[string]int{}} + layer := mustAttach(t, s, r, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 0, 0x41) + ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond) + defer cancel() + if _, err := layer.Cut(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("deadline lost: %v", err) + } + if len(f.installedHeads()) != 0 { + t.Fatal("HEAD moved during outage") + } + r.mu.Lock() + r.mode = "ok" + r.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + assertEveryHeadIsPrefixImage(t, f, w) +} + +func TestChunkCutUploadAttemptBoundRetainsDirt(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &retryUploadRemote{fakeChunkRemote: f, mode: "down", calls: map[string]int{}} + layer := mustAttach(t, s, r, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 0, 0x51) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := layer.Cut(ctx); err == nil { + t.Fatal("persistent upload outage published") + } + r.mu.Lock() + if len(r.calls) != 1 { + t.Fatalf("retry changed object keys: %v", r.calls) + } + for _, n := range r.calls { + if n != 3 { + t.Errorf("single object attempted %d times, want bounded 3", n) + } + } + r.mode = "ok" + r.mu.Unlock() + if len(f.installedHeads()) != 0 { + t.Fatal("failed object published HEAD") + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + assertEveryHeadIsPrefixImage(t, f, w) +} + +func TestChunkCutRetrySustainedWritesPastWALWithFlush(t *testing.T) { + const walBytes = 64 * 1024 + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), ctNumBlocks, ctBlockSize, walBytes, WModeStrict, ctChunkBlocks) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { closeBounded(t, s) }) + f := newFakeChunkRemote() + r := &retryUploadRemote{fakeChunkRemote: f, mode: "transient", calls: map[string]int{}} + layer := mustAttach(t, s, r, ctConfig(1)) + w := newWriteLog() + for i := 0; i < 96; i++ { + w.write(t, s, uint32(i%ctNumBlocks), byte(i+1)) + if (i+1)%4 == 0 { + mustSyncFlush(t, s) + } + if (i+1)%16 == 0 { + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + } + } + assertEveryHeadIsPrefixImage(t, f, w) + if len(f.installedHeads()) != 6 { + t.Fatalf("published %d HEADs", len(f.installedHeads())) + } + t.Logf("payload=%d > WAL=%d; 24 periodic flushes; 6 cuts with transient upload faults", 96*ctBlockSize, walBytes) +} diff --git a/seaweed-block/core/storage/chunk_upload_slow_cut_test.go b/seaweed-block/core/storage/chunk_upload_slow_cut_test.go new file mode 100644 index 0000000000..7f2fd7e4be --- /dev/null +++ b/seaweed-block/core/storage/chunk_upload_slow_cut_test.go @@ -0,0 +1,68 @@ +package storage + +import ( + "bytes" + "context" + "testing" + "time" +) + +type slowSuccessfulUploadRemote struct{ *fakeChunkRemote } + +func (r *slowSuccessfulUploadRemote) Put(ctx context.Context, key string, data []byte) error { + timer := time.NewTimer(600 * time.Millisecond) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return r.fakeChunkRemote.Put(ctx, key, data) + } +} + +func TestChunkCutLegitimateUploadsExceedTwoSeconds(t *testing.T) { + for _, detach := range []bool{false, true} { + name := "cut" + if detach { + name = "detach" + } + t.Run(name, func(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &slowSuccessfulUploadRemote{f} + cfg := ctConfig(1) + cfg.UploadConcurrency = 1 + l := mustAttach(t, s, r, cfg).(*chunkLayerImpl) + want := make([]byte, ctNumBlocks*ctBlockSize) + for i := 0; i < 5; i++ { + data := makeBlock(ctBlockSize, byte(0x41+i)) + if _, err := s.Write(uint32(i*ctChunkBlocks), data); err != nil { + t.Fatal(err) + } + copy(want[i*ctChunkBlocks*ctBlockSize:], data) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + start := time.Now() + var err error + if detach { + _, err = l.Detach(ctx) + } else { + _, err = l.Cut(ctx) + } + if err != nil { + t.Fatalf("legitimate multi-object work canceled: %v", err) + } + if time.Since(start) <= 2*time.Second { + t.Fatal("fixture did not exceed the former whole-cut limit") + } + heads := f.installedHeads() + if len(heads) != 1 || !bytes.Equal(f.imageOf(t, heads[0]), want) { + t.Fatal("slow successful cut did not publish the exact image once") + } + if detach && heads[0].State != ChunkHeadDetached { + t.Fatal("slow detach did not install detached proof") + } + }) + } +} diff --git a/seaweed-block/core/storage/chunkmap_bounded_v3_test.go b/seaweed-block/core/storage/chunkmap_bounded_v3_test.go new file mode 100644 index 0000000000..99c3107f63 --- /dev/null +++ b/seaweed-block/core/storage/chunkmap_bounded_v3_test.go @@ -0,0 +1,41 @@ +package storage + +import ( + "os" + "testing" +) + +// The v3 owned-map file must stay bounded under steady writes. Each cycle +// writes, syncs and checkpoints, so every cycle publishes a new map +// generation with a changed page. After 300 checkpoints the file must not +// exceed a small multiple of one full map (pages + root, each 4 KiB +// aligned): the live map of the two descriptor slots plus one in-flight +// candidate, with slack. +func TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + shape, err := mapShapeForV3(s.v3.pub.current(), s.v3.ownedMap.chunkBlocks) + if err != nil { + t.Fatal(err) + } + rootBytes := (120 + 40*shape.pages + 4095) &^ 4095 + fullMap := int64(shape.pages*4096 + rootBytes) + bound := 8 * fullMap + const cycles = 300 + for i := 0; i < cycles; i++ { + writeSynced(t, s, uint32(i%64), uint32(i%64)) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + } + gen := s.v3.pub.current().MapGeneration + if gen < cycles { + t.Fatalf("setup: %d map generations after %d checkpoint cycles", gen, cycles) + } + fi, err := os.Stat(path + ".chunkmap") + if err != nil { + t.Fatal(err) + } + if fi.Size() > bound { + t.Fatalf("chunkmap is %d B after %d generations; bound %d B (8 x one full map of %d B)", fi.Size(), gen, bound, fullMap) + } +} diff --git a/seaweed-block/core/storage/contract_test.go b/seaweed-block/core/storage/contract_test.go index e383930677..8c1fccbc09 100644 --- a/seaweed-block/core/storage/contract_test.go +++ b/seaweed-block/core/storage/contract_test.go @@ -223,6 +223,17 @@ func TestContract_BoundariesReflectWrites(t *testing.T) { func TestContract_ApplyEntryUsesSuppliedLSN(t *testing.T) { runForEachImpl(t, func(t *testing.T, store LogicalStorage) { + if ws, ok := store.(*storage.WALStore); ok && ws.FormatV3() { + // v3 forbids an unanchored jump: establish the source's BASE + // before applying its next supplied LSN, as the receiver does. + h, err := ws.BeginBaseInstall(99, [16]byte{1}) + if err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + } want := makeBlock(store.BlockSize(), 0xCD) // ApplyEntry is the replication path — the LSN comes from the // source, not from the local allocator. @@ -255,6 +266,18 @@ func TestContract_ApplyEntryUsesSuppliedLSN(t *testing.T) { func TestContract_AdvanceFrontierBumpsH(t *testing.T) { runForEachImpl(t, func(t *testing.T, store LogicalStorage) { store.AdvanceFrontier(50) + if ws, ok := store.(*storage.WALStore); ok && ws.FormatV3() { + if _, _, head := store.Boundaries(); head != 0 { + t.Fatal("v3 allowed an unowned legacy frontier jump") + } + h, err := ws.BeginBaseInstall(50, [16]byte{1}) + if err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + } _, _, H := store.Boundaries() if H != 50 { t.Fatalf("AdvanceFrontier(50) should set H=50, got %d", H) @@ -293,7 +316,10 @@ func TestContract_AllBlocksReturnsCurrentSnapshot(t *testing.T) { _, _ = store.Write(0, makeBlock(store.BlockSize(), 0x01)) _, _ = store.Write(2, makeBlock(store.BlockSize(), 0x02)) _, _ = store.Write(5, makeBlock(store.BlockSize(), 0x05)) - all := store.AllBlocks() + all, snapshotErr := store.AllBlocks() + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(all) != 3 { t.Fatalf("AllBlocks: got %d entries, want 3", len(all)) } @@ -344,7 +370,23 @@ func TestContract_WriteExtentDirect(t *testing.T) { } // WriteExtentDirect must succeed and become readable. - if err := store.WriteExtentDirect(3, baseBytes); err != nil { + walLSN := uint64(5) + if ws, ok := store.(*storage.WALStore); ok && ws.FormatV3() { + if err := store.WriteExtentDirect(3, baseBytes); err == nil { + t.Fatal("v3 allowed a direct extent write outside its install handle") + } + h, err := ws.BeginBaseInstall(0, [16]byte{1}) + if err != nil { + t.Fatal(err) + } + if err := h.WriteBase(3, baseBytes); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + walLSN = 1 // the first contiguous WAL LSN after BASE0 + } else if err := store.WriteExtentDirect(3, baseBytes); err != nil { t.Fatalf("WriteExtentDirect: %v", err) } got, err := store.Read(3) @@ -370,7 +412,7 @@ func TestContract_WriteExtentDirect(t *testing.T) { // bytes — this matches the recovery flow where WAL frames // at higher LSNs naturally overwrite the BASE snapshot. walBytes := makeBlock(bs, 0xBB) - if err := store.ApplyEntry(3, walBytes, 5); err != nil { + if err := store.ApplyEntry(3, walBytes, walLSN); err != nil { t.Fatalf("ApplyEntry after WriteExtentDirect: %v", err) } got2, err := store.Read(3) @@ -385,8 +427,8 @@ func TestContract_WriteExtentDirect(t *testing.T) { // effect), so H bumped — this is the receiver's existing // side-effect contract for ApplyEntry, unrelated to BASE. _, _, h2 := store.Boundaries() - if h2 < 5 { - t.Errorf("after ApplyEntry(lsn=5) H=%d want >= 5", h2) + if h2 != walLSN { + t.Errorf("after ApplyEntry(lsn=%d) H=%d want %d", walLSN, h2, walLSN) } }) } diff --git a/seaweed-block/core/storage/descriptor_v3.go b/seaweed-block/core/storage/descriptor_v3.go new file mode 100644 index 0000000000..62310d03a4 --- /dev/null +++ b/seaweed-block/core/storage/descriptor_v3.go @@ -0,0 +1,438 @@ +package storage + +import ( + "errors" + "fmt" + "sync" + "sync/atomic" +) + +// The single v3 descriptor publisher (format bump v3, DESIGN r15 sections +// 4, 5 and 5.1; plan row 3). +// +// Every v3 descriptor change goes through descriptorPublisherV3.publish: +// Sync W, checkpoint, metadata-only rollover, seed, BASE transitions and +// reset. It is dark until the v3 store is wired in (plan rows 4 and 5) and +// activated (row 12b); the v2 checkpoint path in walstore.go is unchanged. +// +// Lock graph (DESIGN 4), the only order: +// +// metadata callbacks (run by the caller first, holding none of these) +// -> WALStore.mu (snapshot only, released before slot I/O) +// -> descMu +// -> fileSyncMu (leaf, inside syncFile) +// +// Nothing below descMu is ever held while acquiring WALStore.mu, and no +// callback runs under descMu or fileSyncMu. + +var ( + // errDescriptorIdentityChange: a publication tried to change the + // store identity or geometry, which no v3 publication may do. + errDescriptorIdentityChange = errors.New("storage: v3 descriptor identity or geometry change refused") + // errDescriptorTransition: a publication asked for a BASE, map, nonce + // or bounds change that DESIGN 5/8.5 does not allow. + errDescriptorTransition = errors.New("storage: v3 descriptor transition refused") +) + +// descriptorIOV3 is the store I/O the publisher needs. writeSlot does one +// pwrite of a whole slot; syncFile runs the store's leaf (pwrite + fsync +// under fileSyncMu); sticky reports a latched store fault; latch records a +// fault in the store so every other store path (appends, Sync, reuse) is +// refused too. The publisher latches on a slot write error as well as on an +// fsync error (DESIGN 5): the v2 leaf does not latch pwrite errors, so the +// v3 publisher does it itself. +type descriptorIOV3 struct { + writeSlot func(off int64, b []byte) error + fsync func() error + syncFile func(write, sync func() error) error + sticky func() error + latch func(err error) +} + +// ErrDescriptorPublishUncertain: a descriptor slot write or fsync failed, so +// the slot on disk may hold the new generation, the old one, or a torn mix. +// The open store refuses every further publication and all reuse; only a +// reopen, which reads back and selects the actual slots, resolves it +// (DESIGN 5, failure rule). +var ErrDescriptorPublishUncertain = errors.New("storage: v3 descriptor publication outcome uncertain; reopen required") + +// descriptorPublisherV3 holds the authoritative in-memory descriptor and +// the contents of the fallback slot, which pins reuse (DESIGN 5). +type descriptorPublisherV3 struct { + descMu sync.Mutex + // retireGate defers the installed -> none retirement (retireNoGateV3, + // retireDeferredV3, retireAllowedV3); read without a lock. + retireGate atomic.Uint32 + + cur descriptorV3 // selected slot: authoritative + curSlot slotIDV3 + other descriptorV3 // fallback slot, when valid + otherValid bool + + io descriptorIOV3 + accept slotImplAcceptor + + // failed is set by the first slot write or fsync failure. uncertain is + // the candidate that may be on disk: it stays pinned (its tail bounds + // reuse, and its map dependencies stay referenced) until reopen. + failed error + uncertain *descriptorV3 + + // Immutable map dependencies and volatile proof domain, bound before serving. + mapCurrent *chunkMapCandidateV3 + mapDomain *mapProofEpochV3 + + // trace, when set by a test, records lock acquisitions and releases + // in order (the section 11 item 9 lock recorder). + trace func(event string) +} + +func newDescriptorPublisherV3(cur descriptorV3, curSlot slotIDV3, other *descriptorV3, io descriptorIOV3) *descriptorPublisherV3 { + p := &descriptorPublisherV3{cur: cur, curSlot: curSlot, io: io} + if other != nil { + p.other, p.otherValid = *other, true + } + return p +} + +func (p *descriptorPublisherV3) note(event string) { + if p.trace != nil { + p.trace(event) + } +} + +// current returns the authoritative descriptor. +func (p *descriptorPublisherV3) current() descriptorV3 { + p.descMu.Lock() + defer p.descMu.Unlock() + return p.cur +} + +// reuseFloor is the lowest logical WAL position still referenced by a valid +// slot (DESIGN 5): min of both tails when both carry the same nonce. With +// mixed nonces (a reset between its two publications, DESIGN 8.6) tails are +// not comparable and ok is false: nothing may be reused. +func (p *descriptorPublisherV3) reuseFloor() (floor uint64, ok bool) { + p.descMu.Lock() + defer p.descMu.Unlock() + return p.reuseFloorLocked() +} + +func (p *descriptorPublisherV3) reuseFloorLocked() (uint64, bool) { + if p.failed != nil { + return 0, false // an uncertain slot may reference anything: no reuse until reopen + } + if !p.otherValid { + return p.cur.RetainedTail, true + } + if p.other.Nonce != p.cur.Nonce { + return 0, false + } + return min(p.cur.RetainedTail, p.other.RetainedTail), true +} + +// publish is publishDescriptor (DESIGN 5). Callers run their metadata +// callbacks before calling it. If storeMu is non-nil it is taken first, +// snap runs under it, then descMu is taken and storeMu released before any +// slot I/O. mutate edits a copy of the CURRENT authoritative descriptor, +// never a caller's snapshot; the publisher then applies the monotonic merge +// and the transition rules, validates the whole result and writes it into +// the fallback slot with slotGen+1. +func (p *descriptorPublisherV3) publish(storeMu sync.Locker, snap func(), mutate func(next *descriptorV3) error) (descriptorV3, error) { + return p.publishWithMapV3(storeMu, snap, mutate, nil) +} + +func (p *descriptorPublisherV3) publishWithMapV3(storeMu sync.Locker, snap func(), mutate func(next *descriptorV3) error, prepared *preparedMapPublicationV3) (descriptorV3, error) { + if storeMu != nil { + storeMu.Lock() + p.note("lock WALStore.mu") + if snap != nil { + snap() + } + p.descMu.Lock() + p.note("lock descMu") + storeMu.Unlock() + p.note("unlock WALStore.mu") + } else { + p.descMu.Lock() + p.note("lock descMu") + } + defer func() { + p.note("unlock descMu") + p.descMu.Unlock() + }() + return p.publishLockedWithMapV3(mutate, prepared) +} + +// uncertainCandidate returns the candidate whose publication failed, if +// any. Its dependencies (WAL bytes from its tail, its map root and pages) +// stay pinned until reopen. +func (p *descriptorPublisherV3) uncertainCandidate() (descriptorV3, bool) { + p.descMu.Lock() + defer p.descMu.Unlock() + if p.uncertain == nil { + return descriptorV3{}, false + } + return *p.uncertain, true +} + +func (p *descriptorPublisherV3) publishLocked(mutate func(next *descriptorV3) error) (descriptorV3, error) { + return p.publishLockedWithMapV3(mutate, nil) +} + +func (p *descriptorPublisherV3) publishLockedWithMapV3(mutate func(next *descriptorV3) error, prepared *preparedMapPublicationV3) (descriptorV3, error) { + return p.publishLockedCoreV3(mutate, prepared, false) +} + +// publishLockedCoreV3 is the publication body; reset permits the nonce and +// cursor change of the reset transaction (DESIGN 8.6) and nothing else. +func (p *descriptorPublisherV3) publishLockedCoreV3(mutate func(next *descriptorV3) error, prepared *preparedMapPublicationV3, reset bool) (descriptorV3, error) { + if p.failed != nil { + return descriptorV3{}, p.failed + } + if err := p.io.sticky(); err != nil { + return descriptorV3{}, err + } + next := p.cur + if mutate != nil { + if err := mutate(&next); err != nil { + return descriptorV3{}, err + } + } + if p.retireGate.Load() != retireDeferredV3 { + retireBaseV3(&p.cur, &next) + } + if err := mergeDescriptorV3Mode(&p.cur, &next, reset); err != nil { + return descriptorV3{}, err + } + if err := p.validateMapPublicationV3(next, prepared); err != nil { + return descriptorV3{}, err + } + if err := checkCountersV3(&next); err != nil { + return descriptorV3{}, err + } + gen, err := nextSlotGenV3(p.cur.SlotGen) + if err != nil { + return descriptorV3{}, err + } + next.SlotGen = gen + next.MigrationPhase = MigrationNormal + if err := next.validate(p.accept); err != nil { + return descriptorV3{}, err + } + target := slotB + off := int64(slotBOffsetV3) + if p.curSlot == slotB { + target, off = slotA, slotAOffsetV3 + } + buf := next.encode() + wrote := false + err = p.io.syncFile(func() error { + p.note("hold fileSyncMu") + wrote = true + werr := p.io.writeSlot(off, buf) + if werr != nil && p.io.latch != nil { + // Latch inside the leaf, before fileSyncMu is released: a store + // Sync queued on fileSyncMu must not fsync and acknowledge + // through this uncertain slot (codex01 row 3 round 2). + p.io.latch(fmt.Errorf("%w: %w", ErrDescriptorPublishUncertain, werr)) + } + return werr + }, p.io.fsync) + if err != nil { + if wrote { + // The slot write or its fsync failed: the fallback slot may hold + // the new generation, the old one or a torn mix. Latch, keep the + // candidate pinned, and refuse everything until reopen. + uncertain := next + p.uncertain = &uncertain + p.failed = fmt.Errorf("%w: %w", ErrDescriptorPublishUncertain, err) + // The store fault was latched inside the leaf (write error) or by + // the leaf itself (fsync error); latching again is a no-op. + if p.io.latch != nil { + p.io.latch(p.failed) + } + return descriptorV3{}, p.failed + } + return descriptorV3{}, err // refused before any I/O (a latched fault) + } + // Success boundary: a fault latched by another path while this + // publication was in flight still refuses it (#172). The slot write and + // its fsync did happen, so the slot on disk may name this generation: + // its dependencies stay pinned as an uncertain candidate until reopen. + if err := p.io.sticky(); err != nil { + uncertain := next + p.uncertain = &uncertain + return descriptorV3{}, err + } + p.other, p.otherValid = p.cur, true + p.cur, p.curSlot = next, target + if prepared != nil { + p.mapCurrent = prepared.candidate + } + // Report the slot tuples to the owned map (descMu -> liveMu): roots + // neither slot names any more, and superseded candidates, are released. + // A publication before the map is bound reports nothing; that only + // delays a release until the next report. + if p.mapCurrent != nil && p.mapCurrent.owner != nil { + p.mapCurrent.owner.slotsPublishedV3(p.cur, p.other, p.otherValid) + } + return next, nil +} + +// checkCountersV3 refuses a publication whose counters would exceed 2^64-2 +// (DESIGN 2.4) with ErrCounterExhausted, before any write. Slot decoding of +// such a value stays errSuperblockInvalid. +func checkCountersV3(d *descriptorV3) error { + for _, c := range []struct { + name string + v uint64 + }{ + {"W", d.W}, {"CheckpointLSN", d.CheckpointLSN}, {"retainedTail", d.RetainedTail}, + {"retainedHead", d.RetainedHead}, {"mapGeneration", d.MapGeneration}, + {"mapCoveredCheckpoint", d.MapCoveredCheckpoint}, {"BaseLSN", d.BaseLSN}, + {"BaseCursor", d.BaseCursor}, + } { + if c.v > counterMaxV3 { + return fmt.Errorf("%w: %s %d", ErrCounterExhausted, c.name, c.v) + } + } + return nil +} + +// mergeDescriptorV3 applies the monotonic merge and transition rules of +// DESIGN 5 and 8.5 to next, a mutated copy of cur. +func mergeDescriptorV3(cur, next *descriptorV3) error { return mergeDescriptorV3Mode(cur, next, false) } + +func mergeDescriptorV3Mode(cur, next *descriptorV3, reset bool) error { + if next.ImplKind != cur.ImplKind || next.ImplVersion != cur.ImplVersion || next.UUID != cur.UUID || + next.CreatedAt != cur.CreatedAt || !sameGeometryV3(*cur, *next) { + return errDescriptorIdentityChange + } + // W and CheckpointLSN are max-merged: a stale request never lowers them. + next.W = max(cur.W, next.W) + next.CheckpointLSN = max(cur.CheckpointLSN, next.CheckpointLSN) + // The nonce changes only through the reset transaction (DESIGN 8.6, + // plan row 8); within one nonce the retained bounds never move back. + if reset { + // The reset publication (DESIGN 8.6): a new nonce and a fresh, + // empty cursor space; everything else follows the ordinary rules. + if next.Nonce == cur.Nonce || next.Nonce == ([16]byte{}) || next.RetainedTail != next.RetainedHead { + return fmt.Errorf("%w: a reset needs a new nonzero nonce and an empty cursor space", errDescriptorTransition) + } + } else if next.Nonce != cur.Nonce { + return fmt.Errorf("%w: nonce change outside a reset", errDescriptorTransition) + } else if next.RetainedTail < cur.RetainedTail { + return fmt.Errorf("%w: retainedTail %d below %d", errDescriptorTransition, next.RetainedTail, cur.RetainedTail) + } + // The map root changes only to a strictly higher generation; the full + // coverage predicates against the root are added by plan row 7. + if next.MapGeneration != cur.MapGeneration || next.MapRootLocator != cur.MapRootLocator || + next.MapRootHash != cur.MapRootHash || next.MapCoveredCheckpoint != cur.MapCoveredCheckpoint || + next.MapLineage != cur.MapLineage || next.MapFormatID != cur.MapFormatID { + if next.MapGeneration <= cur.MapGeneration { + return fmt.Errorf("%w: %w: map root change without a higher generation (%d -> %d)", + mapCoverageRefusal("map_generation_not_increasing"), errDescriptorTransition, cur.MapGeneration, next.MapGeneration) + } + if next.MapLineage != cur.MapLineage { + return fmt.Errorf("%w: map lineage change outside an install or reset", errDescriptorTransition) + } + } + if next.WMode != cur.WMode && next.WMode != WModeLagged && next.WMode != WModeStrict { + return fmt.Errorf("%w: WMode %d", errDescriptorTransition, next.WMode) + } + return baseTransitionAllowedV3(cur, next) +} + +// The retirement gate (row 12a retired-BASE ruling): a chunk-managed store +// defers retirement until its chunk layer has durably recorded local +// presence for the installed image, so the installed descriptor, the +// provider's evidence that the local image is complete, is not erased +// first. Stores that never set it retire as before. +const ( + retireNoGateV3 uint32 = iota // retire when the 8.4 conditions hold + retireDeferredV3 // keep installed even when they hold + retireAllowedV3 // the deferral was lifted for this open +) + +// retireBaseV3 is the installed -> none retirement (DESIGN 8.4, 8.5): a +// later normal publication of an installed descriptor zeroes the three BASE +// fields once the checkpoint covers BaseLSN and both slots (the current one, +// which becomes the fallback, and the new one) carry retainedTail >= +// BaseCursor. Before that, recovery still needs the BASE scan start. +func retireBaseV3(cur, next *descriptorV3) { + if cur.BaseState != BaseInstalled || next.BaseState != BaseInstalled || + next.BaseInstallID != cur.BaseInstallID || next.CheckpointLSN < next.BaseLSN || + cur.RetainedTail < cur.BaseCursor || next.RetainedTail < cur.BaseCursor { + return + } + next.BaseState, next.BaseLSN, next.BaseCursor, next.BaseInstallID = BaseNone, 0, 0, [16]byte{} +} + +// baseTransitionAllowedV3 is the DESIGN 8.5 edge table. The conditions an +// edge needs (coverage, destructive mutation, drain) are enforced by the +// install callers (plan rows 9 to 11); this refuses every other edge. +func baseTransitionAllowedV3(cur, next *descriptorV3) error { + same := next.BaseState == cur.BaseState && next.BaseLSN == cur.BaseLSN && + next.BaseCursor == cur.BaseCursor && next.BaseInstallID == cur.BaseInstallID + if same { + return nil + } + ok := false + switch cur.BaseState { + case BaseNone: + ok = next.BaseState == BaseInstalling + case BaseInstalling: + switch next.BaseState { + case BaseInstalling: + ok = next.BaseInstallID != cur.BaseInstallID // superseding begin + case BaseInstalled: + ok = next.BaseInstallID == cur.BaseInstallID && next.BaseLSN == cur.BaseLSN + case BaseNone: + ok = false // never: there is no abort (DESIGN r17, 8.5) + } + case BaseInstalled: + switch next.BaseState { + case BaseInstalled: + // Retirement may clear BaseCursor below the tail; the ID and + // BaseLSN stay. + ok = next.BaseInstallID == cur.BaseInstallID && next.BaseLSN == cur.BaseLSN + case BaseNone: + // Retirement (8.4, 8.5): the checkpoint covers the BASE and the + // published tail is at or past BaseCursor; the publisher also + // requires it of the other slot (retireBaseLockedV3). + ok = next.BaseLSN == 0 && next.CheckpointLSN >= cur.BaseLSN && + cur.RetainedTail >= cur.BaseCursor && next.RetainedTail >= cur.BaseCursor + // installed -> installing is not an 8.5 edge: a new install + // begins only after installed -> none (retire, then begin). + } + } + if !ok { + return fmt.Errorf("%w: BASE %d -> %d", errDescriptorTransition, cur.BaseState, next.BaseState) + } + return nil +} + +// rolloverIfPinned is the metadata-only rollover (DESIGN 5.1): when the +// fallback slot still pins reuse below the selected tail, republish the +// current descriptor unchanged into the fallback slot so both carry the new +// tail. It needs no record, Sync, guest write or checkpoint change. It +// reports whether it published. +func (p *descriptorPublisherV3) rolloverIfPinned() (bool, error) { + p.note("lock descMu") + p.descMu.Lock() + defer func() { + p.note("unlock descMu") + p.descMu.Unlock() + }() + if p.failed != nil { + return false, p.failed + } + if !p.otherValid || p.other.Nonce != p.cur.Nonce || p.other.RetainedTail >= p.cur.RetainedTail { + return false, nil + } + if _, err := p.publishLocked(nil); err != nil { + return false, err + } + return true, nil +} diff --git a/seaweed-block/core/storage/descriptor_v3_test.go b/seaweed-block/core/storage/descriptor_v3_test.go new file mode 100644 index 0000000000..2f490ab2b3 --- /dev/null +++ b/seaweed-block/core/storage/descriptor_v3_test.go @@ -0,0 +1,565 @@ +package storage + +import ( + "errors" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" +) + +// Row 3 (DESIGN r15 sections 4, 5, 5.1) controls for the v3 descriptor +// publisher, against a real file through a syncFile leaf that behaves like +// WALStore.syncFile (fileSyncMu, sticky latch on fsync failure). + +type descHarnessV3 struct { + t *testing.T + f *os.File + fileSyncMu sync.Mutex + fault atomic.Pointer[error] + fsyncErr atomic.Pointer[error] + afterFsync func() // test hook inside the leaf, after a successful fsync + // writeHook, when set, replaces the slot pwrite (to inject a full or + // partial write followed by an error). + writeHook func(off int64, b []byte) error + writes atomic.Int64 + // afterUnlock, when set, runs in the leaf right after fileSyncMu is + // released (to let a queued store sync run before the caller resumes). + afterUnlock func() + storeMu sync.Mutex + pub *descriptorPublisherV3 +} + +func newDescHarnessV3(t *testing.T) *descHarnessV3 { + t.Helper() + f, err := os.Create(filepath.Join(t.TempDir(), "store.v3")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = f.Close() }) + ref := readSlotVector(t, "slot-ref") + if _, err := f.WriteAt(ref, slotAOffsetV3); err != nil { + t.Fatal(err) + } + if _, err := f.WriteAt(make([]byte, slotSizeV3), slotBOffsetV3); err != nil { + t.Fatal(err) + } + d, err := decodeSlotV3(ref, nil) + if err != nil { + t.Fatal(err) + } + h := &descHarnessV3{t: t, f: f} + h.pub = newDescriptorPublisherV3(d, slotA, nil, descriptorIOV3{ + writeSlot: func(off int64, b []byte) error { + h.writes.Add(1) + if h.writeHook != nil { + return h.writeHook(off, b) + } + _, err := f.WriteAt(b, off) + return err + }, + latch: func(err error) { h.fault.CompareAndSwap(nil, &err) }, + fsync: func() error { + if e := h.fsyncErr.Load(); e != nil { + return *e + } + return f.Sync() + }, + syncFile: func(write, sync func() error) error { + err := h.leaf(write, sync) + if h.afterUnlock != nil { + h.afterUnlock() + } + return err + }, + sticky: func() error { + if e := h.fault.Load(); e != nil { + return *e + } + return nil + }, + }) + return h +} + +// leaf is the harness syncFile body: one pwrite+fsync under fileSyncMu, +// refused when a fault is latched, latching an fsync failure. +func (h *descHarnessV3) leaf(write, sync func() error) error { + h.fileSyncMu.Lock() + defer h.fileSyncMu.Unlock() + if e := h.fault.Load(); e != nil { + return *e + } + if write != nil { + if err := write(); err != nil { + return err + } + } + if err := sync(); err != nil { + h.fault.CompareAndSwap(nil, &err) + return err + } + if h.afterFsync != nil { + h.afterFsync() + } + return nil +} + +// onDisk selects from the file's two slots, as a reopen would. +func (h *descHarnessV3) onDisk() (descriptorV3, slotIDV3) { + h.t.Helper() + a := make([]byte, slotSizeV3) + b := make([]byte, slotSizeV3) + if _, err := h.f.ReadAt(a, slotAOffsetV3); err != nil { + h.t.Fatal(err) + } + if _, err := h.f.ReadAt(b, slotBOffsetV3); err != nil { + h.t.Fatal(err) + } + d, id, err := selectSlotV3(a, b, nil) + if err != nil { + h.t.Fatal(err) + } + return d, id +} + +func setW(w uint64) func(*descriptorV3) error { + return func(d *descriptorV3) error { d.W = w; return nil } +} + +func TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest(t *testing.T) { + h := newDescHarnessV3(t) + d, err := h.pub.publish(&h.storeMu, nil, setW(9)) + if err != nil { + t.Fatal(err) + } + if d.SlotGen != 2 || d.W != 9 { + t.Fatalf("published gen %d W %d, want gen 2 W 9", d.SlotGen, d.W) + } + if got, id := h.onDisk(); id != slotB || got.SlotGen != 2 || got.W != 9 { + t.Fatalf("reopen selects slot %d gen %d W %d, want B gen 2 W 9", id, got.SlotGen, got.W) + } + if _, err := h.pub.publish(&h.storeMu, nil, setW(11)); err != nil { + t.Fatal(err) + } + if got, id := h.onDisk(); id != slotA || got.SlotGen != 3 || got.W != 11 { + t.Fatalf("reopen selects slot %d gen %d W %d, want A gen 3 W 11", id, got.SlotGen, got.W) + } +} + +func TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges(t *testing.T) { + h := newDescHarnessV3(t) + if _, err := h.pub.publish(&h.storeMu, nil, setW(20)); err != nil { + t.Fatal(err) + } + // A stale request (computed before W reached 20) never lowers W or the + // checkpoint. + d, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.W, n.CheckpointLSN = 12, 3 + return nil + }) + if err != nil { + t.Fatal(err) + } + if d.W != 20 || d.CheckpointLSN != 7 { + t.Fatalf("stale request regressed W %d / checkpoint %d, want 20 / 7", d.W, d.CheckpointLSN) + } + before := h.pub.current() + refused := []struct { + name string + mutate func(*descriptorV3) error + want error + }{ + {"identity", func(n *descriptorV3) error { n.UUID[0] ^= 1; return nil }, errDescriptorIdentityChange}, + {"geometry", func(n *descriptorV3) error { n.WALSize *= 2; return nil }, errDescriptorIdentityChange}, + {"nonce outside reset", func(n *descriptorV3) error { n.Nonce[0] ^= 1; return nil }, errDescriptorTransition}, + {"map root without a higher generation", func(n *descriptorV3) error { n.MapRootHash[0] ^= 1; return nil }, errDescriptorTransition}, + {"map lineage change", func(n *descriptorV3) error { + n.MapGeneration++ + n.MapLineage[0] ^= 1 + return nil + }, errDescriptorTransition}, + {"BASE none -> installed", func(n *descriptorV3) error { + n.BaseState, n.BaseLSN = BaseInstalled, 20 + n.BaseInstallID[0] = 1 + return nil + }, errDescriptorTransition}, + {"checkpoint above map coverage", func(n *descriptorV3) error { n.CheckpointLSN = 8; return nil }, errSuperblockInvalid}, + } + for _, c := range refused { + t.Run(c.name, func(t *testing.T) { + if _, err := h.pub.publish(&h.storeMu, nil, c.mutate); !errors.Is(err, c.want) { + t.Fatalf("err = %v, want %v", err, c.want) + } + if after := h.pub.current(); after != before { + t.Fatal("a refused publication changed the authoritative descriptor") + } + }) + } + // A higher map generation in the same lineage is accepted. + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.MapGeneration++ + n.MapRootHash[0] ^= 1 + return nil + }); err != nil { + t.Fatalf("higher map generation refused: %v", err) + } + // Retained bounds never move back within one nonce. + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.RetainedTail, n.RetainedHead = 100, 100 + return nil + }); err != nil { + t.Fatal(err) + } + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.RetainedTail = 50 + return nil + }); !errors.Is(err, errDescriptorTransition) { + t.Fatalf("tail moved back: err = %v, want errDescriptorTransition", err) + } +} + +func TestDescriptorV3ConcurrentPublishersNeverRegress(t *testing.T) { + h := newDescHarnessV3(t) + const n = 40 + var wg sync.WaitGroup + for i := 1; i <= n; i++ { + wg.Add(1) + go func(w uint64) { + defer wg.Done() + if _, err := h.pub.publish(&h.storeMu, nil, setW(w)); err != nil { + t.Error(err) + } + }(uint64(7 + i)) + } + wg.Wait() + cur := h.pub.current() + if cur.W != 7+n || cur.SlotGen != 1+n { + t.Fatalf("after %d concurrent publications: W %d gen %d, want W %d gen %d", n, cur.W, cur.SlotGen, 7+n, 1+n) + } + if got, _ := h.onDisk(); got != cur { + t.Fatal("reopen selection differs from the authoritative descriptor") + } +} + +func TestDescriptorV3LockOrderRecorder(t *testing.T) { + h := newDescHarnessV3(t) + var events []string + var mu sync.Mutex + h.pub.trace = func(e string) { mu.Lock(); events = append(events, e); mu.Unlock() } + snapped := false + if _, err := h.pub.publish(&h.storeMu, func() { snapped = true }, setW(9)); err != nil { + t.Fatal(err) + } + if !snapped { + t.Fatal("snapshot did not run under WALStore.mu") + } + want := []string{"lock WALStore.mu", "lock descMu", "unlock WALStore.mu", "hold fileSyncMu", "unlock descMu"} + if len(events) != len(want) { + t.Fatalf("lock events %v, want %v", events, want) + } + for i := range want { + if events[i] != want[i] { + t.Fatalf("lock events %v, want %v (WALStore.mu must be released before slot I/O)", events, want) + } + } + // The store lock is not held during slot I/O: another goroutine can + // take it while the publication sits inside fileSyncMu. + h.pub.trace = nil + inLeaf := make(chan struct{}) + release := make(chan struct{}) + h.afterFsync = func() { close(inLeaf); <-release } + done := make(chan error, 1) + go func() { _, err := h.pub.publish(&h.storeMu, nil, setW(10)); done <- err }() + <-inLeaf + if !h.storeMu.TryLock() { + t.Fatal("WALStore.mu held across descriptor I/O") + } + h.storeMu.Unlock() + close(release) + if err := <-done; err != nil { + t.Fatal(err) + } +} + +func TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing(t *testing.T) { + h := newDescHarnessV3(t) + before := h.pub.current() + boom := errors.New("injected fsync failure") + h.fsyncErr.Store(&boom) + if _, err := h.pub.publish(&h.storeMu, nil, setW(9)); !errors.Is(err, boom) { + t.Fatalf("err = %v, want the fsync failure", err) + } + if h.pub.current() != before { + t.Fatal("a failed publication changed the authoritative descriptor") + } + h.fsyncErr.Store(nil) + if _, err := h.pub.publish(&h.storeMu, nil, setW(10)); !errors.Is(err, boom) { + t.Fatalf("publication after a latched fault: err = %v, want the latched fault", err) + } +} + +func TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary(t *testing.T) { + h := newDescHarnessV3(t) + before := h.pub.current() + other := errors.New("fault latched by another path") + h.afterFsync = func() { h.fault.CompareAndSwap(nil, &other) } + if _, err := h.pub.publish(&h.storeMu, nil, setW(9)); !errors.Is(err, other) { + t.Fatalf("err = %v, want the concurrently latched fault", err) + } + if h.pub.current() != before { + t.Fatal("a publication refused at the success boundary changed the descriptor") + } +} + +func TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange(t *testing.T) { + h := newDescHarnessV3(t) + // A checkpoint publishes tail = head = 100 (a full ring of 100 bytes + // retired): the fallback slot still pins tail 0. + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.RetainedTail, n.RetainedHead = 100, 100 + return nil + }); err != nil { + t.Fatal(err) + } + if floor, ok := h.pub.reuseFloor(); !ok || floor != 0 { + t.Fatalf("floor after the checkpoint = %d (ok %v), want 0: the fallback pins it", floor, ok) + } + beforeW, beforeCkpt := h.pub.current().W, h.pub.current().CheckpointLSN + published, err := h.pub.rolloverIfPinned() + if err != nil || !published { + t.Fatalf("rollover: published %v err %v, want a metadata-only publication", published, err) + } + cur := h.pub.current() + if cur.W != beforeW || cur.CheckpointLSN != beforeCkpt || cur.RetainedTail != 100 { + t.Fatal("rollover changed W, the checkpoint or the tail") + } + if floor, ok := h.pub.reuseFloor(); !ok || floor != 100 { + t.Fatalf("floor after rollover = %d (ok %v), want 100", floor, ok) + } + if again, err := h.pub.rolloverIfPinned(); err != nil || again { + t.Fatalf("second rollover: published %v err %v, want nothing to do", again, err) + } +} + +func TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned(t *testing.T) { + h := newDescHarnessV3(t) + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.RetainedTail, n.RetainedHead = 100, 100 + return nil + }); err != nil { + t.Fatal(err) + } + boom := errors.New("injected fsync failure") + h.fsyncErr.Store(&boom) + if _, err := h.pub.rolloverIfPinned(); !errors.Is(err, boom) { + t.Fatalf("rollover err = %v, want the fsync failure", err) + } + if floor, _ := h.pub.reuseFloor(); floor != 0 { + t.Fatalf("floor = %d after a failed rollover, want 0 (still pinned)", floor) + } +} + +func TestDescriptorV3MixedNoncesNeverYieldAReuseFloor(t *testing.T) { + h := newDescHarnessV3(t) + old := h.pub.current() + old.Nonce[0] ^= 0xFF + h.pub.other, h.pub.otherValid = old, true + if _, ok := h.pub.reuseFloor(); ok { + t.Fatal("a reuse floor was computed across different nonces") + } + if published, err := h.pub.rolloverIfPinned(); err != nil || published { + t.Fatalf("rollover across nonces: published %v err %v, want nothing", published, err) + } +} + +func TestDescriptorV3BaseTransitionTable(t *testing.T) { + id1 := [16]byte{1} + id2 := [16]byte{2} + mk := func(state BaseState, lsn uint64, id [16]byte) descriptorV3 { + return descriptorV3{BaseState: state, BaseLSN: lsn, BaseInstallID: id, CheckpointLSN: 7} + } + cases := []struct { + name string + cur, nxt descriptorV3 + ok bool + }{ + {"none -> installing", mk(BaseNone, 0, [16]byte{}), mk(BaseInstalling, 50, id1), true}, + {"installing -> installed same ID", mk(BaseInstalling, 50, id1), mk(BaseInstalled, 50, id1), true}, + {"installing -> installed other ID", mk(BaseInstalling, 50, id1), mk(BaseInstalled, 50, id2), false}, + {"installing -> superseding installing", mk(BaseInstalling, 50, id1), mk(BaseInstalling, 60, id2), true}, + {"installing -> installing same ID new BaseLSN", mk(BaseInstalling, 50, id1), mk(BaseInstalling, 60, id1), false}, + {"installing -> none is refused (no abort, r17)", mk(BaseInstalling, 50, id1), mk(BaseNone, 0, [16]byte{}), false}, + {"none -> installed", mk(BaseNone, 0, [16]byte{}), mk(BaseInstalled, 50, id1), false}, + {"installed -> none needs checkpoint past BaseLSN", mk(BaseInstalled, 50, id1), mk(BaseNone, 0, [16]byte{}), false}, + {"installed -> installing is not an 8.5 edge", mk(BaseInstalled, 50, id1), mk(BaseInstalling, 60, id2), false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + err := baseTransitionAllowedV3(&c.cur, &c.nxt) + if (err == nil) != c.ok { + t.Fatalf("err = %v, want allowed = %v", err, c.ok) + } + }) + } + cur := mk(BaseInstalled, 50, id1) + nxt := mk(BaseNone, 0, [16]byte{}) + nxt.CheckpointLSN = 50 + if err := baseTransitionAllowedV3(&cur, &nxt); err != nil { + t.Fatalf("installed -> none with the checkpoint at BaseLSN refused: %v", err) + } + // Retirement also needs both slots' tails at or past BaseCursor (8.4). + cur.BaseCursor, cur.RetainedTail, nxt.RetainedTail = 100, 100, 99 + if err := baseTransitionAllowedV3(&cur, &nxt); err == nil { + t.Fatal("installed -> none with the new tail below BaseCursor allowed") + } + cur.RetainedTail, nxt.RetainedTail = 99, 100 + if err := baseTransitionAllowedV3(&cur, &nxt); err == nil { + t.Fatal("installed -> none with the fallback tail below BaseCursor allowed") + } +} + +// codex01 row 3 review P1: a slot write error (full or partial), like an +// fsync error, latches the store, keeps the candidate pinned and refuses +// every further publication, rollover and reuse with no further I/O. +// Reopen (read back and select) is the positive control. +func TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate(t *testing.T) { + for _, partial := range []bool{true, false} { + name := "full write then error" + if partial { + name = "partial write then error" + } + t.Run(name, func(t *testing.T) { + h := newDescHarnessV3(t) + // A checkpoint first, so the fallback pins tail 0 and a + // rollover would otherwise be due. + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.RetainedTail, n.RetainedHead = 100, 100 + return nil + }); err != nil { + t.Fatal(err) + } + before := h.pub.current() + boom := errors.New("injected slot write error") + h.writeHook = func(off int64, b []byte) error { + n := len(b) + if partial { + n = 1000 + } + if _, err := h.f.WriteAt(b[:n], off); err != nil { + t.Fatal(err) + } + return boom + } + _, err := h.pub.publish(&h.storeMu, nil, setW(30)) + if !errors.Is(err, ErrDescriptorPublishUncertain) || !errors.Is(err, boom) { + t.Fatalf("err = %v, want ErrDescriptorPublishUncertain wrapping the write error", err) + } + if h.pub.current() != before { + t.Fatal("a failed publication changed the authoritative descriptor") + } + if cand, ok := h.pub.uncertainCandidate(); !ok || cand.W != 30 || cand.SlotGen != before.SlotGen+1 { + t.Fatalf("uncertain candidate not retained: ok %v %+v", ok, cand) + } + if h.fault.Load() == nil { + t.Fatal("the store fault was not latched: other store paths could still acknowledge or reclaim") + } + h.writeHook = nil + writes := h.writes.Load() + if _, err := h.pub.publish(&h.storeMu, nil, setW(31)); !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("publication after the failure: err = %v, want ErrDescriptorPublishUncertain", err) + } + if _, err := h.pub.rolloverIfPinned(); !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("rollover after the failure: err = %v, want ErrDescriptorPublishUncertain", err) + } + if _, ok := h.pub.reuseFloor(); ok { + t.Fatal("reuse allowed while a publication outcome is uncertain") + } + if got := h.writes.Load(); got != writes { + t.Fatalf("%d further slot writes after the failure, want none", got-writes) + } + // Reopen resolves it: a torn slot fails its CRC and the + // previous generation is selected; a complete slot is the new one. + got, _ := h.onDisk() + if partial && got != before { + t.Fatalf("reopen after a torn write selected gen %d W %d, want the previous gen %d", got.SlotGen, got.W, before.SlotGen) + } + if !partial && (got.SlotGen != before.SlotGen+1 || got.W != 30) { + t.Fatalf("reopen after a complete write selected gen %d W %d, want gen %d W 30", got.SlotGen, got.W, before.SlotGen+1) + } + }) + } +} + +// codex01 row 3 review P2: counters beyond 2^64-2 are refused at +// publication with ErrCounterExhausted, before any write. +func TestDescriptorV3PublicationCounterExhaustion(t *testing.T) { + const over = counterMaxV3 + 1 + for _, c := range []struct { + name string + set func(*descriptorV3) + }{ + {"W", func(n *descriptorV3) { n.W = over }}, + {"CheckpointLSN", func(n *descriptorV3) { n.CheckpointLSN = over }}, + {"retainedHead", func(n *descriptorV3) { n.RetainedHead = over }}, + {"mapGeneration", func(n *descriptorV3) { n.MapGeneration = over; n.MapRootHash[0] ^= 1 }}, + } { + t.Run(c.name, func(t *testing.T) { + h := newDescHarnessV3(t) + writes := h.writes.Load() + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { c.set(n); return nil }); !errors.Is(err, ErrCounterExhausted) { + t.Fatalf("err = %v, want ErrCounterExhausted", err) + } + if h.writes.Load() != writes { + t.Fatal("an exhausted publication wrote a slot") + } + }) + } +} + +// codex01 row 3 round 2 P1: the store fault for a slot write error is +// latched inside the leaf, before fileSyncMu is released. An independent +// store Sync B queued on fileSyncMu behind A's failing slot write must be +// refused and must not fsync or acknowledge. The harness lets B run right +// after the leaf unlocks and before A's publisher resumes, so a latch taken +// after the unlock would let B succeed. +func TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError(t *testing.T) { + for _, partial := range []bool{true, false} { + name := "full write then error" + if partial { + name = "partial write then error" + } + t.Run(name, func(t *testing.T) { + h := newDescHarnessV3(t) + boom := errors.New("injected slot write error") + bResult := make(chan error, 1) + var bFsyncs atomic.Int64 + h.writeHook = func(off int64, b []byte) error { + n := len(b) + if partial { + n = 1000 + } + if _, err := h.f.WriteAt(b[:n], off); err != nil { + t.Error(err) + } + // B queues on fileSyncMu while A still holds it. + go func() { + bResult <- h.leaf(nil, func() error { bFsyncs.Add(1); return nil }) + }() + return boom + } + var bErr error + h.afterUnlock = func() { bErr = <-bResult } + if _, err := h.pub.publish(&h.storeMu, nil, setW(30)); !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("A: err = %v, want ErrDescriptorPublishUncertain", err) + } + if bErr == nil || bFsyncs.Load() != 0 { + t.Fatalf("queued store sync B acknowledged after A's slot write failed (err %v, fsyncs %d)", bErr, bFsyncs.Load()) + } + if !errors.Is(bErr, ErrDescriptorPublishUncertain) { + t.Fatalf("B refused with %v, want the latched ErrDescriptorPublishUncertain", bErr) + } + }) + } +} diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index a74b9c37b3..9c6175e044 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -3,7 +3,7 @@ package storage import ( "encoding/binary" "fmt" - "log" + "sort" "sync" "sync/atomic" "time" @@ -56,6 +56,10 @@ type flusher struct { // taken and the publication lock released: the window in which a // concurrent append is not in this cycle's checkpoint. Tests only. afterSnapshotForTest func() + // Pauses after materialization/fsync, before map proof preparation. Tests only. + afterExtentSyncForTest func() + // Pauses after checkpoint/reuse publication, before the outer DM cleanup. + afterCheckpointForTest func() } type flusherConfig struct { @@ -106,6 +110,7 @@ func (f *flusher) runWithStartSignal(started chan<- struct{}) { if started != nil { close(started) } + var diagnostics checkpointLogLimiter for { select { case <-f.stopCh: @@ -115,11 +120,11 @@ func (f *flusher) runWithStartSignal(started chan<- struct{}) { return case <-ticker.C: if err := f.flushOnce(); err != nil { - log.Printf("storage: flusher: %v", err) + diagnostics.report(err, time.Now()) } case <-f.notifyCh: if err := f.flushOnce(); err != nil { - log.Printf("storage: flusher (notify): %v", err) + diagnostics.report(err, time.Now()) } } } @@ -158,6 +163,13 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { if err := store.stickyIOFault(); err != nil { return err // no checkpoint advance after a failed fsync } + // Do not acquire lifecycleMu here: Close holds it while joining Stop. + // The pressure leader is released before snapshot/materialization/checkpoint. + if store.v3 != nil { + if err := store.syncWALPressureV3(); err != nil { + return fmt.Errorf("flusher: pressure WAL sync: %w", err) + } + } store.mu.RLock() if store.closed && !allowClosed { store.mu.RUnlock() @@ -167,9 +179,18 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { // Hold the publication lock across all shards: a later shard must not // include a write whose predecessor was omitted from an earlier shard. // Release before WAL reads, extent writes or fsync. + // Bind materialization to the same Recover lifetime as this snapshot. + // Recover holds store.mu at both generation boundaries. + var recoveryGen uint64 + if store.v3 != nil { + recoveryGen = store.v3.recoverGen.Load() + } entries := store.dm.snapshot() store.mu.RUnlock() if len(entries) == 0 { + if store.v3 != nil { + return store.refreshW() // the mode-C idle refresh (DESIGN 6.2) + } return nil } if f.afterSnapshotForTest != nil { @@ -191,8 +212,27 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { f.instr.recordWrittenOpportunity(writtenEntries, store.sb.BlockSize) }() + // Adjacent blocks of a native batch share one immutable, validated record. + // Keep only one record (at most WALSize bytes), scoped to this Recover lifetime. + var recordCache *flushRecordCacheV3 + if store.v3 != nil { + sort.Slice(entries, func(i, j int) bool { + if entries[i].WALOffset == entries[j].WALOffset { + return entries[i].DataOffset < entries[j].DataOffset + } + return entries[i].WALOffset < entries[j].WALOffset + }) + recordCache = &flushRecordCacheV3{recoveryGen: recoveryGen} + } for _, e := range entries { - data, entrySize, err := f.readDirtyRecord(e) + var data []byte + var entrySize uint64 + var err error + if recordCache != nil { + data, entrySize, err = f.readDirtyRecordV3Cached(e, recordCache) + } else { + data, entrySize, err = f.readDirtyRecord(e) + } if err != nil { return err } @@ -225,6 +265,10 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { return fmt.Errorf("flusher: fsync after extent writes: %w", syncErr) } + if f.afterExtentSyncForTest != nil { + f.afterExtentSyncForTest() + } + // Step 3: advance the on-disk checkpoint to the highest LSN // that was successfully flushed in this cycle. Because we // processed the entire consistent snapshot, every entry @@ -233,10 +277,18 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { if maxLSN > 0 { // The released tail is persisted with the checkpoint, before the // writer may reuse those bytes. - if err := store.persistCheckpointAndRelease(maxLSN, maxLSNPhys, maxLSNEntrySize); err != nil { + var publishErr error + cpBefore := store.CheckpointLSN() + if store.v3 != nil { + publishErr = store.persistCheckpointV3(maxLSN, recoveryGen) + } else { + publishErr = store.persistCheckpointAndRelease(maxLSN, maxLSNPhys, maxLSNEntrySize) + } + f.instr.recordCheckpoint(publishErr, cpBefore, store.CheckpointLSN(), time.Now()) + if err := publishErr; err != nil { return fmt.Errorf("flusher: persist checkpoint %d: %w", maxLSN, err) } - if store.CheckpointLSN() >= maxLSN { + if store.v3 == nil && store.CheckpointLSN() >= maxLSN { store.mu.Lock() if maxLSN+1 > store.walTail { store.walTail = maxLSN + 1 @@ -245,17 +297,51 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { } } + if f.afterCheckpointForTest != nil { + f.afterCheckpointForTest() + } + // Step 4: remove flushed entries from the dirty map using // compare-and-delete. If a concurrent Write() bumped an entry's // LSN after our snapshot, this leaves the newer entry alone. + // V3 may have clamped its checkpoint to Wack (or held it for a map). + // Keep the uncovered entries as retry work even though their extent + // bytes were fsynced: a later Sync plus cycle must advance checkpoint + // AND coverage, rather than merely refreshing W on an empty dirty map. + checkpoint := maxLSN // legacy behavior: remove the whole flushed snapshot + if store.v3 != nil { + // Serialize validation and LSN-only retirement with Recover. A new + // lifetime can reuse the same LBA, physical offset and LSN. + store.mu.Lock() + if !store.v3.flushLifetimeValidV3(recoveryGen) { + store.mu.Unlock() + return mapCoverageRefusal("recovery_lifetime_changed") + } + checkpoint = store.checkpointLSN + if checkpoint >= maxLSN && maxLSN+1 > store.walTail { + store.walTail = maxLSN + 1 + } + } for _, e := range entries { + if e.LSN > checkpoint { + continue + } store.dm.compareAndDelete(e.LBA, e.LSN) } + if store.v3 != nil { + store.mu.Unlock() + } f.flushes.Add(1) + if store.v3 != nil { + return store.refreshW() // the mode-C idle refresh (DESIGN 6.2) + } return nil } func (f *flusher) readDirtyRecord(e snapshotEntry) (data []byte, entrySize uint64, err error) { + if f.store.v3 != nil { + return f.readDirtyRecordV3(e) + } store := f.store readFailed := false defer func() { diff --git a/seaweed-block/core/storage/flusher_instrumentation.go b/seaweed-block/core/storage/flusher_instrumentation.go index 3d7cf587fb..939da10058 100644 --- a/seaweed-block/core/storage/flusher_instrumentation.go +++ b/seaweed-block/core/storage/flusher_instrumentation.go @@ -12,6 +12,9 @@ const maxCheckpointWriteBytes = 1 << 20 // checkpoint work. Operation counters include failed attempts; byte counters // include only successful writes. type FlusherInstrumentationStatus struct { + CheckpointSuccesses uint64 + CheckpointRefusals uint64 + CheckpointFailures uint64 CyclesStarted uint64 CyclesSucceeded uint64 CyclesFailed uint64 @@ -63,6 +66,11 @@ type FlusherInstrumentationStatus struct { } type flusherInstrumentation struct { + checkpointSuccesses atomic.Uint64 + checkpointRefusals atomic.Uint64 + checkpointFailures atomic.Uint64 + checkpointAdvances atomic.Uint64 + checkpointLastAdvanceNanos atomic.Int64 cyclesStarted atomic.Uint64 cyclesSucceeded atomic.Uint64 cyclesFailed atomic.Uint64 @@ -284,6 +292,9 @@ func updateAtomicMax(target *atomic.Uint64, value uint64) { func (i *flusherInstrumentation) snapshot() FlusherInstrumentationStatus { return FlusherInstrumentationStatus{ + CheckpointSuccesses: i.checkpointSuccesses.Load(), + CheckpointRefusals: i.checkpointRefusals.Load(), + CheckpointFailures: i.checkpointFailures.Load(), CyclesStarted: i.cyclesStarted.Load(), CyclesSucceeded: i.cyclesSucceeded.Load(), CyclesFailed: i.cyclesFailed.Load(), diff --git a/seaweed-block/core/storage/flusher_instrumentation_test.go b/seaweed-block/core/storage/flusher_instrumentation_test.go index 07e0884e99..d6a0aa02ca 100644 --- a/seaweed-block/core/storage/flusher_instrumentation_test.go +++ b/seaweed-block/core/storage/flusher_instrumentation_test.go @@ -34,7 +34,7 @@ func TestBoundedExtentWriteOpportunity(t *testing.T) { } func TestFlusherInstrumentationCountsCompleteCycle(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) if err != nil { t.Fatal(err) } @@ -61,10 +61,14 @@ func TestFlusherInstrumentationCountsCompleteCycle(t *testing.T) { t.Fatalf("snapshot/validated/superseded=%d/%d/%d want 4/4/0", got.SnapshotEntries, got.ValidatedRecords, got.SupersededEntries) } - if got.WALHeaderReadOps != 4 || got.WALRecordReadOps != 4 || - got.WALRecordDecodeOps != 4 || got.WALRecordDecodeBytes == 0 || + wantRecords := uint64(4) + if s.FormatV3() { + wantRecords = 1 + } // one full native batch decode, four validated blocks + if got.WALHeaderReadOps != wantRecords || got.WALRecordReadOps != wantRecords || + got.WALRecordDecodeOps != wantRecords || got.WALRecordDecodeBytes == 0 || got.WALRecordDecodeDurationNanos == 0 { - t.Fatalf("header/record reads and decode ops/bytes/ns=%d/%d %d/%d/%d want 4/4 4/nonzero/nonzero", + t.Fatalf("header/record reads and decode ops/bytes/ns=%d/%d %d/%d/%d want actual unique-record counts/nonzero bytes and duration", got.WALHeaderReadOps, got.WALRecordReadOps, got.WALRecordDecodeOps, got.WALRecordDecodeBytes, got.WALRecordDecodeDurationNanos) @@ -176,7 +180,7 @@ func TestFlusherInstrumentationCountsCheckpointFailure(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) if err != nil { t.Fatal(err) } @@ -291,7 +295,7 @@ func TestFlusherInstrumentationCountsWALReadFailures(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/flusher_profile_v3_test.go b/seaweed-block/core/storage/flusher_profile_v3_test.go new file mode 100644 index 0000000000..7477c31955 --- /dev/null +++ b/seaweed-block/core/storage/flusher_profile_v3_test.go @@ -0,0 +1,56 @@ +package storage + +import "testing" + +func TestFlusherV3ProfileCountsRealRecordStages(t *testing.T) { + for _, mode := range []string{"ok", "header", "record", "decode"} { + t.Run(mode, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + if _, err := s.WriteBatch(0, [][]byte{blk(1), blk(2)}); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + switch mode { + case "header": + _ = s.fd.Close() + case "record": + if err := s.fd.Truncate(int64(s.sb.WALOffset + walEntryPrefixSizeV3)); err != nil { + t.Fatal(err) + } + case "decode": + if _, err := s.fd.WriteAt([]byte{0xff}, int64(s.sb.WALOffset+walEntryPrefixSizeV3)); err != nil { + t.Fatal(err) + } + } + err := s.flusher.flushOnce() + got := s.FlusherInstrumentation() + if mode == "ok" { + if err != nil { + t.Fatal(err) + } + if got.ValidatedRecords != 2 || got.WALHeaderReadOps != 1 || got.WALRecordReadOps != 1 || got.WALRecordDecodeOps != 1 || got.ValidationFailures != 0 || got.CyclesSucceeded != 1 { + t.Fatalf("successful batch stages: %+v", got) + } + } else { + if err == nil { + t.Fatal("faulted flush succeeded") + } + var h, r, d, v uint64 + switch mode { + case "header": + h = 1 + case "record": + r = 1 + case "decode": + d = 1 + v = 1 + } + if got.WALHeaderReadFailures != h || got.WALRecordReadFailures != r || got.WALRecordDecodeFailures != d || got.ValidationFailures != v || got.ValidatedRecords != 0 || got.CyclesFailed != 1 { + t.Fatalf("%s failure stages: %+v", mode, got) + } + } + }) + } +} diff --git a/seaweed-block/core/storage/flusher_snapshot_cut_test.go b/seaweed-block/core/storage/flusher_snapshot_cut_test.go index 981fbc6436..5de0f42e2a 100644 --- a/seaweed-block/core/storage/flusher_snapshot_cut_test.go +++ b/seaweed-block/core/storage/flusher_snapshot_cut_test.go @@ -24,7 +24,7 @@ func TestFlusherSnapshotCutPreservesSyncedWrites(t *testing.T) { } t.Run(name, func(t *testing.T) { path := filepath.Join(t.TempDir(), "store.bin") - s, err := CreateWALStore(path, 128, 4096) + s, err := createLegacyWALStoreForTest(path, 128, 4096) if err != nil { t.Fatal(err) } @@ -127,7 +127,7 @@ func TestFlusherSnapshotCutPreservesSyncedWrites(t *testing.T) { t.Fatal(err) } crashed = true - reopened, err := OpenWALStore(path) + reopened, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/flusher_test.go b/seaweed-block/core/storage/flusher_test.go index 0b1ee0e075..3ff75ea1d2 100644 --- a/seaweed-block/core/storage/flusher_test.go +++ b/seaweed-block/core/storage/flusher_test.go @@ -16,7 +16,7 @@ func TestFlusher_AdvancesCheckpointBeforeReadFromExtent(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "store.bin") - s, err := CreateWALStore(path, 16, 4096) + s, err := createLegacyWALStoreForTest(path, 16, 4096) if err != nil { t.Fatal(err) } @@ -69,7 +69,7 @@ func TestFlusher_ReleasesWALPressureAfterCheckpoint(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "store.bin") - s := createWALStoreWithWALSizeForTest(t, path, 128, 4096, 256*1024) + s := createLegacyWALStoreWithWALSizeForTest(t, path, 128, 4096, 256*1024) defer s.Close() for i := uint32(0); i < 32; i++ { @@ -130,7 +130,7 @@ func TestWALWriter_AdvanceTailPastWrappedEntry(t *testing.T) { } } -func createWALStoreWithWALSizeForTest(t *testing.T, path string, numBlocks uint32, blockSize int, walSize uint64) *WALStore { +func createLegacyWALStoreWithWALSizeForTest(t *testing.T, path string, numBlocks uint32, blockSize int, walSize uint64) *WALStore { t.Helper() if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { t.Fatalf("mkdir: %v", err) @@ -144,7 +144,7 @@ func createWALStoreWithWALSizeForTest(t *testing.T, path string, numBlocks uint3 ExtentSize: uint32(blockSize), WALSize: walSize, ImplKind: ImplKindWALStore, - ImplVersion: WALStoreImplVersion, + ImplVersion: 1, // frozen v2 engine fixture, not the production selector }) if err != nil { _ = f.Close() @@ -180,7 +180,7 @@ func TestFlusher_RecoveryHonorsCheckpoint(t *testing.T) { path := filepath.Join(dir, "store.bin") { - s, err := CreateWALStore(path, 16, 4096) + s, err := createLegacyWALStoreForTest(path, 16, 4096) if err != nil { t.Fatal(err) } @@ -204,7 +204,7 @@ func TestFlusher_RecoveryHonorsCheckpoint(t *testing.T) { // Reopen + Recover. The checkpointed records should be skipped; // extent should serve all reads. - s, err := OpenWALStore(path) + s, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -273,7 +273,7 @@ func TestCrashFamily_AbruptKillAtMultipleWindows(t *testing.T) { path := filepath.Join(dir, "store.bin") func() { - s, err := CreateWALStore(path, 16, 4096) + s, err := createLegacyWALStoreForTest(path, 16, 4096) if err != nil { t.Fatal(err) } @@ -313,7 +313,7 @@ func TestCrashFamily_AbruptKillAtMultipleWindows(t *testing.T) { // Reopen + Recover. Verify acked survives, unacked // is either present-as-written or absent, never corrupt. - s, err := OpenWALStore(path) + s, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatalf("reopen after %s: %v", c.name, err) } @@ -373,7 +373,7 @@ func TestFlusher_ManyDirtyEntriesCheckpointStaysCorrect(t *testing.T) { const n = 300 // > any plausible old maxBatch (which was 256) { - s, err := CreateWALStore(path, n+10, 4096) + s, err := createLegacyWALStoreForTest(path, n+10, 4096) if err != nil { t.Fatal(err) } @@ -409,7 +409,7 @@ func TestFlusher_ManyDirtyEntriesCheckpointStaysCorrect(t *testing.T) { // Reopen + Recover. Every LBA must be readable with the bytes // we wrote — the checkpoint advance must have only covered // LBAs whose data is actually in the extent. - s, err := OpenWALStore(path) + s, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -448,7 +448,7 @@ func TestFlusher_ConcurrentWriteRaceLBAStaysFresh(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "store.bin") - s, err := CreateWALStore(path, 16, 4096) + s, err := createLegacyWALStoreForTest(path, 16, 4096) if err != nil { t.Fatal(err) } @@ -502,7 +502,7 @@ func TestAllBlocks_ReturnsBlocksAfterFlush(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "store.bin") - s, err := CreateWALStore(path, 16, 4096) + s, err := createLegacyWALStoreForTest(path, 16, 4096) if err != nil { t.Fatal(err) } @@ -533,7 +533,10 @@ func TestAllBlocks_ReturnsBlocksAfterFlush(t *testing.T) { // AllBlocks must still return both written LBAs even though // they're no longer in the dirty map. - all := s.AllBlocks() + all, snapshotErr := s.AllBlocks() + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(all) != 2 { t.Fatalf("AllBlocks after flush returned %d entries, want 2", len(all)) } @@ -553,7 +556,7 @@ func TestRecovery_DeterministicAcrossMultipleOpens(t *testing.T) { path := filepath.Join(dir, "store.bin") { - s, _ := CreateWALStore(path, 16, 4096) + s, _ := createLegacyWALStoreForTest(path, 16, 4096) for i := uint32(0); i < 5; i++ { _, _ = s.Write(i, makeBlock(4096, byte(0x10+i))) } @@ -565,7 +568,7 @@ func TestRecovery_DeterministicAcrossMultipleOpens(t *testing.T) { } // First reopen + Recover. - s1, _ := OpenWALStore(path) + s1, _ := openLegacyWALStoreForTest(path) r1, err := s1.Recover() if err != nil { t.Fatal(err) @@ -577,7 +580,7 @@ func TestRecovery_DeterministicAcrossMultipleOpens(t *testing.T) { _ = s1.Close() // Second reopen + Recover on the same file. - s2, _ := OpenWALStore(path) + s2, _ := openLegacyWALStoreForTest(path) r2, err := s2.Recover() if err != nil { t.Fatal(err) diff --git a/seaweed-block/core/storage/format_v3_test_support.go b/seaweed-block/core/storage/format_v3_test_support.go new file mode 100644 index 0000000000..1e7de35b79 --- /dev/null +++ b/seaweed-block/core/storage/format_v3_test_support.go @@ -0,0 +1,136 @@ +//go:build swblock_format_v3_test + +package storage + +import ( + "fmt" + "os" +) + +// CreateMappedWALStoreV3Test is available only to tagged cross-package caller +// controls. Production Create/Open remain unchanged until the activation gate. +func CreateMappedWALStoreV3Test(path string, blocks, blockSize, chunkBlocks uint32) (*WALStore, error) { + return createMappedWALStoreV3ForTest(path, blocks, blockSize, 1<<20, WModeLagged, uint64(chunkBlocks)) +} + +func OpenMappedWALStoreV3Test(path string) (*WALStore, error) { + return openWALStoreV3ForTest(path) +} + +func FlushMappedWALStoreV3Test(s *WALStore) error { + return s.flusher.flushOnce() +} + +// CreateWALStoreV3Test creates an unmapped dark v3 store (mode A) for the +// tagged cross-package install controls (plan row 9b). +func CreateWALStoreV3Test(path string, blocks, blockSize uint32) (*WALStore, error) { + s, err := createWALStoreV3ForTest(path, blocks, blockSize, 1<<20, WModeStrict) + if err == nil { + s.DisableAutoFlushForRecoveryTest() + } + return s, err +} + +// SetInstallHooksV3Test sets the install admission hooks (DESIGN 8.7): +// beforeAdmit runs in a handle mutation before it acquires installMu, +// admitted after its ID check and before the write. nil clears a hook. +func SetInstallHooksV3Test(s *WALStore, beforeAdmit, admitted func()) { + s.v3.testInstallBeforeAdmit = beforeAdmit + s.v3.testInstallAdmitted = admitted +} + +// SetScanReadV3Test parks a cross-package sender after its physical WAL +// scan, before source-lifetime revalidation. Set before starting the sender. +func SetScanReadV3Test(s *WALStore, hook func()) { s.v3.testScanRead = hook } + +// SetScanBeforeReadV3Test parks a real sender after capture, before WAL I/O. +func SetScanBeforeReadV3Test(s *WALStore, hook func()) { s.v3.testScanBeforeRead = hook } + +// BaseStateV3Test reports the selected descriptor's BASE state and ID. +func BaseStateV3Test(s *WALStore) (BaseState, [16]byte) { + d := s.v3.pub.current() + return d.BaseState, d.BaseInstallID +} + +// CrashReopenV3Test simulates a crash (no flush, no Close) of an unmapped +// dark v3 store and reopens and recovers it, as a restart would. +func CrashReopenV3Test(s *WALStore, path string) (*WALStore, error) { + s.committer.Stop() + if err := s.fd.Close(); err != nil { + return nil, err + } + r, err := openUnmappedWALStoreV3ForTest(path) + if err != nil { + return nil, err + } + r.DisableAutoFlushForRecoveryTest() + if _, err := r.Recover(); err != nil { + _ = r.Close() + return nil, err + } + return r, nil +} + +// MapCoverageV3Test reports the bound map root's covered checkpoint and +// whether every chunk entry is UNKNOWN (the row 13 initial-map control). +func MapCoverageV3Test(s *WALStore) (covered uint64, allUnknown bool) { + s.v3.pub.descMu.Lock() + defer s.v3.pub.descMu.Unlock() + allUnknown = true + for _, e := range s.v3.pub.mapCurrent.entries { + if !e.Unknown { + allUnknown = false + } + } + return s.v3.pub.cur.MapCoveredCheckpoint, allUnknown +} + +// DamageV3RecordTest flips one payload byte of the v3 WAL record carrying +// lsn in the closed or open file at path (a cross-package corrupt-record +// control). +func DamageV3RecordTest(path string, lsn uint64) error { + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + return err + } + defer f.Close() + a, b := make([]byte, slotSizeV3), make([]byte, slotSizeV3) + if _, err := f.ReadAt(a, 0); err != nil { + return err + } + if _, err := f.ReadAt(b, slotBOffsetV3); err != nil { + return err + } + d, _, err := selectSlotV3(a, b, nil) + if err != nil { + return err + } + r, err := scanWALV3(f, d) + if err != nil { + return err + } + for _, rec := range r.Records { + if rec.Entry.LSN != lsn { + continue + } + size := uint64(walEntryHeaderSizeV3 + len(rec.Entry.Data)) + off := int64(d.WALOffset+(rec.End-size)%d.WALSize) + walEntryPrefixSizeV3 + 100 + x := []byte{0} + if _, err := f.ReadAt(x, off); err != nil { + return err + } + x[0] ^= 0xFF + _, err = f.WriteAt(x, off) + return err + } + return fmt.Errorf("no v3 record with LSN %d", lsn) +} + +// Legacy fixtures only; unavailable in production builds. +// TODO(format-v3 row 14a): replace with captured migration fixtures. +func CreateLegacyWALStoreTest(path string, blocks uint32, blockSize int) (*WALStore, error) { + return createLegacyWALStoreWithOptions(path, blocks, blockSize, WALStoreOptions{}) +} +func OpenLegacyWALStoreTest(path string) (*WALStore, error) { + return openLegacyWALStoreWithOptions(path, WALStoreOptions{}) +} diff --git a/seaweed-block/core/storage/install_log_v3.go b/seaweed-block/core/storage/install_log_v3.go new file mode 100644 index 0000000000..83b72fc325 --- /dev/null +++ b/seaweed-block/core/storage/install_log_v3.go @@ -0,0 +1,100 @@ +package storage + +import ( + "errors" + "fmt" +) + +// Acknowledgement while installing (format bump v3, DESIGN r17.4 section 7; +// plan row 10). Dark: only tests build a v3 store. + +var ( + // ErrBaseInstalling: the logical Sync is gated while BaseState = + // installing. It is always returned with frontier 0 (DESIGN 7). + ErrBaseInstalling = errors.New("storage: v3 BASE install in progress; not ready") + // ErrNotInstalling: SyncInstallLog outside an install. + ErrNotInstalling = errors.New("storage: v3 install-log sync outside a BASE install") + // ErrInstallIDMismatch: SyncInstallLog for an ID that is not installing. + ErrInstallIDMismatch = errors.New("storage: v3 install-log sync for another install ID") +) + +// InstallLogSyncer is the rebuild receiver's install-log durability ack +// (DESIGN 7, O1-a). It is deliberately not on LogicalStorage: only +// core/recovery type-asserts it. +type InstallLogSyncer interface { + SyncInstallLog(installID [16]byte) (uint64, error) +} + +var _ InstallLogSyncer = (*WALStore)(nil) + +// SyncInstallLog makes the install lane durable and acknowledges it while +// installing (DESIGN 7). It revalidates the ID under installMu shared, +// freezes the cut H (every LSN pwritten so far), fsyncs the WAL and then +// publishes W = max(W, H) with BaseState still installing: always mode A, +// whatever the volume's WMode. It attests log durability only, never a +// readable image, and never changes BaseState. A v2 store keeps its +// pre-v3 behaviour: the receiver's ack is its ordinary Sync. +func (s *WALStore) SyncInstallLog(installID [16]byte) (uint64, error) { + v := s.v3 + if v == nil { + return s.Sync() + } + v.installMu.RLock() + defer v.installMu.RUnlock() + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + if err := installLogTargetV3(v.pub.current(), installID); err != nil { + return 0, err + } + v.syncMu.Lock() // the leader role: no committer batch or recovery meanwhile + defer v.syncMu.Unlock() + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return 0, errors.New("storage: SyncInstallLog after Close") + } + if err := s.stickyIOFault(); err != nil { + s.mu.Unlock() + return 0, err + } + H := v.appended.Load() + s.mu.Unlock() + // Mode A: the WAL fsync precedes the slot publication. + if err := s.syncFile(nil, s.fd.Sync); err != nil { + return 0, fmt.Errorf("storage: install-log fsync: %w", err) + } + if _, err := v.pub.publish(&s.mu, nil, func(n *descriptorV3) error { + if err := installLogTargetV3(*n, installID); err != nil { + return err + } + n.W = max(n.W, H) + return nil + }); err != nil { + return 0, err + } + if hook := v.testInstallLogBeforeAck; hook != nil { + hook() + } + // The #172 ack boundary: a fault latched after the publisher's final + // check (a queued append of this ID failing under s.mu) refuses the ack. + s.mu.Lock() + defer s.mu.Unlock() + if err := s.stickyIOFault(); err != nil { + return 0, err + } + if H > v.wack.Load() { + v.wack.Store(H) + } + s.syncedLSN = max(s.syncedLSN, H) + return H, nil +} + +func installLogTargetV3(d descriptorV3, installID [16]byte) error { + if d.BaseState != BaseInstalling { + return ErrNotInstalling + } + if d.BaseInstallID != installID { + return ErrInstallIDMismatch + } + return nil +} diff --git a/seaweed-block/core/storage/install_log_v3_test.go b/seaweed-block/core/storage/install_log_v3_test.go new file mode 100644 index 0000000000..a0b9bf6a74 --- /dev/null +++ b/seaweed-block/core/storage/install_log_v3_test.go @@ -0,0 +1,123 @@ +package storage + +import ( + "errors" + "testing" +) + +// Plan row 10a controls (DESIGN r17.4 section 7; owner claude03): the gated +// logical Sync and the receiver-only install-log ack. + +// While installing, Sync returns exactly (0, ErrBaseInstalling) and writes +// no slot; after complete it acknowledges again. Mutant: an ungated Sync +// acknowledges the install lane through the frontend path and fails here. +func TestInstallLogV3SyncIsGatedWhileInstalling(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 1) + h := beginV3(t, s, 1, idA) + if err := h.ApplyInstallEntry(2, blk(2), 2); err != nil { + t.Fatal(err) + } + writes := countSlotWritesV3(s) + if f, err := s.Sync(); f != 0 || !errors.Is(err, ErrBaseInstalling) { + t.Fatalf("Sync while installing = (%d, %v), want (0, ErrBaseInstalling)", f, err) + } + if writes.Load() != 0 || s.v3.pub.current().W != 1 { + t.Fatalf("gated Sync wrote %d slots, W %d", writes.Load(), s.v3.pub.current().W) + } + s.v3.testBeforeSlotWrite = nil + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + if f, err := s.Sync(); err != nil || f < 2 { + t.Fatalf("Sync after complete = (%d, %v), want >= 2", f, err) + } +} + +// SyncInstallLog refuses outside an install and for another ID, writing +// nothing. Mutant: dropping the ID check acknowledges another install. +func TestInstallLogV3Refusals(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writes := countSlotWritesV3(s) + if _, err := s.SyncInstallLog(idA); !errors.Is(err, ErrNotInstalling) { + t.Fatalf("outside an install: err = %v, want ErrNotInstalling", err) + } + s.v3.testBeforeSlotWrite = nil + beginV3(t, s, 0, idA) + writes = countSlotWritesV3(s) + if _, err := s.SyncInstallLog(idB); !errors.Is(err, ErrInstallIDMismatch) { + t.Fatalf("another ID: err = %v, want ErrInstallIDMismatch", err) + } + if writes.Load() != 0 { + t.Fatal("a refused install-log sync wrote a slot") + } +} + +// The ack is mode A whatever the WMode: on a lagged (mode C) store the slot +// carries W = H as soon as SyncInstallLog returns, with BaseState still +// installing, and a crash keeps that W and the install. Mutant: the ack +// without its publication (the lagged mode's deferred W) fails here. +func TestInstallLogV3IsModeAAndSurvivesACrash(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + h := beginV3(t, s, 0, idA) + for lsn := uint64(1); lsn <= 3; lsn++ { + if err := h.ApplyInstallEntry(uint32(lsn), blk(byte(lsn)), lsn); err != nil { + t.Fatal(err) + } + } + H, err := s.SyncInstallLog(idA) + if err != nil || H != 3 { + t.Fatalf("SyncInstallLog = (%d, %v), want 3", H, err) + } + crashRecoveryHardeningStore(t, s) + a, b := slotsV3(t, path) + newest := a + if b.SlotGen > a.SlotGen { + newest = b + } + if newest.W != 3 || newest.BaseState != BaseInstalling || newest.BaseInstallID != idA { + t.Fatalf("newest slot after the ack: W %d state %d, want W 3 installing under A", newest.W, newest.BaseState) + } + r, err := openUnmappedWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + if _, err := r.Recover(); !errors.Is(err, ErrBaseIncomplete) || errors.Is(err, ErrInstallSuffixDamaged) { + t.Fatalf("reopen: err = %v, want an intact ErrBaseIncomplete", err) + } +} + +// codex01 row 10a P1 (the #172 ack boundary): an append of the same install +// that fails and latches the store after SyncInstallLog's publication and +// before its ack refuses the ack: no H, no volatile acknowledged frontier. +// The held hook runs that append with a failing pwrite (the real latch). Mutant: no +// final locked sticky check returns H and fails here. +func TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + h := beginV3(t, s, 0, idA) + if err := h.ApplyInstallEntry(1, blk(1), 1); err != nil { + t.Fatal(err) + } + var appendErr error + s.v3.testInstallLogBeforeAck = func() { + // The queued same-ID append runs here, and its pwrite fails. + s.v3.w.writeAt = func([]byte, int64) (int, error) { return 0, errors.New("injected pwrite failure") } + appendErr = h.ApplyInstallEntry(2, blk(2), 2) + } + wack := s.v3.wack.Load() + H, err := s.SyncInstallLog(idA) + if err == nil || H != 0 { + t.Fatalf("SyncInstallLog across a latched fault = (%d, %v), want (0, the fault)", H, err) + } + if !errors.Is(appendErr, errWALPwrite) { + t.Fatalf("setup: the held append returned %v, want a pwrite failure", appendErr) + } + if s.v3.wack.Load() != wack { + t.Fatalf("acknowledged frontier moved to %d across the fault", s.v3.wack.Load()) + } +} diff --git a/seaweed-block/core/storage/chunk_bitmap_file.go b/seaweed-block/core/storage/legacy_c11_file_fixture_test.go similarity index 80% rename from seaweed-block/core/storage/chunk_bitmap_file.go rename to seaweed-block/core/storage/legacy_c11_file_fixture_test.go index e7d78dc3dd..a7fff5ce8e 100644 --- a/seaweed-block/core/storage/chunk_bitmap_file.go +++ b/seaweed-block/core/storage/legacy_c11_file_fixture_test.go @@ -1,6 +1,7 @@ package storage -// FileChunkBitmapStore is the production chunkBitmapStore: one state file +// legacyC11FileStore preserves the retired C11 file codec for historical tests. +// It is compiled only into this package's tests: one state file // (header + dirty-since-HEAD chunks, with a SHA-256 over its body) replaced // atomically on every change, plus an append-only delta log with one JSON // record per closed HEAD period. Every method is durable on return. @@ -17,7 +18,7 @@ import ( "sync" ) -type FileChunkBitmapStore struct { +type legacyC11FileStore struct { path string mu sync.Mutex @@ -27,10 +28,10 @@ type FileChunkBitmapStore struct { dirty []uint64 } -// NewFileChunkBitmapStore returns a store at path (the delta log is +// newLegacyC11FileStore returns a store at path (the delta log is // path + ".deltas"). -func NewFileChunkBitmapStore(path string) *FileChunkBitmapStore { - return &FileChunkBitmapStore{path: path} +func newLegacyC11FileStore(path string) *legacyC11FileStore { + return &legacyC11FileStore{path: path} } type chunkBitmapFile struct { @@ -44,7 +45,7 @@ type chunkBitmapEnvelope struct { SHA256 string `json:"sha256"` } -func (b *FileChunkBitmapStore) loadLocked() error { +func (b *legacyC11FileStore) loadLocked() error { if b.loaded { return nil } @@ -72,7 +73,7 @@ func (b *FileChunkBitmapStore) loadLocked() error { return nil } -func (b *FileChunkBitmapStore) writeLocked(hdr chunkBitmapHeader, dirty []uint64) error { +func (b *legacyC11FileStore) writeLocked(hdr chunkBitmapHeader, dirty []uint64) error { body, err := json.Marshal(chunkBitmapFile{Version: 1, Header: hdr, Dirty: dirty}) if err != nil { return err @@ -93,7 +94,7 @@ func (b *FileChunkBitmapStore) writeLocked(hdr chunkBitmapHeader, dirty []uint64 return nil } -func (b *FileChunkBitmapStore) Load() (chunkBitmapHeader, []uint64, bool, error) { +func (b *legacyC11FileStore) Load() (chunkBitmapHeader, []uint64, bool, error) { b.mu.Lock() defer b.mu.Unlock() if err := b.loadLocked(); err != nil { @@ -105,7 +106,7 @@ func (b *FileChunkBitmapStore) Load() (chunkBitmapHeader, []uint64, bool, error) return b.hdr, append([]uint64(nil), b.dirty...), true, nil } -func (b *FileChunkBitmapStore) Save(dirty []uint64) error { +func (b *legacyC11FileStore) Save(dirty []uint64) error { b.mu.Lock() defer b.mu.Unlock() if err := b.loadLocked(); err != nil { @@ -114,7 +115,7 @@ func (b *FileChunkBitmapStore) Save(dirty []uint64) error { return b.writeLocked(b.hdr, dirty) } -func (b *FileChunkBitmapStore) WriteHeader(hdr chunkBitmapHeader) error { +func (b *legacyC11FileStore) WriteHeader(hdr chunkBitmapHeader) error { b.mu.Lock() defer b.mu.Unlock() if err := b.loadLocked(); err != nil { @@ -123,7 +124,7 @@ func (b *FileChunkBitmapStore) WriteHeader(hdr chunkBitmapHeader) error { return b.writeLocked(hdr, b.dirty) } -func (b *FileChunkBitmapStore) Reset(hdr chunkBitmapHeader, stillDirty []uint64, delta chunkDelta) error { +func (b *legacyC11FileStore) Reset(hdr chunkBitmapHeader, stillDirty []uint64, delta chunkDelta) error { b.mu.Lock() defer b.mu.Unlock() if err := b.loadLocked(); err != nil { @@ -152,7 +153,7 @@ func (b *FileChunkBitmapStore) Reset(hdr chunkBitmapHeader, stillDirty []uint64, } // Deltas returns the archived delta records, oldest first. -func (b *FileChunkBitmapStore) Deltas() ([]chunkDelta, error) { +func (b *legacyC11FileStore) Deltas() ([]chunkDelta, error) { raw, err := os.ReadFile(b.path + ".deltas") if errors.Is(err, os.ErrNotExist) { return nil, nil @@ -174,4 +175,4 @@ func (b *FileChunkBitmapStore) Deltas() ([]chunkDelta, error) { return out, nil } -var _ chunkBitmapStore = (*FileChunkBitmapStore)(nil) +var _ chunkBitmapStore = (*legacyC11FileStore)(nil) diff --git a/seaweed-block/core/storage/legacy_fixture_isolation_test.go b/seaweed-block/core/storage/legacy_fixture_isolation_test.go new file mode 100644 index 0000000000..71ce5bb712 --- /dev/null +++ b/seaweed-block/core/storage/legacy_fixture_isolation_test.go @@ -0,0 +1,119 @@ +package storage + +import ( + "context" + "encoding/json" + "go/ast" + "go/parser" + "go/token" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// The old engine remains only for explicit fixtures until row 14a. The +// production import closure must not bring in its frozen tool/test package, +// and no production source may call the legacy constructor chain. +func TestLegacyFixtureIsolation(t *testing.T) { + entries, err := os.ReadDir(".") + if err != nil { + t.Fatal(err) + } + forbidden := map[string]bool{"createLegacyWALStoreWithOptions": true, "openLegacyWALStoreWithOptions": true, "openLegacyReadOnlyWithOptions": true} + for _, e := range entries { + n := e.Name() + if e.IsDir() || !strings.HasSuffix(n, ".go") || strings.HasSuffix(n, "_test.go") || n == "format_v3_test_support.go" { + continue + } + f, err := parser.ParseFile(token.NewFileSet(), n, nil, 0) + if err != nil { + t.Fatal(err) + } + for _, name := range legacyConstructorReferences(f, forbidden) { + t.Errorf("production source %s references legacy fixture %s", e.Name(), name) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, "go", "list", "-deps", "-json", "./core/storage") + cmd.Dir = filepath.Join("..", "..") + cmd.WaitDelay = 2 * time.Second + out, err := cmd.Output() + if err != nil { + t.Fatalf("default production transitive import graph: %v", err) + } + dec := json.NewDecoder(strings.NewReader(string(out))) + foundStorage := false + for dec.More() { + var p struct { + ImportPath string + GoFiles []string + } + if err := dec.Decode(&p); err != nil { + t.Fatal(err) + } + if strings.Contains(p.ImportPath, "/internal/v2legacy") { + t.Errorf("unexpected frozen import %s", p.ImportPath) + } + if p.ImportPath == "github.com/seaweedfs/seaweed-block/core/storage" { + foundStorage = true + for _, n := range p.GoFiles { + if n == "format_v3_test_support.go" || n == "legacy_c11_file_fixture_test.go" { + t.Fatal("test constructors entered default production import closure") + } + } + } + } + if !foundStorage { + t.Fatal("production dependency graph did not contain core/storage") + } +} + +func legacyConstructorReferences(f *ast.File, forbidden map[string]bool) []string { + var refs []string + // A constructor declaration is retained for test linking, but every use + // (including function values, aliases and arguments) is forbidden. + declarations := map[*ast.Ident]bool{} + for _, decl := range f.Decls { + if fn, ok := decl.(*ast.FuncDecl); ok { + declarations[fn.Name] = true + } + } + ast.Inspect(f, func(n ast.Node) bool { + if id, ok := n.(*ast.Ident); ok && forbidden[id.Name] && !declarations[id] { + refs = append(refs, id.Name) + } + return true + }) + return refs +} + +func TestLegacyFixtureIsolationRejectsFunctionValues(t *testing.T) { + const name = "createLegacyWALStoreWithOptions" + for _, body := range []string{ + "func use() { createLegacyWALStoreWithOptions() }", + "var constructor = createLegacyWALStoreWithOptions", + "func use() { constructor := createLegacyWALStoreWithOptions; constructor() }", + "func use() { accept(createLegacyWALStoreWithOptions) }", + } { + t.Run(body, func(t *testing.T) { + f, err := parser.ParseFile(token.NewFileSet(), "production.go", "package storage\n"+body, 0) + if err != nil { + t.Fatal(err) + } + if refs := legacyConstructorReferences(f, map[string]bool{name: true}); len(refs) != 1 { + t.Fatalf("legacy constructor reference escaped guard: %v", refs) + } + }) + } + f, err := parser.ParseFile(token.NewFileSet(), "legacy.go", "package storage\nfunc createLegacyWALStoreWithOptions() {}", 0) + if err != nil { + t.Fatal(err) + } + if refs := legacyConstructorReferences(f, map[string]bool{name: true}); len(refs) != 0 { + t.Fatalf("declaration is not a use: %v", refs) + } +} diff --git a/seaweed-block/core/storage/legacy_fixture_test.go b/seaweed-block/core/storage/legacy_fixture_test.go new file mode 100644 index 0000000000..1efabc06c8 --- /dev/null +++ b/seaweed-block/core/storage/legacy_fixture_test.go @@ -0,0 +1,14 @@ +package storage + +// TODO(format-v3 row 14a): relocate or retire only the inventory-listed v2 +// engine controls after the named v3 replacements and migration receipts pass. +// These explicit fixture constructors are never production selectors. +func createLegacyWALStoreForTest(path string, blocks uint32, blockSize int) (*WALStore, error) { + return createLegacyWALStoreWithOptions(path, blocks, blockSize, WALStoreOptions{}) +} +func openLegacyWALStoreForTest(path string) (*WALStore, error) { + return openLegacyWALStoreWithOptions(path, WALStoreOptions{}) +} +func openLegacyReadOnlyForTest(path string) (*WALStoreReader, error) { + return openLegacyReadOnlyWithOptions(path, WALStoreOptions{}) +} diff --git a/seaweed-block/core/storage/logical_storage.go b/seaweed-block/core/storage/logical_storage.go index b910539d27..9fb9a4176d 100644 --- a/seaweed-block/core/storage/logical_storage.go +++ b/seaweed-block/core/storage/logical_storage.go @@ -1,5 +1,16 @@ package storage +import ( + "context" + "fmt" +) + +// ContextReader is an optional request-aware read seam. One caller context +// may cover several blocks, so implementations must not reset its deadline. +type ContextReader interface { + ReadContext(context.Context, uint32) ([]byte, error) +} + // LogicalStorage is the V3 persistence-seam contract. It separates the // "what data exists, what frontier is durable" question (storage) from // the "what does the engine decide" question (semantic core). The @@ -143,8 +154,9 @@ type LogicalStorage interface { WriteExtentDirect(lba uint32, data []byte) error // AllBlocks snapshots every written LBA's current bytes. Used by - // the rebuild server to enumerate what to ship. - AllBlocks() map[uint32][]byte + // the rebuild server to enumerate what to ship. Any read error fails + // the whole snapshot; callers must not ship a partial image. + AllBlocks() (map[uint32][]byte, error) // ScanLBAs is the T4c-2 tier-1 recovery contract. Emits a // RecoveryEntry callback for each modification the substrate @@ -211,11 +223,86 @@ type LogicalStorage interface { Close() error } -// BaseInstallPreparer is an optional rebuild capability for substrates that -// stage BASE snapshots before making them authoritative. Recovery callers -// invoke it once before the first BASE block (or an empty BASE completion). +// InstallHandle is the only path for one BASE install's mutations (format +// bump v3, DESIGN r17.3.1 section 8.7): the BASE extent writes, the +// install-lane WAL applies and the completion, all bound to the install's +// ID. On a v3 store a handle whose ID has been superseded changes nothing +// and returns ErrInstallSuperseded. +type InstallHandle interface { + WriteBase(lba uint32, data []byte) error + ApplyInstallEntry(lba uint32, data []byte, lsn uint64) error + // MarkBaseComplete is DESIGN 8.2: on any error the install stays + // incomplete and the error propagates. + MarkBaseComplete() error +} + +// BaseInstallPreparer is the BASE install seam (DESIGN 8.1, 8.7): the begin +// of one install at baseLSN under a fresh, random, nonzero installID. type BaseInstallPreparer interface { - BeginBaseInstall() error + BeginBaseInstall(baseLSN uint64, installID [16]byte) (InstallHandle, error) +} + +// BaseStager is the legacy optional rebuild capability for substrates that +// stage BASE snapshots before making them authoritative (parallelwal). The +// legacy install handle invokes it once, before the first BASE block or an +// empty BASE completion, exactly when callers invoked it before the seam. +type BaseStager interface { + BeginBaseStage() error +} + +// BeginInstall begins one BASE install on store: through its seam when it +// has one, otherwise with the legacy handle. +func BeginInstall(store LogicalStorage, baseLSN uint64, installID [16]byte) (InstallHandle, error) { + if p, ok := store.(BaseInstallPreparer); ok { + return p.BeginBaseInstall(baseLSN, installID) + } + return NewLegacyInstallHandle(store, baseLSN), nil +} + +// NewLegacyInstallHandle returns the pre-v3 install behaviour behind the +// handle: WriteBase is WriteExtentDirect, ApplyInstallEntry is ApplyEntry and +// MarkBaseComplete is AdvanceFrontier(baseLSN). A BaseStager store stages +// lazily, before the first WriteBase or MarkBaseComplete. +func NewLegacyInstallHandle(store LogicalStorage, baseLSN uint64) InstallHandle { + return &legacyInstallHandle{store: store, baseLSN: baseLSN} +} + +type legacyInstallHandle struct { + store LogicalStorage + baseLSN uint64 + staged bool +} + +func (h *legacyInstallHandle) stage() error { + if h.staged { + return nil + } + if st, ok := h.store.(BaseStager); ok { + if err := st.BeginBaseStage(); err != nil { + return fmt.Errorf("prepare BASE install: %w", err) + } + } + h.staged = true + return nil +} + +func (h *legacyInstallHandle) WriteBase(lba uint32, data []byte) error { + if err := h.stage(); err != nil { + return err + } + return h.store.WriteExtentDirect(lba, data) +} + +func (h *legacyInstallHandle) ApplyInstallEntry(lba uint32, data []byte, lsn uint64) error { + return h.store.ApplyEntry(lba, data, lsn) +} + +func (h *legacyInstallHandle) MarkBaseComplete() error { + if err := h.stage(); err != nil { + return err + } + h.store.AdvanceFrontier(h.baseLSN) + return nil } // WriteBatcher is an optional LogicalStorage extension for contiguous @@ -225,3 +312,12 @@ type BaseInstallPreparer interface { type WriteBatcher interface { WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error) } + +// ContextWriter and ContextWriteBatcher preserve one caller deadline across +// storage admission. Implementations must not abandon already-started I/O. +type ContextWriter interface { + WriteContext(context.Context, uint32, []byte) (uint64, error) +} +type ContextWriteBatcher interface { + WriteBatchContext(context.Context, uint32, [][]byte) ([]uint64, error) +} diff --git a/seaweed-block/core/storage/memorywal/store.go b/seaweed-block/core/storage/memorywal/store.go index 58d23617c2..4651dc8999 100644 --- a/seaweed-block/core/storage/memorywal/store.go +++ b/seaweed-block/core/storage/memorywal/store.go @@ -303,7 +303,7 @@ func (s *Store) WriteExtentDirect(lba uint32, data []byte) error { // AllBlocks returns last-writer-wins per LBA across retained records, // filtering out all-zero blocks (matches the LogicalStorage contract). -func (s *Store) AllBlocks() map[uint32][]byte { +func (s *Store) AllBlocks() (map[uint32][]byte, error) { s.mu.RLock() defer s.mu.RUnlock() latest := make(map[uint32][]byte) @@ -329,7 +329,7 @@ func (s *Store) AllBlocks() map[uint32][]byte { delete(latest, lba) } } - return latest + return latest, nil } // ScanLBAs is V2-faithful: emits each retained WAL record with its diff --git a/seaweed-block/core/storage/memorywal/store_test.go b/seaweed-block/core/storage/memorywal/store_test.go index 1cbeffa22d..4f97e3d6b6 100644 --- a/seaweed-block/core/storage/memorywal/store_test.go +++ b/seaweed-block/core/storage/memorywal/store_test.go @@ -316,10 +316,14 @@ func TestAllBlocks_LastWriterWins_FiltersZeros(t *testing.T) { s := NewStore(numBlocks, blockSize) _, _ = s.Write(0, mkBlock(0xAA)) _, _ = s.Write(1, mkBlock(0xBB)) - _, _ = s.Write(0, mkBlock(0xCC)) // overwrites lba 0 + _, _ = s.Write(0, mkBlock(0xCC)) // overwrites lba 0 _, _ = s.Write(2, make([]byte, blockSize)) // zero block — should be filtered - all := s.AllBlocks() + all, snapshotErr := s.AllBlocks() + + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(all) != 2 { t.Fatalf("AllBlocks: got %d want 2 (lba 2 should be filtered as zero)", len(all)) } diff --git a/seaweed-block/core/storage/migrate_v3.go b/seaweed-block/core/storage/migrate_v3.go new file mode 100644 index 0000000000..89c12c0e6b --- /dev/null +++ b/seaweed-block/core/storage/migrate_v3.go @@ -0,0 +1,211 @@ +package storage + +import ( + "crypto/rand" + "crypto/sha256" + "errors" + "fmt" + "math" + "os" +) + +// Tool-only exports for the offline migration `sw-block migrate-v3` (format +// bump v3, DESIGN r17.4 section 10.1; plan row 13b). They reuse the row-1 +// slot codec and the row-6 map codec; there is no second encoder. Nothing +// here opens, recovers or serves a store, and the v3 open code calls none of +// it. + +var ( + // ErrMigrateGeometry: the v2 geometry cannot be expressed as v3 without + // moving data (DESIGN 10.1 precondition 4). + ErrMigrateGeometry = errors.New("storage: v2 geometry cannot be migrated in place to v3") +) + +// MigrationSlotAOffset and MigrationSlotBOffset are the v3 slot positions. +const ( + MigrationSlotAOffset = slotAOffsetV3 + MigrationSlotBOffset = slotBOffsetV3 + MigrationSlotSize = slotSizeV3 + // migratedWALMinV3 is the provisional impl-3 minimum WAL size for a + // migrated volume: at least 64 KiB and two single-block records. + migratedWALMinV3 = 64 * 1024 +) + +// MigrationSourceV3 is what the tool read from the v2 superblock. +type MigrationSourceV3 struct { + UUID [16]byte + VolumeSize uint64 + ExtentSize uint32 + BlockSize uint32 + OldWALOffset uint64 // must be 4096 + OldWALSize uint64 + CreatedAt uint64 + CheckpointLSN uint64 + ChunkBlocks uint64 // the map's chunk geometry (the provider's) +} + +// MigrationPlanV3 is the v3 image of a migration: the descriptor slot +// images in their write order and the new descriptor's hash. +type MigrationPlanV3 struct { + PreparedB []byte // step 4: slot B, slotGen 1, MigrationPhase prepared + CommittedA []byte // step 5: slot A, slotGen 2, phase 0 (the commit point) + RolloverB []byte // step 6: slot B, slotGen 3, phase 0 + // DescriptorHash is the SHA-256 of CommittedA, printed at step 8. + DescriptorHash [32]byte +} + +// migrationDescriptorV3 is the v3 descriptor for src (DESIGN 10.1 step 4): +// WALOffset 8192 and WALSize = old WALSize - 4096, so the extent base +// WALOffset + WALSize is unchanged; CheckpointLSN = W = the v2 checkpoint; +// an empty cursor space; BaseState none; WMode C. +func migrationDescriptorV3(src MigrationSourceV3) (descriptorV3, error) { + if src.OldWALOffset != superblockSize { + return descriptorV3{}, fmt.Errorf("%w: v2 WALOffset %d, want %d", ErrMigrateGeometry, src.OldWALOffset, superblockSize) + } + if src.BlockSize == 0 || src.OldWALSize <= slotSizeV3 { + return descriptorV3{}, fmt.Errorf("%w: v2 WAL size %d", ErrMigrateGeometry, src.OldWALSize) + } + walSize := src.OldWALSize - slotSizeV3 + if walSize%uint64(src.BlockSize) != 0 || walSize < migratedWALMinV3 || + walSize < 2*(walEntryHeaderSizeV3+uint64(src.BlockSize)) { + return descriptorV3{}, fmt.Errorf("%w: v3 WAL size %d is not block aligned or below the minimum", ErrMigrateGeometry, walSize) + } + if src.CheckpointLSN > counterMaxV3 { + return descriptorV3{}, fmt.Errorf("%w: checkpoint %d", ErrMigrateGeometry, src.CheckpointLSN) + } + // The checked extent end (codex01 row 13b P1): the same bounds the slot + // validation applies, here, before any backup or sidecar write. + if src.VolumeSize == 0 || src.ExtentSize == 0 || src.VolumeSize%uint64(src.BlockSize) != 0 { + return descriptorV3{}, fmt.Errorf("%w: volume %d, extent %d, block %d", ErrMigrateGeometry, src.VolumeSize, src.ExtentSize, src.BlockSize) + } + if end, ok := checkedAddV3(walOffsetV3, walSize); !ok { + return descriptorV3{}, fmt.Errorf("%w: the WAL region overflows", ErrMigrateGeometry) + } else if fileEnd, ok := checkedAddV3(end, src.VolumeSize); !ok || fileEnd > math.MaxInt64 { + return descriptorV3{}, fmt.Errorf("%w: the extent region overflows", ErrMigrateGeometry) + } + d := descriptorV3{ + ImplKind: ImplKindWALStore, ImplVersion: walStoreImplVersion3, UUID: src.UUID, + VolumeSize: src.VolumeSize, ExtentSize: src.ExtentSize, BlockSize: src.BlockSize, + WALOffset: walOffsetV3, WALSize: walSize, CreatedAt: src.CreatedAt, + CheckpointLSN: src.CheckpointLSN, W: src.CheckpointLSN, WMode: WModeLagged, + MapFormatID: mapFormatIDV1, MapGeneration: 1, SlotGen: 1, + } + if walOffsetV3+walSize != src.OldWALOffset+src.OldWALSize { + return descriptorV3{}, fmt.Errorf("%w: the extent base would move", ErrMigrateGeometry) + } + if _, err := mapShapeForV3(d, src.ChunkBlocks); err != nil { + return descriptorV3{}, fmt.Errorf("%w: map geometry: %w", ErrMigrateGeometry, err) + } + return d, nil +} + +// ValidateMigrationV3 checks precondition 4 (geometry) without writing. +func ValidateMigrationV3(src MigrationSourceV3) error { + _, err := migrationDescriptorV3(src) + return err +} + +// PrepareMigrationV3 runs DESIGN 10.1 step 3 and builds the slot images of +// steps 4 to 6. It (re)creates the initial map sidecar at mapPath durably: +// generation 1, every chunk UNKNOWN with its inherited checkpoint frontier, +// coveredCheckpoint = +// the v2 checkpoint (a fully flushed WAL is not remote-clean). The slots +// carry a fresh random nonce and the map fields of that root. It writes +// nothing to the store file. +func PrepareMigrationV3(mapPath string, src MigrationSourceV3) (MigrationPlanV3, error) { + d, err := migrationDescriptorV3(src) + if err != nil { + return MigrationPlanV3{}, err + } + for _, b := range [][]byte{d.Nonce[:], d.MapLineage[:]} { + for b2 := b; ; { + if _, err := rand.Read(b2); err != nil { + return MigrationPlanV3{}, err + } + if !allZero(b2) { + break + } + } + } + if err := os.Remove(mapPath); err != nil && !errors.Is(err, os.ErrNotExist) { + return MigrationPlanV3{}, err // a rerun rewrites the map (10.1 rerun table) + } + m, err := createChunkLSNMapV3(mapPath, d, src.ChunkBlocks) + if err != nil { + return MigrationPlanV3{}, err + } + shape, err := mapShapeForV3(d, src.ChunkBlocks) + if err != nil { + _ = m.Close() + return MigrationPlanV3{}, err + } + entries := make([]chunkLSNEntryV3, int(shape.chunks)) + for i := range entries { + entries[i].Unknown = true + entries[i].LSN = src.CheckpointLSN + } + c, err := m.Prepare(1, src.CheckpointLSN, entries, nil) + if err = errors.Join(err, m.Close()); err != nil { + return MigrationPlanV3{}, err + } + d = c.descriptor(d) + d.SlotGen, d.MigrationPhase = 1, MigrationPrepared + if err := d.validate(nil); err != nil { + return MigrationPlanV3{}, err + } + var plan MigrationPlanV3 + plan.PreparedB = d.encode() + d.SlotGen, d.MigrationPhase = 2, MigrationNormal + if err := d.validate(nil); err != nil { + return MigrationPlanV3{}, err + } + plan.CommittedA = d.encode() + plan.DescriptorHash = sha256.Sum256(plan.CommittedA) + d.SlotGen = 3 + plan.RolloverB = d.encode() + return plan, nil +} + +// RolloverSlotV3 is step 6 for a rerun that finds a committed slot A of +// slotGen 2: the same descriptor at slotGen 3, phase 0. +func RolloverSlotV3(committedA []byte) ([]byte, error) { + d, err := decodeSlotV3(committedA, nil) + if err != nil { + return nil, err + } + if d.MigrationPhase != MigrationNormal || d.SlotGen != 2 { + return nil, fmt.Errorf("%w: slot A is not a fresh migration commit", errSuperblockInvalid) + } + d.SlotGen = 3 + return d.encode(), nil +} + +// MigrationSlotStateV3 classifies one raw v3 slot for the rerun table. +type MigrationSlotStateV3 int + +const ( + MigrationSlotInvalid MigrationSlotStateV3 = iota // not a valid v3 slot + MigrationSlotPrepared // valid, MigrationPhase prepared + MigrationSlotCommitted // valid and selectable (phase 0) +) + +// ClassifyMigrationSlotV3 reports a slot's state and slotGen. +func ClassifyMigrationSlotV3(raw []byte) (MigrationSlotStateV3, uint64) { + d, err := decodeSlotV3(raw, nil) + if err != nil { + return MigrationSlotInvalid, 0 + } + if d.MigrationPhase == MigrationPrepared { + return MigrationSlotPrepared, d.SlotGen + } + return MigrationSlotCommitted, d.SlotGen +} + +func allZero(b []byte) bool { + for _, x := range b { + if x != 0 { + return false + } + } + return true +} diff --git a/seaweed-block/core/storage/parallelwal/store.go b/seaweed-block/core/storage/parallelwal/store.go index 4cf089b720..7c3139a956 100644 --- a/seaweed-block/core/storage/parallelwal/store.go +++ b/seaweed-block/core/storage/parallelwal/store.go @@ -14,6 +14,7 @@ import ( "sync" "time" + "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -134,6 +135,9 @@ func CreateStore(path string, numBlocks uint32, blockSize int) (*Store, error) { func CreateStoreWithConfig(path string, cfg Config) (*Store, error) { cfg = normalizeConfig(cfg) + if err := geometry.ValidateBlockGeometry(uint64(cfg.NumBlocks), uint64(cfg.BlockSize)); err != nil { + return nil, err + } h, err := headerForConfig(cfg) if err != nil { return nil, err @@ -1205,10 +1209,10 @@ func (s *Store) ApplyEntry(lba uint32, data []byte, lsn uint64) error { return err } -// BeginBaseInstall resets the inactive extent used for the next rebuild. +// BeginBaseStage resets the inactive extent used for the next rebuild. // The active extent remains authoritative until Sync publishes a header that // atomically switches ActiveExtent. -func (s *Store) BeginBaseInstall() error { +func (s *Store) BeginBaseStage() error { s.syncMu.Lock() defer s.syncMu.Unlock() return s.resetBaseStageUnderSync() @@ -1326,16 +1330,19 @@ func (s *Store) resetBaseStageUnderSync() error { return nil } -func (s *Store) AllBlocks() map[uint32][]byte { +func (s *Store) AllBlocks() (map[uint32][]byte, error) { out := make(map[uint32][]byte) zero := make([]byte, s.blockSize) for lba := uint32(0); lba < s.numBlocks; lba++ { data, err := s.Read(lba) - if err == nil && !bytes.Equal(data, zero) { + if err != nil { + return nil, fmt.Errorf("snapshot LBA %d: %w", lba, err) + } + if !bytes.Equal(data, zero) { out[lba] = data } } - return out + return out, nil } func (s *Store) ScanLBAs(fromLSN uint64, fn func(storage.RecoveryEntry) error) error { @@ -1418,6 +1425,6 @@ func (s *Store) extentOffsetFor(extent int, lba uint32) int64 { } var ( - _ storage.LogicalStorage = (*Store)(nil) - _ storage.BaseInstallPreparer = (*Store)(nil) + _ storage.LogicalStorage = (*Store)(nil) + _ storage.BaseStager = (*Store)(nil) ) diff --git a/seaweed-block/core/storage/parallelwal/store_test.go b/seaweed-block/core/storage/parallelwal/store_test.go index 3de82f5df0..b3afd5b6f0 100644 --- a/seaweed-block/core/storage/parallelwal/store_test.go +++ b/seaweed-block/core/storage/parallelwal/store_test.go @@ -1095,7 +1095,7 @@ func TestBaseExtentHeaderFailureKeepsPriorAcknowledgedExtent(t *testing.T) { t.Fatalf("baseline checkpoint=%d activeExtent=%d want=(2,0)", s.checkpointLSN, s.activeExtent) } - if err := s.BeginBaseInstall(); err != nil { + if err := s.BeginBaseStage(); err != nil { t.Fatal(err) } if err := s.WriteExtentDirect(0, testBlock(0x77, s.BlockSize())); err != nil { @@ -1132,13 +1132,13 @@ func TestBaseExtentHeaderFailureKeepsPriorAcknowledgedExtent(t *testing.T) { func TestBeginBaseInstallClearsAbortedStage(t *testing.T) { s, path := createTestStore(t) - if err := s.BeginBaseInstall(); err != nil { + if err := s.BeginBaseStage(); err != nil { t.Fatal(err) } if err := s.WriteExtentDirect(3, testBlock(0x55, s.BlockSize())); err != nil { t.Fatal(err) } - if err := s.BeginBaseInstall(); err != nil { + if err := s.BeginBaseStage(); err != nil { t.Fatal(err) } s.AdvanceFrontier(10) @@ -1208,7 +1208,7 @@ func TestAdvanceFrontierWithoutBaseStageKeepsExistingData(t *testing.T) { func TestNextBaseStagePreservesHeaderFallbackToCurrentExtent(t *testing.T) { s, path := createTestStore(t) - if err := s.BeginBaseInstall(); err != nil { + if err := s.BeginBaseStage(); err != nil { t.Fatal(err) } if err := s.WriteExtentDirect(4, testBlock(0x66, s.BlockSize())); err != nil { @@ -1222,7 +1222,7 @@ func TestNextBaseStagePreservesHeaderFallbackToCurrentExtent(t *testing.T) { t.Fatalf("first BASE activeExtent=%d want=1", s.activeExtent) } - if err := s.BeginBaseInstall(); err != nil { + if err := s.BeginBaseStage(); err != nil { t.Fatal(err) } s.mu.RLock() diff --git a/seaweed-block/core/storage/parallelwal/volume_size_limit_test.go b/seaweed-block/core/storage/parallelwal/volume_size_limit_test.go new file mode 100644 index 0000000000..13efe63057 --- /dev/null +++ b/seaweed-block/core/storage/parallelwal/volume_size_limit_test.go @@ -0,0 +1,23 @@ +package parallelwal + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestCreateCapacityBeforeFilesystem(t *testing.T) { + parent := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(parent, []byte("unchanged"), 0600); err != nil { + t.Fatal(err) + } + s, err := CreateStore(filepath.Join(parent, "volume"), ^uint32(0), 8192) + if s != nil { + s.Close() + t.Fatal("created oversized image") + } + if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("capacity must precede filesystem: %v", err) + } +} diff --git a/seaweed-block/core/storage/recovery_v3.go b/seaweed-block/core/storage/recovery_v3.go new file mode 100644 index 0000000000..8e22c340cb --- /dev/null +++ b/seaweed-block/core/storage/recovery_v3.go @@ -0,0 +1,178 @@ +package storage + +import ( + "errors" + "fmt" +) + +// Impl-3 recovery decisions (format bump v3, DESIGN r15 sections 6.5 and +// 6.6; plan row 5). These are the pure parts: the scan start, the replay +// floor F, the contiguous prefix R with its end E, the R < W* decision for +// serving and installing descriptors, and the exact byte ranges of the drop +// fence. The record scan itself (nonce, cursor, lap and CRC trust order) is +// plan row 4; this file consumes its trusted records. + +// ErrInstallSuffixDamaged: an installing volume's acknowledged install-log +// suffix is missing or corrupt (R < W*). The volume stays not ready, the +// install cannot be resumed, and only a covering superseding install (new +// BaseLSN >= W) may proceed (DESIGN 6.5, 8.3). +var ErrInstallSuffixDamaged = errors.New("storage: v3 install-log suffix damaged; resume refused") + +// ErrBaseIncomplete: the descriptor is installing; the local image is not +// ready (DESIGN 8.3). It wraps ErrInstallSuffixDamaged and a WALIntegrity +// cause when the suffix is damaged. +var ErrBaseIncomplete = errors.New("storage: v3 BASE install incomplete; not ready") + +// scanStartV3 is where recovery starts reading (DESIGN 6.5 step 2): the +// retained tail, or max(BaseCursor, retainedTail) when a BASE state is set +// (G2: after installed the tail may have moved past BaseCursor). +func scanStartV3(d descriptorV3) uint64 { + if d.BaseState == BaseNone { + return d.RetainedTail + } + return max(d.BaseCursor, d.RetainedTail) +} + +// replayFloorV3 is F (DESIGN 6.5 step 1): LSNs at or below it need not be +// in this WAL. +func replayFloorV3(d descriptorV3) uint64 { + if d.BaseState == BaseNone { + return d.CheckpointLSN + } + return max(d.CheckpointLSN, d.BaseLSN) +} + +// trustedRecordV3 is one record of the trusted chain, in cursor order, as +// the row-4 scan returns it: its first and last LSN (a batch covers a +// range; padding carries none) and the logical cursor just past it. +type trustedRecordV3 struct { + FirstLSN uint64 // 0 for padding + LastLSN uint64 + End uint64 // logical cursor after this record + Padding bool +} + +// contiguousPrefixV3 computes R, the contiguous LSN prefix above F, and E, +// the logical cursor just past the last record that belongs to it (or to +// the already-covered region at or below F). Records above R are dropped by +// recovery. start is the scan start, used when no record qualifies. LSNs +// in a trusted chain only increase; a decrease is a contradiction and is +// refused. +func contiguousPrefixV3(start, F uint64, recs []trustedRecordV3) (R, E uint64, err error) { + R, E = F, start + var prev uint64 + for _, r := range recs { + if r.Padding { + // The loop returns at the first gap, so any padding seen here + // lies inside the kept run: E moves past it. + E = r.End + continue + } + if r.FirstLSN == 0 || r.LastLSN < r.FirstLSN { + return 0, 0, fmt.Errorf("storage: v3 recovery: malformed record span %d..%d", r.FirstLSN, r.LastLSN) + } + if prev != 0 && r.FirstLSN <= prev { + return 0, 0, fmt.Errorf("storage: v3 recovery: LSN %d after %d in one trusted chain", r.FirstLSN, prev) + } + prev = r.LastLSN + switch { + case r.LastLSN <= R: + E = r.End // at or below the floor or already counted: part of the kept run + case r.FirstLSN <= R+1: + R, E = r.LastLSN, r.End + default: + return R, E, nil // a gap: everything from here on is dropped + } + } + return R, E, nil +} + +// recoveryOutcomeV3 is what recovery does with the scan (DESIGN 6.5). +type recoveryOutcomeV3 struct { + Start, F, R, E, WStar uint64 + // Serve: replay records <= R, drop the rest, fence above E, publish + // retainedHead = E, admit. Installing: not ready (ErrBaseIncomplete); + // Damaged says whether resume is refused. + Serve bool + Installing bool + Damaged bool +} + +// decideRecoveryV3 applies DESIGN 6.5 steps 3 to 7. maxDurable is the +// highest DurableLSN among the trusted records. It returns an error only +// for a serving descriptor with R < W* (WALIntegrity, wal_corrupt); the +// installing outcomes are reported in the result, damaged or not, and the +// caller wraps them in ErrBaseIncomplete. +func decideRecoveryV3(d descriptorV3, recs []trustedRecordV3, maxDurable uint64) (recoveryOutcomeV3, error) { + o := recoveryOutcomeV3{Start: scanStartV3(d), F: replayFloorV3(d)} + R, E, err := contiguousPrefixV3(o.Start, o.F, recs) + if err != nil { + ierr := NewWALIntegrityFailure(err, err.Error()) + if d.BaseState == BaseInstalling { + // Installing keeps its outer not-ready outcome (DESIGN 8.3). + o.Installing, o.Damaged = true, true + return o, fmt.Errorf("%w: %w: %w", ErrBaseIncomplete, ErrInstallSuffixDamaged, ierr) + } + return o, ierr + } + o.R, o.E = R, E + o.WStar = max(d.W, maxDurable) + if d.BaseState == BaseInstalling { + o.Installing = true + o.Damaged = R < o.WStar + return o, nil + } + if R < o.WStar { + return o, NewWALIntegrityFailure(nil, fmt.Sprintf( + "v3 recovery: synced LSN missing or corrupt: contiguous prefix R=%d below W*=%d (F=%d, start=%d)", + R, o.WStar, o.F, o.Start)) + } + o.Serve = true + return o, nil +} + +// installingErrorV3 is the typed not-ready error for an installing outcome. +func installingErrorV3(o recoveryOutcomeV3) error { + if !o.Damaged { + return ErrBaseIncomplete + } + return fmt.Errorf("%w: %w (R=%d < W*=%d): %w", ErrBaseIncomplete, ErrInstallSuffixDamaged, o.R, o.WStar, + NewWALIntegrityFailure(nil, "acknowledged install-log record missing or corrupt")) +} + +// fenceRangeV3 is one physical byte range of the WAL region to zero, +// relative to the region start (the caller adds the WAL offset). +type fenceRangeV3 struct{ Off, Len uint64 } + +// fenceRangesV3 returns the exact physical byte ranges of the drop fence +// (DESIGN 6.6, r14): the logical interval [E, floor+walSize) mapped modulo +// the ring, split at the physical wrap into at most two ranges. Nothing +// outside it is touched: not [floor, E), and no rounding to pages. With +// sameNonce false (a reset between its two publications) the interval is +// empty, as it is when E >= floor+walSize. +func fenceRangesV3(E, floor, walSize uint64, sameNonce bool) ([]fenceRangeV3, error) { + if walSize == 0 { + return nil, fmt.Errorf("storage: v3 fence: zero WAL size") + } + if !sameNonce { + return nil, nil + } + if E < floor { + return nil, fmt.Errorf("storage: v3 fence: head %d below the reuse floor %d", E, floor) + } + // Interval-length arithmetic: floor+walSize is never formed, so a + // history ending at the last representable cursor still recovers + // (codex01 row 5 P2). The logical end may exceed 2^64-2; only the + // physical bytes matter. + used := E - floor + if used >= walSize { + return nil, nil + } + n := walSize - used // at most walSize + start := E % walSize + if start+n <= walSize { + return []fenceRangeV3{{Off: start, Len: n}}, nil + } + first := walSize - start + return []fenceRangeV3{{Off: start, Len: first}, {Off: 0, Len: n - first}}, nil +} diff --git a/seaweed-block/core/storage/recovery_v3_test.go b/seaweed-block/core/storage/recovery_v3_test.go new file mode 100644 index 0000000000..38098bfa2b --- /dev/null +++ b/seaweed-block/core/storage/recovery_v3_test.go @@ -0,0 +1,170 @@ +package storage + +import ( + "errors" + "reflect" + "testing" +) + +// Row 5 pure recovery decisions (DESIGN r15 6.5, 6.6). + +func rec(first, last, end uint64) trustedRecordV3 { + return trustedRecordV3{FirstLSN: first, LastLSN: last, End: end} +} + +func TestRecoveryV3ScanStartAndFloor(t *testing.T) { + d := descriptorV3{RetainedTail: 500, CheckpointLSN: 40} + if scanStartV3(d) != 500 || replayFloorV3(d) != 40 { + t.Fatalf("none: start %d floor %d, want 500 40", scanStartV3(d), replayFloorV3(d)) + } + d.BaseState, d.BaseLSN, d.BaseCursor = BaseInstalling, 100, 600 + if scanStartV3(d) != 600 || replayFloorV3(d) != 100 { + t.Fatalf("installing: start %d floor %d, want 600 100", scanStartV3(d), replayFloorV3(d)) + } + // G2: after installed the tail moved past BaseCursor; start at the tail. + d.BaseState, d.BaseCursor = BaseInstalled, 300 + if scanStartV3(d) != 500 { + t.Fatalf("installed with tail past BaseCursor: start %d, want 500 (max)", scanStartV3(d)) + } +} + +func TestRecoveryV3ContiguousPrefix(t *testing.T) { + cases := []struct { + name string + F uint64 + recs []trustedRecordV3 + R, E uint64 + isErr bool + }{ + {"empty", 10, nil, 10, 1000, false}, + {"contiguous", 10, []trustedRecordV3{rec(11, 11, 1100), rec(12, 12, 1200)}, 12, 1200, false}, + {"gap drops the rest", 10, []trustedRecordV3{rec(11, 11, 1100), rec(13, 13, 1300)}, 11, 1100, false}, + {"first record above the floor is a gap", 10, []trustedRecordV3{rec(12, 12, 1200)}, 10, 1000, false}, + {"records at or below F are kept", 10, []trustedRecordV3{rec(9, 9, 1050), rec(10, 10, 1080), rec(11, 11, 1100)}, 11, 1100, false}, + {"batch counts as its whole range", 10, []trustedRecordV3{rec(11, 14, 1400), rec(15, 15, 1500)}, 15, 1500, false}, + {"batch straddling the floor", 10, []trustedRecordV3{rec(9, 12, 1200), rec(13, 13, 1300)}, 13, 1300, false}, + {"padding inside the run moves E", 10, []trustedRecordV3{rec(11, 11, 1100), {Padding: true, End: 1150}, rec(12, 12, 1250)}, 12, 1250, false}, + {"padding at the end of the run", 10, []trustedRecordV3{rec(11, 11, 1100), {Padding: true, End: 1150}}, 11, 1150, false}, + {"repeated or decreasing LSN inside the run is refused", 10, []trustedRecordV3{rec(11, 11, 1100), rec(11, 11, 1200)}, 0, 0, true}, + {"malformed span is refused", 10, []trustedRecordV3{rec(12, 11, 1200)}, 0, 0, true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + R, E, err := contiguousPrefixV3(1000, c.F, c.recs) + if c.isErr { + if err == nil { + t.Fatal("want an error") + } + return + } + if err != nil { + t.Fatal(err) + } + if R != c.R || E != c.E { + t.Fatalf("R %d E %d, want R %d E %d", R, E, c.R, c.E) + } + }) + } +} + +func TestRecoveryV3Decision(t *testing.T) { + base := descriptorV3{RetainedTail: 1000, RetainedHead: 1000, CheckpointLSN: 10, W: 12} + recs := []trustedRecordV3{rec(11, 11, 1100), rec(12, 12, 1200), rec(13, 13, 1300)} + + o, err := decideRecoveryV3(base, recs, 12) + if err != nil || !o.Serve || o.R != 13 || o.E != 1300 { + t.Fatalf("serve: %+v %v, want serve R 13 E 1300", o, err) + } + // A synced record (12, W=12) corrupt: the chain stops at 11 < W*. + _, err = decideRecoveryV3(base, recs[:1], 12) + var rf *RecoveryFailure + if !errors.As(err, &rf) || rf.Kind != StorageRecoveryFailureWALIntegrity { + t.Fatalf("R < W: err = %v, want a WALIntegrity failure", err) + } + // W* takes the max DurableLSN of the trusted records. + low := base + low.W = 10 + if _, err := decideRecoveryV3(low, recs[:1], 12); err == nil { + t.Fatal("max DurableLSN 12 above R 11 was not refused") + } + // Installing: intact and damaged, never a bare wal_corrupt. + inst := base + inst.BaseState, inst.BaseLSN, inst.BaseCursor = BaseInstalling, 10, 1000 + inst.BaseInstallID[0] = 1 + o, err = decideRecoveryV3(inst, recs, 12) + if err != nil || !o.Installing || o.Damaged { + t.Fatalf("installing intact: %+v %v", o, err) + } + if !errors.Is(installingErrorV3(o), ErrBaseIncomplete) || errors.Is(installingErrorV3(o), ErrInstallSuffixDamaged) { + t.Fatal("intact installing error is not a plain ErrBaseIncomplete") + } + // A contradictory chain while installing keeps the outer not-ready + // outcome (codex01 row 5). + bad := []trustedRecordV3{rec(11, 11, 1100), rec(11, 11, 1200)} + if _, err := decideRecoveryV3(inst, bad, 11); !errors.Is(err, ErrBaseIncomplete) || !errors.Is(err, ErrInstallSuffixDamaged) { + t.Fatalf("contradictory installing chain: err = %v, want ErrBaseIncomplete wrapping ErrInstallSuffixDamaged", err) + } + o, err = decideRecoveryV3(inst, recs[:1], 12) + if err != nil || !o.Installing || !o.Damaged { + t.Fatalf("installing damaged: %+v %v (the check runs while installing)", o, err) + } + ie := installingErrorV3(o) + if !errors.Is(ie, ErrBaseIncomplete) || !errors.Is(ie, ErrInstallSuffixDamaged) || !errors.As(ie, &rf) || + rf.Kind != StorageRecoveryFailureWALIntegrity { + t.Fatalf("damaged installing error %v must wrap ErrBaseIncomplete, ErrInstallSuffixDamaged and WALIntegrity", ie) + } +} + +func TestRecoveryV3FenceRangesAreExact(t *testing.T) { + cases := []struct { + name string + E, floor, walSize uint64 + sameNonce bool + want []fenceRangeV3 + }{ + // codex03 r13 example: WALSize 256, fallback tail 0, selected 100, + // E 120. The fence is exactly [120, 256): physical [0, 100), which + // the fallback still references, is untouched. + {"floor bound, not the selected tail", 120, 0, 256, true, []fenceRangeV3{{120, 136}}}, + // Unaligned E after a barrier (70) and a one-block write (4166): + // never rounded to a page. + {"unaligned E 70", 70, 0, 1 << 20, true, []fenceRangeV3{{70, 1<<20 - 70}}}, + {"unaligned E 4166", 4166, 0, 1 << 20, true, []fenceRangeV3{{4166, 1<<20 - 4166}}}, + // The interval wraps physically: two exact ranges. + {"no wrap: logical [300,356) is physical [44,100)", 300, 100, 256, true, []fenceRangeV3{{44, 56}}}, + {"wrap: two exact ranges, [floor,E) untouched", 200, 100, 256, true, []fenceRangeV3{{200, 56}, {0, 100}}}, + {"unaligned end after a wrap", 5000, 4166, 4096, true, []fenceRangeV3{{904, 3192}, {0, 70}}}, + {"head at the end: nothing", 356, 100, 256, true, nil}, + {"mixed nonces: nothing", 120, 0, 256, false, nil}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got, err := fenceRangesV3(c.E, c.floor, c.walSize, c.sameNonce) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, c.want) { + t.Fatalf("ranges %v, want %v", got, c.want) + } + var total uint64 + for _, r := range got { + total += r.Len + } + if c.sameNonce && c.E < c.floor+c.walSize && total != c.floor+c.walSize-c.E { + t.Fatalf("fenced %d bytes, want exactly %d", total, c.floor+c.walSize-c.E) + } + }) + } + if _, err := fenceRangesV3(50, 100, 256, true); err == nil { + t.Fatal("a head below the floor was accepted") + } + // codex01 row 5 P2: a history ending at the last representable cursor + // still fences exactly; floor+WALSize is never formed. + got, err := fenceRangesV3(counterMaxV3, counterMaxV3-100, 256, true) + if err != nil { + t.Fatalf("terminal-cursor fence: %v", err) + } + if want := []fenceRangeV3{{254, 2}, {0, 154}}; !reflect.DeepEqual(got, want) { // 2^64-2 mod 256 = 254: wraps + t.Fatalf("terminal-cursor fence %v, want %v", got, want) + } +} diff --git a/seaweed-block/core/storage/reset_store_v3_test.go b/seaweed-block/core/storage/reset_store_v3_test.go new file mode 100644 index 0000000000..d06d8e9940 --- /dev/null +++ b/seaweed-block/core/storage/reset_store_v3_test.go @@ -0,0 +1,517 @@ +package storage + +import ( + "bytes" + "errors" + "io" + "os" + "sync" + "sync/atomic" + "testing" +) + +// Row 8 store controls for the reset transaction (DESIGN 8.6). The reset is +// dark: only these tests call it. + +// slotsV3 decodes both descriptor slots of the file at path. +func slotsV3(t *testing.T, path string) (a, b descriptorV3) { + t.Helper() + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + for i, off := range []int64{slotAOffsetV3, slotBOffsetV3} { + buf := make([]byte, slotSizeV3) + if _, err := f.ReadAt(buf, off); err != nil { + t.Fatal(err) + } + d, err := decodeSlotV3(buf, nil) + if err != nil { + t.Fatalf("slot %d: %v", i, err) + } + if i == 0 { + a = d + } else { + b = d + } + } + return a, b +} + +// checkpointedStoreV3 returns a store whose LSNs 1..n are acknowledged and +// checkpointed, with an empty dirty map: the reset precondition holds. +func checkpointedStoreV3(t *testing.T, n uint32) (*WALStore, string, func()) { + t.Helper() + s, path := newStoreV3(t, WModeLagged) + var once sync.Once + crash := func() { once.Do(func() { crashRecoveryHardeningStore(t, s) }) } + t.Cleanup(crash) + attachMapV3(t, s, path) + writeSynced(t, s, 1, n) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + if d := s.v3.pub.current(); d.CheckpointLSN != uint64(n) { + t.Fatalf("setup: checkpoint %d, want %d", d.CheckpointLSN, n) + } + return s, path, crash +} + +// attachMapV3 gives an unmapped fixture a real sidecar map and a candidate +// source for the flusher (the pattern of the row 5f clamp control), so a +// checkpoint can advance and a reopen binds the map. +func attachMapV3(t *testing.T, s *WALStore, path string) { + t.Helper() + m, err := createChunkLSNMapV3(path+".chunkmap", s.v3.pub.current(), 1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.Close() }) + entries := make([]chunkLSNEntryV3, s.NumBlocks()) + for i := range entries { + entries[i].Unknown = true + } + initial, err := m.Prepare(s.v3.pub.current().MapGeneration+1, 0, entries, nil) + if err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publish(&s.mu, nil, func(d *descriptorV3) error { *d = initial.descriptor(*d); return nil }); err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publish(&s.mu, nil, nil); err != nil { + t.Fatal(err) + } + s.v3.mapCandidate = func(cp uint64) (func(*descriptorV3) error, error) { + c, e := m.Prepare(s.v3.pub.current().MapGeneration+1, cp, entries, nil) + if e != nil { + return nil, e + } + return func(d *descriptorV3) error { *d = c.descriptor(*d); return nil }, nil + } +} + +func countSlotWritesV3(s *WALStore) *atomic.Int64 { + var n atomic.Int64 + s.v3.testBeforeSlotWrite = func() error { n.Add(1); return nil } + return &n +} + +func readAllV3(t *testing.T, s *WALStore, from, to uint32) { + t.Helper() + for lba := from; lba <= to; lba++ { + if got := readV3(t, s, lba); !bytes.Equal(got, blk(byte(lba))) { + t.Fatalf("LBA %d: got %x..., want %x...", lba, got[0], byte(lba)) + } + } +} + +func TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData(t *testing.T) { + t.Run("acknowledged but not checkpointed", func(t *testing.T) { + s, _ := newStoreV3(t, WModeLagged) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 2) + old := s.v3.pub.current() + writes := countSlotWritesV3(s) + if err := s.resetIncarnationV3(); !errors.Is(err, ErrResetNotPreserved) { + t.Fatalf("err = %v, want ErrResetNotPreserved", err) + } + if writes.Load() != 0 || s.v3.pub.current() != old { + t.Fatal("a refused reset wrote or published") + } + }) + t.Run("appended but not acknowledged", func(t *testing.T) { + s, _, _ := checkpointedStoreV3(t, 2) + if _, err := s.Write(3, blk(3)); err != nil { + t.Fatal(err) + } + old := s.v3.pub.current() + writes := countSlotWritesV3(s) + if err := s.resetIncarnationV3(); !errors.Is(err, ErrResetNotPreserved) { + t.Fatalf("err = %v, want ErrResetNotPreserved", err) + } + if writes.Load() != 0 || s.v3.pub.current() != old { + t.Fatal("a refused reset wrote or published") + } + }) + t.Run("checkpointed but the dirty map not yet released", func(t *testing.T) { + // The window between a checkpoint publication and the flusher's + // release of the covered dirty entries: an entry still names an + // old-incarnation WAL position a read would follow. + s, _, _ := checkpointedStoreV3(t, 2) + _, _, lsn, _, _ := s.dm.get(1) + s.dm.put(1, 0, max(lsn, 1), v3TestBlock) + old := s.v3.pub.current() + writes := countSlotWritesV3(s) + if err := s.resetIncarnationV3(); !errors.Is(err, ErrResetNotPreserved) { + t.Fatalf("err = %v, want ErrResetNotPreserved", err) + } + if writes.Load() != 0 || s.v3.pub.current() != old { + t.Fatal("a refused reset wrote or published") + } + }) +} + +func TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash(t *testing.T) { + s, path, crash := checkpointedStoreV3(t, 3) + old := s.v3.pub.current() + if err := s.resetIncarnationV3(); err != nil { + t.Fatalf("reset: %v", err) + } + a, b := slotsV3(t, path) + if a.Nonce != b.Nonce || a.Nonce == old.Nonce { + t.Fatalf("slots after reset: nonces %x / %x, old %x: want both on one new nonce", a.Nonce, b.Nonce, old.Nonce) + } + d := s.v3.pub.current() + if d.RetainedTail != 0 || d.RetainedHead != 0 || d.W != old.W || d.CheckpointLSN != old.CheckpointLSN || d.MapRootHash != old.MapRootHash { + t.Fatalf("after reset %+v (old %+v)", d, old) + } + readAllV3(t, s, 1, 3) + writeSynced(t, s, 4, 6) + if got := s.v3.pub.current(); got.Nonce != d.Nonce { + t.Fatalf("writes after the reset did not land in the new incarnation: %+v", got) + } + crash() + r := mustReopenV3(t, path) + defer r.Close() + readAllV3(t, r, 1, 6) +} + +func TestWALStoreV3ResetCrashOutcomes(t *testing.T) { + boom := errors.New("injected slot write error") + failNth := func(s *WALStore, nth int64) { + var n atomic.Int64 + s.v3.testBeforeSlotWrite = func() error { + if n.Add(1) == nth { + return boom + } + return nil + } + } + t.Run("step 2 fails: the old image", func(t *testing.T) { + s, path, crash := checkpointedStoreV3(t, 3) + old := s.v3.pub.current() + failNth(s, 1) + if err := s.resetIncarnationV3(); !errors.Is(err, boom) { + t.Fatalf("err = %v, want the write error", err) + } + if _, err := s.Write(4, blk(4)); err == nil { + t.Fatal("a write was admitted after a failed reset") + } + crash() + r := mustReopenV3(t, path) + defer r.Close() + if got := r.v3.pub.current(); got.Nonce != old.Nonce { + t.Fatal("a failed step 2 changed the selected incarnation") + } + readAllV3(t, r, 1, 3) + writeSynced(t, r, 4, 5) + readAllV3(t, r, 4, 5) + }) + t.Run("step 3 fails: the new image, never a successful reset", func(t *testing.T) { + s, path, crash := checkpointedStoreV3(t, 3) + old := s.v3.pub.current() + failNth(s, 2) + if err := s.resetIncarnationV3(); !errors.Is(err, boom) { + t.Fatalf("err = %v, want the step-3 write error", err) + } + if _, err := s.Write(4, blk(4)); err == nil { + t.Fatal("a write was admitted after a half-published reset") + } + crash() + a, b := slotsV3(t, path) + if a.Nonce == b.Nonce { + t.Fatal("setup: the slots should carry the old and the new nonce") + } + r := mustReopenV3(t, path) + defer r.Close() + if got := r.v3.pub.current(); got.Nonce == old.Nonce { + t.Fatal("reopen after step 2 did not select the new incarnation") + } + readAllV3(t, r, 1, 3) + writeSynced(t, r, 4, 5) + readAllV3(t, r, 4, 5) + a, b = slotsV3(t, path) + if a.Nonce != b.Nonce { + t.Fatal("the half-published reset is still mixed after a recovered reopen and writes") + } + }) +} + +// After a half-published reset, an opened but not yet recovered store binds +// no writer across the two nonces: a write is refused until Recover has +// completed the new incarnation in the other slot. +func TestWALStoreV3HalfResetRefusesWritesUntilRecover(t *testing.T) { + s, path, crash := checkpointedStoreV3(t, 2) + var n atomic.Int64 + s.v3.testBeforeSlotWrite = func() error { + if n.Add(1) == 2 { + return errors.New("injected step-3 write error") + } + return nil + } + if err := s.resetIncarnationV3(); err == nil { + t.Fatal("setup: the reset should fail at step 3") + } + crash() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatalf("open after a half-published reset: %v", err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + if r.v3.pub.mapDomain == nil { + t.Fatal("an open across a half-published reset did not bind its map") + } + if _, err := r.Write(3, blk(3)); !errors.Is(err, errWALBindingV3) { + t.Fatalf("write before Recover across a half-published reset: err = %v, want errWALBindingV3", err) + } + if _, err := r.Recover(); err != nil { + t.Fatalf("Recover: %v", err) + } + writeSynced(t, r, 3, 3) + readAllV3(t, r, 1, 3) +} + +// codex01 row 8 P1: a Read that resolved LBA 1's WAL position (cursor 0) +// parks before its pread; the real flusher checkpoints and releases the +// entry, the reset starts the new incarnation at cursor 0, and Write(2, B) +// reuses that position. The resumed Read must not return B for LBA 1: it +// validates the whole record against the resolving entry and re-resolves, +// reading A from the extent. +func TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock(t *testing.T) { + s, _, _ := checkpointedStoreV3(t, 0) + h := newHeldV3(t) + writeSynced(t, s, 1, 1) // LBA 1 = A at cursor 0 + if off, _, _, _, ok := s.dm.get(1); !ok || off != 0 { + t.Fatalf("setup: LBA 1 dirty at %d (%v), want cursor 0", off, ok) + } + s.v3.testReadResolved = h.hold + rd := make(chan []byte, 1) + res := h.start(func() error { + b, err := s.Read(1) + rd <- b + return err + }) + waitV3(t, h.parked, "Read after resolving cursor 0") + s.v3.testReadResolved = nil + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + if s.dm.len() != 0 { + t.Fatal("setup: the flusher did not release the entry") + } + if err := s.resetIncarnationV3(); err != nil { + t.Fatalf("reset: %v", err) + } + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + if off, _, _, _, ok := s.dm.get(2); !ok || off != 0 { + t.Fatalf("setup: LBA 2 at %d (%v), want the reused cursor 0", off, ok) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + h.rel() + if err := h.result(res, "Read"); err != nil { + t.Fatalf("Read: %v", err) + } + if got := <-rd; !bytes.Equal(got, blk(1)) { + t.Fatalf("Read(1) across a reset and overwrite returned %x..., want LBA 1's own block %x...", got[0], byte(1)) + } +} + +// The same schedule through the post-OnReadMiss recheck: the read missed the +// dirty map, A was written while the miss was held, the recheck resolved +// cursor 0 and parks there across the flush, reset and overwrite. +func TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock(t *testing.T) { + s, _, _ := checkpointedStoreV3(t, 0) + h := newHeldV3(t) + miss := &heldWALReadMiss{entered: make(chan struct{}), release: make(chan struct{})} + releaseMiss := sync.OnceFunc(func() { close(miss.release) }) + t.Cleanup(releaseMiss) // registered after heldV3's join: runs first + s.chunk.Store(&chunkHooks{sink: miss, closer: func() error { return nil }}) + rd := make(chan []byte, 1) + res := h.start(func() error { + b, err := s.Read(1) + rd <- b + return err + }) + waitV3(t, miss.entered, "Read in OnReadMiss") + writeSynced(t, s, 1, 1) // LBA 1 = A at cursor 0, while the miss is held + s.v3.testReadResolved = h.hold + releaseMiss() + waitV3(t, h.parked, "the post-miss recheck after resolving cursor 0") + s.v3.testReadResolved = nil + s.chunk.Store(nil) + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + if err := s.resetIncarnationV3(); err != nil { + t.Fatalf("reset: %v", err) + } + writeSynced(t, s, 2, 2) // reuses cursor 0 + if off, _, _, _, ok := s.dm.get(2); !ok || off != 0 { + t.Fatalf("setup: LBA 2 at %d (%v), want the reused cursor 0", off, ok) + } + h.rel() + if err := h.result(res, "Read"); err != nil { + t.Fatalf("Read: %v", err) + } + if got := <-rd; !bytes.Equal(got, blk(1)) { + t.Fatalf("post-miss Read(1) across a reset and overwrite returned %x..., want %x...", got[0], byte(1)) + } +} + +// A live dirty entry whose record no longer validates (the entry unchanged +// on re-resolution) is WAL damage: the read fails with a WAL integrity +// fault instead of returning the damaged bytes or retrying forever. +func TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 1) + damageRecord(t, path, 1) + if _, err := s.Read(1); !isWALCorrupt(err) { + t.Fatalf("Read of a damaged live record: err = %v, want a WAL integrity failure", err) + } +} + +// codex01 e72acd40 P2 (1): a same-open Recover can fence a dropped record +// and re-allocate its LSN to the same LBA at the same position. A read +// parked across that saw the fenced bytes; on re-resolution the entry looks +// unchanged (same position and LSN), but it is a new write: the read must +// retry and return it, not report WAL damage. +func TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + resolved, invalid := newHeldV3(t), newHeldV3(t) + writeSynced(t, s, 1, 1) // LSN 1 + if _, err := s.Write(1, blk(0xC1)); err != nil { // LSN 2, not acknowledged + t.Fatal(err) + } + off, _, lsn, _, _ := s.dm.get(1) + if lsn != 2 { + t.Fatalf("setup: LBA 1 dirty LSN %d, want 2", lsn) + } + s.v3.testReadResolved = resolved.hold + rd := make(chan []byte, 1) + res := resolved.start(func() error { + b, err := s.Read(1) + rd <- b + return err + }) + waitV3(t, resolved.parked, "Read after resolving LSN 2") + s.v3.testReadResolved = nil + damageRecord(t, path, 2) + if _, err := s.Recover(); err != nil { // drops LSN 2 and fences its bytes + t.Fatalf("Recover: %v", err) + } + s.v3.testReadInvalid = invalid.hold + resolved.rel() // the pread sees the fenced bytes and fails validation + waitV3(t, invalid.parked, "Read after the failed validation") + s.v3.testReadInvalid = nil + if _, err := s.Write(1, blk(0xC2)); err != nil { // LSN 2 again, same LBA + t.Fatal(err) + } + if off2, _, lsn2, _, _ := s.dm.get(1); off2 != off || lsn2 != 2 { + t.Fatalf("setup: the new write is at %d LSN %d, want the reused %d LSN 2", off2, lsn2, off) + } + invalid.rel() + if err := resolved.result(res, "Read"); err != nil { + t.Fatalf("Read across a reusing recovery: %v (a false WAL integrity failure)", err) + } + if got := <-rd; !bytes.Equal(got, blk(0xC2)) { + t.Fatalf("Read returned %x..., want the current write %x...", got[0], byte(0xC2)) + } +} + +// codex01 e72acd40 P2 (2): a failed pread is substrate I/O, never WAL +// integrity. EOF policy: the WAL region lies inside the file, so a file +// shorter than its geometry (io.EOF) is substrate I/O too. +func TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity(t *testing.T) { + isIO := func(err error) bool { + var rf *RecoveryFailure + return errors.As(err, &rf) && rf.Kind == StorageRecoveryFailureSubstrateIO + } + t.Run("short file (EOF)", func(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 1) + if err := os.Truncate(path, int64(walOffsetV3)); err != nil { + t.Fatal(err) + } + _, err := s.Read(1) + if !isIO(err) || isWALCorrupt(err) || !errors.Is(err, io.EOF) { + t.Fatalf("Read past the end of a truncated file: err = %v, want a substrate I/O failure wrapping io.EOF", err) + } + }) + t.Run("read error", func(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + writeSynced(t, s, 1, 1) + s.committer.Stop() + if err := s.fd.Close(); err != nil { // every later pread fails + t.Fatal(err) + } + _, err := s.Read(1) + if !isIO(err) || isWALCorrupt(err) || !errors.Is(err, os.ErrClosed) { + t.Fatalf("Read on a failing file: err = %v, want a substrate I/O failure", err) + } + }) +} + +// codex01 2fa56078 P2: a read already admitted (past Read's close check) +// captures the recovery generation AFTER a Recover's start bump and the OLD +// dirty entry BEFORE its clear; the recovery fences the dropped record and +// a same-LBA write re-allocates the same position and LSN. Tuple and a +// start-only generation would both match: the end bump (and the odd value +// while a recovery runs) makes the read retry and return the new write. +func TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + admitted, resolved, invalid, rec := newHeldV3(t), newHeldV3(t), newHeldV3(t), newHeldV3(t) + writeSynced(t, s, 1, 1) // LSN 1 + if _, err := s.Write(1, blk(0xC1)); err != nil { // LSN 2, not acknowledged + t.Fatal(err) + } + off, _, _, _, _ := s.dm.get(1) + damageRecord(t, path, 2) + s.v3.testReadAdmitted = admitted.hold + rd := make(chan []byte, 1) + res := admitted.start(func() error { + b, err := s.Read(1) + rd <- b + return err + }) + waitV3(t, admitted.parked, "Read admitted, before its generation capture") + s.v3.testReadAdmitted = nil + s.v3.testRecoverAfterBump = rec.hold + recDone := rec.start(func() error { _, err := s.Recover(); return err }) + waitV3(t, rec.parked, "Recover after its start bump, before the clear") + s.v3.testRecoverAfterBump = nil + s.v3.testReadResolved = resolved.hold + admitted.rel() // captures the bumped generation and the old entry + waitV3(t, resolved.parked, "Read after resolving the old entry") + s.v3.testReadResolved = nil + rec.rel() + if err := rec.result(recDone, "Recover"); err != nil { // drops LSN 2, fences it + t.Fatalf("Recover: %v", err) + } + s.v3.testReadInvalid = invalid.hold + resolved.rel() // the pread sees the fenced bytes + waitV3(t, invalid.parked, "Read after the failed validation") + s.v3.testReadInvalid = nil + if _, err := s.Write(1, blk(0xC2)); err != nil { // LSN 2 again, same LBA + t.Fatal(err) + } + if off2, _, lsn2, _, _ := s.dm.get(1); off2 != off || lsn2 != 2 { + t.Fatalf("setup: the new write is at %d LSN %d, want the reused %d LSN 2", off2, lsn2, off) + } + invalid.rel() + if err := admitted.result(res, "Read"); err != nil { + t.Fatalf("Read admitted inside a recovery: %v (a false WAL integrity failure)", err) + } + if got := <-rd; !bytes.Equal(got, blk(0xC2)) { + t.Fatalf("Read returned %x..., want the current write %x...", got[0], byte(0xC2)) + } +} diff --git a/seaweed-block/core/storage/reset_v3.go b/seaweed-block/core/storage/reset_v3.go new file mode 100644 index 0000000000..654d5c8cd2 --- /dev/null +++ b/seaweed-block/core/storage/reset_v3.go @@ -0,0 +1,130 @@ +package storage + +import ( + "crypto/rand" + "errors" + "fmt" +) + +// The v3 nonce/position reset transaction (format bump v3, DESIGN r16 +// section 8.6; plan row 8), publisher part. +// +// Step 1 (checkpoint or preserve every old acknowledged dependency) is the +// store's: the publisher refuses the reset unless every acknowledged LSN is +// checkpointed (CheckpointLSN >= W). Retained old-incarnation WAL bytes are +// then all at or below the checkpoint, so they are preserved in the extent +// and no longer required; the map root is unchanged by a reset, so no map +// page is retired. Steps 2 and 3 publish the new incarnation into +// one slot and then the other. Between them the slots carry different +// nonces: no reuse floor exists (reuseFloor reports !ok) and no new-nonce +// record may be admitted, so a crash there opens the complete new image +// with the old dependencies untouched. + +// ErrResetNotPreserved: a reset was asked for while old acknowledged data +// is still retained in the WAL or not yet checkpointed (DESIGN 8.6 step 1). +var ErrResetNotPreserved = errors.New("storage: v3 reset refused: old acknowledged data is not checkpointed") + +// resetIncarnationV3 runs DESIGN 8.6 steps 2 and 3. nonce is the new +// incarnation's nonce, and cursor its first logical cursor. The caller +// quiesces the store and recreates the WAL writer afterwards. +func (p *descriptorPublisherV3) resetIncarnationV3(nonce [16]byte, cursor uint64) (descriptorV3, error) { + p.descMu.Lock() + defer p.descMu.Unlock() + if p.failed != nil { + return descriptorV3{}, p.failed + } + cur := p.cur + if cur.CheckpointLSN < cur.W { + return descriptorV3{}, fmt.Errorf("%w: checkpoint %d below W %d", + ErrResetNotPreserved, cur.CheckpointLSN, cur.W) + } + if cur.BaseState != BaseNone { + return descriptorV3{}, fmt.Errorf("%w: reset during a BASE install", errDescriptorTransition) + } + if p.otherValid && p.other.Nonce != cur.Nonce { + // A previous reset stopped between its two publications; only a + // reopen resolves it. + return descriptorV3{}, fmt.Errorf("%w: a reset is already half published", errDescriptorTransition) + } + // Step 2: the new incarnation into the fallback slot. + if _, err := p.publishLockedCoreV3(func(n *descriptorV3) error { + n.Nonce = nonce + n.RetainedTail, n.RetainedHead = cursor, cursor + return nil + }, nil, true); err != nil { + return descriptorV3{}, err + } + // Step 3: republish it into the other slot. A failure here latches the + // publisher (an uncertain slot) and holds: never a successful reset. + return p.publishLockedCoreV3(nil, nil, false) +} + +// resetIncarnationV3 is the store half of the reset transaction (DESIGN 8.6; +// plan row 8). It is dark: nothing in production calls it, and it must not +// be activated before the reset model (r4.5) passes. +// +// It quiesces the store (the capture barrier exclusive, then the leader +// role and the store lock: captureMu -> lifecycleMu -> syncMu -> s.mu), and +// refuses with ErrResetNotPreserved, writing nothing, unless the dirty map +// is empty and every appended LSN is checkpointed (CheckpointLSN >= +// appended; a v3 checkpoint never exceeds the acknowledged W, so this also +// means appended == acknowledged). The empty map also closes the window +// between a checkpoint publication and the flusher's release of the covered +// entries, which still name old-incarnation WAL positions. It then +// publishes the new incarnation into both slots under a fresh random nonce +// with the cursor space starting at 0, recreates the WAL writer on it, bumps +// the recovery generation (an outer Sync that straddles the reset is not +// acknowledged) and invalidates the map proof epoch. LSNs, W and the map +// root are unchanged. +func (s *WALStore) resetIncarnationV3() error { + v := s.v3 + if v == nil { + return errors.New("storage: reset on a non-v3 store") + } + release := s.holdChunkDestructive(true) + defer release() + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + v.syncMu.Lock() + defer v.syncMu.Unlock() + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return errors.New("storage: reset after Close") + } + if err := s.stickyIOFault(); err != nil { + return err + } + d := v.pub.current() + appended := v.appended.Load() + if n := s.dm.len(); n != 0 || d.CheckpointLSN < appended { + return fmt.Errorf("%w: dirty %d, appended %d, checkpoint %d", + ErrResetNotPreserved, n, appended, d.CheckpointLSN) + } + var nonce [16]byte + for nonce == ([16]byte{}) || nonce == d.Nonce { + if _, err := rand.Read(nonce[:]); err != nil { + return err + } + } + v.recoverGen.Add(1) // odd while the reset runs (see recoverGen) + defer v.recoverGen.Add(1) // even again at the end, on every path + if _, err := v.pub.resetIncarnationV3(nonce, 0); err != nil { + return err + } + w, err := newWALWriterV3(s.fd, v.pub) + if err != nil { + s.latchV3(err) + return err + } + v.w = w + return v.pub.invalidateMapProofV3() +} + +// halfResetV3 reports a reset stopped between its two publications: the +// two valid slots carry different nonces. +func (p *descriptorPublisherV3) halfResetV3() bool { + p.descMu.Lock() + defer p.descMu.Unlock() + return p.otherValid && p.other.Nonce != p.cur.Nonce +} diff --git a/seaweed-block/core/storage/reset_v3_test.go b/seaweed-block/core/storage/reset_v3_test.go new file mode 100644 index 0000000000..8499ab5de4 --- /dev/null +++ b/seaweed-block/core/storage/reset_v3_test.go @@ -0,0 +1,139 @@ +package storage + +import ( + "errors" + "testing" +) + +// Row 8 publisher controls for the reset transaction (DESIGN 8.6). + +var newNonceV3 = [16]byte{0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF} + +// The reset precondition is CheckpointLSN >= W (row 8 as coded: no v3 tail +// release exists, so retained old-incarnation bytes at or below the +// checkpoint are preserved in the extent and are not a refusal reason). +func TestResetV3RefusesWhileUncheckpointed(t *testing.T) { + h := newDescHarnessV3(t) + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.W = 9 // acknowledged beyond the checkpoint (7) + return nil + }); err != nil { + t.Fatal(err) + } + writes := h.writes.Load() + if _, err := h.pub.resetIncarnationV3(newNonceV3, 0); !errors.Is(err, ErrResetNotPreserved) { + t.Fatalf("uncheckpointed W: err = %v, want ErrResetNotPreserved", err) + } + if h.writes.Load() != writes { + t.Fatal("a refused reset wrote a slot") + } +} + +func TestResetV3RefusesTheCurrentOrAZeroNonce(t *testing.T) { + for _, n := range [][16]byte{{}, newDescHarnessV3(t).pub.current().Nonce} { + h := newDescHarnessV3(t) + if n != ([16]byte{}) { + n = h.pub.current().Nonce + } + writes := h.writes.Load() + if _, err := h.pub.resetIncarnationV3(n, 0); !errors.Is(err, errDescriptorTransition) { + t.Fatalf("reset to nonce %x: err = %v, want errDescriptorTransition", n, err) + } + if h.writes.Load() != writes { + t.Fatal("a refused reset wrote a slot") + } + } +} + +func TestResetV3RetainedButCheckpointedBytesDoNotBlock(t *testing.T) { + h := newDescHarnessV3(t) + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.RetainedHead = 4166 // one retained record, at or below the checkpoint + return nil + }); err != nil { + t.Fatal(err) + } + d, err := h.pub.resetIncarnationV3(newNonceV3, 0) + if err != nil { + t.Fatalf("reset with checkpointed retained bytes: %v", err) + } + if d.RetainedTail != 0 || d.RetainedHead != 0 || d.Nonce != newNonceV3 { + t.Fatalf("reset result %+v", d) + } +} + +func TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor(t *testing.T) { + h := newDescHarnessV3(t) + old := h.pub.current() + d, err := h.pub.resetIncarnationV3(newNonceV3, 0) + if err != nil { + t.Fatal(err) + } + if d.Nonce != newNonceV3 || d.SlotGen != old.SlotGen+2 || d.W != old.W || d.CheckpointLSN != old.CheckpointLSN { + t.Fatalf("reset result %+v", d) + } + if floor, ok := h.pub.reuseFloor(); !ok || floor != 0 { + t.Fatalf("after both publications: floor %d ok %v, want 0 true", floor, ok) + } + got, _ := h.onDisk() + if got.Nonce != newNonceV3 || got.SlotGen != d.SlotGen { + t.Fatal("reopen does not select the new incarnation") + } +} + +func TestResetV3CrashOutcomes(t *testing.T) { + boom := errors.New("injected slot write error") + t.Run("step 2 fails: the old image", func(t *testing.T) { + h := newDescHarnessV3(t) + old := h.pub.current() + h.writeHook = func(int64, []byte) error { return boom } + if _, err := h.pub.resetIncarnationV3(newNonceV3, 0); !errors.Is(err, boom) { + t.Fatalf("err = %v, want the write error", err) + } + if got, _ := h.onDisk(); got != old { + t.Fatal("a failed step 2 changed the selected image") + } + }) + t.Run("step 3 fails: the new image, mixed nonces, no reuse, hold", func(t *testing.T) { + h := newDescHarnessV3(t) + old := h.pub.current() + n := 0 + h.writeHook = func(off int64, b []byte) error { + n++ + if n == 2 { + return boom + } + _, err := h.f.WriteAt(b, off) + return err + } + if _, err := h.pub.resetIncarnationV3(newNonceV3, 0); !errors.Is(err, boom) { + t.Fatalf("err = %v, want the step-3 write error (never a successful reset)", err) + } + if _, err := h.pub.publish(&h.storeMu, nil, nil); !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("publication after a failed step 3: err = %v, want the latched uncertain failure", err) + } + // Reopen: the new incarnation is selected, the other slot is the old + // incarnation, and no reuse floor exists across the two nonces. + got, id := h.onDisk() + if got.Nonce != newNonceV3 || got.SlotGen != old.SlotGen+1 { + t.Fatalf("reopen after step 2 selected nonce %x gen %d", got.Nonce, got.SlotGen) + } + re := newDescriptorPublisherV3(got, id, &old, h.pub.io) + if _, ok := re.reuseFloor(); ok { + t.Fatal("a reuse floor was computed across the old and new incarnations") + } + if _, err := re.resetIncarnationV3([16]byte{0xEE}, 0); !errors.Is(err, errDescriptorTransition) { + t.Fatalf("a second reset over a half-published one: err = %v, want refusal", err) + } + }) +} + +func TestResetV3OrdinaryPublicationsCannotChangeTheNonce(t *testing.T) { + h := newDescHarnessV3(t) + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.Nonce = newNonceV3 + return nil + }); !errors.Is(err, errDescriptorTransition) { + t.Fatalf("nonce change outside the reset: err = %v, want errDescriptorTransition", err) + } +} diff --git a/seaweed-block/core/storage/smartwal/recovery_scan_test.go b/seaweed-block/core/storage/smartwal/recovery_scan_test.go index b5c0c3c899..2449bcd935 100644 --- a/seaweed-block/core/storage/smartwal/recovery_scan_test.go +++ b/seaweed-block/core/storage/smartwal/recovery_scan_test.go @@ -230,7 +230,11 @@ func TestSmartwalRecovery_AllBlocks_DeterministicOrdering(t *testing.T) { t.Fatalf("Sync: %v", err) } - got := s.AllBlocks() + got, snapshotErr := s.AllBlocks() + + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(got) != len(expected) { t.Fatalf("AllBlocks size: got %d want %d", len(got), len(expected)) } @@ -420,7 +424,10 @@ func TestSmartwalRecovery_Sanity_ExistingAPIsUnchanged(t *testing.T) { } // AllBlocks still works. - all := s.AllBlocks() + all, snapshotErr := s.AllBlocks() + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(all) != 1 { t.Fatalf("AllBlocks: got %d want 1", len(all)) } diff --git a/seaweed-block/core/storage/smartwal/store.go b/seaweed-block/core/storage/smartwal/store.go index 56673d9993..b51d3f9bc9 100644 --- a/seaweed-block/core/storage/smartwal/store.go +++ b/seaweed-block/core/storage/smartwal/store.go @@ -11,6 +11,7 @@ import ( "sync/atomic" "time" + "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -90,6 +91,9 @@ func CreateStoreWithSlots(path string, numBlocks uint32, blockSize int, walSlots if blockSize == 0 { blockSize = storage.DefaultBlockSize } + if err := geometry.ValidateBlockGeometry(uint64(numBlocks), uint64(blockSize)); err != nil { + return nil, err + } if walSlots == 0 { walSlots = defaultWALSlots } @@ -498,12 +502,12 @@ func (s *Store) AppliedLSNs() (map[uint32]uint64, error) { // AllBlocks snapshots every LBA's current bytes by reading directly // from the extent. Linear scan — N reads — but in practice the // rebuild server is the only caller and runs once per session. -func (s *Store) AllBlocks() map[uint32][]byte { +func (s *Store) AllBlocks() (map[uint32][]byte, error) { out := make(map[uint32][]byte, s.hdr.NumBlocks) for lba := uint32(0); lba < s.hdr.NumBlocks; lba++ { data, err := s.Read(lba) if err != nil { - continue + return nil, fmt.Errorf("snapshot LBA %d: %w", lba, err) } // Only include LBAs with non-zero content — preserves the // "snapshot of dirty bits" semantics callers expect. @@ -518,7 +522,7 @@ func (s *Store) AllBlocks() map[uint32][]byte { out[lba] = data } } - return out + return out, nil } // Close fsyncs and releases the file. Idempotent. diff --git a/seaweed-block/core/storage/smartwal/volume_size_limit_test.go b/seaweed-block/core/storage/smartwal/volume_size_limit_test.go new file mode 100644 index 0000000000..406ecb4710 --- /dev/null +++ b/seaweed-block/core/storage/smartwal/volume_size_limit_test.go @@ -0,0 +1,23 @@ +package smartwal + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestCreateCapacityBeforeFilesystem(t *testing.T) { + parent := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(parent, []byte("unchanged"), 0600); err != nil { + t.Fatal(err) + } + s, err := CreateStore(filepath.Join(parent, "volume"), ^uint32(0), 8192) + if s != nil { + s.Close() + t.Fatal("created oversized image") + } + if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("capacity must precede filesystem: %v", err) + } +} diff --git a/seaweed-block/core/storage/store.go b/seaweed-block/core/storage/store.go index aba2b02013..fc901ce3b3 100644 --- a/seaweed-block/core/storage/store.go +++ b/seaweed-block/core/storage/store.go @@ -316,7 +316,7 @@ func (s *BlockStore) WriteExtentDirect(lba uint32, data []byte) error { } // AllBlocks returns all written LBAs and their data (for rebuild serving). -func (s *BlockStore) AllBlocks() map[uint32][]byte { +func (s *BlockStore) AllBlocks() (map[uint32][]byte, error) { s.mu.RLock() defer s.mu.RUnlock() result := make(map[uint32][]byte, len(s.blocks)) @@ -325,5 +325,5 @@ func (s *BlockStore) AllBlocks() map[uint32][]byte { copy(cp, data) result[lba] = cp } - return result + return result, nil } diff --git a/seaweed-block/core/storage/superblock.go b/seaweed-block/core/storage/superblock.go index 0fad23bf38..9880437d39 100644 --- a/seaweed-block/core/storage/superblock.go +++ b/seaweed-block/core/storage/superblock.go @@ -10,11 +10,10 @@ import ( // File-format identity. Bumped only on incompatible layout changes. // -// Version history: -// 1: initial layout (magic+version+geometry+WAL state+CreatedAt) -// 2: T3a Addendum A — added ImplKind + ImplVersion at end of -// layout. Opening a v1 store with v2 code returns -// errSuperblockBadVer (one-way bump; no compat read path). +// Version 1 used magic, version, geometry, WAL state and CreatedAt. +// Version 2 (T3a Addendum A) added ImplKind and ImplVersion. Opening +// a v1 store with v2 code returns errSuperblockBadVer; there is no +// compatible read path. const ( superblockSize = 4096 superblockMagic = "SWBK" @@ -40,7 +39,7 @@ const ( // files. Independent from superblockVersion (which is the shared // superblock-format version) — walstore and smartwal evolve their // WAL+extent layouts on independent clocks. -const WALStoreImplVersion uint32 = 1 +const WALStoreImplVersion uint32 = 3 var ( errSuperblockNotOurs = errors.New("storage: not a store file (bad magic)") diff --git a/seaweed-block/core/storage/superblock_v3.go b/seaweed-block/core/storage/superblock_v3.go new file mode 100644 index 0000000000..b7d3e7ffc3 --- /dev/null +++ b/seaweed-block/core/storage/superblock_v3.go @@ -0,0 +1,400 @@ +package storage + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "hash/crc32" + "math" +) + +// Impl-3 descriptor slots (format bump v3, DESIGN r15 section 2). +// +// A v3 file holds two 4096-byte descriptor slots, A at offset 0 and B at +// 4096; the WAL starts at 8192. Each slot is one complete generation +// descriptor sealed by a CRC32C (Castagnoli). This file holds only the +// slot codec, its validity rules and the production A/B selection. Legacy +// decoding is retained for the explicit offline migration boundary. + +const ( + slotSizeV3 = 4096 + slotAOffsetV3 = 0 + slotBOffsetV3 = slotSizeV3 + walOffsetV3 = 2 * slotSizeV3 + superblockVersionV3 = 3 + walStoreImplVersion3 = 3 + mapFormatIDV1 = 1 + + // counterMaxV3 is the largest value any persisted counter may hold + // (DESIGN 2.4): an operation that would exceed it is refused, so + // nothing ever wraps. + counterMaxV3 = math.MaxUint64 - 1 + + slotCRCOffsetV3 = slotSizeV3 - 4 +) + +// BaseState is the persisted BASE-install state (DESIGN 2.1, 8.5). +type BaseState uint8 + +const ( + BaseNone BaseState = 0 + BaseInstalling BaseState = 1 + BaseInstalled BaseState = 2 +) + +// WMode selects the synced-watermark protocol (DESIGN 6.1). +type WMode uint8 + +const ( + WModeLagged WMode = 0 // C, the default: one fsync, lagged slot W + WModeStrict WMode = 1 // A, opt-in: two fsyncs +) + +// MigrationPhase marks a slot written by the offline v2 to v3 migration +// before its commit (DESIGN 10.1). A prepared slot is never selectable. +type MigrationPhase uint8 + +const ( + MigrationNormal MigrationPhase = 0 + MigrationPrepared MigrationPhase = 1 +) + +var ( + // ErrMigrationIncomplete: no selectable slot exists but a prepared + // migration slot does (DESIGN 2.3, 10.1). The volume must not serve. + ErrMigrationIncomplete = errors.New("storage: v3 migration not committed (only a prepared descriptor slot exists)") + // ErrCounterExhausted: a persisted counter would exceed 2^64-2 + // (DESIGN 2.4). Nothing is written. + ErrCounterExhausted = errors.New("storage: v3 counter exhausted") +) + +// descriptorV3 is one decoded v3 descriptor slot. Field order and offsets +// follow DESIGN 2.1 exactly; see encode/decodeSlotV3. +type descriptorV3 struct { + ImplKind ImplKind + ImplVersion uint32 + UUID [16]byte + VolumeSize uint64 + ExtentSize uint32 + BlockSize uint32 + WALOffset uint64 + WALSize uint64 + CreatedAt uint64 + SlotGen uint64 + + CheckpointLSN uint64 + + Nonce [16]byte + RetainedTail uint64 + RetainedHead uint64 + MapFormatID uint32 + MapGeneration uint64 + MapRootLocator uint64 + MapCoveredCheckpoint uint64 + MapRootHash [32]byte + MapLineage [16]byte + + W uint64 + BaseLSN uint64 + BaseState BaseState + BaseCursor uint64 + BaseInstallID [16]byte + WMode WMode + MigrationPhase MigrationPhase +} + +var crc32cTable = crc32.MakeTable(crc32.Castagnoli) + +// reservedRangesV3 are the [start, end) byte ranges that must be zero. +var reservedRangesV3 = [][2]int{ + {9, 12}, {88, 128}, {164, 168}, {240, 256}, {273, 280}, {306, slotCRCOffsetV3}, +} + +// encode serializes d into one sealed slot. It does not validate; callers +// validate before publishing (publishDescriptor) and tests use it to build +// vectors. +func (d *descriptorV3) encode() []byte { + b := make([]byte, slotSizeV3) + le := binary.LittleEndian + copy(b[0:4], superblockMagic) + le.PutUint16(b[4:], superblockVersionV3) + le.PutUint16(b[6:], 0) // flags + b[8] = uint8(d.ImplKind) + le.PutUint32(b[12:], d.ImplVersion) + copy(b[16:32], d.UUID[:]) + le.PutUint64(b[32:], d.VolumeSize) + le.PutUint32(b[40:], d.ExtentSize) + le.PutUint32(b[44:], d.BlockSize) + le.PutUint64(b[48:], d.WALOffset) + le.PutUint64(b[56:], d.WALSize) + le.PutUint64(b[64:], d.CreatedAt) + le.PutUint64(b[72:], d.SlotGen) + le.PutUint64(b[80:], d.CheckpointLSN) + copy(b[128:144], d.Nonce[:]) + le.PutUint64(b[144:], d.RetainedTail) + le.PutUint64(b[152:], d.RetainedHead) + le.PutUint32(b[160:], d.MapFormatID) + le.PutUint64(b[168:], d.MapGeneration) + le.PutUint64(b[176:], d.MapRootLocator) + le.PutUint64(b[184:], d.MapCoveredCheckpoint) + copy(b[192:224], d.MapRootHash[:]) + copy(b[224:240], d.MapLineage[:]) + le.PutUint64(b[256:], d.W) + le.PutUint64(b[264:], d.BaseLSN) + b[272] = uint8(d.BaseState) + le.PutUint64(b[280:], d.BaseCursor) + copy(b[288:304], d.BaseInstallID[:]) + b[304] = uint8(d.WMode) + b[305] = uint8(d.MigrationPhase) + le.PutUint32(b[slotCRCOffsetV3:], crc32.Checksum(b[:slotCRCOffsetV3], crc32cTable)) + return b +} + +// slotImplAcceptor reports whether an (ImplKind, ImplVersion) pair is +// accepted in a v3 slot. OSS accepts walstore impl 3 only; impl 4 is +// reserved for an accepting enterprise metadata factory (DESIGN 1). +type slotImplAcceptor func(kind ImplKind, version uint32) bool + +func ossSlotImplAcceptor(kind ImplKind, version uint32) bool { + return kind == ImplKindWALStore && version == walStoreImplVersion3 +} + +// decodeSlotV3 decodes and validates one slot (DESIGN 2.2 items 1-3 and 5, +// and the slot-local part of the 9.1 coverage predicates). Map dependency +// validation (item 4: root and pages present, in bounds, hash-valid) needs +// the sidecar and is applied by the map layer on top of this. +func decodeSlotV3(b []byte, accept slotImplAcceptor) (descriptorV3, error) { + if len(b) != slotSizeV3 { + return descriptorV3{}, fmt.Errorf("%w: slot length %d", errSuperblockInvalid, len(b)) + } + le := binary.LittleEndian + if string(b[0:4]) != superblockMagic { + return descriptorV3{}, errSuperblockNotOurs + } + if v := le.Uint16(b[4:]); v != superblockVersionV3 { + return descriptorV3{}, fmt.Errorf("%w: slot version %d, want %d", errSuperblockBadVer, v, superblockVersionV3) + } + if got, want := le.Uint32(b[slotCRCOffsetV3:]), crc32.Checksum(b[:slotCRCOffsetV3], crc32cTable); got != want { + return descriptorV3{}, fmt.Errorf("%w: slot CRC32C %08x, want %08x", errSuperblockInvalid, got, want) + } + if f := le.Uint16(b[6:]); f != 0 { + return descriptorV3{}, fmt.Errorf("%w: slot flags %#x", errSuperblockInvalid, f) + } + for _, r := range reservedRangesV3 { + if i := firstNonZero(b[r[0]:r[1]]); i >= 0 { + return descriptorV3{}, fmt.Errorf("%w: reserved byte %d is nonzero", errSuperblockInvalid, r[0]+i) + } + } + var d descriptorV3 + d.ImplKind = ImplKind(b[8]) + d.ImplVersion = le.Uint32(b[12:]) + copy(d.UUID[:], b[16:32]) + d.VolumeSize = le.Uint64(b[32:]) + d.ExtentSize = le.Uint32(b[40:]) + d.BlockSize = le.Uint32(b[44:]) + d.WALOffset = le.Uint64(b[48:]) + d.WALSize = le.Uint64(b[56:]) + d.CreatedAt = le.Uint64(b[64:]) + d.SlotGen = le.Uint64(b[72:]) + d.CheckpointLSN = le.Uint64(b[80:]) + copy(d.Nonce[:], b[128:144]) + d.RetainedTail = le.Uint64(b[144:]) + d.RetainedHead = le.Uint64(b[152:]) + d.MapFormatID = le.Uint32(b[160:]) + d.MapGeneration = le.Uint64(b[168:]) + d.MapRootLocator = le.Uint64(b[176:]) + d.MapCoveredCheckpoint = le.Uint64(b[184:]) + copy(d.MapRootHash[:], b[192:224]) + copy(d.MapLineage[:], b[224:240]) + d.W = le.Uint64(b[256:]) + d.BaseLSN = le.Uint64(b[264:]) + d.BaseState = BaseState(b[272]) + d.BaseCursor = le.Uint64(b[280:]) + copy(d.BaseInstallID[:], b[288:304]) + d.WMode = WMode(b[304]) + d.MigrationPhase = MigrationPhase(b[305]) + if err := d.validate(accept); err != nil { + return descriptorV3{}, err + } + return d, nil +} + +func firstNonZero(b []byte) int { + for i, c := range b { + if c != 0 { + return i + } + } + return -1 +} + +func invalidV3(format string, args ...any) error { + return fmt.Errorf("%w: "+format, append([]any{errSuperblockInvalid}, args...)...) +} + +// validate applies the field rules of DESIGN 2.1/2.2 that need no sidecar. +func (d *descriptorV3) validate(accept slotImplAcceptor) error { + if accept == nil { + accept = ossSlotImplAcceptor + } + if !accept(d.ImplKind, d.ImplVersion) { + return invalidV3("impl kind %d version %d not accepted in a v3 slot", d.ImplKind, d.ImplVersion) + } + // Identity and counters (2.2 item 2, 2.4). + if d.SlotGen == 0 || d.SlotGen > counterMaxV3 { + return invalidV3("slotGen %d", d.SlotGen) + } + if d.Nonce == ([16]byte{}) { + return invalidV3("all-zero WAL nonce") + } + for _, c := range []struct { + name string + v uint64 + }{ + {"CheckpointLSN", d.CheckpointLSN}, {"retainedHead", d.RetainedHead}, + {"mapGeneration", d.MapGeneration}, {"W", d.W}, {"BaseLSN", d.BaseLSN}, + } { + if c.v > counterMaxV3 { + return invalidV3("%s %d exceeds 2^64-2", c.name, c.v) + } + } + // Geometry and bounds (2.2 item 3), with checked arithmetic. + if d.WALOffset != walOffsetV3 { + return invalidV3("WALOffset %d, want %d", d.WALOffset, walOffsetV3) + } + if d.BlockSize == 0 || d.ExtentSize == 0 || d.WALSize == 0 || d.VolumeSize == 0 { + return invalidV3("zero geometry (block %d extent %d wal %d volume %d)", + d.BlockSize, d.ExtentSize, d.WALSize, d.VolumeSize) + } + if d.VolumeSize%uint64(d.BlockSize) != 0 { + return invalidV3("VolumeSize %d not aligned to BlockSize %d", d.VolumeSize, d.BlockSize) + } + if end, ok := checkedAddV3(d.WALOffset, d.WALSize); !ok { + return invalidV3("WAL region overflows") + } else if _, ok := checkedAddV3(end, d.VolumeSize); !ok { + return invalidV3("extent region overflows") + } + if d.RetainedTail > d.RetainedHead { + return invalidV3("retainedTail %d > retainedHead %d", d.RetainedTail, d.RetainedHead) + } + if d.RetainedHead-d.RetainedTail > d.WALSize { + return invalidV3("retained window %d exceeds WALSize %d", d.RetainedHead-d.RetainedTail, d.WALSize) + } + // Map fields named by the slot (2.1; 9.1 predicate 2, slot-local part). + if d.MapFormatID != mapFormatIDV1 { + return invalidV3("mapFormatID %d", d.MapFormatID) + } + if d.MapRootLocator%slotSizeV3 != 0 { + return invalidV3("map root locator %d not 4096-aligned", d.MapRootLocator) + } + if d.MapCoveredCheckpoint < d.CheckpointLSN { + return invalidV3("map covers %d, below CheckpointLSN %d", d.MapCoveredCheckpoint, d.CheckpointLSN) + } + if d.MapCoveredCheckpoint > d.W { + return invalidV3("map covers %d, above W %d", d.MapCoveredCheckpoint, d.W) + } + // BASE fields (2.1 BASE rules). + var zeroID [16]byte + switch d.BaseState { + case BaseNone: + if d.BaseLSN != 0 || d.BaseCursor != 0 || d.BaseInstallID != zeroID { + return invalidV3("BaseState none with BASE fields set") + } + case BaseInstalling: + if d.BaseInstallID == zeroID { + return invalidV3("installing with a zero BaseInstallID") + } + if d.BaseCursor < d.RetainedTail || d.BaseCursor > d.RetainedHead { + return invalidV3("installing BaseCursor %d outside [%d, %d]", d.BaseCursor, d.RetainedTail, d.RetainedHead) + } + case BaseInstalled: + if d.BaseInstallID == zeroID { + return invalidV3("installed with a zero BaseInstallID") + } + // BaseCursor may lie below retainedTail after retirement (r15). + if d.BaseCursor > d.RetainedHead { + return invalidV3("installed BaseCursor %d above retainedHead %d", d.BaseCursor, d.RetainedHead) + } + default: + return invalidV3("BaseState %d", d.BaseState) + } + if d.WMode != WModeLagged && d.WMode != WModeStrict { + return invalidV3("WMode %d", d.WMode) + } + switch d.MigrationPhase { + case MigrationNormal: + case MigrationPrepared: + if d.SlotGen != 1 || d.BaseState != BaseNone { + return invalidV3("prepared slot with slotGen %d BaseState %d", d.SlotGen, d.BaseState) + } + default: + return invalidV3("MigrationPhase %d", d.MigrationPhase) + } + return nil +} + +// checkedAddV3 adds without wrapping and refuses results above 2^64-2. +func checkedAddV3(a, b uint64) (uint64, bool) { + s := a + b + if s < a || s > counterMaxV3 { + return 0, false + } + return s, true +} + +// nextSlotGenV3 is the slotGen for the next publication (DESIGN 2.4). +func nextSlotGenV3(cur uint64) (uint64, error) { + n, ok := checkedAddV3(cur, 1) + if !ok { + return 0, fmt.Errorf("%w: slotGen %d", ErrCounterExhausted, cur) + } + return n, nil +} + +// slotIDV3 names a descriptor slot. +type slotIDV3 int + +const ( + slotA slotIDV3 = 0 + slotB slotIDV3 = 1 +) + +// selectSlotV3 applies DESIGN 2.3 to the raw bytes of slots A and B and +// returns the selected descriptor and which slot it came from. +func selectSlotV3(a, b []byte, accept slotImplAcceptor) (descriptorV3, slotIDV3, error) { + da, errA := decodeSlotV3(a, accept) + db, errB := decodeSlotV3(b, accept) + if errA != nil && errB != nil { + return descriptorV3{}, 0, fmt.Errorf("%w: neither descriptor slot is valid (A: %v; B: %v)", + errSuperblockInvalid, errA, errB) + } + if errA == nil && errB == nil { + if da.UUID != db.UUID || !sameGeometryV3(da, db) { + return descriptorV3{}, 0, invalidV3("slots A and B disagree on identity or geometry") + } + if da.SlotGen == db.SlotGen && !bytes.Equal(a, b) { + return descriptorV3{}, 0, invalidV3("slots A and B share slotGen %d with different bytes", da.SlotGen) + } + } + selA := errA == nil && da.MigrationPhase == MigrationNormal + selB := errB == nil && db.MigrationPhase == MigrationNormal + switch { + case selA && selB: + if db.SlotGen > da.SlotGen { + return db, slotB, nil + } + return da, slotA, nil + case selA: + return da, slotA, nil + case selB: + return db, slotB, nil + default: + return descriptorV3{}, 0, ErrMigrationIncomplete + } +} + +func sameGeometryV3(x, y descriptorV3) bool { + return x.VolumeSize == y.VolumeSize && x.ExtentSize == y.ExtentSize && + x.BlockSize == y.BlockSize && x.WALOffset == y.WALOffset && x.WALSize == y.WALSize +} diff --git a/seaweed-block/core/storage/superblock_v3_test.go b/seaweed-block/core/storage/superblock_v3_test.go new file mode 100644 index 0000000000..378a6b2f29 --- /dev/null +++ b/seaweed-block/core/storage/superblock_v3_test.go @@ -0,0 +1,228 @@ +package storage + +import ( + "bufio" + "bytes" + "errors" + "math" + "os" + "path/filepath" + "strings" + "testing" +) + +// Row 1 (DESIGN r15 section 2) new-API coverage. The vectors under +// testdata/format_v3/slot were produced by gen_slot_vectors.py, an +// independent stdlib-only generator with its own CRC32C (self-checked +// against CRC32C("123456789") = e3069283), not by this codec. + +const slotVectorDir = "testdata/format_v3/slot" + +func readSlotVector(t *testing.T, name string) []byte { + t.Helper() + b, err := os.ReadFile(filepath.Join(slotVectorDir, name+".bin")) + if err != nil { + t.Fatal(err) + } + return b +} + +func slotVectorNames(t *testing.T) []string { + t.Helper() + f, err := os.Open(filepath.Join(slotVectorDir, "EXPECTED.txt")) + if err != nil { + t.Fatal(err) + } + defer f.Close() + var names []string + sc := bufio.NewScanner(f) + for sc.Scan() { + line := sc.Text() + if i := strings.Index(line, ".bin crc32c="); i > 0 && !strings.Contains(line[:i], " ") { + names = append(names, line[:i]) + } + } + if err := sc.Err(); err != nil { + t.Fatal(err) + } + if len(names) != 25 { + t.Fatalf("EXPECTED.txt lists %d vectors, want 25", len(names)) + } + return names +} + +func TestSlotV3VectorsDecodeAsExpected(t *testing.T) { + for _, name := range slotVectorNames(t) { + t.Run(name, func(t *testing.T) { + raw := readSlotVector(t, name) + d, err := decodeSlotV3(raw, nil) + if strings.HasPrefix(name, "neg-") { + if err == nil { + t.Fatalf("decoded an invalid slot: %+v", d) + } + if !errors.Is(err, errSuperblockInvalid) { + t.Fatalf("err = %v, want errSuperblockInvalid", err) + } + return + } + if err != nil { + t.Fatalf("valid slot refused: %v", err) + } + if got := d.encode(); !bytes.Equal(got, raw) { + t.Fatal("re-encoding the decoded slot is not byte-exact") + } + }) + } +} + +func TestSlotV3ReferenceFields(t *testing.T) { + d, err := decodeSlotV3(readSlotVector(t, "slot-ref"), nil) + if err != nil { + t.Fatal(err) + } + var uuid, nonce, lineage [16]byte + for i := 0; i < 16; i++ { + uuid[i], lineage[i], nonce[i] = byte(i), byte(0x10+i), byte(0x20+i) + } + if d.UUID != uuid || d.Nonce != nonce || d.MapLineage != lineage { + t.Fatal("identity fields differ from the generator") + } + if d.ImplKind != ImplKindWALStore || d.ImplVersion != walStoreImplVersion3 || + d.WALOffset != walOffsetV3 || d.SlotGen != 1 || d.CheckpointLSN != 7 || + d.W != 7 || d.MapCoveredCheckpoint != 7 || d.MapGeneration != 1 || + d.BaseState != BaseNone || d.WMode != WModeLagged || d.MigrationPhase != MigrationNormal { + t.Fatalf("reference fields differ: %+v", d) + } + // The slot names codex03's map fixture root (DESIGN 9.5). + if got := d.MapRootHash; got[0] != 0xb4 || got[1] != 0x7d || got[31] != 0x1b { + t.Fatalf("map root hash %x is not the 9.5 rootBodyDigest", got) + } +} + +func withSlotGen(t *testing.T, raw []byte, gen uint64, mutate func(*descriptorV3)) []byte { + t.Helper() + d, err := decodeSlotV3(raw, nil) + if err != nil { + t.Fatal(err) + } + d.SlotGen = gen + if mutate != nil { + mutate(&d) + } + return d.encode() +} + +func TestSlotV3Selection(t *testing.T) { + ref := readSlotVector(t, "slot-ref") + gen2 := withSlotGen(t, ref, 2, func(d *descriptorV3) { d.W = 9; d.MapCoveredCheckpoint = 9 }) + torn := append([]byte(nil), gen2...) + torn[4092] ^= 1 + garbage := bytes.Repeat([]byte{0xA5}, slotSizeV3) + prepared := readSlotVector(t, "slot-prepared") + + cases := []struct { + name string + a, b []byte + wantErr error + want slotIDV3 + wantGen uint64 + }{ + {"higher generation in B wins", ref, gen2, nil, slotB, 2}, + {"higher generation in A wins", gen2, ref, nil, slotA, 2}, + {"torn newer slot falls back", ref, torn, nil, slotA, 1}, + {"garbage A falls back to B", garbage, gen2, nil, slotB, 2}, + {"both invalid refuse", garbage, torn, errSuperblockInvalid, 0, 0}, + {"identical equal-generation copies are equivalent", ref, append([]byte(nil), ref...), nil, slotA, 1}, + {"equal generation different bytes refuse", readSlotVector(t, "pair-equal-gen-A"), readSlotVector(t, "pair-equal-gen-B"), errSuperblockInvalid, 0, 0}, + {"prepared B is never selected over a valid A", gen2, prepared, nil, slotA, 2}, + {"prepared only refuses as incomplete migration", garbage, prepared, ErrMigrationIncomplete, 0, 0}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + d, id, err := selectSlotV3(c.a, c.b, nil) + if c.wantErr != nil { + if !errors.Is(err, c.wantErr) { + t.Fatalf("err = %v, want %v", err, c.wantErr) + } + return + } + if err != nil { + t.Fatal(err) + } + if id != c.want || d.SlotGen != c.wantGen { + t.Fatalf("selected slot %d gen %d, want slot %d gen %d", id, d.SlotGen, c.want, c.wantGen) + } + }) + } + + t.Run("identity mismatch refuses", func(t *testing.T) { + other := withSlotGen(t, ref, 2, func(d *descriptorV3) { d.UUID[0] ^= 0xFF }) + if _, _, err := selectSlotV3(ref, other, nil); !errors.Is(err, errSuperblockInvalid) { + t.Fatalf("err = %v, want errSuperblockInvalid", err) + } + }) + t.Run("geometry mismatch refuses", func(t *testing.T) { + other := withSlotGen(t, ref, 2, func(d *descriptorV3) { d.WALSize *= 2 }) + if _, _, err := selectSlotV3(ref, other, nil); !errors.Is(err, errSuperblockInvalid) { + t.Fatalf("err = %v, want errSuperblockInvalid", err) + } + }) +} + +func TestSlotV3CounterExhaustion(t *testing.T) { + if counterMaxV3 != math.MaxUint64-1 { + t.Fatalf("counter cutoff %d, want 2^64-2", uint64(counterMaxV3)) + } + if _, err := nextSlotGenV3(counterMaxV3); !errors.Is(err, ErrCounterExhausted) { + t.Fatalf("next after 2^64-2: err = %v, want ErrCounterExhausted", err) + } + if n, err := nextSlotGenV3(counterMaxV3 - 1); err != nil || n != counterMaxV3 { + t.Fatalf("next after 2^64-3 = %d, %v; want 2^64-2", n, err) + } + ref := readSlotVector(t, "slot-ref") + if _, err := decodeSlotV3(withSlotGen(t, ref, counterMaxV3, nil), nil); err != nil { + t.Fatalf("slotGen 2^64-2 refused: %v", err) + } + if _, err := decodeSlotV3(withSlotGen(t, ref, math.MaxUint64, nil), nil); !errors.Is(err, errSuperblockInvalid) { + t.Fatalf("slotGen 2^64-1: err = %v, want errSuperblockInvalid", err) + } +} + +func TestSlotV3InstalledMayHaveCursorBelowTail(t *testing.T) { + ref := readSlotVector(t, "slot-ref") + installed := withSlotGen(t, ref, 3, func(d *descriptorV3) { + d.BaseState = BaseInstalled + d.BaseLSN = 7 + d.BaseInstallID[0] = 1 + d.RetainedTail, d.RetainedHead, d.BaseCursor = 500, 600, 100 + }) + if _, err := decodeSlotV3(installed, nil); err != nil { + t.Fatalf("installed slot with BaseCursor below retainedTail refused (r15): %v", err) + } + installing := withSlotGen(t, ref, 3, func(d *descriptorV3) { + d.BaseState = BaseInstalling + d.BaseLSN = 7 + d.BaseInstallID[0] = 1 + d.RetainedTail, d.RetainedHead, d.BaseCursor = 500, 600, 100 + }) + if _, err := decodeSlotV3(installing, nil); !errors.Is(err, errSuperblockInvalid) { + t.Fatalf("installing slot with BaseCursor below retainedTail: err = %v, want errSuperblockInvalid", err) + } +} + +func TestSlotV3RejectsOtherVersionsAndMagic(t *testing.T) { + ref := readSlotVector(t, "slot-ref") + v2 := append([]byte(nil), ref...) + v2[4] = 2 + if _, err := decodeSlotV3(v2, nil); !errors.Is(err, errSuperblockBadVer) { + t.Fatalf("version 2 bytes: err = %v, want errSuperblockBadVer", err) + } + bad := append([]byte(nil), ref...) + bad[0] = 'X' + if _, err := decodeSlotV3(bad, nil); !errors.Is(err, errSuperblockNotOurs) { + t.Fatalf("bad magic: err = %v, want errSuperblockNotOurs", err) + } + if _, err := decodeSlotV3(ref[:100], nil); !errors.Is(err, errSuperblockInvalid) { + t.Fatalf("short slot: err = %v, want errSuperblockInvalid", err) + } +} diff --git a/seaweed-block/core/storage/testdata/format_v3/README.md b/seaweed-block/core/storage/testdata/format_v3/README.md new file mode 100644 index 0000000000..b035e86b4e --- /dev/null +++ b/seaweed-block/core/storage/testdata/format_v3/README.md @@ -0,0 +1,9 @@ +# Format v3 record vectors + +The barrier vector is a worked example of the frozen format byte table (original design SHA in barrier.json; unchanged through the accepted r15 contract). It was constructed independently using reflected Castagnoli polynomial 0x82f63b78 and initial/final XOR 0xffffffff, without a production encoder. Nonce 00..0f is a nonzero 128-bit value. Prefix62 + no payload + CRC32C/footer8 =70 bytes. Literal fields, CRC and raw-file SHA are recorded in barrier.json. + +The production dark-codec tests encode to and decode from these fixed bytes. This is new-API contract coverage, not a fabricated parent behavioral RED or a claim that production recovery selects v3. Wrong-nonce/current-cursor, correct-nonce/wrong-cursor, lap and physical ring admission belong to the later writer/scanner integration, not codec CRC acceptance. + +Existing-caller REDs (foreign WAL replay and old/equal-LSN capture omission) remain on the separate evidence branch at655091e8; they are intentionally absent from the green integration branch until the corresponding fixes land. + +batch.bin uses count2, LBA3 and8192 bytes of0x72; trim.bin uses LBA5 and affected65536 bytes with no payload. Both use LSN7/DurableLSN6/cursor128 and the barrier nonce. Independent literal fields, CRC32C and SHA256 are in additional-vectors.json. These nonzero count/LBA/length vectors prevent a mutually wrong encoder/decoder from passing only by roundtrip. diff --git a/seaweed-block/core/storage/testdata/format_v3/additional-vectors.json b/seaweed-block/core/storage/testdata/format_v3/additional-vectors.json new file mode 100644 index 0000000000..c8399b6697 --- /dev/null +++ b/seaweed-block/core/storage/testdata/format_v3/additional-vectors.json @@ -0,0 +1,26 @@ +[ + { + "file": "batch.bin", + "lsn": 7, + "count": 2, + "lba": 3, + "length": 8192, + "durable_lsn": 6, + "logical_start": 128, + "payload_byte": "72", + "crc32c_hex": "53d5bcbc", + "sha256": "337cc3a7f13c336deb5682c8dfa0c9ab168be56d340b91679ef5eb66304648e0" + }, + { + "file": "trim.bin", + "lsn": 7, + "count": 0, + "lba": 5, + "length": 65536, + "durable_lsn": 6, + "logical_start": 128, + "payload_byte": null, + "crc32c_hex": "870783db", + "sha256": "05cff7670d346efb2b9e693fa9a8b9e4d9c6035d3df933f3dce4b68d301bb589" + } +] diff --git a/seaweed-block/core/storage/testdata/format_v3/barrier.bin b/seaweed-block/core/storage/testdata/format_v3/barrier.bin new file mode 100644 index 0000000000..c28d4e1ad8 Binary files /dev/null and b/seaweed-block/core/storage/testdata/format_v3/barrier.bin differ diff --git a/seaweed-block/core/storage/testdata/format_v3/barrier.json b/seaweed-block/core/storage/testdata/format_v3/barrier.json new file mode 100644 index 0000000000..14fb93c55e --- /dev/null +++ b/seaweed-block/core/storage/testdata/format_v3/barrier.json @@ -0,0 +1,13 @@ +{ + "design_sha256": "c9c652cbe846822dff5c08ce95081b0156e1df0582e6b9766b62e1742ddc1adf", + "kind": "barrier", + "lsn": 7, + "batch_count": 0, + "durable_lsn": 6, + "logical_start": 128, + "nonce_hex": "000102030405060708090a0b0c0d0e0f", + "prefix_bytes": 62, + "entry_size": 70, + "crc32c_hex": "5d1aabd6", + "sha256": "10056856c951fe00bc95a63ccfe021601fb36aaeb08806511066db438304f493" +} diff --git a/seaweed-block/core/storage/testdata/format_v3/batch.bin b/seaweed-block/core/storage/testdata/format_v3/batch.bin new file mode 100644 index 0000000000..6ba0b91231 Binary files /dev/null and b/seaweed-block/core/storage/testdata/format_v3/batch.bin differ diff --git a/seaweed-block/core/storage/testdata/format_v3/reference-page.bin b/seaweed-block/core/storage/testdata/format_v3/reference-page.bin new file mode 100644 index 0000000000..86e42ad3b9 Binary files /dev/null and b/seaweed-block/core/storage/testdata/format_v3/reference-page.bin differ diff --git a/seaweed-block/core/storage/testdata/format_v3/reference-root.bin b/seaweed-block/core/storage/testdata/format_v3/reference-root.bin new file mode 100644 index 0000000000..7dbe821788 Binary files /dev/null and b/seaweed-block/core/storage/testdata/format_v3/reference-root.bin differ diff --git a/seaweed-block/core/storage/testdata/format_v3/slot/EXPECTED.txt b/seaweed-block/core/storage/testdata/format_v3/slot/EXPECTED.txt new file mode 100644 index 0000000000..4c79c1f2b1 --- /dev/null +++ b/seaweed-block/core/storage/testdata/format_v3/slot/EXPECTED.txt @@ -0,0 +1,29 @@ +Slot vectors for DESIGN r12 (raw c9c652cbe846822dff5c08ce95081b0156e1df0582e6b9766b62e1742ddc1adf), section 2. +Each file is one 4096-byte slot; CRC32C (Castagnoli) LE at 4092 unless the case says otherwise. +Map-dependent predicates assume the map fixture vectors/reference-root.bin (rootBodyDigest b47d24af..., C=7, gen 1). + +slot-ref.bin crc32c=d91cb6ba: valid, selectable (2.1-2.3) +slot-installing.bin crc32c=e4e97a9f: valid: installing with BaseCursor within [tail, head], nonzero ID (2.1) +slot-strict.bin crc32c=3f9c7de6: valid: WMode A (2.1, 6.1) +slot-prepared.bin crc32c=7b225d6f: valid but NEVER selectable: prepared, slotGen 1, BaseState none (2.3, 10.1) +neg-crc.bin crc32c=d91cb6bb: INVALID: CRC32C mismatch / torn (2.2.1) +neg-reserved-88.bin crc32c=17d37bf9: INVALID: nonzero reserved byte in 88..127 (2.2.1) +neg-reserved-306.bin crc32c=dbbd4458: INVALID: nonzero reserved byte in 306..319 (2.1) +neg-reserved-320.bin crc32c=78c27673: INVALID: nonzero reserved byte in 320..4091 (2.1) +neg-flags.bin crc32c=4d19b714: INVALID: nonzero flags (2.2.1) +neg-gen0.bin crc32c=befbd3b6: INVALID: slotGen 0 (2.2.2) +neg-nonce0.bin crc32c=2420b892: INVALID: all-zero nonce (2.2.2) +neg-walofs.bin crc32c=03e94503: INVALID: WALOffset != 8192 (2.2.3) +neg-head.bin crc32c=37068518: INVALID: head > tail + WALSize (2.2.3) +neg-wmode2.bin crc32c=11f156f3: INVALID: WMode not 0/1 (2.1) +neg-phase2.bin crc32c=988d17e1: INVALID: MigrationPhase not 0/1 (2.1) +neg-phase1-gen2.bin crc32c=d30bf27b: INVALID: prepared slot with slotGen != 1 (2.1) +neg-phase1-installing.bin crc32c=46d7914a: INVALID: prepared slot with BaseState != none (2.1) +neg-basestate3.bin crc32c=82cac0e2: INVALID: BaseState not 0/1/2 (2.1) +neg-none-with-id.bin crc32c=7b0cd4b1: INVALID: BaseState none with nonzero BaseInstallID (2.1 BASE rules) +neg-installing-zero-id.bin crc32c=46f91894: INVALID: installing with zero BaseInstallID (2.1 BASE rules) +neg-implv1.bin crc32c=2eeac46d: INVALID: v3 with impl 1 (1, combinations) +neg-coverage.bin crc32c=9ede57a3: INVALID: CheckpointLSN 8 > mapCoveredCheckpoint 7 (9.1 predicate 2) +neg-covered-mismatch.bin crc32c=6c40d7e8: INVALID: descriptor mapCoveredCheckpoint != root coveredCheckpoint 7 (9.1 predicate 1) +pair-equal-gen-A.bin crc32c=436d547b: with pair-equal-gen-B: equal slotGen, different bytes -> refuse errSuperblockInvalid (2.3) +pair-equal-gen-B.bin crc32c=7d6e3c65: see pair-equal-gen-A diff --git a/seaweed-block/core/storage/testdata/format_v3/slot/gen_slot_vectors.py b/seaweed-block/core/storage/testdata/format_v3/slot/gen_slot_vectors.py new file mode 100644 index 0000000000..1fc65cd045 --- /dev/null +++ b/seaweed-block/core/storage/testdata/format_v3/slot/gen_slot_vectors.py @@ -0,0 +1,128 @@ +"""Independent generator for DESIGN r12 section 2.1 slot vectors (row 1 fixtures). + +Pure stdlib. CRC32C (Castagnoli, reflected poly 0x82F63B78) implemented here and +self-checked against the standard check value CRC32C(b"123456789") = 0xE3069283. +Writes one positive reference slot and named negative variants, plus EXPECTED.txt. +""" +import struct +import sys +import os + +POLY = 0x82F63B78 +TABLE = [] +for i in range(256): + c = i + for _ in range(8): + c = (c >> 1) ^ POLY if c & 1 else c >> 1 + TABLE.append(c) + + +def crc32c(data: bytes) -> int: + c = 0xFFFFFFFF + for b in data: + c = TABLE[(c ^ b) & 0xFF] ^ (c >> 8) + return c ^ 0xFFFFFFFF + + +assert crc32c(b"123456789") == 0xE3069283, "crc32c self-check failed" + +UUID = bytes(range(0x00, 0x10)) +LINEAGE = bytes(range(0x10, 0x20)) +NONCE = bytes(range(0x20, 0x30)) +# rootBodyDigest of codex03's reference root (DESIGN 9.5): this slot names that map. +ROOT_HASH = bytes.fromhex("b47d24af8db0e0a2cd2494652c981c48f4d2a861c381f4a04cac4b35e2ac321b") + + +def slot(**kw) -> bytearray: + f = dict( + version=3, flags=0, implKind=1, implVersion=3, + volumeSize=64 * 4096, extentSize=64 * 1024, blockSize=4096, + walOffset=8192, walSize=64 * 1024, createdAt=1, slotGen=1, checkpoint=7, + nonce=NONCE, tail=0, head=0, mapFormatID=1, mapGen=1, rootLocator=0, + mapCovered=7, rootHash=ROOT_HASH, lineage=LINEAGE, + W=7, baseLSN=0, baseState=0, baseCursor=0, installID=bytes(16), + wMode=0, migPhase=0, + ) + f.update(kw) + b = bytearray(4096) + b[0:4] = b"SWBK" + struct.pack_into(" bytes: + struct.pack_into(" tail + WALSize (2.2.3)") +neg("neg-wmode2", seal(slot(wMode=2)), "WMode not 0/1 (2.1)") +neg("neg-phase2", seal(slot(migPhase=2)), "MigrationPhase not 0/1 (2.1)") +neg("neg-phase1-gen2", seal(slot(migPhase=1, slotGen=2)), "prepared slot with slotGen != 1 (2.1)") +neg("neg-phase1-installing", seal(slot(migPhase=1, baseState=1, baseLSN=7, installID=IID)), "prepared slot with BaseState != none (2.1)") +neg("neg-basestate3", seal(slot(baseState=3)), "BaseState not 0/1/2 (2.1)") +neg("neg-none-with-id", seal(slot(installID=IID)), "BaseState none with nonzero BaseInstallID (2.1 BASE rules)") +neg("neg-installing-zero-id", seal(slot(baseState=1, baseLSN=7)), "installing with zero BaseInstallID (2.1 BASE rules)") +neg("neg-implv1", seal(slot(implVersion=1)), "v3 with impl 1 (1, combinations)") +neg("neg-coverage", seal(slot(checkpoint=8)), "CheckpointLSN 8 > mapCoveredCheckpoint 7 (9.1 predicate 2)") +neg("neg-covered-mismatch", seal(slot(mapCovered=6)), "descriptor mapCoveredCheckpoint != root coveredCheckpoint 7 (9.1 predicate 1)") +# Selection pairs (2.3): equal slotGen, different bytes -> refuse. +pairA = seal(slot(slotGen=5)) +pairB = seal(slot(slotGen=5, W=8)) +cases.append(("pair-equal-gen-A", pairA, "with pair-equal-gen-B: equal slotGen, different bytes -> refuse errSuperblockInvalid (2.3)")) +cases.append(("pair-equal-gen-B", pairB, "see pair-equal-gen-A")) + +out = sys.argv[1] +os.makedirs(out, exist_ok=True) +with open(os.path.join(out, "EXPECTED.txt"), "w", encoding="utf-8", newline="\n") as e: + e.write("Slot vectors for DESIGN r12 (raw c9c652cbe846822dff5c08ce95081b0156e1df0582e6b9766b62e1742ddc1adf), section 2.\n") + e.write("Each file is one 4096-byte slot; CRC32C (Castagnoli) LE at 4092 unless the case says otherwise.\n") + e.write("Map-dependent predicates assume the map fixture vectors/reference-root.bin (rootBodyDigest b47d24af..., C=7, gen 1).\n\n") + for name, data, why in cases: + assert len(data) == 4096 + with open(os.path.join(out, name + ".bin"), "wb") as fh: + fh.write(data) + e.write(f"{name}.bin crc32c={struct.unpack_from('= a.hardMark { a.notifyFn() hardStart := time.Now() - for a.walUsed() >= a.hardMark { - if a.closedFn() { + for { + pressure, err = sample() + if err != nil { + return err + } + if pressure < a.hardMark { + break + } + if err := a.terminalFault(); err != nil { + a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds()) + return err + } + if !contextual && a.closedFn() { a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds()) return errVolumeClosed } a.notifyFn() select { + case <-ctx.Done(): + a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds()) + if err := a.terminalFault(); err != nil { + return err + } + return admissionContextError(ctx.Err()) case <-deadline.C: a.hardPressureWaitNs.Add(time.Since(hardStart).Nanoseconds()) - return errWALFull + if err := a.terminalFault(); err != nil { + return err + } + return ErrWALPressureTimeout default: } a.sleepFn(2 * time.Millisecond) @@ -142,10 +188,26 @@ func (a *walAdmission) Acquire(timeout time.Duration) error { select { case a.sem <- struct{}{}: return nil + case <-ctx.Done(): + if err := a.terminalFault(); err != nil { + return err + } + return admissionContextError(ctx.Err()) case <-deadline.C: - return errWALFull + if err := a.terminalFault(); err != nil { + return err + } + return ErrWALPressureTimeout case <-closeTick.C: - if a.closedFn() { + if contextual { + if _, err := sample(); err != nil { + return err + } + } + if err := a.terminalFault(); err != nil { + return err + } + if !contextual && a.closedFn() { return errVolumeClosed } } @@ -154,3 +216,19 @@ func (a *walAdmission) Acquire(timeout time.Duration) error { // Release returns a write slot to the semaphore. func (a *walAdmission) Release() { <-a.sem } + +// terminalFault is sampled only on waiting paths. The store supplies its atomic +// latch lookup; this does not acquire a store lock or perform persistence I/O. +func (a *walAdmission) terminalFault() error { + if a.faultFn != nil { + return a.faultFn() + } + return nil +} + +func admissionContextError(err error) error { + if errors.Is(err, context.DeadlineExceeded) { + return ErrWALPressureTimeout + } + return err +} diff --git a/seaweed-block/core/storage/wal_admission_fault_v3_test.go b/seaweed-block/core/storage/wal_admission_fault_v3_test.go new file mode 100644 index 0000000000..fe85a7181e --- /dev/null +++ b/seaweed-block/core/storage/wal_admission_fault_v3_test.go @@ -0,0 +1,117 @@ +package storage + +import ( + "errors" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait(t *testing.T) { + for _, batch := range []bool{false, true} { + name := "write" + if batch { + name = "batch" + } + t.Run(name, func(t *testing.T) { + s := admissionPressureV3(t, 15) + s.admissionTimeout = 40 * time.Millisecond + parked, resume := make(chan struct{}), make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(resume) }) } + t.Cleanup(release) // unblock before the helper's Close cleanup + var sleeps atomic.Int32 + s.admission.sleepFn = func(time.Duration) { + if sleeps.Add(1) == 1 { + close(parked) + <-resume + } else { + time.Sleep(time.Millisecond) + } + } + before := s.NextLSN() + head := s.v3.w.logicalHeadV3() + done := make(chan error, 1) + go func() { + var err error + if batch { + _, err = s.WriteBatch(16, [][]byte{blk(16), blk(17)}) + } else { + _, err = s.Write(16, blk(16)) + } + done <- err + }() + select { + case <-parked: + case <-time.After(2 * time.Second): + t.Fatal("writer did not enter hard-pressure wait") + } + fault := errors.New("injected terminal persistence fault while admission waits") + s.latchV3(fault) + release() + select { + case err := <-done: + if !errors.Is(err, fault) || errors.Is(err, errWALFull) { + t.Fatalf("waiting writer lost terminal cause: %v", err) + } + case <-time.After(2 * time.Second): + t.Fatal("terminal fault did not end wait") + } + if sleeps.Load() != 1 { + t.Fatalf("writer kept polling after terminal fault: sleeps=%d", sleeps.Load()) + } + if s.NextLSN() != before || s.v3.w.logicalHeadV3() != head { + t.Fatal("faulted waiting writer appended or advanced LSN") + } + }) + } +} + +// The same terminal cause must survive a saturated writer semaphore even +// without hard WAL pressure; the store's normal append guard is too late there. +func TestWALStoreV3AdmissionReturnsFaultWhileWaitingForWriterSlot(t *testing.T) { + s := admissionPressureV3(t, 0) + s.admissionTimeout = 40 * time.Millisecond + for i := 0; i < cap(s.admission.sem); i++ { + s.admission.sem <- struct{}{} + } + t.Cleanup(func() { + for i := 0; i < cap(s.admission.sem); i++ { + <-s.admission.sem + } + }) + entered, resume := make(chan struct{}), make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(resume) }) } + t.Cleanup(release) + var sampled sync.Once + // Observe the real semaphore wait's terminal check. Pressure sampling now + // uses the command-aware callback instead of the legacy float callback. + s.admission.faultFn = func() error { + sampled.Do(func() { close(entered) }) + <-resume + return s.stickyIOFault() + } + done := make(chan error, 1) + go func() { _, err := s.Write(0, blk(1)); done <- err }() + select { + case <-entered: + case <-time.After(2 * time.Second): + t.Fatal("write never reached admission") + } + fault := errors.New("terminal persistence fault while writer slots are full") + s.latchV3(fault) + release() + select { + case err := <-done: + if !errors.Is(err, fault) || errors.Is(err, errWALFull) { + t.Fatalf("slot waiter lost cause: %v", err) + } + case <-time.After(2 * time.Second): + t.Fatal("fault did not release slot waiter") + } + if s.NextLSN() != 1 { + t.Fatal("faulted slot waiter appended") + } +} diff --git a/seaweed-block/core/storage/wal_entry_v3.go b/seaweed-block/core/storage/wal_entry_v3.go new file mode 100644 index 0000000000..b0f4a70aa9 --- /dev/null +++ b/seaweed-block/core/storage/wal_entry_v3.go @@ -0,0 +1,184 @@ +package storage + +import ( + "encoding/binary" + "fmt" + "hash/crc32" + "math" + "time" +) + +// The impl-3 codec is deliberately separate from the 38-byte impl-1 codec. +// No production writer, reader or recovery path selects it before activation. +const ( + walEntryPrefixSizeV3 = 62 + walEntryHeaderSizeV3 = 70 // prefix plus CRC32C and EntrySize +) + +var walEntryCRC32CV3 = crc32.MakeTable(crc32.Castagnoli) + +type walEntryV3 struct { + LSN uint64 + BatchCount uint64 + Type uint8 + Flags uint8 + LBA uint64 + Length uint32 + DurableLSN uint64 + LogicalStart uint64 + Nonce [16]byte + Data []byte +} + +// payloadSizeV3 validates header arithmetic before reading or allocating the +// payload. The reader passes geometry from the selected, validated descriptor. +// Nonce equality, exact expected cursor and lap admission belong to the scanner; +// a valid CRC here alone never makes a record trustworthy for replay. +func (e walEntryV3) payloadSizeV3(blockSize uint32, numBlocks uint64) (uint64, error) { + invalid := func(why string) (uint64, error) { return 0, fmt.Errorf("%w: v3 %s", errInvalidEntry, why) } + if blockSize == 0 || numBlocks == 0 || numBlocks > counterMaxV3/uint64(blockSize) { + return invalid("invalid volume geometry") + } + if e.Nonce == ([16]byte{}) || e.Flags != 0 { + return invalid("nonce or flags") + } + if e.LSN > counterMaxV3 || e.DurableLSN > counterMaxV3 || e.LogicalStart > counterMaxV3 || e.LBA > counterMaxV3 || e.BatchCount > counterMaxV3 { + return 0, ErrCounterExhausted + } + if e.Type != walEntryPadding && e.LSN == 0 { + return invalid("zero record LSN") + } + var payload, blocks uint64 + switch e.Type { + case walEntryWrite: + if e.BatchCount != 0 || e.Length != blockSize { + return invalid("single write geometry") + } + blocks = 1 + payload = uint64(e.Length) + case walEntryWriteBatch: + if e.BatchCount == 0 { + return invalid("empty batch") + } + if e.BatchCount > counterMaxV3/uint64(blockSize) || e.BatchCount-1 > counterMaxV3-e.LSN { + return 0, ErrCounterExhausted + } + blocks = e.BatchCount + payload = blocks * uint64(blockSize) + if payload != uint64(e.Length) { + return invalid("batch payload length") + } + case walEntryTrim: + if e.BatchCount != 0 || e.Length == 0 || e.Length%blockSize != 0 { + return invalid("trim geometry") + } + blocks = uint64(e.Length / blockSize) + case walEntryBarrier: + if e.BatchCount != 0 || e.Length != 0 { + return invalid("barrier geometry") + } + case walEntryPadding: + if e.BatchCount != 0 || e.LSN != 0 || e.LBA != 0 || e.DurableLSN != 0 { + return invalid("padding header") + } + payload = uint64(e.Length) + default: + return invalid("unknown record type") + } + if blocks > 0 && (e.LBA >= numBlocks || blocks > numBlocks-e.LBA) { + return invalid("LBA span outside volume") + } + // EntrySize is a 32-bit wire field. Never truncate it or an allocation size. + if payload > math.MaxUint32-walEntryHeaderSizeV3 || payload > uint64(int(^uint(0)>>1))-walEntryHeaderSizeV3 { + return invalid("encoded record too large") + } + if uint64(walEntryHeaderSizeV3)+payload > counterMaxV3-e.LogicalStart { + return 0, ErrCounterExhausted + } + return payload, nil +} + +func encodeWALEntryV3(e walEntryV3, blockSize uint32, numBlocks uint64) ([]byte, error) { + return encodeWALEntryV3Instrumented(e, blockSize, numBlocks, nil) +} + +func encodeWALEntryV3Instrumented(e walEntryV3, blockSize uint32, numBlocks uint64, instr *writeInstrumentation) ([]byte, error) { + start := time.Now() + n, err := e.payloadSizeV3(blockSize, numBlocks) + if err != nil { + return nil, err + } + if uint64(len(e.Data)) != n { + return nil, fmt.Errorf("%w: v3 payload size", errInvalidEntry) + } + if e.Type == walEntryPadding { + for _, b := range e.Data { + if b != 0 { + return nil, fmt.Errorf("%w: v3 nonzero padding", errInvalidEntry) + } + } + } + buf := make([]byte, walEntryHeaderSizeV3+int(n)) + le := binary.LittleEndian + le.PutUint64(buf[0:8], e.LSN) + le.PutUint64(buf[8:16], e.BatchCount) + buf[16] = e.Type + buf[17] = e.Flags + le.PutUint64(buf[18:26], e.LBA) + le.PutUint32(buf[26:30], e.Length) + le.PutUint64(buf[30:38], e.DurableLSN) + le.PutUint64(buf[38:46], e.LogicalStart) + copy(buf[46:62], e.Nonce[:]) + end := walEntryPrefixSizeV3 + int(n) + copyStart := time.Now() + copy(buf[walEntryPrefixSizeV3:end], e.Data) + if instr != nil { + instr.recordWALCopy(len(e.Data), time.Since(copyStart)) + } + checksumStart := time.Now() + le.PutUint32(buf[end:end+4], crc32.Checksum(buf[:end], walEntryCRC32CV3)) + if instr != nil { + instr.recordWALChecksum(end, time.Since(checksumStart)) + } + le.PutUint32(buf[end+4:end+8], uint32(len(buf))) + if instr != nil { + instr.recordWALEncode(len(buf), time.Since(start)) + } + return buf, nil +} + +func decodeWALEntryV3(buf []byte, blockSize uint32, numBlocks uint64) (walEntryV3, error) { + if len(buf) < walEntryHeaderSizeV3 { + return walEntryV3{}, errEntryTruncated + } + le := binary.LittleEndian + e := walEntryV3{LSN: le.Uint64(buf[0:8]), BatchCount: le.Uint64(buf[8:16]), Type: buf[16], Flags: buf[17], LBA: le.Uint64(buf[18:26]), Length: le.Uint32(buf[26:30]), DurableLSN: le.Uint64(buf[30:38]), LogicalStart: le.Uint64(buf[38:46])} + copy(e.Nonce[:], buf[46:62]) + n, err := e.payloadSizeV3(blockSize, numBlocks) + if err != nil { + return walEntryV3{}, err + } + size := uint64(walEntryHeaderSizeV3) + n + if size > uint64(len(buf)) { + return walEntryV3{}, errEntryTruncated + } + end := walEntryPrefixSizeV3 + int(n) + if le.Uint32(buf[end+4:end+8]) != uint32(size) { + return walEntryV3{}, fmt.Errorf("%w: v3 EntrySize", errInvalidEntry) + } + if le.Uint32(buf[end:end+4]) != crc32.Checksum(buf[:end], walEntryCRC32CV3) { + return walEntryV3{}, errCRCMismatch + } + if e.Type == walEntryPadding { + for _, b := range buf[walEntryPrefixSizeV3:end] { + if b != 0 { + return walEntryV3{}, fmt.Errorf("%w: v3 nonzero padding", errInvalidEntry) + } + } + } + // Only copy after geometry, source bounds, CRC and footer all validate. + if n > 0 { + e.Data = append([]byte(nil), buf[walEntryPrefixSizeV3:end]...) + } + return e, nil +} diff --git a/seaweed-block/core/storage/wal_entry_v3_contract_test.go b/seaweed-block/core/storage/wal_entry_v3_contract_test.go new file mode 100644 index 0000000000..b914de553d --- /dev/null +++ b/seaweed-block/core/storage/wal_entry_v3_contract_test.go @@ -0,0 +1,254 @@ +package storage + +// Row 2 NEW-API contract coverage, prepared before the codec exists. +// Missing walEntryV3/encodeWALEntryV3/decodeWALEntryV3 is NOT a behavioral +// RED. These names are internal codec seams owned by row 2. Slot nonce and +// geometry are passed as values; this test does not invent a slot codec. + +import ( + "bytes" + "encoding/binary" + "hash/crc32" + "os" + "reflect" + "testing" +) + +const v3TestBlockSize uint32 = 4096 +const v3TestNumBlocks uint64 = 1024 + +func v3TestBarrier() walEntryV3 { + var nonce [16]byte + for i := range nonce { + nonce[i] = byte(i) + } + return walEntryV3{LSN: 7, Type: walEntryBarrier, DurableLSN: 6, LogicalStart: 128, Nonce: nonce} +} + +func TestWALEntryV3_CanonicalBarrierBytes(t *testing.T) { + want, err := os.ReadFile("testdata/format_v3/barrier.bin") + if err != nil { + t.Fatal(err) + } + entry := v3TestBarrier() + got, err := encodeWALEntryV3(entry, v3TestBlockSize, v3TestNumBlocks) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatalf("encoded barrier differs from independent signed-layout vector: %x", got) + } + decoded, err := decodeWALEntryV3(want, v3TestBlockSize, v3TestNumBlocks) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(decoded, entry) { + t.Fatalf("decoded barrier=%+v want %+v", decoded, entry) + } +} + +func TestWALEntryV3_TypeFootprints(t *testing.T) { + for _, tc := range []struct { + name string + kind uint8 + count uint64 + length uint32 + data []byte + size int + }{ + {"single block", walEntryWrite, 0, 4096, bytes.Repeat([]byte{0x91}, 4096), 4166}, + {"batch", walEntryWriteBatch, 2, 8192, bytes.Repeat([]byte{0x72}, 8192), 8262}, + {"large trim no payload", walEntryTrim, 0, 65536, nil, 70}, + {"barrier", walEntryBarrier, 0, 0, nil, 70}, + {"padding", walEntryPadding, 0, 12, make([]byte, 12), 82}, + } { + t.Run(tc.name, func(t *testing.T) { + e := v3TestBarrier() + e.Type = tc.kind + e.BatchCount = tc.count + e.Length = tc.length + e.Data = tc.data + if tc.kind == walEntryPadding { + e.LSN = 0 + e.DurableLSN = 0 + } + b, err := encodeWALEntryV3(e, v3TestBlockSize, v3TestNumBlocks) + if err != nil { + t.Fatal(err) + } + if len(b) != tc.size { + t.Fatalf("footprint=%d want %d", len(b), tc.size) + } + if binary.LittleEndian.Uint32(b[len(b)-4:]) != uint32(tc.size) { + t.Fatal("incorrect EntrySize footer") + } + // Return every logical field, not merely an equal CRC or payload. + got, err := decodeWALEntryV3(b, v3TestBlockSize, v3TestNumBlocks) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, e) { + t.Fatalf("decoded=%+v want %+v", got, e) + } + }) + } +} + +func TestWALEntryV3_RefusesInvalidEncode(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*walEntryV3) + }{ + {"unknown type", func(e *walEntryV3) { e.Type = 0x55 }}, + {"flags", func(e *walEntryV3) { e.Flags = 1 }}, + {"zero nonce", func(e *walEntryV3) { e.Nonce = [16]byte{} }}, + {"barrier payload", func(e *walEntryV3) { e.Data = []byte{1}; e.Length = 1 }}, + {"nonbatch count", func(e *walEntryV3) { e.BatchCount = 1 }}, + {"write short", func(e *walEntryV3) { e.Type = walEntryWrite; e.Length = 1; e.Data = []byte{1} }}, + {"write long", func(e *walEntryV3) { e.Type = walEntryWrite; e.Length = 8192; e.Data = make([]byte, 8192) }}, + {"batch zero count", func(e *walEntryV3) { e.Type = walEntryWriteBatch; e.Length = 4096; e.Data = make([]byte, 4096) }}, + {"batch length mismatch", func(e *walEntryV3) { + e.Type = walEntryWriteBatch + e.BatchCount = 2 + e.Length = 4096 + e.Data = make([]byte, 4096) + }}, + {"batch count overflow", func(e *walEntryV3) { + e.Type = walEntryWriteBatch + e.BatchCount = ^uint64(0) + e.Length = 4096 + e.Data = make([]byte, 4096) + }}, + {"batch LSN overflow", func(e *walEntryV3) { + e.Type = walEntryWriteBatch + e.LSN = ^uint64(0) - 1 + e.BatchCount = 2 + e.Length = 8192 + e.Data = make([]byte, 8192) + }}, + {"batch LBA span", func(e *walEntryV3) { + e.Type = walEntryWriteBatch + e.LBA = v3TestNumBlocks - 1 + e.BatchCount = 2 + e.Length = 8192 + e.Data = make([]byte, 8192) + }}, + {"trim outside volume", func(e *walEntryV3) { e.Type = walEntryTrim; e.LBA = v3TestNumBlocks - 1; e.Length = 8192 }}, + {"trim payload", func(e *walEntryV3) { e.Type = walEntryTrim; e.Length = 4096; e.Data = []byte{1} }}, + {"padding data nonzero", func(e *walEntryV3) { + e.Type = walEntryPadding + e.LSN = 0 + e.DurableLSN = 0 + e.Length = 1 + e.Data = []byte{1} + }}, + {"padding LSN", func(e *walEntryV3) { e.Type = walEntryPadding; e.DurableLSN = 0 }}, + {"padding DurableLSN", func(e *walEntryV3) { e.Type = walEntryPadding; e.LSN = 0 }}, + {"padding LBA", func(e *walEntryV3) { e.Type = walEntryPadding; e.LSN = 0; e.DurableLSN = 0; e.LBA = 1 }}, + {"zero normal LSN", func(e *walEntryV3) { e.LSN = 0 }}, + {"LSN exhausted", func(e *walEntryV3) { e.LSN = ^uint64(0) }}, + {"durable exhausted", func(e *walEntryV3) { e.DurableLSN = ^uint64(0) }}, + {"cursor size overflow", func(e *walEntryV3) { e.LogicalStart = ^uint64(0) - 30 }}, + } { + t.Run(tc.name, func(t *testing.T) { + e := v3TestBarrier() + tc.edit(&e) + if _, err := encodeWALEntryV3(e, v3TestBlockSize, v3TestNumBlocks); err == nil { + t.Fatal("invalid record admitted") + } + }) + } +} + +func TestWALEntryV3_RefusesMalformedWire(t *testing.T) { + original, err := os.ReadFile("testdata/format_v3/barrier.bin") + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + edit func([]byte) + repairCRC bool + }{ + {"CRC", func(b []byte) { b[62] ^= 1 }, false}, + {"footer", func(b []byte) { b[66] ^= 1 }, false}, + {"unknown type valid CRC", func(b []byte) { b[16] = 0x55 }, true}, + {"flags valid CRC", func(b []byte) { b[17] = 1 }, true}, + {"count valid CRC", func(b []byte) { b[8] = 1 }, true}, + {"zero nonce valid CRC", func(b []byte) { clear(b[46:62]) }, true}, + {"huge length valid CRC", func(b []byte) { binary.LittleEndian.PutUint32(b[26:30], ^uint32(0)) }, true}, + } { + t.Run(tc.name, func(t *testing.T) { + b := bytes.Clone(original) + tc.edit(b) + if tc.repairCRC { + binary.LittleEndian.PutUint32(b[62:66], crc32.Checksum(b[:62], crc32.MakeTable(crc32.Castagnoli))) + } + if _, err := decodeWALEntryV3(b, v3TestBlockSize, v3TestNumBlocks); err == nil { + t.Fatal("malformed wire record admitted") + } + }) + } + for n := 0; n < len(original); n++ { + if _, err := decodeWALEntryV3(original[:n], v3TestBlockSize, v3TestNumBlocks); err == nil { + t.Fatalf("truncated size%d admitted", n) + } + } +} + +// Native fuzzing runs later against the actual decoder. Seed execution belongs +// to the row-2 package tests; allocation bounds must precede copying payload. +func FuzzWALEntryV3_DecodeNeverPanics(f *testing.F) { + b, err := os.ReadFile("testdata/format_v3/barrier.bin") + if err != nil { + f.Fatal(err) + } + f.Add(b) + f.Add([]byte{}) + f.Add(bytes.Repeat([]byte{0xff}, 70)) + f.Fuzz(func(t *testing.T, b []byte) { + if len(b) > 16384 { + t.Skip() + } + _, _ = decodeWALEntryV3(b, v3TestBlockSize, v3TestNumBlocks) + }) +} + +// Nonzero count/LBA/Length vectors keep a mutually-wrong encoder and decoder +// from passing solely by roundtrip. Expected bytes use the independent fixture. +func TestWALEntryV3_CanonicalBatchAndTrimBytes(t *testing.T) { + for _, name := range []string{"batch", "trim"} { + t.Run(name, func(t *testing.T) { + e := v3TestBarrier() + if name == "batch" { + e.Type = walEntryWriteBatch + e.BatchCount = 2 + e.LBA = 3 + e.Length = 8192 + e.Data = bytes.Repeat([]byte{0x72}, 8192) + } else { + e.Type = walEntryTrim + e.LBA = 5 + e.Length = 65536 + } + want, err := os.ReadFile("testdata/format_v3/" + name + ".bin") + if err != nil { + t.Fatal(err) + } + got, err := encodeWALEntryV3(e, v3TestBlockSize, v3TestNumBlocks) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatal("record differs from independent count/LBA/length vector") + } + decoded, err := decodeWALEntryV3(want, v3TestBlockSize, v3TestNumBlocks) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(decoded, e) { + t.Fatalf("decoded vector differs: %+v", decoded) + } + }) + } +} diff --git a/seaweed-block/core/storage/wal_io_v3.go b/seaweed-block/core/storage/wal_io_v3.go new file mode 100644 index 0000000000..f89e568695 --- /dev/null +++ b/seaweed-block/core/storage/wal_io_v3.go @@ -0,0 +1,414 @@ +package storage + +import ( + "encoding/binary" + "errors" + "fmt" + "io" + "math" + "os" + "sort" + "sync" + "time" +) + +var errWALBindingV3 = errors.New("storage: v3 WAL nonce/cursor binding refused") + +// ErrWALLSNOrder refuses a v3 append whose first LSN does not exceed every +// previously appended LSN. This keeps the physical and logical prefixes aligned. +var ErrWALLSNOrder = errors.New("storage: v3 WAL LSN must strictly increase") + +// walSnapshotV3 takes the descriptor and its reuse floor in one snapshot. +// It releases descMu before any writer lock, pwrite or callback is acquired. +func (p *descriptorPublisherV3) walSnapshotV3() (descriptorV3, uint64, bool) { + p.descMu.Lock() + defer p.descMu.Unlock() + floor, ok := p.reuseFloorLocked() + return p.cur, floor, ok +} + +// walWriterV3 is dark until activation. Its caller serializes store changes, +// supplies the frozen acknowledged frontier for DurableLSN, and admits appends +// only after recovery/fence/head publication (rows 5/11). It performs pwrite, +// not Sync. A pwrite failure is terminal here and must also latch the store's +// append fault when integrated. No descriptor publication is hidden in append. +type walWriterV3 struct { + mu sync.Mutex + pub *descriptorPublisherV3 + nonce [16]byte + head uint64 + highestLSN uint64 // includes the last LSN consumed by a batch + failed error + writeAt func([]byte, int64) (int, error) + // Volatile record boundaries, never payloads. Recovery reconstructs + // only the trusted kept prefix; a batch is one indivisible point. + reclaim []walReclaimPointV3 + instr *writeInstrumentation +} + +type walReclaimPointV3 struct{ lastLSN, end uint64 } + +func newWALWriterV3(fd *os.File, pub *descriptorPublisherV3) (*walWriterV3, error) { + d, _, ok := pub.walSnapshotV3() + if err := d.validate(pub.accept); err != nil { + return nil, err + } + if d.WALSize > uint64(math.MaxInt64)-d.WALOffset { + return nil, ErrCounterExhausted + } + if !ok || d.MigrationPhase != MigrationNormal { + return nil, errWALBindingV3 + } + return &walWriterV3{pub: pub, nonce: d.Nonce, head: d.RetainedHead, highestLSN: max(d.CheckpointLSN, d.BaseLSN), writeAt: fd.WriteAt}, nil +} + +// budget (nil = none) is the guest command's budget: checked after the +// descriptor snapshot, the writer lock wait and the encoding, before the first +// physical write, so an expired command starts no new payload I/O (#252). It +// never cancels a write already started. +func (w *walWriterV3) append(e walEntryV3, durableLSN uint64, budget func() error) (uint64, error) { + // Descriptor snapshot precedes the writer lock. A concurrent floor advance + // makes this snapshot conservative; reset must quiesce/recreate the writer. + d, floor, ok := w.pub.walSnapshotV3() + lockStart := time.Now() + w.mu.Lock() + if w.instr != nil { + w.instr.recordWALAppendLockWait(time.Since(lockStart)) + } + defer w.mu.Unlock() + if w.failed != nil { + return 0, w.failed + } + if err := w.pub.io.sticky(); err != nil { + return 0, err + } + if !ok || d.Nonce != w.nonce || w.head < floor || w.head-floor > d.WALSize { + return 0, errWALBindingV3 + } + // Only both-slot-released points may leave the bounded index. + nReleased := 0 + for nReleased < len(w.reclaim) && w.reclaim[nReleased].end <= floor { + nReleased++ + } + if nReleased > 0 { + copy(w.reclaim, w.reclaim[nReleased:]) + w.reclaim = w.reclaim[:len(w.reclaim)-nReleased] + } + if e.LSN <= w.highestLSN { + return 0, fmt.Errorf("%w: first %d after %d", ErrWALLSNOrder, e.LSN, w.highestLSN) + } + + e.Nonce = w.nonce + e.LogicalStart = w.head + e.DurableLSN = durableLSN + n, err := e.payloadSizeV3(d.BlockSize, d.VolumeSize/uint64(d.BlockSize)) + if err != nil { + return 0, err + } + size := uint64(walEntryHeaderSizeV3) + n + if size > d.WALSize { + return 0, errWALFull + } + remaining := d.WALSize - w.head%d.WALSize + gap := uint64(0) + if size > remaining { + gap = remaining + } + if gap > counterMaxV3-w.head || size > counterMaxV3-w.head-gap { + return 0, ErrCounterExhausted + } + free := d.WALSize - (w.head - floor) + if gap > free || size > free-gap { + return 0, errWALFull + } + start := w.head + gap + e.LogicalStart = start + buf, err := encodeWALEntryV3Instrumented(e, d.BlockSize, d.VolumeSize/uint64(d.BlockSize), w.instr) + if err != nil { + return 0, err + } + var pad []byte + if gap >= walEntryHeaderSizeV3 { + if gap-walEntryHeaderSizeV3 > uint64(^uint32(0)) { + return 0, errWALFull + } + pad, err = encodeWALEntryV3(walEntryV3{Type: walEntryPadding, Length: uint32(gap - walEntryHeaderSizeV3), LogicalStart: w.head, Nonce: w.nonce, Data: make([]byte, int(gap-walEntryHeaderSizeV3))}, d.BlockSize, d.VolumeSize/uint64(d.BlockSize)) + if err != nil { + return 0, err + } + } + write := func(b []byte, pos uint64) error { + start := time.Now() + n, err := w.writeAt(b, int64(d.WALOffset+pos%d.WALSize)) + if w.instr != nil { + w.instr.recordWALAppend(n, time.Since(start)) + } + if err == nil && n != len(b) { + err = io.ErrShortWrite + } + if err != nil { + w.failed = fmt.Errorf("%w: v3 append: %w", errWALPwrite, err) + return w.failed + } + return nil + } + if budget != nil { + if err := budget(); err != nil { + return 0, err + } + } + if len(pad) > 0 { + if err := write(pad, w.head); err != nil { + return 0, err + } + } + if gap > 0 && w.instr != nil { + w.instr.recordWALAppendWrap(gap) + } + // A suffix shorter than 70 is skipped geometrically, never decoded as a record. + if err := write(buf, start); err != nil { + return 0, err + } + w.head = start + size + w.highestLSN = e.LSN + if e.Type == walEntryWriteBatch { + w.highestLSN += e.BatchCount - 1 + } + w.reclaim = append(w.reclaim, walReclaimPointV3{w.highestLSN, w.head}) + return start % d.WALSize, nil +} + +// reclaimThroughV3 returns only a complete, validated record boundary. +// Caller serializes recovery/reset with syncMu; appends can only extend +// the index with higher LSNs. No descriptor lock or I/O is taken here. +func (w *walWriterV3) reclaimThroughV3(lsn uint64) uint64 { + w.mu.Lock() + defer w.mu.Unlock() + var end uint64 + for _, point := range w.reclaim { + if point.lastLSN > lsn { + break + } + end = point.end + } + return end +} + +func (w *walWriterV3) logicalHeadV3() uint64 { w.mu.Lock(); defer w.mu.Unlock(); return w.head } + +// advanceHeadV3 moves the writer forward to p, never back. Plan row 11: a +// covering supersession after an installing reopen restarts the writer at +// P = max(E, persisted retainedHead) after the drop fence zeroed [E, ...). +// It is not a restore: no LSN state changes. +func (w *walWriterV3) advanceHeadV3(p uint64) error { + w.mu.Lock() + defer w.mu.Unlock() + if p < w.head { + return fmt.Errorf("%w: writer head %d cannot move back to %d", errWALBindingV3, w.head, p) + } + w.head = p + return nil +} + +// restoreScanV3 restores only the validated cursor. It does not grant admission: +// the owner must complete the durable drop fence and descriptor publication +// before another append. No ring/nonce reset or floor waiver occurs here. +func (w *walWriterV3) restoreScanV3(r walScanResultV3) error { + d, floor, ok := w.pub.walSnapshotV3() + w.mu.Lock() + defer w.mu.Unlock() + if !ok || r.Nonce != w.nonce || d.Nonce != w.nonce || r.End < floor || r.End-floor > d.WALSize { + return errWALBindingV3 + } + if r.End > counterMaxV3 || r.Frontier > counterMaxV3 { + return ErrCounterExhausted + } + if r.Frontier < max(d.CheckpointLSN, d.BaseLSN) { + return errWALBindingV3 + } + w.head = r.End + // The owner fences any dropped suffix first. Its raw HighestLSN must not + // pin the allocator after that suffix has been discarded. + w.highestLSN = r.Frontier + w.indexReclaimScanLockedV3(r) + return nil +} + +// rememberReclaimScanV3 is physical-recovery bookkeeping only. It does +// NOT restore or rewind the writer position/LSN, including on an +// installing reopen whose suffix cannot be admitted until resume. +func (w *walWriterV3) rememberReclaimScanV3(r walScanResultV3) error { + w.mu.Lock() + defer w.mu.Unlock() + if r.Nonce != w.nonce { + return errWALBindingV3 + } + w.indexReclaimScanLockedV3(r) + return nil +} + +func (w *walWriterV3) indexReclaimScanLockedV3(r walScanResultV3) { + w.reclaim = w.reclaim[:0] + for _, rec := range r.Records { + if rec.End > r.End { + break + } + last := rec.Entry.LSN + if rec.Entry.Type == walEntryWriteBatch { + last += rec.Entry.BatchCount - 1 + } + if last > r.Frontier { + break + } + if rec.Entry.Type == walEntryWrite || rec.Entry.Type == walEntryWriteBatch { + w.reclaim = append(w.reclaim, walReclaimPointV3{last, rec.End}) + } + } +} + +type walScannedRecordV3 struct { + Entry walEntryV3 + End uint64 +} + +// walScanResultV3 is a read-only scan result, not a ready/ACK permission. +// Row 5 consumes Frontier/MaxDurableLSN for R uint64(info.Size()) || d.WALOffset > uint64(info.Size())-d.WALSize { + return r, io.ErrUnexpectedEOF + } + if d.MigrationPhase != MigrationNormal { + return r, ErrMigrationIncomplete + } + // The mathematical lap end may exceed the last representable cursor. + // Clamp the scan, not the acknowledged history: exhaustion refuses NEW + // appends but must not make a valid last record unrecoverable. + limit := uint64(counterMaxV3) + if d.WALSize <= counterMaxV3-d.RetainedTail { + limit = d.RetainedTail + d.WALSize + } + start := d.RetainedTail + base := d.CheckpointLSN + if d.BaseState != BaseNone { + start = max(start, d.BaseCursor) + base = max(base, d.BaseLSN) + } + r.Start = start + r.End = start + r.Frontier = base + r.HighestLSN = base + for cursor := start; cursor < limit; { + remaining := d.WALSize - cursor%d.WALSize + if remaining < walEntryHeaderSizeV3 { + if remaining > limit-cursor { + break + } + cursor += remaining + r.End = cursor + continue + } + if limit-cursor < walEntryHeaderSizeV3 { + break + } + header := make([]byte, walEntryPrefixSizeV3) + if _, err := fd.ReadAt(header, int64(d.WALOffset+cursor%d.WALSize)); err != nil { + if errors.Is(err, io.EOF) { + r.StopCause = errEntryTruncated + break + } + return r, err + } + // Check the binding BEFORE using attacker-controlled Length or count. + le := binary.LittleEndian + var nonce [16]byte + copy(nonce[:], header[46:62]) + if nonce != d.Nonce || le.Uint64(header[38:46]) != cursor { + r.StopCause = errWALBindingV3 + break + } + e := walEntryV3{LSN: le.Uint64(header[0:8]), BatchCount: le.Uint64(header[8:16]), Type: header[16], Flags: header[17], LBA: le.Uint64(header[18:26]), Length: le.Uint32(header[26:30]), DurableLSN: le.Uint64(header[30:38]), LogicalStart: cursor, Nonce: nonce} + n, err := e.payloadSizeV3(d.BlockSize, d.VolumeSize/uint64(d.BlockSize)) + if err != nil { + r.StopCause = err + break + } + size := uint64(walEntryHeaderSizeV3) + n + if (e.Type == walEntryPadding && size != remaining) || size > remaining || size > limit-cursor { + r.StopCause = errEntryTruncated + break + } + buf := make([]byte, int(size)) + if _, err := fd.ReadAt(buf, int64(d.WALOffset+cursor%d.WALSize)); err != nil { + if errors.Is(err, io.EOF) { + r.StopCause = errEntryTruncated + break + } + return r, err + } + e, err = decodeWALEntryV3(buf, d.BlockSize, d.VolumeSize/uint64(d.BlockSize)) + if err != nil { + r.StopCause = err + break + } + if e.Nonce != d.Nonce || e.LogicalStart != cursor || uint64(walEntryHeaderSizeV3+len(e.Data)) != size { + r.StopCause = errWALBindingV3 + break + } + cursor += size + r.End = cursor + if e.Type == walEntryPadding { + continue + } + r.MaxDurableLSN = max(r.MaxDurableLSN, e.DurableLSN) + last := e.LSN + if e.Type == walEntryWriteBatch { + last += e.BatchCount - 1 + } + r.HighestLSN = max(r.HighestLSN, last) + r.Records = append(r.Records, walScannedRecordV3{Entry: e, End: cursor}) + } + // LSN interval union, not an expansion proportional to an untrusted LSN gap + // or batch count. Record geometry and endpoints have already been validated. + type interval struct{ first, last uint64 } + spans := make([]interval, 0, len(r.Records)) + for _, record := range r.Records { + e := record.Entry + last := e.LSN + if e.Type == walEntryWriteBatch { + last += e.BatchCount - 1 + } + spans = append(spans, interval{e.LSN, last}) + } + sort.Slice(spans, func(i, j int) bool { return spans[i].first < spans[j].first }) + for _, span := range spans { + if r.Frontier == counterMaxV3 || span.first > r.Frontier+1 { + break + } + r.Frontier = max(r.Frontier, span.last) + } + return r, nil +} diff --git a/seaweed-block/core/storage/wal_io_v3_test.go b/seaweed-block/core/storage/wal_io_v3_test.go new file mode 100644 index 0000000000..1190ff70a1 --- /dev/null +++ b/seaweed-block/core/storage/wal_io_v3_test.go @@ -0,0 +1,434 @@ +package storage + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "hash/crc32" + "io" + "os" + "path/filepath" + "sync" + "testing" + "time" +) + +// A real file with row-1 slots and row-3 publisher; no v2 constructor or +// legacy recovery scanner is used by this dark writer/scanner harness. +func newWALIOTestV3(t *testing.T, head, tail uint64) (*os.File, *descriptorPublisherV3, *walWriterV3) { + t.Helper() + d, err := decodeSlotV3(readSlotVector(t, "slot-ref"), nil) + if err != nil { + t.Fatal(err) + } + d.WALSize = 16 * 1024 + d.RetainedHead = head + d.RetainedTail = tail + d.W = 0 + d.CheckpointLSN = 0 + d.MapCoveredCheckpoint = 0 + d.BaseState = BaseNone + d.BaseLSN = 0 + d.BaseCursor = 0 + d.BaseInstallID = [16]byte{} + f, err := os.Create(filepath.Join(t.TempDir(), "store.v3")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = f.Close() }) + if err := f.Truncate(int64(d.WALOffset + d.WALSize + d.VolumeSize)); err != nil { + t.Fatal(err) + } + if _, err := f.WriteAt(d.encode(), slotAOffsetV3); err != nil { + t.Fatal(err) + } + var leaf sync.Mutex + pub := newDescriptorPublisherV3(d, slotA, nil, descriptorIOV3{ + writeSlot: func(off int64, b []byte) error { + n, e := f.WriteAt(b, off) + if e == nil && n != len(b) { + return io.ErrShortWrite + } + return e + }, + fsync: f.Sync, sticky: func() error { return nil }, + syncFile: func(write, sync func() error) error { + leaf.Lock() + defer leaf.Unlock() + if err := write(); err != nil { + return err + } + return sync() + }, + }) + w, err := newWALWriterV3(f, pub) + if err != nil { + t.Fatal(err) + } + return f, pub, w +} + +func TestWALIOV3_RealWriterReopenScan(t *testing.T) { + f, p, w := newWALIOTestV3(t, 0, 0) + d := p.current() + for i := uint64(1); i <= 3; i++ { + e := walEntryV3{LSN: i, Type: walEntryWrite, LBA: i, Length: d.BlockSize, Data: bytes.Repeat([]byte{byte(i)}, int(d.BlockSize))} + // Caller binding fields are overwritten, not trusted. + e.Nonce = [16]byte{0xFF} + e.LogicalStart = 999 + if _, err := w.append(e, i-1, nil); err != nil { + t.Fatal(err) + } + } + if err := f.Sync(); err != nil { + t.Fatal(err) + } + // Close/reopen is real; slots still lag the appends, as in mode C. + name := f.Name() + if err := f.Close(); err != nil { + t.Fatal(err) + } + rfd, err := os.Open(name) + if err != nil { + t.Fatal(err) + } + defer rfd.Close() + r, err := scanWALV3(rfd, d) + if err != nil { + t.Fatal(err) + } + if len(r.Records) != 3 || r.Frontier != 3 || r.HighestLSN != 3 || r.MaxDurableLSN != 2 || r.End != w.logicalHeadV3() { + t.Fatalf("validated scan=%+v", r) + } + for i, record := range r.Records { + e := record.Entry + if e.Nonce != d.Nonce || e.LogicalStart != uint64(i)*(uint64(d.BlockSize)+70) || !bytes.Equal(e.Data, bytes.Repeat([]byte{byte(i + 1)}, int(d.BlockSize))) { + t.Fatal("writer/scanner binding or payload mismatch") + } + } +} + +func TestWALIOV3_WrapPaddingAndSlack(t *testing.T) { + for _, remaining := range []uint64{32, 70, 130} { + t.Run(map[uint64]string{32: "geometric slack", 70: "empty padding", 130: "payload padding"}[remaining], func(t *testing.T) { + const size = 16 * 1024 + start := uint64(size) - remaining + f, p, w := newWALIOTestV3(t, start, start) + d := p.current() + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryWrite, LBA: 1, Length: d.BlockSize, Data: make([]byte, d.BlockSize)}, 0, nil); err != nil { + t.Fatal(err) + } + if err := f.Sync(); err != nil { + t.Fatal(err) + } + r, err := scanWALV3(f, d) + if err != nil { + t.Fatal(err) + } + if len(r.Records) != 1 || r.Records[0].Entry.LogicalStart != size || r.Frontier != 1 || r.End != size+70+uint64(d.BlockSize) { + t.Fatalf("wrapped scan=%+v", r) + } + }) + } +} + +func TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord(t *testing.T) { + for _, kind := range []string{"foreign nonce", "wrong cursor same lap", "old lap", "bad CRC", "bad footer"} { + t.Run(kind, func(t *testing.T) { + f, p, _ := newWALIOTestV3(t, 0, 0) + d := p.current() + // A valid barrier is hidden after the first header. The scanner must not + // search onward for it after failing the first record's admission. + good, err := encodeWALEntryV3(walEntryV3{LSN: 1, Type: walEntryBarrier, Nonce: d.Nonce}, d.BlockSize, d.VolumeSize/uint64(d.BlockSize)) + if err != nil { + t.Fatal(err) + } + b := bytes.Clone(good) + switch kind { + case "foreign nonce": + b[46] ^= 1 + case "wrong cursor same lap": + binary.LittleEndian.PutUint64(b[38:46], 70) + case "old lap": + binary.LittleEndian.PutUint64(b[38:46], d.WALSize) + case "bad CRC": + b[62] ^= 1 + case "bad footer": + b[66] ^= 1 + } + if kind != "bad CRC" && kind != "bad footer" { + binary.LittleEndian.PutUint32(b[62:66], crc32.Checksum(b[:62], walEntryCRC32CV3)) + } + hidden := bytes.Clone(good) + binary.LittleEndian.PutUint64(hidden[38:46], 70) + binary.LittleEndian.PutUint32(hidden[62:66], crc32.Checksum(hidden[:62], walEntryCRC32CV3)) + if _, err := f.WriteAt(append(b, hidden...), int64(d.WALOffset)); err != nil { + t.Fatal(err) + } + r, err := scanWALV3(f, d) + if err != nil { + t.Fatal(err) + } + if len(r.Records) != 0 || r.End != 0 || r.MaxDurableLSN != 0 || r.StopCause == nil { + t.Fatalf("untrusted/embedded record admitted: %+v", r) + } + }) + } +} + +func TestWALIOV3_InstalledScanBeginsAtMaxTail(t *testing.T) { + f, p, w := newWALIOTestV3(t, 140, 140) + d := p.current() + d.BaseState = BaseInstalled + d.BaseInstallID = [16]byte{1} + d.BaseCursor = 70 + d.BaseLSN = 5 + d.CheckpointLSN = 5 + d.W = 5 + d.MapCoveredCheckpoint = 5 + if _, err := w.append(walEntryV3{LSN: 6, Type: walEntryBarrier}, 5, nil); err != nil { + t.Fatal(err) + } + r, err := scanWALV3(f, d) + if err != nil { + t.Fatal(err) + } + if r.Start != 140 || r.End != 210 || r.Frontier != 6 || len(r.Records) != 1 { + t.Fatalf("max-tail scan=%+v", r) + } +} + +func TestWALIOV3_ValidatedFrontierIntervals(t *testing.T) { + f, p, w := newWALIOTestV3(t, 0, 0) + d := p.current() + // A physical 102,101,104 chain must never be created. Gaps are legal, + // but a later append cannot fill a gap behind the physical highest LSN. + d.BaseState = BaseInstalling + d.BaseInstallID = [16]byte{1} + d.BaseLSN = 100 + if _, err := w.append(walEntryV3{LSN: 102, Type: walEntryBarrier}, 100, nil); err != nil { + t.Fatal(err) + } + before := w.logicalHeadV3() + if _, err := w.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100, nil); !errors.Is(err, ErrWALLSNOrder) { + t.Fatalf("non-monotone101=%v", err) + } + if w.logicalHeadV3() != before { + t.Fatal("refused101 advanced cursor") + } + if _, err := w.append(walEntryV3{LSN: 104, Type: walEntryBarrier}, 100, nil); err != nil { + t.Fatal(err) + } + if _, err := w.append(walEntryV3{LSN: 103, Type: walEntryBarrier}, 100, nil); !errors.Is(err, ErrWALLSNOrder) { + t.Fatalf("late gap fill103=%v", err) + } + r, err := scanWALV3(f, d) + if err != nil { + t.Fatal(err) + } + if r.Frontier != 100 || r.HighestLSN != 104 || r.MaxDurableLSN != 100 || len(r.Records) != 2 { + t.Fatalf("ordered gap scan=%+v", r) + } +} + +func TestWALIOV3_FloorAndPwriteFailureRefuse(t *testing.T) { + f, p, w := newWALIOTestV3(t, 16*1024, 0) + _ = f + before := w.logicalHeadV3() + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, errWALFull) { + t.Fatalf("full ring error=%v", err) + } + if w.logicalHeadV3() != before { + t.Fatal("full append changed writer head") + } + if _, err := p.publish(nil, nil, func(d *descriptorV3) error { d.RetainedTail = 16 * 1024; return nil }); err != nil { + t.Fatal(err) + } + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, errWALFull) { + t.Fatalf("fallback tail must still pin: %v", err) + } + if ok, err := p.rolloverIfPinned(); err != nil || !ok { + t.Fatalf("rollover=%v %v", ok, err) + } + calls := 0 + w.writeAt = func(b []byte, off int64) (int, error) { calls++; return 1, io.ErrShortWrite } + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, errWALPwrite) { + t.Fatalf("append failure=%v", err) + } + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, errWALPwrite) || calls != 1 { + t.Fatal("failed append retried physical I/O") + } +} + +func TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned(t *testing.T) { + f, p, w := newWALIOTestV3(t, 0, 0) + d := p.current() + inner, err := encodeWALEntryV3(walEntryV3{LSN: 99, Type: walEntryBarrier, DurableLSN: 88, LogicalStart: 100, Nonce: d.Nonce}, d.BlockSize, d.VolumeSize/uint64(d.BlockSize)) + if err != nil { + t.Fatal(err) + } + data := make([]byte, d.BlockSize) + copy(data[100:], inner) + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryWrite, LBA: 4, Length: d.BlockSize, Data: data}, 0, nil); err != nil { + t.Fatal(err) + } + r, err := scanWALV3(f, d) + if err != nil { + t.Fatal(err) + } + if len(r.Records) != 1 || r.Frontier != 1 || r.HighestLSN != 1 || r.MaxDurableLSN != 0 || !bytes.Equal(r.Records[0].Entry.Data, data) { + t.Fatalf("embedded payload interpreted as WAL: %+v", r) + } +} + +func TestWALIOV3_ConcurrentAppendsHaveUniqueCursors(t *testing.T) { + f, p, w := newWALIOTestV3(t, 0, 0) + d := p.current() + done := make(chan error, 40) + // Forty callers race the same first LSN: exactly one may consume it. + for n := 0; n < 40; n++ { + go func() { _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); done <- err }() + } + deadline := time.NewTimer(5 * time.Second) + defer deadline.Stop() + accepted := 0 + for n := 0; n < 40; n++ { + select { + case err := <-done: + if err == nil { + accepted++ + } else if !errors.Is(err, ErrWALLSNOrder) { + t.Errorf("concurrent append=%v", err) + } + case <-deadline.C: + t.Fatal("bounded append completion timed out") + } + } + if accepted != 1 { + t.Fatalf("same LSN admitted %d times", accepted) + } + // The caller's allocator serializes the subsequent increasing stream. + for lsn := uint64(2); lsn <= 40; lsn++ { + if _, err := w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 0, nil); err != nil { + t.Fatal(err) + } + } + r, err := scanWALV3(f, d) + if err != nil { + t.Fatal(err) + } + if len(r.Records) != 40 || r.Frontier != 40 || r.End != 40*70 { + t.Fatalf("concurrent scan=%+v", r) + } +} + +func TestWALIOV3_CounterRefusalBeforePwrite(t *testing.T) { + _, _, w := newWALIOTestV3(t, counterMaxV3-30, counterMaxV3-30) + calls := 0 + w.writeAt = func(b []byte, off int64) (int, error) { calls++; return len(b), nil } + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); !errors.Is(err, ErrCounterExhausted) || calls != 0 { + t.Fatalf("counter error=%v writes=%d", err, calls) + } +} + +func TestWALIOV3_ScanRequiresActualSourceBounds(t *testing.T) { + f, p, _ := newWALIOTestV3(t, 0, 0) + d := p.current() + if err := f.Truncate(int64(d.WALOffset + walEntryPrefixSizeV3)); err != nil { + t.Fatal(err) + } + if _, err := scanWALV3(f, d); !errors.Is(err, io.ErrUnexpectedEOF) { + t.Fatalf("truncated source bounds error=%v", err) + } +} + +func TestWALIOV3_LastRepresentableRecordStillRecovers(t *testing.T) { + start := uint64(counterMaxV3) - 70 + f, p, w := newWALIOTestV3(t, start, start) + d := p.current() + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); err != nil { + t.Fatal(err) + } + r, err := scanWALV3(f, d) + if err != nil { + t.Fatal(err) + } + if len(r.Records) != 1 || r.Frontier != 1 || r.End != counterMaxV3 { + t.Fatalf("last representable scan=%+v", r) + } + if _, err := w.append(walEntryV3{LSN: 2, Type: walEntryBarrier}, 0, nil); !errors.Is(err, ErrCounterExhausted) { + t.Fatalf("next append=%v", err) + } +} + +func TestWALIOV3_RestoreCursorDoesNotPublishOrResetNonce(t *testing.T) { + f, p, w := newWALIOTestV3(t, 0, 0) + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); err != nil { + t.Fatal(err) + } + r, err := scanWALV3(f, p.current()) + if err != nil { + t.Fatal(err) + } + before := p.current() + reopened, err := newWALWriterV3(f, p) + if err != nil { + t.Fatal(err) + } + if err := reopened.restoreScanV3(r); err != nil { + t.Fatal(err) + } + if reopened.logicalHeadV3() != r.End || p.current() != before { + t.Fatal("cursor restore either lost E or published descriptor") + } + wrong := r + wrong.Nonce[0] ^= 1 + if err := reopened.restoreScanV3(wrong); !errors.Is(err, errWALBindingV3) { + t.Fatalf("wrong incarnation restore=%v", err) + } + wrong = r + wrong.End = before.RetainedTail + before.WALSize + 1 + if err := reopened.restoreScanV3(wrong); !errors.Is(err, errWALBindingV3) { + t.Fatalf("out-of-window restore=%v", err) + } + if reopened.logicalHeadV3() != r.End { + t.Fatal("refused cursor restore changed E") + } + // No append is attempted here: fence/publication admission is row5/11. +} + +// The amended row-3 publisher and the existing row-4 writer share one +// refusal boundary even when the caller has not yet wired a global latch. +func TestWALIOV3_UncertainPublisherStopsExistingAndNewWriters(t *testing.T) { + for _, partial := range []bool{false, true} { + t.Run(fmt.Sprintf("partial=%v", partial), func(t *testing.T) { + f, p, w := newWALIOTestV3(t, 0, 0) + boom := errors.New("slot response lost") + p.io.writeSlot = func(off int64, b []byte) error { + if partial { + b = b[:len(b)/2] + } + if _, err := f.WriteAt(b, off); err != nil { + return err + } + return boom + } + _, err := p.publish(nil, nil, func(d *descriptorV3) error { d.W = 1; return nil }) + if !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("publish=%v", err) + } + writes := 0 + w.writeAt = func(b []byte, off int64) (int, error) { writes++; return f.WriteAt(b, off) } + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); err == nil { + t.Fatal("existing writer accepted uncertain publication") + } + if writes != 0 { + t.Fatalf("physical writes after uncertainty=%d", writes) + } + if _, err := newWALWriterV3(f, p); err == nil { + t.Fatal("new writer accepted uncertain publication") + } + }) + } +} diff --git a/seaweed-block/core/storage/wal_lsn_order_v3_test.go b/seaweed-block/core/storage/wal_lsn_order_v3_test.go new file mode 100644 index 0000000000..174a3bb624 --- /dev/null +++ b/seaweed-block/core/storage/wal_lsn_order_v3_test.go @@ -0,0 +1,108 @@ +package storage + +import ( + "bytes" + "errors" + "testing" +) + +func TestWALLSNOrderV3_RefusesDuplicateAndLower(t *testing.T) { + for _, lsn := range []uint64{9, 10} { + t.Run(map[uint64]string{9: "lower", 10: "equal"}[lsn], func(t *testing.T) { + f, p, w := newWALIOTestV3(t, 0, 0) + if _, e := w.append(walEntryV3{LSN: 10, Type: walEntryBarrier}, 0, nil); e != nil { + t.Fatal(e) + } + before := make([]byte, p.current().WALSize) + if _, e := f.ReadAt(before, int64(p.current().WALOffset)); e != nil { + t.Fatal(e) + } + head := w.logicalHeadV3() + if _, e := w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 0, nil); !errors.Is(e, ErrWALLSNOrder) { + t.Fatalf("non-increasing LSN %d verdict after10: %v", lsn, e) + } + after := make([]byte, len(before)) + if _, e := f.ReadAt(after, int64(p.current().WALOffset)); e != nil { + t.Fatal(e) + } + if w.logicalHeadV3() != head || !bytes.Equal(before, after) { + t.Fatal("refused LSN changed cursor or WAL bytes") + } + }) + } +} +func TestWALLSNOrderV3_BatchConsumesFullRange(t *testing.T) { + _, p, w := newWALIOTestV3(t, 0, 0) + bs := p.current().BlockSize + if _, e := w.append(walEntryV3{LSN: 10, BatchCount: 2, Type: walEntryWriteBatch, Length: 2 * bs, Data: make([]byte, 2*bs)}, 0, nil); e != nil { + t.Fatal(e) + } + if _, e := w.append(walEntryV3{LSN: 11, Type: walEntryBarrier}, 0, nil); !errors.Is(e, ErrWALLSNOrder) { + t.Fatalf("overlap with batch last LSN: %v", e) + } + if _, e := w.append(walEntryV3{LSN: 12, Type: walEntryBarrier}, 0, nil); e != nil { + t.Fatal(e) + } +} +func TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier(t *testing.T) { + f, p, _ := newWALIOTestV3(t, 0, 0) + d := p.current() + d.CheckpointLSN = 100 + d.MapCoveredCheckpoint = 100 + d.W = 100 + p.cur = d + w, e := newWALWriterV3(f, p) + if e != nil { + t.Fatal(e) + } + for _, lsn := range []uint64{101, 104} { + if _, e = w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 100, nil); e != nil { + t.Fatal(e) + } + } + r, e := scanWALV3(f, d) + if e != nil { + t.Fatal(e) + } + if r.Frontier != 101 || r.HighestLSN != 104 { + t.Fatalf("setup scan=%+v", r) + } + // The owner discards unacked104 and durably fences the exact remaining lap. + s := &WALStore{fd: f} + if e = s.fenceV3(70, 0, d.WALSize, true, d.WALOffset); e != nil { + t.Fatal(e) + } + r.End = 70 + recovered, e := newWALWriterV3(f, p) + if e != nil { + t.Fatal(e) + } + if e = recovered.restoreScanV3(r); e != nil { + t.Fatal(e) + } + if _, e = recovered.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100, nil); !errors.Is(e, ErrWALLSNOrder) { + t.Fatalf("restored kept frontier duplicate: %v", e) + } + if _, e = recovered.append(walEntryV3{LSN: 102, Type: walEntryBarrier}, 100, nil); e != nil { + t.Fatalf("dropped104 pinned next102: %v", e) + } +} + +func TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed(t *testing.T) { + f, p, _ := newWALIOTestV3(t, 0, 0) + d := p.current() + d.CheckpointLSN = 100 + d.MapCoveredCheckpoint = 100 + d.W = 100 + p.cur = d + w, e := newWALWriterV3(f, p) + if e != nil { + t.Fatal(e) + } + if _, e = w.append(walEntryV3{LSN: 100, Type: walEntryBarrier}, 100, nil); !errors.Is(e, ErrWALLSNOrder) { + t.Fatalf("descriptor floor100 not consumed: %v", e) + } + if _, e = w.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100, nil); e != nil { + t.Fatal(e) + } +} diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 8160294c1e..754caec8d4 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -1,6 +1,7 @@ package storage import ( + "context" "errors" "fmt" "os" @@ -9,6 +10,7 @@ import ( "sync/atomic" "time" + "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/iolatency" ) @@ -81,6 +83,13 @@ type WALStore struct { // (before lifecycleMu); a quiesced cut holds it exclusively. Order: // captureMu -> lifecycleMu -> mu. captureMu sync.RWMutex + // captureMu orders permanent attachment shutdown with hook publication. + attachClosed bool + closeComplete chan struct{} + closeResult error + testDestructiveSnapshot func() // nil scheduling control, before any capture lock + testCloseSnapshot func() // nil in production; called without captureMu + // chunk is the attached chunk layer's hooks; nil when none. chunk atomic.Pointer[chunkHooks] extentMu [64]sync.RWMutex @@ -135,6 +144,10 @@ type WALStore struct { // gates and mounted NVMe/TCP profiling pass. multiBlockRecords bool + // v3 is non-nil for a format-v3 store (walstore_v3.go). Production + // selectors use v3; legacy formats require explicit offline migration. + v3 *walStoreV3State + // Physical WAL sync attempts exclude the separate metadata/checkpoint syncs. syncWALFile func() error walSyncCalls atomic.Uint64 @@ -174,6 +187,28 @@ func CreateWALStore(path string, numBlocks uint32, blockSize int) (*WALStore, er } func CreateWALStoreWithOptions(path string, numBlocks uint32, blockSize int, opts WALStoreOptions) (*WALStore, error) { + if blockSize == 0 { + blockSize = DefaultBlockSize + } + if blockSize < 0 || uint64(blockSize) > uint64(^uint32(0)) { + return nil, errSuperblockBadVolume + } + if err := geometry.ValidateVolumeSize(uint64(numBlocks) * uint64(blockSize)); err != nil { + return nil, err + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return nil, err + } + cb := opts.ChunkBlocks + if cb == 0 { + cb = 1024 + } + return createWALStoreV3Configured(path, numBlocks, uint32(blockSize), 64*1024*1024, opts.WMode, 0, uint64(cb), opts) +} + +// Frozen constructor for legacy-format regression fixtures; public Create +// never reaches it after activation. Removed from production in row 14a. +func createLegacyWALStoreWithOptions(path string, numBlocks uint32, blockSize int, opts WALStoreOptions) (*WALStore, error) { if blockSize == 0 { blockSize = DefaultBlockSize } @@ -190,7 +225,7 @@ func CreateWALStoreWithOptions(path string, numBlocks uint32, blockSize int, opt BlockSize: uint32(blockSize), ExtentSize: uint32(blockSize), // one block per extent slot keeps math trivial ImplKind: ImplKindWALStore, - ImplVersion: WALStoreImplVersion, + ImplVersion: 1, }) if err != nil { _ = f.Close() @@ -229,6 +264,10 @@ func OpenWALStore(path string) (*WALStore, error) { } func OpenWALStoreWithOptions(path string, opts WALStoreOptions) (*WALStore, error) { + return openWALStoreV3WithOptions(path, true, opts) +} + +func openLegacyWALStoreWithOptions(path string, opts WALStoreOptions) (*WALStore, error) { f, err := os.OpenFile(path, os.O_RDWR, 0o644) if err != nil { return nil, fmt.Errorf("storage: open %s: %w", path, err) @@ -263,6 +302,13 @@ func openInitialized(path string, f *os.File, sb *superblock) (*WALStore, error) } func openInitializedWithMetadata(path string, f *os.File, sb *superblock, metadata BlockMetadata) (*WALStore, error) { + return openInitializedInternal(path, f, sb, metadata, nil) +} + +// openInitializedInternal is openInitializedWithMetadata with an optional +// init hook that runs before the committer and flusher goroutines start +// (the v3 store attaches its state there). +func openInitializedInternal(path string, f *os.File, sb *superblock, metadata BlockMetadata, init func(*WALStore) error) (*WALStore, error) { dm := newDirtyMap(64) // 64 shards is plenty for Phase 07 demo workloads s := &WALStore{ @@ -290,6 +336,11 @@ func openInitializedWithMetadata(path string, f *os.File, sb *superblock, metada return f.Sync() } s.syncExtentFile = f.Sync + if init != nil { + if err := init(s); err != nil { + return nil, err + } + } committer := NewGroupCommitter(GroupCommitterConfig{ SyncFunc: s.syncWALBatch, MaxDelay: 1 * time.Millisecond, @@ -298,7 +349,13 @@ func openInitializedWithMetadata(path string, f *os.File, sb *superblock, metada go committer.Run() s.committer = committer s.syncCache = committer.SyncCache + // The two legacy superblock writers pwrite offset 0, which on a v3 file + // is descriptor slot A: they refuse on v3 (codex01 row 7 slice 4 P1). + // A v3 store publishes metadata only through its descriptor publisher. s.syncDirectFrontierMetadata = func(data []byte) error { + if s.v3 != nil { + return errV3LegacySuperblockWrite + } if _, err := f.WriteAt(data, 0); err != nil { return fmt.Errorf("storage: pwrite direct frontier superblock: %w", err) } @@ -308,6 +365,9 @@ func openInitializedWithMetadata(path string, f *os.File, sb *superblock, metada return nil } s.writeSuperblockMetadata = func(data []byte) error { + if s.v3 != nil { + return errV3LegacySuperblockWrite + } if _, err := f.WriteAt(data, 0); err != nil { return err } @@ -331,13 +391,17 @@ func openInitializedWithMetadata(path string, f *os.File, sb *superblock, metada // flusher via NotifyUrgent — same seam V2 wires for pressure- // driven flushes. s.admissionTimeout = 30 * time.Second + if s.v3 != nil { + // WAL pressure gets a budget below the host's I/O timeout. This bounds + // cooperative admission waits, not a blocking callback or physical I/O. + s.admissionTimeout = 4 * time.Second + } s.admission = newWALAdmission(walAdmissionConfig{ MaxConcurrent: 64, SoftWatermark: 0.70, HardWatermark: 0.90, - WALUsedFn: func() float64 { - return s.wal.usedFraction() - }, + WALUsedFn: s.walUsedFraction, + FaultFn: s.stickyIOFault, NotifyFn: func() { if s.flusher != nil { s.flusher.NotifyUrgent() @@ -353,6 +417,30 @@ func openInitializedWithMetadata(path string, f *os.File, sb *superblock, metada return s, nil } +// walUsedFraction samples the active format's writer. The legacy writer is +// still present on a v3 store but receives no appends, so its occupancy is zero. +// Store admission is held only for this snapshot, never across a pressure wait. +func (s *WALStore) walUsedFraction() float64 { + s.mu.RLock() + defer s.mu.RUnlock() + if s.v3 == nil { + return s.wal.usedFraction() + } + w := s.v3.w + if w == nil { + // Not a capacity decision: append must retain its typed binding refusal + // without waiting for pressure that cannot be relieved before Recover. + return 0 + } + d, floor, valid := s.v3.pub.walSnapshotV3() + w.mu.Lock() + defer w.mu.Unlock() + if !valid || d.WALSize == 0 || d.Nonce != w.nonce || w.head < floor || w.head-floor > d.WALSize { + return 0 // append's binding validation still refuses; this grants no reuse + } + return float64(w.head-floor) / float64(d.WALSize) +} + func retainedLSNFromCheckpoint(checkpointLSN uint64) uint64 { if checkpointLSN == 0 { return 0 @@ -407,6 +495,9 @@ func (s *WALStore) persistCheckpointAndRelease(highestLSN, entryPhys, entryLen u } func (s *WALStore) persistCheckpointReleasing(highestLSN, entryPhys, entryLen uint64, release bool) error { + if s.v3 != nil { + return s.persistCheckpointV3(highestLSN, s.v3.recoverGen.Load()) + } s.mu.Lock() defer s.mu.Unlock() if err := s.stickyIOFault(); err != nil { @@ -551,17 +642,37 @@ func (s *WALStore) HolesSuspected() uint64 { // // Idempotent: calling Recover twice on the same on-disk state yields // identical results. -func (s *WALStore) Recover() (uint64, error) { - // Recover republishes the dirty map like a write: it holds the capture - // barrier shared, so it can never publish bytes between a quiesced - // cut's Sync (which fixes H) and that cut's copy. - // Order: captureMu -> lifecycleMu -> mu. - s.captureMu.RLock() - defer s.captureMu.RUnlock() +func (s *WALStore) Recover() (frontier uint64, err error) { + // Drain an attached COW window before taking any lower lock. The lease + // blocks a replacement window and retries a racing first attachment. + // Legacy fixtures retain their shared barrier ordering with full copying. + // Order after drain: captureMu -> lifecycleMu -> syncMu -> mu. + release := s.holdChunkDestructive(false) + defer release() // also releases captureMu, after all lower locks s.lifecycleMu.RLock() defer s.lifecycleMu.RUnlock() + if s.v3 != nil { + // A v3 recovery holds the leader role for its whole run, so no W + // publication or acknowledgement straddles it (walstore_v3.go + // recoverGen). Order: lifecycleMu -> syncMu -> s.mu. + s.v3.syncMu.Lock() + defer s.v3.syncMu.Unlock() + } s.mu.Lock() defer s.mu.Unlock() + if s.v3 != nil { + // The store lock orders both epoch boundaries with real map publishers. + // START invalidates old candidates; END also invalidates candidates + // prepared while this Recover was in flight, including on failure. + defer func() { + if endErr := s.v3.pub.invalidateMapProofV3(); endErr != nil { + frontier, err = 0, errors.Join(err, endErr) + } + }() + if err := s.v3.pub.invalidateMapProofV3(); err != nil { + return 0, err + } + } if s.closed { return 0, errors.New("storage: Recover after Close") } @@ -578,6 +689,9 @@ func (s *WALStore) Recover() (uint64, error) { // are never reused across it), also on a failed or partial scan. Runs // before s.mu is released, so no read sees recovered bytes first. defer s.noteChunkRecovery() + if s.v3 != nil { + return s.recoverV3() + } s.dm.clear() res, err := recoverWAL(s.fd, s.sb, s.dm) if err != nil { @@ -644,10 +758,15 @@ func (s *WALStore) Recover() (uint64, error) { // covers this LSN). Reads after this Write see the new bytes // immediately. func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { - s.captureMu.RLock() + return s.WriteContext(context.Background(), lba, data) +} + +func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (uint64, error) { + deadline := s.writeAdmissionDeadline(ctx) + if err := s.acquireWriteLock(ctx, deadline, s.captureMu.TryRLock, s.captureMu.RLock); err != nil { + return 0, err + } defer s.captureMu.RUnlock() - s.lifecycleMu.RLock() - defer s.lifecycleMu.RUnlock() if err := s.stickyIOFault(); err != nil { return 0, err } @@ -662,8 +781,21 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { // is disabled (admission==nil), Write proceeds immediately. The // admission Acquire may block up to admissionTimeout — under // hard pressure it spins waiting for the flusher to drain. + s.beforeChunkMutation(uint64(lba), 1) + if err := s.acquireWriteLock(ctx, deadline, s.lifecycleMu.TryRLock, s.lifecycleMu.RLock); err != nil { + return 0, err + } + defer s.lifecycleMu.RUnlock() + + if err := s.writeBudgetError(ctx, deadline); err != nil { + return 0, err + } if s.admission != nil { - if err := s.admission.Acquire(s.admissionTimeout); err != nil { + wait := s.admissionTimeout + if !deadline.IsZero() { + wait = time.Until(deadline) + } + if err := s.admission.acquireContext(ctx, wait, s.writePressureSample(ctx, deadline)); err != nil { return 0, fmt.Errorf("storage: WAL admission: %w", err) } defer s.admission.Release() @@ -673,7 +805,7 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { } commitLockStart := time.Now() - s.mu.Lock() + s.mu.Lock() // a short lock: blocking keeps RWMutex writer preference (#252); the budget is checked below s.instr.recordWriteCommitLockWait(time.Since(commitLockStart)) if s.closed { s.mu.Unlock() @@ -685,6 +817,10 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { s.mu.Unlock() return 0, err } + if err := s.writeBudgetError(ctx, deadline); err != nil { + s.mu.Unlock() + return 0, err + } lsn := s.nextLSN entry := &walEntry{ @@ -695,12 +831,20 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { Data: data, } appendStart := time.Now() - walRelOff, err := s.wal.append(entry) + var walRelOff uint64 + var err error + if s.v3 != nil { + walRelOff, err = s.appendWriteV3(lba, data, lsn, func() error { return s.writeBudgetError(ctx, deadline) }) + } else { + walRelOff, err = s.wal.append(entry) + } s.instr.appendLatency.Observe(time.Since(appendStart)) // A failed pwrite may still leave complete records or padding in the file. s.walMutation.Add(1) if err != nil { - s.noteAppendFailure(err) + if s.v3 == nil { + s.noteAppendFailure(err) + } s.mu.Unlock() return 0, fmt.Errorf("storage: WAL append: %w", err) } @@ -721,10 +865,15 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { } func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error) { - s.captureMu.RLock() + return s.WriteBatchContext(context.Background(), startLBA, blocks) +} + +func (s *WALStore) WriteBatchContext(ctx context.Context, startLBA uint32, blocks [][]byte) ([]uint64, error) { + deadline := s.writeAdmissionDeadline(ctx) + if err := s.acquireWriteLock(ctx, deadline, s.captureMu.TryRLock, s.captureMu.RLock); err != nil { + return nil, err + } defer s.captureMu.RUnlock() - s.lifecycleMu.RLock() - defer s.lifecycleMu.RUnlock() if err := s.stickyIOFault(); err != nil { return nil, err } @@ -741,8 +890,21 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error } } + s.beforeChunkMutation(uint64(startLBA), uint64(len(blocks))) + if err := s.acquireWriteLock(ctx, deadline, s.lifecycleMu.TryRLock, s.lifecycleMu.RLock); err != nil { + return nil, err + } + defer s.lifecycleMu.RUnlock() + + if err := s.writeBudgetError(ctx, deadline); err != nil { + return nil, err + } if s.admission != nil { - if err := s.admission.Acquire(s.admissionTimeout); err != nil { + wait := s.admissionTimeout + if !deadline.IsZero() { + wait = time.Until(deadline) + } + if err := s.admission.acquireContext(ctx, wait, s.writePressureSample(ctx, deadline)); err != nil { return nil, fmt.Errorf("storage: WAL admission: %w", err) } defer s.admission.Release() @@ -752,7 +914,7 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error } commitLockStart := time.Now() - s.mu.Lock() + s.mu.Lock() // a short lock: blocking keeps RWMutex writer preference (#252); the budget is checked below s.instr.recordWriteCommitLockWait(time.Since(commitLockStart)) if s.closed { s.mu.Unlock() @@ -762,7 +924,16 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error s.mu.Unlock() return nil, err } + if err := s.writeBudgetError(ctx, deadline); err != nil { + s.mu.Unlock() + return nil, err + } firstLSN := s.nextLSN + if s.v3 != nil { + lsns, err := s.writeBatchV3Locked(startLBA, blocks, firstLSN, func() error { return s.writeBudgetError(ctx, deadline) }) + s.mu.Unlock() + return lsns, err + } useMultiBlock := s.multiBlockRecords && len(blocks) > 1 if useMultiBlock { @@ -875,7 +1046,18 @@ func (s *WALStore) WriteInstrumentation() WriteInstrumentationStatus { // Read returns the current bytes at lba. Dirty entries are served // from the WAL; clean LBAs are served from the extent. -func (s *WALStore) Read(lba uint32) ([]byte, error) { +func (s *WALStore) Read(lba uint32) ([]byte, error) { return s.ReadContext(context.Background(), lba) } + +func (s *WALStore) ReadContext(ctx context.Context, lba uint32) (data []byte, err error) { + defer func() { + if err == nil && ctx.Err() != nil { + data = nil + err = hydrationPending(ctx.Err()) + } + }() + if err := ctx.Err(); err != nil { + return nil, hydrationPending(err) + } maxLBA := uint32(s.sb.VolumeSize / uint64(s.sb.BlockSize)) if lba >= maxLBA { return nil, fmt.Errorf("storage: LBA %d out of range", lba) @@ -887,10 +1069,16 @@ func (s *WALStore) Read(lba uint32) ([]byte, error) { } s.mu.RUnlock() + if s.v3 != nil { + if data, handled, err := s.readDirtyV3(lba); handled { + return data, err + } + return s.readFromExtentContext(ctx, lba) + } if walRelOff, dataOffset, _, _, ok := s.dm.get(uint64(lba)); ok { return s.readFromWAL(walRelOff, dataOffset) } - return s.readFromExtent(lba) + return s.readFromExtentContext(ctx, lba) } // readFromWAL pulls a single block out of a WAL Write/Trim entry @@ -952,10 +1140,22 @@ func (s *WALStore) DisableAutoFlushForRecoveryTest() { } func (s *WALStore) readFromExtent(lba uint32) ([]byte, error) { + return s.readFromExtentContext(context.Background(), lba) +} + +func (s *WALStore) readFromExtentContext(ctx context.Context, lba uint32) ([]byte, error) { // An attached chunk layer resolves blocks that are absent locally // before the extent lock is taken; nil data means read the extent. if h := s.chunk.Load(); h != nil { - data, err := h.sink.OnReadMiss(uint64(lba)) + var data []byte + var err error + if r, ok := h.sink.(interface { + OnReadMissContext(context.Context, uint64) ([]byte, error) + }); ok { + data, err = r.OnReadMissContext(ctx, uint64(lba)) + } else { + data, err = h.sink.OnReadMiss(uint64(lba)) + } if err != nil { return nil, err } @@ -965,10 +1165,23 @@ func (s *WALStore) readFromExtent(lba uint32) ([]byte, error) { // The miss may have waited on a remote fetch while this block was // written: re-resolve through the normal path (dirty map/WAL first) // before the extent. No lock is held here. - if walRelOff, dataOffset, _, _, ok := s.dm.get(uint64(lba)); ok { + if s.v3 != nil { + if data, handled, err := s.readDirtyV3(lba); handled { + return data, err + } + } else if walRelOff, dataOffset, _, _, ok := s.dm.get(uint64(lba)); ok { return s.readFromWAL(walRelOff, dataOffset) } } + if err := ctx.Err(); err != nil { + return nil, hydrationPending(err) + } + return s.readExtentBlock(lba) +} + +// readExtentBlock reads lba's extent bytes under its extent lock, without the +// chunk layer's miss hook: the caller has resolved the block as local. +func (s *WALStore) readExtentBlock(lba uint32) ([]byte, error) { lock := &s.extentMu[uint64(lba)%uint64(len(s.extentMu))] lock.RLock() defer lock.RUnlock() @@ -1006,6 +1219,16 @@ func (s *WALStore) Sync() (uint64, error) { } targetHead := s.walHead targetDirectFrontier := s.pendingDirectFrontierLSN + var targetGen uint64 + if s.v3 != nil { + // The logical Sync is gated while installing (DESIGN 7): exactly + // (0, ErrBaseInstalling), no batch, no new W. + if s.v3.pub.current().BaseState == BaseInstalling { + s.mu.RUnlock() + return 0, ErrBaseInstalling + } + targetGen = s.v3.recoverGen.Load() // captured with targetHead (Recover holds s.mu) + } s.mu.RUnlock() if s.walSyncCovered() { @@ -1020,6 +1243,21 @@ func (s *WALStore) Sync() (uint64, error) { } s.syncs.Add(1) + if v := s.v3; v != nil { + if h := v.testSyncBeforeCompletion; h != nil { + h() + } + // The completion is validated against the recovery generation under + // the leader role: a recovery since the capture refuses the ack. + v.syncMu.Lock() + defer v.syncMu.Unlock() + if v.recoverGen.Load() != targetGen { + return 0, errV3RecoveredMeanwhile + } + if v.pub.current().BaseState == BaseInstalling { + return 0, ErrBaseInstalling // an install began meanwhile + } + } s.mu.Lock() // A fault latched while this Sync waited (another caller's fsync or // append, or a flusher fsync) refuses it: nothing is acknowledged. @@ -1135,6 +1373,9 @@ func (s *WALStore) RecoveryRetentionLSNs() uint64 { // Used by the rebuild server to declare the replica's frontier // matches the primary's head once base blocks are installed. func (s *WALStore) AdvanceFrontier(lsn uint64) { + if s.v3 != nil { + return // v3 frontier jumps happen only inside MarkBaseComplete (rows 9 to 11) + } s.bypassSyncDedup.Store(true) s.lifecycleMu.RLock() defer s.lifecycleMu.RUnlock() @@ -1183,6 +1424,9 @@ func (s *WALStore) AdvanceWALTail(newTail uint64) { // Durability follows the same rule as Write: bytes become durable // only on the next successful Sync (the extent fsync covers them). func (s *WALStore) WriteExtentDirect(lba uint32, data []byte) error { + if s.v3 != nil { + return errV3NotYet // v3 BASE writes go through an install handle (rows 9 to 11) + } s.bypassSyncDedup.Store(true) s.captureMu.RLock() defer s.captureMu.RUnlock() @@ -1240,6 +1484,9 @@ func (s *WALStore) noteChunkMutation(lba uint64) { } func (s *WALStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error { + if s.v3 != nil { + return s.applyEntryV3(lba, data, lsn, false) + } s.bypassSyncDedup.Store(true) s.captureMu.RLock() defer s.captureMu.RUnlock() @@ -1350,14 +1597,14 @@ func (s *WALStore) AppliedLSNs() (map[uint32]uint64, error) { // Linear scan over numBlocks. Acceptable for the rebuild path // (one-shot, off the hot read/write loop). Not appropriate for // a hot-path scan. -func (s *WALStore) AllBlocks() map[uint32][]byte { +func (s *WALStore) AllBlocks() (map[uint32][]byte, error) { n := s.NumBlocks() out := make(map[uint32][]byte) zero := make([]byte, s.sb.BlockSize) for lba := uint32(0); lba < n; lba++ { data, err := s.Read(lba) if err != nil { - continue + return nil, fmt.Errorf("snapshot LBA %d: %w", lba, err) } // Skip never-written / trimmed LBAs. if bytesAllZero(data, zero) { @@ -1365,7 +1612,7 @@ func (s *WALStore) AllBlocks() map[uint32][]byte { } out[lba] = data } - return out + return out, nil } // bytesAllZero is a fast tight-loop equality against a zero slice. @@ -1385,12 +1632,27 @@ func bytesAllZero(data, zero []byte) bool { // Close persists current WAL boundaries into the superblock, // fsyncs the file, stops the group committer, and releases the // underlying file. Idempotent. -func (s *WALStore) Close() error { - // Stop the chunk layer before taking the lifecycle lock: its captures - // and fills call back into the store. - if h := s.chunk.Load(); h != nil { +func (s *WALStore) Close() (err error) { + s.captureMu.Lock() + if s.attachClosed { + done := s.closeComplete + s.captureMu.Unlock() + <-done + return s.closeResult + } + s.attachClosed = true + s.closeComplete = make(chan struct{}) + h := s.chunk.Load() + s.captureMu.Unlock() + defer func() { s.closeResult = err; close(s.closeComplete) }() + if s.testCloseSnapshot != nil { + s.testCloseSnapshot() + } + // No capture or store lock is held while callbacks drain actual I/O. + if h != nil { _ = h.closer() } + s.lifecycleMu.Lock() defer s.lifecycleMu.Unlock() s.mu.Lock() @@ -1421,7 +1683,10 @@ func (s *WALStore) Close() error { if fault := s.stickyIOFault(); fault != nil { closeErrors = append(closeErrors, fault) } - if s.fd != nil && s.stickyIOFault() == nil { + if s.fd != nil && s.v3 == nil && s.stickyIOFault() == nil { + // v2 only: a v3 Close writes nothing; its acknowledged state is + // already durable in the descriptor slots and the WAL, and a + // lagged mode-C W is recovered from the WAL scan on reopen. // Persist current head/tail back into the superblock so a // subsequent OpenWALStore can find the WAL bounds without // relying solely on the defensive scan. @@ -1438,6 +1703,12 @@ func (s *WALStore) Close() error { } } } + if s.v3 != nil && s.v3.ownedMap != nil { + if err := s.v3.ownedMap.Close(); err != nil { + closeErrors = append(closeErrors, err) + } + s.v3.ownedMap = nil + } if s.fd != nil { closeErr := s.fd.Close() s.fd = nil @@ -1467,6 +1738,9 @@ func (s *WALStore) walSyncCovered() bool { // Requests queued during a sync can reuse it only if their mutations predate its // captured cut. Failure leaves the previous durable generation unchanged. func (s *WALStore) syncWALBatch() error { + if s.v3 != nil { + return s.syncWALBatchV3() + } // A batch queued behind a failed fsync must not fsync again (or report // a covered cut as durable): the failed fsync may have dropped pages. if err := s.stickyIOFault(); err != nil { diff --git a/seaweed-block/core/storage/walstore_activation_test.go b/seaweed-block/core/storage/walstore_activation_test.go new file mode 100644 index 0000000000..5b38a839ba --- /dev/null +++ b/seaweed-block/core/storage/walstore_activation_test.go @@ -0,0 +1,158 @@ +package storage + +import ( + "bytes" + "errors" + "fmt" + "os" + "path/filepath" + "testing" +) + +func TestWALStoreProductionSelectorCreatesMappedV3(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + s, err := CreateWALStore(path, 64, 4096) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + if !s.FormatV3() { + t.Fatal("production Create must select mapped v3/impl3") + } + d := s.v3.pub.current() + if d.ImplVersion != 3 || d.WMode != WModeLagged || d.MapRootHash == [32]byte{} { + t.Fatalf("production descriptor: impl=%d mode=%d map=%x", d.ImplVersion, d.WMode, d.MapRootHash) + } + if _, err := s.Write(3, bytes.Repeat([]byte{0x73}, 4096)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + r, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + if _, err := r.Recover(); err != nil { + _ = r.Close() + t.Fatal(err) + } + if err := r.Close(); err != nil { + t.Fatal(err) + } + ro, err := OpenReadOnly(path) + if err != nil { + t.Fatal(err) + } + defer ro.Close() + if data, err := ro.Read(3); err != nil || !bytes.Equal(data, bytes.Repeat([]byte{0x73}, 4096)) { + t.Fatalf("production readonly after reopen: %v", err) + } +} + +func TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + s, err := CreateWALStore(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + if _, err := s.Write(3, blk(0x73)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + _, err = f.WriteAt([]byte{2, 0}, 4) // corrupt A's discriminator, not a valid v2 header + ce := f.Close() + if err != nil || ce != nil { + t.Fatal(err, ce) + } + r, err := OpenWALStore(path) + if err != nil { + t.Fatalf("valid B was masked by a damaged v3 A: %v", err) + } + defer r.Close() + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if got, err := r.Read(3); err != nil || !bytes.Equal(got, blk(0x73)) { + t.Fatalf("fallback bytes: %v", err) + } +} + +func TestWALStoreProductionRefusesLegacyWithoutMutation(t *testing.T) { + for _, version := range []uint32{1, 2} { + t.Run(fmt.Sprint(version), func(t *testing.T) { + path := filepath.Join(t.TempDir(), "legacy") + opts := WALStoreOptions{} + if version == 2 { + opts = recordingOptions(&recordingMetadata{}, 2) + } + s, err := createLegacyWALStoreWithOptions(path, 16, 4096, opts) + if err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if r, err := OpenWALStore(path); !errors.Is(err, ErrUnsupportedLegacyFormat) { + if r != nil { + _ = r.Close() + } + t.Fatalf("legacy writable open: %v", err) + } + if r, err := OpenReadOnly(path); !errors.Is(err, ErrUnsupportedLegacyFormat) { + if r != nil { + _ = r.Close() + } + t.Fatalf("legacy readonly open: %v", err) + } + after, err := os.ReadFile(path) + if err != nil || !bytes.Equal(before, after) { + t.Fatal("legacy refusal changed bytes", err) + } + }) + } +} + +func TestWALStoreProductionCreateOptions(t *testing.T) { + s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), 64, 4096, WALStoreOptions{ChunkBlocks: 4, WMode: WModeStrict}) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if s.v3.pub.current().WMode != WModeStrict || s.v3.ownedMap.chunkBlocks != 4 || len(s.v3.mapEntries) != 16 { + t.Fatal("production create lost the strict mode or map geometry option") + } +} + +func TestWALStoreV3InstrumentationIncludesBatch(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + if _, err := s.Write(0, blk(1)); err != nil { + t.Fatal(err) + } + if _, err := s.WriteBatch(2, [][]byte{blk(2), blk(3)}); err != nil { + t.Fatal(err) + } + i := s.WriteInstrumentation() + // A batch first aggregates its blocks, then copies that payload into + // the encoded frame: both real copies belong in the cost profile. + if i.WALCopyOps != 3 || i.WALCopyBytes != 5*4096 || i.WALEncodeOps != 2 || i.WALChecksumOps != 2 || + i.WALAppendOps != 2 || i.WALAppendWriteAtCalls != 2 || i.DirtyMapUpdateOps != 3 || s.DurabilityLatency().WALAppend.Count != 2 { + t.Fatalf("v3 single+8KiB batch instrumentation incomplete: %+v latency=%+v", i, s.DurabilityLatency()) + } +} diff --git a/seaweed-block/core/storage/walstore_admission_v3_test.go b/seaweed-block/core/storage/walstore_admission_v3_test.go new file mode 100644 index 0000000000..5f589654cd --- /dev/null +++ b/seaweed-block/core/storage/walstore_admission_v3_test.go @@ -0,0 +1,209 @@ +package storage + +import ( + "bytes" + "errors" + "path/filepath" + "sync" + "testing" + "time" +) + +func TestWALStoreV3AdmissionUsesNativeOccupancy(t *testing.T) { + s, err := CreateWALStore(filepath.Join(t.TempDir(), "volume"), 256, 4096) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + if s.v3 == nil { + t.Fatal("public selector did not create v3") + } + if got := s.admission.walUsed(); got != 0 { + t.Fatalf("initial occupancy=%g", got) + } + blocks := make([][]byte, 32) + for i := range blocks { + blocks[i] = blk(byte(i)) + } + if _, err := s.WriteBatch(0, blocks); err != nil { + t.Fatal(err) + } + want := float64(32*4096+70) / float64(64*1024*1024) + if got := s.admission.walUsed(); got != want { + t.Fatalf("native occupancy=%g want%g; legacy=%g", got, want, s.wal.usedFraction()) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if got := s.admission.walUsed(); got != 0 { + t.Fatalf("both-slot-released occupancy=%g", got) + } +} + +// Five physical ring sizes, with the real background flusher and periodic +// durable Syncs. The small geometry keeps this regression a fast unit test; +// the public-provider control separately exercises the default 64 MiB WAL. +func TestWALStoreV3AdmissionBurstFiveRings(t *testing.T) { + const walSize = 64 * 1024 + const blocks = 5 * walSize / 4096 + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), blocks, 4096, walSize, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + for i := uint32(0); i < blocks; i++ { + if _, err := s.Write(i, blk(byte(i+1))); err != nil { + t.Fatalf("write %d of %d: %v", i, blocks, err) + } + if (i+1)%10 == 0 { + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + } + for i := uint32(0); i < blocks; i++ { + if got, err := s.Read(i); err != nil || !bytes.Equal(got, blk(byte(i+1))) { + t.Fatalf("readback %d: %v", i, err) + } + } + if floor, ok := s.v3.pub.reuseFloor(); !ok || floor <= walSize { + t.Fatalf("no actual multi-lap reuse: %d %v", floor, ok) + } +} + +func admissionPressureV3(t *testing.T, records int) *WALStore { + t.Helper() + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 32, 4096, 64*1024, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + for i := 0; i < records; i++ { + if _, err := s.Write(uint32(i), blk(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + return s +} + +func TestWALStoreV3AdmissionSoftThrottles(t *testing.T) { + s := admissionPressureV3(t, 12) + var delay time.Duration + s.admission.sleepFn = func(d time.Duration) { delay += d } + if err := s.admission.Acquire(time.Second); err != nil { + t.Fatal(err) + } + s.admission.Release() + if s.admission.PressureState() != "soft" || delay <= 0 || delay > 5*time.Millisecond { + t.Fatalf("soft throttle: state=%s delay=%v", s.admission.PressureState(), delay) + } +} + +func TestWALStoreV3AdmissionStallDeadlineAndResume(t *testing.T) { + s := admissionPressureV3(t, 15) + if err := s.admission.Acquire(10 * time.Millisecond); !errors.Is(err, errWALFull) { + if err == nil { + s.admission.Release() + } + t.Fatalf("stalled flusher must reach bounded deadline: %v", err) + } + parked, release, done := holdHardAdmissionWaitV3(t, s) + select { + case <-parked: + case <-time.After(5 * time.Second): + t.Fatal("admission never entered hard-pressure sleep") + } + select { + case err := <-done: + t.Fatalf("admitted before actual reclaim: %v", err) + default: + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + // This assertion budget starts AFTER disk fsync/checkpoint work. The + // controller retains the store's real admission deadline, not an artificial1s. + release() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(2 * time.Second): + t.Fatal("reclaim did not release waiter") + } + if got := s.admission.PressureState(); got != "normal" { + t.Fatalf("post-checkpoint pressure=%s", got) + } +} + +func TestWALStoreV3AdmissionCloseEndsPressureWait(t *testing.T) { + s := admissionPressureV3(t, 15) + parked, release, done := holdHardAdmissionWaitV3(t, s) + select { + case <-parked: + case <-time.After(5 * time.Second): + t.Fatal("no existing hard-pressure waiter") + } + // This is an existing controller waiter. An actual Write holds lifecycleMu + // through admission; this test does not claim to change that Close protocol. + if err := s.Close(); err != nil { + t.Fatal(err) + } + release() + select { + case err := <-done: + if !errors.Is(err, errVolumeClosed) { + t.Fatalf("existing pressured waiter after Close: %v", err) + } + case <-time.After(2 * time.Second): + t.Fatal("Close did not release existing controller waiter") + } +} + +// The first actual hard-pressure sleep is the barrier. Notify alone is earlier +// than the loop's closed check and therefore cannot prove an existing waiter. +func holdHardAdmissionWaitV3(t *testing.T, s *WALStore) (<-chan struct{}, func(), <-chan error) { + t.Helper() + if s.admission.PressureState() != "hard" { + t.Fatal("setup lacks native hard pressure") + } + parked, resume := make(chan struct{}), make(chan struct{}) + var releaseOnce, parkOnce sync.Once + release := func() { releaseOnce.Do(func() { close(resume) }) } + sleep := s.admission.sleepFn + s.admission.sleepFn = func(d time.Duration) { + parkOnce.Do(func() { close(parked); <-resume }) + sleep(d) + } + done := make(chan error, 1) + finished := make(chan struct{}) + go func() { + err := s.admission.Acquire(s.admissionTimeout) + if err == nil { + s.admission.Release() + } + done <- err + close(finished) + }() + t.Cleanup(func() { + release() + _ = s.Close() + // Even a broken close guard is bounded by the real controller deadline; + // join the worker instead of abandoning it when an assertion fails. + select { + case <-finished: + case <-time.After(s.admissionTimeout + time.Second): + t.Error("admission worker did not join") + } + }) + return parked, release, done +} diff --git a/seaweed-block/core/storage/walstore_batch_lsn_reuse_test.go b/seaweed-block/core/storage/walstore_batch_lsn_reuse_test.go index a98d4f3f33..a10bc21bb0 100644 --- a/seaweed-block/core/storage/walstore_batch_lsn_reuse_test.go +++ b/seaweed-block/core/storage/walstore_batch_lsn_reuse_test.go @@ -18,7 +18,7 @@ import ( func TestWALStoreFailedBatchAppendDoesNotRevertALaterAckedWrite(t *testing.T) { const blockSize = 4096 path := filepath.Join(t.TempDir(), "store.bin") - s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 64*1024) + s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 64*1024) s.DisableAutoFlushForRecoveryTest() crashed := false t.Cleanup(func() { @@ -80,7 +80,7 @@ func TestWALStoreFailedBatchAppendDoesNotRevertALaterAckedWrite(t *testing.T) { func reopenForB5(t *testing.T, path string) *WALStore { t.Helper() - r, err := OpenWALStore(path) + r, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/walstore_batch_v3_test.go b/seaweed-block/core/storage/walstore_batch_v3_test.go new file mode 100644 index 0000000000..1bd91b7e2d --- /dev/null +++ b/seaweed-block/core/storage/walstore_batch_v3_test.go @@ -0,0 +1,410 @@ +package storage + +import ( + "bytes" + "errors" + "testing" +) + +// v3 WriteBatch controls (DESIGN r17.4 sections 3.1 and 6.7; owner +// claude03): one multi-block record per batch, its replay and reads. + +func batchBlocks(first byte, n int) [][]byte { + out := make([][]byte, n) + for i := range out { + out[i] = blk(first + byte(i)) + } + return out +} + +func readBatchV3(t *testing.T, s *WALStore, lba uint32, first byte, n int, what string) { + t.Helper() + for i := 0; i < n; i++ { + if got := readV3(t, s, lba+uint32(i)); !bytes.Equal(got, blk(first+byte(i))) { + t.Fatalf("%s: LBA %d = %x..., want %x", what, lba+uint32(i), got[0], first+byte(i)) + } + } +} + +// A batch is one record with consecutive LSNs; every block reads back in +// the same open (each dirty entry names its offset inside the record) and +// after a crash and reopen (replay of the whole record); the next write +// continues after the batch's last LSN. Mutants: reading every block at +// offset 0, and replaying only a batch's first block, fail here. +func TestWALStoreV3BatchRoundTripAcrossACrash(t *testing.T) { + for name, mode := range map[string]WMode{"strict": WModeStrict, "lagged": WModeLagged} { + t.Run(name, func(t *testing.T) { + s, path := newStoreV3(t, mode) + lsns, err := s.WriteBatch(10, batchBlocks(0x40, 4)) + if err != nil { + t.Fatal(err) + } + for i, lsn := range lsns { + if lsn != uint64(1+i) { + t.Fatalf("LSNs %v, want 1..4", lsns) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + readBatchV3(t, s, 10, 0x40, 4, "same open") + if lsn, err := s.Write(12, blk(0x99)); err != nil || lsn != 5 { + t.Fatalf("write after the batch: LSN %d err %v, want 5", lsn, err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + r := mustReopenV3(t, path) + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + for lba, want := range map[uint32]byte{10: 0x40, 11: 0x41, 12: 0x99, 13: 0x43} { + if got := readV3(t, r, lba); !bytes.Equal(got, blk(want)) { + t.Fatalf("after reopen LBA %d = %x..., want %x", lba, got[0], want) + } + } + }) + } +} + +// A torn, unacknowledged batch is dropped whole: none of its blocks is +// served after the reopen, the earlier acknowledged write stays. A torn, +// acknowledged batch fails closed (wal_corrupt), never a partial image. +func TestWALStoreV3TornBatchIsAllOrNothing(t *testing.T) { + t.Run("unacknowledged", func(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + writeSynced(t, s, 1, 1) + if _, err := s.WriteBatch(10, batchBlocks(0x40, 4)); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + damageRecord(t, path, 2) // the batch record (LSNs 2..5) + r := mustReopenV3(t, path) + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + readAllV3(t, r, 1, 1) + for lba := uint32(10); lba < 14; lba++ { + if got := readV3(t, r, lba); !bytes.Equal(got, blk(0)) { + t.Fatalf("LBA %d served from a torn batch: %x...", lba, got[0]) + } + } + }) + t.Run("acknowledged", func(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + if _, err := s.WriteBatch(10, batchBlocks(0x40, 4)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + damageRecord(t, path, 1) + if r, err := reopenV3(t, path); err == nil { + crashRecoveryHardeningStore(t, r) + t.Fatal("a torn acknowledged batch reopened") + } else if !isWALCorrupt(err) { + t.Fatalf("reopen: err = %v, want a WAL integrity failure", err) + } + }) +} + +// A crash in the middle of a batch's pwrite (half the record written, then +// an error) latches the store: the batch fails, a later Sync refuses and +// acknowledges nothing, and the reopen serves none of the batch. Mutant: +// writing a batch as one record per block keeps the first blocks of a +// half-written batch and fails here. +func TestWALStoreV3CrashMidBatchServesNoneOfIt(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + writeSynced(t, s, 1, 1) + real := s.v3.w.writeAt + s.v3.w.writeAt = func(b []byte, off int64) (int, error) { + if len(b) > 2*v3TestBlock { + half := len(b) / 2 + n, _ := real(b[:half], off) + return n, errors.New("injected crash mid-batch") + } + return real(b, off) + } + if _, err := s.WriteBatch(10, batchBlocks(0x40, 4)); err == nil { + t.Fatal("a half-written batch succeeded") + } + wack := s.v3.wack.Load() + if _, err := s.Sync(); err == nil { + t.Fatal("Sync acknowledged after a failed batch pwrite") + } + if s.v3.wack.Load() != wack { + t.Fatal("the acknowledged frontier moved after a failed batch") + } + crashRecoveryHardeningStore(t, s) + r := mustReopenV3(t, path) + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + readAllV3(t, r, 1, 1) + for lba := uint32(10); lba < 14; lba++ { + if got := readV3(t, r, lba); !bytes.Equal(got, blk(0)) { + t.Fatalf("LBA %d served from a half-written batch: %x...", lba, got[0]) + } + } +} + +// The ack boundary: Sync after a batch returns at least its last LSN and +// (strict) the slot's W covers it; in mode C the next refresh publishes it. +func TestWALStoreV3BatchAckCoversItsLastLSN(t *testing.T) { + for name, mode := range map[string]WMode{"strict": WModeStrict, "lagged": WModeLagged} { + t.Run(name, func(t *testing.T) { + s, _ := newStoreV3(t, mode) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + if _, err := s.WriteBatch(10, batchBlocks(0x40, 4)); err != nil { + t.Fatal(err) + } + f, err := s.Sync() + if err != nil || f < 4 { + t.Fatalf("Sync = (%d, %v), want >= 4", f, err) + } + if mode == WModeLagged { + if err := s.refreshW(); err != nil { + t.Fatal(err) + } + } + if w := s.v3.pub.current().W; w < 4 { + t.Fatalf("slot W %d does not cover the batch's last LSN 4", w) + } + }) + } +} + +// The flusher materializes every block of a batch at its offset; after the +// checkpoint the reads come from the extent, also across a reopen. Mutant: +// a flusher that reads every block at offset 0 fails here. +func TestWALStoreV3BatchFlushesEveryBlock(t *testing.T) { + s, path, crash := checkpointedStoreV3(t, 1) + if _, err := s.WriteBatch(10, batchBlocks(0x40, 4)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + if d := s.v3.pub.current(); d.CheckpointLSN < 5 || s.dm.len() != 0 { + t.Fatalf("after flush: checkpoint %d, dirty %d", d.CheckpointLSN, s.dm.len()) + } + readBatchV3(t, s, 10, 0x40, 4, "from the extent") + crash() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { crashRecoveryHardeningStore(t, r) }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + readBatchV3(t, r, 10, 0x40, 4, "after reopen") +} + +// The dark offline reader (codex03's walstore_readonly_v3.go) indexes and +// reads every block of a batch record. Mutant: indexing only a batch's +// first block fails here. +func TestWALStoreV3ReadOnlyReaderServesBatchBlocks(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) // the reader validates the owned map + if _, err := s.WriteBatch(10, batchBlocks(0x40, 4)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + reader, err := openReadOnlyV3(path, WALStoreOptions{}) + if err != nil { + t.Fatalf("readonly open: %v", err) + } + t.Cleanup(func() { _ = reader.Close() }) + for i := 0; i < 4; i++ { + got, err := reader.Read(10 + uint32(i)) + if err != nil || !bytes.Equal(got, blk(0x40+byte(i))) { + t.Fatalf("readonly LBA %d: err %v", 10+i, err) + } + } +} + +// The map coverage follows every block's LSN (DESIGN 9.1). Mutant: a batch +// that records no map writes fails here. +func TestWALStoreV3BatchRecordsMapCoverage(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + if _, err := s.WriteBatch(4, batchBlocks(0x40, 8)); err != nil { // chunks 1 and 2 + t.Fatal(err) + } + s.mu.RLock() + defer s.mu.RUnlock() + for c, want := range map[int]uint64{1: 4, 2: 8} { + if got := s.v3.mapEntries[c].LSN; got < want { + t.Fatalf("chunk %d map LSN %d, want >= %d", c, got, want) + } + } +} + +// Ordinary replicated ApplyEntry on v3 (DESIGN 8.1, 6.7, r16.1; codex03 +// 12a inventory): applies append in LSN order and survive a crash; an LSN +// at or below the highest is a superseded no-op when the LBA holds a higher +// LSN and ErrWALLSNOrder otherwise; an unanchored gap is refused; an +// ordinary apply while installing is refused (the install lane is the +// handle's). Mutants: no order check, no gap check, no installing refusal. +func TestWALStoreV3ReplicatedApply(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + for lsn := uint64(1); lsn <= 3; lsn++ { + if err := s.ApplyEntry(uint32(lsn), blk(byte(lsn)), lsn); err != nil { + t.Fatalf("apply %d: %v", lsn, err) + } + } + if err := s.ApplyEntry(2, blk(0x22), 3); err != nil { + // LBA 2 holds LSN 2 < 3, but 3 is already appended (on LBA 3). + if !errors.Is(err, ErrWALLSNOrder) { + t.Fatalf("an appended LSN on another LBA: err = %v, want ErrWALLSNOrder", err) + } + } else { + t.Fatal("an LSN at the highest appended was applied again") + } + if err := s.ApplyEntry(3, blk(0x33), 2); err != nil { + t.Fatalf("a superseded lower LSN for an LBA that holds a higher one: %v, want a no-op", err) + } + if err := s.ApplyEntry(9, blk(9), 9); !errors.Is(err, ErrInstallLSNGap) { + t.Fatalf("a gap above 3: err = %v, want the gap refusal", err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + r := mustReopenV3(t, path) + readAllV3(t, r, 1, 3) + beginV3(t, r, 3, idA) + if err := r.ApplyEntry(4, blk(4), 4); !errors.Is(err, ErrBaseInstalling) { + t.Fatalf("an ordinary apply while installing: err = %v, want ErrBaseInstalling", err) + } + crashRecoveryHardeningStore(t, r) +} + +// v3 ScanLBAs, the primary's catch-up source: single and batch records in +// LSN order (a batch one entry per block), from the start and from the +// middle of a batch; a fromLSN the retention gate has recycled is refused +// with the typed WALRecycled failure. Mutants: the v2 scan on a v3 store +// (emits nothing), a batch emitting only its first block, no ordering. +func TestWALStoreV3ScanLBAs(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 3) // LSNs 1..3 at LBAs 1..3 + if _, err := s.WriteBatch(10, batchBlocks(0x40, 4)); err != nil { // LSNs 4..7 + t.Fatal(err) + } + collect := func(from uint64) []RecoveryEntry { + var out []RecoveryEntry + if err := s.ScanLBAs(from, func(e RecoveryEntry) error { + out = append(out, RecoveryEntry{LSN: e.LSN, LBA: e.LBA, Flags: e.Flags, Data: append([]byte(nil), e.Data...)}) + return nil + }); err != nil { + t.Fatalf("ScanLBAs(%d): %v", from, err) + } + return out + } + all := collect(1) + if len(all) != 7 { + t.Fatalf("ScanLBAs(1) emitted %d entries, want 7", len(all)) + } + for i, e := range all { + lsn := uint64(i + 1) + wantLBA, want := uint32(lsn), blk(byte(lsn)) + if lsn >= 4 { + wantLBA, want = 10+uint32(lsn-4), blk(0x40+byte(lsn-4)) + } + if e.LSN != lsn || e.LBA != wantLBA || !bytes.Equal(e.Data, want) || e.Flags != RecoveryEntryWrite { + t.Fatalf("entry %d: LSN %d LBA %d data %x..., want LSN %d LBA %d", i, e.LSN, e.LBA, e.Data[0], lsn, wantLBA) + } + } + mid := collect(6) + if len(mid) != 2 || mid[0].LSN != 6 || mid[0].LBA != 12 || mid[1].LSN != 7 { + t.Fatalf("ScanLBAs(6) = %+v, want LSNs 6 and 7 at LBAs 12 and 13", mid) + } + c, _, _ := checkpointedStoreV3(t, 4) + err := c.ScanLBAs(1, func(RecoveryEntry) error { return nil }) + if !errors.Is(err, ErrWALRecycled) { + t.Fatalf("ScanLBAs below the checkpoint: err = %v, want ErrWALRecycled", err) + } +} + +// codex01 4caac700 P1s: v3 ScanLBAs is all or nothing. A corrupt middle +// record makes the chain stop short of the head: a typed WAL integrity +// failure carrying the scanner's stop cause, with nothing emitted (never +// a short success, never WALRecycled). An installing +// source is refused before emitting; a source that begins installing +// during a held scan is refused at the revalidation; a Recover during a +// held scan retries from a fresh capture and returns the full range. +// Mutants: accepting a short prefix, ignoring the stop cause, no +// installing refusal, no revalidation. +func TestWALStoreV3ScanLBAsIsAllOrNothing(t *testing.T) { + count := func(s *WALStore, from uint64) (int, error) { + n := 0 + err := s.ScanLBAs(from, func(RecoveryEntry) error { n++; return nil }) + return n, err + } + t.Run("corrupt middle record", func(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 3) + damageRecord(t, path, 2) + n, err := count(s, 1) + if !isWALCorrupt(err) || !errors.Is(err, errCRCMismatch) || n != 0 { + t.Fatalf("ScanLBAs over a corrupt LSN 2: emitted %d, err %v; want 0 and a CRC WAL integrity failure", n, err) + } + }) + t.Run("corrupt first record", func(t *testing.T) { + // The scanner's stop cause decides the kind: a damaged first + // record is an integrity fault, never a recycled WAL. + s, path := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 3) + damageRecord(t, path, 1) + n, err := count(s, 1) + if !isWALCorrupt(err) || !errors.Is(err, errCRCMismatch) || n != 0 { + t.Fatalf("ScanLBAs over a corrupt LSN 1: emitted %d, err %v; want 0 and a CRC WAL integrity failure", n, err) + } + }) + t.Run("installing source", func(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 2) + beginV3(t, s, 2, idA) + if n, err := count(s, 1); !errors.Is(err, ErrBaseInstalling) || n != 0 { + t.Fatalf("installing source: emitted %d, err %v", n, err) + } + }) + t.Run("install begins during a held scan", func(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 2) + once := false + s.v3.testScanRead = func() { + if !once { + once = true + beginV3(t, s, 2, idA) + } + } + if n, err := count(s, 1); !errors.Is(err, ErrBaseInstalling) || n != 0 { + t.Fatalf("install during the scan: emitted %d, err %v", n, err) + } + }) + t.Run("Recover during a held scan retries", func(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 3) + retried := 0 + s.v3.testScanRead = func() { + retried++ + if retried == 1 { + if _, err := s.Recover(); err != nil { + t.Error(err) + } + } + } + if n, err := count(s, 1); err != nil || n != 3 || retried < 2 { + t.Fatalf("Recover during the scan: emitted %d, err %v, scans %d; want 3 entries after a retry", n, err, retried) + } + }) +} diff --git a/seaweed-block/core/storage/walstore_checkpoint_crash_linux_test.go b/seaweed-block/core/storage/walstore_checkpoint_crash_linux_test.go index 08877a68ad..86add171e5 100644 --- a/seaweed-block/core/storage/walstore_checkpoint_crash_linux_test.go +++ b/seaweed-block/core/storage/walstore_checkpoint_crash_linux_test.go @@ -44,7 +44,7 @@ func TestWALStoreCheckpointSIGKILLCrashWindows(t *testing.T) { t.Fatalf("crash helper returned normally: %s", output) } - reopened, err := OpenWALStore(path) + reopened, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -69,7 +69,7 @@ func TestWALStoreCheckpointSIGKILLCrashWindows(t *testing.T) { } func runCheckpointCrashHelper(window, path string) { - s, err := CreateWALStore(path, 16, 4096) + s, err := createLegacyWALStoreForTest(path, 16, 4096) if err != nil { panic(err) } diff --git a/seaweed-block/core/storage/walstore_checkpoint_safety_test.go b/seaweed-block/core/storage/walstore_checkpoint_safety_test.go index 166cdf1312..86b6ce18f3 100644 --- a/seaweed-block/core/storage/walstore_checkpoint_safety_test.go +++ b/seaweed-block/core/storage/walstore_checkpoint_safety_test.go @@ -34,7 +34,7 @@ func TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) if err != nil { t.Fatal(err) } @@ -145,7 +145,7 @@ func TestCheckpointPublicationCrashWindowsRemainRecoverable(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { path := filepath.Join(t.TempDir(), "store.bin") - s, err := CreateWALStore(path, 16, 4096) + s, err := createLegacyWALStoreForTest(path, 16, 4096) if err != nil { t.Fatal(err) } @@ -173,7 +173,7 @@ func TestCheckpointPublicationCrashWindowsRemainRecoverable(t *testing.T) { } s.fd = nil - reopened, err := OpenWALStore(path) + reopened, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -198,7 +198,7 @@ func TestCheckpointPublicationCrashWindowsRemainRecoverable(t *testing.T) { } func TestFlusherWALSlotMismatchFailsClosed(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) if err != nil { t.Fatal(err) } @@ -280,7 +280,7 @@ func TestFlusherRejectsCorruptOrUnsupportedDirtyRecord(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) if err != nil { t.Fatal(err) } @@ -337,7 +337,7 @@ func TestFlusherRejectsCorruptOrUnsupportedDirtyRecord(t *testing.T) { func TestWALStoreClosePerformsFinalFlush(t *testing.T) { path := filepath.Join(t.TempDir(), "store.bin") - s, err := CreateWALStore(path, 16, 4096) + s, err := createLegacyWALStoreForTest(path, 16, 4096) if err != nil { t.Fatal(err) } @@ -352,7 +352,7 @@ func TestWALStoreClosePerformsFinalFlush(t *testing.T) { t.Fatal(err) } - reopened, err := OpenWALStore(path) + reopened, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -373,7 +373,7 @@ func TestWALStoreClosePerformsFinalFlush(t *testing.T) { } func TestWALStoreCloseWaitsForInflightSync(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) if err != nil { t.Fatal(err) } @@ -414,7 +414,7 @@ func TestWALStoreCloseWaitsForInflightSync(t *testing.T) { } func TestWALStoreMutationAPIsRejectAfterClose(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) if err != nil { t.Fatal(err) } @@ -454,7 +454,7 @@ func TestWALStoreCloseReturnsFinalMetadataFailure(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) if err != nil { t.Fatal(err) } @@ -475,7 +475,7 @@ func TestWALStoreCloseReturnsFinalMetadataFailure(t *testing.T) { } func TestWriteExtentDirectSupersedesPriorDirtyWAL(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) if err != nil { t.Fatal(err) } @@ -503,7 +503,7 @@ func TestWriteExtentDirectSupersedesPriorDirtyWAL(t *testing.T) { func TestWriteExtentDirectSupersededWALDoesNotReappearAfterRestart(t *testing.T) { path := filepath.Join(t.TempDir(), "store.bin") - s, err := CreateWALStore(path, 16, 4096) + s, err := createLegacyWALStoreForTest(path, 16, 4096) if err != nil { t.Fatal(err) } @@ -527,7 +527,7 @@ func TestWriteExtentDirectSupersededWALDoesNotReappearAfterRestart(t *testing.T) t.Fatal(err) } - reopened, err := OpenWALStore(path) + reopened, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -545,7 +545,7 @@ func TestWriteExtentDirectSupersededWALDoesNotReappearAfterRestart(t *testing.T) } func TestRunningFlusherCannotOverwriteDirectBase(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) if err != nil { t.Fatal(err) } @@ -572,7 +572,7 @@ func TestRunningFlusherCannotOverwriteDirectBase(t *testing.T) { } func TestFlusherSnapshotCannotOverwriteLaterDirectBase(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) if err != nil { t.Fatal(err) } @@ -609,7 +609,7 @@ func TestFlusherSnapshotCannotOverwriteLaterDirectBase(t *testing.T) { } func TestWriteExtentDirectFailureRetainsDirtyWAL(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/walstore_close_v3_test.go b/seaweed-block/core/storage/walstore_close_v3_test.go new file mode 100644 index 0000000000..f08ff79bdf --- /dev/null +++ b/seaweed-block/core/storage/walstore_close_v3_test.go @@ -0,0 +1,97 @@ +package storage + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "testing" +) + +// codex01 row 7 slice 4 P1: WALStore.Close serialized the legacy superblock +// and pwrote it at offset 0, which on a v3 file is descriptor slot A. The +// schedule: strict create (A gen 1), Recover (B gen 2), Write+Sync (A gen 3, +// W 1), Close (slot A destroyed), reopen (B gen 2, W 0). A v3 Close writes +// nothing; reopen must select the newest slot A and its W. +func TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW(t *testing.T) { + for name, mode := range map[string]WMode{"strict": WModeStrict, "lagged": WModeLagged} { + t.Run(name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "close.v3") + s, err := createMappedWALStoreV3ForTest(path, 64, v3TestBlock, v3TestWAL, mode, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + writeSynced(t, s, 1, 1) + if mode == WModeLagged { + if err := s.refreshW(); err != nil { + t.Fatal(err) + } + } + if s.v3.pub.current().SlotGen%2 == 0 { + // Land the newest publication in slot A, the slot Close hit. + if _, err := s.v3.pub.publish(&s.mu, nil, nil); err != nil { + t.Fatal(err) + } + } + before := s.v3.pub.current() + if before.W != 1 || before.SlotGen%2 != 1 { + t.Fatalf("setup: newest slot gen %d W %d, want an odd (slot A) generation with W 1", before.SlotGen, before.W) + } + rawA := readSlotRawV3(t, path, slotAOffsetV3) + if err := s.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + if got := readSlotRawV3(t, path, slotAOffsetV3); !bytes.Equal(got, rawA) { + t.Fatal("Close rewrote descriptor slot A") + } + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatalf("reopen: %v", err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { r.Close() }) + if got := r.v3.pub.current(); got.SlotGen != before.SlotGen || got.W != 1 { + t.Fatalf("reopen selected gen %d W %d, want gen %d W 1", got.SlotGen, got.W, before.SlotGen) + } + if _, err := r.Recover(); err != nil { + t.Fatalf("Recover: %v", err) + } + readAllV3(t, r, 1, 1) + }) + } +} + +// The other legacy offset-0 writers (the checkpoint/recovery superblock +// writer and the direct-frontier writer behind SeedChunkFrontier and Sync's +// direct frontier) refuse on a v3 store and leave slot A untouched. +func TestWALStoreV3LegacySuperblockWritersRefuse(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 1) + rawA := readSlotRawV3(t, path, slotAOffsetV3) + junk := bytes.Repeat([]byte{0xEE}, 4096) + if err := s.writeSuperblockMetadata(junk); !errors.Is(err, errV3LegacySuperblockWrite) { + t.Fatalf("writeSuperblockMetadata: err = %v, want errV3LegacySuperblockWrite", err) + } + if err := s.syncDirectFrontierMetadata(junk); !errors.Is(err, errV3LegacySuperblockWrite) { + t.Fatalf("syncDirectFrontierMetadata: err = %v, want errV3LegacySuperblockWrite", err) + } + if got := readSlotRawV3(t, path, slotAOffsetV3); !bytes.Equal(got, rawA) { + t.Fatal("a refused legacy writer changed descriptor slot A") + } +} + +func readSlotRawV3(t *testing.T, path string, off int64) []byte { + t.Helper() + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + b := make([]byte, slotSizeV3) + if _, err := f.ReadAt(b, off); err != nil { + t.Fatal(err) + } + return b +} diff --git a/seaweed-block/core/storage/walstore_flushed_progress_v3_test.go b/seaweed-block/core/storage/walstore_flushed_progress_v3_test.go new file mode 100644 index 0000000000..0c4c667c56 --- /dev/null +++ b/seaweed-block/core/storage/walstore_flushed_progress_v3_test.go @@ -0,0 +1,88 @@ +package storage + +import ( + "bytes" + "sync" + "testing" +) + +func TestWALStoreV3_FlushedProgressRetriesAfterLaterSync(t *testing.T) { + for _, mode := range []WMode{WModeLagged, WModeStrict} { + t.Run(map[WMode]string{WModeLagged: "lagged", WModeStrict: "strict"}[mode], func(t *testing.T) { + s, path := newStoreV3(t, mode) + var once sync.Once + crash := func() { once.Do(func() { crashRecoveryHardeningStore(t, s) }) } + t.Cleanup(crash) // own the file/committer even when setup or an assertion fails + d := s.v3.pub.current() + m, err := createChunkLSNMapV3(path+".chunkmap", d, 1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := m.Close(); err != nil { + t.Error(err) + } + }) + // Real durable COW map candidates, with conservative coverage of all chunks. + // Automatic map attach and the bound-proof callback seam are separate row7 work. + es := make([]chunkLSNEntryV3, s.NumBlocks()) + for i := range es { + es[i].Unknown = true + } + generation := d.MapGeneration + var prior *chunkMapCandidateV3 + s.v3.mapCandidate = func(cp uint64) (func(*descriptorV3) error, error) { + generation++ + c, err := m.Prepare(generation, cp, es, prior) + if err != nil { + return nil, err + } + prior = c + return func(n *descriptorV3) error { *n = c.descriptor(*n); return nil }, nil + } + writeSynced(t, s, 1, 1) + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + first := s.v3.pub.current() + if first.CheckpointLSN != 1 || first.MapCoveredCheckpoint != 1 { + t.Fatalf("first clamp: cp=%d coverage=%d", first.CheckpointLSN, first.MapCoveredCheckpoint) + } + if _, _, lsn, _, ok := s.dm.get(2); !ok || lsn != 2 { + t.Error("flushed LSN2 lost its checkpoint retry ownership") + } + // No new write: formerly an empty cycle refreshed W only and stranded cp/coverage1. + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + last := s.v3.pub.current() + if last.CheckpointLSN != 2 || last.MapCoveredCheckpoint != 2 || last.W < 2 { + t.Fatalf("later Sync plus cycle stranded flushed progress: cp=%d coverage=%d W=%d", last.CheckpointLSN, last.MapCoveredCheckpoint, last.W) + } + if s.dm.len() != 0 { + t.Fatal("covered flushed entries did not retire from the dirty map") + } + if _, _, err := readChunkLSNMapV3(m.fd, last, 1); err != nil { + t.Fatalf("published coverage has no valid durable map: %v", err) + } + crash() + r := mustReopenV3(t, path) + t.Cleanup(func() { + if err := r.Close(); err != nil { + t.Error(err) + } + }) + for lba := uint32(1); lba <= 2; lba++ { + if !bytes.Equal(readV3(t, r, lba), blk(byte(lba))) { + t.Fatalf("reopened checkpoint lost LBA%d", lba) + } + } + }) + } +} diff --git a/seaweed-block/core/storage/walstore_format_admission_test.go b/seaweed-block/core/storage/walstore_format_admission_test.go index 98a6a86bc5..f984c47264 100644 --- a/seaweed-block/core/storage/walstore_format_admission_test.go +++ b/seaweed-block/core/storage/walstore_format_admission_test.go @@ -8,7 +8,7 @@ import ( func TestWALStore_UnknownFormatWithoutFactoryRefused(t *testing.T) { path := filepath.Join(t.TempDir(), "store") - s, err := CreateWALStore(path, 16, 4096) + s, err := createLegacyWALStoreForTest(path, 16, 4096) if err != nil { t.Fatal(err) } @@ -33,11 +33,11 @@ func TestWALStore_UnknownFormatWithoutFactoryRefused(t *testing.T) { if err = f.Close(); err != nil { t.Fatal(err) } - if x, err := OpenWALStore(path); err == nil { + if x, err := openLegacyWALStoreForTest(path); err == nil { x.Close() t.Fatal("unknown format opened without accepting factory") } - if x, err := OpenReadOnly(path); err == nil { + if x, err := openLegacyReadOnlyForTest(path); err == nil { x.Close() t.Fatal("unknown format readonly opened without accepting factory") } diff --git a/seaweed-block/core/storage/walstore_legacy_trim_test.go b/seaweed-block/core/storage/walstore_legacy_trim_test.go index 608be710ec..4ea34da5e1 100644 --- a/seaweed-block/core/storage/walstore_legacy_trim_test.go +++ b/seaweed-block/core/storage/walstore_legacy_trim_test.go @@ -14,7 +14,7 @@ func TestWALStoreRecoverReplaysLegacyRangeTrim(t *testing.T) { path := filepath.Join(t.TempDir(), "store.bin") func() { - s, err := CreateWALStore(path, 16, blockSize) + s, err := createLegacyWALStoreForTest(path, 16, blockSize) if err != nil { t.Fatal(err) } @@ -47,7 +47,7 @@ func TestWALStoreRecoverReplaysLegacyRangeTrim(t *testing.T) { crashRecoveryHardeningStore(t, s) }() - reader, err := OpenReadOnly(path) + reader, err := openLegacyReadOnlyForTest(path) if err != nil { t.Fatal(err) } @@ -64,7 +64,7 @@ func TestWALStoreRecoverReplaysLegacyRangeTrim(t *testing.T) { t.Fatal(err) } - s, err := OpenWALStore(path) + s, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go new file mode 100644 index 0000000000..ee902f622d --- /dev/null +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -0,0 +1,209 @@ +package storage + +// Actual owned-map checkpoint path, still dark until the single activation. +// capture/lifecycle admission remains with the existing caller; preparation +// performs no I/O under store/descriptor/leader locks. Publication uses the +// existing syncMu -> store.mu -> descMu -> fileSyncMu graph. + +// Caller holds WALStore.mu. Higher-LSN writes update the max; a reused or +// lower/equal effective LSN is conservative UNKNOWN, independent of the max. +// A reused ordered LSN below a speculative max can set UNKNOWN here without +// invalidating a prefix proof; the max and retained suffix stay conservative. +// Capture is the only future owner allowed to clear UNKNOWN after a version +// check. Keeping it set here cannot manufacture a remotely clean chunk. +func (s *WALStore) recordMapWriteV3(lba, lsn uint64) { + v := s.v3 + if v.ownedMap == nil { + return + } + e := &v.mapEntries[lba/v.ownedMap.chunkBlocks] + if lsn <= e.LSN { + e.Unknown = true + } + e.LSN = max(e.LSN, lsn) +} + +func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicationV3, error) { + v := s.v3 + s.mu.RLock() + if err := s.stickyIOFault(); err != nil { + s.mu.RUnlock() + return nil, err + } + v.pub.descMu.Lock() + prior, domain := v.pub.mapCurrent, v.pub.mapDomain + if prior == nil || prior.owner != v.ownedMap || domain != v.mapProof { + v.pub.descMu.Unlock() + s.mu.RUnlock() + return nil, mapCoverageRefusal("map_binding_changed") + } + proof := domain.snapshotV3() + // Entries may already contain LSNs above cp or W from earlier appends: max-LSN + // entries are monotone and idempotent under retained-suffix replay. + entries := append([]chunkLSNEntryV3(nil), v.mapEntries...) + v.pub.descMu.Unlock() + s.mu.RUnlock() + c, err := v.ownedMap.prepareNextV3(cp, entries, prior) + if err != nil { + return nil, err + } + if !proof.validV3(domain) { + v.ownedMap.abandonCandidateV3(c) // prepared but never publishable + return nil, mapCoverageRefusal("proof_changed_during_prepare") + } + return &preparedMapPublicationV3{candidate: c, proof: proof}, nil +} + +func (s *WALStore) persistOwnedMapCheckpointV3(highestLSN, recoveryGen uint64) error { + v := s.v3 + if err := s.stickyIOFault(); err != nil { + return err + } + cp := min(highestLSN, v.wack.Load()) + s.mu.RLock() + floorSource := s.recycleFloorSrc + s.mu.RUnlock() + if floorSource != nil { + if floor, active := floorSource.MinPinAcrossActiveSessions(); active { + cp = min(cp, floor) + } + } + if cp <= v.pub.current().CheckpointLSN { + v.syncMu.Lock() + defer v.syncMu.Unlock() + s.mu.Lock() + defer s.mu.Unlock() + if !v.flushLifetimeValidV3(recoveryGen) { + return mapCoverageRefusal("recovery_lifetime_changed") + } + return s.rolloverCheckpointV3Locked() + } + // The extent was fsynced by the flusher. + d, err := s.publishCheckpointV3(cp, false, recoveryGen) + if err != nil { + return err + } + s.mu.Lock() + s.checkpointLSN = d.CheckpointLSN + s.mu.Unlock() + return nil +} + +// publishCheckpointV3 is the one v3 checkpoint publication (plan row 9: the +// flusher's checkpoint and SeedChunkFrontier both use it). The optional +// metadata and chunk callbacks settle first, then the owned-map candidate +// is persisted outside every lock, then the sole slot publisher runs under +// the leader role (syncMu), refusing a candidate from another recovery +// lifetime or one above the acknowledged W. seed raises the acknowledged W +// to cp in the same leader section (the inherited remote frontier). The +// caller has made the extent durable. Nothing is published on any error. +func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) (descriptorV3, error) { + v := s.v3 + if s.metadata != nil { + if err := s.metadata.BeforeCheckpointAdvance(cp); err != nil { + return descriptorV3{}, err + } + } + if h := s.chunk.Load(); h != nil { + if err := h.sink.BeforeCheckpointAdvance(cp); err != nil { + return descriptorV3{}, err + } + } + prepared, err := s.prepareOwnedMapCheckpointV3(cp) + if err != nil { + return descriptorV3{}, err + } + if h := v.testMapPrepared; h != nil { + h() + } + v.syncMu.Lock() + defer v.syncMu.Unlock() + // The candidate proof alone is insufficient: it was prepared after extent + // I/O and could belong to a newer Recover lifetime than those bytes. + if !v.flushLifetimeValidV3(recoveryGen) { + prepared.abandonV3() + return descriptorV3{}, mapCoverageRefusal("recovery_lifetime_changed") + } + wack := v.wack.Load() + if seed { + wack = max(wack, cp) + } + if wack < cp { + prepared.abandonV3() + return descriptorV3{}, mapCoverageRefusal("checkpoint_above_wack") + } + s.mu.RLock() + retention := s.recoveryRetentionLSNs + s.mu.RUnlock() + releaseLSN := uint64(0) + if cp > retention { + releaseLSN = cp - retention + } + tail := v.w.reclaimThroughV3(releaseLSN) + current := v.pub.current() + if current.BaseState == BaseInstalling { + // An incomplete BASE still needs its entire install-lane suffix. + tail = min(tail, current.BaseCursor) + } + // Keep writer admission excluded until both durable publications AND the + // old dirty references are settled. The ordinary publisher releases a + // supplied store lock before I/O, so acquire it here and pass nil instead. + s.mu.Lock() + defer s.mu.Unlock() + d, err := v.pub.publishMapV3(nil, nil, prepared, func(n *descriptorV3) error { + n.W = max(n.W, wack) + n.CheckpointLSN = cp + n.RetainedTail = max(n.RetainedTail, tail) + n.RetainedHead = max(n.RetainedHead, n.RetainedTail) + return nil + }) + if err != nil { + return descriptorV3{}, err + } + // Reuse still waits for BOTH valid slots. This uses the same sole + // publisher and existing immutable map; failure keeps the old slot pin + // and latches the store before the flusher retires dirty entries. + if _, err := v.pub.rolloverIfPinned(); err != nil { + return descriptorV3{}, err + } + // Only a successful checkpoint plus rollover may retire retry ownership. + // Every current entry <= cp is durable in extent (a newer concurrent write + // has a higher LSN and survives). No writer can reuse a released slot until + // this store lock is released, after these references have disappeared. + s.retireCheckpointDirtyV3Locked(d.CheckpointLSN) + if seed { + v.appended.Store(max(v.appended.Load(), cp)) + v.wack.Store(wack) + } + return d, nil +} + +// Caller holds store.mu; the successful durable checkpoint proves the current +// versions at/below cp are in extent. Each shard preserves newer WAL entries. +func (s *WALStore) retireCheckpointDirtyV3Locked(cp uint64) { + for i := range s.dm.shards { + shard := &s.dm.shards[i] + shard.mu.Lock() + for lba, e := range shard.m { + if e.lsn <= cp { + delete(shard.m, lba) + } + } + shard.mu.Unlock() + } +} + +// Caller holds store.mu (and, except write admission, the leader role). +// No writer may use the newly released floor until its obsolete dirty +// references are retired. On failure keep those exact retry entries. +func (s *WALStore) rolloverCheckpointV3Locked() error { + d, floor, valid := s.v3.pub.walSnapshotV3() + if valid && floor >= d.RetainedTail { + return nil + } + if _, err := s.v3.pub.rolloverIfPinned(); err != nil { + return err + } + s.retireCheckpointDirtyV3Locked(d.CheckpointLSN) + return nil +} diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go new file mode 100644 index 0000000000..27bba23235 --- /dev/null +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go @@ -0,0 +1,417 @@ +package storage + +import ( + "bytes" + "errors" + "sync" + "testing" + "time" +) + +func newMappedCheckpointStoreV3(t *testing.T) (*WALStore, string) { + t.Helper() + path := t.TempDir() + "/mapped" + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, v3TestWAL, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { s.Close() }) + return s, path +} +func TestWALStoreV3_AutomaticMapCheckpoint(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + if d.CheckpointLSN != 2 || d.MapCoveredCheckpoint != 2 || d.W < 2 { + t.Fatalf("automatic map checkpoint stayed at cp=%d C=%d W=%d", d.CheckpointLSN, d.MapCoveredCheckpoint, d.W) + } + es, _, err := readChunkLSNMapV3(s.v3.ownedMap.fd, d, 4) + if err != nil { + t.Fatal(err) + } + if es[0].LSN != 2 || !es[0].Unknown { + t.Errorf("map lost effective write coverage: %+v", es[0]) + } + if s.dm.len() != 0 { + t.Error("covered dirty entries not retired") + } + crashRecoveryHardeningStore(t, s) // no Close/final flush or descriptor refresh + s.mu.Lock() + s.closed = true + s.mu.Unlock() // cleanup must not touch the crashed file + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { r.Close() }) + if _, err = r.Recover(); err != nil { + t.Fatal(err) + } + for lba := uint32(1); lba <= 2; lba++ { + if !bytes.Equal(readV3(t, r, lba), blk(byte(lba))) { + t.Errorf("LBA%d lost after checkpoint reopen", lba) + } + } +} +func TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore(t *testing.T) { + for _, stage := range []string{"file", "root", "directory"} { + t.Run(stage, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + before := s.v3.pub.current() + injected := errors.New("injected map persistence failure") + if stage == "root" { + realSync := s.v3.ownedMap.syncFile + calls := 0 + s.v3.ownedMap.syncFile = func() error { + calls++ + if calls == 2 { + return injected + } + return realSync() + } + } else if stage == "file" { + s.v3.ownedMap.syncFile = func() error { return injected } + } else { + s.v3.ownedMap.syncDirectory = func() error { return injected } + } + err := s.flusher.flushOnce() + if !errors.Is(err, injected) { + t.Errorf("automatic flusher did not surface map persistence failure: %v", err) + } + if s.stickyIOFault() == nil { + t.Error("map persistence failure did not latch the whole store") + } + if s.v3.pub.current() != before { + t.Error("failed map persistence published a descriptor") + } + if s.dm.len() != 1 { + t.Error("failed map persistence retired dirty retry ownership") + } + if _, err = s.Sync(); err == nil { + t.Error("Sync acknowledged after map persistence failure") + } + if _, err = s.Write(2, blk(2)); err == nil { + t.Error("Write accepted after map persistence failure") + } + if _, err = s.Recover(); err == nil { + t.Error("Recover accepted after map persistence failure") + } + // Close is expected to surface the latched failure and still owns cleanup. + }) + } +} + +func TestWALStoreV3_PreparedCheckpointRefusesChangedProof(t *testing.T) { + for _, event := range []string{"write", "recover"} { + t.Run(event, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + entered, resume, joined := make(chan struct{}), make(chan struct{}), make(chan struct{}) + done := make(chan error, 1) + var once sync.Once + release := func() { once.Do(func() { close(resume) }) } + s.v3.testMapPrepared = func() { close(entered); <-resume } + t.Cleanup(func() { + release() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("flusher did not join") + } + }) + go func() { defer close(joined); done <- s.flusher.flushOnce() }() + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("actual flusher did not persist a map candidate") + } + if event == "write" { + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + } else { + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + } + before := s.v3.pub.current() + release() + select { + case err := <-done: + if event == "recover" && !errors.Is(err, ErrMapCoverageStale) { + t.Errorf("stale prepared checkpoint=%v", err) + } else if event == "write" && err != nil { + t.Errorf("newer retained append invalidated prefix coverage: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("flusher did not settle") + } + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Fatal("flusher result without join") + } + s.v3.testMapPrepared = nil + if event == "recover" && s.v3.pub.current() != before { + t.Error("stale proof published a checkpoint") + } else if event == "write" && s.CheckpointLSN() != 1 { + t.Error("newer retained append blocked the older checkpoint") + } + if s.stickyIOFault() != nil { + t.Error("proof refusal incorrectly latched a persistence fault") + } + if s.dm.len() == 0 { + t.Error("proof refusal lost retry ownership") + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatalf("fresh candidate retry: %v", err) + } + want := uint64(1) + if event == "write" { + want = 2 + } + d := s.v3.pub.current() + if d.CheckpointLSN != want || d.MapCoveredCheckpoint != want { + t.Fatalf("fresh retry cp=%d C=%d want%d", d.CheckpointLSN, d.MapCoveredCheckpoint, want) + } + }) + } +} +func TestWALStoreV3_AutomaticMapClampedProgressRetries(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + if err := s.SetWMode(WModeLagged); err != nil { + t.Fatal(err) + } + writeSynced(t, s, 1, 1) + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + if d.CheckpointLSN != 1 || d.MapCoveredCheckpoint != 1 || s.dm.len() != 1 { + t.Fatal("clamped automatic checkpoint lost retry ownership") + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + d = s.v3.pub.current() + if d.CheckpointLSN != 2 || d.MapCoveredCheckpoint != 2 || s.dm.len() != 0 { + t.Fatal("later Sync did not advance automatic checkpoint and coverage") + } +} +func TestWALStoreV3_UncertainMapCheckpointPinsDependencies(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + before := s.v3.pub.current() + injected := errors.New("descriptor response lost after full pwrite") + realWrite := s.v3.pub.io.writeSlot + s.v3.pub.io.writeSlot = func(off int64, b []byte) error { + if err := realWrite(off, b); err != nil { + return err + } + return injected + } + if err := s.flusher.flushOnce(); !errors.Is(err, ErrDescriptorPublishUncertain) { + t.Fatalf("uncertain checkpoint=%v", err) + } + if s.v3.pub.current() != before || s.dm.len() != 1 { + t.Fatal("unknown publication advanced in-memory checkpoint or retired dirty entries") + } + uncertain, ok := s.v3.pub.uncertainCandidate() + if !ok { + t.Fatal("unknown publication lost candidate pin") + } + if _, _, err := readChunkLSNMapV3(s.v3.ownedMap.fd, uncertain, 4); err != nil { + t.Fatalf("unknown slot references missing map: %v", err) + } + if _, err := s.Sync(); err == nil { + t.Fatal("unknown publication allowed Sync") + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { r.Close() }) + if _, err = r.Recover(); err != nil { + t.Fatal(err) + } + if !bytes.Equal(readV3(t, r, 1), blk(1)) { + t.Fatal("resolved checkpoint lost extent data") + } +} + +type checkpointOrderMetadataV3 struct{ before func(uint64) error } + +func (*checkpointOrderMetadataV3) OnExtentWrite(uint32, []byte) error { return nil } +func (*checkpointOrderMetadataV3) VerifyExtent(uint32, []byte) error { return nil } +func (h *checkpointOrderMetadataV3) BeforeCheckpointAdvance(cp uint64) error { return h.before(cp) } +func TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + dataDurable, metadataDone, mapDurable := false, false, false + failBarrier := true + injected := errors.New("metadata barrier refused") + s.metadata = &checkpointOrderMetadataV3{before: func(cp uint64) error { + if !dataDurable || cp != 1 || s.CheckpointLSN() != 0 { + t.Error("metadata callback not between data sync and checkpoint") + } + if failBarrier { + return injected + } + metadataDone = true + return nil + }} + realExtentSync := s.syncExtentFile + s.syncExtentFile = func() error { + err := realExtentSync() + if err == nil { + dataDurable = true + } + return err + } + m := s.v3.ownedMap + realMapSync, realDirectory := m.syncFile, m.syncDirectory + m.syncFile = func() error { + if !metadataDone { + t.Error("map persisted before metadata barrier") + } + return realMapSync() + } + m.syncDirectory = func() error { + err := realDirectory() + if err == nil { + mapDurable = true + } + return err + } + s.v3.testBeforeSlotWrite = func() error { + if !metadataDone || !mapDurable { + t.Error("descriptor published before map/metadata durability") + } + return nil + } + initial := s.v3.pub.current() + if err := s.flusher.flushOnce(); !errors.Is(err, injected) { + t.Fatalf("metadata failure=%v", err) + } + if s.v3.pub.current() != initial || m.lastGeneration != initial.MapGeneration || s.dm.len() != 1 { + t.Fatal("metadata refusal published/retired progress or prepared a map") + } + failBarrier = false + dataDurable = false + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if !metadataDone || !mapDurable || s.CheckpointLSN() != 1 { + t.Fatal("retry did not complete ordered checkpoint") + } +} +func TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 5, 5) + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { r.Close() }) + if _, err = r.Recover(); err != nil { + t.Fatal(err) + } + if err = r.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + es, _, err := readChunkLSNMapV3(r.v3.ownedMap.fd, r.v3.pub.current(), 4) + if err != nil { + t.Fatal(err) + } + if es[1].LSN != 1 { + t.Fatalf("replayed write omitted from map: %+v", es[1]) + } +} + +func TestWALStoreV3_MapFailureRefusesQueuedSync(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + waiting, joined := make(chan struct{}), make(chan struct{}) + done := make(chan error, 1) + var once sync.Once + s.v3.syncMu.Lock() + release := func() { once.Do(func() { s.v3.syncMu.Unlock() }) } + s.v3.testLeaderWaiting = func() { close(waiting) } + t.Cleanup(func() { + release() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("queued Sync did not join") + } + }) + go func() { defer close(joined); _, err := s.Sync(); done <- err }() + select { + case <-waiting: + case <-time.After(5 * time.Second): + t.Fatal("Sync did not queue for leader role") + } + injected := errors.New("map fsync failed while Sync queued") + s.v3.ownedMap.syncFile = func() error { return injected } + // Preparation is outside syncMu, so this failure must surface while the + // later Sync remains queued behind the held leader role. + flushed := make(chan error, 1) + go func() { flushed <- s.flusher.flushOnce() }() + select { + case err := <-flushed: + if !errors.Is(err, injected) { + t.Fatalf("map failure=%v", err) + } + case <-time.After(5 * time.Second): + // Release and join before failing; never abandon the flusher worker. + release() + <-flushed + t.Fatal("idle pressure check blocked map preparation behind Sync") + } + if s.stickyIOFault() == nil { + t.Error("map failure not globally latched before releasing Sync") + } + release() + select { + case err := <-done: + if err == nil { + t.Error("queued Sync acknowledged after map failure") + } + case <-time.After(5 * time.Second): + t.Fatal("queued Sync did not return") + } + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Fatal("Sync result without join") + } + s.v3.testLeaderWaiting = nil +} diff --git a/seaweed-block/core/storage/walstore_map_open_v3_test.go b/seaweed-block/core/storage/walstore_map_open_v3_test.go new file mode 100644 index 0000000000..7ac7dbd22c --- /dev/null +++ b/seaweed-block/core/storage/walstore_map_open_v3_test.go @@ -0,0 +1,179 @@ +package storage + +import ( + "bytes" + "errors" + "os" + "testing" +) + +// Actual store opener, not a manual bind after open. Bootstrap is explicit +// because this RED also runs before the automatic mapped creator exists. +func TestWALStoreV3_OpenRequiresBothMapGenerations(t *testing.T) { + for _, fault := range []string{"none", "missing", "fallback_page", "zero_root"} { + t.Run(fault, func(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + crashed := false + t.Cleanup(func() { + if !crashed { + crashRecoveryHardeningStore(t, s) + } + }) + d := s.v3.pub.current() + m, err := createChunkLSNMapV3(path+".chunkmap", d, 4) + if err != nil { + t.Fatal(err) + } + mapClosed := false + t.Cleanup(func() { + if !mapClosed { + m.Close() + } + }) + entries := make([]chunkLSNEntryV3, 16) + for i := range entries { + entries[i].Unknown = true + } + old, err := m.Prepare(2, 0, entries, nil) + if err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publish(&s.mu, nil, func(n *descriptorV3) error { *n = old.descriptor(*n); return nil }); err != nil { + t.Fatal(err) + } + entries[0].LSN = 1 // force a distinct immutable page in the newer generation + next, err := m.Prepare(3, 0, entries, old) + if err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publish(&s.mu, nil, func(n *descriptorV3) error { *n = next.descriptor(*n); return nil }); err != nil { + t.Fatal(err) + } + if fault == "fallback_page" { + if _, err = m.fd.WriteAt([]byte{0xff}, int64(old.refs[0].Offset)+64); err != nil { + t.Fatal(err) + } + if err = m.fd.Sync(); err != nil { + t.Fatal(err) + } + } + if fault == "zero_root" { + d = s.v3.pub.current() + d.MapRootHash = [32]byte{} + if _, err = s.fd.WriteAt(d.encode(), int64(s.v3.pub.curSlot)*4096); err != nil { + t.Fatal(err) + } + if err = s.fd.Sync(); err != nil { + t.Fatal(err) + } + } + if err = m.Close(); err != nil { + t.Fatal(err) + } + mapClosed = true + if fault == "missing" { + if err = os.Remove(path + ".chunkmap"); err != nil { + t.Fatal(err) + } + } + crashRecoveryHardeningStore(t, s) + crashed = true + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + mapBefore, mapBeforeErr := os.ReadFile(path + ".chunkmap") + r, err := openWALStoreV3ForTest(path) + if r != nil { + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { r.Close() }) + } + if fault != "none" { + after, e := os.ReadFile(path) + if e != nil { + t.Fatal(e) + } + if !bytes.Equal(before, after) { + t.Error("failed map open changed the store file") + } + mapAfter, mapAfterErr := os.ReadFile(path + ".chunkmap") + if !bytes.Equal(mapBefore, mapAfter) || os.IsNotExist(mapBeforeErr) != os.IsNotExist(mapAfterErr) { + t.Error("failed map open changed sidecar state") + } + if fault == "missing" && !os.IsNotExist(err) { + t.Errorf("missing map error=%v", err) + } + if fault != "missing" && !errors.Is(err, ErrMapInvalid) { + t.Errorf("corrupt map error=%v", err) + } + if err == nil { + t.Fatalf("store open accepted %s map dependency", fault) + } + if r != nil { + t.Error("failed map open returned a store") + } + return + } + if err != nil { + t.Fatal(err) + } + if r.v3.pub.mapDomain == nil || r.v3.pub.mapCurrent == nil { + t.Fatal("store open did not automatically bind its durable map") + } + if _, err = r.Recover(); err != nil { + t.Fatal(err) + } + }) + } +} + +func TestWALStoreV3_MappedCreateOpenOwnsMap(t *testing.T) { + path := t.TempDir() + "/mapped" + s, err := createMappedWALStoreV3ForTest(path, 65, 4096, v3TestWAL, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + closed := false + t.Cleanup(func() { + if !closed { + s.Close() + } + }) + if s.v3.ownedMap == nil || s.v3.pub.mapDomain == nil { + t.Fatal("created store has no owned map/proof") + } + es, _, err := readChunkLSNMapV3(s.v3.ownedMap.fd, s.v3.pub.current(), 4) + if err != nil { + t.Fatal(err) + } + if len(es) != 17 { + t.Fatalf("clipped geometry entries=%d want17", len(es)) + } + for _, e := range es { + if !e.Unknown || e.LSN != 0 { + t.Fatal("initial map is not conservative UNKNOWN") + } + } + oldDomain := s.v3.pub.mapDomain + mapFD := s.v3.ownedMap.fd + if err = s.Close(); err != nil { + t.Fatal(err) + } + closed = true + if _, err = mapFD.Stat(); err == nil { + t.Fatal("store Close leaked owned sidecar") + } + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { r.Close() }) + if r.v3.pub.mapDomain == nil || r.v3.pub.mapDomain == oldDomain { + t.Fatal("reopen did not create a fresh proof domain") + } + if _, err = r.Recover(); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/storage/walstore_map_recover_v3_test.go b/seaweed-block/core/storage/walstore_map_recover_v3_test.go new file mode 100644 index 0000000000..61ef49506d --- /dev/null +++ b/seaweed-block/core/storage/walstore_map_recover_v3_test.go @@ -0,0 +1,161 @@ +package storage + +import ( + "errors" + "path/filepath" + "sync" + "testing" + "time" +) + +// Row7 lifecycle slice: bind a durable map to the actual store publisher. +// This fixture does not claim automatic provider/chunk-layer map attachment. +func bindRecoveryMapV3(t *testing.T, s *WALStore) (*chunkLSNMapV3, *mapProofEpochV3, []chunkLSNEntryV3, *chunkMapCandidateV3) { + t.Helper() + d := s.v3.pub.current() + m, err := createChunkLSNMapV3(filepath.Join(t.TempDir(), "map"), d, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := m.Close(); err != nil { + t.Error(err) + } + }) + shape, err := mapShapeForV3(d, 4) + if err != nil { + t.Fatal(err) + } + es := make([]chunkLSNEntryV3, int(shape.chunks)) + for i := range es { + es[i].Unknown = true + } + c, err := m.Prepare(d.MapGeneration+1, d.CheckpointLSN, es, nil) + if err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publish(&s.mu, nil, func(n *descriptorV3) error { *n = c.descriptor(*n); return nil }); err != nil { + t.Fatal(err) + } + // Bootstrap both slots to the durable initial map before binding. The + // older dark row-5 placeholder has no sidecar dependency and cannot remain + // a valid fallback once the real map binding is installed. + if _, err = s.v3.pub.publish(&s.mu, nil, nil); err != nil { + t.Fatal(err) + } + proof := newMapProofEpochV3() + if err = s.v3.pub.bindMapV3(c, proof); err != nil { + t.Fatal(err) + } + return m, proof, es, c +} + +func TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd(t *testing.T) { + s, _ := newStoreV3(t, WModeLagged) + t.Cleanup(func() { + if err := s.Close(); err != nil { + t.Error(err) + } + }) + m, proof, es, current := bindRecoveryMapV3(t, s) + before, err := prepareMapPublicationV3(m, proof, current.generation+1, 0, es, current) + if err != nil { + t.Fatal(err) + } + startEpoch := proof.epoch.Load() + entered, resume, joined := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(resume) }) } + done := make(chan error, 1) + // The existing slot-write hook parks the real Recover after START and before END. + s.v3.testBeforeSlotWrite = func() error { close(entered); <-resume; return nil } + t.Cleanup(func() { + release() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("Recover did not join") + } + }) + go func() { defer close(joined); _, e := s.Recover(); done <- e }() + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("Recover did not reach its slot publication") + } + if before.proof.validV3(proof) || proof.epoch.Load() != startEpoch+1 { + t.Error("actual Recover START did not invalidate the previous map proof") + } + during, err := prepareMapPublicationV3(m, proof, current.generation+2, 0, es, current) + if err != nil { + t.Fatal(err) + } + release() + select { + case err = <-done: + case <-time.After(5 * time.Second): + t.Fatal("Recover did not finish") + } + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Fatal("Recover result arrived but worker did not join") + } + s.v3.testBeforeSlotWrite = nil + if err != nil { + t.Fatal(err) + } + if proof.epoch.Load() != startEpoch+2 { + t.Error("actual Recover END did not advance the map proof epoch") + } + for label, prepared := range map[string]*preparedMapPublicationV3{"before": before, "during": during} { + if _, err = s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); !errors.Is(err, ErrMapCoverageStale) { + t.Errorf("%s real Recover candidate was not refused as stale: %v", label, err) + } + } + fresh, err := prepareMapPublicationV3(m, proof, current.generation+3, 0, es, current) + if err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publishMapV3(&s.mu, nil, fresh, nil); err != nil { + t.Fatalf("fresh post-Recover candidate refused: %v", err) + } +} + +func TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + t.Cleanup(func() { + if err := s.Close(); err != nil { + t.Error(err) + } + }) + if _, err := s.Write(0, blk(0x51)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + m, proof, es, current := bindRecoveryMapV3(t, s) + before, err := prepareMapPublicationV3(m, proof, current.generation+1, 0, es, current) + if err != nil { + t.Fatal(err) + } + epoch := proof.epoch.Load() + off, _, _, _, ok := s.dm.get(0) + if !ok { + t.Fatal("synced write missing from WAL dirty map") + } + // Corrupt an acknowledged WAL payload: R= 5*time.Second { + t.Fatalf("budget=%v", s.admissionTimeout) + } + start := time.Now() + busyCount := 0 + var maxAttempt time.Duration + for i := uint32(0); i < count; i++ { + retryDeadline := time.Now().Add(30 * time.Second) + cpBefore, wackBefore := s.CheckpointLSN(), s.v3.wack.Load() + retried := false + for { + attemptStart := time.Now() + _, err := s.Write(i, blk(byte(i+1))) + elapsed := time.Since(attemptStart) + maxAttempt = max(maxAttempt, elapsed) + if elapsed >= 5*time.Second || time.Since(start) >= 2*time.Minute || time.Now().After(retryDeadline) { + t.Fatalf("no-client-Sync exceeded wait bound write=%d/%d attempt=%v total=%v busy=%d err=%v", i, count, elapsed, time.Since(start), busyCount, err) + } + if err == nil { + if retried { + t.Logf("no-client-Sync resumed write=%d cp=%d->%d wack=%d->%d busy=%d", i, cpBefore, s.CheckpointLSN(), wackBefore, s.v3.wack.Load(), busyCount) + } + break + } + if !errors.Is(err, ErrWALPressureTimeout) || s.stickyIOFault() != nil { + t.Fatalf("no-client-Sync non-retryable write %d/%d: %v", i, count, err) + } + busyCount++ + retried = true + t.Logf("no-client-Sync busy write=%d cp=%d wack=%d busy=%d attempt=%v", i, s.CheckpointLSN(), s.v3.wack.Load(), busyCount, elapsed) + if busyCount == 1 { + passiveStart := time.Now() + cpAtBusy, wackAtBusy := s.CheckpointLSN(), s.v3.wack.Load() + target := s.v3.appended.Load() + cpObserved, wackObserved := cpAtBusy, wackAtBusy + for cpAtBusy < target && cpObserved <= cpAtBusy && time.Since(passiveStart) < 10*time.Second { + time.Sleep(25 * time.Millisecond) + cpObserved, wackObserved = s.CheckpointLSN(), s.v3.wack.Load() + } + t.Logf("no-client-Sync passive write=%d wait=%v cpBefore=%d cpAtBusy=%d cpObserved=%d target=%d wack=%d->%d", i, time.Since(passiveStart), cpBefore, cpAtBusy, cpObserved, target, wackAtBusy, wackObserved) + if time.Since(passiveStart) >= 10*time.Second || (cpAtBusy < target && cpObserved <= cpAtBusy) || wackObserved < cpObserved { + t.Fatalf("no-client-Sync passive checkpoint did not advance without another write: cp=%d wack=%d busy=%d", cpObserved, wackObserved, busyCount) + } + } + time.Sleep(25 * time.Millisecond) + } + } + for i := uint32(0); i < count; i++ { + got, err := s.Read(i) + if err != nil || !bytes.Equal(got, blk(byte(i+1))) { + t.Fatalf("readback %d: %v", i, err) + } + } + t.Logf("no-client-Sync mode=%d writes=%d busy=%d elapsed=%v maxAttempt=%v", mode, count, busyCount, time.Since(start), maxAttempt) + }) + } +} + +func pressureStoreNoSync(t *testing.T, records uint32) *WALStore { + t.Helper() + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 96, 4096, 64*1024, WModeLagged, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < records; i++ { + if _, err := s.Write(i, blk(byte(i+1))); err != nil { + t.Fatal(err) + } + } + return s +} + +func TestWALStoreV3PressureSyncFaultDoesNotPublishFrontiers(t *testing.T) { + for _, mode := range []WMode{WModeLagged, WModeStrict} { + for _, stage := range []string{"fsync", "slot"} { + t.Run(fmt.Sprintf("mode-%d/%s", mode, stage), func(t *testing.T) { + s := pressureStoreNoSync(t, 12) + if err := s.SetWMode(mode); err != nil { + t.Fatal(err) + } + // SetWMode syncs; add fresh uncovered writes without changing pressure. + if _, err := s.Write(0, blk(99)); err != nil { + t.Fatal(err) + } + before := s.v3.pub.current() + ack := s.v3.wack.Load() + boom := errors.New("pressure persistence fault") + if stage == "slot" { + s.v3.testBeforeSlotWrite = func() error { return boom } + } else { + s.syncWALFile = func() error { return boom } + s.v3.pub.io.fsync = func() error { return boom } + } + err := s.syncWALPressureV3() + if !errors.Is(err, boom) || s.stickyIOFault() == nil { + t.Fatalf("lost pressure fault: %v", err) + } + if s.v3.wack.Load() != ack || s.CheckpointLSN() != before.CheckpointLSN { + t.Fatal("failed pressure persistence advanced frontier") + } + if _, err := s.Write(1, blk(98)); !errors.Is(err, boom) { + t.Fatalf("subsequent write lost cause: %v", err) + } + }) + } + } +} + +func TestWALStoreV3PressureSyncSkipsInstalling(t *testing.T) { + s, _ := newStoreV3(t, WModeLagged) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + h := beginV3(t, s, 0, idA) + for i := uint64(1); i <= 12; i++ { + if err := h.ApplyInstallEntry(uint32(i), blk(byte(i)), i); err != nil { + t.Fatal(err) + } + } + before := s.v3.pub.current() + ack := s.v3.wack.Load() + if err := s.syncWALPressureV3(); err != nil { + t.Fatal(err) + } + if s.v3.pub.current() != before || s.v3.wack.Load() != ack { + t.Fatal("ordinary pressure sync bypassed install-log gate") + } +} + +func TestWALStoreV3PressureWaitBudgetAndPin(t *testing.T) { + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 96, 4096, 64*1024, WModeLagged, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + if s.admissionTimeout <= 0 || s.admissionTimeout >= 5*time.Second { + t.Fatalf("pressure budget %v", s.admissionTimeout) + } + // Contract used by an active RF2 catch-up session: do not release its records. + s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 0, anyActive: true}) + start := time.Now() + var got error + for i := uint32(0); i < 96; i++ { + if _, got = s.Write(i, blk(byte(i+1))); got != nil { + break + } + } + if !errors.Is(got, ErrWALPressureTimeout) || time.Since(start) >= 5*time.Second { + t.Fatalf("pinned burst outcome %v after %v", got, time.Since(start)) + } + if s.CheckpointLSN() != 0 { + t.Fatal("active catch-up pin was bypassed") + } +} + +// TryRLock refuses only once the pending exclusive operation is queued: the +// parked Write still owns a read lock. No sleep guesses when the Lock queues. +func TestWALStoreV3PressureProgressWithPendingCutOrClose(t *testing.T) { + for _, kind := range []string{"cut", "close", "lifecycle"} { + closing := kind == "close" + t.Run(kind, func(t *testing.T) { + s := pressureStoreNoSync(t, 15) + parked, resume := make(chan struct{}), make(chan struct{}) + release := sync.OnceFunc(func() { close(resume) }) + cutRelease := make(chan struct{}) + releaseCut := sync.OnceFunc(func() { close(cutRelease) }) + var joins []chan struct{} + t.Cleanup(func() { + release() + releaseCut() + for _, done := range joins { + select { + case <-done: + case <-time.After(6 * time.Second): + t.Error("pressure worker did not join") + } + } + }) + var once sync.Once + s.admission.sleepFn = func(d time.Duration) { once.Do(func() { close(parked); <-resume }); time.Sleep(d) } + writerDone := make(chan struct{}) + joins = append(joins, writerDone) + var writeErr error + go func() { defer close(writerDone); _, writeErr = s.Write(16, blk(16)) }() + select { + case <-parked: + case <-time.After(2 * time.Second): + t.Fatal("writer not parked") + } + exclusiveDone := make(chan struct{}) + joins = append(joins, exclusiveDone) + go func() { + defer close(exclusiveDone) + if closing { + _ = s.Close() + } else if kind == "lifecycle" { + s.lifecycleMu.Lock() + defer s.lifecycleMu.Unlock() + <-cutRelease + } else { + s.captureMu.Lock() + defer s.captureMu.Unlock() + <-cutRelease + } + }() + deadline := time.Now().Add(time.Second) + for { + var admitted bool + if kind == "lifecycle" { + admitted = s.lifecycleMu.TryRLock() + if admitted { + s.lifecycleMu.RUnlock() + } + } else { + admitted = s.captureMu.TryRLock() + if admitted { + s.captureMu.RUnlock() + } + } + if !admitted { + break + } + if time.Now().After(deadline) { + t.Fatal("exclusive operation did not queue") + } + time.Sleep(time.Millisecond) + } + // Observe reaching physical persistence while the exclusive lock is + // pending; disk latency is not an oracle for a Go lock inversion. + physicalBoundary := make(chan struct{}) + var boundaryOnce sync.Once + s.testBeforeFileSync = func() { boundaryOnce.Do(func() { close(physicalBoundary) }) } + flushDone := make(chan struct{}) + joins = append(joins, flushDone) + var flushErr error + go func() { defer close(flushDone); flushErr = s.flusher.flushOnce() }() + select { + case <-physicalBoundary: + case <-time.After(5 * time.Second): + t.Fatal("pressure flusher did not reach persistence with exclusive lock pending") + } + // Join physical I/O before releasing the parked writer, so Close + // cannot close its file under this manually invoked cycle. This + // join bound is not the admission budget or a whole-I/O promise. + select { + case <-flushDone: + case <-time.After(10 * time.Second): + t.Fatal("pressure flusher physical I/O did not finish") + } + if flushErr != nil { + t.Fatal(flushErr) + } + release() + select { + case <-writerDone: + case <-time.After(3 * time.Second): + t.Fatal("writer did not drain") + } + // The test holds admission at sleep while real fsync runs. A slow + // disk may consume the unchanged production four-second budget; + // that typed outcome is permitted, never an indefinite lock wait. + if writeErr != nil && !errors.Is(writeErr, ErrWALPressureTimeout) { + t.Fatal(writeErr) + } + releaseCut() + select { + case <-exclusiveDone: + case <-time.After(10 * time.Second): + t.Fatal("exclusive operation did not finish") + } + }) + } +} + +func TestWALStoreV3FlushBatchCacheIsBoundToRecoveryLifetime(t *testing.T) { + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 32, 4096, 64*1024, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + if _, err := s.WriteBatch(0, [][]byte{blk(1), blk(2), blk(3), blk(4)}); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + e := s.dm.snapshot()[0] + cache := &flushRecordCacheV3{recoveryGen: s.v3.recoverGen.Load()} + if _, _, err := s.flusher.readDirtyRecordV3Cached(e, cache); err != nil { + t.Fatal(err) + } + before := s.FlusherInstrumentation() + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + after := s.FlusherInstrumentation() + if got := after.WALRecordDecodeOps - before.WALRecordDecodeOps; got != 1 { + t.Fatalf("four-block batch decoded %d times, want1", got) + } + for i := uint32(0); i < 4; i++ { + if got, err := s.Read(i); err != nil || !bytes.Equal(got, blk(byte(i+1))) { + t.Fatalf("batch read%d: %v", i, err) + } + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if _, _, err := s.flusher.readDirtyRecordV3Cached(e, cache); !errors.Is(err, ErrMapCoverageStale) { + t.Fatalf("old recovery lifetime cache accepted: %v", err) + } +} diff --git a/seaweed-block/core/storage/walstore_persisted_tail_test.go b/seaweed-block/core/storage/walstore_persisted_tail_test.go index ae0d9b6ae3..5b35a16deb 100644 --- a/seaweed-block/core/storage/walstore_persisted_tail_test.go +++ b/seaweed-block/core/storage/walstore_persisted_tail_test.go @@ -41,7 +41,7 @@ func TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords(t *testing.T) { ) S := uint64(walEntryHeaderSize + blockSize) path := filepath.Join(t.TempDir(), "store.bin") - s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize) + s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize) s.DisableAutoFlushForRecoveryTest() if _, err := s.Write(0, makeBlock(blockSize, 0x10)); err != nil { // LSN 1 t.Fatal(err) @@ -87,7 +87,7 @@ func TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords(t *testing.T) { t.Fatal(err) } crashRecoveryHardeningStore(t, s) - r, err := OpenWALStore(path) + r, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -106,7 +106,7 @@ func TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords(t *testing.T) { func TestWALStoreFlushPersistsTheReleasedTail(t *testing.T) { const blockSize = 4096 path := filepath.Join(t.TempDir(), "store.bin") - s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024) + s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024) s.DisableAutoFlushForRecoveryTest() t.Cleanup(func() { _ = s.Close() }) for round := 0; round < 3; round++ { @@ -134,7 +134,7 @@ func TestWALStoreFlushPersistsTheReleasedTail(t *testing.T) { func TestWALStoreRecoverPersistsTheRecoveredBounds(t *testing.T) { const blockSize = 4096 path := filepath.Join(t.TempDir(), "store.bin") - s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024) + s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024) s.DisableAutoFlushForRecoveryTest() if _, err := s.Write(0, makeBlock(blockSize, 0x30)); err != nil { // LSN 1 t.Fatal(err) @@ -162,7 +162,7 @@ func TestWALStoreRecoverPersistsTheRecoveredBounds(t *testing.T) { t.Fatal(err) } crashRecoveryHardeningStore(t, s) - r, err := OpenWALStore(path) + r, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -218,7 +218,7 @@ func TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords(t *testing.T) { ) S := uint64(walEntryHeaderSize + blockSize) path := filepath.Join(t.TempDir(), "store.bin") - s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize) + s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize) s.DisableAutoFlushForRecoveryTest() if _, err := s.Write(0, makeBlock(blockSize, 0x10)); err != nil { // LSN 1 t.Fatal(err) @@ -252,7 +252,7 @@ func TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords(t *testing.T) { t.Fatal(err) } crashRecoveryHardeningStore(t, s) - r, err := OpenWALStore(path) + r, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -362,7 +362,7 @@ func TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry(t *testing. for _, seam := range []string{"write", "sync"} { t.Run(seam, func(t *testing.T) { path := filepath.Join(t.TempDir(), "store.bin") - s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024) + s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024) s.DisableAutoFlushForRecoveryTest() crashed := false t.Cleanup(func() { @@ -397,7 +397,7 @@ func TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry(t *testing. crashRecoveryHardeningStore(t, s) crashed = true - r, err := OpenWALStore(path) + r, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -436,7 +436,7 @@ func TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry(t *testing. } crashRecoveryHardeningStore(t, r) rClosed = true - r2, err := OpenWALStore(path) + r2, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -466,7 +466,7 @@ func TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry(t *testing. crashRecoveryHardeningStore(t, live) rClosed = true - q, err := OpenWALStore(path) + q, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/walstore_read_miss_v3_test.go b/seaweed-block/core/storage/walstore_read_miss_v3_test.go new file mode 100644 index 0000000000..8fc1515fea --- /dev/null +++ b/seaweed-block/core/storage/walstore_read_miss_v3_test.go @@ -0,0 +1,85 @@ +package storage + +import ( + "bytes" + "path/filepath" + "sync" + "testing" + "time" +) + +// This sink controls only the read-miss seam; both reads and writes use the +// actual WALStore. No remote fill or manifest behavior is simulated here. +type heldWALReadMiss struct{ entered, release chan struct{} } + +func (h *heldWALReadMiss) OnReadMiss(uint64) ([]byte, error) { + close(h.entered) + <-h.release + return nil, nil +} +func (*heldWALReadMiss) OnExtentWrite(uint64, uint64) {} +func (*heldWALReadMiss) BeforeCheckpointAdvance(uint64) error { return nil } +func (*heldWALReadMiss) BeginBaseInstall() error { return nil } +func (*heldWALReadMiss) EndBaseInstall(uint64) error { return nil } + +func TestWALStore_PostReadMissRechecksWALFormat(t *testing.T) { + for _, version := range []string{"v2", "v3"} { + t.Run(version, func(t *testing.T) { + var s *WALStore + if version == "v3" { + s, _ = newStoreV3(t, WModeLagged) + } else { + var err error + s, err = CreateWALStore(filepath.Join(t.TempDir(), "store"), 16, v3TestBlock) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + } + t.Cleanup(func() { + if err := s.Close(); err != nil { + t.Error(err) + } + }) + h := &heldWALReadMiss{entered: make(chan struct{}), release: make(chan struct{})} + s.chunk.Store(&chunkHooks{sink: h, closer: func() error { return nil }}) + var once sync.Once + release := func() { once.Do(func() { close(h.release) }) } + type result struct { + data []byte + err error + } + done := make(chan result, 1) + joined := make(chan struct{}) + // Release and join before the store closes, including on an assertion failure. + t.Cleanup(func() { + release() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("read-miss worker failed to join") + } + }) + go func() { defer close(joined); data, err := s.Read(3); done <- result{data, err} }() + select { + case <-h.entered: + case <-time.After(5 * time.Second): + t.Fatal("read never reached OnReadMiss") + } + want := bytes.Repeat([]byte{0xB7}, v3TestBlock) + // The read has already missed the dirty map. Write while OnReadMiss is held. + if _, err := s.Write(3, want); err != nil { + t.Fatal(err) + } + release() + select { + case got := <-done: + if got.err != nil || !bytes.Equal(got.data, want) { + t.Fatalf("post-OnReadMiss WAL recheck returned stale or misdecoded bytes: len=%d err=%v", len(got.data), got.err) + } + case <-time.After(5 * time.Second): + t.Fatal("read did not finish after OnReadMiss release") + } + }) + } +} diff --git a/seaweed-block/core/storage/walstore_readonly.go b/seaweed-block/core/storage/walstore_readonly.go index e318b50c75..e699638bca 100644 --- a/seaweed-block/core/storage/walstore_readonly.go +++ b/seaweed-block/core/storage/walstore_readonly.go @@ -37,6 +37,7 @@ import ( // need them must use OpenWALStore + Recover. type WALStoreReader struct { metadata BlockMetadata + v3 *walStoreReaderV3 mu sync.Mutex fd *os.File @@ -63,6 +64,10 @@ func OpenReadOnly(path string) (*WALStoreReader, error) { } func OpenReadOnlyWithOptions(path string, opts WALStoreOptions) (*WALStoreReader, error) { + return openReadOnlyV3(path, opts) +} + +func openLegacyReadOnlyWithOptions(path string, opts WALStoreOptions) (*WALStoreReader, error) { f, err := os.OpenFile(path, os.O_RDONLY, 0) if err != nil { return nil, fmt.Errorf("storage: OpenReadOnly %s: %w", path, err) @@ -104,6 +109,10 @@ func (r *WALStoreReader) Read(lba uint32) ([]byte, error) { r.mu.Unlock() return nil, errors.New("storage: WALStoreReader.Read after Close") } + if r.v3 != nil { + defer r.mu.Unlock() + return r.readV3(lba) + } r.mu.Unlock() maxLBA := uint32(r.sb.VolumeSize / uint64(r.sb.BlockSize)) diff --git a/seaweed-block/core/storage/walstore_readonly_v3.go b/seaweed-block/core/storage/walstore_readonly_v3.go new file mode 100644 index 0000000000..ef5f4fe268 --- /dev/null +++ b/seaweed-block/core/storage/walstore_readonly_v3.go @@ -0,0 +1,224 @@ +package storage + +import ( + "bufio" + "bytes" + "encoding/binary" + "errors" + "fmt" + "math" + "os" + "strconv" + "strings" +) + +// ErrReadOnlyNotResident refuses an offline read that needs a remote lazy +// fill. A sparse local extent is not evidence that the logical block is ZERO. +var ErrReadOnlyNotResident = errors.New("storage: readonly image needs remote materialization") + +// readOnlyBlockV3 names one block of a trusted write or batch record. +type readOnlyBlockV3 struct { + record walScannedRecordV3 + index uint64 // block index inside a batch; 0 for a single write +} + +type walStoreReaderV3 struct { + descriptor descriptorV3 + records map[uint64]readOnlyBlockV3 // the WAL winner of each LBA above F + chunkBlocks uint64 + absent map[uint64]bool +} + +// The production readonly selector validates v3 slots and their dependencies. +// No worker, recovery fence, descriptor publication or writable fd is created. +func openReadOnlyV3(path string, opts WALStoreOptions) (_ *WALStoreReader, err error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + keep := false + defer func() { + if !keep { + _ = f.Close() + } + }() + if err := LockWALStoreFile(f); err != nil { + return nil, err + } + if err := refuseLegacyWALStore(f); err != nil { + return nil, err + } + accept := metadataSlotAcceptorV3(opts) + a, b := make([]byte, slotSizeV3), make([]byte, slotSizeV3) + if _, err = f.ReadAt(a, slotAOffsetV3); err != nil { + return nil, err + } + if _, err = f.ReadAt(b, slotBOffsetV3); err != nil { + return nil, err + } + d, id, err := selectSlotV3(a, b, accept) + if err != nil { + return nil, err + } + otherRaw := b + if id == slotB { + otherRaw = a + } + var fallback *descriptorV3 + if od, e := decodeSlotV3(otherRaw, accept); e == nil && od.MigrationPhase == MigrationNormal { + fallback = &od + } + cb, err := validateReadOnlyMapV3(path+".chunkmap", d, fallback) + if err != nil { + return nil, err + } + sb := superblock{Version: superblockVersionV3, UUID: d.UUID, VolumeSize: d.VolumeSize, ExtentSize: d.ExtentSize, BlockSize: d.BlockSize, WALOffset: d.WALOffset, WALSize: d.WALSize, WALHead: d.RetainedHead, WALTail: d.RetainedTail, WALCheckpointLSN: d.CheckpointLSN, CreatedAt: d.CreatedAt, ImplKind: d.ImplKind, ImplVersion: d.ImplVersion} + copy(sb.Magic[:], superblockMagic) + metadata, _, err := bindBlockMetadata(f, &sb, opts, false, true) + if err != nil { + return nil, err + } + scan, err := scanWALV3Accepted(f, d, accept) + if err != nil { + return nil, err + } + recs := make([]trustedRecordV3, 0, len(scan.Records)) + for _, r := range scan.Records { + last := r.Entry.LSN + if r.Entry.Type == walEntryWriteBatch { + last += r.Entry.BatchCount - 1 + } + recs = append(recs, trustedRecordV3{FirstLSN: r.Entry.LSN, LastLSN: last, End: r.End}) + } + outcome, err := decideRecoveryV3(d, recs, scan.MaxDurableLSN) + if err != nil { + return nil, err + } + if outcome.Installing { + return nil, installingErrorV3(outcome) + } + v := &walStoreReaderV3{descriptor: d, records: map[uint64]readOnlyBlockV3{}, chunkBlocks: cb, absent: map[uint64]bool{}} + for _, r := range scan.Records { + if r.Entry.LSN > outcome.R { + break + } + count := uint64(1) + switch r.Entry.Type { + case walEntryWrite: + case walEntryWriteBatch: + count = r.Entry.BatchCount // a trusted batch is <= R as a whole + default: + return nil, fmt.Errorf("%w: readonly v3 record type %#x", errV3NotYet, r.Entry.Type) + } + for i := uint64(0); i < count; i++ { + if r.Entry.LSN+i > outcome.F { + v.records[r.Entry.LBA+i] = readOnlyBlockV3{record: r, index: i} + } + } + } + if err = v.loadPresence(path); err != nil { + return nil, err + } + keep = true + return &WALStoreReader{fd: f, sb: &sb, metadata: metadata, v3: v}, nil +} + +func validateReadOnlyMapV3(path string, d descriptorV3, fallback *descriptorV3) (uint64, error) { + if d.MapRootLocator > math.MaxInt64-64 { + return 0, ErrMapInvalid + } + f, err := os.Open(path) + if err != nil { + return 0, err + } + defer f.Close() + var b [8]byte + if _, err = f.ReadAt(b[:], int64(d.MapRootLocator)+56); err != nil { + return 0, err + } + cb := binary.LittleEndian.Uint64(b[:]) + if _, _, err = readChunkLSNMapV3(f, d, cb); err != nil { + return 0, err + } + if fallback != nil { + if fallback.UUID != d.UUID || fallback.MapLineage != d.MapLineage || !sameGeometryV3(*fallback, d) { + return 0, ErrMapInvalid + } + if _, _, err = readChunkLSNMapV3(f, *fallback, cb); err != nil { + return 0, err + } + } + return cb, nil +} + +func (v *walStoreReaderV3) loadPresence(path string) error { + if _, err := os.Stat(path + ".chunkfresh"); err == nil { + return ErrReadOnlyNotResident + } else if !errors.Is(err, os.ErrNotExist) { + return err + } + data, err := os.ReadFile(path + ".chunkpresence") + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + scanner := bufio.NewScanner(bytes.NewReader(data)) + for scanner.Scan() { + kind, num, ok := strings.Cut(scanner.Text(), " ") + n, e := strconv.ParseUint(num, 10, 64) + blocks := v.descriptor.VolumeSize / uint64(v.descriptor.BlockSize) + if !ok || e != nil { + return fmt.Errorf("%w: malformed presence", ErrReadOnlyNotResident) + } + switch kind { + case "absent": + if n >= (blocks+v.chunkBlocks-1)/v.chunkBlocks { + return ErrReadOnlyNotResident + } + v.absent[n] = true + case "local": + if n >= blocks { + return ErrReadOnlyNotResident + } + default: + return ErrReadOnlyNotResident + } + } + return scanner.Err() +} + +// Caller holds the reader mutex, so Close cannot release this fd mid-read. +func (r *WALStoreReader) readV3(lba uint32) ([]byte, error) { + v := r.v3 + d := v.descriptor + if uint64(lba) >= d.VolumeSize/uint64(d.BlockSize) { + return nil, fmt.Errorf("storage: readonly LBA %d out of range", lba) + } + if b, ok := v.records[uint64(lba)]; ok { + record := b.record + off := record.Entry.LogicalStart % d.WALSize + e, _, ioErr, verr := readWholeRecordV3(r.fd, recordGeometryV3{d.WALOffset, d.WALSize, d.BlockSize, d.VolumeSize}, off) + if ioErr != nil { + return nil, ioErr + } + if verr != nil { + return nil, NewWALIntegrityFailure(verr, "readonly v3 WAL checksum/encoding") + } + if e.Nonce != d.Nonce || e.LogicalStart != record.Entry.LogicalStart || e.Type != record.Entry.Type { + return nil, NewWALIntegrityFailure(nil, "readonly v3 WAL binding changed") + } + data, err := blockOfRecordV3(e, uint64(lba), uint32(b.index)*d.BlockSize, record.Entry.LSN+b.index, d.BlockSize) + if err != nil { + return nil, NewWALIntegrityFailure(err, "readonly v3 WAL binding changed") + } + return data, nil + } + // A WAL winner is self-contained. Otherwise an absent chunk needs the + // daemon's remote-aware read path, even if a stale local hint names a block. + if v.absent[uint64(lba)/v.chunkBlocks] { + return nil, ErrReadOnlyNotResident + } + return r.readFromExtent(lba) +} diff --git a/seaweed-block/core/storage/walstore_readonly_v3_test.go b/seaweed-block/core/storage/walstore_readonly_v3_test.go new file mode 100644 index 0000000000..d56b391ff8 --- /dev/null +++ b/seaweed-block/core/storage/walstore_readonly_v3_test.go @@ -0,0 +1,240 @@ +package storage + +import ( + "bytes" + "errors" + "os" + "testing" +) + +func TestWALStoreV3_ReadOnlyMergesWALAndExtentWithoutWrites(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if _, err := s.Write(5, blk(0x55)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := s.Write(5, blk(0x77)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + mapBefore, err := os.ReadFile(path + ".chunkmap") + if err != nil { + t.Fatal(err) + } + reader, err := OpenReadOnlyWithOptions(path, WALStoreOptions{}) + if err != nil { + t.Fatalf("actual readonly v3 open refused: %v", err) + } + t.Cleanup(func() { _ = reader.Close() }) + for lba, want := range map[uint32][]byte{0: blk(0), 1: blk(1), 5: blk(0x77)} { + got, e := reader.Read(lba) + if e != nil || !bytes.Equal(got, want) { + t.Fatalf("readonly LBA%d err=%v equal=%v", lba, e, bytes.Equal(got, want)) + } + } + if _, err = reader.fd.WriteAt([]byte{0}, 0); err == nil { + t.Fatal("readonly descriptor allowed writes") + } + if err = reader.Close(); err != nil { + t.Fatal(err) + } + if err = reader.Close(); err != nil { + t.Fatal(err) + } + after, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + mapAfter, err := os.ReadFile(path + ".chunkmap") + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(before, after) || !bytes.Equal(mapBefore, mapAfter) { + t.Fatal("readonly open/read/close mutated store or map") + } +} + +func crashReadOnlyStoreV3(t *testing.T, s *WALStore) { + t.Helper() + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() +} +func TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies(t *testing.T) { + for _, fault := range []string{"installing", "acknowledged_wal", "missing_map", "fallback_page", "presence", "fresh"} { + t.Run(fault, func(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + if fault == "fallback_page" { + // Keep a genuinely referenced prior map in the fallback slot. + // Otherwise tail advance immediately rolls both slots forward. + s.SetRecoveryRetentionLSNs(1) + } + oldPage := s.v3.pub.mapCurrent.refs[0].Offset + writeSynced(t, s, 1, 1) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if _, err := s.Write(5, blk(5)); err != nil { + t.Fatal(err) + } + // Keep the pre-checkpoint root in the valid fallback slot. Another + // strict Sync would rotate that slot to the current map root. + if fault != "fallback_page" { + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + walOff, _, _, _, _ := s.dm.get(5) + if fault == "installing" { + beginV3(t, s, 2, idA) + } + crashReadOnlyStoreV3(t, s) + switch fault { + case "acknowledged_wal": + f, e := os.OpenFile(path, os.O_RDWR, 0) + if e != nil { + t.Fatal(e) + } + _, e = f.WriteAt([]byte{0xff}, int64(walOffsetV3+walOff+walEntryPrefixSizeV3)) + ce := f.Close() + if e != nil || ce != nil { + t.Fatal(e, ce) + } + case "missing_map": + if e := os.Rename(path+".chunkmap", path+".saved-map"); e != nil { + t.Fatal(e) + } + case "fallback_page": + f, e := os.OpenFile(path+".chunkmap", os.O_RDWR, 0) + if e != nil { + t.Fatal(e) + } + _, e = f.WriteAt([]byte{0xff}, int64(oldPage)+64) + ce := f.Close() + if e != nil || ce != nil { + t.Fatal(e, ce) + } + case "presence": + if e := os.WriteFile(path+".chunkpresence", []byte("absent nope\n"), 0600); e != nil { + t.Fatal(e) + } + case "fresh": + if e := os.WriteFile(path+".chunkfresh", []byte("fresh\n"), 0600); e != nil { + t.Fatal(e) + } + } + before, e := os.ReadFile(path) + if e != nil { + t.Fatal(e) + } + reader, e := OpenReadOnlyWithOptions(path, WALStoreOptions{}) + if reader != nil { + _ = reader.Close() + t.Error("refused readonly returned a reader") + } + if e == nil { + t.Fatal("readonly accepted unsafe " + fault) + } + if fault == "installing" && !errors.Is(e, ErrBaseIncomplete) { + t.Errorf("installing error=%v", e) + } + if fault == "acknowledged_wal" && !errors.Is(e, ErrWALIntegrityFault) { + t.Errorf("corrupt ACK error=%v", e) + } + if fault == "fallback_page" && !errors.Is(e, ErrMapInvalid) { + t.Errorf("fallback map error=%v", e) + } + after, e := os.ReadFile(path) + if e != nil || !bytes.Equal(before, after) { + t.Fatal("failed readonly mutated store", e) + } + }) + } +} +func TestWALStoreV3_ReadOnlyNeverReturnsUnfilledExtentZeros(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 5, 5) + crashReadOnlyStoreV3(t, s) + if e := os.WriteFile(path+".chunkpresence", []byte("absent 1\nlocal 4\n"), 0600); e != nil { + t.Fatal(e) + } + r, e := OpenReadOnlyWithOptions(path, WALStoreOptions{}) + if e != nil { + t.Fatal(e) + } + t.Cleanup(func() { _ = r.Close() }) + if got, e := r.Read(5); e != nil || !bytes.Equal(got, blk(5)) { + t.Fatal("trusted WAL winner not readable", e) + } + if data, e := r.Read(4); !errors.Is(e, ErrReadOnlyNotResident) || data != nil { + t.Fatalf("unfilled extent returned bytes=%d error=%v", len(data), e) + } +} +func TestWALStoreV3_ReadOnlyRevalidatesWALAndBindsReadonlyMetadata(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + if e := s.flusher.flushOnce(); e != nil { + t.Fatal(e) + } + if _, e := s.Write(5, blk(5)); e != nil { + t.Fatal(e) + } + if _, e := s.Sync(); e != nil { + t.Fatal(e) + } + walOff, _, _, _, _ := s.dm.get(5) + crashReadOnlyStoreV3(t, s) + h := &recordingMetadata{} + opts := WALStoreOptions{MetadataFactory: func(f BlockMetadataFile, l BlockMetadataLayout) (BlockMetadataBinding, error) { + if !l.ReadOnly || l.Creating || l.ImplVersion != 3 { + t.Errorf("wrong readonly metadata layout: %+v", l) + } + h.file = f + return BlockMetadataBinding{ImplVersion: 3, Hook: h}, nil + }} + r, e := OpenReadOnlyWithOptions(path, opts) + if e != nil { + t.Fatal(e) + } + t.Cleanup(func() { _ = r.Close() }) + if _, e = r.Read(1); e != nil || h.reads != 1 || h.writes != 0 || h.barriers != 0 { + t.Fatalf("readonly metadata reads/writes/barriers=%d/%d/%d err=%v", h.reads, h.writes, h.barriers, e) + } + if _, e = h.file.WriteAt([]byte{0}, 0); e == nil { + t.Fatal("metadata factory obtained writable fd") + } + f, e := os.OpenFile(path, os.O_RDWR, 0) + if e != nil { + t.Fatal(e) + } + _, e = f.WriteAt([]byte{0xff}, int64(walOffsetV3+walOff+walEntryPrefixSizeV3)) + ce := f.Close() + if e != nil || ce != nil { + t.Fatal(e, ce) + } + if data, e := r.Read(5); e == nil || data != nil { + t.Fatalf("changed WAL returned bytes=%d err=%v", len(data), e) + } else { + var failure *RecoveryFailure + if !errors.As(e, &failure) || failure.Kind != StorageRecoveryFailureWALIntegrity { + t.Fatalf("wrong integrity classification: %v", e) + } + } +} diff --git a/seaweed-block/core/storage/walstore_reclaim_v3_test.go b/seaweed-block/core/storage/walstore_reclaim_v3_test.go new file mode 100644 index 0000000000..345ef81f1a --- /dev/null +++ b/seaweed-block/core/storage/walstore_reclaim_v3_test.go @@ -0,0 +1,313 @@ +package storage + +import ( + "bytes" + "errors" + "path/filepath" + "testing" +) + +func TestWALStoreV3CheckpointReclaimsAcrossRingLaps(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, 16, 4096, 64*1024, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + for i := 1; i <= 40; i++ { + if _, err := s.Write(0, blk(byte(i))); err != nil { + t.Fatalf("cycle %d after prior synced checkpoints: %v", i, err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + } + if floor, valid := s.v3.pub.reuseFloor(); !valid || floor <= 64*1024 { + t.Fatalf("both-slot reuse floor did not cross a ring lap: floor=%d valid=%v", floor, valid) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + defer r.Close() + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if got, err := r.Read(0); err != nil || !bytes.Equal(got, blk(40)) { + t.Fatalf("latest acknowledged bytes after ring reuse/reopen: %v", err) + } +} + +func TestWALStoreV3ReclaimKeepsPartialBatchAndRetention(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + if _, err := s.WriteBatch(0, [][]byte{blk(1), blk(2)}); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 1, anyActive: true}) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if d := s.v3.pub.current(); d.CheckpointLSN != 1 || d.RetainedTail != 0 { + t.Fatalf("partial batch released before checkpoint covered its last LSN: %+v", d) + } + s.SetRecycleFloorSource(nil) + s.SetRecoveryRetentionLSNs(1) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if d := s.v3.pub.current(); d.CheckpointLSN != 2 || d.RetainedTail != 0 { + t.Fatalf("retention split and released a retained batch: %+v", d) + } + var got []RecoveryEntry + if err := s.ScanLBAs(2, func(e RecoveryEntry) error { got = append(got, e); return nil }); err != nil || len(got) != 1 || !bytes.Equal(got[0].Data, blk(2)) { + t.Fatalf("retained batch suffix is not available to catch-up: entries=%d err=%v", len(got), err) + } + s.SetRecoveryRetentionLSNs(0) + if _, err := s.Write(3, blk(3)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + if floor, ok := s.v3.pub.reuseFloor(); !ok || floor != d.RetainedTail || floor == 0 { + t.Fatalf("idle post-flush fallback still pins the released prefix: %d %v", floor, ok) + } +} + +func TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 0, 1) + writeSynced(t, s, 1, 2) + crashReadOnlyStoreV3(t, s) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = r.Close() }) + r.DisableAutoFlushForRecoveryTest() + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if err := r.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + d := r.v3.pub.current() + if floor, ok := r.v3.pub.reuseFloor(); !ok || floor == 0 || floor != d.RetainedTail { + t.Fatalf("physical recovery did not restore reclaimable record boundaries: %d %v", floor, ok) + } +} + +func TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 0, 1) + writeSlot := s.v3.pub.io.writeSlot + writes := 0 + s.v3.pub.io.writeSlot = func(off int64, data []byte) error { + writes++ + if writes == 2 { + return errors.New("held fallback rollover write failed") + } + return writeSlot(off, data) + } + before := s.dm.snapshot() + if err := s.flusher.flushOnce(); !errors.Is(err, ErrDescriptorPublishUncertain) || writes != 2 { + t.Fatalf("rollover failure was not surfaced: writes=%d err=%v", writes, err) + } + after := s.dm.snapshot() + if len(before) == 0 || len(after) != len(before) { + t.Fatalf("failed rollover changed dirty retry count: before=%+v after=%+v", before, after) + } + for _, e := range before { + off, dataOff, lsn, length, ok := s.dm.get(e.LBA) + if !ok || off != e.WALOffset || dataOff != e.DataOffset || lsn != e.LSN || length != e.Length { + t.Fatalf("failed rollover changed retry identity for %+v", e) + } + } + if floor, valid := s.v3.pub.reuseFloor(); valid && floor != 0 { + t.Fatalf("failed rollover granted reuse over the old slot: floor=%d", floor) + } + head := s.v3.w.logicalHeadV3() + if _, err := s.Write(1, blk(2)); err == nil || s.v3.w.logicalHeadV3() != head { + t.Fatalf("failed rollover allowed another append: %v", err) + } + crashReadOnlyStoreV3(t, s) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + defer r.Close() + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + if got, err := r.Read(1); err != nil || !bytes.Equal(got, blk(1)) { + t.Fatalf("acknowledged bytes lost at the fallback failure window: %v", err) + } +} + +func TestWALStoreV3ReclaimAfterInstallingPhysicalReopen(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + h, err := s.BeginBaseInstall(0, idA) + if err != nil { + t.Fatal(err) + } + for i := uint64(1); i <= 3; i++ { + if err := h.ApplyInstallEntry(uint32(i), blk(byte(i)), i); err != nil { + t.Fatal(err) + } + } + if _, err := s.SyncInstallLog(idA); err != nil { + t.Fatal(err) + } + crashReadOnlyStoreV3(t, s) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = r.Close() }) + r.DisableAutoFlushForRecoveryTest() + initialHead := r.v3.w.logicalHeadV3() + if _, err := r.Recover(); !errors.Is(err, ErrBaseIncomplete) { + t.Fatalf("installing reopen: %v", err) + } + if r.v3.w.logicalHeadV3() != initialHead { + t.Fatal("reclaim bookkeeping changed the not-yet-resumed writer cursor") + } + h, err = r.resumeBaseInstallV3(idA) + if err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + if _, err := r.Sync(); err != nil { + t.Fatal(err) + } + if err := r.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if floor, ok := r.v3.pub.reuseFloor(); !ok || floor == 0 { + t.Fatalf("completed recovered install suffix cannot be reclaimed: floor=%d valid=%v", floor, ok) + } + if got, err := r.Read(3); err != nil || !bytes.Equal(got, blk(3)) { + t.Fatalf("recovered install bytes: %v", err) + } +} + +// Hold the actual flusher after its durable publication, before its outer +// cleanup, then make the writer reuse the old dirty entry's physical slot. +func TestWALStoreV3ReclaimRetiresReferencesBeforeReuse(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, 32, 4096, 64*1024, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + for i := uint32(0); i < 15; i++ { + if _, err := s.Write(i, blk(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.flusher.afterCheckpointForTest = func() { + s.flusher.afterCheckpointForTest = nil + if _, err := s.Write(15, blk(16)); err != nil { + t.Fatal(err) + } + if got, err := s.Read(0); err != nil || !bytes.Equal(got, blk(1)) { + t.Fatalf("durable old extent must remain readable during physical WAL reuse: %v", err) + } + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if got, err := s.Read(15); err != nil || !bytes.Equal(got, blk(16)) { + t.Fatalf("new dirty version was not preserved: %v", err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashReadOnlyStoreV3(t, s) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + defer r.Close() + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + for lba, want := range map[uint32][]byte{0: blk(1), 15: blk(16)} { + if got, err := r.Read(lba); err != nil || !bytes.Equal(got, want) { + t.Fatalf("post-reuse crash-style reopen LBA%d: %v", lba, err) + } + } +} + +func TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint(t *testing.T) { + for _, trigger := range []string{"idle", "unchanged-checkpoint", "admission", "batch-admission"} { + t.Run(trigger, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(2) + writeSynced(t, s, 0, 1) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + s.SetRecoveryRetentionLSNs(1) + tail := s.v3.w.reclaimThroughV3(d.CheckpointLSN - 1) + // Model a completed first-slot checkpoint publication before its idle + // fallback rollover, with already-durable map/checkpoint and extent. + if _, err := s.v3.pub.publish(nil, nil, func(n *descriptorV3) error { + n.RetainedTail = tail + n.RetainedHead = max(n.RetainedHead, tail) + return nil + }); err != nil { + t.Fatal(err) + } + if floor, ok := s.v3.pub.reuseFloor(); !ok || floor >= tail { + t.Fatal("setup lacks a pinned fallback") + } + switch trigger { + case "idle": + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + case "unchanged-checkpoint": + if err := s.persistOwnedMapCheckpointV3(d.CheckpointLSN, s.v3.recoverGen.Load()); err != nil { + t.Fatal(err) + } + case "batch-admission": + if _, err := s.WriteBatch(2, [][]byte{blk(3), blk(4)}); err != nil { + t.Fatal(err) + } + case "admission": + if _, err := s.Write(2, blk(3)); err != nil { + t.Fatal(err) + } + } + if floor, ok := s.v3.pub.reuseFloor(); !ok || floor != tail { + t.Fatalf("%s did not settle old-slot pin without a new checkpoint: floor=%d want=%d valid=%v", trigger, floor, tail, ok) + } + if got := s.v3.pub.current().CheckpointLSN; got != d.CheckpointLSN { + t.Fatalf("trigger fabricated checkpoint progress: %d", got) + } + }) + } +} diff --git a/seaweed-block/core/storage/walstore_recovery.go b/seaweed-block/core/storage/walstore_recovery.go index 29f01664f6..4863ddf316 100644 --- a/seaweed-block/core/storage/walstore_recovery.go +++ b/seaweed-block/core/storage/walstore_recovery.go @@ -48,6 +48,10 @@ func (s *WALStore) ScanLBAs(fromLSN uint64, fn func(RecoveryEntry) error) error headLSN := s.nextLSN retentionLSNs := s.recoveryRetentionLSNs s.mu.RUnlock() + if s.v3 != nil { + // The v3 source-state gate must precede even an empty scan. + return s.scanLBAsV3(fromLSN, fn) + } // Retention gate: by default the recycle threshold is // checkpointLSN; an operator-tunable retention window lets a @@ -249,3 +253,140 @@ func (s *WALStore) WALCapacityBytes() uint64 { func (s *WALStore) CheckpointLSNForPOC() uint64 { return s.CheckpointLSN() } + +// scanLBAsV3 is ScanLBAs on a v3 store (the primary's catch-up source). +// It is all or nothing (codex01 4caac700 P1s): it captures the recovery +// generation, the descriptor and the head, refuses an installing source +// (ErrBaseInstalling) before emitting anything, scans the trusted v3 chain +// into memory, revalidates the capture (a Recover, reset or BASE transition +// meanwhile retries the whole scan, or refuses if the source is now +// installing), and requires the trusted records to cover every LSN of +// [fromLSN, head): a chain that stops short (the scanner's CRC, binding or +// truncation stop cause) is a typed WAL integrity failure, and a WAL that +// no longer holds fromLSN a typed WALRecycled failure. Only then are the +// entries emitted, from memory, with no store lock held across the +// callbacks. A write record is one entry; a batch one entry per block. +func (s *WALStore) scanLBAsV3(fromLSN uint64, fn func(RecoveryEntry) error) error { + v := s.v3 + const attempts = 8 + for attempt := 0; attempt < attempts; attempt++ { + s.mu.RLock() + gen := v.recoverGen.Load() + installEpoch := v.installEpoch + d := v.pub.current() + headLSN := s.nextLSN + checkpointLSN, retentionLSNs := d.CheckpointLSN, s.recoveryRetentionLSNs + s.mu.RUnlock() + if d.BaseState == BaseInstalling { + return fmt.Errorf("%w: catch-up from an installing source", ErrBaseInstalling) + } + if gen%2 != 0 { + continue // a recovery or reset is running; capture again + } + // A completed BASE authoritatively replaces its prefix; those LSNs + // need a rebuild even if unused ring bytes stop on nonce binding. + // Do not downgrade damage in the retained suffix after BaseLSN. + if d.BaseState == BaseInstalled && fromLSN <= d.BaseLSN { + return NewWALRecycledFailure(ErrWALRecycled, fmt.Sprintf( + "fromLSN=%d is covered by installed BaseLSN=%d", fromLSN, d.BaseLSN)) + } + floor := uint64(0) + if checkpointLSN > retentionLSNs { + floor = checkpointLSN - retentionLSNs + } + if checkpointLSN > 0 && fromLSN <= floor { + return NewWALRecycledFailure(ErrWALRecycled, fmt.Sprintf( + "fromLSN=%d checkpointLSN=%d headLSN=%d retentionLSNs=%d floor=%d", + fromLSN, checkpointLSN, headLSN, retentionLSNs, floor)) + } + if fromLSN >= headLSN { + return nil + } + if h := v.testScanBeforeRead; h != nil { + h() + } + scan, err := scanWALV3Accepted(s.fd, d, v.pub.accept) + if err != nil { + return fmt.Errorf("storage: walstore ScanLBAs (v3): %w", err) + } + if h := v.testScanRead; h != nil { + h() + } + s.mu.RLock() + now := v.pub.current() + stable := v.recoverGen.Load() == gen && v.installEpoch == installEpoch && + now.Nonce == d.Nonce && now.BaseState == d.BaseState && + now.BaseInstallID == d.BaseInstallID && now.BaseCursor == d.BaseCursor && + now.RetainedTail == d.RetainedTail && now.CheckpointLSN == d.CheckpointLSN && + s.recoveryRetentionLSNs == retentionLSNs + s.mu.RUnlock() + if !stable { + if now.BaseState == BaseInstalling { + return fmt.Errorf("%w: catch-up source began installing", ErrBaseInstalling) + } + continue // a transition ran meanwhile: scan again from a fresh capture + } + entries, err := v3CatchUpEntries(scan, d, fromLSN, headLSN) + if err != nil { + return err + } + for _, e := range entries { + if err := fn(e); err != nil { + return err + } + } + return nil + } + return fmt.Errorf("storage: walstore ScanLBAs (v3) did not get a stable capture in %d attempts", attempts) +} + +// v3CatchUpEntries cuts [fromLSN, headLSN) out of a trusted scan, or fails: +// WALRecycled when the chain starts after fromLSN, WAL integrity (with the +// scanner's stop cause) when it ends before headLSN. +func v3CatchUpEntries(scan walScanResultV3, d descriptorV3, fromLSN, headLSN uint64) ([]RecoveryEntry, error) { + blockSize := uint64(d.BlockSize) + next := fromLSN + var out []RecoveryEntry + for _, r := range scan.Records { + if next >= headLSN { + break + } + e := r.Entry + count := uint64(1) + switch e.Type { + case walEntryWrite: + case walEntryWriteBatch: + count = e.BatchCount + default: + continue // padding + } + if e.LSN+count-1 < next { + continue + } + if e.LSN > next { + if next == fromLSN { + return nil, NewWALRecycledFailure(ErrWALRecycled, fmt.Sprintf( + "v3 WAL starts at LSN %d, after the requested %d (head %d)", e.LSN, fromLSN, headLSN)) + } + return nil, NewWALIntegrityFailure(nil, fmt.Sprintf("v3 catch-up: LSN %d missing before %d", next, e.LSN)) + } + for i := uint64(0); i < count; i++ { + lsn := e.LSN + i + if lsn < next || lsn >= headLSN { + continue + } + out = append(out, RecoveryEntry{LSN: lsn, LBA: uint32(e.LBA + i), Flags: RecoveryEntryWrite, + Data: e.Data[i*blockSize : (i+1)*blockSize]}) + next = lsn + 1 + } + } + if next < headLSN { + if next == fromLSN && len(out) == 0 && scan.StopCause == nil { + return nil, NewWALRecycledFailure(ErrWALRecycled, fmt.Sprintf( + "v3 WAL holds no record at LSN %d (head %d)", fromLSN, headLSN)) + } + return nil, NewWALIntegrityFailure(scan.StopCause, fmt.Sprintf( + "v3 catch-up stopped at LSN %d, short of the captured head %d", next, headLSN)) + } + return out, nil +} diff --git a/seaweed-block/core/storage/walstore_recovery_frontier_gap_test.go b/seaweed-block/core/storage/walstore_recovery_frontier_gap_test.go index 7740289100..af72edc020 100644 --- a/seaweed-block/core/storage/walstore_recovery_frontier_gap_test.go +++ b/seaweed-block/core/storage/walstore_recovery_frontier_gap_test.go @@ -17,7 +17,7 @@ import ( func TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump(t *testing.T) { const blockSize = 4096 path := filepath.Join(t.TempDir(), "store.bin") - s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024) + s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024) s.DisableAutoFlushForRecoveryTest() crashed := false t.Cleanup(func() { @@ -47,7 +47,7 @@ func TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump(t *test if sb := diskSuperblockForGapTest(t, path); sb.WALCheckpointLSN != 0 { t.Fatalf("persisted checkpoint %d; want 0 (the frontier jump is not persisted)", sb.WALCheckpointLSN) } - r, err := OpenWALStore(path) + r, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/walstore_recovery_hardening_test.go b/seaweed-block/core/storage/walstore_recovery_hardening_test.go index 1064e2d1ce..0d70159a0d 100644 --- a/seaweed-block/core/storage/walstore_recovery_hardening_test.go +++ b/seaweed-block/core/storage/walstore_recovery_hardening_test.go @@ -12,7 +12,7 @@ import ( func TestWALStoreRecoverRetainsMultiBlockSuffixAcrossRestart(t *testing.T) { const blockSize = 4096 path := filepath.Join(t.TempDir(), "store.bin") - s, err := CreateWALStore(path, 32, blockSize) + s, err := createLegacyWALStoreForTest(path, 32, blockSize) if err != nil { t.Fatal(err) } @@ -55,7 +55,7 @@ func TestWALStoreRecoverRetainsMultiBlockSuffixAcrossRestart(t *testing.T) { } crashRecoveryHardeningStore(t, s) - reopened, err := OpenWALStore(path) + reopened, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -126,7 +126,7 @@ func TestWALStoreRecoverRejectsOverflowingBatchGeometry(t *testing.T) { blocks = 3 ) path := filepath.Join(t.TempDir(), "store.bin") - s, err := CreateWALStore(path, 16, blockSize) + s, err := createLegacyWALStoreForTest(path, 16, blockSize) if err != nil { t.Fatal(err) } @@ -149,7 +149,7 @@ func TestWALStoreRecoverRejectsOverflowingBatchGeometry(t *testing.T) { ) crashRecoveryHardeningStore(t, s) - reopened, err := OpenWALStore(path) + reopened, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -176,7 +176,7 @@ func TestWALStoreRecoverReconstructsLegacyWrappedRetainedWindow(t *testing.T) { lowRecordSize = uint64(walEntryHeaderSize + 2*blockSize) ) path := filepath.Join(t.TempDir(), "store.bin") - s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize) + s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize) s.DisableAutoFlushForRecoveryTest() for lba := uint32(0); lba < 3; lba++ { if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil { @@ -228,7 +228,7 @@ func TestWALStoreRecoverReconstructsLegacyWrappedRetainedWindow(t *testing.T) { } crashRecoveryHardeningStore(t, s) - reopened, err := OpenWALStore(path) + reopened, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -283,6 +283,12 @@ func TestWALStoreRecoverReconstructsLegacyWrappedRetainedWindow(t *testing.T) { func crashRecoveryHardeningStore(t *testing.T, s *WALStore) { t.Helper() s.committer.Stop() + if s.v3 != nil && s.v3.ownedMap != nil { + if err := s.v3.ownedMap.Close(); err != nil { + t.Fatal(err) + } + s.v3.ownedMap = nil + } if err := s.fd.Close(); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/walstore_recovery_lww_test.go b/seaweed-block/core/storage/walstore_recovery_lww_test.go index f51c985cc3..fa41e928e2 100644 --- a/seaweed-block/core/storage/walstore_recovery_lww_test.go +++ b/seaweed-block/core/storage/walstore_recovery_lww_test.go @@ -16,7 +16,7 @@ func TestWALStoreRecoverLastWriterWinsAcrossScanOrder(t *testing.T) { walSize = 24 * 1024 ) path := filepath.Join(t.TempDir(), "store.bin") - s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize) + s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize) s.DisableAutoFlushForRecoveryTest() for lba := uint32(0); lba < 3; lba++ { if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil { @@ -45,7 +45,7 @@ func TestWALStoreRecoverLastWriterWinsAcrossScanOrder(t *testing.T) { t.Fatalf("newest LBA 20 entry at offset %d LSN %d; want the wrapped batch at 0, LSN 5", e.WALOffset, e.LSN) } crashRecoveryHardeningStore(t, s) - r, err := OpenWALStore(path) + r, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/walstore_recovery_test.go b/seaweed-block/core/storage/walstore_recovery_test.go index 5d70171d6f..3f30633e4f 100644 --- a/seaweed-block/core/storage/walstore_recovery_test.go +++ b/seaweed-block/core/storage/walstore_recovery_test.go @@ -245,7 +245,11 @@ func TestWalstoreRecovery_AllBlocks_DeterministicOrdering(t *testing.T) { t.Fatalf("Sync: %v", err) } - got := s.AllBlocks() + got, snapshotErr := s.AllBlocks() + + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(got) != len(expected) { t.Fatalf("AllBlocks size: got %d want %d", len(got), len(expected)) } @@ -418,7 +422,10 @@ func TestWalstoreRecovery_Sanity_ExistingAPIsUnchanged(t *testing.T) { if got[0] != 0x42 { t.Fatalf("Read[0]=%02x want 42", got[0]) } - all := s.AllBlocks() + all, snapshotErr := s.AllBlocks() + if snapshotErr != nil { + t.Fatal(snapshotErr) + } if len(all) != 1 { t.Fatalf("AllBlocks: got %d want 1", len(all)) } diff --git a/seaweed-block/core/storage/walstore_retention_test.go b/seaweed-block/core/storage/walstore_retention_test.go index 3e496b0e34..51960def7b 100644 --- a/seaweed-block/core/storage/walstore_retention_test.go +++ b/seaweed-block/core/storage/walstore_retention_test.go @@ -28,7 +28,7 @@ func freshWALStore(t *testing.T) *WALStore { t.Helper() dir := t.TempDir() path := filepath.Join(dir, "v.bin") - ws, err := CreateWALStore(path, 64, 4096) + ws, err := createLegacyWALStoreForTest(path, 64, 4096) if err != nil { t.Fatalf("CreateWALStore: %v", err) } diff --git a/seaweed-block/core/storage/walstore_sticky_fsync_test.go b/seaweed-block/core/storage/walstore_sticky_fsync_test.go index 4ce832851b..00b0234a1c 100644 --- a/seaweed-block/core/storage/walstore_sticky_fsync_test.go +++ b/seaweed-block/core/storage/walstore_sticky_fsync_test.go @@ -28,7 +28,7 @@ func assertStickyFsync(t *testing.T, err error) { func stickyStore(t *testing.T) (*WALStore, string) { t.Helper() path := filepath.Join(t.TempDir(), "store.bin") - s := createWALStoreWithWALSizeForTest(t, path, 64, 4096, 64*1024) + s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, 4096, 64*1024) s.DisableAutoFlushForRecoveryTest() if _, err := s.Write(0, makeBlock(4096, 0x10)); err != nil { // acked before the fault t.Fatal(err) @@ -63,7 +63,7 @@ func assertRefusesAfterFault(t *testing.T, s *WALStore, path string) { t.Fatalf("the flusher advanced the checkpoint %d -> %d after an fsync failure", ckpt, got) } _ = s.Close() - r, err := OpenWALStore(path) + r, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/walstore_sticky_race_test.go b/seaweed-block/core/storage/walstore_sticky_race_test.go index 62a302055d..11c89f09d1 100644 --- a/seaweed-block/core/storage/walstore_sticky_race_test.go +++ b/seaweed-block/core/storage/walstore_sticky_race_test.go @@ -117,7 +117,7 @@ func startWorker(t workerTB, fn func() error, gates ...*gate) <-chan error { func heldStore(t *testing.T) (*WALStore, string) { t.Helper() path := filepath.Join(t.TempDir(), "store.bin") - s := createWALStoreWithWALSizeForTest(t, path, 64, 4096, 64*1024) + s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, 4096, 64*1024) s.DisableAutoFlushForRecoveryTest() t.Cleanup(func() { // runs after the workers' and gates' cleanups (LIFO) if _, leaked := leakedStores.LoadAndDelete(t); leaked { diff --git a/seaweed-block/core/storage/walstore_sync_frontier_order_test.go b/seaweed-block/core/storage/walstore_sync_frontier_order_test.go index 2145b46ce9..99803d6e9e 100644 --- a/seaweed-block/core/storage/walstore_sync_frontier_order_test.go +++ b/seaweed-block/core/storage/walstore_sync_frontier_order_test.go @@ -13,7 +13,7 @@ import ( func TestWALGenerationFirstCallerReturnOrdering(t *testing.T) { for _, laterPublishesFirst := range []bool{false, true} { t.Run(fmt.Sprintf("later_publishes_first=%v", laterPublishesFirst), func(t *testing.T) { - s := newGenerationStore(t) + s := newLegacyGenerationStore(t) firstEntered, secondEntered, firstCacheReturned := make(chan struct{}), make(chan struct{}), make(chan struct{}) releaseFirst, releaseSecond, publishFirst := make(chan struct{}), make(chan struct{}), make(chan struct{}) var workers sync.WaitGroup diff --git a/seaweed-block/core/storage/walstore_sync_generation_test.go b/seaweed-block/core/storage/walstore_sync_generation_test.go index 25756f7de3..083a7ae694 100644 --- a/seaweed-block/core/storage/walstore_sync_generation_test.go +++ b/seaweed-block/core/storage/walstore_sync_generation_test.go @@ -12,7 +12,9 @@ import ( func newGenerationStore(t *testing.T) *WALStore { t.Helper() - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 32, 4096) + // This control holds the standalone WAL fsync seam. Mode A retains + // that phase; mode C combines WAL durability with descriptor publication. + s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "store.bin"), 32, 4096, WALStoreOptions{WMode: WModeStrict}) if err != nil { t.Fatal(err) } @@ -179,7 +181,7 @@ func TestWALGenerationSyncFailureAndShutdown(t *testing.T) { func TestWALGenerationBypassesUntrackedMutationPaths(t *testing.T) { for _, kind := range []string{"old LSN apply", "direct extent", "direct frontier", "chunk layer"} { t.Run(kind, func(t *testing.T) { - s := newGenerationStore(t) + s := newLegacyGenerationStore(t) if _, err := s.Write(0, makeBlock(4096, 0x81)); err != nil { t.Fatal(err) } @@ -246,7 +248,7 @@ func TestWALGenerationPartialAppendRecoverySync(t *testing.T) { for _, recoverFirst := range []bool{false, true} { t.Run(map[bool]string{false: "failed append without recovery", true: "same-open recovery"}[recoverFirst], func(t *testing.T) { path := filepath.Join(t.TempDir(), "store.bin") - s := createWALStoreWithWALSizeForTest(t, path, 64, 4096, 1<<20) + s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, 4096, 1<<20) s.DisableAutoFlushForRecoveryTest() if _, err := s.Sync(); err != nil { t.Fatal(err) @@ -292,7 +294,7 @@ func TestWALGenerationPartialAppendRecoverySync(t *testing.T) { // A reopen may republish the failed batch's complete prefix (it // was never acknowledged) and serves normally again. - r, err := OpenWALStore(path) + r, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -358,3 +360,17 @@ func TestWALGenerationSameOpenRecoverInvalidatesCoverage(t *testing.T) { t.Fatalf("Recover permanently disabled dedup: syncs=%d want1", n) } } + +// TODO(format-v3 row 14a): v2 callback-cache / direct-mutation controls only. +func newLegacyGenerationStore(t *testing.T) *WALStore { + t.Helper() + // This control holds the standalone WAL fsync seam. Mode A retains + // that phase; mode C combines WAL durability with descriptor publication. + s, err := createLegacyWALStoreWithOptions(filepath.Join(t.TempDir(), "store.bin"), 32, 4096, WALStoreOptions{WMode: WModeStrict}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + return s +} diff --git a/seaweed-block/core/storage/walstore_test.go b/seaweed-block/core/storage/walstore_test.go index cf72f5a04b..cd535f2746 100644 --- a/seaweed-block/core/storage/walstore_test.go +++ b/seaweed-block/core/storage/walstore_test.go @@ -5,12 +5,13 @@ import ( "errors" "os" "path/filepath" + "sync" "testing" ) func TestWALStore_FailedAppendDoesNotConsumeLSN(t *testing.T) { path := filepath.Join(t.TempDir(), "store.bin") - s, err := CreateWALStore(path, 16, 4096) + s, err := createLegacyWALStoreForTest(path, 16, 4096) if err != nil { t.Fatal(err) } @@ -47,7 +48,7 @@ func TestWALStore_FailedAppendDoesNotConsumeLSN(t *testing.T) { // A reopen starts from what is on disk (nothing of the failed append): // the first write gets LSN 1, the next batch LSNs 2 and 3. - r, err := OpenWALStore(path) + r, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -112,7 +113,7 @@ func TestWALStore_SyncDoesNotClaimConcurrentWrite(t *testing.T) { func TestWALStore_DirectFrontierMetadataFailureRetainsRetryState(t *testing.T) { path := filepath.Join(t.TempDir(), "store.bin") - s, err := CreateWALStore(path, 16, 4096) + s, err := createLegacyWALStoreForTest(path, 16, 4096) if err != nil { t.Fatal(err) } @@ -151,7 +152,7 @@ func TestWALStore_DirectFrontierMetadataFailureRetainsRetryState(t *testing.T) { t.Fatalf("refused retry published checkpoint %d", s.checkpointLSN) } _ = s.Close() - reopened, err := OpenWALStore(path) + reopened, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -181,7 +182,7 @@ func TestWALStore_DirectFrontierMetadataFailureRetainsRetryState(t *testing.T) { reopened.committer.Stop() _ = reopened.fd.Close() // crash reopenedOpen = false - again, err := OpenWALStore(path) + again, err := openLegacyWALStoreForTest(path) if err != nil { t.Fatal(err) } @@ -417,7 +418,7 @@ func TestWALStore_WriteBatchCopiesCallerBuffersIntoWALRecords(t *testing.T) { // 1. Write blocks 0,1,2 + Sync (acked, must survive) // 2. Write blocks 3,4 (NOT followed by Sync — may or may not survive) // 3. Bypass Close — drop the file handle without finalizing -// anything (no superblock update, no fsync, no group-committer drain) +// anything (no superblock update, no fsync, no new commit batch) // 4. Reopen + Recover // 5. Acked blocks 0,1,2 MUST be present and intact // 6. Post-Sync blocks 3,4 may be present OR absent — never corrupt @@ -432,6 +433,20 @@ func TestWALStore_AckedWritesSurviveSimulatedCrash(t *testing.T) { if err != nil { t.Fatal(err) } + // A simulated process crash cannot leave an old flusher using the + // descriptor. Stop it BEFORE writes: stopping after them could flush + // the very WAL replay this test is intended to exercise. + crash := sync.OnceFunc(func() { + s.DisableAutoFlushForRecoveryTest() + crashRecoveryHardeningStore(t, s) + }) + t.Cleanup(crash) + s.DisableAutoFlushForRecoveryTest() + select { + case <-s.flusher.doneCh: + default: + t.Fatal("crash fixture flusher is still running before writes") + } for i := uint32(0); i < 3; i++ { if _, err := s.Write(i, makeBlock(4096, byte(0xA0+i))); err != nil { t.Fatal(err) @@ -441,18 +456,18 @@ func TestWALStore_AckedWritesSurviveSimulatedCrash(t *testing.T) { if _, err := s.Sync(); err != nil { t.Fatal(err) } + if cp := s.CheckpointLSN(); cp != 0 { + t.Fatalf("crash fixture checkpoint=%d, want uncheckpointed WAL", cp) + } // Unacked: may or may not survive. for i := uint32(3); i < 5; i++ { if _, err := s.Write(i, makeBlock(4096, byte(0xA0+i))); err != nil { t.Fatal(err) } } - // Simulate crash: stop the group committer (so it doesn't - // race the file close), then drop the *os.File handle without - // going through Close(). The on-disk state is whatever was - // fsync'd by the Sync call above; nothing else. - s.committer.Stop() - _ = s.fd.Close() + // Drop descriptors without store.Close(), a final checkpoint or + // another Sync. Cleanup also runs on an earlier assertion failure. + crash() }() // Reopen + Recover. The acked blocks must be present. diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go new file mode 100644 index 0000000000..8e50399835 --- /dev/null +++ b/seaweed-block/core/storage/walstore_v3.go @@ -0,0 +1,1210 @@ +package storage + +import ( + "crypto/rand" + "encoding/binary" + "errors" + "fmt" + "io" + "os" + "sync" + "sync/atomic" + "time" +) + +// Impl-3 internals of the real WALStore (format bump v3, DESIGN r15 +// section 6; plan rows 5 and 5b). A *WALStore whose v3 field is set runs +// the v3 format: its descriptor publisher (row 3), its WAL writer and scan +// (row 4), and the row-5 recovery (R < W*, the exact drop fence, head = E, +// admission). Every other piece of the store is shared with v2: the group +// committer, the dirty map, the flusher's extent writes, the syncFile leaf, +// fileSyncMu and the sticky fault. +// +// Production Create/Open select this format. Legacy formats require the offline +// migration tool or restore into a newly created volume. BASE mutations use +// install handles; raw extent writes and frontier jumps remain refused. +type walStoreV3State struct { + pub *descriptorPublisherV3 + w *walWriterV3 + ownedMap *chunkLSNMapV3 + mapEntries []chunkLSNEntryV3 // guarded by WALStore.mu; UNKNOWN is never cleared here + mapProof *mapProofEpochV3 + + appended atomic.Uint64 // highest LSN pwritten to the WAL + wack atomic.Uint64 // highest acknowledged LSN (Sync completed) + + // recoverGen is the recovery generation. A v3 Recover holds syncMu (the + // leader role) for its whole run, between lifecycleMu and s.mu, and bumps + // recoverGen first, under syncMu and s.mu. Every W publisher (the Sync + // batch, refreshW, SetWMode) holds syncMu across capture -> publish -> + // acknowledgement, so no publication straddles a recovery (codex01 row + // 5d; Claude01's structural seam). The one boundary that cannot hold + // syncMu across its wait, the outer Sync() completion, captures + // recoverGen with its target and rechecks it under syncMu -> s.mu. + // + // recoverGen is bumped at the start AND at the end of every recovery + // and reset, the start+end pattern of the map proof epoch: a lock-free + // reader whose attempt saw the same value before and after was not cut + // by a recovery's end (codex01 2fa56078 P2: a read admitted between the + // start bump and the dirty-map clear captured the new value with an old + // entry, then a same-tuple rewrite after the recovery). + // + // Lock graph: captureMu -> lifecycleMu -> syncMu -> s.mu -> descMu -> + // fileSyncMu; nothing takes syncMu while holding s.mu or descMu. + recoverGen atomic.Uint64 + + // syncMu is the group-commit leader role for the v3-only publications + // that run outside the committer (refreshW, SetWMode). + syncMu sync.Mutex + + // mapCandidate, when set by plan row 7, prepares the map candidate a + // checkpoint advance needs (DESIGN 9.1). Until then the v3 checkpoint + // and tail do not move: coverage is never fabricated. + mapCandidate func(checkpoint uint64) (func(next *descriptorV3) error, error) + + // Test hooks (never set in production). testBeforeSlotWrite runs inside + // the leaf just before a descriptor slot pwrite; a non-nil error fails + // that write. testLeaderWaiting runs in a committer batch just before it + // takes the leader role. + testBeforeSlotWrite func() error + testLeaderWaiting func() + // testSetWModeHoldingRole runs in SetWMode after it has taken the leader + // role and before it publishes the new mode. + testSetWModeHoldingRole func() + // testRefreshCached runs in refreshW after it has read the acknowledged + // W and before it publishes; testRecoverHold runs in recoverV3 after the + // scan and decision, before the fence; testBatchBeforeAck runs in a + // committer batch after its publication and before its final + // acknowledgement; testSyncBeforeCompletion runs in the outer Sync() + // after the committer returned and before its completion. + testRefreshCached func() + testRecoverHold func() + testBatchBeforeAck func() + testSyncBeforeCompletion func() + // testAfterRollover runs in a v3 write after the checkpoint rollover and + // before the payload append (write-command budget, #252). + testAfterRollover func() + testMapPrepared func() // outside all publication locks, after owned-map persistence + // testReadResolved runs in a v3 read after the dirty map resolved the + // LBA's WAL position and before the record is read. + testReadResolved func() + // testReadInvalid runs in a v3 read after a record failed validation and + // before the entry is re-resolved. + testReadInvalid func() + // testReadAdmitted runs in a v3 read before it captures the recovery + // generation; testRecoverAfterBump runs in recoverV3 after the start + // bump and before the dirty map is cleared. + testReadAdmitted func() + testRecoverAfterBump func() + + // installMu is the install admission lock (DESIGN 8.7), the topmost lock + // of section 4: begin and complete hold it exclusive, a handle mutation + // shared. liveInstallID is the ID this open began (written under + // installMu and s.mu, so either guards a read); an installing ID from + // before the open is a physical reopen's (plan row 11). + installMu sync.RWMutex + liveInstallID [16]byte + // installEpoch counts the begins of this open: mutators hold installMu + // and s.mu; a catch-up scan reads it under s.mu to detect BASE ABA. A + // handle is valid only while no later begin has run. + installEpoch uint64 + // installReopen is the last Recover's installing outcome (guarded by + // installMu and s.mu), consumed by a covering superseding begin. + installReopen *installReopenV3 + // ownerAttachDurable: this open's chunk attach was durably committed + // by the provider (CommitChunkAttachV3); false at open. + ownerAttachDurable atomic.Bool + // preBaseHighest is the highest appended LSN when the live install + // began (guarded by installMu): the records before its BaseCursor. + preBaseHighest uint64 + // testInstallBeforeAdmit runs in a handle mutation before it acquires + // installMu; testInstallAdmitted after its ID check, before the write. + testInstallBeforeAdmit func() + testInstallAdmitted func() + // testInstallLogBeforeAck runs in SyncInstallLog after its publication + // and before its final ack-boundary check. + testInstallLogBeforeAck func() + // testScanRead runs in a v3 ScanLBAs after its scan and before its + // revalidation. + testScanRead func() + // Pauses after the capture, before physical scan I/O. Tests only. + testScanBeforeRead func() +} + +// errV3RecoveredMeanwhile: a recovery ran between an outer Sync's capture +// of its target and its completion; nothing is acknowledged. +var errV3RecoveredMeanwhile = errors.New("storage: v3 recovery ran meanwhile; the Sync is not acknowledged") + +// errV3LegacySuperblockWrite: a legacy superblock write (offset 0, which is +// descriptor slot A on a v3 file) was attempted on a v3 store. +var errV3LegacySuperblockWrite = errors.New("storage: legacy superblock write refused on a v3 store (offset 0 is descriptor slot A)") + +var errV3NotYet = errors.New("storage: operation not yet supported on a v3 store (later plan row)") + +// ErrUnsupportedLegacyFormat requires offline migration or workspace restore; +// a production open never interprets a v2 volume as v3. +var ErrUnsupportedLegacyFormat = errors.New("storage: unsupported legacy walstore format; migrate offline or restore into a new volume") + +func refuseLegacyWALStore(f *os.File) error { + if sb, err := readSuperblock(io.NewSectionReader(f, 0, superblockSize)); err == nil && sb.Version == 2 && sb.validate() == nil { + return ErrUnsupportedLegacyFormat + } + return nil +} + +func metadataSlotAcceptorV3(opts WALStoreOptions) slotImplAcceptor { + return func(kind ImplKind, version uint32) bool { + return ossSlotImplAcceptor(kind, version) || + (kind == ImplKindWALStore && version >= walStoreImplVersion3 && opts.MetadataFactory != nil) + } +} + +// ProbeWALStoreV3 identifies a valid OSS descriptor through the same A/B +// selector as open. It grants no ownership or serving permission; Open +// acquires the file lock and validates all map dependencies afresh. +func ProbeWALStoreV3(path string) error { + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() + return probeWALStoreV3At(f) +} + +// probeWALStoreV3At is ProbeWALStoreV3 on an already open file. +func probeWALStoreV3At(r io.ReaderAt) error { + a, b := make([]byte, slotSizeV3), make([]byte, slotSizeV3) + if _, err := r.ReadAt(a, 0); err != nil { + return err + } + if _, err := r.ReadAt(b, slotBOffsetV3); err != nil { + return err + } + _, _, err := selectSlotV3(a, b, nil) + return err +} + +// testSkipFenceOnRecoverV3 is a test-only mutant switch for the G1 control +// (it proves the schedule resurrects without the fence). Never set outside +// tests. +var testSkipFenceOnRecoverV3 bool + +// FormatV3 reports whether the store uses the v3 format. +func (s *WALStore) FormatV3() bool { return s.v3 != nil } + +func (s *WALStore) latchV3(err error) { + if err != nil { + s.ioFault.CompareAndSwap(nil, NewSubstrateIOFailure(err, + "v3 durable persistence failed; the open store refuses further Syncs, writes and checkpoints")) + } +} + +// createWALStoreV3ForTest creates a v3 file (slot A at generation 1) and +// returns it opened and recovered. It is the only v3 creator before +// activation. +func createWALStoreV3ForTest(path string, numBlocks uint32, blockSize uint32, walSize uint64, mode WMode) (*WALStore, error) { + return createWALStoreV3AtCursorForTest(path, numBlocks, blockSize, walSize, mode, 0) +} + +// createWALStoreV3AtCursorForTest is createWALStoreV3ForTest with the WAL's +// logical cursor (tail = head) starting at cursor, to exercise the last +// representable cursors. +func createWALStoreV3AtCursorForTest(path string, numBlocks uint32, blockSize uint32, walSize uint64, mode WMode, cursor uint64) (*WALStore, error) { + return createWALStoreV3MapAtCursorForTest(path, numBlocks, blockSize, walSize, mode, cursor, 0) +} + +// Explicit geometry selector for dark row7 caller controls. Zero is reserved +// for earlier unmapped row5 fixtures; production activation must never use it. +func createMappedWALStoreV3ForTest(path string, numBlocks, blockSize uint32, walSize uint64, mode WMode, chunkBlocks uint64) (*WALStore, error) { + if chunkBlocks == 0 { + return nil, ErrMapInvalid + } + return createWALStoreV3MapAtCursorForTest(path, numBlocks, blockSize, walSize, mode, 0, chunkBlocks) +} + +// testCreateOwnerV3 parks creation at ownership boundaries; nil in production. +var testCreateOwnerV3 func(*os.File, bool) + +func createWALStoreV3MapAtCursorForTest(path string, numBlocks, blockSize uint32, walSize uint64, mode WMode, cursor, chunkBlocks uint64) (*WALStore, error) { + return createWALStoreV3Configured(path, numBlocks, blockSize, walSize, mode, cursor, chunkBlocks, WALStoreOptions{}) +} + +func createWALStoreV3Configured(path string, numBlocks, blockSize uint32, walSize uint64, mode WMode, cursor, chunkBlocks uint64, opts WALStoreOptions) (*WALStore, error) { + d := descriptorV3{ + ImplKind: ImplKindWALStore, ImplVersion: walStoreImplVersion3, + VolumeSize: uint64(numBlocks) * uint64(blockSize), ExtentSize: 64 * 1024, BlockSize: blockSize, + WALOffset: walOffsetV3, WALSize: walSize, CreatedAt: uint64(time.Now().UnixNano()), SlotGen: 1, + MapFormatID: mapFormatIDV1, MapGeneration: 1, WMode: mode, + RetainedTail: cursor, RetainedHead: cursor, + } + for _, b := range [][]byte{d.UUID[:], d.Nonce[:], d.MapLineage[:]} { + if _, err := rand.Read(b); err != nil { + return nil, err + } + } + if err := d.validate(nil); err != nil { + return nil, err + } + fd, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o644) + if err != nil { + return nil, err + } + if err := LockWALStoreFile(fd); err != nil { + _ = fd.Close() + return nil, err + } + if h := testCreateOwnerV3; h != nil { + h(fd, false) + } + sb := superblock{Version: superblockVersionV3, ImplVersion: d.ImplVersion, BlockSize: d.BlockSize, VolumeSize: d.VolumeSize, WALOffset: d.WALOffset, WALSize: d.WALSize} + metadata, totalSize, err := bindBlockMetadata(fd, &sb, opts, true, false) + if err != nil { + _ = fd.Close() + return nil, err + } + d.ImplVersion = sb.ImplVersion + if err := d.validate(metadataSlotAcceptorV3(opts)); err != nil { + _ = fd.Close() + return nil, err + } + err = fd.Truncate(totalSize) + if err == nil && chunkBlocks != 0 { + var m *chunkLSNMapV3 + m, err = createChunkLSNMapV3(path+".chunkmap", d, chunkBlocks) + if err == nil { + shape, e := mapShapeForV3(d, chunkBlocks) + if e != nil { + err = e + } else if shape.chunks > uint64(int(^uint(0)>>1))/16 { + err = ErrMapInvalid + } else { + entries := make([]chunkLSNEntryV3, int(shape.chunks)) + for i := range entries { + entries[i].Unknown = true + } + var c *chunkMapCandidateV3 + c, err = m.Prepare(1, 0, entries, nil) + if err == nil { + d = c.descriptor(d) + } + } + err = errors.Join(err, m.Close()) + } + } + if err == nil { + _, err = fd.WriteAt(d.encode(), slotAOffsetV3) + } + if err == nil { + err = fd.Sync() + } + if err != nil { + _ = fd.Close() + return nil, err + } + if h := testCreateOwnerV3; h != nil { + h(fd, true) + } + s, err := openWALStoreV3File(path, fd, chunkBlocks != 0, opts, metadata, true) + if err != nil { + return nil, err + } + if _, err := s.Recover(); err != nil { + _ = s.Close() + return nil, err + } + return s, nil +} + +// openWALStoreV3ForTest opens a v3 file WITHOUT recovering it, like +// OpenWALStore: call Recover before any Read or Write. +func openWALStoreV3ForTest(path string) (*WALStore, error) { + return openWALStoreV3MapInternalForTest(path, true) +} + +// Only pre-row7 dark fixtures can opt out of requiring a map. Even these +// fixtures must validate a non-placeholder root; production has no opt-out. +func openUnmappedWALStoreV3ForTest(path string) (*WALStore, error) { + return openWALStoreV3MapInternalForTest(path, false) +} +func openWALStoreV3MapInternalForTest(path string, requireMap bool) (*WALStore, error) { + return openWALStoreV3WithOptions(path, requireMap, WALStoreOptions{}) +} + +func openWALStoreV3WithOptions(path string, requireMap bool, opts WALStoreOptions) (*WALStore, error) { + f, err := os.OpenFile(path, os.O_RDWR, 0o644) + if err != nil { + return nil, fmt.Errorf("storage: open %s: %w", path, err) + } + if err := LockWALStoreFile(f); err != nil { + _ = f.Close() + return nil, err + } + if err := discardCutCOWFiles(path); err != nil { + _ = f.Close() + return nil, err + } + return openWALStoreV3File(path, f, requireMap, opts, nil, false) +} + +// f is already locked. Creation retains this same descriptor and metadata +// binding throughout initialization, so there is no close/reopen owner gap. +func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreOptions, metadata BlockMetadata, creating bool) (*WALStore, error) { + if err := refuseLegacyWALStore(f); err != nil { + _ = f.Close() + return nil, err + } + accept := metadataSlotAcceptorV3(opts) + a := make([]byte, slotSizeV3) + b := make([]byte, slotSizeV3) + _, errA := f.ReadAt(a, slotAOffsetV3) + _, errB := f.ReadAt(b, slotBOffsetV3) + if err := errors.Join(errA, errB); err != nil { + _ = f.Close() + return nil, err + } + d, id, err := selectSlotV3(a, b, accept) + if err != nil { + _ = f.Close() + return nil, err + } + var other *descriptorV3 + otherRaw := b + if id == slotB { + otherRaw = a + } + if od, oerr := decodeSlotV3(otherRaw, accept); oerr == nil && od.MigrationPhase == MigrationNormal { + other = &od + } + var ownedMap *chunkLSNMapV3 + var mapCurrent *chunkMapCandidateV3 + // Earlier dark row5 fixtures have no map tuple. A real immutable root is + // never optional: missing metadata is not a clean map. + if requireMap || d.MapRootHash != [32]byte{} { + ownedMap, mapCurrent, err = openDescriptorMapV3(path+".chunkmap", d, other) + if err != nil { + _ = f.Close() + return nil, err + } + } + // The shared store reads its geometry from sb; WAL bounds and the + // checkpoint come from the selected descriptor. + sb := superblock{ + Version: superblockVersionV3, UUID: d.UUID, VolumeSize: d.VolumeSize, + ExtentSize: d.ExtentSize, BlockSize: d.BlockSize, WALOffset: d.WALOffset, WALSize: d.WALSize, + WALHead: d.RetainedHead, WALTail: d.RetainedTail, WALCheckpointLSN: d.CheckpointLSN, + CreatedAt: d.CreatedAt, ImplKind: d.ImplKind, ImplVersion: d.ImplVersion, + } + copy(sb.Magic[:], superblockMagic) + if !creating && opts.MetadataFactory != nil { + metadata, _, err = bindBlockMetadata(f, &sb, opts, false, false) + if err != nil { + if ownedMap != nil { + _ = ownedMap.Close() + } + _ = f.Close() + return nil, err + } + } + s, err := openInitializedInternal(path, f, &sb, metadata, func(s *WALStore) error { + v := &walStoreV3State{} + v.pub = newDescriptorPublisherV3(d, id, other, descriptorIOV3{ + writeSlot: func(off int64, buf []byte) error { + if h := s.v3.testBeforeSlotWrite; h != nil { + if err := h(); err != nil { + return err + } + } + n, err := f.WriteAt(buf, off) + if err == nil && n != len(buf) { + err = fmt.Errorf("storage: v3 slot short write %d of %d", n, len(buf)) + } + return err + }, + fsync: f.Sync, + syncFile: s.syncFile, + sticky: s.stickyIOFault, + latch: s.latchV3, + }) + v.pub.accept = accept + // A reset stopped between its two publications (DESIGN 8.6) binds no + // writer across the two nonces: Recover's head publication completes + // the new incarnation in the other slot and creates the writer then; + // until then every append is refused. + if !v.pub.halfResetV3() { + w, err := newWALWriterV3(f, v.pub) + if err != nil { + return err + } + v.w = w + v.w.instr = &s.instr + } + v.wack.Store(d.W) + if ownedMap != nil { + v.mapProof = newMapProofEpochV3() + if err := v.pub.bindMapV3(mapCurrent, v.mapProof); err != nil { + return err + } + v.ownedMap = ownedMap + v.mapEntries = append([]chunkLSNEntryV3(nil), mapCurrent.entries...) + ownedMap.latchPersistence = s.latchV3 + } + s.v3 = v + return nil + }) + if err != nil { + if ownedMap != nil { + _ = ownedMap.Close() + } + _ = f.Close() + return nil, err + } + return s, nil +} + +// recoverV3 is Recover for a v3 store (DESIGN 6.5, 6.6). The caller holds +// captureMu, lifecycleMu and s.mu, as v2 Recover does. +func (s *WALStore) recoverV3() (uint64, error) { + v := s.v3 + v.recoverGen.Add(1) // under syncMu and s.mu (see recoverGen); odd now + defer v.recoverGen.Add(1) // even again at the end, on every path + if h := v.testRecoverAfterBump; h != nil { + h() + } + d := v.pub.current() + s.dm.clear() + scan, err := scanWALV3Accepted(s.fd, d, v.pub.accept) + if err != nil { + if d.BaseState == BaseInstalling { + // Installing keeps its typed not-ready outcome; the cause is a + // substrate error, not proven install-log damage (codex01 5b P2). + return 0, fmt.Errorf("%w: scan: %w", ErrBaseIncomplete, err) + } + return 0, err + } + recs := make([]trustedRecordV3, 0, len(scan.Records)) + for _, r := range scan.Records { + last := r.Entry.LSN + if r.Entry.Type == walEntryWriteBatch { + last += r.Entry.BatchCount - 1 + } + recs = append(recs, trustedRecordV3{FirstLSN: r.Entry.LSN, LastLSN: last, End: r.End}) + } + o, err := decideRecoveryV3(d, recs, scan.MaxDurableLSN) + if err != nil { + return 0, err // R < W*: fail closed (wal_corrupt) + } + if o.Installing { + // The recovered bounds of an installing reopen (DESIGN 8.3), kept for + // a covering supersession: E, R and whether the suffix is damaged. + // Nothing is fenced, published or admitted here; the allocator + // state continues above every trusted record so a later install + // never reuses an LSN the WAL still holds. + // + // Only a physical reopen records them: when this open began the + // installing ID, its handle stays valid (DESIGN r17.4: until the next + // begin) and may append and acknowledge past this cut, so a cached E + // would be stale and fencing from it could erase acknowledged + // records (codex01 row 11b P1). A resume or a fenced supersession + // then refuses before any I/O; the live install continues. + if d.BaseInstallID != v.liveInstallID { + ro := &installReopenV3{id: d.BaseInstallID, E: o.E, R: o.R, damaged: o.Damaged, walSize: d.WALSize} + for _, r := range scan.Records { + if r.Entry.LSN > o.R { + break + } + if r.Entry.Type == walEntryWrite || r.Entry.Type == walEntryWriteBatch { + ro.records = append(ro.records, r) + } + } + v.installReopen = ro + if v.w != nil { + kept := scan + kept.End, kept.Frontier = o.E, o.R + if err := v.w.rememberReclaimScanV3(kept); err != nil { + return 0, err + } + } + } else if o.Damaged || v.w == nil || o.E != v.w.logicalHeadV3() { + // A same-open Recover of this open's live install that finds the + // WAL cut short of the live writer (damage under a live install): + // the handle cannot safely continue past it, so the store fails + // closed; a physical reopen then decides intact or damaged. + s.latchV3(fmt.Errorf("storage: v3 same-open installing recovery: recovered cut E %d is not the live writer head", o.E)) + } else { + // The live install continues (r17.4). Its trusted install-lane + // records are republished in the dirty map, which this Recover + // cleared, so the completed image serves them and not older BASE + // bytes; the volatile map coverage (the BASE writes' UNKNOWN) is + // kept as it is (codex01 04180c33 P1). + for _, r := range scan.Records { + if r.Entry.LSN > o.R { + break + } + s.replayRecordV3(r, d.WALSize, d.BlockSize) + } + } + v.appended.Store(max(v.appended.Load(), o.R)) + s.nextLSN = max(s.nextLSN, o.R+1) + s.walHead = max(s.walHead, o.R) + return 0, installingErrorV3(o) + } + // Reconstruct volatile map coverage from the authoritative immutable root, + // then replay only the retained prefix. A same-open Recover must not keep + // speculative cache changes from a dropped suffix. + if v.ownedMap != nil { + v.pub.descMu.Lock() + v.mapEntries = append(v.mapEntries[:0], v.pub.mapCurrent.entries...) + v.pub.descMu.Unlock() + } + // Replay the records <= R into the dirty map (last writer wins); the + // rest are dropped and fenced below. + for _, r := range scan.Records { + e := r.Entry + if e.LSN > o.R { + break + } + if !s.replayRecordV3(r, d.WALSize, d.BlockSize) { + s.dm.clear() + return 0, fmt.Errorf("%w: replay of v3 record type %#x", errV3NotYet, e.Type) + } + // Records at/below the selected checkpoint are already represented by + // its durable map. Re-resolving those same logical bytes is not a new + // lower/equal mutation; conservatively account only the retained suffix. + count := uint64(1) + if e.Type == walEntryWriteBatch { + count = e.BatchCount + } + for i := uint64(0); i < count; i++ { + if e.LSN+i > d.CheckpointLSN { + s.recordMapWriteV3(e.LBA+i, e.LSN+i) + } + } + } + if h := v.testRecoverHold; h != nil { + h() + } + // The drop fence, then the recovered head, then the writer and admission. + floor, sameNonce := v.pub.reuseFloor() + if err := s.fenceV3(o.E, floor, d.WALSize, sameNonce, d.WALOffset); err != nil { + s.dm.clear() + return 0, err + } + if _, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { + n.RetainedHead = o.E + return nil + }); err != nil { + s.dm.clear() + return 0, err + } + if v.w == nil { + // A half-published reset, resolved by the head publication above. + w, err := newWALWriterV3(s.fd, v.pub) + if err != nil { + s.dm.clear() + return 0, err + } + v.w = w + v.w.instr = &s.instr + } + restore := scan + restore.End = o.E + if err := v.w.restoreScanV3(restore); err != nil { + s.dm.clear() + return 0, err + } + s.checkpointLSN = d.CheckpointLSN + s.nextLSN = o.R + 1 + s.walHead, s.syncedLSN = o.R, o.R + if s.walTail == 0 && o.R > 0 { + s.walTail = 1 + } + // The volatile acknowledged frontier is the recovered prefix, never an + // older in-memory maximum: a same-open recovery that dropped mode C's + // newest batch must not let a later refresh publish a W the WAL no + // longer holds (codex01 5b P1). + v.appended.Store(o.R) + v.wack.Store(o.R) + return s.syncedLSN, nil +} + +// fenceV3 zeroes exactly the fence ranges and fsyncs them through the leaf +// before any admission (DESIGN 6.6). A write error latches inside the leaf. +func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset uint64) error { + ranges, err := fenceRangesV3(E, floor, walSize, sameNonce) + if err != nil { + return err + } + if len(ranges) == 0 || testSkipFenceOnRecoverV3 { + return nil + } + return s.syncFile(func() error { + const chunk = 64 * 1024 + zero := make([]byte, chunk) + for _, r := range ranges { + for done := uint64(0); done < r.Len; { + n := min(r.Len-done, chunk) + if _, err := s.fd.WriteAt(zero[:n], int64(walOffset+r.Off+done)); err != nil { + err = fmt.Errorf("storage: v3 drop fence: %w", err) + s.latchV3(err) + return err + } + done += n + } + } + return nil + }, s.fd.Sync) +} + +// appendWriteV3 is the v3 body of Write's append, under s.mu. DurableLSN is +// the acknowledged W at append time; a pwrite failure latches the store. +// budget (nil = none) is the guest command's budget: checked after a +// checkpoint rollover (whose metadata I/O completes) and before any new +// payload WAL I/O, so an expired command never starts one. +func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64, budget func() error) (uint64, error) { + e := walEntryV3{LSN: lsn, Type: walEntryWrite, LBA: uint64(lba), Length: uint32(len(data)), Data: data} + if s.v3.w == nil { + return 0, errWALBindingV3 // a half-published reset before its Recover + } + // A strictly newer append stays in the retained WAL suffix. It cannot + // invalidate coverage of an older checkpoint prefix. BASE writes, capture + // UNKNOWN clearing and lifecycle mutations still invalidate at their seams. + if p := s.v3.mapProof; p != nil && p.mutation.Load() >= counterMaxV3 { + return 0, ErrCounterExhausted + } + if err := s.rolloverCheckpointV3Locked(); err != nil { + return 0, err + } + if err := s.v3BudgetAfterRollover(budget); err != nil { + return 0, err + } + phys, err := s.v3.w.append(e, s.v3.wack.Load(), budget) + if err != nil { + if errors.Is(err, errWALPwrite) { + s.latchV3(err) + } + return 0, err + } + s.recordMapWriteV3(uint64(lba), lsn) + s.v3.appended.Store(lsn) + return phys, nil +} + +// writeBatchV3Locked is WriteBatch on a v3 store, under WALStore.mu: one +// multi-block record (type 0x04) of len(blocks) consecutive LBAs with the +// LSNs firstLSN.. firstLSN+n-1, so a crash keeps the whole batch or none of +// it (one CRC32C); the writer consumes the whole LSN range (DESIGN 6.7, +// r16). A single block is an ordinary write record. Each block's dirty +// entry names its data offset inside the record. +func (s *WALStore) writeBatchV3Locked(startLBA uint32, blocks [][]byte, firstLSN uint64, budget func() error) ([]uint64, error) { + start := time.Now() + if len(blocks) == 1 { + phys, err := s.appendWriteV3(startLBA, blocks[0], firstLSN, budget) + s.instr.appendLatency.Observe(time.Since(start)) + s.walMutation.Add(1) + if err != nil { + return nil, fmt.Errorf("storage: WAL append: %w", err) + } + dirtyStart := time.Now() + s.dm.put(uint64(startLBA), phys, firstLSN, uint32(len(blocks[0]))) + s.instr.recordDirtyMapUpdate(1, time.Since(dirtyStart)) + s.noteChunkMutation(uint64(startLBA)) + s.advanceAfterAppendV3(firstLSN, firstLSN) + return []uint64{firstLSN}, nil + } + if s.v3.w == nil { + return nil, errWALBindingV3 // a half-published reset before its Recover + } + bs := int(s.sb.BlockSize) + payload := make([]byte, 0, len(blocks)*bs) + copyStart := time.Now() + for _, b := range blocks { + payload = append(payload, b...) + } + s.instr.recordWALCopy(len(payload), time.Since(copyStart)) + n := uint64(len(blocks)) + lastLSN := firstLSN + n - 1 + if p := s.v3.mapProof; p != nil && p.mutation.Load() >= counterMaxV3 { + return nil, ErrCounterExhausted + } + e := walEntryV3{LSN: firstLSN, BatchCount: n, Type: walEntryWriteBatch, LBA: uint64(startLBA), Length: uint32(len(payload)), Data: payload} + if err := s.rolloverCheckpointV3Locked(); err != nil { + return nil, err + } + if err := s.v3BudgetAfterRollover(budget); err != nil { + return nil, err + } + phys, err := s.v3.w.append(e, s.v3.wack.Load(), budget) + s.instr.appendLatency.Observe(time.Since(start)) + s.walMutation.Add(1) + if err != nil { + if errors.Is(err, errWALPwrite) { + s.latchV3(err) + } + return nil, fmt.Errorf("storage: WAL batch append: %w", err) + } + lsns := make([]uint64, n) + dirtyStart := time.Now() + for i := uint64(0); i < n; i++ { + lba := uint64(startLBA) + i + lsns[i] = firstLSN + i + s.recordMapWriteV3(lba, lsns[i]) + s.dm.putAt(lba, phys, uint32(i)*uint32(bs), lsns[i], uint32(bs)) + s.noteChunkMutation(lba) + } + s.instr.recordDirtyMapUpdate(len(blocks), time.Since(dirtyStart)) + s.v3.appended.Store(lastLSN) + s.advanceAfterAppendV3(firstLSN, lastLSN) + return lsns, nil +} + +// advanceAfterAppendV3 moves the volatile frontier past an appended range. +// Caller holds WALStore.mu. +func (s *WALStore) advanceAfterAppendV3(first, last uint64) { + s.nextLSN = last + 1 + if last > s.walHead { + s.walHead = last + } + if s.walTail == 0 { + s.walTail = first + } +} + +// replayRecordV3 republishes one trusted write or batch record in the dirty +// map (last writer wins per LBA). It reports false for other types. +func (s *WALStore) replayRecordV3(r walScannedRecordV3, walSize uint64, blockSize uint32) bool { + e := r.Entry + count := uint64(1) + switch e.Type { + case walEntryWrite: + case walEntryWriteBatch: + count = e.BatchCount + default: + return false + } + size := uint64(walEntryHeaderSizeV3 + len(e.Data)) + phys := (r.End - size) % walSize + for i := uint64(0); i < count; i++ { + s.dm.putAtIfNewer(e.LBA+i, phys, uint32(i)*blockSize, e.LSN+i, blockSize) + } + return true +} + +// syncWALBatchV3 is the committer leader's batch for a v3 store (DESIGN 6.2, +// 6.3). The cut H is every record pwritten before the leader starts. +func (s *WALStore) syncWALBatchV3() error { + return s.syncWALBatchV3Internal(false) +} + +// Called only by the flusher, without capture/lifecycle/store locks. Pressure +// cannot depend on a guest Flush: persist locally before checkpointing, using +// the same physical sync and final fault gate as an ordinary sync batch. +func (s *WALStore) syncWALPressureV3() error { + return s.syncWALBatchV3Internal(true) +} + +func (s *WALStore) syncWALBatchV3Internal(pressureOnly bool) error { + if err := s.stickyIOFault(); err != nil { + return err + } + v := s.v3 + // An idle flusher must not queue behind an unrelated Sync leader before + // preparing its map. This is only a scheduling hint: pressure eligibility + // and the mutation/frontier cut are still rechecked together under syncMu. + // A concurrent append missed here is picked up by the next notified cycle. + if pressureOnly && s.walUsedFraction() < 0.70 { + return nil + } + // The leader role: SetWMode holds it while it changes the mode, so no + // batch acknowledges under a stale mode selection (the mode is read + // only after the role is taken). + if h := v.testLeaderWaiting; h != nil && !pressureOnly { + h() + } + v.syncMu.Lock() + defer v.syncMu.Unlock() + if pressureOnly { + // Recheck under the same leader interval as the mutation/frontier cut. + // Installing uses receiver-owned SyncInstallLog, never this normal path. + s.mu.RLock() + closed := s.closed + s.mu.RUnlock() + if closed || v.pub.current().BaseState == BaseInstalling || s.walUsedFraction() < 0.70 || v.appended.Load() <= v.wack.Load() { + return nil + } + } + cut := s.walMutation.Load() + if !s.bypassSyncDedup.Load() && s.chunk.Load() == nil && cut <= s.durableMutation.Load() { + return nil + } + H, prev := v.appended.Load(), v.wack.Load() + // One sample per covering WAL batch, as on v2. In mode C the slot + // publication is the physical sync; mode A also settles its W slot. + syncStart := time.Now() + defer func() { s.fileSyncLatency.Observe(time.Since(syncStart)) }() + switch v.pub.current().WMode { + case WModeStrict: + // A: fsync the WAL, then publish W = H with its own fsync. + if err := s.syncFile(nil, func() error { return s.syncWALFile() }); err != nil { + return err + } + if _, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { n.W = H; return nil }); err != nil { + return err + } + default: + // C: the fallback slot carries the PREVIOUS batch's acknowledged + // W, and the publication's one fsync covers this batch's records + // and the slot. The slot never names an LSN beyond a completed fsync. + s.walSyncCalls.Add(1) + if _, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { n.W = prev; return nil }); err != nil { + return err + } + } + if h := v.testBatchBeforeAck; h != nil { + h() + } + // The acknowledgement boundary (codex01 row 5 P1): a queued append may + // have failed and latched the store fault while this batch's slot I/O + // was in flight. Recheck under the store lock, which that append holds + // until it has latched, before acknowledging anything. + s.mu.Lock() + defer s.mu.Unlock() + if err := s.stickyIOFault(); err != nil { + return err + } + if H > prev { + v.wack.Store(H) + } + s.durableMutation.Store(cut) + return nil +} + +// refreshW is the mode-C idle refresh (DESIGN 6.2): publish W = the +// acknowledged W when the slot lags it. +func (s *WALStore) refreshW() error { + v := s.v3 + if v == nil { + return errV3NotYet + } + v.syncMu.Lock() + defer v.syncMu.Unlock() + s.mu.Lock() + rolloverErr := s.rolloverCheckpointV3Locked() + s.mu.Unlock() + if rolloverErr != nil { + return rolloverErr + } + wack := v.wack.Load() + if wack <= v.pub.current().W { + return nil + } + if h := v.testRefreshCached; h != nil { + h() + } + _, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { n.W = wack; return nil }) + return err +} + +// SetWMode changes the W mode (DESIGN 6.4). It runs a Sync first, so every +// write admitted before it is acknowledged under the old mode, then +// publishes the new mode with W = the actual acknowledged W while holding +// the v3 leader role. Every later batch uses the new mode. +func (s *WALStore) SetWMode(m WMode) error { + v := s.v3 + if v == nil { + return errV3NotYet + } + if _, err := s.Sync(); err != nil { + return err + } + v.syncMu.Lock() + defer v.syncMu.Unlock() + if h := v.testSetWModeHoldingRole; h != nil { + h() + } + wack := v.wack.Load() + _, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { n.WMode, n.W = m, wack; return nil }) + return err +} + +// readDirtyV3 serves a v3 read from the dirty map, if the LBA has an entry +// (handled false: read the extent). A reader holds no lock across its WAL +// read, so the position it resolved may be reused before the pread: after a +// reset (cursor 0 again, codex01 row 8 P1) or a same-open recovery that +// fenced and reused it. The read therefore validates the WHOLE record it +// read, payload included (CRC, footer, write type, LBA and LSN against the +// resolving entry), and re-resolves on a mismatch. LSN allocation runs on +// across a reset, so a matching LBA and LSN identify the resolved write; +// no nonce is checked. A same-open recovery can re-allocate a dropped LSN +// to the same LBA at the same position, so the "entry unchanged" damage +// verdict also requires the same recovery generation before and after the +// whole attempt. A recovery bumps it at its start and its end, so any +// overlap changes it (codex01 e72acd40 and 2fa56078 P2s; see recoverGen). +// A generation captured while a recovery runs can match only if the +// verdict also falls inside that recovery, which holds s.mu: no write can +// re-allocate the tuple, and the replay installs only validated records. A pread error is a +// substrate I/O failure, never WAL integrity: only a record that fails +// validation within one stable lifetime is damage. No lock is taken: the +// lock graph is unchanged. +func (s *WALStore) readDirtyV3(lba uint32) (data []byte, handled bool, err error) { + const attempts = 8 + for i := 0; i < attempts; i++ { + if h := s.v3.testReadAdmitted; h != nil { + h() + } + gen := s.v3.recoverGen.Load() + off, dataOff, lsn, _, ok := s.dm.get(uint64(lba)) + if !ok { + return nil, false, nil + } + if h := s.v3.testReadResolved; h != nil { + h() + } + data, ioErr, verr := s.readRecordV3(lba, off, dataOff, lsn) + if ioErr != nil { + return nil, true, NewSubstrateIOFailure(ioErr, "v3 WAL read") + } + if verr == nil { + return data, true, nil + } + if h := s.v3.testReadInvalid; h != nil { + h() + } + off2, dataOff2, lsn2, _, ok2 := s.dm.get(uint64(lba)) + if ok2 && off2 == off && dataOff2 == dataOff && lsn2 == lsn && s.v3.recoverGen.Load() == gen { + return nil, true, NewWALIntegrityFailure(verr, "v3 WAL read of a live dirty entry") + } + } + return nil, true, fmt.Errorf("storage: v3 WAL read of LBA %d did not settle in %d attempts", lba, attempts) +} + +// readRecordV3 reads and validates the whole v3 write record at walRelOff. +// ioErr is a failed or short pread: the WAL region lies inside the file, so +// io.EOF (a file shorter than its geometry) is substrate I/O too. verr is a +// record that was read but does not validate as the resolved write. +func (s *WALStore) readRecordV3(lba uint32, walRelOff uint64, dataOff uint32, lsn uint64) (data []byte, ioErr, verr error) { + e, _, ioErr, verr := readWholeRecordV3(s.fd, recordGeometryV3{s.sb.WALOffset, s.sb.WALSize, s.sb.BlockSize, s.sb.VolumeSize}, walRelOff) + if ioErr != nil || verr != nil { + return nil, ioErr, verr + } + data, err := blockOfRecordV3(e, uint64(lba), dataOff, lsn, s.sb.BlockSize) + if err != nil { + return nil, nil, fmt.Errorf("storage: v3 WAL read at %d: %w", walRelOff, err) + } + return data, nil, nil +} + +// readWholeRecordV3 reads the prefix at walRelOff, sizes the record from +// its type and Length (a batch carries BatchCount blocks), reads and +// decodes the whole record (CRC32C, footer, geometry). An append never lets +// a record cross the ring end (padding fills the suffix), so one crossing +// it is invalid. A pread error is substrate I/O (ioErr), never integrity. +// recordGeometryV3 is what a whole-record read needs of the format. +type recordGeometryV3 struct { + WALOffset, WALSize uint64 + BlockSize uint32 + VolumeSize uint64 +} + +func readWholeRecordV3(fd *os.File, sb recordGeometryV3, walRelOff uint64) (walEntryV3, uint64, error, error) { + return readWholeRecordProfiledV3(fd, sb, walRelOff, nil) +} + +func readWholeRecordProfiledV3(fd *os.File, sb recordGeometryV3, walRelOff uint64, profile *flusherInstrumentation) (e walEntryV3, size uint64, ioErr, verr error) { + if walRelOff+walEntryHeaderSizeV3 > sb.WALSize { + return e, 0, nil, fmt.Errorf("storage: v3 WAL record at %d crosses the ring end", walRelOff) + } + prefix := make([]byte, walEntryPrefixSizeV3) + var start time.Time + if profile != nil { + start = time.Now() + } + n, readErr := fd.ReadAt(prefix, int64(sb.WALOffset+walRelOff)) + if profile != nil { + profile.recordWALHeaderRead(n, time.Since(start), readErr) + } + if readErr != nil { + return e, 0, fmt.Errorf("storage: v3 WAL read at %d: %w", walRelOff, readErr), nil + } + size = uint64(walEntryHeaderSizeV3) + switch prefix[16] { + case walEntryWrite, walEntryWriteBatch: + size += uint64(binary.LittleEndian.Uint32(prefix[26:30])) + default: + return e, 0, nil, fmt.Errorf("storage: v3 WAL record at %d has type %#x, not a write", walRelOff, prefix[16]) + } + if walRelOff+size > sb.WALSize { + return e, 0, nil, fmt.Errorf("storage: v3 WAL record at %d crosses the ring end", walRelOff) + } + full := make([]byte, size) + if profile != nil { + start = time.Now() + } + n, readErr = fd.ReadAt(full, int64(sb.WALOffset+walRelOff)) + if profile != nil { + profile.recordWALRecordRead(n, time.Since(start), readErr) + } + if readErr != nil { + return e, 0, fmt.Errorf("storage: v3 WAL read at %d: %w", walRelOff, readErr), nil + } + if profile != nil { + start = time.Now() + } + e, err := decodeWALEntryV3(full, sb.BlockSize, sb.VolumeSize/uint64(sb.BlockSize)) + if profile != nil { + profile.recordWALRecordDecode(len(full), time.Since(start), err) + } + if err != nil { + return e, 0, nil, err + } + return e, size, nil, nil +} + +// blockOfRecordV3 returns the block of a validated write or batch record +// that the dirty entry (lba, dataOff, lsn) names: a single write is block 0 +// at the record's LBA and LSN; a batch's block i is at LBA+i with LSN+i and +// data offset i * blockSize. +func blockOfRecordV3(e walEntryV3, lba uint64, dataOff uint32, lsn uint64, blockSize uint32) ([]byte, error) { + if dataOff%blockSize != 0 { + return nil, fmt.Errorf("data offset %d not block aligned", dataOff) + } + idx := uint64(dataOff / blockSize) + count := uint64(1) + switch e.Type { + case walEntryWrite: + case walEntryWriteBatch: + count = e.BatchCount + default: + return nil, fmt.Errorf("record type %#x is not a write", e.Type) + } + if idx >= count || e.LBA+idx != lba || e.LSN+idx != lsn || uint64(len(e.Data)) != count*uint64(blockSize) { + return nil, fmt.Errorf("record is LBA %d LSN %d count %d, want block %d at LBA %d LSN %d", e.LBA, e.LSN, count, idx, lba, lsn) + } + off := idx * uint64(blockSize) + return e.Data[off : off+uint64(blockSize)], nil +} + +// readDirtyRecordV3 is the flusher's record read for a v3 store: it decodes +// and validates the whole record before its data may reach the extent. +type flushRecordCacheV3 struct { + recoveryGen uint64 + offset, size uint64 + entry walEntryV3 + valid bool +} + +func (f *flusher) readDirtyRecordV3(e snapshotEntry) ([]byte, uint64, error) { + return f.readDirtyRecordV3Cached(e, nil) +} + +func (f *flusher) readDirtyRecordV3Cached(e snapshotEntry, cache *flushRecordCacheV3) (data []byte, entrySize uint64, err error) { + readFailed := false + defer func() { + if err == nil { + f.instr.recordValidatedRecord() + } else if !readFailed { + f.instr.recordValidationFailure() + } + }() + store := f.store + d := store.v3.pub.current() + if cache != nil && !store.v3.flushLifetimeValidV3(cache.recoveryGen) { + return nil, 0, mapCoverageRefusal("recovery_lifetime_changed") + } + var entry walEntryV3 + var size uint64 + if cache != nil && cache.valid && cache.offset == e.WALOffset { + entry, size = cache.entry, cache.size + } else { + var ioErr, verr error + entry, size, ioErr, verr = readWholeRecordProfiledV3(store.fd, recordGeometryV3{store.sb.WALOffset, store.sb.WALSize, store.sb.BlockSize, store.sb.VolumeSize}, e.WALOffset, &f.instr) + if ioErr != nil { + readFailed = true + return nil, 0, fmt.Errorf("flusher: read v3 WAL record at %d: %w", e.WALOffset, ioErr) + } + if verr != nil { + return nil, 0, fmt.Errorf("flusher: invalid v3 WAL record LBA %d offset %d: %w", e.LBA, e.WALOffset, verr) + } + if cache != nil { + cache.entry, cache.size, cache.offset, cache.valid = entry, size, e.WALOffset, true + } + } + if entry.Nonce != d.Nonce || e.Length != store.sb.BlockSize { + return nil, 0, fmt.Errorf("flusher: v3 WAL slot mismatch LBA %d offset %d", e.LBA, e.WALOffset) + } + data, err = blockOfRecordV3(entry, e.LBA, e.DataOffset, e.LSN, store.sb.BlockSize) + if err != nil { + return nil, 0, fmt.Errorf("flusher: v3 WAL slot mismatch LBA %d offset %d: %w", e.LBA, e.WALOffset, err) + } + return data, size, nil +} + +// persistCheckpointV3 is the v3 checkpoint/tail publication. It goes +// through the row-3 publisher with the row-7 map candidate; without one, +// the checkpoint and tail do not move (no coverage is fabricated) and the +// flushed bytes stay retained in the WAL. +// +// A v3 checkpoint never exceeds W (DESIGN 2.2 item 5, 9.1 predicate 2: +// CheckpointLSN <= mapCoveredCheckpoint <= W). The flusher may have flushed +// dirty entries that no Sync has acknowledged yet, so the candidate is +// clamped to the acknowledged W; those records stay retained in the WAL +// until a Sync covers them. The map candidate is prepared first, outside +// every lock; the publication is a W publisher, so it runs under the v3 +// leader role (syncMu), like Sync, refreshW and SetWMode, and cannot +// straddle a recovery. If a recovery lowered the acknowledged W below the +// prepared candidate meanwhile, this cycle publishes nothing. +// flushLifetimeValidV3 is checked under syncMu at publication and store.mu +// at retirement. Recover/reset advance the same start/end generation. +func (v *walStoreV3State) flushLifetimeValidV3(gen uint64) bool { + return gen%2 == 0 && v.recoverGen.Load() == gen +} + +func (s *WALStore) persistCheckpointV3(highestLSN, recoveryGen uint64) error { + v := s.v3 + if v.ownedMap != nil { + return s.persistOwnedMapCheckpointV3(highestLSN, recoveryGen) + } + if v.mapCandidate == nil { + return nil + } + checkpoint := min(highestLSN, v.wack.Load()) + if checkpoint <= v.pub.current().CheckpointLSN { + return nil + } + mutateMap, err := v.mapCandidate(checkpoint) + if err != nil { + return err + } + v.syncMu.Lock() + defer v.syncMu.Unlock() + if !v.flushLifetimeValidV3(recoveryGen) { + return mapCoverageRefusal("recovery_lifetime_changed") + } + wack := v.wack.Load() + if wack < checkpoint { + return nil // a recovery lowered the frontier; retry next cycle + } + d, err := v.pub.publish(&s.mu, nil, func(n *descriptorV3) error { + n.W = max(n.W, wack) + n.CheckpointLSN = checkpoint + return mutateMap(n) + }) + if err != nil { + return err + } + s.mu.Lock() + s.checkpointLSN = d.CheckpointLSN + s.mu.Unlock() + return nil +} + +// v3BudgetAfterRollover is the last budget check of a v3 write: after the +// rollover's metadata I/O (completed, owned) and before the payload append. +func (s *WALStore) v3BudgetAfterRollover(budget func() error) error { + if h := s.v3.testAfterRollover; h != nil { + h() + } + if budget == nil { + return nil + } + return budget() +} diff --git a/seaweed-block/core/storage/walstore_v3_test.go b/seaweed-block/core/storage/walstore_v3_test.go new file mode 100644 index 0000000000..f47d8f1596 --- /dev/null +++ b/seaweed-block/core/storage/walstore_v3_test.go @@ -0,0 +1,977 @@ +package storage + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "runtime" + "sync" + "testing" + "time" +) + +// Row 5/5b store-level controls on the REAL *WALStore in its v3 mode +// (DESIGN r15 6.1 to 6.6, section 11 item 5 and the G1 fence). A "crash" +// stops the committer and closes the file without any flush or further +// write (crashRecoveryHardeningStore), so every pwritten byte is still +// visible on reopen; damage is injected into the file directly. + +const v3TestBlock = 4096 +const v3TestWAL = 64 * 1024 + +func newStoreV3(t *testing.T, mode WMode) (*WALStore, string) { + t.Helper() + path := filepath.Join(t.TempDir(), "store.v3") + s, err := createWALStoreV3ForTest(path, 64, v3TestBlock, v3TestWAL, mode) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + return s, path +} + +// reopenV3 opens and recovers, as a restart would. +func reopenV3(t *testing.T, path string) (*WALStore, error) { + t.Helper() + s, err := openUnmappedWALStoreV3ForTest(path) + if err != nil { + return nil, err + } + s.DisableAutoFlushForRecoveryTest() + if _, err := s.Recover(); err != nil { + crashRecoveryHardeningStore(t, s) + return nil, err + } + return s, nil +} + +func mustReopenV3(t *testing.T, path string) *WALStore { + t.Helper() + s, err := reopenV3(t, path) + if err != nil { + t.Fatal(err) + } + return s +} + +func blk(b byte) []byte { return bytes.Repeat([]byte{b}, v3TestBlock) } + +func readV3(t *testing.T, s *WALStore, lba uint32) []byte { + t.Helper() + b, err := s.Read(lba) + if err != nil { + t.Fatal(err) + } + return b +} + +// writeSynced writes one block per LSN, each in its own Sync (batch). +func writeSynced(t *testing.T, s *WALStore, from, to uint32) { + t.Helper() + for lba := from; lba <= to; lba++ { + if _, err := s.Write(lba, blk(byte(lba))); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } +} + +// recordOffset returns the absolute file offset of the record with lsn, +// found by scanning the file as a reopen would. +func recordOffset(t *testing.T, path string, lsn uint64) int64 { + t.Helper() + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + a, b := make([]byte, slotSizeV3), make([]byte, slotSizeV3) + if _, err := f.ReadAt(a, 0); err != nil { + t.Fatal(err) + } + if _, err := f.ReadAt(b, slotBOffsetV3); err != nil { + t.Fatal(err) + } + d, _, err := selectSlotV3(a, b, nil) + if err != nil { + t.Fatal(err) + } + r, err := scanWALV3(f, d) + if err != nil { + t.Fatal(err) + } + for _, rec := range r.Records { + if rec.Entry.LSN == lsn { + size := uint64(walEntryHeaderSizeV3 + len(rec.Entry.Data)) + return int64(d.WALOffset + (rec.End-size)%d.WALSize) + } + } + t.Fatalf("no record with LSN %d", lsn) + return 0 +} + +func damageRecord(t *testing.T, path string, lsn uint64) { + t.Helper() + off := recordOffset(t, path, lsn) + walEntryPrefixSizeV3 + 100 // a payload byte + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + defer f.Close() + b := []byte{0} + if _, err := f.ReadAt(b, off); err != nil { + t.Fatal(err) + } + b[0] ^= 0xFF + if _, err := f.WriteAt(b, off); err != nil { + t.Fatal(err) + } +} + +func isWALCorrupt(err error) bool { + var rf *RecoveryFailure + return errors.As(err, &rf) && rf.Kind == StorageRecoveryFailureWALIntegrity +} + +func TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes(t *testing.T) { + for _, mode := range []WMode{WModeLagged, WModeStrict} { + s, path := newStoreV3(t, mode) + writeSynced(t, s, 1, 5) + crashRecoveryHardeningStore(t, s) + r := mustReopenV3(t, path) + for lba := uint32(1); lba <= 5; lba++ { + if !bytes.Equal(readV3(t, r, lba), blk(byte(lba))) { + t.Fatalf("mode %d: acknowledged LBA %d lost", mode, lba) + } + } + // Writes continue after recovery and survive another crash. + writeSynced(t, r, 6, 7) + crashRecoveryHardeningStore(t, r) + r2 := mustReopenV3(t, path) + if !bytes.Equal(readV3(t, r2, 7), blk(7)) || !bytes.Equal(readV3(t, r2, 1), blk(1)) { + t.Fatalf("mode %d: writes after recovery lost", mode) + } + _ = r2.Close() + } +} + +func TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch(t *testing.T) { + // The newest acknowledged batch corrupted before any later Sync or + // refresh: mode C truncates it silently (the documented window); mode A + // refuses. + for _, c := range []struct { + mode WMode + corrupt bool + }{{WModeLagged, false}, {WModeStrict, true}} { + s, path := newStoreV3(t, c.mode) + writeSynced(t, s, 1, 3) + crashRecoveryHardeningStore(t, s) + damageRecord(t, path, 3) + r, err := reopenV3(t, path) + if c.corrupt { + if !isWALCorrupt(err) { + t.Fatalf("mode A, newest batch corrupt: err = %v, want wal_corrupt", err) + } + continue + } + if err != nil { + t.Fatalf("mode C, newest batch corrupt: err = %v, want the documented silent truncation", err) + } + if !bytes.Equal(readV3(t, r, 2), blk(2)) || bytes.Equal(readV3(t, r, 3), blk(3)) { + t.Fatal("mode C: want LSN 1-2 kept and the newest batch (3) truncated") + } + _ = r.Close() + } + // The second-newest batch is protected in both modes. + for _, mode := range []WMode{WModeLagged, WModeStrict} { + s, path := newStoreV3(t, mode) + writeSynced(t, s, 1, 3) + crashRecoveryHardeningStore(t, s) + damageRecord(t, path, 2) + if _, err := reopenV3(t, path); !isWALCorrupt(err) { + t.Fatalf("mode %d, second-newest batch corrupt: err = %v, want wal_corrupt", mode, err) + } + } +} + +func TestWALStoreV3RefreshAndSetWModeCloseTheWindow(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + writeSynced(t, s, 1, 3) + if err := s.refreshW(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + damageRecord(t, path, 3) + if _, err := reopenV3(t, path); !isWALCorrupt(err) { + t.Fatalf("after the idle refresh: err = %v, want wal_corrupt", err) + } + + s2, path2 := newStoreV3(t, WModeLagged) + writeSynced(t, s2, 1, 3) + if err := s2.SetWMode(WModeStrict); err != nil { + t.Fatal(err) + } + if s2.v3.pub.current().WMode != WModeStrict { + t.Fatal("SetWMode did not publish the new mode") + } + crashRecoveryHardeningStore(t, s2) + damageRecord(t, path2, 3) + if _, err := reopenV3(t, path2); !isWALCorrupt(err) { + t.Fatalf("after SetWMode(A): err = %v, want wal_corrupt (C -> A closes the window)", err) + } +} + +func TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt(t *testing.T) { + for _, mode := range []WMode{WModeLagged, WModeStrict} { + s, path := newStoreV3(t, mode) + writeSynced(t, s, 1, 3) + if _, err := s.Write(4, blk(4)); err != nil { // appended, never synced + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + damageRecord(t, path, 4) // a torn unsynced record + r, err := reopenV3(t, path) + if err != nil { + t.Fatalf("mode %d, torn unsynced tail: err = %v, want recovery", mode, err) + } + if !bytes.Equal(readV3(t, r, 3), blk(3)) || bytes.Equal(readV3(t, r, 4), blk(4)) { + t.Fatalf("mode %d: want 1-3 kept and the unsynced 4 dropped", mode) + } + _ = r.Close() + } +} + +// resurrectionSchedule is the G1 schedule (DESIGN 6.6): records dropped by +// one recovery must not resurface after a second crash. Without the fence, +// re-filling the gap with a record of the same size re-chains the old +// record behind it. +func resurrectionSchedule(t *testing.T, mode WMode, skipFence bool) (resurrected bool) { + t.Helper() + s, path := newStoreV3(t, mode) + writeSynced(t, s, 1, 3) + for _, lba := range []uint32{4, 5} { // unsynced + if _, err := s.Write(lba, blk(byte(lba))); err != nil { + t.Fatal(err) + } + } + crashRecoveryHardeningStore(t, s) + damageRecord(t, path, 4) // a torn LSN 4: recovery keeps 1-3 and drops the trusted 5 + testSkipFenceOnRecoverV3 = skipFence + r, err := reopenV3(t, path) + testSkipFenceOnRecoverV3 = false + if err != nil { + t.Fatal(err) + } + if bytes.Equal(readV3(t, r, 5), blk(5)) { + t.Fatal("first recovery kept LSN 5 above the gap") + } + if _, err := r.Write(9, blk(0x99)); err != nil { // re-fills LSN 4's place, same size + t.Fatal(err) + } + if _, err := r.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, r) + r2 := mustReopenV3(t, path) + defer r2.Close() + return bytes.Equal(readV3(t, r2, 5), blk(5)) +} + +func TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash(t *testing.T) { + for _, mode := range []WMode{WModeLagged, WModeStrict} { + if resurrectionSchedule(t, mode, false) { + t.Fatalf("mode %d: a record dropped by recovery resurfaced after the second crash (G1)", mode) + } + } +} + +func TestWALStoreV3NoFenceResurrectsInBothModes(t *testing.T) { + // The schedule is a real counterexample: with the fence skipped, the + // dropped record comes back. This keeps the G1 control discriminating. + for _, mode := range []WMode{WModeLagged, WModeStrict} { + if !resurrectionSchedule(t, mode, true) { + t.Fatalf("mode %d: the no-fence schedule did not resurrect; the G1 control is not discriminating", mode) + } + } +} + +func TestWALStoreV3FenceTouchesNoByteBeforeTheHead(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + writeSynced(t, s, 1, 3) + if _, err := s.Write(4, blk(4)); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + damageRecord(t, path, 4) + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + e := uint64(recordOffset(t, path, 3)) + walEntryHeaderSizeV3 + v3TestBlock // end of LSN 3 + r := mustReopenV3(t, path) + crashRecoveryHardeningStore(t, r) + after, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(before[walOffsetV3:e], after[walOffsetV3:e]) { + t.Fatal("the fence changed a byte before the recovered head E") + } + if !bytes.Equal(after[e:walOffsetV3+v3TestWAL], make([]byte, walOffsetV3+v3TestWAL-e)) { + t.Fatal("the fence left a nonzero byte in [E, floor+WALSize)") + } + if e%4096 == 0 { + t.Fatal("test setup: E is page-aligned; it should exercise an unaligned head") + } +} + +func TestWALStoreV3AppendWriteErrorLatchesTheStore(t *testing.T) { + s, _ := newStoreV3(t, WModeLagged) + defer s.Close() + writeSynced(t, s, 1, 1) + boom := errors.New("injected WAL pwrite error") + s.v3.w.writeAt = func([]byte, int64) (int, error) { return 0, boom } + if _, err := s.Write(2, blk(2)); !errors.Is(err, boom) { + t.Fatalf("append: err = %v, want the pwrite error", err) + } + if s.stickyIOFault() == nil { + t.Fatal("an append pwrite error did not latch the store-global fault") + } + if _, err := s.Sync(); err == nil { + t.Fatal("Sync acknowledged after an append write error") + } + if _, err := s.Write(3, blk(3)); err == nil { + t.Fatal("a later Write was admitted after an append write error") + } +} + +// Row 5b: the v3 store uses the real flusher. Its extent writes happen, +// but without the row-7 map candidate the checkpoint and tail do not move +// (no fabricated coverage), and the flushed records stay retained. +func TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap(t *testing.T) { + path := filepath.Join(t.TempDir(), "store.v3") + s, err := createWALStoreV3ForTest(path, 64, v3TestBlock, v3TestWAL, WModeLagged) + if err != nil { + t.Fatal(err) + } + writeSynced(t, s, 1, 3) + before := s.v3.pub.current() + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + after := s.v3.pub.current() + if after.CheckpointLSN != before.CheckpointLSN || after.RetainedTail != before.RetainedTail || s.CheckpointLSN() != 0 { + t.Fatalf("checkpoint/tail advanced without a map candidate: %d/%d -> %d/%d", + before.CheckpointLSN, before.RetainedTail, after.CheckpointLSN, after.RetainedTail) + } + // Uncovered dirty entries now remain retry work. Check the extent + // explicitly, so a WAL-first Read cannot mask a missing extent write. + // The data also survives a crash through the still-retained WAL. + for lba := uint32(1); lba <= 3; lba++ { + extent, err := s.readFromExtent(lba) + if err != nil || !bytes.Equal(extent, blk(byte(lba))) { + t.Fatalf("LBA %d not materialized in the extent: %v", lba, err) + } + if !bytes.Equal(readV3(t, s, lba), blk(byte(lba))) { + t.Fatalf("LBA %d unreadable after the v3 flush", lba) + } + } + crashRecoveryHardeningStore(t, s) + r := mustReopenV3(t, path) + defer r.Close() + for lba := uint32(1); lba <= 3; lba++ { + if !bytes.Equal(readV3(t, r, lba), blk(byte(lba))) { + t.Fatalf("LBA %d lost after flush and crash", lba) + } + } +} + +func TestWALStoreV3RefusesPathsOfLaterRows(t *testing.T) { + s, _ := newStoreV3(t, WModeLagged) + defer s.Close() + // WriteBatch is supported since the v3 batch slice (TestWALStoreV3Batch*). + // ApplyEntry is supported since the v3 replicated-apply slice + // (TestWALStoreV3ReplicatedApply*). + if err := s.WriteExtentDirect(0, blk(1)); !errors.Is(err, errV3NotYet) { + t.Fatalf("WriteExtentDirect: err = %v, want errV3NotYet", err) + } +} + +// codex01 row 5 P1-1: a batch's acknowledgement rechecks the store fault +// under the store lock. Schedule, in both modes: batch A's slot write is +// parked (A holds descMu); B's Write, already past capacity admission, +// takes s.mu exclusively and waits on descMu in the writer's snapshot; +// A is released, B's pwrite fails and latches while B +// still holds s.mu; A must then refuse without advancing the acknowledged W. +func TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary(t *testing.T) { + for _, mode := range []WMode{WModeLagged, WModeStrict} { + s, _ := newStoreV3(t, mode) + writeSynced(t, s, 1, 1) + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + prev := s.v3.wack.Load() + parked, release := make(chan struct{}), make(chan struct{}) + rel := sync.OnceFunc(func() { close(release) }) + t.Cleanup(rel) + var once sync.Once + s.v3.testBeforeSlotWrite = func() error { + once.Do(func() { close(parked); <-release }) + return nil + } + // Finish B's admission before A parks descMu. Native capacity sampling + // itself may briefly hold s.mu shared; that is not the append boundary. + admitted, appendB := make(chan struct{}), make(chan struct{}) + resumeB := sync.OnceFunc(func() { close(appendB) }) + t.Cleanup(resumeB) + s.testAfterAdmit = func() { close(admitted); <-appendB } + boom := errors.New("injected append write error") + s.v3.w.writeAt = func([]byte, int64) (int, error) { return 0, boom } + bErr := make(chan error, 1) + go func() { _, err := s.Write(3, blk(3)); bErr <- err }() + waitV3(t, admitted, "B after capacity admission") + aErr := make(chan error, 1) + go func() { _, err := s.Sync(); aErr <- err }() + waitV3(t, parked, "the parked publication") + resumeB() + deadline := time.Now().Add(10 * time.Second) + for s.mu.TryRLock() { // only an exclusive append owner defeats TryRLock + s.mu.RUnlock() + if time.Now().After(deadline) { + t.Fatal("timed out waiting for B to take s.mu") + } + runtime.Gosched() + } + rel() + if err := recvErrV3(t, bErr, "B"); !errors.Is(err, boom) { + t.Fatalf("mode %d: B: err = %v, want the append write error", mode, err) + } + if err := recvErrV3(t, aErr, "A"); err == nil { + t.Fatalf("mode %d: A acknowledged after B latched the store fault", mode) + } + if got := s.v3.wack.Load(); got != prev { + t.Fatalf("mode %d: acknowledged W advanced to %d after the fault (want %d)", mode, got, prev) + } + crashRecoveryHardeningStore(t, s) + } +} + +// codex01 row 5 P2: a history ending at the last representable cursor +// recovers; only further appends are refused. +func TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor(t *testing.T) { + const recSize = uint64(walEntryHeaderSizeV3 + v3TestBlock) + cursor := counterMaxV3 - 3*recSize // 3 records end exactly at 2^64-2, no ring-end crossing + path := filepath.Join(t.TempDir(), "store.v3") + s, err := createWALStoreV3AtCursorForTest(path, 64, v3TestBlock, v3TestWAL, WModeStrict, cursor) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + writeSynced(t, s, 1, 3) + if _, err := s.Write(4, blk(4)); !errors.Is(err, ErrCounterExhausted) { + t.Fatalf("append past the last cursor: err = %v, want ErrCounterExhausted", err) + } + crashRecoveryHardeningStore(t, s) + r := mustReopenV3(t, path) + defer r.Close() + for lba := uint32(1); lba <= 3; lba++ { + if !bytes.Equal(readV3(t, r, lba), blk(byte(lba))) { + t.Fatalf("LBA %d of the terminal history lost", lba) + } + } + if _, err := r.Write(5, blk(5)); !errors.Is(err, ErrCounterExhausted) { + t.Fatalf("append after recovery at the last cursor: err = %v, want ErrCounterExhausted", err) + } +} + +// codex01 row 5 P2 (SetWMode evidence): a held mode-C batch completes and +// acknowledges under C before SetWMode(A) publishes the new mode. +func TestWALStoreV3SetWModeWaitsForAHeldBatch(t *testing.T) { + s, _ := newStoreV3(t, WModeLagged) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 1) + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + parked, release := make(chan struct{}), make(chan struct{}) + rel := sync.OnceFunc(func() { close(release) }) + t.Cleanup(rel) + var once sync.Once + s.v3.testBeforeSlotWrite = func() error { + once.Do(func() { close(parked); <-release }) + return nil + } + aErr := make(chan error, 1) + go func() { _, err := s.Sync(); aErr <- err }() + waitV3(t, parked, "the parked publication") + setErr := make(chan error, 1) + go func() { setErr <- s.SetWMode(WModeStrict) }() + select { + case err := <-setErr: + t.Fatalf("SetWMode returned (%v) while a C batch was held", err) + default: + } + rel() + if err := recvErrV3(t, aErr, "A"); err != nil { + t.Fatal(err) + } + if err := recvErrV3(t, setErr, "SetWMode"); err != nil { + t.Fatal(err) + } + cur := s.v3.pub.current() + if cur.WMode != WModeStrict || cur.W != 2 { + t.Fatalf("after SetWMode: mode %d W %d, want A and W 2", cur.WMode, cur.W) + } + // The held batch's own publication (now the fallback slot) was mode C + // with the lagged W 1. + if fb := s.v3.pub.other; fb.WMode != WModeLagged || fb.W != 1 || fb.SlotGen != cur.SlotGen-1 { + t.Fatalf("held batch publication: mode %d W %d gen %d, want C, W 1, gen %d", fb.WMode, fb.W, fb.SlotGen, cur.SlotGen-1) + } +} + +// No batch acknowledges under a stale mode: a batch that reaches the +// leader role while SetWMode(A) holds it publishes with A's rule (W = H) +// once SetWMode has committed. +func TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode(t *testing.T) { + s, _ := newStoreV3(t, WModeLagged) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 1) + parked, release := make(chan struct{}), make(chan struct{}) + rel := sync.OnceFunc(func() { close(release) }) + t.Cleanup(rel) + s.v3.testSetWModeHoldingRole = func() { close(parked); <-release } + setErr := make(chan error, 1) + go func() { setErr <- s.SetWMode(WModeStrict) }() // parks holding the leader role, before publishing + waitV3(t, parked, "the parked publication") + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + waiting := make(chan struct{}) + var wonce sync.Once + s.v3.testLeaderWaiting = func() { wonce.Do(func() { close(waiting) }) } + bErr := make(chan error, 1) + go func() { _, err := s.Sync(); bErr <- err }() + waitV3(t, waiting, "B at the leader role") // B is about to take the leader role SetWMode holds + rel() + if err := recvErrV3(t, setErr, "SetWMode"); err != nil { + t.Fatal(err) + } + if err := recvErrV3(t, bErr, "B"); err != nil { + t.Fatal(err) + } + if cur := s.v3.pub.current(); cur.WMode != WModeStrict || cur.W != 2 { + t.Fatalf("batch after SetWMode(A): mode %d slot W %d, want A with W = H = 2 (a stale C ack would leave W 1)", cur.WMode, cur.W) + } +} + +// SetWMode crash cases: a committed mode survives a crash; a failed mode +// publication leaves the old mode on disk and latches the store. +func TestWALStoreV3SetWModeCrashCases(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + writeSynced(t, s, 1, 2) + if err := s.SetWMode(WModeStrict); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + r := mustReopenV3(t, path) + if m := r.v3.pub.current().WMode; m != WModeStrict { + t.Fatalf("committed SetWMode lost across a crash: mode %d", m) + } + crashRecoveryHardeningStore(t, r) + + s2, path2 := newStoreV3(t, WModeLagged) + writeSynced(t, s2, 1, 2) + boom := errors.New("injected mode slot write error") + s2.v3.testBeforeSlotWrite = func() error { return boom } + if err := s2.SetWMode(WModeStrict); !errors.Is(err, boom) { + t.Fatalf("SetWMode with a failing slot write: err = %v, want the write error", err) + } + if s2.stickyIOFault() == nil { + t.Fatal("a failed mode publication did not latch the store") + } + crashRecoveryHardeningStore(t, s2) + r2 := mustReopenV3(t, path2) + defer r2.Close() + if m := r2.v3.pub.current().WMode; m != WModeLagged { + t.Fatalf("a failed SetWMode changed the mode on disk: %d", m) + } +} + +func waitV3(t *testing.T, ch <-chan struct{}, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(10 * time.Second): + t.Fatalf("timed out waiting for %s", what) + } +} + +func recvErrV3(t *testing.T, ch <-chan error, what string) error { + t.Helper() + select { + case err := <-ch: + return err + case <-time.After(10 * time.Second): + t.Fatalf("timed out waiting for %s", what) + return nil + } +} + +// codex01 5b P1: a SAME-instance recovery that drops mode C's newest batch +// resets the acknowledged frontier to R, so a later refresh cannot publish +// a W the WAL no longer holds and the next Recover does not report a false +// corruption. Fresh-open tests mask this (they start from the slot W). +func TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + defer crashRecoveryHardeningStore(t, s) + writeSynced(t, s, 1, 2) // slot W 1 (lagged), acknowledged W 2 + damageRecord(t, path, 2) + rec1 := recordOffset(t, path, 1) + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatalf("same-open Recover with the newest C batch damaged: %v (want the documented truncation)", err) + } + if got := s.v3.wack.Load(); got != 1 { + t.Fatalf("acknowledged W after the same-open recovery = %d, want R = 1", got) + } + if err := s.refreshW(); err != nil { + t.Fatal(err) + } + if w := s.v3.pub.current().W; w > 1 { + t.Fatalf("refresh published W %d over a recovered prefix of 1", w) + } + if _, err := s.Recover(); err != nil { + t.Fatalf("second same-open Recover: %v (a false wal_corrupt from a stale W)", err) + } + after, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + end1 := rec1 + int64(walEntryHeaderSizeV3+v3TestBlock) + if !bytes.Equal(before[rec1:end1], after[rec1:end1]) { + t.Fatal("the kept record 1 changed") + } + if !bytes.Equal(after[end1:walOffsetV3+v3TestWAL], make([]byte, walOffsetV3+v3TestWAL-int(end1))) { + t.Fatal("the dropped record 2 was not fenced") + } + if !bytes.Equal(readV3(t, s, 1), blk(1)) { + t.Fatal("LBA 1 lost") + } +} + +// codex01 5b P2: a scan failure under an installing descriptor keeps the +// typed not-ready outcome and leaves the file unchanged. +func TestWALStoreV3InstallingScanErrorIsTypedNotReady(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + if _, err := s.v3.pub.publish(nil, nil, func(n *descriptorV3) error { + n.BaseState, n.BaseLSN = BaseInstalling, 0 + n.BaseCursor = n.RetainedHead + n.BaseInstallID[0] = 7 + return nil + }); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + if err := os.Truncate(path, walOffsetV3+100); err != nil { // the WAL region is now short + t.Fatal(err) + } + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + _, err = reopenV3(t, path) + if !errors.Is(err, ErrBaseIncomplete) || errors.Is(err, ErrInstallSuffixDamaged) { + t.Fatalf("installing scan error: err = %v, want ErrBaseIncomplete (not labelled damaged)", err) + } + after, err2 := os.ReadFile(path) + if err2 != nil { + t.Fatal(err2) + } + if !bytes.Equal(before, after) { + t.Fatal("a refused installing recovery changed the file") + } +} + +// codex01 5b P2: the real flusher cycle performs the mode-C idle refresh, +// also when no dirty entries remain, so the window closes without a Sync. +func TestWALStoreV3FlusherCycleRunsTheIdleRefresh(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + writeSynced(t, s, 1, 3) // slot W 2 (lagged), acknowledged W 3 + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + if w := s.v3.pub.current().W; w != 3 { + t.Fatalf("slot W after a flusher cycle = %d, want 3 (the idle refresh)", w) + } + if err := s.flusher.flushOnceInternal(false); err != nil { // now no dirty entries + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + damageRecord(t, path, 3) + if _, err := reopenV3(t, path); !isWALCorrupt(err) { + t.Fatalf("after the flusher's refresh: err = %v, want wal_corrupt", err) + } +} + +// heldV3 owns a parked hook and the workers a held control starts. Its +// cleanup, registered before any worker starts and after the store crash +// cleanup, first releases the hold, then joins every worker with a bound, +// so an early Fatal never strands store shutdown (codex01 row 5d P2). +type heldV3 struct { + t *testing.T + parked chan struct{} + release chan struct{} + rel func() + once sync.Once + workers []chan error +} + +func newHeldV3(t *testing.T) *heldV3 { + h := &heldV3{t: t, parked: make(chan struct{}), release: make(chan struct{})} + h.rel = sync.OnceFunc(func() { close(h.release) }) + t.Cleanup(func() { + h.rel() + for _, w := range h.workers { + select { + case <-w: + case <-time.After(10 * time.Second): + t.Errorf("a held worker did not finish within 10s") + } + } + }) + return h +} + +// hold parks the caller the first time it runs. +func (h *heldV3) hold() { h.once.Do(func() { close(h.parked); <-h.release }) } + +// start runs f on a worker whose result is joined at cleanup. +func (h *heldV3) start(f func() error) chan error { + c := make(chan error, 1) + h.workers = append(h.workers, c) + go func() { c <- f() }() + return c +} + +// result takes a worker's result with a bound, and leaves a copy so the +// cleanup join does not wait on a consumed channel. +func (h *heldV3) result(c chan error, what string) error { + h.t.Helper() + err := recvErrV3(h.t, c, what) + c <- err + return err +} + +// notDoneV3 asserts a worker is still waiting on the leader role. It waits +// up to 300ms for the worker to (wrongly) finish: the wait only gives a +// broken implementation time to show itself, so a mutant that lets the +// worker run is caught reliably; a correct implementation passes whatever +// the timing. +func notDoneV3(t *testing.T, c chan error, what string) { + t.Helper() + select { + case err := <-c: + c <- err + t.Fatalf("%s returned (%v) while it should be waiting on the leader role", what, err) + case <-time.After(300 * time.Millisecond): + } +} + +// codex01 row 5d schedule A: a refresh attempted DURING a same-open +// recovery waits for it (Recover holds the leader role), then sees the +// recovered frontier and publishes nothing. +func TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + h := newHeldV3(t) + writeSynced(t, s, 1, 2) // slot W 1 (lagged), acknowledged W 2 + damageRecord(t, path, 2) + s.v3.testRecoverHold = h.hold + rec := h.start(func() error { _, err := s.Recover(); return err }) + waitV3(t, h.parked, "Recover after its decision") + ref := h.start(s.refreshW) + notDoneV3(t, ref, "refreshW") + h.rel() + if err := h.result(rec, "Recover"); err != nil { + t.Fatalf("Recover: %v", err) + } + if err := h.result(ref, "refreshW"); err != nil { + t.Fatalf("refreshW: %v", err) + } + if w := s.v3.pub.current().W; w > 1 { + t.Fatalf("a refresh during recovery published W %d over the recovered prefix 1", w) + } + if _, err := s.Recover(); err != nil { + t.Fatalf("next Recover: %v (a false wal_corrupt)", err) + } +} + +// codex01 row 5d schedule B: a recovery attempted while a C batch is parked +// after its publication and before its acknowledgement waits for the batch; +// the recovery then lowers the frontier and nothing revives the dropped cut. +func TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + h := newHeldV3(t) + writeSynced(t, s, 1, 1) + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + s.v3.testBatchBeforeAck = h.hold + syn := h.start(func() error { _, err := s.Sync(); return err }) + waitV3(t, h.parked, "the batch before its acknowledgement") + s.v3.testBatchBeforeAck = nil + damageRecord(t, path, 2) + rec := h.start(func() error { _, err := s.Recover(); return err }) + notDoneV3(t, rec, "Recover") + h.rel() + // The batch acknowledged before the recovery. The outer Sync either + // completed before the recovery took the leader role, or found the + // recovery generation moved and refused its ack: both are correct. + if err := h.result(syn, "Sync"); err != nil && !errors.Is(err, errV3RecoveredMeanwhile) { + t.Fatalf("Sync: %v", err) + } + if err := h.result(rec, "Recover"); err != nil { + t.Fatalf("Recover: %v", err) + } + if got := s.v3.wack.Load(); got != 1 { + t.Fatalf("acknowledged W after the recovery = %d, want R = 1 (the dropped cut revived)", got) + } + if err := s.refreshW(); err != nil { + t.Fatal(err) + } + if w := s.v3.pub.current().W; w > 1 { + t.Fatalf("W %d covers the fenced suffix", w) + } + if _, err := s.Recover(); err != nil { + t.Fatalf("next Recover: %v (a false wal_corrupt)", err) + } +} + +// codex01 row 5d: the outer Sync() completion is validated against the +// recovery generation. A Sync whose batch finished, then waits while a +// recovery drops its cut, must not acknowledge it; a fresh Sync after the +// recovery acknowledges normally. +func TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + h := newHeldV3(t) + writeSynced(t, s, 1, 1) + if _, err := s.Write(2, blk(2)); err != nil { + t.Fatal(err) + } + s.v3.testSyncBeforeCompletion = h.hold + syn := h.start(func() error { _, err := s.Sync(); return err }) + waitV3(t, h.parked, "the outer Sync before its completion") + s.v3.testSyncBeforeCompletion = nil + damageRecord(t, path, 2) + if _, err := s.Recover(); err != nil { + t.Fatalf("Recover: %v", err) + } + h.rel() + if err := h.result(syn, "Sync"); !errors.Is(err, errV3RecoveredMeanwhile) { + t.Fatalf("outer Sync across a recovery: err = %v, want errV3RecoveredMeanwhile", err) + } + if R, _, _ := s.Boundaries(); R > 1 { + t.Fatalf("synced frontier %d revived past the recovered prefix 1", R) + } + // Fresh lifetime: a new write and Sync after the recovery acknowledge. + if _, err := s.Write(3, blk(3)); err != nil { + t.Fatal(err) + } + if lsn, err := s.Sync(); err != nil || lsn < 2 { + t.Fatalf("fresh Sync after the recovery: %d, %v", lsn, err) + } +} + +// codex01 row 5c P2: the empty-dirty-set branch of the flusher cycle runs the +// idle refresh on its own (discriminated separately from the flush branch). +func TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh(t *testing.T) { + s, _ := newStoreV3(t, WModeLagged) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 2) // slot W 1 (lagged), acknowledged W 2 + s.dm.clear() // nothing dirty: the cycle takes the empty branch + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + if w := s.v3.pub.current().W; w != 2 { + t.Fatalf("slot W after an empty flusher cycle = %d, want 2 (the idle refresh)", w) + } +} + +// stubMapCandidateV3 is a test map candidate that covers exactly the +// checkpoint it is asked for (row 7 supplies the real one). +func stubMapCandidateV3(cp uint64) (func(n *descriptorV3) error, error) { + return func(n *descriptorV3) error { + n.MapGeneration++ + n.MapRootHash[0]++ + n.MapCoveredCheckpoint = cp + return nil + }, nil +} + +// A v3 checkpoint never exceeds the acknowledged W (DESIGN 2.2, 9.1): the +// flusher may flush a dirty entry no Sync has acknowledged, and its +// checkpoint candidate is clamped to W; the unsynced record stays retained +// in the WAL and survives a crash. +func TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + var crashOnce sync.Once + crash := func() { crashOnce.Do(func() { crashRecoveryHardeningStore(t, s) }) } + t.Cleanup(crash) + m, err := createChunkLSNMapV3(path+".chunkmap", s.v3.pub.current(), 1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.Close() }) + entries := make([]chunkLSNEntryV3, s.NumBlocks()) + for i := range entries { + entries[i].Unknown = true + } + initial, err := m.Prepare(s.v3.pub.current().MapGeneration+1, 0, entries, nil) + if err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publish(&s.mu, nil, func(d *descriptorV3) error { *d = initial.descriptor(*d); return nil }); err != nil { + t.Fatal(err) + } + if _, err = s.v3.pub.publish(&s.mu, nil, nil); err != nil { + t.Fatal(err) + } + s.v3.mapCandidate = func(cp uint64) (func(*descriptorV3) error, error) { + c, e := m.Prepare(s.v3.pub.current().MapGeneration+1, cp, entries, nil) + if e != nil { + return nil, e + } + return func(d *descriptorV3) error { *d = c.descriptor(*d); return nil }, nil + } + writeSynced(t, s, 1, 1) // acknowledged W 1 + if _, err := s.Write(2, blk(2)); err != nil { // dirty, unsynced + t.Fatal(err) + } + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatalf("flusher cycle: %v (a checkpoint above W is refused at publication)", err) + } + d := s.v3.pub.current() + if d.CheckpointLSN != 1 || d.MapCoveredCheckpoint != 1 || d.W < 1 { + t.Fatalf("checkpoint %d, covered %d, W %d: want the checkpoint clamped to the acknowledged W 1", + d.CheckpointLSN, d.MapCoveredCheckpoint, d.W) + } + if d.RetainedTail != 0 { + t.Fatalf("retainedTail %d: the unsynced record must stay retained", d.RetainedTail) + } + crash() + r := mustReopenV3(t, path) + defer r.Close() + for lba := uint32(1); lba <= 2; lba++ { + if !bytes.Equal(readV3(t, r, lba), blk(byte(lba))) { + t.Fatalf("LBA %d lost after a clamped checkpoint and a crash", lba) + } + } +} diff --git a/seaweed-block/core/storage/walstore_v3_wrap_test.go b/seaweed-block/core/storage/walstore_v3_wrap_test.go new file mode 100644 index 0000000000..61bc7f965c --- /dev/null +++ b/seaweed-block/core/storage/walstore_v3_wrap_test.go @@ -0,0 +1,114 @@ +package storage + +import ( + "bytes" + "errors" + "os" + "testing" +) + +// The forged-replay finding (docs/spec/README.md, open item 2) end to end on +// a mapped v3 WALStore (the production layout). A guest batch in lap 1 carries, in its payload, a +// well-formed v3 record bound to this volume's own nonce (LSN 999, LBA 7) at +// the cursor its bytes occupy in lap 1. The WAL then wraps: one newer record +// overwrites only the start of the batch, so the scan of lap 2 resumes +// exactly at the embedded record's first byte. The cursor binding (lap +// included) must stop the scan there: after a crash and reopen, LBA 7 is +// never the forged data and the recovered frontier is the newest real write, +// never 999. +func TestWALStoreV3StaleLapBytesAtTheWrapAreNotReplayed(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(0) // a checkpoint releases everything it covers + d := s.v3.pub.current() + rec := uint64(walEntryHeaderSizeV3 + v3TestBlock) // one single-block record + if d.WALSize != v3TestWAL || d.RetainedHead != 0 || d.RetainedTail != 0 { + t.Fatalf("fixture: WAL %d, head %d, tail %d", d.WALSize, d.RetainedHead, d.RetainedTail) + } + + // Lap 1, cursor 0: the batch. Its payload follows the record prefix, so a + // single record written at the wrap ends at cursor rec, inside it. + forged, err := encodeWALEntryV3(walEntryV3{LSN: 999, Type: walEntryWrite, LBA: 7, Length: v3TestBlock, + Data: blk(0xF0), LogicalStart: rec, Nonce: d.Nonce}, d.BlockSize, d.VolumeSize/uint64(d.BlockSize)) + if err != nil { + t.Fatal(err) + } + payload := make([]byte, 3*v3TestBlock) + copy(payload, blk(0x11)) + copy(payload[rec-walEntryPrefixSizeV3:], forged) + if _, err := s.WriteBatch(8, [][]byte{payload[:v3TestBlock], payload[v3TestBlock : 2*v3TestBlock], payload[2*v3TestBlock:]}); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if off := recordOffset(t, path, 1); off != int64(d.WALOffset) { + t.Fatalf("batch at file offset %d, want the WAL start %d", off, d.WALOffset) + } + + // Fill lap 1 until the next record cannot fit before the lap end, then let + // the flusher checkpoint everything so the tail releases the batch. + batch := uint64(walEntryHeaderSizeV3 + 3*v3TestBlock) + singles := (d.WALSize - batch) / rec // the last one still fits in lap 1 + writeSynced(t, s, 20, 20+uint32(singles)-1) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + head := batch + singles*rec + if cur := s.v3.pub.current(); cur.RetainedTail != head || cur.CheckpointLSN != 3+singles { + t.Fatalf("after the flusher: tail %d, checkpoint %d; want %d, %d", cur.RetainedTail, cur.CheckpointLSN, head, 3+singles) + } + + // The wrap: one newer record lands at cursor WALSize (file offset 0 of the + // WAL), over the batch's header and first block. + newest := uint32(20 + singles) + if _, err := s.Write(newest, blk(0x5A)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + lastLSN := 3 + singles + 1 + if off := recordOffset(t, path, lastLSN); off != int64(d.WALOffset) { + t.Fatalf("wrapped record at file offset %d, want the WAL start %d", off, d.WALOffset) + } + + // The scan reaches the forged bytes and stops on the binding there. + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + r, err := scanWALV3(f, s.v3.pub.current()) + f.Close() + if err != nil { + t.Fatal(err) + } + if r.End != d.WALSize+rec || !errors.Is(r.StopCause, errWALBindingV3) { + t.Fatalf("scan end %d, stop %v; want %d and the binding refusal at the forged record", r.End, r.StopCause, d.WALSize+rec) + } + for _, x := range r.Records { + if x.Entry.LSN == 999 { + t.Fatalf("forged record admitted by the scan: %+v", x.Entry) + } + } + + crashRecoveryHardeningStore(t, s) + o, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + o.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { crashRecoveryHardeningStore(t, o) }) + frontier, err := o.Recover() + if err != nil { + t.Fatal(err) + } + if frontier != lastLSN { + t.Fatalf("recovered frontier %d, want the newest real write %d (never 999)", frontier, lastLSN) + } + if got := readV3(t, o, 7); bytes.Equal(got, blk(0xF0)) || !bytes.Equal(got, make([]byte, v3TestBlock)) { + t.Fatalf("LBA 7 reads %x..., want never written (the forged record replayed?)", got[:8]) + } + if !bytes.Equal(readV3(t, o, newest), blk(0x5A)) || !bytes.Equal(readV3(t, o, 8), blk(0x11)) { + t.Fatal("a real write was lost") + } +} diff --git a/seaweed-block/core/storage/write_budget_rollover_controls_test.go b/seaweed-block/core/storage/write_budget_rollover_controls_test.go new file mode 100644 index 0000000000..19e56c13a7 --- /dev/null +++ b/seaweed-block/core/storage/write_budget_rollover_controls_test.go @@ -0,0 +1,157 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" +) + +// A completed metadata rollover is retained, but it does not authorize new +// payload I/O after the command's original admission deadline. +func TestWALStoreV3WriteBudgetRechecksAfterRollover(t *testing.T) { + for _, batch := range []bool{false, true} { + for _, outcome := range []string{"expired", "healthy", "fault"} { + t.Run(fmt.Sprintf("batch=%t/%s", batch, outcome), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(2) + writeSynced(t, s, 0, 1) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + s.SetRecoveryRetentionLSNs(1) + tail := s.v3.w.reclaimThroughV3(d.CheckpointLSN - 1) + if _, err := s.v3.pub.publish(nil, nil, func(n *descriptorV3) error { + n.RetainedTail = tail + n.RetainedHead = max(n.RetainedHead, tail) + return nil + }); err != nil { + t.Fatal(err) + } + if floor, ok := s.v3.pub.reuseFloor(); !ok || floor >= tail { + t.Fatal("no pinned fallback") + } + wait := 100 * time.Millisecond + if outcome == "healthy" { + wait = 5 * time.Second + } + ctx, cancel := context.WithTimeout(context.Background(), wait) + defer cancel() + boom := errors.New("rollover slot fault") + writeSlot := s.v3.pub.io.writeSlot + calls := 0 + s.v3.pub.io.writeSlot = func(off int64, b []byte) error { + calls++ + if outcome != "healthy" { + <-ctx.Done() + } + if outcome == "fault" { + return boom + } + return writeSlot(off, b) + } + defer func() { s.v3.pub.io.writeSlot = writeSlot }() + head, next, dirty := s.v3.w.logicalHeadV3(), s.NextLSN(), s.dm.len() + gen := s.v3.pub.current().SlotGen + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 2, [][]byte{blk(3), blk(4)}) + } else { + _, err = s.WriteContext(ctx, 2, blk(3)) + } + if calls != 1 { + t.Fatalf("rollover calls=%d err=%v", calls, err) + } + if outcome == "healthy" { + if err != nil || s.NextLSN() <= next { + t.Fatalf("healthy write: %v", err) + } + return + } + if s.NextLSN() != next || s.v3.w.logicalHeadV3() != head || s.dm.len() != dirty { + t.Fatal("refused command started payload I/O") + } + if outcome == "fault" { + if !errors.Is(err, boom) || s.stickyIOFault() == nil { + t.Fatalf("terminal fault masked: %v", err) + } + return + } + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatalf("expired command: %v", err) + } + if s.v3.pub.current().SlotGen <= gen { + t.Fatal("completed rollover was rolled back") + } + if floor, ok := s.v3.pub.reuseFloor(); !ok || floor != tail { + t.Fatalf("completed rollover not retained: %d %v", floor, ok) + } + }) + } + } +} + +type budgetCaptureWaitContext struct { + context.Context + parked chan struct{} + once sync.Once +} + +func (c *budgetCaptureWaitContext) Done() <-chan struct{} { + c.once.Do(func() { close(c.parked) }) + return c.Context.Done() +} +func TestWALStoreV3LocalBudgetIncludesWitnessedCaptureWait(t *testing.T) { + for _, batch := range []bool{false, true} { + t.Run(fmt.Sprint(batch), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.admissionTimeout = 40 * time.Millisecond + ctx := &budgetCaptureWaitContext{Context: context.Background(), parked: make(chan struct{})} + s.captureMu.Lock() + locked := true + done := make(chan error, 1) + defer func() { + if locked { + s.captureMu.Unlock() + } + select { + case <-done: + case <-time.After(time.Second): + t.Error("writer failed to join after release") + } + }() + go func() { + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 0, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.WriteContext(ctx, 0, blk(1)) + } + done <- err + }() + select { + case <-ctx.parked: + case <-time.After(time.Second): + t.Fatal("capture waiter was not witnessed") + } + select { + case err := <-done: + done <- err + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatal(err) + } + case <-time.After(time.Second): + t.Fatal("local budget restarted behind capture lock") + } + s.captureMu.Unlock() + locked = false + if s.NextLSN() != 1 || s.dm.len() != 0 { + t.Fatal("expired local waiter mutated") + } + }) + } +} diff --git a/seaweed-block/core/storage/write_command_budget.go b/seaweed-block/core/storage/write_command_budget.go new file mode 100644 index 0000000000..58dedfb926 --- /dev/null +++ b/seaweed-block/core/storage/write_command_budget.go @@ -0,0 +1,109 @@ +package storage + +import ( + "context" + "time" +) + +// Compute once, before capture/COW/lifecycle admission. Keep append/completion +// headroom instead of spending the entire command budget in WAL admission. +// This is cooperative: it cannot interrupt a mutex or physical I/O in progress. +func (s *WALStore) writeAdmissionDeadline(ctx context.Context) time.Time { + now := time.Now() + deadline, hasDeadline := ctx.Deadline() + if s.v3 != nil { + local := now.Add(s.admissionTimeout) + if !hasDeadline || local.Before(deadline) { + deadline = local + } + reserve := min(time.Second, max(time.Duration(0), deadline.Sub(now)/4)) + return deadline.Add(-reserve) + } + if hasDeadline { + return deadline + } + return time.Time{} // preserve legacy admission policy +} + +func (s *WALStore) writeBudgetError(ctx context.Context, deadline time.Time) error { + if err := s.stickyIOFault(); err != nil { + return err + } + if ctx.Err() == context.Canceled { + return context.Canceled + } + if !deadline.IsZero() && !time.Now().Before(deadline) { + return ErrWALPressureTimeout + } + return nil +} + +// A parked command owns no new physical I/O. Stop waiting for the long +// admission locks (captureMu, lifecycleMu: held across a capture barrier or a +// lifecycle transition) on expiry, without a helper goroutine that could +// acquire them after return. Short locks (s.mu, descMu, writer.mu) are taken +// blocking, so they keep RWMutex writer preference (#252). +func (s *WALStore) acquireWriteLock(ctx context.Context, deadline time.Time, try func() bool, lock func()) error { + if deadline.IsZero() && ctx.Done() == nil { + lock() + return nil + } + if err := s.writeBudgetError(ctx, deadline); err != nil { + return err + } + if try() { + return nil + } + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for { + if err := s.writeBudgetError(ctx, deadline); err != nil { + return err + } + if try() { + return nil + } + select { + case <-ctx.Done(): + return s.writeBudgetError(ctx, deadline) + case <-tick.C: + } + } +} + +// The legacy controller's callbacks take blocking locks. A v3 guest write +// samples the same descriptor/floor/writer tuple with its command deadline; +// failure to acquire a lock refuses admission, never grants capacity or reuse. +func (s *WALStore) writePressureSample(ctx context.Context, deadline time.Time) func() (float64, error) { + if s.v3 == nil { + return nil + } + return func() (float64, error) { + // Short locks block (RWMutex writer preference, #252); the budget is + // checked once they are held. + s.mu.RLock() + defer s.mu.RUnlock() + if err := s.writeBudgetError(ctx, deadline); err != nil { + return 0, err + } + if s.closed { + return 0, errVolumeClosed + } + v := s.v3 + w := v.w + if w == nil { + return 0, nil + } // append still refuses the missing binding + p := v.pub + p.descMu.Lock() + floor, valid := p.reuseFloorLocked() + d := p.cur + p.descMu.Unlock() // preserve snapshot ordering: no descriptor -> writer edge + w.mu.Lock() + defer w.mu.Unlock() + if !valid || d.WALSize == 0 || d.Nonce != w.nonce || w.head < floor || w.head-floor > d.WALSize { + return 0, nil + } + return float64(w.head-floor) / float64(d.WALSize), nil + } +} diff --git a/seaweed-block/core/storage/write_command_budget_p1_test.go b/seaweed-block/core/storage/write_command_budget_p1_test.go new file mode 100644 index 0000000000..e670a2652d --- /dev/null +++ b/seaweed-block/core/storage/write_command_budget_p1_test.go @@ -0,0 +1,226 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" +) + +// #252 P1-1: an expired command never starts NEW payload WAL I/O. The rollover +// (its metadata I/O completes and stays owned) is held until the command has +// expired; the write must then refuse before the payload append: writer head, +// next LSN and dirty map unchanged, the block still reads its old bytes. +func TestWALStoreV3WriteBudgetRefusesNewPayloadAfterRollover(t *testing.T) { + for _, batch := range []bool{false, true} { + name := map[bool]string{false: "single", true: "batch"}[batch] + t.Run(name, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + ctx, cancel := context.WithTimeout(context.Background(), 400*time.Millisecond) + defer cancel() + held := make(chan struct{}) + s.v3.testAfterRollover = func() { close(held); <-ctx.Done() } + head, next, dirty := s.v3.w.head, s.NextLSN(), s.dm.len() + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 0, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.WriteContext(ctx, 0, blk(1)) + } + select { + case <-held: + default: + t.Fatal("the write never reached the post-rollover point") + } + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatalf("expired command after rollover: %v", err) + } + if s.v3.w.head != head || s.NextLSN() != next || s.dm.len() != dirty { + t.Fatalf("expired command started payload WAL I/O: head %d->%d next %d->%d dirty %d->%d", + head, s.v3.w.head, next, s.NextLSN(), dirty, s.dm.len()) + } + s.v3.testAfterRollover = nil + if got, err := s.Read(0); err != nil || bytes.Equal(got, blk(1)) { + t.Fatalf("refused write visible: %v", err) + } + if _, err := s.WriteContext(context.Background(), 0, blk(3)); err != nil { + t.Fatalf("a fresh write after the refusal: %v", err) + } + }) + } +} + +// #252 P1-2: short locks keep RWMutex writer preference. Continuous overlapping +// readers must not starve a healthy-capacity write into a busy expiry. +func TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders(t *testing.T) { + for _, batch := range []bool{false, true} { + name := map[bool]string{false: "single", true: "batch"}[batch] + t.Run(name, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + var stop atomic.Bool + var wg sync.WaitGroup + t.Cleanup(func() { + stop.Store(true) + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("reader goroutines did not finish") + } + }) + // steady overlapping readers of the store lock (each holds it ~2 ms, + // staggered): some reader is almost always inside, as under heavy + // read traffic. A blocking Lock registers as a waiting writer and + // gets in; a TryLock poll would keep failing until the deadline. + for i := 0; i < 8; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + time.Sleep(time.Duration(i) * 250 * time.Microsecond) + for !stop.Load() { + s.mu.RLock() + time.Sleep(2 * time.Millisecond) + s.mu.RUnlock() + } + }(i) + } + time.Sleep(10 * time.Millisecond) + for i := 0; i < 5; i++ { // within the test WAL (auto-flush is off) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 0, [][]byte{blk(byte(i)), blk(byte(i + 1))}) + } else { + _, err = s.WriteContext(ctx, 0, blk(byte(i))) + } + cancel() + if err != nil { + t.Fatalf("write %d starved by readers: %v", i, err) + } + } + }) + } +} + +// Short locks block; an expired command refuses after the wait, without +// mutating (revises the polling-era lock tests to the agreed lock policy). +func TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait(t *testing.T) { + for _, lock := range []string{"store", "descriptor", "writer"} { + t.Run(lock, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + var unlock func() + switch lock { + case "store": + s.mu.Lock() + unlock = s.mu.Unlock + case "descriptor": + s.v3.pub.descMu.Lock() + unlock = s.v3.pub.descMu.Unlock + default: + s.v3.w.mu.Lock() + unlock = s.v3.w.mu.Unlock + } + var once sync.Once + release := func() { once.Do(unlock) } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + done := make(chan error, 1) + t.Cleanup(func() { + release() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("writer did not finish after the release") + } + }) + go func() { _, err := s.WriteContext(ctx, 0, blk(1)); done <- err }() + <-ctx.Done() // the command expires while the short lock is held + release() + err := <-done + done <- err // for the cleanup join + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatalf("expired writer after a %s lock wait: %v", lock, err) + } + if s.NextLSN() != 1 || s.dm.len() != 0 { + t.Fatal("expired writer mutated after the lock wait") + } + }) + } +} + +// #252 residual P1: the budget is checked inside the WAL writer, after its +// descriptor snapshot and writer lock wait. A real concurrent Sync holds the +// descriptor lock (its slot write, without the store lock) until the command +// has expired; the append waiting behind it must then refuse before any +// payload write, and the Sync completes normally. +func TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync(t *testing.T) { + for _, batch := range []bool{false, true} { + name := map[bool]string{false: "single", true: "batch"}[batch] + t.Run(name, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + if _, err := s.Write(7, blk(7)); err != nil { // unsynced: the Sync has a slot to publish + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 400*time.Millisecond) + defer cancel() + entered := make(chan struct{}) + var enterOnce sync.Once + s.v3.testBeforeSlotWrite = func() error { + enterOnce.Do(func() { close(entered) }) + <-ctx.Done() // the command expires while the Sync holds the descriptor lock + return nil + } + // The Sync runs first and parks at its leader point (past its store + // lock phase); the write's post-rollover hook releases it, so it takes + // the descriptor lock for its slot write after the write's rollover + // snapshot and before the write's own append snapshot. + atLeader, proceed := make(chan struct{}), make(chan struct{}) + var leaderOnce, proceedOnce sync.Once + release := func() { proceedOnce.Do(func() { close(proceed) }) } + s.v3.testLeaderWaiting = func() { + leaderOnce.Do(func() { close(atLeader); <-proceed }) + } + syncDone := make(chan error, 1) + t.Cleanup(func() { + release() + cancel() + select { + case <-syncDone: + case <-time.After(5 * time.Second): + t.Error("the concurrent Sync did not finish") + } + }) + go func() { _, err := s.Sync(); syncDone <- err }() + <-atLeader + s.v3.testAfterRollover = func() { + release() + <-entered + } + head := s.v3.w.head + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 0, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.WriteContext(ctx, 0, blk(1)) + } + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatalf("expired command after the descriptor wait: %v", err) + } + if s.v3.w.head != head { + t.Fatalf("expired command started payload WAL I/O after the descriptor wait: head %d -> %d", head, s.v3.w.head) + } + if err := <-syncDone; err != nil { + t.Fatalf("the concurrent Sync: %v", err) + } + syncDone <- nil + s.v3.testAfterRollover, s.v3.testBeforeSlotWrite, s.v3.testLeaderWaiting = nil, nil, nil + if _, err := s.WriteContext(context.Background(), 0, blk(3)); err != nil { + t.Fatalf("a fresh write after the refusal: %v", err) + } + }) + } +} diff --git a/seaweed-block/core/storage/write_command_budget_test.go b/seaweed-block/core/storage/write_command_budget_test.go new file mode 100644 index 0000000000..6a6ba9c2c3 --- /dev/null +++ b/seaweed-block/core/storage/write_command_budget_test.go @@ -0,0 +1,111 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "testing" + "time" +) + +func TestWALStoreV3WriteBudgetIncludesPostAdmissionWait(t *testing.T) { + for _, batch := range []bool{false, true} { + t.Run(map[bool]string{false: "single", true: "batch"}[batch], func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.admissionTimeout = 40 * time.Millisecond + // Admission is healthy. A delayed admitted writer must not start a fresh + // budget after waiting to reach its mutation boundary. + s.testAfterAdmit = func() { time.Sleep(60 * time.Millisecond) } + before := s.NextLSN() + var err error + if batch { + _, err = s.WriteBatch(0, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.Write(0, blk(1)) + } + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatalf("expired command mutated: %v", err) + } + if s.NextLSN() != before || s.dm.len() != 0 { + t.Fatal("expired write changed WAL/dirty state") + } + s.testAfterAdmit = nil + if _, err := s.Write(0, blk(2)); err != nil { + t.Fatal(err) + } + }) + } +} + +func TestWALStoreV3WriteContextDeadlineIncludesCaptureWait(t *testing.T) { + for _, batch := range []bool{false, true} { + t.Run(fmt.Sprint(batch), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + s.captureMu.Lock() + done := make(chan error, 1) + go func() { + var err error + if batch { + _, err = s.WriteBatchContext(ctx, 0, [][]byte{blk(1), blk(2)}) + } else { + _, err = s.WriteContext(ctx, 0, blk(1)) + } + done <- err + }() + defer s.captureMu.Unlock() + select { + case err := <-done: + if !errors.Is(err, ErrWALPressureTimeout) { + t.Fatal(err) + } + case <-time.After(time.Second): + t.Fatal("writer did not join") + } + if s.NextLSN() != 1 || s.dm.len() != 0 { + t.Fatal("expired capture waiter mutated") + } + }) + } +} + +func TestWALStoreV3WriteBudgetKeepsTerminalFault(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + injected := errors.New("terminal fsync fault") + s.latchV3(injected) + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + if _, err := s.WriteContext(ctx, 0, blk(1)); !errors.Is(err, injected) { + t.Fatalf("fault hidden by deadline: %v", err) + } +} + +// The polling-era append/pressure lock tests are replaced by +// TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait (short locks block, #252). + +func TestWALStoreV3WritePressureSampleMatchesOccupancy(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + check := func() { + t.Helper() + got, err := s.writePressureSample(context.Background(), time.Now().Add(time.Second))() + if err != nil || got != s.walUsedFraction() { + t.Fatalf("sample=%v err=%v normal=%v", got, err, s.walUsedFraction()) + } + } + check() + for lba := uint32(0); lba < 8; lba++ { + if _, err := s.Write(lba, blk(byte(lba))); err != nil { + t.Fatal(err) + } + } + check() + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + check() + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + check() +} diff --git a/seaweed-block/core/transport/catchup_format_v3_test.go b/seaweed-block/core/transport/catchup_format_v3_test.go new file mode 100644 index 0000000000..5694c63278 --- /dev/null +++ b/seaweed-block/core/transport/catchup_format_v3_test.go @@ -0,0 +1,386 @@ +//go:build swblock_format_v3_test + +package transport + +import ( + "bytes" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/engine" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestCatchUpV3AfterCheckpointRingReuse(t *testing.T) { + primary, err := storage.CreateMappedWALStoreV3Test(filepath.Join(t.TempDir(), "primary.v3"), 64, v3RepBlock, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = primary.Close() }) + primary.DisableAutoFlushForRecoveryTest() + primary.SetRecoveryRetentionLSNs(1) + const last = 270 // more than one lap of the real 1MiB test WAL + for i := 1; i <= last; i++ { + if _, err := primary.Write(0, v3RepBlk(byte(i))); err != nil { + t.Fatalf("cycle %d: %v", i, err) + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + if err := storage.FlushMappedWALStoreV3Test(primary); err != nil { + t.Fatal(err) + } + } + replica := v3Rep(t) + h, err := replica.BeginBaseInstall(last-1, [16]byte{1}) + if err != nil { + t.Fatal(err) + } + if err := h.WriteBase(0, v3RepBlk(byte((last-1)%256))); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + l := v3Listen(t, replica) + r := runCatchUpFrom(t, NewBlockExecutor(primary, l.Addr()), last, last+1) + if !r.Success || r.AchievedLSN != last { + t.Fatalf("retained post-wrap record did not catch up: %+v", r) + } + if got := v3Read(t, replica, 0); !bytes.Equal(got, v3RepBlk(byte(last%256))) { + t.Fatal("catch-up after physical reuse returned wrong bytes") + } + r = runCatchUpFrom(t, NewBlockExecutor(primary, l.Addr()), last-1, last+1) + if r.Success || r.FailureKind != engine.RecoveryFailureWALRecycled { + t.Fatalf("released prefix must route to rebuild: %+v", r) + } +} + +func TestCatchUpV3InstallRetireABARefusesOldScan(t *testing.T) { + primary, err := storage.CreateMappedWALStoreV3Test(filepath.Join(t.TempDir(), "primary.v3"), 64, v3RepBlock, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = primary.Close() }) + primary.DisableAutoFlushForRecoveryTest() + for lba := uint32(0); lba < 2; lba++ { + if _, err := primary.Write(lba, v3RepBlk(0x10+byte(lba))); err != nil { + t.Fatal(err) + } + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + parked, resume := make(chan struct{}), make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(resume) }) } + t.Cleanup(release) + defer release() // unblock the sender before listener/store cleanups on failure + var scans atomic.Int32 + storage.SetScanReadV3Test(primary, func() { + if scans.Add(1) == 1 { + close(parked) + <-resume + } + }) + replica := v3Rep(t) + l := v3Listen(t, replica) + exec := NewBlockExecutor(primary, l.Addr()) + closed := make(chan adapter.SessionCloseResult, 1) + exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closed <- r }) + if err := exec.StartCatchUp("r1", 1, 1, 1, 1, 3); err != nil { + t.Fatal(err) + } + select { + case <-parked: + case <-time.After(5 * time.Second): + t.Fatal("sender did not park after reading the original WAL") + } + h, err := primary.BeginBaseInstall(2, [16]byte{1}) + if err != nil { + t.Fatal(err) + } + if err := h.WriteBase(0, v3RepBlk(0x70)); err != nil { + t.Fatal(err) + } + if err := h.ApplyInstallEntry(2, v3RepBlk(0x73), 3); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + if err := storage.FlushMappedWALStoreV3Test(primary); err != nil { + t.Fatal(err) + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + if state, id := storage.BaseStateV3Test(primary); state != storage.BaseNone || id != [16]byte{} { + t.Fatalf("setup must finish the BASE ABA: state=%v id=%x", state, id) + } + release() + select { + case result := <-closed: + if result.Success || result.FailureKind != engine.RecoveryFailureWALRecycled { + t.Fatalf("old pre-BASE WAL must not be shipped after retirement: %+v", result) + } + case <-time.After(5 * time.Second): + t.Fatal("sender did not finish after scan release") + } + if got := v3Read(t, replica, 0); !bytes.Equal(got, make([]byte, v3RepBlock)) { + t.Fatal("sender published superseded pre-BASE bytes to the replica") + } +} + +func TestCatchUpV3CompletedBASEUsesRebuild(t *testing.T) { + primary, err := storage.CreateWALStoreV3Test(filepath.Join(t.TempDir(), "primary.v3"), 64, v3RepBlock) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = primary.Close() }) + h, err := primary.BeginBaseInstall(100, [16]byte{1}) + if err != nil { + t.Fatal(err) + } + if err := h.WriteBase(0, v3RepBlk(0x70)); err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + replica := v3Rep(t) + l := v3Listen(t, replica) + result := runCatchUpFrom(t, NewBlockExecutor(primary, l.Addr()), 3, 101) + if result.Success || result.FailureKind != engine.RecoveryFailureWALRecycled { + t.Fatalf("completed BASE without install WAL needs rebuild, not corruption: %+v", result) + } +} + +func TestCatchUpV3InstallingAtHeadRefuses(t *testing.T) { + primary, err := storage.CreateWALStoreV3Test(filepath.Join(t.TempDir(), "primary.v3"), 64, v3RepBlock) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = primary.Close() }) + for lba := uint32(0); lba < 2; lba++ { + if _, err := primary.Write(lba, v3RepBlk(0x10+byte(lba))); err != nil { + t.Fatal(err) + } + } + if _, err := primary.BeginBaseInstall(2, [16]byte{1}); err != nil { + t.Fatal(err) + } + replica := v3Rep(t) + l := v3Listen(t, replica) + result := runCatchUpFrom(t, NewBlockExecutor(primary, l.Addr()), 3, 3) + if result.Success || !strings.Contains(result.FailReason, storage.ErrBaseInstalling.Error()) { + t.Fatalf("installing source at head must refuse catch-up: %+v", result) + } +} + +// The actual catch-up sender (BlockExecutor.StartCatchUp -> the primary's +// ScanLBAs -> the replica's ship handler) from a dark v3 primary to an empty +// dark v3 replica: single writes and a batch are shipped and the replica +// matches the primary byte for byte. Mutant: ScanLBAs on v3 using the v2 +// scan (emits nothing) leaves the replica empty and fails here. +func TestCatchUpV3PrimaryToV3Replica(t *testing.T) { + primary, err := storage.CreateWALStoreV3Test(filepath.Join(t.TempDir(), "primary.v3"), 64, v3RepBlock) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = primary.Close() }) + for lba := uint32(0); lba < 3; lba++ { + if _, err := primary.Write(lba, v3RepBlk(0x10+byte(lba))); err != nil { + t.Fatal(err) + } + } + batch := [][]byte{v3RepBlk(0x20), v3RepBlk(0x21), v3RepBlk(0x22)} + if _, err := primary.WriteBatch(5, batch); err != nil { + t.Fatal(err) + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + _, _, head := primary.Boundaries() + replica := v3Rep(t) + l := v3Listen(t, replica) + exec := NewBlockExecutor(primary, l.Addr()) + if r := runCatchUp(t, exec, head); !r.Success { + t.Fatalf("catch-up closed unsuccessfully: %+v", r) + } + for lba := uint32(0); lba < 8; lba++ { + want, err := primary.Read(lba) + if err != nil { + t.Fatal(err) + } + if got := v3Read(t, replica, lba); !bytes.Equal(got, want) { + t.Fatalf("replica LBA %d = %x..., primary %x...", lba, got[0], want[0]) + } + } +} + +// A corrupt middle record on the v3 primary must not +// let the actual catch-up sender complete at the prefix before it: the +// session closes unsuccessfully. Mutant: accepting a short prefix fails +// here. +func TestCatchUpV3CorruptMiddleRecordFails(t *testing.T) { + testCatchUpV3CorruptRecordFails(t, 2) +} + +func TestCatchUpV3CorruptFirstRecordFails(t *testing.T) { + testCatchUpV3CorruptRecordFails(t, 1) +} + +func testCatchUpV3CorruptRecordFails(t *testing.T, lsn uint64) { + t.Helper() + path := filepath.Join(t.TempDir(), "primary.v3") + primary, err := storage.CreateWALStoreV3Test(path, 64, v3RepBlock) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = primary.Close() }) + for lba := uint32(0); lba < 3; lba++ { + if _, err := primary.Write(lba, v3RepBlk(0x10+byte(lba))); err != nil { + t.Fatal(err) + } + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + if err := storage.DamageV3RecordTest(path, lsn); err != nil { + t.Fatal(err) + } + _, _, head := primary.Boundaries() + replica := v3Rep(t) + l := v3Listen(t, replica) + exec := NewBlockExecutor(primary, l.Addr()) + if r := runCatchUp(t, exec, head); r.Success || r.FailureKind == engine.RecoveryFailureWALRecycled || !strings.Contains(r.FailReason, "WALIntegrity") { + t.Fatalf("catch-up over corrupt LSN %d must fail with integrity, not rebuild: %+v", lsn, r) + } +} + +func TestCatchUpV3CompletedBASESuffix(t *testing.T) { + for _, corrupt := range []bool{false, true} { + name := "healthy" + if corrupt { + name = "corrupt" + } + t.Run(name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "primary.v3") + primary, err := storage.CreateWALStoreV3Test(path, 64, v3RepBlock) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = primary.Close() }) + replica := v3Rep(t) + for _, store := range []*storage.WALStore{primary, replica} { + h, err := store.BeginBaseInstall(100, [16]byte{1}) + if err != nil { + t.Fatal(err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + } + if _, err := primary.Write(0, v3RepBlk(0x71)); err != nil { + t.Fatal(err) + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + if corrupt { + if err := storage.DamageV3RecordTest(path, 101); err != nil { + t.Fatal(err) + } + } + l := v3Listen(t, replica) + r := runCatchUpFrom(t, NewBlockExecutor(primary, l.Addr()), 101, 102) + if corrupt { + if r.Success || r.FailureKind == engine.RecoveryFailureWALRecycled || !strings.Contains(r.FailReason, "WALIntegrity") { + t.Fatalf("damaged retained BASE suffix must fail with integrity: %+v", r) + } + return + } + if !r.Success || r.AchievedLSN != 101 { + t.Fatalf("healthy retained BASE suffix did not catch up: %+v", r) + } + if got := v3Read(t, replica, 0); !bytes.Equal(got, v3RepBlk(0x71)) { + t.Fatal("healthy retained BASE suffix bytes differ") + } + }) + } +} + +func TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled(t *testing.T) { + primary, err := storage.CreateMappedWALStoreV3Test(filepath.Join(t.TempDir(), "primary.v3"), 64, v3RepBlock, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = primary.Close() }) + primary.DisableAutoFlushForRecoveryTest() + // Leave admission headroom while the flusher is deliberately disabled. + // The post-checkpoint writes still cross the physical 1 MiB ring boundary. + for i := 1; i <= 200; i++ { + if _, err := primary.Write(0, v3RepBlk(byte(i))); err != nil { + t.Fatal(err) + } + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + parked, resume := make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(resume) }) } + defer release() + var scans atomic.Int32 + storage.SetScanBeforeReadV3Test(primary, func() { + if scans.Add(1) == 1 { + close(parked) + <-resume + } + }) + replica := v3Rep(t) + l := v3Listen(t, replica) + exec := NewBlockExecutor(primary, l.Addr()) + closed := make(chan adapter.SessionCloseResult, 1) + exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closed <- r }) + if err := exec.StartCatchUp("r1", 1, 1, 1, 1, 201); err != nil { + t.Fatal(err) + } + select { + case <-parked: + case <-time.After(5 * time.Second): + t.Fatal("sender did not capture old tail") + } + if err := storage.FlushMappedWALStoreV3Test(primary); err != nil { + t.Fatal(err) + } + for i := 201; i <= 270; i++ { + if _, err := primary.Write(0, v3RepBlk(byte(i%256))); err != nil { + t.Fatal(err) + } + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + release() + select { + case result := <-closed: + if result.Success || result.FailureKind != engine.RecoveryFailureWALRecycled { + t.Fatalf("overlapped real reuse must route to rebuild, never false corruption: %+v", result) + } + case <-time.After(5 * time.Second): + t.Fatal("sender did not finish") + } + if got := v3Read(t, replica, 0); !bytes.Equal(got, make([]byte, v3RepBlock)) { + t.Fatal("failed catch-up emitted a partial replay") + } +} diff --git a/seaweed-block/core/transport/rebuild_sender.go b/seaweed-block/core/transport/rebuild_sender.go index a1515e6bdb..90f776d387 100644 --- a/seaweed-block/core/transport/rebuild_sender.go +++ b/seaweed-block/core/transport/rebuild_sender.go @@ -110,7 +110,10 @@ func (e *BlockExecutor) doRebuild(replicaID string, session *activeSession, fron }() e.signalSessionStart(replicaID, session.lineage.SessionID) - blocks := e.primaryStore.AllBlocks() + blocks, err := e.primaryStore.AllBlocks() + if err != nil { + return 0, fmt.Errorf("rebuild snapshot: %w", err) + } lbas := make([]int, 0, len(blocks)) for lba := range blocks { lbas = append(lbas, int(lba)) diff --git a/seaweed-block/core/transport/rebuild_snapshot_error_test.go b/seaweed-block/core/transport/rebuild_snapshot_error_test.go new file mode 100644 index 0000000000..0206108a57 --- /dev/null +++ b/seaweed-block/core/transport/rebuild_snapshot_error_test.go @@ -0,0 +1,45 @@ +package transport + +import ( + "errors" + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/storage" + "strings" + "testing" + "time" +) + +type failedRebuildSnapshot struct{ storage.LogicalStorage } + +func (*failedRebuildSnapshot) AllBlocks() (map[uint32][]byte, error) { + return map[uint32][]byte{0: makeData(0x77)}, errors.New("snapshot read fault") +} +func TestRebuildSnapshotErrorNeverShipsPartialImage(t *testing.T) { + replica := storage.NewBlockStore(64, 4096) + listener, err := NewReplicaListener("127.0.0.1:0", replica) + if err != nil { + t.Fatal(err) + } + listener.Serve() + defer listener.Stop() + primary := &failedRebuildSnapshot{storage.NewBlockStore(64, 4096)} + exec := NewBlockExecutor(primary, listener.Addr()) + defer exec.Stop() + closed := make(chan adapter.SessionCloseResult, 1) + exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closed <- r }) + before := replica.NextLSN() + if err := exec.StartRebuild("r1", 1, 1, 1, 1); err != nil { + t.Fatal(err) + } + select { + case got := <-closed: + if got.Success || !strings.Contains(got.FailReason, "snapshot read fault") { + t.Fatalf("snapshot error lost: %+v", got) + } + case <-time.After(3 * time.Second): + t.Fatal("snapshot failure did not settle rebuild") + } + if replica.NextLSN() != before { + t.Fatal("failed snapshot shipped a partial image") + } +} diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 1e05b9640b..204709474a 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -1,6 +1,7 @@ package transport import ( + "crypto/rand" "fmt" "log" "net" @@ -308,17 +309,33 @@ func (r *ReplicaListener) acceptLoop() { func (r *ReplicaListener) handleConn(conn net.Conn) { defer conn.Close() lane := mutationLaneLive - basePrepared := false - prepareBaseInstall := func() error { - if basePrepared { + // The legacy single-lane rebuild is the second BASE-install caller + // (DESIGN r17.4 section 8.7): the first admitted rebuild message of a + // connection begins one install at its frontier hint under a fresh + // random ID; a reconnect is a new connection and so a superseding + // install. Stores without the seam keep their pre-seam behaviour behind + // the legacy handle (lazy BaseStager staging, WriteExtentDirect, + // AdvanceFrontier at completion). + var install storage.InstallHandle + var installBase uint64 + beginInstall := func(hint uint64) error { + if install != nil { + if hint != installBase { + return fmt.Errorf("rebuild frontier hint %d differs from the install's BaseLSN %d", hint, installBase) + } return nil } - if preparer, ok := r.store.(storage.BaseInstallPreparer); ok { - if err := preparer.BeginBaseInstall(); err != nil { + var id [16]byte + for id == ([16]byte{}) { + if _, err := rand.Read(id[:]); err != nil { return err } } - basePrepared = true + h, err := storage.BeginInstall(r.store, hint, id) + if err != nil { + return err + } + install, installBase = h, hint return nil } @@ -442,11 +459,11 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { // Rebuild blocks are BASE-lane bytes. They must not enter the // WAL apply path and must not advance R/S/H per block; the // frontier is reconciled once, at MsgRebuildDone. - if err := prepareBaseInstall(); err != nil { - log.Printf("replica: prepare rebuild base: %v", err) + if err := beginInstall(lineage.EffectiveFrontierHint()); err != nil { + log.Printf("replica: begin rebuild base: %v", err) return true } - if err := r.store.WriteExtentDirect(lba, data); err != nil { + if err := install.WriteBase(lba, data); err != nil { log.Printf("replica: apply rebuild base block: %v", err) return true } @@ -462,15 +479,24 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true } - if err := prepareBaseInstall(); err != nil { - log.Printf("replica: prepare empty rebuild base: %v", err) + // Done (DESIGN 8.7): an empty rebuild begins here; the hint must + // equal the install's BaseLSN; then complete, then the logical + // Sync, which is ordinary once installed. A failed completion or + // Sync closes the connection with no MsgBarrierResp, so the + // primary never sees an AchievedLSN from a failed call. + if err := beginInstall(lineage.EffectiveFrontierHint()); err != nil { + log.Printf("replica: begin rebuild base at done: %v", err) + return true + } + if err := install.MarkBaseComplete(); err != nil { + log.Printf("replica: complete rebuild base: %v", err) + return true + } + frontier, err := r.store.Sync() + if err != nil { + log.Printf("replica: sync after rebuild done: %v", err) return true } - // The done message carries the engine's frozen base frontier hint. - // Advance the replica's frontier metadata without touching - // any block data — AdvanceFrontier only updates nextLSN/walHead. - r.store.AdvanceFrontier(lineage.EffectiveFrontierHint()) - frontier, _ := r.store.Sync() // Echo the request's full lineage in the rebuild-done ack // so primary-side validators can consume it. resp := EncodeBarrierResp(BarrierResponse{ diff --git a/seaweed-block/core/transport/replica_install_format_v3_test.go b/seaweed-block/core/transport/replica_install_format_v3_test.go new file mode 100644 index 0000000000..5050dd6238 --- /dev/null +++ b/seaweed-block/core/transport/replica_install_format_v3_test.go @@ -0,0 +1,291 @@ +//go:build swblock_format_v3_test + +package transport + +import ( + "bytes" + "errors" + "net" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Plan row 10b controls (DESIGN r17.4 section 8.7, caller 2; owner +// claude03): the legacy single-lane rebuild on a dark v3 replica. The +// first admitted rebuild message begins one install at its frontier hint; +// blocks go through the handle; done completes, then Syncs, and a failure +// closes the connection with no MsgBarrierResp. + +const v3RepBlock = 4096 + +func v3Rep(t *testing.T) *storage.WALStore { + t.Helper() + s, err := storage.CreateWALStoreV3Test(filepath.Join(t.TempDir(), "replica.v3"), 64, v3RepBlock) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} + +func v3Listen(t *testing.T, store storage.LogicalStorage) *ReplicaListener { + t.Helper() + l, err := NewReplicaListener("127.0.0.1:0", store) + if err != nil { + t.Fatal(err) + } + l.Serve() + t.Cleanup(func() { l.Stop() }) + return l +} + +func v3Dial(t *testing.T, l *ReplicaListener) net.Conn { + t.Helper() + c, err := net.Dial("tcp", l.Addr()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + return c +} + +func v3RepBlk(b byte) []byte { return bytes.Repeat([]byte{b}, v3RepBlock) } + +// done sends MsgRebuildDone and returns the BarrierResp, or ok=false when +// the replica closed the connection without one. +func v3Done(t *testing.T, c net.Conn, l RecoveryLineage) (BarrierResponse, bool) { + t.Helper() + if err := WriteMsg(c, MsgRebuildDone, EncodeLineage(l)); err != nil { + t.Fatal(err) + } + _ = c.SetReadDeadline(time.Now().Add(10 * time.Second)) + mt, payload, err := ReadMsg(c) + if err != nil { + var ne net.Error + if errors.As(err, &ne) && ne.Timeout() { + t.Fatal("no reply and no close after MsgRebuildDone") + } + return BarrierResponse{}, false + } + if mt != MsgBarrierResp { + t.Fatalf("reply %d, want MsgBarrierResp", mt) + } + r, err := DecodeBarrierResp(payload) + if err != nil { + t.Fatal(err) + } + return r, true +} + +func v3Read(t *testing.T, s *storage.WALStore, lba uint32) []byte { + t.Helper() + b, err := s.Read(lba) + if err != nil { + t.Fatal(err) + } + return b +} + +// The positive and the empty rebuild through the replica handler: installed, +// AchievedLSN = the hint, the blocks readable. Mutants: no begin (the +// unanchored jump: the store-level direct write is refused on v3) and no +// MarkBaseComplete (the achieved-0 shape: the gated Sync fails the done +// path and nothing is replied) both fail here. +func TestReplicaV3LegacyRebuildInstallsThroughTheHandle(t *testing.T) { + for _, empty := range []bool{false, true} { + name := "blocks" + if empty { + name = "empty" + } + t.Run(name, func(t *testing.T) { + s := v3Rep(t) + l := v3Listen(t, s) + c := v3Dial(t, l) + lin := RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 5} + if !empty { + for lba := uint32(0); lba < 3; lba++ { + if err := WriteMsg(c, MsgRebuildBlock, EncodeRebuildBlock(lin, lba, v3RepBlk(0x10+byte(lba)))); err != nil { + t.Fatal(err) + } + } + } + resp, ok := v3Done(t, c, lin) + if !ok || resp.AchievedLSN != 5 { + t.Fatalf("done: replied %v, AchievedLSN %d, want 5", ok, resp.AchievedLSN) + } + if st, _ := storage.BaseStateV3Test(s); st != storage.BaseInstalled { + t.Fatalf("state %d, want installed", st) + } + if !empty { + for lba := uint32(0); lba < 3; lba++ { + if got := v3Read(t, s, lba); !bytes.Equal(got, v3RepBlk(0x10+byte(lba))) { + t.Fatalf("LBA %d = %x...", lba, got[0]) + } + } + } + }) + } +} + +// The actual caller: BlockExecutor.StartRebuild -> doRebuild -> the +// replica handler, onto a dark v3 replica. The session closes successfully +// and the replica holds the primary's blocks, installed. +func TestReplicaV3RebuildThroughTheBlockExecutor(t *testing.T) { + primary := storage.NewBlockStore(64, v3RepBlock) + for lba := uint32(0); lba < 4; lba++ { + if _, err := primary.Write(lba, v3RepBlk(0x20+byte(lba))); err != nil { + t.Fatal(err) + } + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + _, _, pH := primary.Boundaries() + s := v3Rep(t) + l := v3Listen(t, s) + exec := NewBlockExecutor(primary, l.Addr()) + closeCh := make(chan adapter.SessionCloseResult, 1) + exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r }) + if err := exec.StartRebuild("r1", 7, 1, 1, pH); err != nil { + t.Fatal(err) + } + select { + case r := <-closeCh: + if !r.Success { + t.Fatalf("rebuild closed unsuccessfully: %+v", r) + } + case <-time.After(20 * time.Second): + t.Fatal("rebuild did not close") + } + if st, _ := storage.BaseStateV3Test(s); st != storage.BaseInstalled { + t.Fatalf("state %d, want installed", st) + } + for lba := uint32(0); lba < 4; lba++ { + if got := v3Read(t, s, lba); !bytes.Equal(got, v3RepBlk(0x20+byte(lba))) { + t.Fatalf("LBA %d = %x...", lba, got[0]) + } + } +} + +// failingDoneStore injects a done-path failure: the completion or the +// logical Sync after it. +type failingDoneStore struct { + *storage.WALStore + failComplete, failSync atomic.Bool +} + +type failingHandle struct { + storage.InstallHandle + s *failingDoneStore +} + +func (h failingHandle) MarkBaseComplete() error { + if h.s.failComplete.Load() { + return errors.New("injected MarkBaseComplete failure") + } + return h.InstallHandle.MarkBaseComplete() +} + +func (s *failingDoneStore) BeginBaseInstall(baseLSN uint64, id [16]byte) (storage.InstallHandle, error) { + h, err := s.WALStore.BeginBaseInstall(baseLSN, id) + if err != nil { + return nil, err + } + return failingHandle{InstallHandle: h, s: s}, nil +} + +func (s *failingDoneStore) Sync() (uint64, error) { + if s.failSync.Load() { + return 0, errors.New("injected Sync failure") + } + return s.WALStore.Sync() +} + +// Injected done-path failures (DESIGN 8.7): a failed MarkBaseComplete or a +// failed Sync closes the connection with no MsgBarrierResp. Mutants: a +// handler that discards either error replies and fails here. +func TestReplicaV3RebuildDoneFailureRepliesNothing(t *testing.T) { + for _, which := range []string{"complete", "sync"} { + t.Run(which, func(t *testing.T) { + s := &failingDoneStore{WALStore: v3Rep(t)} + if which == "complete" { + s.failComplete.Store(true) + } else { + s.failSync.Store(true) + } + l := v3Listen(t, s) + c := v3Dial(t, l) + lin := RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 5} + if err := WriteMsg(c, MsgRebuildBlock, EncodeRebuildBlock(lin, 0, v3RepBlk(0x11))); err != nil { + t.Fatal(err) + } + if resp, ok := v3Done(t, c, lin); ok { + t.Fatalf("a failed %s replied MsgBarrierResp AchievedLSN %d", which, resp.AchievedLSN) + } + }) + } +} + +// A reconnect is a new connection and so a superseding install: refused +// unless its hint covers W (the replica acknowledged LSN 4 before the +// rebuild), allowed when it does. +func TestReplicaV3RebuildReconnectSupersedesOnlyUnderCoverage(t *testing.T) { + s := v3Rep(t) + for lba := uint32(10); lba < 14; lba++ { + if _, err := s.Write(lba, v3RepBlk(byte(lba))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + l := v3Listen(t, s) + a := v3Dial(t, l) + linA := RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 5} + if err := WriteMsg(a, MsgRebuildBlock, EncodeRebuildBlock(linA, 0, v3RepBlk(0xAA))); err != nil { + t.Fatal(err) + } + waitInstalling(t, s) + _, idA := storage.BaseStateV3Test(s) + b := v3Dial(t, l) + linB := RecoveryLineage{SessionID: 2, Epoch: 2, EndpointVersion: 2, TargetLSN: 3} // below W 4 + if err := WriteMsg(b, MsgRebuildBlock, EncodeRebuildBlock(linB, 0, v3RepBlk(0xBB))); err != nil { + t.Fatal(err) + } + if _, ok := v3Done(t, b, linB); ok { + t.Fatal("an uncovered reconnect completed") + } + if st, id := storage.BaseStateV3Test(s); st != storage.BaseInstalling || id != idA { + t.Fatalf("after the uncovered reconnect: state %d, id changed %v", st, id != idA) + } + c := v3Dial(t, l) + linC := RecoveryLineage{SessionID: 3, Epoch: 3, EndpointVersion: 3, TargetLSN: 6} + if err := WriteMsg(c, MsgRebuildBlock, EncodeRebuildBlock(linC, 0, v3RepBlk(0xCC))); err != nil { + t.Fatal(err) + } + if resp, ok := v3Done(t, c, linC); !ok || resp.AchievedLSN != 6 { + t.Fatalf("covered reconnect: replied %v AchievedLSN %d, want 6", ok, resp.AchievedLSN) + } + if got := v3Read(t, s, 0); !bytes.Equal(got, v3RepBlk(0xCC)) { + t.Fatalf("LBA 0 = %x..., want the covering install's bytes", got[0]) + } +} + +func waitInstalling(t *testing.T, s *storage.WALStore) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for { + if st, _ := storage.BaseStateV3Test(s); st == storage.BaseInstalling { + return + } + if time.Now().After(deadline) { + t.Fatal("the rebuild never began its install") + } + time.Sleep(5 * time.Millisecond) + } +} diff --git a/seaweed-block/core/transport/replica_ship_format_v3_test.go b/seaweed-block/core/transport/replica_ship_format_v3_test.go new file mode 100644 index 0000000000..bfa4002dd3 --- /dev/null +++ b/seaweed-block/core/transport/replica_ship_format_v3_test.go @@ -0,0 +1,63 @@ +//go:build swblock_format_v3_test + +package transport + +import ( + "bytes" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// The ordinary ship path onto a dark v3 replica, through the real +// MsgShipEntry handler (replica.go, no apply hook): entries apply in LSN +// order, a barrier acknowledges them, and a crash and reopen keep them. An +// out-of-order entry ends the connection (the store refuses it). Mutant: +// ApplyEntry refused on v3 (errV3NotYet) fails here. +func TestReplicaV3ShipEntriesApplyAndSurviveACrash(t *testing.T) { + path := t.TempDir() + "/ship.v3" + s, err := storage.CreateWALStoreV3Test(path, 64, v3RepBlock) + if err != nil { + t.Fatal(err) + } + l := v3Listen(t, s) + c := v3Dial(t, l) + lin := RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 3} + for lsn := uint64(1); lsn <= 3; lsn++ { + if err := WriteMsg(c, MsgShipEntry, EncodeShipEntry(ShipEntry{Lineage: lin, LBA: uint32(lsn), LSN: lsn, Data: v3RepBlk(byte(lsn))})); err != nil { + t.Fatal(err) + } + } + if err := WriteMsg(c, MsgBarrierReq, EncodeLineage(lin)); err != nil { + t.Fatal(err) + } + _ = c.SetReadDeadline(time.Now().Add(10 * time.Second)) + mt, payload, err := ReadMsg(c) + if err != nil || mt != MsgBarrierResp { + t.Fatalf("barrier: type %d err %v", mt, err) + } + if resp, err := DecodeBarrierResp(payload); err != nil || resp.AchievedLSN < 3 { + t.Fatalf("barrier AchievedLSN %d err %v, want >= 3", resp.AchievedLSN, err) + } + if err := WriteMsg(c, MsgShipEntry, EncodeShipEntry(ShipEntry{Lineage: lin, LBA: 7, LSN: 2, Data: v3RepBlk(0x77)})); err == nil { + _ = c.SetReadDeadline(time.Now().Add(10 * time.Second)) + if _, _, err := ReadMsg(c); err == nil { + t.Fatal("an out-of-order ship entry did not end the connection") + } + } + l.Stop() + r, err := storage.CrashReopenV3Test(s, path) + if err != nil { + t.Fatalf("crash and reopen: %v", err) + } + t.Cleanup(func() { _ = r.Close() }) + for lba := uint32(1); lba <= 3; lba++ { + if got := v3Read(t, r, lba); !bytes.Equal(got, v3RepBlk(byte(lba))) { + t.Fatalf("LBA %d = %x... after reopen", lba, got[0]) + } + } + if got := v3Read(t, r, 7); bytes.Equal(got, v3RepBlk(0x77)) { + t.Fatal("the out-of-order entry was applied") + } +} diff --git a/seaweed-block/docs/assets/seaweed-block-agent-workspace.svg b/seaweed-block/docs/assets/seaweed-block-agent-workspace.svg index 6c0d6ba7cb..6cde2d5407 100644 --- a/seaweed-block/docs/assets/seaweed-block-agent-workspace.svg +++ b/seaweed-block/docs/assets/seaweed-block-agent-workspace.svg @@ -86,5 +86,5 @@ Measured on lab hosts: workloads in Firecracker microVMs; snapshot/fork in a host-side proxy (not an SLO) npm ci · git clone · untar · find+stat: same as a local disk snapshot 0.18 ms · fork 0.29 ms (10 GiB volume) · two-host lifecycle 35/35 - fsync: ~7 ms vs ~3 ms local today; ublk frontend and per-stage breakdown in progress + fsync (ublk): 3.2 ms vs 2.7 ms local · every guest fsync reaches the backend sync diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index ca073faaa3..1b8b2a9554 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -12,7 +12,7 @@ The three design documents: | Agent workspace design (this document) | Agent workspace disks: one local replica per workspace, cuts to SeaweedFS, snapshots, forks, GC, host moves | | [Kubernetes block design](kubernetes-block-design.md) | Kubernetes block volumes (alpha): CSI, Helm, RF=2/3 replication and failover, multipath, readiness | -Conventions are those of the core document: code references name a file and a function, not a line number; test references name the test function and its file; "Model-checked" means the protocol was specified in TLA+ and checked exhaustively with TLC at small scale (the specifications are in [`docs/spec/`](../spec/README.md)). +Conventions are those of the core document: code references name a file and a function, not a line number; test references name the test function and its file; "Model-checked" means the protocol was specified in TLA+ and checked exhaustively with TLC at small scale (the specifications are in [`docs/spec/`](../spec/README.md)). The state machines and invariants of this document are also in the shared ledger, [Invariants and state machines](invariants.md). ## Contents @@ -45,12 +45,14 @@ An agent workspace disk is a composition of core parts plus a SeaweedFS chunk ba flowchart LR G["guest microVM"] -->|"virtio-blk"| F["frontend: ublk or NVMe/TCP loopback"] F -->|"Read / Write / Sync"| W["local engine: walstore"] - W -->|"dirty chunk bitmap"| C["chunk layer: quiesced cut"] + W -->|"owned chunk LSN map + WAL dirt"| C["chunk layer: short barrier + COW cut"] C -->|"upload changed 4 MiB chunks, intents first"| S[("SeaweedFS: immutable chunks + segment manifests")] C -->|"CAS HEAD on {gen, epoch}"| H["HEAD root (about 2 KB)"] H -->|"snapshot / fork = copy the root"| H2["snapshot or forked volume"] M["blockmaster: epoch + lease"] -->|"higher epoch"| T["another host: claim HEAD, lazy-load chunks"] T --> H + F -->|"one arrival deadline"| Q["bounded per-chunk shared hydration"] + Q -->|"owned fetch, caller may detach"| S ``` - **Frontend:** the same ublk and NVMe/TCP code as the Kubernetes line ([core §1.1](block-design.md#11-frontends-and-the-backend-contract)). NVMe/TCP binds to loopback (`cmd/blockvolume/main.go` `enforceFrontendLoopbackBind`); ublk serves `/dev/ublkbN` on the same host (`--ublk-device`). The guest sees a plain virtio block device that the hypervisor attaches. @@ -70,7 +72,7 @@ A workspace runs one replica (RF=1). It does not use the replication engine of t | Permanent host loss | the image at the last successful cut (HEAD `RemoteLSN`); writes after it are lost | | Clean move (Detach) | everything written before Detach: guest I/O is stopped, then Detach publishes a final cut before the host releases the volume | -- **When cuts happen.** At semantic points chosen by the integrator (after an agent step, before a risky command, on detach) and on explicit request (`sw-block ops chunk cut`). The periodic timer is off by default (`cmd/blockvolume/chunk_remote.go` `defaultChunkCaptureInterval = 0`); an operator may set one as a host-loss safety net. `--chunk-dirty-threshold` (default 512 chunks, 2 GiB) only bounds how much one cut copies under its barrier; it never triggers a cut. +- **When cuts happen.** At semantic points chosen by the integrator (after an agent step, before a risky command, on detach) and on explicit request (`sw-block ops chunk cut`). The periodic timer is off by default (`cmd/blockvolume/chunk_remote.go` `defaultChunkCaptureInterval = 0`); an operator may set one as a host-loss safety net. `--chunk-dirty-threshold` (default 512 chunks, 2 GiB) bounds pre-copy staging work; native COW copies the remainder outside its barrier. It never triggers a cut. - **So the default RPO is unbounded** until the integrator cuts. This is a design choice for workspaces, where a cut at a semantic point is more useful than a timer. - Multi-replica workspaces combined with chunk snapshots are not supported. @@ -101,13 +103,19 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto - Each HEAD is logically full: restore never chains deltas. - A flat (format 1) HEAD is upgraded at its next cut ([chunk manifests](../chunk-manifests.md)). In a host-side proxy, the root of a 10 GiB volume shrank from 261,531 bytes (flat) to 2,172 bytes (two-level) (§13). +**How versions share data.** A HEAD, a snapshot and a fork root are each a complete map from chunk index to chunk key. There is no backing chain and no per-layer bitmap that falls through to a parent, as qcow2 backing files or overlay layers have. +- A cut uploads a new key only for a chunk whose content changed (§5, step 6) and rewrites only the segments that list such chunks. Every other index keeps its key, and every other segment its object, from the previous HEAD. A snapshot copies the root; a fork writes a new root with the same references (§6). Neither copies a chunk or a segment. +- So a chunk that was not rewritten after a snapshot is the same object in that snapshot, in every later snapshot and in HEAD. A chunk rewritten after the snapshot has an old key that only the snapshot (and any earlier version that shares it) still references. +- A read looks up one map: the root, one segment, one chunk. It never walks a chain, and deleting a version never requires merging another one. +- The dirty bitmap (§4) is local state on the holder's host. It records which chunks changed since the last HEAD, so that the next cut knows what to compare and upload. It is not stored with a snapshot, and reads do not use it. +- Example: a volume holds 100 non-zero chunks when snapshot `init` is taken; then 20 of them are rewritten and snapshot `snap1` is taken. `snap1` and HEAD each list 100 keys, 80 of them the same as in `init`. The store holds 120 chunk objects, not 200. Deleting `init` frees exactly its 20 old keys, and only once GC finds them unreferenced (§6); the 80 shared objects are neither moved nor copied. +- The cost of complete maps falls on the cut: a scattered write pattern dirties many 4 MiB chunks and many segments (§14, cut cost). + ## 4. Dirty tracking -- **In memory:** every extent write marks its chunk dirty, in O(1), with no I/O and no remote call (`chunk_layer.go` `OnExtentWrite`; the set is `chunkLayerImpl.dirty`). A rebuild BASE write sets a constant-time all-dirty flag instead. -- **Off the write path:** WAL entries carry their LBA, so the dirty set is the persisted bitmap plus the chunks of WAL entries above the checkpoint (`walChunks`). The bitmap is made durable before the checkpoint advances past those entries (`BeforeCheckpointAdvance`, called from walstore `persistCheckpointReleasing`); an error refuses the advance and the WAL keeps the entries. -- **On disk:** `FileChunkBitmapStore` (`core/storage/chunk_bitmap_file.go`) is one state file (a header `{BaseLSN, HeadGen, Epoch, Base}` and the dirty chunk indices, with a SHA-256 over the body) replaced atomically on every change, plus an append-only delta log with one record per closed HEAD period. -- **Reset:** only after a successful HEAD CAS at cut H. The new header is `{BaseLSN: H, HeadGen, Epoch}`; chunks dirtied after the cut stay set (`chunkBitmapStore.Reset`, stillDirty). -- **Over-report, never under-report.** A lost bitmap, or a header that does not match HEAD `{RemoteLSN, Gen, Epoch}`, falls back to a background per-chunk SHA-256 comparison against HEAD; cuts are refused until it finishes (`startReconcile`, `errChunkReconciling`). +- **Native v3:** the owned per-chunk LSN map and retained WAL/in-memory mutations determine dirt relative to HEAD (`captureCandidates`). UNKNOWN is conservative. Map coverage is durable with the checkpoint before reuse, and a cut certifies only unchanged captured versions after successful publication. +- **Post-H writes:** per-chunk mutation versions prevent a cut from certifying newer local bytes as remotely clean. Abort merges every in-flight candidate back into dirt. +- **Legacy evidence:** temporary v2 test constructors retain fake bitmap branches and old-format codec controls. There is no production FileChunkBitmapStore or C11 file; the owned map is authoritative for v3. ## 5. The cut @@ -116,18 +124,64 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto 1. **Admit:** refuse when closed, fenced, detached, during a base install, or when `CaptureAllowed` fails (healthy primary, unchanged lineage, valid lease). 2. **Pre-copy:** while more than `BarrierBound` chunks would be copied under the barrier (`--chunk-dirty-threshold`, default 512), stage up to that many per round outside the barrier, for at most `chunkStageRounds` (3) rounds (`stage`). A staged chunk with new bytes is uploaded under a fresh key named by an intent written first. 3. **Quiesce:** take the capture barrier (walstore `captureMu`) exclusively, then `Sync`. H is the synced LSN; no data newer than H exists in the WAL or the extent. -4. **Copy:** read every candidate chunk through the normal read path into immutable buffers and hash them; release the barrier. The pause is `Sync` plus this copy. A staged copy is reused only if its chunk was not written since and HEAD is unchanged. +4. **Open and copy:** install the fixed candidate window under the barrier, then release it. Bounded workers copy through the validated reader outside the barrier. A first writer saves a pending candidate before mutation; a writer waits only for its own copying/saving chunk. A staged copy is reused only if its version and HEAD still match. Pause is Sync plus candidate/window installation, independent of copy bytes. 5. **LSN guard:** if H is below HEAD's `RemoteLSN`, refuse (`lsn_behind`). 6. **Diff:** upload only chunks whose SHA-256 differs from HEAD; drop all-zero chunks from the map. 7. **Intent first:** write an intent naming every key, then upload in parallel (`UploadConcurrency`, `--chunk-upload-concurrency`, default 8, 1 to 64). 8. **Manifest:** build segments; new segments are also covered by an intent before upload (`PrepareManifest`). 9. **Re-admit** right before the CAS; fence if a superseding holder owns HEAD (`supersededBy`). -10. **CAS** HEAD on `{gen, epoch}` with `RemoteLSN = H`. On success, drop the intents and reset the bitmap, keeping post-cut dirt. +10. **CAS** HEAD on `{gen, epoch}` with `RemoteLSN = H`. On success, drop the intents and settle unchanged owned-map versions, keeping post-cut dirt. 11. **Unknown outcome:** re-read HEAD; never retry blindly. If unresolved, keep the proposal pending and keep the intents. `ChunkRemote.CASHead` (`core/frontend/chunkstore/chunk_remote.go`) refuses a lower epoch, any move of a `deleting`, `purging` or `deleted` HEAD, a `{gen, epoch}` mismatch and a lower `RemoteLSN`, then issues the filer's conditional `UpdateEntry` with `expected_extended = {swb.gen, swb.epoch}`. Only a definite refusal is a precondition failure; any other error is an unknown outcome. -**Reads after a move.** A block absent locally is fetched from the chunk named in HEAD, bounded by `ReadMissTimeout` (default 30 s), and installed only if no newer local version exists; the dirty map is consulted again after the fetch, so a newer local write always wins (`OnReadMiss`; walstore `readFromExtent`). +**Reads after a move.** A block absent locally is fetched from the chunk named in HEAD, by a bounded per-chunk shared worker. Frontend callers share their arrival deadline across attach and all missing chunks; contextless internal readers retain `ReadMissTimeout` (default 30 s). Fetched bytes are installed only if they do not overwrite a newer local extent version; the dirty map is consulted again after the fetch, so a newer WAL-only write still wins on reads, and HEAD's value may sit beneath it as the backing value, which is correct if a crash loses that unsynced write (`OnReadMiss`; walstore `readFromExtent`). + + +### Copy-before-write in the cut window (native v3 implementation) + +**Problem.** Steps 3–4 hold `captureMu` exclusively while every non-staged candidate chunk is copied; `Write`, `WriteBatch`, `ApplyEntry` and `WriteExtentDirect` take `captureMu` shared, so every write waited for the whole copy. A cut-stall measurement on two lab hosts gave a maximum stall of 1.50 s with 3 GiB dirty and 0.67 s with 512 MiB (p99 15–20 ms). Pre-copy staging shortens it only when the staging rounds converge. + +**Design.** +1. **Short barrier; `capMu` held for the whole cut.** The chunk layer's `capMu` stays held from admission to the end of the cut, as today; it already serializes Capture with Evict and Begin/EndBaseInstall, so no BASE install can start inside a window. Under `captureMu` exclusive the cut's `Sync` fixes H and the candidate set D is fixed as today (the owned chunk LSN map relative to HEAD plus retained WAL and in-memory mutations). A COW window `{H, D, state per chunk, refcount}` is installed in the chunk layer, then only `captureMu` is released. The stall becomes `Sync` plus fixing D, independent of the bytes to copy. +2. **Per-chunk state and one owner.** Each chunk of D is `pending`, then exactly one owner moves it on, under a small per-chunk mutex that is never held across I/O: + - the copier: `pending â†' copying â†' done`; + - a writer: `pending â†' saving â†' saved` (the copier later reads the saved bytes: `saved â†' done`). + Everyone else who finds `copying` or `saving` waits on that chunk's condition until it reaches `done` or `saved`, or until the window is aborted (step 5). +3. **The save happens before publication, outside `store.mu`.** Every mutation that can change what a read returns (`Write`, `WriteBatch`, `ApplyEntry`) runs the COW step right after it takes `captureMu` shared and **before** it takes `lifecycleMu` / `mu`, appends to the WAL or inserts into the dirty map. The save reads the chunk through the ordinary read path, which needs `store.mu`, so it cannot run inside the mutation's critical section; a hook after publication (on the WAL append, the dirty-map insert or the flusher's extent write) would see the new bytes and cannot implement this. Lock order: `captureMu` (shared) â†' per-chunk COW mutex (leaf, released before any read) â†' the read path's own locks. + - chunk not in D, `done` or `saved`: proceed; + - `pending`: become the owner (`saving`), read the chunk (still its content at H), put it in the side store, mark `saved`, wake waiters, proceed; + - `copying` or `saving`: wait (step 2), then re-check. + - **Batches across chunks** (`WriteBatch`; public `ApplyEntry` accepts one block): visit the batch's chunks in ascending chunk index and finish each chunk's step (wait, or save) before the next; no chunk is held while waiting on another, so batches cannot deadlock with each other or with the copier, which owns one chunk at a time. The batch publishes only after all its chunks are `saved`, `done` or outside D. +4. **Copier**, outside the barrier and parallel: for each chunk of D, become the owner (`copying`) or find `saved`; read the live chunk (or the saved bytes) into the cut's immutable buffer, hash it, mark `done`, wake waiters. When every chunk of D is `done`, the window closes: no mutation runs the COW step any more. Upload, manifest and CAS are unchanged (steps 5–11) and work from the buffers, so an unknown CAS outcome keeps today's semantics (proposal pending, intents kept); it does not need the side store. +5. **Terminal states: closed, or aborted.** The window ends exactly once, either closed (step 4) or aborted. Abort is taken on a save error (side store full or an I/O error), cut cancellation, fencing, and before `Recover`, a reset or `Close` in the same open. Abort happens **before** the mutation that hit the error proceeds: the cut is marked failed (retryable, `finishCut` does not run, so the dirty set keeps every candidate and the next cut takes them again), all waiters are woken and proceed without saving, and the copier stops. A guest write is never refused because of a cut problem. `Recover`, a reset and `Close` wait for the abort to finish and join every outstanding owner and reader (step 6) before they take their own locks. +6. **Side store and drain.** Local and per cut: memory up to a bound, then a file in the volume's local root; at most |D| × 4 MiB, in practice the chunks written during the window. Every saving or copying owner holds a window reference from its state claim until all of its live-chunk reads and side-store I/O finish; every additional saved-buffer or side-store reader holds a reference too. Abort atomically invalidates the cut and wakes waiters without waiting for its caller's own reference. Owners release their references on every success and error path; an owner that initiates an abort releases its own reference before any join. `Recover`, a reset and `Close` join all outstanding owners and readers before their destructive transition. The side store is deleted exactly once, after the window is closed or aborted **and** no reference is outstanding; no later state claim or I/O may acquire a reference to that terminal window. Recovery never reads it: after a crash the cut is gone, HEAD is unchanged, and the dirty set is rebuilt from the owned map and the WAL. A locked RW open discards only regular files with this volume's reserved `.cut-cow-` prefix; it never reads their contents. +7. **Reads go through the store's read path as the format-v3 work defines it** (the stable, validated reader), both for the save and for the copier; COW adds no flusher hook and no raw extent read. The flusher moves WAL content to the extent without changing what a read returns, so saving at the flusher would miss writes still in the WAL. +8. **After the CAS** the dirty set keeps every chunk written after H, as `finishCut` does today, so the next cut uploads them. + +**What it does not change.** The bytes a cut uploads (whole 4 MiB chunks whose content changed), the manifest work and the load on SeaweedFS stay the same; COW moves the copy out of the write stall, it does not reduce upload volume. Per-cut statistics (`barrierPauseNs`, `uploadedChunks`, `uploadedBytes` in the `/chunk/cut` body) measure both. + +**Alternatives.** Holding the flusher for candidate chunks (reading the at-H content back from the extent and WAL entries up to H) needs no side store, but the WAL cannot be released for those chunks during the window, and a long upload fills it. Raising `BarrierBound` staging does not bound the stall when writes keep re-dirtying staged chunks. Redirect-on-write at the extent changes the on-disk layout and is out of scope for the current format work. + +**Implementation and lifetime.** `chunk_cut_cow.go` owns the window, single-owner chunk claims and reference drain; the write hook runs before lifecycle/admission/store locks. Copier workers use the configured upload concurrency (default 8). Side payload retains at most 64 MiB in RAM, then spills to an ephemeral file beside the volume, in checked compact candidate slots. This is not an RSS cap: immutable upload buffers and transient owner reads remain additional memory. Side I/O failures abort the cut, not the guest write. Cleanup failures fail the cut diagnostically; side files are never durable evidence. + +Store Close permanently closes attachment admission and captures hooks under captureMu, releases it, then aborts/joins the layer before closing storage. Every Close caller shares completion/result. Recover/reset acquire a window-admission lease and join owners before lower store locks; hook snapshot recheck includes racing first attachment. BASE begin/complete drain the whole cut through capMu. Resume is excluded by BaseInstalling state, not by capMu. A completed install handle's ApplyInstallEntry uses the same pre-publication hook as ordinary ApplyEntry. + +```mermaid +stateDiagram-v2 + [*] --> OPEN: Sync H and fix D under barrier + OPEN --> CLOSED: every candidate staged or copied + OPEN --> ABORTED: save/read failure, cancel, observed fence, destructive transition + CLOSED --> Drain: no new claims + ABORTED --> Drain: wake waiters, discard late results + Drain --> Cleanup: all real owner/reader references returned + Cleanup --> Upload: CLOSED only, immutable output owns bytes + Cleanup --> Retry: ABORTED, merge all candidates back +``` + +**Statistics.** `barrierPauseNs` runs from the capture barrier's Lock request to its release: `lockWaitNs` (the wait for writers already holding it shared), Sync and window installation; native `barrierCopyChunks` is zero. `copyNs` covers outside-barrier materialization/drain. `cowSavedChunks` counts successful saves; `cowSaveNs` and `cowWaitNs` sum per-owner/per-wait elapsed time and are not wall-clock pause. These fields mirror into the actual cut response. Upload sizes and remote GC roots are unchanged. + +**Model and tests.** The existing S4c r2 `CutCOW2` verdict and limits are bound in the [spec correspondence](../spec/README.md#cut-window-implementation-correspondence). One-copier whole-chunk modelling does not certify actual writer ownership, batches or Close/attach. `TestCutCOWV3_*` exercises real native mutation, abort, spill, recovery and close callers; earlier ACTIVE staging/image/intent/CAS controls remain. See [the implementation lock graph and mount rehearsal](cut-cow-validation.md). ## 6. Snapshots, forks, retention, GC, volume delete @@ -135,12 +189,17 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto - **Fork** (`Catalog.Fork`): claim the parent snapshot, check the source is not being deleted, write the target `VOLUME` (origin fork), then a HEAD at gen 1, epoch 0, no holder, with the parent's `RemoteLSN` and references. No segment or chunk is copied: the fork's references are owner-qualified, so it reads the parent's objects, and its root alone keeps them live after the parent snapshot is deleted. - **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; a snapshot with a live fork claim is always kept; deletion uses the same conditional mark as `DeleteSnapshot`. - **GC** (`gc.go` `Collector.run`, operator-driven through `sw-block ops chunk gc`, preview by default; see also `core/frontend/chunkstore/GC.md`): - - roots: every HEAD, every snapshot (including deleting ones), snapshot attempts, live intents, and segment objects; an unreadable segment aborts the mark; + - roots: every HEAD, every named snapshot (including one whose delete is still in progress), every snapshot attempt that is not aborted, live intents, and segment objects; an unreadable segment aborts the mark. A deleted snapshot's attempt stays a root for one grace period after its delete time, then stops counting (`Collector.snapshotAttemptHeads` in `gc_copy.go`); - a capture intent expires only if it is older than the TTL, blockmaster has issued a higher epoch, and the remote HEAD has moved to a higher epoch; copy intents are settled only by a permanent tombstone at their publication target; - the whole mark must finish within the grace period minus the operation deadline, and the collector requires grace greater than the deadline; - a binding is deleted only if it is older than the grace period and was unrooted in two marks at least one grace period apart with unchanged binding bytes; - deletion tombstones the binding (`swb.gc.deleted=1`), deletes the needle, then marks it `done`; bindings are never removed, so a key is never rebound. -- **Volume delete** (`volume_delete.go` `DeleteVolume`): (a) a blockmaster deletion reservation; (b) one HEAD write to `deleting` (refused while HEAD is held); (c) refuse and revert if any snapshot name record exists; (c') commit `deleting → purging` bound to the same incarnation; (e) HEAD becomes `deleted` with no chunks and `VOLUME` is marked deleted. A deleted id is never attached or created again. +- **Freeing an old snapshot's data** takes three separate steps: + 1. **Delete the snapshot** (`sw-block ops chunk snapshot-delete`, `POST /chunk/snapshot/delete`, `Catalog.DeleteSnapshot`), or let retention delete it. This marks the attempt `deleting` with its delete time and removes the name record; no chunk or segment is touched, and a retry is safe (`deleting` and `absent` are both success). + 2. **Run GC with `--apply`.** The deleted attempt stops being a root one grace period after its delete time. A chunk referenced by nothing else then becomes a candidate (if it is itself older than the grace period), and it is deleted only after a second mark at least one grace period later still finds it unreferenced. With the default grace of one hour, a chunk is reclaimed two hours or more after the snapshot delete, and only by GC passes that run after those points. Chunks still referenced by HEAD, another snapshot or a fork are never candidates. + 3. **Volume vacuum in SeaweedFS.** GC deletes the needle; SeaweedFS returns the disk space when it vacuums that volume. Until then the bytes stay on the volume servers. +- **Why a reachability mark and not reference counts.** Chunks and segments are shared by snapshots and forks of any number of volumes. A reference count kept in filer entries and changed by several hosts can be lost or applied twice by a crash or an unknown outcome; a lost increment would delete live data. The mark recomputes reachability from the roots on every pass, and the two-mark grace covers writers that are about to publish keys they already uploaded. The cost is delay: space comes back hours after a delete, not at once. +- **Volume delete** (`volume_delete.go` `DeleteVolume`): (a) a blockmaster deletion reservation; (b) one HEAD write to `deleting` (refused while HEAD is held); (c) refuse and revert if any snapshot name record exists; (c') commit `deleting â†' purging` bound to the same incarnation; (e) HEAD becomes `deleted` with no chunks and `VOLUME` is marked deleted. A deleted id is never attached or created again. HEAD states: @@ -180,9 +239,11 @@ The attempt path is never removed, so a late create can never land after a delet **Host guard** (`core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard`, enabled with `blockvolume --workspace-lease`; see [workspace lease](../workspace-lease.md)): frontend I/O and cuts are admitted only with a granted, unexpired lease for the exact `{volume, replica, epoch}`. Validity is anchored to the renewal request's start time, and blockmaster's `ValidForNs` already subtracts half the clock-skew bound (`core/host/master/workspace_service.go` `leaseFact`). A late reply cannot extend admission. A fenced guard never reopens. The lease is 30 s (`core/authority/authority.go`, `workspaceTTL`); the skew bound defaults to 20 s (`blockmaster --workspace-max-clock-skew`). -**CLEAN move:** Detach publishes the final cut with `State = detached` in one CAS → revoke → the host drains frontend, replication and provider and acknowledges the stored detached HEAD generation → blockmaster checks the detached HEAD and the matching acknowledgement → new epoch → the new host claims HEAD. +**Master side of a renewal** (`core/authority/workspace_lease_view.go`): blockmaster answers a renewal of an established lease from memory, under a small leaf lock, with no disk write and without waiting for other authority writes. The grant is min(now + TTL, durable horizon), where the horizon is the lease expiry stored on disk; a background extension, an ordinary authority write, keeps the horizon about 1.5·TTL ahead of the last renewal that triggered it. Only the first grant of a lease is written synchronously. If extensions fall behind, grants shrink and the host fences by the horizon minus half the skew bound; a failed extension write makes the volume uncertain and refuses renewals that would issue a new or extended grant (a Revoking lease still gets its bounded drain reply). -**FORCED move:** blockmaster waits until both the stored expiry and its conservative restart deadline plus the full skew bound have passed (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). The old host's late CAS fails on the epoch; its uploads become orphans for GC. Writes since the old host's last cut are lost. +**CLEAN move:** Detach publishes the final cut with `State = detached` in one CAS â†' revoke â†' the host drains frontend, replication and provider and acknowledges the stored detached HEAD generation â†' blockmaster checks the detached HEAD and the matching acknowledgement â†' new epoch â†' the new host claims HEAD. + +**FORCED move:** blockmaster waits until both the persisted lease horizon (at least every grant, so at most TTL/2 later than the last grant) and the granted or conservative restart deadline, plus the full skew bound, have passed (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). The old host's late CAS fails on the epoch; its uploads become orphans for GC. Writes since the old host's last cut are lost. **Takeover** (`core/storage/chunk_restore.go` `ClaimChunkHead`, called before the chunk layer attaches in `core/frontend/durable/provider_chunk.go`): read HEAD; fence if HEAD has a higher epoch or another holder at the same epoch; seed the local LSN frontier from HEAD (`PrepareRestore`); CAS HEAD to the new epoch and holder with `State = active`; on an unknown outcome, succeed only if a re-read shows the exact proposal. I/O opens afterwards; blocks load lazily on first read. @@ -224,11 +285,11 @@ Lease states: stateDiagram-v2 state "Lease (blockmaster)" as L { [*] --> Granted: Renew - Granted --> Granted: Renew before expiry + Granted --> Granted: Renew before horizon and deadline (from memory) Granted --> Revoking: BeginWorkspaceRevocation Revoking --> Acked: host acks detached HEAD gen while the lease is valid Acked --> Moved: CLEAN move - Granted --> Expired: expiry + Granted --> Expired: horizon or deadline passes Expired --> Moved: FORCED move after expiry + skew bound } ``` @@ -307,7 +368,7 @@ Not done yet: Measurements, not SLOs; each is the median of 3 runs. [Workspace measurements](../workspace-measurements.md) has every number and how it was measured. -- **Workloads** (Firecracker microVMs, 4 vCPU, 4 GiB, one bare-metal host, NVMe/TCP loopback): metadata-heavy agent workloads (`npm ci`, `git clone`, untar, `find` + `stat`) ran at local-disk speed. The cost is `fsync` latency: 2,000 × create + write + `fsync` took 14.33 s against 6.09 s on a local disk, about 7 ms against 3 ms per `fsync`. Reducing it is in progress; the per-stage histograms are described in [fsync latency](../fsync-latency.md). +- **Workloads** (Firecracker microVMs, 4 vCPU, 4 GiB, one bare-metal host, NVMe/TCP loopback): metadata-heavy agent workloads (`npm ci`, `git clone`, untar, `find` + `stat`) ran at local-disk speed. The cost was `fsync` latency: 2,000 × create + write + `fsync` took 14.33 s against 6.09 s on a local disk, about 7 ms against 3 ms per `fsync`. After the group-commit fix (#173), guest `fsync` is a median of 3.23 ms against 2.74 ms local with the ublk frontend (3.59 ms over NVMe/TCP loopback); [workspace measurements](../workspace-measurements.md) has both rounds. The per-stage histograms are described in [fsync latency](../fsync-latency.md). - **Snapshot and fork** (host-side proxy, a 10 GiB volume of 2,560 chunks, no network latency, guest `fsync` or block frontend): HEAD root 2,172 bytes; snapshot 0.18 ms; fork 0.29 ms (flat manifest: 261,531 bytes, 5.79 ms, 10.67 ms). - **Cut upload** (same proxy): 64 dirty chunks (256 MiB) in 624 ms with one upload at a time, 434 ms with 8 in parallel. - **Two-host lifecycle** (Firecracker VMs, SeaweedFS chunk backend): create, write, two snapshots, fork, clean move, stale-holder replay refused, delete, GC; 35 of 35 checks passed, GC reclaimed 38 of 38 candidates and every reclaimed chunk returned 404. @@ -319,7 +380,7 @@ These are tracked for fixes. Gaps that apply to the whole codebase (authenticati - **Moving back to a host with a surviving local file** fails closed with `ErrChunkStaleLocalRoot` (§7). **Follow-up:** recreate the local root from HEAD automatically instead of refusing. - **Default RPO is unbounded.** No automatic cut is enabled by default (§2). - **The master is a single point of failure.** A master outage longer than the lease stops I/O on every workspace, and recovery is a forced move. -- **Cut cost.** The barrier pause includes copying every non-staged candidate chunk (up to the dirty threshold, 512 chunks by default), held in RAM until upload. A 4 KiB write re-uploads its 4 MiB chunk, and a read miss after a move fetches the whole chunk with no request coalescing. +- **Cut cost.** The barrier pause includes copying every non-staged candidate chunk (up to the dirty threshold, 512 chunks by default), held in RAM until upload. A 4 KiB write re-uploads its 4 MiB chunk, and a read miss after a move fetches the whole chunk with no request coalescing. **Proposed:** copy-before-write takes the copy out of the barrier (§5); it does not change the upload volume. - **GC is manual.** Needles uploaded without a persisted key binding are never reclaimed. An intent stamped by a host clock running ahead of the GC runner fails the whole pass (liveness, not safety). - **Filer conditional update: multi-filer and old-filer cases.** Reading the open-source SeaweedFS filer: `UpdateEntry` takes an exclusive lock on the path before it validates `expected_extended`. The concurrent case against one pinned filer is tested (#163). Not tested: several filers sharing a store, and a filer that predates the field (there is no capability probe). **Planned:** a multi-filer test and a probe. - **No multi-replica workspaces with chunk snapshots**, and no crash-restart recovery of a ublk server (a crashed server fails closed). diff --git a/seaweed-block/docs/design/block-design.md b/seaweed-block/docs/design/block-design.md index 21912bbebc..dae9c48a72 100644 --- a/seaweed-block/docs/design/block-design.md +++ b/seaweed-block/docs/design/block-design.md @@ -12,6 +12,8 @@ The design is split into three documents: this shared core and one document per Code references name a file and a function, not a line number, so they stay valid as the code changes. Test references name the test function and its file. "Model-checked" means the protocol was specified in TLA+ and checked exhaustively with TLC at small scale. The specifications are in [`docs/spec/`](../spec/README.md); Go regression tests are the in-repo evidence for every counterexample found that way. +The state machines and the invariant ledger of all three documents, with the rules for changing them, are collected in [Invariants and state machines](invariants.md). + ## Contents - [Part 1. Core block service](#part-1-core-block-service) @@ -93,6 +95,22 @@ stateDiagram-v2 ## 1.2 walstore: WAL plus extent +**Production format v3.** Create writes impl3; v2/impl1 and v2/impl2 require explicit offline migration or recreation/HEAD restore. Chunk geometry is fixed at create from the provider configuration. Mode C is the default; mode A is an explicit create option. Both descriptor slots and their owned immutable map dependencies are validated at open, under exclusive file ownership. The creator holds that same fd from O_EXCL through slot publication and store construction. + +```mermaid +flowchart LR + A["slot A: 0..4095"] --- B["slot B: 4096..8191"] --- W["WAL: starts 8192"] --- E["block extent"] + A -. "root hash / lineage" .-> M["owned COW chunk LSN map sidecar"] + B -. "both valid slots pin dependencies" .-> M + F["extent fsync + metadata barrier"] --> C["COW map durable"] --> P["single descriptor publisher"] --> R["reuse only above both-slot floor"] +``` + +The native record is a 62-byte prefix (LSN, batch count, type/flags, LBA/length, DurableLSN, absolute logical start and 128-bit WAL nonce) plus payload and an 8-byte CRC32C/size trailer: 70 bytes overhead. Appends are physically LSN-strict within an incarnation. Reads validate the entire containing record before returning a block. Recovery uses the physical trusted prefix and the mode/BASE watermark rules, then fences dropped byte ranges before reuse. Same-open Recover invalidates map proofs at both entry and exit. All runtime descriptor mutations converge through `descriptorPublisherV3.publishLockedCoreV3`; initial creation and the explicitly offline migration tool are the pre-serving exceptions. + +The flusher prepares map coverage within its original recovery lifetime, syncs extent and metadata, and publishes checkpoint/map/W/tail together; fallback rollover releases no bytes until both slots permit it. Installed/installing BASE uses install handles; logical Sync while installing is refused, while receiver-only SyncInstallLog follows strict durability. Mode C physically syncs each covering batch but can persist the previous acknowledged W; A persists the current covering W before acknowledgment. The final mode-C window and corruption oracles are specified by the canonical format contract; this summary does not weaken its gates. + +The [exact temporary legacy test inventory](format-v3-legacy-test-inventory.md) pairs old-format controls with native replacements. The following original diagrams and scan explanation describe the **legacy v2 fixture/offline-input format**, retained until row 14a; they are not the active production byte layout or recovery algorithm. + **Layout.** One preallocated file with a 4 KB superblock, a circular WAL, and a block-indexed extent (`core/storage/walstore.go`, type comment of `WALStore`). - The superblock holds geometry, `WALHead` and `WALTail` (monotonic logical byte cursors), `WALCheckpointLSN` (the highest LSN durably in the extent) and the engine kind; opening a file of the wrong kind is refused (`core/storage/superblock.go`). - A WAL record is a 30-byte header (LSN, reserved, type, flags, LBA, length), the data, and an 8-byte trailer (CRC32, record size) (`core/storage/wal_entry.go`). A record that does not fit at the end of the region is preceded by a padding record and starts at offset 0 (`core/storage/wal_writer.go` `walWriter.append`). @@ -377,9 +395,7 @@ These are tracked for fixes. Most were raised by an independent review of this r - **NVMe/TCP H2CData offset overflow.** The `DATAO + length` bound check is done in 32-bit arithmetic and can wrap, so one malformed PDU can panic the process (`core/frontend/nvme/session.go` `recvH2CData`). Reachable from loopback by default. **Planned fix:** 64-bit arithmetic, offset and R2T consistency checks, and bounds on wire-supplied allocations. - **Process notes in source comments.** #162 removed reviewer names and decision timestamps from code comments. A few comments still cite internal review labels (for example "ruling F1") where a neutral design rationale would be clearer. -- **fsync latency (about 7 ms against 3 ms local).** Leads to measure with the `/status/durable` histograms: - - the group committer waits a full 1 ms unless 64 waiters are queued, so at queue depth 1 every `fsync` pays at least 1 ms; - - the checkpoint superblock `fsync` runs under the exclusive store lock, stalling reads and writes each flush cycle. +- **fsync latency.** #173 removed the idle group-commit wait: a lone `Sync` no longer waits out the collection delay, and guest `fsync` fell from about 5.5 ms to a median of 3.23 ms against 2.74 ms local (ublk; see [workspace measurements](../workspace-measurements.md)). Remaining lead: the checkpoint superblock `fsync` runs under the exclusive store lock, stalling reads and writes each flush cycle. - **smartwal crash window.** A crash between the in-place write and the ring append can leave the volume unopenable (§1.3). smartwal is experimental and not a default: standalone `blockvolume` creates new volumes as walstore (auto), and Kubernetes and workspaces use walstore. **Planned:** fix the ordering. - **Forged records in user data.** WAL records are not bound to a store incarnation or lap, so bytes inside user data that happen to decode as a valid record could be replayed by the defensive scan. **Planned:** an incarnation nonce and lap in the next format, plus a clean-shutdown marker in the meantime. - **Mid-history WAL corruption only warns** (§1.2 step 2). Fixing it needs the synced watermark in the next format. diff --git a/seaweed-block/docs/design/cut-cow-validation.md b/seaweed-block/docs/design/cut-cow-validation.md new file mode 100644 index 0000000000..7ebff9e2db --- /dev/null +++ b/seaweed-block/docs/design/cut-cow-validation.md @@ -0,0 +1,154 @@ +# Cut-window validation and mount rehearsal + +The native v3 cut fixes H, candidate versions and a window under captureMu, +then copies with bounded workers outside it. It preserves whole chunks, upload +intents, manifest/CAS behavior and the local durability contract. The legacy +engine retained only by test constructors still uses the older barrier cut. + +## Lock and lifetime graph + +```text +BASE begin/complete: installMu X -> capMu -> captureMu -> lifecycleMu + -> syncMu/store.mu -> descMu -> fileSyncMu +completed handle write: installMu R -> captureMu R -> COW claim/release + -> validated Read -> release reference + -> lifecycleMu/admission/store.mu -> WAL/dirty map +cut: capMu -> captureMu X (Sync, H/D, window); release captureMu -> copy +claim/finish: layer.cowMu -> window.mu -> entry.mu; release before all I/O +Close: captureMu X (permanent attach shutdown + stable hook snapshot); RELEASE + -> layer abort + actual reference/waitgroup join -> lifecycleMu X +Recover/reset: admission lease + abort/join, without lower store locks + -> captureMu (hook snapshot recheck) -> existing lower locks +``` + +Only short state transitions hold window/entry locks. No read, file create, +spill read/write, wait, callback into the store or reference join holds them. +A saver that aborts releases its own reference before any join. A terminal +notification wakes waiters immediately; late I/O cannot publish a saved result. +The active-window fast path is an atomic pointer load. With no window there +is no chunk lock, allocation or side I/O. + +Recover/reset keep their lease until their lower locks have been released; +first-attach hook snapshots are retried under captureMu. BASE resume is +excluded by BaseInstalling, not by a nonexistent capMu drain. Close atomically +shuts attachment admission with its hook snapshot and all callers share the +same completed shutdown result. + +## Space and measurements + +The 64 MiB budget covers retained in-memory saved payload only, not immutable +upload buffers or transient owner reads. Spill offsets are compact candidate +slots, checked against MaxInt64 before installation. Spill files are per cut, +not fsynced or replayed, and are removed only after terminal plus zero actual +references. A later exclusively locked RW open removes regular files with +this volume's reserved `.cut-cow-` prefix; other prefixes, directories and +symlinks are left alone. Cleanup failure fails the cut diagnostically, without +changing any guest write outcome. + +`barrierPauseNs` runs from the capture barrier's Lock request (a pending Lock +already blocks new writers) to its release: it includes `lockWaitNs`, the wait for +writers already holding the barrier shared, and Sync/window setup, not chunk reads. `copyNs` is the +outside-barrier copy and drain. Native `barrierCopyChunks`/`barrierOverBound` +are zero; the configured threshold still bounds staging, not a hard COW-copy +limit. `cowSavedChunks`, `cowSaveNs`, `cowWaitNs` are mirrored into the cut +body. Save/wait times sum concurrent owners and must not be added to interpret +a wall-clock pause. `cut_aborted` is retryable (503); a wrapped ordinary fence, +shutdown or authority cause retains its existing classification. + +## Real-mount rehearsal (planned, not executed) + +This is a rehearsal note, not a lab packet or permission to run a mount. The +existing frozen M5 ublk/NVMe packet and its host/volume allocation remain the +starting point. Freeze the reviewed build SHA, weed SHA, map geometry, +UploadConcurrency and frontend options in that packet before execution. +Use only the assigned disposable volume, never a production/user filesystem. + +1. Rebuild the existing blockvolume/sw-block binaries at the reviewed SHA and + replay the unchanged M5 mount/setup. Record the device, filesystem and + status URL. Verify the frontend reads/writes the expected v3 volume. +2. Populate 8 then 64 distinct 4 MiB chunks with deterministic patterns and + fsync. Capture a baseline HEAD and preserve its manifest/hash receipts. +3. On the mounted file, run the existing 4K random-write/fsync workload at + QD1 and QD8 while issuing cuts through the real route: + + ```sh + sw-block ops chunk cut --volume "$VOLUME_ID" \ + --status-addr "$STATUS_URL" --timeout 2m + ``` + + Record fio JSON, all cut JSON, frontend durability-stage histograms, + writer p50/p99/max, barrier/copy/total times, upload bytes, save/wait counts, + RSS and spill bytes. Compare interleaved parent/candidate runs with identical + setup. Backend proxy timings are not guest/mount results. +4. Read back literal acknowledged patterns after the concurrent run. Validate + each HEAD against the write-log prefix at its returned H, then make another + cut and restore it on the packet's second host; verify the complete image. +5. Repeat Close/cancel during a long cut and an abrupt process stop while a + side file exists. Reopen the local v3 image, verify acknowledged data, then + cut and restore again. Side data must not be imported; HEAD can only be + either the last complete CAS or a complete newer CAS, never a partial image. +6. Stop/join workloads before the packet's normal unmount/cleanup. Preserve + receipts and report actual overhead/stalls; do not claim COW reduces upload + volume. Save failure must abort the cut while ordinary writes keep working. + +Deterministic native tests exercise held saving, saved-file and live-copy +owners, first attach vs Close, hook-snapshot races in Recover/reset, overlapping +public batches, cancellation and observed fencing. They complement the +bounded one-copier/whole-chunk S4c r2 verdict; they are not a substitute for the +future real-mount run. + +## Caller closure + +| Caller/path | COW admission or exclusion | Control | +|---|---|---| +| Write, WriteBatch | after immutable argument checks and captureMu R; before lifecycle/admission/store publication | MutationCompletesWhileEarlierChunkCopyIsHeld (including a checkpointed post-H rewrite); OverlappingRealBatchesPreserveCut; InvalidInputsDoNotSaveOrAbortWindow | +| ordinary ApplyEntry, completed handle ApplyInstallEntry | actual applyEntryV3 hook; completed handle's existing install admission stays outside it | MutationCompletesWhileEarlierChunkCopyIsHeld / ApplyEntry and ApplyInstallEntry | +| pending/saving/copying collisions | one owner, wait on per-entry notification or terminal | CopyingChunkWaitsButPendingChunkSaves; TwoWritersOneSaveAndCloseJoinsSavedReader | +| Cut, Capture, Detach, MakeRemoteDurable | same capMu/captureLocked path; immutable buffers after terminal/drain | existing C1/C3 image, staged reuse, Detach, MakeRemoteDurable and unknown-CAS/intent controls remain native | +| Recover and reset | beforeDestructive lease, abort/join, capture barrier snapshot recheck | RecoveryAndCloseDrainSavingOwner; DestructiveSnapshotRetriesFirstAttachment | +| Store Close / standalone layer.Close / second Close | permanent attachment gate + stable snapshot; terminal and actual owner/waitgroup drain | CloseCannotMissFirstAttachment; CloseSnapshotRejectsFirstAttachAndSharesCompletion; CloseJoinsHeldLiveCopy; RecoveryAndCloseDrainSavingOwner; TwoWritersOneSaveAndCloseJoinsSavedReader | +| BASE begin/complete | existing installMu/capMu transition drains whole cut | existing attached BASE lifecycle/capture-generation controls | +| BASE WriteBase / resume | installing state excludes a cut; resume is not capMu-drained | existing install-handle state/owner controls; native COW hook does not weaken them | +| SeedChunkFrontier / WriteExtentDirect | attached seed refused; public v3 direct write refused | existing seed/direct caller controls | +| Flusher / lazy fill | materialize existing visible bytes; no new read-visible mutation, no new hook | SaverUsesValidatedWALBatchAndLazyHEAD (WAL-only and flushed batch); existing PostReadMissRechecksWALFormat | +| Temporary v2 fixture mutation paths | remain behind the full-copy barrier; no production C11 file | existing legacy fixture controls and production reachability guard | + +Test names above have prefix `TestCutCOWV3_` unless an existing control is named. +The abrupt-process control `ProcessCrashDropsSideAndRestoresSyncedImage` exits +with an OPEN spill and no cleanup, then the parent reopens, validates the +synced post-H bytes, observes the actual old HEAD and publishes the next image. +`SpillIsEphemeralAndCleanupIsPrefixScoped` additionally covers ignored corrupt +side payloads and preservation of other-prefix files/directories. + +## Backend proxy result + +The source-identical `BenchmarkCutCOWProxy` was run parent/candidate interleaved +three times, each row with three cuts, on tp04 (i7-13700, Go reports GOMAXPROCS +24; actual work stays under the runner's quota). Parent is main d0e3895a plus +only the benchmark, ref 3faecbd4. Candidate timing head is ee6c6f3b. Staging is +disabled, copy/upload concurrency is 8, chunks are 4 MiB and each released +writer performs one 4K write+Sync per cut. Writers start at the real Sync/H +handshake. A memory ChunkRemote keeps identical upload work in both arms; +this is file-backed storage with an in-process remote, not network, guest or +mount performance. No throughput/fsync guarantee is inferred from it. + +The table reports medians of the three per-run values, in milliseconds. Each +per-run p99 has only 3 samples at QD1 or 24 at QD8; these are sample percentiles, +not estimates of a production tail. The full raw stage/timing rows are kept +with the review receipts. Later source changes are fence-observation ordering, +cleanup-error reporting and additional caller controls; they are not timed by +these earlier-head measurements. + +| Geometry / writers | Barrier ms parent -> COW | Writer p50 ms parent -> COW | Writer p99 ms parent -> COW | Total cut ms parent -> COW | +|---|---:|---:|---:|---:| +| chunks8/QD1 | 41.15 -> 0.54 | 41.72 -> 8.38 | 44.79 -> 8.62 | 74.12 -> 45.44 | +| chunks8/QD8 | 40.46 -> 0.47 | 43.24 -> 9.71 | 43.27 -> 12.48 | 71.84 -> 43.63 | +| chunks64/QD1 | 312.68 -> 0.50 | 324.78 -> 8.35 | 346.51 -> 8.61 | 554.93 -> 356.54 | +| chunks64/QD8 | 308.86 -> 0.54 | 309.59 -> 15.29 | 347.69 -> 20.42 | 531.13 -> 346.85 | + +Each 8-chunk cut uploads 32 MiB and each 64-chunk cut uploads 256 MiB in both +arms. COW reduces the barrier/copy stall and parallelizes materialization; +it does not reduce remote upload volume. The native mutation control reports +one real save (and positive save time), zero barrier copies, and verifies +post-H map dirt even after the new bytes have checkpointed. No mounted result +is claimed; use the rehearsal above for that separate measurement. diff --git a/seaweed-block/docs/design/format-v3-legacy-test-inventory.json b/seaweed-block/docs/design/format-v3-legacy-test-inventory.json new file mode 100644 index 0000000000..fa42b85869 --- /dev/null +++ b/seaweed-block/docs/design/format-v3-legacy-test-inventory.json @@ -0,0 +1,1779 @@ +[ + { + "file": "cmd/sw-block/migrate_test.go", + "test": "TestMigrateV3BadGeometryRefusedBeforeAnyWrite", + "legacy_roots": [ + "CreateLegacyWALStoreTest" + ], + "reason": "real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage", + "v3_controls": [ + "TestMigrateV3VolumeOpensAsV3", + "TestMigrateV3PreparedOnlyRefusedByV3Open" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "cmd/sw-block/migrate_test.go", + "test": "TestMigrateV3CleanVolume", + "legacy_roots": [ + "CreateLegacyWALStoreTest", + "OpenLegacyWALStoreTest" + ], + "reason": "real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage", + "v3_controls": [ + "TestMigrateV3VolumeOpensAsV3", + "TestMigrateV3PreparedOnlyRefusedByV3Open" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "cmd/sw-block/migrate_test.go", + "test": "TestMigrateV3CrashAfterEachStepIsResumable", + "legacy_roots": [ + "CreateLegacyWALStoreTest" + ], + "reason": "real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage", + "v3_controls": [ + "TestMigrateV3VolumeOpensAsV3", + "TestMigrateV3PreparedOnlyRefusedByV3Open" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "cmd/sw-block/migrate_format_v3_test.go", + "test": "TestMigrateV3ExcludesOpenUntilCommitFinishes", + "legacy_roots": [ + "CreateLegacyWALStoreTest" + ], + "reason": "real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage", + "v3_controls": [ + "TestMigrateV3VolumeOpensAsV3", + "TestMigrateV3PreparedOnlyRefusedByV3Open" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "cmd/sw-block/migrate_test.go", + "test": "TestMigrateV3NeverRestoresTheBackup", + "legacy_roots": [ + "CreateLegacyWALStoreTest" + ], + "reason": "real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage", + "v3_controls": [ + "TestMigrateV3VolumeOpensAsV3", + "TestMigrateV3PreparedOnlyRefusedByV3Open" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "cmd/sw-block/migrate_test.go", + "test": "TestMigrateV3OldBinaryAfterPreparation", + "legacy_roots": [ + "CreateLegacyWALStoreTest", + "OpenLegacyWALStoreTest" + ], + "reason": "real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage", + "v3_controls": [ + "TestMigrateV3VolumeOpensAsV3", + "TestMigrateV3PreparedOnlyRefusedByV3Open" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "cmd/sw-block/migrate_test.go", + "test": "TestMigrateV3OldWALOverwritesThePreparedSlot", + "legacy_roots": [ + "CreateLegacyWALStoreTest" + ], + "reason": "real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage", + "v3_controls": [ + "TestMigrateV3VolumeOpensAsV3", + "TestMigrateV3PreparedOnlyRefusedByV3Open" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "cmd/sw-block/migrate_format_v3_test.go", + "test": "TestMigrateV3PreparedOnlyRefusedByV3Open", + "legacy_roots": [ + "CreateLegacyWALStoreTest" + ], + "reason": "real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage", + "v3_controls": [ + "TestMigrateV3VolumeOpensAsV3", + "TestMigrateV3PreparedOnlyRefusedByV3Open" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "cmd/sw-block/migrate_test.go", + "test": "TestMigrateV3RefusalsChangeNothing", + "legacy_roots": [ + "CreateLegacyWALStoreTest" + ], + "reason": "real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage", + "v3_controls": [ + "TestMigrateV3VolumeOpensAsV3", + "TestMigrateV3PreparedOnlyRefusedByV3Open" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "cmd/sw-block/migrate_test.go", + "test": "TestMigrateV3RetirementRerunFsyncsTheDirectory", + "legacy_roots": [ + "CreateLegacyWALStoreTest" + ], + "reason": "real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage", + "v3_controls": [ + "TestMigrateV3VolumeOpensAsV3", + "TestMigrateV3PreparedOnlyRefusedByV3Open" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "cmd/sw-block/migrate_format_v3_test.go", + "test": "TestMigrateV3VolumeOpensAsV3", + "legacy_roots": [ + "CreateLegacyWALStoreTest" + ], + "reason": "real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage", + "v3_controls": [ + "TestMigrateV3VolumeOpensAsV3", + "TestMigrateV3PreparedOnlyRefusedByV3Open" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "cmd/sw-block/internal/v2legacy/real_store_legacy_test.go", + "test": "TestReadSuperblockRefusesOtherFormats", + "legacy_roots": [ + "CreateLegacyWALStoreTest" + ], + "reason": "real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage", + "v3_controls": [ + "TestMigrateV3VolumeOpensAsV3", + "TestMigrateV3PreparedOnlyRefusedByV3Open" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "cmd/sw-block/internal/v2legacy/real_store_legacy_test.go", + "test": "TestScanCleanOnRealV2Stores", + "legacy_roots": [ + "CreateLegacyWALStoreTest" + ], + "reason": "real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage", + "v3_controls": [ + "TestMigrateV3VolumeOpensAsV3", + "TestMigrateV3PreparedOnlyRefusedByV3Open" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/flusher_test.go", + "test": "TestAllBlocks_ReturnsBlocksAfterFlush", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_checkpoint_safety_test.go", + "test": "TestCheckpointPublicationCrashWindowsRemainRecoverable", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_typed_cause_test.go", + "test": "TestChunkCut_BaseInstallRefusalIsTyped", + "legacy_roots": [ + "createLegacyWALStoreWithOptions" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_precopy_test.go", + "test": "TestChunkCut_RecoverWaitsForTheCaptureBarrier", + "legacy_roots": [ + "createLegacyWALStoreWithOptions" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_lsn_order_test.go", + "test": "TestChunkCut_RemoteLSNNeverDecreases", + "legacy_roots": [ + "createLegacyWALStoreWithOptions" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_c11_test.go", + "test": "TestChunkLayer_C11_BaseRebuildRecovery", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_c11_test.go", + "test": "TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_c11_test.go", + "test": "TestChunkLayer_C11_ExtentCallbackIsPureInMemory", + "legacy_roots": [ + "createLegacyWALStoreWithOptions" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_c11_test.go", + "test": "TestChunkLayer_C11_IncrementalAfterRestart", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_c11_test.go", + "test": "TestChunkLayer_C11_LostOrMismatchedBitmapFallsBackToHashCompare", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_c11_test.go", + "test": "TestChunkLayer_C11_ReplicaApplyKeepsBitmap", + "legacy_roots": [ + "createLegacyWALStoreWithOptions" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_c11_test.go", + "test": "TestChunkLayer_C11_RolloverKeepsPostCutDirt", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_c11_test.go", + "test": "TestChunkLayer_C11_SaveThenCheckpointFailureOverReportsOnly", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_fresh_bitmap_test.go", + "test": "TestChunkLayer_LostBitmapReconciles", + "legacy_roots": [ + "createLegacyWALStoreWithOptions" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_precopy_test.go", + "test": "TestChunkPrecopy_LowerLSNApplyAfterStagingIsNotLost", + "legacy_roots": [ + "createLegacyWALStoreWithOptions" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_precopy_test.go", + "test": "TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage", + "legacy_roots": [ + "createLegacyWALStoreWithOptions" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_reconcile_test.go", + "test": "TestChunkReconcile_BaseInstallSupersedesRunningReconciliation", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_reconcile_test.go", + "test": "TestChunkReconcile_DetachDeadlineWhileReconciling", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_reconcile_test.go", + "test": "TestChunkReconcile_DetachWaitsForReconciliation", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_reconcile_test.go", + "test": "TestChunkReconcile_NoHeadMovesWhileReconciling", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_reconcile_test.go", + "test": "TestChunkReconcile_OldCompletionCannotCertifyReplacement", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_reconcile_test.go", + "test": "TestChunkReconcile_OldWorkerCannotModifyReplacementSet", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_reconcile_test.go", + "test": "TestChunkReconcile_ResultPersisted", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_reconcile_test.go", + "test": "TestChunkReconcile_UnpersistedResultKeepsReconciling", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_layer_reconcile_test.go", + "test": "TestChunkReconcile_WritesProceedWhileReconciling", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_restore_test.go", + "test": "TestClaimChunkHeadClearsProductionDetachProof", + "legacy_roots": [ + "NewFileChunkBitmapStore" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/flusher_test.go", + "test": "TestCrashFamily_AbruptKillAtMultipleWindows", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_bitmap_file_test.go", + "test": "TestLegacyC11FileCodec_CorruptStateIsLost", + "legacy_roots": [ + "newLegacyC11FileStore" + ], + "reason": "retired C11 file codec retained only in legacy_c11_file_fixture_test.go; no production constructor or file store", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: review historical fixture disposition; row 14b removed the production file store without deleting these codec assertions" + }, + { + "file": "core/storage/chunk_bitmap_file_test.go", + "test": "TestLegacyC11FileCodec_RoundTripAndReopen", + "legacy_roots": [ + "newLegacyC11FileStore" + ], + "reason": "retired C11 file codec retained only in legacy_c11_file_fixture_test.go; no production constructor or file store", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: review historical fixture disposition; row 14b removed the production file store without deleting these codec assertions" + }, + { + "file": "core/storage/walstore_checkpoint_safety_test.go", + "test": "TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/flusher_instrumentation_test.go", + "test": "TestFlusherInstrumentationCountsCheckpointFailure", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 one-superblock-write/one-sync counters and its raw injection seams; v3 record-stage counters are separate, no numerical equivalence claimed for metadata counts", + "v3_controls": [ + "TestFlusherV3ProfileCountsRealRecordStages", + "TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/flusher_instrumentation_test.go", + "test": "TestFlusherInstrumentationCountsCompleteCycle", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 one-superblock-write/one-sync counters and its raw injection seams; v3 record-stage counters are separate, no numerical equivalence claimed for metadata counts", + "v3_controls": [ + "TestFlusherV3ProfileCountsRealRecordStages", + "TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/flusher_instrumentation_test.go", + "test": "TestFlusherInstrumentationCountsWALReadFailures", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 one-superblock-write/one-sync counters and its raw injection seams; v3 record-stage counters are separate, no numerical equivalence claimed for metadata counts", + "v3_controls": [ + "TestFlusherV3ProfileCountsRealRecordStages", + "TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_checkpoint_safety_test.go", + "test": "TestFlusherRejectsCorruptOrUnsupportedDirtyRecord", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_checkpoint_safety_test.go", + "test": "TestFlusherSnapshotCannotOverwriteLaterDirectBase", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/flusher_snapshot_cut_test.go", + "test": "TestFlusherSnapshotCutPreservesSyncedWrites", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_checkpoint_safety_test.go", + "test": "TestFlusherWALSlotMismatchFailsClosed", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/flusher_test.go", + "test": "TestFlusher_AdvancesCheckpointBeforeReadFromExtent", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3AdmissionBurstFiveRings", + "TestWALStoreV3AdmissionUsesNativeOccupancy" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/flusher_test.go", + "test": "TestFlusher_ConcurrentWriteRaceLBAStaysFresh", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/flusher_test.go", + "test": "TestFlusher_ManyDirtyEntriesCheckpointStaysCorrect", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/flusher_test.go", + "test": "TestFlusher_RecoveryHonorsCheckpoint", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/flusher_test.go", + "test": "TestFlusher_ReleasesWALPressureAfterCheckpoint", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3AdmissionUsesNativeOccupancy", + "TestWALStoreV3AdmissionStallDeadlineAndResume", + "TestWALStoreV3AdmissionBurstFiveRings" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_restore_test.go", + "test": "TestFreshRestoreBitmapStartsAtClaimedHEAD", + "legacy_roots": [ + "createLegacyWALStoreWithOptions" + ], + "reason": "legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery", + "v3_controls": [ + "TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint", + "TestChunkLayerV3_IgnoresProvidedLegacyBitmap", + "TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/flusher_test.go", + "test": "TestRecovery_DeterministicAcrossMultipleOpens", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_checkpoint_safety_test.go", + "test": "TestRunningFlusherCannotOverwriteDirectBase", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/chunk_frontier_test.go", + "test": "TestSeedChunkFrontierMetadataFailureRetry", + "legacy_roots": [ + "createLegacyWALStoreWithOptions", + "openLegacyWALStoreForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry", + "TestBlockMetadata_SeedFailureRetry" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_sync_generation_test.go", + "test": "TestWALGenerationBypassesUntrackedMutationPaths", + "legacy_roots": [ + "createLegacyWALStoreWithOptions" + ], + "reason": "legacy sync cache/direct-mutation callback order; v3 success boundary is serialized and recovery-generation checked", + "v3_controls": [ + "TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary", + "TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery", + "TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_sync_frontier_order_test.go", + "test": "TestWALGenerationFirstCallerReturnOrdering", + "legacy_roots": [ + "createLegacyWALStoreWithOptions" + ], + "reason": "legacy sync cache/direct-mutation callback order; v3 success boundary is serialized and recovery-generation checked", + "v3_controls": [ + "TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary", + "TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery", + "TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_sync_generation_test.go", + "test": "TestWALGenerationPartialAppendRecoverySync", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "openLegacyWALStoreForTest" + ], + "reason": "legacy sync cache/direct-mutation callback order; v3 success boundary is serialized and recovery-generation checked", + "v3_controls": [ + "TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary", + "TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery", + "TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_multiblock_test.go", + "test": "TestWALMultiBlock_EncodeDecode", + "legacy_roots": [ + "decodeWALEntry" + ], + "reason": "v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound", + "v3_controls": [ + "TestWALStoreV3BatchRoundTripAcrossACrash", + "TestWALStoreV3TornBatchIsAllOrNothing", + "TestWALStoreV3InstrumentationIncludesBatch" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_persisted_tail_test.go", + "test": "TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "openLegacyWALStoreForTest", + "readSuperblock" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALIOV3_RealWriterReopenScan", + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash", + "TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_sticky_fsync_test.go", + "test": "TestWALStoreCheckpointFsyncFailureIsSticky", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_checkpoint_crash_linux_test.go", + "test": "TestWALStoreCheckpointSIGKILLCrashWindows", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_checkpoint_safety_test.go", + "test": "TestWALStoreClosePerformsFinalFlush", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_checkpoint_safety_test.go", + "test": "TestWALStoreCloseReturnsFinalMetadataFailure", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_checkpoint_safety_test.go", + "test": "TestWALStoreCloseWaitsForInflightSync", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_sticky_fsync_test.go", + "test": "TestWALStoreExtentFsyncFailureIsSticky", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_sticky_race_test.go", + "test": "TestWALStoreExtentFsyncFaultAfterThePublicationCheck", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "readSuperblock" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_sticky_race_test.go", + "test": "TestWALStoreExtentFsyncFaultDuringDirectFrontierPublication", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "readSuperblock" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_batch_lsn_reuse_test.go", + "test": "TestWALStoreFailedBatchAppendDoesNotRevertALaterAckedWrite", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound", + "v3_controls": [ + "TestWALStoreV3BatchRoundTripAcrossACrash", + "TestWALStoreV3TornBatchIsAllOrNothing", + "TestWALStoreV3InstrumentationIncludesBatch" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_persisted_tail_test.go", + "test": "TestWALStoreFlushPersistsTheReleasedTail", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "readSuperblock" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALStoreV3CheckpointReclaimsAcrossRingLaps", + "TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_sticky_race_test.go", + "test": "TestWALStoreFsyncsOfTheFileAreSerialized", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_persisted_tail_test.go", + "test": "TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "openLegacyWALStoreForTest" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALStoreV3ReclaimRetiresReferencesBeforeReuse", + "TestWALStoreV3CheckpointReclaimsAcrossRingLaps" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_sticky_race_test.go", + "test": "TestWALStoreHeldWorkersSettleOnAFailurePath", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_checkpoint_safety_test.go", + "test": "TestWALStoreMutationAPIsRejectAfterClose", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_activation_test.go", + "test": "TestWALStoreProductionRefusesLegacyWithoutMutation", + "legacy_roots": [ + "createLegacyWALStoreWithOptions" + ], + "reason": "legacy input construction for the native public-refusal control itself; the production test stays on v3", + "v3_controls": [ + "TestWALStoreProductionRefusesLegacyWithoutMutation" + ], + "todo": "row 14a: replace only old input construction with frozen bytes; retain the production refusal control" + }, + { + "file": "core/storage/walstore_sticky_race_test.go", + "test": "TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_persisted_tail_test.go", + "test": "TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "openLegacyWALStoreForTest", + "readSuperblock" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3HalfResetRefusesWritesUntilRecover" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b", + "coverage_status": "partial", + "coverage_gaps": [ + "Native real-Recover descriptor-publication write/fsync failure, refused append and subsequent safe recovery/reopen schedule is not established by standalone publisher-failure or half-reset controls." + ] + }, + { + "file": "core/storage/walstore_midhistory_hole_test.go", + "test": "TestWALStoreRecoverKeepsATornTail", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALIOV3_RealWriterReopenScan", + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash", + "TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_recovery_frontier_gap_test.go", + "test": "TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "openLegacyWALStoreForTest", + "readSuperblock" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALIOV3_RealWriterReopenScan", + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash", + "TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_recovery_lww_test.go", + "test": "TestWALStoreRecoverLastWriterWinsAcrossScanOrder", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "openLegacyWALStoreForTest" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALIOV3_RealWriterReopenScan", + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash", + "TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_persisted_tail_test.go", + "test": "TestWALStoreRecoverPersistsTheRecoveredBounds", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "openLegacyWALStoreForTest", + "readSuperblock" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery", + "TestWALStoreV3FenceTouchesNoByteBeforeTheHead" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_recovery_hardening_test.go", + "test": "TestWALStoreRecoverReconstructsLegacyWrappedRetainedWindow", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "openLegacyWALStoreForTest" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALIOV3_RealWriterReopenScan", + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash", + "TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_recovery_hardening_test.go", + "test": "TestWALStoreRecoverRejectsOverflowingBatchGeometry", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALIOV3_RealWriterReopenScan", + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash", + "TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_legacy_trim_test.go", + "test": "TestWALStoreRecoverReplaysLegacyRangeTrim", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyReadOnlyForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_recovery_hardening_test.go", + "test": "TestWALStoreRecoverRetainsMultiBlockSuffixAcrossRestart", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALIOV3_RealWriterReopenScan", + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash", + "TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_midhistory_hole_test.go", + "test": "TestWALStoreRecoverStaleReleasedGarbageKeepsRetainedData", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALIOV3_RealWriterReopenScan", + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash", + "TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_midhistory_hole_test.go", + "test": "TestWALStoreRecoverSurvivesAnOutOfOrderUnsyncedTail", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALIOV3_RealWriterReopenScan", + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash", + "TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_midhistory_hole_test.go", + "test": "TestWALStoreRecoverWarnsOnMidHistoryHole", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALIOV3_RealWriterReopenScan", + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash", + "TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_midhistory_hole_test.go", + "test": "TestWALStoreRecoverWrappedHoleIsNoOutage", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "openLegacyWALStoreForTest" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALIOV3_RealWriterReopenScan", + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash", + "TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_sticky_fsync_test.go", + "test": "TestWALStoreWALFsyncFailureIsSticky", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_sticky_race_test.go", + "test": "TestWALStoreWALFsyncFaultDuringCheckpointPublication", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest", + "readSuperblock" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_sticky_race_test.go", + "test": "TestWALStoreWritersQueuedBehindAFailedAppendAreRefused", + "legacy_roots": [ + "createLegacyWALStoreWithWALSizeForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_test.go", + "test": "TestWALStore_DirectFrontierMetadataFailureRetainsRetryState", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_multiblock_test.go", + "test": "TestWALStore_DisableAutoFlushForRecoveryTestPreservesReplayAfterCrash", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound", + "v3_controls": [ + "TestWALStoreV3BatchRoundTripAcrossACrash", + "TestWALStoreV3TornBatchIsAllOrNothing", + "TestWALStoreV3InstrumentationIncludesBatch" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_test.go", + "test": "TestWALStore_FailedAppendDoesNotConsumeLSN", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors", + "v3_controls": [ + "TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes", + "TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_multiblock_test.go", + "test": "TestWALStore_MultiBlockDirtyRead", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound", + "v3_controls": [ + "TestWALStoreV3BatchRoundTripAcrossACrash", + "TestWALStoreV3TornBatchIsAllOrNothing", + "TestWALStoreV3InstrumentationIncludesBatch" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_multiblock_test.go", + "test": "TestWALStore_MultiBlockFeatureDisabledByDefault", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound", + "v3_controls": [ + "TestWALStoreV3BatchRoundTripAcrossACrash", + "TestWALStoreV3TornBatchIsAllOrNothing", + "TestWALStoreV3InstrumentationIncludesBatch" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_multiblock_test.go", + "test": "TestWALStore_MultiBlockFlusherSplitsPerBlock", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound", + "v3_controls": [ + "TestWALStoreV3BatchRoundTripAcrossACrash", + "TestWALStoreV3TornBatchIsAllOrNothing", + "TestWALStoreV3InstrumentationIncludesBatch" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_multiblock_profile_test.go", + "test": "TestWALStore_MultiBlockProfile_RecordCountReduction", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound", + "v3_controls": [ + "TestWALStoreV3BatchRoundTripAcrossACrash", + "TestWALStoreV3TornBatchIsAllOrNothing", + "TestWALStoreV3InstrumentationIncludesBatch" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_multiblock_test.go", + "test": "TestWALStore_MultiBlockRecoverSplitsPerBlock", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound", + "v3_controls": [ + "TestWALStoreV3BatchRoundTripAcrossACrash", + "TestWALStoreV3TornBatchIsAllOrNothing", + "TestWALStoreV3InstrumentationIncludesBatch" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_multiblock_test.go", + "test": "TestWALStore_MultiBlockRecoveryHeadLSNUsesRecoveredFrontier", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound", + "v3_controls": [ + "TestWALStoreV3BatchRoundTripAcrossACrash", + "TestWALStoreV3TornBatchIsAllOrNothing", + "TestWALStoreV3InstrumentationIncludesBatch" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_multiblock_test.go", + "test": "TestWALStore_MultiBlockScanLBAsSplitsPerLSN", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound", + "v3_controls": [ + "TestWALStoreV3BatchRoundTripAcrossACrash", + "TestWALStoreV3TornBatchIsAllOrNothing", + "TestWALStoreV3InstrumentationIncludesBatch" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_retention_test.go", + "test": "TestWALStore_RecoveryRetention_Default_StrictRecycle", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots", + "v3_controls": [ + "TestWALStoreV3RecycleFloorCompatibilityMatrix", + "TestWALStoreV3RetentionCompatibilityMatrix", + "TestWALStoreV3ReclaimKeepsPartialBatchAndRetention" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_retention_test.go", + "test": "TestWALStore_RecoveryRetention_LargerThanCheckpoint_ClampsToZero", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots", + "v3_controls": [ + "TestWALStoreV3RecycleFloorCompatibilityMatrix", + "TestWALStoreV3RetentionCompatibilityMatrix", + "TestWALStoreV3ReclaimKeepsPartialBatchAndRetention" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_retention_test.go", + "test": "TestWALStore_RecoveryRetention_NonZero_WidensWindow", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots", + "v3_controls": [ + "TestWALStoreV3RecycleFloorCompatibilityMatrix", + "TestWALStoreV3RetentionCompatibilityMatrix", + "TestWALStoreV3ReclaimKeepsPartialBatchAndRetention" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_retention_test.go", + "test": "TestWALStore_RecoveryRetention_TypedFailureKind", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots", + "v3_controls": [ + "TestWALStoreV3RecycleFloorCompatibilityMatrix", + "TestWALStoreV3RetentionCompatibilityMatrix", + "TestWALStoreV3ReclaimKeepsPartialBatchAndRetention" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_recycle_pin_test.go", + "test": "TestWALStore_RecycleGate_FloorAboveProposed_NoClamp", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots", + "v3_controls": [ + "TestWALStoreV3RecycleFloorCompatibilityMatrix", + "TestWALStoreV3RetentionCompatibilityMatrix", + "TestWALStoreV3ReclaimKeepsPartialBatchAndRetention" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_recycle_pin_test.go", + "test": "TestWALStore_RecycleGate_FloorBelowCurrentCheckpoint_NoRegress", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots", + "v3_controls": [ + "TestWALStoreV3RecycleFloorCompatibilityMatrix", + "TestWALStoreV3RetentionCompatibilityMatrix", + "TestWALStoreV3ReclaimKeepsPartialBatchAndRetention" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_recycle_pin_test.go", + "test": "TestWALStore_RecycleGate_NilSource_LegacyBehavior", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots", + "v3_controls": [ + "TestWALStoreV3RecycleFloorCompatibilityMatrix", + "TestWALStoreV3RetentionCompatibilityMatrix", + "TestWALStoreV3ReclaimKeepsPartialBatchAndRetention" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_recycle_pin_test.go", + "test": "TestWALStore_RecycleGate_SetRecycleFloorSourceNil_Disables", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots", + "v3_controls": [ + "TestWALStoreV3RecycleFloorCompatibilityMatrix", + "TestWALStoreV3RetentionCompatibilityMatrix", + "TestWALStoreV3ReclaimKeepsPartialBatchAndRetention" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_recycle_pin_test.go", + "test": "TestWALStore_RecycleGate_SourceActive_ClampsAtFloor", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots", + "v3_controls": [ + "TestWALStoreV3RecycleFloorCompatibilityMatrix", + "TestWALStoreV3RetentionCompatibilityMatrix", + "TestWALStoreV3ReclaimKeepsPartialBatchAndRetention" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_recycle_pin_test.go", + "test": "TestWALStore_RecycleGate_SourceInactive_LegacyBehavior", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots", + "v3_controls": [ + "TestWALStoreV3RecycleFloorCompatibilityMatrix", + "TestWALStoreV3RetentionCompatibilityMatrix", + "TestWALStoreV3ReclaimKeepsPartialBatchAndRetention" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_format_admission_test.go", + "test": "TestWALStore_UnknownFormatWithoutFactoryRefused", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyReadOnlyForTest", + "openLegacyWALStoreForTest", + "readSuperblock" + ], + "reason": "raw frozen v2 codec/format fixtures remain; v3 has a distinct CRC32C/binding/dual-slot byte contract", + "v3_controls": [ + "TestWALIOV3_RealWriterReopenScan", + "TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest", + "TestWALStoreProductionRefusesLegacyWithoutMutation" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_persisted_tail_test.go", + "test": "TestWALWriterBatchReuseIsBoundedByTheDurableTail", + "legacy_roots": [ + "newWALWriter" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALStoreV3ReclaimKeepsPartialBatchAndRetention", + "TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b", + "coverage_status": "partial", + "coverage_gaps": [ + "Native batch-refusal schedule must explicitly assert unchanged physical head and wrap/padding bytes; indivisible-record/retention controls do not establish that refusal oracle." + ] + }, + { + "file": "core/storage/walstore_persisted_tail_test.go", + "test": "TestWALWriterReuseIsBoundedByTheDurableTail", + "legacy_roots": [ + "newWALWriter" + ], + "reason": "raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes", + "v3_controls": [ + "TestWALIOV3_FloorAndPwriteFailureRefuse", + "TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_checkpoint_safety_test.go", + "test": "TestWriteExtentDirectFailureRetainsDirtyWAL", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_checkpoint_safety_test.go", + "test": "TestWriteExtentDirectSupersededWALDoesNotReappearAfterRestart", + "legacy_roots": [ + "createLegacyWALStoreForTest", + "openLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + }, + { + "file": "core/storage/walstore_checkpoint_safety_test.go", + "test": "TestWriteExtentDirectSupersedesPriorDirtyWAL", + "legacy_roots": [ + "createLegacyWALStoreForTest" + ], + "reason": "v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles", + "v3_controls": [ + "TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing", + "TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate", + "TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore", + "TestBaseInstallV3CompleteServesTheImageAcrossACrash" + ], + "todo": "row 14a: move or retire explicitly only after replacement/migration review; no deletion in 12b" + } +] diff --git a/seaweed-block/docs/design/format-v3-legacy-test-inventory.md b/seaweed-block/docs/design/format-v3-legacy-test-inventory.md new file mode 100644 index 0000000000..31d0761ff0 --- /dev/null +++ b/seaweed-block/docs/design/format-v3-legacy-test-inventory.md @@ -0,0 +1,219 @@ +# Temporary legacy test inventory at v3 activation + +Ruling: explicit test-only legacy constructors preserve old engine/bitmap controls until row 14a. Production Create/Open/readonly select v3, and v2 input is explicitly refused. `TestLegacyFixtureIsolation` checks that no default production source references the private legacy constructor chain and that the storage transitive import closure excludes tool/test support. + +The JSON companion is the exact test inventory (including helper reachability), with each old control’s existing named v3 controls and its remaining format-specific scope. Constructor wrappers live in `_test.go`; cross-package migration fixture entry points exist only under `swblock_format_v3_test`. The real-v2 decoder/migration fixtures moved into that explicit tagged suite; raw codec table tests stay in the default suite. Full validation runs BOTH default and tagged suites. No frozen engine snapshot or test deletion is used. + +These mappings are coverage references, not a claim that different disk formats share identical mechanics. In particular v2 one-superblock metrics, permissive nonmonotone record scans and C11 bitmap-failure branches have no identical native-v3 branch. V3 instead uses the listed nonce/strict-order/BASE, map-proof and both-slot controls. The old controls remain executable until their row-14a disposition is reviewed. + +Public/format-neutral controls remain on production v3: durable provider capture/HEAD restore/readonly/status; auto probe/fallback; chunk C3/C4 upload races, typed admission, parallel workers; BASE priming and recovery lane controls; CRC-valid corrupt-batch rejection; acknowledged startup corruption refusal; pin/retention matrix driven by real writes. Initial UNKNOWN candidates and native batching expectations are explicit. The old warning-only startup test is replaced by `TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness`; the old v2 warning scanner test remains in this inventory. + +Row 14b removes the production C11 file store and all callers of its constructor. Its roundtrip/corruption codec assertions remain in `TestLegacyC11FileCodec_*`, backed only by `legacy_c11_file_fixture_test.go`. `TestChunkLayer_OwnedMapIncrementalAfterRestart` is now an explicit native-v3 checkpoint/reopen/incremental-capture control with no C11 sidecar; it is no longer a legacy inventory entry. The temporary fake-bitmap legacy engine controls below remain subject to row 14a. + +TODO(row 14a): relocate or retire every listed legacy control explicitly; preserve raw migration input receipts and all named native controls. Do not treat this inventory as approval to remove a test or weaken an ACTIVE invariant. + +| Retained test | Reason | Existing native-v3 controls | +| --- | --- | --- | +| `cmd/sw-block/migrate_test.go::TestMigrateV3BadGeometryRefusedBeforeAnyWrite` | real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage | `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | +| `cmd/sw-block/migrate_test.go::TestMigrateV3CleanVolume` | real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage | `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | +| `cmd/sw-block/migrate_test.go::TestMigrateV3CrashAfterEachStepIsResumable` | real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage | `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | +| `cmd/sw-block/migrate_format_v3_test.go::TestMigrateV3ExcludesOpenUntilCommitFinishes` | real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage | `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | +| `cmd/sw-block/migrate_test.go::TestMigrateV3NeverRestoresTheBackup` | real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage | `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | +| `cmd/sw-block/migrate_test.go::TestMigrateV3OldBinaryAfterPreparation` | real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage | `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | +| `cmd/sw-block/migrate_test.go::TestMigrateV3OldWALOverwritesThePreparedSlot` | real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage | `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | +| `cmd/sw-block/migrate_format_v3_test.go::TestMigrateV3PreparedOnlyRefusedByV3Open` | real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage | `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | +| `cmd/sw-block/migrate_test.go::TestMigrateV3RefusalsChangeNothing` | real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage | `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | +| `cmd/sw-block/migrate_test.go::TestMigrateV3RetirementRerunFsyncsTheDirectory` | real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage | `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | +| `cmd/sw-block/migrate_format_v3_test.go::TestMigrateV3VolumeOpensAsV3` | real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage | `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | +| `cmd/sw-block/internal/v2legacy/real_store_legacy_test.go::TestReadSuperblockRefusesOtherFormats` | real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage | `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | +| `cmd/sw-block/internal/v2legacy/real_store_legacy_test.go::TestScanCleanOnRealV2Stores` | real v2 input fixture for the frozen decoder/migration; row 14a replaces construction, not migration refusal coverage | `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | +| `core/storage/flusher_test.go::TestAllBlocks_ReturnsBlocksAfterFlush` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | +| `core/storage/walstore_checkpoint_safety_test.go::TestCheckpointPublicationCrashWindowsRemainRecoverable` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/chunk_layer_typed_cause_test.go::TestChunkCut_BaseInstallRefusalIsTyped` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_precopy_test.go::TestChunkCut_RecoverWaitsForTheCaptureBarrier` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_lsn_order_test.go::TestChunkCut_RemoteLSNNeverDecreases` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_c11_test.go::TestChunkLayer_C11_BaseRebuildRecovery` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_c11_test.go::TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_c11_test.go::TestChunkLayer_C11_ExtentCallbackIsPureInMemory` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_c11_test.go::TestChunkLayer_C11_IncrementalAfterRestart` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_c11_test.go::TestChunkLayer_C11_LostOrMismatchedBitmapFallsBackToHashCompare` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_c11_test.go::TestChunkLayer_C11_ReplicaApplyKeepsBitmap` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_c11_test.go::TestChunkLayer_C11_RolloverKeepsPostCutDirt` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_c11_test.go::TestChunkLayer_C11_SaveThenCheckpointFailureOverReportsOnly` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_fresh_bitmap_test.go::TestChunkLayer_LostBitmapReconciles` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_precopy_test.go::TestChunkPrecopy_LowerLSNApplyAfterStagingIsNotLost` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_precopy_test.go::TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_reconcile_test.go::TestChunkReconcile_BaseInstallSupersedesRunningReconciliation` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_reconcile_test.go::TestChunkReconcile_DetachDeadlineWhileReconciling` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_reconcile_test.go::TestChunkReconcile_DetachWaitsForReconciliation` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_reconcile_test.go::TestChunkReconcile_NoHeadMovesWhileReconciling` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_reconcile_test.go::TestChunkReconcile_OldCompletionCannotCertifyReplacement` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_reconcile_test.go::TestChunkReconcile_OldWorkerCannotModifyReplacementSet` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_reconcile_test.go::TestChunkReconcile_ResultPersisted` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_reconcile_test.go::TestChunkReconcile_UnpersistedResultKeepsReconciling` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_layer_reconcile_test.go::TestChunkReconcile_WritesProceedWhileReconciling` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_restore_test.go::TestClaimChunkHeadClearsProductionDetachProof` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/flusher_test.go::TestCrashFamily_AbruptKillAtMultipleWindows` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | +| `core/storage/chunk_bitmap_file_test.go::TestLegacyC11FileCodec_CorruptStateIsLost` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/chunk_bitmap_file_test.go::TestLegacyC11FileCodec_RoundTripAndReopen` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/walstore_checkpoint_safety_test.go::TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/flusher_instrumentation_test.go::TestFlusherInstrumentationCountsCheckpointFailure` | v2 one-superblock-write/one-sync counters and its raw injection seams; v3 record-stage counters are separate, no numerical equivalence claimed for metadata counts | `TestFlusherV3ProfileCountsRealRecordStages`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry` | +| `core/storage/flusher_instrumentation_test.go::TestFlusherInstrumentationCountsCompleteCycle` | v2 one-superblock-write/one-sync counters and its raw injection seams; v3 record-stage counters are separate, no numerical equivalence claimed for metadata counts | `TestFlusherV3ProfileCountsRealRecordStages`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry` | +| `core/storage/flusher_instrumentation_test.go::TestFlusherInstrumentationCountsWALReadFailures` | v2 one-superblock-write/one-sync counters and its raw injection seams; v3 record-stage counters are separate, no numerical equivalence claimed for metadata counts | `TestFlusherV3ProfileCountsRealRecordStages`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry` | +| `core/storage/walstore_checkpoint_safety_test.go::TestFlusherRejectsCorruptOrUnsupportedDirtyRecord` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_checkpoint_safety_test.go::TestFlusherSnapshotCannotOverwriteLaterDirectBase` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/flusher_snapshot_cut_test.go::TestFlusherSnapshotCutPreservesSyncedWrites` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | +| `core/storage/walstore_checkpoint_safety_test.go::TestFlusherWALSlotMismatchFailsClosed` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/flusher_test.go::TestFlusher_AdvancesCheckpointBeforeReadFromExtent` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3AdmissionBurstFiveRings`, `TestWALStoreV3AdmissionUsesNativeOccupancy` | +| `core/storage/flusher_test.go::TestFlusher_ConcurrentWriteRaceLBAStaysFresh` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | +| `core/storage/flusher_test.go::TestFlusher_ManyDirtyEntriesCheckpointStaysCorrect` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | +| `core/storage/flusher_test.go::TestFlusher_RecoveryHonorsCheckpoint` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | +| `core/storage/flusher_test.go::TestFlusher_ReleasesWALPressureAfterCheckpoint` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3AdmissionUsesNativeOccupancy`, `TestWALStoreV3AdmissionStallDeadlineAndResume`, `TestWALStoreV3AdmissionBurstFiveRings` | +| `core/storage/chunk_restore_test.go::TestFreshRestoreBitmapStartsAtClaimedHEAD` | legacy C11 bitmap persistence/reconciliation or pre-v3 permissive frontier/record surgery | `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation` | +| `core/storage/flusher_test.go::TestRecovery_DeterministicAcrossMultipleOpens` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | +| `core/storage/walstore_checkpoint_safety_test.go::TestRunningFlusherCannotOverwriteDirectBase` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/chunk_frontier_test.go::TestSeedChunkFrontierMetadataFailureRetry` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestBlockMetadata_SeedFailureRetry` | +| `core/storage/walstore_sync_generation_test.go::TestWALGenerationBypassesUntrackedMutationPaths` | legacy sync cache/direct-mutation callback order; v3 success boundary is serialized and recovery-generation checked | `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut` | +| `core/storage/walstore_sync_frontier_order_test.go::TestWALGenerationFirstCallerReturnOrdering` | legacy sync cache/direct-mutation callback order; v3 success boundary is serialized and recovery-generation checked | `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut` | +| `core/storage/walstore_sync_generation_test.go::TestWALGenerationPartialAppendRecoverySync` | legacy sync cache/direct-mutation callback order; v3 success boundary is serialized and recovery-generation checked | `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut` | +| `core/storage/walstore_multiblock_test.go::TestWALMultiBlock_EncodeDecode` | v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3InstrumentationIncludesBatch` | +| `core/storage/walstore_persisted_tail_test.go::TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALIOV3_RealWriterReopenScan`, `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness` | +| `core/storage/walstore_sticky_fsync_test.go::TestWALStoreCheckpointFsyncFailureIsSticky` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_checkpoint_crash_linux_test.go::TestWALStoreCheckpointSIGKILLCrashWindows` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | +| `core/storage/walstore_checkpoint_safety_test.go::TestWALStoreClosePerformsFinalFlush` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_checkpoint_safety_test.go::TestWALStoreCloseReturnsFinalMetadataFailure` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_checkpoint_safety_test.go::TestWALStoreCloseWaitsForInflightSync` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_sticky_fsync_test.go::TestWALStoreExtentFsyncFailureIsSticky` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_sticky_race_test.go::TestWALStoreExtentFsyncFaultAfterThePublicationCheck` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_sticky_race_test.go::TestWALStoreExtentFsyncFaultDuringDirectFrontierPublication` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_batch_lsn_reuse_test.go::TestWALStoreFailedBatchAppendDoesNotRevertALaterAckedWrite` | v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3InstrumentationIncludesBatch` | +| `core/storage/walstore_persisted_tail_test.go::TestWALStoreFlushPersistsTheReleasedTail` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin` | +| `core/storage/walstore_sticky_race_test.go::TestWALStoreFsyncsOfTheFileAreSerialized` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_persisted_tail_test.go::TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3CheckpointReclaimsAcrossRingLaps` | +| `core/storage/walstore_sticky_race_test.go::TestWALStoreHeldWorkersSettleOnAFailurePath` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_checkpoint_safety_test.go::TestWALStoreMutationAPIsRejectAfterClose` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_activation_test.go::TestWALStoreProductionRefusesLegacyWithoutMutation` | legacy input construction for the native public-refusal control itself; the production test stays on v3 | `TestWALStoreProductionRefusesLegacyWithoutMutation` | +| `core/storage/walstore_sticky_race_test.go::TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_persisted_tail_test.go::TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` | PARTIAL: Native real-Recover descriptor-publication write/fsync failure, refused append and subsequent safe recovery/reopen schedule is not established by standalone publisher-failure or half-reset controls. | `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover` | +| `core/storage/walstore_midhistory_hole_test.go::TestWALStoreRecoverKeepsATornTail` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALIOV3_RealWriterReopenScan`, `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness` | +| `core/storage/walstore_recovery_frontier_gap_test.go::TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALIOV3_RealWriterReopenScan`, `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness` | +| `core/storage/walstore_recovery_lww_test.go::TestWALStoreRecoverLastWriterWinsAcrossScanOrder` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALIOV3_RealWriterReopenScan`, `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness` | +| `core/storage/walstore_persisted_tail_test.go::TestWALStoreRecoverPersistsTheRecoveredBounds` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead` | +| `core/storage/walstore_recovery_hardening_test.go::TestWALStoreRecoverReconstructsLegacyWrappedRetainedWindow` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALIOV3_RealWriterReopenScan`, `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness` | +| `core/storage/walstore_recovery_hardening_test.go::TestWALStoreRecoverRejectsOverflowingBatchGeometry` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALIOV3_RealWriterReopenScan`, `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness` | +| `core/storage/walstore_legacy_trim_test.go::TestWALStoreRecoverReplaysLegacyRangeTrim` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | +| `core/storage/walstore_recovery_hardening_test.go::TestWALStoreRecoverRetainsMultiBlockSuffixAcrossRestart` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALIOV3_RealWriterReopenScan`, `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness` | +| `core/storage/walstore_midhistory_hole_test.go::TestWALStoreRecoverStaleReleasedGarbageKeepsRetainedData` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALIOV3_RealWriterReopenScan`, `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness` | +| `core/storage/walstore_midhistory_hole_test.go::TestWALStoreRecoverSurvivesAnOutOfOrderUnsyncedTail` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALIOV3_RealWriterReopenScan`, `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness` | +| `core/storage/walstore_midhistory_hole_test.go::TestWALStoreRecoverWarnsOnMidHistoryHole` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALIOV3_RealWriterReopenScan`, `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness` | +| `core/storage/walstore_midhistory_hole_test.go::TestWALStoreRecoverWrappedHoleIsNoOutage` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALIOV3_RealWriterReopenScan`, `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness` | +| `core/storage/walstore_sticky_fsync_test.go::TestWALStoreWALFsyncFailureIsSticky` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_sticky_race_test.go::TestWALStoreWALFsyncFaultDuringCheckpointPublication` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_sticky_race_test.go::TestWALStoreWritersQueuedBehindAFailedAppendAreRefused` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_test.go::TestWALStore_DirectFrontierMetadataFailureRetainsRetryState` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | +| `core/storage/walstore_multiblock_test.go::TestWALStore_DisableAutoFlushForRecoveryTestPreservesReplayAfterCrash` | v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3InstrumentationIncludesBatch` | +| `core/storage/walstore_test.go::TestWALStore_FailedAppendDoesNotConsumeLSN` | v2 engine/layout, forced legacy fields or callback seams; v3 uses coherent descriptors | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | +| `core/storage/walstore_multiblock_test.go::TestWALStore_MultiBlockDirtyRead` | v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3InstrumentationIncludesBatch` | +| `core/storage/walstore_multiblock_test.go::TestWALStore_MultiBlockFeatureDisabledByDefault` | v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3InstrumentationIncludesBatch` | +| `core/storage/walstore_multiblock_test.go::TestWALStore_MultiBlockFlusherSplitsPerBlock` | v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3InstrumentationIncludesBatch` | +| `core/storage/walstore_multiblock_profile_test.go::TestWALStore_MultiBlockProfile_RecordCountReduction` | v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3InstrumentationIncludesBatch` | +| `core/storage/walstore_multiblock_test.go::TestWALStore_MultiBlockRecoverSplitsPerBlock` | v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3InstrumentationIncludesBatch` | +| `core/storage/walstore_multiblock_test.go::TestWALStore_MultiBlockRecoveryHeadLSNUsesRecoveredFrontier` | v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3InstrumentationIncludesBatch` | +| `core/storage/walstore_multiblock_test.go::TestWALStore_MultiBlockScanLBAsSplitsPerLSN` | v2 opt-in batch framing/failure injection; v3 batch is native and nonce-bound | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3InstrumentationIncludesBatch` | +| `core/storage/walstore_retention_test.go::TestWALStore_RecoveryRetention_Default_StrictRecycle` | fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots | `TestWALStoreV3RecycleFloorCompatibilityMatrix`, `TestWALStoreV3RetentionCompatibilityMatrix`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention` | +| `core/storage/walstore_retention_test.go::TestWALStore_RecoveryRetention_LargerThanCheckpoint_ClampsToZero` | fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots | `TestWALStoreV3RecycleFloorCompatibilityMatrix`, `TestWALStoreV3RetentionCompatibilityMatrix`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention` | +| `core/storage/walstore_retention_test.go::TestWALStore_RecoveryRetention_NonZero_WidensWindow` | fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots | `TestWALStoreV3RecycleFloorCompatibilityMatrix`, `TestWALStoreV3RetentionCompatibilityMatrix`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention` | +| `core/storage/walstore_retention_test.go::TestWALStore_RecoveryRetention_TypedFailureKind` | fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots | `TestWALStoreV3RecycleFloorCompatibilityMatrix`, `TestWALStoreV3RetentionCompatibilityMatrix`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention` | +| `core/storage/walstore_recycle_pin_test.go::TestWALStore_RecycleGate_FloorAboveProposed_NoClamp` | fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots | `TestWALStoreV3RecycleFloorCompatibilityMatrix`, `TestWALStoreV3RetentionCompatibilityMatrix`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention` | +| `core/storage/walstore_recycle_pin_test.go::TestWALStore_RecycleGate_FloorBelowCurrentCheckpoint_NoRegress` | fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots | `TestWALStoreV3RecycleFloorCompatibilityMatrix`, `TestWALStoreV3RetentionCompatibilityMatrix`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention` | +| `core/storage/walstore_recycle_pin_test.go::TestWALStore_RecycleGate_NilSource_LegacyBehavior` | fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots | `TestWALStoreV3RecycleFloorCompatibilityMatrix`, `TestWALStoreV3RetentionCompatibilityMatrix`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention` | +| `core/storage/walstore_recycle_pin_test.go::TestWALStore_RecycleGate_SetRecycleFloorSourceNil_Disables` | fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots | `TestWALStoreV3RecycleFloorCompatibilityMatrix`, `TestWALStoreV3RetentionCompatibilityMatrix`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention` | +| `core/storage/walstore_recycle_pin_test.go::TestWALStore_RecycleGate_SourceActive_ClampsAtFloor` | fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots | `TestWALStoreV3RecycleFloorCompatibilityMatrix`, `TestWALStoreV3RetentionCompatibilityMatrix`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention` | +| `core/storage/walstore_recycle_pin_test.go::TestWALStore_RecycleGate_SourceInactive_LegacyBehavior` | fabricated v2 checkpoint/retention geometry; v3 replacement drives real acknowledged writes and both slots | `TestWALStoreV3RecycleFloorCompatibilityMatrix`, `TestWALStoreV3RetentionCompatibilityMatrix`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention` | +| `core/storage/walstore_format_admission_test.go::TestWALStore_UnknownFormatWithoutFactoryRefused` | raw frozen v2 codec/format fixtures remain; v3 has a distinct CRC32C/binding/dual-slot byte contract | `TestWALIOV3_RealWriterReopenScan`, `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestWALStoreProductionRefusesLegacyWithoutMutation` | +| `core/storage/walstore_persisted_tail_test.go::TestWALWriterBatchReuseIsBoundedByTheDurableTail` | PARTIAL: Native batch-refusal schedule must explicitly assert unchanged physical head and wrap/padding bytes; indivisible-record/retention controls do not establish that refusal oracle. | `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint` | +| `core/storage/walstore_persisted_tail_test.go::TestWALWriterReuseIsBoundedByTheDurableTail` | raw v2 header/window/IEEE-CRC/permissive scan assumptions; native v3 refuses holes below W and fences rolled-back suffixes | `TestWALIOV3_FloorAndPwriteFailureRefuse`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin` | +| `core/storage/walstore_checkpoint_safety_test.go::TestWriteExtentDirectFailureRetainsDirtyWAL` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_checkpoint_safety_test.go::TestWriteExtentDirectSupersededWALDoesNotReappearAfterRestart` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | +| `core/storage/walstore_checkpoint_safety_test.go::TestWriteExtentDirectSupersedesPriorDirtyWAL` | v2 fd/callback/checkpoint injection or direct-extent API; v3 fails through the shared publisher/owned map and uses install handles | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` | + +Native typed-error controls use the owned-map v3 store directly: `TestChunkCut_UploadFailureIsRemoteUnavailable` checks both upload error causes; `TestChunkCut_ClosedLayerIsTyped` checks the closed-cut cause; `TestChunkCut_CASLostToMovedHeadIsHeadConflict` checks ambiguous CAS with a moved HEAD remains a conflict, not fencing. They are not legacy coverage mappings. `TestLegacyFixtureIsolationRejectsFunctionValues` exercises direct calls, package/local aliases and function arguments against the same reference guard. CI executes both default and explicit tagged configurations. + +## Liveness audit after the native admission regression + +The earlier replacement matrix mapped checkpoint safety to generic recovery +controls. That did not test the *binding* of the common admission controller to +v3 occupancy. The production closure was therefore incomplete: the legacy writer +remained at zero and no test crossed the default ring while relying on automatic +pressure relief. Codec, manual-flush and safety tests could all pass. + +The audit inspected the retained legacy constructor inventory and storage tests +using admission, pressure, throttling, `errWALFull`, wait/timeout and stalled-flusher +paths. The five concrete retained controls above name related native controls, not complete equivalent closure: +`TestFlusher_AdvancesCheckpointBeforeReadFromExtent`, +`TestFlusher_ReleasesWALPressureAfterCheckpoint`, +`TestWALWriterReuseIsBoundedByTheDurableTail`, +`TestWALWriterBatchReuseIsBoundedByTheDurableTail`, and +`TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry`. +The last three include safety gates needed to make reuse liveness safe; v3's +sticky persistence failure intentionally requires physical reopen rather than +v2's same-instance retry. These are not claimed to have identical retry semantics. +`TestWriteExtentDirectSupersedesPriorDirtyWAL` also mentions pressure, but tests +BASE supersession, not admission; its existing install/map mapping stays intact. +Raw writer controls remain format-specific; no test is removed. + +| Behaviour | Native-v3 control | Scope | +| --- | --- | --- | +| Healthy burst and automatic pressure relief | `TestWALStoreV3AdmissionBurstFiveRings` | Fresh mapped 64 KiB ring, five ring sizes of writes, Sync every ten blocks, real automatic flusher, all submitted bytes read back; legacy-sampler mutant must fail this test | +| Production default geometry and frontend Flush | `TestWALStoreChunkV3_SequentialBurstFlush` | Public provider, 64 MiB WAL, 320 MiB via NVMe handler, periodic Flush and literal-byte readback | +| Occupancy and checkpoint pressure reset | `TestWALStoreV3AdmissionUsesNativeOccupancy` | Actual append size and both-slot released floor, not a mocked pressure value | +| Soft-watermark throttling | `TestWALStoreV3AdmissionSoftThrottles` | Real occupied v3 ring drives a positive bounded soft delay; only sleep is recorded | +| Hard watermark, stopped flusher, timeout and resumed progress | `TestWALStoreV3AdmissionStallDeadlineAndResume` | Native occupied ring and timeout; barrier at actual hard-pressure sleep, then checkpoint/reclaim and release. Post-release response timer excludes fsync; controller retains the real store admission deadline | +| Close during pressure | `TestWALStoreV3AdmissionCloseEndsPressureWait` | Already-parked controller Acquire is released after actual store Close and returns typed close error; no claim that public Write lifecycle/Close behavior changed | +| Idle/admission rollover without a new checkpoint | `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint` | Both single/batch admission triggers plus idle and unchanged-checkpoint paths | +| Flusher persistence fault | `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore` | Real owned-map failure latches the store; no false progress or unsafe admission | + +There were no dedicated `walAdmission` unit tests in the retained v2 suite for +soft delay, hard-wait timeout or stopped-flusher resumption. Those gaps are covered +by the new native tests rather than reported as already covered. The new small-ring +tests use the production engine, controller and flusher with test-only geometry; +they do not replace the public default-size provider control. They preserve the +existing bounded admission policy, not a reservation guarantee for oversized or +concurrently pre-admitted batches, or a promise that an entirely unsynced ring can +reclaim unacknowledged bytes. + +The adjacent tail-persistence/reuse safety rows are also made specific: +`TestWALStoreFlushPersistsTheReleasedTail`, +`TestWALStoreRecoverPersistsTheRecoveredBounds`, and +`TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` now cite the native +both-slot, real multi-lap/reopen and retired-dirty-reference controls above. +These are necessary reuse-safety checks, not independent backpressure tests. +The scope of this audit is storage WAL capacity and pressure-driven progress; +`TestWALStoreCloseWaitsForInflightSync` is a lifecycle/Sync join control, not a +capacity waiter or flusher-stall oracle, and its old generic mapping must not be +read as proving the native capacity behavior. Capture/BASE reconciliation waits +likewise remain in their separate protocol inventory. + +## Partial replacement status (review P2 disposition) + +This matrix is **partial**, not a declaration of equivalent replacement or +permission to remove the retained legacy tests. In particular: + +| Retained legacy control | Native references establish | Still missing native schedule | +| --- | --- | --- | +| `TestWALWriterBatchReuseIsBoundedByTheDurableTail` | complete-record/retention and rollover constraints | refused batch leaves physical head and all wrap/padding bytes unchanged | +| `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` | publisher/half-reset fault refusal in their own callers | real Recover publication write/fsync failure, refused append and safe subsequent recovery/reopen | + +The JSON marks both rows `coverage_status: partial` and preserves their exact +`coverage_gaps`. Existing references remain useful scoped safety evidence; they +do not close these schedules. Keep their legacy fixtures until row14a disposition +and do not claim 100% native liveness/replacement closure. + +The resumed-admission and Close controls now synchronize at the first actual +hard-pressure sleep, not Notify (which precedes the loop's live close check). +The resume response timeout starts only after the actual checkpoint/fsync and +barrier release; the controller itself uses the store's normal30s admission +policy. Close acts after the controller is already waiting. These are controller +waiter controls, not a claim that Close interrupts a public Write holding the +store lifecycle read lock. Cleanup releases and joins the worker, bounded by +that real admission policy, even when an assertion fails. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md new file mode 100644 index 0000000000..0f0bc7958d --- /dev/null +++ b/seaweed-block/docs/design/invariants.md @@ -0,0 +1,544 @@ +# Seaweed Block invariants and state machines + +This is the protocol contract of Seaweed Block: the state machines the code implements, the invariants each transition must keep, where each invariant is enforced, which test asserts it, and which TLA+ property models it. It is written for people and for coding agents. Before changing a protocol path, find the machine in Part A and the rows in Part B, and follow the change rules in Part C. + +This document supersedes the internal ledger [`internal/docs/protocol/invariant-ledger.md`](../../internal/docs/protocol/invariant-ledger.md). Every ID from that ledger is kept here and was re-checked against the code; some statements were narrowed to what the tests in this repository actually assert, and each narrowing is noted under its table. The internal file stays for history; new rows go here. + +The design is described in three documents, and this one collects their machines and invariants in one place: the [core design](block-design.md), the [agent workspace design](agent-workspace-design.md) and the [Kubernetes block design](kubernetes-block-design.md). + +**Conventions.** These are the same as in the design documents. + +- Code references name a file and a function, not a line number. Test references name the test function and its file. +- A TLA+ entry names a specification in [`docs/spec/`](../spec/README.md) and an invariant or property defined in it. The models check designs at small scale and are mapped to the code by reading (see the [limits](../spec/README.md#limits)). +- Status: + - `ACTIVE`: a Go test in this repository asserts the statement. + - `STUB`: the code enforces the statement (by reading), but no test asserts it yet. A release note must not claim behaviour backed only by a `STUB` row. + - `ARCHIVED`: a retired row, kept with its reason. There are none yet. +- The rule carried over from the internal ledger still applies: an invariant without a test is a wish, not an invariant. + +## Contents + +- [Part A. State machines](#part-a-state-machines) + - [M1 walstore: open, recover, serve, fault](#m1-walstore-open-recover-serve-fault) + - [M2 Authority: assignment, epoch, lease](#m2-authority-assignment-epoch-lease) + - [M3 Replica role and peer state](#m3-replica-role-and-peer-state) + - [M4 Workspace HEAD holder and takeover](#m4-workspace-head-holder-and-takeover) + - [M5 The cut pipeline](#m5-the-cut-pipeline) + - [M6 Chunk lifecycle](#m6-chunk-lifecycle) +- [Part B. Invariant ledger](#part-b-invariant-ledger) +- [Part C. Change rules](#part-c-change-rules) + +--- + +## Part A. State machines + +Each machine lists its states, the allowed transitions, the guard that must hold for each transition, where the guard is enforced, and the IDs of the Part B rows that protect it. A state name in `code font` is a value in the code; the other names describe a condition and are not code types. + +### M1 walstore: open, recover, serve, fault + +The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent). + +```mermaid +stateDiagram-v2 + [*] --> Opened: OpenWALStore / CreateWALStore + Opened --> Recovering: RecoverVolume + Recovering --> Serving: Recover ok, backend operational + Recovering --> RecoveryFailed: Recover error (typed reason) + Serving --> FaultLatched: fsync or WAL append fails + FaultLatched --> Closed: Close + RecoveryFailed --> Closed: Close + Serving --> Closed: Close + Closed --> Opened: reopen +``` + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | 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` | +| 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 (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-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` | +| Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001` | +| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse (C11 bitmap/superblock path remains legacy-fixture-only) | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` | +| Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `noteAppendFailure`, `syncFile` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | +| FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | +| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | + +Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestCheckpointDiagnostics_RefusalThenSuccess`, `TestCheckpointDiagnostics_PrepareRefusalAndIOFailure`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. + +Public walstore Create now selects mapped format v3/impl3 (mode C by default, mode A by create option). Open and offline readonly use A/B slot and owned-map validation; valid legacy formats are refused with `ErrUnsupportedLegacyFormat`, rather than silently retrofitted. The temporary old-engine/raw-codec test scope and every named native replacement are recorded in [the legacy inventory](format-v3-legacy-test-inventory.md). Native recovery validates nonce/cursor binding and a contiguous physical LSN prefix before applying the mode-specific W rule; an acknowledged-range integrity failure blocks startup. The provider's create geometry, auto probe, capture, HEAD restore and readonly/status controls exercise the public selector (`INV-WAL-V3-ACTIVATION-001`). Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock; the offline migration CLI acquires the same lock before any descriptor read or mutation (`INV-WAL-V3-OWNER-001`). Contention refuses open/migration without changing bytes; descriptor close or process exit releases ownership. This implements the existing offline-migration precondition, not a new serving state. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails and retirement of checkpointed dirty references under writer exclusion; idle, unchanged-checkpoint and admission paths also settle a pinned fallback. An unlocked catch-up scan revalidates the coherent checkpoint and tail before emitting anything. A failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`). + +Recovery warnings such as `wal_hole_suspected` are recorded in Serving without changing health (`INV-WAL-WARN-NO-HEALTH-001`). The open gaps of this machine (a corrupted synced record mid-history only warns; forged records in user data) are listed in the [core known issues](block-design.md#24-known-issues-and-work-in-progress) and are not ledger rows. + +### M2 Authority: assignment, epoch, lease + +blockmaster's publisher is the only component that mints epochs. Diagrams: the assignment lifecycle in [core §1.5](block-design.md#15-authority-blockmaster-assignments-epochs-leases), and the workspace lease and move in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves). + +**Assignment line, per volume.** + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| Unbound | Bound (epoch 1, endpoint version 1) | `IntentBind`; no slot of this volume holds a present line (checked per volume, also after a restart); to move to another slot use `IntentReassign` | `core/authority/authority.go` `applyWithWorkspaceMove`, `boundReplicaForVolume`; `core/authority/controller.go` `decideVolume` (binds only a volume with no line) | `INV-AUTH-ONE-PRIMARY-001`, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | +| Bound | Bound (endpoint version + 1) | `IntentRefreshEndpoint`; same epoch; a no-op when the addresses are unchanged | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | +| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` | +| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing, but its durable outcome may be unknown | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | +| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` | +| Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | + +**Workspace lease and move, in blockmaster.** + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | +| Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | +| Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | +| Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | +| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | +| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001` | +| Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | +| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | +| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | + +### M3 Replica role and peer state + +The role a blockvolume takes from each assignment, its replica listener's admission, and the primary's view of each replica. This is the replication engine of [core §1.6](block-design.md#16-replication-and-failover) (which has the peer-state diagram) as the Kubernetes line uses it; promotion is in [Kubernetes §6](kubernetes-block-design.md#6-authority-promotion) (diagram) and the failover sequence in [Kubernetes §4](kubernetes-block-design.md#4-replication-and-failover). + +```mermaid +stateDiagram-v2 + [*] --> Unassigned: listener with a floor record, no role yet + Unassigned --> Primary: fact names self, listener fenced at e + Unassigned --> Supporting: fact names another primary, self in peers + Supporting --> Primary: promotion, fact names self at a higher epoch + Primary --> Supporting: fact names another primary, self in peers + Primary --> Excluded: fact names another primary, self not in peers + Supporting --> Excluded: fact names another primary, self not in peers + Excluded --> Supporting: later fact lists self as a peer +``` + +**Host role and listener admission.** + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| any | (no change) | local readiness blocked (recovery pending or failed): the fact is stored and replayed when readiness clears | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `INV-ROLE-READINESS-BLOCK-001` | +| any | (no change) | a role call below the current desired epoch is refused and does not clear a newer admission failure | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `INV-ROLE-STALE-REPLAY-001` | +| Unassigned, Supporting | Primary at e | the fact names this replica; the replica set is installed; the listener is fenced as primary and its floor e is persisted before the adapter is told | `core/host/volume/host.go` `applyFact`, `fenceSelfWithPeers`; `core/transport/replica.go` `FenceAsPrimary`, `raiseFloor` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001` | +| Unassigned, Primary | Supporting at e | the fact names another primary and lists this replica as a peer; the floor e is persisted first; the frontend stays gated | `core/host/volume/host.go` `applyFact`; `core/transport/replica.go` `AdmitAsReplica` | `INV-FENCE-FLOOR-DURABLE-001` | +| Primary, Supporting | Excluded | the fact names another primary and does not list this replica; ingress is closed, the other line is recorded and the frontend is unhealthy | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001` | +| any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` | +| (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | +| Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | + +**Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | +| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001` | +| `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | +| any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | +| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | + +`ReplicaPeer.Invalidate`, called on a ship, barrier or fence error, goes through the same gate as `SetState` (`replicaStateTransitionAllowed`): `Healthy`, `Degraded` and `CatchingUp` move to `Degraded`; from `NeedsRebuild` the state is kept and the reason is still logged ([#182](https://github.com/seaweedfs/seaweed-block/issues/182)). A replicated `Sync` is judged per durability mode (`core/replication/durability.go` `EvaluateBarrierAcks`; `INV-REPL-DURABILITY-MODE-001`). + +### M4 Workspace HEAD holder and takeover + +One host at a time holds a workspace volume's HEAD in SeaweedFS. The sequence diagram of a clean and a forced move is in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves); blockmaster's side of the lease is in M2. + +```mermaid +stateDiagram-v2 + state "Lease guard (host)" as G { + [*] --> NoLease + NoLease --> Valid: renewal reply for this volume, replica and epoch + Valid --> Valid: renewal before the local deadline + Valid --> Fenced: deadline passed, invalid reply, or revoking + Fenced --> Drained: frontend and cuts stopped + Drained --> Acked: revocation acknowledged with the HEAD gen + } + state "HEAD holder" as H { + [*] --> Attaching + Attaching --> Claiming: fresh local root + Attaching --> Holder: existing root, HEAD is this holder's + Attaching --> Refused: existing root, HEAD published by another holder + Claiming --> Holder: CAS to this epoch and holder, state active + Claiming --> HolderFenced: HEAD epoch higher, or another holder at this epoch + Holder --> Detached: Detach final cut, state detached + Holder --> HolderFenced: a superseding HEAD is seen + } +``` + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| NoLease, Valid | Valid | the reply names this `{volume, replica, epoch}`, its validity is positive and at most 30 s, and it arrives before the old deadline; the new deadline is anchored to the request start | `core/host/volume/workspace_lease.go` `Refresh` | `INV-WS-LEASE-001`, `INV-WS-FORCED-MOVE-001` | +| Valid | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` | +| Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent | `core/host/volume/workspace_lease.go` `drain` | `INV-WS-REVOKE-ACK-001` | +| Attaching | Refused | an existing local root whose HEAD another holder has published (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` | +| Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; the local frontier is seeded from HEAD before the CAS; I/O opens only after the claim | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001` | +| Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | +| Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | +| Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | +| Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | +| Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | +| Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | + +### M5 The cut pipeline + +A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. The steps are described in [agent workspace §5](agent-workspace-design.md#5-the-cut), and the figure in [§3](agent-workspace-design.md#3-remote-layout) shows them against the remote layout. All steps are in `core/storage/chunk_layer.go` `captureLocked` unless stated. + +```mermaid +stateDiagram-v2 + [*] --> Admit + Admit --> Refused: closed, fenced, detached, base install, reconciling, or lineage or lease invalid + Admit --> Stage: earlier unknown CAS settled + Stage --> Quiesce: at most 3 pre-copy rounds + Quiesce --> OpenWindow: Sync H and D fixed under barrier + OpenWindow --> Copy: release barrier + Copy --> Closed: all candidates done + Copy --> Aborted: error, cancellation, observed fence, recovery or close + Aborted --> Refused: drain owners, cleanup, merge candidates + Copy --> Refused: H below HEAD RemoteLSN + Closed --> Upload: drain and cleanup; intent durable first + Upload --> Manifest + Manifest --> Readmit + Readmit --> Fenced: superseding HEAD + Readmit --> CAS + CAS --> Settled: CAS ok, or a re-read shows the proposal + CAS --> Pending: outcome unknown and HEAD unchanged + CAS --> Fenced: HEAD moved to a superseding holder + CAS --> Refused: HEAD moved otherwise (conflict) + Pending --> Admit: next cut settles it first +``` + +| Step | Guard | Enforced in | Protects | +|---|---|---|---| +| Admit | not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease); no cut while reconciling | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-CUT-RECONCILING-001`, `INV-WS-LEASE-001` | +| Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | +| Stage | while more than the barrier bound would be copied, pre-copy outside the barrier; new keys are covered by an intent first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001` | +| Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | +| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read into buffers; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | +| LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | +| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after a durable intent names them | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | +| Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | +| No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` | +| Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` | +| CAS | conditional update on `{gen, epoch}`, with `RemoteLSN = H`; refused for a lower epoch, a lower `RemoteLSN`, or a HEAD in a delete state | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001`, `INV-HEAD-DELETE-FROZEN-001` | +| Settled | drop the intents; reset the bitmap to the cut, keeping chunks dirtied after it | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | +| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | + +### M6 Chunk lifecycle + +HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). + +**HEAD states** (`active`, `detached`, `deleting`, `purging`, `deleted`, `aborted`). + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | +| `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | +| `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | +| `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | +| `active`, `detached` | `deleting` | a blockmaster deletion reservation exists and HEAD is not held | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `markHeadDeleting` | `INV-VOLDEL-HELD-HEAD-001`, `INV-VOL-ID-NO-REUSE-001` | +| `deleting` | previous state | a snapshot name record exists: the delete is refused and reverted | `core/frontend/chunkstore/volume_delete.go` `snapshotsBlock`, `revertHeadDeleting` | `INV-VOLDEL-COMMIT-001` | +| `deleting` | `purging` | commit point, bound to the same delete incarnation | `core/frontend/chunkstore/volume_delete.go` `commitHeadPurging` | `INV-VOLDEL-COMMIT-001` | +| `purging` | `deleted` | chunks dropped and `VOLUME` marked deleted | `core/frontend/chunkstore/volume_delete.go` `finishHeadDeleted`, `markVolumeDeleted` | `INV-VOL-ID-NO-REUSE-001` | +| `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | +| — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | + +**Snapshots and forks.** + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | +| name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | +| published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | +| published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | + +**Intents and key bindings.** + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | +| intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | +| intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` | +| — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | +| bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001` | +| tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | + +--- + +### Local WAL-pressure durability progress + +A serving v3 store at the soft WAL watermark may perform an internal local +sync from its existing flusher, before snapshotting dirty work. This transition +uses the ordinary A/C physical-sync and final fault gate under one `syncMu` +interval; it takes neither `captureMu` nor `lifecycleMu`. It is ineligible while +BASE is installing or the store is closed. The leader is released before extent, +map and checkpoint publication. Client Flush acknowledgements keep their own +covering durability and observer requirements. Recovery invalidates the existing +snapshot lifetime; local persistence does not bypass it. + +- `INV-WAL-V3-PRESSURE-001`: I1, within a recovery/reset lifetime `wack` advances + only after covering local persistence; I2, checkpoint remains at most `wack` + and the active-session pin floor; I3, record reuse remains below the durable + checkpoint, both-slot floor and dirty-reference retirement; I4, with healthy + local progress and no guest Sync, the reuse floor advances. Enforced by + `syncWALBatchV3Internal`, `persistOwnedMapCheckpointV3` and the existing reclaim + publisher. Tests: `TestWALStoreV3NoClientSyncSixRings`, + `TestWALStoreV3PressureSyncFaultDoesNotPublishFrontiers`, + `TestWALStoreV3PressureSyncSkipsInstalling`, + `TestWALStoreV3PressureProgressWithPendingCutOrClose` and + `TestWALStoreV3PressureWaitBudgetAndPin`. Model correspondence: `WALReclaim.tla` I1/I2/I3 and + `AllWritten`/`NoStuckWaiter` in `REC_safe`/`REC_safe_big`; the no-internal-sync + mutant violates liveness. Prior authored LIGHT receipts are referenced in + `docs/spec/README.md`; this change does not claim a new TLC execution. +- A v3 write carries one four-second command deadline through dispatch, + adapter batches, store admission locks and occupancy snapshots. Admission + reserves append headroom and expiry before append refuses without mutation. + Already-started physical I/O, COW/observer callbacks and higher-layer waits + are not preempted. An unresolved pin or local stall returns + `ErrWALPressureTimeout`, preserved as `frontend.ErrBackendBusy`; NVMe returns + Generic/Namespace Not Ready (SC0x82), DNR=0. Sticky faults retain their original + non-retryable mapping. This is a local pressure outcome, not a whole-I/O + deadline; the broader budget gap is tracked separately in issue221. +- A flusher cycle sorts native snapshot entries by record offset and reuses at + most one fully validated record (bounded by WALSize). Every block still checks + its LBA/data offset/LSN/nonce; the cache is local to the snapshot recovery + generation and cannot publish or materialize after that lifetime changes. + `TestWALStoreV3FlushBatchCacheIsBoundToRecoveryLifetime` covers one batch decode + and refusal after Recover. Missing map coverage still forbids checkpoint + advancement; the earlier unmapped dark fixture is not a production geometry. + +## Part B. Invariant ledger + +81 rows: 70 ACTIVE, 11 STUB; 15 kept from the internal ledger, 66 new. + +The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. + +### B.1 Core: storage, durability and the frontend gate + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-REBUILD-SNAPSHOT-COMPLETE-001` | A rebuild snapshot returns all readable nonzero blocks or an error, never a partial success. The sender propagates snapshot failure before shipping blocks or RebuildDone. | M3 NeedsRebuild (base enumeration) | `core/storage/logical_storage.go` `AllBlocks`; storage implementations; `core/transport/rebuild_sender.go` `doRebuild` | `TestChunkHydration_SnapshotFailsOnReadError`, `TestRebuildSnapshotErrorNeverShipsPartialImage` | Existing fail-closed recovery contract; error propagation only | ACTIVE | +| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | +| `INV-FE-NVME-READY-001` | Reads and writes on successfully recovered chunk volumes awaiting attachment wait up to 3s (or an earlier caller deadline) for attachment readiness before storage admission; NVMe readiness timeout/refusal returns Namespace Not Ready (SC0x82), DNR=0, without reading or mutating storage; closed/stale lineage retain their ANA errors and physical I/O faults retain Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable`; `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` | — | ACTIVE | +| `INV-WAL-REPLAY-LWW-001` | Replay applies the highest LSN per LBA, independent of the physical scan order. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALStoreRecoverLastWriterWinsAcrossScanOrder` (`core/storage/walstore_recovery_lww_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | +| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-FRONTIER-GAP-001` | Synced entries above an intentional LSN gap (a rebuild's frontier jump) are kept by recovery. | M1 Recovering | `core/storage/recovery.go` `recoverWAL` | `TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump` (`core/storage/walstore_recovery_frontier_gap_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore.go` `persistCheckpointReleasing` | `TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle` (`core/storage/walstore_checkpoint_safety_test.go`) | — | ACTIVE | +| `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent or superblock), the open store refuses every later `Sync`, write and checkpoint without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestWALStoreWALFsyncFailureIsSticky`, `TestWALStoreExtentFsyncFailureIsSticky`, `TestWALStoreCheckpointFsyncFailureIsSticky` (`core/storage/walstore_sticky_fsync_test.go`); `TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | +| `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteAppendFailure`, `WALStore.Write` | `TestWALStoreWritersQueuedBehindAFailedAppendAreRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | +| `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestWALGenerationFirstCallerReturnOrdering` (`core/storage/walstore_sync_frontier_order_test.go`) | — | ACTIVE | +| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE | +| `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE | +| `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned mapped v3/impl3 volume with the requested chunk geometry and C default/A option. Writable/readonly open validate A/B dependencies, reject actual legacy headers without mutation, and can select a valid fallback when A is damaged. Production provider capture/HEAD restore/status use those selectors. Legacy fixture constructors cannot be called by default production code or enter its transitive storage import closure. | M1 open/create/readonly | `walstore.go` public selectors; `walstore_v3.go` `refuseLegacyWALStore`, `ProbeWALStoreV3`; `provider.go` | `TestWALStoreProductionSelectorCreatesMappedV3`, `TestWALStoreProductionRefusesLegacyWithoutMutation`, `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy`, `TestWALStoreProductionCreateOptions`, `TestLegacyFixtureIsolation`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE | +| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | +| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | +| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | +| `INV-WAL-V3-RECORD-001` | An impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | +| `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | +| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. One earliest command deadline spans adapter batches and the long store admission waits (capture, lifecycle); short locks (store, descriptor, WAL writer) are taken blocking and keep RWMutex writer preference, with the deadline checked once held. The deadline is checked again after a checkpoint rollover and inside the WAL writer after its descriptor snapshot, lock wait and encoding, before the first payload write: an expired command starts no new payload WAL I/O, and expiry before append preserves the WAL/nextLSN/dirty state. A batch that returns a committed prefix with a storage error keeps that error in the classified error set. Issued WAL I/O retains its existing lifecycle ownership. Pure caller expiry stays retryable through required-observer classification and NVMe; a provided physical cause remains terminal. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire`; `write_command_budget.go`; `StorageBackend.Write`; NVMe `handleWrite` | `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait`, `TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders`, `TestWALStoreV3WriteBudgetRefusesNewPayloadAfterRollover`, `TestWALStoreV3WriteBudgetRechecksAfterRollover`, `TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync`, `TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline`, `TestWALStoreV3WritePressureSampleMatchesOccupancy`, `TestStorageBackendExpiredWriteDoesNotAppend`, `TestStorageBackendRequiredObserverDeadlineStaysRetryable`; `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | +| `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains exact dirty retry identity. Checkpoint publication excludes writer admission through both-slot rollover and dirty-reference retirement. Idle, unchanged-checkpoint and admission settle pending rollover; catch-up revalidates tail/checkpoint before delivering its buffered scan. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint`, tagged `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | +| `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | +| `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | +| `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`, `TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | +| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | +| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | +| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | +| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | +| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | +| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | +| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | +| `INV-WAL-V3-MIGRATE-001` | `sw-block migrate-v3` rewrites only the descriptor of a cleanly closed v2/impl1 volume whose WAL the exhaustive scan proves flushed; the scan and the geometry check run before any write, and a refusal leaves the volume and every sidecar byte-identical. It keeps the extent base (WALSize = old - 4096), writes an atomic operator backup, an all-UNKNOWN initial map (covered = the v2 checkpoint), the prepared slot B, slot A at phase 0 (the commit point), slot B at phase 0, and only then retires the v2 chunk bitmap; each step is durable before the next. A rerun decides from the slot bytes alone: before the commit it restarts with a full rescan; after it, it only finishes the rollover and the retirement; a prepared B with an invalid A refuses with `ErrMigrationIncomplete`, as v3 open does; it never reads or restores the backup. | offline tool | `cmd/sw-block/migrate.go`; `cmd/sw-block/internal/v2legacy`; `core/storage/migrate_v3.go` | `TestMigrateV3CleanVolume`, `TestMigrateV3RefusalsChangeNothing`, `TestMigrateV3CrashAfterEachStepIsResumable`, `TestMigrateV3OldBinaryAfterPreparation`, `TestMigrateV3OldWALOverwritesThePreparedSlot`, `TestMigrateV3NeverRestoresTheBackup` (`cmd/sw-block/migrate_test.go`); tagged `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | none (tool) | STUB | +| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA` (expiry and joined physical-fault wire status); `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | + +Notes: + +- `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. +- `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. + +- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. The entry snapshot may already contain LSNs above cp or W from pre-snapshot appends; max-LSN entries remain monotone and idempotent under replay. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. BASE writes, capture UNKNOWN clearing and lifecycle boundaries still invalidate proofs. A reused ordered LSN below a speculative retained map maximum can set UNKNOWN without invalidating the prefix; the high max and replayed retained suffix remain conservative. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. + +- `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests. + +- `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only. +- `INV-FE-FLUSH-SYNC-001`: NVMe/TCP also asserts failed-Sync status and reason logging through the actual session dispatch, and success produces no failure log. +- `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. No v3 tail release exists yet, so the precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired. +- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). Until the chunk layer's side of the v3 install protocol lands (codex03), a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until codex03's v3 FreshFromHead restore lands; since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from (codex01 row 11b P1); it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). +- `INV-WAL-V3-MIGRATE-001`: Format bump v3, plan rows 13a and 13b (DESIGN 10.1). Not yet in this row: the exclusive advisory lock that v3 open will share (precondition 1; it lands with the 12b open path), and raw v2 fixtures committed under testdata (today's controls build v2 volumes with the v2 code that row 14 deletes). The minimum migrated WAL size (64 KiB and two single-block records) is provisional. +- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model (claude05), not by these tests. Installing recovery is row 11. +- `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). It is a STUB until the v3 store is wired in (rows 4 and 5) and activated (row 12b). The v2 checkpoint path (`persistCheckpointReleasing`) is unchanged and is retired in row 14a. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11. +- `INV-WAL-V3-DESCRIPTOR-001`: Format bump v3, plan row 1 (DESIGN r15 section 2). It is a STUB until the activation commit (plan row 12b): no production open or create path reaches the v3 codec before then. The map-dependency checks (root and pages present and hash-valid) are added by plan row 7. The tests decode vectors from an independent generator (`core/storage/testdata/format_v3/slot/gen_slot_vectors.py`). + +### B.2 Core: authority and epochs + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | +| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that clears the lease is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | +| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | + +Notes: + +- `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, directory sync failed): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. +- `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2). +- `INV-WS-RENEW-NONBLOCKING-001`: The cited tests inject delays or holds before or inside the store write; they show sensitivity to a slow store, not a measured disk trace. + +### B.3 Core: replication and replica roles + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | +| `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | +| `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE | +| `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | +| `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | +| `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. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | 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 | + +Notes: + +- `INV-REPL-INGRESS-SLOTS-001`: Binary test: builds and runs the real `blockvolume`; build tag `subprocess`, not on Windows. +- `INV-REPL-PEER-TRANSITIONS-001`: `ReplicaPeer.Invalidate` uses the same gate as `SetState`; from `NeedsRebuild` it keeps the state and still logs the reason (see Part A, M3; [#182](https://github.com/seaweedfs/seaweed-block/issues/182)). + +### B.4 Workspace: HEAD holder, lease and takeover + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-WS-HEAD-CAS-001` | Every HEAD publish is a conditional update on `{gen, epoch}`, so only one holder can publish each HEAD generation; a holder that sees a superseding HEAD fences itself. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | +| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`) | `WorkspaceTakeover` `HeadMonotone` | 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-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published 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`) | — | ACTIVE | +| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | +| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | + +Notes: + +- `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary. +- `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits). +- `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. + +### B.5 Workspace: the cut pipeline + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | +| `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | +| `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | +| `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE | +| `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | +| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | +| `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | +| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | +A guest read has a cooperative arrival budget; internal contextless readers keep the owned fill timeout (default 30 s). With five immediate host retries, cold fills slower than roughly 20–24 s can still end in guest EIO despite shared work; retry-delay advertisement remains separate. A changed generation replaces its promise without abandoning the old worker. `AllBlocks` returns an error and no partial image on a failed read; the rebuild sender propagates it before sending blocks. + + +Notes: + +- `INV-CUT-STAGED-REUSE-001`: `captureLocked` also requires HEAD's generation to be the one the stage was compared against (code reading; not asserted by these tests). + +### B.6 Workspace: chunk lifecycle, GC and delete + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | +| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | +| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | +| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | +| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | +| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | +| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | +| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | +| `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | + +Notes: + +- `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace. + +### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | +| `INV-PROMOTE-FRONTIER-001` | The RF=3 promotion gate promotes only a probed candidate that covers the required acknowledgement frontier, and blocks promotion without a fresh probe. With a known frontier the candidate's durable LSN must be at least the required LSN. With an unknown frontier under `sync_quorum` or `sync_all`, the highest-durable ready candidate is promoted only when at least P-K+1 distinct peers are probed ready and fresh in the same tick (K from `waitForSyncAcks`; RF=3: both peers under `sync_quorum`, one under `sync_all`); otherwise nothing is promoted. An unknown frontier is never read as zero; `best_effort` is unchanged. | M3 Supporting → Primary (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe`, `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe`, `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused`, `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | +| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE | +| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE | +| `INV-OBS-PRODUCT-EVENTS-001` | blockmaster records placement-verified, promotion-candidate-evaluation and authority-published events, and the CSI node reports `csi_reattach_observed` after a successful stage. | M3 promotion decision (observation) | `core/host/master/product_loop.go` `recordPlacementVerifiedEvents`, `recordPromotionEvaluationEvents`, `recordAuthorityPublishedEvent` | `TestMasterTimeline_RecordsPlacementVerified`, `TestMasterTimeline_RecordsPromotionCandidateEvaluation`, `TestMasterTimeline_RecordsAuthorityPublishedAfterMint` (`core/host/master/event_ring_test.go`); `TestNodeStage_ReportsCSIReattachObservedAfterSuccessfulStage` (`core/csi/node_test.go`) | — | ACTIVE | +| `INV-HELM-RF-NODECOUNT-001` | Generated Helm values fail closed when the requested replication factor exceeds the selected Ready schedulable node count. | M3 (configuration) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`, `selectHelmValuesNodes` | `TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes` (`cmd/sw-block/main_test.go`) | — | ACTIVE | +| `INV-HOSTPATH-TRANSPARENT-001` | The read model reports transparent host-path recovery only with a multipathed, Active/Optimized, stale-fenced path, writer and reader checks, and the same pod UID. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume`, `deriveManagedVolumeStates` | `TestManagedVolumeProjection_TransparentISCSIALUARecovered`, `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-K8S-REATTACH-001` | A CSI re-stage after failover uses the fresh publish target, and the read model reports recovery by reattach only with CSI reattach observed and a verified reader. | K8s readiness model | `core/csi/node.go` `refreshPublishContext`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestManagedVolumeProjection_NodeLossReattachRecovered` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-MANAGED-VOLUME-READMODEL-001` | Volume explanations in the observation report and explain output are rendered from the `ManagedVolume` projection. | K8s readiness model | `core/ops/managed_volume_model.go` `ProjectManagedVolume` | `TestObservationExplain_IncludesManagedVolumeProjectionAndDryRunActions`, `TestObservationReportSummary_IncludesManagedVolumeStatus` (`core/ops/observation_report_test.go`); `TestProjectManagedVolumeFromEvidence_DualPrimaryInvalid` (`core/ops/managed_volume_evidence_test.go`) | — | ACTIVE | +| `INV-CONTROL-CONTEXT-001` | Cross-layer explanations replayed from a bundle are derived from recorded facts and events. Superseded in scope by `INV-MANAGED-VOLUME-READMODEL-001`; kept for continuity. | K8s readiness model | `core/ops/observation_bundle.go` `BuildObservationFromBundle` | `TestObservationBundle_RendersNodeLossRecoveryStory`, `TestObservationBundle_ManagedVolumeUsesPrimaryFailureArtifactHints` (`core/ops/observation_bundle_test.go`) | — | ACTIVE | +| `INV-K8S-ADAPTOR-FACTS-001` | PVC, pod, node and CSI conditions enter the read model as typed facts and map to distinct blocked reasons before any recovery status is derived. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestManagedVolumeProjection_PVCPendingBlocked`, `TestManagedVolumeProjection_WriterFailedMountBlocked`, `TestManagedVolumeProjection_CSINodeImagePullBlocked`, `TestManagedVolumeProjection_LoopbackCrossNodeBlocked` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-HOSTPATH-FACTS-001` | The read model keeps path facts separate from the recovery claim: missing multipath blocks the transparent claim, and an NVMe ANA seam alone does not infer transparent recovery. | K8s readiness model | `core/ops/managed_volume_model.go` `deriveManagedVolumeStates`, `hasTransparentHostPathEvidence` | `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim`, `TestManagedVolumeProjection_NVMeANASeamDoesNotInferTransparentRecovery` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-FENCE-SELF-ON-PROMOTE-001` | A primary at epoch e applies no inbound replication traffic (ship, recovery lane start, rebuild), and none below e; it still answers probes, and its epoch floor never goes down when it later supports another primary (fencing gap G2). | M3 Supporting → Primary | `core/transport/replica.go` `FenceAsPrimary`, `acceptMutationLineage`; `core/host/volume/host.go` `fenceSelfWithPeers` | `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`); `TestG2_PrimaryListenerRefusesMutationsButAnswersProbes`, `TestG2_FloorStaysWhenThePrimaryLaterSupportsAnother` (`core/transport/g2_self_fence_test.go`) | `ReplicationFailover` `AckedSurvive`, `NoStaleAck` | ACTIVE | +| `INV-FENCE-FLOOR-DURABLE-001` | A replica never accepts mutating traffic below the highest epoch it has acknowledged or taken a role at, across restarts, and accepts none before its assignment is known; a role call whose floor cannot be made durable is not adopted and keeps the frontend unhealthy (fencing gap G1). | M3 Unassigned → Primary \| Supporting | `core/transport/replica.go` `raiseFloor`, `admitMutation`, `AdmitAsReplica`; `core/host/volume/host.go` `latchRoleAdmission` | `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch`, `TestG1_ConcurrentRaisesNeverLowerTheRecord`, `TestG1_RoleCallsPersistBeforeReturning` (`core/transport/g1_durable_floor_test.go`); `TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | + +Notes: + +- `INV-AUTH-ONE-PRIMARY-001`: Narrowed. The lab evidence field `post_failure_primary_count=1` is not read by any Go test. `IntentBind` is checked per volume: the Publisher refuses a genesis `Bind` (`ErrBindAlreadyBound`) once any slot of the volume holds a present line, also after a restart, when only the current slot is reloaded; `decideVolume` also binds only when the volume has no line ([#183](https://github.com/seaweedfs/seaweed-block/issues/183)). +- `INV-FENCE-STALE-PRIMARY-001`: Narrowed. A primary cut off from blockmaster that has not seen the newer line keeps admitting I/O, and under `best_effort` its local `fsync` still acknowledges (no primary lease on the Kubernetes path; see the Kubernetes known gaps). The lab counter `old_primary_stale_io_success_count=0` is lab evidence only. +- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`. +- `INV-K8S-NONLOOPBACK-001`: Rejection is opt-in: the chart default for `network.rejectLoopbackPublishTargets` is false; the generator sets it for multi-node values. +- `INV-OBS-PRODUCT-EVENTS-001`: Each event type has a unit test; all four together in one node-loss run is lab evidence only. +- `INV-HOSTPATH-TRANSPARENT-001`: Narrowed to the classifier. It does not compare the host path target with the promoted target, and only the missing-multipath case has a negative test. The mounted-failover run is lab evidence. +- `INV-K8S-REATTACH-001`: The full node-loss run through pod recreate is lab evidence; the classifier does not check that the re-stage target equals the promoted frontend. +- `INV-MANAGED-VOLUME-READMODEL-001`: Partial. No guard test shows that other surfaces never build their own status, and `core/ops/observation_bundle.go` `applyPrimaryFailureSummary` sets a recovered status from summary keys without the classifier. +- `INV-K8S-ADAPTOR-FACTS-001`: Narrowed. The fact metadata the internal row names (source, time, generation, confidence) is neither filled in nor read by the classifier. +- `INV-HOSTPATH-FACTS-001`: Narrowed. There is no session-reachability fact, the classifier does not read the ALUA state, and the artifact path derives the multipath and Active/Optimized facts from one `transparent_failover_claimed` hint. + +**Not in the ledger.** Known gaps where the code does not yet hold the property are tracked as known issues, not as rows: the [core known issues](block-design.md#24-known-issues-and-work-in-progress), the [agent workspace known gaps](agent-workspace-design.md#14-known-gaps) and the [Kubernetes known gaps](kubernetes-block-design.md#12-known-gaps). A fix that closes one adds its row here. + +--- + + +### B.8 NVMe/TCP receive bounds + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | + +## Part C. Change rules + +How a fix or a feature is calibrated against this model: + +1. **Name the touched IDs.** The pull request lists every Part B ID whose statement, enforcing function or test it touches, and the Part A machine and transition. A change on a protocol path that touches no ID says why. +2. **States and transitions move together.** A new or changed state, transition or guard updates, in the same pull request: the Part A table, its diagram (in the design document, or here when the design document has none), the Part B rows, and the TLA+ specification if one models that machine (with its configurations re-run and the results in `docs/spec/README.md`). +3. **An ACTIVE row never loses its test.** Renaming or moving a test updates the row. Deleting a test, or weakening it so it no longer asserts the statement, needs a replacement test in the same pull request. +4. **Every bug becomes a test and a row.** A bug found by a unit test, a review, a soak or chaos run, or a TLA+ counterexample becomes a regression test that fails before the fix and passes after it, and a new or updated Part B row naming that test. +5. **Rows are stable.** IDs are never reused or renumbered. A retired row stays with status `ARCHIVED` and a reason. A narrowed statement says what was dropped in a note. +6. **STUB rows block claims.** A release note or a design document must not claim a property backed only by a `STUB` row. Turning a `STUB` into `ACTIVE` is the test plus the status change. + +Format v3 row 4 remains dark. Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The later W/BASE/fence owner must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. + +### Dark v3 offline reader (row12a) + +- `INV-WAL-V3-READONLY-001` (ACTIVE for the explicit dark selector only): the explicit dark reader opens store and map read-only, validates both live slot dependencies and the trusted WAL prefix, merges WAL winners above the checkpoint with extents, and never runs recovery, a fence, a worker, or publication. Installing images, corrupt acknowledged WAL/map dependencies and unfinished fresh restores refuse. WAL records are checked again at read. An absent remote chunk returns `ErrReadOnlyNotResident`, even with a local hint; offline reading does not perform remote fills. The public selector remains legacy until row12b. +- Controls: `TestWALStoreV3_ReadOnlyMergesWALAndExtentWithoutWrites`, `TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies`, `TestWALStoreV3_ReadOnlyNeverReturnsUnfilledExtentZeros`, `TestWALStoreV3_ReadOnlyRevalidatesWALAndBindsReadonlyMetadata`, and the actual endpoint snapshot caller `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture`. Reader mutex covers the descriptor read and Close; no new lock edge or durability state transition. + +### Dark v3 chunk/BASE integration (row12a) + +- `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for dark mapped v3): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu. +- The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging/reconciliation generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission. +- Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. The provider keeps the constructed layer private as chunkPending until this commit succeeds; explicit publication cannot resolve it and the scheduler starts only after commit. Failed commits retain the private layer for retry without reattaching. Held pre-marker controls require Capture/Cut/MakeRemoteDurable to return ErrNotChunkVolume with no new remote writes, intents or HEAD changes, then crash/reopen exact local bytes. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam. diff --git a/seaweed-block/docs/design/kubernetes-block-design.md b/seaweed-block/docs/design/kubernetes-block-design.md index da6027ef69..f414c1838f 100644 --- a/seaweed-block/docs/design/kubernetes-block-design.md +++ b/seaweed-block/docs/design/kubernetes-block-design.md @@ -12,7 +12,7 @@ The three design documents: | [Agent workspace design](agent-workspace-design.md) | Agent workspace disks (proof of concept): one local replica per workspace, cuts to SeaweedFS, snapshots, forks, GC, host moves | | Kubernetes block design (this document) | The product view of Kubernetes volumes: CSI, Helm and the operator controllers, replication and failover, multipath, promotion, readiness, the operation layer | -The replication engine itself (shipping by LSN, barriers, durability modes, replica fencing, catch-up and rebuild decisions) is a core component and is described in [core §1.6](block-design.md#16-replication-and-failover). Conventions are those of the core document: code references name a file and a function; test references name the test function and its file. +The replication engine itself (shipping by LSN, barriers, durability modes, replica fencing, catch-up and rebuild decisions) is a core component and is described in [core §1.6](block-design.md#16-replication-and-failover). Conventions are those of the core document: code references name a file and a function; test references name the test function and its file. The state machines and invariants of this document are also in the shared ledger, [Invariants and state machines](invariants.md). ## Contents @@ -208,7 +208,7 @@ The volume computes whether it may become primary; blockmaster decides; only the | 5 | `post_close_durable_ack_needed` | a recovered replica has not delivered its post-rebuild durable acknowledgement | | 6 | `promotion_ready` | all checks pass | -**RF=3 gate** (`core/host/master/promotion_probe.go`, `promotionAllowedReplicas`, `chooseAllowedPromotionTarget`): no promotion when the probe failed or is not installed, or the ack profile is unknown; a candidate is skipped when it is not `replica_ready` with a known frontier, or its durable LSN is below the required frontier. The decision is recorded as an ops event (`candidate_covers_required_frontier`, `candidate_frontier_behind`, `no_promotion_ready_candidate`). The required frontier per volume (`RequiredLSNByVolume`) is not set by `cmd/blockmaster` today, so the effective rule is "ready, highest durable LSN" (§12). +**RF=3 gate** (`core/host/master/promotion_probe.go`, `promotionAllowedReplicas`, `chooseAllowedPromotionTarget`): no promotion when the probe failed or is not installed, or the ack profile is unknown; a candidate is skipped when it is not `replica_ready` with a known frontier, or its durable LSN is below the required frontier. The decision is recorded as an ops event (`candidate_covers_required_frontier`, `candidate_frontier_behind`, `no_promotion_ready_candidate`). The required frontier per volume (`RequiredLSNByVolume`) is not set by `cmd/blockmaster` today, so the frontier is unknown and coverage is proven from the survivors instead: with `sync_quorum` or `sync_all`, the ready candidate with the highest durable LSN is promoted only when at least P-K+1 of the P peers are probed ready (known durable LSN) and have a fresh heartbeat, where K is the number of peer acks a write needs (`waitForSyncAcks`: P for `sync_all`, (P+1)/2 for `sync_quorum`). Any P-K+1 peers include one that holds every acknowledged write that their sampled frontiers represent. The probes of one tick are snapshots, not a fence: a primary that is still running can acknowledge after a sample was taken (for example, r3 reports 70 in a held probe response, the old primary then acknowledges 71, and r2 at 70 is still selected). That is the missing primary lease below (§12, #195). For RF=3 that is both peers under `sync_quorum` and one under `sync_all`; with fewer, nothing is promoted. An unknown frontier is never read as zero. `best_effort` is unchanged (§12). **What blocks a promotion:** any engine reason above; `unhealthy_reason` set or withdrawn; an unreachable or ineligible server; boot grace still holding; a current primary whose probe is ready; a snapshot rejected for slot count; slots that changed while the probe ran. @@ -303,9 +303,9 @@ Status per feature is in [Kubernetes status](../kubernetes-status.md) and [what These are found by reading the code at this revision; most are tracked for fixes. Gaps that apply to the whole codebase are in the [core known issues](block-design.md#24-known-issues-and-work-in-progress). -- **No primary lease on the Kubernetes path.** A primary cut off from blockmaster keeps admitting I/O under its last assignment until it observes a newer one. The replicas' epoch floors refuse its shipped frames, which fails its `Sync` under `sync_quorum` or `sync_all`; under best-effort, the chart default, its local `fsync` still acknowledges. Its frontend also keeps reporting Active/Optimized, so a node that still reaches it may keep using that path. The workspace lease (`--workspace-lease`) requires `walstore-chunk` and is not rendered for Kubernetes volumes. +- **No primary lease on the Kubernetes path.** A primary cut off from blockmaster keeps admitting I/O under its last assignment until it observes a newer one. The replicas' epoch floors refuse its shipped frames, which fails its `Sync` under `sync_quorum` or `sync_all`; under best-effort, the chart default, its local `fsync` still acknowledges. Its frontend also keeps reporting Active/Optimized, so a node that still reaches it may keep using that path. The workspace lease (`--workspace-lease`) requires `walstore-chunk` and is not rendered for Kubernetes volumes. It also bounds the RF=3 survivor rule (§6): that rule covers only the acknowledgements represented by the frontiers sampled in one tick, so an acknowledgement the old primary gives after the sample (for example, 71 after a held r3=70 response, with r2=70 selected) is not covered. Tracked in #195. - **Synchronous durability needs two settings.** `replication.ackProfile` reaches blockvolume only with `compat.launcherReplicationAckFlag: true`. -- **The RF=3 required frontier is not wired.** `RequiredLSNByVolume` is never set by `cmd/blockmaster`, so promotion picks the ready candidate with the highest durable LSN without checking it against the last acknowledged sync. +- **The RF=3 required frontier is not wired.** `RequiredLSNByVolume` is never set by `cmd/blockmaster`, and the master has no source for it: heartbeats carry no LSN and the master stores no acknowledged LSN. Promotion therefore relies on the survivor rule in §6 (all peers seen under `sync_quorum`), so an RF=3 `sync_quorum` volume with one peer down and its primary lost is not promoted automatically. A real acknowledged-frontier source remains a gap (#192). - **Returned-replica rebuild is not deployable through Helm.** The executor exists, but `--runtime-rebuild-endpoint` is not rendered. - **CSI publish is not fenced per node.** `ControlStatusLookup` ignores the node id. - **The CSI node uses the controller's service account**, with write access to PVs, PVCs and `SwBlockVolume` objects. diff --git a/seaweed-block/docs/design/wal-v3-burst-admission.md b/seaweed-block/docs/design/wal-v3-burst-admission.md new file mode 100644 index 0000000000..dd29a0dbf0 --- /dev/null +++ b/seaweed-block/docs/design/wal-v3-burst-admission.md @@ -0,0 +1,45 @@ +# Native WAL burst admission + +A fresh v3 walstore-chunk volume has a 64 MiB WAL by default. Before this fix, +the common admission callback sampled `s.wal`, the legacy writer. V3 appends go +to `s.v3.w`, so the inactive legacy occupancy stayed zero. A real provider and +NVMe handler writing 128 KiB requests with Flush every 48 MiB hit WRITE +InternalError / WAL region full at 66,977,792 submitted bytes. The same schedule +reproduced on root WSL and non-root tp04. The preceding Flush and a direct Sync +after the failed Write succeeded. This does not establish the cause of the +reported guest SyncAll EIO; a host fsync error is not by itself an observed +backend Sync error. + +Admission now samples native physical head minus the both-slot reuse floor. +The existing soft/hard watermarks, flusher notification and deadline stay in +place. The sampler holds store.mu shared while selecting the writer, snapshots +the descriptor/floor, releases descMu, then samples head under writer.mu. It +releases all these locks before admission can sleep or wait. Existing publication +order is unchanged; there is no fsync, slot/map write, early acknowledgement or +new reuse permission in this callback. A missing/unbound writer remains an append-binding refusal, not capacity pressure; +the existing typed guard runs without a pressure wait. +Legacy fixtures keep the original legacy occupancy. Very large batches, +concurrent already-admitted requests or a fully unsynced ring can still exhaust +space; this change is not a reservation scheme or a guarantee for every burst. + +The real NVMe session logs failed Flush status and IOResult.Reason using its +existing target logger. This preserves the backend diagnostic that the CQE +cannot carry. Success emits no failure log; the status/error mapping is +unchanged. Use that target log to attribute a future Flush failure rather than +inferring its cause from a guest EIO alone. + +Controls: `TestWALStoreV3AdmissionUsesNativeOccupancy` asserts exact encoded +occupancy and release after checkpoint/rollover; the public provider + actual +NVMe handler `TestWALStoreChunkV3_SequentialBurstFlush` writes 320 MiB and verifies +every byte against submitted literals; `TestSessionFlushLogsBackendReason` +uses actual session dispatch, asserts error status, reason logging exactly once, +and no failure log on success. INV-WAL-V3-ADMISSION-001 and +INV-FE-FLUSH-SYNC-001 record these checks. The durability/format model is unchanged; +no new TLC or mounted performance claim is made. + +The fault-at-ACK-boundary control parks writer B after existing capacity +admission, before A's held slot publication, then requires B to own store.mu +exclusively (TryRLock fails) before releasing A. A shared sampling lock cannot +stand in for that handshake. Its injected failing append and no-W-advance +assertions remain unchanged. The half-reset control keeps its original typed +binding-refusal assertion. diff --git a/seaweed-block/docs/spec/CutCOW.tla b/seaweed-block/docs/spec/CutCOW.tla new file mode 100644 index 0000000000..73ca53329f --- /dev/null +++ b/seaweed-block/docs/spec/CutCOW.tla @@ -0,0 +1,158 @@ +------------------------------- MODULE CutCOW ------------------------------- +(***************************************************************************) +(* S4b: copy-before-write (COW) in the cut window (roadmap 1b), against *) +(* today's barrier cut. Proposed design, not implemented (2026-11-18). *) +(* *) +(* Today (Mode "barrier", chunk_layer.go captureLocked, main afe1d32d): *) +(* the capture barrier is held while every candidate chunk is copied, so *) +(* no write lands between H and the end of the copy (the stall: 1.50 s at *) +(* 3 GiB dirty, lab measurement). *) +(* COW (Mode "cow"): the barrier only fixes H (the cut's Sync) and the *) +(* candidate set D, then releases. A write to a chunk of D that is not *) +(* yet copied first saves that chunk's current (= at-H) content to a side *) +(* file; the copier reads the side file if present, else the live chunk. *) +(* The side file is local and is dropped after the HEAD CAS and on crash. *) +(* *) +(* Content is abstracted to "the LSN of the write a chunk holds", as in *) +(* CutCapture. vis = what the read path returns (WAL over extent); ext = *) +(* the extent (the flusher moves vis to ext). *) +(* *) +(* Mut (each must violate a safety invariant; "none" must hold): *) +(* noCopy a write in the window never saves the old content *) +(* copyAfter the side file is written with the NEW content *) +(* sideReuse the side file is not dropped after the CAS *) +(* earlyRelease writes are admitted between fixing H and fixing D *) +(* copyAtFlush the old content is saved when the flusher overwrites the *) +(* extent, not when the write becomes visible *) +(* noChunkLock (r1) a write proceeds while its chunk is being copied *) +(* r1: the copy of one chunk is two steps (CopyStart, CopyFinish): a real *) +(* copy reads 1,024 blocks. The fix: a write to a chunk in "copying" waits. *) +(***************************************************************************) +EXTENDS Integers, FiniteSets, Sequences, TLC + +CONSTANTS Chunks, MaxLSN, MaxCuts, MaxCrash, Mode, Mut + +NONE == -1 +Zero == [c \in Chunks |-> 0] +NoSide == [c \in Chunks |-> NONE] +Idle == [pc |-> "idle", H |-> 0, D |-> {}, copied |-> {}, copying |-> {}, buf |-> Zero] + +VARIABLES hist, \* the current lineage: hist[i] = the chunk written at LSN i + synced, \* highest synced LSN + vis, \* read-visible content per chunk + ext, \* extent content per chunk + side, \* side file: saved at-H content per chunk, or NONE + head, \* published HEAD: [lsn, img] + cut, \* the cut in progress + dirty, \* chunks changed since HEAD (the dirty set) + cuts, crashes, + crashedWithSide \* ghost: a crash dropped a non-empty side file +vars == <> + +VA(h, c, L) == LET ws == {i \in 1..L : i <= Len(h) /\ h[i] = c} + IN IF ws = {} THEN 0 ELSE CHOOSE m \in ws : \A k \in ws : k <= m +ValueAt(c, L) == VA(hist, c, L) +WrittenAfter(h, L) == {h[i] : i \in {j \in (L + 1)..Len(h) : j >= 1}} + +Init == /\ hist = <<>> /\ synced = 0 /\ vis = Zero /\ ext = Zero /\ side = NoSide + /\ head = [lsn |-> 0, img |-> Zero] /\ cut = Idle /\ dirty = {} + /\ cuts = 0 /\ crashes = 0 /\ crashedWithSide = FALSE + +\* Write admission. "barrier": no write from CutBegin until the CAS. "cow": no write while H and D are +\* being fixed (pc "barrier"); mutant earlyRelease admits writes there too. +Blocked == \/ Mode = "barrier" /\ cut.pc \in {"barrier", "copying"} + \/ Mode = "cow" /\ cut.pc = "barrier" /\ Mut # "earlyRelease" + +Write(c) == + /\ Len(hist) < MaxLSN /\ ~Blocked + /\ ~(Mode = "cow" /\ c \in cut.copying /\ Mut # "noChunkLock") \* r1: the per-chunk wait + /\ LET n == Len(hist) + 1 + inWin == cut.pc = "copying" /\ c \in cut.D \ (cut.copied \cup cut.copying) + save == Mode = "cow" /\ inWin /\ side[c] = NONE /\ Mut \notin {"noCopy", "copyAtFlush"} + IN /\ hist' = Append(hist, c) + /\ side' = IF save THEN [side EXCEPT ![c] = IF Mut = "copyAfter" THEN n ELSE vis[c]] ELSE side + /\ vis' = [vis EXCEPT ![c] = n] + /\ dirty' = dirty \cup {c} + /\ UNCHANGED <> + +Sync == /\ synced < Len(hist) /\ synced' = Len(hist) + /\ UNCHANGED <> + +\* The flusher writes the visible content to the extent. Mutant copyAtFlush saves the extent's old +\* content here (too late: the read path already returns the new write). +Flush(c) == + /\ ext[c] # vis[c] + /\ ext' = [ext EXCEPT ![c] = vis[c]] + /\ side' = IF Mode = "cow" /\ Mut = "copyAtFlush" /\ cut.pc = "copying" /\ c \in cut.D \ cut.copied /\ side[c] = NONE + THEN [side EXCEPT ![c] = ext[c]] ELSE side + /\ UNCHANGED <> + +\* The barrier: the cut's own Sync fixes H. +CutBegin == /\ cut.pc = "idle" /\ cuts < MaxCuts /\ Len(hist) > head.lsn + /\ synced' = Len(hist) + /\ cut' = [Idle EXCEPT !.pc = "barrier", !.H = Len(hist)] + /\ UNCHANGED <> + +\* D is fixed; in "cow" the barrier is released here. +FixD == /\ cut.pc = "barrier" + /\ cut' = [cut EXCEPT !.pc = "copying", !.D = dirty, !.copied = {}] + /\ UNCHANGED <> + +\* The copier reads one candidate: the side file if present, else the live chunk (the normal read path). +CopyStart(c) == /\ cut.pc = "copying" /\ c \in cut.D \ (cut.copied \cup cut.copying) + /\ cut' = [cut EXCEPT !.copying = @ \cup {c}] + /\ UNCHANGED <> +\* the read completes: the side file if present, else the live chunk as it is now +CopyFinish(c) == /\ c \in cut.copying + /\ cut' = [cut EXCEPT !.copying = @ \ {c}, !.copied = @ \cup {c}, + !.buf[c] = IF side[c] # NONE THEN side[c] ELSE vis[c]] + /\ UNCHANGED <> + +\* Upload + HEAD CAS at H; the dirty set keeps the chunks written after H; the side file is dropped. +CutCAS == /\ cut.pc = "copying" /\ cut.copied = cut.D /\ cut.copying = {} + /\ head' = [lsn |-> cut.H, img |-> [c \in Chunks |-> IF c \in cut.D THEN cut.buf[c] ELSE head.img[c]]] + /\ dirty' = WrittenAfter(hist, cut.H) + /\ side' = IF Mut = "sideReuse" THEN side ELSE NoSide + /\ cut' = Idle + /\ cuts' = cuts + 1 + /\ UNCHANGED <> + +\* Power loss: unsynced writes are gone; the cut in flight and the side file are dropped; recovery +\* rebuilds content and the dirty set from the synced prefix (WAL replay), never from the side file. +Crash == /\ crashes < MaxCrash + /\ LET h == SubSeq(hist, 1, synced) + img == [c \in Chunks |-> VA(h, c, Len(h))] + IN /\ hist' = h /\ vis' = img /\ ext' = img + /\ dirty' = WrittenAfter(h, head.lsn) + /\ side' = NoSide /\ cut' = Idle + /\ crashes' = crashes + 1 + /\ crashedWithSide' = (crashedWithSide \/ side # NoSide) + /\ UNCHANGED <> + +Next == \/ \E c \in Chunks : Write(c) \/ Flush(c) \/ CopyStart(c) \/ CopyFinish(c) + \/ Sync \/ CutBegin \/ FixD \/ CutCAS \/ Crash +Spec == Init /\ [][Next]_vars + +----------------------------------------------------------------------------- +\* HEAD is the exact image of the lineage at HEAD.lsn: every uploaded chunk is its content as of H. +HeadImage == \A c \in Chunks : head.img[c] = ValueAt(c, head.lsn) +\* Every copied candidate holds its content as of H (the direct form of HeadImage, before the CAS). +BufFrozen == \A c \in cut.copied : cut.buf[c] = ValueAt(c, cut.H) +\* A saved side-file entry holds the chunk's content as of H. +SideFrozen == cut.pc = "copying" => \A c \in Chunks : side[c] # NONE => side[c] = ValueAt(c, cut.H) +\* The side file exists only inside a cut window. +SideOnlyInCut == cut.pc = "idle" => side = NoSide +\* COW never changes what a read returns: every chunk shows its newest write. +ReadsNewest == \A c \in Chunks : vis[c] = ValueAt(c, Len(hist)) +\* HEAD never covers more than is synced. +HeadLeSynced == head.lsn <= synced /\ head.lsn <= Len(hist) +TypeOK == /\ cut.pc \in {"idle", "barrier", "copying"} /\ cut.copied \subseteq cut.D /\ cut.copying \subseteq cut.D /\ cut.copied \cap cut.copying = {} /\ cut.D \subseteq Chunks + +\* Witnesses (expected VIOLATED = reachable, for non-vacuity): +\* a write landed in a candidate chunk before it was copied, and the side file took the old content +W_WriteInWindow == ~(Mode = "cow" /\ cut.pc = "copying" /\ \E c \in cut.D \ cut.copied : side[c] # NONE) +\* a cut is ready to CAS with at least one candidate taken from the side file +W_CASAfterWindowWrite == ~(Mode = "cow" /\ cut.pc = "copying" /\ cut.copied = cut.D /\ side # NoSide) +\* a crash dropped a non-empty side file (and HeadImage still holds afterwards) +W_CrashDroppedSide == ~crashedWithSide +============================================================================= diff --git a/seaweed-block/docs/spec/CutCOW2.tla b/seaweed-block/docs/spec/CutCOW2.tla new file mode 100644 index 0000000000..292cb4c7ad --- /dev/null +++ b/seaweed-block/docs/spec/CutCOW2.tla @@ -0,0 +1,146 @@ +------------------------------- MODULE CutCOW2 ------------------------------- +(***************************************************************************) +(* S4c r2: copy-before-write in the cut window, with the save as I/O and *) +(* an abort. Proposed design, not implemented (2026-11-18). *) +(* *) +(* As r1 (CutCOW): barrier vs COW; the barrier fixes H and D, then (COW) *) +(* releases; a chunk copy is CopyStart + CopyFinish and a write to a chunk *) +(* being copied waits. New in r2: *) +(* - the writer's save is I/O too: SaveStart claims the chunk (state *) +(* saving, it reads the at-H content), SaveFinish writes it to the side *) +(* store. The write itself waits until its chunk is saved. The in- *) +(* flight save lives in `pend`, outside the cut record, as real I/O *) +(* outlives a cut record that someone else tears down. *) +(* - an abort (save error, cancel, Close): AbortStart invalidates the cut *) +(* and releases waiters; AbortFinish deletes the side store and ends *) +(* the window only once no saving or copying owner is left (the join). *) +(* Mut: *) +(* noCopy a write in the window never saves *) +(* noChunkLock a write proceeds while its chunk is being copied *) +(* abortNoJoin AbortFinish does not wait for saving/copying owners: a *) +(* save still in I/O completes into a side store that has *) +(* already been deleted, i.e. into whatever window is next *) +(***************************************************************************) +EXTENDS Integers, FiniteSets, Sequences, TLC + +CONSTANTS Chunks, MaxLSN, MaxCuts, MaxCrash, MaxAborts, Mode, Mut + +NONE == -1 +Zero == [c \in Chunks |-> 0] +NoSide == [c \in Chunks |-> NONE] +Idle == [pc |-> "idle", H |-> 0, D |-> {}, copied |-> {}, copying |-> {}, saving |-> {}, buf |-> Zero] + +VARIABLES hist, synced, vis, ext, side, pend, head, cut, dirty, cuts, crashes, aborts +vars == <> + +VA(h, c, L) == LET ws == {i \in 1..L : i <= Len(h) /\ h[i] = c} + IN IF ws = {} THEN 0 ELSE CHOOSE m \in ws : \A k \in ws : k <= m +ValueAt(c, L) == VA(hist, c, L) +WrittenAfter(h, L) == {h[i] : i \in {j \in (L + 1)..Len(h) : j >= 1}} + +Init == /\ hist = <<>> /\ synced = 0 /\ vis = Zero /\ ext = Zero /\ side = NoSide /\ pend = NoSide + /\ head = [lsn |-> 0, img |-> Zero] /\ cut = Idle /\ dirty = {} + /\ cuts = 0 /\ crashes = 0 /\ aborts = 0 + +Open == Mode = "cow" /\ cut.pc = "copying" \* a live COW window (not aborting) +\* c still needs a save before a write to it may publish +NeedSave(c) == Open /\ c \in cut.D \ (cut.copied \cup cut.copying \cup cut.saving) /\ side[c] = NONE + +Blocked(c) == \/ Mode = "barrier" /\ cut.pc \in {"barrier", "copying"} + \/ Mode = "cow" /\ cut.pc = "barrier" + \/ Open /\ c \in cut.copying /\ Mut # "noChunkLock" \* wait for the copier + \/ Open /\ c \in cut.saving \* wait for the saving owner + \/ NeedSave(c) /\ Mut # "noCopy" \* a save must come first + +Write(c) == + /\ Len(hist) < MaxLSN /\ ~Blocked(c) + /\ LET n == Len(hist) + 1 IN + /\ hist' = Append(hist, c) + /\ vis' = [vis EXCEPT ![c] = n] + /\ dirty' = dirty \cup {c} + /\ UNCHANGED <> + +\* a writer becomes the owner of a pending candidate and reads its current (= at-H) content +SaveStart(c) == /\ NeedSave(c) /\ Mut # "noCopy" /\ Len(hist) < MaxLSN /\ pend[c] = NONE + /\ cut' = [cut EXCEPT !.saving = @ \cup {c}] + /\ pend' = [pend EXCEPT ![c] = vis[c]] + /\ UNCHANGED <> + +\* the save's I/O completes: into the live window's side store; discarded if the window is aborting; +\* an orphan (only reachable with abortNoJoin) writes into whatever side store exists now +SaveFinish(c) == /\ pend[c] # NONE + /\ side' = IF cut.pc = "aborting" THEN side ELSE [side EXCEPT ![c] = pend[c]] + /\ cut' = [cut EXCEPT !.saving = @ \ {c}] + /\ pend' = [pend EXCEPT ![c] = NONE] + /\ UNCHANGED <> + +Sync == /\ synced < Len(hist) /\ synced' = Len(hist) + /\ UNCHANGED <> + +Flush(c) == /\ ext[c] # vis[c] /\ ext' = [ext EXCEPT ![c] = vis[c]] + /\ UNCHANGED <> + +CutBegin == /\ cut.pc = "idle" /\ cuts < MaxCuts /\ Len(hist) > head.lsn + /\ synced' = Len(hist) + /\ cut' = [Idle EXCEPT !.pc = "barrier", !.H = Len(hist)] + /\ UNCHANGED <> + +FixD == /\ cut.pc = "barrier" + /\ cut' = [cut EXCEPT !.pc = "copying", !.D = dirty] + /\ UNCHANGED <> + +CopyStart(c) == /\ cut.pc = "copying" /\ c \in cut.D \ (cut.copied \cup cut.copying \cup cut.saving) + /\ cut' = [cut EXCEPT !.copying = @ \cup {c}] + /\ UNCHANGED <> + +CopyFinish(c) == /\ c \in cut.copying + /\ cut' = IF cut.pc = "aborting" THEN [cut EXCEPT !.copying = @ \ {c}] + ELSE [cut EXCEPT !.copying = @ \ {c}, !.copied = @ \cup {c}, + !.buf[c] = IF side[c] # NONE THEN side[c] ELSE vis[c]] + /\ UNCHANGED <> + +CutCAS == /\ cut.pc = "copying" /\ cut.copied = cut.D /\ cut.copying = {} /\ cut.saving = {} + /\ head' = [lsn |-> cut.H, img |-> [c \in Chunks |-> IF c \in cut.D THEN cut.buf[c] ELSE head.img[c]]] + /\ dirty' = WrittenAfter(hist, cut.H) + /\ side' = NoSide /\ cut' = Idle /\ cuts' = cuts + 1 + /\ UNCHANGED <> + +\* abort: invalidate and release waiters at once; the dirty set is kept (no finishCut) +AbortStart == /\ cut.pc = "copying" /\ aborts < MaxAborts + /\ cut' = [cut EXCEPT !.pc = "aborting"] + /\ aborts' = aborts + 1 + /\ UNCHANGED <> +\* the join: delete the side store and end the window once no owner is in I/O (abortNoJoin: at once) +AbortFinish == /\ cut.pc = "aborting" + /\ Mut = "abortNoJoin" \/ (cut.saving = {} /\ cut.copying = {}) + /\ side' = NoSide /\ cut' = Idle + /\ UNCHANGED <> + +Crash == /\ crashes < MaxCrash + /\ LET h == SubSeq(hist, 1, synced) + img == [c \in Chunks |-> VA(h, c, Len(h))] + IN /\ hist' = h /\ vis' = img /\ ext' = img /\ dirty' = WrittenAfter(h, head.lsn) + /\ side' = NoSide /\ pend' = NoSide /\ cut' = Idle + /\ crashes' = crashes + 1 + /\ UNCHANGED <> + +Next == \/ \E c \in Chunks : Write(c) \/ SaveStart(c) \/ SaveFinish(c) \/ Flush(c) \/ CopyStart(c) \/ CopyFinish(c) + \/ Sync \/ CutBegin \/ FixD \/ CutCAS \/ AbortStart \/ AbortFinish \/ Crash +Spec == Init /\ [][Next]_vars + +----------------------------------------------------------------------------- +HeadImage == \A c \in Chunks : head.img[c] = ValueAt(c, head.lsn) +BufFrozen == \A c \in cut.copied : cut.buf[c] = ValueAt(c, cut.H) +SideFrozen == cut.pc = "copying" => \A c \in Chunks : side[c] # NONE => side[c] = ValueAt(c, cut.H) +SideOnlyInCut == cut.pc = "idle" => side = NoSide +ReadsNewest == \A c \in Chunks : vis[c] = ValueAt(c, Len(hist)) +HeadLeSynced == head.lsn <= synced /\ head.lsn <= Len(hist) +TypeOK == /\ cut.pc \in {"idle", "barrier", "copying", "aborting"} + /\ cut.copied \subseteq cut.D /\ cut.copying \subseteq cut.D /\ cut.saving \subseteq cut.D + /\ cut.copied \cap cut.copying = {} /\ cut.copying \cap cut.saving = {} + +\* Witnesses (expected VIOLATED = reachable): +W_AbortWhileSaving == ~(cut.pc = "aborting" /\ cut.saving # {}) +W_SaveUsedByCopier == ~(Open /\ \E c \in cut.copied : side[c] # NONE) +W_CASAfterAbort == ~(aborts >= 1 /\ cuts >= 1) +============================================================================= diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index f099fe7432..0e35840f6b 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -92,6 +92,8 @@ Two kinds of config are **expected to violate**: | `WALReplica.tla` | `cfg/S3_rep_*` | | | `CutCapture.tla` | `cfg/S4_*` | | | `CutPipeline.tla` | `cfg/S4b_*` | | +| `CutCOW.tla` | `cfg/S4c_*` | earlier copy-window abstraction | +| `CutCOW2.tla` | `cfg/S4r2_*` | selected native COW: save I/O and abort/drain | | `ControlPlane.tla` | `cfg/S5_*` | | | `ReplicationFailover.tla` | `cfg/S6_*` | design-level | | `RetentionGCTiming.tla` | `cfg/S9_*` | | @@ -107,9 +109,10 @@ length of TLC's shortest counterexample. | # | Spec | What it models | Key invariants | Results | Code (at `5c7c1a7f`) | |---|---|---|---|---|---| | S1 | `ChunkLifecycleFixed` (+ historical `ChunkLifecycle`) | Chunk HEAD, capture intents, snapshots (name record + attempt path), fork claims, tombstones, GC mark+sweep, and volume delete with a blockmaster deletion reservation. Actors: host, 0-2 snapshot callers, a fork, explicit DeleteSnapshot callers, 1-3 volume deleters with reruns, CreateVolume, GC. Filer semantics: conditional write on HEAD gen, exclusive create, conditional update/delete, uncancellable late create. | `GCSafe`, `SnapOnlyExplicitDelete`, `CommitClean`, `NoPublishAfterCommit`, `AckedChunksSurvive`, `NoIdReuse`, `GiveBackReleases`, temporal `HeadMonotone` | **Fixed design, all pass:** `Fix_P1` 51,375,412; `Fix_P2_aba` 46,245,848; `Fix_mix_small` 29,194,420; `Fix_token` 41,256; `Fix_create` 100. `Fix_mix` no violation in 138M states (20-min limit, incomplete). All `Fix_reach_*` reached. **Historical (pre-fix) counterexamples:** `Bug_P1_mark` (18-step), `Bug_P1_giveback` (23), `Bug_P1_data` (25: GC reclaims an acked snapshot's chunk), `Bug_P2_aba` (22), `Bug_token` (16), `Bug_create` (7). | `core/frontend/chunkstore/volume_delete.go:106` DeleteVolume (incarnation loop `:150`), `:269` markHeadDeleting, `:400` snapshotsBlock, `:314` revertHeadDeleting, `:347` commitHeadPurging; `catalog.go:824` CreateSnapshot (gate `:863`), `:943` claimName, `:771` createResolved, `:1058` DeleteSnapshot, `:1157` Fork, `:1337` claimForkParent, `:709` AbortSnapshot, `:1438` AbortFork; `retention.go:448` markDeleting, `:570` liveClaims; `gc.go:108` Collector.run; `chunk_remote.go:404` CASHead refuses delete states; `core/host/master/services.go:53` CreateVolume (holds workspaceMu `:64`), `:132` MarkVolumeDeleting; `core/lifecycle/deletion_reservations.go:111` Admit; `cmd/sw-block/chunk_volume_delete.go:32` `--request-id` | -| S2 | `WorkspaceTakeover` | A workspace volume moving from host A (epoch 1) to host B by a clean move (detach, revoke, ACK, assign) or a forced move (lease expiry). Blockmaster clock, host clock lag up to `Drift`, lossy and reordered messages, master restart, each host's cut as one remote call per step, takeover CAS, GC intent expiry. Code pinned at `5c293821`. | `NoDualServing`, `NoOldCasAfterTakeover`, `NoLateChunkReachable`, `GCSafe`, `NoLiveIntentExpired`, `CleanNoLoss`, `ForcedLossBounded`, `SeedMatchesTakeover`, temporal `HeadMonotone` | **Pass:** `W4_clean` 6,048,496; `W4_forced` 22,619,644; `W4_drift_heads` 56,242,345; `W4_clean_large` 590,137,925 (depth 70). `W4_forced_large`: no violation in 910,907,693 states (time limit, incomplete). **RED:** `RED_early_assign` NoDualServing (12-step); `RED_gc_ageonly` GCSafe (12); `RED_epoch` NoOldCasAfterTakeover (22-24); `RED_lsn` HeadMonotone (24). `RED_epoch_storeonly`/`_hostonly` pass (438,406 / 827,500): either epoch check alone suffices. `RED_lsn_storeonly` passes (28,389,024). **Findings:** `W4_drift` NoDualServing (13-step, fixed by #158, see below); `W4_forced_exact` ForcedLossExact (16-step, benign, open). | `core/frontend/chunkstore/chunk_remote.go:390` CASHead (epoch guard `:391`, gen/epoch/LSN guard `:409`, conditional update `:420`); `core/host/volume/workspace_lease.go:57` permits, `:70` Refresh (anchor `:73`, accept `:117`); `core/authority/workspace.go:95` RenewWorkspaceLease, `:222` BeginWorkspaceRevocation, `:237` AckWorkspaceRevocation, `:309` prepareWorkspaceMoveLocked (forced-move margin `:316-320`); `core/host/master/workspace_service.go:109` MoveWorkspace (HEAD read `:116`); `core/authority/authority.go:251` reloadFromStore (deadline reset `:261`); `core/frontend/durable/provider_chunk.go:289` PrepareRestore, `:309` ClaimChunkHead; `core/storage/chunk_restore.go:14`; `core/storage/chunk_layer.go:680` captureLocked (admit `:695`, lsn_behind `:800`, PutIntent `:853`, re-admit `:911`, supersededBy `:916`, CAS `:926`, settle `:972`); `core/frontend/chunkstore/gc.go:221` intent-expiry epoch rule | -| S3 | `WALRecovery`, `SmartWALRecovery`, `WALReplica` | Local WAL crash recovery. **walstore:** a ring of K pages, 1-2 page records, page cache written back in any order, Sync, flusher checkpoint, crash at any point with optionally one corrupted record page; recovery is a pure function of the durable image, with a selectable `Rule`. **smartwal:** in-place extent write plus a metadata ring slot, written back in any order, torn slots. **Replica:** RF=2 classification and promotion eligibility, BASE jump. | `I1` every synced write is recovered (or superseded) or recovery fails closed; `I2` a crash without corruption never reports corruption; `ReplayLastWriter`; `I0Prefix`; `I1Frontier`; `NoForgedReplay`; `I3` the promoted node has every acked write | **walstore, current main** (rule `rootLww`, reuse bounded by the persisted tail): `S3r_rootLww_I1_crashonly`/`_I2`/`_replay` pass (849,003); with an in-memory rebuild jump `S3r_rebuild_rootLww_*` pass (1,460,772). **Pre-fix code:** `S3_wal_current_I1_crashonly` I1 violated (synced write lost after a plain crash, #156); `S3v_code_lww_I1_crashonly` I1 violated (LWW replay alone is not enough, #159). **Open:** one corrupted synced record `S3v1_root_lww_I1` violated; Sync-persisted watermark `S3m_*` pass (1,320,984 / 3,955,400); `S3f_*` NoForgedReplay violated (confirmed on main, see Open items). **smartwal, current:** `S3_sw_current_I2` violated (false `wal_corrupt`), `_I1`, `_I1frontier` violated; proposal `S3_sw2_ordered_marker_repair_I2` pass (65,401), `_I1slot` pass (345,084). **Replica:** `S3_rep_c1_I2` pass (29,196), `S3_rep_c1_g2_I2` pass (12,712), `S3_rep_c1_g1_I3` pass (74,527); RED `S3_rep_c2_I2`, `S3_rep_c1_g2jump_I2`, `S3_rep_nogate_I3` violated. | `core/storage/recovery.go:43` recoverWAL (head==tail scan from its position `:63-73`, defensive scan `:74-90`, a range stops at its first bad entry `:141`, `:154`, hole warning `:437`), LWW replay `:193` via `core/storage/dirty_map.go:56` putAtIfNewer; `core/storage/wal_writer.go:41` durableTail, `:70` spaceUsed, `:443` tailPersisted; `core/storage/walstore.go:390` checkpoint release, `:933` Sync, `:1065` AdvanceFrontier, `:1167` ApplyEntry; `core/storage/smartwal/store.go:297` writeAt (extent `:304`, then ring `:313`), `:345` Sync; `smartwal/recovery.go:47` runRecoveryCounting (fail closed `:99-100`); `smartwal/ring.go:45` appendAt, `:69` scanSlots; `core/replication/volume.go:680` RebaseShipLSN | +| S2 | `WorkspaceTakeover` | A workspace volume moving from host A (epoch 1) to host B by a clean move (detach, revoke, ACK, assign) or a forced move (lease expiry). Blockmaster clock, host clock lag up to `Drift`, lossy and reordered messages, master restart, each host's cut as one remote call per step, takeover CAS, GC intent expiry. Code pinned at `5c293821`. | `NoDualServing`, `NoOldCasAfterTakeover`, `NoLateChunkReachable`, `GCSafe`, `NoLiveIntentExpired`, `CleanNoLoss`, `ForcedLossBounded`, `SeedMatchesTakeover`, temporal `HeadMonotone` | **Rerun with the durable lease horizon (#205, PR #209; model `7074febd`, 2026-11-18; TLC 2.19, 27 configurations, BFS).** **Pass:** `W4_clean` 18,378,104 (depth 63); `W4_forced` 33,690,232 (54); `W4_drift_heads` 82,446,907 (55); `W4_hz_clean` 25,464,387 (63) and `W4_hz_forced` 47,511,490 (54), with failing extension writes (landed or not), one restart, and the new `HostWithinHorizon`, `DiskCoversMemory`; `RED_hz_noclamp_safety` 25,511,482 (no clamp, split-brain invariants: passes, the restart rule covers grants). **Time limit, no violation (incomplete):** `W4_clean_large` 592,158,353 and `W4_forced_large` 592,791,914 (100 min each); `W4_both` 124,916,894 and `W4_hz_both` 132,152,744 (40 min each). **RED:** `RED_hz_noclamp` HostWithinHorizon (9-step: a renewal without the clamp grants validity past the durable horizon); `RED_early_assign` NoDualServing (13); `RED_gc_ageonly` GCSafe (12); `RED_epoch` NoOldCasAfterTakeover (23); `RED_lsn` HeadMonotone (25). `RED_epoch_storeonly`/`_hostonly` pass (213,607 / 322,067); `RED_lsn_storeonly` passes (33,690,232). **Witnesses (expected violated):** `W4_reach_clean`, `W4_reach_forced`, `W4_reach_bcut`, `W4_reach_restart`, `W4_hz_reach_ext` (an extension raises the horizon), `W4_hz_reach_landed` (a failed extension lands on disk), `W4_hz_reach_uncertain_restart`. **Findings (unchanged):** `W4_drift` NoDualServing (17-step: the model's forced move has no clock-skew margin; the code adds it, #158); `W4_forced_exact` ForcedLossExact (17-step, benign, open). Earlier results (before #205): `W4_clean` 6,048,496; `W4_forced` 22,619,644; `W4_drift_heads` 56,242,345; `W4_clean_large` 590,137,925 (depth 70); `W4_forced_large` no violation in 910,907,693 (incomplete). | `core/frontend/chunkstore/chunk_remote.go:390` CASHead (epoch guard `:391`, gen/epoch/LSN guard `:409`, conditional update `:420`); `core/host/volume/workspace_lease.go:57` permits, `:70` Refresh (anchor `:73`, accept `:117`); `core/authority/workspace.go:95` RenewWorkspaceLease, `:222` BeginWorkspaceRevocation, `:237` AckWorkspaceRevocation, `:309` prepareWorkspaceMoveLocked (forced-move margin `:316-320`); `core/host/master/workspace_service.go:109` MoveWorkspace (HEAD read `:116`); `core/authority/authority.go:251` reloadFromStore (deadline reset `:261`); `core/frontend/durable/provider_chunk.go:289` PrepareRestore, `:309` ClaimChunkHead; `core/storage/chunk_restore.go:14`; `core/storage/chunk_layer.go:680` captureLocked (admit `:695`, lsn_behind `:800`, PutIntent `:853`, re-admit `:911`, supersededBy `:916`, CAS `:926`, settle `:972`); `core/frontend/chunkstore/gc.go:221` intent-expiry epoch rule | +| S3 | `WALRecovery`, `SmartWALRecovery`, `WALReplica` | Local WAL crash recovery. **walstore:** a ring of K pages, 1-2 page records, page cache written back in any order, Sync, flusher checkpoint, crash at any point with optionally one corrupted record page; recovery is a pure function of the durable image, with a selectable `Rule`. **smartwal:** in-place extent write plus a metadata ring slot, written back in any order, torn slots. **Replica:** RF=2 classification and promotion eligibility, BASE jump. | `I1` every synced write is recovered (or superseded) or recovery fails closed; `I2` a crash without corruption never reports corruption; `ReplayLastWriter`; `I0Prefix`; `I1Frontier`; `NoForgedReplay`; `I3` the promoted node has every acked write | **walstore, current main** (rule `rootLww`, reuse bounded by the persisted tail): `S3r_rootLww_I1_crashonly`/`_I2`/`_replay` pass (849,003); with an in-memory rebuild jump `S3r_rebuild_rootLww_*` pass (1,460,772). **Pre-fix code:** `S3_wal_current_I1_crashonly` I1 violated (synced write lost after a plain crash, #156); `S3v_code_lww_I1_crashonly` I1 violated (LWW replay alone is not enough, #159). **Model findings, resolved in v3 code (see Open items 1-2):** one corrupted synced record `S3v1_root_lww_I1` violated; Sync-persisted watermark `S3m_*` pass (1,320,984 / 3,955,400; rerun on `d0e3895a`: unchanged); `S3f_*` NoForgedReplay violated (the model has no v3 nonce/cursor binding). **smartwal, current:** `S3_sw_current_I2` violated (false `wal_corrupt`), `_I1`, `_I1frontier` violated; proposal `S3_sw2_ordered_marker_repair_I2` pass (65,401), `_I1slot` pass (345,084). **Replica:** `S3_rep_c1_I2` pass (29,196), `S3_rep_c1_g2_I2` pass (12,712), `S3_rep_c1_g1_I3` pass (74,527); RED `S3_rep_c2_I2`, `S3_rep_c1_g2jump_I2`, `S3_rep_nogate_I3` violated. | `core/storage/recovery.go:43` recoverWAL (head==tail scan from its position `:63-73`, defensive scan `:74-90`, a range stops at its first bad entry `:141`, `:154`, hole warning `:437`), LWW replay `:193` via `core/storage/dirty_map.go:56` putAtIfNewer; `core/storage/wal_writer.go:41` durableTail, `:70` spaceUsed, `:443` tailPersisted; `core/storage/walstore.go:390` checkpoint release, `:933` Sync, `:1065` AdvanceFrontier, `:1167` ApplyEntry; `core/storage/smartwal/store.go:297` writeAt (extent `:304`, then ring `:313`), `:345` Sync; `smartwal/recovery.go:47` runRecoveryCounting (fail closed `:99-100`); `smartwal/ring.go:45` appendAt, `:69` scanSlots; `core/replication/volume.go:680` RebaseShipLSN | | S4 | `CutCapture`, `CutPipeline` | Which chunks the next cut must upload: the dirty bitmap vs a per-chunk last-write-LSN map, across RF=1 restart, crash mid-cut and RF=2 failover; dirty state persisted before a checkpoint passes WAL entries. Then the pipeline: precopy tagged with a per-chunk mutation generation, two-level manifest segments, root CAS, and `reconciling` after a restart without a bound bitmap. | `HeadImage` (HEAD is the exact image of the lineage at HEAD.lsn), `HeadLeDurable`, `SegConsistent` | **Pass:** `S4_rf1_bitmap` 47,670, `S4_rf1_lsnmap` 46,934, `S4_rf2_bitmapHash` 7,166,376, `S4_rf2_lsnmap` 8,226,004, `S4_rf2_lsnmap_base` 901,390; `S4b_design` 69,645, `S4b_design_big` 1,515,837. **RED:** `S4_rf2_bitmap` (failover without hashMode, 7-step), `S4_rf2_lsnmap_localCut` (6), `S4_rf1_*_noPersist` (7), `S4_rf1_bitmap_clearEarly` (8); `S4b_red_noGen`, `S4b_red_cutWhileRec` HeadImage; `S4b_red_segReuse` SegConsistent. | `core/storage/chunk_layer.go:356` BeforeCheckpointAdvance, `:299` OnExtentWrite, `:95` hashMode (set on attach `:184-230`), `:111` chunkMut, `:324` noteMutation, `:762` and `:1435` staged upload reused only if its generation is unchanged, `:702-704` cut refused while reconciling, `:877-881` PrepareManifest, `:1542` finishCut; `core/frontend/chunkstore/manifest.go:101` segment reused only if its chunk refs are unchanged | +| S4c | `CutCOW` | Copy-before-write in the cut window (proposed): today's barrier cut against COW, where the barrier only fixes the cut point H and the candidate set D, the first write to an uncopied candidate saves its at-H content to a local side store, a write to a chunk being copied waits, the copier reads the side store or the live chunk, and the side store is dropped at the CAS and on crash. A chunk copy is two steps (`CopyStart`, `CopyFinish`); read-visible content and the extent are separate; one crash. | `HeadImage`, `BufFrozen` (every uploaded chunk equals the image at H), `SideFrozen`, `SideOnlyInCut`, `ReadsNewest`, `HeadLeSynced` | `S4c_cow_safe` pass (34,342,214), `S4c_barrier_safe` pass (5,070,320), MaxLSN 6, 2 cuts. **RED**, each violates `BufFrozen`: `noChunkLock` (6,814), `noCopy` (6,617), and on the atomic-copy predecessor `copyAfter` (2,493), `earlyRelease` (1,067), `copyAtFlush` (2,191), `sideReuse` (272,908); those four carry over because every atomic-copy behaviour is a two-step behaviour with the steps adjacent. Witnesses reachable: `WriteInWindow` (508), `CASAfterWindowWrite`, `CrashDroppedSide` (atomic-copy runs). Atomic-copy COW at MaxLSN 8, 3 cuts: clean through depth 22 (605M states, time cap). | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `captureMu` (at `c5eb5819`) | | S5 | `ControlPlane` | Blockmaster authority store: one volume record `{epoch, holder, move journal}`, two retried move requests, durable Puts that succeed, fail, or land with the reply lost, and restarts. | `UniqueEpoch` (issued epochs strictly increase), `Idempotent` (one epoch per request id), `JournalComplete` | `S5_code` pass (298). **RED:** `S5_red_noUncertain` UniqueEpoch violated (5-step: a lost-reply Put, then a reservation from stale memory puts the old assignment back). `S5_red_noReserve` passes (the reservation step is not needed for these invariants). | `core/authority/authority.go:436` applyWithWorkspaceMove (uncertain refusal `:442-444`, Put `:564`, mark uncertain `:568`); `core/authority/workspace.go:309` prepareWorkspaceMoveLocked (expected line `:313`, resume a reserved entry `:324-333`, reserve max+1 `:344-355`), journal replay `:192-219`, persist and mark uncertain `:276-288` | | S6 | `ReplicationFailover` | RF=2: P ships to R, R acks what is durable, the client is acked when both are durable; promotion of R at a new epoch with an evidence gate; R refuses old-epoch shipping; cuts and snapshots cover only the replicated-durable frontier; an in-flight snapshot create from the old primary may still land after the failover. Design-level. | `AckedSurvive`, `HeadOnLineage`, `SnapOnLineage`, `NoStaleAck` | `S6_design` pass (52,897), `S6_design_big` (598,353). **RED:** `S6_red_localCut` HeadOnLineage; `S6_red_noFence` AckedSurvive. `S6_red_noEvidence` passes: with synchronous RF=2 acks the gate is redundant (it matters for quorum or async shipping, not modelled). | `core/transport/replica.go:362` replica rejects a stale-lineage ship entry; `core/replication/volume.go:680` RebaseShipLSN; takeover CAS as in S2 | | S9 | `RetentionGCTiming`, `RetentionGCMulti` | GC timing with an explicit clock: a copy operation with deadline D, marks of duration up to MD, deletion only after two marks at least Grace apart; then marks across two volumes with a fork and a snapshot delete. | `NoLiveDelete` | **Single op:** `S9_rule_G4` (G > D + MD) pass (10,798; `_big` 43,780); G = D passes (`S9_red_G2_noguard`, 11,953). **RED:** `S9_red_G1_noguard`, `S9_red_G1_D3` (G < D) NoLiveDelete violated. **Two volumes:** `S9b_G1_MD2`, `_G2_MD2`, `_G2_MD3`, `_G3_MD1` pass (5,743-9,079). | `core/frontend/chunkstore/gc.go:89` grace > operation deadline, `:280` mark-duration margin, `:306-318` two-mark rule, `:214-221` intent expiry; `catalog.go:896-905` intent deadline re-checked before publish; `gc_copy.go:143`, `:177` a deleting attempt stays a root until grace | @@ -158,32 +161,59 @@ are good candidates for regression tests. These are model-level results on the current design. They are not confirmed bugs in production paths unless stated. -1. **Corrupted synced WAL records need a format change (walstore).** If a - synced record's bytes are corrupted, the current recovery stops that range - at the bad record and continues; data after it in the range is dropped and - recovery reports success (a hole warning is logged since #155). An - in-record durable watermark alone is not enough (a corrupt *last* synced - record leaves no valid witness). The configs that pass (`S3m_*`) need Sync - to persist the watermark and any frontier jump out of band (for example in - the superblock) before acknowledging, plus recovery that decodes every - record position and replays by LSN. -2. **Forged replay (confirmed, open).** Recovery accepts any well-formed - record. A guest payload can contain bytes that decode as a valid WAL - record (CRC32 is not keyed). If a newer, shorter record overwrites only the - start of an old multi-block record, the scan continues into the old - payload and replays the forged record. Every rule modelled, including the - current one, violates `NoForgedReplay` (`S3f_*`). - - **Reproduced on main.** A 3-block batch write carries an encoded WAL - entry (LSN 999, LBA 7) in its guest data. After a newer 1-block record - wraps over the batch's start, recovery decodes the embedded entry: LBA 7 - reads the forged data, and the frontier jumps to 999. This also happens - after a clean close and reopen. - - **Effect.** It stays inside the guest's own volume: a write at a chosen - LBA, or a bogus LSN that moves the frontier. - - **Planned fix.** An interim fix persists the WAL head on Close and adds - a clean-shutdown flag. The full fix comes with the format change: bind - each record to its WAL incarnation and lap, for example with an epoch or - nonce in the header. +1. **Corrupted synced WAL records: resolved in v3 (code), with one residual + in mode C.** Before v3, if a synced record's bytes were corrupted, + recovery stopped that range at the bad record and continued; data after + it in the range was dropped and recovery reported success (a hole warning + is logged since #155). An in-record durable watermark alone is not enough + (a corrupt *last* synced record leaves no valid witness). The configs that + pass (`S3m_*`) need Sync to persist the watermark and any frontier jump out + of band before acknowledging, plus recovery that decodes every record + position and replays by LSN. Format v3 does this: the acknowledged + frontier W is published in the descriptor slot, and recovery checks the + scan against it. + - **Mode A (`WModeStrict`).** A corrupted acknowledged record fails + recovery closed (`wal_corrupt`), and a crash without corruption never + reports corruption: `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` + (its mode A cases), `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, + `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`. + - **Open residual, mode C (`WModeLagged`, the default).** The slot W lags + by one batch, so a corrupted *newest* acknowledged batch is truncated + silently (documented by the same test). An idle refresh or + `SetWMode(A)` closes the window + (`TestWALStoreV3RefreshAndSetWModeCloseTheWindow`). +2. **Forged replay: resolved in v3 (code); the model is not updated.** + Before v3, recovery accepted any well-formed record. A guest payload could + contain bytes that decode as a valid WAL record (CRC32 is not keyed). If a + newer, shorter record overwrote only the start of an old multi-block + record, the scan continued into the old payload and replayed the forged + record. Every rule modelled violates `NoForgedReplay` (`S3f_*`). + - **Reproduced on the pre-v3 format.** A 3-block batch write carried an + encoded WAL entry (LSN 999, LBA 7) in its guest data. After a newer + 1-block record wrapped over the batch's start, recovery decoded the + embedded entry: LBA 7 read the forged data, and the frontier jumped to + 999, also after a clean close and reopen. The effect stayed inside the + guest's own volume. + - **Fix (format v3).** Every record is bound to the volume's nonce and to + its exact logical cursor, lap included. The scanner checks the binding + before it trusts a length or count, and never searches past a record it + refused (`wal_io_v3.go`, `scanWALV3Accepted`). + - **Tests.** `TestWALStoreV3StaleLapBytesAtTheWrapAreNotReplayed` replays + the reproduction end to end on a mapped v3 WALStore, with the embedded + record bound to the volume's own nonce at its lap-1 cursor. After the + wrap the scan stops at it, recovery returns the newest real LSN, and LBA + 7 is never the forged data. With the lap dropped from the cursor check, + the scan admits the record and the test fails. Also + `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord` (foreign nonce, wrong + cursor in the same lap, old lap, bad CRC, bad footer) and + `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`. + - **Threat boundary.** The nonce lives in the descriptor slots, outside + the guest's address space. A guest that knew it could place a record at + a cursor it predicts; that is outside the boundary. + - **Open, model.** `WALRecovery.tla` has no nonce, cursor or lap binding, + so `S3f_*` still violate `NoForgedReplay`, and `S3v1_root_lww_I1` still + violates I1 (rerun on main `d0e3895a` with TLC 2.19: unchanged). This + stays open until the binding is modelled. 3. **SmartWAL.** - The extent write and the ring slot have no ordering barrier (`smartwal/store.go:304`, `:313`), and recovery fails closed on any CRC @@ -210,9 +240,65 @@ bugs in production paths unless stated. ## Parse check -All 12 specs parse and pass SANY's semantic check with `tla2tools.jar` v1.7.4 -(`java -cp tla2tools.jar tla2sany.SANY `), checked on 2026-11-16: +All 13 specs parse and pass SANY's semantic check with `tla2tools.jar` v1.7.4 +(`java -cp tla2tools.jar tla2sany.SANY `), checked on 2026-11-18: `ChunkLifecycle`, `ChunkLifecycleFixed`, `ControlPlane`, `CutCapture`, -`CutPipeline`, `ReplicationFailover`, `RetentionGCMulti`, `RetentionGCTiming`, +`CutCOW`, `CutPipeline`, `ReplicationFailover`, `RetentionGCMulti`, `RetentionGCTiming`, `SmartWALRecovery`, `WALRecovery`, `WALReplica`, `WorkspaceTakeover`. The state counts above come from earlier TLC runs of these specs; comment-only edits were made since. + +## Format-v3 activation correspondence + +The public selector now reaches the mapped impl3 paths in `walstore_v3.go`, `descriptor_v3.go`, `wal_io_v3.go` and `walstore_map_checkpoint_v3.go`. This is activation of the previously reviewed format contract, not a new abstract transition. Its canonical signed design is r17.4 (`e2a5304ef8fdc29f7e109883b8664a5c93d37a559e7b93e1d24964cb09cb7824`), with the composed external S3/BASE/install/map TLC receipts referenced by that design. The in-repository `WALRecovery.tla` remains an abstraction and is not a proof of every physical nonce/cursor/map/dual-slot rule. Pending external bounded runs remain pending; activation tests and source correspondence do not turn them into exhaustive proof. + +Native Go controls and the temporary frozen-v2 fixture disposition are listed in [the activation inventory](../design/format-v3-legacy-test-inventory.md). Old-codec tests are preserved, and both default and tagged migration/caller suites are validation gates. No model equation is changed by the selector wiring; a new counterexample still requires an amendment before affected integration. + +## Cut-window implementation correspondence + +The mapped v3 cut now uses `chunk_cut_cow.go`. `CutCOW2.tla` is the unchanged +S4c r2 model (SHA-256 `0b9bc89a9aed6c42dda6b1d23ba8515c406b1c2cb265cd83e78122238df6bcca`); +its header records its pre-implementation status at the time of the run. +The existing bounded verdict is not a new run: Chunks={a,b,c}, MaxLSN=6, +MaxCuts=2, MaxCrash=1, MaxAborts=1. `S4r2_cow_safe` checked seven invariants, +252,733,280 states, depth 36; barrier checked 27,790,736, depth 31. +`abortNoJoin` violates SideOnlyInCut at 31,835 states; `noChunkLock` and +`noCopy` violate BufFrozen at 6,982 and 7,484. The three witness configs +reach AbortWhileSaving (1,682), SaveUsedByCopier (28,250), CASAfterAbort +(614,292); their exit 12 is expected reachability, not a safe-config pass. + +SaveStart/SaveFinish correspond to the saving owner's validated read and +side-store publication. AbortStart is terminal invalidation/wakeup; AbortFinish +is reference drain followed by one cleanup. The model has one copier and +whole-chunk writes. Actual multi-writer/batch ownership, first-attach/Close, +Recover/reset snapshot recheck and saved-file readers are covered by the +native `TestCutCOWV3_*` caller controls, not claimed as model proofs. +The earlier thirteen-spec parse statement above predates this imported model; +no new independent TLC/parse or cloud run is claimed here. + + +### WAL pressure progress without guest Sync + +`WALReclaim.tla` models native local pressure persistence and checkpoint/reuse +progress. `InternalSync` is weakly fair and does not take the capture lock; +`GuestSync` has no fairness requirement. `REC_safe.cfg` and `REC_safe_big.cfg` +check I1/I2/I3, ring/pin safety, `AllWritten` and `NoStuckWaiter`. Removing internal +sync (`REC_red_noInternalSync.cfg`) violates liveness; removing the durable clamp +violates I2. The capture-lock mutant and permanently held pin also violate +liveness. The Go implementation bounds a permanent pin with retryable admission +expiry rather than assuming that it always releases. + +Run, from `docs/spec`, with the existing TLC tool: + +```sh +java -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config cfg/REC_safe.cfg WALReclaim +java -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config cfg/REC_red_noInternalSync.cfg WALReclaim +``` + +The authored LIGHT receipts report exhaustive safe searches at 2,700 and 25,550 +states, plus the expected mutant/witness failures. Source and configs are copied +from the sealed `claude05-walreclaim-tla-r0-20261119` artifact with line-ending +normalization only. Those are prior author runs, not a claim that this PR reran +TLC. This is an abstraction: physical fsync success, byte layout, crash recovery, +both-slot retirement, timing and multiple writers remain covered by their other +models and actual Go controls. Do not treat finite liveness checking as an +end-to-end wall-clock latency guarantee. Keep long model runs off tp04. diff --git a/seaweed-block/docs/spec/WALReclaim.tla b/seaweed-block/docs/spec/WALReclaim.tla new file mode 100644 index 0000000000..4895234f72 --- /dev/null +++ b/seaweed-block/docs/spec/WALReclaim.tla @@ -0,0 +1,119 @@ +----------------------------- MODULE WALReclaim ----------------------------- +(***************************************************************************) +(* Liveness of v3 WAL reclaim under write pressure (claude05, 2026-11-19). *) +(* Abstracts core/storage at seaweed-block main 39f11d6a: *) +(* head = WAL head LSN (records appended) *) +(* wack = durable WAL frontier; today advanced only by Sync *) +(* (walstore_v3.go:829) *) +(* flushed = records the flusher has written to the extent *) +(* ckpt = checkpoint = reuse floor, clamped to *) +(* min(flushed, wack, session pin) *) +(* (walstore_map_checkpoint_v3.go:57-62) *) +(* A writer may append only while head - ckpt < Cap (the hard watermark). *) +(* A blocked writer waits INSIDE the capture read lock *) +(* (walstore.go:829-832, admission at :850). A cut takes the capture *) +(* write lock; Go's RWMutex makes a pending writer block new readers. *) +(* *) +(* InternalOn: the fix under review (codex03 design r0) - under pressure *) +(* the store makes its own WAL durable (wack := head) with no guest Sync. *) +(* Mut: *) +(* "none" the design *) +(* "noClamp" checkpoint ignores wack (reclaims non-durable WAL) *) +(* "syncTakesCapture" the internal sync needs the capture read lock *) +(* (finding F2) *) +(* PinFair: a catch-up session pin is eventually released (finding F3). *) +(* The guest's Sync has NO fairness: a guest may never flush. *) +(***************************************************************************) +EXTENDS Naturals + +CONSTANTS Cap, MaxLSN, MaxCuts, MaxPins, InternalOn, Mut, PinOn, PinFair + +VARIABLES head, wack, flushed, ckpt, inside, cutPending, cuts, pin, pins, gsync + +vars == <> + +Min(a, b) == IF a < b THEN a ELSE b +NoPin == MaxLSN + 1 +Full == head - ckpt >= Cap + +Init == /\ head = 0 /\ wack = 0 /\ flushed = 0 /\ ckpt = 0 + /\ inside = FALSE /\ cutPending = FALSE /\ cuts = 0 /\ pin = NoPin /\ pins = 0 /\ gsync = FALSE + +\* A writer that finds the ring full enters the admission wait holding the +\* capture read lock; it can enter only if no cut is pending. +EnterWait == /\ head < MaxLSN /\ Full /\ ~inside /\ ~cutPending + /\ inside' = TRUE + /\ UNCHANGED <> + +\* Append: a fresh writer needs the read lock (blocked by a pending cut); a +\* writer already inside the wait holds it. +Append == /\ head < MaxLSN /\ ~Full /\ (inside \/ ~cutPending) + /\ head' = head + 1 /\ inside' = FALSE + /\ UNCHANGED <> + +\* Guest Flush/Sync: may happen or never (no fairness). +GuestSync == /\ wack < head + /\ wack' = head /\ gsync' = TRUE + /\ UNCHANGED <> + +\* The fix: internal sync on pressure. In the mutant it also needs the +\* capture read lock, so it is blocked while a cut is pending. +InternalSync == /\ InternalOn /\ wack < head /\ Full + /\ (Mut = "syncTakesCapture" => ~cutPending) + /\ wack' = head + /\ UNCHANGED <> + +Flush == /\ flushed < head + /\ flushed' = flushed + 1 + /\ UNCHANGED <> + +Target == IF Mut = "noClamp" THEN Min(flushed, pin) ELSE Min(Min(flushed, wack), pin) + +Checkpoint == /\ Target > ckpt + /\ ckpt' = Target + /\ UNCHANGED <> + +\* A cut requests the capture write lock; it completes once no reader holds +\* the lock (the waiting writer is a reader). +CutStart == /\ cuts < MaxCuts /\ ~cutPending + /\ cutPending' = TRUE /\ cuts' = cuts + 1 + /\ UNCHANGED <> +CutFinish == /\ cutPending /\ ~inside + /\ cutPending' = FALSE + /\ UNCHANGED <> + +\* An RF2 catch-up session pins the WAL at the current checkpoint, later +\* releases it. +PinSet == /\ PinOn /\ pin = NoPin /\ pins < MaxPins + /\ pin' = ckpt /\ pins' = pins + 1 + /\ UNCHANGED <> +PinRelease == /\ pin # NoPin + /\ pin' = NoPin + /\ UNCHANGED <> + +Next == \/ EnterWait \/ Append \/ GuestSync \/ InternalSync \/ Flush \/ Checkpoint + \/ CutStart \/ CutFinish \/ PinSet \/ PinRelease + +Fairness == /\ WF_vars(Append) /\ WF_vars(EnterWait) /\ WF_vars(Flush) /\ WF_vars(Checkpoint) + /\ WF_vars(InternalSync) /\ WF_vars(CutFinish) + /\ (PinFair => WF_vars(PinRelease)) + +Spec == Init /\ [][Next]_vars /\ Fairness + +\* ---- safety ---- +TypeOK == /\ head \in 0..MaxLSN /\ wack \in 0..MaxLSN /\ flushed \in 0..MaxLSN + /\ ckpt \in 0..MaxLSN /\ inside \in BOOLEAN /\ cutPending \in BOOLEAN + /\ cuts \in 0..MaxCuts /\ pin \in 0..(MaxLSN + 1) /\ pins \in 0..MaxPins /\ gsync \in BOOLEAN +I1 == wack <= head \* durable frontier never ahead of the head +I2 == ckpt <= wack \* never reclaim WAL that is not durable +I3 == ckpt <= flushed \* never reclaim a record not yet in the extent +IRing == head - ckpt <= Cap \* the ring never overflows +IPin == pin # NoPin => ckpt >= pin \* a pin never moves the floor backwards (sanity) + +\* ---- witness: all writes complete with NO guest Sync (must be violated = reachable when InternalOn) ---- +W_NeedsGuestSync == ~(head = MaxLSN /\ ~gsync) + +\* ---- liveness ---- +AllWritten == <>(head = MaxLSN) \* no write stalls forever +NoStuckWaiter == [](inside => <>(~inside)) \* a waiting writer is always admitted +============================================================================= diff --git a/seaweed-block/docs/spec/WALRecovery.tla b/seaweed-block/docs/spec/WALRecovery.tla index 4ec471be59..6d1ea01a7b 100644 --- a/seaweed-block/docs/spec/WALRecovery.tla +++ b/seaweed-block/docs/spec/WALRecovery.tla @@ -1,4 +1,12 @@ ----------------------------- MODULE WALRecovery ----------------------------- +(* V3 writer admission is physically LSN-strict, including batch end LSN. *) +(* This code guard does not change the legacy model below; the r16 composed *) +(* model correspondence and raw-recovery integrity policy are separate. *) +(* V3 map publication controls test merged C/checkpoint/W and volatile proof *) +(* tokens. Real Recover lifecycle wiring is separate from those dark tests. *) +(* V3 row 6: COW map digest domains and pages/root/directory persistence are *) +(* code-test obligations. The composed WALFormatR5 model abstracts validated *) +(* map dependencies; this legacy model is not a proof of the byte codec. *) (***************************************************************************) (* S3, walstore layout: a ring WAL of K pages in front of an extent. *) (* Records of 1 or 2 pages are appended to the page cache, written back to *) @@ -25,6 +33,14 @@ (* "watermarkFull" watermarkSB, and recovery decodes every page position *) (* instead of stopping a range at its first bad entry. *) (***************************************************************************) +(* Impl-3 row 2 adds a DARK byte codec in wal_entry_v3.go. Its 62/70-byte *) +(* framing, CRC32C, type/size bounds and allocation order are code-test *) +(* obligations, abstracted as record validity here, NOT proved by this model.*) +(* No production state/transition or model action changes in codec row 2. *) +(* Impl-3 row4 adds dark nonce/cursor-bound file writer and scan muscles. *) +(* They return evidence, not readiness: R intent epoch gc.go:221 - WaitLeaseExpiry \* forced move waits for the lease to expire authority/workspace.go:314-318 + WaitLeaseExpiry,\* forced move waits for the lease to expire authority/workspace.go:314-318 + Clamp, \* #205: a renewal's grant is clamped to the published horizon (FALSE: unsafe memory-only renewal) + ExtFail \* #205: an extension write may fail, landed or not (unknown outcome -> uncertain) Hosts == {"A", "B"} NoRec == [gen |-> 0, epoch |-> 0, holder |-> "-", st |-> "-", dgen |-> 0, lsn |-> 0, img |-> <<"-", 0>>] Head0 == [gen |-> 1, epoch |-> 1, holder |-> "A", st |-> "active", dgen |-> 0, lsn |-> 0, img |-> <<"A", 0>>] Other(h) == IF h = "A" THEN "B" ELSE "A" +Min(a, b) == IF a < b THEN a ELSE b +Max(a, b) == IF a > b THEN a ELSE b +\* #205 horizon geometry (workspace_lease_view.go): an extension writes H = trigger + TTL + HSlack; a renewal +\* triggers one when the published horizon is closer than TTL + Margin. Code: TTL/2 and TTL/4; at least one tick here. +HSlack == Max(1, TTL \div 2) +Margin == Max(1, TTL \div 4) VARIABLES now, lag, \* clocks head, stored, intents, \* remote store: HEAD, chunk bodies, intents msgs, \* in-flight messages - asg, lease, ack, journal, maxEpoch, \* blockmaster durable state (authority store) - deadline, restarts, \* blockmaster in-memory lease deadline (reset on restart) + asg, lease, ack, journal, maxEpoch, \* blockmaster published state (= the authority store unless uncertain) + deadline, restarts, \* blockmaster in-memory lease deadline (the latest grant; reset on restart) + dhz, uncertain, extReq, \* #205: horizon on disk; a write outcome is unknown; pending extension trigger time (-1: none) mv, \* operator's move in progress host, \* per-host state cut, \* per-host chunk-layer cut in progress @@ -49,7 +69,7 @@ VARIABLES hist \* history (never read by the protocol) vars == <> + deadline, restarts, dhz, uncertain, extReq, mv, host, cut, bpc, bobs, hist>> HNow(h) == now - lag[h] @@ -73,11 +93,13 @@ Init == /\ head = Head0 /\ stored = {<<"A", 0>>} /\ intents = {} /\ msgs = {} /\ asg = [holder |-> "A", epoch |-> 1] - /\ lease = [holder |-> "A", epoch |-> 1, exp |-> TTL, revoking |-> FALSE, none |-> FALSE] + \* A's first grant: horizon now + TTL + HSlack on disk, grant (deadline, A's validity) now + TTL + /\ lease = [holder |-> "A", epoch |-> 1, exp |-> TTL + HSlack, revoking |-> FALSE, none |-> FALSE] /\ ack = [gen |-> 0, holder |-> "-", epoch |-> 0] /\ journal = [kind |-> "-", gen |-> 0, lsn |-> 0, newEpoch |-> 0] /\ maxEpoch = 1 /\ deadline = TTL /\ restarts = 0 + /\ dhz = TTL + HSlack /\ uncertain = FALSE /\ extReq = -1 /\ mv = [st |-> "none", kind |-> "-", h |-> NoRec] /\ host = [h \in Hosts |-> IF h = "A" THEN [epoch |-> 1, until |-> TTL, fenced |-> FALSE, revoked |-> FALSE, stopIO |-> FALSE, @@ -94,25 +116,25 @@ Init == (* clocks and the VM *) Tick == /\ now < MaxT /\ now' = now + 1 - /\ UNCHANGED <> + /\ UNCHANGED <> \* the master clock advances, A's does not (bounded drift) SlowTick == /\ now < MaxT /\ lag["A"] < Drift /\ now' = now + 1 /\ lag' = [lag EXCEPT !["A"] = @ + 1] - /\ UNCHANGED <> + /\ UNCHANGED <> \* a VM write accepted by a serving host (WAL LSN + 1) VMWrite(h) == /\ Serving(h) /\ host[h].lsn < MaxLSN /\ host' = [host EXCEPT ![h].lsn = @ + 1] /\ hist' = [hist EXCEPT !.acked[h] = host[h].lsn + 1, !.bServeT = IF h = "B" /\ hist.bServeT < 0 THEN now ELSE hist.bServeT] - /\ UNCHANGED <> + /\ UNCHANGED <> LoseMsg == \E m \in msgs : /\ msgs' = msgs \ {m} /\ host' = IF m.t = "renew" \/ m.t = "lease" THEN [host EXCEPT ![m.h].renewing = FALSE] ELSE host - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- -(* workspace lease (core/host/volume/workspace_lease.go, core/authority/workspace.go) *) +(* workspace lease (core/host/volume/workspace_lease.go, core/authority/workspace_lease_view.go) *) \* Refresh: validity anchored to the request START (workspace_lease.go:68-127) SendRenew(h) == @@ -122,23 +144,51 @@ SendRenew(h) == /\ msgs' = msgs ELSE /\ host' = [host EXCEPT ![h].renewing = TRUE] /\ msgs' = msgs \cup {[t |-> "renew", h |-> h, e |-> host[h].epoch, s |-> HNow(h)]} - /\ UNCHANGED <> + /\ UNCHANGED <> -\* Publisher.RenewWorkspaceLease (authority/workspace.go:73-106), reply validFor = exp - now (workspace_service.go:41-52) +\* Publisher.RenewWorkspaceLease (#205, workspace_lease_view.go), reply validFor = expiry - now (workspace_service.go leaseFact). +\* - Revoking: the drain reply, expiry min(horizon, deadline); never extends (allowed while uncertain, as before). +\* - No lease yet: the FIRST grant, a synchronous durable write (refused while uncertain): horizon now + TTL + HSlack. +\* - Live lease: memory only. grant = min(now + TTL, horizon) (Clamp); refused while uncertain or when it leaves no +\* validity; deadline = max(deadline, grant); triggers an extension when the horizon is closer than TTL + Margin. MasterRenew == \E m \in msgs : /\ m.t = "renew" /\ LET okLine == asg.holder = m.h /\ asg.epoch = m.e - live == lease.none \/ (now < lease.exp /\ now < deadline) + Reply(ok, v, rv) == [t |-> "lease", h |-> m.h, s |-> m.s, ok |-> ok, valid |-> v, revoking |-> rv] + grant == IF Clamp THEN Min(now + TTL, lease.exp) ELSE now + TTL IN IF okLine /\ ~lease.none /\ lease.revoking - THEN /\ msgs' = (msgs \ {m}) \cup {[t |-> "lease", h |-> m.h, s |-> m.s, ok |-> TRUE, valid |-> lease.exp - now, revoking |-> TRUE]} - /\ UNCHANGED <> - ELSE IF okLine /\ live - THEN /\ lease' = [holder |-> m.h, epoch |-> m.e, exp |-> now + TTL, revoking |-> FALSE, none |-> FALSE] + THEN /\ msgs' = (msgs \ {m}) \cup {Reply(TRUE, Min(lease.exp, deadline) - now, TRUE)} + /\ UNCHANGED <> + ELSE IF okLine /\ lease.none /\ ~uncertain + THEN /\ lease' = [holder |-> m.h, epoch |-> m.e, exp |-> now + TTL + HSlack, revoking |-> FALSE, none |-> FALSE] + /\ dhz' = now + TTL + HSlack /\ deadline' = now + TTL - /\ msgs' = (msgs \ {m}) \cup {[t |-> "lease", h |-> m.h, s |-> m.s, ok |-> TRUE, valid |-> TTL, revoking |-> FALSE]} - ELSE /\ msgs' = (msgs \ {m}) \cup {[t |-> "lease", h |-> m.h, s |-> m.s, ok |-> FALSE, valid |-> 0, revoking |-> FALSE]} - /\ UNCHANGED <> - /\ UNCHANGED <> + /\ msgs' = (msgs \ {m}) \cup {Reply(TRUE, TTL, FALSE)} + /\ extReq' = extReq + ELSE IF okLine /\ ~lease.none /\ now < lease.exp /\ now < deadline /\ ~uncertain /\ grant > now + THEN /\ deadline' = Max(deadline, grant) + /\ extReq' = IF lease.exp < now + TTL + Margin /\ extReq < 0 THEN now ELSE extReq + /\ msgs' = (msgs \ {m}) \cup {Reply(TRUE, grant - now, FALSE)} + /\ UNCHANGED <> + ELSE /\ msgs' = (msgs \ {m}) \cup {Reply(FALSE, 0, FALSE)} + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* the extender (#205, workspace_lease_view.go extendWorkspaceLease): an ordinary writer serialized with every other +\* write; it rechecks the lease and writes H = trigger + TTL + HSlack. Success publishes H. A failed write latches +\* uncertain whether or not it landed on disk (ExtFail). A failed recheck is a known no-write. +MasterExtend == + /\ extReq >= 0 + /\ LET H == extReq + TTL + HSlack + ok == /\ ~lease.none /\ ~lease.revoking /\ ~uncertain + /\ lease.holder = asg.holder /\ lease.epoch = asg.epoch /\ H > lease.exp + IN IF ok + THEN \/ /\ lease' = [lease EXCEPT !.exp = H] /\ dhz' = H /\ uncertain' = uncertain + \/ /\ ExtFail /\ lease' = lease /\ dhz' = dhz /\ uncertain' = TRUE \* failed, nothing landed + \/ /\ ExtFail /\ lease' = lease /\ dhz' = H /\ uncertain' = TRUE \* landed, reply lost + ELSE UNCHANGED <> + /\ extReq' = -1 + /\ UNCHANGED <> \* the host applies a reply (workspace_lease.go:88-127): the OLD deadline is checked first HostLease == \E m \in msgs : @@ -153,7 +203,7 @@ HostLease == \E m \in msgs : ![h].until = IF m.ok /\ ~fence /\ ~host[h].fenced THEN m.s + m.valid ELSE @] /\ msgs' = msgs \ {m} /\ hist' = [hist EXCEPT !.aStopT = IF m.h = "A" /\ hist.aStopT < 0 /\ m.revoking THEN now ELSE hist.aStopT] - /\ UNCHANGED <> + /\ UNCHANGED <> \* drain then clean ACK with the last committed HEAD gen, only while the lease is valid (:129-160) SendAck == @@ -161,35 +211,39 @@ SendAck == /\ host["A"].until > HNow("A") /\ host["A"].lh.gen # 0 /\ ~\E m \in msgs : m.t = "ack" /\ msgs' = msgs \cup {[t |-> "ack", h |-> "A", e |-> host["A"].epoch, gen |-> host["A"].lh.gen]} - /\ UNCHANGED <> + /\ UNCHANGED <> -\* Publisher.AckWorkspaceRevocation (authority/workspace.go:215-235) +\* Publisher.AckWorkspaceRevocation (authority/workspace.go:215-235): a durable write (refused while uncertain) MasterAck == \E m \in msgs : /\ m.t = "ack" /\ msgs' = msgs \ {m} /\ IF asg.holder = m.h /\ asg.epoch = m.e /\ m.gen # 0 /\ ~lease.none /\ lease.revoking - /\ now < lease.exp /\ now < deadline + /\ now < lease.exp /\ now < deadline /\ ~uncertain THEN ack' = [gen |-> m.gen, holder |-> m.h, epoch |-> m.e] ELSE ack' = ack - /\ UNCHANGED <> + /\ UNCHANGED <> -\* operator: BeginWorkspaceRevocation (authority/workspace.go:200-213) +\* operator: BeginWorkspaceRevocation (authority/workspace.go:200-213): a durable write (refused while uncertain) Revoke == /\ "clean" \in Kinds /\ ~lease.none /\ ~lease.revoking /\ lease.holder = asg.holder /\ asg.holder = "A" + /\ ~uncertain /\ lease' = [lease EXCEPT !.revoking = TRUE] - /\ UNCHANGED <> + /\ UNCHANGED <> \* operator / orchestrator: stop guest I/O on A before the final cut StopGuest == /\ "clean" \in Kinds /\ ~host["A"].stopIO /\ host' = [host EXCEPT !["A"].stopIO = TRUE] /\ hist' = [hist EXCEPT !.aStopT = IF hist.aStopT < 0 THEN now ELSE hist.aStopT] - /\ UNCHANGED <> + /\ UNCHANGED <> -\* blockmaster restart: durable state kept; the in-memory deadline conservatively -\* covers a full TTL again (authority.go:256-261) +\* blockmaster restart: the published state is reloaded from disk (so the published horizon becomes dhz), the +\* in-memory deadline conservatively covers a full TTL again (authority.go reloadFromStore), uncertainty and any +\* pending extension are gone MasterRestart == /\ restarts < MaxRestarts /\ restarts' = restarts + 1 /\ deadline' = now + TTL - /\ UNCHANGED <> + /\ lease' = IF lease.none THEN lease ELSE [lease EXCEPT !.exp = dhz] + /\ uncertain' = FALSE /\ extReq' = -1 + /\ UNCHANGED <> ----------------------------------------------------------------------------- (* the move (workspace_service.go:100-145, authority/workspace.go:157-198, 287-335) *) @@ -197,15 +251,17 @@ MasterRestart == /\ restarts < MaxRestarts \* the HEAD is read before the publisher lock (workspace_service.go:104-109) MoveRead == /\ mv.st = "none" /\ asg.holder = "A" /\ \E k \in Kinds : mv' = [st |-> "read", kind |-> k, h |-> head] - /\ UNCHANGED <> + /\ UNCHANGED <> +\* a durable write (refused while uncertain, authority.go apply); the forced barrier reads the published horizon +\* and the in-memory deadline MovePrepare == /\ mv.st = "read" /\ LET q == mv.h headOK == q.gen # 0 /\ q.epoch = asg.epoch /\ q.holder = asg.holder cleanOK == q.st = "detached" /\ ~lease.none /\ lease.revoking /\ ack.gen = q.gen /\ ack.epoch = asg.epoch forcedOK == ~WaitLeaseExpiry \/ (now >= lease.exp /\ now >= deadline) - ok == headOK /\ ~lease.none /\ IF mv.kind = "clean" THEN cleanOK ELSE forcedOK + ok == headOK /\ ~lease.none /\ ~uncertain /\ IF mv.kind = "clean" THEN cleanOK ELSE forcedOK IN IF ok THEN /\ maxEpoch' = maxEpoch + 1 /\ journal' = [kind |-> mv.kind, gen |-> q.gen, lsn |-> q.lsn, newEpoch |-> maxEpoch + 1] @@ -216,7 +272,7 @@ MovePrepare == /\ mv' = [mv EXCEPT !.st = "done"] ELSE /\ mv' = [st |-> "none", kind |-> "-", h |-> NoRec] \* refused; may be retried /\ UNCHANGED <> - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- (* B: VOLUME hook -> attach -> seed -> takeover CAS -> serve @@ -229,23 +285,23 @@ BAssign == \E m \in msgs : /\ msgs' = msgs \ {m} /\ host' = [host EXCEPT !["B"].epoch = m.e] /\ bpc' = "hook" - /\ UNCHANGED <> + /\ UNCHANGED <> BHook == /\ bpc = "hook" /\ bpc' = "attach" /\ Step("hook") \* EnsureVolume / attach check (provider_chunk.go:240-247) - /\ UNCHANGED <> + /\ UNCHANGED <> BAttach == /\ bpc = "attach" \* ClaimChunkHead: GetHead (chunk_restore.go:30-36) /\ IF head.epoch > host["B"].epoch THEN /\ bpc' = "failed" /\ bobs' = bobs /\ hist' = hist ELSE /\ bpc' = "seed" /\ bobs' = head /\ Step("attach") - /\ UNCHANGED <> + /\ UNCHANGED <> BSeed == /\ bpc = "seed" \* PrepareRestore -> SeedChunkFrontier (provider_chunk.go:286-307) /\ LET L == IF SeedFromObserved THEN bobs.lsn ELSE journal.lsn IN /\ host' = [host EXCEPT !["B"].lsn = L] /\ hist' = [hist EXCEPT !.steps = Append(hist.steps, "seed"), !.bSeed = L] /\ bpc' = "claim" - /\ UNCHANGED <> + /\ UNCHANGED <> BClaim == /\ bpc = "claim" \* the takeover CAS (chunk_restore.go:55-79) /\ LET next == [bobs EXCEPT !.gen = bobs.gen + 1, !.epoch = host["B"].epoch, !.holder = "B", @@ -257,7 +313,7 @@ BClaim == /\ bpc = "claim" \* the takeover /\ hist' = [hist EXCEPT !.steps = Append(hist.steps, "claim"), !.takeover = TRUE, !.bFirst = next] ELSE /\ bpc' = "attach" \* not installed: the attach is retried /\ UNCHANGED <> - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- (* the chunk layer's cut on host h (chunk_layer.go:680-988) *) @@ -271,20 +327,20 @@ CutStart(h, det) == /\ LayerLsnCheck => host[h].lsn >= host[h].lh.lsn \* lsn_behind (:800) /\ cut' = [cut EXCEPT ![h] = [pc |-> "intent", n |-> @.n, base |-> host[h].lh, lsn |-> host[h].lsn, img |-> <>, detach |-> det]] - /\ UNCHANGED <> + /\ UNCHANGED <> CutIntent(h) == \* PutIntent before any upload (:853, :1489) /\ cut[h].pc = "intent" /\ intents' = intents \cup {[own |-> h, n |-> cut[h].n + 1, epoch |-> host[h].epoch, key |-> cut[h].img, created |-> now]} /\ cut' = [cut EXCEPT ![h].pc = "upload"] - /\ UNCHANGED <> + /\ UNCHANGED <> CutUpload(h) == /\ cut[h].pc = "upload" /\ stored' = stored \cup {cut[h].img} /\ hist' = [hist EXCEPT !.late = IF h = "A" /\ hist.takeover THEN @ \cup {cut[h].img} ELSE @] /\ cut' = [cut EXCEPT ![h].pc = "admit"] - /\ UNCHANGED <> + /\ UNCHANGED <> DropOwn(h) == {i \in intents : ~(i.own = h /\ i.n = cut[h].n + 1)} @@ -293,7 +349,7 @@ CutAdmit(h) == \* admis /\ IF Permits(h) /\ (~HostFence \/ ~SupersededBy(h, host[h].lh)) THEN /\ cut' = [cut EXCEPT ![h].pc = "cas"] /\ intents' = intents ELSE /\ cut' = [cut EXCEPT ![h].pc = "idle", ![h].n = @ + 1] /\ intents' = DropOwn(h) - /\ UNCHANGED <> + /\ UNCHANGED <> CutCAS(h) == \* CASHead (:926), then settle by re-read (:957-987) /\ cut[h].pc = "cas" @@ -312,13 +368,13 @@ CutCAS(h) == \* CASHe ELSE [host EXCEPT ![h].lh = head] /\ hist' = hist /\ cut' = [cut EXCEPT ![h].pc = "drop"] - /\ UNCHANGED <> + /\ UNCHANGED <> CutDrop(h) == \* DeleteIntent after settling (:1378-1421) /\ cut[h].pc = "drop" /\ intents' = DropOwn(h) /\ cut' = [cut EXCEPT ![h].pc = "idle", ![h].n = @ + 1] - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- (* GC (core/frontend/chunkstore/gc.go:108-300) *) @@ -330,20 +386,20 @@ GCExpire == \E i \in intents : /\ GCEpochRule => (maxEpoch > i.epoch /\ head.epoch > i.epoch /\ head.epoch <= maxEpoch) /\ intents' = intents \ {i} /\ hist' = [hist EXCEPT !.badExpire = @ \/ (i.epoch = head.epoch /\ i.own = head.holder)] - /\ UNCHANGED <> + /\ UNCHANGED <> \* mark + sweep, atomic: roots are HEAD and live intents (grace abstracted, as in ChunkLifecycle) GCCollect == LET roots == {head.img} \cup {i.key : i \in intents} IN /\ stored \ roots # {} /\ stored' = stored \cap roots - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- Next == \/ Tick \/ SlowTick \/ LoseMsg \/ \E h \in Hosts : VMWrite(h) \/ SendRenew(h) \/ CutStart(h, FALSE) \/ CutStart(h, TRUE) \/ CutIntent(h) \/ CutUpload(h) \/ CutAdmit(h) \/ CutCAS(h) \/ CutDrop(h) - \/ MasterRenew \/ HostLease \/ SendAck \/ MasterAck \/ Revoke \/ StopGuest \/ MasterRestart + \/ MasterRenew \/ MasterExtend \/ HostLease \/ SendAck \/ MasterAck \/ Revoke \/ StopGuest \/ MasterRestart \/ MoveRead \/ MovePrepare \/ BAssign \/ BHook \/ BAttach \/ BSeed \/ BClaim \/ GCExpire \/ GCCollect @@ -388,11 +444,21 @@ SeedMatchesTakeover == hist.bFirst # NoRec => hist.bSeed = hist.bFirst.lsn \* HEAD epoch and remote_lsn never decrease HeadMonotone == [][head'.epoch >= head.epoch /\ head'.lsn >= head.lsn]_vars +\* #205 (S1, scoped to the active lease): the current holder's validity never exceeds the published horizon, and the +\* published horizon never exceeds the disk; they are equal unless a write outcome is unknown +HostWithinHorizon == ~lease.none => + \A h \in Hosts : (h = lease.holder /\ host[h].epoch = lease.epoch) => host[h].until <= lease.exp +DiskCoversMemory == ~lease.none => (lease.exp <= dhz /\ (~uncertain => lease.exp = dhz)) + \* reachability witnesses (each is EXPECTED to be violated) W_NoCleanServe == ~(journal.kind = "clean" /\ Serving("B") /\ hist.acked["A"] > 0) W_NoForcedServe == ~(journal.kind = "forced" /\ Serving("B") /\ hist.acked["A"] > 0) W_NoBCut == ~(head.holder = "B" /\ hist.bFirst # NoRec /\ head.gen > hist.bFirst.gen) W_NoRestartMove == ~(restarts > 0 /\ hist.takeover) +W_NoExtension == ~(~lease.none /\ lease.epoch = 1 /\ lease.exp > TTL + HSlack) \* an extension raised A's horizon +W_NoExtLanded == ~(~lease.none /\ dhz > lease.exp) \* a failed extension landed on disk +W_NoUncertain == ~uncertain TypeOK == /\ now \in 0..MaxT /\ head.gen \in Nat /\ stored \subseteq (Hosts \X (0..MaxCuts)) + /\ uncertain \in BOOLEAN /\ extReq \in -1..MaxT ============================================================================= diff --git a/seaweed-block/docs/spec/cfg/REC_red_noClamp.cfg b/seaweed-block/docs/spec/cfg/REC_red_noClamp.cfg new file mode 100644 index 0000000000..4008158c3f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/REC_red_noClamp.cfg @@ -0,0 +1,12 @@ +\* REC_red_noClamp +SPECIFICATION Spec +CONSTANTS + Cap = 2 + MaxLSN = 5 + MaxCuts = 2 + MaxPins = 1 + InternalOn = TRUE + Mut = "noClamp" + PinOn = TRUE + PinFair = TRUE +INVARIANT TypeOK I1 I2 I3 IRing diff --git a/seaweed-block/docs/spec/cfg/REC_red_noInternalSync.cfg b/seaweed-block/docs/spec/cfg/REC_red_noInternalSync.cfg new file mode 100644 index 0000000000..26289b082d --- /dev/null +++ b/seaweed-block/docs/spec/cfg/REC_red_noInternalSync.cfg @@ -0,0 +1,13 @@ +\* REC_red_noInternalSync +SPECIFICATION Spec +CONSTANTS + Cap = 2 + MaxLSN = 5 + MaxCuts = 2 + MaxPins = 1 + InternalOn = FALSE + Mut = "none" + PinOn = TRUE + PinFair = TRUE +INVARIANT TypeOK I1 I2 I3 IRing +PROPERTY AllWritten diff --git a/seaweed-block/docs/spec/cfg/REC_red_pinForever.cfg b/seaweed-block/docs/spec/cfg/REC_red_pinForever.cfg new file mode 100644 index 0000000000..7875a2f210 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/REC_red_pinForever.cfg @@ -0,0 +1,13 @@ +\* REC_red_pinForever +SPECIFICATION Spec +CONSTANTS + Cap = 2 + MaxLSN = 5 + MaxCuts = 2 + MaxPins = 1 + InternalOn = TRUE + Mut = "none" + PinOn = TRUE + PinFair = FALSE +INVARIANT TypeOK I1 I2 I3 IRing +PROPERTY AllWritten diff --git a/seaweed-block/docs/spec/cfg/REC_red_syncTakesCapture.cfg b/seaweed-block/docs/spec/cfg/REC_red_syncTakesCapture.cfg new file mode 100644 index 0000000000..937f32efb1 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/REC_red_syncTakesCapture.cfg @@ -0,0 +1,13 @@ +\* REC_red_syncTakesCapture +SPECIFICATION Spec +CONSTANTS + Cap = 2 + MaxLSN = 5 + MaxCuts = 2 + MaxPins = 1 + InternalOn = TRUE + Mut = "syncTakesCapture" + PinOn = TRUE + PinFair = TRUE +INVARIANT TypeOK I1 I2 I3 IRing +PROPERTY AllWritten diff --git a/seaweed-block/docs/spec/cfg/REC_red_syncTakesCapture_big.cfg b/seaweed-block/docs/spec/cfg/REC_red_syncTakesCapture_big.cfg new file mode 100644 index 0000000000..e8d28ae290 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/REC_red_syncTakesCapture_big.cfg @@ -0,0 +1,13 @@ +\* REC_red_syncTakesCapture_big +SPECIFICATION Spec +CONSTANTS + Cap = 3 + MaxLSN = 9 + MaxCuts = 3 + MaxPins = 2 + InternalOn = TRUE + Mut = "syncTakesCapture" + PinOn = TRUE + PinFair = TRUE +INVARIANT TypeOK I1 I2 I3 IRing +PROPERTY AllWritten diff --git a/seaweed-block/docs/spec/cfg/REC_safe.cfg b/seaweed-block/docs/spec/cfg/REC_safe.cfg new file mode 100644 index 0000000000..a5b4fbb84e --- /dev/null +++ b/seaweed-block/docs/spec/cfg/REC_safe.cfg @@ -0,0 +1,13 @@ +\* REC_safe +SPECIFICATION Spec +CONSTANTS + Cap = 2 + MaxLSN = 5 + MaxCuts = 2 + MaxPins = 1 + InternalOn = TRUE + Mut = "none" + PinOn = TRUE + PinFair = TRUE +INVARIANT TypeOK I1 I2 I3 IRing IPin +PROPERTY AllWritten NoStuckWaiter diff --git a/seaweed-block/docs/spec/cfg/REC_safe_big.cfg b/seaweed-block/docs/spec/cfg/REC_safe_big.cfg new file mode 100644 index 0000000000..ea144fc132 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/REC_safe_big.cfg @@ -0,0 +1,13 @@ +\* REC_safe_big +SPECIFICATION Spec +CONSTANTS + Cap = 3 + MaxLSN = 9 + MaxCuts = 3 + MaxPins = 2 + InternalOn = TRUE + Mut = "none" + PinOn = TRUE + PinFair = TRUE +INVARIANT TypeOK I1 I2 I3 IRing IPin +PROPERTY AllWritten NoStuckWaiter diff --git a/seaweed-block/docs/spec/cfg/REC_wit_noGuestSync.cfg b/seaweed-block/docs/spec/cfg/REC_wit_noGuestSync.cfg new file mode 100644 index 0000000000..7d99e37c27 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/REC_wit_noGuestSync.cfg @@ -0,0 +1,12 @@ +\* REC_wit_noGuestSync +SPECIFICATION Spec +CONSTANTS + Cap = 2 + MaxLSN = 5 + MaxCuts = 2 + MaxPins = 1 + InternalOn = TRUE + Mut = "none" + PinOn = TRUE + PinFair = TRUE +INVARIANT W_NeedsGuestSync diff --git a/seaweed-block/docs/spec/cfg/RED_early_assign.cfg b/seaweed-block/docs/spec/cfg/RED_early_assign.cfg index c2789b527e..9ca9fc16d6 100644 --- a/seaweed-block/docs/spec/cfg/RED_early_assign.cfg +++ b/seaweed-block/docs/spec/cfg/RED_early_assign.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = FALSE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing diff --git a/seaweed-block/docs/spec/cfg/RED_epoch.cfg b/seaweed-block/docs/spec/cfg/RED_epoch.cfg index c4947609dd..55b77b11b9 100644 --- a/seaweed-block/docs/spec/cfg/RED_epoch.cfg +++ b/seaweed-block/docs/spec/cfg/RED_epoch.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoOldCasAfterTakeover diff --git a/seaweed-block/docs/spec/cfg/RED_epoch_hostonly.cfg b/seaweed-block/docs/spec/cfg/RED_epoch_hostonly.cfg index 4884ce7a5f..627215a43f 100644 --- a/seaweed-block/docs/spec/cfg/RED_epoch_hostonly.cfg +++ b/seaweed-block/docs/spec/cfg/RED_epoch_hostonly.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoOldCasAfterTakeover NoLateChunkReachable diff --git a/seaweed-block/docs/spec/cfg/RED_epoch_storeonly.cfg b/seaweed-block/docs/spec/cfg/RED_epoch_storeonly.cfg index 163650f5d2..16cf2005e8 100644 --- a/seaweed-block/docs/spec/cfg/RED_epoch_storeonly.cfg +++ b/seaweed-block/docs/spec/cfg/RED_epoch_storeonly.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoOldCasAfterTakeover NoLateChunkReachable diff --git a/seaweed-block/docs/spec/cfg/RED_gc_ageonly.cfg b/seaweed-block/docs/spec/cfg/RED_gc_ageonly.cfg index 7181fb20b7..7a33af37c6 100644 --- a/seaweed-block/docs/spec/cfg/RED_gc_ageonly.cfg +++ b/seaweed-block/docs/spec/cfg/RED_gc_ageonly.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = FALSE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK GCSafe diff --git a/seaweed-block/docs/spec/cfg/RED_hz_noclamp.cfg b/seaweed-block/docs/spec/cfg/RED_hz_noclamp.cfg new file mode 100644 index 0000000000..60d5d9620a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RED_hz_noclamp.cfg @@ -0,0 +1,22 @@ +\* RED_hz_noclamp: #205 RED (EXPECTED violated): renewal answered from memory WITHOUT the horizon clamp grants validity beyond the durable horizon (run from docs/spec: ./run.sh RED_hz_noclamp) +SPECIFICATION Spec +CONSTANTS + Kinds = {"forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = FALSE + ExtFail = FALSE +INVARIANT TypeOK HostWithinHorizon diff --git a/seaweed-block/docs/spec/cfg/RED_hz_noclamp_safety.cfg b/seaweed-block/docs/spec/cfg/RED_hz_noclamp_safety.cfg new file mode 100644 index 0000000000..ffbc8c68a0 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RED_hz_noclamp_safety.cfg @@ -0,0 +1,23 @@ +\* RED_hz_noclamp_safety: #205 control: without the clamp the restart rule still covers grants (expected to pass: the clamp is for S1 and fail-closed, not split-brain) (run from docs/spec: ./run.sh RED_hz_noclamp_safety) +SPECIFICATION Spec +CONSTANTS + Kinds = {"forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = FALSE + ExtFail = FALSE +INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable ForcedLossBounded GCSafe +PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/RED_lsn.cfg b/seaweed-block/docs/spec/cfg/RED_lsn.cfg index 146314a001..37a1b25034 100644 --- a/seaweed-block/docs/spec/cfg/RED_lsn.cfg +++ b/seaweed-block/docs/spec/cfg/RED_lsn.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = FALSE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK TypeOK PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/RED_lsn_storeonly.cfg b/seaweed-block/docs/spec/cfg/RED_lsn_storeonly.cfg index ee6c562e7b..a959a95480 100644 --- a/seaweed-block/docs/spec/cfg/RED_lsn_storeonly.cfg +++ b/seaweed-block/docs/spec/cfg/RED_lsn_storeonly.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/S4c_barrier_safe.cfg b/seaweed-block/docs/spec/cfg/S4c_barrier_safe.cfg new file mode 100644 index 0000000000..0843ae3abf --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4c_barrier_safe.cfg @@ -0,0 +1,10 @@ +\* S4c_barrier_safe (CutCOW): Mode=barrier Mut=none +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + Mode = "barrier" + Mut = "none" +INVARIANTS TypeOK HeadImage BufFrozen SideFrozen SideOnlyInCut ReadsNewest HeadLeSynced diff --git a/seaweed-block/docs/spec/cfg/S4c_cow_safe.cfg b/seaweed-block/docs/spec/cfg/S4c_cow_safe.cfg new file mode 100644 index 0000000000..fdb0fdb5c5 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4c_cow_safe.cfg @@ -0,0 +1,10 @@ +\* S4c_cow_safe (CutCOW): Mode=cow Mut=none +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + Mode = "cow" + Mut = "none" +INVARIANTS TypeOK HeadImage BufFrozen SideFrozen SideOnlyInCut ReadsNewest HeadLeSynced diff --git a/seaweed-block/docs/spec/cfg/S4c_red_copyAfter.cfg b/seaweed-block/docs/spec/cfg/S4c_red_copyAfter.cfg new file mode 100644 index 0000000000..0ae2e88e89 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4c_red_copyAfter.cfg @@ -0,0 +1,10 @@ +\* S4c_red_copyAfter (CutCOW): Mode=cow Mut=copyAfter +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + Mode = "cow" + Mut = "copyAfter" +INVARIANTS HeadImage BufFrozen diff --git a/seaweed-block/docs/spec/cfg/S4c_red_copyAtFlush.cfg b/seaweed-block/docs/spec/cfg/S4c_red_copyAtFlush.cfg new file mode 100644 index 0000000000..645785bead --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4c_red_copyAtFlush.cfg @@ -0,0 +1,10 @@ +\* S4c_red_copyAtFlush (CutCOW): Mode=cow Mut=copyAtFlush +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + Mode = "cow" + Mut = "copyAtFlush" +INVARIANTS HeadImage BufFrozen diff --git a/seaweed-block/docs/spec/cfg/S4c_red_earlyRelease.cfg b/seaweed-block/docs/spec/cfg/S4c_red_earlyRelease.cfg new file mode 100644 index 0000000000..ff9156881d --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4c_red_earlyRelease.cfg @@ -0,0 +1,10 @@ +\* S4c_red_earlyRelease (CutCOW): Mode=cow Mut=earlyRelease +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + Mode = "cow" + Mut = "earlyRelease" +INVARIANTS HeadImage BufFrozen diff --git a/seaweed-block/docs/spec/cfg/S4c_red_noChunkLock.cfg b/seaweed-block/docs/spec/cfg/S4c_red_noChunkLock.cfg new file mode 100644 index 0000000000..ec10c8f293 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4c_red_noChunkLock.cfg @@ -0,0 +1,10 @@ +\* S4c_red_noChunkLock (CutCOW): Mode=cow Mut=noChunkLock +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + Mode = "cow" + Mut = "noChunkLock" +INVARIANTS HeadImage BufFrozen diff --git a/seaweed-block/docs/spec/cfg/S4c_red_noCopy.cfg b/seaweed-block/docs/spec/cfg/S4c_red_noCopy.cfg new file mode 100644 index 0000000000..741b72fad2 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4c_red_noCopy.cfg @@ -0,0 +1,10 @@ +\* S4c_red_noCopy (CutCOW): Mode=cow Mut=noCopy +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + Mode = "cow" + Mut = "noCopy" +INVARIANTS HeadImage BufFrozen diff --git a/seaweed-block/docs/spec/cfg/S4c_red_sideReuse.cfg b/seaweed-block/docs/spec/cfg/S4c_red_sideReuse.cfg new file mode 100644 index 0000000000..3e75a074a7 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4c_red_sideReuse.cfg @@ -0,0 +1,10 @@ +\* S4c_red_sideReuse (CutCOW): Mode=cow Mut=sideReuse +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + Mode = "cow" + Mut = "sideReuse" +INVARIANTS HeadImage BufFrozen diff --git a/seaweed-block/docs/spec/cfg/S4c_wit_CASAfterWindowWrite.cfg b/seaweed-block/docs/spec/cfg/S4c_wit_CASAfterWindowWrite.cfg new file mode 100644 index 0000000000..0b66bf30cd --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4c_wit_CASAfterWindowWrite.cfg @@ -0,0 +1,10 @@ +\* S4c_wit_CASAfterWindowWrite (CutCOW): Mode=cow Mut=none +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + Mode = "cow" + Mut = "none" +INVARIANTS W_CASAfterWindowWrite diff --git a/seaweed-block/docs/spec/cfg/S4c_wit_CrashDroppedSide.cfg b/seaweed-block/docs/spec/cfg/S4c_wit_CrashDroppedSide.cfg new file mode 100644 index 0000000000..aaff84de01 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4c_wit_CrashDroppedSide.cfg @@ -0,0 +1,10 @@ +\* S4c_wit_CrashDroppedSide (CutCOW): Mode=cow Mut=none +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + Mode = "cow" + Mut = "none" +INVARIANTS W_CrashDroppedSide diff --git a/seaweed-block/docs/spec/cfg/S4c_wit_WriteInWindow.cfg b/seaweed-block/docs/spec/cfg/S4c_wit_WriteInWindow.cfg new file mode 100644 index 0000000000..dd93222252 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4c_wit_WriteInWindow.cfg @@ -0,0 +1,10 @@ +\* S4c_wit_WriteInWindow (CutCOW): Mode=cow Mut=none +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + Mode = "cow" + Mut = "none" +INVARIANTS W_WriteInWindow diff --git a/seaweed-block/docs/spec/cfg/S4r2_barrier_safe.cfg b/seaweed-block/docs/spec/cfg/S4r2_barrier_safe.cfg new file mode 100644 index 0000000000..245e4a1be0 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4r2_barrier_safe.cfg @@ -0,0 +1,11 @@ +\* S4r2_barrier_safe (CutCOW2, S4c r2: save as I/O + abort): Mode=barrier Mut=none +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + MaxAborts = 1 + Mode = "barrier" + Mut = "none" +INVARIANTS TypeOK HeadImage BufFrozen SideFrozen SideOnlyInCut ReadsNewest HeadLeSynced diff --git a/seaweed-block/docs/spec/cfg/S4r2_cow_safe.cfg b/seaweed-block/docs/spec/cfg/S4r2_cow_safe.cfg new file mode 100644 index 0000000000..7cdbbc53cf --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4r2_cow_safe.cfg @@ -0,0 +1,11 @@ +\* S4r2_cow_safe (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=none +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + MaxAborts = 1 + Mode = "cow" + Mut = "none" +INVARIANTS TypeOK HeadImage BufFrozen SideFrozen SideOnlyInCut ReadsNewest HeadLeSynced diff --git a/seaweed-block/docs/spec/cfg/S4r2_red_abortNoJoin.cfg b/seaweed-block/docs/spec/cfg/S4r2_red_abortNoJoin.cfg new file mode 100644 index 0000000000..0adba0a68f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4r2_red_abortNoJoin.cfg @@ -0,0 +1,11 @@ +\* S4r2_red_abortNoJoin (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=abortNoJoin +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + MaxAborts = 1 + Mode = "cow" + Mut = "abortNoJoin" +INVARIANTS HeadImage BufFrozen SideOnlyInCut diff --git a/seaweed-block/docs/spec/cfg/S4r2_red_noChunkLock.cfg b/seaweed-block/docs/spec/cfg/S4r2_red_noChunkLock.cfg new file mode 100644 index 0000000000..754fbe39ba --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4r2_red_noChunkLock.cfg @@ -0,0 +1,11 @@ +\* S4r2_red_noChunkLock (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=noChunkLock +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + MaxAborts = 1 + Mode = "cow" + Mut = "noChunkLock" +INVARIANTS HeadImage BufFrozen diff --git a/seaweed-block/docs/spec/cfg/S4r2_red_noCopy.cfg b/seaweed-block/docs/spec/cfg/S4r2_red_noCopy.cfg new file mode 100644 index 0000000000..ef8441a309 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4r2_red_noCopy.cfg @@ -0,0 +1,11 @@ +\* S4r2_red_noCopy (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=noCopy +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + MaxAborts = 1 + Mode = "cow" + Mut = "noCopy" +INVARIANTS HeadImage BufFrozen diff --git a/seaweed-block/docs/spec/cfg/S4r2_wit_AbortWhileSaving.cfg b/seaweed-block/docs/spec/cfg/S4r2_wit_AbortWhileSaving.cfg new file mode 100644 index 0000000000..f143dfbf9a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4r2_wit_AbortWhileSaving.cfg @@ -0,0 +1,11 @@ +\* S4r2_wit_AbortWhileSaving (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=none +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + MaxAborts = 1 + Mode = "cow" + Mut = "none" +INVARIANTS W_AbortWhileSaving diff --git a/seaweed-block/docs/spec/cfg/S4r2_wit_CASAfterAbort.cfg b/seaweed-block/docs/spec/cfg/S4r2_wit_CASAfterAbort.cfg new file mode 100644 index 0000000000..7812c4008c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4r2_wit_CASAfterAbort.cfg @@ -0,0 +1,11 @@ +\* S4r2_wit_CASAfterAbort (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=none +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + MaxAborts = 1 + Mode = "cow" + Mut = "none" +INVARIANTS W_CASAfterAbort diff --git a/seaweed-block/docs/spec/cfg/S4r2_wit_SaveUsedByCopier.cfg b/seaweed-block/docs/spec/cfg/S4r2_wit_SaveUsedByCopier.cfg new file mode 100644 index 0000000000..f6ad59d8b4 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/S4r2_wit_SaveUsedByCopier.cfg @@ -0,0 +1,11 @@ +\* S4r2_wit_SaveUsedByCopier (CutCOW2, S4c r2: save as I/O + abort): Mode=cow Mut=none +SPECIFICATION Spec +CONSTANTS + Chunks = {"a", "b", "c"} + MaxLSN = 6 + MaxCuts = 2 + MaxCrash = 1 + MaxAborts = 1 + Mode = "cow" + Mut = "none" +INVARIANTS W_SaveUsedByCopier diff --git a/seaweed-block/docs/spec/cfg/W4_both.cfg b/seaweed-block/docs/spec/cfg/W4_both.cfg index defb4bbe28..5ebc51c670 100644 --- a/seaweed-block/docs/spec/cfg/W4_both.cfg +++ b/seaweed-block/docs/spec/cfg/W4_both.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_clean.cfg b/seaweed-block/docs/spec/cfg/W4_clean.cfg index a96f132365..75787a5b90 100644 --- a/seaweed-block/docs/spec/cfg/W4_clean.cfg +++ b/seaweed-block/docs/spec/cfg/W4_clean.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_clean_large.cfg b/seaweed-block/docs/spec/cfg/W4_clean_large.cfg index ed97a39b60..7cc398a976 100644 --- a/seaweed-block/docs/spec/cfg/W4_clean_large.cfg +++ b/seaweed-block/docs/spec/cfg/W4_clean_large.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_drift.cfg b/seaweed-block/docs/spec/cfg/W4_drift.cfg index 5a3f44b966..bafbe79583 100644 --- a/seaweed-block/docs/spec/cfg/W4_drift.cfg +++ b/seaweed-block/docs/spec/cfg/W4_drift.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing diff --git a/seaweed-block/docs/spec/cfg/W4_drift_heads.cfg b/seaweed-block/docs/spec/cfg/W4_drift_heads.cfg index 78d42cea93..a7d97c0ed3 100644 --- a/seaweed-block/docs/spec/cfg/W4_drift_heads.cfg +++ b/seaweed-block/docs/spec/cfg/W4_drift_heads.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoOldCasAfterTakeover NoLateChunkReachable ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_forced.cfg b/seaweed-block/docs/spec/cfg/W4_forced.cfg index d29d30835b..4bc6d011bb 100644 --- a/seaweed-block/docs/spec/cfg/W4_forced.cfg +++ b/seaweed-block/docs/spec/cfg/W4_forced.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_forced_exact.cfg b/seaweed-block/docs/spec/cfg/W4_forced_exact.cfg index 24ff032104..81b5759336 100644 --- a/seaweed-block/docs/spec/cfg/W4_forced_exact.cfg +++ b/seaweed-block/docs/spec/cfg/W4_forced_exact.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK ForcedLossExact diff --git a/seaweed-block/docs/spec/cfg/W4_forced_large.cfg b/seaweed-block/docs/spec/cfg/W4_forced_large.cfg index 7888ba01b0..cc517ff834 100644 --- a/seaweed-block/docs/spec/cfg/W4_forced_large.cfg +++ b/seaweed-block/docs/spec/cfg/W4_forced_large.cfg @@ -17,5 +17,7 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_hz_both.cfg b/seaweed-block/docs/spec/cfg/W4_hz_both.cfg new file mode 100644 index 0000000000..65971e9d11 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/W4_hz_both.cfg @@ -0,0 +1,23 @@ +\* W4_hz_both: #205 durable horizon, both move kinds, failing extensions, one restart (run from docs/spec: ./run.sh W4_hz_both) +SPECIFICATION Spec +CONSTANTS + Kinds = {"clean", "forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = TRUE +INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover HostWithinHorizon DiskCoversMemory +PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_hz_clean.cfg b/seaweed-block/docs/spec/cfg/W4_hz_clean.cfg new file mode 100644 index 0000000000..7173d26318 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/W4_hz_clean.cfg @@ -0,0 +1,23 @@ +\* W4_hz_clean: #205 durable horizon, clean move, extension writes may fail landed or not, one restart (run from docs/spec: ./run.sh W4_hz_clean) +SPECIFICATION Spec +CONSTANTS + Kinds = {"clean"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = TRUE +INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover HostWithinHorizon DiskCoversMemory +PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_hz_forced.cfg b/seaweed-block/docs/spec/cfg/W4_hz_forced.cfg new file mode 100644 index 0000000000..63720fa5f9 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/W4_hz_forced.cfg @@ -0,0 +1,23 @@ +\* W4_hz_forced: #205 durable horizon, forced move, extension writes may fail landed or not, one restart (run from docs/spec: ./run.sh W4_hz_forced) +SPECIFICATION Spec +CONSTANTS + Kinds = {"forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = TRUE +INVARIANT TypeOK NoDualServing NoOldCasAfterTakeover NoLateChunkReachable CleanNoLoss ForcedLossBounded GCSafe NoLiveIntentExpired AttachOrder SeedMatchesTakeover HostWithinHorizon DiskCoversMemory +PROPERTY HeadMonotone diff --git a/seaweed-block/docs/spec/cfg/W4_hz_reach_ext.cfg b/seaweed-block/docs/spec/cfg/W4_hz_reach_ext.cfg new file mode 100644 index 0000000000..4b2ae416f2 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/W4_hz_reach_ext.cfg @@ -0,0 +1,22 @@ +\* W4_hz_reach_ext: #205 witness (EXPECTED violated): an extension raises the holder's horizon (run from docs/spec: ./run.sh W4_hz_reach_ext) +SPECIFICATION Spec +CONSTANTS + Kinds = {"forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE +INVARIANT TypeOK W_NoExtension diff --git a/seaweed-block/docs/spec/cfg/W4_hz_reach_landed.cfg b/seaweed-block/docs/spec/cfg/W4_hz_reach_landed.cfg new file mode 100644 index 0000000000..aa1264372e --- /dev/null +++ b/seaweed-block/docs/spec/cfg/W4_hz_reach_landed.cfg @@ -0,0 +1,22 @@ +\* W4_hz_reach_landed: #205 witness (EXPECTED violated): a failed extension lands on disk above the published horizon (run from docs/spec: ./run.sh W4_hz_reach_landed) +SPECIFICATION Spec +CONSTANTS + Kinds = {"forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = TRUE +INVARIANT TypeOK W_NoExtLanded diff --git a/seaweed-block/docs/spec/cfg/W4_hz_reach_uncertain_restart.cfg b/seaweed-block/docs/spec/cfg/W4_hz_reach_uncertain_restart.cfg new file mode 100644 index 0000000000..22a4b4f678 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/W4_hz_reach_uncertain_restart.cfg @@ -0,0 +1,22 @@ +\* W4_hz_reach_uncertain_restart: #205 witness (EXPECTED violated): with failing extensions a restart followed by a takeover is still reachable (run from docs/spec: ./run.sh W4_hz_reach_uncertain_restart) +SPECIFICATION Spec +CONSTANTS + Kinds = {"forced"} + MaxT = 4 + TTL = 2 + ITTL = 1 + MaxLSN = 2 + MaxCuts = 2 + Drift = 0 + MaxRestarts = 1 + LeaseOn = TRUE + LsnGuard = TRUE + StoreEpochGuard = TRUE + HostFence = TRUE + LayerLsnCheck = TRUE + SeedFromObserved = TRUE + GCEpochRule = TRUE + WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = TRUE +INVARIANT TypeOK W_NoRestartMove diff --git a/seaweed-block/docs/spec/cfg/W4_reach_bcut.cfg b/seaweed-block/docs/spec/cfg/W4_reach_bcut.cfg index 3201dfe6cf..b8515809cb 100644 --- a/seaweed-block/docs/spec/cfg/W4_reach_bcut.cfg +++ b/seaweed-block/docs/spec/cfg/W4_reach_bcut.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK W_NoBCut diff --git a/seaweed-block/docs/spec/cfg/W4_reach_clean.cfg b/seaweed-block/docs/spec/cfg/W4_reach_clean.cfg index dcc1ec1e69..95f11e83dc 100644 --- a/seaweed-block/docs/spec/cfg/W4_reach_clean.cfg +++ b/seaweed-block/docs/spec/cfg/W4_reach_clean.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK W_NoCleanServe diff --git a/seaweed-block/docs/spec/cfg/W4_reach_forced.cfg b/seaweed-block/docs/spec/cfg/W4_reach_forced.cfg index 58436d68e6..e810bc52e6 100644 --- a/seaweed-block/docs/spec/cfg/W4_reach_forced.cfg +++ b/seaweed-block/docs/spec/cfg/W4_reach_forced.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK W_NoForcedServe diff --git a/seaweed-block/docs/spec/cfg/W4_reach_restart.cfg b/seaweed-block/docs/spec/cfg/W4_reach_restart.cfg index 991eb9dca9..160fb8d535 100644 --- a/seaweed-block/docs/spec/cfg/W4_reach_restart.cfg +++ b/seaweed-block/docs/spec/cfg/W4_reach_restart.cfg @@ -17,4 +17,6 @@ CONSTANTS SeedFromObserved = TRUE GCEpochRule = TRUE WaitLeaseExpiry = TRUE + Clamp = TRUE + ExtFail = FALSE INVARIANT TypeOK W_NoRestartMove diff --git a/seaweed-block/docs/spec/run.sh b/seaweed-block/docs/spec/run.sh index c0c685c1ca..05391d8a5e 100755 --- a/seaweed-block/docs/spec/run.sh +++ b/seaweed-block/docs/spec/run.sh @@ -21,6 +21,7 @@ case $cfg in S3_sw*) spec=SmartWALRecovery ;; S3_rep_*) spec=WALReplica ;; S4b_*) spec=CutPipeline ;; + S4c_*) spec=CutCOW ;; S4_*) spec=CutCapture ;; S5_*) spec=ControlPlane ;; S6_*) spec=ReplicationFailover ;; diff --git a/seaweed-block/docs/workspace-lease.md b/seaweed-block/docs/workspace-lease.md index e310ecbda9..bb089340fe 100644 --- a/seaweed-block/docs/workspace-lease.md +++ b/seaweed-block/docs/workspace-lease.md @@ -35,9 +35,38 @@ mutex then guard state mutex. Canceled renewal replies cannot publish a grant. renewal intervals for the 30s lease). Set a positive bound below 60s that covers the deployment's clock drift. The bound is persisted with each lease; a restart or smaller setting cannot shorten an outstanding grant's bound. -The master grants a FORCED move only after both the stored expiry and its -conservative restart deadline plus the full bound. `ValidForNs` in lease +The master grants a FORCED move only after both the persisted lease horizon +and the granted or conservative restart deadline plus the full bound. `ValidForNs` in lease replies excludes half the bound. Hosts anchor that shortened duration to request start, self-fencing early without comparing remote wall-clock times. Delayed replies cannot extend admission. The bound is an operational clock assumption; arbitrarily stopped or unbounded clocks are not covered. + +## Master-side renewal + +Blockmaster answers a renewal of an established lease from memory: it takes +only a small leaf lock, writes nothing and never waits for another authority +write or a lifecycle store write. The grant is the smaller of now plus the TTL +and the durable horizon, the lease expiry stored on disk. A grant that would +leave the host no validity (grant minus half the skew bound not after now) is +refused with an error, so the host keeps its remaining validity instead of +fencing on an invalid reply. + +Only the first grant of a lease is written synchronously; it stores a horizon +of now plus 1.5 times the TTL. When a renewal finds the horizon less than +1.25 times the TTL ahead, it starts one background extension for that volume. +The extension is an ordinary authority write under the publisher lock and +stores the renewal time plus 1.5 times the TTL. A failed extension write is +an unknown outcome: the volume becomes uncertain, renewals that would issue a +new or extended grant are refused, and its host fences within its current +validity. A Revoking lease still gets its bounded drain reply, never extended. A restart reloads the stored +horizon, and a FORCED move waits for that horizon plus the skew bound. + +All authority writes stay serialized. With N live leases and store write time +P, extensions stay ahead without shortening grants only while N·P is below +TTL/4 minus one host renewal interval r (about (TTL − skew/2)/3), and hosts +stay unfenced while N·P stays below 1.25·TTL − skew/2 − 2r (about 14 s at the +defaults). Beyond that, grants shrink and hosts fence: the design fails +closed. Blockmaster logs one warning per failure streak, with the write's +latency and the remaining horizon, when an extension fails, and one when +grants start to be clamped to the horizon, and a line when either recovers. diff --git a/seaweed-block/docs/workspace-measurements.md b/seaweed-block/docs/workspace-measurements.md index 0a9e901765..8a532d684d 100644 --- a/seaweed-block/docs/workspace-measurements.md +++ b/seaweed-block/docs/workspace-measurements.md @@ -28,15 +28,37 @@ bare-metal host; NVMe/TCP loopback; seconds): kernel absorbs metadata and the block device only sees batched writes. - Every guest `fsync` was verified to reach the backend sync: about 2 NVMe flushes per `fsync`, and zero in an unsafe-cache control. -- The cost in these runs is `fsync` latency, about 7 ms against 3 ms local. - The runs used the NVMe/TCP loopback frontend. The ublk frontend - (`--ublk-device`) and the per-stage `fsync` histograms (`/status/durable`, - see [fsync latency](fsync-latency.md)) are on `main` now; reducing the - latency, including group-commit tuning, is in progress. The numbers here - record those runs, not a measurement of current `main`. +- The cost in these runs was `fsync` latency, about 7 ms against 3 ms local, + over the NVMe/TCP loopback frontend. These are the original runs, kept as + history; the next section measures `fsync` after the group-commit fix. - The same comparison on an Azure `D16s_v5` nested-virtualization host gives the same picture. +**`fsync` after the group-commit fix** ([#173](https://github.com/seaweedfs/seaweed-block/pull/173); +one bare-metal lab host; Firecracker guest; fio 4 KiB random write, one request +at a time, `fsync` after every write, 60 s; median of 3 boots per setup): + +| Setup | `fsync` p50 | `fsync` p99 | Write IOPS | 2,000 × create + write + `fsync` | +|---|---|---|---|---| +| ublk, `walstore-chunk` | 3.23 ms | 9.11 ms | 283 | 8.48 s | +| ublk, `smartwal` (experimental) | 3.26 ms | 5.21 ms | 299 | 8.29 s | +| NVMe/TCP loopback, `walstore-chunk` | 3.59 ms | 9.63 ms | 258 | 9.27 s | +| NVMe/TCP loopback, `smartwal` (experimental) | 3.59 ms | 7.57 ms | 263 | 8.68 s | +| Local file-backed disk | 2.74 ms | 4.42 ms | 357 | 6.11 s | + +- Before the fix, on the same pack and host, guest `fsync` p50 was 5.54 ms + (ublk) and 5.87 ms (NVMe/TCP) against 2.74 ms local. +- The fix removed an idle wait: a lone `Sync` used to sit out the group-commit + collection delay with nobody to batch with. On `walstore-chunk` the + group-commit wait fell to about 8 µs (histogram p50 bucket), and a backend + `Sync` now takes about 1.2 ms on average (mean over the gate window). Each guest `fsync` causes two backend syncs. +- All four Seaweed Block setups passed a gate that every guest `fsync` reaches the backend sync + (at least 2,000 flushes and 2,000 backend syncs per run); an unsafe-cache + control showed zero. +- The other workloads (`npm ci`, `git clone`, untar, `find` + `stat`) stayed at + local-disk speed. +- One time window, 3 runs per setup: descriptive, not a performance gate. + **Snapshot and fork cost** (a 10 GiB volume written as 2,560 chunks of 4 MiB; median of 3). This is a host-side proxy, not a guest or network run: chunks are local files on a native Linux host, and filer metadata calls use a diff --git a/seaweed-block/scripts/check-manifest-scaling.py b/seaweed-block/scripts/check-manifest-scaling.py new file mode 100644 index 0000000000..1ad129ccb7 --- /dev/null +++ b/seaweed-block/scripts/check-manifest-scaling.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""Check three-sample manifest benchmark scaling; no device or host access. + +Run go test with -bench BenchmarkPrepareManifestUnchangedGroups -benchtime=20x +-count=3, save stdout, then pass that file to this checker. A 16x metadata +scale must grow less than 64x on the same serial runner. This is an explicit +qualification benchmark, not a wall-clock CI unit test. +""" +import re +import statistics +import sys +from pathlib import Path + +if len(sys.argv) != 2: + raise SystemExit("usage: check-manifest-scaling.py BENCHMARK_LOG") +samples = {256: [], 1024: [], 4096: []} +for count, ns in re.findall( + r"BenchmarkPrepareManifestUnchangedGroups/(256|1024|4096)-\d+\s+\d+\s+(\d+) ns/op", + Path(sys.argv[1]).read_text(encoding="utf-8-sig"), +): + samples[int(count)].append(int(ns)) +if any(len(values) != 3 for values in samples.values()): + raise SystemExit("need exactly three samples per group count") +medians = {count: statistics.median(values) for count, values in samples.items()} +if min(medians.values()) <= 0: + raise SystemExit("benchmark durations must be positive") +growth = medians[4096] / medians[256] +print("median_ns", medians, "growth_4096_over_256", growth, "limit", 64) +raise SystemExit(0 if growth < 64 else 1)