Store holding lots and re-key them on remap and reset

Merged
JA
24d ago
+981-24

Replaces #4496, closed so the stack can be a native GitHub stack (heads in this repo). Its review history, including jjmata's threads and their answers, stays there.

Part of #4449.

Slice 2 (U2) of the per-lot cost basis series that #4449 proposes. Slice 1 (#4495) is merged. This is the bottom of a GitHub stack of the remaining slices: each one targets the branch below it, and the stack map in the merge box shows the order. Merge bottom-up.

In short. Lots now persist: a holding_lots table holds each account's lots per security, written by the materializer from the calculators' lot books, and remap/reset re-key them. Look first: Holding::Materializer, HoldingLot.store!, Holding::ReverseCalculator#open_lots. Check: bin/rails test test/models/holding_lot_test.rb test/models/holding/lot_book_test.rb.

Fork pre-flight: jaysbeekay/sure#600 (https://github.com/jaysbeekay/sure/pull/600), which holds this slice's CI and review history. Same commits: the pre-flight runs on the fork's copy of this branch. It ports the merged fork PR jaysbeekay/sure#579, whose review history is there too.

Problem

Slice 1 keeps lots in memory during a sync and throws them away. Every later step in #4449 (FIFO disposals, a user's cost on one lot, remap moving lots) needs lots that persist between syncs and follow their trades.

What this changes

A new holding_lots table holds each account's lots per security. The holdings materializer writes them from the calculators' lot books on every sync.

  • Derived lots. One per acquiring trade (a buy or a transfer-in), keyed by its source entry. A closed lot stays at qty 0.
  • Opening lots. One per position, for units no imported trade accounts for. On the reverse path this is the baseline the walk already computes: the units held before the first trade, or the whole provider quantity when there are no trades. It is seeded as an unknown-cost lot, so sales relieve it pro rata like any other, and it stays out of the average.
  • Clamp. Where the provider reports fewer units than the trades add up to, the opening lot is stored at qty 0 with clamped: true. Nothing else changes.
  • Forward keeps opening lots. Only the reverse walk produces opening lots, so a forward materialization (for example, the first sync after a provider is unlinked) leaves them in place and keeps only derived lots in step.
  • Remap and reset. remap_security! and reset_security_to_provider! move lots with their trades in the same transaction. An opening lot keeps origin_security_id, so a reset returns it.

Two book rules land with storage:

  • Shortfall. A sale beyond the open lots becomes a shortfall. The next acquisitions fill it before they open a lot, so open lots equal the position. A split restates the shortfall.
  • Rounding. Pro-rata relief rounds each lot to the stored scale (18), and the residual goes to the last open lot.

Every stored figure is unchanged. Nothing reads lots yet, and the pool the figure comes from is untouched. Slice 1's characterisation pins and byte-identity dumps pass unedited. No UI, no params, average only.

Blast radius

Who else hits these lines, and what do they pass? Only Balance::Materializer calls Holding::Materializer#materialize_holdings, from account sync, remap/reset and trade edits. It passes account, strategy and an optional security_ids. The same account and security scope now also writes holding_lots, and lots for out-of-scope securities are left alone.

Siblings:

CodeStatus
Both calculatorsChanged: they expose lots_by_security; reverse seeds opening lots and records clamps
CostBasisTracker < LotBookUnchanged interface; its pool and average_cost are line-for-line unchanged
Transfer gates, Holding#calculate_avg_cost, FlowClassifierUnchanged: they read trades, not lots
Trade#basis_holdingUnchanged: it reads holdings rows, which do not change
Holding#remap_security!, #reset_security_to_provider!Changed: lots move with the trades
Snaptrade split repair, Trade Republic rematch, securities.rake, data_migration.rakeUnchanged. They move trades without lots, and the next materialization's upsert re-keys each derived lot to its trade's security. The security_id FK cascades, so destroying a duplicate security is not blocked by its lots
import_holding and the provider processorsUnchanged: they write provider holdings rows, from which the opening lot is derived

Migration notes

db/migrate/20261023090000_create_holding_lots.rb: schema only, reversible (change), no data backfill. Lots appear at each account's next materialization.

  • Columns: account_id, security_id (FKs, cascade); source_entry_id (FK to entries, cascade, so deleting a trade deletes its lot; nil marks the opening lot); origin_security_id (FK, nullify); acquired_on; qty decimal(34,18) as holdings.qty; unit_cost decimal(25,10), the same 15 integer digits as holdings.cost_basis; currency; clamped; timestamps.
  • Indexes and constraints: unique (account_id, source_entry_id); partial unique (account_id, security_id) WHERE source_entry_id IS NULL, one opening lot per position; source_entry_id, security_id, origin_security_id; check qty >= 0.
  • Verified: migrate, rollback and migrate again in a throwaway test container. db/schema.rb takes only this table's hunks.

Tests

test/models/holding_lot_test.rb, 21 tests.

  • Book rules, failing before: the shortfall after a sale with nothing held, then a transfer-in; a split restating the shortfall; the rounding residual on the last open lot.
  • Storage: a buy adds one lot and leaves earlier ones untouched (ids, created_at); open lots equal the snapshot quantity on every forward date across a buy, sale, 3:1 split and transfer-in, and equal the provider snapshot on reverse, opening lot included; a provider-only position keeps its provider basis; the opening lot does not move the figure; a clamp is stored and recorded, and flips both ways on re-materialization; an opening lot goes once the trades explain the position; a forward sync after unlinking keeps opening lots.
  • Lifecycle: deleting a trade deletes its lot; a buy edited into a sale loses its lot; a trade moved to another security without its lot takes the lot along; remap and reset move lots, keeping ids; remap onto a position with its own opening lot leaves one there.
  • Mutations (22, all caught): each book rule, each storage rule, the remap and reset moves, the upsert keys, and the forward/reverse opening-lot handling. Two survived the first round, and the tests that catch them were added.

Validation

  • Full suite at d9290e2ec: 13477 runs, 62070 assertions, 0 failures, 0 errors, 36 skips.
  • bin/rubocop: no offenses. bin/brakeman: 0 warnings. No ERB.

Known limit

Opening-lot collision on remap. With one opening lot per position, an opening lot cannot move onto a security that already has one. This slice drops the moved opening lot there, and the re-materialization the controller runs straight after a remap restates the target's opening lot over the merged provider quantity. Derived lots always move intact, and opening lots carry nothing user-set yet. Slice 4 (U4) merges them instead.

AGENTS.md

  • Code placement: model logic, a current-version migration with notes above, and Minitest with no new fixtures.
  • Comments: they describe current behaviour.
  • Commits: subjects are ≤72 characters, with no fork references.
  • UI, API, providers: none.

Summary by CodeRabbit

  • New Features
    • Holdings now retain acquisition-level lot details, including quantities, costs, and dates, alongside position records.
    • Opening positions can include provider-reported cost basis, and lot details remain aligned when securities are remapped or reset.
    • Lot details update alongside calculated holdings and reflect trades, transfers, and security splits.
  • Bug Fixes
    • Improved lot and position reconciliation for shortfalls, splits, rounding, and provider-reported quantities and costs. Acquisitions cover outstanding shortfalls before contributing to open lots, and positions that close to zero can reopen with known average cost.