Skip to content

fix(ffi): metadata is part of a directive's identity - #1984

Merged
robcohen merged 2 commits into
mainfrom
fix/meta-hash-identity
Aug 7, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/meta-hash-identity

Conversation

@robcohen

@robcohen robcohen commented Aug 7, 2026

Copy link
Copy Markdown
Member

Closes #1968 — with option B: metadata in, comments out.

Why this way

meta.hash is not a label, it's 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.

Comments stay out. They're presentation, they don't 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, because a decision to exclude something is only recorded if a test
fails when someone quietly reverses it.

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."

What this is not

Uniqueness. Two transactions identical in every hashed field still collide, and
duplicates like that are ordinary in real ledgers. Only hashing source position
would make it unique, and that costs stability under every edit above the entry.
The consumer-side half is rustfava#273, which stops _get_entry silently picking
the first match.

Two details that aren't incidental

  • Keys are sorted. Metadata is an FxHashMap; 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.
  • Values are variant-tagged, not rendered. MetaValue's Display is lossy:
    Number(42) and Int(42) both print 42. WIT contract: entries-accepting surfaces classify/render with default ledger options #1766 went to deliberate trouble to
    keep those distinct; hashing the rendering would throw it away one layer down.

Separately — four fields reached no digest at all

Not the #1968 judgment call. 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.

field what collided
Open::booking FIFO vs LIFO — 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 / links a Document carries both exactly as a Transaction does
Custom::values the values are the directive — every custom "budget" on a date hashed the same

Verification

Six sabotages, six failures, restored green: drop transaction metadata, flatten the
MetaValue variant tags, remove the key sort, un-hash booking, un-hash
Custom::values, and start hashing comments.

The map-order test 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.

cargo test --workspace — 132 suites, 0 failures. Clippy clean on 1.97.0.

⚠️ Ordering

No CACHE_VERSION bump (the digest is derived at convert time from cached
directives, which are unchanged) and no WIT bump (the type is untouched) — which is
exactly the thing 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, which is #1967.

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).
@robcohen
robcohen requested a review from a team as a code owner August 7, 2026 14:10
Copilot AI review requested due to automatic review settings August 7, 2026 14:10
@codecov

codecov Bot commented Aug 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.8ms ± 1.2ms 24.1 MB
beancount 905.1ms ± 3.4ms 50.6 MB
Comparison 26x faster 2.1x less

vs main branch (2026-08-07)

Metric main this PR Change
Time 37.1ms 34.8ms -6.2% 🟢
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Updates the rustledger-ffi-wasi directive identity hash (meta.hash) so that user metadata participates in identity (while comments remain excluded), preventing metadata-only edits (notably insert_metadata) from resolving the wrong directive. It also completes hashing for several directive fields that previously did not affect the digest.

Changes:

  • Hash directive + posting Metadata with key-sorting for determinism and variant-tagged MetaValue hashing to avoid lossy Display collisions.
  • Extend compute_directive_hash coverage to previously-unhashed identity-bearing fields (Open::booking, Balance::tolerance, Document::{tags,links}, Custom::values).
  • Add property tests asserting metadata-in / comments-out behavior and guarding against regressions/collisions.

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 Includes metadata (sorted keys, variant-tagged values) in directive/posting identity; adds hashing for several previously-ignored directive fields while keeping comments excluded.
crates/rustledger-ffi-wasi/tests/hash_identity_properties.rs Adds regression/property tests covering metadata identity semantics, map-order determinism, meta-value type distinction, comment exclusion, and formerly-unhashed fields.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/rustledger-ffi-wasi/src/hash.rs Resolved
@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

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

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.
@robcohen

robcohen commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Fixed in 7f64aaa. posting_identity's doc comment still carried the pre-#1968 line saying posting metadata was deliberately excluded — left behind by the change that reversed it. A comment contradicting the code it sits on is worse than none, since it's what a reader trusts before reading the body. It now states the split (metadata in, comments out) and points at metadata.

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.

Decide whether posting/directive metadata is part of meta.hash identity

2 participants