Skip to content

Check index and sorted files for corruption (format version 2) - #39

Merged
tamirms merged 5 commits into
mainfrom
integrity-v2
Nov 27, 2026
Merged

tamirms merged 5 commits into
mainfrom
integrity-v2

Conversation

@tamirms

@tamirms tamirms commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Why

Most corruption in a streamhash file goes unnoticed today.

  • Index header. The header at the start of an index file holds its settings: the seed, the key count, the caller's metadata and the algorithm's parameters. A flipped bit there can make every lookup return a wrong result, and nothing reports an error.
  • RAM index. Keys are grouped into blocks of thousands of keys. The RAM index has one entry per block, saying where the block's metadata and payloads start. A flipped bit in an entry breaks every lookup that reads it, also with no error.
  • Verify() has checksums only for the payloads and the block metadata, so it misses most of this.
  • Sorted files have no checksum at all. A corrupt record goes into the index built from them.

stellar-rpc keeps its index files for years, so it needs to know when one is corrupt.

What changes

Index files

  • The header gets a checksum. Open checks it, with no extra reads.
  • User metadata and the algorithm config are capped at 64 KiB each, as sorted files' metadata already is. Open checks both lengths before hashing them, so a corrupt length fails at once instead of hashing the rest of the file.
  • Each RAM index entry gets its own checksum. A lookup checks the two entries it reads: its block's and the next block's.
  • A lookup still doesn't check the block metadata or the payload it reads. Checking them would cost extra reads or extra bytes per key.
  • Verify() now checks every byte of the file.

Sorted files

  • The header gets two checksums: one of the header itself, and one of all the records.
  • Finish writes both. A file whose writer stopped before Finish doesn't open.
  • The header's checksum is checked whenever the header is read.
  • The records' checksum is checked when a reader, a build or a merge reaches the end of the file. A build or merge with a bad input fails and leaves no output.

A failed check returns ErrChecksumFailed. The checksums catch corruption, not tampering. No exported function changes. WithMetadata now takes at most 64 KiB, and larger metadata fails with the new ErrMetadataTooLarge.

Both formats go to version 2. Version 1 files are rejected and have to be rebuilt. streamhash-spec.md has the new layouts.

Cost

Operation Before After
One PTRHash lookup, index in memory 40.5 ns 56.6 ns
64 PTRHash lookups, index through mmap 27.6 µs 30.5 µs
One Bijection lookup, index in memory 1,143 ns 1,135 ns
Open an index held in memory 90 ns 125 ns
Write one record to a sorted file 10.4 ns 12.1 ns
Build an index from sorted files, 1 worker 11.6M keys/s 11.4M keys/s
Merge sorted files 18.6M records/s 18.0M records/s
  • With 4 or 8 workers, the build's speed doesn't change measurably.
  • The RAM index grows by 4 bytes per block. With Bijection, that's about 0.01 bits per key.

How these were measured:

  • Each figure is the median of 10 runs on an Apple M1 Max.
  • Lookups use QueryRank, or QueryBatch for the mmap row, on an index of 1M keys with 4-byte payloads and 1-byte fingerprints.
  • The build uses BuildFromSortedFiles on 16M keys.
  • The merge uses MergeSortedFiles on 90 files of 1M records each.
  • Writing uses SortedFileWriter.Add alone, without fsync.

🤖 Generated with Claude Code

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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AqbUZNMtZZBu8cT6ZLzFVp

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The incompatible format migration and concurrent sorted-build checksum changes require byte-equivalence and race-suite validation unavailable in this review environment.

No open issues 🎉

What changed in this PR

This PR adds corruption detection to StreamHash’s index and sorted-file formats, upgrading both to version 2. Version 1 files must be rebuilt; no new exported API is introduced.

Changes:

  • Adds header hashes and per-entry RAM index checks, and expands Verify to cover the entire index.
  • Adds sorted-file header and record hashes, checked during reading, building, and merging.
  • Updates the format specification and tests for checksums, corruption, and unfinished writes.
