Skip to content

fix(core): compute the pooled average cost exactly, escalating to BigDecimal - #2354

Merged
robcohen merged 3 commits into
mainfrom
fix/average-cost-precision-2353
Sep 20, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/average-cost-precision-2353

Conversation

@robcohen

@robcohen robcohen commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

Closes #2353.

Only exact arithmetic is right

#2352 stopped AVERAGE booking pooling small lots at a zero cost and left the
rest: a sum that loses digits without reaching zero is still divided as-is. The
issue offered a cheaper trigger or exact arithmetic. Measured against an exact
reference, counting results more than 100 units in the last place from correct:

comparable small lots whole range
products, divided (main) 28,146 8,894
ratio form when a product vanished, if ratios are well-conditioned 215 8,348
incremental weighted mean (avg += (c − avg)·u/Σu) 0 123,365
exact escalation (this PR) 0 0

Every Decimal-only form wins one population and loses the other, because
rust_decimal keeps 28 decimal places, not 28 significant digits: a small
product loses digits to the floor and a small ratio loses them just the same.
The incremental mean is the best of them on realistic pools and the worst on
wide ones.

Two tiers, the #1240 shape

The Decimal sum of products while every step is exact; otherwise the same
expression in BigDecimal, rounded once — the escalation the balance validator
already uses for an over-precise residual. Ordinary pools stay on the
Decimal path, unchanged to the last digit.

Writing the property test as correctly rounded immediately found that checking
exactness per product is not enough: summing exact products rounds too once
their magnitudes fill the 96-bit mantissa, which left one class two ulps from
correct. An exact addition keeps the larger of the two scales, so the
accumulation is now checked the same way. That seed is committed, and removing
the check fails it deterministically.

The dependency

bigdecimal becomes a dependency of rustledger-core, which had avoided one.
Nothing new enters the workspace — it is already here for #1240 — and the
cost falls on a rustledger-parser-only consumer, which gains four crates on
65 (num-traits is already there). to_bigdecimal is now core's canonical
conversion, and booking's precise residual delegates to it so the two cannot
drift. If you would rather not take the edge, the conditioned heuristic in the
table is the fallback; it is worse on both populations and gives up "never worse
than main".

Performance

check --no-cache, 24,000 transactions with 8,000 AVERAGE reductions, release,
median of 7 interleaved runs:

ledger main this PR
18-decimal amounts (every reduction escalates) 310.3 ms 306.4 ms (−1.2%)
ordinary money 294.3 ms 288.6 ms (−1.9%)

Both inside the run-to-run spread. The 18-decimal figure is the escalation's
real cost, not a path that never ran: its products need 36 decimal places and
come back with 28, which I verified directly. The first attempt at that
benchmark was invalid — Python wrote the cash amounts in exponent notation,
which the grammar rejects — and the assertion that the ledger loads clean is
what caught it.

Review pass: the curve, and a regime with no coverage

Perf was measured on pools of 2–3 lots; the question is the curve. A real
AVERAGE account accumulates lots for years before a sale, and the escalation does
a BigInt multiply per lot. Timing Inventory::reduce directly, best of five,
release:

lots escalated fast path ratio
500 0.100 ms 0.033 ms 3.0×
2,000 0.408 ms 0.139 ms 2.9×
8,000 1.498 ms 0.652 ms 2.3×

Linear — 4× the lots costs 3.7–4.1× the time — so one pool of 8,000 lots
reduces in 1.5 ms against 0.65 ms. No quadratic hiding in the escalation.

Mixed-sign pools had no coverage. The property test draws pools whose lots
share a sign, and a pool holding both directions of one commodity is where a
weighted average is least intuitive: the numerator is a difference of products.
Checked the regime is reachable first (+10 {2.5} and −4 {3.5} reduce at
11/6, correctly rounded), then pinned it with 18-decimal costs so it runs
through the escalation rather than the fast path. Disabling the escalation fails
it.

Both of this PR's claims, verified after the fact:

Tests

The property test now asserts correct rounding outright, where it could only
assert "no fabricated zero, and otherwise the old formula" while the fix was a
heuristic. 20,000 cases over the whole magnitude range, long and short pools.
Both sabotages — escalation disabled, sum-exactness check removed — fail 3 of 3
runs. #2351's reproducers still pass.

2,845 tests across seven suites; clippy, fmt and cargo doc clean at 1.98.1.
Changelog entry added, and #2352's "not fixed" clause corrected, since both ship
in the same unreleased section.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

…Decimal

#2352 stopped AVERAGE booking pooling small lots at a ZERO cost, and left the
rest: a sum that loses digits without reaching zero is still divided as-is, so
the average is wrong in proportion. The issue offered a cheaper trigger or
exact arithmetic. Measured, only exact arithmetic is right.

