Store holding lots and re-key them on remap and reset (U2)

Draft
JA
19d ago
+981-24

Part of jaysbeekay/sure#551.

Upstream pre-flight for slice U2 of we-promise/sure#4449 (decision 19 on jaysbeekay/sure#551: U2 = PR 1b). The branch up/551-u2 is cut from up/551-u1 (U1's pre-flight, jaysbeekay/sure#599), so this PR's base is that branch and the diff shows only this slice. It carries jaysbeekay/sure#579, cherry-picked, with fork references removed from the commit messages. The only conflict was the db/schema.rb version line. Upstream PR: we-promise/sure#4899 (https://github.com/we-promise/sure/pull/4899), part of the native GitHub stack we-promise/sure#4905. It replaces we-promise/sure#4496, closed on 2026-11-11 so the stack's branches could all live upstream; that PR keeps the earlier review history. Same commits: the upstream PR's head is this branch's copy in we-promise/sure.

Problem

Slice 1 keeps lots in memory during a sync and throws them away. Every later step in we-promise/sure#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(19,10) as trades.price; 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.