From b62d2d99d5fd6fac4f27f589684c903a45386f92 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 02:57:42 -0800 Subject: [PATCH] test(storage): an unfinished chunk record behind the store is never trusted The record pages, their header, and a reader. The red: pages are written, the fence is left half done, a writer that does not keep the pages acknowledges a write, and the new version opens again with the store still marked; the reader takes the pages that miss that write. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_record.go | 229 ++++++++++++++++++ .../core/storage/chunk_record_test.go | 212 ++++++++++++++++ 2 files changed, 441 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_record.go create mode 100644 seaweed-block/core/storage/chunk_record_test.go diff --git a/seaweed-block/core/storage/chunk_record.go b/seaweed-block/core/storage/chunk_record.go new file mode 100644 index 0000000000..edd0ca025b --- /dev/null +++ b/seaweed-block/core/storage/chunk_record.go @@ -0,0 +1,229 @@ +package storage + +import ( + "encoding/binary" + "errors" + "fmt" + "hash/crc32" + "os" + "path/filepath" +) + +// The persisted per-chunk record: one page per segment of +// chunkRecordSegment chunks and one header. A page carries each chunk's state +// and hash and the store position it is valid through; the header carries the +// local-work epoch and G, the position every page is valid through. +const chunkRecordSegment = 10000 + +var ( + chunkRecordPageMagic = [8]byte{'S', 'W', 'C', 'R', 'P', 'G', '0', '1'} + chunkRecordHeaderMagic = [8]byte{'S', 'W', 'C', 'R', 'H', 'D', '0', '1'} + + // errChunkRecordCheck: a page or header failed its check. + errChunkRecordCheck = errors.New("storage: chunk record: check failed") +) + +const chunkRecordEntryBytes = 1 + 32 + +type chunkRecordEntry struct { + State uint8 + Hash [32]byte +} + +type chunkRecordPage struct { + Segment uint64 + ValidThrough uint64 + Entries []chunkRecordEntry +} + +type chunkRecordHeader struct { + Epoch uint64 + Chunks uint64 + G uint64 +} + +func chunkRecordDir(storePath string) string { return storePath + ".chunkrecord" } + +func chunkRecordPageName(seg uint64) string { return fmt.Sprintf("page-%08d", seg) } + +const chunkRecordHeaderName = "header" + +func chunkRecordSegments(chunks uint64) uint64 { + return (chunks + chunkRecordSegment - 1) / chunkRecordSegment +} + +func encodeChunkRecordPage(p *chunkRecordPage) []byte { + le := binary.LittleEndian + b := make([]byte, 8+8+8+4, 8+8+8+4+len(p.Entries)*chunkRecordEntryBytes+4) + copy(b, chunkRecordPageMagic[:]) + le.PutUint64(b[8:], p.Segment) + le.PutUint64(b[16:], p.ValidThrough) + le.PutUint32(b[24:], uint32(len(p.Entries))) + for _, e := range p.Entries { + b = append(b, e.State) + b = append(b, e.Hash[:]...) + } + return le.AppendUint32(b, crc32.Checksum(b, crc32cTable)) +} + +func decodeChunkRecordPage(b []byte, seg uint64) (*chunkRecordPage, error) { + le := binary.LittleEndian + if len(b) < 8+8+8+4+4 || [8]byte(b[:8]) != chunkRecordPageMagic { + return nil, errChunkRecordCheck + } + body := b[:len(b)-4] + if crc32.Checksum(body, crc32cTable) != le.Uint32(b[len(b)-4:]) { + return nil, errChunkRecordCheck + } + n := int(le.Uint32(b[24:])) + if len(body) != 28+n*chunkRecordEntryBytes || le.Uint64(b[8:]) != seg { + return nil, errChunkRecordCheck + } + p := &chunkRecordPage{Segment: seg, ValidThrough: le.Uint64(b[16:]), Entries: make([]chunkRecordEntry, n)} + for i := range p.Entries { + at := 28 + i*chunkRecordEntryBytes + p.Entries[i].State = b[at] + copy(p.Entries[i].Hash[:], b[at+1:at+chunkRecordEntryBytes]) + } + return p, nil +} + +func encodeChunkRecordHeader(h chunkRecordHeader) []byte { + le := binary.LittleEndian + b := make([]byte, 8+24) + copy(b, chunkRecordHeaderMagic[:]) + le.PutUint64(b[8:], h.Epoch) + le.PutUint64(b[16:], h.Chunks) + le.PutUint64(b[24:], h.G) + return le.AppendUint32(b, crc32.Checksum(b, crc32cTable)) +} + +func decodeChunkRecordHeader(b []byte) (chunkRecordHeader, error) { + le := binary.LittleEndian + if len(b) != 8+24+4 || [8]byte(b[:8]) != chunkRecordHeaderMagic || + crc32.Checksum(b[:32], crc32cTable) != le.Uint32(b[32:]) { + return chunkRecordHeader{}, errChunkRecordCheck + } + return chunkRecordHeader{Epoch: le.Uint64(b[8:]), Chunks: le.Uint64(b[16:]), G: le.Uint64(b[24:])}, nil +} + +// writeChunkRecordFile writes one page or the header as one durable step: +// a temporary file, its fsync, a rename and the directory's fsync. +func writeChunkRecordFile(dir, name string, b []byte) error { + if err := os.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("storage: chunk record: %w", err) + } + if err := writeFileDurable(filepath.Join(dir, name), b); err != nil { + return fmt.Errorf("storage: chunk record: %w", err) + } + if err := syncDir(dir); err != nil { + return fmt.Errorf("storage: chunk record: fsync directory: %w", err) + } + return nil +} + +func writeChunkRecordPage(dir string, p *chunkRecordPage) error { + return writeChunkRecordFile(dir, chunkRecordPageName(p.Segment), encodeChunkRecordPage(p)) +} + +// completeChunkRecord writes the record's header, which makes the record +// complete. It is written only after the store's fence: both descriptor slots +// carry the chunk-state marker at this epoch, synced and read back. Before +// it, an old version may still open the store from an unmarked slot. +func completeChunkRecord(s *WALStore, dir string, h chunkRecordHeader) error { + if err := s.FenceChunkStateUpgrade(h.Epoch); err != nil { + return err + } + return writeChunkRecordFile(dir, chunkRecordHeaderName, encodeChunkRecordHeader(h)) +} + +// chunkRecordLoad is what a restart may take from the record. +type chunkRecordLoad struct { + // Complete: the header is valid and its epoch is the store's marked + // epoch. Pages then hold every segment whose page passed its check; + // Damaged names the rest, to be rebuilt from the store's bitmap. + Complete bool + Header chunkRecordHeader + Pages map[uint64]*chunkRecordPage + Damaged []uint64 + // Discarded says why an unfinished record was not used: the upgrade + // builds it again from the legacy presence. + Discarded string +} + +// loadChunkRecord reads the record of a store. marked and epoch are the +// store's descriptor marker; storePos is the store's last durable position +// after recovery (its replayed log included). +// +// An unfinished record (no valid header) is used only when every page is +// present, passes its check, and is valid through storePos: a page behind +// the store missed writes, for example those an old version acknowledged and +// checkpointed between the pages and the fence, so it is never trusted. A +// store without the marker discards any record: an old version published +// after the pages. +func loadChunkRecord(dir string, chunks uint64, marked bool, epoch, storePos uint64) (chunkRecordLoad, error) { + var out chunkRecordLoad + if !marked { + out.Discarded = "store not marked" + return out, nil + } + h, hdrErr := readChunkRecordHeader(dir) + if hdrErr != nil && !errors.Is(hdrErr, errChunkRecordCheck) && !errors.Is(hdrErr, os.ErrNotExist) { + return out, hdrErr + } + complete := hdrErr == nil && h.Epoch == epoch && h.Chunks == chunks + pages := make(map[uint64]*chunkRecordPage) + var damaged []uint64 + for seg := uint64(0); seg < chunkRecordSegments(chunks); seg++ { + b, err := os.ReadFile(filepath.Join(dir, chunkRecordPageName(seg))) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return out, fmt.Errorf("storage: chunk record: %w", err) + } + var p *chunkRecordPage + if err == nil { + p, err = decodeChunkRecordPage(b, seg) + } + if err == nil && len(p.Entries) != chunkRecordSegmentLen(chunks, seg) { + err = errChunkRecordCheck + } + if err != nil { + if !complete { + out.Discarded = fmt.Sprintf("unfinished record: page %d missing or damaged", seg) + return out, nil + } + damaged = append(damaged, seg) + continue + } + pages[seg] = p + } + out.Complete, out.Header, out.Pages, out.Damaged = complete, h, pages, damaged + if !complete { + out.Header = chunkRecordHeader{} + } + return out, nil +} + +func readChunkRecordHeader(dir string) (chunkRecordHeader, error) { + b, err := os.ReadFile(filepath.Join(dir, chunkRecordHeaderName)) + if err != nil { + return chunkRecordHeader{}, err + } + return decodeChunkRecordHeader(b) +} + +func chunkRecordSegmentLen(chunks, seg uint64) int { + if rest := chunks - seg*chunkRecordSegment; rest < chunkRecordSegment { + return int(rest) + } + return chunkRecordSegment +} + +// ChunkStateMarker reports the store's chunk-state upgrade marker: whether its +// descriptor carries the format and the epoch of local work. +func (s *WALStore) ChunkStateMarker() (marked bool, epoch uint64) { + if s.v3 == nil || s.v3.pub == nil { + return false, 0 + } + d := s.v3.pub.current() + return d.ChunkStateFormat == 1, d.LocalWorkEpoch +} diff --git a/seaweed-block/core/storage/chunk_record_test.go b/seaweed-block/core/storage/chunk_record_test.go new file mode 100644 index 0000000000..4f1c8050d5 --- /dev/null +++ b/seaweed-block/core/storage/chunk_record_test.go @@ -0,0 +1,212 @@ +package storage + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +// recordPagesAt writes a full set of pages for s, valid through pos, as the +// upgrade writes them before the store's fence. +func recordPagesAt(t *testing.T, s *WALStore, dir string, pos uint64) uint64 { + t.Helper() + chunks := uint64(s.NumBlocks()) / s.ChunkBlocks() + for seg := uint64(0); seg < chunkRecordSegments(chunks); seg++ { + p := &chunkRecordPage{Segment: seg, ValidThrough: pos, Entries: make([]chunkRecordEntry, chunkRecordSegmentLen(chunks, seg))} + for i := range p.Entries { + p.Entries[i] = chunkRecordEntry{State: 2, Hash: [32]byte{byte(i)}} + } + if err := writeChunkRecordPage(dir, p); err != nil { + t.Fatal(err) + } + } + return chunks +} + +// halfFence leaves s with one descriptor slot marked: the second slot's +// write fails, as a crash between the two would leave it. +func halfFence(t *testing.T, s *WALStore, epoch uint64) { + t.Helper() + writes := 0 + s.v3.testBeforeSlotWrite = func() error { + writes++ + if writes == 2 { + return errors.New("crash before the second slot") + } + return nil + } + if err := s.FenceChunkStateUpgrade(epoch); err == nil { + t.Fatal("half fence succeeded") + } +} + +func crashStore(t *testing.T, s *WALStore) { + t.Helper() + crashRecoveryHardeningStore(t, s) + s.mu.Lock() + s.closed = true + s.mu.Unlock() +} + +func reopenRecovered(t *testing.T, path string) *WALStore { + t.Helper() + r, err := openWALStoreV3MapInternalForTest(path, true) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + return r +} + +// The pages are written, the fence is half done, and then a writer that does +// not keep the pages (the old version, opening from its unmarked slot) +// acknowledges a write before the new version opens again. The store is still +// marked, so only the position check can tell that the pages miss the write. +func TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 2) + dir := chunkRecordDir(path) + chunks := recordPagesAt(t, s, dir, s.NextLSN()-1) + halfFence(t, s, 7) + _ = s.Close() + + old := reopenRecovered(t, path) + writeSynced(t, old, 3, 3) // acknowledged; the pages do not know it + crashStore(t, old) + + next := reopenRecovered(t, path) + marked, epoch := next.ChunkStateMarker() + if !marked || epoch != 7 { + t.Fatalf("store marker %v/%d; the control needs the half-fenced marked slot", marked, epoch) + } + got, err := loadChunkRecord(dir, chunks, marked, epoch, next.NextLSN()-1) + if err != nil { + t.Fatal(err) + } + if got.Pages != nil || got.Complete || !strings.Contains(got.Discarded, "valid through") { + t.Fatalf("pages that miss an acknowledged write were trusted: %+v", got) + } +} + +// The same window, with the old version's checkpoint: its publication drops +// the marker, so the whole record is discarded. +func TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 2) + oldPair := make([]byte, 2*slotSizeV3) + if _, err := s.fd.ReadAt(oldPair, 0); err != nil { + t.Fatal(err) + } + dir := chunkRecordDir(path) + chunks := recordPagesAt(t, s, dir, s.NextLSN()-1) + halfFence(t, s, 7) + _ = s.Close() + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + if _, err = f.WriteAt(oldPair, 0); err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + t.Fatal(err) + } + old := reopenRecovered(t, path) + writeSynced(t, old, 3, 3) + if err := old.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if err := old.Close(); err != nil { + t.Fatal(err) + } + + next := reopenRecovered(t, path) + marked, epoch := next.ChunkStateMarker() + got, err := loadChunkRecord(dir, chunks, marked, epoch, next.NextLSN()-1) + if err != nil { + t.Fatal(err) + } + if got.Pages != nil || got.Complete { + t.Fatalf("record trusted after the old version's checkpoint: %+v", got) + } +} + +// Pages current with the store, and the fence done: the header completes the +// record and a restart takes every page. +func TestCurrentPagesCompleteAfterTheFence(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 2) + dir := chunkRecordDir(path) + pos := s.NextLSN() - 1 + chunks := recordPagesAt(t, s, dir, pos) + if err := completeChunkRecord(s, dir, chunkRecordHeader{Epoch: 7, Chunks: chunks, G: pos}); err != nil { + t.Fatal(err) + } + marked, epoch := s.ChunkStateMarker() + got, err := loadChunkRecord(dir, chunks, marked, epoch, s.NextLSN()-1) + if err != nil { + t.Fatal(err) + } + if !got.Complete || got.Header.G != pos || len(got.Pages) != int(chunkRecordSegments(chunks)) || len(got.Damaged) != 0 { + t.Fatalf("complete record not loaded: %+v", got) + } +} + +// The header is never written before both slots are fenced. +func TestRecordHeaderWaitsForTheFence(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + dir := chunkRecordDir(path) + chunks := recordPagesAt(t, s, dir, s.NextLSN()-1) + writes := 0 + s.v3.testBeforeSlotWrite = func() error { + writes++ + if writes == 2 { + return errors.New("second slot fails") + } + return nil + } + if err := completeChunkRecord(s, dir, chunkRecordHeader{Epoch: 7, Chunks: chunks}); err == nil { + t.Fatal("header written with one slot fenced") + } + if _, err := os.Stat(filepath.Join(dir, chunkRecordHeaderName)); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("header exists before the fence: %v", err) + } +} + +// In a complete record a damaged page is named for rebuild; in an unfinished +// one any damaged page discards the record. +func TestDamagedPage(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + dir := chunkRecordDir(path) + pos := s.NextLSN() - 1 + chunks := recordPagesAt(t, s, dir, pos) + page := filepath.Join(dir, chunkRecordPageName(0)) + b, err := os.ReadFile(page) + if err != nil { + t.Fatal(err) + } + b[30] ^= 1 + if err := os.WriteFile(page, b, 0o644); err != nil { + t.Fatal(err) + } + got, err := loadChunkRecord(dir, chunks, true, 7, pos) + if err != nil || got.Pages != nil || got.Discarded == "" { + t.Fatalf("unfinished record with a damaged page: %+v %v", got, err) + } + if err := completeChunkRecord(s, dir, chunkRecordHeader{Epoch: 7, Chunks: chunks, G: pos}); err != nil { + t.Fatal(err) + } + got, err = loadChunkRecord(dir, chunks, true, 7, pos) + if err != nil || !got.Complete || len(got.Damaged) != 1 || got.Damaged[0] != 0 { + t.Fatalf("complete record with a damaged page: %+v %v", got, err) + } +}