Add a per-account repair for split SnapTrade securities
Summary
Closes jaysbeekay/sure#423
Context: this is the fork side of we-promise/sure#4025. This PR is fork-only. An upstream version depends on we-promise/sure#3999 merging first, because upstream/main still uses the ticker-only lookup that creates new splits.
Problem. Before jaysbeekay/sure#334, SnaptradeAccount::DataHelpers#resolve_security used Security.find_by(ticker:). That lookup had no exchange and no order, so a SnapTrade position's holdings and trades could end up on different Security rows of the same ticker. Cost basis is read by security_id (Holding#calculate_avg_cost, Holding.preload_avg_costs), so the holding shows "No cost basis". The deterministic lookup from jaysbeekay/sure#334 keeps the position on the row it already holds, so the split stays in place. Neither existing repair route can fix it:
- The UI remap cannot select the nil-MIC row.
securities:deduplicateruns across all families, is live by default and destroys rows. It also fails with a unique-index error when both rows have a holding on the same day.
Behaviour after. bin/rails snaptrade:repair_split_securities repairs this one account at a time. It runs on every SnapTrade-linked account, or on one account with [ACCOUNT_ID]. It is a dry run unless DRY_RUN=false is set. For each ticker spread over more than one row, it does the following:
- Takes the target row from
held_security_for(account, ticker, snaptrade_provider_id), which is the row the next sync resolves to. Like the sync, it counts only SnapTrade's own holdings and provider-less holdings. If no holding names a row, it takes the row with the most trades and reports that. - Moves the account's trades from the other rows onto the target.
- Moves the account's SnapTrade holdings and provider-less holdings onto the target. Where the target already has a holding for that date and currency, one row survives and nothing is summed. A SnapTrade snapshot replaces a calculated target row. Otherwise the target's row is kept and the moved one is dropped.
- Re-materializes with
Balance::Materializer.new(account, strategy: :reverse, security_ids: targets).
A live run refuses an account, writing nothing, when the target row lacks prices for dates in the account's history that a source row has (PriceGapsRefused). The rake task prints the refusal. ALLOW_PRICE_GAPS=true overrides it, and only together with an account id, so the override covers one reviewed account at a time.
Each account is repaired in one transaction. The repair does not set security_locked or provider_security_id. It destroys no Security row and moves no Security::Price.
Prices stay where they are. Prices are shared by every family that holds the security, so they are not moved. If the target has fewer prices than the other row, the moved history can be unpriced on some days until market data fills the target. Today's holding is unaffected, because it is priced from the holding itself. The repair reports, per ticker, the dates in the account's history that have a price on another row but not on the target.
Dry-run transcript from a seeded split (the we-promise/sure#3988 shape, plus a same-day collision and two prices on the other row only; ids masked):
before: avg_cost=nil
DRY RUN: nothing will be written. Set DRY_RUN=false to apply.
Account <account> (Stake US):
ACN: target <row B> (held), from <row A>
trades moved: 2, holdings moved: 0, holdings dropped (target already had the date): 1
price gap: 2 date(s) priced on another row but not the target: 2026-09-27, 2026-10-04
after dry run: avg_cost=nil
Scope and dependencies
- Issue: jaysbeekay/sure#423 (upstream context: we-promise/sure#4025)
- Parent PR/branch, if stacked: none. The base is fork
main;mainat8d4842986(with jaysbeekay/sure#429) is merged in asd3feb6261. - Merge order, decided by the owner on 2026-10-13: jaysbeekay/sure#429 merges first, then #433 passes the extra argument. Done: #429 merged into
mainas8d4842986; this branch merged it ind3feb6261and changed the call inSplitSecurityRepair#target_fortoheld_security_for(account, ticker, snaptrade_provider_id)in14c310e3e. - Interaction with the jaysbeekay/sure#425 port of
553c850d1(PR jaysbeekay/sure#429), now resolved. The port changedheld_security_for(account, ticker)toheld_security_for(account, ticker, account_provider_id), so only SnapTrade's own holdings and provider-less holdings count. This repair now passes its memoisedsnaptrade_provider_id, so repair and sync resolve the same target and both ignore other providers' holdings. Which rows the repair moves is unchanged, because it already moved only SnapTrade and provider-less holdings. - Intentionally out of scope:
- a global
Securitymerge, destroyingSecurityrows, and moving or copying prices; - other accounts, other families and other providers' holdings;
securities:deduplicate;- the other providers' ticker-only lookups listed in the issue;
- porting
553c850d1anddda1f44b3(that is jaysbeekay/sure#425); - any UI.
- a global
Blast radius
Who else hits this line, and what do they pass? SnaptradeAccount::SplitSecurityRepair is new, and only the new rake task calls it. It reuses three things without changing them:
held_security_for(account, ticker, account_provider_id), whichresolve_securityalso reaches (with the SnapTrade provider id) fromHoldingsProcessor#process_holding(holdings_processor.rb:100) andActivitiesProcessor#process_trade(activities_processor.rb:209);Balance::Materializer.new(account, strategy: :reverse, security_ids: [...]), the same callHoldingsController#remap_securitymakes (holdings_controller.rb:169) and sync makes;update_allanddelete_all, scoped to this account's trades and this account's SnapTrade or provider-less holdings.
What else reads what this changes? These read holdings and trades by security_id:
Holding#calculate_avg_cost(holding.rb:398),.preload_avg_costs(:82),#trades,#day_changeand#destroy_holding_and_entries!;Holding::ForwardCalculator,Holding::ReverseCalculatorandHolding::Materializer(which upserts on account, security, date and currency);Account::ProviderImportAdapter#import_holding;held_security_for;InvestmentStatementand the portfolio views.
After the repair, all of them see one row per position. The target is the row held_security_for returns, so the next sync resolves to the same row and the repair does not undo itself. The holdings move preserves the (account_id, security_id, date, currency) unique index: the target's existing keys are kept, and moved holdings that collide are dropped. Where two non-target rows share a date, the provider row is kept.
Line references in the issue were rechecked at 3b1e600e2. Several had moved since 3727ee4e0: calculate_avg_cost is at 408 → 398, preload_avg_costs at 101 → 82, the controller remap target at 139-142 → 140-143, and its materializer call at 167-168 → 169. held_security_for (105-116), the summing in remap_security! (247-248), the trade move in reset_security_to_provider! (341) and db/schema.rb:2479 are unchanged.
Evidence checklist
- Each issue in this PR has its own acceptance criteria and no unrelated issue work is included.
- Contract rows touched by this change name existing tests. (No contract rows are touched.)
- Any gate test has an observed failing mutation transcript attached (below).
- Fixtures used as evidence assert internal consistency. Each split is built inside its test, and the preconditions are asserted.
- Financial calculations use
BigDecimaland documented rounding points. (No new calculation: cost basis is computed by the existing readers.) - De-identification uses token-shape allowlists; no personal data is included.
- Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.
Files:
app/models/snaptrade_account/split_security_repair.rb(new PORO)lib/tasks/snaptrade.rake(new task)test/models/snaptrade_account/split_security_repair_test.rb(17 tests)
Validation
Tests (all written first)
The tests were first run against a skeleton whose run returned [] and whose rake task did nothing, so each failure comes from behaviour, not a missing constant.
| Test | Kind | Against the skeleton |
|---|---|---|
| repair moves the duplicate row's trades onto the held row and restores avg_cost | positive | fails. Its precondition assert_nil holding.avg_cost passes (P1 reproduced at 3b1e600e2); then there is no result |
| repair resolves to the row resolve_security keeps picking | positive | fails (no result) |
| repair handles a duplicate row that has trades but no holding | positive | fails (no result) |
| repair keeps the target holding on a same-day collision without summing qty | positive | fails (no result) |
| dry run changes nothing | negative + report | fails on the report half (no result); the state half holds |
| another account's holdings and trades on the duplicate row are untouched | negative | passes before and after |
| another provider's holding on the same account is untouched | negative | passes before and after |
| a non-SnapTrade account is skipped | negative + scope | fails at line 137, .accounts excludes the SnapTrade account; the skip half holds |
| a ticker with one row is a no-op | negative | passes before and after |
| a different ticker is unaffected | negative | fails at line 158, Expected: ["SPLT"] Actual: [] |
| no Security row is destroyed and no price is moved | negative | passes before and after |
| moved holdings are not security_locked and carry no provider_security_id | negative | fails (no result) |
| a split in the opposite direction keeps today's value and reports the price gap | negative | fails (no result) |
| the rake task is a dry run unless DRY_RUN is false | positive | fails, Expected /DRY RUN/ to match "" |
The gate assertion from the plan is assert_equal Money.new(150, "USD"), holding.reload.avg_cost. It is nil before the repair and 150 USD after, and Holding.preload_avg_costs agrees. The "the rake task is a dry run" test is an addition to the plan's list: it covers the "default to a live run" mutation at the rake layer as well as in the PORO.
Mutations (each applied to the committed tree, then reverted; git diff HEAD empty afterwards)
| Mutation | Caught by |
|---|---|
| drop the trade move | restores avg_cost (E), resolves to the row resolve_security keeps picking (F), trades but no holding (F), rake dry-run test (E) |
| sum qty on a collision | same-day collision without summing qty (F) |
| drop the account scope (trades) | another account's holdings and trades untouched (F) |
| drop the account scope (holdings) | another account's holdings and trades untouched (E) |
| default to a live run (PORO) | dry run changes nothing (F) |
| default to a live run (rake) | rake task is a dry run unless DRY_RUN is false (E) |
| choose the oldest row instead of the held row | resolves to the row resolve_security keeps picking (F), plus 6 others |
set security_locked | moved holdings are not security_locked (F) |
| move other providers' holdings too | another provider's holding untouched (F) |
| skip the SnapTrade-link check | a non-SnapTrade account is skipped (F) |
| report every price date, not the gap | opposite direction ... reports the price gap (F) |
| move prices with the rows | no Security row is destroyed and no price is moved (F), opposite direction (E) |
Commands
bin/rails test test/models/snaptrade_account/split_security_repair_test.rb: 14 runs, 61 assertions, 0 failures.- Neighbouring suites (
snaptrade_data_helpers_test.rb,snaptrade_account/,holding_test.rb,holding/,holdings_controller_test.rb,account/provider_import_adapter_test.rb): 312 runs, 1136 assertions, 0 failures, 0 errors. - Full
bin/rails test: 12397 runs, 53497 assertions, 0 failures, 0 errors, 35 skips. bin/rubocop -f githubon the changed files: no offences.bin/brakeman --no-pager: 0 security warnings.- No ERB or JS changed, so erb_lint and Biome do not apply.
- Checked against upstream
AGENTS.md:- business logic is in a model PORO;
- Minitest with in-test edge cases;
- no new dependency, migration or UI;
DebugLogEntrydoes not apply to an operator-run repair task that prints its own report.
Risks, blockers, and follow-up
- Collision rule, decided by the owner on 2026-10-13. On a same date and currency, a calculated target row gives way to a SnapTrade snapshot, which keeps that day's provider
cost_basis. The reverse re-materialization rebuilds calculated rows from the trades and skips provider rows, so the snapshot survives it. Where both rows are provider rows, the target's is kept, as planned. - Run the dry run first on the affected accounts (the we-promise/sure#3988 cases: ACN on Stake US; A200, NDQ and WRLD on Stake AU) and read the price-gap lines before applying. A live run on an account with a gap is refused until the target's prices are filled, or until it is rerun for that account with
ALLOW_PRICE_GAPS=true. - Coordination with jaysbeekay/sure#425 / #429 is done (#429 merged first; see below).
Review follow-up (2026-10-13, commit 61ba40f49)
- Nightly 6134294080, HIGH: a live run proceeds despite price gaps. Fixed by the refusal described above. Tests:
a live repair that would leave price gaps is refused and writes nothing(account state unchanged, avg_cost still nil), andthe rake task refuses a live repair with price gaps unless ALLOW_PRICE_GAPS names one account. Two existing tests now passallow_price_gaps: true, because their fixtures price the source row only. - Collision rule (owner decision): test
a calculated target row gives way to the SnapTrade snapshot on a same-day collision.repair keeps the target holding on a same-day collision without summing qtystill covers two provider rows. - Fail-first against
d31c9c8f0: the rake test applied the repair instead of refusing it, the collision test kept the calculated row, and the model refusal test failed because the class had noPriceGapsRefused. - Mutations, each caught: removing the refusal (2 tests); removing the snapshot preference (collision test); letting a provider target row be replaced too (
repair keeps the target holding ...); dropping the rake's account-id requirement (rake test); ignoringALLOW_PRICE_GAPSin the rake task (rake test). - Results: the repair file gives 17 runs, 78 assertions, 0 failures.
test/models/snaptrade_account,snaptrade_data_helpers_test.rbandtest/models/holdinggive 190 runs, 0 failures. Fullbin/rails teston61ba40f49: 12400 runs, 53516 assertions, 0 failures, 0 errors, 35 skips. rubocop on the changed files and brakeman: clean. - Light review 6131515998: the
most_tradesnote is acknowledged, and #429 coordination is settled above.
Merge of main with jaysbeekay/sure#429 (2026-10-14, head 14c310e3e)
Answers nightly 6157135259 (MEDIUM), as planned in 6160840861.
d3feb6261: mergesmainat8d4842986(no rebase). It merged textually clean.14c310e3e:target_forpassessnaptrade_provider_idtoheld_security_for. Theresolve_securityprecondition inrepair resolves to the row resolve_security keeps pickingnow passesaccount_provider_id: @provider_id, asHoldingsProcessor#process_holdingdoes; without it the held lookup sees only provider-less holdings and the precondition picks the older row.- Fail-first on the merge head
d3feb6261: the repair file gave 17 runs, 4 failures, 11 errors. The 11 errors and 3 of the failures areArgumentError: wrong number of arguments (given 2, expected 3)fromtarget_for(the two rake tests print it as "failed, rolled back"; the price-gap test got it instead ofPriceGapsRefused). The fourth failure is the precondition described above. - Mutations of the new argument, each caught by 8 tests in the repair file:
nil; a random id; another provider's id. - Sibling grep:
held_security_forhas two callers,existing_security_for(already passes the provider id) andtarget_for(fixed). - Results:
test/models/snaptrade_accountplussnaptrade_data_helpers_test.rb: 110 runs, 403 assertions, 0 failures, 0 errors. Fullbin/rails teston14c310e3e: 12419 runs, 53581 assertions, 0 failures, 0 errors, 35 skips. rubocop on the changed files and brakeman (0 warnings): clean.