Three Decimal-only forms, against an exact reference, counting results more
than 100 units in the last place from correct:

                                                comparable small lots   whole range
    products, divided (main)                              28,146           8,894
    ratio form when a product vanished,
      if the ratios are well-conditioned                     215           8,348
    incremental weighted mean                                  0         123,365
    exact escalation (this)                                    0               0

Each Decimal-only form wins one population and loses the other, because
rust_decimal keeps 28 decimal PLACES, not 28 significant digits: a small
product loses digits to the floor and a small ratio loses them just the same.
The incremental mean is the best of them on realistic pools and the worst of
them on wide ones.

So the average is computed in two tiers, the shape the balance validator
already uses for an over-precise residual (#1240): the Decimal sum of products
while every step is exact, otherwise the same expression in BigDecimal, rounded
once. Ordinary pools stay on the Decimal path, unchanged to the last digit.

Writing the property test as "correctly rounded" immediately found that
tracking exactness per PRODUCT is not enough. Summing exact products rounds
too, once their magnitudes fill the 96-bit mantissa, and that left one class two
units in the last place from correct. An exact addition keeps the larger of the
two scales, so the accumulation is checked the same way the products are. The
seed is committed; removing that check fails it deterministically.

This makes bigdecimal a dependency of rustledger-core, which had avoided one.
Nothing new enters the workspace -- it is already here for #1240 -- and the
cost falls on a rustledger-parser-only consumer, which gains four crates on 65.
`to_bigdecimal` is now core's canonical conversion, and rustledger-booking's
precise residual delegates to it so the two cannot drift.

Measured on `check --no-cache`, 24,000 transactions with 8,000 AVERAGE
reductions, release, median of 7 interleaved runs: -1.2% on 18-decimal amounts
and -1.9% on ordinary money, both inside the run-to-run spread. Every reduction
in the 18-decimal ledger escalates -- its products need 36 decimal places and
come back with 28 -- so that figure is the escalation's real cost, not a
measurement of a path that never ran. The first attempt at that benchmark was
invalid (Python wrote the cash amounts in exponent notation, which the grammar
rejects); the assertion that the ledger loads clean is what caught it.

The property test now asserts correct rounding outright, where it could only
assert "no fabricated zero, and otherwise the old formula" while the fix was a
heuristic.

Closes #2353
@robcohen
robcohen requested a review from a team as a code owner September 20, 2026 04:23
@github-actions

github-actions Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 44.8ms ± 0.9ms 829.3ms ± 7.0ms 18.5x 51.1 MB / 50.1 MB
investment 66.1ms ± 0.4ms 3070.2ms ± 33.4ms 46.4x 57.0 MB / 58.1 MB
fifo 64.4ms ± 0.5ms 15680.3ms ± 276.3ms 243.6x 57.2 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 44.4ms ± 0.2ms 44.8ms ± 0.9ms +0.8% ✅ within noise 51.2 MB → 51.1 MB (-0.3%)
investment 66.1ms ± 0.5ms 66.1ms ± 0.4ms +0.0% ✅ within noise 57.1 MB → 57.0 MB (-0.1%)
fifo 64.5ms ± 0.7ms 64.4ms ± 0.5ms -0.2% ✅ within noise 57.0 MB → 57.2 MB (+0.4%)

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

@codecov

codecov Bot commented Sep 20, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.44444% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/booking.rs 93.33% 2 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 99% (raw 93%, 169 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

Review pass over this PR, on perf and on coverage.

Perf, which the last pass measured only on pools of two or three lots. A real
AVERAGE account accumulates lots for years before a sale, and the escalation
does a BigInt multiply per lot, so the question was the curve rather than the
constant. Timing `Inventory::reduce` directly, best of five, release:

    lots    escalated   fast path   ratio
     500     0.100 ms    0.033 ms    3.0x
    2000     0.408 ms    0.139 ms    2.9x
    8000     1.498 ms    0.652 ms    2.3x

Linear -- 4x the lots costs 3.7-4.1x the time -- so a single pool of 8,000 lots
reduces in 1.5 ms against 0.65 ms. No quadratic hiding in the escalation.

Coverage: the property test draws pools whose lots all share a sign, so a pool
holding BOTH directions of one commodity had none, and it is where a weighted
average is least intuitive -- the numerator is a difference of products rather
than a sum of like terms. Checked first that the regime is reachable at all: a
pool of +10 {2.5} and -4 {3.5} reduces at 11/6, correctly rounded. That one
takes the fast path, so the test uses 18-decimal costs to force the escalation,
and asserts its own premise. Disabling the escalation fails it.

Also verified this pass, both claims this PR makes:

The dependency cost. `rustledger-parser`, the published crate that uses core
standalone, goes from 65 dependency crates to 69 -- bigdecimal, libm,
num-bigint and num-integer; num-traits was already there. That is the "+4 on
65" the PR body states, now measured after the change rather than predicted
before it.

The `Update Exemptions` failure is not transient. Re-running the job reproduces
it exactly: `cargo vet regenerate exemptions` cannot parse
supply-chain/audits.toml, where three entries use a `trusted-publisher` key no
released cargo-vet understands. Pre-existing since #2323, path-gated on
Cargo.lock, and tracked in #2355; this branch does not touch supply-chain/.
robcohen added a commit that referenced this pull request Sep 20, 2026
…rust (#2357)

* ci(vet): pin cargo-vet to 0.10.2, the version that parses publisher trust

`Update Exemptions` has failed on every Cargo.lock PR since #2323:

    ERROR × Failed to parse toml file
      ╰─▶ missing field `user-id` for key `trusted.mach2`

My first diagnosis was that no released cargo-vet understands the
`trusted-publisher` key those entries use, and that they should be rewritten as
`user-id` entries. Both halves were wrong, and testing locally is what showed
it.

cargo-vet 0.10.2 parses the store and vets it: "Vetting Succeeded (320 fully
audited, 3 partially audited, 228 exempted)". It also suggests `cargo vet trust
<crate> github:owner/repo` on its own. So the entries are valid.

They are also the only form that works here. Every version we depend on --
mach2 0.6.0, pin-project-lite 0.2.17, portable-atomic 1.15.0 -- was published
through trusted publishing, with NO publishing user; earlier versions of all
three came from a user. A `user-id` entry would therefore match nothing and
silently grant none of the trust it appears to, which is the failure #2321 was
about. Rewriting them, as I had started to do, would have quietly turned three
trusted crates into exemptions.

The defect is the version CI installs. `taiki-e/install-action` with an
unversioned `tool: cargo-vet` takes the newest GitHub RELEASE -- v0.10.0, from
2024-10-03 -- which predates the feature. Its manifest offers no 0.10.2 (checked:
it lists 0.10 and 0.10.0), and there is no 0.10.2 GitHub release for its
binstall fallback either, so the pin has to go through crates.io:

    cargo install cargo-vet --version 0.10.2 --locked

Pinned in supply-chain.yml as well. That job was resolving its own version from
crates.io, so the two could disagree about whether this store parses; now they
cannot.

Verified locally, with the exact commands CI runs: the install succeeds and
yields 0.10.2, `cargo vet regenerate exemptions` exits 0, and `cargo vet
--locked` succeeds.

Two things found while verifying:

`cargo vet check` -- what a contributor runs, without `--locked` -- fails on
main for a missing `audit-as-crates-io` entry on rustledger-budget,
rustledger-ops and rustledger-returns, three first-party crates absent from a
list of fourteen. CI's invocation does not reach that check, which is why it
went unnoticed. Added, and `check` now succeeds.

`regenerate exemptions` prunes one stale exemption (rustls-webpki 0.103.15).
That is the fixed automation's own output, so it ships here rather than waiting
for the next dependency PR.

The job is path-gated on Cargo.lock, so it will not run on this PR; the
evidence is the local runs above, and re-running it on #2354 after this merges.

Closes #2355

* fix(vet): keep the rustls-webpki exemption; its pruning needed imports.lock

My own change broke the `Cargo Vet` job on this PR:

    Vetting Failed!
      rustls-webpki:0.103.15 missing ["safe-to-deploy"]

I had kept half of one output. `cargo vet regenerate exemptions` pruned that
exemption AND updated imports.lock, which is what made it prunable: the audit
covering the crate came from a freshly fetched import. I reverted imports.lock
to keep this PR focused on the version pin and kept the pruning, so the store
claimed an exemption was unnecessary while the audit that replaced it was no
longer there.

It passed locally because my tree still held the fetched imports at that moment.
CI runs `cargo vet --locked`, which forbids fetching them, so the crate came out
unvetted. Verified the fix with `--locked` this time, the flag CI actually uses,
rather than the bare command.

The exemption is back, so this PR now touches only the version pin and the three
missing `audit-as-crates-io` entries; exemptions are byte-identical to main. The
automation can prune it on the next dependency PR, when it updates imports.lock
in the same commit -- which is the point of that job, and it works again once
this merges.
@robcohen robcohen closed this Sep 20, 2026
@robcohen robcohen reopened this Sep 20, 2026
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.

Average cost stays imprecise for small lots whose product sum survives as one or two digits

1 participant