Repository navigation
fix(ffi): length-prefix the directive-identity hash; it had real collisions - #1961
Conversation
…isions #1902 Phase 1: `rustledger-ffi-wasi` is the most inverted cell on that issue's table - 13.1 fixes/kloc, the highest, with fuzz as its only verification. The first property written for it found three collisions. `compute_directive_hash` fed fields into SHA256 unseparated, and `Sha256::update` concatenates, so the digest was ambiguous at every field boundary: payee "ab" + narration "c" == payee "a" + narration "bc" tags ["ab"] == tags ["a"] + links ["b"] no payee + narration "ab" == payee "a" + narration "b" All three verified against the real function before the fix. The third is the one that matters most: a transaction WITH a payee hashed identically to one WITHOUT. WHY IT MATTERS This is not an internal convenience. The hash is surfaced as `meta.hash` across the WIT contract, so rustfava and the desktop app use it as a directive's identity. Two distinct directives sharing a digest are the same object to those consumers - conflated in a list, deduplicated wrongly, or one silently shadowing the other. THE FIX Length-prefix every field. Not a separator byte: fields are arbitrary UTF-8 and any sentinel could legitimately occur inside one, where a u64 length cannot. Applied to every arm, not just Transaction - `Note` (account + comment), `Event` (type + value), `Query` (name + query), `Pad` (account + source) and `Document` (account + path) all had the same ambiguity. FOUR PROPERTIES - hashing is deterministic, and the digest is 64 hex chars - field boundaries are unambiguous (the three collisions above) - every hashed field can move the digest - a collision here says the identity contract ignores something a consumer may consider identifying - directive KIND is part of the identity, so an open and a close on the same date and account cannot collide Verified the boundary property fails when the length prefix is removed. WIRE IMPACT, STATED PLAINLY Every hash value changes. The WIT schema does not - `meta.hash` is still a string - so no contract version moves. A consumer that PERSISTS hashes across a rustledger upgrade would see them all differ; one that uses them within a session is unaffected. Worth knowing before the next release rather than after. Refs #1902.
📊 Benchmark Results
vs main branch (2026-08-05)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
Updates the FFI directive identity hash (meta.hash) in rustledger-ffi-wasi to avoid real collisions caused by concatenating unseparated fields into SHA256, and adds property tests to guard the identity contract.
Changes:
- Introduce length-prefixed field hashing for
compute_directive_hashto make field boundaries unambiguous across all directive kinds. - Add a new property-test suite asserting determinism, boundary unambiguity, per-field influence, and directive-kind separation.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| crates/rustledger-ffi-wasi/src/hash.rs | Switch hashing to length-prefixed field encoding to eliminate boundary ambiguities/collisions. |
| crates/rustledger-ffi-wasi/tests/hash_identity_properties.rs | Add property tests that prevent regressions in the directive identity hash semantics. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
| Metric | Result |
|---|---|
| Check Compatibility | 100% |
| BQL Compatibility | 95% (raw 89%, 162 masked) |
| Full AST Match | 100% |
| Total Files | 812 |
What's tested
- Check: Exit codes and error counts match
bean-check - BQL: Query results match
bean-query
The headline is the EFFECTIVE rate, after pairs where beanquery
itself is wrong are masked. raw is the same run with nothing
masked. A widening gap means the registry grew, not that rledger
changed. - Files: ~800 test files downloaded from 10+ beancount repositories
Full results available in workflow artifacts
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Length alone would also accept a 64-character base64 or uppercase
encoding, either of which keeps the count while breaking every consumer
that parses the digest. Verified by flipping the {:02x} renderer to
{:02X}, which the new assertion catches.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
Suppressed comments (1)
crates/rustledger-ffi-wasi/tests/hash_identity_properties.rs:74
field_boundaries_are_unambiguouscovers string-boundary ambiguity inside a single tag/link value, but it misses the remaining collision class where the partition betweentagsandlinksis ambiguous (e.g. tags ["a","b"], links [] vs tags ["a"], links ["b"]). Adding a regression case here will fail under the current hashing scheme and will guard the collection-length/delimiter fix.
let cases: [(Directive, Directive, &str); 3] = [
(
txn(Some("ab"), "c", &[], &[]),
txn(Some("a"), "bc", &[], &[]),
"payee/narration boundary",
|
Deep review turned up a downstream break that this PR should not merge without a plan for.
|
| failing rustfava tests | |
|---|---|
| #1960 (merged, no hash change) | test_api_errors, test_serialise_entry_types |
| #1962 (loader test only, no hash change) | the same 2 |
| #1961 (this PR) | those 2 + test_get_ledger_data + test_api[account_report_off_by_one_journal…] |
And the assertion diff on test_get_ledger_data is exactly the payload:
- 'hash': '3f43843fea1277977ca64674e0255cf3ac68b8e59…'
+ 'hash': '89a5cc60095860b4164bcfca2be2edff4f4d27374…'
- 'hash': '96bfce852ea742b9a298e7a3d9d4041d6331bb38a…'
+ 'hash': 'bf73a4628ea234d9818288e038c7da691557e63bf…'
(Note entry_hash is scrubbed to ENTRY_HASH in those snapshots; hash — the one that moved — is not.)
That is the field this PR's own doc comment identifies as the contract: "compute_directive_hash is the FFI identity contract — it is surfaced as meta.hash across the WIT boundary." Length-prefixing changes every digest, and rustfava pins them in committed snapshots.
This does not make the fix wrong
The collisions were real — a transaction with a payee hashing identically to one without is not something to keep. The fix is right. But it is a breaking change to a published artifact contract, and the PR body does not say so.
What it needs before merging
- Say so in the PR body / commit trailer. Anyone bisecting a rustfava snapshot churn should land here.
- Coordinate the rustfava snapshot regeneration (
pytest --snapshot-update) so the two land together, or land this first and accept a red window with a tracking issue. - Decide whether
meta.hashis versioned. If consumers may pin it, a silent value change is the same class of problem as a parser change without aCACHE_VERSIONbump — the fix is right but the contract needs a signal. Worth a note in the WIT or a changelog entry either way.
Separately: the other 2 failures (test_api_errors, test_serialise_entry_types) are pre-existing — red on merged #1960 and on #1962 — so they are not from this PR, but they mean the rustfava check has been red on every PR for a while and nobody is reading it. Worth its own issue.
The test change in ad6eff2 (lowercase-hex assertion) is unaffected by any of this and is good to go.
Copilot caught this on review and it is correct. Length-prefixing each field makes the stream decode to a unique SEQUENCE of byte strings, but two different structures can still produce the SAME sequence wherever a variable-length collection abuts anything else. All three collide against the previous commit: tags [a,b], links [] == tags [a], links [b] no payee, narration a, tags[b] == payee a, narration b, no tags links [a,b], no postings == links [a], posting on b Same defect the length prefix fixed, one level up: element boundaries were unambiguous, collection boundaries were not. Fixed by hashing each collection length before its elements. The counts do not subsume the optionals. Within the postings list a posting emits its account then zero, one, or two further fields depending on its units, so even at a fixed posting count: [Assets:A 1 USD] [Assets:B] -> A 1 USD B [Assets:A 1 ] [USD Assets:B] -> A 1 USD B reachable only through the units presence tag. Verified by removing the tag while keeping every count - that case, and only that case, fails. Attribution is not uniform, so the boundary test collects every colliding case instead of stopping at the first: tag/link is caught only by the counts, the other two independently by either mechanism. The payee tag is belt-and-braces and is documented as such rather than pinned by a test it cannot fail.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
Suppressed comments (4)
crates/rustledger-ffi-wasi/src/hash.rs:124
Open.bookingis part of the directive’s semantics (and is surfaced over WIT), but it is not included incompute_directive_hash. Two distinctopendirectives that differ only in booking method will still collide and be conflated by consumers usingmeta.hashas identity.
Directive::Open(o) => {
field(&mut hasher, b"Open");
field(&mut hasher, o.date.to_string().as_bytes());
field(&mut hasher, o.account.as_bytes());
count(&mut hasher, o.currencies.len());
for c in &o.currencies {
field(&mut hasher, c.as_bytes());
}
crates/rustledger-ffi-wasi/src/hash.rs:136
Balance.toleranceis ignored bycompute_directive_hash, so two balance assertions that differ only by explicit tolerance will hash identically. Sincemeta.hashis treated as directive identity across the FFI boundary, this is still a correctness-level collision.
Directive::Balance(b) => {
field(&mut hasher, b"Balance");
field(&mut hasher, b.date.to_string().as_bytes());
field(&mut hasher, b.account.as_bytes());
field(&mut hasher, b.amount.number.to_string().as_bytes());
field(&mut hasher, b.amount.currency.as_bytes());
crates/rustledger-ffi-wasi/src/hash.rs:172
Documentdirectives carrytagsandlinks, butcompute_directive_hashcurrently hashes only date/account/path. That means two distinct documents with different tags/links will collide undermeta.hashand be conflated by FFI consumers.
Directive::Document(d) => {
field(&mut hasher, b"Document");
field(&mut hasher, d.date.to_string().as_bytes());
field(&mut hasher, d.account.as_bytes());
field(&mut hasher, d.path.as_bytes());
crates/rustledger-ffi-wasi/src/hash.rs:183
Custom.valuesis part of the directive payload, butcompute_directive_hashcurrently only hashes date +custom_type. Two distinct custom directives with different arguments will collide undermeta.hash, which defeats its use as a directive identity key across FFI.
Directive::Custom(c) => {
field(&mut hasher, b"Custom");
field(&mut hasher, c.date.to_string().as_bytes());
field(&mut hasher, c.custom_type.as_bytes());
Copilot caught this on review and it is real. A different defect from
the boundary ambiguity in the previous two commits: not two fields
blurring together, but fields never consulted at all. The posting hash
fed in only account and units, so all seven of these collided:
a different cost number 2 HOOL {100 USD} == 2 HOOL {200 USD}
a cost vs no cost
per-unit {100} vs total {{100}}
a lot label
a posting flag
a price vs no price
@ vs @@ at the same amount
The first is the one that matters: two purchases of the same stock at
different prices were the same object to every consumer of meta.hash.
The CostNumber match is written out variant by variant rather than
going through the per_unit()/total() accessors. Those cannot separate
PerUnitFromTotal from Compound - both set both - and an exhaustive
match makes adding a variant a compile error here, which forces the
identity question to be answered rather than silently defaulted.
Posting and transaction metadata and comments are deliberately left
out. That one is a contract question, not a bug: including them means
adding a comment changes a directive identity and breaks anything keyed
on it across a cosmetic edit. Filed as #1968.
Verified by reverting posting_identity to account+units: 7 of 7 cases
collide.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.
Suppressed comments (3)
crates/rustledger-ffi-wasi/src/hash.rs:264
Customdirectives ignorevalues, so different custom directives with the same date andcustom_typebut different arguments will hash identically. SinceMetaValuecan render the same text across variants (e.g.Int(42)vsNumber(42)), hashingvaluesneeds a variant tag plus a canonical encoding of the payload.
Directive::Custom(c) => {
field(&mut hasher, b"Custom");
field(&mut hasher, c.date.to_string().as_bytes());
field(&mut hasher, c.custom_type.as_bytes());
}
crates/rustledger-ffi-wasi/src/hash.rs:217
Balancedirectives have an optionaltolerancefield that changes their semantics, but it is not included in the hash. Two balances with different tolerances will collide as the samemeta.hash. Hashtolerancewith an explicit presence tag.
Directive::Balance(b) => {
field(&mut hasher, b"Balance");
field(&mut hasher, b.date.to_string().as_bytes());
field(&mut hasher, b.account.as_bytes());
field(&mut hasher, b.amount.number.to_string().as_bytes());
field(&mut hasher, b.amount.currency.as_bytes());
}
crates/rustledger-ffi-wasi/src/hash.rs:205
Opendirectives currently hash date, account, and currencies but ignorebooking. Two opens that differ only by booking method would still collide and be treated as the same identity across the FFI (meta.hash). Includebookingas a presence-tagged field.
This issue also appears in the following locations of the same file:
- line 211
- line 260
Directive::Open(o) => {
field(&mut hasher, b"Open");
field(&mut hasher, o.date.to_string().as_bytes());
field(&mut hasher, o.account.as_bytes());
count(&mut hasher, o.currencies.len());
for c in &o.currencies {
field(&mut hasher, c.as_bytes());
}
}
* fix(ffi): metadata is part of a directive's identity Closes #1968. `meta.hash` is not a label - it is a WRITE ADDRESS. rustfava resolves an entry by it and then mutates that entry's line in the source file: save_entry_slice, delete_entry_slice, insert_metadata. Two of those carry a second factor (the sha256sum of the displayed source slice), so a wrong resolution is caught. `insert_metadata` carries nothing - and it is the endpoint whose entire job is CREATING metadata-only differences. The one operation that could act on a metadata collision was the one operation unguarded against it. So: metadata IN. It is structured user data with a whole write API premised on it being meaningful. Comments OUT - they are presentation, they do not reliably survive a parse/format round trip, and including them would mean fixing a typo in a comment changes a directive's identity. `comments_are_deliberately_not_part_of_the_identity` pins that exclusion, because a decision to EXCLUDE something is only recorded if a test fails when someone quietly reverses it. Worth noting what this is NOT: uniqueness. Two transactions identical in every hashed field still collide, and duplicates like that are ordinary in real ledgers. Only source position would make the hash unique, and that costs stability under every edit. This narrows the gap; the consumer-side fix for the rest is rustfava's `_get_entry`, which used to pick the first match silently. For reference, this is closer to where fava started. Before the rustledger hash was bolted on, rustfava called `beancount.core.compare.hash_entry(entry)` - default `exclude_meta= False`, i.e. metadata INCLUDING filename and lineno. Beancount's own docstring: "when you're using the hashes to uniquely identify transactions, you want to include the filenames and line numbers". Two implementation details that are not incidental: - `Metadata` is an FxHashMap, so keys are SORTED before hashing. Hashing it in iteration order would make the digest depend on insertion history - nondeterminism in the one field every consumer treats as stable. Sorting also matches `meta_entries_from_core` in the component converter, which sorts for the same reason. - Metadata VALUES are variant-tagged, not rendered. `MetaValue`'s Display is lossy: `Number(42)` and `Int(42)` both print `42`. #1766 went to deliberate trouble to keep those distinct and hashing the rendering would throw it away again one layer down. Separately - and NOT a judgment call - four fields reached no digest at all, found by auditing every directive struct's fields against the arms of compute_directive_hash. Same class as the cost/price/flag omission #1961 fixed: Open::booking FIFO vs LIFO hashed identically, and the method decides how every reduction against the account books. Balance::tolerance `100 USD` and `100 USD ~ 0.05` are different assertions; one can pass where the other fails. Document::tags a Document carries tags and links exactly as a Document::links Transaction does; neither reached the digest. Custom::values the values ARE the directive - every `custom "budget"` on a date hashed the same. Every new test sabotage-verified: drop transaction metadata, flatten the MetaValue variant tags, remove the key sort, un-hash booking, un-hash Custom values, and start hashing comments - six sabotages, six failures, restored green. The map-order test also self-checks. Whether two maps iterate differently is a property of the chosen keys and FxHashMap's bucket layout, not something the test controls - so it asserts the orders DIFFER before asserting the hashes match. Without that, a hasher change could leave it passing with the sort deleted. No CACHE_VERSION bump: the digest is derived at convert time from cached directives, and directives are unchanged. No WIT bump: the type is untouched. Which is exactly the problem worth flagging - this is a breaking behavioral change to a wire field that neither cargo-semver-checks nor the WIT gate can see. rustfava's snapshots are the only thing that catches it (#1967). * docs(ffi): correct the stale posting-metadata exclusion note Copilot: posting_identity now hashes p.meta, but its doc comment still said metadata was deliberately excluded - the pre-#1968 text, left behind by the change that reversed it. A comment that contradicts the code it sits on is worse than none, because it is the thing a reader trusts before reading the body.
Addresses review feedback on the previous commit. It said the digest is "stable only within a WIT package version". That reads as a guarantee the project does not actually keep: #1961 changed the hash format in an ordinary release and did not touch the WIT package version (verified against its merge commit, 2f707c6 — it edits hash.rs and a test, and the `package rustledger:ledger@...` line is untouched). Documenting a promise nobody honors is worse than documenting nothing, because a consumer could reasonably rely on it. Now states what is true: the digest is deterministic for a given build, and carries no cross-version guarantee, with #1961 cited as the precedent for it changing in a normal release. Two smaller points from the same review, both fair: - "within a single loaded session" understated determinism. The value is reproducible across runs; the real caveat is across versions, not across runs. - "hashes the directive's content" sat oddly against the later note that comments are excluded. The exclusion is now stated up front, as part of what the digest covers. Left out deliberately: the suggestion to require a WIT package version bump on any hash-format change. That is a policy decision about the release process, not something a doc comment should assert unilaterally — and asserting it here would re-create the same gap, since the practice does not currently work that way. WIT parses; clippy 1.97 with -D warnings clean.
* docs(wit): state the stability contract for meta.hash Closes #2111. `meta.hash` was declared as a bare `string` with no statement of what consumers may rely on. That silence is what made #1961 a surprise downstream: it length-prefixed every field fed into `compute_directive_hash` — correct, and it fixed three real collisions, the worst being a transaction with a payee hashing identically to one without — but it changed every digest, and rustfava was pinning them in committed snapshots (#1967). Nothing is broken now: rustfava#280 stopped pinning the digest rather than versioning it, so a future format change no longer costs a regeneration downstream. What was missing is the written contract, so the next person changing the hash format knows what they are and are not promising. Records that the algorithm is an implementation detail, that the value is stable only within a WIT package version, and that it must not be persisted, pinned in tests, or compared across versions. Also notes that comments are excluded (#1968), so two directives differing only in their comments share a digest — which is a property a consumer might otherwise discover the hard way. Field-level doc comments are an established pattern in this file (3 of 37 records already use them). Comment-only: the WIT still parses (verified the check can fail, by feeding it a deliberate syntax error), the component crate builds, and clippy 1.97 with -D warnings plus rustdoc with -D warnings are both clean — the docs reach generated Rust through the `wit_bindgen::generate!` proc macro, so they are lintable even though nothing lands on disk. * docs(wit): describe meta.hash's actual stability, not an unkept promise Addresses review feedback on the previous commit. It said the digest is "stable only within a WIT package version". That reads as a guarantee the project does not actually keep: #1961 changed the hash format in an ordinary release and did not touch the WIT package version (verified against its merge commit, 2f707c6 — it edits hash.rs and a test, and the `package rustledger:ledger@...` line is untouched). Documenting a promise nobody honors is worse than documenting nothing, because a consumer could reasonably rely on it. Now states what is true: the digest is deterministic for a given build, and carries no cross-version guarantee, with #1961 cited as the precedent for it changing in a normal release. Two smaller points from the same review, both fair: - "within a single loaded session" understated determinism. The value is reproducible across runs; the real caveat is across versions, not across runs. - "hashes the directive's content" sat oddly against the later note that comments are excluded. The exclusion is now stated up front, as part of what the digest covers. Left out deliberately: the suggestion to require a WIT package version bump on any hash-format change. That is a policy decision about the release process, not something a doc comment should assert unilaterally — and asserting it here would re-create the same gap, since the practice does not currently work that way. WIT parses; clippy 1.97 with -D warnings clean.
#1902 Phase 1.
rustledger-ffi-wasiis the most inverted cell on that issue's table — 13.1 fixes/kloc, the highest, with fuzz as its only verification. The first property written for it found three collisions.compute_directive_hashfed fields into SHA256 unseparated, andSha256::updateconcatenates, so the digest was ambiguous at every field boundary:All three verified against the real function before the fix. The third matters most: a transaction with a payee hashed identically to one without.
Why it matters
This isn't an internal convenience. The hash is surfaced as
meta.hashacross the WIT contract, so rustfava and the desktop app use it as a directive's identity. Two distinct directives sharing a digest are the same object to those consumers — conflated in a list, deduplicated wrongly, or one silently shadowing the other.The fix
Length-prefix every field. Not a separator byte: fields are arbitrary UTF-8 and any sentinel could legitimately occur inside one, where a
u64length cannot.Applied to every arm, not just
Transaction—Note(account + comment),Event(type + value),Query(name + query),Pad(account + source) andDocument(account + path) all had the same ambiguity.Four properties
openand acloseon the same date/account cannot collideVerified the boundary property fails when the length prefix is removed:
Wire impact, stated plainly
Every hash value changes. The WIT schema does not —
meta.hashis still astring— so no contract version moves. A consumer that persists hashes across a rustledger upgrade would see them all differ; one that uses them within a session is unaffected. Worth knowing before the next release rather than after.Verification
cargo fmt --checkcleanRefs #1902.
BREAKING: every
meta.hashvalue changesLength-prefixing changes every digest this function produces.
meta.hashisthe FFI identity contract, and rustfava pins these values in committed
snapshots, so landing this turns two of its tests red:
tests/test_internal_api.py::test_get_ledger_datatests/test_json_api.py::test_api[account_report_off_by_one_journal-…]Attribution is isolated — #1960 and #1962 carry no hash change and fail only
the 2 pre-existing rustfava tests; this PR fails those plus the two above, and
the assertion diff is literally the
hashvalues moving.Landing knowingly with #1967 tracking the snapshot regeneration. The
collisions being fixed here are worse than a red downstream check: a
transaction with a payee hashing identically to one without means two
distinct directives are the same object to every consumer of
meta.hash.If you are bisecting rustfava snapshot churn to this commit — this is why.
Review found the prefix was only half of it
Copilot caught that length-prefixing individual fields does not disambiguate
collection boundaries, and it was right. Three further structures collided
against the first commit:
Same defect one level up: length prefixes make the stream decode to a unique
sequence of byte strings, but two structures can produce the same sequence
wherever a variable-length collection abuts anything else.
Every collection length is now hashed before its elements. Counting alone is
still not sufficient — a posting emits a variable number of fields itself, so
even at a fixed posting count:
which needs a presence tag on the optionals. Verified by removing the tag while
keeping every count: that case, and only that case, fails.
The three mechanisms are not uniformly load-bearing, so the boundary test
collects every colliding case rather than stopping at the first. The payee tag
is belt-and-braces and is documented as such rather than pinned by a test it
cannot fail.
And a third defect: fields that were never hashed
Copilot then caught that the posting hash fed in only
accountandunits—cost,priceandflagwere absent entirely. Not two fields blurringtogether, but fields never consulted. Seven cases collided:
The first is the one that matters: two purchases of the same stock at different
prices were the same object to every consumer of
meta.hash.The
CostNumbermatch is written out variant by variant rather than using theper_unit()/total()accessors, which cannot separatePerUnitFromTotalfromCompound(both set both). Exhaustiveness also makes adding a variant acompile error here.
Deliberately out of scope: posting and transaction
metaand comments.That is a contract question, not a bug — including them means adding a comment
changes a directive's identity. Filed as #1968.