From 57387740f17e6c0322bf63a5c1f2e4e27acf6f8c Mon Sep 17 00:00:00 2001 From: tamirms Date: Wed, 25 Nov 2026 11:20:20 +0000 Subject: [PATCH 1/5] Check index and sorted files for corruption (format version 2) A flipped bit in an index's seed, key count, user metadata or RAM index made lookups land wrong with no error, and sorted files had no checksum. Index files: an xxHash64 HeaderHash in the header's reserved bytes covers the header, user metadata and algo config, and is checked at open. Each RAM index entry gains a CRC-32C over the entry and its block index, which a lookup verifies for the two entries it reads. Verify now covers every byte: it also rejects non-zero reserved footer bytes and no longer skips an empty metadata region. A lookup still does not check the payload or block metadata it reads; that takes Verify. Sorted files: the header gains an xxHash64 RecordsHash and HeaderHash, written by Finish with the count. The header hash is checked whenever a header is read, and the records hash once BuildFromSortedFiles, MergeSortedFiles or SortedFileReader has read every record. Both formats go to version 0x0002; version 1 files must be rebuilt. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01AqbUZNMtZZBu8cT6ZLzFVp --- corrupt_input_fuzz_test.go | 3 + corruption_context_test.go | 1 + framework_test.go | 2 +- header.go | 64 +++++++-- index.go | 93 +++++++----- index_writer.go | 50 +++---- index_writer_test.go | 4 +- integrity_test.go | 285 +++++++++++++++++++++++++++++++++++++ open_variants_test.go | 6 +- sorted_build.go | 23 ++- sorted_build_test.go | 2 + sorted_file.go | 157 ++++++++++++++------ sorted_file_test.go | 19 ++- sorted_merge.go | 17 ++- streamhash-spec.md | 118 ++++++++++----- 15 files changed, 662 insertions(+), 182 deletions(-) create mode 100644 integrity_test.go diff --git a/corrupt_input_fuzz_test.go b/corrupt_input_fuzz_test.go index 3b33eed..f1c7d09 100644 --- a/corrupt_input_fuzz_test.go +++ b/corrupt_input_fuzz_test.go @@ -174,5 +174,8 @@ func FuzzOpenCorruptIndex(f *testing.F) { }() exerciseCorruptIndex(data, base.keys, base.hasPayload) + // With the checksums recomputed, the edits reach the code behind them. + rehashIndex(data) + exerciseCorruptIndex(data, base.keys, base.hasPayload) }) } diff --git a/corruption_context_test.go b/corruption_context_test.go index 9729278..a6e7228 100644 --- a/corruption_context_test.go +++ b/corruption_context_test.go @@ -91,6 +91,7 @@ func TestCorruptionDetection(t *testing.T) { for i := 0; i < 5 && ramIndexOffset+i < len(corrupted); i++ { corrupted[ramIndexOffset+i] = 0xFF } + rehashIndex(corrupted) if err := os.WriteFile(corruptedPath, corrupted, 0644); err != nil { t.Fatal(err) } diff --git a/framework_test.go b/framework_test.go index aab4938..bea413b 100644 --- a/framework_test.go +++ b/framework_test.go @@ -531,7 +531,7 @@ func TestRAMIndexEntryRoundtrip(t *testing.T) { MetadataOffset: rng.Uint64() & mask40, } - encodeRAMIndexEntryTo(e, buf) + encodeRAMIndexEntryTo(e, uint32(i), buf) got := decodeRAMIndexEntry(buf) if got.KeysBefore != e.KeysBefore { diff --git a/header.go b/header.go index 2017f49..3eff911 100644 --- a/header.go +++ b/header.go @@ -2,7 +2,9 @@ package streamhash import ( "encoding/binary" + "hash/crc32" + "github.com/cespare/xxhash/v2" "github.com/stellar/streamhash/internal/sherr" ) @@ -12,7 +14,7 @@ const ( magic = uint32(0x53544D48) // version is the current format version - version = uint16(0x0001) + version = uint16(0x0002) // headerSize is the exact size of the serialized header (64 bytes) headerSize = 64 @@ -20,10 +22,16 @@ const ( // footerSize is the exact size of the serialized footer (32 bytes) footerSize = 32 - // ramIndexEntrySize is the size of each RAM index entry (10 bytes for compact layout) - // Format: [KeysBefore: 40 bits (5 bytes)][MetadataOffset: 40 bits (5 bytes)] + // headerHashOffset is where the header's HeaderHash is. + headerHashOffset = 56 + + // ramIndexEntrySize is the size of each RAM index entry. + // Format: [KeysBefore: 40 bits (5 bytes)][MetadataOffset: 40 bits (5 bytes)][Check: 4 bytes] // This supports up to ~1.1 trillion keys and ~1.1TB metadata region. - ramIndexEntrySize = 10 + ramIndexEntrySize = 14 + + // ramIndexEntryDataSize is the entry's bytes before its check. + ramIndexEntryDataSize = 10 ) // header is the 64-byte file header (spec §3.2). @@ -32,14 +40,15 @@ const ( // // Offset Size Field Type // 0 4 Magic 0x53544D48 ("STMH") -// 4 2 Version 0x0001 +// 4 2 Version 0x0002 // 6 8 TotalKeys uint64_le // 14 4 NumBlocks uint32_le // 18 4 PayloadSize uint32_le // 22 1 FingerprintSize uint8 (bytes) // 23 8 Seed uint64_le (globalSeed) // 31 2 BlockAlgorithm uint16_le (0=Bijection, 1=PTRHash) -// 33 31 Reserved [31]byte (zero) +// 33 23 Reserved [23]byte (zero) +// 56 8 HeaderHash uint64_le (xxHash64, see headerHash) // // Note: TotalBuckets, BucketsPerBlock, and PrefixBits are algorithm-internal. // Each algorithm derives these from NumBlocks using its own constants. @@ -53,7 +62,8 @@ type header struct { FingerprintSize uint8 // 1 byte: fingerprint bytes (0 = none) Seed uint64 // 8 bytes: global seed for hashing BlockAlgorithm Algorithm // 2 bytes: algorithm (0=Bijection, 1=PTRHash) - Reserved [31]byte // 31 bytes: reserved (zero) + Reserved [23]byte // 23 bytes: reserved (zero) + HeaderHash uint64 // 8 bytes: xxHash64 of the header and variable sections } // encodeTo serializes the header to an existing buffer. @@ -66,7 +76,17 @@ func (h *header) encodeTo(buf []byte) { buf[22] = h.FingerprintSize binary.LittleEndian.PutUint64(buf[23:31], h.Seed) binary.LittleEndian.PutUint16(buf[31:33], uint16(h.BlockAlgorithm)) - copy(buf[33:64], h.Reserved[:]) + copy(buf[33:56], h.Reserved[:]) + binary.LittleEndian.PutUint64(buf[56:64], h.HeaderHash) +} + +// headerHash is the HeaderHash of an index whose bytes before the RAM index +// are prefix: xxHash64 of them, without the HeaderHash bytes. +func headerHash(prefix []byte) uint64 { + d := xxhash.New() + _, _ = d.Write(prefix[:headerHashOffset]) + _, _ = d.Write(prefix[headerSize:]) + return d.Sum64() } // decodeHeader parses a 64-byte header. @@ -85,7 +105,8 @@ func decodeHeader(buf []byte) (*header, error) { Seed: binary.LittleEndian.Uint64(buf[23:31]), BlockAlgorithm: Algorithm(binary.LittleEndian.Uint16(buf[31:33])), } - copy(h.Reserved[:], buf[33:64]) + copy(h.Reserved[:], buf[33:56]) + h.HeaderHash = binary.LittleEndian.Uint64(buf[56:64]) if h.Magic != magic { return nil, sherr.ErrInvalidMagic @@ -170,13 +191,14 @@ func decodeFooter(buf []byte) (*footer, error) { } // ramIndexEntry is a single entry in the RAM index. -// Each entry is 10 bytes (Compact Layout with uint40+uint40). +// Each entry is 14 bytes (Compact Layout with uint40+uint40, and a check). // -// Wire format (10 bytes packed, little-endian): +// Wire format (14 bytes packed, little-endian): // // Offset Size Field Type // 0 5 KeysBefore uint40_le (cumulative count, max ~1.1 trillion) // 5 5 MetadataOffset uint40_le (relative offset, max ~1.1 TB) +// 10 4 Check uint32_le (see ramIndexEntryCheck) // // Note: Payloads are at fixed offsets (globalRank × entrySize), so no BlockOffset needed. // MetadataOffset is relative to the start of the metadata region. @@ -185,9 +207,20 @@ type ramIndexEntry struct { MetadataOffset uint64 // Relative offset within metadata region (stored as 40-bit) } -// encodeRAMIndexEntryTo serializes a RAM index entry into an existing buffer. -// Uses little-endian 40-bit encoding for both fields. -func encodeRAMIndexEntryTo(e ramIndexEntry, buf []byte) { +var castagnoli = crc32.MakeTable(crc32.Castagnoli) + +// ramIndexEntryCheck is the check of block's entry, whose first +// ramIndexEntryDataSize bytes are data: CRC-32C of those bytes, continued +// from the block index as the running CRC. The index makes an entry read at +// another block's position fail too. Passing it as the running CRC, not as +// bytes, keeps a buffer off the heap on every lookup. +func ramIndexEntryCheck(block uint32, data []byte) uint32 { + return crc32.Update(block, castagnoli, data[:ramIndexEntryDataSize]) +} + +// encodeRAMIndexEntryTo serializes block's RAM index entry, with its check, +// into an existing buffer. Uses little-endian 40-bit encoding for both fields. +func encodeRAMIndexEntryTo(e ramIndexEntry, block uint32, buf []byte) { // Little-endian 40-bit KeysBefore (bytes 0-4) buf[0] = byte(e.KeysBefore) buf[1] = byte(e.KeysBefore >> 8) @@ -200,9 +233,10 @@ func encodeRAMIndexEntryTo(e ramIndexEntry, buf []byte) { buf[7] = byte(e.MetadataOffset >> 16) buf[8] = byte(e.MetadataOffset >> 24) buf[9] = byte(e.MetadataOffset >> 32) + binary.LittleEndian.PutUint32(buf[10:14], ramIndexEntryCheck(block, buf)) } -// decodeRAMIndexEntry parses a 10-byte RAM index entry. +// decodeRAMIndexEntry parses a RAM index entry without verifying its check. // Uses little-endian 40-bit decoding for both fields. func decodeRAMIndexEntry(buf []byte) ramIndexEntry { return ramIndexEntry{ diff --git a/index.go b/index.go index 91e4767..4b2eeef 100644 --- a/index.go +++ b/index.go @@ -19,8 +19,8 @@ import ( const ( // minFileSize is a conservative lower bound for valid index files. - // Derived from: headerSize(64) + variableSections(8 min) + ramIndex(30 min for 2 blocks + sentinel) - // + footerSize(32) = 134 bytes minimum structure. 304 adds margin for metadata region. + // Derived from: headerSize(64) + variableSections(8 min) + ramIndex(42 min for 2 blocks + sentinel) + // + footerSize(32) = 146 bytes minimum structure. 304 adds margin for metadata region. minFileSize = 304 ) @@ -46,7 +46,7 @@ type Index struct { userMetadata []byte // RAM index — entries are decoded on demand from this mmap-backed - // byte view via ramEntry(). Keeping it as []byte avoids the + // byte view via checkedRAMEntry(). Keeping it as []byte avoids the // per-Open allocation + decode loop a Go-heap []ramIndexEntry // would require, which scales linearly with NumBlocks. ramIndexBytes []byte @@ -138,7 +138,7 @@ func OpenBytes(data []byte) (*Index, error) { // initFromData parses the header and locates the variable-length // sections and RAM index inside idx.data. Open() only touches the // contiguous prefix (header + variable sections + RAM-index span); -// individual RAM index entries are decoded on demand via ramEntry(), +// individual RAM index entries are decoded on demand via checkedRAMEntry(), // and footer decoding is deferred to Verify(). func (idx *Index) initFromData() error { fileSize := uint64(len(idx.data)) @@ -178,6 +178,10 @@ func (idx *Index) initFromData() error { algoConfig := idx.data[offset : offset+uint64(algoConfigLen)] offset += uint64(algoConfigLen) + if headerHash(idx.data[:offset]) != hdr.HeaderHash { + return fmt.Errorf("%w: header", sherr.ErrChecksumFailed) + } + // Calculate RAM index position (after variable sections) idx.numRAMEntries = hdr.NumBlocks + 1 // includes sentinel ramIndexStart := offset @@ -189,7 +193,7 @@ func (idx *Index) initFromData() error { return sherr.ErrCorruptedIndex } - // RAM index — keep the mmap'd region as a byte view; ramEntry() + // RAM index — keep the mmap'd region as a byte view; checkedRAMEntry() // decodes individual entries on demand. See the field doc on Index. idx.ramIndexBytes = idx.data[ramIndexStart:ramIndexEnd] @@ -210,14 +214,19 @@ func (idx *Index) initFromData() error { return nil } -// ramEntry decodes RAM index entry i from the mmap'd byte view. -// decodeRAMIndexEntry reads exactly ramIndexEntrySize bytes from the -// start of the slice and does a per-byte little-endian unpack, so the -// open-ended slice expression is safe and incurs only one bounds -// check (avoiding the 3-index form keeps this method small enough to -// inline alongside the inlined decoder). -func (idx *Index) ramEntry(i uint32) ramIndexEntry { - return decodeRAMIndexEntry(idx.ramIndexBytes[uint64(i)*ramIndexEntrySize:]) +// checkedRAMEntry decodes RAM index entry i from the mmap'd byte view, and +// reports whether its check matches. +func (idx *Index) checkedRAMEntry(i uint32) (ramIndexEntry, bool) { + b := idx.ramIndexBytes[uint64(i)*ramIndexEntrySize:][:ramIndexEntrySize] + return decodeRAMIndexEntry(b), ramIndexEntryCheck(i, b) == binary.LittleEndian.Uint32(b[ramIndexEntryDataSize:]) +} + +// blockRAMEntries returns block i's entry and the next, which a lookup reads +// together, and reports whether both their checks match. +func (idx *Index) blockRAMEntries(i uint32) (entry, next ramIndexEntry, ok bool) { + entry, ok = idx.checkedRAMEntry(i) + next, nextOK := idx.checkedRAMEntry(i + 1) + return entry, next, ok && nextOK } // payloadMapping is the page-aligned part of the payload region, or nil for @@ -322,9 +331,9 @@ func (idx *Index) prefetch(keys [][]byte, advise func(start, end uint64)) { // reading them. ranges = ranges[:0] for _, b := range blocks { - e, next := idx.ramEntry(b), idx.ramEntry(b+1) + e, next, ok := idx.blockRAMEntries(b) start, end := idx.metadataRegionOffset+e.MetadataOffset, idx.metadataRegionOffset+next.MetadataOffset - if e.KeysBefore < next.KeysBefore && start < end && end <= uint64(len(idx.data)) { + if ok && e.KeysBefore < next.KeysBefore && start < end && end <= uint64(len(idx.data)) { ranges = append(ranges, byteRange{start, end}) } } @@ -368,6 +377,9 @@ func willNeed(ranges []byteRange, advise func(start, end uint64)) { } } +// errRAMIndexChecksum is preallocated: lookups return it. +var errRAMIndexChecksum = fmt.Errorf("%w: RAM index entry", sherr.ErrChecksumFailed) + // verifyFingerprintSeparated checks if the fingerprint matches. // Reads from the separated payload region. // Always uses extractFingerprint(k0, k1, fpSize) for both build and query. @@ -410,9 +422,11 @@ func (idx *Index) lookup(key []byte, checkFingerprint bool) (uint64, error) { } // Step 2: Get block info from RAM index (on-demand decode from - // mmap'd bytes — see ramEntry). - entry := idx.ramEntry(blockIdx) - nextEntry := idx.ramEntry(blockIdx + 1) + // mmap'd bytes — see checkedRAMEntry). + entry, nextEntry, ok := idx.blockRAMEntries(blockIdx) + if !ok { + return 0, errRAMIndexChecksum + } baseRank := entry.KeysBefore // KeysBefore is read raw from the (untrusted) RAM index and must be @@ -626,10 +640,12 @@ func (idx *Index) Stats() *Stats { } } -// Verify checks the integrity of the entire index. -// For separated layout, this verifies: -// 1. PayloadRegionHash (hash-of-hashes: H(H(b0) || H(b1) || ...)) -// 2. MetadataRegionHash (streaming hash of metadata region) +// Verify checks the integrity of the entire index, every byte of it: +// 1. HeaderHash, as Open does +// 2. The footer's reserved bytes, which must be zero (ErrCorruptedIndex) +// 3. Each RAM index entry's check +// 4. PayloadRegionHash (hash-of-hashes: H(H(b0) || H(b1) || ...)) +// 5. MetadataRegionHash (streaming hash of metadata region) // // The footer (last 32 bytes) is decoded on each Verify call rather than at Open time, // so Open() only touches the contiguous prefix and avoids a scattered page fault. @@ -649,22 +665,40 @@ func (idx *Index) Verify() error { defer adviseRandom(p) } + // The bytes may have changed since they were opened. + if headerHash(idx.data[:idx.ramIndexOffset]) != binary.LittleEndian.Uint64(idx.data[headerHashOffset:]) { + return fmt.Errorf("%w: header", sherr.ErrChecksumFailed) + } + // Lazy footer decode — only touched by Verify, not Open. fileSize := uint64(len(idx.data)) ft, err := decodeFooter(idx.data[fileSize-footerSize:]) if err != nil { return err } + if ft.Reserved != ([16]byte{}) { + return fmt.Errorf("%w: the footer's reserved bytes are not zero", sherr.ErrCorruptedIndex) + } numBlocks := idx.header.NumBlocks + // A file of no blocks still has entry 0, its sentinel. + entry, ok := idx.checkedRAMEntry(0) + if !ok { + return errRAMIndexChecksum + } + // Verify payload region hash using hash-of-hashes // This matches the build-time computation: fold per-block hashes in order payloadHasher := xxhash.New() for blockID := range numBlocks { // Get this block's payload range from RAM index - startKey := idx.ramEntry(blockID).KeysBefore - endKey := idx.ramEntry(blockID + 1).KeysBefore + next, ok := idx.checkedRAMEntry(blockID + 1) + if !ok { + return errRAMIndexChecksum + } + startKey, endKey := entry.KeysBefore, next.KeysBefore + entry = next if startKey > endKey { return sherr.ErrCorruptedIndex } @@ -694,7 +728,7 @@ func (idx *Index) Verify() error { } if payloadHasher.Sum64() != ft.PayloadRegionHash { - return sherr.ErrChecksumFailed + return fmt.Errorf("%w: payload region", sherr.ErrChecksumFailed) } // Verify metadata region hash (streaming hash of entire region) @@ -702,13 +736,8 @@ func (idx *Index) Verify() error { if footerOffset < idx.metadataRegionOffset { return sherr.ErrCorruptedIndex } - metadataRegionSize := footerOffset - idx.metadataRegionOffset - if metadataRegionSize > 0 { - metadataRegion := idx.data[idx.metadataRegionOffset:footerOffset] - actualMetaHash := xxhash.Sum64(metadataRegion) - if actualMetaHash != ft.MetadataRegionHash { - return sherr.ErrChecksumFailed - } + if xxhash.Sum64(idx.data[idx.metadataRegionOffset:footerOffset]) != ft.MetadataRegionHash { + return fmt.Errorf("%w: metadata region", sherr.ErrChecksumFailed) } return nil diff --git a/index_writer.go b/index_writer.go index be12d3d..79bd3e8 100644 --- a/index_writer.go +++ b/index_writer.go @@ -16,7 +16,7 @@ import ( const ramIndexBufEntries = (64 << 10) / ramIndexEntrySize // indexWriter writes index data to disk via positional *os.File.WriteAt calls. -// File layout: [Header 64B][UserMetaLen 4B][UserMeta][AlgoConfigLen 4B][AlgoConfig][RAM Index (N+1)×10B][Payload Region][Metadata Region][Footer 32B] +// File layout: [Header 64B][UserMetaLen 4B][UserMeta][AlgoConfigLen 4B][AlgoConfig][RAM Index (N+1)×14B][Payload Region][Metadata Region][Footer 32B] type indexWriter struct { file *os.File @@ -24,10 +24,6 @@ type indexWriter struct { payloadRegionOffset uint64 metadataRegionOffset uint64 - // Variable section offsets - userMetadataOffset uint64 - algoConfigOffset uint64 - // Write tracking metadataWriteOffset uint64 // Current write position in metadata region ramIndexWriteOffset uint64 // Current write position in RAM index @@ -95,9 +91,7 @@ func newIndexWriter(path string, cfg *buildConfig, numBlocks uint32, algo blockB // Compute region offsets for separated layout with variable sections // Layout: [Header][UserMetaLen 4B][UserMeta][AlgoConfigLen 4B][AlgoConfig][RAM Index]... - userMetadataOffset := uint64(headerSize) - algoConfigOffset := userMetadataOffset + 4 + uint64(userMetadataLen) - ramIndexOffset := algoConfigOffset + 4 + uint64(algoConfigLen) + ramIndexOffset := uint64(headerSize) + 4 + uint64(userMetadataLen) + 4 + uint64(algoConfigLen) ramIndexSize := uint64(numBlocks+1) * uint64(ramIndexEntrySize) payloadRegionOffset := ramIndexOffset + ramIndexSize payloadRegionSize := cfg.totalKeys * uint64(entrySize) @@ -113,8 +107,6 @@ func newIndexWriter(path string, cfg *buildConfig, numBlocks uint32, algo blockB file: file, payloadRegionOffset: payloadRegionOffset, metadataRegionOffset: metadataRegionOffset, - userMetadataOffset: userMetadataOffset, - algoConfigOffset: algoConfigOffset, metadataWriteOffset: metadataRegionOffset, ramIndexWriteOffset: ramIndexOffset, ramIndexBuf: make([]byte, 0, min(ramIndexSize, ramIndexBufEntries*ramIndexEntrySize)), @@ -198,12 +190,13 @@ func (iw *indexWriter) recordAndWriteMetadata(metadata []byte) error { // appendRAMIndexEntry buffers the RAM index entry for the current key count // and metadata write position. func (iw *indexWriter) appendRAMIndexEntry() { - var entry [ramIndexEntrySize]byte + // Encoded in place: the check would move a local array to the heap. + n := len(iw.ramIndexBuf) + iw.ramIndexBuf = append(iw.ramIndexBuf, make([]byte, ramIndexEntrySize)...) encodeRAMIndexEntryTo(ramIndexEntry{ KeysBefore: iw.keyCount, MetadataOffset: iw.metadataWriteOffset - iw.metadataRegionOffset, - }, entry[:]) - iw.ramIndexBuf = append(iw.ramIndexBuf, entry[:]...) + }, iw.blockCount, iw.ramIndexBuf[n:]) } // flushRAMIndex writes the buffered RAM index entries after those already @@ -276,33 +269,22 @@ func (iw *indexWriter) finalize() error { iw.header.TotalKeys = iw.keyCount iw.header.NumBlocks = iw.blockCount - // Write header at offset 0 - var headerBuf [headerSize]byte - iw.header.encodeTo(headerBuf[:]) - if err := iw.writeAt(headerBuf[:], 0); err != nil { - primaryErr := fmt.Errorf("write header failed: %w", err) - return errors.Join(primaryErr, iw.close()) - } - - // Write variable-length sections - // UserMetadata: [length 4B][data] - userMetaBuf := make([]byte, 4+len(iw.userMetadata)) + // The header, then the variable-length sections, each [length 4B][data]: + // UserMetadata, then AlgoConfig + algoConfigLen := iw.algo.GlobalConfigSize() + prefix := make([]byte, headerSize+4+len(iw.userMetadata)+4+algoConfigLen) + iw.header.encodeTo(prefix) + userMetaBuf := prefix[headerSize:] binary.LittleEndian.PutUint32(userMetaBuf, uint32(len(iw.userMetadata))) copy(userMetaBuf[4:], iw.userMetadata) - if err := iw.writeAt(userMetaBuf, int64(iw.userMetadataOffset)); err != nil { - primaryErr := fmt.Errorf("write user metadata failed: %w", err) - return errors.Join(primaryErr, iw.close()) - } - - // AlgoConfig: [length 4B][data] - algoConfigLen := iw.algo.GlobalConfigSize() - algoConfigBuf := make([]byte, 4+algoConfigLen) + algoConfigBuf := userMetaBuf[4+len(iw.userMetadata):] binary.LittleEndian.PutUint32(algoConfigBuf, uint32(algoConfigLen)) if algoConfigLen > 0 { iw.algo.EncodeGlobalConfigInto(algoConfigBuf[4:]) } - if err := iw.writeAt(algoConfigBuf, int64(iw.algoConfigOffset)); err != nil { - primaryErr := fmt.Errorf("write algo config failed: %w", err) + binary.LittleEndian.PutUint64(prefix[headerHashOffset:], headerHash(prefix)) + if err := iw.writeAt(prefix, 0); err != nil { + primaryErr := fmt.Errorf("write header failed: %w", err) return errors.Join(primaryErr, iw.close()) } diff --git a/index_writer_test.go b/index_writer_test.go index f3a141e..f18729f 100644 --- a/index_writer_test.go +++ b/index_writer_test.go @@ -28,7 +28,7 @@ func TestRAMIndexAcrossBufferFlushes(t *testing.T) { want := make([]byte, (numBlocks+1)*ramIndexEntrySize) var entry ramIndexEntry for b := range numBlocks { - encodeRAMIndexEntryTo(entry, want[b*ramIndexEntrySize:]) + encodeRAMIndexEntryTo(entry, b, want[b*ramIndexEntrySize:]) numKeys := int(b % 5) metadata := bytes.Repeat([]byte{byte(b)}, int(b%3)) if err := iw.commitBlockWithData(metadata, nil, numKeys); err != nil { @@ -37,7 +37,7 @@ func TestRAMIndexAcrossBufferFlushes(t *testing.T) { entry.KeysBefore += uint64(numKeys) entry.MetadataOffset += uint64(len(metadata)) } - encodeRAMIndexEntryTo(entry, want[numBlocks*ramIndexEntrySize:]) + encodeRAMIndexEntryTo(entry, numBlocks, want[numBlocks*ramIndexEntrySize:]) if cap(iw.ramIndexBuf) > ramIndexBufEntries*ramIndexEntrySize { t.Fatalf("the writer buffered %d bytes of RAM index", cap(iw.ramIndexBuf)) } diff --git a/integrity_test.go b/integrity_test.go new file mode 100644 index 0000000..c2870c1 --- /dev/null +++ b/integrity_test.go @@ -0,0 +1,285 @@ +package streamhash + +import ( + "context" + "encoding/binary" + "errors" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/cespare/xxhash/v2" +) + +// rehashIndex recomputes the HeaderHash and the RAM index entries' checks of +// the index in data, so that a test's patch reaches the code behind them. +func rehashIndex(data []byte) { + off := uint64(headerSize) + for range 2 { + if off+4 > uint64(len(data)) { + return + } + off += 4 + uint64(binary.LittleEndian.Uint32(data[off:])) + } + if off > uint64(len(data)) { + return + } + binary.LittleEndian.PutUint64(data[headerHashOffset:], headerHash(data[:off])) + entries := uint64(binary.LittleEndian.Uint32(data[14:])) + 1 + for i := uint64(0); i < entries && off+ramIndexEntrySize <= uint64(len(data)); i++ { + entry := data[off : off+ramIndexEntrySize] + binary.LittleEndian.PutUint32(entry[ramIndexEntryDataSize:], ramIndexEntryCheck(uint32(i), entry)) + off += ramIndexEntrySize + } +} + +// rehashSortedFile recomputes the RecordsHash and HeaderHash of the sorted +// file in data, so that a test's patch reaches the code behind them. +func rehashSortedFile(data []byte) { + if len(data) < sortedFileFixedSize { + return + } + metadataLen := int(binary.LittleEndian.Uint32(data[sortedFileMetadataLenOffset:])) + if metadataLen > len(data)-sortedFileFixedSize { + return + } + if off := sortedFileRecordsOffset(metadataLen); off <= int64(len(data)) { + binary.LittleEndian.PutUint64(data[sortedFileRecordsHashOffset:], xxhash.Sum64(data[off:])) + } + hash := sortedFileHeaderHash(data[:sortedFileFixedSize], data[sortedFileFixedSize:sortedFileFixedSize+metadataLen]) + binary.LittleEndian.PutUint64(data[sortedFileHeaderHashOffset:], hash) +} + +// integrityIndex builds an index of several blocks, with payloads, +// fingerprints and user metadata, and returns its bytes and records. +func integrityIndex(t *testing.T) ([]byte, []sortedRecord) { + t.Helper() + recs := uniqueSortedRecords(newTestRNG(t), 20000, 3) + path := filepath.Join(t.TempDir(), "index.idx") + return referenceIndex(t, path, recs, WithPayload(3), WithFingerprint(1), WithMetadata([]byte("user metadata"))), recs +} + +// TestOpenChecksHeaderHash flips a bit in every byte Open reads: the header, +// the user metadata and the algorithm config. +func TestOpenChecksHeaderHash(t *testing.T) { + data, _ := integrityIndex(t) + idx, err := OpenBytes(data) + if err != nil { + t.Fatal(err) + } + for off := range idx.ramIndexOffset { + bad := slices.Clone(data) + bad[off] ^= 0x10 + _, err := OpenBytes(bad) + if err == nil { + t.Fatalf("Open accepted a flipped bit in byte %d", off) + } + // No other check covers TotalKeys' low bytes, the seed or the user + // metadata. + if (off >= 6 && off < 10 || off >= 23 && off < 31 || off >= 68 && off < 81) && !errors.Is(err, ErrChecksumFailed) { + t.Fatalf("a flipped bit in byte %d returned %v, want ErrChecksumFailed", off, err) + } + } +} + +// TestLookupChecksRAMIndexEntry flips a bit in each field of a block's RAM +// index entry, and moves an intact entry to another block's position. +func TestLookupChecksRAMIndexEntry(t *testing.T) { + data, recs := integrityIndex(t) + clean, err := OpenPayloadBytes(data) + if err != nil { + t.Fatal(err) + } + numBlocks := clean.NumBlocks() + if numBlocks < 4 { + t.Fatalf("the index has %d blocks, the test needs 4", numBlocks) + } + const block = 2 + entry := func(data []byte, b uint32) []byte { + return data[clean.ramIndexOffset+uint64(b)*ramIndexEntrySize:][:ramIndexEntrySize] + } + for _, tc := range []struct { + name string + mutate func(data []byte) + }{ + {"KeysBefore", func(data []byte) { entry(data, block)[0] ^= 1 }}, + {"MetadataOffset", func(data []byte) { entry(data, block)[5] ^= 1 }}, + {"another block's entry", func(data []byte) { copy(entry(data, block), entry(data, block+1)) }}, + } { + t.Run(tc.name, func(t *testing.T) { + bad := slices.Clone(data) + tc.mutate(bad) + idx, err := OpenPayloadBytes(bad) + if err != nil { + t.Fatal(err) + } + for _, r := range recs { + // A lookup reads its block's entry and the next. + b := blockIndexFromPrefix(extractPrefix(r.key[:]), numBlocks) + reads := b == block || b == block-1 + _, payload, err := idx.QueryPayload(r.key[:]) + if reads && !errors.Is(err, ErrChecksumFailed) { + t.Fatalf("a lookup in block %d returned %v, want ErrChecksumFailed", b, err) + } + if !reads && (err != nil || payload != r.payload) { + t.Fatalf("a lookup in block %d returned %d, %v", b, payload, err) + } + } + if err := idx.Verify(); !errors.Is(err, ErrChecksumFailed) { + t.Fatalf("Verify returned %v, want ErrChecksumFailed", err) + } + }) + } +} + +// TestVerifyCoversWholeFile flips a bit in bytes past the ones Open checks: +// every byte of the RAM index and the footer, its reserved bytes included, +// and a sample of the regions between them. +func TestVerifyCoversWholeFile(t *testing.T) { + data, _ := integrityIndex(t) + idx, err := OpenBytes(data) + if err != nil { + t.Fatal(err) + } + if err := idx.Verify(); err != nil { + t.Fatal(err) + } + flipped := func(off int) { + t.Helper() + data[off] ^= 0x04 + if err := idx.Verify(); err == nil { + t.Fatalf("Verify accepted a flipped bit in byte %d of %d", off, len(data)) + } + data[off] ^= 0x04 + } + for off := int(idx.ramIndexOffset); off < int(idx.payloadRegionOffset); off++ { + flipped(off) + } + for off := int(idx.payloadRegionOffset); off < len(data)-footerSize; off += 97 { + flipped(off) + } + for off := len(data) - footerSize; off < len(data); off++ { + flipped(off) + } + data[headerHashOffset-1] ^= 0x04 + if err := idx.Verify(); !errors.Is(err, ErrChecksumFailed) { + t.Fatalf("Verify returned %v for a header changed since Open, want ErrChecksumFailed", err) + } +} + +// TestSortedFileRecordsHash flips a bit in a record's payload, which leaves +// the records in order, and checks that everything that reads the records +// rejects the file. +func TestSortedFileRecordsHash(t *testing.T) { + dir := t.TempDir() + rng := newTestRNG(t) + recs := uniqueSortedRecords(rng, 30000, 3) + clean, other := filepath.Join(dir, "clean.sorted"), filepath.Join(dir, "other.sorted") + writeSortedFile(t, clean, SortedFileConfig{PayloadSize: 3, Metadata: []byte("meta")}, recs) + writeSortedFile(t, other, SortedFileConfig{PayloadSize: 3}, uniqueSortedRecords(rng, 5000, 3)) + + // The first and last records, and one past a refill of the merge's buffer. + for _, i := range []int{0, 431, len(recs) - 1} { + data := readFileBytes(t, clean) + data[sortedFileAlign+i*19+MinKeySize] ^= 0x01 + corrupt := filepath.Join(dir, "corrupt.sorted") + if err := os.WriteFile(corrupt, data, 0o600); err != nil { + t.Fatal(err) + } + if _, err := ReadSortedFileHeader(corrupt); err != nil { + t.Fatalf("record %d: the header: %v", i, err) + } + + for _, w := range []int{1, 4} { + output := filepath.Join(dir, "corrupt.idx") + err := buildFilesWithWatchdog(t, context.Background(), output, []string{other, corrupt}, sortedBuildTuning{}, WithWorkers(w)) + if !errors.Is(err, ErrChecksumFailed) { + t.Fatalf("record %d: the build with %d workers returned %v, want ErrChecksumFailed", i, w, err) + } + if _, err := os.Stat(output); !os.IsNotExist(err) { + t.Fatalf("a failed build left its output: %v", err) + } + } + + output := filepath.Join(dir, "merged.sorted") + err := mergeWithWatchdog(t, context.Background(), output, []string{other, corrupt}, SortedFileConfig{PayloadSize: 3}, 2*directAlign) + if !errors.Is(err, ErrChecksumFailed) { + t.Fatalf("record %d: the merge returned %v, want ErrChecksumFailed", i, err) + } + if _, err := os.Stat(output); !os.IsNotExist(err) { + t.Fatalf("a failed merge left its output: %v", err) + } + + r, err := OpenSortedFile(corrupt) + if err != nil { + t.Fatal(err) + } + for range len(recs) - 1 { + if _, _, err := r.Next(); err != nil { + t.Fatalf("record %d: Next returned %v before the last record", i, err) + } + } + if _, _, err := r.Next(); !errors.Is(err, ErrChecksumFailed) { + t.Fatalf("record %d: Next returned %v for the last record, want ErrChecksumFailed", i, err) + } + r.Close() + } +} + +// TestSortedFileHeaderHash flips a bit in every byte of the fixed header and +// the metadata. +func TestSortedFileHeaderHash(t *testing.T) { + path := filepath.Join(t.TempDir(), "header.sorted") + writeSortedFile(t, path, SortedFileConfig{PayloadSize: 3, Metadata: []byte("meta")}, randomSortedRecords(newTestRNG(t), 10, 3)) + data := readFileBytes(t, path) + for off := range sortedFileFixedSize + len("meta") { + data[off] ^= 0x20 + if err := os.WriteFile(path, data, 0o600); err != nil { + t.Fatal(err) + } + _, err := ReadSortedFileHeader(path) + if err == nil { + t.Fatalf("a flipped bit in byte %d was accepted", off) + } + // Past the magic, version, payload size and metadata length, only + // the hash covers the header. A flipped count is caught by it first. + if off >= 7 && off < sortedFileMetadataLenOffset || off >= sortedFileFixedSize { + if !errors.Is(err, ErrChecksumFailed) { + t.Fatalf("a flipped bit in byte %d returned %v, want ErrChecksumFailed", off, err) + } + } + data[off] ^= 0x20 + } +} + +// TestSortedFileUnfinishedWriter checks that a file whose writer never reached +// Finish does not open, with or without records on disk. +func TestSortedFileUnfinishedWriter(t *testing.T) { + for _, records := range []int{0, 10} { + path := filepath.Join(t.TempDir(), "unfinished.sorted") + w, err := NewSortedFileWriter(path, SortedFileConfig{PayloadSize: 3}) + if err != nil { + t.Fatal(err) + } + for _, r := range randomSortedRecords(newTestRNG(t), records, 3) { + if err := w.Add(r.key[:], r.payload); err != nil { + t.Fatal(err) + } + } + // As a crash would leave it: written, never finished. + if err := w.bw.Flush(); err != nil { + t.Fatal(err) + } + if _, err := ReadSortedFileHeader(path); !errors.Is(err, ErrChecksumFailed) { + t.Fatalf("%d records: ReadSortedFileHeader returned %v, want ErrChecksumFailed", records, err) + } + if r, err := OpenSortedFile(path); err == nil { + r.Close() + t.Fatalf("%d records: OpenSortedFile accepted the file", records) + } + if err := w.f.Close(); err != nil { + t.Fatal(err) + } + } +} diff --git a/open_variants_test.go b/open_variants_test.go index 1e11efc..9e6308e 100644 --- a/open_variants_test.go +++ b/open_variants_test.go @@ -197,7 +197,11 @@ func TestMaxBlockKeys(t *testing.T) { // checked against adjacent cumulative counts in the RAM index (the // sentinel entry at NumBlocks makes the last block's count defined). for i := uint32(0); i < idx.NumBlocks(); i++ { - occ := idx.ramEntry(i+1).KeysBefore - idx.ramEntry(i).KeysBefore + e, next, ok := idx.blockRAMEntries(i) + if !ok { + t.Fatalf("block %d: its RAM index entries fail their checks", i) + } + occ := next.KeysBefore - e.KeysBefore if occ > uint64(idx.MaxBlockKeys()) { t.Fatalf("block %d holds %d keys, above the reported ceiling %d", i, occ, idx.MaxBlockKeys()) } diff --git a/sorted_build.go b/sorted_build.go index 77457ce..8b3ec57 100644 --- a/sorted_build.go +++ b/sorted_build.go @@ -9,6 +9,7 @@ import ( "os" "sync" + "github.com/cespare/xxhash/v2" intbits "github.com/stellar/streamhash/internal/bits" ) @@ -42,7 +43,8 @@ const ( // // The files are not merged. Each is checked, then read once, sequentially and // directly where the filesystem allows it. A file whose keys are out of order -// fails the build, and so does a duplicate key. +// fails the build, and so does a duplicate key, or a file whose records do +// not match its hash (ErrChecksumFailed). // // Speed: about 6M keys/s per worker (WithWorkers), up to what the disk reads // at 16+PayloadSize bytes per key. Memory: about 256 MiB, plus each worker's @@ -145,7 +147,7 @@ func (g *sortedBuild) start(ctx context.Context, runs []sortedRun) error { if err != nil { return err } - r := &fileReader{run: run, f: f, reqs: g.reqs, next: run.start, valid: -1} + r := &fileReader{run: run, f: f, reqs: g.reqs, next: run.start, valid: -1, hash: xxhash.New()} for range nbuf { r.bufs = append(r.bufs, alignedBuffer(bufSize)) r.done = append(r.done, make(chan readResult, 1)) @@ -289,6 +291,8 @@ func (g *sortedBuild) gather(ctx context.Context, s int, st *stripe) error { cut = firstAtOrPast(rest, recordSize, n, bound) } st.data = append(st.data, rest[:cut*recordSize]...) + // Only the gather sees a file's records in order. + _, _ = r.hash.Write(rest[:cut*recordSize]) r.pos += cut * recordSize count += cut if cut < n { @@ -335,11 +339,17 @@ func firstAtOrPast(buf []byte, recordSize, n int, bound uint64) int { return hi } -// checkCount checks that the gathered records add up to the files' counts. -func (g *sortedBuild) checkCount() error { +// checkInputs checks that the gathered records add up to the files' counts, +// and that each file's match its hash. +func (g *sortedBuild) checkInputs() error { if g.gathered != g.b.cfg.totalKeys { return fmt.Errorf("%w: read %d records, the sorted files count %d", ErrKeyCountMismatch, g.gathered, g.b.cfg.totalKeys) } + for _, r := range g.readers { + if err := r.run.check(r.hash.Sum64()); err != nil { + return err + } + } return nil } @@ -353,7 +363,7 @@ func (g *sortedBuild) buildInline(ctx context.Context) error { return errors.Join(err, b.cleanup()) } } - if err := g.checkCount(); err != nil { + if err := g.checkInputs(); err != nil { return errors.Join(err, b.cleanup()) } return b.finalizeIndex() @@ -420,7 +430,7 @@ func (g *sortedBuild) gatherAll(ctx context.Context, stripes chan<- *stripe, fre } stripes <- st // never blocks: inFlight stripes exist and stripes holds inFlight } - return g.checkCount() + return g.checkInputs() } // runStripeWorker routes and solves stripes until stripes closes or the @@ -536,6 +546,7 @@ type fileReader struct { reqs chan<- readRequest bufs [][]byte done []chan readResult // each buffer's read result; never full + hash *xxhash.Digest // of the records gathered next int64 // the file offset of the next read to post cur int // the buffer being consumed pos int // bytes of bufs[cur] consumed diff --git a/sorted_build_test.go b/sorted_build_test.go index 302f475..9ff9701 100644 --- a/sorted_build_test.go +++ b/sorted_build_test.go @@ -302,6 +302,7 @@ func TestBuildFromSortedFilesRejects(t *testing.T) { swapped := func(path string, recordSize, i int) string { data := readFileBytes(t, path) swapRecords(data, recordSize, i) + rehashSortedFile(data) out := filepath.Join(dir, fmt.Sprintf("swapped%d-%s", i, filepath.Base(path))) if err := os.WriteFile(out, data, 0o600); err != nil { t.Fatal(err) @@ -313,6 +314,7 @@ func TestBuildFromSortedFilesRejects(t *testing.T) { data := readFileBytes(t, path) span := data[sortedFileAlign+to*recordSize : sortedFileAlign+(from+1)*recordSize] copy(span, slices.Concat(span[len(span)-recordSize:], span[:len(span)-recordSize])) + rehashSortedFile(data) out := filepath.Join(dir, fmt.Sprintf("moved%d-%d-%s", from, to, filepath.Base(path))) if err := os.WriteFile(out, data, 0o600); err != nil { t.Fatal(err) diff --git a/sorted_file.go b/sorted_file.go index 256e7fd..129fccc 100644 --- a/sorted_file.go +++ b/sorted_file.go @@ -7,26 +7,34 @@ import ( "fmt" "io" "os" + + "github.com/cespare/xxhash/v2" ) // Sorted file header (spec §3.9): // // Offset Size Field Type // 0 4 Magic 0x53545346 ("STSF") -// 4 2 Version 0x0001 +// 4 2 Version 0x0002 // 6 1 PayloadSize uint8 (0-8) // 7 1 Reserved zero // 8 8 Count uint64_le -// 16 4 MetadataLen uint32_le -// 20 ML Metadata +// 16 8 RecordsHash uint64_le (xxHash64 of the records) +// 24 8 HeaderHash uint64_le (xxHash64 of the header's other fields and the metadata) +// 32 4 MetadataLen uint32_le +// 36 ML Metadata // // Zero bytes pad the header to a multiple of 4096, and the records follow. const ( sortedFileMagic = uint32(0x53545346) - sortedFileVersion = uint16(0x0001) + sortedFileVersion = uint16(0x0002) - sortedFileFixedSize = 20 - sortedFileCountOffset = 8 + sortedFileFixedSize = 36 + // Finish writes Count, RecordsHash and HeaderHash, which are contiguous. + sortedFileCountOffset = 8 + sortedFileRecordsHashOffset = 16 + sortedFileHeaderHashOffset = 24 + sortedFileMetadataLenOffset = 32 // sortedFileAlign aligns the records, so direct reads can start at them. // It is a multiple of directAlign. @@ -50,6 +58,17 @@ type SortedFileHeader struct { Metadata []byte // the SortedFileConfig.Metadata the file was written with } +// sortedFileHeaderHash is the HeaderHash of a header whose fixed fields are +// fixed: xxHash64 of the fields before HeaderHash, then MetadataLen and the +// metadata. +func sortedFileHeaderHash(fixed, metadata []byte) uint64 { + d := xxhash.New() + _, _ = d.Write(fixed[:sortedFileHeaderHashOffset]) + _, _ = d.Write(fixed[sortedFileMetadataLenOffset:sortedFileFixedSize]) + _, _ = d.Write(metadata) + return d.Sum64() +} + // recordsOffset is where the file's records start. func (h SortedFileHeader) recordsOffset() int64 { return sortedFileRecordsOffset(len(h.Metadata)) @@ -81,7 +100,9 @@ func (k sortKey) less(o sortKey) bool { // as PayloadSize little-endian bytes. MergeSortedFiles merges several into one. type SortedFileWriter struct { f *os.File + out *writebackWriter bw *bufio.Writer + header []byte // the fixed fields and the metadata recordSize int maxPayload uint64 last sortKey @@ -106,14 +127,18 @@ func NewSortedFileWriter(path string, cfg SortedFileConfig) (*SortedFileWriter, if err != nil { return nil, err } + header := encodeSortedFileHeader(cfg) + out := &writebackWriter{f: f, bytesPerSync: cfg.BytesPerSync, skip: len(header), records: xxhash.New()} w := &SortedFileWriter{ f: f, - bw: bufio.NewWriterSize(&writebackWriter{f: f, bytesPerSync: cfg.BytesPerSync}, 1<<20), + out: out, + bw: bufio.NewWriterSize(out, 1<<20), + header: header[:sortedFileFixedSize+len(cfg.Metadata)], recordSize: MinKeySize + cfg.PayloadSize, maxPayload: ^uint64(0) >> (64 - 8*cfg.PayloadSize), } // The header fits in the empty buffer, so this write cannot fail. - _, _ = w.bw.Write(encodeSortedFileHeader(cfg)) + _, _ = w.bw.Write(header) return w, nil } @@ -153,8 +178,8 @@ func (w *SortedFileWriter) appendEncoded(records []byte) error { return nil } -// Finish writes the record count, syncs and closes the file. If it fails, it -// removes the file. +// Finish writes the record count and the hashes, syncs and closes the file. +// If it fails, it removes the file. func (w *SortedFileWriter) Finish() error { if w.closed { return os.ErrClosed @@ -166,15 +191,18 @@ func (w *SortedFileWriter) Finish() error { return nil } -// commit flushes, patches the count, syncs and closes, in that order: a short -// file's header is still in the buffer until the flush, and ENOSPC and EIO -// can surface only at close. +// commit flushes, patches the count and the hashes, syncs and closes, in that +// order: a short file's header is still in the buffer until the flush, which +// also completes the records' hash, and ENOSPC and EIO can surface only at +// close. func (w *SortedFileWriter) commit() error { err := w.bw.Flush() if err == nil { - var count [8]byte - binary.LittleEndian.PutUint64(count[:], w.count) - _, err = w.f.WriteAt(count[:], sortedFileCountOffset) + fixed := w.header[:sortedFileFixedSize] + binary.LittleEndian.PutUint64(fixed[sortedFileCountOffset:], w.count) + binary.LittleEndian.PutUint64(fixed[sortedFileRecordsHashOffset:], w.out.records.Sum64()) + binary.LittleEndian.PutUint64(fixed[sortedFileHeaderHashOffset:], sortedFileHeaderHash(fixed, w.header[sortedFileFixedSize:])) + _, err = w.f.WriteAt(fixed[sortedFileCountOffset:sortedFileMetadataLenOffset], sortedFileCountOffset) } if err == nil { err = w.f.Sync() @@ -196,20 +224,28 @@ func encodeSortedFileHeader(cfg SortedFileConfig) []byte { binary.LittleEndian.PutUint32(buf[0:4], sortedFileMagic) binary.LittleEndian.PutUint16(buf[4:6], sortedFileVersion) buf[6] = byte(cfg.PayloadSize) - binary.LittleEndian.PutUint32(buf[16:20], uint32(len(cfg.Metadata))) + binary.LittleEndian.PutUint32(buf[sortedFileMetadataLenOffset:], uint32(len(cfg.Metadata))) copy(buf[sortedFileFixedSize:], cfg.Metadata) return buf } // writebackWriter writes to f, starting writeback every bytesPerSync bytes. +// It hashes what it writes past the first skip bytes, the header, into +// records: the buffer's flushes hash the records in bulk, where hashing in +// Add would cost several times more. type writebackWriter struct { f *os.File bytesPerSync int unsynced int + skip int + records *xxhash.Digest } func (w *writebackWriter) Write(p []byte) (int, error) { n, err := w.f.Write(p) + skipped := min(w.skip, n) + w.skip -= skipped + _, _ = w.records.Write(p[skipped:n]) if w.bytesPerSync > 0 { w.unsynced += n if w.unsynced >= w.bytesPerSync { @@ -220,56 +256,66 @@ func (w *writebackWriter) Write(p []byte) (int, error) { return n, err } -// ReadSortedFileHeader reads and checks the header at path: magic, version, -// payload size, and that the record count matches the file's length. -func ReadSortedFileHeader(path string) (SortedFileHeader, error) { +// readSortedFileHeaderAt is readSortedFileHeader for the file at path. +func readSortedFileHeaderAt(path string) (SortedFileHeader, uint64, error) { f, err := os.Open(path) if err != nil { - return SortedFileHeader{}, err + return SortedFileHeader{}, 0, err } defer f.Close() return readSortedFileHeader(f) } +// ReadSortedFileHeader reads and checks the header at path: magic, version, +// payload size, its hash, and that the record count matches the file's length. +// It does not read the records, so it does not check their hash. +func ReadSortedFileHeader(path string) (SortedFileHeader, error) { + h, _, err := readSortedFileHeaderAt(path) + return h, err +} + // readSortedFileHeader reads the header of f, which must not be open for -// direct reads: these reads are not aligned. -func readSortedFileHeader(f *os.File) (SortedFileHeader, error) { +// direct reads: these reads are not aligned. It also returns the RecordsHash. +func readSortedFileHeader(f *os.File) (SortedFileHeader, uint64, error) { info, err := f.Stat() if err != nil { - return SortedFileHeader{}, err + return SortedFileHeader{}, 0, err } size := info.Size() if size < sortedFileFixedSize { - return SortedFileHeader{}, fmt.Errorf("sorted file %s: %w", f.Name(), ErrTruncatedFile) + return SortedFileHeader{}, 0, fmt.Errorf("sorted file %s: %w", f.Name(), ErrTruncatedFile) } var fixed [sortedFileFixedSize]byte if _, err := f.ReadAt(fixed[:], 0); err != nil { - return SortedFileHeader{}, err + return SortedFileHeader{}, 0, err } if binary.LittleEndian.Uint32(fixed[0:4]) != sortedFileMagic { - return SortedFileHeader{}, fmt.Errorf("sorted file %s: %w", f.Name(), ErrInvalidMagic) + return SortedFileHeader{}, 0, fmt.Errorf("sorted file %s: %w", f.Name(), ErrInvalidMagic) } if binary.LittleEndian.Uint16(fixed[4:6]) != sortedFileVersion { - return SortedFileHeader{}, fmt.Errorf("sorted file %s: %w", f.Name(), ErrInvalidVersion) + return SortedFileHeader{}, 0, fmt.Errorf("sorted file %s: %w", f.Name(), ErrInvalidVersion) } - h := SortedFileHeader{PayloadSize: int(fixed[6]), Count: binary.LittleEndian.Uint64(fixed[8:16])} + h := SortedFileHeader{PayloadSize: int(fixed[6]), Count: binary.LittleEndian.Uint64(fixed[sortedFileCountOffset:])} if h.PayloadSize > maxPayloadSize { - return SortedFileHeader{}, fmt.Errorf("sorted file %s: %w: payload size %d", f.Name(), ErrCorruptedIndex, h.PayloadSize) + return SortedFileHeader{}, 0, fmt.Errorf("sorted file %s: %w: payload size %d", f.Name(), ErrCorruptedIndex, h.PayloadSize) } - metadataLen := binary.LittleEndian.Uint32(fixed[16:20]) + metadataLen := binary.LittleEndian.Uint32(fixed[sortedFileMetadataLenOffset:]) if metadataLen > maxSortedFileMetadata { - return SortedFileHeader{}, fmt.Errorf("sorted file %s: %w: metadata length %d is over the maximum of %d", f.Name(), ErrCorruptedIndex, metadataLen, maxSortedFileMetadata) + return SortedFileHeader{}, 0, fmt.Errorf("sorted file %s: %w: metadata length %d is over the maximum of %d", f.Name(), ErrCorruptedIndex, metadataLen, maxSortedFileMetadata) } recordsOffset := sortedFileRecordsOffset(int(metadataLen)) if size < recordsOffset { - return SortedFileHeader{}, fmt.Errorf("sorted file %s: %w", f.Name(), ErrTruncatedFile) + return SortedFileHeader{}, 0, fmt.Errorf("sorted file %s: %w", f.Name(), ErrTruncatedFile) } if metadataLen > 0 { h.Metadata = make([]byte, metadataLen) if _, err := f.ReadAt(h.Metadata, sortedFileFixedSize); err != nil { - return SortedFileHeader{}, err + return SortedFileHeader{}, 0, err } } + if sortedFileHeaderHash(fixed[:], h.Metadata) != binary.LittleEndian.Uint64(fixed[sortedFileHeaderHashOffset:]) { + return SortedFileHeader{}, 0, fmt.Errorf("sorted file %s: %w: header", f.Name(), ErrChecksumFailed) + } // Divide the trusted size rather than multiply the untrusted count, so a // corrupt count cannot overflow. body, recordSize := size-recordsOffset, int64(MinKeySize+h.PayloadSize) @@ -278,17 +324,26 @@ func readSortedFileHeader(f *os.File) (SortedFileHeader, error) { if holds < h.Count { sentinel = ErrTruncatedFile } - return SortedFileHeader{}, fmt.Errorf("sorted file %s: %w: the header counts %d records of %d bytes, the file holds %d bytes of records", + return SortedFileHeader{}, 0, fmt.Errorf("sorted file %s: %w: the header counts %d records of %d bytes, the file holds %d bytes of records", f.Name(), sentinel, h.Count, recordSize, body) } - return h, nil + return h, binary.LittleEndian.Uint64(fixed[sortedFileRecordsHashOffset:]), nil } // sortedRun is a sorted file's records: the file offsets where they start -// and end. +// and end, and their hash. type sortedRun struct { path string start, end int64 + hash uint64 +} + +// check fails if the records read from the run hash to sum, not to its hash. +func (r sortedRun) check(sum uint64) error { + if sum != r.hash { + return fmt.Errorf("sorted file %s: %w: records", r.path, ErrChecksumFailed) + } + return nil } // readAt reads the run's file f at off into buf, and returns how many bytes @@ -314,7 +369,7 @@ func readSortedRuns(paths []string) ([]sortedRun, int, uint64, error) { var payloadSize int var total uint64 for i, path := range paths { - h, err := ReadSortedFileHeader(path) + h, recordsHash, err := readSortedFileHeaderAt(path) if err != nil { return nil, 0, 0, err } @@ -325,7 +380,7 @@ func readSortedRuns(paths []string) ([]sortedRun, int, uint64, error) { } if h.Count > 0 { start := h.recordsOffset() - runs = append(runs, sortedRun{path: path, start: start, end: start + int64(h.Count)*int64(MinKeySize+h.PayloadSize)}) + runs = append(runs, sortedRun{path: path, start: start, end: start + int64(h.Count)*int64(MinKeySize+h.PayloadSize), hash: recordsHash}) } total += h.Count } @@ -350,7 +405,9 @@ func checkOutputNotInput(output string, inputs []string) error { // SortedFileReader reads a sorted file's records in order. type SortedFileReader struct { f *os.File + hash *xxhash.Digest br *bufio.Reader + run sortedRun payloadSize int left uint64 last sortKey @@ -358,24 +415,32 @@ type SortedFileReader struct { } // OpenSortedFile opens the sorted file at path to read its records in order. -// It checks the header as ReadSortedFileHeader does. +// It checks the header as ReadSortedFileHeader does. The records' hash is +// checked when the last record is read: only once Next has returned it are +// the records known to be the ones written. func OpenSortedFile(path string) (*SortedFileReader, error) { f, err := os.Open(path) if err != nil { return nil, err } - h, err := readSortedFileHeader(f) + h, recordsHash, err := readSortedFileHeader(f) if err == nil { _, err = f.Seek(h.recordsOffset(), io.SeekStart) } if err != nil { return nil, errors.Join(err, f.Close()) } - return &SortedFileReader{f: f, br: bufio.NewReaderSize(f, 1<<20), payloadSize: h.PayloadSize, left: h.Count}, nil + hash := xxhash.New() + return &SortedFileReader{ + f: f, hash: hash, br: bufio.NewReaderSize(io.TeeReader(f, hash), 1<<20), + run: sortedRun{path: path, hash: recordsHash}, + payloadSize: h.PayloadSize, left: h.Count, + }, nil } // Next returns the next record's key and payload, and io.EOF after the last -// record. A record out of order fails with ErrUnsortedInput. +// record. A record out of order fails with ErrUnsortedInput. If the records +// do not match the file's hash, the last one fails with ErrChecksumFailed. func (r *SortedFileReader) Next() (key [MinKeySize]byte, payload uint64, err error) { if r.left == 0 { return key, 0, io.EOF @@ -393,6 +458,12 @@ func (r *SortedFileReader) Next() (key [MinKeySize]byte, payload uint64, err err return key, 0, fmt.Errorf("sorted file %s: %w", r.f.Name(), ErrUnsortedInput) } r.last = k + if r.left == 0 { + // The buffered reader has read every record by now. + if err := r.run.check(r.hash.Sum64()); err != nil { + return key, 0, err + } + } copy(key[:], rec[:MinKeySize]) return key, unpackPayloadFromBytes(rec[MinKeySize:], r.payloadSize), nil } diff --git a/sorted_file_test.go b/sorted_file_test.go index 2d4264b..992f1c5 100644 --- a/sorted_file_test.go +++ b/sorted_file_test.go @@ -12,6 +12,8 @@ import ( "path/filepath" "slices" "testing" + + "github.com/cespare/xxhash/v2" ) type sortedRecord struct { @@ -132,14 +134,16 @@ func TestSortedFileLayout(t *testing.T) { t.Fatal(err) } want := make([]byte, 4096) - copy(want, []byte{0x46, 0x53, 0x54, 0x53, 0x01, 0x00, 0x03, 0x00}) + copy(want, []byte{0x46, 0x53, 0x54, 0x53, 0x02, 0x00, 0x03, 0x00}) binary.LittleEndian.PutUint64(want[8:], 2) - binary.LittleEndian.PutUint32(want[16:], 4) - copy(want[20:], "meta") + binary.LittleEndian.PutUint32(want[32:], 4) + copy(want[36:], "meta") want = append(want, recs[0].key[:]...) want = append(want, 0x01, 0x02, 0x03) want = append(want, recs[1].key[:]...) want = append(want, 0x04, 0x05, 0x06) + binary.LittleEndian.PutUint64(want[16:], xxhash.Sum64(want[4096:])) + binary.LittleEndian.PutUint64(want[24:], xxhash.Sum64(slices.Concat(want[0:24], want[32:40]))) if !bytes.Equal(data, want) { t.Fatalf("file bytes differ from the layout\ngot: %x\nwant: %x", data, want) } @@ -351,6 +355,7 @@ func TestReadSortedFileHeaderRejects(t *testing.T) { mutated := func(data []byte, mutate func([]byte)) []byte { b := slices.Clone(data) mutate(b) + rehashSortedFile(b) return b } @@ -361,19 +366,19 @@ func TestReadSortedFileHeaderRejects(t *testing.T) { }{ {"shorter than the fixed header", data3[:sortedFileFixedSize-1], ErrTruncatedFile}, {"cut in the padding", data3[:100], ErrTruncatedFile}, - {"metadata longer than the file", mutated(data3, func(b []byte) { binary.LittleEndian.PutUint32(b[16:], 5000) }), ErrTruncatedFile}, + {"metadata longer than the file", mutated(data3, func(b []byte) { binary.LittleEndian.PutUint32(b[32:], 5000) }), ErrTruncatedFile}, {"cut mid-record", data3[:len(data3)-1], ErrTruncatedFile}, {"cut a whole record", data3[:len(data3)-19], ErrTruncatedFile}, {"count one too large", mutated(data3, func(b []byte) { binary.LittleEndian.PutUint64(b[8:], 11) }), ErrTruncatedFile}, // 16 × (10 + 2^60) wraps to 16 × 10, so only a division catches it. {"count that overflows", mutated(data0, func(b []byte) { binary.LittleEndian.PutUint64(b[8:], 10+1<<60) }), ErrTruncatedFile}, {"an extra record", append(slices.Clone(data3), make([]byte, 19)...), ErrKeyCountMismatch}, - {"an unfinished writer's count of 0", mutated(data3, func(b []byte) { binary.LittleEndian.PutUint64(b[8:], 0) }), ErrKeyCountMismatch}, + {"a count of 0", mutated(data3, func(b []byte) { binary.LittleEndian.PutUint64(b[8:], 0) }), ErrKeyCountMismatch}, {"wrong magic", mutated(data3, func(b []byte) { b[0] ^= 1 }), ErrInvalidMagic}, {"an index file", index, ErrInvalidMagic}, - {"wrong version", mutated(data3, func(b []byte) { b[4] = 2 }), ErrInvalidVersion}, + {"wrong version", mutated(data3, func(b []byte) { b[4] = 1 }), ErrInvalidVersion}, {"payload size over 8", mutated(data3, func(b []byte) { b[6] = maxPayloadSize + 1 }), ErrCorruptedIndex}, - {"metadata length over the maximum", mutated(data3, func(b []byte) { binary.LittleEndian.PutUint32(b[16:], maxSortedFileMetadata+1) }), ErrCorruptedIndex}, + {"metadata length over the maximum", mutated(data3, func(b []byte) { binary.LittleEndian.PutUint32(b[32:], maxSortedFileMetadata+1) }), ErrCorruptedIndex}, } { t.Run(tc.name, func(t *testing.T) { path := filepath.Join(dir, "bad.sorted") diff --git a/sorted_merge.go b/sorted_merge.go index 9d5ab9f..79e4425 100644 --- a/sorted_merge.go +++ b/sorted_merge.go @@ -5,6 +5,8 @@ import ( "errors" "fmt" "os" + + "github.com/cespare/xxhash/v2" ) const ( @@ -20,8 +22,9 @@ const ( // MergeSortedFiles merges the sorted files at inputs, which must all have // cfg.PayloadSize, into one at output, written with cfg. It is for a writer // that spilled sorted pieces. It keeps every input open, with a 128 KiB read -// buffer each. An input whose keys are out of order fails the merge, and a -// failed or canceled merge removes the output. +// buffer each. An input whose keys are out of order fails the merge, as does +// one whose records do not match its hash (ErrChecksumFailed), and a failed or +// canceled merge removes the output. func MergeSortedFiles(ctx context.Context, output string, inputs []string, cfg SortedFileConfig) error { return mergeSortedFiles(ctx, output, inputs, cfg, mergeReadBuffer) } @@ -147,6 +150,9 @@ func mergeFiles(ctx context.Context, runs []sortedRun, recordSize, bufBytes int, if r.err != nil { return r.err } + if err := r.run.check(r.hash.Sum64()); err != nil { + return err + } n-- if n > 0 { h[0] = h[n] @@ -196,6 +202,8 @@ type runReader struct { cursor int // offset in buf of the current record valid int // bytes of buf that hold records fileOff int64 // file offset of buf[0], a multiple of directAlign + hashed int64 // file offset the records are hashed up to + hash *xxhash.Digest err error } @@ -209,7 +217,7 @@ func newRunReader(run sortedRun, recordSize, bufBytes int) (*runReader, error) { if err != nil { return nil, err } - r := &runReader{run: run, f: f, buf: alignedBuffer(bufBytes), recordSize: recordSize} + r := &runReader{run: run, f: f, buf: alignedBuffer(bufBytes), recordSize: recordSize, hashed: run.start, hash: xxhash.New()} if !r.fill(run.start) { f.Close() return nil, r.err @@ -238,5 +246,8 @@ func (r *runReader) fill(off int64) bool { return false } r.fileOff, r.cursor = alignedOff, int(off-alignedOff) + // A refill rereads the bytes from alignedOff, hashed already. + _, _ = r.hash.Write(r.buf[r.hashed-alignedOff : r.valid]) + r.hashed = alignedOff + int64(r.valid) return true } diff --git a/streamhash-spec.md b/streamhash-spec.md index f3935e1..67cb261 100644 --- a/streamhash-spec.md +++ b/streamhash-spec.md @@ -65,7 +65,7 @@ With a configured payload size (1–8 bytes), the index doubles as a **static pe | | Bijection | PTRHash | |---|---|---| | **Best for** | Compactness, low build RAM | Query speed | -| Index size | ~2.46 bits/key | ~2.70 bits/key | +| Index size | ~2.47 bits/key | ~2.70 bits/key | | Query latency (CPU only) | ~1.5 µs (decode ≤128 buckets) | ~0.07 µs (one pilot byte) | | Build throughput (4 workers) | ~65 M keys/sec | ~62 M keys/sec | | Peak heap (4 workers) | ~8 MB | ~61 MB | @@ -84,7 +84,7 @@ Reference measurements on an Apple M1 Max, 100M keys, MPHF mode, pre-sorted inpu | Metric | Bijection | PTRHash | |--------|-----------|---------| -| Index size (MPHF) | ~2.46 bits/key | ~2.70 bits/key | +| Index size (MPHF) | ~2.47 bits/key | ~2.70 bits/key | | Query latency (CPU only) | ~1.5 µs | ~0.07 µs | | Build throughput (1 / 4 workers) | ~16 / ~65 M keys/sec | ~17 / ~62 M keys/sec | | Peak heap (1 / 4 workers) | ~1 / ~8 MB | ~8 / ~61 MB | @@ -222,6 +222,8 @@ function Query(key) → (rank, error): entry = ramIndex[blockIdx] // RAM index (§3.4) nextEntry = ramIndex[blockIdx + 1] + if either entry's Check does not match: // §3.4 + return error(ChecksumFailed) keysBefore = entry.KeysBefore keysInBlock = nextEntry.KeysBefore - entry.KeysBefore if keysInBlock == 0: @@ -254,7 +256,7 @@ The format is language-independent. The byte layouts, encodings, and hash functi +--------------------------------------------------+ | AlgoConfigLen (4 B) + AlgoConfig (variable) | +--------------------------------------------------+ -| RAM Index ((NumBlocks + 1) × 10 B) | +| RAM Index ((NumBlocks + 1) × 14 B) | +--------------------------------------------------+ | Payload Region (N × entrySize B) | +--------------------------------------------------+ @@ -272,7 +274,7 @@ Offset Size Content 68 UML B UserMetadata 68+UML 4 B AlgoConfigLen (uint32_le) 72+UML ACL B AlgoConfig -72+UML+ACL (NumBlocks+1)×10 B RAM Index +72+UML+ACL (NumBlocks+1)×14 B RAM Index ramIndexEnd N × entrySize B Payload Region payloadEnd variable Metadata Region metadataEnd 32 B Footer @@ -285,17 +287,24 @@ where `UML = UserMetadataLen`, `ACL = AlgoConfigLen`, `N = TotalKeys`, and `entr | Offset | Size | Field | Type | Description | |--------|------|-------|------|-------------| | 0 | 4 | Magic | uint32_le | `0x53544D48` ("STMH") | -| 4 | 2 | Version | uint16_le | `0x0001` | +| 4 | 2 | Version | uint16_le | `0x0002` | | 6 | 8 | TotalKeys | uint64_le | Total keys (N) | | 14 | 4 | NumBlocks | uint32_le | Number of blocks | | 18 | 4 | PayloadSize | uint32_le | Payload bytes per key (0 = MPHF only) | | 22 | 1 | FingerprintSize | uint8 | Fingerprint bytes (0–4) | | 23 | 8 | Seed | uint64_le | Global hash seed | | 31 | 2 | BlockAlgorithm | uint16_le | 0 = Bijection, 1 = PTRHash | -| 33 | 31 | Reserved | bytes | Zero-filled | +| 33 | 23 | Reserved | bytes | Zero-filled | +| 56 | 8 | HeaderHash | uint64_le | xxHash64 of the header and the variable-length sections | `TotalBuckets`, `BucketsPerBlock`, and similar values are **not** in the header — they are algorithm-internal and derived from `NumBlocks` (§2.3). Note that `Seed` and `BlockAlgorithm` are intentionally unaligned (they start at offsets 23 and 31). +`HeaderHash` is canonical unseeded xxHash64 of every byte before the RAM index except its own: + +``` +HeaderHash = xxHash64(file[0:56] || file[64 : 72+UML+ACL]) +``` + ### 3.3. Variable-length sections Immediately after the header: @@ -312,15 +321,23 @@ Immediately after the header: `NumBlocks + 1` entries. The final entry is a **sentinel**: it stores `KeysBefore == TotalKeys` and the end offset of the last block's metadata, so the last block's size can be computed by subtraction like any other. -**Entry (10 bytes):** +**Entry (14 bytes):** | Offset | Size | Field | Type | |--------|------|-------|------| | 0 | 5 | KeysBefore | uint40_le | | 5 | 5 | MetadataOffset | uint40_le | +| 10 | 4 | Check | uint32_le | - `KeysBefore` — cumulative keys in all blocks before this one. - `MetadataOffset` — byte offset of this block's metadata, relative to the start of the metadata region. +- `Check` — CRC-32C (Castagnoli) of the entry's first 10 bytes, with the entry's index as the running CRC it continues from: + + ``` + Check(i) = crc32c_update(crc = i, entry[0:10]) + ``` + + `crc32c_update(0, data)` is the standard CRC-32C of `data` (in Go, `crc32.Update` with the Castagnoli table). Starting from `i` gives the standard CRC-32C of the same 10 bytes with `LittleEndian.Bytes4(i)` XORed into the first four, so an intact entry read at another block's position fails too. The sentinel has index `NumBlocks`. A CRC detects every single flipped bit and every burst of up to 32 bits. Per-block values are derived by subtraction (this is the query path in §2.6): @@ -331,7 +348,7 @@ metadataSlice = metadataRegion[ramIndex[b].MetadataOffset : ramIndex[b+1].Metada Payloads need no offset in the index — they are at a fixed stride: `payloadOffset = rank × entrySize`. -**The RAM index is an optimization, not a requirement.** It lives at a fixed, computable file offset, so a query can instead read the two needed entries (20 contiguous bytes) straight from disk — one extra read per query. Keeping it in memory is cheap (10 B/block, e.g. ~32 KB for a 10M-key Bijection index of ~3,256 blocks), so the reference implementation does. +**The RAM index is an optimization, not a requirement.** It lives at a fixed, computable file offset, so a query can instead read the two needed entries (28 contiguous bytes) straight from disk — one extra read per query. Keeping it in memory is cheap (14 B/block, e.g. ~46 KB for a 10M-key Bijection index of ~3,256 blocks), so the reference implementation does. ### 3.5. Payload Region @@ -367,7 +384,7 @@ Empty blocks (`keysInBlock = 0`) still occupy a metadata entry, so block offsets | 8 | 8 | MetadataRegionHash | uint64_le | | 16 | 16 | Reserved | bytes | -Both use canonical **unseeded xxHash64**: +The reserved bytes are zero, and `Verify` rejects a footer where they are not. Both hashes use canonical **unseeded xxHash64**: - **MetadataRegionHash** — a single pass over the raw metadata-region bytes (region start to footer start). - **PayloadRegionHash** — a deterministic **hash-of-hashes** so it can be folded incrementally during a parallel build: @@ -394,26 +411,26 @@ A minimal Bijection index, 5 keys in 2 blocks, MPHF mode (no payloads or fingerp ``` Offset Bytes Meaning ──────────────────────────────────────────────────────────────────────────── -0x0000 48 4D 54 53 01 00 05 00 00 00 00 00 00 00 02 00 Magic "STMH", Version 1, +0x0000 48 4D 54 53 02 00 05 00 00 00 00 00 00 00 02 00 Magic "STMH", Version 2, TotalKeys=5, NumBlocks=2 (lo) 0x0010 00 00 00 00 00 00 00 12 34 56 78 9A BC DE F0 00 NumBlocks (hi), PayloadSize=0, FingerprintSize=0, Seed=0xF0DEBC9A78563412, BlockAlgorithm=0 (lo, 0x1F–0x20) -0x0020 00 ... (zeros) BlockAlgorithm (hi) + Reserved (0x21–0x3F) -0x0030 00 ... (zeros) Reserved +0x0020 00 ... (zeros) BlockAlgorithm (hi) + Reserved (0x21–0x37) +0x0038 9F E6 D0 68 62 4B BF DF HeaderHash 0x0040 00 00 00 00 UserMetadataLen = 0 0x0044 00 00 00 00 AlgoConfigLen = 0 -0x0048 00 00 00 00 00 00 00 00 00 00 RAM[0]: KeysBefore=0, MetaOff=0 -0x0052 03 00 00 00 00 A5 00 00 00 00 RAM[1]: KeysBefore=3, MetaOff=0xA5 -0x005C 05 00 00 00 00 42 01 00 00 00 RAM[2] sentinel: KeysBefore=5, - MetaOff=0x142 -0x0066 ... (block 0 metadata, 0xA5 = 165 B) Metadata region begins here -0x010B ... (block 1 metadata, 0x9D = 157 B) -0x01A8 [32-byte footer] Footer +0x0048 00 00 00 00 00 00 00 00 00 00 6B F0 DD E3 RAM[0]: KeysBefore=0, MetaOff=0, Check +0x0056 03 00 00 00 00 A5 00 00 00 00 C7 C0 C3 DD RAM[1]: KeysBefore=3, MetaOff=0xA5, Check +0x0064 05 00 00 00 00 42 01 00 00 00 BC 60 90 02 RAM[2] sentinel: KeysBefore=5, + MetaOff=0x142, Check +0x0072 ... (block 0 metadata, 0xA5 = 165 B) Metadata region begins here +0x0117 ... (block 1 metadata, 0x9D = 157 B) +0x01B4 [32-byte footer] Footer ``` -The metadata region starts at `0x66` (RAM index ends at `0x48 + 3×10 = 0x66`; the payload region is empty). The per-block byte sizes shown are illustrative encoded lengths; they come straight from the RAM-index offsets by subtraction: block 0 = `0xA5 − 0 = 165 B`, block 1 = `0x142 − 0xA5 = 0x9D = 157 B`. Block 1 here happens to equal the empty-block Bijection size from §3.6 (157 B) purely by coincidence — there is nothing to reconcile between the 165 B and 157 B figures. The footer therefore sits at `0x66 + 0x142 = 0x1A8`. +The metadata region starts at `0x72` (RAM index ends at `0x48 + 3×14 = 0x72`; the payload region is empty). The per-block byte sizes shown are illustrative encoded lengths; they come straight from the RAM-index offsets by subtraction: block 0 = `0xA5 − 0 = 165 B`, block 1 = `0x142 − 0xA5 = 0x9D = 157 B`. Block 1 here happens to equal the empty-block Bijection size from §3.6 (157 B) purely by coincidence — there is nothing to reconcile between the 165 B and 157 B figures. The footer therefore sits at `0x72 + 0x142 = 0x1B4`. ### 3.9. Sorted files @@ -432,14 +449,25 @@ A sorted file is not an index. It holds keys with their payloads in key order, i | Offset | Size | Field | Type | Description | |--------|------|-------|------|-------------| | 0 | 4 | Magic | uint32_le | `0x53545346` ("STSF") | -| 4 | 2 | Version | uint16_le | `0x0001` | +| 4 | 2 | Version | uint16_le | `0x0002` | | 6 | 1 | PayloadSize | uint8 | Payload bytes per record (0–8) | | 7 | 1 | Reserved | byte | Zero | | 8 | 8 | Count | uint64_le | Number of records | -| 16 | 4 | MetadataLen | uint32_le | Metadata length, at most 65,536 | -| 20 | MetadataLen | Metadata | bytes | Application-defined, not interpreted | +| 16 | 8 | RecordsHash | uint64_le | xxHash64 of the records | +| 24 | 8 | HeaderHash | uint64_le | xxHash64 of the rest of the header | +| 32 | 4 | MetadataLen | uint32_le | Metadata length, at most 65,536 | +| 36 | MetadataLen | Metadata | bytes | Application-defined, not interpreted | -Zero bytes pad the header to `RecordsOffset = ceil((20 + MetadataLen) / 4096) × 4096`, so the records start at a 4096-aligned offset, as direct reads (`O_DIRECT`) need. +Zero bytes pad the header to `RecordsOffset = ceil((36 + MetadataLen) / 4096) × 4096`, so the records start at a 4096-aligned offset, as direct reads (`O_DIRECT`) need. + +**Hashes.** Both are canonical unseeded xxHash64: + +``` +RecordsHash = xxHash64(file[RecordsOffset : RecordsOffset + Count × (16 + PayloadSize)]) +HeaderHash = xxHash64(file[0:24] || file[32 : 36 + MetadataLen]) +``` + +`HeaderHash` covers every header byte but its own, `RecordsHash` and `Count` included, so a header that passes pins the records. The padding is not covered, and no reader interprets it. **Records.** Record `i` is at `RecordsOffset + i × (16 + PayloadSize)`: @@ -449,7 +477,7 @@ Zero bytes pad the header to `RecordsOffset = ceil((20 + MetadataLen) / 4096) × `Key` is the first 16 bytes of the key the index uses (§2.1). Records are in non-decreasing bytewise order of `Key`, which is the order of big-endian bytes 0–7, then big-endian bytes 8–15. `fastRange32` is monotonic in the prefix (§2.2), so this is also non-decreasing block order, the order sorted mode needs (§6.1). A key may repeat; an index build rejects it as a duplicate (§7.1). -**Validation.** A file's size must be exactly `RecordsOffset + Count × (16 + PayloadSize)`. A reader checks this by dividing the size, never by multiplying `Count`, so a corrupt `Count` cannot overflow the arithmetic and pass. The writer writes `Count` after the records, then syncs. §7.5 lists the errors. +**Validation.** A file's size must be exactly `RecordsOffset + Count × (16 + PayloadSize)`. A reader checks this by dividing the size, never by multiplying `Count`, so a corrupt `Count` cannot overflow the arithmetic and pass. The writer writes `Count`, `RecordsHash` and `HeaderHash` after the records, then syncs; until then `HeaderHash` is zero, so a file whose writer did not finish is not valid. §7.5 lists the errors. **Building an index from sorted files.** `BuildFromSortedFiles` builds an index from any number of sorted files that share a payload size, without merging them. The index is byte-identical to the one a `SortedBuilder` builds from the same keys in block order (§6.1), because the order of the keys inside a block does not change the index. The build splits the blocks into **stripes** of `B` consecutive blocks holding about `S` keys each, with `S` between 32K and 256K, chosen so the stripes in flight fit in 128 MiB. Stripe `s` covers blocks `[s·B, (s+1)·B)` and so, by §2.2, the prefixes `[ceil(s·B·2^64 / numBlocks), ceil((s+1)·B·2^64 / numBlocks))`; the last stripe has no upper bound. Every file is in key order, so it holds a stripe's keys as one contiguous run. One goroutine gathers each stripe in turn: in each file it finds where the run ends, with a galloping search, and copies the run out. The files are read once, sequentially and directly where the filesystem allows it, through fixed aligned buffers, two or three per file. Each buffer is its share of 128 MiB, kept between 64 KiB and 4 MiB, then rounded down to a multiple of lcm(4096, record size), and never less than one: 36 KiB to 92 KiB at the 64 KiB floor, depending on the record size. Past about 700 files those floors take more than the 128 MiB, up to 192 KiB per file. Each worker (`WithWorkers`) takes whole stripes: it sorts a stripe's records by block with a counting sort, solves the blocks, and hands them to the writer of §6.3, which commits them in block order. With one worker, the calling goroutine gathers, solves and writes each stripe itself. While sorting, a worker checks that each file's run is in order and that every record's block is in the stripe; a record that fails either check means a file out of order (`ErrUnsortedInput`). A duplicate key fails its block (`ErrDuplicateKey`), and the build fails if the records it read do not add up to the headers' counts (`ErrKeyCountMismatch`). @@ -863,7 +891,7 @@ StreamHash targets large datasets (N > ~100K). For smaller sets, fixed costs (he **Maximum:** `2^40 − 1` keys (~1.1 trillion), set by the 40-bit RAM-index fields. The sentinel entry stores `KeysBefore == TotalKeys`, so exactly `2^40` would wrap to 0 and is rejected. The 40-bit `MetadataOffset` likewise supports metadata regions up to ~1.1 TB. -The resident RAM index is ≈ 10 bytes × numBlocks (≈ 3.3 MB per billion keys for Bijection, ≈ 0.3 MB per billion for PTRHash). At the `2^40 − 1` maximum this is ~3.6 GB (Bijection, ~358M blocks) or ~348 MB (PTRHash, ~34.8M blocks). +The resident RAM index is ≈ 14 bytes × numBlocks (≈ 4.6 MB per billion keys for Bijection, ≈ 0.4 MB per billion for PTRHash). At the `2^40 − 1` maximum this is ~5.0 GB (Bijection, ~358M blocks) or ~487 MB (PTRHash, ~34.8M blocks). ### 7.4. PTRHash build-failure frequency @@ -907,10 +935,10 @@ An index with `N = 0` keys is not an error: it builds successfully, and every `Q | Error | Condition | |-------|-----------| | `ErrInvalidMagic` | magic ≠ `0x53544D48` | -| `ErrInvalidVersion` | version ≠ `0x0001` | +| `ErrInvalidVersion` | version ≠ `0x0002` | | `ErrTruncatedFile` | file shorter than the layout requires | | `ErrCorruptedIndex` | invalid metadata or out-of-bounds offset | -| `ErrChecksumFailed` | footer hash mismatch (from `Verify`) | +| `ErrChecksumFailed` | any checksum mismatch (§7.6) | | `ErrNotFound` | empty block, or fingerprint mismatch | **Sorted files (§3.9):** @@ -920,7 +948,7 @@ An index with `N = 0` keys is not an error: it builds successfully, and every `Q | `ErrTruncatedFile` | file shorter than its header, or than its `Count` records | | `ErrKeyCountMismatch` | file longer than its header and `Count` records; or a build read a different number of records than the files count | | `ErrInvalidMagic` | magic ≠ `0x53545346` | -| `ErrInvalidVersion` | version ≠ `0x0001` | +| `ErrInvalidVersion` | version ≠ `0x0002` | | `ErrCorruptedIndex` | PayloadSize > 8, or MetadataLen > 65,536 | | `ErrUnsortedInput` | a key sorts before the key before it, when it is written, merged, read or built from; or a build finds a record outside its stripe | @@ -934,7 +962,21 @@ if metadataStart >= metadataRegionOffset + metadataRegionSize: return ErrCorruptedIndex ``` -For end-to-end integrity, the footer's two unseeded-xxHash64 region hashes (§3.7) can be verified after open (the reference implementation exposes this as `Verify`, returning `ErrChecksumFailed` on mismatch). **`Verify` covers only the payload and metadata regions, not the header or RAM index** — detecting tampering there requires a checksum stored **outside** the file (e.g. a manifest), since any in-file checksum would itself be part of what needs protecting. +Checksums cover every byte of an index file, and every byte of a sorted file but its padding. Each is checked where its bytes are read anyway, and a mismatch is `ErrChecksumFailed`: + +| Bytes | Checksum | Checked | +|-------|----------|---------| +| Index header, UserMetadata, AlgoConfig | `HeaderHash` (§3.2) | at open, and by `Verify` | +| RAM index | each entry's `Check` (§3.4) | by a query, for the two entries it reads, and by `Verify` | +| Payload region | `PayloadRegionHash` (§3.7) | by `Verify` | +| Metadata region | `MetadataRegionHash` (§3.7) | by `Verify` | +| Footer | the hashes are their own check | by `Verify`, which also rejects non-zero reserved bytes (`ErrCorruptedIndex`) | +| Sorted file header, metadata | `HeaderHash` (§3.9) | whenever the header is read | +| Sorted file records | `RecordsHash` (§3.9) | once every record is read: by `SortedFileReader` at the last record, by `MergeSortedFiles` before it finishes its output, by `BuildFromSortedFiles` before it finishes the index | + +Opening an index reads no page it did not read before, as long as the user metadata fits in the header's page; larger metadata is read in full to be hashed. A query reads nothing more, so it does not detect corruption in the block metadata or the payload entry it reads: that takes `Verify`, which reads the whole file. + +**The checksums catch corruption, not tampering.** They use no secret, so anyone who can write the file can recompute them. Detecting tampering requires a keyed or cryptographic checksum stored **outside** the file (e.g. a manifest). ### 7.7. Security considerations @@ -957,7 +999,7 @@ StreamHash assumes uniformly random input. Consequences of violating that: ### 7.8. Durability and compatibility - **Failed builds leave no usable index.** If `Finish` fails, the partial output file is deleted, so a crashed or errored build never leaves behind a file that looks like a valid index. -- **Single format version.** The format is Version `0x0001`; a reader rejects any other version with `ErrInvalidVersion`. There is no forward- or backward-compatibility guarantee across format versions yet. +- **Single format version.** The format is Version `0x0002`, for index files and sorted files alike; a reader rejects any other version with `ErrInvalidVersion`. There is no forward- or backward-compatibility guarantee across format versions yet. --- @@ -990,9 +1032,9 @@ A collision surfaces as `ErrDuplicateKey` at build time — a clean failure, nev | lambda | bits/key | Fallback rate | Split rate | | |--------|----------|---------------|------------|---| | 2.0 | ~2.8 | <0.01% | ~1% | conservative | -| 3.0 | ~2.46 | ~0.01% | ~1.2% | **default** | -| 3.6 | ~2.40 | ~0.02% | ~3% | | -| 5.0 | ~2.30 | ~0.3% | ~7% | aggressive | +| 3.0 | ~2.47 | ~0.01% | ~1.2% | **default** | +| 3.6 | ~2.41 | ~0.02% | ~3% | | +| 5.0 | ~2.31 | ~0.3% | ~7% | aggressive | **PTRHash** — `lambda = 3.16`, `alpha = 0.99` (~1% spare slots, absorbed by the remap table). @@ -1007,8 +1049,8 @@ A collision surfaces as `ErrDuplicateKey` at build time — a clean failure, nev | Seed stream (split, sizes 8+) | ~0.12 | | Checkpoints (28 B/block) | ~0.07 | | Fallback list | ~0.01 | -| RAM index (10 B/block) | ~0.03 | -| **Total** | **~2.46** | +| RAM index (14 B/block) | ~0.04 | +| **Total** | **~2.47** | *PTRHash* (bucketsPerBlock 10,000, lambda 3.16, alpha 0.99): @@ -1016,10 +1058,10 @@ A collision surfaces as `ErrDuplicateKey` at build time — a clean failure, nev |-----------|----------| | Pilots (1 B × 10,000 / block) | ~2.53 | | Remap table (~1% overflow) | ~0.16 | -| RAM index (10 B/block) | ~0.003 | +| RAM index (14 B/block) | ~0.004 | | **Total** | **~2.70** | -With payloads/fingerprints, total bits/key ≈ `routing_overhead + 8 × (PayloadSize + FingerprintSize)`, where `routing_overhead` is the MPHF figure above (~2.46 Bijection, ~2.70 PTRHash). For example, a 4-byte payload + 1-byte fingerprint on Bijection is ≈ `2.46 + 40 = ~42.5` bits/key. +With payloads/fingerprints, total bits/key ≈ `routing_overhead + 8 × (PayloadSize + FingerprintSize)`, where `routing_overhead` is the MPHF figure above (~2.47 Bijection, ~2.70 PTRHash). For example, a 4-byte payload + 1-byte fingerprint on Bijection is ≈ `2.47 + 40 = ~42.5` bits/key. ### 8.3. Glossary From 91d7a3fbcb9dea15bd48315bd8a2be3be742e570 Mon Sep 17 00:00:00 2001 From: tamirms Date: Wed, 25 Nov 2026 13:08:22 +0000 Subject: [PATCH 2/5] Hash the records a merge writes, and check an empty sorted file's hash A merge hashed the start of a record cut off at the end of its buffer, then reread that record on the next refill without hashing it again, so bytes that changed between the reads went out unchecked. Each refill now hashes only whole records, from the buffer the merge writes them from. A sorted file with no records never had its RecordsHash checked. Reading the header now requires the hash of no records, so a file whose writer did not finish fails even if its header hashes to the zero it holds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AqbUZNMtZZBu8cT6ZLzFVp --- integrity_test.go | 11 +++++++++++ sorted_file.go | 8 ++++++-- sorted_merge.go | 9 ++++----- streamhash-spec.md | 4 ++-- 4 files changed, 23 insertions(+), 9 deletions(-) diff --git a/integrity_test.go b/integrity_test.go index c2870c1..e4022c8 100644 --- a/integrity_test.go +++ b/integrity_test.go @@ -278,6 +278,17 @@ func TestSortedFileUnfinishedWriter(t *testing.T) { r.Close() t.Fatalf("%d records: OpenSortedFile accepted the file", records) } + if records == 0 { + // As if the unfinished header hashed to the zero it holds. + fixed := w.header[:sortedFileFixedSize] + binary.LittleEndian.PutUint64(fixed[sortedFileHeaderHashOffset:], sortedFileHeaderHash(fixed, w.header[sortedFileFixedSize:])) + if _, err := w.f.WriteAt(fixed[sortedFileHeaderHashOffset:sortedFileMetadataLenOffset], sortedFileHeaderHashOffset); err != nil { + t.Fatal(err) + } + if _, err := ReadSortedFileHeader(path); !errors.Is(err, ErrChecksumFailed) { + t.Fatalf("an unfinished empty file with a matching header hash returned %v, want ErrChecksumFailed", err) + } + } if err := w.f.Close(); err != nil { t.Fatal(err) } diff --git a/sorted_file.go b/sorted_file.go index 129fccc..9a53fbb 100644 --- a/sorted_file.go +++ b/sorted_file.go @@ -268,7 +268,7 @@ func readSortedFileHeaderAt(path string) (SortedFileHeader, uint64, error) { // ReadSortedFileHeader reads and checks the header at path: magic, version, // payload size, its hash, and that the record count matches the file's length. -// It does not read the records, so it does not check their hash. +// It does not read the records, so it checks their hash only when there are none. func ReadSortedFileHeader(path string) (SortedFileHeader, error) { h, _, err := readSortedFileHeaderAt(path) return h, err @@ -327,7 +327,11 @@ func readSortedFileHeader(f *os.File) (SortedFileHeader, uint64, error) { return SortedFileHeader{}, 0, fmt.Errorf("sorted file %s: %w: the header counts %d records of %d bytes, the file holds %d bytes of records", f.Name(), sentinel, h.Count, recordSize, body) } - return h, binary.LittleEndian.Uint64(fixed[sortedFileRecordsHashOffset:]), nil + recordsHash := binary.LittleEndian.Uint64(fixed[sortedFileRecordsHashOffset:]) + if h.Count == 0 && recordsHash != xxhash.Sum64(nil) { + return SortedFileHeader{}, 0, fmt.Errorf("sorted file %s: %w: records", f.Name(), ErrChecksumFailed) + } + return h, recordsHash, nil } // sortedRun is a sorted file's records: the file offsets where they start diff --git a/sorted_merge.go b/sorted_merge.go index 79e4425..89b16fb 100644 --- a/sorted_merge.go +++ b/sorted_merge.go @@ -202,7 +202,6 @@ type runReader struct { cursor int // offset in buf of the current record valid int // bytes of buf that hold records fileOff int64 // file offset of buf[0], a multiple of directAlign - hashed int64 // file offset the records are hashed up to hash *xxhash.Digest err error } @@ -217,7 +216,7 @@ func newRunReader(run sortedRun, recordSize, bufBytes int) (*runReader, error) { if err != nil { return nil, err } - r := &runReader{run: run, f: f, buf: alignedBuffer(bufBytes), recordSize: recordSize, hashed: run.start, hash: xxhash.New()} + r := &runReader{run: run, f: f, buf: alignedBuffer(bufBytes), recordSize: recordSize, hash: xxhash.New()} if !r.fill(run.start) { f.Close() return nil, r.err @@ -246,8 +245,8 @@ func (r *runReader) fill(off int64) bool { return false } r.fileOff, r.cursor = alignedOff, int(off-alignedOff) - // A refill rereads the bytes from alignedOff, hashed already. - _, _ = r.hash.Write(r.buf[r.hashed-alignedOff : r.valid]) - r.hashed = alignedOff + int64(r.valid) + // A record cut off at the end is hashed once a refill reads it whole. + whole := (r.valid - r.cursor) / r.recordSize * r.recordSize + _, _ = r.hash.Write(r.buf[r.cursor : r.cursor+whole]) return true } diff --git a/streamhash-spec.md b/streamhash-spec.md index 67cb261..0c85347 100644 --- a/streamhash-spec.md +++ b/streamhash-spec.md @@ -477,7 +477,7 @@ HeaderHash = xxHash64(file[0:24] || file[32 : 36 + MetadataLen]) `Key` is the first 16 bytes of the key the index uses (§2.1). Records are in non-decreasing bytewise order of `Key`, which is the order of big-endian bytes 0–7, then big-endian bytes 8–15. `fastRange32` is monotonic in the prefix (§2.2), so this is also non-decreasing block order, the order sorted mode needs (§6.1). A key may repeat; an index build rejects it as a duplicate (§7.1). -**Validation.** A file's size must be exactly `RecordsOffset + Count × (16 + PayloadSize)`. A reader checks this by dividing the size, never by multiplying `Count`, so a corrupt `Count` cannot overflow the arithmetic and pass. The writer writes `Count`, `RecordsHash` and `HeaderHash` after the records, then syncs; until then `HeaderHash` is zero, so a file whose writer did not finish is not valid. §7.5 lists the errors. +**Validation.** A file's size must be exactly `RecordsOffset + Count × (16 + PayloadSize)`. A reader checks this by dividing the size, never by multiplying `Count`, so a corrupt `Count` cannot overflow the arithmetic and pass. The writer writes `Count`, `RecordsHash` and `HeaderHash` after the records, then syncs; until then both hashes are zero. A file with no records must have the hash of no records, so a file whose writer did not finish is not valid. §7.5 lists the errors. **Building an index from sorted files.** `BuildFromSortedFiles` builds an index from any number of sorted files that share a payload size, without merging them. The index is byte-identical to the one a `SortedBuilder` builds from the same keys in block order (§6.1), because the order of the keys inside a block does not change the index. The build splits the blocks into **stripes** of `B` consecutive blocks holding about `S` keys each, with `S` between 32K and 256K, chosen so the stripes in flight fit in 128 MiB. Stripe `s` covers blocks `[s·B, (s+1)·B)` and so, by §2.2, the prefixes `[ceil(s·B·2^64 / numBlocks), ceil((s+1)·B·2^64 / numBlocks))`; the last stripe has no upper bound. Every file is in key order, so it holds a stripe's keys as one contiguous run. One goroutine gathers each stripe in turn: in each file it finds where the run ends, with a galloping search, and copies the run out. The files are read once, sequentially and directly where the filesystem allows it, through fixed aligned buffers, two or three per file. Each buffer is its share of 128 MiB, kept between 64 KiB and 4 MiB, then rounded down to a multiple of lcm(4096, record size), and never less than one: 36 KiB to 92 KiB at the 64 KiB floor, depending on the record size. Past about 700 files those floors take more than the 128 MiB, up to 192 KiB per file. Each worker (`WithWorkers`) takes whole stripes: it sorts a stripe's records by block with a counting sort, solves the blocks, and hands them to the writer of §6.3, which commits them in block order. With one worker, the calling goroutine gathers, solves and writes each stripe itself. While sorting, a worker checks that each file's run is in order and that every record's block is in the stripe; a record that fails either check means a file out of order (`ErrUnsortedInput`). A duplicate key fails its block (`ErrDuplicateKey`), and the build fails if the records it read do not add up to the headers' counts (`ErrKeyCountMismatch`). @@ -972,7 +972,7 @@ Checksums cover every byte of an index file, and every byte of a sorted file but | Metadata region | `MetadataRegionHash` (§3.7) | by `Verify` | | Footer | the hashes are their own check | by `Verify`, which also rejects non-zero reserved bytes (`ErrCorruptedIndex`) | | Sorted file header, metadata | `HeaderHash` (§3.9) | whenever the header is read | -| Sorted file records | `RecordsHash` (§3.9) | once every record is read: by `SortedFileReader` at the last record, by `MergeSortedFiles` before it finishes its output, by `BuildFromSortedFiles` before it finishes the index | +| Sorted file records | `RecordsHash` (§3.9) | once every record is read: by `SortedFileReader` at the last record, by `MergeSortedFiles` before it finishes its output, by `BuildFromSortedFiles` before it finishes the index. A file with no records: whenever the header is read | Opening an index reads no page it did not read before, as long as the user metadata fits in the header's page; larger metadata is read in full to be hashed. A query reads nothing more, so it does not detect corruption in the block metadata or the payload entry it reads: that takes `Verify`, which reads the whole file. From 1b63f4563ef89fef1a6e96d1e6b7266644f0ee7e Mon Sep 17 00:00:00 2001 From: tamirms Date: Wed, 25 Nov 2026 13:55:19 +0000 Subject: [PATCH 3/5] Write each file's header last, after the rest is synced The index writer wrote its header, with a valid HeaderHash, before the rest of the RAM index and the footer, and synced once at the end. A crash in between left a file that opens, and after a power cut the header could reach disk before the data, so lookups could return wrong results with no error. Both writers now sync the rest of the file, write the header, and sync again, so a header that passes its check means the whole file reached disk. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AqbUZNMtZZBu8cT6ZLzFVp --- index_writer.go | 55 +++++++++++++++++++++++++--------------------- sorted_file.go | 12 ++++++---- streamhash-spec.md | 4 +++- 3 files changed, 41 insertions(+), 30 deletions(-) diff --git a/index_writer.go b/index_writer.go index 79bd3e8..dedf96b 100644 --- a/index_writer.go +++ b/index_writer.go @@ -249,8 +249,8 @@ func (iw *indexWriter) commitBlockWithData(metadata []byte, payloads []byte, num return nil } -// finalize completes the index file by writing header, variable sections, -// the rest of the RAM index, and footer via pwrite. +// finalize completes the index file via pwrite: the rest of the RAM index and +// the footer, a sync, then the header and variable sections, and another sync. // On error, delegates to close() for idempotent cleanup. // On success, nils file so that close() is a safe no-op. func (iw *indexWriter) finalize() error { @@ -265,29 +265,6 @@ func (iw *indexWriter) finalize() error { payloadRegionHash := iw.payloadHasher.Sum64() metadataRegionHash := iw.metadataHasher.Sum64() - // Update header - iw.header.TotalKeys = iw.keyCount - iw.header.NumBlocks = iw.blockCount - - // The header, then the variable-length sections, each [length 4B][data]: - // UserMetadata, then AlgoConfig - algoConfigLen := iw.algo.GlobalConfigSize() - prefix := make([]byte, headerSize+4+len(iw.userMetadata)+4+algoConfigLen) - iw.header.encodeTo(prefix) - userMetaBuf := prefix[headerSize:] - binary.LittleEndian.PutUint32(userMetaBuf, uint32(len(iw.userMetadata))) - copy(userMetaBuf[4:], iw.userMetadata) - algoConfigBuf := userMetaBuf[4+len(iw.userMetadata):] - binary.LittleEndian.PutUint32(algoConfigBuf, uint32(algoConfigLen)) - if algoConfigLen > 0 { - iw.algo.EncodeGlobalConfigInto(algoConfigBuf[4:]) - } - binary.LittleEndian.PutUint64(prefix[headerHashOffset:], headerHash(prefix)) - if err := iw.writeAt(prefix, 0); err != nil { - primaryErr := fmt.Errorf("write header failed: %w", err) - return errors.Join(primaryErr, iw.close()) - } - // Write the rest of the RAM index, ending with its sentinel entry (spec §3.4) iw.appendRAMIndexEntry() if err := iw.flushRAMIndex(); err != nil { @@ -319,6 +296,34 @@ func (iw *indexWriter) finalize() error { return errors.Join(primaryErr, iw.close()) } + // The header goes last, once the rest is on disk, so a header that passes + // its check means a complete file. + iw.header.TotalKeys = iw.keyCount + iw.header.NumBlocks = iw.blockCount + + // The header, then the variable-length sections, each [length 4B][data]: + // UserMetadata, then AlgoConfig + algoConfigLen := iw.algo.GlobalConfigSize() + prefix := make([]byte, headerSize+4+len(iw.userMetadata)+4+algoConfigLen) + iw.header.encodeTo(prefix) + userMetaBuf := prefix[headerSize:] + binary.LittleEndian.PutUint32(userMetaBuf, uint32(len(iw.userMetadata))) + copy(userMetaBuf[4:], iw.userMetadata) + algoConfigBuf := userMetaBuf[4+len(iw.userMetadata):] + binary.LittleEndian.PutUint32(algoConfigBuf, uint32(algoConfigLen)) + if algoConfigLen > 0 { + iw.algo.EncodeGlobalConfigInto(algoConfigBuf[4:]) + } + binary.LittleEndian.PutUint64(prefix[headerHashOffset:], headerHash(prefix)) + if err := iw.writeAt(prefix, 0); err != nil { + primaryErr := fmt.Errorf("write header failed: %w", err) + return errors.Join(primaryErr, iw.close()) + } + if err := iw.file.Sync(); err != nil { + primaryErr := fmt.Errorf("fsync failed: %w", err) + return errors.Join(primaryErr, iw.close()) + } + closeErr := iw.file.Close() iw.file = nil return closeErr diff --git a/sorted_file.go b/sorted_file.go index 9a53fbb..5128962 100644 --- a/sorted_file.go +++ b/sorted_file.go @@ -191,12 +191,16 @@ func (w *SortedFileWriter) Finish() error { return nil } -// commit flushes, patches the count and the hashes, syncs and closes, in that -// order: a short file's header is still in the buffer until the flush, which -// also completes the records' hash, and ENOSPC and EIO can surface only at -// close. +// commit flushes and syncs the records, patches the count and the hashes, +// syncs again and closes. The header goes last, so a header that passes its +// check means the records are on disk. A short file's header is still in the +// buffer until the flush, which also completes the records' hash, and ENOSPC +// and EIO can surface only at close. func (w *SortedFileWriter) commit() error { err := w.bw.Flush() + if err == nil { + err = w.f.Sync() + } if err == nil { fixed := w.header[:sortedFileFixedSize] binary.LittleEndian.PutUint64(fixed[sortedFileCountOffset:], w.count) diff --git a/streamhash-spec.md b/streamhash-spec.md index 0c85347..72f1790 100644 --- a/streamhash-spec.md +++ b/streamhash-spec.md @@ -477,7 +477,7 @@ HeaderHash = xxHash64(file[0:24] || file[32 : 36 + MetadataLen]) `Key` is the first 16 bytes of the key the index uses (§2.1). Records are in non-decreasing bytewise order of `Key`, which is the order of big-endian bytes 0–7, then big-endian bytes 8–15. `fastRange32` is monotonic in the prefix (§2.2), so this is also non-decreasing block order, the order sorted mode needs (§6.1). A key may repeat; an index build rejects it as a duplicate (§7.1). -**Validation.** A file's size must be exactly `RecordsOffset + Count × (16 + PayloadSize)`. A reader checks this by dividing the size, never by multiplying `Count`, so a corrupt `Count` cannot overflow the arithmetic and pass. The writer writes `Count`, `RecordsHash` and `HeaderHash` after the records, then syncs; until then both hashes are zero. A file with no records must have the hash of no records, so a file whose writer did not finish is not valid. §7.5 lists the errors. +**Validation.** A file's size must be exactly `RecordsOffset + Count × (16 + PayloadSize)`. A reader checks this by dividing the size, never by multiplying `Count`, so a corrupt `Count` cannot overflow the arithmetic and pass. The writer syncs the records, then writes `Count`, `RecordsHash` and `HeaderHash` and syncs again; until then both hashes are zero. A file with no records must have the hash of no records, so a file whose writer did not finish is not valid. §7.5 lists the errors. **Building an index from sorted files.** `BuildFromSortedFiles` builds an index from any number of sorted files that share a payload size, without merging them. The index is byte-identical to the one a `SortedBuilder` builds from the same keys in block order (§6.1), because the order of the keys inside a block does not change the index. The build splits the blocks into **stripes** of `B` consecutive blocks holding about `S` keys each, with `S` between 32K and 256K, chosen so the stripes in flight fit in 128 MiB. Stripe `s` covers blocks `[s·B, (s+1)·B)` and so, by §2.2, the prefixes `[ceil(s·B·2^64 / numBlocks), ceil((s+1)·B·2^64 / numBlocks))`; the last stripe has no upper bound. Every file is in key order, so it holds a stripe's keys as one contiguous run. One goroutine gathers each stripe in turn: in each file it finds where the run ends, with a galloping search, and copies the run out. The files are read once, sequentially and directly where the filesystem allows it, through fixed aligned buffers, two or three per file. Each buffer is its share of 128 MiB, kept between 64 KiB and 4 MiB, then rounded down to a multiple of lcm(4096, record size), and never less than one: 36 KiB to 92 KiB at the 64 KiB floor, depending on the record size. Past about 700 files those floors take more than the 128 MiB, up to 192 KiB per file. Each worker (`WithWorkers`) takes whole stripes: it sorts a stripe's records by block with a counting sort, solves the blocks, and hands them to the writer of §6.3, which commits them in block order. With one worker, the calling goroutine gathers, solves and writes each stripe itself. While sorting, a worker checks that each file's run is in order and that every record's block is in the stripe; a record that fails either check means a file out of order (`ErrUnsortedInput`). A duplicate key fails its block (`ErrDuplicateKey`), and the build fails if the records it read do not add up to the headers' counts (`ErrKeyCountMismatch`). @@ -974,6 +974,8 @@ Checksums cover every byte of an index file, and every byte of a sorted file but | Sorted file header, metadata | `HeaderHash` (§3.9) | whenever the header is read | | Sorted file records | `RecordsHash` (§3.9) | once every record is read: by `SortedFileReader` at the last record, by `MergeSortedFiles` before it finishes its output, by `BuildFromSortedFiles` before it finishes the index. A file with no records: whenever the header is read | +Both writers write the header last, after syncing the rest of the file, then sync again, so a header that passes its check means the whole file reached disk. + Opening an index reads no page it did not read before, as long as the user metadata fits in the header's page; larger metadata is read in full to be hashed. A query reads nothing more, so it does not detect corruption in the block metadata or the payload entry it reads: that takes `Verify`, which reads the whole file. **The checksums catch corruption, not tampering.** They use no secret, so anyone who can write the file can recompute them. Detecting tampering requires a keyed or cryptographic checksum stored **outside** the file (e.g. a manifest). From 71e0b1708807c7b85b696b539221296ad1743f2a Mon Sep 17 00:00:00 2001 From: tamirms Date: Wed, 25 Nov 2026 14:33:10 +0000 Subject: [PATCH 4/5] Cap the index's user metadata and algorithm config at 64 KiB Open read both section lengths and hashed that many bytes before the header check could confirm them, so a flipped bit in a length made Open hash up to the rest of the file before it failed. Each length is now at most 64 KiB, the limit sorted files already put on their metadata, and Open refuses a larger one before reading or hashing the section. A build refuses user metadata over the limit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AqbUZNMtZZBu8cT6ZLzFVp --- builder_options.go | 2 +- header.go | 4 ++++ index.go | 6 ++++++ index_writer.go | 8 ++------ integrity_test.go | 23 +++++++++++++++++++++++ streamhash-spec.md | 2 ++ 6 files changed, 38 insertions(+), 7 deletions(-) diff --git a/builder_options.go b/builder_options.go index 9fc3e1e..0f52517 100644 --- a/builder_options.go +++ b/builder_options.go @@ -74,7 +74,7 @@ func WithGlobalSeed(seed uint64) BuildOption { } } -// WithMetadata sets the variable-length user metadata. +// WithMetadata sets the variable-length user metadata, at most 64 KiB. // The metadata is copied, so the caller can reuse the slice after this call. func WithMetadata(data []byte) BuildOption { return func(c *buildConfig) { diff --git a/header.go b/header.go index 3eff911..c357a1b 100644 --- a/header.go +++ b/header.go @@ -32,6 +32,10 @@ const ( // ramIndexEntryDataSize is the entry's bytes before its check. ramIndexEntryDataSize = 10 + + // maxVariableSectionLen bounds UserMetadata and AlgoConfig, so a corrupt + // length fails before Open hashes past them. + maxVariableSectionLen = 64 << 10 ) // header is the 64-byte file header (spec §3.2). diff --git a/index.go b/index.go index 4b2eeef..943afc0 100644 --- a/index.go +++ b/index.go @@ -160,6 +160,9 @@ func (idx *Index) initFromData() error { } userMetadataLen := binary.LittleEndian.Uint32(idx.data[offset:]) offset += 4 + if userMetadataLen > maxVariableSectionLen { + return sherr.ErrCorruptedIndex + } if offset+uint64(userMetadataLen) > fileSize { return sherr.ErrTruncatedFile } @@ -172,6 +175,9 @@ func (idx *Index) initFromData() error { } algoConfigLen := binary.LittleEndian.Uint32(idx.data[offset:]) offset += 4 + if algoConfigLen > maxVariableSectionLen { + return sherr.ErrCorruptedIndex + } if offset+uint64(algoConfigLen) > fileSize { return sherr.ErrTruncatedFile } diff --git a/index_writer.go b/index_writer.go index dedf96b..affa444 100644 --- a/index_writer.go +++ b/index_writer.go @@ -4,7 +4,6 @@ import ( "encoding/binary" "errors" "fmt" - "math" "os" "sync/atomic" @@ -71,11 +70,8 @@ func (iw *indexWriter) writeAt(b []byte, off int64) error { func newIndexWriter(path string, cfg *buildConfig, numBlocks uint32, algo blockBuilder) (*indexWriter, error) { // Compute variable section sizes userMetadataLen := len(cfg.userMetadata) - // The length is written to disk as a uint32, so reject anything larger. - // Comparing via uint64 keeps this compiling on 32-bit builds, where the - // math.MaxUint32 constant doesn't fit in an int. - if uint64(userMetadataLen) > math.MaxUint32 { - return nil, fmt.Errorf("user metadata size %d exceeds maximum of %d bytes", userMetadataLen, uint64(math.MaxUint32)) + if userMetadataLen > maxVariableSectionLen { + return nil, fmt.Errorf("user metadata size %d exceeds maximum of %d bytes", userMetadataLen, maxVariableSectionLen) } algoConfigLen := algo.GlobalConfigSize() diff --git a/integrity_test.go b/integrity_test.go index e4022c8..7578a7f 100644 --- a/integrity_test.go +++ b/integrity_test.go @@ -60,6 +60,29 @@ func integrityIndex(t *testing.T) ([]byte, []sortedRecord) { return referenceIndex(t, path, recs, WithPayload(3), WithFingerprint(1), WithMetadata([]byte("user metadata"))), recs } +// TestOpenRefusesOversizedSections checks that a section length over the +// limit fails before Open hashes anything, and that a build refuses user +// metadata over it. +func TestOpenRefusesOversizedSections(t *testing.T) { + data, _ := integrityIndex(t) + algoLenOff := headerSize + 4 + len("user metadata") + for _, off := range []int{headerSize, algoLenOff} { + bad := slices.Clone(data) + binary.LittleEndian.PutUint32(bad[off:], maxVariableSectionLen+1) + if _, err := OpenBytes(bad); !errors.Is(err, ErrCorruptedIndex) { + t.Fatalf("a section length of %d at byte %d returned %v, want ErrCorruptedIndex", maxVariableSectionLen+1, off, err) + } + } + + recs := uniqueSortedRecords(newTestRNG(t), 100, 3) + path := filepath.Join(t.TempDir(), "big-metadata.idx") + b, err := NewSortedBuilder(context.Background(), path, uint64(len(recs)), WithPayload(3), WithMetadata(make([]byte, maxVariableSectionLen+1))) + if err == nil { + b.Close() + t.Fatal("a build accepted user metadata over the limit") + } +} + // TestOpenChecksHeaderHash flips a bit in every byte Open reads: the header, // the user metadata and the algorithm config. func TestOpenChecksHeaderHash(t *testing.T) { diff --git a/streamhash-spec.md b/streamhash-spec.md index 72f1790..2468f37 100644 --- a/streamhash-spec.md +++ b/streamhash-spec.md @@ -317,6 +317,8 @@ Immediately after the header: - **UserMetadata** — application-defined bytes, not interpreted by the index. May be zero-length. - **AlgoConfig** — per-algorithm configuration. Currently zero-length for both shipped algorithms (they use compile-time constants); reserved for future tunable algorithms. +Each length is at most 65,536 (64 KiB). A reader checks that before it reads or hashes the section, so a corrupt length fails with `ErrCorruptedIndex` at once instead of making the header check (§7.6) hash the rest of the file. + ### 3.4. RAM Index `NumBlocks + 1` entries. The final entry is a **sentinel**: it stores `KeysBefore == TotalKeys` and the end offset of the last block's metadata, so the last block's size can be computed by subtraction like any other. From 0b297f4efdf42b2451f8d830c8581d77fc282d8b Mon Sep 17 00:00:00 2001 From: tamirms Date: Fri, 27 Nov 2026 06:40:13 +0000 Subject: [PATCH 5/5] Name the metadata limit's error and keep a sorted reader's first error Review follow-ups. User metadata over 64 KiB now fails with the new ErrMetadataTooLarge, as an oversized payload or fingerprint fails with its own sentinel, and the README states the limit. The writer also checks the algorithm config against the cap Open enforces, so no algorithm can write an index Open refuses. SortedFileReader keeps its first error and returns it from every later call, so a caller that keeps reading after a failed check cannot end on a clean EOF. The spec's sorted-file error table and the QueryRank and QueryPayload docs now list ErrChecksumFailed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AqbUZNMtZZBu8cT6ZLzFVp --- README.md | 2 +- index.go | 6 ++++-- index_writer.go | 5 ++++- integrity_test.go | 7 ++++++- internal/sherr/errors.go | 1 + sentinels.go | 1 + sorted_file.go | 10 ++++++++++ streamhash-spec.md | 2 ++ 8 files changed, 29 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 63ba6de..99c8716 100644 --- a/README.md +++ b/README.md @@ -176,7 +176,7 @@ rank, err := idx.QueryRank(streamhash.PreHash(originalKey)) | `WithFingerprint(sizeBytes)` | Fingerprint size in bytes (0-4) | 0 (disabled) | | `WithAlgorithm(algo)` | `AlgoBijection` or `AlgoPTRHash` | `AlgoBijection` | | `WithGlobalSeed(seed)` | Hash seed (change on build failure) | fixed default | -| `WithMetadata(data)` | Arbitrary metadata stored in the file | none | +| `WithMetadata(data)` | Arbitrary metadata stored in the file, at most 64 KiB | none | | `WithBytesPerSync(n)` | Start writeback of the index every `n` bytes written (Linux) | 0 (left to the kernel) | | `WithYield(yield)` | Call `yield` before each block: one that blocks holds the build back, an error fails it | none (never yields) | diff --git a/index.go b/index.go index 943afc0..ff05d8b 100644 --- a/index.go +++ b/index.go @@ -264,7 +264,8 @@ func (idx *Index) Close() error { // QueryRank returns the rank (0-based index) for a key. // This is the core MPHF operation. -// Returns ErrKeyTooShort if key is less than 16 bytes. +// Returns ErrKeyTooShort if key is less than 16 bytes, and ErrChecksumFailed if +// a RAM index entry it reads fails its check. func (idx *Index) QueryRank(key []byte) (uint64, error) { if idx.closed.Load() { return 0, sherr.ErrIndexClosed @@ -542,7 +543,8 @@ func (idx *Index) WithPayload() (*PayloadIndex, error) { } // QueryPayload returns the rank and payload for a key. -// Returns ErrKeyTooShort if key is less than 16 bytes. +// Returns ErrKeyTooShort if key is less than 16 bytes, and ErrChecksumFailed if +// a RAM index entry it reads fails its check. func (pi *PayloadIndex) QueryPayload(key []byte) (rank uint64, payload uint64, err error) { if pi.closed.Load() { return 0, 0, sherr.ErrIndexClosed diff --git a/index_writer.go b/index_writer.go index affa444..b986408 100644 --- a/index_writer.go +++ b/index_writer.go @@ -71,9 +71,12 @@ func newIndexWriter(path string, cfg *buildConfig, numBlocks uint32, algo blockB // Compute variable section sizes userMetadataLen := len(cfg.userMetadata) if userMetadataLen > maxVariableSectionLen { - return nil, fmt.Errorf("user metadata size %d exceeds maximum of %d bytes", userMetadataLen, maxVariableSectionLen) + return nil, fmt.Errorf("%w: %d bytes", ErrMetadataTooLarge, userMetadataLen) } algoConfigLen := algo.GlobalConfigSize() + if algoConfigLen > maxVariableSectionLen { + return nil, fmt.Errorf("algorithm config size %d exceeds maximum of %d bytes", algoConfigLen, maxVariableSectionLen) + } // Estimate total file size for pre-allocation estimatedSize := estimateFileSizeForAlgo(cfg, numBlocks, algo, userMetadataLen, algoConfigLen) diff --git a/integrity_test.go b/integrity_test.go index 7578a7f..2d1f55b 100644 --- a/integrity_test.go +++ b/integrity_test.go @@ -79,7 +79,9 @@ func TestOpenRefusesOversizedSections(t *testing.T) { b, err := NewSortedBuilder(context.Background(), path, uint64(len(recs)), WithPayload(3), WithMetadata(make([]byte, maxVariableSectionLen+1))) if err == nil { b.Close() - t.Fatal("a build accepted user metadata over the limit") + } + if !errors.Is(err, ErrMetadataTooLarge) { + t.Fatalf("a build with user metadata over the limit returned %v, want ErrMetadataTooLarge", err) } } @@ -246,6 +248,9 @@ func TestSortedFileRecordsHash(t *testing.T) { if _, _, err := r.Next(); !errors.Is(err, ErrChecksumFailed) { t.Fatalf("record %d: Next returned %v for the last record, want ErrChecksumFailed", i, err) } + if _, _, err := r.Next(); !errors.Is(err, ErrChecksumFailed) { + t.Fatalf("record %d: Next returned %v after the failed record, want ErrChecksumFailed again", i, err) + } r.Close() } } diff --git a/internal/sherr/errors.go b/internal/sherr/errors.go index 906bf60..5b19554 100644 --- a/internal/sherr/errors.go +++ b/internal/sherr/errors.go @@ -20,6 +20,7 @@ var ( var ( ErrPayloadTooLarge = errors.New("streamhash: PayloadSize exceeds maximum 8 bytes") ErrFingerprintTooLarge = errors.New("streamhash: FingerprintSize exceeds maximum (4 bytes)") + ErrMetadataTooLarge = errors.New("streamhash: user metadata exceeds maximum (64 KiB)") ErrSplitBucketSeedSearchFailed = errors.New("streamhash: split bucket seed search failed - retry with different globalSeed") ErrIndistinguishableHashes = errors.New("streamhash: indistinguishable hashes in bucket - retry with different globalSeed") ) diff --git a/sentinels.go b/sentinels.go index 409cb18..c01e45c 100644 --- a/sentinels.go +++ b/sentinels.go @@ -18,6 +18,7 @@ var ( var ( ErrPayloadTooLarge = sherr.ErrPayloadTooLarge ErrFingerprintTooLarge = sherr.ErrFingerprintTooLarge + ErrMetadataTooLarge = sherr.ErrMetadataTooLarge ErrSplitBucketSeedSearchFailed = sherr.ErrSplitBucketSeedSearchFailed ErrIndistinguishableHashes = sherr.ErrIndistinguishableHashes diff --git a/sorted_file.go b/sorted_file.go index 5128962..cbde635 100644 --- a/sorted_file.go +++ b/sorted_file.go @@ -420,6 +420,7 @@ type SortedFileReader struct { left uint64 last sortKey record [MinKeySize + maxPayloadSize]byte + err error } // OpenSortedFile opens the sorted file at path to read its records in order. @@ -449,7 +450,16 @@ func OpenSortedFile(path string) (*SortedFileReader, error) { // Next returns the next record's key and payload, and io.EOF after the last // record. A record out of order fails with ErrUnsortedInput. If the records // do not match the file's hash, the last one fails with ErrChecksumFailed. +// After an error, every later call returns it. func (r *SortedFileReader) Next() (key [MinKeySize]byte, payload uint64, err error) { + if r.err != nil { + return key, 0, r.err + } + defer func() { + if err != nil { + r.err = err + } + }() if r.left == 0 { return key, 0, io.EOF } diff --git a/streamhash-spec.md b/streamhash-spec.md index 2468f37..5272219 100644 --- a/streamhash-spec.md +++ b/streamhash-spec.md @@ -923,6 +923,7 @@ Error names are from the reference implementation; other implementations may dif | `ErrDuplicateKey` | Bijection: identical `k0` and `k1`. PTRHash: two keys in a bucket share `k0 ^ k1` (§7.1) | | `ErrPayloadTooLarge` | PayloadSize > 8 | | `ErrFingerprintTooLarge` | FingerprintSize > 4 | +| `ErrMetadataTooLarge` | UserMetadata > 64 KiB | | `ErrPayloadOverflow` | payload value exceeds PayloadSize capacity | | `ErrKeyCountMismatch` | declared `totalKeys` ≠ keys added | | `ErrTooManyKeys` | key count exceeds `2^40 − 1` | @@ -952,6 +953,7 @@ An index with `N = 0` keys is not an error: it builds successfully, and every `Q | `ErrInvalidMagic` | magic ≠ `0x53545346` | | `ErrInvalidVersion` | version ≠ `0x0002` | | `ErrCorruptedIndex` | PayloadSize > 8, or MetadataLen > 65,536 | +| `ErrChecksumFailed` | HeaderHash mismatch whenever the header is read; RecordsHash mismatch once every record is read, or when the header is read for a file with no records (§7.6) | | `ErrUnsortedInput` | a key sorts before the key before it, when it is written, merged, read or built from; or a build finds a record outside its stripe | ### 7.6. Integrity and corruption safety