Repository navigation
fix(parser): evaluate arithmetic in a cost spec instead of truncating it - #1942
Conversation
`{10.00 * 3 USD}` booked a cost of 10.00. The price path has always evaluated
expressions (`convert_amount_to_incomplete` -> `evaluate_amount_expression`),
while the cost path latched the first NUMBER token and dropped the rest - so a
single posting could carry a correctly evaluated price and a truncated cost.
Assets:Something 2 HOOL {10.00 * 3 USD} @ 20.00 * 2 USD
beancount cost 30.00 price 40.00
before cost 10.00 price 40.00
after cost 30.00 price 40.00
Two consequences, the second worse. The cost basis was wrong, which propagates
into capital gains and every cost-denominated report. And because the weight
follows the cost, the transaction then failed to balance - a FALSE E3001
rejecting a file beancount loads with zero errors.
THE FIX IS TO SHARE THE EVALUATOR, NOT TO ADD A SECOND ONE
This is the drift shape CLAUDE.md's Canonical-Function Discipline describes:
two implementations of one computation with nothing asserting agreement. So
`parse_arith_expr` / `_term` / `_primary` are generalized from
`&[crate::SyntaxToken]` to `&[T] where T: TokenView` - the trait already
exposes exactly the `kind()` + `text()` the evaluator needs - and the cost path
now calls them. Both green and red conversion go through
`cost_spec_from_tokens`, so both are fixed by construction rather than by
mirroring.
A bare NUMBER still takes the existing latch: `cost_region_value` returns None
unless an operator or paren is present. That is deliberate. The latch carries
legacy sign handling and is what the current tests pin, so routing plain
numbers through the evaluator would be a behavior change smuggled in beside a
bug fix.
TWO THINGS THAT COST A DEBUG CYCLE EACH, BOTH NOW COMMENTED IN PLACE
Trivia. `cost_spec_from_tokens` is handed EVERY child token, whitespace
included, and the evaluator refuses tokens it does not recognize - so the first
version saw `10.00 WS * WS 3`, failed, and fell back to the latch. The bug was
still there, with more code in front of it. The other two evaluators filter
trivia for exactly this reason.
The CACHE. After the parser was provably fixed (a probe showed
`PerUnit { value: 30.00 }`), `rledger check` still reported the imbalance:
a stale cache was serving the old parser output. CACHE_VERSION 17 -> 18. The
archived LAYOUT is unchanged, which is precisely why the bump matters - nothing
would have rejected the old bytes, so users on a fixed build would have kept
the truncated cost basis until they cleared the cache by hand. The two
FIXTURE_VERSION tripwires in cache.rs asked the right question and are moved
with a note saying which of the two cases this is.
TESTS
- `cost_spec_arithmetic_is_evaluated` asserts the resolved cost number, not a
substring of debug output: a bare `contains("30.00")` would be satisfied by
the price, which is `20.00 * 2` and also renders `40.00`.
- `cost_spec_arithmetic_green_eq_red` runs six shapes - plain, parenthesized,
with a date, compound `#`, and two MALFORMED ones - through both conversion
paths and requires identical output. Every historical cost-spec divergence
(#1704, #1713, the `{*}` merge flag) landed in a hand-mirrored copy of these
semantics.
- Verified the new test FAILS with the fix disabled, so it is a guard rather
than decoration.
Both `parser-lima` corpus fixtures now match beancount exactly (252.021 and
252.0210, previously 120.01 and 120.010).
Closes #1939.
📊 Benchmark Results
vs main branch (2026-08-03)
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
Fixes a parser correctness bug where arithmetic expressions inside cost specs (e.g. {10.00 * 3 USD}) were truncated to the first operand, producing an incorrect cost basis and potentially triggering false E3001 imbalance errors. The change aligns cost-spec parsing with the already-correct price/amount arithmetic evaluation path by reusing the shared arithmetic evaluator across token sources.
Changes:
- Generalize the arithmetic evaluator (
parse_arith_expr/_term/_primary) to work overTokenView, and apply it to cost-spec number regions (with trivia filtering and fallback to the legacy latch for non-arithmetic). - Add regression tests asserting evaluated cost-spec arithmetic and guarding green-vs-red conversion parity.
- Bump loader cache version to invalidate previously archived parse results whose layout is unchanged but values differ.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| crates/rustledger-parser/tests/fuzz_regressions.rs | Adds regression tests for evaluated cost-spec arithmetic and green/red parity. |
| crates/rustledger-parser/src/cst/convert.rs | Reuses the arithmetic evaluator for cost-spec parsing by operating over TokenView and overriding latched numbers only when arithmetic is present. |
| crates/rustledger-loader/src/cache.rs | Bumps cache version (and fixture versions) to prevent stale cached directives from preserving truncated cost values. |
Suppressed comments (1)
crates/rustledger-parser/src/cst/convert.rs:1763
- The comment above this
collect()explains the allocation, but the rustdoc forcost_spec_from_tokens(just above the changed hunk) still claims cost numbers have “no arithmetic evaluation”. Since this function now evaluates arithmetic viacost_region_value, it would help to mention that here as well to avoid future confusion when reading only this hunk.
// Materialized because the arithmetic evaluator needs random access
// (backtracking over a `(`...`)` group). Cost specs are a handful of
// tokens, so the allocation is not on any hot path worth defending.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
| Metric | Result |
|---|---|
| Check Compatibility | 100% |
| BQL Compatibility | 95% (raw 89%, 162 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 corpus baseline drifted on FOUR files, not the two the arithmetic fix
predicted. The other two are TotalsAndSigns.CostNegative and
TotalCostNegative, and they turned out to be the same root cause wearing a
different hat.
{-200.00 USD} before 200.00 after -200.00 beancount -200.00
{# -200.00 USD} before 20.00 after -20.00 beancount -20.00
A leading MINUS was never part of the latched number, so a negative cost was
booked with its SIGN INVERTED. Routing it through the shared evaluator, which
handles unary minus, fixes it; both fixtures now agree with beancount exactly.
That contradicts the claim in the previous commit that plain numbers keep the
old latch and sign behavior is untouched. A signed number does now route
through the evaluator. It is a fix, not a regression - verified that both
tools rejected these two files before AND after (beancount InterpolationError,
rledger E3001), so only the recorded cost changed - but the earlier wording
was wrong and the PR description is corrected.
`negative_cost_keeps_its_sign` pins it separately from the arithmetic test:
"arithmetic is evaluated" and "a leading sign is part of the number" are
different claims, and a refactor could satisfy one while breaking the other.
Verified it fails with the fix disabled.
BASELINE REGENERATED SURGICALLY, NOT WHOLESALE. A blanket BASELINE_UPDATE=1
rewrote 22 lines. My local corpus is 734 files against the manifest's 715 -
three repository clones failed during fetch, and the checkout carries
committed fixtures the CI corpus does not - so it also added interpolation/*
entries and changed a donearm-ledger hash that this change cannot possibly
affect. Committing that would have smuggled unrelated baseline movement past
review. Only the 4 lines CI actually reported as drifted are updated.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 4 changed files in this pull request and generated no new comments.
Suppressed comments (2)
crates/rustledger-parser/tests/fuzz_regressions.rs:68
- These assertions compare
CostNumbervia itsDebugstring, which is not a stable contract and can change without semantic changes (causing spurious test failures). SinceCostNumberisPartialEq, prefer asserting on the structured value (andDecimal) directly.
assert_eq!(
format!("{:?}", cs.number),
"Some(PerUnit { value: 30.00 })",
"cost spec arithmetic must be evaluated, not truncated",
);
crates/rustledger-parser/tests/fuzz_regressions.rs:137
- This test asserts
CostNumberby comparing itsDebugformatting.Debugoutput is not a stable API and can change without semantic changes, causing brittle failures. Prefer asserting on the structuredCostNumbervalue directly.
seen += 1;
assert_eq!(format!("{:?}", cs.number), want, "for: {src}");
Three review comments, one of which was a bug I missed.
THE WASM CACHE (the real one). `crates/rustledger-wasm/src/cache.rs` archives
`Vec<Directive>` - the same parsed directives whose cost numbers this PR
changes - behind its own CACHE_VERSION, which I did not touch. Its layout is
unchanged, so a v3 blob would be ACCEPTED and deserialized happily, serving a
truncated or sign-flipped cost basis on a build that has the fix. Exactly the
failure the loader bump exists to prevent, in a second cache. 3 -> 4.
I had already seen this file while grepping for CACHE_VERSION and did not
follow it up.
THE SIGN COMMENTS. Two comments claimed the latch "carries legacy sign
handling". It does not: the latch reads NUMBER tokens only and never applied a
leading sign, which is why `{-200.00 USD}` was booked POSITIVE. Both now say
what is actually true - an UNSIGNED bare number keeps the latch, a signed one
routes through the evaluator, and that is itself a fix.
THE DEBUG-STRING ASSERTIONS. Replaced with typed access. The arithmetic test
uses `CostNumber::per_unit()`; the sign test matches the enum structurally,
because `Compound` carries both halves and NEITHER accessor can express it
(both return None by design until units are known), so an accessor alone
cannot state that claim. Both still fail under sabotage - verified - so the
change did not soften them into decoration.
cost_spec_arithmetic_is_evaluated --- FAILED
negative_cost_keeps_its_sign --- FAILED
a negative per-unit cost must keep its sign, got Some(PerUnit { value: 200.00 })
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.
Suppressed comments (1)
crates/rustledger-parser/src/cst/convert.rs:1589
- The doc comment claims unsigned bare
NUMBERstays on an “allocation-free path”, butcost_region_valuealways allocateskept: Vec<&T>(andcost_spec_from_tokensnow materializestoks). This makes the comment misleading even when the evaluator is skipped.
Consider rewording to reflect what’s actually preserved here (latch semantics / skipping arithmetic evaluation), or refactor to avoid allocations when no arithmetic is present.
/// Returns `None` for an UNSIGNED bare `NUMBER` so the caller keeps its
/// existing single-token latch, leaving the overwhelmingly common case on the
/// allocation-free path.
…ances #1939 was an instance of a class, not a one-off. An audit of the eleven sites that read a number straight from tokens, against the three that route through an arithmetic evaluator, found two more with the identical shape. METADATA - silent key: 2 * 3 beancount 6 before 2 after 6 Any plugin or query reading that metadata got a third of the value, with nothing to indicate it. BALANCE TOLERANCE - rejected valid files balance Assets:A 10.00 ~ 0.005 * 2 USD against a 0.008 residual The tolerance is 0.010, so it passes; beancount loads the file with zero errors. rledger truncated it to 0.005 and raised E2002 - and the message printed `~ 0.005`, so the diagnostic itself displayed the bug. THE AUDIT Eleven `parse_decimal_token` call sites, three evaluator entry points. Nine sites were already fine: five are evaluator internals or `.or_else()` fallbacks that run only AFTER an evaluator declines, three are the cost-spec latches #1942 now overrides, and one is the green amount fast path, which bails to red rather than guessing. The two above were the real gaps. Both now call the shared evaluator, which #1942 made generic over `TokenView`, so green and red are covered by construction rather than by mirroring. A TEST THAT PINNED THE BUG `metadata_minus_applies_only_before_the_number` asserted `42 - 1` is `Int(42)` - "a minus past the number is not a sign; the first NUMBER closes it". That described the truncation faithfully and was never the right answer: beancount evaluates it to 41. Checked against the oracle BEFORE touching the expectation, because "the test disagrees with my change" is not evidence about which one is wrong. Updated with that reasoning recorded in place. CACHE AND BASELINES CACHE_VERSION 18 -> 19. Values move, layout does not - which is exactly why the bump is mandatory: nothing rejects the old bytes, so a stale cache would keep serving the truncated tolerance and keep rejecting a file the fixed build accepts. Both FIXTURE_VERSION tripwires moved with a note on which case this is; the MetaValue layout hash is unchanged and the assertion, not the comment, proves it. Two baselines drifted, both `parser-lima` Arithmetic fixtures, because they carry `number: -(5662.23 + 22.3)` metadata. Verified the new value is -5684.53, matching beancount exactly, before accepting the drift. Updated surgically - only those two lines - for the same reason as #1942: a blanket regeneration rewrites unrelated entries my corpus and CI's do not share. TESTS Both positions pinned, and each verified to FAIL on its own sabotage, so neither guard is decoration. A green/red test covers six shapes including two malformed ones, so they degrade identically rather than failing identically by accident. Refs #1944. Stacked on #1942 (needs its generic evaluator).
Same reasoning as the loader bump, and the same cache Copilot caught me missing on #1942: rustledger-wasm archives Vec<Directive>, the layout does not move, so a v4 blob would be accepted and its directives deserialized with the truncated tolerance still in them. The rule this makes explicit: a parser change that alters a VALUE has to bump BOTH caches, not just the loader's.
Review point: the two new assertions compared Debug output, which couples them to formatting and is inconsistent with the typed assertions the rest of this file uses after the same comment on #1942. compares against and against . Re-verified both still fail under sabotage, so the rewrite did not soften them into decoration.
…ances (#1945) * fix(parser): evaluate arithmetic in metadata values and balance tolerances #1939 was an instance of a class, not a one-off. An audit of the eleven sites that read a number straight from tokens, against the three that route through an arithmetic evaluator, found two more with the identical shape. METADATA - silent key: 2 * 3 beancount 6 before 2 after 6 Any plugin or query reading that metadata got a third of the value, with nothing to indicate it. BALANCE TOLERANCE - rejected valid files balance Assets:A 10.00 ~ 0.005 * 2 USD against a 0.008 residual The tolerance is 0.010, so it passes; beancount loads the file with zero errors. rledger truncated it to 0.005 and raised E2002 - and the message printed `~ 0.005`, so the diagnostic itself displayed the bug. THE AUDIT Eleven `parse_decimal_token` call sites, three evaluator entry points. Nine sites were already fine: five are evaluator internals or `.or_else()` fallbacks that run only AFTER an evaluator declines, three are the cost-spec latches #1942 now overrides, and one is the green amount fast path, which bails to red rather than guessing. The two above were the real gaps. Both now call the shared evaluator, which #1942 made generic over `TokenView`, so green and red are covered by construction rather than by mirroring. A TEST THAT PINNED THE BUG `metadata_minus_applies_only_before_the_number` asserted `42 - 1` is `Int(42)` - "a minus past the number is not a sign; the first NUMBER closes it". That described the truncation faithfully and was never the right answer: beancount evaluates it to 41. Checked against the oracle BEFORE touching the expectation, because "the test disagrees with my change" is not evidence about which one is wrong. Updated with that reasoning recorded in place. CACHE AND BASELINES CACHE_VERSION 18 -> 19. Values move, layout does not - which is exactly why the bump is mandatory: nothing rejects the old bytes, so a stale cache would keep serving the truncated tolerance and keep rejecting a file the fixed build accepts. Both FIXTURE_VERSION tripwires moved with a note on which case this is; the MetaValue layout hash is unchanged and the assertion, not the comment, proves it. Two baselines drifted, both `parser-lima` Arithmetic fixtures, because they carry `number: -(5662.23 + 22.3)` metadata. Verified the new value is -5684.53, matching beancount exactly, before accepting the drift. Updated surgically - only those two lines - for the same reason as #1942: a blanket regeneration rewrites unrelated entries my corpus and CI's do not share. TESTS Both positions pinned, and each verified to FAIL on its own sabotage, so neither guard is decoration. A green/red test covers six shapes including two malformed ones, so they degrade identically rather than failing identically by accident. Refs #1944. Stacked on #1942 (needs its generic evaluator). * fix(wasm): bump the WASM cache for the metadata and tolerance changes Same reasoning as the loader bump, and the same cache Copilot caught me missing on #1942: rustledger-wasm archives Vec<Directive>, the layout does not move, so a v4 blob would be accepted and its directives deserialized with the truncated tolerance still in them. The rule this makes explicit: a parser change that alters a VALUE has to bump BOTH caches, not just the loader's. * test(parser): assert MetaValue and tolerance by type, not Debug string Review point: the two new assertions compared Debug output, which couples them to formatting and is inconsistent with the typed assertions the rest of this file uses after the same comment on #1942. compares against and against . Re-verified both still fail under sabotage, so the rewrite did not soften them into decoration.
…ions together #1902 Phase 1 asks for cache round-trip properties on the grounds that "a stale cache resurrects fixed bugs unless CACHE_VERSION is bumped, which is a property, not a review". This session proved that literally, twice. WHAT THE SESSION SHOWED The loader cache moved 17 -> 23 and the wasm cache 3 -> 9, six bumps each, every one done by hand and every one requiring a fresh judgment about whether the archived LAYOUT moved or only the VALUE. Two things went wrong: - On #1942 the parser was provably fixed - a probe showed the corrected cost - while `rledger check` still reported the old imbalance, because a stale cache was answering. - On the same PR I bumped the loader and MISSED the wasm cache entirely. It archives the same `Vec<Directive>`, so a stale blob would have kept serving a truncated cost basis on a fixed build. Review caught it. No test did. THREE PROPERTIES 1. `cache_roundtrip_preserves_parsed_directives` round-trips REAL PARSED ledgers, one per shape whose parser output changed in this series: cost arithmetic, negative cost, compound cost, metadata arithmetic, balance tolerance, a unicode account, tags and links, and lots with prices. The existing tests hand-build a CacheEntry from a literal directive, which proves the format works on the shape the author thought of - not the shape that keeps breaking. 2. `a_stale_version_is_refused_rather_than_reinterpreted` writes a real cache, rewrites the header version word to the previous version, and asserts the loader refuses it. This is the property that actually protects an upgrade: the layout usually does NOT change when parser output does, so nothing else stops an old blob deserializing cleanly into the new types and serving a pre-fix answer. 3. `loader_cache_version_is_pinned` pins the wasm cache against the loader's, so moving one without the other fails with a message that asks the right question: did PARSER OUTPUT change (bump both), or was it loader-internal (update the pin alone)? This is the guard for the bug that got past me. ALL THREE VERIFIED TO FAIL version check disabled -> "a cache blob one version behind must be refused" loader moved, pin did not -> the tripwire message above a fixture stops parsing -> "expected a multi-directive parse, got 0" The third is the non-vacuity guard on property 1: without it the comparison is satisfied by two empty vectors, and a shape that stopped parsing would pass as a clean round-trip. `CACHE_VERSION` is now `pub` so the wasm crate can pin against it; that pulled in a stricter doc lint on the public item, hence the paragraph break in its history comment. Refs #1902.
…ions together stale cache resurrects fixed bugs unless CACHE_VERSION is bumped, which is a property, not a review". This session proved that literally, twice. WHAT THE SESSION SHOWED The loader cache moved 17 -> 23 and the wasm cache 3 -> 9, six bumps each, every one done by hand and every one requiring a fresh judgment about whether the archived LAYOUT moved or only the VALUE. Two things went wrong: - On #1942 the parser was provably fixed - a probe showed the corrected cost - while `rledger check` still reported the old imbalance, because a stale cache was answering. - On the same PR I bumped the loader and MISSED the wasm cache entirely. It archives the same `Vec<Directive>`, so a stale blob would have kept serving a truncated cost basis on a fixed build. Review caught it. No test did. THREE PROPERTIES 1. `cache_roundtrip_preserves_parsed_directives` round-trips REAL PARSED ledgers, one per shape whose parser output changed in this series: cost arithmetic, negative cost, compound cost, metadata arithmetic, balance tolerance, a unicode account, tags and links, and lots with prices. The existing tests hand-build a CacheEntry from a literal directive, which proves the format works on the shape the author thought of - not the shape that keeps breaking. 2. `a_stale_version_is_refused_rather_than_reinterpreted` writes a real cache, rewrites the header version word to the previous version, and asserts the loader refuses it. This is the property that actually protects an upgrade: the layout usually does NOT change when parser output does, so nothing else stops an old blob deserializing cleanly into the new types and serving a pre-fix answer. 3. `loader_cache_version_is_pinned` pins the wasm cache against the loader's, so moving one without the other fails with a message that asks the right question: did PARSER OUTPUT change (bump both), or was it loader-internal (update the pin alone)? This is the guard for the bug that got past me. ALL THREE VERIFIED TO FAIL version check disabled -> "a cache blob one version behind must be refused" loader moved, pin did not -> the tripwire message above a fixture stops parsing -> "expected a multi-directive parse, got 0" The third is the non-vacuity guard on property 1: without it the comparison is satisfied by two empty vectors, and a shape that stopped parsing would pass as a clean round-trip. `CACHE_VERSION` is now `pub` so the wasm crate can pin against it; that pulled in a stricter doc lint on the public item, hence the paragraph break in its history comment. Refs #1902.
…ions together (#1960) * test(loader): cache round-trip properties, and pin the two cache versions together stale cache resurrects fixed bugs unless CACHE_VERSION is bumped, which is a property, not a review". This session proved that literally, twice. WHAT THE SESSION SHOWED The loader cache moved 17 -> 23 and the wasm cache 3 -> 9, six bumps each, every one done by hand and every one requiring a fresh judgment about whether the archived LAYOUT moved or only the VALUE. Two things went wrong: - On #1942 the parser was provably fixed - a probe showed the corrected cost - while `rledger check` still reported the old imbalance, because a stale cache was answering. - On the same PR I bumped the loader and MISSED the wasm cache entirely. It archives the same `Vec<Directive>`, so a stale blob would have kept serving a truncated cost basis on a fixed build. Review caught it. No test did. THREE PROPERTIES 1. `cache_roundtrip_preserves_parsed_directives` round-trips REAL PARSED ledgers, one per shape whose parser output changed in this series: cost arithmetic, negative cost, compound cost, metadata arithmetic, balance tolerance, a unicode account, tags and links, and lots with prices. The existing tests hand-build a CacheEntry from a literal directive, which proves the format works on the shape the author thought of - not the shape that keeps breaking. 2. `a_stale_version_is_refused_rather_than_reinterpreted` writes a real cache, rewrites the header version word to the previous version, and asserts the loader refuses it. This is the property that actually protects an upgrade: the layout usually does NOT change when parser output does, so nothing else stops an old blob deserializing cleanly into the new types and serving a pre-fix answer. 3. `loader_cache_version_is_pinned` pins the wasm cache against the loader's, so moving one without the other fails with a message that asks the right question: did PARSER OUTPUT change (bump both), or was it loader-internal (update the pin alone)? This is the guard for the bug that got past me. ALL THREE VERIFIED TO FAIL version check disabled -> "a cache blob one version behind must be refused" loader moved, pin did not -> the tripwire message above a fixture stops parsing -> "expected a multi-directive parse, got 0" The third is the non-vacuity guard on property 1: without it the comparison is satisfied by two empty vectors, and a shape that stopped parsing would pass as a clean round-trip. `CACHE_VERSION` is now `pub` so the wasm crate can pin against it; that pulled in a stricter doc lint on the public item, hence the paragraph break in its history comment. Refs #1902. * test(wasm): pin catches up to loader v24 - the tripwire firing for real Rebasing onto main after #1959 landed, the new tripwire fired on an actual version move rather than a sabotage: the rustledger-loader cache version moved and this one did not... Answering its own question: #1959 made tags and links parse errors in custom and pushmeta values, so PARSER OUTPUT changed - and it correctly bumped BOTH caches, loader 23 to 24 and wasm 9 to 10. Only the pin was behind. So this is the update-the-pin-alone branch of the message, and the guard did exactly what it exists for: it made the question get asked at the moment the versions diverged, rather than leaving it to be noticed in review, or not at all. * test(loader): unique fixture dirs and an env guard for the cache properties Two review findings, both real hazards rather than style. CONCURRENT RUNS COLLIDED. `temp_dir()` built a fixed name under the global temp dir, so two `cargo test` processes landed on the same path - and the cleanup at the START of the helper would delete the other run's fixture out from under it. Now a `tempfile::TempDir` with a unique suffix, which also removes itself on drop, so a failing assertion leaves no litter. Verified by running two copies of the suite concurrently: both pass. THE ENV VARS WERE INHERITED. `save_cache_entry` / `load_cache_entry` read process env, so an inherited BEANCOUNT_LOAD_CACHE_FILENAME would redirect these writes out of the fixture - silently making the round-trip assert nothing - and BEANCOUNT_DISABLE_LOAD_CACHE would stop a cache being written at all. Either could also clobber a developer's real cache file. The unit tests in cache.rs already guard themselves this way (`assert_clean_cache_env`). I did not follow the pattern the crate had already established. Verified the guard fires: $ BEANCOUNT_DISABLE_LOAD_CACHE=1 cargo test --test cache_roundtrip_properties unset BEANCOUNT_DISABLE_LOAD_CACHE before running this test ... Noted in place that CLAUDE.md warns against asserting environment as a precondition (#1729). The exception earns itself here: the alternative is not a hermetic test but one that writes somewhere unexpected, and failing loudly beats that. * docs(loader): backtick the generics in the now-public cache-version history CI's Documentation job failed with "unclosed HTML tag `Decimal`". The v8 entry in the version history contains `Option<Decimal> + Option<Decimal>` unescaped, and rustdoc parses a bare `<Decimal>` as an HTML tag. It has been there since v8 and was harmless because the constant was PRIVATE - rustdoc does not document private items by default. Making `CACHE_VERSION` public so the wasm crate could pin against it is what exposed the comment. Worth noting the shape: `cargo test` and clippy both pass on this. Only `cargo doc` catches it, which is why the repo has a separate Documentation job - and why I should have run it after making an item public rather than after CI told me. Checked the rest of the block for the same problem (none) and ran `RUSTDOCFLAGS=-D warnings cargo doc --workspace`, which is clean.
#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
#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): 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]>
{10.00 * 3 USD}booked a cost of 10.00. The price path has always evaluated expressions (convert_amount_to_incomplete→evaluate_amount_expression); the cost path latched the firstNUMBERtoken and dropped the rest — so a single posting could carry a correctly evaluated price and a truncated cost.Two consequences, the second worse. The cost basis was wrong, which propagates into capital gains and every cost-denominated report. And because the weight follows the cost, the transaction then failed to balance — a false E3001 rejecting a file beancount loads with zero errors.
The fix shares the evaluator rather than adding a second one
This is the drift shape CLAUDE.md's Canonical-Function Discipline describes: two implementations of one computation, nothing asserting agreement.
parse_arith_expr/_term/_primaryare generalized from&[crate::SyntaxToken]to&[T] where T: TokenView— the trait already exposes exactly thekind()+text()the evaluator needs — and the cost path calls them. Both green and red conversion go throughcost_spec_from_tokens, so both are fixed by construction, not by mirroring.An unsigned bare
NUMBERstill takes the existing latch (cost_region_valuereturnsNoneunless an operator or paren is present), so the common case is untouched.Two things that cost a debug cycle each
Trivia.
cost_spec_from_tokensreceives every child token, whitespace included, and the evaluator refuses tokens it doesn't recognize — so the first version saw10.00 WS * WS 3, failed, and fell back to the latch. The bug was still there, with more code in front of it.The cache. After the parser was provably fixed (a probe showed
PerUnit { value: 30.00 }),rledger checkstill reported the imbalance — a stale cache was serving old parser output.CACHE_VERSION17 → 18. The archived layout is unchanged, which is exactly why the bump matters: nothing would have rejected the old bytes, so users on a fixed build would have kept the truncated cost basis until clearing the cache by hand. The twoFIXTURE_VERSIONtripwires incache.rsasked the right question and are moved with a note on which case this is.Both are now commented in place.
Tests
cost_spec_arithmetic_is_evaluatedasserts the resolved cost number, not a substring of debug output — a barecontains("30.00")would be satisfied by the price, which is20.00 * 2and also renders40.00.cost_spec_arithmetic_green_eq_redruns six shapes through both conversion paths and requires identical output: plain, parenthesized, with a date, compound#, and two malformed ones ({10.00 * USD},{1 / 0 USD}) so they degrade the same way rather than failing the same way by accident.Verification
parser-limacorpus fixtures now match beancount exactly: 252.021 and 252.0210 (were 120.01 and 120.010)cargo test -p rustledger-parser: 603 passed, 0 failedcargo test -p rustledger-loader: 184 passed, 0 failedrustledger-validate155,rustledger-query631,rustledger-booking153 — all passingcargo +1.97.0 clippyon both crates,--all-features --all-targets -D warnings: cleancargo fmt --check: cleanCloses #1939.
Baseline
tests/baselines/parser-corpus.manifestupdated for the 4 files CI reported as drifted — the 2 arithmetic fixtures and the 2 negative-cost ones.Updated surgically rather than by blanket regeneration. A plain
BASELINE_UPDATE=1rewrote 22 lines: my local corpus is 734 files against the manifest's 715 (three repo clones failed during fetch, and the checkout carries committed fixtures the CI corpus lacks), so it also addedinterpolation/*entries and changed adonearm-ledgerhash that this change cannot affect. Committing that would have smuggled unrelated baseline movement past review.