Skip to content

fix(parser): end an unterminated quote at its own line - #2788

Merged
robcohen merged 3 commits into
mainfrom
fix/unterminated-quote
Oct 28, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/unterminated-quote

Conversation

@robcohen

@robcohen robcohen commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

What changed

  • Lexer (TokenIter's Err(()) arm, crates/rustledger-parser/src/logos_lexer.rs): an error token that starts with " and runs past its line now ends at the line end (line_end_before_newline), and the lexer is restarted there, so the next call emits the line's Newline and lexing carries on.
  • Linear time: after a failed scan is cut, TokenIter lexes one line at a time up to the furthest point any cut scan reached (chunk_until, line_chunk_end), then returns to the whole rest of the source. Every " before that point is escaped in the cut scan's alignment, so each later scan there stops at its own line. Without that, restarting over the whole file at each cut was quadratic, whichever way the scans failed: 900 KB of \" lines took 55 s (end-of-input stop) or 43 s (with a trailing lone \, a backslash stop); main takes under 2 ms. That is a denial of service on untrusted input. Now 300k such lines lex in about 27 ms and parse in about 70 ms, for both shapes and a mixed one. A cfg(test) counter of the bytes visible to restarted lexers keeps both shapes linear (without the line mode it saw 5,999,000 bytes of a 6,000-byte input).
  • Fuzz (fuzz_targets/common/lossless.rs, shared by fuzz_parse and fuzz_green_eq_red): asserts that no error token spans a line ending.
  • Loader CACHE_VERSION 47 -> 48, WASM 62 -> 63 (pin and fixture versions follow); CHANGELOG entry.
  • tests/indented_star_line.rs (fix(parser): report an indented * line instead of silencing it as a heading #2785): its quote rows were written to change here, and now keep the directives after the line.

Why

The lexer has one String regex. When a " has no closing quote before the end of the file, logos reports everything it scanned as ONE error token, so one typo hid the rest of the ledger behind a single error:

2024-01-01 * "Lunch
  Assets:A  1 USD
  Assets:B
2024-01-02 open Assets:B

On main everything after line 1 is gone. Beancount 3.2.3 reports the stray quote (Invalid token) and keeps the directives after it; it drops the broken transaction itself. With this PR the later open is kept, and so is the transaction, with its header error reported: a deliberate divergence (its postings still get checked), noted in the test.

The cut cannot change which quotes pair up. A string scan fails in one of two ways: it reaches the end of the input without a closing ", or it stops at a \ before a line break (\\. does not match a newline), which can happen inside an otherwise closed multi-line string. Every " inside the scanned region was escaped from the scan's point of view, so re-lexing from the line end meets the same stop or the same end of input. A test pins the backslash case.

How to test

cargo test -p rustledger-parser --test unterminated_quote --test indented_star_line:

  • a lone ", a CRLF line, an escaped \", and the last line: exact error span (the quote's own line) and exactly the surviving opens;
  • the narration typo keeps the transaction (2 postings) and the later open;
  • the error token is the quote plus the rest of its line, ending before \r\n, followed by the Newline;
  • terminated multi-line strings (LF and CRLF interiors) are unchanged;
  • every case: lossless token stream, CST round-trip, green == red.

With the fix disabled, 3 of the 4 new tests fail (the fourth is the terminated-string control) and so does the updated #2785 row. Durable fuzz corpus replay (58,362 UTF-8 inputs) through the shared lossless checks including the new one: 0 failures with the fix, 110 with it disabled. Parser, loader and WASM suites: 60 test binaries, 0 failures; clippy (parser and fuzz crate) and fmt clean.

Not in this PR

Closes #2784

🤖 Generated with Claude Code

The lexer has one String regex. When a " has no closing quote before
the end of the file, logos reports everything it scanned as one error
token, so a single typo (2024-01-01 * "Lunch) lost every later
directive behind one error that ran to the end of the file. Beancount
reports the stray quote and carries on.

- TokenIter: an error token that starts with " and runs past its line
  ends at the line end (line_end_before_newline), and the lexer is
  restarted there. Nothing after the cut can belong to a string: any
  later unescaped " would have closed this one, so terminated
  multi-line strings are unchanged.
- The indented * line case from #2783 now keeps its directives too.
- Fuzz: common/lossless.rs asserts no error token spans a line ending
  (0 of 58,362 corpus inputs fail with the fix, 110 without).
- Loader CACHE_VERSION 48, WASM 63.
- Tests, CHANGELOG.

Closes #2784

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner October 28, 2026 19:26
@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 32.5ms ± 2.2ms 496.5ms ± 6.1ms 15.3x 33.6 MB / 51.2 MB
investment 49.1ms ± 1.2ms 1707.0ms ± 51.6ms 34.7x 44.4 MB / 59.1 MB
fifo 47.1ms ± 5.5ms 8378.7ms ± 101.0ms 177.9x 40.6 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 32.6ms ± 5.6ms 32.5ms ± 2.2ms -0.6% ✅ within noise 34.7 MB → 33.6 MB (-3.1%)
investment 49.7ms ± 6.0ms 49.1ms ± 1.2ms -1.1% ✅ within noise 44.7 MB → 44.4 MB (-0.7%)
fifo 45.7ms ± 1.1ms 47.1ms ± 5.5ms +3.1% ✅ within noise 40.6 MB → 40.6 MB (-0.0%)

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

@codecov

codecov Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.55172% with 2 lines in your changes missing coverage. Please review.

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

📢 Thoughts on this report? Let us know!

robcohen and others added 2 commits October 28, 2026 14:46
Review of the #2784 fix: restarting the lexer over the whole file at
each cut made lexing quadratic. After the first unterminated quote, a
later \" is re-lexed outside a string, its " opens a new scan that also
cannot close, and each scan re-read to the end of the file: 900 KB of
\" lines took 55 s (main: under 2 ms). A denial of service on untrusted
input in wasm and the LSP.

- Once a string scan reaches the end of the input, no later scan can
  close (no unescaped " and no backslash-before-newline stop is left),
  so TokenIter lexes the rest one line at a time (lex_end,
  line_chunk_end); each later scan stops at its own line. 300k such
  lines: 55 s down to 75 ms, output unchanged.
- restart_lexer counts, under cfg(test), the bytes each restarted lexer
  can see; a unit test keeps that linear (it saw 5,999,000 bytes of a
  6,000-byte input without the line-at-a-time mode).
- The cut's comment covers both ways a scan fails (end of input, or a
  backslash before a line break) and why pairing cannot change; a test
  pins the backslash case. The narration test notes that keeping the
  broken transaction is a deliberate divergence (beancount drops it).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Round-2 review: line-at-a-time mode only started after a string scan
reached the end of the input. A scan can also stop at a backslash
before a line break, and every later \" shares its alignment, so each
of their scans ran to that same far stop: 300k \" lines followed by a
lone backslash line still took 43 s.

Line mode now lasts up to the furthest end of ANY failed scan that was
cut (chunk_until), then lexing returns to the whole rest of the source;
the end-of-input case is the special case where that end is the source
length. 300k lines: 43 s down to 27 ms; the end-of-input and mixed
shapes stay linear. The linear-cost guard covers both stops.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) October 28, 2026 20:12
@robcohen
robcohen merged commit 25599cb into main Oct 28, 2026
66 of 67 checks passed
@robcohen
robcohen deleted the fix/unterminated-quote branch October 28, 2026 20:18
robcohen added a commit that referenced this pull request Oct 29, 2026
…ote (#2800)

#2788 (end an unterminated quote at its own line) already fixed #2781:
`#TODO buy 27" monitor` followed by two opens now reports one error on
line 1 and keeps both opens, as beancount 3.2.3 does. Before #2788 the
error ran to the end of the file and both opens were lost.

Add a parse-level regression test for the tag shape and its variants
(CRLF, a bare `#TODO "x`, a directive-looking tag line, the last line,
and a later quote that closes the string across lines). Each case
matches beancount 3.2.3's error line and surviving directives, and goes
through the lossless and green/red agreement invariants.

Closes #2781

Co-authored-by: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 2, 2026
…ay quote

- The range walk now tracks a top-level WHITESPACE token before a node,
  as the whole-file walk does, so a verbatim-copied indented directive
  keeps its indentation (#2786). Dropping it also removed the
  indentation parse error, so a second pass reformatted the line.
- The line-ending helpers (lf_to_crlf_outside_strings and
  crlf_to_lf_outside_strings) read a `"` as the lexer does: one that no
  later unescaped quote closes, or that a `\` before a line break stops,
  is an error token cut at its own line (#2788), not a string. A stray
  quote copied into a CRLF edit left every later line LF. A failed scan
  is remembered so many stray quotes stay linear. The lexer-agreement
  drift guard now runs the same step and has two unterminated-quote
  fixtures.
- Corrects two stale comments that said whole-file formatting drops
  ERROR_NODE content.

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

* fix(lsp): keep unparsable text inside a directive when range formatting

The LSP range-format fallback (files with parse errors) rebuilt each
directive in the selection from its typed values, so text the parser
could not read into one (`junk` after a header, after a posting amount,
inside a cost) vanished from the edit along with its parse error.

A new `format::format_parsed_range` takes the parse result and builds the
same `ErrorRanges` the whole-file error-tolerant formatter uses (#2794);
a directive overlapping a parse error is copied verbatim. The per-node
emission is now one `NodeEmitter` shared by the whole-file and range
walks, so the two cannot disagree on which directives they rebuild. Also
corrects doc comments that said whole-file formatting drops ERROR_NODE
content (it copies it verbatim since #1335).

Closes #2803

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

* fix(format): keep the indent in range formatting and CRLF after a stray quote

- The range walk now tracks a top-level WHITESPACE token before a node,
  as the whole-file walk does, so a verbatim-copied indented directive
  keeps its indentation (#2786). Dropping it also removed the
  indentation parse error, so a second pass reformatted the line.
- The line-ending helpers (lf_to_crlf_outside_strings and
  crlf_to_lf_outside_strings) read a `"` as the lexer does: one that no
  later unescaped quote closes, or that a `\` before a line break stops,
  is an error token cut at its own line (#2788), not a string. A stray
  quote copied into a CRLF edit left every later line LF. A failed scan
  is remembered so many stray quotes stay linear. The lexer-agreement
  drift guard now runs the same step and has two unterminated-quote
  fixtures.
- Corrects two stale comments that said whole-file formatting drops
  ERROR_NODE content.

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

* docs(changelog): note the range indent and CRLF fixes for #2803

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

* fix(format): one quote rule for every line-ending walker; pin it

- cr_outside_strings_present now reads quotes through lexer_source_state,
  like the two helpers it mirrors, so a stray quote no longer hides the
  `\r` after it.
- A fixture with a later quote (`"a\` + newline, then `"x"`) pins the
  `\`-before-line-break rule in the lexer-agreement drift guard and the
  LF->CRLF helper test; an unconditional escape now fails both.
- A linear-cost guard counts the bytes quote scans step over (one stray
  quote then 20k `\"` lines): without the memo it is 400M bytes for 60k.
- A test pins the error-tolerant formatter folding a bare `\r` after a
  stray quote into a line break.
- CHANGELOG: name the affected paths precisely (LSP range edits;
  format_source behind WASM/FFI for bare `\r`), not WASM/FFI CRLF.

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

---------

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): an unterminated quote hides every directive after it behind one error

1 participant