diff --git a/seaweed-block/.github/model-code-trace.tsv b/seaweed-block/.github/model-code-trace.tsv index 635123eff3..a32d734bea 100644 --- a/seaweed-block/.github/model-code-trace.tsv +++ b/seaweed-block/.github/model-code-trace.tsv @@ -123,3 +123,6 @@ core/transport/replica.go FencingRound.Recv core/transport/replica.go ReplicationPeer.CatchUp core/transport/replica.go ReplicationPeer.Rebuild core/transport/replica.go ReplicationPeer.Ship +core/storage/chunk_coverage.go SlotFence.Publish +core/storage/chunk_coverage_map.go MoveWide2.Write +core/storage/walstore_v3.go SlotFence2.OpenNew diff --git a/seaweed-block/core/storage/block_metadata.go b/seaweed-block/core/storage/block_metadata.go index 33fc39ac8d..9447074afd 100644 --- a/seaweed-block/core/storage/block_metadata.go +++ b/seaweed-block/core/storage/block_metadata.go @@ -46,6 +46,9 @@ type BlockMetadataBinding struct { // on open it must accept exactly the stored version. No registry or hook chain. type BlockMetadataFactory func(BlockMetadataFile, BlockMetadataLayout) (BlockMetadataBinding, error) type WALStoreOptions struct { + // RecoveryEvent observes typed open-time diagnostic decisions synchronously. + // It must not call storage or perform I/O; it authorizes no serving or writes. + RecoveryEvent func(RecoveryEvent) // RecoveryProgress observes validated open-map entries. It may take the // watchdog lock, but must never call back into storage or perform I/O. RecoveryProgress func(RecoveryPhase, uint64) diff --git a/seaweed-block/core/storage/chunk_coverage.go b/seaweed-block/core/storage/chunk_coverage.go new file mode 100644 index 0000000000..6c85c5df17 --- /dev/null +++ b/seaweed-block/core/storage/chunk_coverage.go @@ -0,0 +1,264 @@ +package storage + +import ( + "context" + "errors" + "fmt" +) + +// LocalCoverage describes the locally authoritative blocks of one chunk. +// These values do not say that the bytes equal a remote reference. +type LocalCoverage uint8 + +const ( + CoverageNone LocalCoverage = iota + CoverageSome + CoverageAll +) + +// ErrChunkCoverageUnavailable means the durable per-block map has not been +// initialized. An old presence cache is not evidence for this answer. +var ErrChunkCoverageUnavailable = errors.New("storage: durable chunk coverage unavailable; initialize the bitmap before using coverage") + +// ChunkCoverageEpochMismatchError refuses upgrade seeding across a marked +// local-work epoch. Attach-after-move, not legacy presence, owns that transition. +type ChunkCoverageEpochMismatchError struct{ StoredEpoch, RequestedEpoch uint64 } + +func (e *ChunkCoverageEpochMismatchError) Error() string { + return fmt.Sprintf("storage: chunk coverage epoch %d differs from requested epoch %d; attach-after-move must establish the epoch", e.StoredEpoch, e.RequestedEpoch) +} + +// ChunkCoverageSeed supplies the legacy local blocks of a chunk during the +// one-way upgrade. Blocks are offsets within the chunk. All avoids enumerating +// every block of a wholly local chunk; All and Blocks must not both be set. +type ChunkCoverageSeed struct { + All bool + Blocks []uint64 +} + +// ChunkCoverageReader is the atomic read seam shared by the live store and an +// immutable prepared bitmap. The prepared view lets the caller persist record +// pages before the store publishes its one-way descriptor fence. +// A read costs O(1), performs no I/O and returns coverage and position together. +// The live store takes lifecycle/store read locks; the prepared reader takes no +// locks and remains immutable after the callback returns. Bounds, unavailable +// recovery/initialization and latched store faults are errors, never CoverageNone. +type ChunkCoverageReader interface { + Coverage(chunk uint64) (LocalCoverage, uint64, error) +} + +var ( + _ ChunkCoverageReader = (*WALStore)(nil) + _ ChunkCoverageReader = chunkCoverageSnapshot{} +) + +type chunkCoverageSnapshot struct { + entries []chunkLSNEntryV3 + position uint64 +} + +func (v chunkCoverageSnapshot) Coverage(chunk uint64) (LocalCoverage, uint64, error) { + return coverageObservation(v.entries, chunk, v.position) +} +func coverageObservation(entries []chunkLSNEntryV3, chunk, position uint64) (LocalCoverage, uint64, error) { + if chunk >= uint64(len(entries)) { + return CoverageNone, 0, fmt.Errorf("storage: chunk %d out of range", chunk) + } + e := entries[chunk] + if e.LSN > position { + return CoverageNone, 0, mapCoverageRefusal("coverage_position_ahead_of_recovery") + } + if e.Local == nil { + return CoverageNone, 0, ErrChunkCoverageUnavailable + } + if e.Local.all { + return CoverageAll, e.LSN, nil + } + if len(e.Local.words) != 0 { + return CoverageSome, e.LSN, nil + } + return CoverageNone, e.LSN, nil +} + +// Coverage returns one atomic observation of local coverage and the chunk's +// store position. The chunk index and returned position are always 64-bit. +// Coverage is unavailable until the bitmap upgrade completes. +func (s *WALStore) Coverage(chunk uint64) (LocalCoverage, uint64, error) { + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + s.mu.RLock() + defer s.mu.RUnlock() + if s.closed { + return CoverageNone, 0, errors.New("storage: coverage after Close") + } + if err := s.stickyIOFault(); err != nil { + return CoverageNone, 0, err + } + v := s.v3 + if v == nil || v.ownedMap == nil || (!v.coverageRecovered || v.pub.current().MapFormatID != mapFormatIDCoverage) { + return CoverageNone, 0, ErrChunkCoverageUnavailable + } + return coverageObservation(v.mapEntries, chunk, v.appended.Load()) +} + +// InitializeChunkCoverage runs before chunk attachment, with extent draining +// held and recovery complete. The seed reads no guest bytes; it describes the +// legacy presence and recovered local blocks. A completed same-epoch call is +// idempotent. After a marker, presence is never seeded again; a different +// epoch is refused because attach-after-move owns that transition. +// The bitmap pages are persisted first; preparePages then receives an immutable +// view and must persist the matching chunk-record pages. Only after it succeeds +// does the store publish both descriptor slots. The caller writes the record's +// completion header and removes legacy presence AFTER this method succeeds. +func (s *WALStore) InitializeChunkCoverage(ctx context.Context, epoch uint64, seed func(chunk, blocks uint64) (ChunkCoverageSeed, error), preparePages func(ChunkCoverageReader) error) error { + if ctx == nil || seed == nil || preparePages == nil || epoch == 0 || epoch > counterMaxV3 { + return errors.New("storage: invalid coverage initialization") + } + release := s.holdChunkDestructive(true) + defer release() + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + v := s.v3 + if v == nil || v.ownedMap == nil { + return ErrChunkCoverageUnavailable + } + s.mu.RLock() + if s.closed || !v.coverageRecovered || s.chunk.Load() != nil || !s.drainHeld.Load() { + s.mu.RUnlock() + return errors.New("storage: initialize coverage before chunk attachment with extent draining held") + } + if err := s.stickyIOFault(); err != nil { + s.mu.RUnlock() + return err + } + current := v.pub.current() + v.pub.descMu.Lock() + resetting := v.pub.otherValid && v.pub.other.Nonce != current.Nonce + v.pub.descMu.Unlock() + if current.BaseState != BaseNone || resetting { + s.mu.RUnlock() + return fmt.Errorf("%w: initialize coverage during BASE install or reset", errDescriptorTransition) + } + shapeDescriptor := current + shapeDescriptor.MapFormatID = mapFormatIDCoverage + if _, err := mapShapeForV3(shapeDescriptor, v.ownedMap.chunkBlocks); err != nil { + s.mu.RUnlock() + return err + } + if current.ChunkStateFormat != 0 { + if current.LocalWorkEpoch != epoch { + s.mu.RUnlock() + return &ChunkCoverageEpochMismatchError{StoredEpoch: current.LocalWorkEpoch, RequestedEpoch: epoch} + } + if current.MapFormatID != mapFormatIDCoverage { + s.mu.RUnlock() + return ErrChunkCoverageUnavailable + } + } + position := v.wack.Load() + if s.nextLSN-1 != position { + s.mu.RUnlock() + return errors.New("storage: initialize coverage after recovery and Sync") + } + if current.MapFormatID == mapFormatIDCoverage && current.LocalWorkEpoch == epoch { + view := chunkCoverageSnapshot{entries: append([]chunkLSNEntryV3(nil), v.mapEntries...), position: position} + s.mu.RUnlock() + if err := preparePages(view); err != nil { + return err + } + if err := ctx.Err(); err != nil { + return err + } + v.syncMu.Lock() + defer v.syncMu.Unlock() + s.mu.Lock() + defer s.mu.Unlock() + return s.finishCoverageFenceLocked(epoch) + } + entries := append([]chunkLSNEntryV3(nil), v.mapEntries...) + v.pub.descMu.Lock() + prior, domain := v.pub.mapCurrent, v.pub.mapDomain + proof := domain.snapshotV3() + v.pub.descMu.Unlock() + s.mu.RUnlock() + cb := v.ownedMap.chunkBlocks + blocks := s.sb.VolumeSize / uint64(s.sb.BlockSize) + for index := range entries { + if err := ctx.Err(); err != nil { + return err + } + count := min(cb, blocks-uint64(index)*cb) + local, err := seed(uint64(index), count) + if err != nil { + return err + } + if local.All && len(local.Blocks) != 0 { + return errors.New("storage: coverage seed mixes All and Blocks") + } + bits := noChunkLocalBits + if local.All { + bits = &chunkLocalBits{blocks: count, all: true} + } else if len(local.Blocks) != 0 { + bits = &chunkLocalBits{blocks: count, words: make([]uint64, (count+63)/64)} + for _, block := range local.Blocks { + if block >= count { + return fmt.Errorf("storage: local block %d outside chunk %d", block, index) + } + bits.words[block/64] |= uint64(1) << (block % 64) + } + if bits.count() == count { + bits = &chunkLocalBits{blocks: count, all: true} + } + } + entries[index].Local = bits + // A reset snapshot covers all prior writes, even when it drops their bits. + // Retained WAL at or below this position must not resurrect old local work. + entries[index].LSN = max(entries[index].LSN, position) + } + if err := ctx.Err(); err != nil { + return err + } + m := v.ownedMap + m.mu.Lock() + candidate, err := m.prepareLockedV3(m.lastGeneration+1, current.MapCoveredCheckpoint, entries, prior, coverageMapPreparation{format: mapFormatIDCoverage, zeroPosition: position}) + m.mu.Unlock() + if err != nil { + return err + } + prepared := &preparedMapPublicationV3{candidate: candidate, proof: proof} + if err := preparePages(chunkCoverageSnapshot{entries: append([]chunkLSNEntryV3(nil), entries...), position: position}); err != nil { + prepared.abandonV3() + return err + } + if err := ctx.Err(); err != nil { + prepared.abandonV3() + return err + } + v.syncMu.Lock() + defer v.syncMu.Unlock() + s.mu.Lock() + defer s.mu.Unlock() + if v.pub.current() != current { + prepared.abandonV3() + return mapCoverageRefusal("coverage_initialization_changed") + } + _, err = v.pub.publishMapV3(nil, nil, prepared, func(d *descriptorV3) error { d.ChunkStateFormat = 1; d.LocalWorkEpoch = epoch; return nil }) + if err != nil { + return err + } + v.mapEntries = entries + return s.finishCoverageFenceLocked(epoch) +} + +func (s *WALStore) finishCoverageFenceLocked(epoch uint64) error { + p := s.v3.pub + p.descMu.Lock() + otherReady := p.otherValid && p.other.MapFormatID == mapFormatIDCoverage && p.other.LocalWorkEpoch == epoch + p.descMu.Unlock() + if !otherReady { + if _, err := p.publish(nil, nil, nil); err != nil { + return err + } + } + return s.fenceChunkStateUpgradeLocked(epoch) +} diff --git a/seaweed-block/core/storage/chunk_coverage_map.go b/seaweed-block/core/storage/chunk_coverage_map.go new file mode 100644 index 0000000000..82a9cf2428 --- /dev/null +++ b/seaweed-block/core/storage/chunk_coverage_map.go @@ -0,0 +1,446 @@ +package storage + +import ( + "bytes" + "encoding/binary" + "math/bits" + "os" + "slices" +) + +const coveragePagePayload uint64 = 4000 + +// Admission for the current eager runtime, not a disk-format limit. Count the +// logical bitmap and entry/reference tables before allocating any of them. +// A later paged runtime can lift this without another on-disk format change. +const coverageShapeBudget uint64 = 1 << 30 + +func coverageShapeAdmitted(shape mapShapeV3, cb uint64) bool { + remaining := coverageShapeBudget + take := func(count, width uint64) bool { + if width == 0 || count > remaining/width { + return false + } + remaining -= count * width + return true + } + if cb > counterMaxV3-63 || !take(shape.chunks, ((cb+63)/64)*8) || !take(shape.chunks, chunkMapEntryMemoryBytes) { + return false + } + for nodes := shape.pages; ; nodes = (nodes + coverageTreeFanout - 1) / coverageTreeFanout { + if !take(nodes, 40) { + return false + } + if nodes <= coverageTreeFanout { + return true + } + } +} + +type coverageMapMetadata struct{ zeroPosition uint64 } +type coverageMapPreparation struct { + format uint32 + zeroPosition uint64 +} + +func isCoverageZeroRef(r mapPageRefV3) bool { return r.Offset == 0 && r.Hash == ([32]byte{}) } +func defaultCoverageByte(offset, position uint64) byte { + if offset < 8 { + return byte(position >> (8 * offset)) + } + if offset == 8 { + return 1 + } + return 0 +} + +// Immutable values are shared by live state and COW candidates. None and all +// need no bit allocation; only partial chunks carry words. +type chunkLocalBits struct { + blocks uint64 + all bool + words []uint64 +} + +var noChunkLocalBits = &chunkLocalBits{} + +func (b *chunkLocalBits) has(block uint64) bool { + if b == nil || block >= b.blocks { + return false + } + if b.all { + return true + } + return block/64 < uint64(len(b.words)) && b.words[block/64]&(uint64(1)<<(block%64)) != 0 +} +func (b *chunkLocalBits) count() uint64 { + if b.all { + return b.blocks + } + var n uint64 + for _, w := range b.words { + n += uint64(bits.OnesCount64(w)) + } + return n +} +func (b *chunkLocalBits) mark(block, blocks uint64) *chunkLocalBits { + if b.has(block) { + return b + } + next := &chunkLocalBits{blocks: blocks, words: make([]uint64, (blocks+63)/64)} + copy(next.words, b.words) + next.words[block/64] |= uint64(1) << (block % 64) + if next.count() == blocks { + return &chunkLocalBits{blocks: blocks, all: true} + } + return next +} +func coverageEntryBytes(cb uint64) (uint64, error) { + if cb == 0 || cb > counterMaxV3-7 { + return 0, ErrMapInvalid + } + return 16 + (cb+7)/8, nil +} +func (c *chunkMapCandidateV3) formatID() uint32 { + if c.format == 0 { + return mapFormatIDV1 + } + return c.format +} +func mapPageEntrySpanV3(d descriptorV3, cb, page, chunks uint64) (uint64, uint64) { + if d.MapFormatID != mapFormatIDCoverage { + start := page * 250 + return start, min(start+250, chunks) + } + width, _ := coverageEntryBytes(cb) + start := page * coveragePagePayload / width + end := ((page+1)*coveragePagePayload + width - 1) / width + return start, min(end, chunks) +} +func coverageByte(e chunkLSNEntryV3, offset uint64) byte { + if offset < 8 { + return byte(e.LSN >> (8 * offset)) + } + if offset == 8 && e.Unknown { + return 1 + } + if offset < 16 { + return 0 + } + var out byte + for bit := uint64(0); bit < 8; bit++ { + if e.Local.has((offset-16)*8 + bit) { + out |= 1 << bit + } + } + return out +} +func encodeCoverageMapPageV3(d descriptorV3, g, page, cb uint64, entries []chunkLSNEntryV3, zeroPosition uint64) ([]byte, error) { + shape, err := mapShapeForV3(d, cb) + if err != nil || g == 0 || g > counterMaxV3 || page >= shape.pages || uint64(len(entries)) != shape.chunks { + return nil, ErrMapInvalid + } + width, _ := coverageEntryBytes(cb) + start, end := page*coveragePagePayload, min((page+1)*coveragePagePayload, shape.chunks*width) + b := make([]byte, 4096) + copy(b, "CLM3") + le := binary.LittleEndian + le.PutUint16(b[4:], uint16(mapFormatIDCoverage)) + copy(b[8:], d.UUID[:]) + copy(b[24:], d.MapLineage[:]) + le.PutUint64(b[40:], g) + le.PutUint64(b[48:], page) + le.PutUint32(b[56:], uint32(end-start)) + zero := true + for at := start; at < end; at++ { + e := entries[at/width] + if e.Local == nil { + return nil, ErrChunkCoverageUnavailable + } + b[64+at-start] = coverageByte(e, at%width) + if b[64+at-start] != defaultCoverageByte(at%width, zeroPosition) { + zero = false + } + } + if zero { + return nil, nil + } + hash := mapDigestV3(mapPageDomainV3, b[:4064]) + copy(b[4064:], hash[:]) + return b, nil +} +func readCoverageMapPagesV3(f *os.File, d descriptorV3, cb uint64, shape mapShapeV3, root []byte, size uint64, progress *recoveryReporter) ([]chunkLSNEntryV3, []mapPageRefV3, error) { + le := binary.LittleEndian + if le.Uint64(root[88:]) > counterMaxV3 { + return nil, nil, ErrMapInvalid + } + entries := make([]chunkLSNEntryV3, shape.chunks) + refs, err := coverageTreeRefsV3(f, d, shape, root, size) + if err != nil { + return nil, nil, err + } + seen := map[uint64]bool{} + for _, r := range refs[shape.pages:] { + if !isCoverageZeroRef(r) { + seen[r.Offset] = true + } + } + width, _ := coverageEntryBytes(cb) + for page := uint64(0); page < shape.pages; page++ { + r := refs[page] + start, end := page*coveragePagePayload, min((page+1)*coveragePagePayload, shape.chunks*width) + var p []byte + if !isCoverageZeroRef(r) { + if seen[r.Offset] || (r.Offset < d.MapRootLocator+shape.aligned && r.Offset+4096 > d.MapRootLocator) { + return nil, nil, ErrMapInvalid + } + seen[r.Offset] = true + var err error + p, err = mapReadAtV3(f, r.Offset, 4096, size) + if err != nil { + return nil, nil, err + } + hash := mapDigestV3(mapPageDomainV3, p[:4064]) + pg := le.Uint64(p[40:]) + if string(p[:4]) != "CLM3" || le.Uint16(p[4:]) != uint16(mapFormatIDCoverage) || le.Uint16(p[6:]) != 0 || !bytes.Equal(p[8:24], d.UUID[:]) || !bytes.Equal(p[24:40], d.MapLineage[:]) || pg == 0 || pg > d.MapGeneration || le.Uint64(p[48:]) != page || uint64(le.Uint32(p[56:])) != end-start || !mapZeroV3(p[60:64]) || hash != r.Hash || !bytes.Equal(hash[:], p[4064:]) || !mapZeroV3(p[64+end-start:4064]) { + return nil, nil, ErrMapInvalid + } + } + for at := start; at < end; at++ { + e := &entries[at/width] + offset := at % width + value := defaultCoverageByte(offset, le.Uint64(root[88:])) + if p != nil { + value = p[64+at-start] + } + switch { + case offset < 8: + e.LSN |= uint64(value) << (8 * offset) + case offset == 8: + if value > 1 { + return nil, nil, ErrMapInvalid + } + e.Unknown = value == 1 + case offset < 16: + if value != 0 { + return nil, nil, ErrMapInvalid + } + case value != 0: + actual := min(cb, d.VolumeSize/uint64(d.BlockSize)-(at/width)*cb) + if e.Local == nil { + e.Local = &chunkLocalBits{blocks: actual, words: make([]uint64, (cb+63)/64)} + } + bit := (offset - 16) * 8 + e.Local.words[bit/64] |= uint64(value) << (bit % 64) + } + } + } + for i := range entries { + e := &entries[i] + if e.LSN > counterMaxV3 { + return nil, nil, ErrMapInvalid + } + if e.Local == nil { + e.Local = noChunkLocalBits + progress.advance(1) + continue + } + for bit := e.Local.blocks; bit < cb; bit++ { + if e.Local.words[bit/64]&(uint64(1)<<(bit%64)) != 0 { + return nil, nil, ErrMapInvalid + } + } + // The last byte's padding is not an addressable block either. + for bit := cb; bit < ((cb+7)/8)*8; bit++ { + if e.Local.words[bit/64]&(uint64(1)<<(bit%64)) != 0 { + return nil, nil, ErrMapInvalid + } + } + if e.Local.count() == e.Local.blocks { + e.Local = &chunkLocalBits{blocks: e.Local.blocks, all: true} + } + progress.advance(1) + } + return entries, refs, nil +} + +const coverageTreeFanout uint64 = 96 +const coverageIndexDomain = "swblock:chunk-map:index:v2\x00" + +func coverageTreeHeight(pages uint64) uint16 { + var height uint16 + for pages > coverageTreeFanout { + pages = (pages + coverageTreeFanout - 1) / coverageTreeFanout + height++ + } + return height +} +func coverageTreeSpan(level uint16) uint64 { + span := uint64(1) + for level > 0 { + span *= coverageTreeFanout + level-- + } + return span +} +func mapRootLevelV3(d descriptorV3, pages uint64) uint16 { + if d.MapFormatID == mapFormatIDCoverage { + return coverageTreeHeight(pages) + } + return 0 +} + +// The coverage format has a fixed 4-KiB root and bounded-fanout index pages. +// Keeping this structure in the first upgrade permits later lazy caches and +// proportional publication without another disk-format change. +func encodeCoverageTreeRootV3(d descriptorV3, g, cb, C uint64, leaves []mapPageRefV3, prior *chunkMapCandidateV3, zeroPosition uint64, write func([]byte) (uint64, error)) ([]byte, []mapPageRefV3, error) { + shape, err := mapShapeForV3(d, cb) + if err != nil || uint64(len(leaves)) != shape.pages { + return nil, nil, ErrMapInvalid + } + all := append([]mapPageRefV3(nil), leaves...) + current := leaves + oldStart, oldEnd := 0, len(leaves) + var level uint16 + for uint64(len(current)) > coverageTreeFanout { + parents := make([]mapPageRefV3, 0, (uint64(len(current))+coverageTreeFanout-1)/coverageTreeFanout) + oldParentStart := oldEnd + for start := uint64(0); start < uint64(len(current)); start += coverageTreeFanout { + end := min(start+coverageTreeFanout, uint64(len(current))) + oldIndex := oldParentStart + int(start/coverageTreeFanout) + same := prior != nil && prior.formatID() == mapFormatIDCoverage && oldIndex < len(prior.refs) && oldStart+int(end) <= len(prior.refs) && slices.Equal(current[start:end], prior.refs[oldStart+int(start):oldStart+int(end)]) + zero := true + for _, r := range current[start:end] { + if !isCoverageZeroRef(r) { + zero = false + break + } + } + if zero { + parents = append(parents, mapPageRefV3{}) + continue + } + if same { + parents = append(parents, prior.refs[oldIndex]) + continue + } + b := make([]byte, 4096) + copy(b, "CLI3") + le := binary.LittleEndian + le.PutUint16(b[4:], uint16(mapFormatIDCoverage)) + le.PutUint16(b[6:], level) + copy(b[8:], d.UUID[:]) + copy(b[24:], d.MapLineage[:]) + le.PutUint64(b[40:], g) + le.PutUint64(b[48:], start*coverageTreeSpan(level)) + le.PutUint32(b[56:], uint32(end-start)) + for i, r := range current[start:end] { + at := 64 + 40*i + le.PutUint64(b[at:], r.Offset) + copy(b[at+8:], r.Hash[:]) + } + hash := mapDigestV3(coverageIndexDomain, b[:4064]) + copy(b[4064:], hash[:]) + offset, err := write(b) + if err != nil { + return nil, nil, err + } + parents = append(parents, mapPageRefV3{Offset: offset, Hash: hash}) + } + all = append(all, parents...) + oldStart, oldEnd = oldEnd, oldEnd+len(parents) + current = parents + level++ + } + b := make([]byte, 4096) + copy(b, "CLR3") + le := binary.LittleEndian + le.PutUint16(b[4:], uint16(mapFormatIDCoverage)) + le.PutUint16(b[6:], level) + copy(b[8:], d.UUID[:]) + copy(b[24:], d.MapLineage[:]) + le.PutUint64(b[40:], g) + le.PutUint64(b[48:], shape.chunks) + le.PutUint64(b[56:], cb) + le.PutUint64(b[64:], C) + le.PutUint64(b[72:], shape.pages) + le.PutUint64(b[80:], shape.raw) + le.PutUint64(b[88:], zeroPosition) + for i, r := range current { + at := 96 + 40*i + le.PutUint64(b[at:], r.Offset) + copy(b[at+8:], r.Hash[:]) + } + hash := mapDigestV3(mapRootDomainV3, b[:4064]) + copy(b[4064:], hash[:]) + return b, all, nil +} + +func coverageTreeRefsV3(f *os.File, d descriptorV3, shape mapShapeV3, root []byte, size uint64) ([]mapPageRefV3, error) { + if shape.pages > uint64(int(^uint(0)>>1))/40 { + return nil, ErrMapInvalid + } + leaves := make([]mapPageRefV3, shape.pages) + height := coverageTreeHeight(shape.pages) + indexes := make([][]mapPageRefV3, height) + for level := uint16(0); level < height; level++ { + span := coverageTreeSpan(level + 1) + indexes[level] = make([]mapPageRefV3, (shape.pages+span-1)/span) + } + seen := map[uint64]bool{d.MapRootLocator: true} + le := binary.LittleEndian + var walk func(mapPageRefV3, uint16, uint64) error + walk = func(ref mapPageRefV3, remaining uint16, first uint64) error { + if isCoverageZeroRef(ref) { + return nil + } + if remaining == 0 { + leaves[first] = ref + return nil + } + if seen[ref.Offset] { + return ErrMapInvalid + } + seen[ref.Offset] = true + b, err := mapReadAtV3(f, ref.Offset, 4096, size) + if err != nil { + return err + } + level := remaining - 1 + span := coverageTreeSpan(level) + count := (min(coverageTreeSpan(remaining), shape.pages-first) + span - 1) / span + hash := mapDigestV3(coverageIndexDomain, b[:4064]) + generation := le.Uint64(b[40:]) + if string(b[:4]) != "CLI3" || le.Uint16(b[4:]) != uint16(mapFormatIDCoverage) || le.Uint16(b[6:]) != level || !bytes.Equal(b[8:24], d.UUID[:]) || !bytes.Equal(b[24:40], d.MapLineage[:]) || generation == 0 || generation > d.MapGeneration || le.Uint64(b[48:]) != first || uint64(le.Uint32(b[56:])) != count || !mapZeroV3(b[60:64]) || hash != ref.Hash || !bytes.Equal(hash[:], b[4064:]) || !mapZeroV3(b[64+40*count:4064]) { + return ErrMapInvalid + } + indexes[level][first/coverageTreeSpan(remaining)] = ref + for i := uint64(0); i < count; i++ { + at := 64 + 40*i + child := mapPageRefV3{Offset: le.Uint64(b[at:])} + copy(child.Hash[:], b[at+8:at+40]) + if err := walk(child, remaining-1, first+i*span); err != nil { + return err + } + } + return nil + } + span := coverageTreeSpan(height) + count := (shape.pages + span - 1) / span + if !mapZeroV3(root[96+40*count : 4064]) { + return nil, ErrMapInvalid + } + for i := uint64(0); i < count; i++ { + at := 96 + 40*i + child := mapPageRefV3{Offset: le.Uint64(root[at:])} + copy(child.Hash[:], root[at+8:at+40]) + if err := walk(child, height, i*span); err != nil { + return nil, err + } + } + all := leaves + for _, refs := range indexes { + all = append(all, refs...) + } + return all, nil +} diff --git a/seaweed-block/core/storage/chunk_coverage_paged_test.go b/seaweed-block/core/storage/chunk_coverage_paged_test.go new file mode 100644 index 0000000000..ab29cfce87 --- /dev/null +++ b/seaweed-block/core/storage/chunk_coverage_paged_test.go @@ -0,0 +1,189 @@ +package storage + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "io" + "os" + "testing" +) + +func TestChunkCoverageMapProgressCountsValidatedEntries(t *testing.T) { + for _, badPadding := range []bool{false, true} { + d := descriptorV3{BlockSize: 4096, VolumeSize: 9 * 4096, MapFormatID: mapFormatIDCoverage, MapGeneration: 3, MapRootLocator: 4096} + d.UUID[0], d.MapLineage[0] = 1, 2 + entries := []chunkLSNEntryV3{{Local: noChunkLocalBits}, {Local: noChunkLocalBits}, {Local: noChunkLocalBits.mark(0, 1)}} + leaf, err := encodeCoverageMapPageV3(d, 3, 0, 4, entries, 0) + if err != nil { + t.Fatal(err) + } + if badPadding { + leaf[64+2*17+16] |= 0x80 // not an addressable block of the short last chunk + } + hash := mapDigestV3(mapPageDomainV3, leaf[:4064]) + copy(leaf[4064:], hash[:]) + root, _, err := encodeCoverageTreeRootV3(d, 3, 4, 0, []mapPageRefV3{{Hash: hash}}, nil, 0, func([]byte) (uint64, error) { + t.Fatal("small map unexpectedly needs an index") + return 0, nil + }) + if err != nil { + t.Fatal(err) + } + f, err := os.CreateTemp(t.TempDir(), "progress-map") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { f.Close() }) + if _, err := f.Write(append(leaf, root...)); err != nil { + t.Fatal(err) + } + var observed uint64 + reporter := newRecoveryReporter(WithRecoveryProgress(context.Background(), func(phase RecoveryPhase, done uint64) { + if phase != RecoveryOpenMap { + t.Fatal("unexpected progress phase") + } + observed = done + }), RecoveryOpenMap) + shape, _ := mapShapeForV3(d, 4) + _, _, err = readCoverageMapPagesV3(f, d, 4, shape, root, 8192, reporter) + reporter.finish() + want := uint64(3) + if badPadding { + want = 2 + } + if observed != want || (badPadding && !errors.Is(err, ErrMapInvalid)) || (!badPadding && err != nil) { + t.Fatalf("padding=%v: completed=%d want=%d err=%v", badPadding, observed, want, err) + } + } +} + +// This independent, test-only reader pins the format's paging boundary. The +// production reader deliberately remains eager; no cache or runtime API is added. +func coverageEntryByPath(t *testing.T, f io.ReaderAt, rootOffset, chunk, cb uint64) ([]byte, int) { + t.Helper() + cache := map[uint64][]byte{} + read := func(offset uint64, hash [32]byte, domain string) []byte { + if p := cache[offset]; p != nil { + return p + } + p := make([]byte, 4096) + if _, err := f.ReadAt(p, int64(offset)); err != nil { + t.Fatal(err) + } + got := mapDigestV3(domain, p[:4064]) + if !bytes.Equal(got[:], p[4064:]) || (hash != ([32]byte{}) && got != hash) { + t.Fatal("paged reader hash mismatch") + } + cache[offset] = p + return p + } + le := binary.LittleEndian + root := read(rootOffset, [32]byte{}, mapRootDomainV3) + height := le.Uint16(root[6:]) + width := uint64(16) + (cb+7)/8 + entry := make([]byte, width) + for done := uint64(0); done < width; { + absolute := chunk*width + done + leaf, within := absolute/4000, absolute%4000 + page, base, first := root, uint64(96), uint64(0) + var ref mapPageRefV3 + for remaining := height; ; remaining-- { + span := uint64(1) + for i := uint16(0); i < remaining; i++ { + span *= 96 + } + index := (leaf - first) / span + at := base + index*40 + ref.Offset = le.Uint64(page[at:]) + copy(ref.Hash[:], page[at+8:at+40]) + first += index * span + if ref == (mapPageRefV3{}) || remaining == 0 { + break + } + page = read(ref.Offset, ref.Hash, coverageIndexDomain) + base = 64 + } + n := min(width-done, 4000-within) + if ref == (mapPageRefV3{}) { + for i := uint64(0); i < n; i++ { + entry[done+i] = defaultCoverageByte(done+i, le.Uint64(root[88:])) + } + } else { + p := read(ref.Offset, ref.Hash, mapPageDomainV3) + copy(entry[done:done+n], p[64+within:64+within+n]) + } + done += n + } + return entry, len(cache) +} + +func TestChunkCoveragePagedFormatMatchesWholeMap(t *testing.T) { + const cb, chunks = uint64(1024), uint64(260000) + d := descriptorV3{BlockSize: 4096, VolumeSize: cb * chunks * 4096, MapFormatID: mapFormatIDCoverage, MapGeneration: 3} + d.UUID[0], d.MapLineage[0] = 1, 2 + shape, err := mapShapeForV3(d, cb) + if err != nil || coverageTreeHeight(shape.pages) != 2 { + t.Fatalf("need two index levels: shape=%+v err=%v", shape, err) + } + entries := make([]chunkLSNEntryV3, chunks) + for i := range entries { + entries[i] = chunkLSNEntryV3{LSN: 7, Unknown: true, Local: noChunkLocalBits} + } + // Entry 27 occupies bytes 3888..4031: its bitmap crosses two leaves. + entries[27] = chunkLSNEntryV3{LSN: 11, Local: noChunkLocalBits.mark(0, cb).mark(1023, cb)} + entries[chunks-1] = chunkLSNEntryV3{LSN: 13, Local: &chunkLocalBits{blocks: cb, all: true}} + f, err := os.CreateTemp(t.TempDir(), "map") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { f.Close() }) + var next uint64 + write := func(p []byte) (uint64, error) { + offset := next + _, err := f.WriteAt(p, int64(offset)) + next += uint64(len(p)) + return offset, err + } + leaves := make([]mapPageRefV3, shape.pages) + for _, leaf := range []uint64{0, 1, shape.pages - 1} { + p, err := encodeCoverageMapPageV3(d, 3, leaf, cb, entries, 7) + if err != nil { + t.Fatal(err) + } + offset, err := write(p) + if err != nil { + t.Fatal(err) + } + leaves[leaf] = mapPageRefV3{Offset: offset, Hash: mapDigestV3(mapPageDomainV3, p[:4064])} + } + root, _, err := encodeCoverageTreeRootV3(d, 3, cb, 13, leaves, nil, 7, write) + if err != nil { + t.Fatal(err) + } + d.MapRootLocator, err = write(root) + if err != nil { + t.Fatal(err) + } + whole, _, err := readCoverageMapPagesV3(f, d, cb, shape, root, next, nil) + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + chunk uint64 + reads int + }{{27, 5}, {10000, 2}, {chunks - 1, 4}} { + got, reads := coverageEntryByPath(t, f, d.MapRootLocator, tc.chunk, cb) + want := make([]byte, 144) + for i := range want { + want[i] = coverageByte(whole[tc.chunk], uint64(i)) + } + if !bytes.Equal(got, want) || reads != tc.reads { + t.Fatalf("chunk %d: entry equal=%v, page reads=%d want=%d", tc.chunk, bytes.Equal(got, want), reads, tc.reads) + } + } + if !whole[27].Local.has(0) || !whole[27].Local.has(1023) || whole[27].LSN != 11 || !whole[chunks-1].Local.all { + t.Fatal("whole-map oracle lost the literal cross-leaf bitmap/position") + } +} diff --git a/seaweed-block/core/storage/chunk_coverage_test.go b/seaweed-block/core/storage/chunk_coverage_test.go new file mode 100644 index 0000000000..e1e934b7d5 --- /dev/null +++ b/seaweed-block/core/storage/chunk_coverage_test.go @@ -0,0 +1,958 @@ +package storage + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "os" + "syscall" + "testing" +) + +func TestChunkCoverageInitializesEmptyWithoutFabricatingLocalBlocks(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if _, _, err := s.Coverage(0); !errors.Is(err, ErrChunkCoverageUnavailable) { + t.Fatalf("legacy map fabricated coverage: %v", err) + } + err := s.InitializeChunkCoverage(context.Background(), 7, func(chunk, blocks uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil }, coverageNoPages) + if err != nil { + t.Fatal(err) + } + coverage, position, err := s.Coverage(0) + if err != nil || coverage != CoverageNone || position != 0 { + t.Fatalf("empty seed: coverage=%d position=%d err=%v", coverage, position, err) + } +} + +func TestChunkCoverageAcknowledgedWriteSurvivesReplay(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 7, func(chunk, blocks uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil }, coverageNoPages); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + coverage, position, err := s.Coverage(0) + if err != nil || coverage != CoverageSome || position != 1 { + t.Fatalf("write: coverage=%d position=%d err=%v", coverage, position, err) + } + crashStore(t, s) + next, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + next.HoldExtentDrainUntilChunkLayer() + next.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { next.Close() }) + if _, err := next.Recover(); err != nil { + t.Fatal(err) + } + coverage, position, err = next.Coverage(0) + if err != nil || coverage != CoverageSome || position != 1 { + t.Fatalf("replay: coverage=%d position=%d err=%v", coverage, position, err) + } +} + +func TestChunkCoverageCheckpointKeepsAllAcrossAPageBoundary(t *testing.T) { + path := t.TempDir() + "/coverage" + s, err := createMappedWALStoreV3ForTest(path, 1001, 4096, v3TestWAL, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { s.Close() }) + if err := s.InitializeChunkCoverage(context.Background(), 7, func(chunk, blocks uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil }, coverageNoPages); err != nil { + t.Fatal(err) + } + // Chunk 235's metadata straddles a 4000-byte bitmap-page payload. + for lba := uint32(940); lba < 944; lba++ { + if _, err := s.Write(lba, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if coverage, pos, err := s.Coverage(235); err != nil || coverage != CoverageAll || pos != 4 { + t.Fatalf("before checkpoint: %d/%d %v", coverage, pos, err) + } + // Release only the test's drain hold so the real checkpoint owns the bits. + s.drainHeld.Store(false) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if s.CheckpointLSN() != 4 { + t.Fatal("control did not checkpoint the acknowledged writes") + } + crashStore(t, s) + next, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + next.HoldExtentDrainUntilChunkLayer() + next.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { next.Close() }) + if _, err := next.Recover(); err != nil { + t.Fatal(err) + } + if coverage, pos, err := next.Coverage(235); err != nil || coverage != CoverageAll || pos != 4 { + t.Fatalf("checkpoint reopen: %d/%d %v", coverage, pos, err) + } + if coverage, pos, err := next.Coverage(236); err != nil || coverage != CoverageNone || pos != 0 { + t.Fatalf("neighbor fabricated bits: %d/%d %v", coverage, pos, err) + } + if coverage, _, err := next.Coverage(250); err != nil || coverage != CoverageNone { + t.Fatalf("last short chunk: %d %v", coverage, err) + } +} + +func TestChunkCoverageMarkedEpochNeverReseedsPresence(t *testing.T) { + for _, want := range []uint64{6, 7, 8} { + t.Run(fmt.Sprint(want), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 7, func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil }, coverageNoPages); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + before := s.v3.pub.current() + seeds, pages := 0, 0 + err := s.InitializeChunkCoverage(context.Background(), want, func(uint64, uint64) (ChunkCoverageSeed, error) { seeds++; return ChunkCoverageSeed{All: true}, nil }, func(view ChunkCoverageReader) error { + pages++ + if c, p, err := view.Coverage(0); err != nil || c != CoverageSome || p != 1 { + t.Fatalf("bitmap view %d/%d %v", c, p, err) + } + return nil + }) + if seeds != 0 { + t.Fatalf("read presence after marker: %d", seeds) + } + if want == 7 { + if err != nil || pages != 1 { + t.Fatalf("same epoch did not rebuild from bitmap: %v pages=%d", err, pages) + } + } else { + var mismatch *ChunkCoverageEpochMismatchError + if !errors.As(err, &mismatch) || mismatch.StoredEpoch != 7 || mismatch.RequestedEpoch != want || pages != 0 || before != s.v3.pub.current() { + t.Fatalf("epoch mismatch not typed/unchanged: %v pages=%d", err, pages) + } + } + if c, p, err := s.Coverage(0); err != nil || c != CoverageSome || p != 1 { + t.Fatalf("marked bits changed: %d/%d %v", c, p, err) + } + }) + } +} + +func TestChunkCoverageMarkerWithoutBitmapCannotReadPresence(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.FenceChunkStateUpgrade(7); err != nil { + t.Fatal(err) + } + before := s.v3.pub.current() + seeds, pages := 0, 0 + err := s.InitializeChunkCoverage(context.Background(), 7, func(uint64, uint64) (ChunkCoverageSeed, error) { seeds++; return ChunkCoverageSeed{All: true}, nil }, func(ChunkCoverageReader) error { pages++; return nil }) + if !errors.Is(err, ErrChunkCoverageUnavailable) || seeds != 0 || pages != 0 || before != s.v3.pub.current() { + t.Fatalf("marked legacy map read presence: err=%v seed=%d pages=%d", err, seeds, pages) + } +} + +func TestChunkCoverageRequiresSuccessfulRecovery(t *testing.T) { + original, path := newMappedCheckpointStoreV3(t) + crashStore(t, original) + s, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + s.HoldExtentDrainUntilChunkLayer() + t.Cleanup(func() { s.Close() }) + calls := 0 + seed := func(chunk, blocks uint64) (ChunkCoverageSeed, error) { calls++; return ChunkCoverageSeed{}, nil } + if err := s.InitializeChunkCoverage(context.Background(), 7, seed, coverageNoPages); err == nil || calls != 0 { + t.Fatalf("initialized before recovery: calls=%d err=%v", calls, err) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 7, seed, coverageNoPages); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ctx = WithRecoveryProgress(ctx, func(phase RecoveryPhase, done uint64) { + if phase == RecoveryMap { + cancel() + } + }) + if _, err := s.RecoverContext(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("control did not interrupt recovery: %v", err) + } + if _, _, err := s.Coverage(0); !errors.Is(err, ErrChunkCoverageUnavailable) { + t.Fatalf("failed recovery exposed coverage: %v", err) + } + calls = 0 + if err := s.InitializeChunkCoverage(context.Background(), 7, seed, coverageNoPages); err == nil || calls != 0 { + t.Fatalf("initialized after failed recovery: calls=%d err=%v", calls, err) + } +} + +func TestChunkCoverageSeedsPartialWholeAndLastShortChunk(t *testing.T) { + path := t.TempDir() + "/seed" + s, err := createMappedWALStoreV3ForTest(path, 9, 4096, v3TestWAL, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + s.HoldExtentDrainUntilChunkLayer() + t.Cleanup(func() { s.Close() }) + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + seed := func(chunk, blocks uint64) (ChunkCoverageSeed, error) { + if chunk == 1 { + return ChunkCoverageSeed{Blocks: []uint64{0, 2}}, nil + } + return ChunkCoverageSeed{All: true}, nil + } + if err := s.InitializeChunkCoverage(context.Background(), 7, seed, coverageNoPages); err != nil { + t.Fatal(err) + } + crashStore(t, s) + next, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + next.DisableAutoFlushForRecoveryTest() + next.HoldExtentDrainUntilChunkLayer() + t.Cleanup(func() { next.Close() }) + if _, err := next.Recover(); err != nil { + t.Fatal(err) + } + for chunk, want := range []LocalCoverage{CoverageAll, CoverageSome, CoverageAll} { + got, pos, err := next.Coverage(uint64(chunk)) + if err != nil || got != want || pos != 0 { + t.Fatalf("seed chunk %d: %d/%d want %d err=%v", chunk, got, pos, want, err) + } + } +} + +func coverageNoPages(ChunkCoverageReader) error { return nil } + +func TestChunkCoverageLegacyFenceCannotRelabelAnInitializedEpoch(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 7, func(uint64, uint64) (ChunkCoverageSeed, error) { + return ChunkCoverageSeed{Blocks: []uint64{1}}, nil + }, coverageNoPages); err != nil { + t.Fatal(err) + } + before := s.v3.pub.current() + for _, epoch := range []uint64{8, 6} { + var mismatch *ChunkCoverageEpochMismatchError + if err := s.FenceChunkStateUpgrade(epoch); !errors.As(err, &mismatch) || mismatch.StoredEpoch != 7 || mismatch.RequestedEpoch != epoch { + t.Fatalf("legacy fence relabeled coverage epoch %d: %v", epoch, err) + } + if s.v3.pub.current() != before { + t.Fatal("refused legacy fence changed descriptor") + } + } + if err := s.FenceChunkStateUpgrade(7); err != nil { + t.Fatalf("same epoch confirmation refused: %v", err) + } +} + +func TestChunkCoverageBaselineCannotOutliveItsRetainedWAL(t *testing.T) { + for _, damaged := range []bool{false, true} { + t.Run(fmt.Sprint(damaged), func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 7, func(uint64, uint64) (ChunkCoverageSeed, error) { + return ChunkCoverageSeed{}, nil + }, coverageNoPages); err != nil { + t.Fatal(err) + } + if _, err := s.Write(0, blk(0x61)); err != nil { + t.Fatal(err) + } + off, _, _, _, ok := s.dm.get(0) + if !ok { + t.Fatal("write missing from WAL") + } + prepared, err := s.prepareOwnedMapCheckpointV3(0) + if err != nil { + t.Fatal(err) + } + if _, err := s.v3.pub.publishMapV3(&s.mu, nil, prepared, nil); err != nil { + t.Fatal(err) + } + if s.v3.pub.current().W != 0 || s.v3.pub.mapCurrent.entries[0].LSN != 1 { + t.Fatal("control did not persist a bitmap ahead of W") + } + if damaged { + if _, err := s.fd.WriteAt([]byte{0x62}, int64(s.sb.WALOffset+off+walEntryPrefixSizeV3)); err != nil { + t.Fatal(err) + } + } + _, err = s.Recover() + if damaged { + if !isWALCorrupt(err) { + t.Fatalf("coverage baseline survived discarded WAL: %v", err) + } + if _, _, err := s.Coverage(0); !errors.Is(err, ErrChunkCoverageUnavailable) { + t.Fatalf("failed recovery exposed bitmap: %v", err) + } + return + } + if err != nil { + t.Fatal(err) + } + got, pos, err := s.Coverage(0) + if err != nil || got != CoverageSome || pos != 1 { + t.Fatalf("intact retained WAL lost coverage: %v/%d %v", got, pos, err) + } + data, readErr := s.Read(0) + if readErr != nil || string(data) != string(blk(0x61)) { + t.Fatalf("intact retained bytes differ: %v", readErr) + } + }) + } +} + +func TestChunkCoverageAdmissionPrecedesSeed(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + // Inject the oversized shape at the admission boundary, avoiding an actual + // multi-gigabyte legacy fixture just to prove callbacks have not begun. + before := s.v3.pub.cur + cb := s.v3.ownedMap.chunkBlocks + s.v3.pub.cur.VolumeSize = 34_000_000 * 64 * 4096 + s.v3.ownedMap.chunkBlocks = 64 + defer func() { s.v3.pub.cur = before; s.v3.ownedMap.chunkBlocks = cb }() + calls := 0 + err := s.InitializeChunkCoverage(context.Background(), 7, func(uint64, uint64) (ChunkCoverageSeed, error) { + calls++ + return ChunkCoverageSeed{}, nil + }, coverageNoPages) + if !errors.Is(err, ErrMapInvalid) || calls != 0 { + t.Fatalf("oversized initialization began seed: calls=%d err=%v", calls, err) + } +} + +func TestChunkCoveragePreparedViewPrecedesTheFence(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + refused := errors.New("record pages were not persisted") + err := s.InitializeChunkCoverage(context.Background(), 7, func(chunk, blocks uint64) (ChunkCoverageSeed, error) { + return ChunkCoverageSeed{Blocks: []uint64{1}}, nil + }, func(view ChunkCoverageReader) error { + if got, pos, err := view.Coverage(0); err != nil || got != CoverageSome || pos != 0 { + t.Fatalf("prepared view: %d/%d %v", got, pos, err) + } + if marked, _ := s.ChunkStateMarker(); marked { + t.Fatal("descriptor fence ran before record pages") + } + if _, _, err := s.Coverage(0); !errors.Is(err, ErrChunkCoverageUnavailable) { + t.Fatalf("prepared bitmap became live before fence: %v", err) + } + return refused + }) + if !errors.Is(err, refused) { + t.Fatal(err) + } + if marked, _ := s.ChunkStateMarker(); marked { + t.Fatal("refused record pages still published the fence") + } + if _, _, err := s.Coverage(0); !errors.Is(err, ErrChunkCoverageUnavailable) { + t.Fatalf("refused preparation exposed coverage: %v", err) + } +} + +func TestChunkCoverageTreeKeepsBothIndexBranches(t *testing.T) { + path := t.TempDir() + "/tree" + s, err := createMappedWALStoreV3ForTest(path, 92000, 4096, v3TestWAL, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + s.HoldExtentDrainUntilChunkLayer() + t.Cleanup(func() { s.Close() }) + if err := s.InitializeChunkCoverage(context.Background(), 7, func(chunk, blocks uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil }, coverageNoPages); err != nil { + t.Fatal(err) + } + for _, lba := range []uint32{4, 91996} { + if _, err := s.Write(lba, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.drainHeld.Store(false) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + s.HoldExtentDrainUntilChunkLayer() + } + crashStore(t, s) + next, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + next.DisableAutoFlushForRecoveryTest() + next.HoldExtentDrainUntilChunkLayer() + t.Cleanup(func() { next.Close() }) + if _, err := next.Recover(); err != nil { + t.Fatal(err) + } + for _, want := range []struct { + chunk, pos uint64 + coverage LocalCoverage + }{{1, 1, CoverageSome}, {22999, 2, CoverageSome}, {10000, 0, CoverageNone}} { + got, pos, err := next.Coverage(want.chunk) + if err != nil || got != want.coverage || pos != want.pos { + t.Fatalf("tree chunk %d: %d/%d %v", want.chunk, got, pos, err) + } + } +} + +func TestChunkCoverageDataSyncPrecedesBitmapPreparation(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 7, func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil }, coverageNoPages); err != nil { + t.Fatal(err) + } + synced := false + s.testBeforeFileSync = func() { synced = true } + s.v3.ownedMap.testBeforeLiveSnapshot = func() { + if !synced { + t.Error("bitmap preparation preceded data synchronization") + } + } + defer func() { s.testBeforeFileSync = nil; s.v3.ownedMap.testBeforeLiveSnapshot = nil }() + prepared, err := s.prepareOwnedMapCheckpointV3(0) + if err != nil { + t.Fatal(err) + } + prepared.abandonV3() +} + +func TestChunkCoverageFailedPublicationResumesAfterRecovery(t *testing.T) { + for _, point := range []string{"write1", "write2", "sync1", "sync2", "read1", "read2"} { + t.Run(point, func(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + seed := func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{Blocks: []uint64{1}}, nil } + writes, syncs, reads := 0, 0, 0 + originalSync, originalRead := s.v3.pub.io.fsync, s.v3.pub.io.readSlot + injected := errors.New("lost " + point) + s.v3.testBeforeSlotWrite = func() error { + writes++ + if point == fmt.Sprint("write", writes) { + return injected + } + return nil + } + s.v3.pub.io.fsync = func() error { + syncs++ + if point == fmt.Sprint("sync", syncs) { + return injected + } + return originalSync() + } + s.v3.pub.io.readSlot = func(off int64, b []byte) error { + reads++ + if point == fmt.Sprint("read", reads) { + return injected + } + return originalRead(off, b) + } + if err := s.InitializeChunkCoverage(context.Background(), 7, seed, coverageNoPages); err == nil { + t.Fatal("uncertain initialization completed") + } + s.v3.testBeforeSlotWrite = nil + s.v3.pub.io.fsync, s.v3.pub.io.readSlot = originalSync, originalRead + if err := s.InitializeChunkCoverage(context.Background(), 7, seed, coverageNoPages); err == nil { + t.Fatal("latched initialization completed before reopen") + } + _ = s.Close() + next, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { next.Close() }) + next.HoldExtentDrainUntilChunkLayer() + next.DisableAutoFlushForRecoveryTest() + if _, err := next.Recover(); err != nil { + t.Fatal(err) + } + if err := next.InitializeChunkCoverage(context.Background(), 7, seed, func(view ChunkCoverageReader) error { + if c, p, err := view.Coverage(0); err != nil || c != CoverageSome || p != 0 { + return fmt.Errorf("prepared view %d/%d: %v", c, p, err) + } + return nil + }); err != nil { + t.Fatal(err) + } + if c, p, err := next.Coverage(0); err != nil || c != CoverageSome || p != 0 { + t.Fatalf("reopened view %d/%d: %v", c, p, err) + } + current := next.v3.pub.current() + next.v3.pub.descMu.Lock() + other := next.v3.pub.other + next.v3.pub.descMu.Unlock() + if current.MapFormatID != mapFormatIDCoverage || other.MapFormatID != mapFormatIDCoverage || current.LocalWorkEpoch != 7 || other.LocalWorkEpoch != 7 { + t.Fatal("returned before both bitmap slots were published") + } + }) + } +} + +func TestChunkCoverageInitializationRefusesActiveBaseBeforeWriting(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + _ = beginV3(t, s, 0, idA) + before := s.v3.pub.current() + seedCalls, pageCalls := 0, 0 + err := s.InitializeChunkCoverage(context.Background(), 7, func(uint64, uint64) (ChunkCoverageSeed, error) { seedCalls++; return ChunkCoverageSeed{}, nil }, func(ChunkCoverageReader) error { pageCalls++; return nil }) + if err == nil || seedCalls != 0 || pageCalls != 0 || s.v3.pub.current() != before { + t.Fatalf("active BASE refusal wrote state: err=%v seed=%d pages=%d changed=%v", err, seedCalls, pageCalls, s.v3.pub.current() != before) + } +} + +// The legacy allocator sees only the unmarked slot's root. Its next candidate +// may reuse pages named solely by the marked slot before it publishes a slot. +func TestChunkCoverageHalfFenceReusedMapOpensTheIntactLegacySlot(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + payload := make([]byte, 4096) + payload[0] = 0xa7 + if _, err := s.Write(1, payload); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + writes := 0 + s.v3.testBeforeSlotWrite = func() error { + writes++ + if writes == 2 { + return errors.New("half fence") + } + return nil + } + if err := s.InitializeChunkCoverage(context.Background(), 7, func(chunk, _ uint64) (ChunkCoverageSeed, error) { + if chunk == 0 { + return ChunkCoverageSeed{Blocks: []uint64{1}}, nil + } + return ChunkCoverageSeed{}, nil + }, coverageNoPages); err == nil { + t.Fatal("half fence completed") + } + marked := s.v3.pub.current() + legacy := s.v3.pub.other + if marked.MapFormatID != mapFormatIDCoverage || legacy.ChunkStateFormat != 0 { + t.Fatal("control did not leave one marked and one legacy slot") + } + s.v3.testBeforeSlotWrite = nil + _ = s.Close() + // Use the unchanged format-1 allocator with exactly the slot/root the old + // decoder can see. Stop after preparing pages, before publishing its slot. + oldMap, prior, err := openChunkLSNMapV3(path+".chunkmap", legacy, 4) + if err != nil { + t.Fatal(err) + } + entries := append([]chunkLSNEntryV3(nil), prior.entries...) + entries[0].Unknown = !entries[0].Unknown + _, err = oldMap.Prepare(prior.generation+1, prior.covered, entries, prior) + if err != nil { + oldMap.Close() + t.Fatal(err) + } + // Verify the modeled old allocation really destroyed the marked dependency, + // and that the unmarked slot's dependency is still independently readable. + if _, _, err := readChunkLSNMapV3(oldMap.fd, marked, 4); err == nil { + oldMap.Close() + t.Fatal("control did not reuse the marked map") + } + if _, _, err := readChunkLSNMapV3(oldMap.fd, legacy, 4); err != nil { + oldMap.Close() + t.Fatalf("legacy dependency damaged: %v", err) + } + if err := oldMap.Close(); err != nil { + t.Fatal(err) + } + var events []RecoveryEvent + next, err := openWALStoreV3WithOptions(path, true, WALStoreOptions{RecoveryEvent: func(event RecoveryEvent) { events = append(events, event) }}) + if err != nil { + t.Fatalf("intact legacy slot could not reopen after half-fence page reuse: %v", err) + } + defer next.Close() + if len(events) != 1 || events[0].Kind != RecoveryHalfFenceFallback || events[0].DiscardedSlotGeneration != marked.SlotGen || events[0].SelectedSlotGeneration != legacy.SlotGen || next.ChunkMapStatsV3().HalfFenceFallbacks != 1 { + t.Fatalf("missing typed fallback receipt: events=%+v stats=%+v", events, next.ChunkMapStatsV3()) + } + next.DisableAutoFlushForRecoveryTest() + next.HoldExtentDrainUntilChunkLayer() + if next.v3.pub.current().ChunkStateFormat != 0 { + t.Fatal("reused marked map was trusted") + } + if _, err := next.Recover(); err != nil { + t.Fatal(err) + } + got, err := next.Read(1) + if err != nil { + t.Fatal(err) + } + if string(got) != string(payload) { + t.Fatal("legacy fallback lost acknowledged bytes") + } + if err := next.InitializeChunkCoverage(context.Background(), 7, func(chunk, _ uint64) (ChunkCoverageSeed, error) { + if chunk == 0 { + return ChunkCoverageSeed{Blocks: []uint64{1}}, nil + } + return ChunkCoverageSeed{}, nil + }, coverageNoPages); err != nil { + t.Fatalf("upgrade after fallback did not converge: %v", err) + } + if err := next.Close(); err != nil { + t.Fatal(err) + } + again, err := openWALStoreV3WithOptions(path, true, WALStoreOptions{RecoveryEvent: func(event RecoveryEvent) { events = append(events, event) }}) + if err != nil { + t.Fatal(err) + } + defer again.Close() + again.DisableAutoFlushForRecoveryTest() + again.HoldExtentDrainUntilChunkLayer() + if len(events) != 1 || again.ChunkMapStatsV3().HalfFenceFallbacks != 0 { + t.Fatal("normal reopen reported another fallback") + } + if _, err := again.Recover(); err != nil { + t.Fatal(err) + } + if got, err := again.Read(1); err != nil || string(got) != string(payload) { + t.Fatalf("completed upgrade lost acknowledged bytes: %v", err) + } +} + +func TestChunkCoveragePreparedReaderRemainsImmutableAfterWrites(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + var prepared ChunkCoverageReader + if err := s.InitializeChunkCoverage(context.Background(), 7, func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil }, func(view ChunkCoverageReader) error { prepared = view; return nil }); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if c, p, err := s.Coverage(0); err != nil || c != CoverageSome || p != 1 { + t.Fatalf("live %d/%d: %v", c, p, err) + } + if c, p, err := prepared.Coverage(0); err != nil || c != CoverageNone || p != 0 { + t.Fatalf("retained prepared view changed: %d/%d: %v", c, p, err) + } +} + +func TestChunkCoverageRejectsRehashedImpossibleBitmapGeometry(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 7, func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil }, coverageNoPages); err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + const impossibleChunkBlocks = uint64(1) << 63 + // Stop the red before exercising the allocator: the old admission accepts + // petabytes of references here. This assertion is the safe negative control. + if shape, err := mapShapeForV3(d, impossibleChunkBlocks); err == nil { + t.Fatalf("impossible allocation admitted: %+v", shape) + } + root := make([]byte, 4096) + if _, err := s.v3.ownedMap.fd.ReadAt(root, int64(d.MapRootLocator)); err != nil { + t.Fatal(err) + } + binary.LittleEndian.PutUint64(root[56:], impossibleChunkBlocks) + hash := mapDigestV3(mapRootDomainV3, root[:4064]) + copy(root[4064:], hash[:]) + d.MapRootHash = hash + if _, err := s.v3.ownedMap.fd.WriteAt(root, int64(d.MapRootLocator)); err != nil { + t.Fatal(err) + } + if _, _, err := readChunkLSNMapV3(s.v3.ownedMap.fd, d, impossibleChunkBlocks); !errors.Is(err, ErrMapInvalid) { + t.Fatalf("rehashed impossible root answered %v", err) + } +} + +func TestChunkCoverageBothMarkedDamagedMapNeverFallsBack(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if err := s.InitializeChunkCoverage(context.Background(), 7, func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{}, nil }, coverageNoPages); err != nil { + t.Fatal(err) + } + prepared, err := s.prepareOwnedMapCheckpointV3(s.v3.pub.current().MapCoveredCheckpoint) + if err != nil { + t.Fatal(err) + } + if _, err := s.v3.pub.publishMapV3(nil, nil, prepared, nil); err != nil { + t.Fatal(err) + } + marked, other := s.v3.pub.current(), s.v3.pub.other + if marked.ChunkStateFormat == 0 || other.ChunkStateFormat == 0 || marked.MapRootLocator == other.MapRootLocator { + t.Fatal("control did not create two independent marked roots") + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + f, err := os.OpenFile(path+".chunkmap", os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + if _, err := f.WriteAt([]byte("BAD!"), int64(marked.MapRootLocator)); err != nil { + f.Close() + t.Fatal(err) + } + if err := f.Sync(); err != nil { + f.Close() + t.Fatal(err) + } + if _, _, err := readChunkLSNMapV3(f, other, 4); err != nil { + f.Close() + t.Fatalf("older marked root not intact: %v", err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + events := 0 + next, err := openWALStoreV3WithOptions(path, true, WALStoreOptions{RecoveryEvent: func(RecoveryEvent) { events++ }}) + if next != nil { + next.Close() + } + if !errors.Is(err, ErrMapInvalid) || events != 0 { + t.Fatalf("marked dependency loss was hidden: err=%v events=%d", err, events) + } +} + +func TestChunkCoverageFallbackRequiresIntegrityOnlyErrorTree(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + legacy := s.v3.pub.current() + marked := legacy + marked.SlotGen++ + marked.ChunkStateFormat = 1 + marked.LocalWorkEpoch = 7 + marked.MapFormatID = mapFormatIDCoverage + cases := []struct { + name string + cause error + want bool + }{ + {"nil", nil, false}, {"invalid", ErrMapInvalid, true}, {"eof", io.EOF, true}, {"short", io.ErrUnexpectedEOF, true}, + {"wrapped-eof", fmt.Errorf("read: %w", io.EOF), true}, {"joined-integrity", errors.Join(io.EOF, ErrMapInvalid), true}, + {"eio", syscall.EIO, false}, {"permission", os.ErrPermission, false}, + {"joined-eof-eio", errors.Join(io.EOF, syscall.EIO), false}, + {"nested-operational", fmt.Errorf("map: %w", errors.Join(ErrMapInvalid, fmt.Errorf("close: %w", syscall.EIO))), false}, + {"multiple-wrap-operational", fmt.Errorf("read %w; close %w", io.ErrUnexpectedEOF, os.ErrPermission), false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := coverageHalfFenceFallbackEligible(marked, &legacy, tc.cause); got != tc.want { + t.Fatalf("eligibility=%v want=%v cause=%v", got, tc.want, tc.cause) + } + }) + } +} + +func TestChunkCoverageFallbackAuthorityGuards(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + legacy := s.v3.pub.current() + marked := legacy + marked.SlotGen++ + marked.ChunkStateFormat = 1 + marked.LocalWorkEpoch = 7 + marked.MapFormatID = mapFormatIDCoverage + cases := []struct { + name string + change func(*descriptorV3, **descriptorV3) + want bool + }{ + {"intact-unmarked-half", func(*descriptorV3, **descriptorV3) {}, true}, + {"selected-unmarked", func(d *descriptorV3, _ **descriptorV3) { d.ChunkStateFormat = 0 }, false}, + {"selected-format1", func(d *descriptorV3, _ **descriptorV3) { d.MapFormatID = mapFormatIDV1 }, false}, + {"missing-other", func(_ *descriptorV3, o **descriptorV3) { *o = nil }, false}, + {"other-marked", func(_ *descriptorV3, o **descriptorV3) { (*o).ChunkStateFormat = 1 }, false}, + {"other-format2", func(_ *descriptorV3, o **descriptorV3) { (*o).MapFormatID = mapFormatIDCoverage }, false}, + {"other-migration", func(_ *descriptorV3, o **descriptorV3) { (*o).MigrationPhase = MigrationPhase(1) }, false}, + {"same-generation", func(d *descriptorV3, o **descriptorV3) { (*o).SlotGen = d.SlotGen }, false}, + {"newer-other", func(d *descriptorV3, o **descriptorV3) { (*o).SlotGen = d.SlotGen + 1 }, false}, + {"identity", func(_ *descriptorV3, o **descriptorV3) { (*o).UUID[0] ^= 1 }, false}, + {"volume-size", func(_ *descriptorV3, o **descriptorV3) { (*o).VolumeSize += 4096 }, false}, + {"extent-size", func(_ *descriptorV3, o **descriptorV3) { (*o).ExtentSize += 4096 }, false}, + {"block-size", func(_ *descriptorV3, o **descriptorV3) { (*o).BlockSize *= 2 }, false}, + {"wal-offset", func(_ *descriptorV3, o **descriptorV3) { (*o).WALOffset += 4096 }, false}, + {"wal-size", func(_ *descriptorV3, o **descriptorV3) { (*o).WALSize += 4096 }, false}, + {"nonce", func(_ *descriptorV3, o **descriptorV3) { (*o).Nonce[0] ^= 1 }, false}, + {"map-lineage", func(_ *descriptorV3, o **descriptorV3) { (*o).MapLineage[0] ^= 1 }, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + d, o := marked, legacy + other := &o + tc.change(&d, &other) + if got := coverageHalfFenceFallbackEligible(d, other, ErrMapInvalid); got != tc.want { + t.Fatalf("eligibility=%v want=%v", got, tc.want) + } + }) + } +} + +func TestChunkCoverageFallbackRefusesUnavailableOtherDependencies(t *testing.T) { + for _, point := range []string{"invalid-other-slot", "missing-map", "directory-map", "damaged-other-root", "truncated-other-root"} { + t.Run(point, func(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + writes := 0 + s.v3.testBeforeSlotWrite = func() error { + writes++ + if writes == 2 { + return errors.New("half fence") + } + return nil + } + if err := s.InitializeChunkCoverage(context.Background(), 7, func(uint64, uint64) (ChunkCoverageSeed, error) { return ChunkCoverageSeed{Blocks: []uint64{1}}, nil }, coverageNoPages); err == nil { + t.Fatal("half fence completed") + } + marked, legacy, slot := s.v3.pub.current(), s.v3.pub.other, s.v3.pub.curSlot + s.v3.testBeforeSlotWrite = nil + _ = s.Close() + mapPath := path + ".chunkmap" + f, err := os.OpenFile(mapPath, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + if _, err := f.WriteAt([]byte("BAD!"), int64(marked.MapRootLocator)); err != nil { + f.Close() + t.Fatal(err) + } + if point == "damaged-other-root" { + if _, err := f.WriteAt([]byte("BAD!"), int64(legacy.MapRootLocator)); err != nil { + f.Close() + t.Fatal(err) + } + } + if point == "truncated-other-root" { + if err := f.Truncate(int64(legacy.MapRootLocator + 32)); err != nil { + f.Close() + t.Fatal(err) + } + } + if err := f.Sync(); err != nil { + f.Close() + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + switch point { + case "invalid-other-slot": + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + offset := int64(slotAOffsetV3) + if slot == slotA { + offset = slotBOffsetV3 + } + if _, err := f.WriteAt([]byte("BAD!"), offset); err != nil { + f.Close() + t.Fatal(err) + } + if err := f.Sync(); err != nil { + f.Close() + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + case "missing-map", "directory-map": + if err := os.Remove(mapPath); err != nil { + t.Fatal(err) + } + if point == "directory-map" { + if err := os.Mkdir(mapPath, 0700); err != nil { + t.Fatal(err) + } + } + } + events := 0 + next, err := openWALStoreV3WithOptions(path, true, WALStoreOptions{RecoveryEvent: func(RecoveryEvent) { events++ }}) + if next != nil { + next.Close() + } + if err == nil || next != nil || events != 0 { + t.Fatalf("unavailable dependency authorized fallback: err=%v store=%v events=%d", err, next != nil, events) + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_lsn_map_v3.go b/seaweed-block/core/storage/chunk_lsn_map_v3.go index a46f1fb469..2c03561170 100644 --- a/seaweed-block/core/storage/chunk_lsn_map_v3.go +++ b/seaweed-block/core/storage/chunk_lsn_map_v3.go @@ -15,8 +15,11 @@ import ( "os" "path/filepath" "sync" + "unsafe" ) +const chunkMapEntryMemoryBytes = uint64(unsafe.Sizeof(chunkLSNEntryV3{})) + const mapPageDomainV3 = "swblock:chunk-map:page:v1\x00" const mapRootDomainV3 = "swblock:chunk-map:root:v1\x00" @@ -25,6 +28,7 @@ var ErrMapInvalid = errors.New("storage: v3 chunk map invalid") type chunkLSNEntryV3 struct { LSN uint64 Unknown bool + Local *chunkLocalBits // immutable; nil means legacy coverage is unavailable } type mapPageRefV3 struct { Offset uint64 @@ -42,13 +46,32 @@ func mapShapeForV3(d descriptorV3, cb uint64) (mapShapeV3, error) { if nb%cb != 0 { s.chunks++ } - s.pages = s.chunks / 250 - if s.chunks%250 != 0 { - s.pages++ + if d.MapFormatID == mapFormatIDCoverage { + width, err := coverageEntryBytes(cb) + if err != nil || s.chunks > counterMaxV3/width { + return s, ErrMapInvalid + } + size := s.chunks * width + s.pages = size / coveragePagePayload + if size%coveragePagePayload != 0 { + s.pages++ + } + } else { + s.pages = s.chunks / 250 + if s.chunks%250 != 0 { + s.pages++ + } } if s.pages == 0 || s.pages > (counterMaxV3-120)/40 { return s, ErrCounterExhausted } + if d.MapFormatID == mapFormatIDCoverage { + s.raw, s.aligned = 4096, 4096 + if !coverageShapeAdmitted(s, cb) { + return s, ErrMapInvalid + } + return s, nil + } s.raw = 120 + 40*s.pages if s.raw > uint64(math.MaxInt64)-4095 { return s, ErrCounterExhausted @@ -112,7 +135,7 @@ func encodeMapRootV3(d descriptorV3, g, cb, C uint64, refs []mapPageRefV3) ([]by b := make([]byte, int(s.aligned)) copy(b, "CLR3") le := binary.LittleEndian - le.PutUint16(b[4:], 1) + le.PutUint16(b[4:], uint16(d.MapFormatID)) copy(b[8:], d.UUID[:]) copy(b[24:], d.MapLineage[:]) le.PutUint64(b[40:], g) @@ -150,7 +173,7 @@ func readChunkLSNMapV3(f *os.File, d descriptorV3, cb uint64) ([]chunkLSNEntryV3 return readChunkLSNMapV3Progress(f, d, cb, nil) } -func readChunkLSNMapV3Progress(f *os.File, d descriptorV3, cb uint64, progress *recoveryReporter) ([]chunkLSNEntryV3, []mapPageRefV3, error) { +func readChunkLSNMapV3Progress(f *os.File, d descriptorV3, cb uint64, progress *recoveryReporter, metadata ...*coverageMapMetadata) ([]chunkLSNEntryV3, []mapPageRefV3, error) { s, e := mapShapeForV3(d, cb) if e != nil { return nil, nil, e @@ -159,7 +182,7 @@ func readChunkLSNMapV3Progress(f *os.File, d descriptorV3, cb uint64, progress * return nil, nil, ErrMapInvalid } // Reject an impossible entry allocation before root allocation or file I/O. - if s.chunks > uint64(int(^uint(0)>>1))/16 { + if s.chunks > uint64(int(^uint(0)>>1))/chunkMapEntryMemoryBytes { return nil, nil, ErrMapInvalid } info, e := f.Stat() @@ -175,7 +198,7 @@ func readChunkLSNMapV3Progress(f *os.File, d descriptorV3, cb uint64, progress * return nil, nil, e } le := binary.LittleEndian - if string(b[:4]) != "CLR3" || le.Uint16(b[4:]) != 1 || le.Uint16(b[6:]) != 0 || !bytes.Equal(b[8:24], d.UUID[:]) || !bytes.Equal(b[24:40], d.MapLineage[:]) || le.Uint64(b[40:]) != d.MapGeneration || d.MapGeneration == 0 || le.Uint64(b[48:]) != s.chunks || le.Uint64(b[56:]) != cb || le.Uint64(b[64:]) != d.MapCoveredCheckpoint || le.Uint64(b[72:]) != s.pages || le.Uint64(b[80:]) != s.raw || d.MapFormatID != 1 { + if string(b[:4]) != "CLR3" || le.Uint16(b[4:]) != uint16(d.MapFormatID) || le.Uint16(b[6:]) != mapRootLevelV3(d, s.pages) || !bytes.Equal(b[8:24], d.UUID[:]) || !bytes.Equal(b[24:40], d.MapLineage[:]) || le.Uint64(b[40:]) != d.MapGeneration || d.MapGeneration == 0 || le.Uint64(b[48:]) != s.chunks || le.Uint64(b[56:]) != cb || le.Uint64(b[64:]) != d.MapCoveredCheckpoint || le.Uint64(b[72:]) != s.pages || le.Uint64(b[80:]) != s.raw || (d.MapFormatID != mapFormatIDV1 && d.MapFormatID != mapFormatIDCoverage) { return nil, nil, ErrMapInvalid } hash := mapDigestV3(mapRootDomainV3, b[:s.raw-32]) @@ -184,9 +207,15 @@ func readChunkLSNMapV3Progress(f *os.File, d descriptorV3, cb uint64, progress * } // Root is file-bounded before page and entry allocations; every page needs // 4096 distinct bytes. Reject impossible geometry before allocating entries. - if s.pages > size/4096 { + if d.MapFormatID != mapFormatIDCoverage && s.pages > size/4096 { return nil, nil, ErrMapInvalid } + if d.MapFormatID == mapFormatIDCoverage { + if len(metadata) != 0 { + metadata[0].zeroPosition = le.Uint64(b[88:]) + } + return readCoverageMapPagesV3(f, d, cb, s, b, size, progress) + } entries := make([]chunkLSNEntryV3, 0, int(s.chunks)) refs := make([]mapPageRefV3, 0, int(s.pages)) seen := make(map[uint64]bool) @@ -230,10 +259,12 @@ type chunkMapCandidateV3 struct { hash [32]byte refs []mapPageRefV3 entries []chunkLSNEntryV3 + format uint32 + zeroPosition uint64 } func (c *chunkMapCandidateV3) descriptor(d descriptorV3) descriptorV3 { - d.MapFormatID = 1 + d.MapFormatID = c.formatID() d.MapGeneration = c.generation d.MapCoveredCheckpoint = c.covered d.MapRootLocator = c.rootOffset @@ -300,10 +331,10 @@ func openChunkLSNMapV3Progress(path string, d descriptorV3, cb uint64, progress if e != nil { return nil, nil, e } - es, refs, e := readChunkLSNMapV3Progress(f, d, cb, progress) + var metadata coverageMapMetadata + es, refs, e := readChunkLSNMapV3Progress(f, d, cb, progress, &metadata) if e != nil { - f.Close() - return nil, nil, e + return nil, nil, errors.Join(e, f.Close()) } m := &chunkLSNMapV3{fd: f, identity: d, chunkBlocks: cb, lastGeneration: d.MapGeneration} m.initLiveV3() @@ -315,7 +346,7 @@ func openChunkLSNMapV3Progress(path string, d descriptorV3, cb uint64, progress } 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} + c := &chunkMapCandidateV3{owner: m, generation: d.MapGeneration, covered: d.MapCoveredCheckpoint, rootOffset: d.MapRootLocator, hash: d.MapRootHash, format: d.MapFormatID, zeroPosition: metadata.zeroPosition, refs: refs, entries: es} return m, c, nil } @@ -347,11 +378,21 @@ func (m *chunkLSNMapV3) prepareNextV3(C uint64, entries []chunkLSNEntryV3, prior } return m.prepareLockedV3(m.lastGeneration+1, C, entries, prior) } -func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3) (out *chunkMapCandidateV3, err error) { +func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, prior *chunkMapCandidateV3, formats ...coverageMapPreparation) (out *chunkMapCandidateV3, err error) { if m.failed != nil { return nil, m.failed } - s, e := mapShapeForV3(m.identity, m.chunkBlocks) + identity := m.identity + zeroPosition := uint64(0) + if prior != nil { + identity.MapFormatID = prior.formatID() + zeroPosition = prior.zeroPosition + } + if len(formats) != 0 { + identity.MapFormatID = formats[0].format + zeroPosition = formats[0].zeroPosition + } + s, e := mapShapeForV3(identity, m.chunkBlocks) if e != nil { return nil, e } @@ -447,9 +488,8 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, } refs := make([]mapPageRefV3, s.pages) for j := uint64(0); j < s.pages; j++ { - start := j * 250 - end := min(start+250, s.chunks) - same := prior != nil && len(prior.entries) == len(entries) + start, end := mapPageEntrySpanV3(identity, m.chunkBlocks, j, s.chunks) + same := prior != nil && prior.formatID() == identity.MapFormatID && len(prior.entries) == len(entries) if same { for i := start; i < end; i++ { if prior.entries[i] != entries[i] { @@ -458,14 +498,27 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, } } } + if same && identity.MapFormatID == mapFormatIDCoverage && isCoverageZeroRef(prior.refs[j]) && prior.zeroPosition != zeroPosition { + same = false + } if same { refs[j] = prior.refs[j] continue } - p, e := encodeMapPageV3(m.identity, g, j, entries[start:end]) + var p []byte + var e error + if identity.MapFormatID == mapFormatIDCoverage { + p, e = encodeCoverageMapPageV3(identity, g, j, m.chunkBlocks, entries, zeroPosition) + } else { + p, e = encodeMapPageV3(identity, g, j, entries[start:end]) + } if e != nil { return nil, e } + if identity.MapFormatID == mapFormatIDCoverage && p == nil { + refs[j] = mapPageRefV3{} + continue + } at, e := write(p) if e != nil { return nil, e @@ -475,7 +528,12 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, if e = m.syncFile(); e != nil { return nil, e } - root, e := encodeMapRootV3(m.identity, g, m.chunkBlocks, C, refs) + var root []byte + if identity.MapFormatID == mapFormatIDCoverage { + root, refs, e = encodeCoverageTreeRootV3(identity, g, m.chunkBlocks, C, refs, prior, zeroPosition, write) + } else { + root, e = encodeMapRootV3(identity, g, m.chunkBlocks, C, refs) + } if e != nil { return nil, e } @@ -490,7 +548,7 @@ func (m *chunkLSNMapV3) prepareLockedV3(g, C uint64, entries []chunkLSNEntryV3, return nil, e } m.lastGeneration = g - out = &chunkMapCandidateV3{owner: m, generation: g, covered: C, rootOffset: at, hash: mapDigestV3(mapRootDomainV3, root[:s.raw-32]), refs: refs, entries: append([]chunkLSNEntryV3(nil), entries...)} + 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: append([]chunkLSNEntryV3(nil), entries...)} // 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.go b/seaweed-block/core/storage/chunk_map_extents_v3.go index 859d3766a1..9bfe1caeb5 100644 --- a/seaweed-block/core/storage/chunk_map_extents_v3.go +++ b/seaweed-block/core/storage/chunk_map_extents_v3.go @@ -36,11 +36,12 @@ type mapRootExtentsV3 struct { // chunkMapLiveV3 is the live set of one owned map. type chunkMapLiveV3 struct { - roots map[mapRootKeyV3]mapRootExtentsV3 - inflight map[mapRootKeyV3]bool - truncations atomic.Uint64 - priorRefused atomic.Uint64 // prepares refused because their prior root was released - fileBytes atomic.Uint64 // set at open, after each prepare and truncation + roots map[mapRootKeyV3]mapRootExtentsV3 + inflight map[mapRootKeyV3]bool + truncations atomic.Uint64 + priorRefused atomic.Uint64 // prepares refused because their prior root was released + halfFenceFallbacks atomic.Uint64 // successful opens selecting an intact unmarked slot + fileBytes atomic.Uint64 // set at open, after each prepare and truncation } // ChunkMapStats reports the owned map file's size, the bytes its live roots @@ -48,6 +49,7 @@ type chunkMapLiveV3 struct { // prepares were refused because their prior root had been released. type ChunkMapStats struct { FileBytes, LiveBytes, Truncations, PriorReleased uint64 + HalfFenceFallbacks uint64 // since this process opened the store; not a replay/ready count } // registerRootV3 records a slot-named root read at open. Caller holds no lock @@ -59,9 +61,11 @@ func (m *chunkLSNMapV3) registerRootV3(gen, rootOff, rootLen uint64, refs []mapP } 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 + x := mapRootExtentsV3{rootOff: rootOff, rootLen: rootLen, pages: make([]uint64, 0, len(refs))} + for _, r := range refs { + if !isCoverageZeroRef(r) { + x.pages = append(x.pages, r.Offset) + } } return x } @@ -220,7 +224,7 @@ func (a *extentAllocatorV3) alloc(n uint64) uint64 { // 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(), PriorReleased: m.live.priorRefused.Load()} + return ChunkMapStats{FileBytes: m.live.fileBytes.Load(), LiveBytes: live, Truncations: m.live.truncations.Load(), PriorReleased: m.live.priorRefused.Load(), HalfFenceFallbacks: m.live.halfFenceFallbacks.Load()} } // ChunkMapStatsV3 reports the owned map file's bounded-growth counters, or diff --git a/seaweed-block/core/storage/chunk_map_publication_v3.go b/seaweed-block/core/storage/chunk_map_publication_v3.go index b93c51d090..874b24b34c 100644 --- a/seaweed-block/core/storage/chunk_map_publication_v3.go +++ b/seaweed-block/core/storage/chunk_map_publication_v3.go @@ -75,7 +75,7 @@ func sameMapTupleV3(d descriptorV3, c *chunkMapCandidateV3) bool { return false } id := c.owner.identity - return d.UUID == id.UUID && sameGeometryV3(d, id) && d.MapLineage == id.MapLineage && d.MapFormatID == mapFormatIDV1 && d.MapGeneration == c.generation && d.MapCoveredCheckpoint == c.covered && d.MapRootLocator == c.rootOffset && d.MapRootHash == c.hash + return d.UUID == id.UUID && sameGeometryV3(d, id) && d.MapLineage == id.MapLineage && d.MapFormatID == c.formatID() && d.MapGeneration == c.generation && d.MapCoveredCheckpoint == c.covered && d.MapRootLocator == c.rootOffset && d.MapRootHash == c.hash } // bindMapV3 is used only while opening/quiesced. Snapshot both slots under @@ -216,8 +216,7 @@ func openDescriptorMapV3Progress(path string, selected descriptorV3, fallback *d } } if err != nil { - _ = m.Close() - return nil, nil, err + return nil, nil, errors.Join(err, m.Close()) } } return m, c, nil diff --git a/seaweed-block/core/storage/chunk_state_upgrade.go b/seaweed-block/core/storage/chunk_state_upgrade.go index 1435102dfb..f793cb1df9 100644 --- a/seaweed-block/core/storage/chunk_state_upgrade.go +++ b/seaweed-block/core/storage/chunk_state_upgrade.go @@ -30,6 +30,12 @@ func (s *WALStore) FenceChunkStateUpgrade(epoch uint64) error { defer v.syncMu.Unlock() s.mu.Lock() defer s.mu.Unlock() + return s.fenceChunkStateUpgradeLocked(epoch) +} + +// Caller holds the store lifecycle, sync-leader and store locks. +func (s *WALStore) fenceChunkStateUpgradeLocked(epoch uint64) error { + v := s.v3 if s.closed { return errors.New("storage: chunk-state upgrade after Close") } @@ -45,6 +51,9 @@ func (s *WALStore) FenceChunkStateUpgrade(epoch uint64) error { if err := s.stickyIOFault(); err != nil { return err } + if p.cur.MapFormatID == mapFormatIDCoverage && p.cur.LocalWorkEpoch != epoch { + return &ChunkCoverageEpochMismatchError{StoredEpoch: p.cur.LocalWorkEpoch, RequestedEpoch: epoch} + } if p.cur.LocalWorkEpoch > epoch { return fmt.Errorf("%w: local-work epoch moved backwards", errDescriptorTransition) } diff --git a/seaweed-block/core/storage/layout_fresh_mutators_test.go b/seaweed-block/core/storage/layout_fresh_mutators_test.go index 4a4c8ca324..a757d5b86f 100644 --- a/seaweed-block/core/storage/layout_fresh_mutators_test.go +++ b/seaweed-block/core/storage/layout_fresh_mutators_test.go @@ -24,10 +24,12 @@ var walStoreMethods = map[string]string{ "BeginBaseInstall": "base", "CommitChunkAttachV3": "base", "SeedChunkFrontier": "base", "SyncInstallLog": "base", "AdvanceWALTail": "replication", "FormatV3": "base", "Recover": "recovery", "RecoverContext": "recovery (observed Recover; does not admit guest writes)", - "FenceChunkStateUpgrade": "control (format upgrade; no guest write or layout-fresh release)", "SetLayoutIdentity": "control", "SetWMode": "control", "SetMultiBlockRecords": "control", "SetRecoveryRetentionLSNs": "control", + "InitializeChunkCoverage": "control (startup bitmap upgrade; no guest write or layout-fresh release)", + "FenceChunkStateUpgrade": "control (format upgrade; no guest write or layout-fresh release)", "SetLayoutIdentity": "control", "SetWMode": "control", "SetMultiBlockRecords": "control", "SetRecoveryRetentionLSNs": "control", "SetRecycleFloorSource": "control", "AllowBaseRetirementV3": "control", "DeferBaseRetirementV3": "control", "HoldExtentDrainUntilChunkLayer": "control (holds the extent drain until the chunk layer attaches)", "DisableAutoFlushForRecoveryTest": "test control", "ResetFlusherForMeasurement": "test control", "Sync": "control", "Close": "control", + "Coverage": "read (atomic local bitmap coverage and chunk position)", "AllBlocks": "read", "AppliedLSNs": "read", "CanSeedChunkFrontier": "read (the seed precondition, no write)", "BlockSize": "read", "StoreID": "read (the superblock UUID)", "ChunkBlocks": "read (immutable local map shape)", "ChunkStateMarker": "read (the descriptor's chunk-state marker)", "Boundaries": "read", "CheckpointLSN": "read", "CheckpointLSNForPOC": "read", "CheckpointPersistence": "read", "ChunkMapStatsV3": "read", "DataSyncPolicy": "read", "DurabilityLatency": "read", "ExtentDrainHeld": "read", "FlushCount": "read", "FlusherInstrumentation": "read", "HolesSuspected": "read", diff --git a/seaweed-block/core/storage/recovery_progress.go b/seaweed-block/core/storage/recovery_progress.go index 00acaf4ba6..5dd5cbc9b0 100644 --- a/seaweed-block/core/storage/recovery_progress.go +++ b/seaweed-block/core/storage/recovery_progress.go @@ -25,6 +25,19 @@ const ( RecoveryAttach ) +// RecoveryEventKind names a diagnostic decision, not a readiness grant. +type RecoveryEventKind string + +const RecoveryHalfFenceFallback RecoveryEventKind = "chunk_coverage_half_fence_fallback" + +// RecoveryEvent reports a validated open-time choice. A fallback means legacy +// recovery and upgrade must restart; it does not report replay or serving done. +type RecoveryEvent struct { + Kind RecoveryEventKind + DiscardedSlotGeneration uint64 + SelectedSlotGeneration uint64 +} + type recoveryProgressKey struct{} type recoveryClockKey struct{} diff --git a/seaweed-block/core/storage/superblock_v3.go b/seaweed-block/core/storage/superblock_v3.go index 27c7199b56..29500e5e27 100644 --- a/seaweed-block/core/storage/superblock_v3.go +++ b/seaweed-block/core/storage/superblock_v3.go @@ -25,6 +25,7 @@ const ( superblockVersionV3 = 3 walStoreImplVersion3 = 3 mapFormatIDV1 = 1 + mapFormatIDCoverage = 2 // counterMaxV3 is the largest value any persisted counter may hold // (DESIGN 2.4): an operation that would exceed it is refused, so @@ -345,7 +346,7 @@ func (d *descriptorV3) validate(accept slotImplAcceptor) error { return invalidV3("retained window %d exceeds WALSize %d", d.RetainedHead-d.RetainedTail, d.WALSize) } // Map fields named by the slot (2.1; 9.1 predicate 2, slot-local part). - if d.MapFormatID != mapFormatIDV1 { + if d.MapFormatID != mapFormatIDV1 && (d.MapFormatID != mapFormatIDCoverage || d.ChunkStateFormat != 1) { return invalidV3("mapFormatID %d", d.MapFormatID) } if d.MapRootLocator%slotSizeV3 != 0 { diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 9a6c2afa9f..9cb1b55a15 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -445,6 +445,9 @@ func (s *WALStore) RecoverContext(ctx context.Context) (frontier uint64, err err s.mu.Lock() defer s.mu.Unlock() + s.v3.coverageRecovered = false + defer func() { s.v3.coverageRecovered = err == nil }() + // The store lock orders both epoch boundaries with real map publishers. // START invalidates old candidates; END also invalidates candidates // prepared while this Recover was in flight, including on failure. diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index ee902f622d..c738abf099 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -21,6 +21,29 @@ func (s *WALStore) recordMapWriteV3(lba, lsn uint64) { e.Unknown = true } e.LSN = max(e.LSN, lsn) + if e.Local != nil { + cb := v.ownedMap.chunkBlocks + start := (lba / cb) * cb + count := min(cb, s.sb.VolumeSize/uint64(s.sb.BlockSize)-start) + e.Local = e.Local.mark(lba%cb, count) + } +} + +// Recover may scan retained records already represented by the durable bitmap. +// Re-mark only the suffix above that chunk's persisted position; otherwise an +// epoch reset could resurrect local work that the bitmap durably cleared. +func (s *WALStore) recordMapReplayV3(lba, lsn uint64) { + v := s.v3 + if v.ownedMap == nil { + return + } + index := lba / v.ownedMap.chunkBlocks + prior := v.mapEntries[index].Local + baseline := v.pub.mapCurrent.entries[index].LSN + s.recordMapWriteV3(lba, lsn) + if lsn <= baseline { + v.mapEntries[index].Local = prior + } } func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicationV3, error) { @@ -43,6 +66,14 @@ func (s *WALStore) prepareOwnedMapCheckpointV3(cp uint64) (*preparedMapPublicati entries := append([]chunkLSNEntryV3(nil), v.mapEntries...) v.pub.descMu.Unlock() s.mu.RUnlock() + // 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. + if prior.formatID() == mapFormatIDCoverage { + if err := s.syncFile(nil, s.fd.Sync); err != nil { + return nil, err + } + } c, err := v.ownedMap.prepareNextV3(cp, entries, prior) if err != nil { return nil, err diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index bfb526efe3..1af9b55246 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -29,12 +29,13 @@ import ( type walStoreV3State struct { // layoutFresh mirrors the descriptor's layout identity: set while the // local root is fresh, when no guest write may be acknowledged. - layoutFresh atomic.Bool - pub *descriptorPublisherV3 - w *walWriterV3 - ownedMap *chunkLSNMapV3 - mapEntries []chunkLSNEntryV3 // guarded by WALStore.mu; UNKNOWN is never cleared here - mapProof *mapProofEpochV3 + layoutFresh atomic.Bool + 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 + mapProof *mapProofEpochV3 appended atomic.Uint64 // highest LSN pwritten to the WAL wack atomic.Uint64 // highest acknowledged LSN (Sync completed) @@ -282,7 +283,7 @@ func createWALStoreV3Configured(path string, numBlocks, blockSize uint32, walSiz shape, e := mapShapeForV3(d, chunkBlocks) if e != nil { err = e - } else if shape.chunks > uint64(int(^uint(0)>>1))/16 { + } else if shape.chunks > uint64(int(^uint(0)>>1))/chunkMapEntryMemoryBytes { err = ErrMapInvalid } else { entries := make([]chunkLSNEntryV3, int(shape.chunks)) @@ -385,11 +386,35 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO } var ownedMap *chunkLSNMapV3 var mapCurrent *chunkMapCandidateV3 + var fallbackEvent *RecoveryEvent openProgress := newRecoveryReporter(progressCtx, RecoveryOpenMap) // Earlier dark row5 fixtures have no map tuple. A real immutable root is // never optional: missing metadata is not a clean map. if requireMap || d.MapRootHash != [32]byte{} { ownedMap, mapCurrent, err = openDescriptorMapV3Progress(path+".chunkmap", d, other, openProgress) + // An old writer can reuse pages named only by the marked half of a + // fence, then crash before overwriting that descriptor. Only an intact + // UNMARKED slot can restart this upgrade; a marked fallback may hide + // acknowledged writes and is never eligible. + if err != nil && coverageHalfFenceFallbackEligible(d, other, err) { + back, candidate, backErr := openDescriptorMapV3Progress(path+".chunkmap", *other, nil, openProgress) + if backErr == nil { + fallbackEvent = &RecoveryEvent{Kind: RecoveryHalfFenceFallback, DiscardedSlotGeneration: d.SlotGen, SelectedSlotGeneration: other.SlotGen} + d = *other + if id == slotA { + id = slotB + } else { + id = slotA + } + // The discarded slot is not a live map dependency. Recover will + // replace it through the existing single descriptor publisher. + other = nil + ownedMap, mapCurrent, err = back, candidate, nil + ownedMap.live.halfFenceFallbacks.Add(1) + } else { + err = errors.Join(err, fmt.Errorf("half-fence fallback map: %w", backErr)) + } + } if err != nil { _ = f.Close() return nil, err @@ -476,9 +501,50 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO _ = f.Close() return nil, err } + if fallbackEvent != nil && opts.RecoveryEvent != nil { + opts.RecoveryEvent(*fallbackEvent) + } return s, nil } +// A fallback is a half-fence recovery decision, never general corruption +// recovery to an older checkpoint. Identity, incarnation and map lineage must +// agree, and operational I/O errors do not authorize another slot. +func coverageHalfFenceFallbackEligible(selected descriptorV3, other *descriptorV3, cause error) bool { + integrityFailure := mapIntegrityFailureOnly(cause) + return integrityFailure && selected.ChunkStateFormat != 0 && selected.MapFormatID == mapFormatIDCoverage && + other != nil && other.ChunkStateFormat == 0 && other.MapFormatID == mapFormatIDV1 && + other.MigrationPhase == MigrationNormal && other.SlotGen < selected.SlotGen && + other.UUID == selected.UUID && sameGeometryV3(*other, selected) && other.Nonce == selected.Nonce && other.MapLineage == selected.MapLineage +} + +// Every leaf must be an integrity failure. errors.Is on a joined error is +// insufficient: a short root read joined with a failed close still contains an +// operational I/O failure and cannot authorize another slot. +func mapIntegrityFailureOnly(cause error) bool { + if cause == nil { + return false + } + switch wrapped := cause.(type) { + case interface{ Unwrap() []error }: + found := false + for _, child := range wrapped.Unwrap() { + if child == nil { + continue + } + found = true + if !mapIntegrityFailureOnly(child) { + return false + } + } + return found + case interface{ Unwrap() error }: + return mapIntegrityFailureOnly(wrapped.Unwrap()) + default: + return cause == ErrMapInvalid || cause == io.EOF || cause == io.ErrUnexpectedEOF + } +} + // recoverV3 is Recover for a v3 store (DESIGN 6.5, 6.6). The caller holds // captureMu, lifecycleMu and s.mu, as v2 Recover does. func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { @@ -583,6 +649,20 @@ func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { // speculative cache changes from a dropped suffix. if v.ownedMap != nil { v.pub.descMu.Lock() + if v.pub.mapCurrent.formatID() == mapFormatIDCoverage { + for index, entry := range v.pub.mapCurrent.entries { + if index%256 == 0 { + if err := ctx.Err(); err != nil { + v.pub.descMu.Unlock() + return 0, err + } + } + if entry.LSN > o.R { + v.pub.descMu.Unlock() + return 0, NewWALIntegrityFailure(nil, fmt.Sprintf("coverage chunk %d position %d exceeds retained WAL frontier %d", index, entry.LSN, o.R)) + } + } + } var err error v.mapEntries, err = copyRecoveryMap(ctx, v.mapEntries, v.pub.mapCurrent.entries) v.pub.descMu.Unlock() @@ -615,7 +695,7 @@ func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { } for i := uint64(0); i < count; i++ { if e.LSN+i > d.CheckpointLSN { - s.recordMapWriteV3(e.LBA+i, e.LSN+i) + s.recordMapReplayV3(e.LBA+i, e.LSN+i) } } progress.advance(1) diff --git a/seaweed-block/docs/design/chunk-coverage.md b/seaweed-block/docs/design/chunk-coverage.md new file mode 100644 index 0000000000..726a93d674 --- /dev/null +++ b/seaweed-block/docs/design/chunk-coverage.md @@ -0,0 +1,109 @@ +# Durable chunk coverage (draft) + +This draft specifies the storage-only target contract below. Its component tests do not establish daemon activation; the ledger remains STUB until that integration is qualified. + +The store exposes `Coverage(chunk uint64) (LocalCoverage, uint64, error)`. +The coverage and position are one observation under the store lock. Coverage +is `CoverageNone`, `CoverageSome`, or `CoverageAll`; it describes local blocks, +not equality with a remote reference. An uninitialized or unrecovered store +returns `ErrChunkCoverageUnavailable`. Failed recovery invalidates the answer. A persisted chunk position above the retained WAL frontier refuses recovery with a WAL-integrity error; later LSN reuse cannot authorize those bits. + +## Upgrade boundary + +`InitializeChunkCoverage(ctx, epoch, seed, preparePages)` runs after recovery +and Sync, before chunk attachment, with extent draining held. The seed provides +local block offsets or `All` per chunk. The store persists the bitmap candidate, +then calls `preparePages(ChunkCoverageReader)` with its immutable prepared view. +That callback must persist the corresponding checked chunk-record pages. Only +then does the store publish the bitmap root and epoch together and complete the +two-slot fence, including sync and exact readback of both slots. The caller may +write the completion header and remove legacy presence only after success. +A same-epoch retry reuses the recovered bitmap and calls preparePages again. +An active BASE install or descriptor reset refuses before calling either +callback or publishing any candidate. + +Presence is evidence only before the marker. Once marked at this epoch, the +initializer never calls seed: it rebuilds pages from the recovered bitmap. A +marked store without a readable initialized bitmap refuses as unavailable. +A marker at another epoch returns `ChunkCoverageEpochMismatchError` before +calling either callback or writing storage. Attach-after-move owns Drop and +the new epoch; neither this initialization API nor the legacy fence can relabel an initialized coverage map. +Failed or uncertain descriptor publication retains the existing +fault latch and requires reopening. + +## Map format 2 + +All integer fields are little endian. The descriptor's MapFormatID is 2 and +requires the chunk-state format marker and a nonzero local-work epoch. The map +file uses immutable 4096-byte pages and the existing root publication mechanism. +The root is 4096 bytes; its hash and locator are named by the descriptor. + +The logical entry stream contains, per chunk, LSN (8 bytes), Unknown (1 byte), +seven zero bytes, and ceil(chunkBlocks/8) bitmap bytes, least-significant bit +first. Entries may cross leaf boundaries. Bits beyond the last short chunk and +unused bits in the final byte are zero. Each leaf has the CLM3 header (version 2), +4000 payload bytes, and the existing 32-byte page hash. Header identity includes +UUID, map lineage, generation, page index and payload length. + +The CLR3 root uses version 2, a level at offset 6, the existing identity and +shape fields through offset 87, and a default position at offsets 88..95. +References start at offset 96. Each reference is an 8-byte locator and 32-byte +hash. At most 96 references appear in a page. CLI3 index pages use version 2, +level, UUID, lineage, generation, first leaf index (offset 48), child count +(offset 56), zero padding through offset 63, and references from offset 64. +Their final 32 bytes hash the preceding 4064 bytes with domain +`swblock:chunk-map:index:v2\0`. Root and leaf hashes retain their existing +domains. A zero locator AND zero hash is a virtual subtree: the reader supplies the root-defined default byte at each entry-relative offset covered by that subtree. Bytes supplied by other leaves remain unchanged. A physical page +at locator zero has a nonzero hash. Virtual references pin no file extent. + +Unchanged leaves and index branches are shared across roots. New leaves are +synced first; index pages and the root share the final sync before descriptor publication. +A captured bitmap's data file is synced before preparing its metadata pages. + +## Qualification boundary + +The ledger remains STUB until the daemon caller and runtime fill/BASE paths +are integrated and qualified. This draft implements recovery, initialization, +WAL write/replay, and checkpoint observations. Fill/BASE bitmap updates and +metadata-only persistence still need integration. The disk tree allows bounded +fanout, but the current runtime retains full entry/reference arrays and scans +them during preparation. No proportional runtime cost or scale claim is made. Before allocation, eager +runtime admission limits the combined logical bitmap and entry/reference tables +to a 1-GiB shape estimate. This is a runtime guard, not an on-disk format limit +or a total resident-memory promise; larger geometry refuses with ErrMapInvalid +until a paged implementation is qualified. + +## Half-fence recovery + +```mermaid +flowchart TD + A[Selected slot map] --> B{Intact?} + B -->|yes| C[Open selected slot] + B -->|no| D{Integrity-only failure; selected marked; same incarnation; other valid, unmarked and intact?} + D -->|yes| E[Open legacy slot; restart recovery and upgrade] + D -->|no| F[Refuse open] +``` + +A marked map can be overwritten by an old writer before that writer publishes +its next descriptor. The opener can then select the other slot only when it is +valid, unmarked, and has an intact map, with the same identity, geometry, nonce +and map lineage. Every leaf of a wrapped or joined cause tree must be an integrity error; +a short-read joined with a failed close does not authorize fallback. If the +fallback map also fails, both causes are returned. Operational I/O errors do +not authorize fallback. The discarded +marked slot is excluded from map binding; Recover replaces it through the sole +publisher. Both-marked map damage refuses, even when the older marked map is +intact, because falling back there could lose acknowledged marked writes. + +`WALStoreOptions.RecoveryEvent` observes a typed `RecoveryHalfFenceFallback` +event after successful open, carrying discarded and selected slot generations. +The observer performs no I/O or storage calls. `ChunkMapStatsV3.HalfFenceFallbacks` +counts these opens in this process (zero on an ordinary reopen). Neither means +replay, upgrade or readiness is complete. Legacy presence remains the evidence +for restarting the unmarked upgrade; stale record pages must not be trusted. + +The component control uses the unchanged format-1 allocator with only the +legacy root visible, prepares pages without a descriptor publication, confirms +marked-root damage and intact legacy dependencies, then checks byte-exact ACKed +replay, re-upgrade and another reopen. This is not the separately owed actual +released-binary downgrade/crash qualification. Ledger and trace remain STUB. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6bcc916940..adaf34bcb1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -56,6 +56,7 @@ stateDiagram-v2 [*] --> Opened: OpenWALStore / CreateWALStore [*] --> CreateRefused: CreateWALStore without local headroom (free < size + WAL) [*] --> CreateRefused: chunk volume, create mode: geometry flags disagree with the volume record, or the record is not read + [*] --> Opened: half-fence marked map integrity failure, same-incarnation other slot valid unmarked and intact; restart legacy recovery Opened --> Recovering: RecoverVolume Recovering --> Serving: Recover ok, backend operational; workspace primary: lease held, then HEAD claim, then frontends listen, then ready Serving --> Closed: runtime HEAD fence, exit 78 head_fenced @@ -70,7 +71,7 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001`, `INV-WAL-V3-ACTIVATION-001`, `INV-WAL-V3-DESCRIPTOR-001`, `INV-WAL-V3-MAP-PUBLISH-001` | +| — | Opened | v3 A/B descriptors and owned-map dependencies valid (or the selected marked map has an integrity-only failure and the same-incarnation valid unmarked half-fence slot has an intact map); exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001`, `INV-WAL-V3-ACTIVATION-001`, `INV-WAL-V3-DESCRIPTOR-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-CHUNK-HALF-FENCE-FALLBACK-001` | | — | CreateRefused | a new volume needs the durable root's free space >= its size + WAL (a lab build, tag `swblock_lab_bigvol`, only warns), checked before the store, its WAL or its fresh marker is created (the replica floor, written when the assignment arrives, precedes the check and stays); the refusal ends the process with status 1; an existing volume opens and warns when its remaining data growth + WAL exceed the free space | `core/frontend/durable/headroom.go`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-LOCAL-HEADROOM-001` | | — | CreateRefused | a chunk volume in create mode (no local store yet): before the provider is built, the geometry flags are compared with the volume record; they disagree, or the record is there but does not decode: exit 78; the filer failed the read: exit 75; nothing is created; an absent record keeps the create path; an existing store is never rechecked against the flags | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001`, `INV-RECOVERY-PROGRESS-WINDOW-001` | @@ -618,6 +619,10 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-CHUNK-UPGRADE-PASS-CURSOR-001` | Upgrade pass: rewinds only at open, before Run; a failed rewind latches it until reopen; the persisted cursor is only ever min(earliest unpublished rewind, last written-through position); a restart resumes there; while it runs, a request needing every hash answers in_progress. | M1 Opened (v1.1 upgrade compare pass) | `core/storage/chunk_upgrade_pass.go` `upgradePass.Run`, `advance`, `Rewind`, `Admit` | `TestUpgradePassCursorFollowsThePagesBehindIt`, `TestUpgradePassRestartContinuesAtTheCursor`, `TestUpgradePassRefusesWithProgress`, `TestUpgradePassRewindAtOpenAfterARebuiltPage`, `TestUpgradePassPauseAndHurry`, `TestUpgradePassFailedRewindLatchesUntilReopen`, `TestUpgradePassRewindOnlyBeforeRun`, `TestUpgradePassKeepsItsCountAcrossRuns`, `TestUpgradePassCursorRuleUnderInterleavings` (`core/storage/chunk_upgrade_pass_test.go`) | UpgradePass `BehindCursorKnown`, `NoWorkTwice`; UpgradeWide3 rows 119 to 124, rewinds at restart only (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-RECORD-RUNTIME-001` | While serving: state only via the kernel, a known hash only with its evidence; a page dirties only when a state or hash changes, is written by its own count or age, an evict's at once, in snapshot order; header G = min(applied, dirty pages' dirty-from). | M3 Serving (chunk record runtime) | `core/storage/chunk_record_runtime.go` `chunkRecordRuntime.Apply`, `Due`, `WriteDue`, `WriteThrough`, `Flush` | `TestRecordRuntimeAppliesTheKernel`, `TestRecordRuntimeEvictWritesThePageFirst`, `TestRecordRuntimeSchedulePerPage`, `TestRecordRuntimeFlushIsLoadedBack`, `TestRecordRuntimeWriteThrough`, `TestRecordRuntimeAnUnchangedStateWritesNothing`, `TestRecordRuntimeHeaderMovesUnderWrites`, `TestRecordRuntimeEvictDuringAFlushLandsLast`, `TestRecordRuntimePageWritesFollowChangesNotSize`, `TestRecordRuntimePageWritersPublishInOrder`, `TestRecordRuntimeHashEvidence`, `TestRecordRuntimeCopiesItsInputs`, `TestRecordRuntimeAPageChangedAtOpenHoldsG` (`core/storage/chunk_record_runtime_test.go`) | chunk-kernel/2; ChunkPages rule 1 (pages before the header) and rule 3 (an evict writes its page first) (the per-chunk state models are not in this repository) | STUB | | `INV-CHUNK-RECORD-PAYLOAD-001` | Persisting and loading a chunk record preserves every entry's state and hash, including entries on either side of a segment boundary. | M1 chunk record codec (caller not wired) | `core/storage/chunk_record.go` `encodeChunkRecordPage`, `decodeChunkRecordPage` | `TestRecordEntryPayloadRoundTripsAcrossSegments` (`core/storage/chunk_record_test.go`; state-zero and one-entry hash-drop controls) | Encoding fidelity; no state transition change | STUB | +| `INV-CHUNK-COVERAGE-RETAINED-001` | A coverage-map baseline is installed by recovery only when every chunk position is at or below the retained WAL frontier; a discarded suffix cannot regain local bits through later LSN reuse. | M1 recovery (caller not wired) | `core/storage/walstore_v3.go` `WALStore.recoverV3` | `TestChunkCoverageBaselineCannotOutliveItsRetainedWAL` | SlotFence2 position-check premise; storage component guard | STUB | +| `INV-CHUNK-LOCAL-COVERAGE-001` | Coverage returns local none/some/all and the chunk position from one observation; it is unavailable until successful recovery and bitmap initialization. | M1 chunk bitmap (caller not wired) | `core/storage/chunk_coverage.go` `WALStore.Coverage`, `WALStore.InitializeChunkCoverage` | `TestChunkCoverageBaselineCannotOutliveItsRetainedWAL`, `TestChunkCoverageAdmissionPrecedesSeed`, `TestChunkCoverageInitializesEmptyWithoutFabricatingLocalBlocks`, `TestChunkCoverageAcknowledgedWriteSurvivesReplay`, `TestChunkCoverageCheckpointKeepsAllAcrossAPageBoundary`, `TestChunkCoverageRequiresSuccessfulRecovery` (`core/storage/chunk_coverage_test.go`) | MoveWide2 durable per-block map premise; SlotFence publication | STUB | +| `INV-CHUNK-LOCAL-EPOCH-001` | After a format marker, initialization never reads legacy presence: the same epoch rebuilds pages from the bitmap; another epoch is refused without changing storage. | M1 bitmap initialization (caller not wired) | `core/storage/chunk_coverage.go` `WALStore.InitializeChunkCoverage` | `TestChunkCoverageLegacyFenceCannotRelabelAnInitializedEpoch`, `TestChunkCoverageMarkedEpochNeverReseedsPresence`, `TestChunkCoverageMarkerWithoutBitmapCannotReadPresence` (`core/storage/chunk_coverage_test.go`) | SlotFence marker authority; UpgradeWide3 | STUB | +| `INV-CHUNK-HALF-FENCE-FALLBACK-001` | A damaged selected marked map may fall back only on integrity-only errors, to an intact valid unmarked slot of the same store incarnation; two marked slots never authorize fallback. Each successful fallback reports a typed event and one process-local counter increment. | M1 half-fence open (caller not wired) | `core/storage/walstore_v3.go` `openWALStoreV3File`, `coverageHalfFenceFallbackEligible` | `TestChunkCoverageHalfFenceReusedMapOpensTheIntactLegacySlot`, `TestChunkCoverageBothMarkedDamagedMapNeverFallsBack` (`core/storage/chunk_coverage_test.go`) | SlotFence2.OpenNew | STUB | | `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-CONFLICT-001` | Open is refused when both v3 descriptor slots are valid but carry the same slotGen with different bytes, or disagree on the UUID or the geometry. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3`, `sameGeometryV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`) | — | ACTIVE | | `INV-WAL-V3-RECORD-001` | An impl-3 WAL record has a fixed 62-byte prefix, 70 bytes of overhead in all, a CRC32C (Castagnoli) and an explicit EntrySize. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `encodeWALEntryV3`, `payloadSizeV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | ACTIVE | diff --git a/seaweed-block/docs/design/model-code-trace-coverage.tsv b/seaweed-block/docs/design/model-code-trace-coverage.tsv new file mode 100644 index 0000000000..cd93d08afa --- /dev/null +++ b/seaweed-block/docs/design/model-code-trace-coverage.tsv @@ -0,0 +1,10 @@ +model item go_function tests status +SlotFence prepare pages before publishing the field core/storage/chunk_coverage.go:WALStore.InitializeChunkCoverage core/storage/chunk_coverage_test.go:TestChunkCoveragePreparedViewPrecedesTheFence; core/storage/chunk_coverage_test.go:TestChunkCoveragePreparedReaderRemainsImmutableAfterWrites STUB +MoveWide2 durable per-block map premise core/storage/chunk_coverage_map.go:readCoverageMapPagesV3; core/storage/walstore_map_checkpoint_v3.go:prepareOwnedMapCheckpointV3 core/storage/chunk_coverage_test.go:TestChunkCoverageCheckpointKeepsAllAcrossAPageBoundary STUB +MoveWide2 WAL suffix restores local bits core/storage/walstore_map_checkpoint_v3.go:recordMapReplayV3 core/storage/chunk_coverage_test.go:TestChunkCoverageAcknowledgedWriteSurvivesReplay STUB +SlotFence marker excludes legacy seeding and cross-epoch initialization core/storage/chunk_coverage.go:WALStore.InitializeChunkCoverage core/storage/chunk_coverage_test.go:TestChunkCoverageMarkedEpochNeverReseedsPresence; core/storage/chunk_coverage_test.go:TestChunkCoverageMarkerWithoutBitmapCannotReadPresence STUB +MoveWide2 typed atomic bitmap observation core/storage/chunk_coverage.go:WALStore.Coverage core/storage/chunk_coverage_test.go:TestChunkCoverageRequiresSuccessfulRecovery; core/storage/chunk_coverage_test.go:TestChunkCoverageSeedsPartialWholeAndLastShortChunk STUB +MoveWide2 bounded fanout format and shared COW nodes core/storage/chunk_coverage_map.go:encodeCoverageTreeRootV3; core/storage/chunk_coverage_map.go:coverageTreeRefsV3 core/storage/chunk_coverage_test.go:TestChunkCoverageTreeKeepsBothIndexBranches STUB +SlotFence uncertain publication resumes only after reopen and recovery core/storage/chunk_coverage.go:WALStore.InitializeChunkCoverage; core/storage/chunk_coverage.go:WALStore.finishCoverageFenceLocked core/storage/chunk_coverage_test.go:TestChunkCoverageFailedPublicationResumesAfterRecovery STUB +SlotFence BASE and reset exclude upgrade before callback or publication core/storage/chunk_coverage.go:WALStore.InitializeChunkCoverage core/storage/chunk_coverage_test.go:TestChunkCoverageInitializationRefusesActiveBaseBeforeWriting STUB +SlotFence2 intact unmarked half-fence fallback only, typed event and process counter core/storage/walstore_v3.go:openWALStoreV3File; core/storage/walstore_v3.go:coverageHalfFenceFallbackEligible core/storage/chunk_coverage_test.go:TestChunkCoverageHalfFenceReusedMapOpensTheIntactLegacySlot; core/storage/chunk_coverage_test.go:TestChunkCoverageBothMarkedDamagedMapNeverFallsBack; core/storage/chunk_coverage_test.go:TestChunkCoverageFallbackRequiresIntegrityOnlyErrorTree; core/storage/chunk_coverage_test.go:TestChunkCoverageFallbackAuthorityGuards; core/storage/chunk_coverage_test.go:TestChunkCoverageFallbackRefusesUnavailableOtherDependencies STUB