Skip to content

fix(core): consume interchangeable lots independently of write order - #2138

Closed
robcohen wants to merge 2 commits into
mainfrom
feat/rfc-interchangeable-lot-ordering
Closed

robcohen wants to merge 2 commits into
mainfrom
feat/rfc-interchangeable-lot-ordering

Conversation

@robcohen

Copy link
Copy Markdown
Member

Closes #2118. Implements the rules proposed in rustledger/pta-standards#45, which is in review.

The defect

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, measuring remaining cost basis:

order before after Python beancount
A B C 200.00 250.00 250.00
A C B 250.00 250.00 250.00
C A B 250.00 250.00 250.00
C B A 200.00 250.00 250.00
B A C 150.00 150.00 150.00
B C A 150.00 150.00 150.00

Three outcomes became two. Sorting a journal or switching importers could move a reported cost basis and a realized gain without changing a fact.

Why this direction

No external standard supplies the finer distinction. Treas. Reg. 1.1012-1(j)(3)(i) orders units "in order of time from the earliest date" and is silent 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 ordinarily interchangeable. Lots identical in commodity, basis and date are interchangeable by definition.

So the ordering below date granularity was ours to invent, and deriving it from where a line was typed was the wrong invention. The full argument is in the RFC.

Result

The last divergence class the differential booking fuzzer reported against Python beancount is gone:

250/250 agreed
0 expected divergence(s) (#2118 lot pooling)
  of which 0 are ACCEPTANCE differences
0 unexplained divergence(s)

main reports six on the same sweep, two of them journals one engine refuses to load.

Performance: parity, and that took work

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.

ex-FIFO-2000 ex-FIFO-20000
main 357ms 22021ms
this branch 357ms 21782ms

LIFO, HIFO and STRICT are at parity too.

Worth recording, because the obvious implementations are the slow ones and I wrote two of them before measuring: a scan inside the sort comparator is 9.7x (213s at 20k), rebuilding a map per insert 5.7x, and a dedicated identity map 1.15x to 1.21x. Profiling showed the map was never the cost; rebuilding a lot identity, cloning a currency and a label String on every add, was.

Test note

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 of the test covered only the scan and passed with the insert path's lookup disabled. Each path was verified by mutating it separately.

This is user-visible

Cost basis, realized gains, surviving lot acquisition dates and meta.hash change for any account holding a repeated lot identity within a date, and a reduction naming an explicit cost may begin or cease to resolve. Journals that never repeat a lot identity within a date are unaffected. Changelog entry included.

Merge order

The RFC is in review and this implements its outcome. If reviewers would rather wait for the RFC to be accepted, hold this; the two are consistent by construction and I would rather they land in that order than have the implementation set the precedent.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

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
Copilot AI lite review requested due to automatic review settings August 24, 2026 15:50
@robcohen
robcohen requested a review from a team as a code owner August 24, 2026 15:50
@codecov

codecov Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.00990% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/mod.rs 98.03% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

🔴 Slower than base on: simple, investment, fifo

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 52.4ms ± 6.9ms 790.7ms ± 7.6ms 15.1x 55.1 MB / 49.9 MB
investment 77.2ms ± 4.8ms 2985.2ms ± 7.1ms 38.7x 61.2 MB / 57.9 MB
fifo 71.6ms ± 4.3ms 15407.6ms ± 173.3ms 215.3x 61.2 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 47.8ms ± 4.0ms 52.4ms ± 6.9ms +9.6% 🟡 slower 54.9 MB → 55.1 MB (+0.3%)
investment 73.3ms ± 4.1ms 77.2ms ± 4.8ms +5.3% 🟡 slower 59.1 MB → 61.2 MB (+3.5%)
fifo 67.4ms ± 3.2ms 71.6ms ± 4.3ms +6.2% 🟡 slower 60.9 MB → 61.2 MB (+0.4%)

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

@robcohen

Copy link
Copy Markdown
Member Author

Self-review. The fix is incomplete, and the PR body overstates it. Found by widening the sweep past the 250 seeds CI runs.

What I claimed, and what is true

The PR says the divergence class is gone, citing 250/250 agreed, 0 divergences. That holds at 250 seeds. It does not hold further out:

sweep main this branch
seeds 0-249 6 divergences 0
seeds 0-999 21 divergences (9 FIFO, 12 LIFO) 2, both LIFO
seeds 5000-5499 not measured 1

So this removes roughly 90% of the class rather than all of it, and the remainder is real. Claiming elimination on the strength of the seed window CI happens to run is exactly the mistake the expected/unexplained split in #2120 was meant to prevent.

The residual is LIFO-specific

Reduced from seed 578. The same ledger, changing only the booking method:

  • under FIFO, rledger and Beancount agree (2 x 8.75 remaining)
  • under LIFO, they differ: rledger leaves 2 x 13.25, Beancount leaves 2 x 12.00

That points at LotOrder::DateDescending. It reverses the primary key while the canonical tie-break stays ascending, which is correct for FIFO and evidently not sufficient for a descending walk: an interchangeable group needs to sit at the position its earliest member occupies, and reversing the sort moves the group somewhere else.

I have not confirmed the mechanism, so I am stating it as the leading hypothesis rather than the cause. One hypothesis I did test and disprove along the way: that draining the earliest member of a group shifts the group's position. A minimal ledger doing exactly that agrees with Beancount.

Also verified while reviewing

  • add pushes to cost_index before calling ordered_index_insert, so the canonical lookup always sees a live bucket.
  • Drain-then-reinsert is handled: a lot tombstoned and removed from its bucket lets a later interchangeable acquisition become its own canonical, and the result matches Beancount.
  • No inline review threads or external reviews on either PR yet.

What I am doing

Not merging. I will diagnose the LIFO case, fix it, and re-measure at 1000 seeds and on a fresh seed range rather than the range I have been developing against. The PR body will be corrected to state the measured rate rather than the headline.

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 170 masked)
Full AST Match 100%
Total Files 811
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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR updates rustledger-core inventory booking so that lots that are indistinguishable in the model (same commodity, cost number/currency, cost date, and label) are consumed contiguously from the earliest “interchangeable” lot, making consumption independent of acquisition write order and aligning behavior with the proposed PTA standards rule (and closing #2118).

Changes:

  • Introduces an “interchangeable lot” canonical-slot tiebreak used in ordered booking so identical lots consume as a pooled group rather than by raw slot order.
  • Extends ordered-index maintenance logic to incorporate the canonical-slot tiebreak (build, insert, and rebuild paths).
  • Adds a regression test for FIFO showing interchangeable acquisitions consume identically across write orders, and records the user-visible behavior change in the changelog.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
crates/rustledger-core/src/inventory/mod.rs Adds canonical-slot mapping and uses it as a secondary ordering key in ordered lot indexes and their rebuild/insert logic.
crates/rustledger-core/src/inventory/booking.rs Updates scan fallback ordering to include the canonical-slot tiebreak; adds regression test for write-order independence.
CHANGELOG.md Documents the user-visible change in lot consumption ordering and its implications.
Suppressed comments (2)

crates/rustledger-core/src/inventory/mod.rs:2070

  • build_ordered_index() sorts slots by (order_key, canonical) but omits the final slot tiebreak. However, ordered_index_insert() later assumes the vector is sorted by (order_key, canonical, slot) (it compares existing as a third key inside partition_point). If the initial build doesn’t also sort by slot, the partition_point predicate is not guaranteed monotonic and the binary-search insertion can produce incorrectly ordered indices.
            slots.sort_by_key(|&idx| {
                (
                    self.order_key(order, idx),
                    *canonical_ref.get(&idx).unwrap_or(&idx),
                )

crates/rustledger-core/src/inventory/mod.rs:2409

  • This rebuild path sorts by (order_key, canonical) but omits the slot tiebreak, while ordered_index_insert() maintains ordering by (order_key, canonical, slot). After a rebuild, the index may no longer satisfy the ordering precondition expected by the insert path’s partition_point binary search.
                slots.sort_by_key(|&idx| {
                    (
                        self.order_key(order, idx),
                        *canonical.get(&idx).unwrap_or(&idx),
                    )

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +1910 to +1914
// The new slot's canonical is whatever already claimed its identity,
// or itself when it is the first of its kind.
// ONE identity construction per insert, to place the new slot. Every
// later comparison reads `canonical_of` by slot number.
let own_canonical = self.canonical_via_cost_index(slot);
Comment on lines +558 to +559
let (canonical, _) = self.canonical_slots();
all.sort_by_key(|&i| (self.order_key(order, i), *canonical.get(&i).unwrap_or(&i)));
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
@robcohen

Copy link
Copy Markdown
Member Author

LIFO case fixed in b522c2b. Correctness is now complete; there is a performance regression I have not recovered.

The cause

The first cut derived a group's ordering position from its earliest surviving member. That is not 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.

That is why it was LIFO-specific. The same ledger agrees under FIFO and differs under LIFO, because LIFO reverses the primary key, so a group whose anchor slides ends up 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 is exactly what Python beancount does: 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, and each was a separate bug in the first cut:

  1. add assigns the ordinal before the ordered insert reads it.
  2. cost_index_remove releases it only when the cost bucket holds no other lot with that identity, and asks the bucket rather than every slot: scanning slot_ordinal was O(lots) per drained lot, worth +23%.
  3. rebuild_index repopulates the per-slot view after compaction renumbers slots, while keeping ident_ordinal.

Missing (3) converted two LIFO divergences into one unexplained HIFO divergence, which is a worse failure. The 250-seed sweep would not have shown that either.

Correctness

sweep main previous commit now
seeds 0-999 21 2 0
seeds 5000-5499 not measured 1 0

1000/1000 agreed, 0 expected, 0 unexplained. Capgains fuzzer 200/200, 491 core tests, clippy clean on 1.97.

The regression, stated plainly

main this branch
ex-FIFO-2000 361ms 389ms (+8%)
ex-FIFO-20000 21795ms 24846ms (+14%)

The cost is the ordinal bookkeeping in add. The earlier cost-index approach was at parity and wrong, so this is not a trade I can undo by reverting.

Two things I already removed: an O(lots) scan per drained lot (+23%), and a duplicate cost_key computation per add. What remains is building and hashing a (CostKey, date, label) per acquisition, which is inherent to keying the anchor by identity.

I do not think 8-14% is acceptable to merge as-is, and I would rather say so than bury it. Options, roughly in order of appeal:

  1. Only assign ordinals when a repeated identity actually exists. A ledger that never repeats a lot identity within a date, which is most of them, would pay nothing.
  2. Intern the identity so the key is a u32 rather than a tuple with a String.
  3. Accept the cost on the grounds that the pre-existing behavior was wrong.

I am not marking this ready to merge. The RFC is also still in review, and if it is rejected this branch should be closed rather than optimized.

@robcohen

Copy link
Copy Markdown
Member Author

Tried the more elegant route and it is genuinely better on every axis I can measure, but it changes something wider than this PR is asking for. Both are pushed so the comparison is on the record: feat/merge-interchangeable-lots alongside this branch.

The realisation

add already merged cost-less positions, through simple_slot. The merge machinery was fully general and only the gate was narrow:

let merge_idx = position.cost.is_none().then(|| ...)

Widening that gate to lots agreeing on cost, cost currency, date and label makes the group ONE position, which is what Rule 1 says it is. The whole anchoring apparatus then evaporates: no ident_ordinal, no slot_ordinal, no next_ordinal, no per-slot anchor, and the sort key returns to (order_key, slot) exactly as on main. The group holds its slot until its units reach zero and a re-acquisition lands at the end, both for free, because that is what a single position does.

That is also why the anchoring version needed three separate fixes: it was reconstructing, at three call sites, a property that merging gives you by construction.

It is better on every axis

anchoring (this PR) merging
fuzzer, seeds 0-999 1000/1000, 0 divergences 1000/1000, 0 divergences
ex-FIFO-2000 +8% +2%
ex-FIFO-20000 +14% +5%
code vs the other baseline 109 lines fewer
state to keep in sync 3 maps, 3 call sites none

Why I am not simply switching

It changes what add MEANS, not just how lots are ordered. add(+10 @cost) followed by add(-10 @cost) now nets to one zero-unit position where the codebase deliberately keeps two lots. Six tests fail, and they are a documented decision rather than incidental coverage:

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

with the comment "costed positions are kept as separate lots for O(1) add performance; aggregation happens at display time".

The RFC asks for interchangeable lots to consume as one position. It does not ask for add to become a netting operation. That is a bigger change, it touches short-position handling, and it deserves its own decision rather than arriving as an optimisation inside a lot-ordering fix.

What I would do

Merging is the right end state, and the residual regression on this branch is the price of emulating it. But I would rather land the narrow fix and open the merge separately with those six tests examined one at a time, than fold a change to add's contract into a PR whose stated subject is consumption ordering.

If a reviewer prefers the opposite, the branch is ready to evaluate and the six tests are the entire review surface.

robcohen added a commit that referenced this pull request Aug 24, 2026
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
@robcohen

Copy link
Copy Markdown
Member Author

Superseded by #2139, which takes the merging approach: same semantics, none of the anchoring machinery, and at parity instead of 8-14% slower.

Leaving this open only so the two can be compared. If #2139 is accepted this should be closed unmerged; if a reviewer would rather not change what add means, this branch is the narrower option and its 8-14% regression is the price of emulating merging rather than doing it.

@robcohen

Copy link
Copy Markdown
Member Author

Closing in favour of #2139, which takes the merging approach: same semantics, none of the anchoring machinery, and at parity instead of 8-14% slower.

Keeping the record of why, since the intermediate results are the useful part. This branch emulated "interchangeable lots are one position" by ordering per-acquisition slots around a stable anchor. That needed an identity-to-ordinal map, a per-slot view of it, and a monotonic counter, all kept in step across add, cost_index_remove and rebuild_index. Each of those three was separately wrong at some point during development, because each was reconstructing a property that #2139 gets by construction.

Measured cost of emulating it, against a 22.0s baseline at 20,000 transactions:

scan inside the sort comparator 213s 9.7x
map rebuilt per sort and per insert 124s 5.7x
identity map maintained in the index 26.4s 1.21x
same map keyed by slot 25.2s 1.15x
derived from an existing cost index 21.8s parity, but incorrect
merging in add (#2139) 21.8s parity, correct

The parity row above #2139 is the trap: it was fast and wrong, and only showed up when the sweep was widened past the 250 seeds CI runs.

@robcohen robcohen closed this Aug 24, 2026
@robcohen
robcohen deleted the feat/rfc-interchangeable-lot-ordering branch August 24, 2026 18:11
robcohen added a commit that referenced this pull request Aug 24, 2026
* fix(core): consume interchangeable lots independently of write order

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

* fix(core): anchor an interchangeable group so draining does not move it

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

* explore: merge interchangeable lots in `add` instead of anchoring them

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.

* style: rustfmt after removing the anchor apparatus

* fix(core): store interchangeable lots as one position

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

* docs(core): correct comments left over from the anchoring approach

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

---------

Co-authored-by: Claude Opus 5 <[email protected]>
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.

[Compat]: rustledger keeps a slot per acquisition where beancount pools identical lots — FIFO/LIFO consume in different orders

2 participants