Skip to content

perf(parser): record the lines a defect check reads while the tree is built (ADR 0010) - #3113

Merged
robcohen merged 9 commits into
mainfrom
perf/defects-at-build
Nov 29, 2026
Merged

robcohen merged 9 commits into
mainfrom
perf/defects-at-build

Conversation

@robcohen

@robcohen robcohen commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Rebased onto main (2ecf161), now that #3105 and #3106 have merged: their two carried commits are dropped, and the series is the PR's own five commits plus one fix and three doc follow-ups found while re-checking it against #3096, #3099 and #3101 (see Rebase below).

What

Since #2802 and the parser-correctness PRs after it, the converter holds every line to beancount's grammar: transaction and directive headers, posting lines and the posting builder's cost and price rules, metadata lines, other transaction body lines, repeated metadata keys, invalid dates. Each check walked the finished tree again and re-collected each line's tokens (flattening the AMOUNT / COST_SPEC / PRICE_ANNOTATION nodes of every posting), on every line of every file, and the descendants walk was one more whole-tree pass. On a clean ledger they all found nothing, and together they were the largest part of the clean-path regression against v0.24.0.

Design (ADR 0010)

The tree builder is where a line's role is decided: it is the code that opens a POSTING or a META_ENTRY. A check that re-derived the line from the tree read that decision a second time. Now:

  • The builder reports each line to an observer (parser::BuildObserver): each token as it leaves the lexer; per top-level item its header line, each posting line, each metadata line (and whether it hangs on a posting), each other transaction body line, each COST_SPEC. The lines are the builder's own token slices, so nothing is re-collected. () observes nothing and is what parse_structured builds with: the formatter, the LSP's tree users and every other caller pay nothing.
  • The converter builds with a recorder (cst::line_checks::Recorder) that runs the same canonical rules on those slices, once, and keeps only a verdict per top-level item: which check could report there (HEADER, POSTING, META, BODY, DUP_META), whether any DATE is not a calendar date, and whether anything needs the descendants walk (an invalid token or a second BOM, a cost spec with a shape defect or no closing brace, a link as a metadata value, a custom / pushmeta directive). It also collects the column-0 comments by the walk's own rule.
  • The checks are unchanged and run where they ran, on the tree, but only for the items the recorder flagged. Everything that decides what is reported (errors already on the line, message, span, order) stays in the check. A clean ledger flags nothing, so no check walks it; the loader's lean parse (parse_without_occurrences) also skips the descendants walk when nothing needs it.

A verdict is a superset ("a rule found something on this line"), so skipping an unflagged item hides no error as long as the recorder reads the same tokens the check reads. Pinned three ways:

  • One extraction: which tokens form a header or metadata line is one function each (line_checks::txn_header_tokens, header_line_tokens), shared by the checks and the recorder; the token-collection loops in green::tl_transaction_header_check, convert::header_line_tokens and MetaCheck::line now call them.
  • Debug replay: in debug builds every check still runs on every unflagged item, and the descendants walk on every file it skipped, and asserts it reports nothing (for the walk: exactly the comments the recorder collected). Every debug test run replays it; a mutation that drops every flag fails 33 parser unit tests at once.
  • Red parity in release: parse_red_only records nothing and runs every check and the walk, so green_red_properties and fuzz_green_eq_red compare the two paths; new lean_equals_red_on_generated_ledgers (and the node-shape fixtures) do the same for parse_without_occurrences. Mutation-checked: skipping the walk unconditionally fails the fixture test in a release build.

Beancount-specific by design: the recorder calls the beancount frontend's rules, the observer is the beancount builder's. No format-neutral layer learns a beancount rule; another grammar's frontend brings its own builder and observer, or none.

