Skip to content

fix(booking)!: check a {*} merge spec's cost, currency, date and label - #2416

Merged
robcohen merged 6 commits into
mainfrom
fix/merge-spec-cost-number-2398
Sep 25, 2026
Merged

robcohen merged 6 commits into
mainfrom
fix/merge-spec-cost-number-2398

Conversation

@robcohen

@robcohen robcohen commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Problem

{*} merges an account's lots into one pool at their weighted-average cost. Anything else the spec wrote was dropped without a word. Holding 10 X at 100 and 10 X at 120 (a pool of 20 at 110):

sale before after
-5 X {*} 110 110
-5 X {*, 110.00 USD} 110 110
-5 X {*, 100.00 USD} / {100.00 USD, *} 110, the 100 dropped error: the merged pool costs 110.00 USD per unit, not the 100.00 USD the cost spec states
-5 X {*, 110.00 EUR} 110 error: the pool is held in USD
-5 X {*, 2024-01-01} / {*, "lot"} 110 error: the merged lot has no date or label
-5 X {{*, 600.00 USD}} 110 error: 5 X at the pool's 110 cost 550.00
-5 X {*, 100 # 50 USD} 110 checked as the total 550

The rule

Beancount has no merge to compare with (Cost merging is not supported yet). The issue proposed reading the number as an assertion of the pool's cost, and this PR applies that to every part of the spec:

  • Cost: it must be the pool's cost at the precision written, meaning within half a unit in the last place written. On top of that, the allowance covers the pool's own rounding. A pool that fills Decimal's ~28 significant digits was rounded, so half a unit in its last place is added, once per unit sold for a total. This matters for a cost written as an expression ({{*, 1604500/66 USD}}): without it, 32 of 150 generated correct total claims were refused. An exact pool adds nothing, so a pool of exactly 110.00 still refuses a stated 110.01. A stated number that fills Decimal's digits comes from an expression, and how many times it was rounded depends on how the expression was written, so it is held to one unit in the place before its last digit. Typed numbers keep half a unit in the last place written. The pool is a quotient and seldom has a finite decimal: for a pool of 106.666… USD, {*, 106.67 USD} and {*, 107 USD} hold, and {*, 106.66 USD} does not. This is deliberately not the ledger's balance tolerance, which bounds how far two sides of a transaction may disagree; this compares one number with itself.
  • Total and compound: checked as a total, meaning what the units sold cost at the pool's price. A compound cost's allowance is the sum of both parts' (the per-unit part's counted once per unit).
  • Currency: must be the pool's.
  • Date or label: refused, because the merge builds one undated, unlabeled lot.

An accepted claim still books the pool's own unrounded cost, not the number written.

The error message gives the pool's cost to the places the spec writes, which is the number the author should have written. A mismatch is more than half a unit away, so it never rounds to the stated number.

Where the check lives

The check runs only in BookingEngine::book, on the spec as written, before a compound cost is folded into one total so each part keeps its precision. apply, the validator and the query replay see booked postings, whose cost is the pool's by then. A filtered query replay builds a different pool on purpose (#1985), so checking there would reject correct answers.

Breaking

  • A ledger whose merge spec states a wrong cost, a wrong currency, a date or a label now fails booking. Before, it booked at the pool's cost.
  • rustledger_core::BookingError gains MergeSpecMismatch, reported as E4001 like any cost spec that names no lot. Its detail type is the new rustledger_core::MergeSpecMismatch. BookingError is not #[non_exhaustive].
  • Wasm cache v29: a restored Ledger skips booking and serves its cached errors. The loader cache holds only parsed directives, and I confirmed the error still appears from a warm loader cache.

