Skip to content

perf(parser): parse a file of 1 MiB or more on up to 4 threads - #3191

Merged
robcohen merged 2 commits into
mainfrom
perf/parallel-chunk-parse
Dec 1, 2026
Merged

robcohen merged 2 commits into
mainfrom
perf/parallel-chunk-parse

Conversation

@robcohen

@robcohen robcohen commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

What

The loader now parses a single large file on up to 4 threads, by default, for files of 1 MiB or more. The output is byte-identical to the sequential parse.

parse_streamed_parallel (in crates/rustledger-parser/src/cst/convert/parallel.rs) works in three steps:

  1. Cut. A byte scan cuts the file into regions of about 512 KiB. Each cut falls at a likely item boundary: after a transaction's last indented line, with only blank or comment lines before the next dated line.
  2. Parse. Each region runs on the rayon pool through the same builder, recorder and Conversion::chunk as today. A region starts at its own boundary and stops at the first item boundary at or past the next region's start. No converter is duplicated.
  3. Merge. Results are appended in order, and Conversion::finish runs once, exactly as for one region.

Each region's parse is speculative. The merge checks two things for every region:

  • it starts where the previous region actually stopped;
  • nothing is carried into it (dates_carry, no_meta_carried).

If either check fails, the region is re-parsed from the real boundary with the real carried state. The scan therefore only decides how much runs in parallel, never the result.

Cross-item rule (ADR-0011) How it crosses a region boundary
open_body_holds_a_failed_line A region never stops right after an open
report_no_metadata_continuations no_meta_carried must be empty, otherwise the next region is re-parsed with it
report_invalid_dates Same, for dates_carry
Recorder lookahead Dropped with the region; the next region records it again
Lexer line-at-a-time spans A region stops only where none crosses (KindTokenIter::restartable_at)
push/pop, error order, reconciliation, span fixup Run in finish, once

Cap and controls

  • At most 4 regions per file in flight. The cap is PARALLEL_PARSE_THREADS = 4, and never more than the rayon pool has. That many pool tasks take region indices from a shared counter, in waves of two regions per thread.
  • No oversubscription. Inside the loader's parallel include parse, the tasks share the pool's threads and add none.
  • Why 4. On the hledger 1M journal, earlier sweeps measured check at 3.53 s sequential, 2.45 s on 4 threads and 2.16 s on 16. CPU cost was +17% on 4 threads and +80% on 16. Past 4 threads, the remaining wall time is the sequential rest of the load.
  • Environment variables. RLEDGER_PARALLEL_PARSE=0 turns the feature off. RLEDGER_PARSE_THREADS=N changes the cap.
  • No CLI flag. check has no --jobs-style option to hang one on, so the controls are env-only. They are documented in docs/commands/check.md.
  • Spike leftovers removed. The tuning knobs (region size and wave env vars) are gone.
  • Sequential path kept for files under 1 MiB, a one-thread pool or RLEDGER_PARSE_THREADS=1, a parser built without the parallel feature, and wasm targets (not(target_family = "wasm")). A small file never even starts the rayon pool.
  • Feature wiring. The loader turns on the parser's parallel feature, so the CLI and LSP get it.
  • Wasm still builds. rustledger-wasm (wasm32-unknown-unknown) and rustledger-ffi-component (wasm32-wasip2) both build and use the sequential path.

Bug found and fixed

The oracle's thread-local NestingGuard conflicted with rayon work-stealing. A thread waiting on regions can steal another file's whole parse. That parse then saw the wrong nesting depth and skipped its error reconciliation. The guard is now released while regions run, and entered again only around finish.

Equivalence

Check Result
streamed_parse_parity against the whole-tree parse: pools of 1/2/4/16 threads, region sizes from 1 byte to 4 KiB, cap 4 and uncapped Pinned fuzz corpus + compat corpus (1,458 files): 46,049 files, 0 differences. 216k regions, 14.2k speculative re-parses exercised.
The same, release build Proptest 20,000 cases, debug build (recorder replay asserts), and repository ledgers all pass
rledger check --format json and exit code (earlier rounds) Byte-identical on the hledger, simple, metadata, errors, junkline, tagged, investment and native shapes, 100k–1M, and an include set
BQL journal output (earlier rounds) Same sha256 at 1M
Clean profile workloads 0 re-parses

CI guards:

  • The compat.yml parse-error-parity job runs the parity test with --features parallel. It now also asserts that regions actually ran.
  • fuzz_streamed_eq_whole compares the parallel parse (1-byte and 48-byte regions, cap 4 and uncapped) alongside the streamed parse.

