Skip to content

fix(parser): model bison's error recovery on beancount's tokens, so rledger is as quiet as beancount after every failed line - #3035

Merged
robcohen merged 1 commit into
mainfrom
fix/recovery-window-general
Nov 26, 2026
Merged

robcohen merged 1 commit into
mainfrom
fix/recovery-window-general

Conversation

@robcohen

@robcohen robcohen commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

What

After a line beancount cannot read, rledger now reports what bean-check 3.2.3 reports until beancount's grammar has read three tokens again. This now holds after every kind of failed line, where the earlier windows covered a few kinds. The changes, by issue:

Model

beancount's grammar has one error rule, declarations: declarations error. After a failure, bison:

  • discards every token a declarations cannot start with, so an indented line goes to its end;
  • shifts an end of line, a date or an undated keyword;
  • reports no syntax error until three tokens have been shifted.

During that window its lexer still reports invalid tokens, invalid dates and malformed numbers. A lexer error is YYerror, which puts bison straight into recovery.

crates/rustledger-parser/src/cst/recovery.rs (quiet_bison_recovery) implements this in four parts.

BcLexer is a port of lexer.l:

  • the same rules in the same order, with flex's longest match;
  • trailing context counted in a match's length;
  • INDENT, and the IGNORE rules for lines it skips;
  • YYerror for invalid runs, invalid dates and malformed numbers.

accepts encodes the first three tokens of every statement, taken from grammar.y.

The driver starts at each error rledger reports while bison is not recovering. It finds the token bison fails at, which is an indent for an orphan indented line, and steps the error status. Then, on each physical line inside the window, it keeps as many of rledger's errors as beancount's lexer finds there. It keeps the error that failed the line first, then rledger's invalid-token errors.

  • When reporting resumes at a statement that starts a line, that statement keeps rledger's own errors.
  • compat(parser): a dated line that opens no directive reports each indented line under it, unlike beancount #2979, what to model: bison sometimes shifts the start of a dated entry mid-line or on an indented line. beancount then builds that entry, and the indented lines under it are its body.
    • The entry's text is parsed on its own, and its errors replace rledger's on those lines.
    • The entry is not emitted. I chose to model only the error lines it causes, not the entry. Building an entry from a malformed line is a recovery artifact (the issue says "need not be copied"), so the AGENTS.md Python compatibility policy applies. This is documented in the module docs.
    • Parsed directives are unchanged, and a test pins that.
  • A push/pop that bison builds mid-line changes state, and that is not modeled, so that line keeps its errors.

Linear time:

  • The input is lexed forward once, plus at most one re-read of a line.
  • An entry built mid-line is parsed once, never nested.
  • The bytes it lexes are added to RECOVERY_SHIFT_SCANNED_BYTES. A new unit test requires at most 8× the input over seven shapes.

Not replaced: quiet_after_failed_line_starts still runs ahead of the new pass. I tested removing each part of it:

  • its unreadable-line windows: 133 parity regressions;
  • its dated-line windows: 26 in G1 and 11 in G3.

It still wins on its calibrated shapes (BOM-started lines, an invalid second date), so I kept it and documented the division between the two.

Deliberate differences (documented, not copied)

  • End-of-line placement. beancount reports a syntax error at an end of line on the next line, because bison's location is the lexer's line after it has read \n. rledger keeps it on the line whose statement fails, where the mistake is.
    • The parity harness now moves beancount's syntax error, unexpected EOL back one line (docstring and self-test updated).
    • Applied to main alone, that change turns 446 pinned mismatches into matches and breaks none (92,739 → 93,185).
    • This also covers the lone posting flag !, whose error beancount puts on the next line.
  • Builder errors. beancount drops an entry whose next column-0 line starts with an invalid token: bison pops the entry unreduced on YYerror. That also drops the entry's builder errors (too many strings, booking method): * "a" "b" "c" / foo gives bean-check {3}, rledger {2, 3}. Losing a valid entry is a beancount bug, so rledger keeps the entry and its error. A test pins this.

Leftovers, each

Shape bean-check main branch
AB-C / key:2024/01/03 P | 1 1 2x2 1 2 1 2x2
$ 2024-01-02 * "y" + posting 1 1 2 1
$ / Assets:A 1 USD 2024-01-02 1 1 2 1
$ / 2024-01-02 123 / posting 1 1 2 1
P T h1 Z\r\n (also at EOF) 3x2 3 3x2
option "a" (EOL on next line) 3 → normalized 2 2 2 (deliberate)
* "a" "b" "c" / foo 3 2 3 2 3 (deliberate)
P T ! / posting 4 → normalized 3 3 3

Also fixed (found by the timing runs)

Three lookups were quadratic in a file with many parse errors. All three were present on main:

Each is now a binary search over one sorted list. Effect: 160k pushmeta k: "v" lines took 205 s and now take 0.27 s; 40k bad postings took 11.6 s and now take 0.29 s.

