Skip to content

fix(parser): diagnose a balance tolerance that says two things at once - #2200

Merged
robcohen merged 8 commits into
mainfrom
fix/balance-tolerance-grammar
Aug 31, 2026
Merged

robcohen merged 8 commits into
mainfrom
fix/balance-tolerance-grammar

Conversation

@robcohen

Copy link
Copy Markdown
Member

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.

form beancount 3.2.3 before after
1.00 ~ 0.01 USD ok ok ok
0.25 + 0.75 ~ 0.01 USD ok ok ok
1.00 ~ 0.005 + 0.005 USD ok ok ok
1.00 USD ~ 0.01 USD syntax error ok ok (kept)
0.25 + 0.75 USD ~ 0.01 USD syntax error ok ok (kept)
1.00 USD ~ 0.01 EUR syntax error ok, EUR discarded diagnosed
1.00 ~ 0.001 0.02 USD syntax error ok, 0.02 discarded diagnosed

Laxer on purpose. 1.00 USD ~ 0.01 USD states the currency twice and agrees with itself. One reading, and rledger format canonicalizes it to 1.00 ~ 0.01 USD losslessly — 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 format then wrote that loss back to the file:

$ rledger format m.bean          # before this PR
2024-01-15 balance Assets:C 1.00 ~ 0.01 USD     <- the EUR is gone from the file

Arithmetic is untouched

~ 0.005 + 0.005 and ~ 0.005 * 2 still 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.005 passes and bare ~ 0.005 fails.

Controls

mutation result
disable the currency-mismatch check fails
disable the juxtaposed-number check fails
over-strict: also reject the agreeing-currency form fails

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

  • Every row of the test table was run against beancount 3.2.3 and records what it does, so the divergence is legible where someone would change it.
  • docs/reference/compatibility.md gains 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.
  • 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.
  • Workspace green, clippy 1.97 clean, fmt/typos/rustdoc clean, corpus baseline unchanged, format-idempotence.sh reports checked=693 non_idempotent=0 diagnostics_changed=0.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

@robcohen
robcohen requested a review from a team as a code owner August 31, 2026 13:22
Copilot AI lite review requested due to automatic review settings August 31, 2026 13:22
@codecov

codecov Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/convert.rs 99.01% 1 Missing ⚠️
crates/rustledger-parser/src/cst/format.rs 98.66% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 49.5ms ± 6.1ms 850.3ms ± 12.1ms 17.2x 55.0 MB / 50.1 MB
investment 71.6ms ± 2.7ms 3074.0ms ± 30.8ms 42.9x 59.0 MB / 58.0 MB
fifo 68.0ms ± 4.3ms 15527.1ms ± 256.6ms 228.3x 61.0 MB / 58.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 49.5ms ± 5.1ms 49.5ms ± 6.1ms -0.0% ✅ within noise 54.9 MB → 55.0 MB (+0.1%)
investment 73.8ms ± 5.1ms 71.6ms ± 2.7ms -3.0% ✅ within noise 58.9 MB → 59.0 MB (+0.3%)
fifo 68.7ms ± 3.5ms 68.0ms ± 4.3ms -1.1% ✅ within noise 61.1 MB → 61.0 MB (-0.2%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 3.6ms, investment 2.6ms, fifo 2.5ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

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.

🟢 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 balance directives 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.

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 170 masked)
Full AST Match 100%
Total Files 811
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

@robcohen

Copy link
Copy Markdown
Member Author

Applied in the latest commit, and the point led somewhere.

The two Vecs are gone — you're right that cost_region_value takes the same &[SyntaxToken] the tail is already a slice of, so building a Vec<&SyntaxToken> and then cloning every token back out bought nothing. The region is sliced out of tail now.

The bigger waste was upstream of it. The function collected every direct token of the directive before checking whether there was a ~ at all — on a path that runs for every balance in every ledger, where the vast majority carry no tolerance. That check is now an iterator and the common path allocates nothing.

And chasing it turned up two more things. The check was commenting on input it doesn't understand: on ~ .005 + .005 the lexer already reports the real problem, and this added "the second was being discarded" next to it — a claim about input that never parsed. It now requires the region to be expression-shaped.

Which surfaced the actual bug: .005 is a number beancount accepts and we reject, in every numeric position — postings, balance amounts, prices, tolerances, metadata. Filed as #2201; out of scope here since the fix is in the number lexer and moves parser output corpus-wide.

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.
@robcohen
robcohen force-pushed the fix/balance-tolerance-grammar branch from d1754df to e31163d Compare August 31, 2026 18:41
@robcohen
robcohen merged commit cb4b6ee into main Aug 31, 2026
66 of 69 checks passed
@robcohen
robcohen deleted the fix/balance-tolerance-grammar branch August 31, 2026 19:25
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.

A balance tolerance silently ignores a second number: ~ 0.001 0.02 USD uses 0.001

2 participants