Skip to content

fix(parser): report stray characters in directive header lines - #2805

Merged
robcohen merged 5 commits into
mainfrom
fix/parser-reports-stray-chars-in-directives
Oct 29, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/parser-reports-stray-chars-in-directives

Conversation

@robcohen

@robcohen robcohen commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

What changed

Stage 1 of #2802: a stray character on a non-transaction directive's header line is now a parse error, as it is in beancount. Before this PR, rledger accepted it without a word, and rledger format then deleted it.

input before now
2024-01-01 open! Assets:A no errors; format deletes the ! unexpected "!" in the open directive: expected an account
2024-01-01 open Assets:A USD @ no errors; format deletes the @ error at the @
2024-01-01 price HOOL ? 10 USD no errors; format deletes the ? error at the ?
2024-01-01 open Assets:A U*SD no errors; loaded as the currency list U,SD error at the U
2024-01-01 close! Assets:A format deletes the ! error at the !
2024-01-01 commodity /6J no errors; loaded as the commodity J the commodity /6J, as in beancount
2024-01-01 price HOOL 10 /6J no errors; loaded as 10 / 6 in J, formatted 10 / 6 J 10 /6J

Cause. The CST parser groups a header line into flat tokens, and each convert_* reads the fields it needs and ignores the rest.

