Skip to content

fix(format): never change what a file means; round-trip properties for the formatter - #3060

Merged
robcohen merged 4 commits into
mainfrom
test/formatter-roundtrip-properties
Nov 27, 2026
Merged

robcohen merged 4 commits into
mainfrom
test/formatter-roundtrip-properties

Conversation

@robcohen

@robcohen robcohen commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

What

Adds round-trip properties that retire the "formatter changes what the file means" category (#3046 / #3048 was the latest instance), and fixes every bug they found.

The properties

One oracle, crates/rustledger-parser/fuzz/fuzz_targets/common/format_roundtrip.rs, shared by a test file and a fuzz target, asserts for any UTF-8 input:

  1. Idempotence: format(format(x)) == format(x).
  2. Meaning: the directives, options, includes and plugins parsed from the output equal those parsed from the input. They are compared through Debug with spans stripped, not PartialEq, because Decimal's == ignores scale (1.5 == 1.50). Comment values are compared without trailing blanks, which the canonical form trims.
  3. Comments: a structural comment stream (where each comment sits among directives, postings and metadata lines, trailing or own-line, with its text) is unchanged.
  4. Errors: a clean file stays clean and a broken one broken. Every line holding a parse error is kept byte for byte. try_format_source (the CLI's entry) refuses exactly the broken inputs and otherwise agrees with format_source byte for byte.

Two relaxations apply on broken input only, each documented in the oracle. A directive touching an error line is a recovery artifact and is left out of the meaning comparison; the line itself is still checked verbatim. And a line may gain a reported error only where the input already held one the parser quiets inside bison's recovery window.

Where it runs:

  • crates/rustledger-parser/tests/format_roundtrip_properties.rs
    • a proptest generator of realistic ledgers (format_roundtrip_common/ledger_gen.rs): every directive kind, multi-line, unicode and escaped strings, comments in every slot and at every indent, metadata of every type, tags and links, cost specs (per-unit, total, compound, dated, labelled, merge), prices, arithmetic, 28-digit numbers, thousands separators, tabs and sloppy spacing, a whole-file BOM, CRLF, no final newline. The default is 256 cases (FORMAT_ROUNDTRIP_CASES overrides); 30k cases ran clean locally.
    • every ledger under tests/, the format_compat fixtures, and every committed fuzz regression input.
    • a minimized regression per root cause.
    • explore_dir (ignored) for a local sweep of any directory.
  • the new cargo-fuzz target fuzz_format_roundtrip, registered in fuzz.yml. fuzz.yml seeds it with fuzz_parse's corpus from the fuzz-corpus branch (read-only, via the existing seed step) as well as its own, so every PR replays the parser's fuzz corpus through the oracle.
  • crates/rustledger-lsp/tests/format_surface_parity.rs (formatter-specific, not the general surface-parity test):
    • on clean files, LSP textDocument/formatting equals the CLI's output, with CRLF re-injected on a CRLF document (the LSP's documented difference); whole-document rangeFormatting equals it too; and range formatting of any line or line pair changes nothing outside the selection and converges on the canonical form.
    • on broken files, both LSP fallbacks keep error lines, values and comments.
    • runs over the repo's ledgers and over generated clean and broken ledgers.

Bugs found and fixed

  1. A comment stopped at a mid-line \r (lexer). beancount's ;.* takes the \r. Our ;, %, #! and #+ comment regexes stopped at any \r (a column-0 # comment already ran to the line end). The formatter wrote only the comment token, so open Assets:A ;c \rmore lost \rmore, and #!\rqu turned into an error line.

  2. format_source folded a bare \r into a line break. The lexer does not end a line there. As a result, ; c\r2024-01-01 open Assets:A grew an open the comment had hidden (bean-format has the same bug; checked with bean-check), and a classic-Mac file that bean-check rejects became a different, valid file. The fold now keeps such a \r, and the broken file is copied verbatim. This also fixes format_source disagreeing with format_source_with_parsed/CLI on clean files with a \r in a comment.

  3. A second BOM was dropped one per pass. format_source stripped the leading BOM and the parser then took the second for the leading one, and the top-level walk skipped BOM tokens. Formatting was not idempotent.

  4. Unicode whitespace on a broken line was trimmed (str::trim_end), deleting the error. This covers NBSP, vertical tab and the like.

  5. Directives holding a quieted error were rebuilt. The parser quiets errors inside bison's recovery window to match bean-check, and the formatter only copied directives with reported errors verbatim, so include E after a failed line became include, and a plugin { line lost its name: ... body (found in the lima fixtures). ParseResult now carries the pre-quieting spans (crate-private defect_spans, with a #[doc(hidden)] accessor for the oracle).

  6. Normalizing a broken line repaired it. A lone capital before a \r is beancount's invalid token (CAPITAL needs a space, a tab or a \n after it), so open Assets:As,A\r\n is an error and open Assets:As,A\n a valid open (verified with bean-check). Folding the CRLF, dropping a stray \r (R\r\t\n), or adding the final newline after ...T at EOF repaired the line, and the formatter then rebuilt it. Such a line now keeps its \r/missing newline. The decision is per line, from the line's own tokens, so it stays idempotent.

  7. A reported, indented comment line was dedented (e.g. \t; after an include), which removed the error.

  8. LSP surface cleanup rewrote multi-line strings. On a broken file, textDocument/formatting converted a line's leading tabs and stripped its trailing blanks, even on a line that starts or ends inside a multi-line string, changing the string's value.

  9. LSP range formatting could duplicate a posting. It keeps the whole-document edits inside the selection, and the line diff can express a reformatted posting as an insertion inside the selection plus a deletion outside it. Kept edits are now returned only when they converge on the canonical form; otherwise the selected directives are formatted whole (the existing CST-snap path).

How to test

cargo test -p rustledger-parser --test format_roundtrip_properties
FORMAT_ROUNDTRIP_CASES=20000 cargo test --release -p rustledger-parser --test format_roundtrip_properties generated
cargo test -p rustledger-lsp --test format_surface_parity
# the parser fuzz corpus, locally:
git fetch --depth=1 origin fuzz-corpus && mkdir -p /tmp/c && git archive FETCH_HEAD fuzz_parse | tar -x -C /tmp/c
FORMAT_CORPUS_DIR=/tmp/c/fuzz_parse cargo test --release -p rustledger-parser --test format_roundtrip_properties explore_dir -- --ignored

CI follow-ups

  • fuzz_format_roundtrip corpus replay found \t;\n\t+: a file-leading indented comment was moved to column 0. rledger reads it as a comment (beancount reports unexpected INDENT; a deliberate deviation) but keeps bison's recovery after it quiet, so the next indented line is clean; after a column-0 comment it is an error. Top-level indented comments (only the file-leading region has them) now keep their indent. The input is in fuzz/regressions/fuzz_format_roundtrip/ and pinned by test_format_source_keeps_a_leading_indented_comment_indented.
  • The generated-ledger proptests overflowed the default test-thread stack in debug builds on macOS and Windows: building the deeply nested strategy does. They now run on a thread with an explicit 256 MiB stack (ledger_gen::run_property). Verified locally in a debug build with RUST_MIN_STACK=1048576.

Caches

Parser output moves (a comment's text in a parsed directive now runs through a mid-line \r), so the loader cache goes to v81 and the WASM cache to v146 (v80/v145 are taken by #3057) (pin updated).

Parse-error parity baseline

The lexer fix (1) brings 53 inputs (pinned fuzz corpus and generator sample) in line with beancount 3.2.3. The parse-error parity baseline listed them as mismatches. It also moves 7 between mismatch categories and shifts 18 category counts. tests/baselines/parse-error-parity.manifest was regenerated with --update (beancount 3.2.3, ptadiff at the pinned rev); --check reports 0 regressions. One regression showed up on the way: T;c is part of beancount's invalid token, not a comment. It is fixed (a ; glued to a lone capital does not take the \r), and the regression run now passes.

Known limitations / left open

  • 0861-02-13T at the end of a file after a clean line parses clean in rledger, where bean-check reports Invalid token: 'T'. That is a parser parity gap, not a formatter one: rledger's own reading is preserved by the formatter. Reported here rather than fixed in this formatter lane.
  • The deliberate fix(parser): treat a stray \r before a line ending as trivia, as beancount does #2804 deviation (a mid-line \r outside a comment is an error in rledger and a blank in beancount) was justified by the formatter folding such a \r into a line break. The formatter no longer does that, so the deviation could now be revisited; the docs say so.
  • The oracle relaxes two things on broken input only (see the oracle's docs): directives touching an error line are recovery artifacts and are left out of the meaning comparison, and a line may gain a reported error where bison's recovery window had quieted one.

🤖 Generated with Claude Code

@robcohen
robcohen requested a review from a team as a code owner November 27, 2026 06:32
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 52.4ms ± 2.0ms 803.9ms ± 8.1ms 15.3x 43.2 MB / 51.1 MB
investment 79.4ms ± 1.5ms 2928.4ms ± 11.1ms 36.9x 47.2 MB / 59.1 MB
fifo 76.3ms ± 0.9ms 14576.9ms ± 67.0ms 191.0x 49.4 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 52.3ms ± 2.0ms 52.4ms ± 2.0ms +0.1% ✅ within noise 43.2 MB → 43.2 MB (+0.0%)
investment 77.7ms ± 1.3ms 79.4ms ± 1.5ms +2.1% ✅ within noise 47.3 MB → 47.2 MB (-0.3%)
fifo 75.9ms ± 1.4ms 76.3ms ± 0.9ms +0.5% ✅ within noise 49.2 MB → 49.4 MB (+0.4%)

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

@codecov

codecov Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
crates/rustledger-lsp/src/handlers/formatting.rs 97.91% 1 Missing ⚠️
...es/rustledger-lsp/src/handlers/range_formatting.rs 94.44% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@robcohen
robcohen force-pushed the test/formatter-roundtrip-properties branch from a0f8d6e to 8b36f5e Compare November 27, 2026 07:59
robcohen and others added 3 commits November 27, 2026 02:46
Root causes found by the new formatter round-trip properties, each
pinned by a minimized regression in format_roundtrip_properties.rs:

- format_source folded a bare `\r` with more of the line after it into
  a line break. The lexer does not end a line there, so a comment's tail
  became a line of its own (`; c\r2024-01-01 open ...` grew an open the
  comment hid) and a classic-Mac file bean-check rejects became a
  different, valid one. Such a `\r` is now kept and the broken line is
  copied verbatim; format_source agrees with format_source_with_parsed.
- A second BOM was dropped one per pass: format_source stripped the
  leading BOM and the parser then took the second for it, and the
  top-level walk skipped BOM tokens. Formatting was not idempotent.
- The verbatim copy of a broken line trimmed Unicode whitespace
  (str::trim_end), deleting the error the lexer reports for it.
- A directive holding an error the parser quiets inside bison's recovery
  window was rebuilt from its typed values, deleting unread text
  (`include E` became `include`, a `plugin {` lost its `name:` line).
  ParseResult now carries the pre-quieting spans (crate-private
  defect_spans), and such directives are copied verbatim too.
- Normalizing a broken line could repair it: a lone capital before a
  `\r` is beancount's invalid token, so folding the CRLF, dropping a
  stray `\r`, or adding the final newline after a broken last line made
  it valid and the formatter rebuilt it. Such a line keeps its bytes;
  the decision is per line, so formatting stays idempotent.
- A reported, indented comment line was moved to column 0, where it is
  an ordinary comment and the error is gone.

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

beancount's `;.*` takes a `\r` (flex's `.`), as does our column-0 `#`
comment, but the `;`, `%`, `#!` and `#+` regexes stopped at any `\r`.
The rest of the line became tokens of its own, which the formatter
dropped or moved to a line of its own. A `;` glued to a lone capital
(`T;c`) is part of beancount's invalid token, which a `\r` ends, and is
left alone.

Matches beancount on 53 inputs (fuzz corpus and generator sample) the
parse-error parity baseline listed as mismatches and moves 7 between
categories; the manifest is regenerated with --update (no regressions).

Bumps the loader cache to v81 and the WASM cache to v146: a comment's
text in a parsed directive now runs through such a `\r`.

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

- Surface cleanup (textDocument/formatting on a broken file) converted
  leading tabs and stripped trailing blanks on lines that start or end
  inside a multi-line string, rewriting the string's value. Such lines
  are now left alone.
- Range formatting kept the whole-document edits inside the selection
  by position alone; the line diff can express a reformatted posting as
  an insertion inside the selection and a deletion outside it, so
  keeping only the insertion duplicated the posting. Kept edits are now
  returned only when they converge on the canonical form; otherwise the
  selected directives are formatted whole (the CST-snap path).

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

One oracle (fuzz/fuzz_targets/common/format_roundtrip.rs) checks
idempotence, unchanged parsed meaning (Debug with spans stripped, so
decimal scale counts), an unchanged comment stream, error preservation
(clean stays clean, broken stays broken with every error line kept
byte for byte) and try_format_source == format_source. It runs:

- as proptest over a generator of realistic ledgers (multi-line and
  unicode strings, comments in every slot, metadata, cost/price specs,
  arithmetic, long numbers, BOM, CRLF, tabs, no final newline);
- over every ledger under tests/, the format_compat fixtures and every
  committed fuzz regression;
- as the new cargo-fuzz target fuzz_format_roundtrip, which fuzz.yml
  seeds with fuzz_parse's corpus so every PR replays the parser corpus.

rustledger-lsp's format_surface_parity pins LSP whole-document and range
formatting to the CLI on clean files and both LSP fallbacks to keep a
broken file's meaning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 27, 2026
@robcohen
robcohen force-pushed the test/formatter-roundtrip-properties branch from 8b36f5e to b9a0441 Compare November 27, 2026 09:15
@robcohen
robcohen merged commit 807d6dd into main Nov 27, 2026
72 of 73 checks passed
@robcohen
robcohen deleted the test/formatter-roundtrip-properties branch November 27, 2026 09:55
robcohen added a commit that referenced this pull request Nov 27, 2026
robcohen added a commit that referenced this pull request Nov 27, 2026
…, and make --auto load beancount's auto plugin (#3059)

* fix(booking): refuse a price to compute beside a cost, as beancount does

1 HOOL {10 USD} @ USD (or a bare @, @@, @@ USD) was accepted and the price
ignored (#1919). beancount reports "Cannot infer price for postings with
units held at cost" (and then crashes); rledger now refuses it as a booking
failure on the posting (InterpolationError::PriceBesideCost). A price NUMBER
without a currency (@ 12) still takes the cost currency (#3047).

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

* fix(loader)!: report bytes that are not UTF-8 where beancount does

A non-UTF-8 file was decoded lossily and accepted. The decode stays lossy
(no panic, the text is still shown), but SourceText now remembers where the
invalid sequences were, and the loader reports them as beancount 3.2.3 does:
an invalid token outside strings (one per run), one error per string on its
last line (UnicodeDecodeError), nothing in a comment. Loader cache v81.

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

* fix(check)!: --auto runs auto_accounts and implicit_prices, as bean-check --auto does

bean-check --auto adds beancount.plugins.auto; rledger --auto ran
auto_accounts alone. LoadOptions::auto_accounts now runs both parts, each in
its own pass, through plugin_parts. check also renders parse-error snippets
of a non-UTF-8 file from the lossily decoded text the loader parsed.

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

* docs(compat): fix stale sections, mark the decided upstream checks covered, bump caches

compatibility.md sections 1 (beancount refuses unbalanced multi-currency
transactions too), 3 (rledger reports all four push/pop mistakes) and 4
(unknown options are E7001, deprecated E7004) described old behavior.
checks.toml: the bare-price row is covered, the lexer row names the UTF-8
test. WASM cache v145.

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

* chore(cache): WASM v147 / loader v82, after #3060's v146 / v81

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 27, 2026
model_stray_cr_lines parsed the input a second time with each stray \r read
as a blank, and was the last user of BcLexer, the recovery model's port of
beancount's lexer. The error oracle already reads beancount's own tokens, a
stray \r among them as a blank, and a comment already runs through a stray
\r as beancount's does (#3060), so the second parse hid nothing more: the
rest of cst/recovery.rs goes.

Parity unchanged: 122,378 of 123,394 inputs match beancount 3.2.3, none
lost; BOM matrix and corpus baselines unchanged.

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

* refactor(parser): retire quiet_bison_recovery for the error oracle

The hand-modeled copy of bison's recovery (quiet_bison_recovery, its
phantom re-parses and accepts()) no longer runs; the oracle's trace of
beancount's own parse decides which lines its recovery keeps quiet:

- a line beancount discards whole (it reads no token there) keeps none of
  rledger's errors, builder checks included; so does a tokenless tail read
  while recovering;
- entries beancount's recovery starts mid-line carry its verdict on their
  lines, built or dropped, with the builder errors of the built ones (parsed
  once on their own) and the pipe warnings of the dropped ones;
- rledger's own errors on a line beancount reports (a stray \r) count
  against that line's slots first;
- a number beancount's lexer rejects is synthesized as InvalidNumber, and
  synthesized messages quote tokens as rledger's own do.

Parity: 122,378 of 123,394 inputs match beancount 3.2.3 where 120,099 did,
none lost; BOM matrix unchanged at 13,349 rows. The linear-time test of the
deleted pass is ported to the oracle path. WASM cache v149.

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

* refactor(parser): delete cst/recovery.rs

model_stray_cr_lines parsed the input a second time with each stray \r read
as a blank, and was the last user of BcLexer, the recovery model's port of
beancount's lexer. The error oracle already reads beancount's own tokens, a
stray \r among them as a blank, and a comment already runs through a stray
\r as beancount's does (#3060), so the second parse hid nothing more: the
rest of cst/recovery.rs goes.

Parity unchanged: 122,378 of 123,394 inputs match beancount 3.2.3, none
lost; BOM matrix and corpus baselines unchanged.

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

* refactor(parser): delete quiet_after_failed_line_starts

The windows convert.rs kept quiet after a line a BOM starts, or a column-0
dated line that opens no directive, are beancount's recovery windows, which
the error oracle now replays from its own grammar. Removing the pass changes
no error count on any parity input (122,376 of 123,394 still match, none
lost); the BOM matrix and corpus baselines are unchanged. Its linear-time
counter test goes with it, its shapes ported to the oracle's.

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.

1 participant