Skip to content

fix(parser): evaluate arithmetic in metadata values and balance tolerances - #1945

Merged
robcohen merged 3 commits into
mainfrom
fix/arith-everywhere
Aug 4, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/arith-everywhere

Conversation

@robcohen

@robcohen robcohen commented Aug 3, 2026 •

Copy link
Copy Markdown
Member

#1942 has landed. Rebased onto main with git rebase --onto — a squash-merge leaves a stacked branch conflicting, which showed here as DIRTY until the rebase. Now a single-parent branch off main.

#1939 was an instance of a class. Auditing 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 before after
6 2 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

Tolerance is 0.010, so it passes — beancount loads it with zero errors. rledger truncated to 0.005 and raised E2002, and the message printed ~ 0.005, so the diagnostic itself displayed the bug.

The audit

Nine of the eleven 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 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, generic over TokenView since #1942, 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.

I checked against the oracle before touching the expectation — "the test disagrees with my change" is not evidence about which one is wrong. The reasoning is recorded in the test.

Cache and baselines

Two caches, not one. Loader CACHE_VERSION 18 → 19 and wasm 4 → 5 — rustledger-wasm archives Vec<Directive> behind its own version, and missing it on #1942 is exactly what review caught there. The rule: a parser change that alters a value bumps both.

Loader CACHE_VERSION 18 → 19. Values move, layout doesn't — which is precisely 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 applies; the MetaValue layout hash is unchanged and the assertion 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 (2 lines), same reasoning as #1942.

Verification

  • each position pinned, and each verified to fail on its own sabotage:
    assertion failed: tolerance arithmetic must be evaluated; 0.005 would reject a valid file
    assertion failed: metadata arithmetic must be evaluated (beancount reports 6)
    
  • green/red test over six shapes including two malformed ones, so they degrade identically rather than failing identically by accident
  • parser 606, loader 184, validate 155, query 631, booking 161 — all passing
  • cargo +1.97.0 clippy clean, cargo fmt --check clean

Refs #1944.

@robcohen
robcohen requested a review from a team as a code owner August 3, 2026 20:05
Base automatically changed from fix/cost-spec-arithmetic to main August 3, 2026 20:42
…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.
Copilot AI review requested due to automatic review settings August 3, 2026 20:46
@robcohen
robcohen force-pushed the fix/arith-everywhere branch from cd6a3c4 to 7121c3f Compare August 3, 2026 20:46
@robcohen
robcohen enabled auto-merge (squash) August 3, 2026 20:47

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.

Pull request overview

Fixes two additional parser truncation bugs (same class as #1939/#1942) by routing metadata numeric values and balance ... ~ tolerance numbers through the shared arithmetic evaluator, ensuring green/red CST conversions behave identically and cached parse outputs are invalidated when values change.

Changes:

  • Evaluate arithmetic expressions in metadata values (e.g. key: 2 * 3) and balance tolerances (e.g. ~ 0.005 * 2), instead of latching the first NUMBER token.
  • Add regression tests to pin correct evaluation and green/red parity for these positions.
  • Bump loader + wasm cache versions and update the affected parser-corpus baseline entries.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/baselines/parser-corpus.manifest Updates baseline hashes for the two parser-lima arithmetic fixtures affected by corrected evaluation.
crates/rustledger-wasm/src/cache.rs Bumps wasm parsed-ledger cache version (v4→v5) to invalidate cached directives whose values now differ.
crates/rustledger-parser/tests/fuzz_regressions.rs Adds regression tests for metadata/tolerance arithmetic evaluation and green/red agreement.
crates/rustledger-parser/src/cst/convert.rs Implements arithmetic-aware extraction for balance tolerance and metadata values via the shared evaluator.
crates/rustledger-loader/src/cache.rs Bumps loader cache version (v18→v19) and fixture tripwires to prevent stale cached parses with old truncated values.
Suppressed comments (1)

crates/rustledger-parser/tests/fuzz_regressions.rs:224

  • This assertion compares a Debug-formatted string for Option, which is brittle and can fail due to formatting differences rather than semantic regressions. Prefer a typed equality check against the expected Decimal value.
            assert_eq!(
                format!("{:?}", b.tolerance),
                "Some(0.010)",
                "tolerance arithmetic must be evaluated; 0.005 would reject a valid file",
            );

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 35.2ms ± 2.9ms 24.2 MB
beancount 900ms ± 6.1ms 50.7 MB
Comparison 25.6x faster 2.1x less

vs main branch (2026-08-03)

Metric main this PR Change
Time 37ms 35.2ms -4.9% ✅
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@codecov

codecov Bot commented Aug 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

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

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.
Copilot AI review requested due to automatic review settings August 4, 2026 02:11

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.

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

  • number_meta_value intentionally treats exponent literals (e.g. 1e3) as MetaValue::Number, but the new arithmetic path passes dec.to_string() as the text hint. rust_decimal::Decimal renders in non-exponent form, so an expression like num: 1e3 * 1 would likely be classified as Int(1000) instead of Number(1000), changing downstream behavior (e.g. query typing) compared to the non-arithmetic literal case (num: 1e3). Consider preserving an exponent "hint" from the source tokens when deciding Int vs Number.
        // Render the RESULT to decide Int vs Number, so `2 * 3` is Int(6) —
        // what beancount reports — rather than inheriting the first operand's
        // spelling.
        return number_meta_value(&dec.to_string(), dec);

@robcohen
robcohen merged commit 0f46e56 into main Aug 4, 2026
71 of 72 checks passed
@robcohen
robcohen deleted the fix/arith-everywhere branch August 4, 2026 02:40
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.

2 participants