What users get by default

rledger check --no-cache, first run, comparing the default (cap 4, 16-core pool) against RLEDGER_PARALLEL_PARSE=0. Timing was gated on 1-minute load < 4. The 1-minute load was about 3.1–3.6, but the machine was shared (5- and 15-minute loads of 6–8 from other jobs), so absolute times are about 25% slower than in the earlier quiet runs. The relative numbers match the earlier noisier repeat.

Workload Wall: sequential Wall: default CPU (user+sys) Peak RSS
hledger 100k (14 MB) 458 ± 10 ms 286 ± 6 ms (−38%) 459 → 493 ms (+7%) 94.5 → 110.6 MB (+17%)
simple 100k (10 MB) 338 ± 6 ms 239 ± 12 ms (−29%) 340 → 429 ms (+26%) 77.4 → 93.8 MB (+21%)
metadata 100k (33 MB) 891 ± 44 ms 569 ± 35 ms (−36%) 891 → 1,091 ms (+22%) 191 → 203 MB (+6%)
hledger 1M (143 MB) 4.58 s 3.09 s (−33%) 4.55 → 5.35 s (+18%) 835 → 880 MB (+5%)
simple 1M (106 MB) 3.52 s 2.50 s (−29%) 3.50 → 4.30 s (+23%) 714 → 754 MB (+6%)
metadata 1M (330 MB) 8.94 s 5.43 s (−39%) 8.83 → 10.15 s (+15%) 1,859 → 1,890 MB (+2%)

