Repository navigation
fix(core): store interchangeable lots as one position - #2139
Conversation
Two lots agreeing on commodity, cost per unit, cost currency, acquisition date and label are indistinguishable in every attribute the model records. Booking consumed them in acquisition order anyway, so an unrelated lot written BETWEEN them changed which units were sold. Three purchases on one date at two costs, written in the six possible orders, produced three distinct cost bases where Python beancount produces two. Sorting a journal or switching importers could therefore move a reported basis and a realized gain without changing a fact. No external standard supplies the missing distinction. Treas. Reg. 1.1012-1(j)(3)(i) orders units "in order of time from the earliest DATE" and says nothing about sequence within one; IAS 2.23 and ASC 330 treat FIFO as a cost-flow assumption over INTERCHANGEABLE items, reserving specific identification for items that are not. Lots identical in commodity, basis and date are interchangeable by definition, so the finer ordering was ours to invent, and inventing it from an editing accident was the wrong choice. Ordering now breaks ties on the earliest slot holding an interchangeable lot. That removes the last divergence class the differential booking fuzzer reported: 250/250 seeds agree with zero divergences of any kind, where main reports six, two of them ledgers one engine refuses to load. Implemented at PARITY. `cost_index` already buckets slots by (units currency, cost number, cost currency) in slot order, so the earliest interchangeable slot is the first bucket member agreeing on date and label. Buckets hold one or two entries and the lookup hashes three cheap values. The obvious implementations are much worse and are recorded in the RFC: a scan inside the sort comparator is 9.7x, a dedicated identity map 1.15x to 1.21x. ex-FIFO-2000 main 357ms branch 357ms ex-FIFO-20000 main 22021ms branch 21782ms LIFO, HIFO and STRICT are at parity too. The regression test covers BOTH ordering paths deliberately. `try_reduce` on a fresh inventory sorts a scanned list; a reduction after the index exists places later acquisitions through `ordered_index_insert`. An earlier version covered only the scan and passed with the insert path's lookup disabled. This is a user-visible change: cost basis, realized gains, surviving lot dates and `meta.hash` move for any account holding a repeated lot identity within a date, and a reduction naming an explicit cost may begin or cease to resolve. Closes #2118. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
The first cut derived a group's ordering position from its earliest
SURVIVING member. That is not the same thing as the group's position, and
the difference is observable: drain the earliest member and the survivors
jump to wherever the next one sits, so a group that sat before another lot
lands behind it part-way through a ledger.
Found by widening the sweep past the 250 seeds CI runs. At 1000 seeds the
previous commit still reported two divergences, both LIFO. Reduced: the same
ledger agrees under FIFO and differs under LIFO, because LIFO reverses the
primary key, so a group whose anchor slides lands on the wrong side of its
neighbor.
The anchor is now a monotonic ordinal assigned when an identity is first
acquired and released only when no lot carries it. That reproduces Python
beancount exactly, where a pooled position holds its slot in the inventory
dict until its units reach zero and a re-acquired identity is re-inserted at
the end.
Three places had to agree for that to hold, and each was a separate bug in
the first cut:
- `add` assigns the ordinal before the ordered insert reads it
- `cost_index_remove` releases it only when the cost bucket has no lot left
sharing the identity, asking the bucket rather than every slot: scanning
`slot_ordinal` was O(lots) per drained lot, worth +23%
- `rebuild_index` repopulates the per-slot view after compaction renumbers
slots, while keeping `ident_ordinal`, which is the entire reason the
anchor is keyed by identity
Missing the last one turned two LIFO divergences into one UNEXPLAINED HIFO
divergence, a worse failure that the earlier 250-seed sweep would not have
shown either.
Differential booking fuzzer, seeds 0-999: 1000/1000 agreed, zero divergences
of any kind. Seeds 5000-5499, a range never developed against: also zero.
Capgains fuzzer: 200/200. 491 core tests, clippy clean on 1.97.
Costs 8% at 2,000 transactions and 14% at 20,000 on the FIFO shape, from the
ordinal bookkeeping in `add`. That is a real regression and not yet
recovered; the previous approach was at parity but wrong.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Exploratory. Do not merge as-is: six tests encode the contract this changes. `add` already merged cost-less positions through `simple_slot`; the merge machinery was general and only the gate was narrow. Widening that gate to lots agreeing on cost, cost currency, date and label deletes the whole ordinal apparatus the previous commit needed: no `ident_ordinal`, no `slot_ordinal`, no `next_ordinal`, no per-slot anchor, and the sort key goes back to `(order_key, slot)` exactly as on main. Net 109 lines removed against that approach, and it is faster: +2%/+5% at 2,000/20,000 transactions against +8%/+14%. Correctness is identical, 1000/1000 fuzzer agreement with zero divergences. The catch is that it changes what `add` MEANS, not just how lots are ordered. `add(+10 @cost)` then `add(-10 @cost)` now nets to a single zero-unit position where the codebase deliberately kept two lots: test_add_costed_positions_kept_separate test_merge_keeps_lots_separate test_add_costed_positions_net_units test_add_no_cancel_same_sign iter_slots_yields_indices_that_address_their_own_position Those are a documented decision ("costed positions are kept as separate lots for O(1) add performance; aggregation happens at display time"), not incidental coverage. The RFC asks for interchangeable lots to consume as one position; it does not ask for `add` to become a netting operation, and that is a wider change than the one under review. Recorded so the comparison is on the record rather than in a scratch branch.
Supersedes the anchoring approach on #2138. Same semantics, far less machinery, and at parity rather than 8-14% slower. `add` already merged cost-less positions through `simple_slot`. The merge machinery was general and only the gate was narrow. Lots agreeing on commodity, cost per unit, cost currency, acquisition date and label are indistinguishable in the same way: no attribute the model records separates them, so keeping them apart only let the order they were WRITTEN decide which units a reduction consumed (#2118). Widening that gate makes the group one position, which is what Rule 1 of the pta-standards RFC says it is, and what Python beancount stores. Everything the anchoring approach needed then disappears: no identity-to-ordinal map, no per-slot view, no monotonic counter, no anchor in the sort key. Ordering goes back to `(order_key, slot)` exactly as before this work started. The group holds its position until its units reach zero, and a re-acquisition after a full drain lands at the end, both because that is what one position does. That is also why anchoring needed three separate fixes across `add`, `cost_index_remove` and `rebuild_index`: it was reconstructing at three call sites a property merging gives by construction. This changes what `add` MEANS, not only how lots are ordered, so the six tests encoding the old contract were each examined rather than swept: test_add_no_cancel_same_sign -> test_add_merges_same_identity. It asserted two same-cost same-date buys stay separate, which is the exact case #2118 is about. Rewritten, plus a new boundary test that LABELLED lots still stay apart, since that is what labels are for. test_add_costed_positions_kept_separate -> test_add_nets_a_negative_of_ the_same_identity, and test_add_costed_positions_net_units likewise: a negative of the same identity nets into the lot. Booking a sale is unaffected, since that goes through `reduce`. test_merge_keeps_lots_separate -> test_merge_nets_the_same_identity. iter_slots_yields_indices_that_address_their_own_position keeps its subject, which is slot addressing, not merging. It needed two positions equal by value; they now differ by label, so they stay two lots while still comparing equal on units and cost, which is the trap it guards. Differential booking fuzzer, seeds 0-999: 1000/1000, zero divergences of any kind. Capgains fuzzer 200/200. 492 core tests, clippy clean on 1.97. ex-FIFO-2000 main 384ms branch 363ms ex-FIFO-20000 main 21996ms branch 21759ms Faster, for having fewer positions to sort and walk. `corpus_parity` fails identically here and on main (28 files, stale prebuilt wasm), unaffected by this change. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
There was a problem hiding this comment.
Pull request overview
This PR updates rustledger-core’s Inventory::add semantics so that cost-bearing lots that are interchangeable by the model (same units currency, cost number/currency, acquisition date, and label) are stored as a single pooled position—matching the stated RFC rule and aligning behavior with Python beancount’s inventory pooling for identical lot identities.
Changes:
- Extend
Inventory::addmerge behavior from cost-less positions to also merge cost-bearing interchangeable lots viacost_indexlookup. - Make ordered-slot sorting explicitly deterministic by sorting with
(order_key, slot)in both the core index builder and booking scan path. - Update/expand unit tests to reflect the new pooling semantics and to pin “write-order independence” for interchangeable lots; add a changelog entry describing the user-visible impact.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| crates/rustledger-core/src/inventory/mod.rs | Implements interchangeable-lot merging in add, adjusts ordered-index sorting, and updates tests/comments around inventory behavior. |
| crates/rustledger-core/src/inventory/booking.rs | Aligns scan-path candidate ordering with (order_key, slot) tie-breaking and adds a regression test for interchangeable-lot write-order independence. |
| CHANGELOG.md | Documents the user-visible semantics change (pooling interchangeable lots) and its impacts. |
Suppressed comments (3)
crates/rustledger-core/src/inventory/mod.rs:1929
- This comment mentions a slot “anchor” recorded by
add, but there is no anchor concept used inordered_index_insertanymore (the insertion key is(order_key, slot)). This should be revised to avoid implying there’s additional state affecting ordering.
// The slot's anchor is already recorded by `add`, so this reads it.
crates/rustledger-core/src/inventory/mod.rs:2314
- This comment says an “identity map” is rebuilt during compaction, but the code here is rebuilding the ordered index lists after slot renumbering. The current wording is confusing/outdated (especially now that the identity-map machinery from #2138 is gone).
// Compaction renumbers slots, so the identity map is rebuilt with
// them rather than patched.
crates/rustledger-core/src/inventory/mod.rs:1946
- The rustdoc refers to
Self::anchor, but there is noanchormethod, and interchangeable lots are now merged into one position so this tie-break description is no longer accurate. This also risks a broken intra-doc link warning.
/// Ties fall through to [`Self::anchor`], which keeps interchangeable lots
/// together at the position of the first of them and otherwise preserves
/// source order. That tiebreak is ascending for EVERY ordering, including
💡 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?
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Four comments still described an anchor tiebreak that no longer exists: the ordered index sorts by `(order_key, slot)`, with no secondary key, because `add` stores interchangeable lots as ONE position rather than keeping several adjacent. Reported by Copilot on #2139, which caught all four sites. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
|
Good catch, and correct on all four sites — fixed in b4d807e. Those comments were written for the anchoring approach on #2138, which ordered per-acquisition slots around a stable anchor. This PR removed that machinery but I left its documentation behind, so the file described a secondary tiebreak the code no longer has. Corrected:
I also swept the file for other references to the removed machinery ( Worth noting the class of defect: this is documentation describing a design that was replaced, which is exactly the kind of thing that survives review and then misleads the next reader. The four sites you listed were all of them. |
Self-review findings on the new booked-value gate. The step was inserted between an existing comment block and the step it documents, so "Mirrors the BQL step's `--baseline`..." -- written about `Gate on check regressions` -- read as though it described this gate instead. Moved up beside the other comparison gates, which is where it belongs anyway. `steps.booked_values.outputs.failed != '0'` fired on an EMPTY output. When an earlier step aborts the job, this one is skipped, its outputs are unset, and `'' != '0'` is true: the gate ran on an already-red build and annotated it with a booked-value divergence that never happened. Added `outcome != 'skipped'`. Kept `!= '0'` rather than the `== '1'` the fuzz gates use, and said why in a comment: those report a boolean, this forwards the script's exit code, and a usage error exits 2. `--limit` truncates the corpus, so it silently produced a partial divergence set. `--write-baseline --limit 5` would have shrunk the recorded file from 34 entries to whatever the first five files happened to diverge on, and `--baseline --limit 5` reports every unvisited entry as RESOLVED and exits 0. Both read as success. Now refused outright. Dropped a function-local `import os` for `path.name`; `path` is already a `Path` and the KNOWN_POSTING_DIVERGENCES lookup keys on `path.name` two hundred lines up. Documented what the key does not pin: it records WHERE we diverge, not by how much, so a known-diverging cell whose numbers get worse still passes. Pinning values was considered and rejected -- CI installs beancount from master, so its side can move with no change here, and a baseline that churns on upstream commits gets regenerated reflexively instead of read. Also noted that KNOWN_POSTING_DIVERGENCES is the better home for a divergence that has a reason worth writing down. Re-ran every path: baseline clean (known 34, found 34), pre-#2139 binary still exits 1 naming both keys, three malformed-baseline shapes and a missing file each give one line and a non-zero exit, --limit alone is unchanged, self-test passes, actionlint holds at main's 3. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…2148) * test(compat): fail on NEW booked-value divergences against beancount `compat-values.py` compares booked values, per-posting cost/price/lot-date, error kinds and price directives against Python beancount across the corpus. Its docstring says why it exists: a bug producing the right number of postings with the wrong numbers in them "passes silently, which for an accounting tool is the failure that matters most". Nothing failed when it found one. The step was `continue-on-error`, `main()` returned 0 unconditionally, and no gate read the output -- it went to `compat-values.txt` and the step summary. Every other comparison in this workflow is gated (budget, booking, capgains, returns, check regressions, synthetic differential); this one was not. A PR introducing a fresh divergence printed it into a summary and stayed green. Gating on ANY divergence was never an option, which is presumably how it ended up this way. There are 34 today, largely rustledger carrying an exact value where Python's `decimal` context rounds an intermediate at 28 significant digits: number: beancount=-720.0200000000000000000000001 rledger=-720.02 price_number: beancount=54.13684210526315789473684211 rledger=54.136842105263157894736842105 rustledger is arguably the better side of those, and a gate that failed on them would simply be switched off again. So this takes the shape the BQL step already uses in the same workflow: a recorded baseline, where only departures fail. `--write-baseline` records the current set, `--baseline` fails on anything outside it, and a divergence that GOES AWAY is reported as RESOLVED rather than failing, so the file can be trimmed instead of silently accumulating entries that pin nothing. Keys are (basename, field), matching how `KNOWN_POSTING_DIVERGENCES` is already keyed: the corpus is fetched to different absolute paths in CI and locally, so a baseline keyed on full paths would match nothing and pass everything. Verified in both directions, which is the only way a gate is worth having: against its own baseline exit 0, "known 34, found 34, new 0" against a pre-#2139 binary on a ledger exercising #2118 exit 1, naming "value:Income:Gains USD" and "posting:<row count>" Closes #2147. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * test(compat): report a malformed baseline instead of a stack trace The baseline is generated, so two PRs that both record divergences collide in it, and an unresolved conflict marker is the likeliest way it goes bad. Only FileNotFoundError was handled, so that surfaced as a JSONDecodeError traceback in a CI log. Also validates shape, which is the quieter half. `set(map(tuple, raw))` turns a bare string entry into a tuple of its characters rather than a key, so a hand-edit leaving `["value:x"]` instead of `[["f.beancount", "value:x"]]` would match nothing and report every known divergence as new, with nothing in the output to say why. Each rejection path was run: a conflict marker, a list of bare strings, and a pair with a non-string element all give one line and exit 1. The real baseline still reports known 34, found 34, new 0. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * test(compat): fix gate placement, skip-safety and the --limit footgun Self-review findings on the new booked-value gate. The step was inserted between an existing comment block and the step it documents, so "Mirrors the BQL step's `--baseline`..." -- written about `Gate on check regressions` -- read as though it described this gate instead. Moved up beside the other comparison gates, which is where it belongs anyway. `steps.booked_values.outputs.failed != '0'` fired on an EMPTY output. When an earlier step aborts the job, this one is skipped, its outputs are unset, and `'' != '0'` is true: the gate ran on an already-red build and annotated it with a booked-value divergence that never happened. Added `outcome != 'skipped'`. Kept `!= '0'` rather than the `== '1'` the fuzz gates use, and said why in a comment: those report a boolean, this forwards the script's exit code, and a usage error exits 2. `--limit` truncates the corpus, so it silently produced a partial divergence set. `--write-baseline --limit 5` would have shrunk the recorded file from 34 entries to whatever the first five files happened to diverge on, and `--baseline --limit 5` reports every unvisited entry as RESOLVED and exits 0. Both read as success. Now refused outright. Dropped a function-local `import os` for `path.name`; `path` is already a `Path` and the KNOWN_POSTING_DIVERGENCES lookup keys on `path.name` two hundred lines up. Documented what the key does not pin: it records WHERE we diverge, not by how much, so a known-diverging cell whose numbers get worse still passes. Pinning values was considered and rejected -- CI installs beancount from master, so its side can move with no change here, and a baseline that churns on upstream commits gets regenerated reflexively instead of read. Also noted that KNOWN_POSTING_DIVERGENCES is the better home for a divergence that has a reason worth writing down. Re-ran every path: baseline clean (known 34, found 34), pre-#2139 binary still exits 1 naming both keys, three malformed-baseline shapes and a missing file each give one line and a non-zero exit, --limit alone is unchanged, self-test passes, actionlint holds at main's 3. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr --------- Co-authored-by: Claude Opus 5 <[email protected]>
… (#2488) The migration guide's "Repeated same-day lots" item and the booking fuzzer's "expected" bucket still described #2118 as an open divergence. It was fixed in v0.23.0 (#2139): interchangeable lots are stored as one position, as Python beancount does. - docs/migration/from-beancount.md: the worked example now books the same on both engines (checked: 10 ACME {20.00 USD} + 5 ACME {10.00 USD} left, -150.00 USD gain, bean-check clean). The item now says the engines agree since v0.23.0 and what older releases did. - scripts/compat-booking-fuzz.py: the #2118 waiver is now a tripwire. A divergence on a ledger with a repeated lot identity within a date is labeled as a likely #2118 regression, counted on its own line, and fails the run. same_totals (only used by the waiver) is gone; a new classify() carries the verdict and has its own self-test cases. - compat.yml: the step comment no longer says #2118 does not fail CI. Verified: self-test passes; seeds 0-249 (the PR window) agree 250/250 with the current binary; the v0.22.0 release binary trips the tripwire on seed 117 (exit 1). Closes #2392 Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Supersedes #2138, which should be closed if this is accepted. Same semantics, far less machinery, and at parity rather than 8-14% slower. Implements Rule 1 of rustledger/pta-standards#45.
The realisation
addalready merged cost-less positions, throughsimple_slot. The merge machinery was fully general and only the gate was narrow:Lots agreeing on commodity, cost per unit, cost currency, acquisition date and label are indistinguishable in exactly the same way: no attribute the model records separates them. Keeping them apart only let the order they were written decide which units a reduction consumed (#2118).
Widening that gate makes the group one position, which is what the RFC says it is and what Python beancount stores. Everything #2138 needed then disappears: no identity-to-ordinal map, no per-slot view, no monotonic counter, no anchor in the sort key. Ordering returns to
(order_key, slot)exactly as before this work began. The group holds its position until its units reach zero and a re-acquisition after a full drain lands at the end, both because that is what one position does.That is also why #2138 needed three separate fixes across
add,cost_index_removeandrebuild_index: it was reconstructing at three call sites a property merging gives by construction.Faster, for having fewer positions to sort and walk.
This changes what
addmeans, so here are the six tests, one at a timeIt is not only an ordering change, and the tests encoding the old contract were examined individually rather than swept:
test_add_no_cancel_same_signtest_add_merges_same_identity, plus a new boundary test that labelled lots still stay apart, since that is what labels are for.test_add_costed_positions_kept_separatereduce, notadd.test_add_costed_positions_net_unitstest_merge_keeps_lots_separatemergeadds each position, so the same identity lands in one. Renamed.iter_slots_yields_indices_that_address_their_own_positioninterchangeable_lots_consume_independently_of_write_orderThe
add(+10)/add(-10)netting is the part worth a reviewer's attention. It is a real change to a documented contract, and it is why I did not fold this into #2138 as an optimisation.Verification
corpus_parityfails identically here and onmain(28 files, stale prebuilt wasm), unaffected🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr