Skip to content

fix(parser): report stray characters in transactions and postings - #2817

Merged
robcohen merged 4 commits into
mainfrom
fix/parser-reports-stray-chars-in-transactions
Nov 2, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/parser-reports-stray-chars-in-transactions

Conversation

@robcohen

@robcohen robcohen commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Stage 3 of 3 of #2802: stray characters in transaction headers and posting lines.

What changed

  • Posting lines are checked against beancount's posting rule (optflag account incomplete_amount cost_spec [@|@@ price]), as one recognizer next to the header and metadata ones in cst/directive_header.rs (first_posting_defect). It replaces stage 1's narrower leftover-token check. A token with no place in a posting (Assets:A ! 1 USD, 1 USD % x, {1 USD} {2 USD}, @ 2 USD @ 3 USD, {2 & USD}, {#2 USD}) used to be dropped and then deleted by rledger format; it is now an error. The transaction is kept, as for a header line (fix(parser): report stray characters in directive header lines #2805).
  • Transaction header: one flag only (txn is one token in beancount); 2024-01-01 * * "x", !*, * A "x" were accepted.
  • %, #! and #+ that are indented or mid-line anywhere in a transaction are errors (only ; starts a comment there in beancount). Before, they silently commented out the rest of the line. At column 0 they are still comments.
  • Builder errors beancount reports at parse time: a duplicate cost, date or label in a cost spec ({2, USD} is two costs), a # inside {{ }}, a negative price (evaluated by the shared parse_arith_expr), and @@ on a posting with no number for its units.
  • Now accepted, as in beancount:
    • a flag glued to its account ( !Assets:A 1 USD), a CST parser change;
    • stacked signs (--1 USD = 1, 2 * - 3 USD = -6). The AMOUNT emitter takes any run of signs, and both the red Amount::is_arithmetic and the green simple_amount route stacked signs to the evaluator, so --1 is not read as -1;
    • one leading comma in a cost spec ({, 2 USD}), in cost_spec_shape.rs.
  • % is a flag outside column 0, as in beancount (its FLAG set is [!&#?%]): % Assets:A 1 USD and %Assets:A are flagged postings and 2024-01-01 % "x" is a transaction. We lexed % as a comment to the end of the line, so the posting was dropped in silence. The lexer now emits a one-character FLAG for a % that is not at column 0 (a column-0 % line is still a comment), and the formatter's source classifier (pinned by its drift guard and a new fixture) and the LSP's rledger.alignAmounts agree. This applies everywhere, not only in transactions: an indented or mid-line % comment under any directive, in metadata or at top level is now an error, as in beancount ("unexpected FLAG"); no corpus, in-tree or doc file has one.
  • One-letter currency or transaction flag before \r, or glued to what follows (2024-01-01 P;c), is an error on any line, as beancount's [A-Z]/[ \t\n].
  • Split dates (compat(parser): dates with extra digits (02024-01-01, 2024-001-01) are rejected; beancount accepts them #2808) in posting, cost and price amounts are reported, as stage 2 does for metadata (2024-002-02 USD loaded as 2020 USD).

Deviations and decisions (please review)

  1. Cost merging ({*}) is accepted, by decision. beancount 3.2.3 rejects it ("Cost merging is not supported yet"); rledger implements it (average-cost merge booking). Decided: rledger keeps correct features beancount lacks; the rule is to match beancount on correctness, not on missing features. Documented at posting_builder_error, pinned by test_parse_accepts_cost_merging_unlike_beancount and 1 matrix row.
  2. Cost and price in different currencies are not reported at parse time. beancount's builder rejects them for any posting. rledger already reports them at booking for a sale (E4001, CostPriceCurrencyMismatch, with the reason), and a parse-time check reported every such sale twice (P0012 plus E4001). So this PR keeps main's behavior: a sale gets E4001, and a buy with mismatched currencies still loads. It is pinned by test_parse_leaves_a_cost_and_price_currency_mismatch_to_booking and 64 matrix rows. Decision pending: move the rule to parse time only, or leave it at booking. This PR does not change it.
  3. A one-letter currency at the very end of a file with no final newline is accepted, though beancount rejects it. Correctness reason: rledger format adds that newline, after which beancount accepts the file too, so reporting it made formatting non-idempotent (found by the fuzz-corpus replay). Documented at glued_one_letter_currency and pinned by a test.

The keep-the-transaction policy and one-flag-only are the decisions you made for #2802.

Matrix (scripts/stray-char-matrix.py, beancount 3.2.3)

18 transaction snippets were added: every transaction flag form, every posting flag spaced and glued (cases() never inserts at a posting's first character, so the flag position has bases of its own), expressions, every cost-spec shape, prices, a posting with no amount, trailing comments, an indented tags line, and CRLF. One counting rule throughout: a miss is a case beancount rejects and rledger accepts; a false error is the reverse; every non-excluded row counts.

stage checked cases misses, main / this PR false errors, main / this PR
1: header lines 30,435 0 / 0 320 / 320 (#2779, #2808, mid-line \r)
2: metadata lines 6,148 0 / 0 66 / 66 (#2779, deliberate dates)
3: transactions and postings 28,335 3,618 / 65 442 / 251

The stage-3 rows left on this branch are all pinned by count in tests/stray_char_matrix.rs:

Every stage is checked now; none is unchecked.

Verification

  • Matrix test: tests/stray_char_matrix.rs passes (29 tests). Copied onto main, the stage-3 tests fail.

  • Test suites: cargo test for parser, core, loader, rledger, lsp, booking, query and wasm (--all-features): 210 result lines, 0 failed. Also clean: cargo clippy -D warnings (parser, rledger, lsp, loader, wasm), RUSTDOCFLAGS=-Dwarnings cargo doc --document-private-items, cargo fmt --check, and cargo check -p rustledger-wasm.

  • Corpus baselines: STRICT_BASELINE=1 corpus_baseline and cst_baseline pass on the 732-file corpus. 7 rows of parser-corpus.manifest moved, all with unchanged source. Each now reports errors on exactly the lines beancount does (checked file by file):

    • LexerErrorsInPostings (lines 17, 23, 29: unexpected RPAREN)
    • CostEmptyComponents
    • CostRepeated, CostRepeatedDate, CostRepeatedLabel
    • PriceNegative, TotalPriceInverted

    The CST baseline did not move.

  • False-error sweep: 662 more files (382 in-tree .beancount/.bean and 280 doc code blocks), main vs this PR vs beancount. No line errors on this PR that main accepted and beancount accepts. 8 files changed, and each now matches beancount exactly; all 8 are lima fixtures main under-reported.

  • Fuzz: all 42,587 UTF-8 inputs on origin/fuzz-corpus (fuzz_parse, fuzz_green_eq_red, fuzz_parse_line) pass lossless and green == red (errors and directives), and format_source is idempotent on all of them in my replay. An independent review's harness found 2 inputs (a run of BOMs, a \v input) that are not idempotent; they fail identically on main, so they are pre-existing, not from this PR. The in-tree fuzz regressions pass.

  • Perf: release parse, best of 20 per run, main and branch binaries alternated 12 times, pinned to one core (taskset -c 2), medians: the 913 KB fava_investor_examples_huge-example.beancount 8.84 ms on main vs 9.29 ms (+5.0%); a 2.6 MB posting-heavy synthetic ledger (16,000 transactions, each posting with a cost and a price) 49.32 ms vs 52.35 ms (+6.1%). Before this round's fixes the same method measured +28% and +19%: the indented-comment check built red nodes for every transaction, and the builder check allocated per posting.

  • Cache: loader v53, WASM v68, pin and both fixture versions 53.

Test changes worth a look

  • Stage-1 test wording: a leftover token that is not glued to a currency now reports unexpected X in a posting. The glued case still says "a currency cannot end in".
  • fix(format): keep #! and #+ lines that follow a directive #2792 tests (format_keeps_hash_bang_lines.rs): indented #!/#+ lines in a transaction and after a posting amount are errors now (beancount: unexpected FLAG/HASH). The tests assert they are reported and that the error-tolerant formatter keeps them verbatim. The open metadata-block case is unchanged (deferred, see below).
  • [Bug]: rledger format deletes the currency and price/cost annotation when a posting's units number is missing #2142 formatter test: the two @@-without-units cases are errors now (beancount: "Total price on a posting without units"), so the error-tolerant formatter copies them verbatim.
  • Lima fixtures: TotalPriceInverted, TotalPriceWithMissing, PriceNegative and CostRepeated* now expect a parse error, as beancount gives.
  • Generators: green_red_properties keeps prices non-negative and gives a posting's cost and price one currency, weighting the error shapes ({*}, a negative difference) down so at least 25% of ledgers stay clean. pipeline_invariants generates non-negative prices.

Found, not fixed (follow-ups)

Closes #2802

🤖 Generated with Claude Code

Closes #2802 (stage 3 of 3)

Each posting line is checked against beancount's posting rule, a
transaction has one flag, and a %, #! or #+ that is indented or mid-line
inside a transaction is an error. The parse-time errors beancount's
builder reports on postings are reported too (duplicate cost, date or
label; # inside {{ }}; negative price; @@ without units). What beancount
accepts and we did not now parses: a flag glued to its account, stacked
signs (--1 USD is 1 USD), one leading comma in a cost spec. Cost merging
({*}) and cost/price currency mismatch are deliberately left as they were
(see the PR). Loader cache v53, WASM cache v68.

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

codecov Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.60835% with 7 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/convert.rs 97.65% 6 Missing ⚠️
...ates/rustledger-parser/src/cst/directive_header.rs 99.10% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

🔴 Slower than base on: simple, investment, fifo

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 33.5ms ± 6.7ms 383.7ms ± 0.7ms 11.4x 33.5 MB / 51.0 MB
investment 45.8ms ± 0.5ms 1467.9ms ± 2.6ms 32.1x 44.5 MB / 59.0 MB
fifo 44.3ms ± 2.0ms 7762.4ms ± 77.4ms 175.3x 40.5 MB / 59.1 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 28.9ms ± 0.6ms 33.5ms ± 6.7ms +16.0% 🔴 regression 34.9 MB → 33.5 MB (-4.0%)
investment 43.5ms ± 0.7ms 45.8ms ± 0.5ms +5.1% 🟡 slower 44.5 MB → 44.5 MB (-0.0%)
fifo 41.8ms ± 0.2ms 44.3ms ± 2.0ms +6.0% 🟡 slower 40.5 MB → 40.5 MB (+0.0%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 3.0ms, investment 0.4ms, fifo 0.9ms), 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 3 commits November 1, 2026 16:31
beancount lexes % as a FLAG anywhere but a column-0 line, so `  % Assets:A
1 USD` is a flagged posting and `2024-01-01 % "x"` a transaction there; we
lexed it as a comment to the end of the line, dropping the posting. The
lexer now emits a one-character flag for a % that is not at column 0, and
the formatter's source classifier agrees. The matrix gained posting- and
transaction-flag snippets (cases() never inserts at a posting's first
character).

Also: a one-letter transaction flag glued to what follows (`P;c`, `P\r\n`)
is an error, as for a one-letter currency; the indented-comment check
skips a transaction with a byte search instead of walking it, and the
builder check no longer allocates per posting; the v53 cache note no
longer claims {*} and currency mismatches are parse errors; {*} is kept
as a correct feature beancount lacks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The formatter's source-state drift guard now classifies PercentComment
tokens too, with an idempotence fixture that mixes a column-0 % comment
and % posting and transaction flags. rledger.alignAmounts treats an
indented % as a posting flag, as the lexer does. An indented % now gets
its Indent token on the AST path (the rewrite happens before the arms that
synthesize it), and the dead PERCENT_COMMENT arms are gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The file (source hash unchanged) now gets beancount's parse error for a
`@@` total price on a posting with no units (beancount: "Total price on a
posting without units"). The row was missing from the local corpus copy,
so the local strict run did not see it; CI did.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit d34af0e into main Nov 2, 2026
65 of 66 checks passed
@robcohen
robcohen deleted the fix/parser-reports-stray-chars-in-transactions branch November 2, 2026 02:46
robcohen added a commit that referenced this pull request Nov 5, 2026
…te on its line (#2868)

* fix(parser): read a date as beancount does, and name every invalid date on its line

beancount's DATE is [0-9]{4,}[-/][0-9]+[-/][0-9]+ with the fields read as
integers, so 02024-01-01, 2024-001-01 and 2024-01-016 are dates there. Our
lexer took \d{4}[-/]\d{1,2}[-/]\d{1,2}: such a header date was an error,
and a value was split into a number expression that #2810/#2817 reported
as a stopgap. The lexer now takes beancount's shape, and one rule,
parse_date_token (via diagnostics::date_fields), decides whether the fields
form a real date (years 1 to 9999). The split-date stopgap
(split_beancount_date, the pushmeta exemption, the 440 pinned matrix rows)
is gone: those rows now match beancount and are checked.

An invalid date is now reported wherever it stands, as beancount reports
it while lexing, and stands for its line (report_invalid_dates, one pass
over the green tree): event, price, transaction header, option, plugin and
orphan lines name the date instead of a generic syntax error; two bad
dates on one line are two errors; bad value dates under a directive with a
bad date of its own are reported too. FFI input dates go through the same
rule (rustledger_parser::parse_date), so year 0 is refused there and an
invalid cost date is an error instead of an undated lot.

Checked against bean-check 3.2.3 on 147 probe files (15 date shapes in 8
positions, the #2856 shapes, header dates): the same lines get parse
errors, with the same counts. No compatibility-corpus or in-tree ledger
changes (1,113 files); strict corpus baselines unchanged; the fuzz corpus
replays clean (45,973 inputs, same 3 pre-existing idempotence cases as
main); about 0.6% more instructions on the 913 KB example ledger.

Loader cache v57, WASM cache v73.

Closes #2808
Closes #2856

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

* fix(parser): keep lexer errors on a bad-date line, linear date pass, ASCII date digits

Review follow-ups on the date rework:

- report_invalid_dates is linear: dates sorted, line bounds from one
  forward pass, errors matched by binary search; counter-based test.
- Diagnostic columns are found through a character-mark table, so many
  errors on one long line no longer make check --format json quadratic.
- A bad date drops only its line's grammar errors; an error covering an
  ERROR_TOKEN (stray character, mid-file BOM) stands, as in beancount. A
  date inside a beancount invalid-token run is not named.
- parse_date takes only text the lexer reads as one DATE token, so
  24-01-15 and 1-1-1 are refused; new leading_date_len shares the rule.
- The DATE regex uses ASCII [0-9], as beancount does.
- An out-of-range date field is named as written, not saturated.
- Completion recognizes every header date shape via leading_date_len.

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

* chore: regenerate cargo-vet exemptions

* fix(parser): keep a grammar error that comes before an invalid date

Review round 2 on the date rework:

- A bad date now drops only the grammar errors it causes: those that start
  at or after the line's first bad date, or a dropped directive's
  whole-node error when the header grammar fails at or after the date.
  An error before the date stands, as in beancount
  (`balance Assets:A USD 2024-02-30`, `note Assets:A 5 2024-02-30`).
- rustledger-completion re-exports rustledger_core::ACCOUNT_TYPES instead
  of keeping a copy; the LSP drift test for the copy is gone.
- parse_date's not-a-date error no longer repeats the input, so the FFI
  message names it once.

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

* fix(parser): place a dropped directive's error by its header, and keep an orphan line's earlier error

Review round 3 on the date rework:

- A dropped directive's whole-node error spans the blank and comment lines
  before it, so it was not placed on its bad-date line and was kept beside
  the date. Each dropped directive now records its header start and the
  header grammar's failure point (usize::MAX when there is none).
- A whole-line recovery error (an orphan indented line, a body line no
  posting takes) fails at its first token, or at the indent after a blank
  line, a column-0 comment or the top of the file, as beancount does; an
  error from before the date stands.
- The regression test checks 22 rows directly, after a blank line and
  after a comment line, against bean-check 3.2.3's counts.
- rustledger-completion's ACCOUNT_TYPES keeps its `&[&str]` type.

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

* fix(parser): report a dropped directive's error on its header line, and more indent gaps

Review round 4 on the date rework:

- The whole-node error of a dropped directive now starts at the header,
  not at the blank or comment line its node span takes in, so it is on the
  line bean-check reports.
- An indented line after option, include, plugin, pushtag, poptag,
  pushmeta, popmeta or an org-mode heading is no continuation, so it
  fails at the indent, as in bean-check 3.2.3.
- The regression matrix asserts each error's line as well as the count.

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

* fix(parser): a line inside a multi-line string is never an indent gap

Review round 5 on the date rework:

- previous_line_is_a_gap read raw text, so a multi-line string continuing
  on a line that starts with `*`, `;` or a gap keyword counted as a gap.
  The tree walk now records STRING tokens that run over a line end, and a
  line starting inside one is not a gap.
- `%` and `# ` comment lines are gaps, as in bean-check 3.2.3.
- Test rows for those and for pushtag, poptag, pushmeta and popmeta.

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

* fix(parser): no indent gap after a bare marker, and read a string's line for the gap

Review round 6 on the date rework:

- A column-0 comment is `;` and anything, or `*`, `%` or `#` with at least
  one more character on the line and `#` not starting a tag, as in
  bean-check 3.2.3. A bare marker is a token there, so it is no gap.
- A previous line that starts inside a multi-line string steps back to the
  line the string starts on, and only the no-metadata check applies there,
  so an indented line after a multi-line `option`, `plugin`, `include` or
  `pushmeta` value fails at the indent as in beancount.
- Test rows for both.

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

* fix(parser): a broken no-metadata directive is no indent gap, and `#\r` is a comment

Review round 7 on the date rework:

- A directive that takes no metadata but is itself a syntax error is no
  gap: beancount's recovery from it swallows the indented line after it,
  so it reports no unexpected INDENT there (bean-check 3.2.3).
- `#\r`, `%\r` and `*\r` are comments, as flex's `.` takes the `\r`.
- Test rows for both, including a valid multi-line plugin that still is a
  gap.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: rustledger-bot[bot] <257329324+rustledger-bot[bot]@users.noreply.github.com>
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): stray characters inside a directive parse silently and rledger format deletes them

1 participant