Results

Parse-error parity (pinned fuzz 9bc79f4f, matrix, tracked, compat; beancount 3.2.3 from nixpkgs):

  • Matches: 93,185 (main, with the EOL normalization) → 106,447, with 0 regressions against main's manifest.
  • The manifest is rewritten with --update; 13,999 pins were stale.

BOM combination matrix: 11,179 → 11,893 rows match. Regenerated with BOM_MATRIX_UPDATE=1 BOM_MATRIX_RELABEL=1:

  • 6 stale exceptions removed;
  • 159 accepted worse-than-main rows that are no longer worse removed.

Generated differentials against main (8e6feae). Three generator designs, six seeds each, 870,000 inputs:

Generator Inputs Gained Closer Regressed Further Sideways
G1: line-type sequences (failed headers, unreadable lines, second-date lines, indented lines, blank/comment lines; CRLF, no final newline) 300,000 121,411 8,952 0 0 1
G2: random lines of beancount lexer tokens (BOM, \x11, \r, glued) 300,000 174,533 22,421 0 2 5
G3: mutated real ledgers (compat corpus, examples/, parser test data) 240,000 81,783 7,595 1 0 0

Timing: linear. Seconds at 20k / 40k / 80k / 160k repetitions, branch:

Shape Seconds
$ lines 0.03 / 0.05 / 0.12 / 0.23
$ + posting 0.05 / 0.11 / 0.25 / 0.52
pushmeta k: "v" lines 0.03 / 0.06 / 0.13 / 0.26 (main 2.44 / 9.79 / 41.6 / 205)
second-date entries + posting 0.11 / 0.21 / 0.44 / 0.88
pushtag #a $ / blank / 2024-02-30 5 0.07 / 0.14 / 0.28 / 0.59
$ 2024-01-02 * "y" × N on one line 0.01 / 0.01 / 0.03 / 0.06
bad postings in one transaction 0.03 / 0.08 / 0.14 / 0.29 (main 0.76 s at 10k, 11.6 s at 40k)

A further sweep of 17 shapes at 20k vs 80k gave ratios between 3.1 and 4.6.

Caches:

Tests

  • New: crates/rustledger-parser/tests/bison_recovery_model.rs. It pins:

    Every count was checked against bean-check 3.2.3, and green and red agree on each.

  • Unit tests in recovery.rs cover the lexer port, accepts, and the linear byte bound.

  • Updated, all toward bean-check 3.2.3 (re-measured): unreadable_line_recovery.rs (its "not modeled" rows now match), dated_line_no_directive.rs (EOL placement), bom_account_and_tag_recovery.rs, bom_mid_line_run.rs, line_start_bom_recovery.rs, green_red_properties.rs and bom_combination_matrix.rs.

    • In green_red_properties.rs, the unclosed-cost fixture moved after a blank line, because a posting right after the failed metadata line is now quiet, as in beancount.
  • Corpus manifest: tests/baselines/parser-corpus.manifest takes the new output hashes of the three compat files whose parse errors move (double-entry-generator/example_oklink, parser-lima/examples_data_custom, examples_data_full), sources unchanged.

  • Checks: cargo test -p rustledger-parser -p rustledger-lsp -p rustledger-wasm -p rustledger-loader -p rustledger passes, as do clippy with -D warnings --all-targets --all-features, cargo doc -Dwarnings for the parser, cargo fmt --check, and the harness --self-test.

How to test

cargo test -p rustledger-parser --test bison_recovery_model
cargo test -p rustledger-parser --lib recovery
cargo build --release -p rustledger-loader --no-default-features --example parse_error_lines
python -I scripts/compat-parse-error-parity.py --rledger target/release/examples/parse_error_lines \
  --fuzz-dir <fuzz_parse + fuzz_green_eq_red at 9bc79f4f> --fuzz-commit 9bc79f4f35f52c50813164f43307e7d151d70d8c \
  --compat-dir tests/compatibility/files --check
printf '2024-01-01 open Assets:A\npushtag #a $\n\n  2024-02-30 5\n' > x.beancount && rledger check x.beancount

Closes #2993
Closes #2979

🤖 Generated with Claude Code

@robcohen
robcohen requested a review from a team as a code owner November 26, 2026 02:17
…ledger is as quiet as beancount after every failed line

beancount's one error rule is `declarations: declarations error`: after a
failed statement bison discards what a `declarations` cannot start with,
shifts only an end of line, a date or an undated keyword, and reports no
syntax error until it has shifted three tokens; only its lexer's errors are
reported meanwhile. The earlier windows modeled this for a few line kinds.