Other effects:

  • Files under 1 MiB: unchanged; they take the sequential path.
  • Instructions on the sequential path (instr-bench check/*, measured on the same algorithm before the cap): −0.01% to +0.05% on clean workloads, and +0.12% / +0.19% on junkline / errors.

Docs

  • ADR-0011 gets a "Parallel regions" section covering: speculation and how the merge validates it, the 4-thread cap and why, the nesting-guard bug, and the extended rule that cross-item passes must be checked against region boundaries as well as chunk boundaries.
  • CHANGELOG has a Performance entry.
  • docs/commands/check.md has a "Parallel Parsing" section.
  • docs/reference/performance.md no longer says rustledger is single-threaded.

How to test

cargo test --release -p rustledger-parser --features parallel --test streamed_parse_parity
STREAMED_PARITY_DIRS=<fuzz>:<compat> cargo test --release -p rustledger-parser --features parallel \
  --test streamed_parse_parity test_streamed_parse_equals_whole_on_files -- --nocapture
rledger check --no-cache big.beancount                            # parallel by default
RLEDGER_PARALLEL_PARSE=0 rledger check --no-cache big.beancount   # sequential

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Dec 1, 2026 •

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 Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.62637% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/parser.rs 85.71% 3 Missing ⚠️
...ates/rustledger-parser/src/cst/convert/parallel.rs 99.14% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Instruction counts and wasm fuel vs base (deterministic)

Workload base this PR Change vs v0.24.0
check/simple 285.4M 285.5M +0.06% ✅ -18.3%
check/investment 440.7M 440.9M +0.04% ✅ -14.6%
check/tagged 420.8M 420.9M +0.02% ✅ -18.4%
check/multicurrency 398.7M 398.8M +0.02% ✅ -31.8%
check/fifo 432.1M 432.6M +0.12% ✅ -18.1%
check/metadata 622.4M 622.7M +0.05% ✅ -22.0%
check/hledger 3.71G 3.71G +0.05% ✅ —
check-warm/simple 121.5M 121.5M -0.03% ✅ -22.9%
format/simple 626.3M 626.3M +0.00% ✅ +16.2%
format/metadata 1.55G 1.55G +0.03% ✅ +30.7%
format/errors 92.1M 92.1M -0.01% ✅ +103.3%
check/errors 265.2M 265.2M -0.03% ✅ —
check-json/errors 145.2M 145.1M -0.04% ✅ —
check/junkline 30.9M 30.9M -0.02% ✅ +305.2%
check-json/junkline 44.3M 44.2M -0.20% ✅ +620.3%
query/journal/simple 435.7M 435.9M +0.05% ✅ -30.0%
query/groupby/simple 338.0M 338.2M +0.05% ✅ -26.5%
query/groupby/investment 552.0M 551.6M -0.07% ✅ -26.0%
lsp/open-diagnostics/simple 328.7M 328.8M +0.04% ✅ —
lsp/open-diagnostics/metadata 906.1M 906.5M +0.04% ✅ —
lsp/format/simple 1.01G 1.01G +0.06% ✅ —
lsp/format/metadata 2.54G 2.54G +0.03% ✅ —
lsp/edit/simple 656.6M 656.5M -0.01% ✅ —
Workload (wasmtime fuel) base this PR Change vs v0.24.0
wasm/validate/simple 1.13G 1.13G +0.01% ✅ —
wasm/validate/metadata 2.85G 2.85G +0.01% ✅ —
wasm/format/simple 1.42G 1.42G +0.00% ✅ —
wasm/format/metadata 3.63G 3.63G +0.00% ✅ —
wasm/query/simple 1.27G 1.27G +0.01% ✅ —
ffi/load/simple 1.73G 1.73G +0.01% ✅ —
ffi/load/metadata 4.09G 4.09G +0.03% ✅ —
ffi/query/simple 1.36G 1.36G +0.02% ✅ —
ffi/validate/simple 1.20G 1.20G +0.01% ✅ —
ffi/format/simple 1.48G 1.48G +0.00% ✅ —

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 wasm/ and ffi/ rows are wasmtime fuel (WebAssembly operators the guest executed), which is exact: the same .wasm on the same input gives the same fuel on any machine. Static data moves the component's heap, so a change to embedded strings alone can move ffi/ by a few hundredths of a percent. 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 29.3ms ± 0.8ms 565.8ms ± 7.2ms 19.3x 38.9 MB / 51.2 MB
investment 39.5ms ± 1.6ms 2128.2ms ± 22.2ms 53.9x 83.0 MB / 59.1 MB
fifo 39.7ms ± 2.2ms 11654.9ms ± 62.7ms 293.5x 58.9 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 29.5ms ± 1.3ms 29.3ms ± 0.8ms -0.7% ✅ within noise 38.9 MB → 38.9 MB (-0.2%)
investment 47.5ms ± 0.5ms 39.5ms ± 1.6ms -16.8% 🟢 faster 43.1 MB → 83.0 MB (+92.5%)
fifo 47.4ms ± 0.5ms 39.7ms ± 2.2ms -16.3% 🟢 faster 53.2 MB → 58.9 MB (+10.7%)

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

`parse_streamed_parallel` runs the loader's streamed parse (ADR-0011) of a
large file in regions of 512 KiB on the rayon pool, at most 4 at a time
(`PARALLEL_PARSE_THREADS`, and never more than the pool has). Each region is
the same builder, recorder and `Conversion::chunk`, started at a likely item
boundary found by a byte scan and stopped at the first boundary past the
next region's start; the results are appended in order and `finish` runs
once. A region's parse is speculative: the merge checks that it starts
where the region before ended and that nothing is carried into it
(`dates_carry`, `no_meta_carried`), and re-parses it from the real boundary
otherwise, so the scan never decides the result. Regions run in waves of
two per thread so peak memory does not hold every region's directives.

The loader uses it by default. `RLEDGER_PARALLEL_PARSE=0` turns it off and
`RLEDGER_PARSE_THREADS=N` changes the cap. Files under two regions, a
one-thread pool, the parser without its `parallel` feature, and wasm
targets keep the sequential streamed parse, whose instruction count is
unchanged: the region stop test is a const generic compiled out of it.

`rledger check`, first run, 16 cores, against `RLEDGER_PARALLEL_PARSE=0`:
29-39% less wall time, 7-26% more CPU time, 2-21% more peak RSS.

The oracle's nesting guard is released while the regions run: a rayon
thread waiting for them can take up another file's whole parse, which
would otherwise see this parse's depth and skip its reconciliation.

`streamed_parse_parity` compares the parallel parse with the whole-tree
parse on pools of 1, 2, 4 and 16 threads; the `compat.yml` job runs it with
`--features parallel` and asserts that regions ran, and
`fuzz_streamed_eq_whole` fuzzes it. ADR-0011 gains a "Parallel regions"
section.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen force-pushed the perf/parallel-chunk-parse branch from 873c94e to ea6e2d4 Compare December 1, 2026 22:18
@robcohen robcohen changed the title perf(parser): parse a large file's regions in parallel, opt-in (spike) perf(parser): parse a file of 1 MiB or more on up to 4 threads Dec 1, 2026
@robcohen
robcohen marked this pull request as ready for review December 1, 2026 22:19
@robcohen
robcohen requested a review from a team as a code owner December 1, 2026 22:19
…lots

check-sync-primitives.sh forbids std::sync locks in library code (#1076).

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