Replace the cost-basis tracker with an in-memory lot book (U1)

Closed
JA
25d ago
+20577-12579

Part of jaysbeekay/sure#551.

Upstream pre-flight for slice U1 of we-promise/sure#4449 (decision 19 on jaysbeekay/sure#551: U1 = PR0 + PR1a). The branch up/551-u1 is cut from upstream main at 6f670ebe7 and carries jaysbeekay/sure#577 and jaysbeekay/sure#578, cherry-picked. Upstream PR: we-promise/sure#4495 (https://github.com/we-promise/sure/pull/4495), opened ready. Same branch, same commit.

Adaptations from the fork commits, all in test/models/investment_statement_test.rb, because upstream lacks three fork-only readers:

  • holdings_table_rows is replaced by upstream's current_holdings (qty, avg_cost, trend);
  • the InvestmentStatement#realized_gains assertions are dropped; the sale's own Trade#realized_gain_loss still pins 392 and nil;
  • the realized_gain_loss_unavailable_reason assertion is dropped.

Problem

Cost basis is a running weighted average per position (Holding::CostBasisTracker). There is no notion of a lot, so nothing can say what each acquisition cost, which a FIFO method, a per-lot cost or a transferred-in parcel's own cost all need (we-promise/sure#4449).

What this changes

Behaviour does not change. This slice adds the lot structure under today's figures. No stored figure moves, and there is no schema change, UI or new param.

  • Characterisation tests first. They pin today's figures before anything moves:
    • the remap merge's weighted cost_basis, and its unknown-side fallback;
    • InvestmentStatement's unrealized figures and the sale's realized gain on we-promise/sure#4449's two-parcel Example (15.20, 888, 608, 392);
    • the same Example with the first parcel transferred in (unknown throughout, and the sale has no realized gain).
  • Holding::LotBook replaces the tracker's internals: an in-memory book of lots per security, used by both holding calculators.
    • One lot per acquisition, 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.
    • A sale relieves every open lot pro rata (the average method), 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 position, because the last open lot takes the rounding.
    • The figure still comes from the running pool of priced acquisitions. That equals the lots' weighted mean, but pro-rata quantities carry BigDecimal rounding the pool does not, so the pool keeps every stored cost_basis byte-identical.
    • The unknown gate is unchanged: a position holding transferred-in units is still reported unknown, as before.
  • Holding::CostBasisTracker stays as a subclass with the same interface (apply, buy, sell, split, average_cost), so code written against it keeps working, including the fallback replay proposed in we-promise/sure#4151.

Blast radius

Who else hits these lines, and what do they pass? The tracker was constructed only by ForwardCalculator and ReverseCalculator#precompute_cost_basis. Both pass a converted, fee-adjusted price (or nil) and a signed quantity to #apply, a Rational ratio to #split, and read #average_cost after each event. apply's new source_id: and acquired_on: keywords are optional. The materializer consumes the same HoldingData fields and is unchanged.

Siblings, unchanged: the label checks (INTERNAL_MOVEMENT_LABELS, TRANSFER_LABEL), Trade#basis_holding, Holding.preload_avg_costs and the remap/reset writes all read snapshot rows or labels, never the tracker.

Tests

  • Characterisation (holding_test.rb, investment_statement_test.rb): four tests that pass on main by design. Run at this head, each of these mutations fails at least one of them: a plain mean in the remap merge, the merge's fallback keeping the moved row's basis, the sale's basis using the holding's quantity, unrealized_gains summing the current value, and the fallback's transfer guard removed. Sale relief and the transfer gate inside the calculators are covered by the lot book tests below.
  • test/models/holding/lot_book_test.rb (new, 19 tests). It keeps today's tracker verbatim as ReferenceTracker, the oracle.
    • Equivalence: the book under average matches the tracker exactly at every step over four sequences (liquidation and repurchase, the two-parcel Example, 1/3 relief with 3:1 and 1:7 splits, unknown prices with an oversell and transfers).
    • Byte identity: forward and reverse materialization write identical holdings rows (date, security, qty, cost basis, source, lock, currency) with the oracle and with the book, on fixtures of more than 20 rows covering a locked manual row, a transfer sold out and bought back, a split with fees, a provider-only position and units held before the first trade.
    • Lots: one per acquisition, keyed by its entry; pro-rata relief keeps each lot's cost; a split restates them; a transfer-in is an unknown lot that does not move the average.
    • Partition: open lots sum to the position after every step, and on every date of the forward calculator.
  • Fail-first: before the book existed, 15 of its 17 original tests errored on the missing constant; the other two are interface and lock guards that pass by design.
  • Mutations (11, all caught): figure from the lots' mean instead of the pool; a transfer counted in the pool; splits not scaling lots, or keeping the unit cost; a sale not relieving lots; rounding not absorbed; either calculator dropping a transfer lot or a lot's source entry; a pool reset clearing the lots.

Validation

  • Full suite at 727a6778c: 13456 runs, 61989 assertions, 0 failures, 0 errors, 36 skips.
  • bin/rubocop: no offenses. bin/brakeman: no warnings.
  • No ERB, JS, migration, API or UI change.

AGENTS.md

I checked the change against the current AGENTS.md:

  • Code placement: model POROs, with Minitest and fixtures. minitest/mock's stub is used only to swap in the oracle.
  • Comments: they describe current behaviour, not history.
  • Commits: subjects are ≤72 characters, with no fork references.
  • Dependencies: none added.
  • Added Holding::LotBook to track acquisition lots, apply pro-rata sale relief, restate lots on splits, and record transfers-in as unknown-cost lots.
  • Updated forward and reverse holding calculators to use the lot book. Kept Holding::CostBasisTracker as a subclass for interface compatibility and retained running-pool cost-basis figures.
  • Added characterization and calculator tests for existing figures, lot behavior, and holding quantity reconciliation.
ContributorLines addedLines removed
jaysbeekay75893