Tests

  • crates/rustledger-booking/tests/merge_spec_claims_test.rs covers the precision rule at both edges, total and compound costs, currency, date and label, and an accepted cost booking the exact pool and applying. It also checks that a -Decimal::MAX stated cost is reported rather than panicking.
    • With the check disabled, the 4 rejection tests fail.
    • With an unchecked subtraction, the overflow test panics.
  • wildcard_merge_test ([Compat]: a trailing * cost component does not set the merge flag #2329) pinned {100.00 USD, *} booking at 110, which is the drop this fixes. It now expects the error.
  • Sweep over five expression forms (1,100 generated correct claims: r*S/N, S/N*r, sums of rounded parts, scaled fractions): none refused. Every claim shifted by 0.01, and by 1E-20: all refused.
  • The boundary is pinned: for a pool of 100.5, both 100 and 101 hold. The message for each detail variant is pinned in core.
  • Mutation testing on the diff (cargo mutants --in-diff, 17 mutants): 13 caught and 3 didn't compile. The one survivor is the message formatter. It lives in core, and the test that catches it is in booking, which a core-only mutation run doesn't execute; the core message test added after that run covers it.
  • Workspace: 172 test binaries, 0 failures. cargo clippy --workspace --all-features --all-targets -D warnings and cargo doc -D warnings are clean.

Closes #2398

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`{*}` computes its cost, and everything else a merge spec wrote was
dropped without a word: `-5 X {*, 100.00 USD}` against a 110 pool booked
at 110, and a wrong currency, a date or a label passed the same way.

Each is now a claim checked against the merged pool. A cost must be the
pool's at the precision written (half a unit in the last place; a
compound cost sums both parts' allowances), a total or compound cost is
checked as what the units sold cost, a currency must be the pool's, and
a date or label is refused since the merged lot has neither. An accepted
claim still books the pool's own unrounded cost. The check runs in
`book` only: apply, the validator and the query replay see booked
postings, and a filtered replay builds a different pool on purpose.

New `BookingError::MergeSpecMismatch` (E4001) with `MergeSpecMismatch`
detail; wasm cache v29.

Closes #2398

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner September 24, 2026 20:33
@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.17486% with 7 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-booking/src/book.rs 94.92% 7 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 45.1ms ± 1.8ms 825.4ms ± 6.9ms 18.3x 51.0 MB / 49.9 MB
investment 68.6ms ± 0.9ms 3035.8ms ± 24.5ms 44.3x 54.8 MB / 58.1 MB
fifo 65.5ms ± 0.8ms 15610.7ms ± 440.8ms 238.2x 55.1 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 44.6ms ± 0.7ms 45.1ms ± 1.8ms +1.2% ✅ within noise 51.0 MB → 51.0 MB (-0.1%)
investment 67.6ms ± 0.6ms 68.6ms ± 0.9ms +1.4% ✅ within noise 54.9 MB → 54.8 MB (-0.2%)
fifo 65.8ms ± 1.1ms 65.5ms ± 0.8ms -0.4% ✅ within noise 57.0 MB → 55.1 MB (-3.4%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.9ms, investment 0.5ms, fifo 0.6ms), 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%, 178 masked)
Full AST Match 100%
Total Files 813
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 and others added 2 commits September 24, 2026 20:47
Mutation testing the #2398 diff left two survivors: `>` to `>=` in the
precision check (no test stood exactly half a unit from the pool) and an
empty `MergeSpecMismatch` Display (only the loader test read the text).
A pool of 100.5 now holds for 100 and 101, and each detail variant's
message is pinned in core.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
A `{*}` cost written as an expression (`{*, 500/3 USD}`) has 28 decimal
places, where half a unit in the last place cannot be written, so the
allowance fell to zero and the claim was compared exactly. It and the
pool are both quotients rounded to 28 places, each up to half a unit
from the true value, so an exact comparison would reject a correct claim
whenever the two roundings landed on neighboring digits. Eight probed
pools happened to round identically; the allowance should not rely on
that.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

robcohen commented Sep 24, 2026 •

Copy link
Copy Markdown
Member Author

Deep review (three passes)

Fixed: correct claims written as expressions were refused (80fd42f, ebae0b1). A total claim is checked against units × pool. When the pool doesn't divide evenly, Decimal rounds it to about 28 significant digits, and that rounding error is carried once per unit sold. A correct total written as an expression is rounded only once.

For example, {{*, 1604500/66 USD}} for 50 units of a 32090/66 pool landed 1e-24 away from units × pool. That is outside half a unit in the last place written, so the claim was refused. In a sweep of 150 generated correct total claims, 32 were refused.

The first pass's fix, a floor of one unit in the 28th place, didn't reach these: Decimal holds 28 significant digits, not 28 decimal places, so the floor never applied. rounding_bound replaces it:

  • A result that fills Decimal's digits counts as rounded and adds half a unit in its last place: once per unit for the pool, and once for the product.
  • A shorter result is exact and adds nothing, so an exact 110.00 pool still refuses 110.01.

Fixed in pass 3: claims that are sums of rounded parts (ab46b6c). The pool-rounding allowance assumed the stated number was rounded once, which holds for r*S/N. Other ways of writing the same total round more than once. r*a/N + r*b/N rounds three times, and one of 200 generated correct totals written that way landed two units out in the last place and was refused. A stated number that fills Decimal's digits can only be an expression's result, so its last digit is noise. It is now held to one unit in the place before its last digit. Typed numbers keep half a unit in the last place written.

