Repository navigation
perf(parser): compute the formatter alignment on demand, not on every parse - #2057
Conversation
… 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.
📊 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 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: PostingAlignmentwith a lazyOnceLockaccessed throughParseResult::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.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
✅ Compatibility Test Results
What's tested
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`.
7.6%–12.4% fewer instructions depending on workload, by not doing work most callers never read.
The waste
parse_via_cst_innercomputedcompute_alignmenteagerly intoParseResult.alignment. That walk goes through the red ast accessors (Posting::flag,Amount::is_arithmetic, …), and rowan allocates aBox<NodeData>per red node with no recycling. Everyrledger check, every LSP diagnostic pass and everyloadpaid for a full formatter pass whether or not it ever formatted anything.dhat on
simpleshows the scale:Box<NodeData>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, plusdoctor roundtrip. The field becomes aOnceLockbehindParseResult::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 freshcompute_alignment— whichparse_result_alignment_cache::*pins.OnceLock, notOnceCell:ParseResultis shared asArc<ParseResult>across the LSP's threads, and a compile-time assertion in that file requiresSend + Sync.Measured — 2000 transactions per shape
Wall clock,
rledger check --no-cache, 10k transactions, hyperfine 12 runs: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:
extract_*passes —simpletriggers none of them and still allocates 50k red nodes;fixup_directive_spans— itsfindshort-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