Skip to content

perf(parser): green-tree transaction conversion with red fallback (-16% load) - #1594

Merged
robcohen merged 9 commits into
mainfrom
perf/green-convert-transactions
Jun 25, 2026
Merged

robcohen merged 9 commits into
mainfrom
perf/green-convert-transactions

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

Green-tree transaction conversion — the lossless-CST-tax removal (PR 1). Converts transactions off the immutable green tree instead of red SyntaxNode cursors, wired into the load path with a red fallback.

Measured on a 10k-txn load: 1,062,145,403 → 891,072,035 I refs (−16.1%).

Why (the profiling chain)

The nightly profiling data branch + a sizing spike showed the CST→AST conversion is ~74% of the load, and ~33% of that is red-node traversal — each node touch heap-allocates + refcounts a NodeData. A prototype measured green traversal at ~24× cheaper per pass. This PR realizes it for transactions (the bulk of real ledgers).

How — correct by construction

  • cst/green.rs: a top-down green walk threading the absolute byte offset (no red-node allocation), building the full transaction (date / flag / payee+narration / tags / links / postings with units, all cost-spec forms {N CCY}/{{T CCY}}/{N # T CCY}, prices @/@@). Value parsing reuses the now-shared text parsers (parse_date_token, decode_string_token, parse_decimal_token, is_comment_kind) — one source of truth for red + green.
  • green::convert_transaction returns Some only when its output is byte-identical to red, and bails to red on anything it doesn't yet replicate (transaction metadata, direct-child comments, deprecated |, unparseable amounts, posting flags/metadata/arithmetic). So the hybrid is output-equivalent to the pure-red path by construction.

Verification

  • 283 parser + 57 integration + 89 loader + booking tests pass (they pin exact parse() output).
  • Field-level oracles for header / posting / cost / price (byte-identical to red).
  • parse_green_eq_red_corpus differential unit test: green-wired parse == parse_red_only across the green path and every fallback trigger (flag / meta / comment / arithmetic / multi-amount / pipe / invalid date / BOM / multi-byte / error recovery).
  • fuzz_green_eq_red differential fuzz target (registered in fuzz.yml) generalizes that invariant to arbitrary input.

Scope

This is the first slice. The walk_descendants_once / walk_top_level_once passes are still red (greening them adds more), and posting flags/metadata/arithmetic still fall back to red — all additive follow-ons the fallback already handles correctly. For context: the four prior optimization PRs combined moved the load ~−1.4%; this one moves it −16.1%.

🤖 Generated with Claude Code

robcohen added 5 commits June 25, 2026 14:16
…wip)

First increment of the green-conversion rewrite (profiling sizing spike: CST->AST
convert is ~74% of load, ~33% of it red-node traversal that allocs a NodeData
per node touch). Adds cst/green.rs: a top-down green-tree walk threading the
absolute byte offset, with a differential test proving its top-level node spans
are byte-identical to the red node_span across BOM/multi-byte/error-recovery
cases. De-risks offset drift (the #1 hazard) before directive-body conversion is
layered on. Not yet wired into the parse path.
… wip)

Adds convert_transaction_header: a single fused green pass extracting date /
flag / payee+narration / tags / links / span with no red-node allocation,
reusing the now-shared text parsers (parse_date_token, decode_string_token
extracted from StringLit::text_decoded so red+green share one decoder). A
field-level oracle pins every header field byte-identical to the red parse()
across flag variants, multi-string, tags/links, escapes, and multi-byte cases.
Postings/metadata/comments/error-recovery next. 282 parser tests pass.
Adds convert_simple_posting + simple_amount: a green pass building a Posting
(account + non-arithmetic units + posting_span + same-line trailing comments)
with no red-node allocation, reusing the shared parse_decimal_token /
is_comment_kind (now pub(super)). Bails (None) on flag/cost/price/metadata/
arithmetic/multi-amount postings (later increments; the oracle corpus excludes
them). Field oracle pins the full Posting + span byte-identical to red across
simple/elided/negative/trailing-comment/decimal cases. clippy clean; 283 tests.
…(PR1 wip)

Adds green convert_cost_spec (forms {N CCY} / {{T CCY}} / {N # T CCY} / {*}
merge, + date + label, via a fused pass mirroring convert_cost_spec +
cost_total_after_hash) and convert_price_annotation (@@->Total/@->Unit + amount,
bailing on arithmetic amounts). Wired into convert_simple_posting (cost/price no
longer bail). Oracle corpus extended with all cost-spec forms + @/@@ prices +
cost+price together; full Posting+span byte-identical to red. clippy clean,
283 tests.
… load)

Adds green::convert_transaction (header + simple postings, bailing to red on
txn-metadata / direct-child comments / deprecated-pipe / unparseable amount /
posting flag-meta-arithmetic) and wires it into parse_via_cst_opts dispatch with
a red fallback: green is used only when its output is identical to red, so the
hybrid is output-equivalent. Measured on the 10k-txn load: 1,062,145,403 ->
891,072,035 I refs (-16.1%) -- the lossless-CST-tax recovery the sizing spike
predicted, from converting transactions off the green tree instead of red-node
cursors. 283 parser + 57 integration + 89 loader + booking tests pass.
@robcohen
robcohen requested a review from a team as a code owner June 25, 2026 15:14
Copilot AI review requested due to automatic review settings June 25, 2026 15:14
Adds parse_red_only (forces the red conversion path), a parse_green_eq_red_corpus
differential unit test (green-wired parse == red across the green path + every
fallback trigger), and the fuzz_green_eq_red fuzz target (registered in
fuzz.yml) generalizing the invariant to arbitrary input. The hybrid is verified
output-equivalent to pure red.
@robcohen
robcohen force-pushed the perf/green-convert-transactions branch from 1357954 to 1e92899 Compare June 25, 2026 15:14
@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 32.7ms ± 0.3ms 23.9 MB
beancount 913ms ± 11.8ms 50.5 MB
Comparison 27.9x faster 2.1x less

vs main branch (2026-06-25)

Metric main this PR Change
Time 37.4ms 32.7ms -12.6% 🟢
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

This PR introduces a high-performance “green tree” conversion path for parsing transactions in rustledger-parser, using direct traversal of Rowan’s immutable green tree to avoid red-node cursor allocations. It integrates the green conversion into the normal parse path with a red fallback to preserve byte-identical output, and adds differential tests/fuzzing to pin equivalence.

Changes:

  • Wire a green-tree transaction converter into parse_via_cst_opts, falling back to the existing red conversion when unsupported constructs are encountered.
  • Deduplicate shared token-parsing logic by moving string decoding and some token parsers into cst::convert for reuse by both red and green paths.
  • Add a differential fuzz target and CI workflow entry to continuously validate parse() (green-enabled) == parse_red_only() across arbitrary inputs.

Reviewed changes

Copilot reviewed 8 out of 9 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
crates/rustledger-parser/src/lib.rs Re-exports updated to include the new red-only parsing hook.
crates/rustledger-parser/src/cst/mod.rs Adds the new green module and re-exports parse_red_only.
crates/rustledger-parser/src/cst/green.rs Implements green-tree transaction/posting conversion plus differential unit tests.
crates/rustledger-parser/src/cst/convert.rs Adds parse_red_only() and integrates green conversion with red fallback; shares token parsers with green.
crates/rustledger-parser/src/cst/ast.rs Switches string decoding to the shared token decoder in convert.
crates/rustledger-parser/fuzz/fuzz_targets/fuzz_green_eq_red.rs New differential fuzz target asserting green-wired parse matches red-only parse.
crates/rustledger-parser/fuzz/Cargo.toml Registers the new fuzz target binary.
crates/rustledger-parser/fuzz/Cargo.lock Updates lockfile for new/updated fuzz dependencies.
.github/workflows/fuzz.yml Adds the new fuzz target to the CI matrix.

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

Comment thread crates/rustledger-parser/src/lib.rs Resolved
@codecov

codecov Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.31783% with 19 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/green.rs 96.59% 16 Missing ⚠️
crates/rustledger-parser/src/cst/convert.rs 93.33% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 792
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 3 commits June 25, 2026 11:25
- drop crate-root re-export of parse_red_only (stays at cst::parse_red_only,
  a doc-hidden test/fuzz hook) so it doesn't widen the crate public API
- replace module-level allow(dead_code) with a targeted one on the test-only
  top_level_node_spans helper, so real dead code elsewhere is still caught
- fix stale docs: convert_simple_posting now handles cost/price; convert_cost_spec
  tolerates an unparseable number (number: None, matching red)
fuzz_green_eq_red found a divergence: for input with an invalid first date
(e.g. `3333/33/3`, month 33) followed by a valid-looking later date token,
red drops the directive (InvalidDateValue on node.date()), but green's
`date.is_none()` guard kept scanning DATE tokens and latched a later valid one
— keeping a transaction red discards. Fix: latch on the first date token seen
(date_seen flag); if it fails to parse, date stays None and the directive bails
to red, matching node.date() semantics. Same latch fix applied to cost-spec
date/label. Regression cases added to parse_green_eq_red_corpus.

Also fixes the CI build/Clippy failure: 3 collapsible_if warnings in test
helpers (missed locally — needed clippy --all-targets, not bare -p).
@robcohen
robcohen merged commit c97f501 into main Jun 25, 2026
53 checks passed
@robcohen
robcohen deleted the perf/green-convert-transactions branch June 25, 2026 16:38
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.

2 participants