Skip to content

perf(parser): compute the formatter alignment on demand, not on every parse - #2057

Merged
robcohen merged 3 commits into
mainfrom
perf/lazy-alignment
Aug 15, 2026
Merged

robcohen merged 3 commits into
mainfrom
perf/lazy-alignment

Conversation

@robcohen

Copy link
Copy Markdown
Member

7.6%–12.4% fewer instructions depending on workload, by not doing work most callers never read.

The waste

parse_via_cst_inner computed compute_alignment eagerly into ParseResult.alignment. That walk goes through the red ast accessors (Posting::flag, Amount::is_arithmetic, …), and rowan allocates a Box<NodeData> per red node with no recycling. Every rledger check, every LSP diagnostic pass and every load paid for a full formatter pass whether or not it ever formatted anything.

dhat on simple shows the scale:

blocks share
RED Box<NodeData> 50,325 34.2% of all allocations
GREEN node 40,053

The derived view cost more allocations than the green tree it derives from.

The change

Only the formatter reads it — format_source_with_parsed, and through it LSP formatting, range-formatting and inlay hints, plus doctor roundtrip. The field becomes a OnceLock behind ParseResult::alignment(), so those callers pay and nobody else does. Their caching contract is unchanged: first call computes, later calls are free, and the value still equals a fresh compute_alignment — which parse_result_alignment_cache::* pins.

OnceLock, not OnceCell: ParseResult is shared as Arc<ParseResult> across the LSP's threads, and a compile-time assertion in that file requires Send + Sync.

Measured — 2000 transactions per shape

workload main lazy
simple 118,186,605 103,592,947 −12.35%
multicurrency 173,907,155 158,761,387 −8.71%
tagged 184,579,083 169,001,365 −8.44%
investment 207,113,683 191,351,889 −7.61%

Wall clock, rledger check --no-cache, 10k transactions, hyperfine 12 runs:

main lazy
simple 132.5 ms 121.2 ms 1.09×
investment 414.7 ms 395.4 ms 1.05×

Both binaries rebuilt from their current HEADs. Worth stating: the first run of that comparison reported 1.23× against a main binary that predated #2056 by forty minutes — the win looked twice as large as it is.

The test that matters

A new test pins the laziness itself. Nothing else can: the value is identical either way, so a reintroduced eager computation would be invisible to every other test while costing 7.6–12.4% of the program. Mutation-checked by restoring the eager call.

How it was found

Three plausible explanations came first and all were wrong:

  • the guarded extract_* passes — simple triggers none of them and still allocates 50k red nodes;
  • top-level red iteration — the green fast path succeeds 1999/2000;
  • fixup_directive_spans — its find short-circuits at the first non-trivia token.

Only the dhat stacks named the real caller, and an ablation confirmed the size before any code was written. This is the first change in the series that #2055's workloads did not need to reveal — but they did size it correctly across shapes.

🤖 Generated with Claude Code

https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG

… parse

7.6%-12.4% fewer instructions depending on workload, by not doing work most
callers never read.

`parse_via_cst_inner` computed `compute_alignment` eagerly and stored it in
`ParseResult.alignment`. That walk goes through the RED ast accessors
(`Posting::flag`, `Amount::is_arithmetic`, ...), and rowan allocates a
`Box<NodeData>` per red node with no recycling. So every `rledger check`,
every LSP diagnostic pass and every `load` paid for a full formatter pass
whether or not it ever formatted anything.

It is not a small tax. dhat on the `simple` workload:

    50,325 blocks  RED Box<NodeData>    34.2% of all allocations
    40,053 blocks  GREEN node

The derived view cost more allocations than the green tree it derives from.

Only the formatter reads the value — `format_source_with_parsed`, and
through it the LSP's formatting, range-formatting and inlay hints, plus
`doctor roundtrip`. The field is now a `OnceLock` behind
`ParseResult::alignment()`, so those callers pay for it and nobody else
does. Their caching contract is unchanged: first call computes, later calls
are free, and the value still equals a fresh `compute_alignment` on the same
tree, which is what `parse_result_alignment_cache::*` pins.

`OnceLock`, not `OnceCell`: `ParseResult` is shared as `Arc<ParseResult>`
across the LSP's threads, and there is a compile-time assertion in this file
that it stays `Send + Sync`.

Measured, 2000 transactions per shape:

    simple         118,186,605 -> 103,592,947   -12.35%
    multicurrency  173,907,155 -> 158,761,387    -8.71%
    tagged         184,579,083 -> 169,001,365    -8.44%
    investment     207,113,683 -> 191,351,889    -7.61%

Wall clock, `rledger check --no-cache`, 10k transactions, hyperfine 12 runs:

    simple      132.5 ms -> 121.2 ms   1.09x
    investment  414.7 ms -> 395.4 ms   1.05x

Both binaries rebuilt from their current HEADs for that comparison. Worth
saying because the first run of it reported 1.23x against a main binary that
predated #2056 by forty minutes — the win looked twice as large as it is.