Fix. A new module, cst/directive_header.rs, holds one small recognizer per directive, taken from beancount 3.2.3's grammar.y. It covers open, close, commodity, pad, balance, price, event, query, note, document, custom, option, include, plugin, pushtag/poptag and pushmeta/popmeta.

  • Where it runs. It runs from the shared directive loop in parse_via_cst_inner. The non-transaction converters are shared by the green and red paths (only transactions have a green fast path), so no green mirror is needed and the two paths cannot diverge.
  • One error per problem. It reports only the first problem on a line, and it skips any directive that already has an error on its header line, from the converter or from the tree walks. So a problem is never reported twice.
  • Kept, not dropped. The error is reported but the directive is kept, as reject_tags_and_links keeps one ([Bug]: open accepts a trailing tag or link that beancount rejects (and that close rejects) #1949), so one stray character does not cascade into unopened-account errors.
  • Formatting. rledger format refuses the file. The error-tolerant formatter copies the directive verbatim (fix(format): keep unparsable text inside a directive in the error-tolerant formatter #2801).
  • Cost. The check walks the GREEN children (no red-node allocation) into one token buffer reused across directives, and the recognizer reads that slice in place. Release-build parse on 400k price and balance lines (the worst case, every directive checked), best of 7: main 542.7 ms; the first version of this PR 612.0 ms (+12.8%); now 558.6 to 572.1 ms across three runs (+3 to +5%). Transaction-heavy ledgers pay almost nothing, since transactions are not checked here.

Following beancount exactly

The rule for this PR is to match beancount's accept/reject verdict unless that would cause a correctness problem. Error positions and messages may differ. That rule decided the following. The comma and the /-currency rows make rledger accept what beancount accepts; the rest are stricter than before, and all are beancount's behavior:

  • A /-currency may have a digit right after the slash. beancount's lexer rule is \/[A-Z0-9'._-]*[A-Z]([A-Z0-9'._-]*[A-Z0-9])?, and its own comment uses /6J (a futures symbol). Ours required a letter first, so /6J lexed as /, 6, J: price /6J 10 USD loaded as a price of J, and price HOOL 10 /6J, balance Assets:A 1 /6J and custom "b" 1 /6J loaded clean as 10 / 6 in J. The lexer now uses beancount's regex for the / form (logos_lexer.rs); longest match decides between it and Slash exactly as flex does, so 10 /6J is an amount and 10/4 is still a division. is_valid_currency runs the lexer, so it follows. Fuzz check: all 42,083 inputs of the fuzz-corpus branch (fuzz_parse, fuzz_green_eq_red, fuzz_parse_line) replay clean through the lossless and green==red invariants and format_source, and format_source is idempotent on every one of them; both corpus baselines are unchanged by the lexer change.
  • A plain currency must end with a letter or digit. beancount's rule is [A-Z][A-Z0-9'._-]*[A-Z0-9] or one capital letter; ours was [A-Z][A-Z0-9'._-]*, so commodity CAC_, price HOOL_ 10 USD (and HOOL', HOOL.), price HOOL 10 CAC-, open Assets:A USD_,EUR and a posting Assets:A 1 CAC_ loaded clean, while bean-check reports Invalid token or unexpected MINUS. The lexer now uses beancount's rule for both currency forms; the trailing character is left over and is an error, matching bean-check on every case. Inner punctuation is unchanged (NT.TO, BRK-B, TLT_040921C144, USD.5), and quotes in strings are not affected. is_valid_currency runs the lexer, so its callers (CSV importer, rledger price, rledger extract) now refuse such a currency instead of writing one bean-check rejects.
  • A token left over after a posting's amount is an error. Ending a currency at its last letter or digit made 1 USD- lex as USD then -, and the posting converter reads only its amount, cost and price, so Assets:A 1 USD- loaded clean as 1 USD and rledger format wrote that back (main reported E3001, currency USD-). A flat token after a posting's AMOUNT, COST_SPEC or PRICE_ANNOTATION is now reported (unexpected "-" after the posting amount: a currency cannot end in `-`), matching bean-check's unexpected MINUS on 1 USD-, 1 HOOL @ 2 USD-, 1 HOOL @@ 2 USD-, {2 USD} @ 3 USD-, -1 USD-, 1 USD--, 1 USD- ; c, 1 USD+, and the spaced 1 USD - and 1 USD * that main already accepted silently. It runs from the shared loop over green children, so green and red agree; comment kinds on posting lines stay stage 3. Over the stage-3 matrix rows it adds no false error (the same 31 rows as on main); stage-3 misses go from 743 on main to 594.
  • A character glued to the end of a currency is named. commodity CAC_ reports unexpected `_` after the currency `CAC`: a currency cannot end in `_` instead of unexpected input.
  • One leading comma in an open currency list is valid, because currency_list COMMA currency reduces from %empty: open Assets:A , USD,EUR. rledger already accepted it, but rledger format deleted the comma. The formatter now keeps it, emitted as ,USD,EUR. Two leading commas are an error.
  • Only ; starts a comment in the middle of a line. beancount lexes % as a FLAG token, and #! / #+ as HASH followed by a flag or PLUS. Our lexer reads all three as a comment to the end of the line, which silently commented out the rest of the header (open Assets:A % USD). After a header's first token they are now reported. Column-0 %, #! and #+ lines are unchanged.
  • A one-letter currency must be followed by whitespace. beancount lexes a lone capital letter as a currency only before whitespace ([A-Z]/[ \t\n]), so U,SD and V, USD are invalid tokens there.
  • A custom value cannot be NULL. custom_value has no NONE.
  • Changed deliberate leniency (A balance tolerance silently ignores a second number: ~ 0.001 0.02 USD uses 0.001 #2193). balance Assets:A 1.00 USD ~ 0.01 USD, 0.25 + 0.75 USD ~ 0.01 USD and 1.00 USD ~ 0.01 were accepted on purpose. Each has one reading, but no correctness reason requires accepting them, and beancount rejects them, so they are now syntax errors. The directive is kept with its one reading.
    • Updated to match: docs/reference/compatibility.md section 6 and its pinned test, balance_tolerance_accepts_one_reading_and_diagnoses_none.
    • Consequence 1: rustledger-core's directive formatter wrote tolerances as 1000.00 USD ~ 0.01, a form neither parser reads. It now writes 1000.00 ~ 0.01 USD. This is the text behind canonicalize_directives, so rledger add / extract, BQL PRINT and FFI format.entry were writing it. Display for Balance and the fuzz_parse_line generator also moved to beancount's form.
    • Consequence 2: the balance_with_arithmetic_and_tolerance idempotence fixture now uses beancount's spelling.
    • The spec showed the old form too: spec/impl/decimals.md, spec/project/glossary.md, and spec/core/syntax.md (now Number ~ Tolerance Currency).

Within the matrix, no other header-line disagreement with beancount remains. Misplaced thousands separators (price HOOL 1,23,4.50 USD) were already an error here, and beancount rejects them too (Invalid number format).

The matrix

scripts/stray-char-matrix.py runs beancount 3.2.3 in the compat container.

  • Inputs. For 26 snippets covering every directive kind (five of them with /-currencies such as /6J and /6E_X), it inserts each of ! @ ? * ~ ^ $ & | { } ( ) , # % " / _ - ' . plus a letter A and a digit 0 at every byte offset, bare and, after a space, followed by a space. That gives 23,160 inputs. Each is parsed in a forked child, because beancount's C parser segfaults on some of them (1./00, a division by zero); a crash is no verdict and is excluded.
  • Output. It records beancount's verdict for each input in crates/rustledger-parser/tests/data/stray_char_matrix.tsv (about 24 KB, one expectation character per case).
  • The test. crates/rustledger-parser/tests/stray_char_matrix.rs regenerates the same inputs, so it needs no Python, and checks rledger against every verdict.

Stage-1 rows: 17,895 header-line cases. 789 rows are excluded (681 of them stage-1 rows), where beancount crashed or rejected an option name or an account name (AAssets:A, A-ssets:A). rledger rejects an unknown option name at load time (E7001), and an invalid account name in most directives, but NOT in a custom value: 2024-01-01 custom "budget" AAssets:A "x" 10 USD TRUE (also A-ssets:A, Assets0:A; 19 rows) gives "No errors found" in rledger while beancount reports Invalid account name. That is a separate gap, tracked outside this PR.

main this PR
verdict differs from beancount (either direction) 3,557 of 17,709 0
known: column-0 ! ? & lines beancount ignores (#2779) 60 60, pinned by count
known: a digit added to the leading date (02024-01-01, 2024-001-01), which beancount's [0-9]{4,}[-/][0-9]+[-/][0-9]+ accepts and our date lexer does not 126 126, pinned by count (a date-lexing difference, not a stray header token; follow-up)
clean in both, but rledger format loses text yes (open! ..., leading comma) 0

All stages, counted the same way: every non-excluded row of the current matrix, compared with beancount's verdict. A miss is a row beancount rejects and rledger accepts; a false error is the reverse.

stage (rows) misses, main / this PR false errors, main / this PR
1: header lines (17,895) 3,527 / 0 216 / 186 (the 60 #2779 rows and the 126 date rows, all pinned)
2: metadata lines (216) 72 / 72 3 / 3
3: transactions and postings (4,260) 743 / 594 31 / 31 (the same rows)

Only stage 1 is checked by the test; stages 2 and 3 are generated for the later PRs. The stage-3 misses drop because of the posting-amount check below.

Found, left for stage 3

Checked against bean-check 3.2.3 and rledger on this branch (all also on main):

  • %, #! or #+ after a posting amount ( Assets:A 1 USD % c): beancount reports a syntax error; rledger reads a comment.
  • {*} and {1 USD, *}: beancount reports Cost merging is not supported yet; rledger parses them.
  • Two cost specs or two prices on one posting (1 HOOL {1 USD} {2 USD}, 1 HOOL @ 2 USD @ 3 USD): beancount reports a syntax error; rledger parses them, and rledger format drops the second one, so text is lost.
  • A flag glued to the account ( !Assets:A 1 USD): beancount ACCEPTS it, and rledger reports unexpected input, a false error (the spaced ! Assets:A 1 USD is accepted by both).

Fixed during review

  • format_source was not idempotent on a bare pushtag, poptag, pushmeta, popmeta, option, include or plugin at the end of a file with no newline (pushtag formatted to pushtag , then to pushtag). The missing-token error had an empty span at the very end, which overlaps no directive, so the directive was rebuilt instead of copied. A defect at the end of a line now points at the last token on it.
  • Naming a currency tail sliced inside a multibyte character before the currency and panicked on fuzz-corpus inputs. Fixed, pinned by a test, and the input is in-tree at fuzz/regressions/fuzz_parse/currency-tail-multibyte-2802.

Corpus baselines

Three parser-corpus.manifest rows move, all with unchanged source hashes. Each is a new error that beancount also reports:

file line beancount 3.2.3
parser-lima/examples_data_error-duplicates.beancount open Expenses:Technology NZD NZD GBP unexpected CURRENCY, expecting end of file or EOL
parser-lima/examples_data_error-parse.beancount open Assets:Bank:Current*, open Expenses:Groceries! unexpected ASTERISK / unexpected FLAG
parser-lima/test-cases_ParserEntryTypes.BalanceWithCost.beancount balance ... 10 MSFT {45.30 USD} unexpected LCURL

The CST manifest does not move.

Caches

Parse output changes, so the cache versions are bumped:

  • loader CACHE_VERSION 49 to 50;
  • WASM CACHE_VERSION 64 to 65;
  • LOADER_CACHE_VERSION_PIN to 50;
  • both FIXTURE_VERSIONs to 50.

No archived layout moves.

Decisions (the user's)

How to test

cargo test -p rustledger-parser --test stray_char_matrix
STRICT_BASELINE=1 cargo test -p rustledger-parser --test corpus_baseline --test cst_baseline   # needs the compat corpus

The matrix tests in stray_char_matrix.rs fail on main, for example:

  • the matrix test: 3,557 of 17,709 cases disagree;
  • the matrix format test: open! ... loses the !;
  • the property test: its minimal failing input is option "title"! "T".
  • the /6J test (it also fails with only the lexer change reverted).
  • the trailing-punctuation test, which also fails with only the plain-currency rule reverted (35 matrix cases then disagree).

To regenerate the expectations: podman run --rm -i --userns=keep-id -v "$PWD:$PWD:Z" --workdir "$PWD" rustledger-compat:latest python3 -I scripts/stray-char-matrix.py > crates/rustledger-parser/tests/data/stray_char_matrix.tsv

Part of #2802 (stage 1 of 3).

🤖 Generated with Claude Code

Each non-transaction converter read the fields it wanted from the header
line and ignored the rest, so `2024-01-01 open! Assets:A` loaded clean and
`rledger format` deleted the `!`, and `open Assets:A U*SD` loaded as the
currency list `U,SD`. A new `cst::directive_header` module checks each
header line against beancount 3.2.3's grammar (one recognizer per
directive, from grammar.y) from the shared directive loop, so the green
and red paths cannot diverge. The error is reported and the directive is
kept, as for a tag on an `open` (#1949).

Matching beancount's accept/reject verdict exactly also means: one leading
comma in a currency list is valid (and `rledger format` now keeps it);
only `;` starts a comment mid-line; a one-letter currency must be followed
by whitespace; a custom value cannot be NULL; and the balance spellings
`1.00 USD ~ 0.01 USD` / `1.00 USD ~ 0.01` (accepted on purpose by #2193)
are syntax errors. rustledger-core's formatter and `Display for Balance`
now write a tolerance as `1.00 ~ 0.01 USD`, the form both parsers read.

scripts/stray-char-matrix.py records beancount's verdict on 13,498
single-character insertions; tests/stray_char_matrix.rs checks rledger
against the 9,897 header-line cases without Python: 2,143 disagreed on
main, none now. Three parser-corpus baseline rows move, each a new error
beancount also reports. Loader cache v50, WASM cache v65.

Part of #2802 (stage 1 of 3).

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

codecov Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.19639% with 9 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/convert.rs 97.82% 4 Missing ⚠️
...ates/rustledger-parser/src/cst/directive_header.rs 98.93% 3 Missing ⚠️
crates/rustledger-core/src/directive.rs 50.00% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

🔴 Slower than base on: simple

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 32.8ms ± 3.7ms 445.8ms ± 10.1ms 13.6x 34.5 MB / 51.0 MB
investment 46.7ms ± 1.6ms 1608.0ms ± 35.7ms 34.5x 44.6 MB / 59.1 MB
fifo 44.5ms ± 0.6ms 8371.9ms ± 185.7ms 188.2x 40.4 MB / 59.1 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 30.0ms ± 0.7ms 32.8ms ± 3.7ms +9.4% 🟡 slower 34.6 MB → 34.5 MB (-0.4%)
investment 46.3ms ± 1.4ms 46.7ms ± 1.6ms +0.9% ✅ within noise 44.7 MB → 44.6 MB (-0.2%)
fifo 46.4ms ± 3.0ms 44.5ms ± 0.6ms -4.2% ✅ within noise 40.5 MB → 40.4 MB (-0.1%)

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

Review of the first commit. The lexer required a letter right after the
slash, so `/6J` (a futures symbol, beancount's own example) lexed as `/`,
`6`, `J`: `price HOOL 10 /6J` loaded clean as `10 / 6` in `J`, and the
header check then rejected `commodity /6J`, which beancount accepts. The
`/` form now uses beancount's regex, and longest match decides it against
`Slash` as flex does (`10/4` stays a division).

The matrix gains five `/`-currency snippets (16,405 cases; 12,849 on
header lines, all matching beancount except 60 column-0 #2779 rows), plus
explicit tests. The header check walks green children into a buffer
reused across directives and reads it as a slice: +3 to +5% on 400k
price/balance lines, down from +12.8%. The spec no longer shows the
`1000 USD ~ 0.01` form, and the CHANGELOG states the #2779 exception and
the cache bumps.

Part of #2802 (stage 1 of 3).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The plain currency form was `[A-Z][A-Z0-9'._-]*`, so `commodity CAC_`,
`price HOOL. 10 USD` or `open Assets:A USD_,EUR` loaded clean while
bean-check rejects them. Both currency alternatives are now beancount's
rules exactly: `[A-Z][A-Z0-9'._-]*[A-Z0-9]` or one capital letter. The
trailing character is left over and is an error, matching bean-check.

The matrix adds `/ _ - ' .`, a letter and a digit to its characters
(23,160 cases) and parses each in a forked child, since beancount
segfaults on `1./00`. Account-name rejections are excluded like option
names (rledger reports both at load). 17,709 header cases match
beancount; 60 column-0 #2779 rows and 126 dates with an extra digit
(beancount's looser DATE rule) are pinned as known divergences.

Part of #2802 (stage 1 of 3).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen and others added 2 commits October 29, 2026 14:06
Review of 66a43b7. Ending a currency at its last letter or digit made
`1 USD-` lex as `USD` then `-`, and the posting converter reads only its
amount, cost and price, so the posting loaded clean as `1 USD` (main
reported the currency `USD-`). A flat token after a posting's AMOUNT,
COST_SPEC or PRICE_ANNOTATION is now an error, matching bean-check's
`unexpected MINUS`. It runs from the shared loop over green children; on
the stage-3 matrix rows it adds no false error and closes 133 misses.

Also: a missing-token header defect points at the last token on the line
instead of an empty span at its end, so a bare `pushtag` at EOF is copied
verbatim and `format_source` is idempotent on it; a character glued to the
end of a currency is named (`a currency cannot end in `_``), without
slicing inside a multibyte character (that panicked on fuzz-corpus input,
now in-tree under fuzz/regressions).

Part of #2802 (stage 1 of 3).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of 3812321. The posting check said "a currency cannot end in
X" for any token touching the end of an amount (`1-`, `{1 USD}-`,
`1 USD+`, `1 USD)`); it now does so only when the amount ends in a
CURRENCY and the stray character is one a currency may hold inside it.
The currency-tail message falls back to the generic one when the word is
glued to a non-ASCII character (`ÜSD_` named `SD`).

Part of #2802 (stage 1 of 3).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) October 29, 2026 19:46
@robcohen
robcohen merged commit 8013f04 into main Oct 29, 2026
68 of 69 checks passed
@robcohen
robcohen deleted the fix/parser-reports-stray-chars-in-directives branch October 29, 2026 19:47
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