Skip to content

fix(parser): reject malformed cost-spec component lists - #2022

Merged
robcohen merged 3 commits into
mainfrom
fix/parser-cost-spec-strict
Aug 11, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/parser-cost-spec-strict

Conversation

@robcohen

Copy link
Copy Markdown
Member

Cases 1 and 2 of #2008. Stacked on #2020 — review that one first; this branch contains its commits.

# construct beancount before after
1 10 AAPL {, 100.0 USD, , } unexpected COMMA, expecting HASH or CAPITAL or CURRENCY accepted, then E3001 does not balance rejected, cause named
2 1.1 AAPL {45.23 USD / 2015-07-16 / "blabla"} unexpected SLASH, expecting RCURL or COMMA accepted, then E3001 rejected, cause named

A cost spec is a comma-separated component list, each component a compound_amount, DATE, STRING or *. An empty component is not a component, and CURRENCY completes a compound_amount so only , or a closer may follow.

The obvious reading of case 2 would have been worse than the bug

"SLASH is illegal in a cost spec" passes both fixtures — and breaks every ledger that divides. / is a number_expr operator; {10.00 * 3 USD} is valid and archives 30.00 (#1939/#1942). The defect is positional, which is exactly what beancount's message says: expecting RCURL or COMMA, not "that token is banned".

* is left as ordinary content for the same reason — it is both the "any lot" component and multiplication, so treating it as a complete component turns {10.00 * 3 USD} into junk. That cost me a failing test before the corpus ever saw it.

The corpus caught the one I got wrong

A first draft recognised only } as a closer and fired on 42 real {{total}} specs across the 731-file sweep — fava_investor, healthequity, tests_lots, all valid. With {{/}}/{# in the brace sets:

--- swept 731 files, 2 cost-spec diagnostics ---
  test-cases_ParseLots.CostEmptyComponents.beancount
  test-cases_ParseLots.CostWithSlashes.beancount

Exactly the two targets, zero false positives. {{...}} is now a unit test rather than something only the sweep covers.

No green mirror, deliberately

Unlike #2020, this 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 — so the absence of a mirror is the design, not an omission.

Case 5 is deliberately still accepted

{USD} / { # USD} is rejected by beancount from the booker — "Too many missing numbers for currency group" — a judgment across a currency group, not a property of one spec's tokens. It cannot be decided from the spec alone, so it stays out of the parser. A unit test asserts it stays clean, so the split is explicit rather than a gap, and the LIMA_2008_CASES table (from #2020) keeps tracking it.

What this does not fix

rledger check still prints the downstream E3001 does not balance alongside the new parse error, because we keep processing where beancount stops at the syntax error:

P0012  parse error: empty cost-spec component before ","…
E1001  Account Assets:Invest:AAPL was never opened
E3001  Transaction does not balance: residual 980.10 USD

The real cause is now named first, and rledger query refuses the file (matching bean-query), which is the compatibility half of the issue. Fully removing the invented-cost residual means dropping the directive on a parse error — a booking-layer change, not this PR. I'd rather say so than claim the misdiagnosis is gone.

Verification

  • Corpus sweep: 2 diagnostics, both targets
  • Full workspace suite green; clippy 1.97.0 green; fmt clean
  • LIMA_2008_CASES rows for cases 1 and 2 flipped false → true — the table is two-sided, so this had to be updated to stay green
  • Baseline manifest: only the 2 affected rows, source hashes asserted unchanged before applying
  • Cache 25 → 26 (wasm 11 → 12): a separate bump from fix(parser): reject transaction headers beancount refuses #2020's, because a cache written between the two lands carries v25 and is still stale for this change

Refs #2008

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR tightens rustledger-parser’s cost-spec parsing to reject malformed comma-separated component lists that beancount rejects (issue #2008 cases 1 and 2), preventing downstream misdiagnoses (e.g., erroneous E3001 balance errors) by surfacing a targeted syntax error earlier in the pipeline.

Changes:

  • Add a cost-spec “component shape” validator that detects (1) empty components like {, ...} / ..., , ... and (2) trailing junk after a complete component like ... USD / ....
  • Integrate the new rule into the existing CST conversion error extraction so it runs for both green/red paths without introducing a second walker.
  • Update corpus baselines, conformance fixtures, and bump loader/wasm cache versions to invalidate stale permissive parses.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/baselines/parser-corpus.manifest Updates baseline hashes for the two affected lima fixtures.
crates/rustledger/tests/fixture_tests.rs Flips #2008 strictness-table rows for cases 1 & 2 to true (now rejected).
crates/rustledger-wasm/src/cache.rs Bumps wasm cache version and loader cache pin to match the loader change.
crates/rustledger-parser/tests/txn_header_conformance.rs Adds regression tests for the two malformed cost-spec cases plus “must stay valid” specs (including {{...}}).
crates/rustledger-parser/src/cst/mod.rs Registers the new cost_spec_shape module.
crates/rustledger-parser/src/cst/cost_spec_shape.rs Implements the cost-spec component-shape defect detector + shared message generator.
crates/rustledger-parser/src/cst/convert.rs Hooks the new extraction into CST conversion and adds the extractor implementation.
crates/rustledger-loader/src/cache.rs Bumps loader cache version and fixture pins to invalidate cached parser output.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@robcohen
robcohen force-pushed the fix/parser-cost-spec-strict branch from 704a9aa to 383b6f2 Compare August 11, 2026 04:02
Base automatically changed from fix/parser-txn-header-strict to main August 11, 2026 04:31
#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
@robcohen
robcohen force-pushed the fix/parser-cost-spec-strict branch from 383b6f2 to 5615459 Compare August 11, 2026 04:33
@codecov

codecov Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/convert.rs 95.83% 1 Missing ⚠️
...rates/rustledger-parser/src/cst/cost_spec_shape.rs 99.58% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 40.2ms ± 1.3ms 24.1 MB
beancount 763.9ms ± 4.1ms 50.7 MB
Comparison 19x faster 2.1x less

vs main branch (2026-08-11)

Metric main this PR Change
Time 27.9ms 40.2ms +44.1% 🔴
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

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

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
@robcohen

Copy link
Copy Markdown
Member Author

Both taken, in 59aa241c0e — and the second one was more than wording, so thank you for it.

The scan really was duplicated. 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 existed 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.

It is now genuinely fused into extract_unclosed_cost_brace_errors' loop: one walk, and the module doc describes what the code does. An unclosed spec continues past the shape check — reporting a component defect on a truncated spec is just noise about the truncation.

The message did name the wrong delimiter. {{total}} closes with }}, and the diagnostic said "only , or } may follow". Naming the wrong closer in a message about malformed syntax is the same species of misdirection #2008 is about. It reads "the closing brace" now.

While in there, the cost-spec path also picked up the non-char-boundary fallback the header path got from the #2020 review, rather than an empty-quoted message.

Re-verified after the restructure — the corpus sweep is the part that matters, since the check moved:

--- swept 731 files, 6 #2008 diagnostics ---
  CostEmptyComponents · CostWithSlashes · TransactionThreeStrings
  ErrorInTransactionLine · TagThenLink · TooManyStrings

All six targets, no false positives. Full workspace suite, clippy 1.97.0 and fmt clean. This PR now targets main (#2020 merged), so its compat and corpus-baseline gates run for real — both passed on the previous push, with Check Compatibility at 100%.

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
@robcohen
robcohen merged commit beeb356 into main Aug 11, 2026
63 of 67 checks passed
@robcohen
robcohen deleted the fix/parser-cost-spec-strict branch August 11, 2026 05:38
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.

2 participants