Skip to content

fix(booking): check a cost written on an AVERAGE sale against the pool - #2611

Merged
robcohen merged 7 commits into
mainfrom
fix/average-cost-number-spec
Oct 12, 2026
Merged

robcohen merged 7 commits into
mainfrom
fix/average-cost-number-spec

Conversation

@robcohen

@robcohen robcohen commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

What

An AVERAGE sale's cost spec number is now checked against the pool instead of being dropped.

On main, with an AVERAGE pool of 20 X at 11.00 EUR, this books at 11.00 and says nothing:

2024-03-01 * "sell"
  Assets:Brokerage  -1 X {99.00 EUR}
  Assets:Cash       99.00 EUR
  Income:Gains

Under every other booking method a written cost is a filter, and a spec that no lot matches is an error. #2589 already checked the spec's currency against the pool. This PR checks the number too. A number the pool is not is an E4001 error that names the pool's cost:

Assets:Brokerage: AVERAGE pool of X costs 11.00 EUR per unit, not the 99.00 EUR the cost spec states; write the pool's cost or leave the spec empty

The rule (robcohen's decision)

Beancount has no AVERAGE booking (bean-check 3.2.3: AVERAGE method is not supported), so this is rledger's own definition. It is documented under E4001 in docs/reference/errors.md and in an amendment to ADR 0007.

A claim holds when it is a correct rounding of the pool's exact average at the precision written: |claim − average| ≤ w(claim), where w is half a unit in the claim's last written digit, inclusive. This is the rule {*, N} claims already follow (#2398).

  • Per unit. For a pool of 1600/15 = 106.666… USD, {106.67 USD} and {107 USD} hold, and {106.66 USD} and {160.67 USD} do not.
  • Independent of the rest of the transaction. The verdict depends only on the claim and the pool, never on the transaction's other postings or on infer_tolerance_from_cost. {106.67 USD} holds beside cash written 106.667 USD, beside 106.67, beside 107, and with the cash elided.
  • Total {{T}}, compared as a total. The check is |T − average × units sold| ≤ w(T), without dividing T by the units first. For 3 units of the 500/3 pool, {{500.00 USD}} holds and {{500.01 USD}} does not; divided first, 500.01 would pass at 0.0033 per unit.
  • Compound {a # b}. It states the total a × units + b, written in two parts, each rounded to its own places. A correctly rounded a contributes at most units × w(a) to the total's error, and b at most w(b). So it holds within units × w(a) + w(b), which is the reading {*, a # b} already uses. Neither part alone names a pool quantity, because how a total splits between the parts is the author's choice.
  • Exact. The average is never rounded. The new Inventory::reduction_pool_exact sums the pool's units and its cost (each lot's kept exact total from Selling a whole {{T}} lot whose total doesn't divide evenly fails to balance: a lot keeps only its rounded per-unit cost #2425/fix(booking)!: a lot keeps its exact total, and its sales add up to it #2427, else units × per-unit) in BigDecimal. The comparison is |claim × units − total × denominator| ≤ allowance × |units|.
  • Unchanged cases. A spec that names no cost ({}, {EUR}) books at the pool as before. A wrong currency keeps fix(booking): refuse a sale priced or paid in another currency than its cost #2589's error. A {*} sale keeps its own A number in a {*} merge spec is silently ignored: {*, 100 USD} books at the pool's 110 #2398 check, and the two now give the same verdicts (see How tested).

The first head of this PR held the claim to the transaction's tolerance instead. That rule was replaced because it:

  • made the verdict depend on the cash leg;
  • let infer_tolerance_from_cost widen the check by the claim's own value;
  • gave AVERAGE a different rule from {*}.

Validator and BQL

The check runs in booking only, the same place as the {*} check. Here is why the other consumers can't accept what booking refuses:

  • apply, the validator's update_inventories and BQL's replay_posting see only the booked posting, whose cost is already the pool's.
  • A transaction that fails booking is filtered out of the validator's input, so the error is reported once (pinned by the loader test).
  • query and report refuse to derive figures from a ledger with an unbooked transaction. Checked on the CLI: both print 1 transaction(s) could not be booked; refusing to derive figures … naming this error.

A filtered BQL replay builds a different pool on purpose (#1985), so the replay must not re-check the claim.

Breaking

rustledger_core::BookingError gained AverageSpecMismatch. The enum is not #[non_exhaustive], so an exhaustive match on it needs the new arm. Inventory::reduction_pool_exact is new public API.

WASM CACHE_VERSION goes from 38 to 39: a sale that booked before now fails, and Ledger archives booked directives and their errors. The loader cache is unchanged, because parsed directives did not move.

How tested

  • rustledger-booking/tests/average_cost_claim_2603.rs (12 tests). Every test runs through book, book_and_interpolate and book_interpolate_apply, which must agree. It covers:
    • the issue's case and its message, and the pool's own cost;
    • correct rounding: 106.67, 106.7, 107 and 106.666667 hold, while 160.67, 106.66, 106 and 106.6 are refused, and the message shows the pool to the places written;
    • the key regression: {106.67} and {107} beside cash 106.667, 106.67, 107 or elided;
    • the exact half-way case;
    • totals compared as totals (500.01 refused, 333.33 vs 333.34);
    • compound claims within units × w(a) + w(b);
    • covering a short pool, and a later claim against a remainder's exact total;
    • unchanged cases: {}, {EUR}, a wrong currency, and {*}.
  • rustledger-loader/tests/average_cost_claim_test.rs: the full pipeline reports the mismatch exactly once, and infer_tolerance_from_cost does not widen the check (-1.5 X {11.30 EUR} against 11.00 is refused with the option on or off).
  • Fail-without-fix. Against main, 8 of the booking tests fail and the loader mismatch test fails; the other 4 pin behavior that must not change. Against this PR's first head (the transaction-tolerance rule), the 4 rule tests fail (correct rounding, the other-postings regression, totals as totals, compound), and so does the infer_tolerance_from_cost loader test.
  • Independent oracle. A generator writes 1,500 random AVERAGE ledgers. Each has 1 to 4 buys and one sale stating a per-unit or total cost, perturbed around the rounded average by a few units in its last place, with cash written to 0, 2 or 3 places or elided. The generator computes the expected verdict with Python Fractions, from the decided rule as stated above. Against this branch: 662 accepted, 838 refused, 0 mismatches. Self-check: the first head's binary has 49 mismatches in 300 ledgers.
  • AVERAGE vs {*} consistency. The same claim against the same generated pool, as AVERAGE {N} and as FIFO {*, N}, gave 0 disagreements in 800 ledgers with the cash elided and 600 with the cash written to 3 places. Self-check: the first head disagrees in 101 of 300 of the latter.
  • Differential against main: check plus SELECT date, account, position, balance over the repo's 329 ledgers, cache off, gave 0 differences.
  • Checks:
    • cargo test --all-features for rustledger-core, rustledger-booking, rustledger-validate, rustledger-loader and rustledger-wasm: 1,544 passed, 0 failed.
    • Workspace clippy -D warnings and the release-config clippy.
    • cargo doc -D warnings for the changed crates.

Closes #2603

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

An AVERAGE sale books at the pool's average cost, and the cost number in
its spec was dropped: with the pool at 11.00 EUR, `-1 X {99.00 EUR}`
booked at 11.00 without a word. Under every other method a written cost
is a filter, and #2589 already checked the spec's currency.

The number is now a claim about the average. It holds within the
transaction's tolerance for the cost currency of the pool's exact
average (the balance check's tolerance, rounded down, so never looser);
a transaction with no tolerance in that currency holds it to the places
written, as a `{*}` claim is. A total states the total over the units
sold, compared against the pool's exact total, and a compound cost
`a + b / units`. A claim the pool is not is the new
BookingError::AverageSpecMismatch (E4001), naming the pool's cost.

Beancount has no AVERAGE booking, so this is rledger's definition,
documented under E4001 and in ADR 0007. WASM cache version 39.

Closes #2603

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 October 11, 2026 16:51
@github-actions

github-actions Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 46.3ms ± 0.9ms 866.6ms ± 21.3ms 18.7x 51.2 MB / 50.2 MB
investment 76.8ms ± 0.9ms 3106.1ms ± 8.3ms 40.5x 57.3 MB / 58.2 MB
fifo 76.2ms ± 1.2ms 15649.6ms ± 107.6ms 205.3x 57.3 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 46.5ms ± 0.9ms 46.3ms ± 0.9ms -0.6% ✅ within noise 51.2 MB → 51.2 MB (-0.1%)
investment 74.1ms ± 1.0ms 76.8ms ± 0.9ms +3.6% ✅ within noise 57.3 MB → 57.3 MB (-0.1%)
fifo 77.2ms ± 4.0ms 76.2ms ± 1.2ms -1.3% ✅ within noise 57.4 MB → 57.3 MB (-0.1%)

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

@codecov

codecov Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.61062% with 14 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-booking/src/book.rs 88.75% 9 Missing ⚠️
crates/rustledger-core/src/inventory/mod.rs 50.00% 5 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

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

robcohen commented Oct 11, 2026 •

Copy link
Copy Markdown
Member Author

Review rounds (#2603)

First head: transaction-tolerance rule, since replaced

Round Head reviewed Findings Fix
1 5b1c2a7 none (adversarial re-read, boundary probes, Fraction oracle, 329-ledger sweep, suites) —

Decided rule (robcohen): a correct rounding at the precision written

Change: 489876d. The claim must be within half a unit in its last written digit of the pool's exact average, inclusive (the #2398 {*} rule). A {{T}} total is compared as a total (|T − average × units| ≤ w(T)). A compound {a # b} holds within units × w(a) + w(b). The transaction-tolerance threading into book_with is reverted.

Round Head reviewed Checks Findings Fix
1 7de32c4 (rule change + merge of main) New tests fail against the first head (4 rule tests and the infer_tolerance_from_cost loader test) and pass now. Key regression on the CLI: pool 106.666…, cash 106.667 USD: {106.67} passes, {107} passes, {160.67} is refused naming 106.67. Fraction oracle with the decided rule: 1,500 ledgers, 0 mismatches (662 accepted / 838 refused); the first head shows 49 mismatches in 300. New AVERAGE {N} vs FIFO {*, N} consistency sweep: 0 disagreements in 800 ledgers (cash elided) and 600 (cash to 3 places); the first head disagrees in 101 of 300. 329-ledger sweep against main: 0 differences. Suites: 1,544 passed. Both clippy configs and rustdoc are clean. none in the code —
2 7de32c4 Grepped the diff for leftover tolerance wording. Docs (LOW). BookingError::AverageSpecMismatch's doc still described the tolerance rule. 7b9276b
3 7b9276b Re-read E4001, ADR 0007 and the CHANGELOG. Docs (LOW). A code span with a trailing space (units × ) in the compound wording of E4001 and the CHANGELOG. cd54fd3
4 cd54fd3, then e15f989 (merge of main, which had moved to CONFLICTING) Re-read rounds 2–3. Resolved the CHANGELOG as main's file plus this PR's one entry (verified by diff). Post-merge, after #2617's error-chain change: suites 1,545 passed, 0 failed; both clippy configs; rustdoc with and without --document-private-items (#2615's CI gate). WASM CACHE_VERSION is still 38 on main, so this PR's 39 stands. none —

The required checks are green on the final head. Non-required: rustfava shows the expected 8 failed, 671 passed. SemVer (plugin-types) and Slim Build also fail on main.

Merge note: #2616 also bumps WASM CACHE_VERSION from 38 to 39. Whichever of the two merges second must bump to 40.

robcohen and others added 2 commits October 11, 2026 23:21
…sion

robcohen's decision on #2603: a cost written on an AVERAGE sale holds
when it is a correct rounding of the pool's exact average at the
precision written, half a unit in its last written digit, inclusive,
the rule a `{*}` claim follows (#2398). This replaces the
transaction-tolerance rule, whose verdict depended on the cash leg
(`{106.67 USD}` for 106.666... failed beside cash written `106.667`),
which `infer_tolerance_from_cost` widened by the claim's own value, and
which gave AVERAGE and `{*}` different rules.

A total cost is compared as a total, |T - average x units| <= w(T),
not divided by the units first; a compound `{a # b}` states the total
`a x units + b` and holds within units x w(a) + w(b), each part being
rounded to its own places. Booking no longer needs the transaction's
tolerances, so their threading into `book_with` is reverted.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen and others added 4 commits October 11, 2026 23:33
The variant doc still described the transaction-tolerance rule that
#2603's decision replaced. Review round 2.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
A code span with a trailing space (`units × `) read badly in E4001 and
the CHANGELOG. Review round 3.

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.

booking: an AVERAGE reduction ignores the cost number written in its spec

1 participant