Repository navigation
fix(format): never change what a file means; round-trip properties for the formatter - #3060
Merged
Merged
Conversation
Contributor
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
robcohen
force-pushed
the
test/formatter-roundtrip-properties
branch
from
November 27, 2026 07:59
a0f8d6e to
8b36f5e
Compare
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
Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen
force-pushed
the
test/formatter-roundtrip-properties
branch
from
November 27, 2026 09:15
8b36f5e to
b9a0441
Compare
robcohen
added a commit
that referenced
this pull request
Nov 27, 2026
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:format(format(x)) == format(x).Debugwith spans stripped, notPartialEq, becauseDecimal's==ignores scale (1.5 == 1.50). Comment values are compared without trailing blanks, which the canonical form trims.try_format_source(the CLI's entry) refuses exactly the broken inputs and otherwise agrees withformat_sourcebyte 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.rsformat_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_CASESoverrides); 30k cases ran clean locally.tests/, theformat_compatfixtures, and every committed fuzz regression input.explore_dir(ignored) for a local sweep of any directory.fuzz_format_roundtrip, registered infuzz.yml.fuzz.ymlseeds it withfuzz_parse's corpus from thefuzz-corpusbranch (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):textDocument/formattingequals the CLI's output, with CRLF re-injected on a CRLF document (the LSP's documented difference); whole-documentrangeFormattingequals it too; and range formatting of any line or line pair changes nothing outside the selection and converges on the canonical form.Bugs found and fixed
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, soopen Assets:A ;c \rmorelost\rmore, and#!\rquturned into an error line.format_sourcefolded a bare\rinto a line break. The lexer does not end a line there. As a result,; c\r2024-01-01 open Assets:Agrew 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 fixesformat_sourcedisagreeing withformat_source_with_parsed/CLI on clean files with a\rin a comment.A second BOM was dropped one per pass.
format_sourcestripped the leading BOM and the parser then took the second for the leading one, and the top-level walk skippedBOMtokens. Formatting was not idempotent.Unicode whitespace on a broken line was trimmed (
str::trim_end), deleting the error. This covers NBSP, vertical tab and the like.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 Eafter a failed line becameinclude, and aplugin {line lost itsname: ...body (found in the lima fixtures).ParseResultnow carries the pre-quieting spans (crate-privatedefect_spans, with a#[doc(hidden)]accessor for the oracle).Normalizing a broken line repaired it. A lone capital before a
\ris beancount's invalid token (CAPITALneeds a space, a tab or a\nafter it), soopen Assets:As,A\r\nis an error andopen Assets:As,A\na valid open (verified with bean-check). Folding the CRLF, dropping a stray\r(R\r\t\n), or adding the final newline after...Tat 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.A reported, indented comment line was dedented (e.g.
\t;after aninclude), which removed the error.LSP surface cleanup rewrote multi-line strings. On a broken file,
textDocument/formattingconverted 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.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
CI follow-ups
fuzz_format_roundtripcorpus replay found\t;\n\t+: a file-leading indented comment was moved to column 0. rledger reads it as a comment (beancount reportsunexpected 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 infuzz/regressions/fuzz_format_roundtrip/and pinned bytest_format_source_keeps_a_leading_indented_comment_indented.ledger_gen::run_property). Verified locally in a debug build withRUST_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.manifestwas regenerated with--update(beancount 3.2.3, ptadiff at the pinned rev);--checkreports 0 regressions. One regression showed up on the way:T;cis 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-13Tat the end of a file after a clean line parses clean in rledger, where bean-check reportsInvalid 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.\routside a comment is an error in rledger and a blank in beancount) was justified by the formatter folding such a\rinto a line break. The formatter no longer does that, so the deviation could now be revisited; the docs say so.🤖 Generated with Claude Code