Smaller pieces in the same commits, each output-neutral:

  • name_misspelled_booleans / name_mid_line_hash_comments only rename errors already found: skipped when there are none (the second scanned the whole source for #! / #+).
  • unevaluable_meta_value returns None before allocating when the value has no operator or parenthesis, which is where cost_region_read returns None anyway.
  • perf(parser): skip the defect checks a clean posting or metadata line cannot fail #3106's plain-posting shortcut takes a sale's empty cost {} (full_posting_check replayed by its debug assertion; the shapes test moves {} to the plain list).
  • txn_header::first_header_defect_in takes a slice instead of an owned Vec.

Numbers

rledger check, instructions:u, profiling profile (LTO), BEANCOUNT_DISABLE_LOAD_CACHE=1, 10k transactions, re-measured after the rebase (run-to-run spread about 0.1%):

workload v0.24.0 main (2ecf161) this PR vs main vs v0.24.0
simple 396.6M 469.0M 408.1M −13.0% +2.9%
investment 574.8M 682.9M 608.0M −11.0% +5.8%
tagged 612.7M 756.6M 648.7M −14.3% +5.9%
multicurrency 642.3M 650.2M 582.6M −10.4% −9.3%
fifo 545.7M 652.5M 582.0M −10.8% +6.7%
metadata-heavy 675.7M 824.9M 715.5M −13.3% +5.9%

v0.24.0 is built from its tag with today's toolchain, so the comparison is not a toolchain artifact.

By step (measured before the rebase, profiling profile without LTO, against main with #3105 and #3106): recording the line verdicts in the builder −39M / −57M / −62M on simple / metadata-heavy / tagged; slice-based extraction (no copies for a clean line) −4M to −6M; skipping the descendants walk −13M / −32M / −26M; the recorder hook inlined and cheaper metadata and sale-posting verdicts −5M to −16M.

Where the rest goes

(Measured before the rebase; #3099 and #3101 do not touch these paths on a clean ledger.)

Parse alone (parse_without_occurrences on the file, same toolchain, LTO), v0.24.0 → this PR: simple 258.6M → 257.9M (−0.3%), investment 346.4M → 354.2M (+2.3%), tagged 470.6M → 485.8M (+3.2%), multicurrency 382.7M → 387.8M (+1.3%), fifo 300.6M → 308.9M (+2.8%), metadata-heavy 535.1M → 551.3M (+3.0%). The parser, with every correctness check added since v0.24.0, is within ~3% of it. Of that, the lexer is more than all of it: lexing alone (lossless_kind_tokens) went 28.0M → 51.9M on simple and 54.9M → 105.4M on metadata-heavy, about 60% in the logos DFA (the token regexes changed for correctness, e.g. the Unicode classes of account names) and 40% in the TokenIter rewrite chain #3105 started on; the defect-check and walk savings above more than pay for it. That is the next lever, and it is a lexer change, not a checks change.

The rest of the check gap to v0.24.0 is outside the parser: booking and inventory work for fifo / investment (fifo +24M after parse), post-parse work on simple (+9.4M, the exact-decimal validation among it), and process start-up relocations of a larger binary (_dl_relocate_object_no_relro, about +6M). So the ≤5% target holds on simple and investment, is missed by a few tenths of a percent on tagged and metadata-heavy (where the lexer is the remaining parser cost), and is not reachable on fifo from the parser side.

Rebase

No output change

Against origin/main (2ecf161), on 45,182 inputs (the pinned fuzz_parse + fuzz_green_eq_red corpus, the compat corpus, every tracked ledger, the profiling workloads), at 4d63d00, the last code change (the commits after it touch only the CHANGELOG, the ADR and a doc comment):

  • parse_error_lines --jsonl and semantic_snapshot: byte-identical (tempdir names normalized).
  • The same inputs built with debug-assertions = true (parse_error_lines and semantic_snapshot): no assertion fires, so every skipped check and walk was replayed and found nothing.
  • parse vs parse_without_occurrences (directives, options, includes, plugins, comments, errors, warnings) in release: 0 mismatches (25 before the BOM fix).
  • scripts/compat-beancount-oracle-drift.py: 123,007 compared, tokens and errors all agree. compat-parse-error-parity.py --check and compat-semantic-parity.py --check: no regressions.
  • cargo test -p rustledger-parser -p rustledger-loader -p rustledger -p rustledger-lsp -p rustledger-surface-parity-tests (debug, so every check is replayed): 3,497 passed, 0 failed. cargo clippy --all-features --all-targets -- -D warnings: clean.
  • No cache-version bump: tokens, tree, errors and directives are byte-identical.

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Instruction counts vs base (cachegrind, deterministic)

Workload base this PR Change vs v0.24.0
check/simple 417.9M 362.4M -13.27% 🟢 +3.7%
check/investment 621.1M 551.2M -11.25% 🟢 +6.8%
check/tagged 645.1M 543.4M -15.76% 🟢 +5.4%
check/multicurrency 583.9M 517.8M -11.33% 🟢 -11.4%
check/fifo 598.5M 534.2M -10.75% 🟢 +1.1%
check/metadata 1.02G 862.8M -15.29% 🟢 +8.1%
check-warm/simple 162.4M 162.4M +0.00% ✅ +3.1%
format/simple 1.07G 977.8M -8.75% 🟢 +81.4%
format/metadata 2.73G 2.49G -8.82% 🟢 +109.1%
format/errors 121.3M 117.1M -3.44% 🟢 +158.4%
check/errors 303.8M 299.6M -1.41% 🟢 —
check-json/errors 183.9M 179.7M -2.27% 🟢 —
check/junkline 33.3M 33.1M -0.49% ✅ +333.9%
check-json/junkline 46.7M 46.5M -0.46% ✅ +657.1%
query/journal/simple 644.7M 588.8M -8.67% 🟢 -5.4%
query/groupby/simple 512.7M 456.3M -11.01% 🟢 -0.8%
query/groupby/investment 804.9M 734.5M -8.74% 🟢 -1.4%

Instruction counts (cachegrind I refs) are deterministic: the same binary on the same input gives the same count to within ~0.02%, so unlike wall clock a 1% change is real. 🟡 ≥ 1%, 🔴 ≥ 5%. The last column is cumulative drift from the pinned v0.24.0 baseline (scripts/perf-baseline.json).

Wall clock (hyperfine)

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 36.0ms ± 0.5ms 521.5ms ± 6.0ms 14.5x 35.5 MB / 51.1 MB
investment 55.2ms ± 0.5ms 2008.8ms ± 4.0ms 36.4x 44.4 MB / 59.2 MB
fifo 54.6ms ± 0.7ms 11516.8ms ± 52.5ms 210.9x 43.2 MB / 59.1 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 40.0ms ± 0.4ms 36.0ms ± 0.5ms -9.8% 🟢 faster 43.1 MB → 35.5 MB (-17.7%)
investment 61.1ms ± 0.5ms 55.2ms ± 0.5ms -9.7% 🟢 faster 55.1 MB → 44.4 MB (-19.4%)
fifo 60.5ms ± 0.5ms 54.6ms ± 0.7ms -9.7% 🟢 faster 57.2 MB → 43.2 MB (-24.4%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.3ms, investment 0.3ms, fifo 0.4ms), 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

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 828
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

codecov Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.74127% with 11 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/line_checks.rs 97.32% 6 Missing ⚠️
crates/rustledger-parser/src/cst/convert.rs 97.54% 3 Missing ⚠️
crates/rustledger-parser/src/cst/green.rs 92.59% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

robcohen and others added 8 commits November 29, 2026 07:39
… built

The tree builder hands each line, in the role it gives it (header, posting,
metadata, other body line), to a BuildObserver. The converter builds with a
recorder that runs the canonical line rules on the builder's own token
slice once and keeps only which top-level items hold a line some check
could report on. The checks then read the tree for those items alone; a
clean file flags nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hing it reports

The recorder now also notes what the descendants walk could report on (an
invalid token, a cost spec with a shape defect or no closing brace, a link as
a metadata value, a custom or pushmeta directive) and collects the column-0
comments by the walk's own rule as the tokens go by. Without occurrences to
collect, a file with none of those needs no walk. The line extraction is now
slice-based, so the recorder copies no tokens for a clean line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Inline the recorder's per-token hook; a plain metadata line skips the walk's
link scan; the plain-posting shortcut takes a sale's empty cost {}; and
unevaluable_meta_value answers None before allocating when the value holds
no operator or parenthesis, as cost_region_read would.

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

Since #3101 the descendants walk reports every BOM token in the tree (the
leading BOM is stripped before the build, so one there is a second BOM), but
the recorder only asked for the walk on an invalid token: the lean parse
skipped it on such a file and lost the BomInDirectiveBody error. The recorder
now flags a BOM token as it does an invalid one. The node-shape fixtures gain
a second BOM at the start of the file and on a later line, and stray \r
blanks after a line first token (#3099).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen force-pushed the perf/defects-at-build branch from 8d619e2 to 14679a4 Compare November 29, 2026 13:54
@robcohen
robcohen marked this pull request as ready for review November 29, 2026 13:54
@robcohen
robcohen requested a review from a team as a code owner November 29, 2026 13:54
@robcohen
robcohen merged commit 29e39c0 into main Nov 29, 2026
68 of 69 checks passed
@robcohen
robcohen deleted the perf/defects-at-build branch November 29, 2026 14:24
robcohen added a commit that referenced this pull request Nov 29, 2026
…check recorder (#3129)

The recorder added by #3113 kept each transaction's and posting's metadata
keys in a plain list and searched it for every new key, so one entry with
n keys cost n²/2 string comparisons. metadata_many_keys (50,000 keys) went
from 0.11 s to 1.54 s in release and from 0.73 s to 6.7 s in debug, and
fails its 15 s bound on CI runners (21 s), so main's Test job is red.

KeySet keeps the list for the first 16 keys, which covers every real
ledger, then moves into a hash set. The test is back to 0.12 s / 0.82 s.

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.

1 participant