Skip to content

fix(parser): a balance tolerance may follow an arithmetic amount - #2195

Merged
robcohen merged 8 commits into
mainfrom
fix/balance-tolerance-arithmetic
Aug 30, 2026
Merged

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

Conversation

@robcohen

Copy link
Copy Markdown
Member

Closes #2191.

The bug

rledger format could produce a file that no longer loads:

$ cat b.bean
2024-01-15 balance Assets:Cash 0.25 + 0.75 USD ~ 0.01 USD
$ rledger format b.bean
2024-01-15 balance Assets:Cash 0.25 + 0.75 ~ 0.01 USD     <- does not parse

Root cause is the parser, not the formatter. 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, it swallowed the tolerance and handed 0.25 + 0.75 ~ 0.01 to 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 USD and 0.25 + 0.75 USD ~ 0.01 USD both worked. ~ now ends the expression, which is what it means.

A regression this introduced, caught in review

directive_arithmetic_value is shared with price, and a price has no tolerance. Stopping at ~ for both turned price USD 1.10 + 0.05 ~ 0.01 EUR from a diagnosed error into a silent 1.15 with the tolerance discarded. ToleranceForm now 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.1 into 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 holding 0.25 confirming that 0.25 + 0.75 does not match it:

form parses evaluates to
100.00 USD yes 100.00
100.00 ~ 0.01 USD yes 100.00
100.00 USD ~ 0.01 USD yes 100.00
0.25 + 0.75 USD yes 1.00
0.25 + 0.75 ~ 0.01 USD now yes 1.00
0.25 + 0.75 USD ~ 0.01 USD yes 1.00
(0.25 + 0.75) ~ 0.01 USD now yes 1.00

Price: 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

  • The matrix-wide format-fidelity harness that fix(format): stop deleting a note's tags and links #2192 could not land — it fails on balance_with_arithmetic_and_tolerance without this fix, which is how the bug was found. Its floor is raised from > 20 to >= 35 against a measured 37 of 42, so ten fixtures could not start failing to parse unnoticed.
  • A census of which directives keep tags and which refuse them. Seven refuse, three keep, each refusal checked against its tag-free form too. query is in neither set — it accepts a tag and drops it — pinned here as current behavior with query accepts tags and links and silently drops them #2194 filed to decide it.
  • Cache versions: loader 32 → 33, wasm 17 → 18, pin 33. Output moves both ways: a stale blob holds an error where this build makes a balance, and a truncated 1.10 where this build makes an error.

Workspace green, clippy 1.97 clean, fmt/typos clean, parser baseline unchanged, corpus_parity 0 divergences against a freshly built wasip2 component.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

robcohen and others added 5 commits August 30, 2026 08:31
`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.
@robcohen
robcohen requested a review from a team as a code owner August 30, 2026 08:38
Copilot AI lite review requested due to automatic review settings August 30, 2026 08:38
@codecov

codecov Bot commented Aug 30, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

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.

🟡 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 a balance amount expression (tolerance is parsed separately), and diagnose price directives 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-loader and rustledger-wasm to 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_value treats a leading +/- as “arithmetic” (because has_op includes PLUS/MINUS), so a simple signed literal like -0.00 will be evaluated via parse_arith_primary’s -inner path instead of the caller’s fast-path that applies negate_python. That can reintroduce a signed-zero Decimal (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.

@github-actions

github-actions Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 33.8ms ± 2.3ms 496.6ms ± 15.8ms 14.7x 55.0 MB / 50.1 MB
investment 50.8ms ± 3.9ms 1741.3ms ± 46.0ms 34.3x 59.0 MB / 57.9 MB
fifo 47.4ms ± 3.6ms 8887.7ms ± 56.5ms 187.4x 61.1 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 32.9ms ± 0.8ms 33.8ms ± 2.3ms +2.8% ✅ within noise 54.9 MB → 55.0 MB (+0.2%)
investment 50.0ms ± 3.1ms 50.8ms ± 3.9ms +1.7% ✅ within noise 59.1 MB → 59.0 MB (-0.2%)
fifo 48.9ms ± 7.8ms 47.4ms ± 3.6ms -2.9% ✅ within noise 63.1 MB → 61.1 MB (-3.2%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 1.1ms, investment 2.2ms, fifo 3.8ms), 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

@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

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

Copy link
Copy Markdown
Member Author

Fixed — the assertion now matches ParseErrorKind::SyntaxError(m) and searches m, rather than stringifying the whole ParseError with {e:?} and searching that.

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.
@robcohen
robcohen merged commit bda2bbd into main Aug 30, 2026
68 of 69 checks passed
@robcohen
robcohen deleted the fix/balance-tolerance-arithmetic branch August 30, 2026 17:46
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.

rledger format turns a balance with arithmetic + tolerance into a file that no longer parses

2 participants