Skip to content

fix(ffi): a balance diff belongs to its own assertion - #2242

Merged
robcohen merged 2 commits into
mainfrom
fix/ffi-balance-diff-key
Sep 3, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/ffi-balance-diff-key

Conversation

@robcohen

@robcohen robcohen commented Sep 3, 2026

Copy link
Copy Markdown
Member

attach_balance_diffs keyed the validator's results by (date, account, currency). Those three do not identify a balance assertion — a ledger may assert the same account and currency twice on one date with different amounts, and so different differences. Building a map collapsed them, and one directive received the other's diff. Closes #2239.

2024-03-01 balance Assets:Cash    90.00 USD
2024-03-01 balance Assets:Cash   120.00 USD

before  both carry -20.00
after   90.00 carries 10.00, 120.00 carries -20.00

bean-query reports 10.00 and -20.00 here. The query layer had the same collision, fixed in #2238 — which is also what added BalanceActual::asserted, so the fix here is the key, not the semantics.

This surface deliberately attaches a diff for every assertion including passing ones, where it is zero. That is its contract (#1663) and is unchanged, which is why this wasn't folded into #2238.

The asserted number is compared as the string the WIT directive carries. Both sides come from Decimal::to_string() on the same value — amount_from_core for the directive, the validator's record for the map — so they agree by construction rather than by luck. I checked that rather than assuming, since a string key that silently never matched would drop the diff entirely, which is worse than attaching the wrong one.

Tested at the WIT level

The collision is in the map the component builds, so a validator unit test cannot see it. When I filed #2239 I noted I'd read the code but not built a component-level test; this is that test.

The component wasm was rebuilt for both runs. The checked-in one was three days stale, and testing against it would have measured old code whichever way it came out. Against a freshly built unfixed component the test fails with both diffs at -20.00; against a freshly built fixed one it passes.

Full parity suite: 27 passed, including the existing load_reports_balance_assertion_failure that pins the #1663 contract.

No WIT change — the wire contract is untouched, only which record attaches to which directive.

4725 workspace tests green, clippy clean on 1.97.0, typos clean.

`attach_balance_diffs` keyed the validator's results by
`(date, account, currency)`. Those three do not identify a balance
assertion: a ledger may assert the same account and currency twice on
one date with different amounts, and so different differences. Building
a map collapsed them, and one directive received the other's diff.
Closes #2239.

  2024-03-01 balance Assets:Cash    90.00 USD
  2024-03-01 balance Assets:Cash   120.00 USD

    before  both carry -20.00
    after   90.00 carries 10.00, 120.00 carries -20.00

bean-query reports 10.00 and -20.00 here. The query layer had the same
collision, fixed in #2238, which is also what added
`BalanceActual::asserted` -- so the fix here is the key, not the
semantics. This surface deliberately attaches a diff for EVERY
assertion including passing ones, where it is zero; that is its
contract (#1663) and is unchanged.

The asserted number is compared as the STRING the WIT directive
carries. Both sides come from `Decimal::to_string()` on the same value
-- `amount_from_core` for the directive, the validator's record for the
map -- so they agree by construction rather than by luck.

Tested at the WIT level, because the collision is in the map the
component builds and a validator unit test cannot see it. The component
wasm was REBUILT for both runs: the checked-in one was three days stale,
and testing against it would have measured old code either way. The
test fails against a freshly built unfixed component (both diffs
-20.00) and passes against a freshly built fixed one.

No WIT change; the wire contract is untouched.
Copilot AI lite review requested due to automatic review settings September 3, 2026 03:18
@robcohen
robcohen requested a review from a team as a code owner September 3, 2026 03:18

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 doc comment in attach_balance_diffs states passing assertions have a zero diff, but the validator records and exposes the raw signed computed - asserted even when within tolerance, making the contract documentation inaccurate.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Fixes an FFI Component bug where attach_balance_diffs could attach the wrong balance diff to a balance directive when multiple assertions share the same (date, account, currency), by keying the validator results with the asserted amount as well (closing #2239). Adds a WIT-level parity test to prevent regressions at the component boundary.

Changes:

  • Update attach_balance_diffs to key balance actuals by (date, account, currency, asserted) instead of (date, account, currency).
  • Add a parity test that loads a ledger with two same-day balance assertions and verifies each directive receives its own diff.
File summaries
File Description
crates/rustledger-ffi-component/src/convert.rs Fixes the balance-actual lookup key used to attach diff values to WIT balance directives (prevents same-day assertion collisions).
crates/rustledger-ffi-component-tests/tests/parity.rs Adds a component-level regression test covering the same-day, same-account, same-currency double-assertion case.
Review details
  • Files reviewed: 2/2 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.

@codecov

codecov Bot commented Sep 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 Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 45.8ms ± 2.8ms 719.4ms ± 3.6ms 15.7x 55.1 MB / 50.1 MB
investment 69.9ms ± 4.0ms 2741.3ms ± 9.7ms 39.2x 59.0 MB / 58.0 MB
fifo 67.7ms ± 5.0ms 15701.6ms ± 187.5ms 232.0x 61.1 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 46.2ms ± 3.4ms 45.8ms ± 2.8ms -0.8% ✅ within noise 55.1 MB → 55.1 MB (+0.1%)
investment 67.1ms ± 0.5ms 69.9ms ± 4.0ms +4.2% ✅ within noise 59.1 MB → 59.0 MB (-0.2%)
fifo 66.0ms ± 1.9ms 67.7ms ± 5.0ms +2.5% ✅ within noise 60.9 MB → 61.1 MB (+0.3%)

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

github-actions Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 99% (raw 93%, 169 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

The comment claimed a passing assertion carries a diff of zero. It does
not: `BalanceActual::diff` is the raw signed `computed - asserted`,
recorded before the tolerance is consulted, so an assertion that passes
WITHIN tolerance carries its real difference. Measured through the
component: `100.01` asserted against an accumulated `100.00` under a
`0.05` tolerance carries `-0.01`, and only an exact match carries
`0.00`.

That distinction is the reason `#balances.discrepancy` could not reuse
this value directly -- it reports a difference only for failures -- so
the comment was wrong about the very thing it existed to explain.

Caught in review of #2242. No behavior change.
@robcohen

robcohen commented Sep 3, 2026

Copy link
Copy Markdown
Member Author

Right, and the comment was wrong about the thing it existed to explain — corrected in the latest commit.

BalanceActual::diff is the raw signed computed - asserted, recorded before the tolerance is consulted. Measured through the component rather than reasoned about:

asserted=100.01  diff=-0.01   <- passes within a 0.05 tolerance, diff is NOT zero
asserted=100.00  diff= 0.00   <- zero only on an exact match

The comment now says the value is the raw signed difference, zero only on an exact match — and notes that this is precisely why #balances.discrepancy, which reports a difference only for failures, could not reuse it.

@robcohen
robcohen merged commit c648799 into main Sep 3, 2026
47 of 50 checks passed
@robcohen
robcohen deleted the fix/ffi-balance-diff-key branch September 3, 2026 04:08
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.

FFI: attach_balance_diffs collapses same-date assertions on one account, so a Balance can carry another's diff

2 participants