File Description
streamhash-spec.md Documents version 2 layouts, checksums, validation, and storage costs.
sorted_merge.go Checks each input’s record hash before completing a merge.
sorted_file.go Writes and validates sorted-file header and record hashes.
sorted_file_test.go Updates layout and validation tests for version 2.
sorted_build.go Checks input record hashes before finalizing an index.
sorted_build_test.go Recomputes checksums in ordering-error fixtures.
open_variants_test.go Uses checked RAM entries in block-size assertions.
integrity_test.go Adds checksum, corruption, and unfinished-writer tests.
index.go Checks headers and RAM entries and expands full-file verification.
index_writer.go Writes header hashes and checksummed RAM entries.
index_writer_test.go Updates expected RAM entries to include checksums.
header.go Defines version 2 fields and checksum encoding helpers.
framework_test.go Updates RAM-entry round-trip tests for block-index checksums.
corruption_context_test.go Recomputes checksums to exercise structural corruption checks.
corrupt_input_fuzz_test.go Exercises corrupted indexes with checksums recomputed as well.

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The merge can emit modified partial-record data without detecting a checksum mismatch, and empty files bypass record-hash validation.

2 open issues

Review effort: Max

Comment thread sorted_merge.go Resolved
Comment thread sorted_file.go Resolved
tamirms and others added 2 commits November 25, 2026 13:08
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AqbUZNMtZZBu8cT6ZLzFVp
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AqbUZNMtZZBu8cT6ZLzFVp

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Unchecked variable-section lengths can cause Open to scan roughly 2 GiB before rejecting a corrupt index, creating a significant stall.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Validate variable-section lengths before hashing

index.go:181

The hash range comes from variable-section lengths whose integrity has not yet been checked. On an index larger than 2 GiB, flipping the high bit of an empty AlgoConfigLen makes Open scan about 2 GiB before failing; a corrupt UserMetadataLen can cause a similar stall. Reject invalid algorithm-config lengths before hashing, and protect the metadata length separately or impose a supported bound.

2 resolved since last review

Review effort: Max

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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AqbUZNMtZZBu8cT6ZLzFVp

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new 64 KiB metadata limit breaks previously supported v1 index rebuilds, and the compatibility change and migration path for affected callers remain undocumented.

1 open issue

Review effort: Max

Comment thread index_writer.go Resolved
tamirms added a commit to stellar/stellar-rpc that referenced this pull request Nov 25, 2026
Pins streamhash to 71e0b1708807, the head of stellar/streamhash#39,
four commits on main's 697af37a32ae. Main adds the sorted-file format,
BuildFromSortedFiles and WithYield (stellar/streamhash#29 and #31 to #35),
and stellar/streamhash#39 checks index and sorted files for corruption,
in format version 2, so files of version 1 no longer open. Its writers
write each file's header last, after syncing the rest of the file, so a
finished file costs two fsyncs, and it caps an index's user metadata and
algorithm config at 64 KiB. golang.org/x/sync and golang.org/x/sys move
up to the versions streamhash requires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AqbUZNMtZZBu8cT6ZLzFVp
@tamirms
tamirms requested a review from marwen-abid November 25, 2026 19:40
tamirms added a commit to stellar/stellar-rpc that referenced this pull request Nov 26, 2026
Pins streamhash to 71e0b1708807, the head of stellar/streamhash#39,
four commits on main's 697af37a32ae. Main adds the sorted-file format,
BuildFromSortedFiles and WithYield (stellar/streamhash#29 and #31 to #35),
and stellar/streamhash#39 checks index and sorted files for corruption,
in format version 2, so files of version 1 no longer open. Its writers
write each file's header last, after syncing the rest of the file, so a
finished file costs two fsyncs, and it caps an index's user metadata and
algorithm config at 64 KiB. golang.org/x/sync and golang.org/x/sys move
up to the versions streamhash requires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AqbUZNMtZZBu8cT6ZLzFVp

@marwen-abid marwen-abid left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! All minor comments

Comment thread index_writer.go Resolved
Comment thread streamhash-spec.md Resolved
Comment thread sorted_file.go Resolved
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AqbUZNMtZZBu8cT6ZLzFVp
@tamirms
tamirms merged commit ddc126a into main Nov 27, 2026
11 checks passed
@tamirms
tamirms deleted the integrity-v2 branch November 27, 2026 06:45
tamirms added a commit to stellar/stellar-rpc that referenced this pull request Nov 27, 2026
Pins streamhash to ddc126a36a49 on its main branch, where
stellar/streamhash#39 merged. Main adds the sorted-file format,
BuildFromSortedFiles and WithYield (stellar/streamhash#29 and #31 to #35),
and stellar/streamhash#39 checks index and sorted files for corruption,
in format version 2, so files of version 1 no longer open. Its writers
write each file's header last, after syncing the rest of the file, so a
finished file costs two fsyncs, and it caps an index's user metadata and
algorithm config at 64 KiB. golang.org/x/sync and golang.org/x/sys move
up to the versions streamhash requires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AqbUZNMtZZBu8cT6ZLzFVp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants