From 87c17dbb8b237de7e5397b0b9a1c6f0e7fb8d56a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 20:25:08 -0800 Subject: [PATCH] Freeze owned map entry snapshots without copying the live vector --- seaweed-block/core/storage/base_install_v3.go | 4 +- .../core/storage/base_install_v3_test.go | 2 +- .../checkpoint_append_progress_v3_test.go | 12 +- .../core/storage/chunk_birth_export_test.go | 4 +- .../storage/chunk_compare_progress_test.go | 3 +- seaweed-block/core/storage/chunk_coverage.go | 14 +- .../core/storage/chunk_coverage_map.go | 7 +- .../core/storage/chunk_fresh_known_zero.go | 6 +- seaweed-block/core/storage/chunk_layer.go | 10 +- .../core/storage/chunk_layer_map_v3.go | 14 +- .../core/storage/chunk_local_mutation.go | 8 +- .../core/storage/chunk_lsn_map_v3.go | 43 ++++-- .../core/storage/chunk_map_extents_v3_test.go | 6 +- .../core/storage/chunk_map_publication_v3.go | 5 +- seaweed-block/core/storage/chunk_recency.go | 2 +- .../core/storage/chunk_recency_budget_test.go | 7 +- .../core/storage/chunk_record_upgrade_test.go | 2 +- .../map_checkpoint_changed_pages_test.go | 139 ++++++++++++++++++ .../core/storage/map_entry_builder.go | 87 +++++++++++ .../core/storage/map_entry_snapshot.go | 71 ++++++++- .../core/storage/recovery_progress_test.go | 4 +- .../core/storage/walstore_activation_test.go | 2 +- .../core/storage/walstore_batch_v3_test.go | 2 +- .../storage/walstore_map_checkpoint_v3.go | 24 +-- seaweed-block/core/storage/walstore_v3.go | 8 +- seaweed-block/docs/design/invariants.md | 2 +- .../docs/design/map-checkpoint-cost.md | 2 +- 27 files changed, 400 insertions(+), 90 deletions(-) create mode 100644 seaweed-block/core/storage/map_entry_builder.go diff --git a/seaweed-block/core/storage/base_install_v3.go b/seaweed-block/core/storage/base_install_v3.go index 5f9d8d2188..4a9767ac9c 100644 --- a/seaweed-block/core/storage/base_install_v3.go +++ b/seaweed-block/core/storage/base_install_v3.go @@ -645,7 +645,8 @@ func (s *WALStore) markMapUnknownV3(lba uint64) { if v.ownedMap == nil { return } - e := &v.mapEntries[lba/v.ownedMap.chunkBlocks] + index := int(lba / v.ownedMap.chunkBlocks) + e := v.mapEntries.at(index) e.Unknown = true // A BASE byte has no WAL record: inherit its image frontier, not an // unrelated later write. Keep UNKNOWN conservative as before. @@ -654,6 +655,7 @@ func (s *WALStore) markMapUnknownV3(lba uint64) { birth = d.BaseLSN } e.LSN = max(e.LSN, birth) + v.mapEntries.set(index, e) } // InstalledBaseLSN reports a completed local BASE obligation, not a normal diff --git a/seaweed-block/core/storage/base_install_v3_test.go b/seaweed-block/core/storage/base_install_v3_test.go index 43e2ddf6e6..89ccb1ebcf 100644 --- a/seaweed-block/core/storage/base_install_v3_test.go +++ b/seaweed-block/core/storage/base_install_v3_test.go @@ -422,7 +422,7 @@ func TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites(t *testing.T) { s.DisableAutoFlushForRecoveryTest() writeSynced(t, s, 1, 1) s.mu.Lock() - s.v3.mapEntries[2] = chunkLSNEntryV3{} + s.v3.mapEntries.set(2, chunkLSNEntryV3{}) s.mu.Unlock() if err := s.flusher.flushOnceInternal(false); err != nil { t.Fatal(err) 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 78ff83eac9..2a109850fc 100644 --- a/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go +++ b/seaweed-block/core/storage/checkpoint_append_progress_v3_test.go @@ -479,7 +479,7 @@ func TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix(t *testing.T) { if _, err := layer.Cut(ctTimeout(t)); err != nil { t.Fatal(err) } - if s.v3.mapEntries[0].Unknown { + if s.v3.mapEntries.at(int(0)).Unknown { t.Fatal("setup: initial definite cut did not clear UNKNOWN") } if _, err := s.Write(1, blk(0xA2)); err != nil { @@ -517,7 +517,7 @@ func TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix(t *testing.T) { if _, err := r.Recover(); err != nil { t.Fatal(err) } - if r.NextLSN() != 2 || r.v3.mapEntries[0].LSN != 3 { + if r.NextLSN() != 2 || r.v3.mapEntries.at(int(0)).LSN != 3 { t.Fatal("dropped suffix did not leave the conservative persisted maximum") } held, err := r.prepareOwnedMapCheckpointV3(1) @@ -530,7 +530,7 @@ func TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix(t *testing.T) { 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 { + if !r.v3.mapEntries.at(int(0)).Unknown || r.v3.mapEntries.at(int(0)).LSN != 3 { t.Fatal("reused LSN did not conservatively set UNKNOWN beneath the high maximum") } if !held.proof.validV3(r.v3.mapProof) { @@ -555,7 +555,7 @@ func TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix(t *testing.T) { if _, err := r2.Recover(); err != nil { t.Fatal(err) } - if !r2.v3.mapEntries[0].Unknown || !bytes.Equal(readV3(t, r2, 1), blk(0xB2)) { + if !r2.v3.mapEntries.at(int(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)) @@ -686,13 +686,13 @@ func TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof(t *testing.T) { if err != nil { t.Fatal(err) } - if !s.v3.mapEntries[0].Unknown { + if !s.v3.mapEntries.at(int(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 { + if s.v3.mapEntries.at(int(0)).Unknown { t.Fatal("definite cut did not clear UNKNOWN") } // Inspect the proof itself so the newer map generation cannot mask a missing diff --git a/seaweed-block/core/storage/chunk_birth_export_test.go b/seaweed-block/core/storage/chunk_birth_export_test.go index 8c5561b6bf..1c2c740886 100644 --- a/seaweed-block/core/storage/chunk_birth_export_test.go +++ b/seaweed-block/core/storage/chunk_birth_export_test.go @@ -61,7 +61,7 @@ func DroppedSuffixBirthStoreForTest(t *testing.T, remote ChunkRemote) *WALStore return r } r := reopen() - if r.NextLSN() != 2 || r.v3.mapEntries[0].LSN != 3 { + if r.NextLSN() != 2 || r.v3.mapEntries.at(int(0)).LSN != 3 { t.Fatal("missing conservative maximum after dropped suffix") } if n, err := r.Write(1, blk(0xB2)); err != nil || n != 2 { @@ -75,7 +75,7 @@ func DroppedSuffixBirthStoreForTest(t *testing.T, remote ChunkRemote) *WALStore 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)) { + if e := r2.v3.mapEntries.at(int(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_compare_progress_test.go b/seaweed-block/core/storage/chunk_compare_progress_test.go index 794146965c..dcd2eccd84 100644 --- a/seaweed-block/core/storage/chunk_compare_progress_test.go +++ b/seaweed-block/core/storage/chunk_compare_progress_test.go @@ -66,7 +66,8 @@ func TestFilledChunksAreFirstCutCandidatesAfterARestart(t *testing.T) { l2.stMu.Unlock() unknown := 0 s2.mu.RLock() - for _, e := range s2.v3.mapEntries { + for entryIndex := 0; entryIndex < s2.v3.mapEntries.len(); entryIndex++ { + e := s2.v3.mapEntries.at(entryIndex) if e.Unknown { unknown++ } diff --git a/seaweed-block/core/storage/chunk_coverage.go b/seaweed-block/core/storage/chunk_coverage.go index c7c9ebe932..08e42c73d3 100644 --- a/seaweed-block/core/storage/chunk_coverage.go +++ b/seaweed-block/core/storage/chunk_coverage.go @@ -58,13 +58,13 @@ type chunkCoverageSnapshot struct { } func (v chunkCoverageSnapshot) Coverage(chunk uint64) (LocalCoverage, uint64, error) { - return coverageObservation(v.entries, chunk, v.position) + return coverageObservation(flatMapEntries(v.entries), chunk, v.position) } -func coverageObservation(entries []chunkLSNEntryV3, chunk, position uint64) (LocalCoverage, uint64, error) { - if chunk >= uint64(len(entries)) { +func coverageObservation(entries mapEntryReader, chunk, position uint64) (LocalCoverage, uint64, error) { + if chunk >= uint64(entries.len()) { return CoverageNone, 0, fmt.Errorf("storage: chunk %d out of range", chunk) } - e := entries[chunk] + e := entries.at(int(chunk)) if e.LSN > position { return CoverageNone, 0, mapCoverageRefusal("coverage_position_ahead_of_recovery") } @@ -161,7 +161,7 @@ func (s *WALStore) InitializeChunkCoverage(ctx context.Context, epoch uint64, se return fmt.Errorf("%w: initialize coverage after recovery and Sync", ErrMapCoverageStale) } if current.MapFormatID == mapFormatIDCoverage && current.LocalWorkEpoch == epoch { - view := chunkCoverageSnapshot{entries: append([]chunkLSNEntryV3(nil), v.mapEntries...), position: position} + view := chunkCoverageSnapshot{entries: v.mapEntries.all(), position: position} s.mu.RUnlock() if err := preparePages(view); err != nil { return err @@ -175,7 +175,7 @@ func (s *WALStore) InitializeChunkCoverage(ctx context.Context, epoch uint64, se defer s.mu.Unlock() return s.finishCoverageFenceLocked(epoch) } - entries := append([]chunkLSNEntryV3(nil), v.mapEntries...) + entries := v.mapEntries.all() v.pub.descMu.Lock() prior, domain := v.pub.mapCurrent, v.pub.mapDomain proof := domain.snapshotV3() @@ -246,7 +246,7 @@ func (s *WALStore) InitializeChunkCoverage(ctx context.Context, epoch uint64, se if err != nil { return err } - v.mapEntries = entries + v.mapEntries = newLiveMapEntries(entries, candidate.entries) return s.finishCoverageFenceLocked(epoch) } diff --git a/seaweed-block/core/storage/chunk_coverage_map.go b/seaweed-block/core/storage/chunk_coverage_map.go index 4ce5e55221..de5693c976 100644 --- a/seaweed-block/core/storage/chunk_coverage_map.go +++ b/seaweed-block/core/storage/chunk_coverage_map.go @@ -148,8 +148,11 @@ func coverageByte(e chunkLSNEntryV3, offset uint64) byte { return out } func encodeCoverageMapPageV3(d descriptorV3, g, page, cb uint64, entries []chunkLSNEntryV3, zeroPosition uint64) ([]byte, error) { + return encodeCoverageMapPageSourceV3(d, g, page, cb, flatMapEntries(entries), zeroPosition) +} +func encodeCoverageMapPageSourceV3(d descriptorV3, g, page, cb uint64, entries mapEntrySource, zeroPosition uint64) ([]byte, error) { shape, err := mapShapeForV3(d, cb) - if err != nil || g == 0 || g > counterMaxV3 || page >= shape.pages || uint64(len(entries)) != shape.chunks { + if err != nil || g == 0 || g > counterMaxV3 || page >= shape.pages || uint64(entries.len()) != shape.chunks { return nil, ErrMapInvalid } width, _ := coverageEntryBytes(cb) @@ -165,7 +168,7 @@ func encodeCoverageMapPageV3(d descriptorV3, g, page, cb uint64, entries []chunk le.PutUint32(b[56:], uint32(end-start)) zero := true for at := start; at < end; at++ { - e := entries[at/width] + e := entries.at(int(at / width)) if e.Local == nil { return nil, ErrChunkCoverageUnavailable } diff --git a/seaweed-block/core/storage/chunk_fresh_known_zero.go b/seaweed-block/core/storage/chunk_fresh_known_zero.go index 7b88d65e77..9f57e2b4f6 100644 --- a/seaweed-block/core/storage/chunk_fresh_known_zero.go +++ b/seaweed-block/core/storage/chunk_fresh_known_zero.go @@ -30,12 +30,12 @@ func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uin s.mu.RLock() defer s.mu.RUnlock() out := map[uint64]uint64{} - for idx := uint64(0); idx < l.numChunks && idx < uint64(len(s.v3.mapEntries)); idx++ { + for idx := uint64(0); idx < l.numChunks && idx < uint64(s.v3.mapEntries.len()); idx++ { l.attachProgress.add(1) // attach only (its one caller): every inspected entry, candidate or not if _, named := head.Chunks[idx]; named { continue } - if e := s.v3.mapEntries[idx]; e.LSN != 0 || !e.Unknown { + if e := s.v3.mapEntries.at(int(idx)); e.LSN != 0 || !e.Unknown { continue } out[idx] = l.chunkVersion(idx) @@ -63,7 +63,7 @@ func (l *chunkLayerImpl) ApplyFreshKnownZero() { s.mu.RLock() certified := 0 for idx := range tokens { - if idx < uint64(len(s.v3.mapEntries)) && !s.v3.mapEntries[idx].Unknown { + if idx < uint64(s.v3.mapEntries.len()) && !s.v3.mapEntries.at(int(idx)).Unknown { certified++ } } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index b75c09ffea..33faac136d 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -154,7 +154,7 @@ type chunkLayerImpl struct { // captured version and hash, no bytes): the record's Commit for them // waits for the settlement that finds the proposal landed. pendingCaptured []capturedChunk - pendingCut chunkCutResult + pendingCut chunkCutResult // pendingBase is the version the unresolved CAS expected. While HEAD is // still at it, that CAS may still land, so a read alone never settles it. pendingBase chunkHeadVersion @@ -531,7 +531,8 @@ func (l *chunkLayerImpl) recoveredLocked(sh *chunkRecordShadow) { for idx := range wal { changed[idx] = true } - for idx, e := range l.s.v3.mapEntries { + for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ { + e := l.s.v3.mapEntries.at(idx) if e.LSN > base { changed[uint64(idx)] = true } @@ -610,7 +611,8 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { l.addOwnCandidatesLocked(out) l.stMu.Unlock() l.s.mu.RLock() - for idx, e := range l.s.v3.mapEntries { + for idx := 0; idx < l.s.v3.mapEntries.len(); idx++ { + e := l.s.v3.mapEntries.at(idx) i := uint64(idx) if !absent[i] && ((e.Unknown && !filled[i]) || e.LSN > base) { out[i] = true @@ -2031,7 +2033,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap l.s.mu.RLock() for idx := range need { - recent[idx] = l.s.v3.mapEntries[idx].LSN + recent[idx] = l.s.v3.mapEntries.at(int(idx)).LSN } l.s.mu.RUnlock() diff --git a/seaweed-block/core/storage/chunk_layer_map_v3.go b/seaweed-block/core/storage/chunk_layer_map_v3.go index 17177c3724..94740eee34 100644 --- a/seaweed-block/core/storage/chunk_layer_map_v3.go +++ b/seaweed-block/core/storage/chunk_layer_map_v3.go @@ -27,7 +27,7 @@ func (l *chunkLayerImpl) persistCapturedMapV3(versions map[uint64]uint64) { } var clear []uint64 for idx, version := range versions { - if idx < uint64(len(v.mapEntries)) && v.mapEntries[idx].Unknown && l.chunkVersion(idx) == version { + if idx < uint64(v.mapEntries.len()) && v.mapEntries.at(int(idx)).Unknown && l.chunkVersion(idx) == version { clear = append(clear, idx) } } @@ -37,18 +37,14 @@ func (l *chunkLayerImpl) persistCapturedMapV3(versions map[uint64]uint64) { return } for _, idx := range clear { - v.mapEntries[idx].Unknown = false + e := v.mapEntries.at(int(idx)) + e.Unknown = false + v.mapEntries.set(int(idx), e) } } v.pub.descMu.Lock() cp := v.pub.cur.CheckpointLSN - need := false - for i, e := range v.mapEntries { - if e != v.pub.mapCurrent.entries.at(i) { - need = true - break - } - } + need := v.mapEntries.view.entries.root != v.pub.mapCurrent.entries.root v.pub.descMu.Unlock() s.mu.Unlock() if !need { diff --git a/seaweed-block/core/storage/chunk_local_mutation.go b/seaweed-block/core/storage/chunk_local_mutation.go index b41d39352b..2ceb96b852 100644 --- a/seaweed-block/core/storage/chunk_local_mutation.go +++ b/seaweed-block/core/storage/chunk_local_mutation.go @@ -67,9 +67,9 @@ func (s *WALStore) publishChunksLocal(chunks []uint64, all bool) error { return ErrChunkCoverageUnavailable } for _, chunk := range chunks { - if chunk >= uint64(len(v.mapEntries)) { + if chunk >= uint64(v.mapEntries.len()) { s.mu.Unlock() - return &ChunkCoverageRangeError{Chunk: chunk, Chunks: uint64(len(v.mapEntries))} + return &ChunkCoverageRangeError{Chunk: chunk, Chunks: uint64(v.mapEntries.len())} } } if d.BaseState != BaseNone { @@ -87,7 +87,9 @@ func (s *WALStore) publishChunksLocal(chunks []uint64, all bool) error { blocks := min(cb, s.sb.VolumeSize/uint64(s.sb.BlockSize)-chunk*cb) bits = &chunkLocalBits{blocks: blocks, all: true} } - v.mapEntries[chunk].Local = bits + e := v.mapEntries.at(int(chunk)) + e.Local = bits + v.mapEntries.set(int(chunk), e) } proof := v.mapProof.snapshotV3() recoveryGen := v.recoverGen.Load() diff --git a/seaweed-block/core/storage/chunk_lsn_map_v3.go b/seaweed-block/core/storage/chunk_lsn_map_v3.go index 13b32cc9ca..de7e68495e 100644 --- a/seaweed-block/core/storage/chunk_lsn_map_v3.go +++ b/seaweed-block/core/storage/chunk_lsn_map_v3.go @@ -370,6 +370,9 @@ func (m *chunkLSNMapV3) Prepare(g, C uint64, entries []chunkLSNEntryV3, prior *c // 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) { + return m.prepareNextEntriesV3(C, flatMapEntries(entries), prior) +} +func (m *chunkLSNMapV3) prepareNextEntriesV3(C uint64, entries mapEntrySource, prior *chunkMapCandidateV3) (*chunkMapCandidateV3, error) { m.mu.Lock() defer m.mu.Unlock() if m.failed != nil { @@ -378,9 +381,12 @@ func (m *chunkLSNMapV3) prepareNextV3(C uint64, entries []chunkLSNEntryV3, prior if m.lastGeneration >= counterMaxV3 { return nil, ErrCounterExhausted } - return m.prepareLockedV3(m.lastGeneration+1, C, entries, prior) + return m.prepareEntriesLockedV3(m.lastGeneration+1, C, entries, prior) } func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3, formats ...coverageMapPreparation) (out *chunkMapCandidateV3, err error) { + return m.prepareEntriesLockedV3(g, C, flatMapEntries(entries), prior, formats...) +} +func (m *chunkLSNMapV3) prepareEntriesLockedV3(g, C uint64, entries mapEntrySource, prior *chunkMapCandidateV3, formats ...coverageMapPreparation) (out *chunkMapCandidateV3, err error) { if m.failed != nil { return nil, m.failed } @@ -401,17 +407,20 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, if g > counterMaxV3 || C > counterMaxV3 { return nil, ErrCounterExhausted } - if uint64(len(entries)) != s.chunks || g == 0 || g <= m.lastGeneration { + if uint64(entries.len()) != s.chunks || g == 0 || g <= m.lastGeneration { return nil, ErrMapInvalid } if prior != nil && (prior.owner != m || prior.generation >= g) { return nil, ErrMapInvalid } - // Validate every entry before any I/O. - for _, v := range entries { - if v.LSN > counterMaxV3 { - return nil, ErrCounterExhausted - } + previous := mapEntrySnapshot{} + if prior != nil { + previous = prior.entries + } + // Untrusted flat inputs validate every entry. An immutable snapshot only + // validates pages that differ from its already validated prior. + if err := entries.validate(previous); err != nil { + return nil, err } info, e := m.fd.Stat() if e != nil { @@ -491,10 +500,10 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, refs := make([]mapPageRefV3, s.pages) for j := uint64(0); j < s.pages; j++ { start, end := mapPageEntrySpanV3(identity, m.chunkBlocks, j, s.chunks) - same := prior != nil && prior.formatID() == identity.MapFormatID && prior.entries.len() == len(entries) + same := prior != nil && prior.formatID() == identity.MapFormatID && prior.entries.len() == entries.len() if same { for i := start; i < end; i++ { - if prior.entries.at(int(i)) != entries[i] { + if prior.entries.at(int(i)) != entries.at(int(i)) { same = false break } @@ -510,9 +519,15 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, var p []byte var e error if identity.MapFormatID == mapFormatIDCoverage { - p, e = encodeCoverageMapPageV3(identity, g, j, m.chunkBlocks, entries, zeroPosition) + p, e = encodeCoverageMapPageSourceV3(identity, g, j, m.chunkBlocks, entries, zeroPosition) } else { - p, e = encodeMapPageV3(identity, g, j, entries[start:end]) + if flat, ok := entries.(flatMapEntries); ok { + p, e = encodeMapPageV3(identity, g, j, flat[start:end]) + } else { + values := make([]chunkLSNEntryV3, end-start) + entries.copyInto(values, int(start)) + p, e = encodeMapPageV3(identity, g, j, values) + } } if e != nil { return nil, e @@ -550,11 +565,7 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, return nil, e } m.lastGeneration = g - previous := mapEntrySnapshot{} - if prior != nil { - previous = prior.entries - } - out = &chunkMapCandidateV3{owner: m, generation: g, covered: C, rootOffset: at, hash: mapDigestV3(mapRootDomainV3, root[:s.raw-32]), format: identity.MapFormatID, zeroPosition: zeroPosition, refs: refs, entries: snapshotMapEntries(entries, previous)} + out = &chunkMapCandidateV3{owner: m, generation: g, covered: C, rootOffset: at, hash: mapDigestV3(mapRootDomainV3, root[:s.raw-32]), format: identity.MapFormatID, zeroPosition: zeroPosition, refs: refs, entries: entries.snapshot(previous)} // The candidate is live (in flight) until a publication names it or // supersedes it. x := rootExtentsV3(at, s.aligned, refs) diff --git a/seaweed-block/core/storage/chunk_map_extents_v3_test.go b/seaweed-block/core/storage/chunk_map_extents_v3_test.go index 1267a93c31..81dfee6f3c 100644 --- a/seaweed-block/core/storage/chunk_map_extents_v3_test.go +++ b/seaweed-block/core/storage/chunk_map_extents_v3_test.go @@ -364,7 +364,7 @@ func TestChunkMapExtentsV3UncertainCandidateStaysPinned(t *testing.T) { 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 { + if _, err := m.prepareNextV3(cp, s.v3.mapEntries.all(), unc); err != nil { t.Fatalf("admitted prepare %d: %v", i, err) } } @@ -440,7 +440,7 @@ func TestChunkMapExtentsV3ProofStalePreparesStayBounded(t *testing.T) { g := s.v3.pub.current().MapGeneration for i := 0; i < 150; i++ { g += 1000 - entries := append([]chunkLSNEntryV3(nil), s.v3.mapEntries...) + entries := s.v3.mapEntries.all() _, 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" { @@ -494,7 +494,7 @@ func TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned(t *testing.T) 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 := s.v3.mapEntries.all() entries[0].LSN += uint64(i + 1) if _, err := m.prepareNextV3(cp, entries, prepared.candidate); err != nil { t.Fatalf("admitted prepare %d: %v", i, err) diff --git a/seaweed-block/core/storage/chunk_map_publication_v3.go b/seaweed-block/core/storage/chunk_map_publication_v3.go index 874b24b34c..61bfae9ebf 100644 --- a/seaweed-block/core/storage/chunk_map_publication_v3.go +++ b/seaweed-block/core/storage/chunk_map_publication_v3.go @@ -49,8 +49,9 @@ func (p mapPublicationProofV3) validV3(d *mapProofEpochV3) bool { } type preparedMapPublicationV3 struct { - candidate *chunkMapCandidateV3 - proof mapPublicationProofV3 + candidate *chunkMapCandidateV3 + proof mapPublicationProofV3 + entryCapturePages uint64 } // The caller supplies entries from its permitted mutation/version boundary. diff --git a/seaweed-block/core/storage/chunk_recency.go b/seaweed-block/core/storage/chunk_recency.go index e135373c3c..a8c95612dc 100644 --- a/seaweed-block/core/storage/chunk_recency.go +++ b/seaweed-block/core/storage/chunk_recency.go @@ -10,7 +10,7 @@ func (l *chunkLayerImpl) chunkRecency(candidates map[uint64]bool, frontier uint6 l.s.mu.RLock() defer l.s.mu.RUnlock() for idx := range candidates { - out[idx] = min(l.s.v3.mapEntries[idx].LSN, frontier) + out[idx] = min(l.s.v3.mapEntries.at(int(idx)).LSN, frontier) } return out } diff --git a/seaweed-block/core/storage/chunk_recency_budget_test.go b/seaweed-block/core/storage/chunk_recency_budget_test.go index fc75b2ec12..4759a2173d 100644 --- a/seaweed-block/core/storage/chunk_recency_budget_test.go +++ b/seaweed-block/core/storage/chunk_recency_budget_test.go @@ -10,11 +10,12 @@ import ( func BenchmarkChunkRecencyMaxVolumeDefaultChunk(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()}} + entries := make([]chunkLSNEntryV3, count) for i := uint64(0); i < count; i++ { candidates[i] = true - s.v3.mapEntries[i].LSN = i + 1 + entries[i].LSN = i + 1 } + s := &WALStore{v3: &walStoreV3State{mapEntries: newLiveMapEntries(entries, snapshotMapEntries(entries, mapEntrySnapshot{})), mapProof: newMapProofEpochV3()}} l := &chunkLayerImpl{s: s} b.ReportAllocs() b.ResetTimer() @@ -28,7 +29,7 @@ func BenchmarkChunkRecencyMaxVolumeDefaultChunk(b *testing.B) { } } func TestChunkRecencyIncludesStoreLockWait(t *testing.T) { - s := &WALStore{v3: &walStoreV3State{mapEntries: []chunkLSNEntryV3{{LSN: 7}}, mapProof: newMapProofEpochV3()}} + s := &WALStore{v3: &walStoreV3State{mapEntries: newLiveMapEntries([]chunkLSNEntryV3{{LSN: 7}}, snapshotMapEntries([]chunkLSNEntryV3{{LSN: 7}}, mapEntrySnapshot{})), mapProof: newMapProofEpochV3()}} l := &chunkLayerImpl{s: s} candidates := map[uint64]bool{0: true} s.mu.Lock() diff --git a/seaweed-block/core/storage/chunk_record_upgrade_test.go b/seaweed-block/core/storage/chunk_record_upgrade_test.go index 159bb14058..37f9f952c0 100644 --- a/seaweed-block/core/storage/chunk_record_upgrade_test.go +++ b/seaweed-block/core/storage/chunk_record_upgrade_test.go @@ -81,7 +81,7 @@ func checkLocalBits(t *testing.T, s *WALStore) { s.mu.RLock() defer s.mu.RUnlock() for c := uint64(0); c < 16; c++ { - e := s.v3.mapEntries[c] + e := s.v3.mapEntries.at(int(c)) if e.Local == nil { t.Fatalf("chunk %d has no bitmap", c) } diff --git a/seaweed-block/core/storage/map_checkpoint_changed_pages_test.go b/seaweed-block/core/storage/map_checkpoint_changed_pages_test.go index 9203d0df46..b1306be062 100644 --- a/seaweed-block/core/storage/map_checkpoint_changed_pages_test.go +++ b/seaweed-block/core/storage/map_checkpoint_changed_pages_test.go @@ -1,11 +1,57 @@ package storage import ( + "bytes" + "context" "path/filepath" "runtime" "testing" ) +func TestOwnedMapPreparationDoesNotCopyTheLiveEntryVector(t *testing.T) { + path := filepath.Join(t.TempDir(), "store") + // One 64-MiB store with one-block chunks gives a large entry vector + // without allocating a TiB-sized data file on the test host. + s, err := createMappedWALStoreV3ForTest(path, 16384, 4096, v3TestWAL, WModeStrict, 1) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 1, func(uint64, uint64) (ChunkCoverageSeed, error) { + return ChunkCoverageSeed{}, nil + }, coverageNoPages); err != nil { + t.Fatal(err) + } + if _, err := s.Write(0, blk(0x51)); err != nil { + t.Fatal(err) + } + runtime.GC() + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + prepared, err := s.prepareOwnedMapCheckpointV3(0) + runtime.ReadMemStats(&after) + if err != nil { + t.Fatal(err) + } + defer prepared.abandonV3() + if prepared.candidate.entries.at(0).LSN != 1 || !prepared.candidate.entries.at(0).Local.has(0) { + t.Fatal("owned capture lost the appended entry") + } + const bound = 128 << 10 + t.Logf("owned preparation allocated %d bytes", after.TotalAlloc-before.TotalAlloc) + if allocated := after.TotalAlloc - before.TotalAlloc; allocated > bound { + t.Fatalf("owned one-page preparation allocated %d bytes; %d excludes the full live entry vector", allocated, bound) + } + if prepared.entryCapturePages > 1 { + t.Fatalf("one changed entry page visited %d live entry pages during capture", prepared.entryCapturePages) + } +} + // This allocation bound is deliberately loose: one changed leaf and its // bounded-fanout ancestors fit well below it, whereas copying the 1-TiB // entry vector alone costs 6 MiB. It is a copy-cost control, not a CPU or @@ -108,3 +154,96 @@ func TestChunkMapEntrySnapshotsKeepOldValuesAcrossPageBoundaries(t *testing.T) { } } } + +// Capture, abandon and publication must never retire a later memory version. +func TestOwnedMapCandidatesFreezeCapturedVersions(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 1, func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil }, coverageNoPages); err != nil { + t.Fatal(err) + } + write := func(lba uint32, value byte) { + t.Helper() + if _, err := s.Write(lba, blk(value)); err != nil { + t.Fatal(err) + } + } + prepare := func() *preparedMapPublicationV3 { + t.Helper() + p, err := s.prepareOwnedMapCheckpointV3(0) + if err != nil { + t.Fatal(err) + } + t.Cleanup(p.abandonV3) + return p + } + check := func(p *preparedMapPublicationV3, position uint64, last uint64) { + t.Helper() + e := p.candidate.entries.at(0) + if e.LSN != position || !e.Local.has(last) || e.Local.has(last+1) { + t.Fatalf("candidate changed: pos=%d last=%d entry=%+v", position, last, e) + } + } + write(0, 0x51) + abandoned := prepare() + write(1, 0x52) + check(abandoned, 1, 0) + abandoned.abandonV3() + selected := prepare() + check(selected, 2, 1) + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, selected, nil); err != nil { + t.Fatal(err) + } + write(2, 0x53) + held := prepare() + write(3, 0x54) + check(held, 3, 2) + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, held, nil); err != nil { + t.Fatal(err) + } + latest := prepare() + check(latest, 4, 3) + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, latest, nil); 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() + r.HoldExtentDrainUntilChunkLayer() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + for lba := uint32(0); lba < 4; lba++ { + if got := readV3(t, r, lba); !bytes.Equal(got, blk(0x51+byte(lba))) { + t.Fatalf("replay lost bytes at %d", lba) + } + } + // Recovery creates a new mutable owner; it cannot alter the retired snapshots. + if _, err := r.Write(4, blk(0x55)); err != nil { + t.Fatal(err) + } + check(latest, 4, 3) +} + +func TestMapEntryOwnerRolloverKeepsOldSnapshots(t *testing.T) { + values := make([]chunkLSNEntryV3, 257) + b := newMapEntryBuilder(snapshotMapEntries(values, mapEntrySnapshot{})) + b.owner.generation = ^uint64(0) + old := b.capture() + b.set(128, chunkLSNEntryV3{LSN: 1}) + next := b.capture() + b.set(128, chunkLSNEntryV3{LSN: 2}) + if old.at(128).LSN != 0 || next.at(128).LSN != 1 || b.entries.at(128).LSN != 2 { + t.Fatal("owner rollover changed a frozen page") + } +} diff --git a/seaweed-block/core/storage/map_entry_builder.go b/seaweed-block/core/storage/map_entry_builder.go new file mode 100644 index 0000000000..bd1c344995 --- /dev/null +++ b/seaweed-block/core/storage/map_entry_builder.go @@ -0,0 +1,87 @@ +package storage + +import "context" + +// The live flat map remains the O(1) read surface. This cache mirrors its +// mutations under WALStore.mu and freezes an immutable root in constant work. +// After a capture, a first write copies its leaf/path; further writes before +// the next capture reuse those private pages. The selected disk root, never +// this cache's generation, decides which captured versions are durable. +type mapEntryOwner struct{ generation uint64 } +type mapEntryBuilder struct { + entries mapEntrySnapshot + owner *mapEntryOwner +} + +func newMapEntryBuilder(entries mapEntrySnapshot) mapEntryBuilder { + return mapEntryBuilder{entries: entries, owner: &mapEntryOwner{generation: 1}} +} + +func (b *mapEntryBuilder) capture() mapEntrySnapshot { + result := b.entries + result.visitedPages = 0 + if b.owner.generation == ^uint64(0) { + // A new private owner freezes every old page without wrapping a page's + // ownership identity. This counter has no durable meaning. + b.owner = &mapEntryOwner{generation: 1} + } else { + b.owner.generation++ + } + return result +} + +func (b *mapEntryBuilder) set(index int, value chunkLSNEntryV3) { + if b.entries.at(index) == value { + return + } + var update func(*mapEntryNode, uint) *mapEntryNode + update = func(n *mapEntryNode, depth uint) *mapEntryNode { + if n.owner != b.owner || n.generation != b.owner.generation { + copyNode := *n + copyNode.owner, copyNode.generation = b.owner, b.owner.generation + if depth == 0 { + copyNode.values = append([]chunkLSNEntryV3(nil), n.values...) + } else { + copyNode.children = new([mapEntryFanout]*mapEntryNode) + *copyNode.children = *n.children + } + n = ©Node + } + if depth == 0 { + n.values[index%mapEntryLeafSize] = value + } else { + page := uint(index / mapEntryLeafSize) + i := (page >> ((depth - 1) * mapEntryBranchBits)) & (mapEntryFanout - 1) + n.children[i] = update(n.children[i], depth-1) + } + return n + } + b.entries.root = update(b.entries.root, b.entries.depth) +} + +// One owner updates the O(1) live read vector and its COW view together. +// Callers cannot mutate entries by taking a pointer into the live vector. +// Every method is protected by the existing WALStore.mu. +type liveMapEntries struct { + values []chunkLSNEntryV3 + view mapEntryBuilder +} + +func newLiveMapEntries(values []chunkLSNEntryV3, snapshot mapEntrySnapshot) liveMapEntries { + return liveMapEntries{values: values, view: newMapEntryBuilder(snapshot)} +} +func (e liveMapEntries) len() int { return len(e.values) } +func (e liveMapEntries) at(i int) chunkLSNEntryV3 { return e.values[i] } +func (e liveMapEntries) all() []chunkLSNEntryV3 { return append([]chunkLSNEntryV3(nil), e.values...) } +func (e *liveMapEntries) set(i int, value chunkLSNEntryV3) { + e.view.set(i, value) + e.values[i] = value +} +func (e *liveMapEntries) capture() mapEntrySnapshot { return e.view.capture() } +func (e liveMapEntries) recover(ctx context.Context, phase RecoveryPhase, snapshot mapEntrySnapshot) (liveMapEntries, error) { + values, err := copyRecoverySnapshotPhase(ctx, phase, e.values, snapshot) + if err != nil { + return e, err + } + return newLiveMapEntries(values, snapshot), nil +} diff --git a/seaweed-block/core/storage/map_entry_snapshot.go b/seaweed-block/core/storage/map_entry_snapshot.go index cf00834dc8..8bc2b71a50 100644 --- a/seaweed-block/core/storage/map_entry_snapshot.go +++ b/seaweed-block/core/storage/map_entry_snapshot.go @@ -8,14 +8,73 @@ const mapEntryBranchBits = 6 const mapEntryFanout = 1 << mapEntryBranchBits type mapEntryNode struct { - children *[mapEntryFanout]*mapEntryNode - values []chunkLSNEntryV3 + children *[mapEntryFanout]*mapEntryNode + values []chunkLSNEntryV3 + owner *mapEntryOwner + generation uint64 } type mapEntrySnapshot struct { - root *mapEntryNode - count int - depth uint + root *mapEntryNode + count int + depth uint + visitedPages uint64 // work performed while capturing this snapshot +} + +// Raw slice callers require full input validation. The owned store supplies +// an immutable snapshot, so validated prior pages can be reused directly. +type mapEntryReader interface { + len() int + at(int) chunkLSNEntryV3 +} +type mapEntrySource interface { + mapEntryReader + copyInto([]chunkLSNEntryV3, int) + validate(mapEntrySnapshot) error + snapshot(mapEntrySnapshot) mapEntrySnapshot +} + +type flatMapEntries []chunkLSNEntryV3 + +func (s flatMapEntries) len() int { return len(s) } +func (s flatMapEntries) at(i int) chunkLSNEntryV3 { return s[i] } +func (s flatMapEntries) copyInto(dst []chunkLSNEntryV3, start int) { copy(dst, s[start:]) } +func (s flatMapEntries) snapshot(prior mapEntrySnapshot) mapEntrySnapshot { + return snapshotMapEntries(s, prior) +} +func (s flatMapEntries) validate(mapEntrySnapshot) error { + for _, value := range s { + if value.LSN > counterMaxV3 { + return ErrCounterExhausted + } + } + return nil +} +func (s mapEntrySnapshot) snapshot(mapEntrySnapshot) mapEntrySnapshot { return s } +func (s mapEntrySnapshot) validate(prior mapEntrySnapshot) error { + var check func(*mapEntryNode, *mapEntryNode, uint) error + check = func(n, old *mapEntryNode, depth uint) error { + if n == nil || n == old { + return nil + } + if depth == 0 { + return flatMapEntries(n.values).validate(mapEntrySnapshot{}) + } + for i, child := range n.children { + var before *mapEntryNode + if old != nil && old.children != nil { + before = old.children[i] + } + if err := check(child, before, depth-1); err != nil { + return err + } + } + return nil + } + if prior.count != s.count || prior.depth != s.depth { + prior = mapEntrySnapshot{} + } + return check(s.root, prior.root, s.depth) } func (s mapEntrySnapshot) len() int { return s.count } @@ -50,6 +109,7 @@ func replaceMapEntryLeaf(n *mapEntryNode, depth uint, page int, values []chunkLS func snapshotMapEntries(entries []chunkLSNEntryV3, prior mapEntrySnapshot) mapEntrySnapshot { s := prior + s.visitedPages = 0 if prior.count != len(entries) { s = mapEntrySnapshot{count: len(entries)} pages := (len(entries) + mapEntryLeafSize - 1) / mapEntryLeafSize @@ -60,6 +120,7 @@ func snapshotMapEntries(entries []chunkLSNEntryV3, prior mapEntrySnapshot) mapEn for start := 0; start < len(entries); start += mapEntryLeafSize { end := min(start+mapEntryLeafSize, len(entries)) page := start / mapEntryLeafSize + s.visitedPages++ old := s.leaf(page) same := old != nil && len(old.values) == end-start if same { diff --git a/seaweed-block/core/storage/recovery_progress_test.go b/seaweed-block/core/storage/recovery_progress_test.go index 3e1b572406..2932251c58 100644 --- a/seaweed-block/core/storage/recovery_progress_test.go +++ b/seaweed-block/core/storage/recovery_progress_test.go @@ -27,8 +27,8 @@ func TestRecoveryCancellationKeepsLiveGeometryAndCanRetry(t *testing.T) { if _, err := s.RecoverContext(ctx); !errors.Is(err, context.Canceled) { t.Fatalf("cancel: %v", err) } - if len(s.v3.mapEntries) != 2048 { - t.Fatalf("interrupted recovery published %d entries, want 2048", len(s.v3.mapEntries)) + if s.v3.mapEntries.len() != 2048 { + t.Fatalf("interrupted recovery published %d entries, want 2048", s.v3.mapEntries.len()) } got, err := s.Read(1500) if err != nil || !bytes.Equal(got, blk(byte(1500%256))) { diff --git a/seaweed-block/core/storage/walstore_activation_test.go b/seaweed-block/core/storage/walstore_activation_test.go index fe97b7d953..e6fe0559a2 100644 --- a/seaweed-block/core/storage/walstore_activation_test.go +++ b/seaweed-block/core/storage/walstore_activation_test.go @@ -95,7 +95,7 @@ func TestWALStoreProductionCreateOptions(t *testing.T) { t.Fatal(err) } defer s.Close() - if s.v3.pub.current().WMode != WModeStrict || s.v3.ownedMap.chunkBlocks != 4 || len(s.v3.mapEntries) != 16 { + if s.v3.pub.current().WMode != WModeStrict || s.v3.ownedMap.chunkBlocks != 4 || s.v3.mapEntries.len() != 16 { t.Fatal("production create lost the strict mode or map geometry option") } } diff --git a/seaweed-block/core/storage/walstore_batch_v3_test.go b/seaweed-block/core/storage/walstore_batch_v3_test.go index 914059ebd5..dc82537b0c 100644 --- a/seaweed-block/core/storage/walstore_batch_v3_test.go +++ b/seaweed-block/core/storage/walstore_batch_v3_test.go @@ -236,7 +236,7 @@ func TestWALStoreV3BatchRecordsMapCoverage(t *testing.T) { s.mu.RLock() defer s.mu.RUnlock() for c, want := range map[int]uint64{1: 4, 2: 8} { - if got := s.v3.mapEntries[c].LSN; got < want { + if got := s.v3.mapEntries.at(int(c)).LSN; got < want { t.Fatalf("chunk %d map LSN %d, want >= %d", c, got, want) } } diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index c76a9f69e3..4c36c1de1c 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -16,7 +16,8 @@ func (s *WALStore) recordMapWriteV3(lba, lsn uint64) { if v.ownedMap == nil { return } - e := &v.mapEntries[lba/v.ownedMap.chunkBlocks] + index := int(lba / v.ownedMap.chunkBlocks) + e := v.mapEntries.at(index) if lsn <= e.LSN { e.Unknown = true } @@ -27,6 +28,7 @@ func (s *WALStore) recordMapWriteV3(lba, lsn uint64) { count := min(cb, s.sb.VolumeSize/uint64(s.sb.BlockSize)-start) e.Local = e.Local.mark(lba%cb, count) } + v.mapEntries.set(index, e) } // Recover may scan retained records already represented by the durable bitmap. @@ -38,35 +40,37 @@ func (s *WALStore) recordMapReplayV3(lba, lsn uint64) { return } index := lba / v.ownedMap.chunkBlocks - prior := v.mapEntries[index].Local + prior := v.mapEntries.at(int(index)).Local baseline := v.pub.mapCurrent.entries.at(int(index)).LSN s.recordMapWriteV3(lba, lsn) if lsn <= baseline { - v.mapEntries[index].Local = prior + e := v.mapEntries.at(int(index)) + e.Local = prior + v.mapEntries.set(int(index), e) } } func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicationV3, error) { v := s.v3 - s.mu.RLock() + s.mu.Lock() if err := s.stickyIOFault(); err != nil { - s.mu.RUnlock() + s.mu.Unlock() return nil, err } v.pub.descMu.Lock() prior, domain := v.pub.mapCurrent, v.pub.mapDomain if prior == nil || prior.owner != v.ownedMap || domain != v.mapProof { v.pub.descMu.Unlock() - s.mu.RUnlock() + s.mu.Unlock() 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...) + entries := v.mapEntries.capture() walHead := s.walHead v.pub.descMu.Unlock() - s.mu.RUnlock() + s.mu.Unlock() // Capture bitmap entries before the data sync. A fill or append may have // arrived after the flusher's earlier sync; publishing that bit first could // make an unwritten extent authoritative after a crash. @@ -83,7 +87,7 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati return nil, err } } - c, err := v.ownedMap.prepareNextV3(cp, entries, prior) + c, err := v.ownedMap.prepareNextEntriesV3(cp, entries, prior) if err != nil { return nil, err } @@ -91,7 +95,7 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati v.ownedMap.abandonCandidateV3(c) // prepared but never publishable return nil, mapCoverageRefusal("proof_changed_during_prepare") } - return &preparedMapPublicationV3{candidate: c, proof: proof}, nil + return &preparedMapPublicationV3{candidate: c, proof: proof, entryCapturePages: entries.visitedPages}, nil } func (s *WALStore) persistOwnedMapCheckpointV3(highestLSN, recoveryGen uint64) error { diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 1753436199..2e3473ad35 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -33,8 +33,8 @@ type walStoreV3State struct { pub *descriptorPublisherV3 w *walWriterV3 ownedMap *chunkLSNMapV3 - coverageRecovered bool // store.mu; derived from the last completed Recover - mapEntries []chunkLSNEntryV3 // guarded by WALStore.mu; UNKNOWN is never cleared here + coverageRecovered bool // store.mu; derived from the last completed Recover + mapEntries liveMapEntries // guarded by WALStore.mu; UNKNOWN is never cleared here mapProof *mapProofEpochV3 appended atomic.Uint64 // highest LSN pwritten to the WAL @@ -485,7 +485,7 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO } openProgress.finish() v.ownedMap = ownedMap - v.mapEntries, err = copyRecoverySnapshotPhase(progressCtx, RecoveryOpenCopy, nil, mapCurrent.entries) + v.mapEntries, err = v.mapEntries.recover(progressCtx, RecoveryOpenCopy, mapCurrent.entries) if err != nil { return err } @@ -665,7 +665,7 @@ func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { } } var err error - v.mapEntries, err = copyRecoverySnapshotPhase(ctx, RecoveryMap, v.mapEntries, v.pub.mapCurrent.entries) + v.mapEntries, err = v.mapEntries.recover(ctx, RecoveryMap, v.pub.mapCurrent.entries) v.pub.descMu.Unlock() if err != nil { return 0, err diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b084d56d0a..02df541774 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -666,7 +666,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-MAP-PUBLISH-ROLLOVER-001` | A v3 publication without a prepared map candidate (a W-only publication or a rollover) carries the bound map root unchanged. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3` | `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix` | — | STUB | | `INV-WAL-V3-FLUSH-LIFETIME-001` | A 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 v3 map candidate names immutable pages and root in the store's owned sidecar, checked against the descriptor's identity and geometry. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`, `encodeMapPageV3`, `encodeMapRootV3` | `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_CorruptionAndBounds` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | ACTIVE | -| `INV-WAL-V3-MAP-CANDIDATE-IMMUTABLE-001` | A prepared map candidate retains immutable entry values; later changes to the caller's mutable entry slice cannot change an earlier candidate. | M1 map preparation | `core/storage/map_entry_snapshot.go` `snapshotMapEntries`; `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkMapEntrySnapshotsKeepOldValuesAcrossPageBoundaries`, `TestChunkMapCheckpointOneChangedPageDoesNotCopyTheWholeMap` | PageReuse.Prepare; entry-value representation only, dirty-version retirement pending | STUB | +| `INV-WAL-V3-MAP-CANDIDATE-IMMUTABLE-001` | A prepared map candidate retains immutable entry values; later writes or source-slice changes cannot change an earlier candidate. | M1 map preparation | `core/storage/map_entry_snapshot.go` `snapshotMapEntries`; `core/storage/map_entry_builder.go` `capture`, `set`; `core/storage/chunk_lsn_map_v3.go` `prepareEntriesLockedV3` | `TestChunkMapEntrySnapshotsKeepOldValuesAcrossPageBoundaries`, `TestOwnedMapCandidatesFreezeCapturedVersions`, `TestMapEntryOwnerRolloverKeepsOldSnapshots`, `TestChunkMapCheckpointOneChangedPageDoesNotCopyTheWholeMap` | PageReuse.Prepare / Publish / Abandon; selected root is the durable version baseline | STUB | | `INV-WAL-V3-MAP-VALIDATE-001` | A v3 map read returns no entry before the root and every page pass their domain-separated body digests, zero reserved and unused bytes, exact page counts, file bounds and non-aliasing page intervals. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `readChunkLSNMapV3`, `mapReadAtV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest` | — | STUB | | `INV-WAL-V3-MAP-PERSIST-ORDER-001` | A v3 map candidate exists only after its new pages are written and fsynced, then its root is written and fsynced, then the sidecar's directory is fsynced. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage` | — | ACTIVE | | `INV-WAL-V3-MAP-PERSIST-FAIL-001` | An error inside a v3 map persistence transaction yields no candidate and latches the store against later I/O; a preflight or Stat error latches nothing. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore` | — | STUB | diff --git a/seaweed-block/docs/design/map-checkpoint-cost.md b/seaweed-block/docs/design/map-checkpoint-cost.md index e6a9bab6a4..28650b1c35 100644 --- a/seaweed-block/docs/design/map-checkpoint-cost.md +++ b/seaweed-block/docs/design/map-checkpoint-cost.md @@ -15,4 +15,4 @@ Until the coverage format is declared, release user-facing creates above 256 GiB Production open continues to require the valid immutable root created above. Missing or corrupt map metadata must keep refusing; it cannot stand for a new empty store. No encoding prerequisite remains. The required creation/first-open regression is that a store above 256 GiB never publishes a format-1 map checkpoint after create; that control and its native qualification remain pending in this draft. The obsolete test requiring every direct store create above 256 GiB to refuse has been removed: it did not express this boundary. -Candidate entries now use immutable leaf pages with shared bounded-fanout paths. A one-page change in the map preparer allocates 877,480 bytes at 1 TiB in the Windows Go1.25.6 control (previously 7,164,632). This is a candidate-copy result, not end-to-end checkpoint complexity: live entry capture, full input validation/comparison, reference-tree scans and extent live-set rebuilds remain O(S). Dirty-version retirement, incremental pins, typed phases, resource-grid cells and native stop qualification are still pending. No V10 completion claim. +Candidate entries now use immutable leaf pages with shared bounded-fanout paths. A one-page change in the map preparer allocates 877,480 bytes at 1 TiB in the Windows Go1.25.6 control (previously 7,164,632). This is a candidate-copy result, not end-to-end checkpoint complexity: live capture now freezes a COW entry tree in O(1), and immutable input validation skips unchanged subtrees. The 64-MiB owned-store capture control allocates 15,592 bytes instead of 413,048, with no full entry-page scan. All live writes update the flat read vector and its COW view through one private container. A candidate retains its captured version through later writes, abandonment, publication and recovery. The selected published root remains the durable baseline; preparation alone retires nothing. Full page comparison, reference-tree scans and extent live-set rebuilds remain O(S). Incremental pins, typed phases, resource-grid cells and native stop qualification are still pending. No V10 completion claim.