Repository navigation
fix(parser): reject transaction headers beancount refuses - #2020
Conversation
Four of the seven constructs in #2008. All four live in the transaction header, so one rule covers them: #3 `* #trip "Money from CC" ^610f` string after a tag #4 `* "Dinner" A:*:B` junk after the narration #6 `* "Mermaid Inn" "Nice dinner" "With Caroline"` #7 `* "A" "B" "C"` more than two strings beancount's grammar is `DATE txn txn_strings tags_links eol`, so strings come first and tags/links follow; more than two strings parses but the builder rejects it with "Too many strings on transaction description". Our CST parser is deliberately permissive - it is lossless and recovers rather than rejecting - and nothing downstream re-imposed that shape. Case 4 falls out of the same rule rather than needing lexer work: in `* "Dinner" A:*:B` the `A` lexes as a one-character CURRENCY, which is a valid flag in the flag position and junk after a string. Scoping the flag position to "before any string/tag/link" is what catches it. The rule is written once over `(SyntaxKind, Range)` pairs in a new `cst::txn_header`, and the red and green walkers differ only in how they enumerate tokens. The green/red mirrors are the drift source CLAUDE.md names; the shared rule plus the parity corpus is the defense. Removing the green call makes `parse_green_eq_red_corpus` fail, verified. Kind and range are all the rule needs - even the one-character CURRENCY flag is decided by `range.len() == 1` - so neither walker needs source access to reach a verdict, only to word the message. Scope was set by measurement, not by taste. Tallying every token kind that appears in a transaction header across the 731-file corpus (~30k transactions) gives DATE, STAR, PENDING_KW, TXN_KW, STRING, TAG, LINK, WHITESPACE, COMMENT, one-character CURRENCY - and two COLONs, both inside the case-4 fixture. So the allowlist is evidence, and sweeping the corpus after the change produces exactly four diagnostics: the four target fixtures, no false positives. Deliberately NOT widened past the evidence: `2014-01-01 * * "x"` has two flags and beancount rejects it, but it is not one of the seven and guessing at extra strictness is how a compatibility fix starts breaking real files. The `|` separator keeps its own DeprecatedPipeSymbol diagnostic instead of being re-reported here. Requires a cache bump, and this was observed rather than reasoned: after the parser change the first `rledger check` against the fixtures still reported only the old downstream E1001s, because the parse cache held the permissive parse. Loader 24 -> 25, wasm 10 -> 11, the wasm pin with it, and both archived-layout FIXTURE_VERSION tripwires - which fire with instructions saying which case applies. This is v15's case: which errors are emitted changed, how anything is archived did not. `test_lima_tests_parse` did not catch any of this, and could not have. Its allowlist branch is a bare `continue`, so listing a fixture only permits an error and never checks one occurs. TagThenLink, CostEmptyComponents and CostWithSlashes sat in that list for the parser's whole life while producing no error at all. A new LIMA_2008_CASES table replaces that with a two-sided assertion over all seven cases: the three unfixed rows assert we are STILL permissive, so finishing #2008 turns the test red and forces the row to flip. 28 allowlisted fixtures are in that same one-sided position today. 22 are `GrammarExceptions*`, whose intended semantics I have not verified, so they are left alone and noted rather than guessed at. Effect on compat: all four files now fail to load in `rledger query` too (#1912), matching bean-query, which is the point - they were returning rows here and erroring there. Refs #2008 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG
📊 Benchmark Results
vs main branch (2026-08-11)
What do these numbers mean?
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
Pull request overview
Aligns rustledger-parser transaction-header handling with beancount by adding a shared (red+green) token-sequence validation rule for headers, turning previously-silent acceptances into parse errors. This closes a compatibility gap identified in #2008 and ensures loader/WASM caches invalidate correctly when parser output changes.
Changes:
- Add a shared transaction-header validation rule (
cst::txn_header) and invoke it from both the red and green CST walkers. - Add end-to-end parser tests for the four targeted #2008 fixtures plus “valid header” guard cases (without relying on downloaded corpora).
- Bump loader/WASM cache versions (and update pins/fixture tripwires) to avoid serving stale permissive parses.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/rustledger/tests/fixture_tests.rs | Extends lima allowlist and adds a two-sided strictness table test for #2008 fixtures. |
| crates/rustledger-wasm/src/cache.rs | Bumps WASM cache version and pins it to the loader cache version. |
| crates/rustledger-parser/tests/txn_header_conformance.rs | Adds end-to-end conformance tests for rejected/accepted transaction-header shapes. |
| crates/rustledger-parser/src/cst/txn_header.rs | Implements the shared transaction-header token-sequence validation rule and unit tests. |
| crates/rustledger-parser/src/cst/mod.rs | Registers the new txn_header CST module. |
| crates/rustledger-parser/src/cst/green.rs | Runs the shared header rule in the green walker and adds parity corpus cases. |
| crates/rustledger-parser/src/cst/convert.rs | Runs the shared header rule in the red walker and centralizes error construction. |
| crates/rustledger-parser/src/cst/ast.rs | Exposes Transaction::header_tokens for internal use by the new rule. |
| crates/rustledger-loader/src/cache.rs | Bumps loader cache version and updates archived-layout fixture tripwires. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
| Metric | Result |
|---|---|
| Check Compatibility | 100% |
| BQL Compatibility | 95% (raw 91%, 101 masked) |
| Full AST Match | 100% |
| Total Files | 812 |
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
The parser-output baseline gate reported drift on exactly the four fixtures this branch now rejects, with their SOURCE hashes unchanged - which is the confirmation, not a surprise: same input, different parser output, and nothing else in the corpus moved. Only those four rows are updated. A full `regen-corpus-baselines.sh` run also wanted to add 17 `interpolation/` rows and rewrite `donearm-ledger/accounts.beancount`'s SOURCE hash, neither of which belongs in this commit: the interpolation fixtures are in-tree and absent from the committed manifest today, which CI tolerates and which is unrelated to this change, and a differing source hash means my local corpus copy differs from the one CI fetches. Committing either would be drift smuggled in under a green checkmark. The four new hashes are cross-checked: CI's strict run reported the same 16-hex prefixes that the local regeneration produced in full. Refs #2008 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG
Four review comments, all taken. The one that matters: `test_lima_2008_cases_have_expected_strictness` skipped itself when the fixture directory was missing. Those 441 fixtures are committed to the repo, so a missing directory is a broken checkout rather than an unavailable dependency - and a self-skipping test is the exact failure mode CLAUDE.md warns about under "Availability-gated tests must fail loudly somewhere". Worse, skipping would hide the very thing this table exists to pin. Now a hard assert. I quoted that same rule in the conformance test's module doc while leaving this skip two files away. Also: - `first_header_defect`'s contract said tokens run "through (not past)" the terminating NEWLINE, which reads as "include it". Both callers exclude it. Says so now, and records that NEWLINE stays in the trivia set only so feeding one in cannot change the verdict. - The `unwrap_or_default()` on a non-char-boundary slice would have rendered `unexpected "" in transaction header`, naming nothing. Token ranges are always char boundaries so it is unreachable, but the branch now falls back to the byte range and defect kind instead of an empty quote. - "three constructs" then listed four cases. Cases 6 and 7 are two fixtures of one construct; the doc now says that instead of leaving the reader to work it out. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG
|
All four taken, in The third one is a real catch and the one I'd flag: The other three:
Re-verified after the change: parser lib, conformance and |
Both #2022 review comments, and the second was more than wording. I documented the check as riding the existing whole-tree COST_SPEC scan and then gave it its own `descendants()` walk - so the doc was false AND the code did the thing the doc was written to avoid. That scan already sits behind a `contains('{')` guard precisely because `descendants()` allocates a red node per node; profiling once flagged it as ~50k wasted allocations on cost-spec-free ledgers. A second identical pass doubles a cost the codebase deliberately profiled down. Now genuinely fused into `extract_unclosed_cost_brace_errors`' loop: one walk, and the module doc describes what the code does. An unclosed spec skips the shape check - reporting a component defect on a truncated spec is noise about the truncation. The other comment: the trailing-junk message hardcoded "only `,` or `}` may follow", but a `{{total}}` spec closes with `}}`. Naming the wrong delimiter in a message about malformed syntax is the same species of misdirection #2008 is about. It says "the closing brace" now. Also gives the cost-spec path the same non-char-boundary fallback the header path got in the #2020 review, instead of an empty-quoted message. Re-swept the 731-file corpus after the restructure: exactly six diagnostics, the six target fixtures, no false positives. Refs #2008 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG
* fix(parser): reject malformed cost-spec component lists #2008 cases 1 and 2, stacked on the transaction-header PR. #1 `10 AAPL {, 100.0 USD, , }` beancount: unexpected COMMA, expecting HASH or CAPITAL or CURRENCY #2 `1.1 AAPL {45.23 USD / 2015-07-16 / "blabla"}` beancount: unexpected SLASH, expecting RCURL or COMMA beancount's cost spec is a comma-separated component list where each component is a compound_amount, DATE, STRING or `*`. An empty component is not a component, and CURRENCY completes a compound_amount so nothing but `,` or a closer may follow it. The obvious reading of case 2 - "SLASH is illegal in a cost spec" - is wrong and would have been worse than the bug. `/` is a number_expr operator: `{10.00 * 3 USD}` is valid and archives 30.00 (#1939/#1942), so a token ban would have passed both fixtures and broken every ledger that divides in a cost spec. The defect is positional, which is what beancount's own message says ("expecting RCURL or COMMA"). `*` is left as ordinary content for the same reason - it is both the "any lot" component and multiplication, and reading it as a complete component turns `{10.00 * 3 USD}` into junk. The corpus caught the one I did get wrong. A first draft recognized only `}` as a closer and fired on 42 real `{{total}}` specs across the 731-file sweep. With `{{`/`}}`/`{#` in the brace sets the sweep produces exactly two diagnostics: the two target fixtures, no false positives. That case is now a unit test rather than something the sweep alone covers. No green mirror this time, and that is not an oversight: the check rides the existing whole-tree COST_SPEC scan next to `extract_unclosed_cost_brace_errors`, which sits outside the `use_green` branch and already runs for both paths. One walker, nothing to drift. Case 5 (`{USD}`, `{ # USD}`) is deliberately still accepted. beancount rejects it from the BOOKER - "Too many missing numbers for currency group" - which is a judgment across a currency group, not a property of one spec's tokens, so it cannot be decided here. A unit test asserts it stays clean so the split is explicit rather than an omission. Honest about what this does NOT fix: `rledger check` still reports the downstream `E3001 does not balance` alongside the new parse error, because we continue processing where beancount stops at the syntax error. The real cause is now named first and `rledger query` refuses the file (matching bean-query), but fully removing the invented-cost residual means dropping the directive, which is a booking-layer change and not this PR. Cache 25 -> 26 (wasm 11 -> 12, pins with them) - a separate bump from v25 because a cache written between the two lands carries v25 and is still stale for this change. Refs #2008 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG * fix(parser): fuse the cost-spec shape check into the existing scan Both #2022 review comments, and the second was more than wording. I documented the check as riding the existing whole-tree COST_SPEC scan and then gave it its own `descendants()` walk - so the doc was false AND the code did the thing the doc was written to avoid. That scan already sits behind a `contains('{')` guard precisely because `descendants()` allocates a red node per node; profiling once flagged it as ~50k wasted allocations on cost-spec-free ledgers. A second identical pass doubles a cost the codebase deliberately profiled down. Now genuinely fused into `extract_unclosed_cost_brace_errors`' loop: one walk, and the module doc describes what the code does. An unclosed spec skips the shape check - reporting a component defect on a truncated spec is noise about the truncation. The other comment: the trailing-junk message hardcoded "only `,` or `}` may follow", but a `{{total}}` spec closes with `}}`. Naming the wrong delimiter in a message about malformed syntax is the same species of misdirection #2008 is about. It says "the closing brace" now. Also gives the cost-spec path the same non-char-boundary fallback the header path got in the #2020 review, instead of an empty-quoted message. Re-swept the 731-file corpus after the restructure: exactly six diagnostics, the six target fixtures, no false positives. Refs #2008 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG * chore(baselines): update CostWithSlashes for the reworded diagnostic The parser-output baseline hashes the diagnostics too, so changing "only `,` or `}` may follow" to "the closing brace" moved this fixture's output hash. One row, source hash unchanged, and the locally regenerated hash matches the prefix CI reported. Refs #2008 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG --------- Co-authored-by: Claude Opus 5 <[email protected]>
The two booking-layer halves of #2008. They looked like separate problems and turned out to be one root cause: the parser manufactured a number where the source had none, and every layer downstream treated the invention as fact. Case 5 (`{USD}` / `{ # USD}`) loaded clean where beancount reports "Too many missing numbers for currency group". The rule was not missing - interpolation already enforces "at most one unknown per currency group" and counts a cost spec with no determinable number as one unknown. It never fired because `{ # USD}` parsed as `Compound { per_unit: 0, total: 0 }`: `unwrap_or_default()` on both sides of the `#`. A determinable zero is not an unknown, so the count rule saw nothing to count. With both sides reported as `None`, the existing rule rejects the fixture unchanged. The misdiagnosis was the same defect wearing different clothes. `{, 100.0 USD, , }` had its `100.0` scraped out of a spec we had just diagnosed as malformed, and `rledger check` then reported `E3001 does not balance: residual 980.10 USD` - an arithmetic complaint about a typo, whose number this parser produced rather than the author. A malformed component list now yields no cost number at all, which hands the posting to interpolation as an unknown. Both fixtures lose the E3001 and keep the parse error that names the real cause. That reuses `cost_spec_shape`'s rule rather than adding a second predicate: `first_cost_spec_defect` is now generic over the payload carried with each kind, so the diagnostic path passes byte ranges and the converter passes `()` and asks only whether the spec is malformed. One rule, two uses. Scoped to BOTH sides of the `#` missing. `{100 # USD}` and `{# 500 USD}` still default the absent side to zero; beancount treats it as MISSING and would solve for it, which is a larger change I have no oracle to check against. The corpus says it is not urgent: `{ # CCY}` appears in exactly one file (the #2008 fixture) and the one-sided forms only in other parser-lima conformance fixtures. Two things about the verification are worth recording, because the first version of both was wrong. The new load-level test originally asserted only that `rledger check` fails. That can never fail: the fixture's accounts are never opened, so check exits non-zero on E1001 whatever the booker decides. Reverting the fix left it green. It now asserts the rejection contains the too-many-unknowns message. And the sabotage run that should have caught THAT was itself invalid: the reverted binary kept passing because the parse cache still held the fixed build's output, and reverting code does not change CACHE_VERSION. Only with `BEANCOUNT_DISABLE_LOAD_CACHE=1` does removing the fix turn the test red. Same cache that hid the #2020 diagnostics, twice in one issue. Cache 26 -> 27 (wasm 12 -> 13). Unlike v25/v26 this one changes archived VALUES rather than which errors are emitted, so a stale blob would serve the invented number to a build that no longer produces one. Closes #2008 Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG Co-authored-by: Claude Opus 5 <[email protected]>
Four of the seven constructs in #2008 — the ones that live in the transaction header, so one rule covers them all.
* #trip "Money from CC" ^610funexpected STRING, expecting … TAG or LINK* "Dinner" A:*:BInvalid token: 'A:*:B'* "Mermaid Inn" "Nice dinner" "With Caroline"Too many strings on transaction description* "A" "B" "C"beancount's grammar is
DATE txn txn_strings tags_links eol— strings first, then tags/links. More than two strings parses, and the builder rejects it. Our CST parser is deliberately permissive (lossless, recovers rather than rejects) and nothing downstream re-imposed that shape.Case 4 needed no lexer work. In
* "Dinner" A:*:BtheAlexes as a one-characterCURRENCY— a perfectly valid flag in the flag position, and junk after a string. Scoping the flag position to "before any string/tag/link" catches it structurally.One rule, two walkers
The rule is written once over
(SyntaxKind, Range)pairs in a newcst::txn_header; the red and green walkers differ only in how they enumerate tokens. Green/red mirrors are the drift source CLAUDE.md names by name, so the shared rule plus the parity corpus is the defense.Kind and range are all the rule needs — even the one-character
CURRENCYflag is decided byrange.len() == 1— so neither walker touches source text to reach a verdict, only to word the message.Scope came from measurement, not taste
I tallied every token kind appearing in a transaction header across the 731-file corpus (~30k transactions):
So the allowlist is evidence, not guesswork. Re-sweeping after the change produces exactly four diagnostics — the four target fixtures, zero false positives. The 3
CURRENCYhits are2012-12-17 P "Payee" "Narration"(a real single-letter ticker flag, kept working) plus theAandBof case 4.Deliberately not widened past that evidence.
2014-01-01 * * "x"has two flags and beancount rejects it, but it is not one of the seven; guessing at extra strictness is how a compatibility fix starts breaking real files. The|separator keeps its ownDeprecatedPipeSymboldiagnostic rather than being re-reported here.The cache bump was observed, not reasoned
After the parser change, the first
rledger checkagainst the fixtures still reported only the old downstreamE1001s — the parse cache was serving the permissive parse. Loader 24 → 25, wasm 10 → 11, the wasm pin with it, and both archived-layoutFIXTURE_VERSIONtripwires. Those tripwires fire with instructions naming which case applies; this is v15's case — which errors are emitted changed, how anything is archived did not.test_lima_tests_parsecould not have caught thisIts allowlist branch is a bare
continue, so listing a fixture only permits an error — it never checks one occurs.TagThenLink,CostEmptyComponentsandCostWithSlashessat in that list for the parser's entire life while producing no error at all. That is how #2008 stayed invisible.A new
LIMA_2008_CASEStable replaces that with a two-sided assertion over all seven cases. The three unfixed rows assert we are still permissive, so landing the rest of #2008 turns this test red and forces the row to flip. A row that can only be right is not a test.28 allowlisted fixtures are in that same one-sided position today. 22 are
GrammarExceptions*, whose intended semantics I have not verified — left alone and noted rather than guessed at.Verification
1.97.0(CI's version) green;cargo docgreenparse_green_eq_red_corpusfail; flipping afalserow in the strictness table fails withexpected REJECTED, got accepted (0 parse errors)rledger querytoo (fix(cli): refuse to report on a file that failed to parse #1912), matching bean-query — they were returning rows here and erroring there, which is the 105 mismatches the issue was filed fromRemaining
Cases 1, 2, 5 are the cost-spec group (
{, 100.0 USD, , },{45.23 USD / 2015-07-16 / "blabla"},{USD}) and want their own PR — those are also the two where we currently emit a misdiagnosis (E3001 does not balance, a residual invented by our own recovery). The strictness table tracks them.Refs #2008