A new pass, `cst/recovery.rs`, ports beancount's lexer (`lexer.l`) and runs
bison's recovery over its tokens from each error rledger reports while bison
is not recovering. On every line inside the window it keeps as many of
rledger's errors as beancount's lexer finds there. An entry bison builds at a
date it shifts mid-line (#2979) is parsed on its own for its body's errors
and not emitted, a recovery artifact not copied. A lone capital glued to a
`\r` or the end of the input is the invalid token it is to beancount (#3028's
leftover).

The parity harness moves beancount's `unexpected EOL` errors back one line:
rledger reports an end-of-line error on the line it ends, on purpose.

Also makes three error lookups linear (multi-line string placement, the
posting and metadata line checks), which were quadratic in a file with many
parse errors.

Parity corpus: 93,185 -> 106,447 matching, 0 regressions. WASM cache 132.

Closes #2993
Closes #2979

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@codecov

codecov Bot commented Nov 26, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.29242% with 16 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/recovery.rs 98.19% 16 Missing ⚠️

📢 Thoughts on this report? Let us know!

@robcohen
robcohen force-pushed the fix/recovery-window-general branch from b63e244 to da10f0e Compare November 26, 2026 02:25
@github-actions

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 53.0ms ± 0.9ms 789.5ms ± 2.2ms 14.9x 43.2 MB / 51.0 MB
investment 79.0ms ± 1.7ms 2928.5ms ± 51.8ms 37.1x 47.3 MB / 59.1 MB
fifo 75.2ms ± 0.6ms 14846.4ms ± 61.6ms 197.3x 49.1 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 53.7ms ± 0.7ms 53.0ms ± 0.9ms -1.3% ✅ within noise 43.1 MB → 43.2 MB (+0.3%)
investment 77.7ms ± 1.4ms 79.0ms ± 1.7ms +1.6% ✅ within noise 47.0 MB → 47.3 MB (+0.8%)
fifo 79.5ms ± 1.5ms 75.2ms ± 0.6ms -5.4% 🟢 faster 49.1 MB → 49.1 MB (+0.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.5ms, investment 1.0ms, fifo 0.7ms), 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
robcohen merged commit e604613 into main Nov 26, 2026
63 of 64 checks passed
@robcohen
robcohen deleted the fix/recovery-window-general branch November 26, 2026 02:42
robcohen added a commit that referenced this pull request Nov 26, 2026
…valid token, and model four more recovery shapes (#3036)

#3035's differential left eight inputs that moved away from bean-check
3.2.3, each holding a BOM or a `\r`. The port of beancount's lexer in
`cst/recovery.rs` was not the cause: it agrees with `lexer.l` token for
token on about 190,000 BOM- and `\r`-heavy inputs. The causes, and what
fixing them led to:

- A mid-file BOM's diagnostic never started bison's recovery. It now does
  where beancount's lexer reads that BOM into an invalid token (not an
  account, a string or a comment, nor on a stray-`\r` line), checked with a
  forward-only probe lexer.
- An entry bison builds mid-line whose own line holds an invalid token is
  dropped at that token's YYerror: its line counts as that line parsed on
  its own, and the window goes on from the line's end, so its indented lines
  are quiet. A BOM inside such an entry no longer leaves it unmodeled.
- A misgrouped number (`1,50`) inside the window is reported as
  `InvalidNumber`, as beancount's lexer reports it, where rledger had no
  error of its own; a lone BOM token no longer blocks that addition.
- A header failing at a token after a multi-line string is reported on that
  token's line (`report_at_multi_line_string_ends`).

Also documents and pins rledger's deliberate acceptance of an indented
comment after a column-0 comment, a blank line or the top of the file, and
the parse-error parity harness drops beancount's `unexpected INDENT` there.

Parity corpus: 106,447 -> 107,279 matching, 0 regressions. BOM matrix:
11,854 -> 12,762. WASM cache 133.

Co-authored-by: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 27, 2026
… four more BOM and pipe line shapes (#3052)

A stray `\r` is a blank to beancount's lexer; rledger reports one before a
token that lexes as an error of its own (deliberate, #2980) and started no
model of bison's recovery from such a line, so the lines bison keeps quiet
after a statement failing there kept their errors. The input is now parsed
once more as beancount reads it (`recovery::stray_cr_analog`), and from the
first line holding a stray `\r` on, each line takes that parse's errors,
except a line where rledger reports the `\r` itself, which keeps its own.

Also: a line's BOM diagnostic stands for a first invalid token with no BOM;
a misgrouped number beside a BOM-led token or a BOM inside an account is
reported in the recovery; a pipe after a header failure gives no warning;
an invalid booking method is reported on its `open`'s line.

Generated differential (1.26M inputs, #3035/#3036 generators): 24,188 gained,
25,725 closer, 237 moved away (168 reproduce on the \r-free analog, 66 are the
booking line where beancount drops the open). Parity corpus 107,647 ->
108,454, no regressions; BOM matrix 12,853 -> 12,917. WASM cache 142.

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

1 participant