Resolve a SnapTrade security deterministically when its ticker has duplicate rows
Requested by Jonathan · project thread
Summary
Closes #333
Upstream issue: we-promise/sure#3988. No upstream PR yet.
Before: when a ticker had more than one Security row (one per exchange), each SnapTrade sync attached the holding or trade to whichever row Postgres read first. A position could move off the row its trades, cost basis and prices sat on (the ACN "No cost basis" case in #333).
After: SnapTrade resolves the same row on every sync, in a fixed order:
- the row the account's latest holding for that ticker is on;
- else the row on SnapTrade's reported exchange, matched on
exchange_operating_micand then onexchange_mic(where rows SnapTrade created keep it); - else online rows first, then rows with a price provider, then the oldest.
A new row is created only when the ticker has none, as before. The race retry after a failed create runs the same three steps.
How: SnaptradeAccount::DataHelpers#resolve_security replaces Security.find_by(ticker:) (in the main lookup and in the race retry) with existing_security_for, which chains three private lookups. It also takes an account: keyword that both callers now pass.
Scope and dependencies
- Issue: #333 (plan revised in place after its Gatekeeper review and after cubic's review here)
- Parent PR/branch, if stacked: none, branched from
main - Intentionally out of scope:
- Merging existing duplicate rows. Steps 1 to 3 keep positions where they are, so an instance that already has split positions needs that per-instance merge, not optionally.
- The create path still writes SnapTrade's exchange to
exchange_mic, notexchange_operating_mic(Gatekeeper option (b)).extract_exchangecan return SnapTrade's exchange UUID or a segment MIC, and neither belongs in the column that drives price lookup and the unique index. - Sibling providers with the same
find_by(ticker:)pattern, listed below.
Blast radius. The SnapTrade callers of resolve_security are HoldingsProcessor#process_holding and ActivitiesProcessor#process_trade, and both now pass account:. Security.find_by_ticker_and_exchange is reused unchanged. It is shared with Security::Resolver and Trade Republic, and its existing legacy-MIC upgrade side effect now also applies to SnapTrade lookups.
Siblings. grep -rn "Security.find_by(ticker" app/ also finds these, left alone: the questrade_account, indexa_capital_account, trading212_account and ibkr_account data helpers, onchain/security_resolver.rb:82, and trade_republic_account/data_helpers.rb (ISIN). Each needs its own provider's exchange field, and none was observed failing. family/data_importer.rb:1648 already orders its fallback.
Step 1 uses security_id, not provider_security_id. SnapTrade imports holdings without an external_id, so the import adapter's provider_security fallbacks never run for it. Returning the provider's original row would put each new day back on that row and undo a same-ticker remap. Returning the row the position is on keeps it.
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:
test/models/snaptrade_data_helpers_test.rb(the existingresolve_securitytests still pass) andtest/models/snaptrade_account/activities_processor_test.rb. - Any gate test has an observed failing mutation transcript attached (below).
- Fixtures used as evidence assert internal consistency: tests create their own duplicate rows and force the read order by rewriting the held row, so its tuple sorts after the other.
- Financial calculations use
BigDecimal: n/a, no calculation changes. - De-identification: no personal data included.
- Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.
Validation
There are 10 new tests, and each was seen failing on the code before it, returning the wrong row:
| Test | File |
|---|---|
| a held position stays on its security across syncs when the ticker has duplicate rows | holdings_processor_test.rb (new) |
| a security created on one sync is the one the next sync resolves after a duplicate row appears | holdings_processor_test.rb |
| a trade resolves to the security the account already holds when its ticker has duplicate rows | activities_processor_test.rb |
| prefers the row on the exchange SnapTrade reports, whichever was created first | snaptrade_data_helpers_test.rb |
| matches a row SnapTrade created on the reported exchange | snaptrade_data_helpers_test.rb |
| without an exchange prefers an online priced row over an older unpriced one | snaptrade_data_helpers_test.rb |
| race retry picks the same row as the ordered lookup | snaptrade_data_helpers_test.rb |
| race retry still prefers the row on the reported exchange | snaptrade_data_helpers_test.rb |
| follows the account's latest holding when its position already moved rows | snaptrade_data_helpers_test.rb |
| keeps a holding the user remapped to another row of the same ticker | snaptrade_data_helpers_test.rb |
There is also a negative test: a different ticker is unaffected when another ticker has duplicates. Existing tests already cover a single row being returned unchanged and an unknown ticker creating a row.
Each of these mutations was caught by at least one test:
| Mutation | Tests that fail |
|---|---|
| Skip the held-row step | both holdings processor tests, the activities test |
| Skip the reported-exchange step | prefers the row on the exchange SnapTrade reports |
Drop the exchange_mic fallback | matches a row SnapTrade created on the reported exchange |
Order the fallback by created_at only | online priced row; race retry |
Race retry back to find_by(ticker:) | race retry |
| Race retry runs only the ordered fallback | race retry still prefers the reported exchange |
| Held row: oldest date first | follows the account's latest holding |
Held row: return provider_security_id | keeps a same-ticker remap |
Commands:
bin/rails test test/models/snaptrade_data_helpers_test.rb test/models/snaptrade_account/: 84 runs, 0 failures.bin/rails teston 7bb87d0, with the sandbox'sANTHROPIC_BASE_URLunset: 11871 runs, 1 failure. The failure isProvider::OpenaiTest#test_extra_headers_stringifies_nested_values_Ruby-style, which expects Ruby 3.4'sHash#inspectformat; the sandbox runs Ruby 3.3.6, and the test fails identically without this change. CI'stest_unitwas green on 577152e.bin/rubocopon the changed files: no offenses. No ERB changed.bin/brakeman --no-pager: 0 warnings.- Checked against upstream
AGENTS.md(frommirror/upstream-main): model-only change, Minitest with fixtures, no new dependencies, no UI or API change.
Risks, blockers, and follow-up
- A holding already sitting on the "wrong" row stays there. Step 1 deliberately keeps positions where they are, so existing splits need the per-instance merge described in #333.
- Follow-up: the sibling providers above, if this approach is accepted.
Summary by CodeRabbit
- Bug Fixes
- Trade and holdings syncs now consistently match duplicate-ticker securities to the one already associated with the account, helping preserve existing holdings when security records change.
- When no existing account holding matches, duplicate tickers are matched by reported exchange, with a consistent fallback selection.