Skip to content

fix(parser): report stray characters in metadata lines - #2810

Merged
robcohen merged 3 commits into
mainfrom
fix/parser-reports-stray-chars-in-metadata
Oct 30, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/parser-reports-stray-chars-in-metadata

Conversation

@robcohen

@robcohen robcohen commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

What changed

Stage 2 of #2802: a stray character on a metadata line (key: value under any directive, a transaction or a posting) is now a parse error, matching beancount 3.2.3.

The metadata converter (meta_value_from_tokens) takes the first value token of each kind and ignores the rest. So these loaded clean on main, and rledger format then deleted the rest of the value:

line main loaded beancount 3.2.3
kk: "v" ! "v" syntax error
kk: 10 USD @ 10 USD syntax error
kk: USD,EUR USD syntax error
kk: Assets:B Assets:C Assets:B syntax error

Each metadata line is now checked against beancount's grammar rule:

key_value_line : INDENT key_value eol
key_value      : KEY COLON key_value_value

pushmeta already followed the same rule, so stage 1's pushmeta code was factored out into key_value_value in cst/directive_header.rs and is now shared. The new entry point is first_meta_defect.

The check (meta_entry_check in cst/convert.rs) runs from the shared directive loop over green children. So the green and red parse paths cannot disagree, and it allocates nothing per directive.

As in stage 1:

  • The directive is kept. Your earlier decision applies: a stray character must not cascade into unopened-account errors.
  • A line that already has an error is not reported again.
  • The error names the line, for example unexpected "!" in a metadata line: expected the end of the line.

Matrix

scripts/stray-char-matrix.py gains 22 metadata snippets, one per value type, each under a parent:

  • value types: string, number, expression, amount, currency, account, date, TRUE, FALSE, tag, NULL, empty, a ; comment, a key with -/_/digits, CRLF, two lines;
  • parents: open, balance, price, custom, note, a transaction and a posting.

That gives 44,616 cases, 1,241 of them excluded. Existing rows are unchanged.

stray_char_matrix.rs now classifies each case by the line the character lands on (stage()) and checks stages 1 and 2. A miss is a row beancount rejects that rledger accepts; a false error is the reverse. Every non-excluded row is counted, with no pins:

stage (rows) misses, main / PR false errors, main / PR
1: header lines (30,435) 0 / 0 320 / 320
2: metadata lines (6,148) 2,501 / 0 60 / 66
3: transactions and postings (6,792) 755 / 755 61 / 61

Everything left in stages 1 and 2 is pinned by count in the test:

The stage-1 false-error count is unchanged in meaning. It grew from #2805's 186 only because the new snippets carry header lines too.

Deviations (AGENTS.md checklist)

Two places where rledger is now stricter than beancount on purpose. In both, our lexer splits a token that beancount reads whole, and on main the pieces loaded as a wrong value with no error. A wrong value is worse than an error.

1. Text beancount reads as one date.

beancount's DATE is [0-9]{4,}[-/][0-9]+[-/][0-9]+ and ours is \d{4}[-/]\d{1,2}[-/]\d{1,2}. Where they differ, our tokens come out glued (no whitespace between them), in one of two shapes. split_beancount_date in cst/directive_header.rs reports both:

  • a DATE with a NUMBER right after it, when the last field has more than two digits: 2024-02-002, 2024/02/002, 2024-2-002, 2024-02-0002;
  • a NUMBER, - or /, NUMBER, - or /, NUMBER run whose first two numbers are plain digits, the first at least four of them: 2024-002-02, 02024-02-02, 2024/002/02, and invalid dates such as 20024-02-02 and 99999-01-01.

In both shapes the last number may run on past the digits (2024-002-02.5, 2024-002-02,000, 2024-02-002.). beancount's DATE takes the leading digits and then rejects the rest, and bean-check rejects all of these.

Where they were silently misread on main, and what happens now:

place example main loaded now
metadata value kk: 2024-002-02 integer 2020 error
metadata value kk: 2024-02-002 integer 2 error
custom value custom "x" 2024-02-002 the number 2 (the invalid date 2024-02-00 is dropped, #2811) error
pushmeta value pushmeta kk: 2024-002-02 integer 2024 (pushmeta keeps the first number, #2812) error
metadata, custom, balance, price, pushmeta kk: 2024-002-02.5, balance Assets:A 2024-002-02,000 USD 2019.5, 22 USD error
balance / price amount balance Assets:A 2024-002-02 USD 2020 USD error

beancount reads a date there (2024-02-02), or rejects an invalid one. So this is a false error where beancount's date is valid, and agreement where it is not. These are still read as before: a spaced expression (2024 - 002 - 02), a thousands separator (1,234-02-02), a short first number (202-002-02), and a decimal in the first two numbers (2024.5-02-02, 2024-0.5-02), which is arithmetic in beancount too. The real fix, lexing these the way beancount does, is #2808.

2. Doubled thousands separators.

beancount's NUMBER is [0-9][0-9,]+[0-9], so kk: 1,,000 is 1000 there. Ours lexes 1, ,, ,, 000, which loaded as the integer 1. The metadata grammar now reports the stray comma. A posting amount (1,,000 USD) and a balance amount already reported it.

Where both are recorded:

  • the comments on split_beancount_date and first_meta_defect;
  • the pinning tests test_parse_reports_a_split_beancount_date_instead_of_misreading_it (15 values in 5 places, plus 7 controls that must still parse) and test_parse_reports_doubled_thousands_separators_instead_of_misreading_them;
  • KNOWN_DATES in the matrix test.

Tests

  • Matrix test: test_parse_reports_a_stray_character_exactly_when_beancount_does checks rledger against beancount for stages 1 and 2. On main it fails.

  • Explicit stray-character test: test_parse_reports_a_stray_character_in_a_metadata_line_and_keeps_the_directive covers 10 shapes, including posting and transaction metadata. For each it checks:

    • the error span;
    • that the message names a metadata line;
    • that the directive is kept;
    • that try_format_source refuses the file;
    • that format_source copies it verbatim.

    On main it fails.

  • Accepted values: test_parse_accepts_every_metadata_value_type checks that every value type beancount accepts still parses, with and without a trailing ; c.

  • Property test: test_try_format_source_keeps_the_text_of_a_clean_metadata_line makes up to three insertions into a metadata value (2,048 cases, fixed seed). For each clean result it checks that rledger format keeps every non-whitespace character.

  • Format-text check: the existing matrix check now allows the formatter's documented thousands-separator normalization, since kk: 2,024-02-02 formats as 2024 - 02 - 02.

How to test

cargo test -p rustledger-parser --test stray_char_matrix
# regenerate the expectations (beancount 3.2.3 in the compat image):
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

Verified locally

  • Test suites: cargo test -p rustledger-parser -p rustledger-core -p rustledger-loader -p rustledger -p rustledger-lsp --all-features, 125 results, 0 failed (rerun after the review fixes).

  • Builds and lints: cargo check -p rustledger-wasm, clippy -D warnings on the parser, loader and wasm crates, rustdoc -Dwarnings with private items, and cargo fmt --check are all clean.

  • Corpus baselines: both strict baselines pass with no row moved, over the 731-file compat corpus.

  • Fuzz corpus: all 42,092 UTF-8 inputs of the fuzz-corpus branch (fuzz_parse, fuzz_green_eq_red, fuzz_parse_line) plus the in-tree regressions pass. Checked for each: lossless round-trip, green==red on directives, errors and currency occurrences, and format_source idempotence. 0 failures.

  • Parse time (release, best of 25, fava_investor_examples_huge-example.beancount, 913 KB):

    • as is: 9.2 to 9.5 ms against 8.9 to 9.3 ms on main;
    • with two metadata lines added to every transaction: 11.9 to 12.0 ms against 11.7 to 11.8 ms on main.

    That is about 2 to 3%. After the review fixes, a rerun against main was within noise: 12.0 vs 11.5 to 12.0 ms, and 15.2 vs 15.0 to 15.1 ms with metadata.

  • Caches: loader v51, WASM v66; the pin and both FIXTURE_VERSIONs are 51.

Found, left for stage 3 or other issues

Part of #2802

🤖 Generated with Claude Code

The metadata converter took the first value token of each kind on a
`key: value` line and ignored the rest, so `kk: "v" !`, `kk: 10 USD @`,
`kk: USD,EUR` and `kk: Assets:B Assets:C` loaded clean and `rledger format`
deleted the rest of the value. Every metadata line, under any directive, a
transaction or a posting, is now checked against beancount's `key_value`
rule (shared with `pushmeta`), from the shared directive loop so the green
and red paths agree. The directive is still kept.

The stray-character matrix gains 22 metadata snippets. Of its 6,148
metadata-line cases, rledger accepted 2,501 that beancount rejects; it now
agrees on all but 68 pinned rows (60 column-0 lines, #2779; 8 date digits,
#2808, of which 3 are deliberately stricter: `kk: 2024-02-002` loaded as
the integer 2). Loader cache v51, WASM cache v66.

Part of #2802 (stage 2 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 20:26
@codecov

codecov Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/convert.rs 98.01% 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

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 47.7ms ± 0.4ms 823.0ms ± 3.2ms 17.3x 34.8 MB / 51.1 MB
investment 72.0ms ± 0.6ms 2974.1ms ± 17.7ms 41.3x 44.6 MB / 59.1 MB
fifo 71.1ms ± 1.0ms 14732.8ms ± 74.3ms 207.3x 40.5 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 46.7ms ± 0.3ms 47.7ms ± 0.4ms +2.0% ✅ within noise 34.6 MB → 34.8 MB (+0.6%)
investment 71.5ms ± 1.5ms 72.0ms ± 0.6ms +0.7% ✅ within noise 44.5 MB → 44.6 MB (+0.1%)
fifo 69.9ms ± 0.9ms 71.1ms ± 1.0ms +1.7% ✅ within noise 40.5 MB → 40.5 MB (-0.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.2ms, investment 0.7ms, fifo 0.6ms), 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 2 commits October 29, 2026 16:01
beancount's DATE is `[0-9]{4,}[-/][0-9]+[-/][0-9]+`, ours
`\d{4}[-/]\d{1,2}[-/]\d{1,2}`. Where they differ our tokens come out glued:
a DATE then a NUMBER (`2024-02-002`, `2024/02/002`, `2024-02-0002`) or a
plain-digit NUMBER, `-`/`/`, NUMBER, `-`/`/`, NUMBER run (`2024-002-02`,
`02024-02-02`, `20024-02-02`). Read our way they loaded as a wrong number
with no error in a metadata value, a custom or pushmeta value, and a
balance or price amount (`kk: 2024-002-02` was 2020). They are now
reported, on header and metadata lines, until #2808 lexes them as
beancount does; documented as a deliberate deviation and pinned.

Also documents and pins `kk: 1,,000` (1000 in beancount, the integer 1
here before), now reported like a posting or header amount already was.

Part of #2802 (stage 2 of 3)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
beancount's DATE takes the leading digits of `2024-002-02.5`,
`2024-002-02,000` or `2024-02-002.` and then rejects the rest; read our
way the run was arithmetic again (2019.5, 22). The split-date check no
longer requires the last number to be plain digits (the first two still
must: `2024.5-02-02` is arithmetic in beancount too). Also corrects what
main loaded for `custom "x" 2024-02-002` (just 2, #2811).

Part of #2802 (stage 2 of 3)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit 65f37db into main Oct 30, 2026
67 of 68 checks passed
@robcohen
robcohen deleted the fix/parser-reports-stray-chars-in-metadata branch October 30, 2026 02:12
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.

1 participant