Skip to content

perf(core)!: store metadata as an ordered vector with interned keys - #2891

Merged
robcohen merged 4 commits into
mainfrom
perf/metadata-memory
Nov 8, 2026
Merged

robcohen merged 4 commits into
mainfrom
perf/metadata-memory

Conversation

@robcohen

@robcohen robcohen commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

What changed

Metadata was FxHashMap<String, MetaValue> behind a box. Two costs dominated:

  • hashbrown never allocates fewer than four 64-byte buckets plus control bytes, so a posting with one memo: line held about 276 bytes of table;
  • every key was its own heap String. The loader's interning (dedup.rs) covered accounts, currencies, tags and links, but not metadata keys.

Changes:

  • Metadata is a struct now (crates/rustledger-core/src/metadata.rs). Entries are { key: InternedStr, value: MetaValue } in an insertion-ordered Vec, 56 bytes each, with no spare capacity.
    • insert grows by exactly one slot up to 4 entries. Without that, the first push reserves 4 slots, and the shrink realloc cost +1.1% instructions.
    • MetaMap::from trims anything built in bulk.
    • The API is HashMap-shaped: get, insert(impl Into<InternedStr>, _), remove, contains_key, retain, iter, keys, values, values_mut, Index<&str>, FromIterator, Extend. Most callers did not change.
    • Lookups are a linear scan, which is faster than hashing at 1 to 4 short keys.
    • Equality ignores order, as before. Serde writes a map in insertion order. rkyv is derived.
  • Keys are interned through the existing paths only, with no second interner:
    • the parser builds keys straight from &str;
    • reintern_directives (dedup.rs) now walks keys through the shared StringInterner;
    • the cache-hit path interns them through the existing InternScope / AsInternedStr.
  • Unchanged:
    • MetaValue;
    • the plugin wire types (still a key-sorted Vec<(String, MetaValueData)>, so the SemVer check is unaffected);
    • the WIT contract (still a sorted pair list);
    • the serde shape;
    • MetaMap (still 8 bytes, Option<Box<Metadata>>).
  • Caches: loader CACHE_VERSION 61 and WASM 80 (loader 60 and WASM 77, 78 and 79 went to fix(parser): report the metadata shapes beancount rejects #2888, refactor: the source-text query surfaces answer by the file-based rule #2889 and fix(validate): report an invalid account name in a custom directive's values #2890), with FIXTURE_VERSION and LOADER_CACHE_VERSION_PIN updated.
    • The WASM directive_archived_form_is_pinned fixture gained metadata on a transaction and a posting. The old map's archived bytes followed hash order, so the fixture had no metadata to pin until now.
    • The MetaValue layout hash is unchanged.
  • augmented_meta (the BQL meta column) puts filename and lineno first and then the written keys in source order, which is beancount's dict order.

Options measured

dhat on the 100k --meta journal; instructions are relative to main.

variant retained blocks peak instructions
main 177.1 MB 1.67M 372 MB 15.816 G
hash map + interned keys 166.0 MB (-6%) 1.27M 371 MB +1.45%
compact vec, keys not interned 122.4 MB (-31%) 1.67M 317 MB -0.37%
compact vec + interned keys (this PR) 112.8 MB (-36%) 1.27M 317 MB +0.23%
... + interned string values 115.8 MB 1.07M 325 MB +1.47%

Interning string values was rejected. Unique values (ids, descriptions) each gain a 16-byte Arc header, and the walk costs time. It would also have changed MetaValue at 144 sites.

Before and after, 1M-transaction --meta journal

python3 scripts/gen-hledger-perf-journal.py 1000000 --meta, 238 MB, release profiling builds.

main this PR change
retained (dhat retained:) 1,773 MB in 16.67M blocks (1,773 B/txn) 1,130 MB in 12.67M blocks (1,130 B/txn) -36%
of which metadata 967 MB 324 MB -67%
dhat peak 3.72 GB 3.17 GB -15%
peak RSS, profile_pipeline (check pipeline) 4.29 GB 3.65 GB -15%
peak RSS, report balances --no-cache 4.29 GB 3.65 GB -15%
peak RSS, report balances cold (writes the cache) 5.86 GB 4.67 GB -20%
peak RSS, report balances cached 2.74 GB 1.75 GB -36%
parse cache file 896 MB 671 MB -25%
instructions, profile_pipeline 156.32 G 156.74 G +0.27%
instructions, 1M journal without metadata 76.222 G 76.205 G -0.02%

Retained metadata, main against this PR:

site main this PR
map storage 828 MB, 3M hashbrown tables 224 MB, 3M exact-size entry vectors
map boxes 96 MB 72 MB
keys 15 MB in 4M Strings shared: one Arc per distinct key
string values 27.8 MB 27.8 MB

Notes on the numbers:

  • The main-side dhat runs used main at 9fe2e2e. RSS and instructions were measured against 036554b, the base of this branch. The commits between them are parser fixes that do not touch metadata.
  • The machine was heavily loaded, so wall times were noise: 24 to 27 s for both builds in alternating runs. Instruction counts come from perf stat -e instructions:u (valgrind is not in the dev shell); repeat runs agree within 0.01%.
  • report balances output is byte-identical to main, cold and cached.

What output changes

Main iterated metadata in hash order; this branch iterates in insertion order, which is source order for a parsed directive. I compared a main build (separate tree and target dir) against this branch on every corpus file with metadata (23 files), a fixture with mixed metadata on every directive kind, and the 100k --meta journal. Each file got format, check --format json, and 8 BQL queries in text and JSON form (PRINT, meta from postings / #transactions / #commodities / #balances / #entries, entry_meta, meta(), COMMODITY_META). 440 outputs are identical. 10 differ, all of them text-rendered metadata cells, deliberately:

  • SELECT ... meta FROM postings lists filename, lineno, then the written keys in source order. On main it was hash order, for example filename: ..., memo: "in", lineno: 1008.
  • COMMODITY_META('USD') lists the keys as written, where main gave hash order.
  • The WASM and FFI query cells render the same Value::Metadata through the same iteration, so they change the same way. The Display of Posting / Transaction also iterates in source order.

Unchanged, because they sort or never depended on order:

  • format and PRINT;
  • the JSON query output (serde_json::Map is sorted);
  • the #transactions meta object;
  • the plugin wire, the WIT user list and directive hashes;
  • the lint and importer reports;
  • the corpus baseline fingerprint.

The WASM JSON meta map was already a std HashMap, which has random order; this PR does not change it. LSP hover reads the CST, not Metadata.

Rust API change: Metadata is no longer a HashMap alias, so entry() and the hasher are gone. Keys are InternedStr: insert takes &str or String, and iteration yields &InternedStr, which derefs to str. Noted in the CHANGELOG.

Tests

  • metadata.rs unit tests pin:
    • the layout: entry at most 56 bytes, Metadata at most 24;
    • the growth policy: exact capacity for 1 to 4 entries, amortized above;
    • trimming in MetaMap::from;
    • order, replace-in-place, retain/remove order, order-independent equality, and the serde round trip.
  • crates/rustledger-loader/tests/meta_key_interning_test.rs asserts InternedStr::ptr_eq for equal keys across directives, transactions and postings, and an included file, on both the load path and the cache-hit path. It fails when the dedup pass skips keys; I checked by removing the key walk.
  • augmented_meta order test in the query crate.
  • The WASM archived-form pin now covers metadata.

Review round 1

  • Bulk building is near-linear again. Metadata::insert scans for its key, so a loop of inserts was quadratic, and the parser built every map that way. Bulk paths now append entries unchecked and deduplicate once. A repeated key keeps its first position and its last value, as the inserts gave. Deduplication is pairwise up to 16 entries and uses a temporary hash index above that. The bulk paths:

    • the red and green parser paths, through the new public MetadataBuilder;
    • Extend and FromIterator;
    • serde deserialization;
    • augmented_meta;
    • pushmeta inheritance.

    PartialEq uses an index above 16 entries. The sorted renderers sort entries instead of looking each key up again: format, the FFI directive hash, the BQL value hash, and the control-character lint.

  • Measured with release builds, rledger check --no-cache (best of 3) and perf stat -e instructions:u:

    input main round 0 (d0635f4) this round
    one transaction, 40k keys 0.07 s, 0.396 G instr 2.54 s, 15.7 G 0.06 s, 0.423 G
    one transaction, 100k keys 0.28 s, 1.27 G 16.5 s, 120.4 G 0.21 s, 1.34 G
    importer shape, 20k transactions x 50 keys 1.53 s, 9.43 G 1.76 s, 9.96 G 1.68 s, 9.48 G
    format, 40k keys 0.06 s, 0.478 G 2.38 s, 15.8 G 0.05 s, 0.486 G

    The importer shape costs +0.5% instructions against main; round 0 cost +5.7%. Wall times on that row are within noise; the machine was loaded.

  • Regression tests that fail on the old code:

    • test_bulk_paths_are_not_quadratic in rustledger-core counts key comparisons for 50,000 keys through MetadataBuilder, FromIterator and PartialEq. The bound is under 10 per key. With a loop of inserts it counts 1,249,975,000 and fails.
    • metadata_many_keys.rs in rustledger-parser parses a transaction with 50,000 keys on both paths with a 15 s bound. It takes about 4 s in a debug build, and 34 s with the old inserts, where it fails.
    • test_bulk_paths_match_inserts_with_repeated_keys checks that the bulk paths give exactly what a run of inserts gives, on both sides of the threshold.
  • Breaking. The PR is retitled perf(core)!:. The CHANGELOG has a ### Breaking entry for the Metadata and MetaMap API change: not an FxHashMap, no entry(), InternedStr keys, and changed insert / retain / IntoIterator signatures. It also notes the source-order iteration and MetadataBuilder.

  • pushmeta order matches beancount. Pushed keys come first, each at the place it was first pushed, then the written ones. A key written over a pushed one keeps the pushed place and takes the written value. bean-query 0.2.0 prints {'zz-pushed': 'p', 'shared': 'written', 'written': 'w'} for the new test_parse_orders_pushed_keys_before_written_ones_as_beancount fixture, and rledger now gives the same order.

  • The augmented_meta test now expects beancount's order for a written lineno: it stays in the second position with the written value, where the old test pinned it at the end. That behavior comes from the same extend.

  • IterMut is a DoubleEndedIterator.

  • Invalid account metadata errors (E1005) come out in written order, as bean-check reports them, now that the order is stable without sorting (from the fix(validate): report an invalid account name in a custom directive's values #2890 review). The new test_validate_reports_invalid_account_metadata_in_written_order fails with the old sort.

  • Merged origin/main (feat: add opt-in lint for linked transit transfers #2819, fix(validate): report an invalid account name in a custom directive's values #2890). WASM moves to cache 80 because fix(validate): report an invalid account name in a custom directive's values #2890 took 79; loader stays at 61. Each version has one note.

  • Removed the stale ffi-component if let bullet; that change came from main.

How to test

python3 scripts/gen-hledger-perf-journal.py 1000000 --meta > hl1m-meta.beancount
cargo build -p rustledger --profile profiling --example profile_pipeline --features dhat-heap
./target/profiling/examples/profile_pipeline hl1m-meta.beancount   # see the retained: line
cargo test -p rustledger-core metadata
cargo test -p rustledger-loader --test meta_key_interning_test

All of these pass:

  • cargo test --workspace --all-features --no-fail-fast
  • cargo clippy --workspace --all-features --all-targets -- -D warnings
  • RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps
  • cargo fmt --check
  • cargo check -p rustledger-wasm --target wasm32-unknown-unknown
  • wasm-pack test --node in crates/rustledger-wasm

Parser output is unchanged; the corpus baseline fingerprint sorts metadata and passes.

Closes #2835

🤖 Generated with Claude Code

`Metadata` was `FxHashMap<String, MetaValue>` behind a box. hashbrown
never allocates fewer than four 64-byte buckets plus control bytes, so
a one-entry posting map held about 276 bytes of table, and every key was
its own heap `String` that the loader's interning did not reach.

`Metadata` is now a struct over an insertion-ordered `Vec` of
`{ key: InternedStr, value: MetaValue }` (56 bytes per entry, allocated
at its exact size up to four entries) with a HashMap-shaped API. Keys
are interned through the existing paths: the loader's dedup pass walks
them through the shared `StringInterner`, and the cache-hit path through
`InternScope`. `MetaValue`, the plugin wire types, the WIT contract and
the serde shape are unchanged.

On the 1M-transaction `--meta` journal, retained memory drops from
1,773 to 1,130 B per transaction (metadata from 967 MB to 324 MB), the
dhat peak from 3.72 to 3.17 GB, cold `report balances` peak RSS from
5.86 to 4.67 GB, and the parse cache from 896 to 671 MB, for +0.27%
instructions.

Metadata iterates in source order now: BQL `meta` cells list
`filename`, `lineno`, then the written keys, as beancount's dicts do.
Output that sorted keys is unchanged. The archived layout moved, so the
loader and WASM cache versions are bumped.

Closes #2835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 7, 2026 17:01
@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.93139% with 34 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/metadata.rs 92.26% 30 Missing ⚠️
crates/rustledger-query/src/executor/types.rs 0.00% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 51.4ms ± 0.8ms 821.7ms ± 5.9ms 16.0x 41.8 MB / 51.2 MB
investment 77.8ms ± 0.8ms 2929.4ms ± 13.3ms 37.6x 59.0 MB / 59.0 MB
fifo 73.6ms ± 0.6ms 14683.4ms ± 41.6ms 199.4x 54.8 MB / 58.7 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 50.1ms ± 0.7ms 51.4ms ± 0.8ms +2.5% ✅ within noise 42.9 MB → 41.8 MB (-2.4%)
investment 77.4ms ± 1.2ms 77.8ms ± 0.8ms +0.5% ✅ within noise 59.0 MB → 59.0 MB (-0.0%)
fifo 74.3ms ± 1.8ms 73.6ms ± 0.6ms -0.9% ✅ within noise 55.0 MB → 54.8 MB (-0.3%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.5ms, investment 0.6ms, fifo 0.8ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 826
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

robcohen and others added 3 commits November 7, 2026 12:39
…d keys as beancount

`Metadata::insert` scans for its key, so building a map one insert at a
time was quadratic: one transaction with 40,000 metadata lines took
2.35 s to parse where the hash map took 0.08 s. The parser, `Extend`,
`FromIterator`, deserialization and `augmented_meta` now append entries
unchecked and deduplicate once (first position, last value, as the
inserts give), pairwise up to 16 entries and through a temporary hash
index above. `PartialEq` uses an index above 16 entries too, and the
sorted renderers (format, directive hash, BQL value hash, the
control-character lint) sort entries instead of looking each key up
again. `MetadataBuilder` is the public way to build in bulk.

Pushed metadata now comes ahead of the written keys, each at the place
it was first pushed, as beancount's transaction meta dicts order them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	CHANGELOG.md
#	crates/rustledger-wasm/src/cache.rs
bean-check reports an invalid account among a directive's metadata
values in the order the lines are written. The sort by key was only
needed while `Metadata` was a hash map; it keeps insertion order now
(#2835), so the errors come out as bean-check orders them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen robcohen changed the title perf(core): store metadata as an ordered vector with interned keys perf(core)!: store metadata as an ordered vector with interned keys Nov 7, 2026
@robcohen
robcohen merged commit 8f4f518 into main Nov 8, 2026
68 of 69 checks passed
@robcohen
robcohen deleted the perf/metadata-memory branch November 8, 2026 05:02
robcohen added a commit that referenced this pull request Nov 8, 2026
… accounts' state (#2895)

* fix(validate): report a pad on a closed account, and pad whatever the accounts' state

Both checked against full bean-check 3.2.3 output:

- A pad dated after one of its accounts' close loaded clean; beancount
  reports `Invalid reference to inactive account`. It is now E1003, for
  the target and the source. On the close date itself the account is
  still active, as for a posting.
- A pad with an unopened (or not yet opened) account was dropped after
  its E1001, so the balance after it failed too (E2001), or, with an
  unopened target, the pad was never reported unused where beancount
  reports `Unused Pad entry`. Beancount inserts the padding before it
  validates anything, so the pad is now registered in every case; the
  half whose account was never opened has no inventory to land in, and
  a balance on an unopened target still uses (and so does not leave
  unused) the pad. `effective_pads` is the one rule for which pads a
  balance can use, shared by both paths.

`pad_balance_and_note_before_the_open_are_unopened` expected the old
E2001; bean-check reports no balance failure there, so it no longer does.

WASM CACHE_VERSION 81 (v80 is #2891's): its cached error lists change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(validate): document the pad count divergence, share the E2004 check, and cross-reference process_pads

Review round 1 on the pad gaps:

- The one-error-per-account choice is now a documented, deliberate
  divergence (maintainer decision): bean-check reports a pad account a
  second time against its synthesized padding transaction when the padding
  is non-zero; rledger pads inline and reports it once, at the pad. Code
  comment at the pad check, CHANGELOG, PR body.
- `effective_pads` and `rustledger_booking::process_pads` name each other as
  two implementations of which pad a balance uses, with a revisit condition.
- E2004 (multiple pads) is one helper, used on the opened-target and the
  unopened-target paths alike; a zero amount on an unopened target uses no
  pad, as on an opened one.
- Tests: a zero balance on an unopened target and an unopened-account pad
  with no balance are unused (E1001s plus E2003); E2004 on both paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(validate): pin the exact pad error counts, and describe the pad rule as it is

Review round 2 on the pad gaps:

- `test_validate_pad_with_an_unopened_account_still_pads` asserts the exact
  E1001 list per shape (one per unopened account at the pad, plus the
  balance's own on an unopened target), as the closed-account test does,
  so it actually pins the one-error-per-account divergence it is cited for.
- The zero-balance test's doc no longer contradicts itself.
- The `effective_pads` / `process_pads` cross-references describe the
  current rule: a superseded earlier pad stays usable in the validator,
  where beancount keeps only the latest, a bug on main that #2896 fixes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

perf(core): metadata entries cost about 210 B each; keys are not interned

1 participant