Repository navigation
fix(core): report an ambiguous STRICT match instead of guessing FIFO (closes #2097) - #2099
Conversation
…loses #2097) When a reduction's cost spec matched several lots, `plan_strict` compared their cost NUMBER and CURRENCY only; if those agreed it drained them oldest-first. The comment justifying it claimed the user "could not have observed a different outcome" and that "beancount falls back to FIFO in that case". Neither holds. Beancount's `booking_method_STRICT` has no fallback at all: more than one match is the total-match exception or an `AmbiguousMatchError`. And the outcome is observable, because the lots differ in ACQUISITION DATE. Selling 16 against `4 GLOB {74.09, 2022-05-10}` + `16 GLOB {74.09, 2024-02-09}` leaves 4 GLOB dated 2024 under FIFO and dated 2022 under any other choice — same cost basis, which is what kept it quiet, but a different holding period. This codebase acts on holding periods, in `report capgains`'s short/long split and in per-lot IRR eligibility. So the fallback made a tax-visible choice silently, under the one booking method whose purpose is to make the user state it. The comparison is now the FULL cost — number, currency, date and label. Lots identical in all four stay interchangeable, which is not a concession: beancount's inventory is keyed by (currency, cost), so two buys of the same commodity at the same price on the same day are ONE position there and can never be ambiguous. Ours keeps two lots, so deleting the arm outright would have rejected that very ordinary ledger. Comparing the whole cost reproduces beancount's observable behavior without changing how positions are stored. Found while sizing #2096: the `investment` profiling shape generates sales of this form, so it loaded cleanly under rledger and failed under bean-check. Its sells now name the lot by cost AND date. That is not cosmetic — costs are drawn from tens of thousands of strings across thousands of buys per ticker, so collisions are a birthday-problem certainty, and at n=10000 there were 46 of them. `check-profile-workloads.sh` gains the cross-check that would have caught this: every shape must load under bean-check too, where it is available. It also gains `fifo`, which had never been checked at all despite being the shape added because ordered selection was unprofiled. Corpus: of 735 files, exactly one changes — and it changes to AGREE with beancount, which reports `Ambiguous matches` on the same line. Comparing exit status alone showed no differences at all; that file already failed on an unopened account, so only comparing error TEXT surfaced it.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
Pull request overview
Fixes a Beancount-compatibility bug in STRICT booking where rustledger previously resolved ambiguous lot matches by silently draining FIFO, and updates profiling workloads + tests to prevent regression.
Changes:
plan_strictnow treats multiple matching lots as ambiguous unless their full cost is identical (number, currency, date, label), preserving the “total-match” exception behavior.- Updates generator + workload checks so the
investmentprofiling shape disambiguates sells by cost and acquisition date, and addsfifoto the verified shapes plus an optionalbean-checkcross-check. - Updates/extends core + validator tests and documents the behavior change in the changelog.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| scripts/gen-profile-workload.py | Makes investment sells include acquisition date in the cost spec to avoid STRICT ambiguity. |
| scripts/check-profile-workloads.sh | Verifies fifo shape, asserts the dated-lot syntax for investment, and optionally cross-checks shapes with bean-check. |
| crates/rustledger-validate/src/lib.rs | Updates validator regression test to assert AmbiguousLotMatch for partial sale matching two dated lots under STRICT. |
| crates/rustledger-core/src/inventory/mod.rs | Updates inventory-level tests to require ambiguity for same-cost/different-date partial matches, and keeps total-match exception covered. |
| crates/rustledger-core/src/inventory/booking.rs | Changes STRICT matching from “same number+currency” to “full cost equality” for indistinguishable lots; otherwise reports ambiguity (except total-match). |
| CHANGELOG.md | Adds breaking-change entry describing STRICT ambiguity reporting change and rationale. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
📊 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?
|
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Found reviewing the STRICT fix in this PR — the same defect, one method
over, and it produces a wrong number rather than a wrong error.
Beancount's `booking_method_STRICT_WITH_SIZE` sorts the size matches by
`cost.date` and takes the first. Ours took the first in SLOT order, which
is insertion order. That is usually date order, so the two usually agreed
by accident — but a lot carrying an explicit cost date is inserted when
its transaction books and dated whenever the user wrote:
2024-01-01 * "buy A"
Assets:B 10 X {100.00 USD, 2030-01-01}
2024-01-02 * "buy B"
Assets:B 10 X {200.00 USD, 2020-01-01}
2024-02-01 * "sell by size"
Assets:B -10 X {} @ 300.00 USD
Both lots are size 10, so size does not disambiguate. beancount sells the
2020 lot and leaves 1000.00 USD of basis; slot order sold the 2030 lot
and left 2000.00. Neither tool reports anything. Verified against 3.2.3;
rledger now also answers 1000.00.
Ties break on slot index so the choice stays deterministic when two size
matches share a date, and `None` dates sort last: a booked lot always
carries one.
The new test builds its lots in the opposite order to their dates, which
is what makes it fail on the old code — a fixture in date order would
have passed either way.
|
Deep review pass. It found the same bug one method over, and that one returns a wrong number rather than a wrong error.
|
Review feedback. The change to a 3-tuple added a comment rather than updating the one already there, leaving two adjacent lines describing the same variable differently — the older one still saying (units, cost).
* 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).
Closes #2097.
What was wrong
plan_strictcompared matched lots by cost number and currency only, and drained them oldest-first when those agreed. The comment justifying it said the user "could not have observed a different outcome" and that "beancount falls back to FIFO in that case". Neither is true.booking_method_STRICThas no fallback: more than one match is the total-match exception or anAmbiguousMatchError.report capgains's short/long split (feat(report): realized capital-gains / tax-lot report (capgains) #1860) and per-lot IRR eligibility (feat(report): realized IRR for capgains (--irr) #1861). Cost basis is identical either way, which is exactly what kept it quiet.A silent, tax-visible lot choice, under the one booking method whose purpose is to make the user state it.
The fix is a narrowing, not a deletion
Comparison is now the full cost — number, currency, date and label. Lots identical in all four remain interchangeable.
That is not a hedge. Beancount's
Inventoryis keyed by(currency, cost), so two buys of the same commodity at the same price on the same day are one position there and can never be ambiguous. Ours keeps two lots. Deleting the arm outright rejected that ledger — I tried it first, and a same-day same-price pair started failing:Comparing the whole cost reproduces beancount's observable behaviour without changing how positions are stored. Merging at
addwould be the more faithful model and a much larger change —Inventory::lencounts lots andcurrency_accountsbranches on it — so it is noted in the code rather than attempted here.Agreement, measured
AmbiguousAmbiguous✓No position matchesCorpus
Of 735 files, exactly one changes —
parser-lima/test-cases_TotalsAndSigns.TotalCost.beancount— and it changes to agree with beancount, which reportsAmbiguous matcheson the same line.Worth flagging how nearly I missed that: comparing exit status showed zero differences, because that file already failed on an unopened account. Only comparing error text surfaced it. A status-only sweep answers "does it still pass", not "does it behave the same".
Fallout fixed here
gen-profile-workload.py'sinvestmentshape generates sales of exactly this form, which is why it loaded under rledger and failed under bean-check — the observation that started #2097. Its sells now name the lot by cost and date. Not cosmetic: costs are drawn from a few tens of thousands of strings across thousands of buys per ticker, so collisions are a birthday-problem certainty — 46 of them at n=10000.check-profile-workloads.shgains the cross-check that would have caught this years earlier: every shape must load underbean-checktoo, where it is available. It also gainsfifo, which had never been checked at all — the shape added because ordered selection was unprofiled was itself unverified.Both new tests were confirmed to fail on
main.