Skip to content

fix(format): keep unparsable text inside a directive in the error-tolerant formatter - #2801

Merged
robcohen merged 5 commits into
mainfrom
fix/format-keeps-directive-error-tokens
Oct 29, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/format-keeps-directive-error-tokens

Conversation

@robcohen

@robcohen robcohen commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

What changed

format_source (the error-tolerant formatter behind the FFI component's best-effort format.source / format.file, rustfava's default) no longer deletes unparsable text inside a directive. A directive that holds a parse error is copied verbatim, the same way a top-level ERROR_NODE already is (#1335).

Input Before After
2024-01-01 open Assets:A junk\n2024-01-02 open Assets:B\n 2024-01-01 open Assets:A\n2024-01-02 open Assets:B\n (errors 1 -> 0) unchanged
2024-01-01 open Assets:A* h\n 2024-01-01 open Assets:A\n unchanged
2024-01-01 open Assets:A" 2024-01-01 open Assets:A\n 2024-01-01 open Assets:A"\n

Why

emit_directive rebuilds a directive from its typed values. Text the parser could not read into one is part of no value, so it was dropped, and the parse error disappeared with it. That breaks the #1335 rule that format never deletes the author's text.

Approach and trade-off

  • format_source_grouped now runs the full parse (parse_without_occurrences) instead of the bare tree parse, so it has the parser's own error list. The error spans are merged into sorted ranges (ErrorRanges), and the top-level walk copies any directive whose range overlaps one verbatim, through the existing ERROR_NODE path (same blank-line and indentation handling).
  • Why the parser's error list and not a scan for ERROR_TOKENs: I tried the token scan first, and the property test below broke it at once. pushtag! #t is a parse error with no ERROR_TOKEN (the ! is a flag token), and the rebuild dropped the !. Errors come from many rules (error tokens, header defects, catch-all body lines, shape checks), and a second classifier in the formatter would drift from them (Canonical-Function Discipline).
  • Why the whole directive verbatim, not just its error tokens: putting error tokens back in place needs a position in the rebuilt output, and the rebuild also drops tokens that are not error tokens (the * in Assets:A* h, the ! above). Copying verbatim is the only option that keeps every byte for sure. The cost is that the rest of a broken directive is not normalized: a broken transaction keeps its own spacing until the error is fixed. The directives around it are still formatted (pinned by test_format_source_formats_the_directives_around_a_broken_one).
  • Cost: format_source now pays for the conversion pass. On a 913 KB corpus file (fava_investor_examples_huge-example.beancount), a release-build time per call went from 17.0 ms to 25.6 ms. The hot clean-file paths do not go through format_source: rledger format (try_format_source), LSP formatting and FFI format.source on a clean file all use format_source_with_parsed, which is unchanged. canonicalize_directives (used by rledger add / extract, BQL PRINT and FFI format.entry / format.entries / format.loaded) does not pay it either: it already holds an error-free parse, so it formats that tree directly instead of parsing again.
  • format_node / format_node_grouped take only a tree, which does not carry its errors, so they still rebuild every directive. Their rustdoc now says so and points broken input at format_source. Their callers only pass clean trees.

Tests

  • crates/rustledger-parser/tests/format_keeps_error_lines.rs (reuses error_lines / assert_unchanged): the three issue cases with exact output, junk after a transaction header, after a posting, after transaction, posting and open metadata values, mid-line error tokens (open, price, posting, pushtag!), and a broken transaction between formatted ones.

  • Property test test_format_source_keeps_every_byte_of_a_broken_file: proptest with a fixed seed (RngSeed::Fixed(2794)), 512 cases, no failure file, runs in about 0.1 s. It joins canonical snippets of every directive kind (transactions with tags, links, metadata, cost and price included) and inserts junk (junk, ", *, * h, !, @, {, }, ~, #, ^, $, ...) at random offsets. For inputs with parse errors it asserts:

    1. The output's non-whitespace characters equal the input's, in order. Since the snippets are canonical and the formatter only moves whitespace, this is exact. It is stricter than a multiset check, which would accept a reordering.
    2. The output's error lines equal the input's.
    3. Formatting is idempotent.

    Only inputs where every insertion lands on a line with a parse error are checked. The parser silently accepts some stray characters inside an otherwise valid directive (see "Found, not fixed" below). The formatter drops those with no error reported, which is a parser leniency and not this bug.

  • Fails on main. The first counterexample: "pushtagjunk #t\n" -> "pushtag #t\n". The new example tests also fail on main, e.g. "2024-01-01 * \"p\" junk\n Assets:A 1 USD\n Assets:B\n" -> "2024-01-01 * \"p\"\n Assets:A 1 USD\n Assets:B\n" with the error lines going from 2 to 0.

  • An exhaustive single-insertion sweep over the same snippets and junk (18,678 inputs with the insertion on an error line): 8,056 failures on main, 0 with this fix.

  • FFI: convert::format_source_tests::test_format_source_keeps_unparsable_text_in_a_directive pins this at the format.source entry point.

Clean-file output unchanged

  • format_source over 1,068 .beancount files (the 731-file compatibility corpus and the in-tree fixtures), main vs this branch: all 992 files without parse errors give byte-identical output. 45 of the 75 broken files changed.
  • On those 75 broken files: text lost 34 -> 3, error count changed after formatting 24 -> 0, non-idempotent 0 -> 0. The 3 left are all parser leniency (a silently accepted ) posting amount, open Assets:Bank:Current*, open Expenses:Groceries!).
  • The existing formatter tests pass: cst::format::tests (including the idempotence matrix), format_compat, pipeline_invariants, and the LSP format tests, which include lsp_matches_format_source.

Baselines

corpus_baseline and cst_baseline pass unchanged. They fingerprint parser output and the CST, and this PR does not touch the parser. The formatter has no corpus baseline (retired in #1284, per tests/baselines/README.md). The CI corpus format gates run rledger format, which refuses files with parse errors, so they cannot see this change.

Found, not fixed (follow-ups)

  • Parser leniency. Many stray characters inside a directive parse with no error, and the formatter then drops them, or worse: 2024-01-01 open Assets:A U*SD formats to open Assets:A U,SD, and open! Assets:A, close! Assets:A, open Assets:A USD @ and price HOOL ? 10 USD all lose a character. Because the file parses clean, rledger format is affected too. Beancount rejects these.
  • LSP range formatting. textDocument/rangeFormatting's parse-error fallback (format_node_range) refuses only when the range covers an ERROR_NODE, so a selected directive that holds an error token is rebuilt and loses that token, the same as this bug.

How to test

cargo test -p rustledger-parser --test format_keeps_error_lines
cargo test -p rustledger-parser --all-features
cargo test -p rustledger-ffi-component format_source

An indented directive is reported as an error, so it is copied verbatim too and keeps that error instead of being dedented and silently repaired. That settles #2795 in favor of copying it unchanged; test_format_source_keeps_an_indented_directive_an_error pins it.

Trailing whitespace in a copied directive is trimmed only outside strings, so a multi-line string keeps its value (including a \r\n inside a string in a CRLF file). canonicalize_directives formats the tree it has already parsed instead of parsing the emitter text a second time. The same token-walk trim also stops a whitespace-only line beside an error node from coming out as two blank lines (#2796).

Closes #2794
Closes #2795
Closes #2796

🤖 Generated with Claude Code

…erant formatter

format_source (behind the FFI component's best-effort format.source /
format.file) rebuilds each directive from its typed values. Text the
parser could not read into one is part of no value, so it was deleted
and the parse error went with it: `2024-01-01 open Assets:A junk`
became `2024-01-01 open Assets:A`, and likewise for junk after a
transaction header, a posting or a metadata value, a stray `"` or `*`,
or a `!` after `pushtag`.

format_source now takes the parser's own error list (one full parse
instead of the bare tree parse) and copies every directive that
overlaps an error span verbatim, as top-level ERROR_NODEs already are
(#1335). The error list is used rather than a scan for ERROR_TOKENs:
errors come from many rules, and a token scan misses e.g. `pushtag!`.
Directives without errors are formatted exactly as before.

A seeded property test mutates canonical snippets of every directive
kind and checks that a broken file keeps its non-whitespace text in
order, keeps its error lines, and formats idempotently. On main its
first counterexample is `pushtagjunk #t\n` -> `pushtag #t\n`.

Closes #2794

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

codecov Bot commented Oct 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 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 36.6ms ± 2.1ms 600.8ms ± 10.3ms 16.4x 34.5 MB / 51.0 MB
investment 56.6ms ± 1.2ms 2191.6ms ± 16.6ms 38.7x 44.8 MB / 59.1 MB
fifo 53.6ms ± 0.6ms 11653.8ms ± 22.6ms 217.3x 40.6 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 36.6ms ± 1.4ms 36.6ms ± 2.1ms +0.0% ✅ within noise 33.8 MB → 34.5 MB (+2.0%)
investment 57.3ms ± 0.8ms 56.6ms ± 1.2ms -1.2% ✅ within noise 44.7 MB → 44.8 MB (+0.3%)
fifo 54.6ms ± 0.8ms 53.6ms ± 0.6ms -1.7% ✅ within noise 40.6 MB → 40.6 MB (-0.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 1.1ms, investment 0.7ms, fifo 0.4ms), 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 4 commits October 29, 2026 08:17
…arse

A broken directive is copied verbatim through emit_error_node, which
trimmed trailing whitespace on every line of its text, including lines
inside a multi-line STRING, so the string's value changed ("SELECT\n  1  \n"
lost its spaces, and a \r\n inside a CRLF file's string lost its \r). The
trim now walks tokens and never reaches into a string.

canonicalize_directives has already parsed the emitter's text and checked
it is error-free, so it formats that tree instead of calling
format_source_grouped, which parsed it again only to find no errors.

Also records that indented directives in a broken file are now copied
verbatim and keep their error (#2795), with a test, and narrows the
CHANGELOG's LSP claim to whole-document formatting (range formatting is
#2803).

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

The token-walk trim in emit_error_node strips a whitespace-only line at
the edge of an error node before its leading and trailing blank lines are
counted, so the line is no longer emitted both as a gap and as an empty
line of the node.

Closes #2796

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The token-walk trim called trim_end on the whole output buffer, so on a
blank line it also ate the newline ending the line before, and every
blank line inside an error node or a verbatim-copied directive was
deleted. The trim now stops at the start of the current line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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
robcohen enabled auto-merge (squash) October 29, 2026 14:10
@robcohen
robcohen merged commit 68c93fc into main Oct 29, 2026
60 of 61 checks passed
@robcohen
robcohen deleted the fix/format-keeps-directive-error-tokens branch October 29, 2026 14:19
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