Skip to content

feat(parser): a table-driven beancount error oracle, behind RLEDGER_ERROR_ORACLE - #3061

Merged
robcohen merged 2 commits into
mainfrom
feat/lalr-error-oracle
Nov 27, 2026
Merged

robcohen merged 2 commits into
mainfrom
feat/lalr-error-oracle

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

Phase 2, part 1 of replacing the hand-modeled bison recovery (cst/recovery.rs, the convert.rs quieting passes) with a table-driven error oracle. This PR adds the oracle and wires it into convert behind a switch, off by default (RLEDGER_ERROR_ORACLE=1). Nothing changes for users until a follow-up turns it on.

  • Tables — scripts/gen-beancount-lalr-tables.py runs the flake's bison 3.8.2 (it refuses any other version) on pta-standards' clean-room, MIT-licensed formats/beancount/v3/grammar/beancount.y. The grammar is vendored at rustledger/pta-standards@1463db773ac5 as crates/rustledger-parser/grammar/beancount.y, and the script checks its SHA-256. The output is the checked-in cst/oracle/beancount/tables.rs. A new CI job, Beancount LALR tables freshness, regenerates the tables and diffs them, and build requires it.

  • Driver — cst/oracle/beancount/lr.rs replays yacc.c exactly:

    • default reductions;
    • the error shift and yyerrstatus 3, with discard;
    • a lexer YYerror entering recovery with no report;
    • YYMAXDEPTH 10000 ("memory exhausted");
    • abort at EOF.

    It has no recursion and no panics (every table read goes through get), and runs in linear time. It emits slots plus a reduction trace (built and dropped statements).

  • Clean lexer — cst/oracle/beancount/lexer.rs is written from LEXICAL.md / harness/reflexer.py only. It does not touch BcLexer; deleting BcLexer is a later PR.

  • Reconciler + overlays

    • cst/oracle/mod.rs is format-neutral, with no beancount types. It holds ReferenceOracle, Slot/Reference, the DeviationOverlay trait, and reconcile. The trait's hooks are: an input/token rewrite before the reference lexes; a transform of the reference; and claims on rledger errors or lines as rledger's own.
    • reconcile works line by line:
      • a line with slots gets exactly that many errors: rledger's own diagnostic where one exists (kept for its message), a synthesized one where none does, and extras dropped;
      • a line the reference's recovery swallowed has rledger's syntax errors dropped;
      • elsewhere rledger's errors stand.
    • Builder-class errors (push/pop, booking, pipe, cost/price checks) stand and can take a slot's place. They are classified with convert's existing is_a_builder_* canonicals.
  • Deviations — ten named overlays in cst/oracle/beancount/overlays.rs, each citing a new "Parse-Error Differences" section of docs/reference/compatibility.md: byte-0 BOM, EOL error on the failing line (compat(parser): stay quiet after any line beancount cannot read, until its grammar has read three tokens #2993), stray \r (fix(parser): read a stray \r before an invalid token as a blank, as beancount does #2980), tags after first posting (A #tag after a transaction's first posting is kept by rledger, not by beancount #2575), indented comment after a gap, BOM orphan line, kept entries, {*} cost merge, divide-by-zero (a fixable beancount crash), and numbers beyond 28 digits. A test checks that every overlay's section exists. No deviation's behaviour changes: measured, see below.

  • Gate — the oracle runs only when rledger's own parse reports an error, so a clean ledger pays nothing. scripts/compat-beancount-oracle-drift.py checks the gate (below).

  • Lexer drift — cst::bc_lexer_drift (feat(parity): name parse-error mismatches by category key through ptadiff #3056) now checks the new lexer instead of BcLexer.

Measurements

The parity harness here is main's, after #3056: it uses ptadiff and includes its generator sample.

main this PR, switch off this PR, switch on
parse-error parity: matching inputs 119,048 / 123,304 119,048 (unchanged; the manifest is not re-pinned) 119,952
parity regressions (pinned match → mismatch) — 0 0
pinned mismatches that now match — — 1,103
category keys whose count moves — — 182: 170 shrink, 12 grow; 2,143 → 1,239 inputs across them
oracle vs beancount 3.2.3 (scripts/compat-beancount-oracle-drift.py) — 122,917 / 122,917 agree on tokens and syntax errors same
cst::bc_lexer_drift, now on the new lexer — 123,833 inputs agree same
clean 10.8 MB ledger, callgrind instructions 4,069,622,607 — 4,069,622,622 (+15)
same ledger plus one bad line 4,745,422,117 — 5,853,953,232 (+23%)
WASM (wasm-pack --target web --release) 6,058,283 B — 6,120,094 B (+61,811 B, +1.0%)
  • BOM matrix and STRICT_BASELINE — unchanged with the switch off, since the default path is untouched. With the switch on, 13 parser tests change, the BOM matrix among them. Those are re-pinned in the follow-up that turns the switch on.
  • Drift and the gate
    • The drift check runs in the parse-error parity job, where beancount 3.2.3 and ptadiff are installed, so it cannot skip.
    • It also holds the gate to beancount: on the 8,486 inputs rledger reports nothing on, the overlaid reference finds no syntax error.
    • On 20 of them it finds a lexer error (a lone capital beancount rejects, 2229-4/3G). Those stay as they are on main and are counted.
    • A first version also lexed every clean file to catch those 20. That cost +19% instructions on a clean 10.8 MB ledger, so I dropped it.
  • Cost on a file with errors — the +23% is the full lexer and LR pass plus reconciliation. Main's hand-modeled passes already add 17% there, and the follow-up deletions remove them.
  • What still differs with the switch on — of the 2,910 inputs that still differ, 2,611 hold a stray \r (the documented fix(parser): read a stray \r before an invalid token as a blank, as beancount does #2980 difference). The rest are mostly builder or state errors the token grammar doesn't model: push/pop built mid-line during recovery, repeated pipe warnings.

Follow-ups (separate PRs)

  1. Turn the switch on by default, re-pinning the parity manifest, the BOM matrix lists and the corpus baselines.
  2. Delete the hand-modeled code one piece per commit: quiet_bison_recovery and the phantom recursion, accepts(), model_stray_cr_lines / stray_cr_analog, the convert.rs quieting passes, BcLexer and the logos patches that depend on it. Each deletion is gated on parity --check, the BOM matrix, STRICT_BASELINE and the parser suite.
  3. Use the trace's "dropped statement" bit in validation (casc2–4 regression tests).

How to test

nix shell --inputs-from . nixpkgs#bison nixpkgs#python3 -c python3 scripts/gen-beancount-lalr-tables.py --check
cargo test -p rustledger-parser --lib oracle
cargo build --release -p rustledger-loader --no-default-features --example parse_error_lines --example beancount_reference
python3 -I scripts/compat-beancount-oracle-drift.py --reference target/release/examples/beancount_reference --fuzz-dir DIR --compat-dir tests/compatibility/files   # needs ptadiff, as the parity harness does
# parity with the switch on:
RLEDGER_ERROR_ORACLE=1 python3 -I scripts/compat-parse-error-parity.py --rledger target/release/examples/parse_error_lines --fuzz-dir DIR --fuzz-commit 9bc79f4f35f52c50813164f43307e7d151d70d8c --compat-dir tests/compatibility/files --check

Clean-room note: nothing here was derived from beancount's grammar.y / lexer.l / generated parser, or from BcLexer's rule logic. The provenance is recorded in each new module.

🤖 Generated with Claude Code

@robcohen
robcohen requested a review from a team as a code owner November 27, 2026 06:54
@robcohen
robcohen force-pushed the feat/lalr-error-oracle branch from 6d986aa to 3b97161 Compare November 27, 2026 07:00
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

🔴 Slower than base on: simple

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 55.1ms ± 6.3ms 812.6ms ± 11.5ms 14.7x 43.2 MB / 51.1 MB
investment 79.0ms ± 0.6ms 2974.0ms ± 19.2ms 37.6x 47.2 MB / 59.1 MB
fifo 76.4ms ± 0.7ms 14858.1ms ± 157.0ms 194.4x 49.3 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 51.6ms ± 0.4ms 55.1ms ± 6.3ms +6.8% 🟡 slower 43.2 MB → 43.2 MB (-0.0%)
investment 79.1ms ± 0.5ms 79.0ms ± 0.6ms -0.2% ✅ within noise 47.3 MB → 47.2 MB (-0.3%)
fifo 76.4ms ± 1.6ms 76.4ms ± 0.7ms +0.1% ✅ within noise 49.2 MB → 49.3 MB (+0.3%)

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

robcohen and others added 2 commits November 27, 2026 04:39
…RROR_ORACLE

Replace the hand-modeled bison recovery step by step with beancount's own
grammar. This adds the pieces, off by default:

- scripts/gen-beancount-lalr-tables.py compiles pta-standards' clean-room,
  MIT-licensed beancount.y (vendored at 1463db773ac5, hash-checked) with the
  flake's bison 3.8.2 into cst/oracle/beancount/tables.rs; a new CI job
  regenerates and diffs them.
- cst/oracle/beancount/lr.rs replays yacc.c's semantics over the tables:
  default reductions, error shift and yyerrstatus 3, discard, a lexer
  YYerror entering recovery without a report, YYMAXDEPTH 10000, EOF abort.
  No recursion, no panics, linear time; slots plus a reduction trace.
- cst/oracle/beancount/lexer.rs: beancount's tokenization written from
  LEXICAL.md only.
- cst/oracle/mod.rs: the format-neutral ReferenceOracle / reconcile /
  DeviationOverlay seam; ten named overlays for the documented deliberate
  differences, each citing a new compatibility.md section.
- scripts/compat-beancount-oracle-drift.py (in the parity job) holds the
  model to beancount itself: 122,917 of 122,917 inputs agree on tokens and
  syntax errors.

With RLEDGER_ERROR_ORACLE=1 the parity harness matches 119,952 of 123,304
inputs where main matches 119,048, with no regression. The oracle runs only
when rledger's own parse reports an error, so a clean ledger pays nothing.

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

The drift test from #3056 compared BcLexer, the recovery model's port of
beancount's lexer, with lex_iter_string. Point it at the oracle's reference
lexer, written from pta-standards' clean-room LEXICAL.md, which the
remaining recovery code is being replaced with: 123,833 pinned inputs agree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen force-pushed the feat/lalr-error-oracle branch from 3b97161 to cb67c38 Compare November 27, 2026 10:45
@robcohen
robcohen merged commit 72f0804 into main Nov 27, 2026
65 of 66 checks passed
@robcohen
robcohen deleted the feat/lalr-error-oracle branch November 27, 2026 11:17
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