Repository navigation
perf(parser): fold the node shape rules into the green walk - #2059
Conversation
Three error passes in `parse_via_cst_inner` — unclosed cost braces, a link
used as a metadata value, tags/links used as custom/pushmeta values — each
did its OWN whole-tree red `descendants()` walk. Red iteration allocates a
`Box<NodeData>` per node with no recycling.
The green `DescendantsWalker` already visits every node and already tracks
the byte offset, so the rules now cost one `match` per node on a walk that
was happening anyway. Cachegrind, 10k txns, both sides rebuilt at HEAD:
tagged 1,109.08M -> 1,030.42M -7.09%
investment 2,203.54M -> 2,158.85M -2.03%
simple 784.36M -> 779.73M -0.59%
An ablation that deletes the three passes outright bounds the win at -7.46%
/ -2.15% / -0.57%, so this captures ~95% of what is there to get.
WHY IT WAS INVISIBLE. Each pass carried a `stripped.contains(..)` byte-scan
guard, so all three are free on a ledger with no `{`, `^` or `#` — which is
exactly the `simple` profiling shape. An earlier pass over `simple` alone
concluded these were not a hotspot. A `#` appears in any tagged ledger and a
`{` in any investment one, so real files paid all three. The green path
needs no guards at all now: no `{` in the source means no COST_SPEC node was
built, so the folded rule finds nothing.
Green-only. Red keeps the three standalone `extract_*` functions, because
folding them into its flat `descendants_with_tokens()` walk would need each
token's immediate parent kind, and `t.parent()` allocates the very red node
this avoids. Green is the path every caller but the parity test takes.
Error ORDER is preserved exactly — three separate vecs extended in the old
sequence, each in document order — and `first_cost_spec_defect` stays the
one shared rule both paths call, so they cannot drift on what a defect is.
TESTS. `green_equals_red_on_the_node_shape_rules` pins green against red on
sources that actually trigger all three; `ledger_source()` generates
well-formed ledgers and emits none of these constructs, so the existing
proptest reported agreement without ever having compared one. Five deliberate
mutations were run against the suite and all five are caught. Two of them
were NOT caught by the first version and are why the test looks like it does:
- `pushmeta` fixtures were written with a leading date, which is invalid,
so no PUSHMETA_DIRECTIVE node existed and a mutation making `pushmeta`
reject tags survived. The self-check now counts each RULE's own message
rather than "any error", which is what hid it.
- dropping the BOM subtraction on the cost-defect path survived, because
the only BOM fixture had an UNCLOSED spec, which returns before reaching
the path that indexes `stripped`.
`a_child_node_advances_the_offset_for_later_tokens` pins the offset
accumulation over child nodes on a hand-built green node: all four matching
kinds have token-only children today (even a parenthesized arithmetic cost
component stays flat), so no source fixture can reach it, and dropping the
accumulation otherwise passes the whole suite.
📊 Benchmark Results
vs main branch (2026-08-15)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
This PR removes three allocation-heavy red-tree descendants() scans from the default (green) CST conversion path by folding the corresponding per-node “shape rules” into the existing green DescendantsWalker traversal. It preserves diagnostic ordering/semantics while reducing per-node red allocations that were showing up heavily in tagged/investment workloads.
Changes:
- Fold cost-spec brace/component-shape checks, link-as-metadata-value checks, and custom/pushmeta tag/link value checks into the green CST descendants walk (keeping red behavior unchanged behind the existing
contains(..)guards). - Preserve observable error ordering by collecting the three rule families into separate vectors and extending them into the main error list in a fixed sequence.
- Add targeted tests that actually exercise these shape rules (including BOM offsets) and a focused unit test to pin offset accumulation across nested green child nodes; check in proptest regression seeds.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| crates/rustledger-parser/src/cst/green.rs | Implements the folded per-node shape rules in the green descendants walker, including BOM-aware span handling and a unit test pinning child-node offset advancement. |
| crates/rustledger-parser/src/cst/convert.rs | Wires the new green-walker outputs into parse_via_cst_inner while keeping the red path’s standalone extract_* passes and preserving diagnostic ordering. |
| crates/rustledger-parser/tests/green_red_properties.rs | Adds fixtures + assertions that pin green/red equivalence specifically for the moved shape rules, including BOM cases and an explicit self-check that the fixtures still exercise the rules. |
| crates/rustledger-parser/tests/green_red_properties.proptest-regressions | Adds stored proptest regression seeds for previously found failing cases. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Self-review of the fold.
`green_red_properties.proptest-regressions` was committed by accident. Its
two seeds are `{{1 USD}}`, which proptest only ever failed on while a
DELIBERATE mutation had `R_DOUBLE_BRACE` removed from the closer set during
mutation testing. No such failure exists in committed code, so checking the
seeds in would assert a bug that never happened.
The seeds did expose a real hole, though: `{{`/`}}` is a separate token pair
from `{`/`}`, and the hand-written fixtures only used single braces. Running
that mutation against each suite separately shows the two are complementary,
which is now recorded in the test's rustdoc rather than assumed:
mutation fixtures proptest
pushmeta wrongly rejects a tag catches misses
BOM not subtracted on defect path catches misses
double-brace closer not recognized MISSED catches
So the double-brace cases are pinned explicitly here too, and the fixture
suite now catches all three.
This also corrects the rustdoc claim that `ledger_source()` "emits none of
these constructs". It does emit well-formed cost specs — that is how it
caught the closer mutation. What it does not emit is the MALFORMED input
these rules diagnose, so on those it compares two empty error lists.
Separately, mutation-checked that the rules are reached with
`collect_occurrences = false`: gating them on that flag fails
`a_malformed_cost_spec_does_not_produce_a_balance_error`. The loader and CLI
take that path and `parse_without_occurrences` promises a result identical to
`parse`'s apart from the occurrence indices, so the call site now says why it
must not be gated.
…#2085) * perf(core): stop rebuilding and rescanning on every ordered reduction A FIFO ledger was quadratic. 20k transactions took 9.1s, growing 93x for 10x the input; the same size on the `investment` shape takes 0.04s. Now 0.29s and linear. Two costs, both per reduction and both proportional to lots held. `commit_updates` tombstoned the drained lots with a `retain` over every slot and then called `rebuild_index()`, which walks every slot again and rehashes every key. But `updates` already names the slots that changed, so the repair is now proportional to the lots the reduction touched — the treatment `commit_from_lot` got in #2063, applied to the multi-lot half. On its own this was 5.2x. `plan_ordered` then scanned every slot, applied the cost-spec predicate to each, sorted the survivors and summed them, to take from the front. `ordered_index` keeps each currency's lots in (date, slot) order, so the walk starts where the answer is and stops once the reduction is covered. The up-front sufficiency sum went with it: that existed to guarantee a failed reduction does not mutate, which the plan/commit split (#2061) made structural — exhausting the walk reports the same shortfall having visited the same lots. The index costs +2.35% on `investment` and +0.9-1.3% on the other three shapes, which is the honest trade for removing the growth term. It is built on the first reduction under an ordered method and maintained from `add` only once built, so a ledger whose reductions resolve through `cost_index` never pays for it. Two things the differential test caught, neither of which the existing 480 core tests noticed: - The index must hold COST-LESS positions too. An empty cost spec matches one (`matches_cost_spec`: `(None, true)`), so ordered selection can drain one, and omitting them chose a different lot than the scan. `commit_from_lot` documents the same subtlety. - The first version of that test was vacuous: it called `plan_ordered` directly, which never builds the index, so it compared the scan against itself and passed against a deliberately reversed tiebreak. Adds a `fifo` shape to the workload generator. The existing four reach ordered selection twice in 2k transactions between them, which is why this survived the six superlinear terms fixed in #2059-#2067. Fixes #2083 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * perf(core): box the ordered index and keep it unbuilt until needed Review of my own diff, plus a correction to the numbers in the PR. `rebuild_index` repopulated `ordered_index` unconditionally, and both compaction and rollback call it — so an inventory acquired the index (and its maintenance) whether or not ordered selection was ever used, which defeated building it on demand. It now preserves whether the index was built rather than deciding. `cost_index_remove` cloned the currency and probed the index on every drained lot, including for inventories that never built one. The map is also `Option<Box<..>>` now: an inventory that never needs it carries a pointer instead of three words plus an allocation, on a type created per account and cloned per BQL output row. The regressions reported in the PR description were mostly not real. The two binaries had been built with different toolchains — one inside `nix develop` (1.96.0) and one outside (1.97.0) — which `cg_annotate --diff` exposed as equal-and-opposite entries for the same functions under `drop_in_place` versus `drop_glue` naming. Rebuilt identically: simple -0.03% tagged +0.03% multicurrency +0.04% investment +2.02% and the investment figure is codegen noise too: forcing the scan path in ONE binary, via an environment variable, moves it 45k instructions out of 1.36 billion — 0.003%. That shape books under STRICT, so it resolves through `cost_index` and never builds an ordered index at all. So: no measurable cost to ledgers that do not use ordered selection, and the ones that do are the ones getting 32x. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * docs(core): say that the ordered index holds cost-less lots too Copilot's review: the field, its accessor, its builder and the comment in `plan_ordered` all described `ordered_index` as holding "cost-bearing lots", while the code indexes every position. Worth more than a wording fix. The first version really did index only cost-bearing lots, and that was a wrong-lot-selection bug: an empty cost spec matches a cost-less position (`matches_cost_spec`: `(None, true)`), so ordered selection can drain one, and omitting them chose a different lot than the scan. Leaving the old description in place would have documented the bug as the design — the same shape as the three stale "O(1) clone" comments that hid quadratics through #2056. All four sites now say every lot, and say why the cost-less ones are there. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * fix(core): keep insufficiency ahead of overflow, and stop indexing for HIFO Two findings from reviewing my own diff for architectural correctness. Removing `plan_ordered`'s up-front sufficiency sum changed which error a doubly-broken reduction reports. Sufficiency used to be settled before any basis arithmetic ran, so a reduction that was both short of units and unrepresentable reported the shortfall — the half the ledger author can act on. Walking lazily reached the `checked_mul` first and reported the overflow instead. Nothing asked for that change and no test covered it: the whole suite passed either way. The overflow is now recorded and raised only once the reduction is known to be satisfiable, which restores the old precedence exactly: `NoMatchingLot`, then `InsufficientUnits`, then `Overflow`. `insufficient_units_are_reported_even_when_the_basis_would_overflow` pins it, and fails if the error returns eagerly again. `reduce_hifo` does not use `plan_ordered` — it sorts by cost and carries its own scan — so gating the index build on `Hifo` built a map nothing reads. FIFO and LIFO only now. Worth noting that HIFO's scan is the same shape this PR fixes and is still quadratic; it needs a cost-ordered index rather than this date-ordered one. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * fix(core): stop a multi-lot reduction sweeping unrelated empty lots Third architectural pass, on the half I had reviewed least. `commit_updates` used to finish with `retain(|p| !p.is_empty())` over the WHOLE inventory, so any reduction that happened to cross two lots also deleted every unrelated zero-unit position as a side effect. Those are not scrap: `Inventory::len` counts them and `currency_accounts` branches on `len() == 1` to match Python, so whether one survived depended on whether some other reduction was multi-lot. The incremental repair removes what it drained and nothing else. `a_multi_lot_reduction_leaves_unrelated_empty_lots_alone` pins it and fails on main. Getting there took two attempts: the first fixture added a zero-unit position directly, which `add` drops outright, so the test passed on both sides while proving nothing. A cost-less lot NETTING to zero is the only way one exists — which is the case `Inventory::len`'s contract is actually about. Also asserts the invariant the repair introduced. Adjusting one currency's running total is only correct because every producer of `ReductionPlan::Updates` filters on `units.currency` first; the old rebuild recomputed every currency and so could not have noticed that being violated. Checked before the loop, since afterwards the drained lots are tombstones and indexing one panics. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr --------- Co-authored-by: Claude Opus 5 <[email protected]>
Three error passes in
parse_via_cst_inner— unclosed cost braces, a link used as a metadata value, tags/links used ascustom/pushmetavalues — each did its own whole-tree reddescendants()walk. Red iteration allocates aBox<NodeData>per node with no recycling.The green
DescendantsWalkeralready visits every node and already tracks the byte offset, so the rules now cost onematchper node on a walk that was happening anyway.Measured
Cachegrind, 10k txns, both sides rebuilt at HEAD:
taggedinvestmentsimpleThe ceiling column is an ablation that deletes the three passes outright, so this captures ~95% of what is available. Supporting heap data (dhat): red
NodeDatawas 48.6% of all allocation blocks ontagged— a block-count problem, not a byte one — and malloc/free is the single largest instruction bucket in the program there at 15.3%.Why it was invisible
Each pass carried a
stripped.contains(..)byte-scan guard, so all three are free on a ledger with no{,^or#— which is exactly thesimpleprofiling shape. An earlier profiling pass that looked only atsimpleconcluded these were not a hotspot. But a#appears in any tagged ledger and a{in any investment one, so real files paid all three.The green path needs no guards now: no
{in the source means the parser built noCOST_SPECnode, so the folded rule finds nothing to report.Scope
Green only. Red keeps the three standalone
extract_*functions: folding them into its flatdescendants_with_tokens()walk would need each token's immediate parent kind, andt.parent()allocates the very red node this change exists to avoid. Green is the path every caller but the parity test takes.Error order is preserved exactly — three separate vecs extended in the old sequence, each in document order.
first_cost_spec_defectstays the one shared rule both paths call, so they cannot drift on what counts as a defect.Tests
green_equals_red_on_the_node_shape_rulespins green against red on sources that actually trigger all three rules. The existing proptest could not:ledger_source()generates well-formed ledgers and emits none of these constructs, so it reported agreement without ever having compared one.Five deliberate mutations were run against the suite and all five are caught. Two were not caught by the first version of the test, which is why it looks like it does:
pushmetafixtures were written with a leading date, which is invalid — noPUSHMETA_DIRECTIVEnode was built, and a mutation makingpushmetareject tags survived. The self-check now counts each rule's own message rather than "any error", which is what hid it.stripped.a_child_node_advances_the_offset_for_later_tokenspins the offset accumulation over child nodes on a hand-built green node. All four matching kinds have token-only children today — even a parenthesized arithmetic cost component stays flat — so no source fixture can reach it, and dropping the accumulation otherwise passes the entire suite.Gates run locally:
cargo test --workspace --all-features,cargo +1.97.0 clippy --workspace --all-features --all-targets -- -D warnings,cargo fmt --all -- --check,RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --all-features.🤖 Generated with Claude Code