Replace the cost-basis tracker with an in-memory lot book
Summary
This replaces Holding::CostBasisTracker's internals with Holding::LotBook, an in-memory book of lots per security. Both holding calculators use it. The method is average only, and the change is byte-identical: no stored figure moves. There is no schema change, no UI and no new params.
- One lot per acquisition. Each lot is keyed by its source entry, with its own
acquired_on, open quantity and per-unit cost. A transfer-in is a lot of unknown cost. - Disposals and splits. Under
average, a sale relieves every open lot pro rata, so each lot keeps its own cost. A split restates every lot: more units at a lower cost, with the same money. For any history that never goes negative, the lots sum exactly to the trade-driven position, because the last open lot takes the rounding. A sale with nothing held is not recorded in the book (see the scope note below), so after it the lots can exceed the position; PR 1b, which stores lots, reconciles that. - The figure.
#average_coststill comes from the tracker's running pool of priced acquisitions. That equals the lots' weighted mean, but pro-rata lot quantities carry BigDecimal rounding the pool does not, so the pool keeps every storedcost_basisbyte-identical. - The nil gate is unchanged. The calculators still report a position holding transferred-in units as unknown, using the same position-based gate as before. On a reverse account that gate depends on units held before the first imported trade. The book does not hold those until PR 1b adds the opening lot, and owner decision 8 keeps that lot out of the mean.
- Interface kept.
Holding::CostBasisTrackerstays as a subclass with the same interface (apply,buy,sell,split,average_cost), so code written against it keeps working. That includes the fallback replay proposed upstream in we-promise/sure#4151, which owner decision 11 keeps.
Part of jaysbeekay/sure#551
Stack: PR 1a of 7. PR 0 (jaysbeekay/sure#577) merged into main on 2026-10-23 (a9ef4fc40), so this PR now targets main. The order is PR 0 <- 1a <- 1b <- 2 <- 3 <- 4 <- 5 (owner decision 7 on jaysbeekay/sure#551). PR 1b adds holding_lots storage on top of this branch.
Blast radius
Who else hits these lines, and what do they pass? Holding::CostBasisTracker was constructed only by ForwardCalculator (:11) and ReverseCalculator#precompute_cost_basis (:130). Both pass the same arguments:
- a converted, fee-adjusted acquisition price (or nil) and a signed quantity to
#apply; - a
Rationalsplit ratio to#split; - and they read
#average_costafter each event.
The materializer consumes the resulting HoldingData.cost_basis / cost_basis_unknown and is unchanged. Both calculator paths change in this one commit. apply's new source_id: and acquired_on: keywords are optional, so existing call shapes still work.
Siblings (re-grepped at f666272b9)
| Pattern | Sites | Status |
|---|---|---|
CostBasisTracker | forward_calculator.rb:11, reverse_calculator.rb:130, test/models/holding/cost_basis_tracker_test.rb | Both calculators moved to LotBook. The tracker test is unchanged and green against the subclass. |
INTERNAL_MOVEMENT_LABELS / TRANSFER_LABEL | holding.rb:112,421,427, realized_gains.rb:226, flow_classifier, daily_returns.rb:585, provider_import_adapter.rb:246, event.rb:178 | Unchanged: they classify trades by label and never read the tracker. The Sweep In divergence between holding.rb:112 and :421 stays tracked in jaysbeekay/sure#420. |
basis_holding | trade.rb:192,231,254 | Unchanged: it reads snapshot rows, whose figures do not move. It changes in PR 2. |
preload_avg_costs | holding.rb:83, investment_statement.rb:100,901, realized_gains.rb:267 | Unchanged: snapshot readers. |
update_columns( / update_all( on holdings and trades | holding.rb:289,304,314,342,352 (remap/reset) | Unchanged here. Nothing is stored yet, so there is nothing to re-key; that comes in PR 1b. |
Tests
New file: test/models/holding/lot_book_test.rb (19 tests). It keeps today's tracker verbatim as ReferenceTracker, the oracle.
Positive
lot book under average reproduces the tracker, over 4 sequences: buys, partial sells, full liquidation and a repurchase; the two-parcel example; non-terminating (1/3) relief with 3:1 and 1:7 splits; and an unknown price, an oversell and transfer lots. It asserts exact equality at every step.materialize writes identical holdings with lots, on the forward and reverse strategies. Each run starts from an empty holdings table, so a figure left by an earlier run can't stand in. Each compares every[date, security, qty, cost_basis, cost_basis_source, cost_basis_locked, currency]row with the calculators running on the oracle against the same with the lot book, using array equality. It also asserts the dump has more than 20 rows with both nil and calculated figures, and a provider row on the reverse run.- The forward fixture has the two-parcel example with a locked manual row; a transfer-in sold out and bought back; a negative position that a transfer brings back to zero; and a 3:1 split with fractional sales and a fee.
- The reverse fixture has a provider-only position, units held before the first trade, and a gapped import whose trades net to more than the provider reports.
- Lot identity:
- each acquisition is one lot keyed by its source entry, and a later buy leaves earlier lots alone;
- pro-rata relief keeps each lot's cost (60@12 + 40@20, sell 40, gives 36 and 24, with a mean of 15.20);
- a split restates lots;
- the reverse calculator books a lot per acquisition, a transfer-in included.
Negative
locked manual row keeps its value through re-materialization with lots present: the value is 99 and the lock and themanualsource are kept. The neighbouring unlocked row still takes 15.20.transfer-in leaves the position unknown while its lot is held, and known once sold out: nil on d3 and d4 and 15 on d7. Only the rebuy's lot (its entry id, d7, 8 units at 15) is open afterwards.a transfer-in is a lot of unknown cost and does not move the average.a sale that empties the priced pool leaves every lot's share of what is still held.- Partition:
sum of open lot qty equals the running position after every step(book level);sum of open lot qty equals the trade-driven position on every date(forward calculator, every date of 3 positions, crossing buy, sell, transfer and split).
the tracker keeps its public interface.
The PR 0 pins (holding_test.rb remap merge 60 / unknown side, and investment_statement_test.rb two-parcel 15.20 / 888 / 608 / 392 / transfer-in nil) are unchanged and green.
Fail-first. On the PR 0 head, 15 of the 17 tests then written error with uninitialized constant Holding::LotBook or a nil @lot_books. The other two are guards that pass on today's code by design: the interface test and the locked-row test. The reverse identity test was added after the first commit. With only the reverse calculator change stashed, it errors with undefined method '[]' for nil. The pool-reset test was added because mutation M11 survived; it fails under M11 (table below).
The partition and figure guarantees hold for non-negative histories. A position that goes negative (a sale with nothing held) clamps in the book exactly as the tracker did, so the book and the position cannot agree there. The forward partition fixture excludes that position, and the byte-identity fixture includes it.
Mutation checks
Each mutation was applied to the committed fix. I ran lot_book_test, cost_basis_tracker_test, the forward and reverse calculator tests, materializer_test, holding_test and investment_statement_test (274 runs), then restored the file from the commit.
| # | Mutation | Caught by |
|---|---|---|
| M1 | figure from the lots' mean instead of the pool | tracker oracle (non-terminating; transfer lots), forward byte-identity, transfer-lot average (4 failures) |
| M2 | transfer-in lot counted in the pool | tracker oracle (transfer lots), forward byte-identity, transfer-lot average (3) |
| M3 | split leaves lots unscaled | split restates lots, both partition tests, lots' mean vs average (4) |
| M4 | sale does not relieve lots | pro-rata relief, sell-out closes every lot, both partition tests, transfer-in calculator test (5) |
| M5 | rounding drift not absorbed by the last lot | book partition (1) |
| M6 | split keeps the per-unit cost | split restates lots, lots' mean vs average (2) |
| M7 | forward: transfer-in books no lot | forward per-date partition (1) |
| M8 | forward: buy lot loses its source entry | transfer-in calculator test (1) |
| M9 | reverse: transfer-in books no lot | reverse lot-per-acquisition (1) |
| M10 | reverse: buy lot loses its source entry | reverse lot-per-acquisition (1) |
| M11 | pool reset also clears the lots | a sale that empties the priced pool ... (added for this; it survived before) |
Validation
-
Full suite on the exact head
e0623d95b(beastpc, 6 workers): 14329 runs, 66639 assertions, 0 failures, 0 errors, 38 skips. No baseline failures appeared, so none are listed. -
bin/rubocopon the changed files: no offenses. -
bin/brakeman: no warnings. -
erb_lint, Biome and system tests: not applicable, since no ERB, JS or UI changed.
There is no migration in this PR.
Size: about 160 non-test lines added (lot_book.rb 135, calculators 20, tracker subclass 4), and about 93 removed (the tracker body moved into LotBook).
Checked against upstream AGENTS.md:
- logic lives in models/POROs;
- comments describe current behaviour, not history;
- the commit subject is 72 characters or fewer;
- Minitest is used, with
minitest/mock'sstubonly to swap in the oracle; - no new dependency.
Summary by CodeRabbit
- New Features
- Holdings now track individual acquisition lots, including trade details, through buys, sells, transfers, and stock splits.
- Improvements
- Average-cost calculations now account for priced and unknown-cost units, including pro-rata reductions when holdings are sold.
- Cost basis is updated consistently across forward and reverse portfolio calculations, including when a position is fully sold.