Skip to content

fix(parser): treat a stray \r before a line ending as trivia, as beancount does - #2804

Merged
robcohen merged 3 commits into
mainfrom
fix/stray-cr-before-line-ending
Oct 29, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/stray-cr-before-line-ending

Conversation

@robcohen

Copy link
Copy Markdown
Member

What changed

  • Lexer (TokenIter::stray_cr_trivia_end, crates/rustledger-parser/src/logos_lexer.rs): when the lexer produces a Whitespace token or a lone-\r error, the whole [ \t\r] run starting there becomes one Whitespace token if it contains a \r and reaches the line ending or the end of the source. The scan stops before the \r of a \r\n, so that pair stays in the Newline as on every other CRLF line. The \r bytes stay in the token stream and the CST as trivia. An ordinary Whitespace token costs one byte comparison, and the scan only moves forward over bytes the run then consumes.
  • line_end_before_newline (column-0 # comments, * headings, the cut of an unterminated string) also ends before such a run. The stray bytes become the same Whitespace trivia instead of comment text, so # note\r\r\n is now Comment("# note"), Whitespace("\r"), Newline (it was Comment("# note\r")). The fix(parser): a column-0 # comment with CRLF line endings breaks the next directive #2769 lib test is updated to match.
  • Formatter (crlf_to_lf_outside_strings, crates/rustledger-parser/src/cst/format.rs): a stray run is dropped instead of having each \r turned into a \n. The old fold added a blank line, which ends a transaction, so format_source cut the postings off a transaction whose header ended in \r\r\n. try_format_source (what rledger format calls) formats the parsed tree and did not hit this, so the two entry points disagreed. stray_cr_run mirrors the lexer rule, and the two sites point at each other. Any other bare \r is still folded into a line break (classic-Mac files).
  • Drift guards: the new crlf_to_lf_keeps_the_lexer_line_structure test checks that each stray-\r source parses clean, still parses to the same directives after the fold, and gives the same output from try_format_source and format_source. There is a new IDEMPOTENCE_MATRIX fixture stray_cr_before_line_ending (*, #, #!, ; with a ", metadata, posting, trailing \r at EOF), so source_state_classification_agrees_with_lexer, the idempotence tests and the round-trip fidelity tests run on these shapes too. There is also a new parse_green_eq_red_corpus entry.
  • Loader CACHE_VERSION 48 -> 49, WASM 63 -> 64 (pin and fixture versions follow).
  • CHANGELOG ### Fixed entry.

Why: beancount's behaviour, measured

Beancount's lexer has [ \t\r]+ { } (whitespace) and \n as EOL, and its indent rule is ^[ \t]+/[^ \t\r\n]. I ran bean-check 3.2.3 in the compat container, and also called beancount.parser.parse_string to see the parse errors and entries. Files use CRLF unless noted.

Shape bean-check 3.2.3 rledger main this PR
\r\r\n on an open line ok 1 error ok
\r\r\n on a ; comment line ok 1 error ok
\r\r\n on a posting line ok 1 error ok
\r\r\n on a transaction header ok 2 errors ok
\r\r\n on a metadata line (key: "v") ok 1 error ok
control: " \r\n" ok ok ok
\r\r\r\n, " \r\r\n", "\r \r\n" ok errors ok
\r\r\n on posting metadata ok 1 error ok
\r\r\n in an otherwise-LF file ok 1 error ok
trailing \r at EOF (no \n), \r\r at EOF, a file that is just \r ok errors ok
\r\r\n after %, #!, #+ ok 1 error ok
\r\r\n after a column-0 # comment, an org * heading ok ok ok (stray bytes are now trivia, not comment text)
\r\r\n line of its own, \r\r\r\n\r\n at file start ok error ok
\r inside a string ("a\rb") ok, narration a\rb ok ok, unchanged
\r-only line endings (classic Mac) error (unexpected DATE) error error
\r\r\n (blank line) inside a transaction error (unexpected INDENT, same as \r\n) error error (same as \r\n)
\r inside a posting's indentation ( \rAssets..., \r Assets...) error (unexpected ACCOUNT) error error
mid-line \r (open\rAssets:Cash, Assets:Cash\rUSD, Cash\r; c) ok (token separator) error error, deliberately
\r at column 0 before a directive (\r2024-01-01 open ...) ok error error, deliberately
a \r inside a ; comment with more text after it ok error error, deliberately

bean-check exits 1 on a garbage line in the same setup, so its exit 0 above means something.

Deliberately stricter than beancount

A \r with more of the line after it stays an error. Beancount reads it as a token separator. We don't, because the formatter folds a bare \r into a line break: that is what lets rledger format repair classic-Mac (\r-only) files, and you cannot tell the two cases apart byte by byte. If we accepted open\rAssets:Cash, rledger check would pass a file that format_source then splits into two broken lines. The AGENTS.md deviation checklist is covered: the rustdoc on stray_cr_trivia_end and on stray_cr_run names the beancount behaviour and the reason, and test_parse_cr_with_more_of_the_line_after_it_stays_an_error pins the exact errors. A \r at column 0 before content is part of the same rule. Accepting it would also take CST indentation changes, because the parser reads any line-start WHITESPACE as an indent.

Test evidence

  • crates/rustledger-parser/tests/stray_cr.rs (8 tests): one assertion per issue-table row, plus the extra shapes beancount accepts. Each asserts an empty error list and the exact parsed directives (accounts, narration, metadata keys on opens and postings). They also check the exact Whitespace / Newline tokens and spans, and that a ; comment's value has no \r. The shapes beancount rejects are pinned with exact errors, and so is the deliberate deviation. Every case also checks that the lossless token stream has no gaps or overlaps, that parse_structured(..).text() equals the source, and that green parse equals parse_red_only (directives and errors). try_format_source on each stray variant gives the same output as on the plain CRLF file.
  • crlf_hash_comment.rs: the ; control now covers \r\r\n and \r\r\r\n too (on main it could only cover \n / \r\n).
  • Fail on origin/main: with the base lexer and formatter, 7 of the 8 stray_cr tests fail, and so does the extended crlf_hash_comment test. The one that passes pins the deviation, which main already errors on. With the new lexer but the old fold, crlf_to_lf_keeps_the_lexer_line_structure and formatting_preserves_the_parsed_directives (on the new fixture) fail.
  • Durable fuzz corpus replay (fuzz-corpus branch, 42,083 UTF-8 inputs from fuzz_parse, fuzz_green_eq_red, fuzz_parse_line), using a throwaway harness that is not committed:
    • Every input passes the shared fuzz_targets/common/lossless.rs checks, and green and red agree on directives, errors, comments and options.
    • From the 13,324 inputs with a \n and no " or \r, I made a variant with every \n replaced by \r\r\n. All of them pass the same checks. Each one parses to the same directives (spans aside) and the same error kinds as the plain CRLF variant. Each one also gives the same format_source output, and try_format_source == format_source wherever it parses clean.
  • Suites (inside nix develop): cargo test -p rustledger-parser --all-features, cargo test -p rustledger-loader and cargo test -p rustledger-wasm --lib cache gave 58 test result: ok, 0 FAILED, 1,111 tests passed. cargo test -p rustledger-lsp --all-features --lib also passed (323 tests; semantic tokens use the AST-path tokenize). Also clean: cargo clippy -p rustledger-parser --all-features --all-targets -- -D warnings, cargo fmt --all --check, RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser --no-deps.

Baseline / cache impact

  • Corpus baselines: STRICT_BASELINE=1 corpus_baseline::parser_output_matches_baseline and cst_baseline::cst_output_matches_baseline both pass on the local corpus (731 files). No corpus file contains a \r byte at all, so no entry can move. CI's fresh fetch is the authoritative run. My local copy has 9 upstream-changed files and 15 missing ones, which are skipped with the usual info and warning lines.
  • Cache: this changes parser output with no archived layout move. A file with a stray \r before a line ending used to parse with errors and now parses clean with all its directives. The WASM cache archives parse_errors, so a v63 blob would keep serving the old errors. Loader v49 / WASM v64, following fix(parser): an unterminated quote hides every directive after it behind one error #2784 / fix(parser): end a column-0 # comment before the CRLF that follows it #2773.

Interactions and not in this PR

How to test

cargo test -p rustledger-parser --test stray_cr --test crlf_hash_comment
cargo test -p rustledger-parser --lib crlf_to_lf_keeps_the_lexer_line_structure source_state_classification_agrees_with_lexer test_tokenize_lossless_hash_comment_ends_before_crlf
printf '2024-01-01 open Assets:Cash\r\r\n2024-01-01 open Equity:Opening\r\n' > /path/to/stray.beancount
rledger check /path/to/stray.beancount   # no errors (was: unexpected input)

Closes #2774

🤖 Generated with Claude Code

…count does

A line ending in `\r\r\n`, or a file ending in a lone `\r`, was a parse
error ("unexpected input"; two errors on a transaction header) while
bean-check 3.2.3 accepts it: beancount skips `\r` as whitespace, but our
`Newline` token (`\r?\n`) claims only the `\r` right before the `\n`, so
any other one became an error token.

- Lexer (`TokenIter::stray_cr_trivia_end`): a `[ \t\r]` run that contains
  a `\r` and reaches the line ending (stopping before the `\r` of a
  `\r\n`) or the end of the source is one `Whitespace` token. The bytes
  stay in the token stream and the CST.
- `line_end_before_newline` (column-0 `#` comments, `*` headings, the cut
  of an unterminated string) also ends before such a run, so a comment's
  text no longer carries the stray bytes.
- Formatter: `crlf_to_lf_outside_strings` drops such a run instead of
  folding each `\r` into a `\n`, which added a blank line that ended a
  transaction. `stray_cr_run` mirrors the lexer; a drift guard pins it.
- A `\r` with more of the line after it stays an error (stricter than
  beancount, documented at both sites): the formatter folds that `\r`
  into a line break, which keeps classic-Mac files formattable.
- Loader cache v49, WASM cache v64 (parser output changed).

Closes #2774

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner October 29, 2026 12:27
@codecov

codecov Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
crates/rustledger-parser/src/logos_lexer.rs 98.70% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 44.4ms ± 0.5ms 800.6ms ± 7.8ms 18.0x 34.6 MB / 51.1 MB
investment 67.0ms ± 1.0ms 2886.9ms ± 14.8ms 43.1x 43.8 MB / 59.2 MB
fifo 65.2ms ± 0.3ms 14481.7ms ± 47.4ms 222.2x 40.7 MB / 59.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 45.0ms ± 1.4ms 44.4ms ± 0.5ms -1.3% ✅ within noise 34.6 MB → 34.6 MB (+0.1%)
investment 68.3ms ± 0.4ms 67.0ms ± 1.0ms -1.9% ✅ within noise 44.6 MB → 43.8 MB (-1.7%)
fifo 67.5ms ± 0.6ms 65.2ms ± 0.3ms -3.4% ✅ within noise 40.6 MB → 40.7 MB (+0.4%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.6ms, investment 0.5ms, fifo 0.3ms), 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 821
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 October 29, 2026 08:24
… its line

A long [ \t\r] run followed by more of its line was rescanned from each
of its \r bytes, each scan failing at the same byte: O(N^2), over 120 s
on 1 MB. The end of a failed scan is now remembered and tokens inside it
skip the scan, so each byte is scanned at most once. A cfg(test) counter
pins the scanned bytes as linear.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) October 29, 2026 13:54
@robcohen
robcohen merged commit f9b22ea into main Oct 29, 2026
65 of 66 checks passed
@robcohen
robcohen deleted the fix/stray-cr-before-line-ending branch October 29, 2026 13:57
robcohen added a commit that referenced this pull request Oct 29, 2026
Brings in #2804. The only conflict was CHANGELOG.md (both added an entry
at the top of Fixed); both are kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 29, 2026
`  Assets:A  10 USD @@\r 9 EUR` and `  Assets:A  10\r USD` are clean in
beancount 3.2.3, which reads a `\r` that is not part of a CRLF line end
as a blank. rledger reported the `\r` as an error of its own (P3, kept
from when the formatter folded a bare `\r` into a line break, #2804),
and the parser then dropped what followed it from the posting (the
price, the units), so the transaction also failed to book.

The lexer now turns any `[ \t\r]` run holding a stray `\r` into
`Whitespace` trivia once the line has a token. A run that starts its
line keeps its error (beancount does not take it as an indent, so it
reads the line as unindented), unless it ends the line or the token
after it is an error anyway. With mid-line runs always trivia, the
longer needed: a line-start run peeks one token.

P3 in compatibility.md and the overlay doc say only the line-start
case now. Parse-error parity: 122,478 of 123,394 (was 122,378); the 13
inputs that newly mismatch read the same as with a space for the `\r`.
Loader cache v85, WASM cache v167.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 29, 2026
`  Assets:A  10 USD @@\r 9 EUR` and `  Assets:A  10\r USD` are clean in
beancount 3.2.3, which reads a `\r` that is not part of a CRLF line end
as a blank. rledger reported the `\r` as an error of its own (P3, kept
from when the formatter folded a bare `\r` into a line break, #2804),
and the parser then dropped what followed it from the posting (the
price, the units), so the transaction also failed to book.

The lexer now turns any `[ \t\r]` run holding a stray `\r` into
`Whitespace` trivia once the line has a token. A run that starts its
line keeps its error (beancount does not take it as an indent, so it
reads the line as unindented), unless it ends the line or the token
after it is an error anyway. With mid-line runs always trivia, the
longer needed: a line-start run peeks one token.

P3 in compatibility.md and the overlay doc say only the line-start
case now. Parse-error parity: 122,478 of 123,394 (was 122,378); the 13
inputs that newly mismatch read the same as with a space for the `\r`.
Loader cache v85, WASM cache v167.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 29, 2026
`  Assets:A  10 USD @@\r 9 EUR` and `  Assets:A  10\r USD` are clean in
beancount 3.2.3, which reads a `\r` that is not part of a CRLF line end
as a blank. rledger reported the `\r` as an error of its own (P3, kept
from when the formatter folded a bare `\r` into a line break, #2804),
and the parser then dropped what followed it from the posting (the
price, the units), so the transaction also failed to book.

The lexer now turns any `[ \t\r]` run holding a stray `\r` into
`Whitespace` trivia once the line has a token. A run that starts its
line keeps its error (beancount does not take it as an indent, so it
reads the line as unindented), unless it ends the line or the token
after it is an error anyway. With mid-line runs always trivia, the
longer needed: a line-start run peeks one token.

P3 in compatibility.md and the overlay doc say only the line-start
case now. Parse-error parity: 122,478 of 123,394 (was 122,378); the 13
inputs that newly mismatch read the same as with a space for the `\r`.
Loader cache v85, WASM cache v167.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 29, 2026
…3099)

`  Assets:A  10 USD @@\r 9 EUR` and `  Assets:A  10\r USD` are clean in
beancount 3.2.3, which reads a `\r` that is not part of a CRLF line end
as a blank. rledger reported the `\r` as an error of its own (P3, kept
from when the formatter folded a bare `\r` into a line break, #2804),
and the parser then dropped what followed it from the posting (the
price, the units), so the transaction also failed to book.

The lexer now turns any `[ \t\r]` run holding a stray `\r` into
`Whitespace` trivia once the line has a token. A run that starts its
line keeps its error (beancount does not take it as an indent, so it
reads the line as unindented), unless it ends the line or the token
after it is an error anyway. With mid-line runs always trivia, the
longer needed: a line-start run peeks one token.

P3 in compatibility.md and the overlay doc say only the line-start
case now. Parse-error parity: 122,478 of 123,394 (was 122,378); the 13
inputs that newly mismatch read the same as with a space for the `\r`.
Loader cache v85, WASM cache v167.

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.

fix(parser): a stray \r before the line ending is a parse error; bean-check accepts it

1 participant