Repository navigation
fix(parser): diagnose a balance tolerance that says two things at once - #2200
Conversation
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
📊 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?
|
There was a problem hiding this comment.
🟢 Approval recommended
The changes are narrowly scoped to diagnostics, include targeted regression tests, and correctly coordinate cache-version bumps to avoid stale-cache masking.
Pull request overview
Updates rustledger’s parser to avoid silently discarding parts of balance tolerances by diagnosing tolerance clauses that are ambiguous or contradictory (while still accepting the redundant-but-unambiguous “currency repeated and agrees” form), and bumps cache versions so stale cached parses can’t hide the new diagnostics.
Changes:
- Add parser-side tolerance validation for
balancedirectives to diagnose (a) mismatched tolerance currency vs amount currency and (b) juxtaposed-number tolerances that don’t parse as an expression. - Add an integration test that pins accepted vs diagnosed forms (including arithmetic tolerances) and asserts redundant-currency equivalence.
- Document the deliberate divergence in the compatibility reference and bump loader/wasm cache versions + pins to surface the new diagnostics.
File summaries
| File | Description |
|---|---|
| docs/reference/compatibility.md | Documents rustledger’s deliberate tolerance-grammar divergence and portability note. |
| crates/rustledger-wasm/src/cache.rs | Bumps wasm cache version to ensure new diagnostics aren’t masked by cached blobs; updates loader pin. |
| crates/rustledger-parser/tests/parser_integration_test.rs | Adds regression test coverage for the acceptance/diagnostic matrix and equivalence assertions. |
| crates/rustledger-parser/src/cst/convert.rs | Introduces check_balance_tolerance and wires it into convert_balance before extracting tolerance. |
| crates/rustledger-loader/src/cache.rs | Bumps loader cache version (v35) for the same diagnostic-surfacing reason; updates fixture pins. |
Review details
- 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.
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
|
Applied in the latest commit, and the point led somewhere. The two Vecs are gone — you're right that The bigger waste was upstream of it. The function collected every direct token of the directive before checking whether there was a And chasing it turned up two more things. The check was commenting on input it doesn't understand: on Which surfaced the actual bug: Controls: forcing the early-exit to always fire, and removing the expression-shaped guard, each fail their own assertion. |
Beancount's tolerance grammar is `NUMBER ~ NUMBER CURRENCY` -- one
currency, trailing -- and it rejects any currency before the `~`. We
differ in both directions now, on one rule: accept what has exactly one
meaning, diagnose what has none or contradicts itself.
Laxer, on purpose. `1.00 USD ~ 0.01 USD` states the currency twice and
agrees with itself, so there is one reading, and `rledger format`
canonicalizes it to `1.00 ~ 0.01 USD` losslessly. beancount calls it a
syntax error; refusing a file whose meaning is not in doubt buys
nothing.
Stricter, because the other two are not redundancy:
* `1.00 USD ~ 0.01 EUR` asserts a tolerance denominated in a currency
the amount does not use. The model has no field for it, so it was
accepted, the EUR dropped, and `rledger format` then wrote the loss
back to the file as `1.00 ~ 0.01 USD` (#2193).
* `1.00 ~ 0.001 0.02 USD` is two numbers with no operator, which has
no reading at all. It took the first and discarded the rest in
silence.
Arithmetic tolerances are untouched: `~ 0.005 + 0.005` and `~ 0.005 * 2`
still evaluate, which is why the second check asks whether the region
FAILS to parse as an expression rather than merely counting numbers.
Every row of the test table was run against beancount 3.2.3 and records
what it does, so the divergence is visible where someone would change
it. Three controls: disabling either check fails, and so does the
over-strict version that also rejects the agreeing-currency form -- that
last one is what stops "just match beancount" being applied later
without noticing it is a decision.
Cache versions move for the same reason as v34: the archived directive
is identical and the diagnostic is what a stale blob would hide. Loader
34 -> 35, wasm 19 -> 20, pin 35.
Closes #2193
Reviewing my own diagnostics turned up one that misdescribes its input. `1.00 ~ 0.01 ~ 0.02 USD` fell into the juxtaposed-numbers arm, whose message says the two numbers are "side by side" -- when a `~` sits between them. Telling an author their file says something it does not is the failure this whole change is about, so it should not appear in the fix for it. A second `~` now gets its own sentence naming the actual shape: `AMOUNT ~ TOLERANCE CURRENCY`. The test now asserts each rejection is diagnosed for the RIGHT reason rather than merely rejected. Removing the new check fails it -- which the previous version of the test would not have noticed, since the input was already being rejected, just for the wrong reason. `1.00 USD ~ 0.01` is documented alongside: no trailing currency, one statement of it before the `~`, one reading, accepted by the same rule that keeps `1.00 USD ~ 0.01 USD`.
Found by round-tripping every form this PR accepts, which the fidelity
harness cannot reach -- none of them is in the idempotence matrix.
The tolerance is an expression: `~ 0.005 + 0.005 USD` and
`~ 0.005 * 2 USD` both mean 0.010. `balance_tolerance` kept only the
first NUMBER after the tilde and emitted `~ 0.005 USD`, halving it.
That is worse than data loss, because the result is still valid:
before format balance PASSES (tolerance 0.010, agrees with beancount)
after format balance FAILS (tolerance 0.005)
`rledger format` turned a passing ledger into a failing one, silently,
and the output reparsed clean so nothing downstream could tell. Same
truncation as #1944, which fixed the parser's `extract_balance_tolerance`
and left this one standing -- the sibling implementation the fix did not
reach.
The whole expression is now emitted, parens included. Verified on the
VALUE rather than the text: a text comparison would pass on any spelling
that happens to round-trip while still meaning something new. Restoring
the first-number-only behavior fails the test.
693 corpus files still report non_idempotent=0 and
dropped_comments_in=0.
While placing the test I detached the adjacent test's doc comment by
inserting between it and its `fn` -- the fourth time that has happened in
this session and the reason clippy's duplicate-attribute warning is
worth reading rather than silencing.
Emitting the whole tolerance expression exposed two more things in the same function. main dropped a MINUS after the tilde outright, so `~ -0.01 USD` formatted to `~ 0.01 USD` -- a second changed value alongside the truncation, from the same "keep the first NUMBER, ignore everything else" loop. Emitting it then rendered `~ - 0.01`, which evaluates the same and reads wrong: the amount on that line renders `-1.00` tight, so one directive disagreed with itself. A `+`/`-` with nothing that can end an operand before it is unary and now binds to its number; a binary one keeps its spaces, so `0.02 - 0.01` is untouched. The test needed the more important fix. It compared the parsed tolerance VALUE before and after formatting, which cannot see a spacing change -- and reverting the unary handling PASSED it. Every fixture is already canonical, so formatting must also be a no-op on the TEXT, and that is now asserted. All three controls fail with it in place: reverting the unary tightening, dropping the MINUS, and restoring the first-number-only truncation. A value assertion that accepts any spelling which happens to evaluate the same is the same shape as comparing two equally-empty models.
Review feedback: `check_balance_tolerance` built a `Vec<&SyntaxToken>` and then cloned every token back out into a `Vec<SyntaxToken>`, when `cost_region_value` takes the same `&[SyntaxToken]` the tail is already a slice of. Both are gone; the region is sliced out of `tail`. The larger waste was upstream of that. It collected every direct token of the directive before checking whether there was a `~` at all, on a function that runs for every `balance` in every ledger, where the vast majority carry no tolerance. That answer now comes from an iterator and the common path allocates nothing. Also stops the check commenting on input it does not understand. On `~ .005 + .005` the lexer already reports the real problem, and this added "the second was being discarded" beside it -- a claim about input that never parsed. The check now requires the region to be made only of things an expression can contain. `.005` turns out to be a number beancount accepts and we reject in every numeric position, not just here; filed as #2201, and out of scope for this PR since the fix is in the number lexer. Controls: forcing the early-exit to always fire, and removing the expression-shaped guard, each fail their own assertion.
`docs/reference/compatibility.md` is where someone goes to find out why their file loads here and not in beancount, and it restates the same rows the parser test pins. Two copies of one table drift, and the copy that goes stale is the prose one, because nothing runs it. This runs it. Each row of the markdown table is parsed out and checked against the behavior it claims. I verified the nine current rows by hand first and they all matched -- which is exactly the state in which a table starts to rot, since the next behavior change is the one nobody re-checks. Only our half is checked. The beancount column is a recorded measurement against 3.2.3, not something reproducible without the container, so asserting it here would either be a lie or a skip. Three controls, one per way this fails: a row whose claim is wrong fails it; deleting rows so the table stops being recognized fails it on the row-count floor rather than passing vacuously; and disabling a check in the parser fails it from the other direction, with the docs unchanged.
I added a validation pass without measuring it. On a 56,000-balance ledger that cost +7% against main, reproducibly -- the check walked the tokens, then `extract_balance_tolerance` walked them again, and the early-exit I had added to make the common path cheap still collected every token before looking for a `~`. Two changes. Validation and extraction now share one walk and one region, so `extract_balance_tolerance` is gone and its contract moved into `tolerance_value` (including the #1944 note about why the first NUMBER is not the answer). And the "is there a tolerance at all" question is answered from an iterator before anything is collected -- main reached the same answer through a `skip_while` that left an empty Vec, which allocates nothing, and my collect-then-search did not. Measured on two 56,000-directive fixtures, best of 9: no tolerances main 189.4ms PR 188.0ms -0.7% 2% tolerances main 188.4ms PR 188.5ms +0.0% Both within run-to-run variance, which is about 1-2% on this machine -- main itself moved 189.4 to 188.4 between runs. The +7% was not: it reproduced across runs and sat well outside that band. So this is "no measurable difference", not "faster". Real ledgers are mostly transactions, so none of this was ever going to be visible in practice. It is still a cost paid on every balance directive for nothing, on a path this repository has done real work to keep tight.
Codecov flagged one uncovered line in `balance_tolerance`, the guard for an empty tolerance expression. Chasing what could reach it found the bug: `1.00 USD ~` and `1.00 ~ USD` parse with no complaint. The `~` says a tolerance follows and none does, so it was accepted as though never written -- and `rledger format` then deleted the tilde, erasing the difference from the file the way the mismatched currency did. beancount reports a syntax error for both. Under the rule this PR is built on -- accept what has exactly one meaning, diagnose what has none -- a tilde with nothing after it has no reading, so it is now diagnosed. The docs table and the census gain the row, and removing the check fails both the behavior assertion and the documented-table test. The message also had its whitespace mangled: a Rust line continuation was collapsed by the script that inserted it, so the text rendered with eighteen spaces mid-sentence. Every message in the file is now checked by rendering it rather than by reading the source. The `expr.is_empty()` line codecov pointed at stays, and stays uncovered: with a dangling tilde now failing to parse, the formatter can no longer be handed one. It is a defensive branch on a function that would otherwise index into an empty slice, and deleting it to satisfy a coverage percentage would be the wrong trade.
d1754df to
e31163d
Compare
Closes #2193.
The rule
Beancount's tolerance grammar is
NUMBER ~ NUMBER CURRENCY— one currency, trailing — and it rejects any currency written before the~. This PR differs in both directions, on a single rule: accept what has exactly one meaning, diagnose what has none or contradicts itself.1.00 ~ 0.01 USD0.25 + 0.75 ~ 0.01 USD1.00 ~ 0.005 + 0.005 USD1.00 USD ~ 0.01 USD0.25 + 0.75 USD ~ 0.01 USD1.00 USD ~ 0.01 EUR1.00 ~ 0.001 0.02 USD0.02discardedLaxer on purpose.
1.00 USD ~ 0.01 USDstates the currency twice and agrees with itself. One reading, andrledger formatcanonicalizes it to1.00 ~ 0.01 USDlosslessly — refusing a file whose meaning is not in doubt buys nothing.Stricter because the other two are not redundancy. A tolerance denominated in a currency the amount does not use asserts something the model has no field for; two juxtaposed numbers have no reading at all. Both were accepted, read in part, and the remainder dropped in silence — and
rledger formatthen wrote that loss back to the file:Arithmetic is untouched
~ 0.005 + 0.005and~ 0.005 * 2still evaluate. That is why the second check asks whether the tolerance region fails to parse as an expression, rather than merely counting numbers — counting would have caught the legitimate arithmetic forms too. Verified by value, not just by acceptance: against an account off by 0.007,~ 0.005 + 0.005passes and bare~ 0.005fails.Controls
The third is the one worth having. It stops "just match beancount" being applied later without noticing that it is a decision rather than a cleanup.
Also
docs/reference/compatibility.mdgains a section, including the portability note: a file using the accepted-but-non-standard spelling loads here and is a syntax error in beancount and tools built on it.format-idempotence.shreportschecked=693 non_idempotent=0 diagnostics_changed=0.🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr