Repository navigation
perf(core)!: store metadata as an ordered vector with interned keys - #2891
Merged
Merged
Conversation
`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]>
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
…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
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changed
MetadatawasFxHashMap<String, MetaValue>behind a box. Two costs dominated:memo:line held about 276 bytes of table;String. The loader's interning (dedup.rs) covered accounts, currencies, tags and links, but not metadata keys.Changes:
Metadatais a struct now (crates/rustledger-core/src/metadata.rs). Entries are{ key: InternedStr, value: MetaValue }in an insertion-orderedVec, 56 bytes each, with no spare capacity.insertgrows by exactly one slot up to 4 entries. Without that, the firstpushreserves 4 slots, and the shrinkrealloccost +1.1% instructions.MetaMap::fromtrims anything built in bulk.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.&str;reintern_directives(dedup.rs) now walks keys through the sharedStringInterner;InternScope/AsInternedStr.MetaValue;Vec<(String, MetaValueData)>, so the SemVer check is unaffected);MetaMap(still 8 bytes,Option<Box<Metadata>>).CACHE_VERSION61 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), withFIXTURE_VERSIONandLOADER_CACHE_VERSION_PINupdated.directive_archived_form_is_pinnedfixture 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.MetaValuelayout hash is unchanged.augmented_meta(the BQLmetacolumn) putsfilenameandlinenofirst and then the written keys in source order, which is beancount's dict order.Options measured
dhat on the 100k
--metajournal; instructions are relative to main.Interning string values was rejected. Unique values (ids, descriptions) each gain a 16-byte
Archeader, and the walk costs time. It would also have changedMetaValueat 144 sites.Before and after, 1M-transaction
--metajournalpython3 scripts/gen-hledger-perf-journal.py 1000000 --meta, 238 MB, releaseprofilingbuilds.retained:)profile_pipeline(check pipeline)report balances --no-cachereport balancescold (writes the cache)report balancescachedprofile_pipelineRetained metadata, main against this PR:
StringsArcper distinct keyNotes on the numbers:
perf stat -e instructions:u(valgrind is not in the dev shell); repeat runs agree within 0.01%.report balancesoutput 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
--metajournal. Each file gotformat,check --format json, and 8 BQL queries in text and JSON form (PRINT,metafrom 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 postingslistsfilename,lineno, then the written keys in source order. On main it was hash order, for examplefilename: ..., memo: "in", lineno: 1008.COMMODITY_META('USD')lists the keys as written, where main gave hash order.Value::Metadatathrough the same iteration, so they change the same way. TheDisplayofPosting/Transactionalso iterates in source order.Unchanged, because they sort or never depended on order:
formatandPRINT;serde_json::Mapis sorted);#transactionsmetaobject;userlist and directive hashes;The WASM JSON
metamap was already a stdHashMap, which has random order; this PR does not change it. LSP hover reads the CST, notMetadata.Rust API change:
Metadatais no longer aHashMapalias, soentry()and the hasher are gone. Keys areInternedStr:inserttakes&strorString, and iteration yields&InternedStr, which derefs tostr. Noted in the CHANGELOG.Tests
metadata.rsunit tests pin:Metadataat most 24;MetaMap::from;retain/removeorder, order-independent equality, and the serde round trip.crates/rustledger-loader/tests/meta_key_interning_test.rsassertsInternedStr::ptr_eqfor 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_metaorder test in the query crate.Review round 1
Bulk building is near-linear again.
Metadata::insertscans 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:MetadataBuilder;ExtendandFromIterator;augmented_meta;PartialEquses 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) andperf stat -e instructions:u:format, 40k keysThe 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_quadraticinrustledger-corecounts key comparisons for 50,000 keys throughMetadataBuilder,FromIteratorandPartialEq. The bound is under 10 per key. With a loop of inserts it counts 1,249,975,000 and fails.metadata_many_keys.rsinrustledger-parserparses 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_keyschecks 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### Breakingentry for theMetadataandMetaMapAPI change: not anFxHashMap, noentry(),InternedStrkeys, and changedinsert/retain/IntoIteratorsignatures. It also notes the source-order iteration andMetadataBuilder.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 newtest_parse_orders_pushed_keys_before_written_ones_as_beancountfixture, and rledger now gives the same order.The
augmented_metatest now expects beancount's order for a writtenlineno: 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.IterMutis aDoubleEndedIterator.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_orderfails 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 letbullet; that change came from main.How to test
All of these pass:
cargo test --workspace --all-features --no-fail-fastcargo clippy --workspace --all-features --all-targets -- -D warningsRUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-depscargo fmt --checkcargo check -p rustledger-wasm --target wasm32-unknown-unknownwasm-pack test --nodeincrates/rustledger-wasmParser output is unchanged; the corpus baseline fingerprint sorts metadata and passes.
Closes #2835
🤖 Generated with Claude Code