Repository navigation
fix(parser): a balance tolerance may follow an arithmetic amount - #2195
Conversation
`directive_arithmetic_value` scanned to the first top-level CURRENCY and treated everything before it as the amount expression. With no currency between the amount and the tolerance, that swallowed the tolerance: `0.25 + 0.75 ~ 0.01 USD` was handed to the expression parser as `0.25 + 0.75 ~ 0.01`, which is not arithmetic, so the whole value was reported malformed. Only the currency-less arithmetic form reached that state. With a currency after the expression the scan stopped there and parsed, which is why `100.00 ~ 0.01 USD` and `0.25 + 0.75 USD ~ 0.01 USD` both worked and `0.25 + 0.75 ~ 0.01 USD` did not. `~` now ends the expression, which is what it means; the tolerance is read separately as it always was. This is what made `rledger format` emit a balance that no longer parses (#2191): the formatter emits the single-trailing-currency form, which is the beancount form and the one the parser already accepted for a plain number. Tested for VALUES, not just for parsing. An earlier bug in this same scan fell back to "take the first NUMBER" and turned `(1 + 5) / 2.1` into a silent assertion against 1 -- parsed cleanly, asserted the wrong thing -- so each of the seven accepted forms is checked against the amount it should evaluate to, with a ledger holding 0.25 confirming that `0.25 + 0.75` does not match it. Brings in the matrix-wide format-fidelity harness that #2192 could not land: it fails on `balance_with_arithmetic_and_tolerance` without this fix, which is how the bug was found. Closes #2191 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Review of the commit before this one caught a regression it introduced. `directive_arithmetic_value` is shared by `balance` and `price`, so making `~` end the amount expression applied to both -- and a price has no tolerance. `price USD 1.10 + 0.05 ~ 0.01 EUR` went from a malformed-value error to silently evaluating 1.15 and dropping the tolerance on the floor. Trading a diagnosed error for a silent half-reading of the author's input is a bad trade. `ToleranceForm` now says which grammar is being parsed: `balance` stops at `~`, `price` does not. That restores the old handling of the arithmetic form and leaves the plain one, `price USD 1.10 ~ 0.01 EUR`, which main ALREADY accepted the same silent way -- `~` is not an arithmetic operator, so the scan took the fast path and fell back to the first NUMBER, yielding 1.10 with the rest discarded. Fixing only the half I broke would leave the identical silent truncation one keystroke away, so a top-level `~` on a price is now diagnosed outright. Both forms are covered, and so are the three tolerance-free price forms with the values they must evaluate to -- an error path that also stopped accepting valid input would pass a test that only asserted rejection. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
The fidelity harness guards against going quiet by asserting a minimum number of fixtures reached the comparison. `> 20` was a third of the way down from the real figure: 37 of the 42 fixtures round-trip today, the other 5 being error fixtures, so ten could start failing to parse and be skipped without the floor noticing. Skipping is exactly how this test would go quiet. Measured rather than guessed, and set just under the measured value so adding fixtures does not churn it.
The failure this session kept turning up is a third state between the two: accept the tag, then drop it because the model has nowhere to put it. `note` was in it (#2160), both formatters were in it (#2184), and a price's tolerance was in it. So this counts the directives rather than testing one. Seven refuse, three keep, and each refusal is checked against its tag-free form too -- a rejection that also rejected valid input would satisfy an assertion that only looked for an error. `query` is in neither set: it accepts a tag and discards it. That is asserted here as CURRENT behavior, not as correct behavior. Which way it should go needs `bean-check` (beancount's `Query` has no tags field, which argues for refusing; a parser-lima corpus file uses the form, which argues it appears in the wild) and the container is not built here. Filed as #2194. Written as an assertion so the day it changes this fails and the census gets updated rather than quietly going stale. I implemented the refusal and backed it out: it makes `parser-lima/examples_data_full.beancount` error, and an unverifiable strictness increase does not belong in a PR about tolerance parsing.
Loader 32 -> 33, wasm 17 -> 18, pin 33. Parser OUTPUT moves in both directions here, which is why both caches have to: a v32/v17 blob holds a parse error where this build now produces a balance directive, and holds a silently truncated 1.10 where this build now produces an error. Either way the cache would serve a reading the binary no longer agrees with. Both `CostNumber` and `MetaValue` fixture tripwires move version only -- balance and price amounts are `Decimal`s on the directive and take part in neither archived layout, and the assertions after each comment prove that rather than take the comment's word for it.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
🟡 Changes recommended
The updated arithmetic fast-path can bypass the negate_python behavior for signed literals (risking -0.00 semantics), and one new test uses brittle debug-string matching for diagnostics.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
This PR fixes a parser inconsistency where a balance tolerance (~ ...) could be incorrectly consumed as part of an arithmetic amount expression (breaking round-trips such as rledger format → rledger check). It also adds regression tests/harnesses to prevent future format-fidelity regressions and bumps loader/WASM cache versions to reflect the changed parser output.
Changes:
- Update arithmetic-value scanning so
~terminates abalanceamount expression (tolerance is parsed separately), and diagnosepricedirectives that contain a top-level~(since prices have no tolerance). - Add integration tests covering balance arithmetic+tolerance forms, price tolerance rejection, and a directive tag/link “census”; add a matrix-wide format-fidelity test (parse → format → parse) for CST formatting.
- Bump cache versions in
rustledger-loaderandrustledger-wasmto invalidate stale blobs whose parsed directive output differs under the new parser behavior.
File summaries
| File | Description |
|---|---|
| crates/rustledger-parser/src/cst/convert.rs | Adjusts directive arithmetic scanning to stop at ~ for balances and adds explicit rejection of price tolerances. |
| crates/rustledger-parser/tests/parser_integration_test.rs | Adds regression coverage for balance tolerance-after-arithmetic, price tolerance rejection, and tag/link behavior across directives. |
| crates/rustledger-parser/src/cst/format.rs | Adds a format-fidelity harness that asserts formatting preserves parsed directive models across the idempotence matrix. |
| crates/rustledger-loader/src/cache.rs | Bumps loader cache version to 33 with rationale tied to parser-output changes. |
| crates/rustledger-wasm/src/cache.rs | Bumps WASM cache version to 18 and updates the loader-version pin to 33. |
Review details
Suppressed comments (1)
crates/rustledger-parser/src/cst/convert.rs:1679
directive_arithmetic_valuetreats a leading+/-as “arithmetic” (becausehas_opincludes PLUS/MINUS), so a simple signed literal like-0.00will be evaluated viaparse_arith_primary’s-innerpath instead of the caller’s fast-path that appliesnegate_python. That can reintroduce a signed-zeroDecimal(rendering-0.00) and diverge from the documented beancount/Python behavior.
// Fast-path: zero or one token = no arithmetic.
let has_op = tokens.iter().any(|t| {
matches!(
t.kind(),
crate::SyntaxKind::PLUS
| crate::SyntaxKind::MINUS
| crate::SyntaxKind::STAR
| crate::SyntaxKind::SLASH
| crate::SyntaxKind::L_PAREN
)
});
if !has_op {
return None;
}
- Files reviewed: 5/5 changed files
- Comments generated: 1
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Review feedback on #2192 was that `emit_header_tags_and_links` bailed out of its walk at the first child NODE, so it did not scan the whole header. I fixed that there and then wrote `has_top_level_tilde` with the identical `break` a few hours later. Harmless today for the same reason it was harmless there -- a price's only child node is a META_ENTRY, whose tokens are not direct children, so nothing here can see a `~` written inside metadata. But a header that ever gains a child node would stop being scanned at all, and the whole point of this function is to refuse a tolerance rather than skip past one. Also records a blind spot in the format-fidelity test, found while checking whether the tolerance clause is validated at all (it is not, #2193): a model comparison cannot see data the model never held. `balance X 1.00 USD ~ 0.01 EUR` formats to `1.00 ~ 0.01 USD`, erasing the EUR from the file, and the test passes -- both sides lost it in the parser. Which is exactly why the note-tag test also asserts on output text.
Review feedback: the assertion stringified the whole `ParseError` with
`{e:?}` and searched that. Debug output carries the span and context
fields too, so the test was coupled to formatting it does not care
about.
It now matches `ParseErrorKind::SyntaxError(m)` and searches `m`, which
is the part the test is actually about. Still pins the wording --
rewording the message fails it -- so this narrows what the assertion is
brittle to rather than weakening it.
|
Fixed — the assertion now matches You're right that the Debug form drags in span and context, which the test does not care about. Worth noting it still pins the wording: rewording the message fails the test, verified by changing it. So this narrows what the assertion is coupled to rather than weakening it. |
Four PRs shipped user-visible behavior changes without an entry: the two formatter tag losses (#2192), the blank-line tag drop (#2189), the same-date pad (#2187), and this branch's tolerance grammar (#2195). The changelog already carries the direct sibling of the first one -- "`rledger format` no longer deletes a posting's currency, cost or price when it has no units number" (#2142) -- so the omission was mine, not a question of whether this class belongs here. Each entry records the cache versions that moved with it, which is the part a reader upgrading actually needs and the part not recoverable from the diff.
Closes #2191.
The bug
rledger formatcould produce a file that no longer loads:Root cause is the parser, not the formatter.
directive_arithmetic_valuescanned to the first top-levelCURRENCYand treated everything before it as the amount expression. With no currency between the amount and the tolerance, it swallowed the tolerance and handed0.25 + 0.75 ~ 0.01to the expression parser, which is not arithmetic — so the whole value was reported malformed.Only the currency-less arithmetic form reached that state, which is why
100.00 ~ 0.01 USDand0.25 + 0.75 USD ~ 0.01 USDboth worked.~now ends the expression, which is what it means.A regression this introduced, caught in review
directive_arithmetic_valueis shared withprice, and a price has no tolerance. Stopping at~for both turnedprice USD 1.10 + 0.05 ~ 0.01 EURfrom a diagnosed error into a silent 1.15 with the tolerance discarded.ToleranceFormnow says which grammar is being parsed.That fix left the plain form,
price USD 1.10 ~ 0.01 EUR, which main already accepted the same silent way —~is not an arithmetic operator, so the scan took the fast path and fell back to the first NUMBER. Fixing only the half I broke would leave the identical silent truncation one keystroke away, so a top-level~on a price is now diagnosed.Verification
Values, not just parse success. An earlier bug in this same scan fell back to "take the first NUMBER" and turned
(1 + 5) / 2.1into a silent assertion against 1 — parsed cleanly, asserted the wrong thing. So every accepted form is checked against the amount it must evaluate to, including a ledger holding0.25confirming that0.25 + 0.75does not match it:100.00 USD100.00 ~ 0.01 USD100.00 USD ~ 0.01 USD0.25 + 0.75 USD0.25 + 0.75 ~ 0.01 USD0.25 + 0.75 USD ~ 0.01 USD(0.25 + 0.75) ~ 0.01 USDPrice: both tolerance forms diagnosed; the three tolerance-free forms still parse to the right values, because a rejection that also rejected valid input would pass a test asserting only rejection.
Also here
balance_with_arithmetic_and_tolerancewithout this fix, which is how the bug was found. Its floor is raised from> 20to>= 35against a measured 37 of 42, so ten fixtures could not start failing to parse unnoticed.queryis in neither set — it accepts a tag and drops it — pinned here as current behavior withqueryaccepts tags and links and silently drops them #2194 filed to decide it.Workspace green, clippy 1.97 clean, fmt/typos clean, parser baseline unchanged,
corpus_parity0 divergences against a freshly built wasip2 component.🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr