Store holding lots and re-key them on remap and reset (#551 PR 1b)

Merged
JA
1mo ago
+634-9

Summary

Part of jaysbeekay/sure#551

Stack: PR 1b of 7, on main after PR 0 (#577) and PR 1a (#578) merged.

Adds lot storage. A new holding_lots table holds each account's lots per security. The holdings materializer now 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 that 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 into the book as an unknown-cost lot, so sales relieve it pro rata like any other lot. It stays out of the average (decision 8).
  • 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 (decision 9).
  • 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.

Every stored figure is unchanged. Nothing reads lots yet, and the pool that the figure comes from is untouched. PR 0's pins (holding_test.rb, investment_statement_test.rb) and PR 1a's oracle tests (lot_book_test.rb, including the forward and reverse byte-identical dumps) pass without being edited. This PR adds no UI, no params and no data-quality kind, and supports average only.

Two book rules land with storage, as #551's PR 1b plan and the reviews on #578 required:

  • 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.
  • Pro-rata relief rounds each lot to the stored scale (18). The rounding residual goes to the last open lot.

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. Only the materializer builds the calculators.

LotBook is used by both calculators and by CostBasisTracker (a subclass). Its pool, and so average_cost, is line-for-line unchanged. Only lot quantities move: the shortfall, the rounding, and the closed-lot ledger.

Siblings re-grepped at c93cde4ef

PatternSiteStatus
CostBasisTracker / LotBookforward and reverse calculatorschanged: they expose lots_by_security, and reverse seeds opening lots and records clamps
CostBasisTracker < LotBookunchanged interface
INTERNAL_MOVEMENT_LABELS / TRANSFER_LABELboth calculators' transfer gatesunchanged
Holding#calculate_avg_cost, preload_avg_costs, Portfolio::RealizedGains, FlowClassifier, DailyReturnsunchanged: they read trades, not lots. The preload divergence stays jaysbeekay/sure#420
basis_holdingTradeunchanged: reads holdings rows, which this PR does not change
preload_avg_costsInvestmentStatement, Portfolio::RealizedGainsunchanged, same reason
update_all / update_columns moving a securityHolding#remap_security!, #reset_security_to_provider!changed: lots move with the trades
SnaptradeAccount::SplitSecurityRepair#apply, TradeRepublicAccount::DataHelpers#rematch_account_from_isin!, lib/tasks/securities.rake, lib/tasks/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 a rake task destroying a duplicate security is not blocked by its lots
update_columns on holdingsremap merge (holding.rb:289), TradeRepublicAccount::DataHelpers row mergeunchanged: holdings figures only
import_holdingprovider adapter and 13 processors, plus the generator templateunchanged: they write provider holdings rows, and the opening lot is derived from those

Migration notes

  • db/migrate/20261023090000_create_holding_lots.rb: schema only and reversible (change). It has no data backfill (decision 10). Lots appear at each account's next materialization.
  • Columns:
    • account_id, security_id: FKs, cascade on delete
    • source_entry_id: FK to entries, cascade, so deleting a trade deletes its lot; nil marks the opening lot
    • origin_security_id: FK to securities, nullify
    • acquired_on: the trade's date, or nil for the opening lot
    • qty: decimal(34,18), the same as holdings.qty
    • unit_cost: decimal(19,10), the same scale 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
  • db/schema.rb: only the hunks for this table were taken from the container's dump. The container's Postgres also rewrote four unrelated check-constraint expressions, and those were left out.

Run inside a throwaway beastpc test container: db:schema:load at c93cde4ef, then migrate, rollback and migrate again. No shared or dev database was touched.

$ bin/rails db:migrate
== 20261023090000 CreateHoldingLots: migrating ================================
-- create_table(:holding_lots, {id: :uuid})
   -> 0.0317s
-- add_index(:holding_lots, [:account_id, :source_entry_id], {unique: true})
   -> 0.0025s
-- add_index(:holding_lots, [:account_id, :security_id], {unique: true, where: "source_entry_id IS NULL", name: "index_holding_lots_one_opening_lot_per_position"})
   -> 0.0050s
-- add_check_constraint(:holding_lots, "qty >= 0", {name: "holding_lots_qty_non_negative"})
   -> 0.0003s
== 20261023090000 CreateHoldingLots: migrated (0.0396s) =======================

$ bin/rails db:rollback
== 20261023090000 CreateHoldingLots: reverting ================================
-- remove_check_constraint(:holding_lots, "qty >= 0", {name: "holding_lots_qty_non_negative"})
   -> 0.0017s
-- remove_index(:holding_lots, [:account_id, :security_id], {unique: true, where: "source_entry_id IS NULL", name: "index_holding_lots_one_opening_lot_per_position"})
   -> 0.0014s
-- remove_index(:holding_lots, [:account_id, :source_entry_id], {unique: true})
   -> 0.0010s
-- drop_table(:holding_lots, {id: :uuid})
   -> 0.0011s
== 20261023090000 CreateHoldingLots: reverted (0.0100s) =======================

holding_lots exists: false
$ bin/rails db:migrate
== 20261023090000 CreateHoldingLots: migrating ================================
-- create_table(:holding_lots, {id: :uuid})
   -> 0.0167s
-- add_index(:holding_lots, [:account_id, :source_entry_id], {unique: true})
   -> 0.0016s
-- add_index(:holding_lots, [:account_id, :security_id], {unique: true, where: "source_entry_id IS NULL", name: "index_holding_lots_one_opening_lot_per_position"})
   -> 0.0032s
-- add_check_constraint(:holding_lots, "qty >= 0", {name: "holding_lots_qty_non_negative"})
   -> 0.0004s
== 20261023090000 CreateHoldingLots: migrated (0.0220s) =======================

holding_lots exists: true
index index_holding_lots_on_account_id_and_source_entry_id ["account_id", "source_entry_id"] unique
index index_holding_lots_on_origin_security_id ["origin_security_id"]
index index_holding_lots_on_security_id ["security_id"]
index index_holding_lots_on_source_entry_id ["source_entry_id"]
index index_holding_lots_one_opening_lot_per_position ["account_id", "security_id"] unique where (source_entry_id IS NULL)
fk security_id -> securities on_delete cascade
fk origin_security_id -> securities on_delete nullify
fk source_entry_id -> entries on_delete cascade
fk account_id -> accounts on_delete cascade
check holding_lots_qty_non_negative: qty >= 0::numeric

Tests

test/models/holding_lot_test.rb, 21 tests. Fail-first was run against the PR 1a tree (c93cde4ef) with this file copied in.

TestFails before (why)
a sale with nothing held, then a transfer-in, keeps the book's lots equal to the positionExpected: 0 Actual: 5: the 1a book drops the oversold quantity
a split restates the shortfall with the positionExpected: 0 Actual: 12
a pro-rata rounding residual lands on the last open lot of the bookper-lot qty 0.666…67 (32 digits) vs stored-scale 0.666666666666666667 / …67 / …66
a buy after lots exist adds one derived lot and leaves the earlier one aloneNameError, no storage. Asserts HoldingLot.count +1 and the first lot's qty, cost, date and created_at unchanged
a sale with nothing held, then a transfer-in, keeps the stored lots equal to the positionNameError. Lot sum 10 == holding qty 10, transfer lot stored at 0
a pro-rata rounding residual lands on the last open lotNameError. Stored per-lot […67, …67, …66] by acquired_on
sum of open lot qty equals snapshot qty on every dateNameError. Forward, materialized at each day d2–d10 across a buy, sale, 3:1 split and transfer-in
sum of open lot qty equals the provider snapshot, opening lot includedNameError. Reverse, provider-only and pre-history positions
provider-only position with no trades keeps its provider basisNameError. Holding stays 50/provider, opening lot qty 10 and cost 50
the opening lot does not move the calculated figureNameError. Figure 102.5 (trades only), opening lot 1.333… after pro-rata relief, cost nil
provider quantity below trade-derived quantity clamps the opening lot and records itNameError. Opening lot qty 0 and clamped, figure 125 as today, only that security flagged
a clamped position that the provider brings back above its trades is unclampedPasses before: it pins existing behaviour for the light review 6375184168. M19 shows it is not vacuous
an unclamped position that the provider drops below its trades is clampedSame: pins existing behaviour, caught by M19
an opening lot goes once the trades explain the whole positionPasses before: pins existing behaviour, caught by M22
a forward sync after unlinking leaves the opening lots aloneFailed at 48e3235fe: Expected [3 ids] Actual [], because the forward full sync deleted every opening lot. Fixed in 64f594e71
deleting a trade deletes its derived lotNameError
a buy edited into a sale loses its lot on the next materializationNameError
a trade moved to another security without its lot takes the lot along at the next materializationNameError. Covers the siblings that move trades but not lots (snaptrade split repair, rake tasks)
remap moves lots with their tradesNameError. Lots on the new security before any sync, ids unchanged after it, merged figure 60
reset returns lots to the provider securityNameError. Lots back on the original security, same ids, opening lot's origin kept
remap onto a position with its own opening lot leaves one opening lot thereNameError

The 14 storage tests fail with NameError on HoldingLot before this PR, because no storage exists. Their behaviour is pinned by the mutation table below, where each mutation leaves the model in place and breaks one rule.

Mutation check

Each mutation was applied to a copy of the committed tree and run against holding_lot_test.rb, lot_book_test.rb, holding_test.rb and reverse_calculator_test.rb.

#MutationCaught by
M1Shortfall not filled by the next acquisition (add_lot)both shortfall tests (book and stored), split shortfall
M2Oversold quantity not recorded (relieve_lots)both shortfall tests, split shortfall
M3Split leaves the shortfall unscaleda split restates the shortfall with the position
M4Residual onto the first lot instead of the lastboth rounding-residual tests
M5No rounding to the stored scaleboth rounding-residual tests
M6Ledger drops closed lotsboth shortfall tests (the transfer lot at qty 0 is missing)
M7Opening lot enters the pool (buy(nil, qty) instead of add_unknown)the opening lot does not move the calculated figure; also PR 1a's reverse byte-identical dump and reverse_calculator_test "cost_basis_for ignores sell trades"
M8No opening lot seededopening-lot figure test, provider-only test, provider-snapshot partition, reset
M9Clamp not recordedclamp test
M10Opening lot ignores the provider's costprovider-only position keeps its provider basis
M11Stale derived lots kept (no delete in store!)a buy edited into a sale loses its lot
M12Opening upsert overwrites origin_security_idreset returns lots to the provider security
M13Rows deleted and re-inserted instead of upserteda buy after lots exist (id/created_at), remap (ids), reset (ids), and 3 more
M14remap_security! leaves lotsremap moves lots; reset; remap collision
M15reset_security_to_provider! leaves lotsreset returns lots
M16Opening lot always re-keyed on remap (no collision branch)remap onto a position with its own opening lot (unique violation)
M17persist_lots not calledevery storage test
M18Derived upsert does not update security_ida trade moved to another security without its lot takes the lot along. This mutation survived the first round, so the test was added in 48e3235fe and now catches it
M19clamped dropped from the opening upsert's update_onlyboth clamp-flip tests
M20Materializer passes openings: true on forwarda forward sync after unlinking leaves the opening lots alone
M21store! ignores openings:the same
M22Reverse passes openings: false (stale opening lots kept)an opening lot goes once the trades explain the whole position. This mutation survived until that test was added in 2477e17f3

The test files above, and the 1a and PR 0 tests, pass at the head.

Suite

Full bin/rails test on the exact head 2477e17f3, run in a throwaway beastpc container with PARALLEL_WORKERS=6: 14350 runs, 66720 assertions, 0 failures, 0 errors, 38 skips. No baseline failures appeared. The earlier run at 48e3235fe had 14346 runs and was also green.

bin/rubocop: no offenses. bin/brakeman: 0 security warnings. erb_lint: n/a (no ERB).

Changes after the light review 6375184168

  • bbb498767: pins the clamped flag both ways on re-materialization (the review's MINOR finding).
  • 64f594e71: keeps opening lots through a forward materialization. The review's sibling note says a forward full sync would empty opening lots. That path is reachable, not hypothetical: every caller chooses its strategy from Account#linked?, and unlinking a provider destroys the AccountProvider rows. HoldingLot.store!(…, openings:) now deletes stale opening lots only on the reverse strategy. This change is figure-neutral, because nothing reads lots.
  • 2477e17f3: pins the reverse path still removing an opening lot it no longer needs (M22).

Checked against upstream AGENTS.md

  • Logic is in models.
  • Minitest only, with no fixtures added.
  • The migration uses the current Rails version, [8.1].
  • Comments describe current behaviour, not history.
  • Commit subjects are at most 72 characters.
  • Migration notes are above.
  • No UI, API or provider change.

Gaps against #551's PR 1b definition

  • Opening-lot collision on remap. The plan says remap "does not merge lots". With the specified one-opening-lot-per-position index, an opening lot cannot move onto a security that already has one. This PR drops the moved opening lot in that case, and the next materialization (which the controller runs straight after a remap) restates the target's opening lot over the merged provider quantity. Derived lots always move intact. Opening lots carry nothing user-set until PR 3, so nothing is lost now. PR 3 needs an owner decision before user basis can sit on an opening lot.
  • "On every date". The partition is checked for stored lots at each materialization date on the forward path, and at today on the reverse path. Stored lots are a current state, not per-date history.
  • Opening-lot cost. It takes the provider's latest per-share figure only where no trade explains the position, and is otherwise nil. The provider figure for a mixed position is a blend, not the opening units' cost.

Summary by CodeRabbit

  • New Features
    • Holdings now track individual lots, including quantities, acquisition details, and cost basis, alongside account positions.
    • Lot quantities and cost basis are updated as trades and stock splits affect holdings. Oversold quantities are accounted for as later acquisitions arrive.
    • Lot records are maintained when securities are remapped or reset, helping keep holdings history aligned with the associated security.
  • Bug Fixes
    • Improved consistency between recorded lots and calculated holding quantities, including when rounding affects how quantities are distributed.