Sweep, with a check that it can fail:

  • Five expression forms, 1,100 generated correct claims (r*S/N, S/N*r, sums of rounded parts, scaled fractions): none refused.
  • Every claim shifted by 0.01, and by 1E-20: all refused.
  • Before the fix, per-unit claims never failed: the claim and the pool are the same fraction rounded the same way. Only totals did.

Checked, no change needed

  • Other code paths:

  • Two merge sales in one transaction: each is checked. A wrong claim on the second is refused.

  • Shorts: a {*} buy that closes a short pool is checked the same way.

  • Negative stated cost: it gets E4005 plus the merge mismatch, the same as main gives a plain {-100 USD} sale (E4005 plus "No matching lot").

  • No currency: {*, 166.67} is compared in the pool's currency.

  • Caches: the loader cache stores parsed directives, and the error appears from a warm cache. The wasm cache holds booked errors, hence v29.

  • Mutation testing on the diff:

    • Earlier survivors (the half-unit boundary, the message text, a digit count one short at exactly 28 digits) are all pinned now.
    • The latest booking run: 17 caught, 2 didn't compile, none survived.
  • Style: the unit tests now sit below the test module's imports.

  • CI: required checks green on ab46b6c. Three fuzz jobs in that run were cancelled together about three minutes in, with no failing job and no newer run to replace them. They passed on every earlier head, and on a rerun they passed here too. The advisory rustfava check fails on the same five stale snapshots as fix(loader)!: read account-name options as leaves under a root, as beancount does #2415, none merge-related.

  • Known limit, not this PR's: for pools of very small lots, Average cost stays imprecise for small lots whose product sum survives as one or two digits #2353 left the pool cost itself off by more than a few units in its last place. A claim that is correct against the true pool could be refused there, because the pool is what's wrong.

Pre-existing bugs this review found (not in this PR)

  1. A whole pool whose average cost doesn't divide evenly fails to balance (Selling a whole AVERAGE or {*} pool at a non-terminating average cost fails to balance (residual -1E-26) #2417). Example: 1 X at 100 plus 2 X at 200, sold as -3 X {*} for 500 USD. It also happens with an AVERAGE account and {}. The result is Transaction does not balance: residual -1E-26 USD, even though the posted cash is written to whole dollars.
  2. A {*} that no merge runs for drops its claims silently (A {*} merge spec on a buy (or a NONE-method sale) is silently ignored, with its cost, date and label #2418). On a buy, 5 X {*, 100.00 USD} books a lot at 100. On a NONE-method account, a {*} sale doesn't reduce a lot, so -5 X {*, 100.00 USD} against a 110 pool passes. Beancount rejects merges outright ("Cost merging is not supported yet").

robcohen and others added 3 commits September 24, 2026 22:29
A total claim is checked against `units x pool`, and a pool that fills
Decimal's digits was rounded, so its error is carried once per unit. A
correct total written as an expression (`{{*, 1604500/66 USD}}` for 50
units of a 32090/66 pool) rounds once and landed 1e-24 away, outside
half a unit in the last place written: 32 of 150 generated correct total
claims were refused. The 28-place floor added before did not reach them,
since Decimal holds 28 significant digits, not 28 decimal places.

A result that fills the digits (28 or more) now counts as rounded, and
the allowance adds half a unit in its last place, per unit for the pool
and once for the product. Shorter results are exact and add nothing, so
an exact 110.00 pool still refuses 110.01. Swept: 0 of 300 generated
correct claims refused; all 300 refused when shifted by 0.01 or by 1e-20.

Also moves the two unit tests below the test module's imports.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Mutation testing left `l + 1` -> `l * 1` in the digit count alive: the
only rounded fixture had 29 digits, which clears the threshold either
way. 1/3 has 28 and must still count as rounded.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
A stated cost that fills Decimal's digits was not typed but computed,
and how often the expression rounded depends on how it was written:
`r*S/N` rounds once, `r*a/N + r*b/N` three times. Half a unit in its
last place assumed once, and one of 200 generated correct totals summed
from parts landed two units out and was refused. Such a number is now
held to one unit in the place before its last; typed numbers keep half
a unit in the last place written.

Swept five expression forms (1,100 correct claims): none refused, and
all refused when shifted by 0.01 or by 1e-20. Mutation testing on the
booking diff: 17 caught, 2 unviable, none missed.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
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 number in a {*} merge spec is silently ignored: {*, 100 USD} books at the pool's 110

1 participant