New test pins the laziness itself. Nothing else can: the value is identical
either way, so a reintroduced eager computation would be invisible to every
other test while costing 7.6%-12.4% of the program. Mutation-checked by
restoring the eager call.

How this was found is worth recording, because three plausible explanations
came first and all were wrong. The guarded `extract_*` passes were not it —
`simple` triggers none of them and still allocates 50k red nodes. Top-level
red iteration was not it — the green fast path succeeds 1999/2000.
`fixup_directive_spans` was not it — its `find` short-circuits at the first
non-trivia token. Only the dhat stacks named the real caller, and an
ablation confirmed the size before any code was written.
@robcohen
robcohen requested a review from a team as a code owner August 15, 2026 03:43
Copilot AI lite review requested due to automatic review settings August 15, 2026 03:43
@github-actions

github-actions Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 27ms ± 0.6ms 24.2 MB
beancount 512.5ms ± 5.8ms 50.7 MB
Comparison 19x faster 2.1x less

vs main branch (2026-08-15)

Metric main this PR Change
Time 38.3ms 27ms -29.5% 🟢
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 removes an eager, formatter-only CST walk from the parser hot path by making ParseResult’s posting alignment computation lazy and cached (via OnceLock), so parse() callers that never format don’t pay the red-tree allocation cost. This fits the performance workstream introduced in #2055 by reducing rowan RED-node allocation overhead during parsing and LSP diagnostics.

Changes:

  • Replaces ParseResult.alignment: PostingAlignment with a lazy OnceLock accessed through ParseResult::alignment().
  • Updates formatter + LSP callers to use alignment() so alignment is computed only when actually needed.
  • Adds/updates tests to pin the laziness property and preserve cache equivalence against compute_alignment.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
crates/rustledger-parser/src/lib.rs Makes alignment lazy (OnceLock) and adds ParseResult::alignment() + tests guarding laziness and cache equivalence.
crates/rustledger-parser/src/cst/convert.rs Stops eagerly computing alignment during CST conversion; initializes an empty OnceLock.
crates/rustledger-parser/src/cst/format.rs Switches cached-format path to call parse_result.alignment() on demand.
crates/rustledger-lsp/src/handlers/range_formatting.rs Uses alignment() for alignment-based range formatting fallback.
crates/rustledger-lsp/src/handlers/inlay_hints.rs Uses alignment() for formatter-aligned inlay hint column calculations.
crates/rustledger-parser/tests/green_red_properties.rs Updates observable snapshot to call alignment() instead of field access.
crates/rustledger-parser/src/cst/green.rs Updates green/red equivalence test harness to call alignment().

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

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

codecov Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.67442% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-parser/src/lib.rs 97.22% 1 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% (raw 93%, 169 masked)
Full AST Match 100%
Total Files 812
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

Three Copilot findings on #2057, all real:

1. The fuzz target still read `green.alignment` as a field, so
   `fuzz_green_eq_red` failed to compile. Fuzz targets live outside the
   workspace with their own manifest, so `cargo build --workspace
   --all-targets` never touched them — only the Fuzz CI job caught it.
   Now calls `alignment()`, which is what the target wants anyway: it
   must compare the VALUE both paths produce, so forcing it on both is
   the point.

2. `alignment()` fell back to `PostingAlignment::default()` when the
   root would not cast to `SourceFile`. That formats the whole file to
   the wrong columns while looking like it worked. Now `expect`s, as
   `format_node_grouped` already does on the same breach, with the
   matching `#[allow(clippy::expect_used)]` and a `# Panics` section.

3. The field's rustdoc still described the eager cache and a "refresh
   the cache" flow that lazy computation makes moot. Rewritten to the
   actual contract, plus the two stale `parse_result.alignment` prose
   references in cst/format.rs.

The fuzz lockfile also picks up rowan 0.16.1 -> 0.17.0; it had drifted
behind the workspace lock, which is already on 0.17.0.
Self-review of the lazy-alignment change. Three call sites pointed at a
"producer-only invariant" heading in the `ParseResult::alignment`
rustdoc that the lazy rewrite removed. What they actually describe is
`format_source_with_parsed`'s own pairing contract — the caller must
pass the `source` the `parse_result` came from — so it is now named
there instead of by dangling reference.

Also: the `parse_result_alignment_cache` failure message still blamed
"parse_via_cst forgot to call compute_alignment" and "refreshing the
cache in the converter", neither of which can happen now; it would have
sent the next reader to the wrong file. Retargeted at the two things
that CAN diverge: the accessor's `GroupingStyle` and compute_alignment
itself. Plus a missing blank doc line before `# Panics`.
@robcohen
robcohen merged commit 3e17b0c into main Aug 15, 2026
63 of 65 checks passed
@robcohen
robcohen deleted the perf/lazy-alignment branch August 15, 2026 12:30
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