diff --git a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go index b964b0ced5..910d5408b3 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -3,6 +3,7 @@ package storage import ( "bytes" "errors" + "path/filepath" "testing" ) @@ -19,6 +20,7 @@ func TestChunkLayerV3_CheckpointProgressUnderContinuousAppends(t *testing.T) { 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 { @@ -41,6 +43,11 @@ func TestChunkLayerV3_CheckpointProgressUnderContinuousAppends(t *testing.T) { 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) } @@ -147,3 +154,175 @@ func TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend(t *testing.T) { } } } + +// 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) + for cycle := 0; cycle < 8; cycle++ { + for s.walUsedFraction() < 0.72 { + if _, err := s.Write(uint32(s.NextLSN()%64), blk(byte(s.NextLSN()))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + injected := false + s.v3.ownedMap.syncFile = func() error { + if !injected { + injected = true + if _, err := s.Write(uint32(s.NextLSN()%64), blk(byte(s.NextLSN()))); 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) + } + t.Logf("cycles8 checkpoint%d floor%d busy0", previousCP, floor) + }) + } +} diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index 029d0ba210..3b9fe9aca1 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -36,6 +36,8 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati return nil, ErrMapCoverageStale } proof := domain.snapshotV3() + // Entries may already contain LSNs above cp 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() diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 624b409247..aef36d1bbf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -355,7 +355,7 @@ 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. 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. Effective BASE/UNKNOWN changes and lifecycle boundaries still invalidate proofs. 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-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 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. Effective BASE/UNKNOWN changes and lifecycle boundaries still invalidate proofs. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. - `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests.