diff --git a/seaweed-block/.github/workflows/test.yml b/seaweed-block/.github/workflows/test.yml index 3af9bd21a6..df5114a0a4 100644 --- a/seaweed-block/.github/workflows/test.yml +++ b/seaweed-block/.github/workflows/test.yml @@ -37,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 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/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 df27929c40..2516140cb2 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -194,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") @@ -548,19 +550,7 @@ func durableCreateGeometry(f flags) (uint32, int, error) { 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 @@ -630,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 @@ -898,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() @@ -1460,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/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/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/main.go b/seaweed-block/cmd/sw-block/main.go index a0015447bb..249ead1fac 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -86,7 +86,7 @@ func run(args []string, stdout, stderr io.Writer) int { 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 } @@ -129,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) @@ -2296,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/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 7cf968bcd9..52f8d7fe1f 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -158,6 +158,7 @@ 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 + lostRanges map[string][]WorkspaceLostRange // forced moves' abandoned ranges (side files) workspaceUncertain map[string]bool workspaceNow func() time.Time workspaceTTL time.Duration @@ -234,6 +235,7 @@ func NewPublisher(dir Directive, opts ...PublisherOption) *Publisher { 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, @@ -283,6 +285,12 @@ 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 { 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/workspace.go b/seaweed-block/core/authority/workspace.go index 514520b38c..6d6301e1b3 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -280,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.leaseDeadlineLocked(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. @@ -294,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 @@ -319,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 index 128cfc0291..2a43a9c5b9 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -616,10 +616,61 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { lastEpoch := map[string]uint64{} var extensions atomic.Int64 heldEntered, heldRelease := make(chan struct{}), make(chan struct{}) - var holdOnce, releaseOnce sync.Once - releaseHold := func() { releaseOnce.Do(func() { close(heldRelease) }) } + 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 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 { @@ -636,9 +687,23 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { if ext { extensions.Add(1) first := false - holdOnce.Do(func() { first = true }) + 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 { - holding.Store(true) // before the hold: a renewal started after this saw it + 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 } @@ -648,13 +713,17 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // 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. - var offNS atomic.Int64 - offNS.Store(int64(-10 * time.Second)) - p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, func() time.Time { return time.Now().Add(time.Duration(offNS.Load())) })) + 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 - offNS.Store(0) + 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") @@ -664,10 +733,14 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { 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 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{}) @@ -681,6 +754,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // 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) }() @@ -715,11 +789,21 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { 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 { @@ -735,12 +819,29 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { } // Handshake 1: the first extension write is held inside the store. - <-heldEntered // progress, no timer (#227): renewers keep triggering extensions + // 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. - for { + // 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 { @@ -750,9 +851,15 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { if all { break } - time.Sleep(5 * time.Millisecond) + 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++ { @@ -761,11 +868,16 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { 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 } - if err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil { + 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 } @@ -979,3 +1091,125 @@ func TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite(t *testing.T) { 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_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/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/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 b24d94f720..eb6fd6f4eb 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -228,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. @@ -673,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) @@ -684,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 } @@ -870,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 @@ -1231,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 { @@ -1285,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 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 5e666b46a6..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 { @@ -648,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_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go index 7bee5cbf5b..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() 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/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/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 9a4708655d..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 @@ -94,6 +103,9 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch // 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{} @@ -104,10 +116,14 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch 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 } @@ -119,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 { @@ -161,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_test.go b/seaweed-block/core/frontend/chunkstore/manifest_test.go index eb53976606..fa0309f434 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest_test.go +++ b/seaweed-block/core/frontend/chunkstore/manifest_test.go @@ -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) 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/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 7a499b43d7..7c74e579b7 100644 --- a/seaweed-block/core/frontend/durable/export_chunk_test.go +++ b/seaweed-block/core/frontend/durable/export_chunk_test.go @@ -24,3 +24,8 @@ func SetTestDetachTrace(p *DurableProvider, f func(stage string, deadline time.T // 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 f305998a2e..6174905117 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -162,6 +162,9 @@ 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. @@ -173,10 +176,12 @@ type ProviderConfig struct { // 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 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. + // 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 @@ -251,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 @@ -875,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 { diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 2fee16c71f..4af44da113 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -364,13 +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, - 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 { diff --git a/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go b/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go index 674102985b..1e3e2a9734 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go @@ -4,7 +4,9 @@ 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" @@ -15,6 +17,19 @@ import ( "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) { @@ -63,8 +78,10 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) { } 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()) - h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: be, BlockSize: 4096, VolumeSize: 1 << 30}) + 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 { @@ -73,14 +90,50 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) { binary.LittleEndian.PutUint64(data[i:i+8], uint64(off+i)) } } - writeStart := time.Now() - r := h.Handle(ctx, nvme.IOCommand{Opcode: 0x01, NSID: 1, SLBA: uint64(off / 4096), NLB: transfer / 4096, Data: data}) - durations = append(durations, time.Since(writeStart)) - if r.AsError() != nil { - dump := make([]byte, 2<<20) - n := runtime.Stack(dump, true) - t.Logf("TIMEOUT STACKS\n%s", dump[:n]) - t.Fatalf("NO FLUSH write bytes=%d elapsed=%v result=%+v cp=%d next=%d", off, time.Since(start), r, ws.CheckpointLSN(), ws.NextLSN()) + 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()) @@ -109,7 +162,7 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) { if mode == storage.WModeStrict { fsyncs *= 2 } - t.Logf("COST mode=%d bytes=%d pressureBatches=%d internalFsyncsPerGiB=%.2f writeP99=%v max=%v", mode, total, batches, float64(fsyncs)/(float64(total)/(1<<30)), durations[(len(durations)-1)*99/100], durations[len(durations)-1]) + 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) @@ -155,7 +208,8 @@ func TestWALStoreChunkV3NoFlushWithActiveRF2CatchupPin(t *testing.T) { t.Fatal(err) } ws.SetRecycleFloorSource(c) - h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: be, BlockSize: 4096, VolumeSize: 1 << 30}) + 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) { @@ -183,8 +237,29 @@ func TestWALStoreChunkV3NoFlushWithActiveRF2CatchupPin(t *testing.T) { t.Fatalf("retained catch-up records=%d err=%v", count, err) } c.EndSession("r2") - r := h.Handle(ctx, nvme.IOCommand{Opcode: 1, NSID: 1, SLBA: 20000, NLB: 32, Data: data}) - if err := r.AsError(); err != nil { - t.Fatalf("no-Flush progress after catch-up release: %v", err) + 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/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 2aab01a159..83545e2a54 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -149,6 +149,9 @@ 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 @@ -159,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 @@ -288,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() @@ -316,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, } } @@ -343,6 +358,7 @@ func (b *StorageBackend) Close() error { b.mu.Lock() defer b.mu.Unlock() b.closed = true + b.notifyReadReadyLocked() return nil } @@ -371,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 } @@ -401,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 } @@ -444,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 @@ -531,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 } @@ -539,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 @@ -547,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 @@ -558,10 +682,18 @@ 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 errors.Is(err, storage.ErrWALPressureTimeout) { + 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 { @@ -654,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: @@ -661,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 } @@ -671,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) } @@ -748,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) @@ -762,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) @@ -798,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) @@ -809,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 } } @@ -852,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 { @@ -861,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/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 0368d64e3e..84691012a8 100644 --- a/seaweed-block/core/frontend/errors.go +++ b/seaweed-block/core/frontend/errors.go @@ -9,7 +9,8 @@ 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 diff --git a/seaweed-block/core/frontend/nvme/io.go b/seaweed-block/core/frontend/nvme/io.go index 4615b3d08a..437737aa49 100644 --- a/seaweed-block/core/frontend/nvme/io.go +++ b/seaweed-block/core/frontend/nvme/io.go @@ -76,7 +76,7 @@ type IOResult struct { SC uint8 Data []byte // read payload (nil for writes / errors) Reason string - retryable bool // only transient backend pressure clears wire DNR + retryable bool // transient pressure or readiness refusal clears wire DNR } func (r IOResult) completionStatus() uint16 { return MakeStatusField(r.SCT, r.SC, !r.retryable) } @@ -263,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"} } @@ -281,22 +283,32 @@ 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 { @@ -317,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/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 fef22cfca6..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)) @@ -572,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, @@ -588,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() 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/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_service.go b/seaweed-block/core/host/master/workspace_service.go index f8a068cff9..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" @@ -143,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 { @@ -157,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) @@ -180,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() 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 cac46d325a..c84cfb7877 100644 --- a/seaweed-block/core/host/volume/chunk_control_adapter_test.go +++ b/seaweed-block/core/host/volume/chunk_control_adapter_test.go @@ -3,7 +3,9 @@ package volume import ( "context" "encoding/json" + "fmt" "reflect" + "sync" "testing" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" @@ -19,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 @@ -36,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) } 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/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/receiver_base_pin_test.go b/seaweed-block/core/recovery/receiver_base_pin_test.go index 9608f3b1e3..0a305db5f5 100644 --- a/seaweed-block/core/recovery/receiver_base_pin_test.go +++ b/seaweed-block/core/recovery/receiver_base_pin_test.go @@ -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/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/storage/base_install_v3.go b/seaweed-block/core/storage/base_install_v3.go index 9b3ef91ecb..dba6fb0aaa 100644 --- a/seaweed-block/core/storage/base_install_v3.go +++ b/seaweed-block/core/storage/base_install_v3.go @@ -423,7 +423,7 @@ func (s *WALStore) applyEntryV3(lba uint32, data []byte, lsn uint64, installLane return fmt.Errorf("%w: %d above %d", ErrInstallLSNGap, lsn, anchor) } dataCopy := append([]byte(nil), data...) - phys, err := s.appendWriteV3(lba, dataCopy, lsn) + phys, err := s.appendWriteV3(lba, dataCopy, lsn, nil) s.walMutation.Add(1) if err != nil { if installLane && errors.Is(err, errWALFull) { @@ -517,6 +517,7 @@ func (s *WALStore) markBaseCompleteV3(id [16]byte) error { 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 { @@ -633,7 +634,15 @@ func (s *WALStore) markMapUnknownV3(lba uint64) { if v.ownedMap == nil { return } - v.mapEntries[lba/v.ownedMap.chunkBlocks].Unknown = true + 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 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_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_fake_remote_test.go b/seaweed-block/core/storage/chunk_fake_remote_test.go index f3eef79172..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) } 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 57d8e3401f..a2e6c10709 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -74,7 +74,10 @@ type chunkLayerImpl struct { 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 @@ -123,6 +126,7 @@ type chunkLayerImpl struct { keySeq uint64 // Test-only scheduling hooks; nil in production. + testHydrationWait func(uint64) // after promise registration, outside locks testCOWWait func() testCOWRead func(idx uint64, saved bool) testCOWSave func() error @@ -178,6 +182,15 @@ 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 } @@ -534,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 @@ -780,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 @@ -907,6 +883,9 @@ 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) var copyErr error @@ -974,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: @@ -986,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++ @@ -1012,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++ @@ -1397,6 +1377,13 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error func (l *chunkLayerImpl) Stats() chunkLayerStats { l.stMu.Lock() 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 @@ -1731,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) } @@ -2006,6 +1993,7 @@ func (l *chunkLayerImpl) Close() error { return nil } l.closed = true + l.closeHydrationLocked() l.stMu.Unlock() l.cowMu.Lock() l.cowClosed = true diff --git a/seaweed-block/core/storage/chunk_layer_map_v3.go b/seaweed-block/core/storage/chunk_layer_map_v3.go index 295c436f5e..28b62756b0 100644 --- a/seaweed-block/core/storage/chunk_layer_map_v3.go +++ b/seaweed-block/core/storage/chunk_layer_map_v3.go @@ -9,7 +9,8 @@ func (l *chunkLayerImpl) usesOwnedMapV3() bool { return l.s.v3 != nil && l.s.v3. // (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 write updates max LSN and invalidates proofs. +// 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. diff --git a/seaweed-block/core/storage/chunk_layer_races_test.go b/seaweed-block/core/storage/chunk_layer_races_test.go index 8ef33cc2e6..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") diff --git a/seaweed-block/core/storage/chunk_lsn_map_v3.go b/seaweed-block/core/storage/chunk_lsn_map_v3.go index 5c3cd936c2..caac02dcb7 100644 --- a/seaweed-block/core/storage/chunk_lsn_map_v3.go +++ b/seaweed-block/core/storage/chunk_lsn_map_v3.go @@ -1,7 +1,9 @@ package storage -// Dark impl-3 COW map, DESIGN r15 9.2-9.5. All bytes are append-only; -// neither fallback slots nor pending candidates can lose a dependency. +// 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" @@ -242,6 +244,14 @@ type chunkLSNMapV3 struct { 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) { @@ -256,6 +266,7 @@ func createChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3 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 { @@ -281,6 +292,13 @@ func openChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3, 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} @@ -291,7 +309,9 @@ func openChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3, // 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. -// No pages are reclaimed in this append-only implementation. +// 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() @@ -300,7 +320,8 @@ func (m *chunkLSNMapV3) Prepare(g, C uint64, entries []chunkLSNEntryV3, prior *c // Generation reservation and persistence share the existing sidecar mutex. // Concurrent preparers cannot select the same generation; no new lock or -// scheduler is introduced, and aborted candidates remain immutable orphans. +// 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() @@ -342,11 +363,14 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, if info.Size() < 0 { return nil, ErrMapInvalid } - off := uint64(info.Size()) - if off > math.MaxInt64-4095 { + fileBytes := uint64(info.Size()) + if fileBytes > math.MaxInt64-4095 { return nil, ErrCounterExhausted } - off = (off + 4095) &^ uint64(4095) + // 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 @@ -355,19 +379,39 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, } } }() + // 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) { - if uint64(len(b)) > math.MaxInt64-off { + at := alloc.alloc(uint64(len(b)+4095) / 4096) + if uint64(len(b)) > math.MaxInt64-at { return 0, ErrCounterExhausted } - at := off 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 } - off += uint64(len(b)) return at, nil } refs := make([]mapPageRefV3, s.pages) @@ -416,6 +460,15 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, } 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 { 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_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 index c6496a298c..2ef10237b2 100644 --- a/seaweed-block/core/storage/chunk_map_publication_v3.go +++ b/seaweed-block/core/storage/chunk_map_publication_v3.go @@ -57,7 +57,7 @@ type preparedMapPublicationV3 struct { // 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, ErrMapCoverageStale + return nil, mapCoverageRefusal("map_binding_missing") } proof := d.snapshotV3() c, e := m.Prepare(g, C, entries, prior) @@ -65,7 +65,8 @@ func prepareMapPublicationV3(m *chunkLSNMapV3, d *mapProofEpochV3, g, C uint64, return nil, e } if !proof.validV3(d) { - return nil, ErrMapCoverageStale + m.abandonCandidateV3(c) // prepared but never publishable + return nil, mapCoverageRefusal("proof_changed_during_prepare") } return &preparedMapPublicationV3{candidate: c, proof: proof}, nil } @@ -83,13 +84,13 @@ func sameMapTupleV3(d descriptorV3, c *chunkMapCandidateV3) bool { // 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 ErrMapCoverageStale + 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 ErrMapCoverageStale + return mapCoverageRefusal("map_tuple_changed") } if _, _, e := readChunkLSNMapV3(c.owner.fd, current, c.owner.chunkBlocks); e != nil { return e @@ -105,7 +106,7 @@ func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpo p.descMu.Lock() defer p.descMu.Unlock() if p.cur != current || p.otherValid != otherValid || (otherValid && p.other != other) { - return ErrMapCoverageStale + return mapCoverageRefusal("descriptor_changed_during_bind") } p.mapCurrent = c p.mapDomain = d @@ -114,7 +115,7 @@ func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpo func (p *descriptorPublisherV3) validateMapPublicationV3(next descriptorV3, prepared *preparedMapPublicationV3) error { if p.mapCurrent == nil { if prepared != nil { - return ErrMapCoverageStale + return mapCoverageRefusal("map_not_bound") } return nil } // dark core not bound yet @@ -122,22 +123,22 @@ func (p *descriptorPublisherV3) validateMapPublicationV3(next descriptorV3, prep if prepared != nil { c = prepared.candidate if c == nil || c.owner != p.mapCurrent.owner || !prepared.proof.validV3(p.mapDomain) { - return ErrMapCoverageStale + return mapCoverageRefusal("proof_changed") } if c.generation <= p.mapCurrent.generation || c.covered < p.mapCurrent.covered { - return ErrMapCoverageStale + return mapCoverageRefusal("candidate_superseded") } } if !sameMapTupleV3(next, c) || c.covered < next.CheckpointLSN || c.covered > next.W { - return ErrMapCoverageStale + 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{}, ErrMapCoverageStale + return descriptorV3{}, mapCoverageRefusal("candidate_missing") } - return p.publishWithMapV3(storeMu, snap, func(d *descriptorV3) error { + d, err := p.publishWithMapV3(storeMu, snap, func(d *descriptorV3) error { if mutate != nil { if e := mutate(d); e != nil { return e @@ -146,6 +147,18 @@ func (p *descriptorPublisherV3) publishMapV3(storeMu sync.Locker, snap func(), p *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. @@ -187,7 +200,12 @@ func openDescriptorMapV3(path string, selected descriptorV3, fallback *descripto if fallback.UUID != selected.UUID || fallback.MapLineage != selected.MapLineage || !sameGeometryV3(*fallback, selected) { err = ErrMapInvalid } else { - _, _, err = readChunkLSNMapV3(m.fd, *fallback, cb) + 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() 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_seam.go b/seaweed-block/core/storage/chunk_seam.go index a578fefcec..c1cc2888f2 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -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 @@ -342,6 +347,10 @@ type chunkLayerConfig struct { CaptureAllowed func() error // ReadMissTimeout bounds one OnReadMiss remote fetch. ReadMissTimeout time.Duration + // 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 @@ -426,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 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 c843ccee54..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" @@ -105,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 @@ -128,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 9e63b2e04c..8c1fccbc09 100644 --- a/seaweed-block/core/storage/contract_test.go +++ b/seaweed-block/core/storage/contract_test.go @@ -316,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)) } diff --git a/seaweed-block/core/storage/descriptor_v3.go b/seaweed-block/core/storage/descriptor_v3.go index ec5f3ea477..62310d03a4 100644 --- a/seaweed-block/core/storage/descriptor_v3.go +++ b/seaweed-block/core/storage/descriptor_v3.go @@ -257,8 +257,12 @@ func (p *descriptorPublisherV3) publishLockedCoreV3(mutate func(next *descriptor 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). + // 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 @@ -266,6 +270,13 @@ func (p *descriptorPublisherV3) publishLockedCoreV3(mutate func(next *descriptor 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 } @@ -321,7 +332,7 @@ func mergeDescriptorV3Mode(cur, next *descriptorV3, reset bool) error { 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)", - ErrMapCoverageStale, errDescriptorTransition, cur.MapGeneration, next.MapGeneration) + 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) diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index 6d52d7bf24..9c6175e044 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -3,7 +3,6 @@ package storage import ( "encoding/binary" "fmt" - "log" "sort" "sync" "sync/atomic" @@ -111,6 +110,7 @@ func (f *flusher) runWithStartSignal(started chan<- struct{}) { if started != nil { close(started) } + var diagnostics checkpointLogLimiter for { select { case <-f.stopCh: @@ -120,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()) } } } @@ -278,11 +278,13 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { // The released tail is persisted with the checkpoint, before the // writer may reuse those bytes. 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) } @@ -313,7 +315,7 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { store.mu.Lock() if !store.v3.flushLifetimeValidV3(recoveryGen) { store.mu.Unlock() - return ErrMapCoverageStale + return mapCoverageRefusal("recovery_lifetime_changed") } checkpoint = store.checkpointLSN if checkpoint >= maxLSN && maxLSN+1 > store.walTail { 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_test.go b/seaweed-block/core/storage/flusher_test.go index 9155b34594..3ff75ea1d2 100644 --- a/seaweed-block/core/storage/flusher_test.go +++ b/seaweed-block/core/storage/flusher_test.go @@ -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)) } diff --git a/seaweed-block/core/storage/logical_storage.go b/seaweed-block/core/storage/logical_storage.go index 4fdc11cf1d..9fb9a4176d 100644 --- a/seaweed-block/core/storage/logical_storage.go +++ b/seaweed-block/core/storage/logical_storage.go @@ -1,6 +1,15 @@ package storage -import "fmt" +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 @@ -145,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 @@ -302,3 +312,12 @@ func (h *legacyInstallHandle) MarkBaseComplete() error { 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 index 16ebb3964d..89c12c0e6b 100644 --- a/seaweed-block/core/storage/migrate_v3.go +++ b/seaweed-block/core/storage/migrate_v3.go @@ -107,7 +107,8 @@ func ValidateMigrationV3(src MigrationSourceV3) error { // 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 maxWriteLSN 0, coveredCheckpoint = +// 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. @@ -141,6 +142,7 @@ func PrepareMigrationV3(mapPath string, src MigrationSourceV3) (MigrationPlanV3, 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 { diff --git a/seaweed-block/core/storage/parallelwal/store.go b/seaweed-block/core/storage/parallelwal/store.go index 863b8795ac..7c3139a956 100644 --- a/seaweed-block/core/storage/parallelwal/store.go +++ b/seaweed-block/core/storage/parallelwal/store.go @@ -1330,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 { 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 e054fa170e..b51d3f9bc9 100644 --- a/seaweed-block/core/storage/smartwal/store.go +++ b/seaweed-block/core/storage/smartwal/store.go @@ -502,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. @@ -522,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/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/volume_unheld.go b/seaweed-block/core/storage/volume_unheld.go new file mode 100644 index 0000000000..b3f9709a9e --- /dev/null +++ b/seaweed-block/core/storage/volume_unheld.go @@ -0,0 +1,56 @@ +package storage + +import ( + "errors" + "fmt" + "os" +) + +// ErrVolumeHeld: a live process on this host holds the volume file's lock. +var ErrVolumeHeld = errors.New("storage: volume held by a live owner on this host") + +// ProbeVolumeUnheld reports whether no process on THIS host holds the v3 +// volume file at path. It takes and releases the exclusive, nonblocking +// advisory lock that every v3 owner holds for as long as its store is open; +// the kernel releases that lock when the owner's process exits. +// +// nil: unheld. ErrVolumeHeld: held. Any other error: unknown (missing file, +// not a v3 volume, the lock call failed); treat it as not proven. +// +// The proof is per host and for local filesystems only: it says nothing +// about a process on another host, and nothing on a network or shared mount, +// where advisory lock semantics vary. It covers the file at path when the +// probe opens it, not a file renamed away earlier. It is not proof the owner +// process is dead; host cleanup must check that separately. The probe holds +// the lock only for an instant and leaves no reservation behind, so it does +// not keep a new owner out; an owner opening the volume in that instant is +// refused with ErrWALStoreLocked: probe only when the owner is believed gone. +func ProbeVolumeUnheld(path string) error { + // One descriptor for both steps, locked first: the answer is about the + // file this descriptor opened, whatever the path names afterwards, and + // on Windows an owner's byte lock would refuse a read made before ours. + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() // closing releases the probe's lock + if hook := testProbeUnheldAfterOpen; hook != nil { + hook() + } + switch err := LockWALStoreFile(f); { + case errors.Is(err, ErrWALStoreLocked): + return ErrVolumeHeld // held, whatever the file is: the safe answer + case err != nil: + return err + } + // Only a v3 owner takes the lock; for any other file a free lock proves + // nothing. + if err := probeWALStoreV3At(f); err != nil { + return fmt.Errorf("storage: %s is not a v3 volume, unheld cannot be proven: %w", path, err) + } + return nil +} + +// testProbeUnheldAfterOpen, test-only, runs in ProbeVolumeUnheld after the +// open, before the lock. +var testProbeUnheldAfterOpen func() diff --git a/seaweed-block/core/storage/volume_unheld_test.go b/seaweed-block/core/storage/volume_unheld_test.go new file mode 100644 index 0000000000..7a23e26b7f --- /dev/null +++ b/seaweed-block/core/storage/volume_unheld_test.go @@ -0,0 +1,180 @@ +package storage + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +func createClosedV3Volume(t *testing.T) string { + t.Helper() + path := filepath.Join(t.TempDir(), "v.bin") + s, err := CreateWALStore(path, 64, 4096) + if err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + return path +} + +// A closed v3 volume is unheld, and the probe leaves it openable (it +// released its own lock). +func TestProbeVolumeUnheldClosedVolume(t *testing.T) { + path := createClosedV3Volume(t) + if err := ProbeVolumeUnheld(path); err != nil { + t.Fatalf("closed volume: %v; want unheld", err) + } + s, err := OpenWALStore(path) + if err != nil { + t.Fatalf("open after the probe: %v", err) + } + _ = s.Close() +} + +// An open store holds the volume: the probe says held (also from another +// descriptor in the same process), and unheld once the store is closed. +func TestProbeVolumeUnheldOpenStoreIsHeld(t *testing.T) { + path := createClosedV3Volume(t) + s, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + if err := ProbeVolumeUnheld(path); !errors.Is(err, ErrVolumeHeld) { + _ = s.Close() + t.Fatalf("open store: %v; want ErrVolumeHeld", err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + if err := ProbeVolumeUnheld(path); err != nil { + t.Fatalf("after close: %v; want unheld", err) + } +} + +// Unknown is neither unheld nor held: a missing file and a file that is not +// a v3 volume (its owner would not take the lock). +func TestProbeVolumeUnheldUnknown(t *testing.T) { + missing := filepath.Join(t.TempDir(), "missing.bin") + junk := filepath.Join(t.TempDir(), "junk.bin") + if err := os.WriteFile(junk, make([]byte, 64<<10), 0o644); err != nil { + t.Fatal(err) + } + for name, path := range map[string]string{"missing": missing, "not v3": junk} { + if err := ProbeVolumeUnheld(path); err == nil || errors.Is(err, ErrVolumeHeld) { + t.Fatalf("%s: %v; want an unknown (non-nil, not held) result", name, err) + } + } +} + +const unheldHelperEnv = "SWBLOCK_UNHELD_HELPER_PATH" + +// TestProbeVolumeUnheldHelper is the holder process of the test below: it +// opens the store, says so, and waits to be killed. +func TestProbeVolumeUnheldHelper(t *testing.T) { + path := os.Getenv(unheldHelperEnv) + if path == "" { + t.Skip("helper process only") + } + s, err := OpenWALStore(path) + if err != nil { + os.Stdout.WriteString("OPEN-FAILED " + err.Error() + "\n") + os.Exit(3) + } + defer s.Close() + os.Stdout.WriteString("HOLDING\n") + time.Sleep(time.Minute) + os.Exit(4) +} + +// The property cleanup relies on: a volume held by another process is held, +// and becomes unheld when that process dies without closing it (the kernel +// releases the lock). +func TestProbeVolumeUnheldHolderProcessDies(t *testing.T) { + path := createClosedV3Volume(t) + cmd := exec.Command(os.Args[0], "-test.run=^TestProbeVolumeUnheldHelper$", "-test.count=1") + cmd.Env = append(os.Environ(), unheldHelperEnv+"="+path) + out, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + exited := make(chan struct{}) + // Reaped on every path; the cleanup kills the holder and joins its reaper. + go func() { _ = cmd.Wait(); close(exited) }() + t.Cleanup(func() { + _ = cmd.Process.Kill() + select { + case <-exited: + case <-time.After(10 * time.Second): + t.Error("holder process not reaped") + } + }) + ready := make(chan string, 1) + go func() { + buf := make([]byte, 256) + n, _ := out.Read(buf) + ready <- string(buf[:n]) + }() + select { + case line := <-ready: + if !strings.Contains(line, "HOLDING") { + t.Fatalf("holder: %q", line) + } + case <-time.After(30 * time.Second): + t.Fatal("holder never opened the volume") + } + if err := ProbeVolumeUnheld(path); !errors.Is(err, ErrVolumeHeld) { + t.Fatalf("held by a live process: %v; want ErrVolumeHeld", err) + } + if err := cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + select { + case <-exited: + case <-time.After(10 * time.Second): + t.Fatal("holder did not exit after kill") + } + if err := ProbeVolumeUnheld(path); err != nil { + t.Fatalf("after the holder died: %v; want unheld", err) + } +} + +// The answer is about the file the probe opened: a held volume whose path is +// replaced (by an unlocked non-v3 file) between the probe's open and its lock +// is still reported held, never unheld. +func TestProbeVolumeUnheldDecidesOnTheOpenedFile(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("an open file cannot be renamed over on Windows") + } + path := createClosedV3Volume(t) + s, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + junk := filepath.Join(filepath.Dir(path), "junk.bin") + if err := os.WriteFile(junk, make([]byte, 64<<10), 0o644); err != nil { + t.Fatal(err) + } + replaced := false + testProbeUnheldAfterOpen = func() { + replaced = os.Rename(junk, path) == nil + } + t.Cleanup(func() { testProbeUnheldAfterOpen = nil }) + err = ProbeVolumeUnheld(path) + if !replaced { + t.Fatal("fixture: the path was not replaced after the open") + } + if !errors.Is(err, ErrVolumeHeld) { + t.Fatalf("held volume replaced at its path mid-probe: %v; want ErrVolumeHeld", err) + } +} diff --git a/seaweed-block/core/storage/wal_admission.go b/seaweed-block/core/storage/wal_admission.go index 8302bdc5fd..26be803ba1 100644 --- a/seaweed-block/core/storage/wal_admission.go +++ b/seaweed-block/core/storage/wal_admission.go @@ -1,6 +1,7 @@ package storage import ( + "context" "errors" "fmt" "sync/atomic" @@ -96,27 +97,57 @@ func (a *walAdmission) HardMark() float64 { return a.hardMark } // expires. Returns errWALFull on timeout, errVolumeClosed if the // store closes during the wait. func (a *walAdmission) Acquire(timeout time.Duration) error { + return a.acquireContext(context.Background(), timeout, nil) +} + +func (a *walAdmission) acquireContext(ctx context.Context, timeout time.Duration, sample func() (float64, error)) error { + contextual := sample != nil + if sample == nil { + sample = func() (float64, error) { return a.walUsed(), nil } + } + if err := ctx.Err(); err != nil { + if fault := a.terminalFault(); fault != nil { + return fault + } + return admissionContextError(err) + } deadline := time.NewTimer(timeout) defer deadline.Stop() - pressure := a.walUsed() + pressure, err := sample() + if err != nil { + return err + } // Hard watermark: wait for flusher to drain before competing // for the semaphore. if pressure >= a.hardMark { a.notifyFn() hardStart := time.Now() - for a.walUsed() >= a.hardMark { + 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 a.closedFn() { + 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()) if err := a.terminalFault(); err != nil { @@ -157,16 +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: if err := a.terminalFault(); err != nil { return err } return ErrWALPressureTimeout case <-closeTick.C: + if contextual { + if _, err := sample(); err != nil { + return err + } + } if err := a.terminalFault(); err != nil { return err } - if a.closedFn() { + if !contextual && a.closedFn() { return errVolumeClosed } } @@ -184,3 +225,10 @@ func (a *walAdmission) terminalFault() error { } 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 index 2f1aaf023a..fe85a7181e 100644 --- a/seaweed-block/core/storage/wal_admission_fault_v3_test.go +++ b/seaweed-block/core/storage/wal_admission_fault_v3_test.go @@ -85,12 +85,13 @@ func TestWALStoreV3AdmissionReturnsFaultWhileWaitingForWriterSlot(t *testing.T) var once sync.Once release := func() { once.Do(func() { close(resume) }) } t.Cleanup(release) - sample := s.admission.walUsed - s.admission.walUsed = func() float64 { - used := sample() // its store/descriptor/writer locks have all released - close(entered) + 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 used + return s.stickyIOFault() } done := make(chan error, 1) go func() { _, err := s.Write(0, blk(1)); done <- err }() diff --git a/seaweed-block/core/storage/wal_io_v3.go b/seaweed-block/core/storage/wal_io_v3.go index 59a05ffd2c..f89e568695 100644 --- a/seaweed-block/core/storage/wal_io_v3.go +++ b/seaweed-block/core/storage/wal_io_v3.go @@ -62,7 +62,11 @@ func newWALWriterV3(fd *os.File, pub *descriptorPublisherV3) (*walWriterV3, erro return &walWriterV3{pub: pub, nonce: d.Nonce, head: d.RetainedHead, highestLSN: max(d.CheckpointLSN, d.BaseLSN), writeAt: fd.WriteAt}, nil } -func (w *walWriterV3) append(e walEntryV3, durableLSN uint64) (uint64, error) { +// 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() @@ -148,6 +152,11 @@ func (w *walWriterV3) append(e walEntryV3, durableLSN uint64) (uint64, error) { } 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 diff --git a/seaweed-block/core/storage/wal_io_v3_test.go b/seaweed-block/core/storage/wal_io_v3_test.go index b113a13bf5..1190ff70a1 100644 --- a/seaweed-block/core/storage/wal_io_v3_test.go +++ b/seaweed-block/core/storage/wal_io_v3_test.go @@ -77,7 +77,7 @@ func TestWALIOV3_RealWriterReopenScan(t *testing.T) { // Caller binding fields are overwritten, not trusted. e.Nonce = [16]byte{0xFF} e.LogicalStart = 999 - if _, err := w.append(e, i-1); err != nil { + if _, err := w.append(e, i-1, nil); err != nil { t.Fatal(err) } } @@ -116,7 +116,7 @@ func TestWALIOV3_WrapPaddingAndSlack(t *testing.T) { 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); err != nil { + 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 { @@ -187,7 +187,7 @@ func TestWALIOV3_InstalledScanBeginsAtMaxTail(t *testing.T) { d.CheckpointLSN = 5 d.W = 5 d.MapCoveredCheckpoint = 5 - if _, err := w.append(walEntryV3{LSN: 6, Type: walEntryBarrier}, 5); err != nil { + if _, err := w.append(walEntryV3{LSN: 6, Type: walEntryBarrier}, 5, nil); err != nil { t.Fatal(err) } r, err := scanWALV3(f, d) @@ -207,20 +207,20 @@ func TestWALIOV3_ValidatedFrontierIntervals(t *testing.T) { d.BaseState = BaseInstalling d.BaseInstallID = [16]byte{1} d.BaseLSN = 100 - if _, err := w.append(walEntryV3{LSN: 102, Type: walEntryBarrier}, 100); err != nil { + 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); !errors.Is(err, ErrWALLSNOrder) { + 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); err != nil { + 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); !errors.Is(err, ErrWALLSNOrder) { + 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) @@ -236,7 +236,7 @@ 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); !errors.Is(err, errWALFull) { + 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 { @@ -245,7 +245,7 @@ func TestWALIOV3_FloorAndPwriteFailureRefuse(t *testing.T) { 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); !errors.Is(err, errWALFull) { + 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 { @@ -253,10 +253,10 @@ func TestWALIOV3_FloorAndPwriteFailureRefuse(t *testing.T) { } 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); !errors.Is(err, errWALPwrite) { + 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); !errors.Is(err, errWALPwrite) || calls != 1 { + 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") } } @@ -270,7 +270,7 @@ func TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned(t *testing.T) { } 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); err != nil { + 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) @@ -288,7 +288,7 @@ func TestWALIOV3_ConcurrentAppendsHaveUniqueCursors(t *testing.T) { 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); done <- err }() + go func() { _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); done <- err }() } deadline := time.NewTimer(5 * time.Second) defer deadline.Stop() @@ -310,7 +310,7 @@ func TestWALIOV3_ConcurrentAppendsHaveUniqueCursors(t *testing.T) { } // 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); err != nil { + if _, err := w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 0, nil); err != nil { t.Fatal(err) } } @@ -327,7 +327,7 @@ 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); !errors.Is(err, ErrCounterExhausted) || calls != 0 { + 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) } } @@ -347,7 +347,7 @@ 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); err != nil { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); err != nil { t.Fatal(err) } r, err := scanWALV3(f, d) @@ -357,14 +357,14 @@ func TestWALIOV3_LastRepresentableRecordStillRecovers(t *testing.T) { 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); !errors.Is(err, ErrCounterExhausted) { + 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); err != nil { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); err != nil { t.Fatal(err) } r, err := scanWALV3(f, p.current()) @@ -420,7 +420,7 @@ func TestWALIOV3_UncertainPublisherStopsExistingAndNewWriters(t *testing.T) { } 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); err == nil { + if _, err := w.append(walEntryV3{LSN: 1, Type: walEntryBarrier}, 0, nil); err == nil { t.Fatal("existing writer accepted uncertain publication") } if writes != 0 { diff --git a/seaweed-block/core/storage/wal_lsn_order_v3_test.go b/seaweed-block/core/storage/wal_lsn_order_v3_test.go index fa5dfaf3a1..174a3bb624 100644 --- a/seaweed-block/core/storage/wal_lsn_order_v3_test.go +++ b/seaweed-block/core/storage/wal_lsn_order_v3_test.go @@ -10,7 +10,7 @@ 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); e != nil { + if _, e := w.append(walEntryV3{LSN: 10, Type: walEntryBarrier}, 0, nil); e != nil { t.Fatal(e) } before := make([]byte, p.current().WALSize) @@ -18,7 +18,7 @@ func TestWALLSNOrderV3_RefusesDuplicateAndLower(t *testing.T) { t.Fatal(e) } head := w.logicalHeadV3() - if _, e := w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 0); !errors.Is(e, ErrWALLSNOrder) { + 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)) @@ -34,13 +34,13 @@ func TestWALLSNOrderV3_RefusesDuplicateAndLower(t *testing.T) { 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); e != nil { + 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); !errors.Is(e, ErrWALLSNOrder) { + 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); e != nil { + if _, e := w.append(walEntryV3{LSN: 12, Type: walEntryBarrier}, 0, nil); e != nil { t.Fatal(e) } } @@ -56,7 +56,7 @@ func TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier(t *testing.T) { t.Fatal(e) } for _, lsn := range []uint64{101, 104} { - if _, e = w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 100); e != nil { + if _, e = w.append(walEntryV3{LSN: lsn, Type: walEntryBarrier}, 100, nil); e != nil { t.Fatal(e) } } @@ -80,10 +80,10 @@ func TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier(t *testing.T) { if e = recovered.restoreScanV3(r); e != nil { t.Fatal(e) } - if _, e = recovered.append(walEntryV3{LSN: 101, Type: walEntryBarrier}, 100); !errors.Is(e, ErrWALLSNOrder) { + 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); e != nil { + if _, e = recovered.append(walEntryV3{LSN: 102, Type: walEntryBarrier}, 100, nil); e != nil { t.Fatalf("dropped104 pinned next102: %v", e) } } @@ -99,10 +99,10 @@ func TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed(t *testing.T) { if e != nil { t.Fatal(e) } - if _, e = w.append(walEntryV3{LSN: 100, Type: walEntryBarrier}, 100); !errors.Is(e, ErrWALLSNOrder) { + 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); e != nil { + 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 d2b84e21ae..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" @@ -757,7 +758,14 @@ func (s *WALStore) Recover() (frontier uint64, err 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() if err := s.stickyIOFault(); err != nil { return 0, err @@ -774,11 +782,20 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { // admission Acquire may block up to admissionTimeout — under // hard pressure it spins waiting for the flusher to drain. s.beforeChunkMutation(uint64(lba), 1) - s.lifecycleMu.RLock() + 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() @@ -788,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() @@ -800,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{ @@ -813,7 +834,7 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { var walRelOff uint64 var err error if s.v3 != nil { - walRelOff, err = s.appendWriteV3(lba, data, lsn) + walRelOff, err = s.appendWriteV3(lba, data, lsn, func() error { return s.writeBudgetError(ctx, deadline) }) } else { walRelOff, err = s.wal.append(entry) } @@ -844,7 +865,14 @@ 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() if err := s.stickyIOFault(); err != nil { return nil, err @@ -863,11 +891,20 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error } s.beforeChunkMutation(uint64(startLBA), uint64(len(blocks))) - s.lifecycleMu.RLock() + 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() @@ -877,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() @@ -887,9 +924,13 @@ 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) + lsns, err := s.writeBatchV3Locked(startLBA, blocks, firstLSN, func() error { return s.writeBudgetError(ctx, deadline) }) s.mu.Unlock() return lsns, err } @@ -1005,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) @@ -1021,12 +1073,12 @@ func (s *WALStore) Read(lba uint32) ([]byte, error) { if data, handled, err := s.readDirtyV3(lba); handled { return data, err } - return s.readFromExtent(lba) + 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 @@ -1088,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 } @@ -1109,6 +1173,9 @@ func (s *WALStore) readFromExtent(lba uint32) ([]byte, error) { return s.readFromWAL(walRelOff, dataOffset) } } + if err := ctx.Err(); err != nil { + return nil, hydrationPending(err) + } return s.readExtentBlock(lba) } @@ -1530,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) { @@ -1545,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. diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index 568eefa2fe..ee902f622d 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -7,6 +7,8 @@ package storage // 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) { @@ -33,9 +35,11 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati if prior == nil || prior.owner != v.ownedMap || domain != v.mapProof { v.pub.descMu.Unlock() s.mu.RUnlock() - return nil, ErrMapCoverageStale + 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() @@ -44,7 +48,8 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati return nil, err } if !proof.validV3(domain) { - return nil, ErrMapCoverageStale + v.ownedMap.abandonCandidateV3(c) // prepared but never publishable + return nil, mapCoverageRefusal("proof_changed_during_prepare") } return &preparedMapPublicationV3{candidate: c, proof: proof}, nil } @@ -69,7 +74,7 @@ func (s *WALStore) persistOwnedMapCheckpointV3(highestLSN, recoveryGen uint64) e s.mu.Lock() defer s.mu.Unlock() if !v.flushLifetimeValidV3(recoveryGen) { - return ErrMapCoverageStale + return mapCoverageRefusal("recovery_lifetime_changed") } return s.rolloverCheckpointV3Locked() } @@ -116,14 +121,16 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) // 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) { - return descriptorV3{}, ErrMapCoverageStale + prepared.abandonV3() + return descriptorV3{}, mapCoverageRefusal("recovery_lifetime_changed") } wack := v.wack.Load() if seed { wack = max(wack, cp) } if wack < cp { - return descriptorV3{}, ErrMapCoverageStale + prepared.abandonV3() + return descriptorV3{}, mapCoverageRefusal("checkpoint_above_wack") } s.mu.RLock() retention := s.recoveryRetentionLSNs diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go index b479497f55..27bba23235 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3_test.go @@ -144,8 +144,10 @@ func TestWALStoreV3_PreparedCheckpointRefusesChangedProof(t *testing.T) { release() select { case err := <-done: - if !errors.Is(err, ErrMapCoverageStale) { + 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") @@ -156,8 +158,10 @@ func TestWALStoreV3_PreparedCheckpointRefusesChangedProof(t *testing.T) { t.Fatal("flusher result without join") } s.v3.testMapPrepared = nil - if s.v3.pub.current() != before { + 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") diff --git a/seaweed-block/core/storage/walstore_noflush_pressure_v3_test.go b/seaweed-block/core/storage/walstore_noflush_pressure_v3_test.go index ae079f7e96..b525470054 100644 --- a/seaweed-block/core/storage/walstore_noflush_pressure_v3_test.go +++ b/seaweed-block/core/storage/walstore_noflush_pressure_v3_test.go @@ -29,9 +29,48 @@ func TestWALStoreV3NoClientSyncSixRings(t *testing.T) { if s.admissionTimeout >= 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++ { - if _, err := s.Write(i, blk(byte(i+1))); err != nil { - t.Fatalf("no-client-Sync write %d/%d: %v", i, count, err) + 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++ { @@ -40,6 +79,7 @@ func TestWALStoreV3NoClientSyncSixRings(t *testing.T) { 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) }) } } 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_v3.go b/seaweed-block/core/storage/walstore_v3.go index ea7f8d68fd..8e50399835 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -81,7 +81,10 @@ type walStoreV3State struct { testRecoverHold func() testBatchBeforeAck func() testSyncBeforeCompletion func() - testMapPrepared func() // outside all publication locks, after owned-map persistence + // 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() @@ -165,14 +168,19 @@ func ProbeWALStoreV3(path string) error { 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 := f.ReadAt(a, 0); err != nil { + if _, err := r.ReadAt(a, 0); err != nil { return err } - if _, err := f.ReadAt(b, slotBOffsetV3); err != nil { + if _, err := r.ReadAt(b, slotBOffsetV3); err != nil { return err } - _, _, err = selectSlotV3(a, b, nil) + _, _, err := selectSlotV3(a, b, nil) return err } @@ -649,22 +657,27 @@ func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset u // 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. -func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, error) { +// 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 } - // Reserve proof invalidation before the WAL can change. This is under - // the existing store lock; a refused append only causes conservative retry. - if s.v3.mapProof != nil { - if err := s.v3.mapProof.mutatedV3(); err != nil { - return 0, err - } + // 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 } - phys, err := s.v3.w.append(e, s.v3.wack.Load()) + 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) @@ -682,10 +695,10 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, e // 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) ([]uint64, error) { +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) + phys, err := s.appendWriteV3(startLBA, blocks[0], firstLSN, budget) s.instr.appendLatency.Observe(time.Since(start)) s.walMutation.Add(1) if err != nil { @@ -710,16 +723,17 @@ func (s *WALStore) writeBatchV3Locked(startLBA uint32, blocks [][]byte, firstLSN s.instr.recordWALCopy(len(payload), time.Since(copyStart)) n := uint64(len(blocks)) lastLSN := firstLSN + n - 1 - if s.v3.mapProof != nil { - if err := s.v3.mapProof.mutatedV3(); err != nil { - return nil, err - } + 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 } - phys, err := s.v3.w.append(e, s.v3.wack.Load()) + 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 { @@ -1094,7 +1108,7 @@ func (f *flusher) readDirtyRecordV3Cached(e snapshotEntry, cache *flushRecordCac store := f.store d := store.v3.pub.current() if cache != nil && !store.v3.flushLifetimeValidV3(cache.recoveryGen) { - return nil, 0, ErrMapCoverageStale + return nil, 0, mapCoverageRefusal("recovery_lifetime_changed") } var entry walEntryV3 var size uint64 @@ -1163,7 +1177,7 @@ func (s *WALStore) persistCheckpointV3(highestLSN, recoveryGen uint64) error { v.syncMu.Lock() defer v.syncMu.Unlock() if !v.flushLifetimeValidV3(recoveryGen) { - return ErrMapCoverageStale + return mapCoverageRefusal("recovery_lifetime_changed") } wack := v.wack.Load() if wack < checkpoint { @@ -1182,3 +1196,15 @@ func (s *WALStore) persistCheckpointV3(highestLSN, recoveryGen uint64) error { 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/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/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/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 48b9ca7a58..1b8b2a9554 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -51,6 +51,8 @@ flowchart LR 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. @@ -133,7 +135,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto `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 it does 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`). +**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) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6ee4916e12..0f0bc7958d 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -63,7 +63,7 @@ stateDiagram-v2 | 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 `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. +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`). @@ -93,6 +93,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | 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` | @@ -176,6 +177,7 @@ stateDiagram-v2 | 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 @@ -287,9 +289,11 @@ snapshot lifetime; local persistence does not bypass it. `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. -- The v3 pressure admission budget is four seconds of cooperative waiting. It - cannot preempt a blocking occupancy/closed callback, lock acquisition or - physical file I/O. An unresolved pin or local stall returns +- 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 @@ -304,7 +308,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 new. +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. @@ -312,8 +316,10 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | 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 | @@ -330,14 +336,14 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `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. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire` | `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-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`, `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-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. Append-only retention preserves both slots and pending candidates. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `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-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 | @@ -346,7 +352,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `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` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `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 | @@ -355,9 +361,9 @@ 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. Writes invalidate proofs before append and update per-chunk max LSN under store.mu, while Recover rebuilds that 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-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. No sidecar page reclamation is implemented, so fallback or uncertain generations remain pinned conservatively. +- `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. @@ -435,13 +441,17 @@ Notes: | `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: