Skip to content

fix(booking): preserve exact lot cost on single-lot wildcard reductions - #2058

Merged
robcohen merged 1 commit into
rustledger:mainfrom
myukitty:fix/single-lot-total-cost-wildcard-reduction
Aug 17, 2026
Merged

robcohen merged 1 commit into
rustledger:mainfrom
myukitty:fix/single-lot-total-cost-wildcard-reduction

Conversation

@myukitty

Copy link
Copy Markdown
Contributor

Summary

Fixes #2048.

On a single-lot match in book(), crates/rustledger-booking/src/book.rs previously recalculated the per-unit cost by re-dividing cost_basis.number / units.number.abs().

For lots acquired via total-cost syntax ({{total}}), the stored per-unit cost c is a full-precision Decimal quotient. In 96-bit fixed-point arithmetic, (take * c) / take does not round-trip identically for certain reduction quantities take (such as -0.02 or -0.029), causing CostSpec::matches in phase 2 (apply_posting) to fail exact equality against lot.cost.number and trigger E4001 No matching lot.

Changes

  • In crates/rustledger-booking/src/book.rs, use the matched lot's stored Cost directly when available (matching how multi-lot expansion already copies cost from each matched lot), falling back to cost_basis.number / units.number.abs() only if no lot cost is present.
  • Added regression tests in test_book_partial_wildcard_reduction_of_total_cost_lot covering multiple partial wildcard reductions (-0.02, -0.029) against a total-cost lot and verifying that lot label and date metadata are preserved.

Verification

  • cargo check --all-features --all-targets (passed)
  • cargo clippy --all-features --all-targets -- -D warnings (passed, 0 warnings)
  • cargo test -p rustledger-booking (all 157 unit/integration tests passed)
  • cargo fmt --check (clean)

When a single lot is matched in `book()`, avoid recalculating the per-unit
cost by re-dividing `cost_basis.number / units.number.abs()`. On lots acquired
via total-cost syntax (`{{total}}`), the stored per-unit cost is a full-precision
quotient; `(take * c) / take` loses 96-bit decimal precision due to rounding,
causing the rewritten cost specification to mismatch the stored lot in phase 2
and throwing E4001 "No matching lot" on partial wildcard reductions (`{}`).

Cloning the matched lot's stored `Cost` directly preserves the exact per-unit
cost along with date and label metadata, matching the behavior of the multi-lot
expansion path.

Fixes rustledger#2048
@myukitty
myukitty requested a review from a team as a code owner August 15, 2026 13:04
@codecov

codecov Bot commented Aug 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.73684% with 3 lines in your changes missing coverage. Please review.

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

📢 Thoughts on this report? Let us know!

@CLAassistant

CLAassistant commented Aug 16, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@robcohen
robcohen merged commit e3123ad into rustledger:main Aug 17, 2026
62 of 64 checks passed
robcohen added a commit that referenced this pull request Aug 23, 2026
* test(compat): add a differential booking fuzzer

Booking decides WHICH lot a reduction consumes. Get it wrong and the
postings still balance, the count is still right and the error list is
still empty — the ledger is simply wrong about what you own and what you
gained. Example-based tests are worst at exactly that, and the fix log
shows it: five booking fixes in twenty commits (#2058, #2069, #2081,
#2093, #2099), each an ordering or lot-selection case nobody had written
a test for.

So this generates ledgers and compares BOOKED LOTS against Python
beancount — an independent implementation, not a restatement of our own
logic. For every account it compares full lot identity, (currency,
per-unit cost, cost currency, lot date) -> units, so consuming the wrong
lot at the same total value is still a failure. It also compares
ACCEPTANCE: a ledger one engine books and the other rejects is a
divergence even when no numbers differ, which is the shape of #2099.

It found a real divergence on its first campaign — 58/60 agreed, both
failures LIFO with same-date lots. Filed separately with a 12-line
reproduction.

Two things learned building it, both encoded in the script:

`cost(position)` is the wrong column to read. For a costless posting it
returns the units themselves, so a cash leg looks like it holds a cost
of 1. `cost_number` is per-unit and null when there is no cost, which is
what makes it the right discriminator. The first draft compared cash
legs against nothing and reported four false divergences per run.

AVERAGE and NONE booking are deliberately not generated: beancount
rejects both outright, so every such run would be a known-unsupported
skip rather than a test.

`--self-test` plants six known outcomes (wrong lot, wrong units, either
side rejecting, and two agreements) and requires each be classified
correctly, then requires the real engines to agree on a hand-checked
ledger. A harness that has only ever printed "no divergences" cannot be
distinguished from one that is incapable of printing anything else; this
one is checked in both directions before it is believed.

* test(compat): address review of the booking fuzzer

Two of the four were real defects, not style.

The `--python` default was `/home/dev/.compat-venv/bin/python` — my own
machine's path, committed. It now defaults to `sys.executable`, which
matches how the sibling compat scripts are invoked (`python3
scripts/compat-values.py`, under an interpreter that already has
beancount) and still takes an override for a dedicated venv.

`json.loads` was unguarded on the rledger side while the beancount side
already caught decode failures. A banner or stray log line on stdout
would have aborted the whole campaign rather than counting as one
booking failure — and the asymmetry between the two paths is what made
it wrong, since the comparison treats them as equivalent. Verified: a
non-JSON stdout now returns ERROR instead of raising.

Also extracted the query out of adjacent string literals so the intent
is explicit, and stopped materializing the seed sequence a second time
after iterating it.

Self-test still passes and seed 35 still reproduces the LIFO divergence
(#2115).
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.

[Bug]: Partial {} reduction of a {{total-cost}} lot fails E4001 "No matching lot" — booked per-unit cost doesn't round-trip to the stored lot cost

3 participants