Repository navigation
fix(core): compute the pooled average cost exactly, escalating to BigDecimal - #2354
Merged
Merged
Conversation
…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
Contributor
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
✅ Compatibility Test Results
What's tested
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.
This was referenced Sep 20, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
main)avg += (c − avg)·u/Σu)Every
Decimal-only form wins one population and loses the other, becauserust_decimalkeeps 28 decimal places, not 28 significant digits: a smallproduct 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
Decimalsum of products while every step is exact; otherwise the sameexpression in
BigDecimal, rounded once — the escalation the balance validatoralready uses for an over-precise residual. Ordinary pools stay on the
Decimalpath, 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
bigdecimalbecomes a dependency ofrustledger-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 on65 (
num-traitsis already there).to_bigdecimalis now core's canonicalconversion, 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:
mainBoth 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
BigIntmultiply per lot. TimingInventory::reducedirectly, best of five,release:
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 at11/6, correctly rounded), then pinned it with 18-decimal costs so it runsthrough the escalation rather than the fast path. Disabling the escalation fails
it.
Both of this PR's claims, verified after the fact:
rustledger-parsergoes 65 → 69crates (
bigdecimal,libm,num-bigint,num-integer;num-traitswasalready present) — measured after the change, not predicted before it.
Update Exemptionsis not transient: re-running the job reproduces itexactly.
cargo vet regenerate exemptionscannot parsesupply-chain/audits.toml, where three entries use atrusted-publisherkeyno released cargo-vet understands. Pre-existing since chore(supply-chain): trust ICU4X's sffc and portable-atomic's publisher; regenerate from the PR's store #2323, path-gated on
Cargo.lock, tracked in Update Exemptions fails on every Cargo.lock PR: trusted-publisher is not a key any released cargo-vet understands #2355; this branch does not touchsupply-chain/.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 docclean 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