fix(snaptrade): pick one security when a ticker has duplicate rows

Merged
JA
2mo ago
+558-9

Fixes #3988

Fork pre-flight: https://github.com/jaysbeekay/sure/pull/335 (same branch, same commit; its CI and review history are there)

Problem
SnaptradeAccount::DataHelpers#resolve_security found the security for a SnapTrade holding or trade with Security.find_by(ticker:): no exchange, no ORDER BY. A ticker can have one Security row per exchange, so once it has two (for example one SnapTrade created with no operating MIC and one a CSV import or ticker search created on XNYS), each sync lands on whichever row Postgres reads first. The holding then moves off the row its trades are on, and Holding#calculate_avg_cost returns nil, so it shows "No cost basis". Details and the observed case are in #3988.

What changes
resolve_security now picks the same row on every sync, in this order:

the row the account's latest holding for that ticker is already on, so an existing position never moves (and a holding the user remapped to another row of the same ticker stays there); Only SnapTrade's own holdings and those with no provider (materialized from the account's trades) count here: SnapTrade sends no external_id, so following another provider's holding onto its row would let the import overwrite that provider's quantity (CodeRabbit, 0240195de).
otherwise the row on the exchange SnapTrade reports: Security.find_by_ticker_and_exchange first, then a row with that value in exchange_mic, which is where rows SnapTrade created keep it;
otherwise online rows first, then rows with a price provider, then the oldest.
A row is still only created when the ticker has none, and the retry after a failed create runs the same three steps. HoldingsProcessor#process_holding and ActivitiesProcessor#process_trade now pass account: so step 1 can run.

Left as is, on purpose:

Rows SnapTrade creates still get its exchange in exchange_mic, not exchange_operating_mic. extract_exchange can return SnapTrade's exchange UUID or a segment MIC, and neither belongs in the column that drives price lookup and the unique index.
Existing duplicate rows aren't merged. A position that has already split across two rows stays on the row its latest holding is on, and needs merging by hand on that instance.
The same find_by(ticker:) pattern in the Questrade, Indexa Capital, Trading 212 and IBKR data helpers, onchain/security_resolver.rb and kraken_account/security_resolver.rb (added since this PR was opened). Each needs its own provider's exchange field, and I've only seen SnapTrade fail. Happy to follow up if this approach is accepted.
Validation
New test/models/snaptrade_account/holdings_processor_test.rb, plus new cases in snaptrade_data_helpers_test.rb and snaptrade_account/activities_processor_test.rb: a held position stays put across syncs, a row SnapTrade created keeps being picked after a second row appears, a trade lands on the held row, the reported exchange wins regardless of creation order (including a SnapTrade-created exchange_mic row), the ordered fallback, both race-retry paths, the latest holding wins, a same-ticker remap is kept, and a different ticker is unaffected. The tests force Postgres to read the wrong row first by updating the held row.
All 10 new tests fail against main at eb34c06 and pass with the change. Three more cover the provider scope: the helper does not follow another provider's holding, still follows a holding with no provider, and a sync leaves another provider's same-ticker holding alone. Without the scope, the helper test and the processor test both fail.
bin/rails test on Ruby 3.4.9 (the version upstream pins), at 0240195de: 10,579 runs, 0 failures, 0 errors. (An earlier run on Ruby 3.3.6 failed only Provider::OpenaiTest's Ruby-3.4 Hash#inspect test, which passes on 3.4.9.)
bin/rubocop (changed files) and bin/brakeman: clean. No UI, API or migration changes.

Rebased onto main (6 Oct)

Rebased onto main at ea38fa6a3; the commits carry the same changes under new SHAs. SHAs elsewhere in this description refer to the commits as they were before.

  • fd2906eac → 1b1bd7ecc fix(snaptrade): pick one security when a ticker has duplicate rows
  • 0240195de → 553c850d1 fix(snaptrade): follow only SnapTrade's own or trade-derived holdings

bin/rails test on 553c850d1: 10,591 runs, 45,045 assertions, 0 failures, 0 errors, 33 skips. bin/rubocop on the changed files: no offenses.

Follow-up for review (7 Oct)

dda1f44b3 answers jjmata's review of 7 Oct. When the last fallback tier has more than one candidate, it records a provider_sync warning in /settings/debug, carrying the account, its SnapTrade connection and every candidate row. It adds a test documenting the known limit: two online, priced rows differing only by exchange resolve to the older one. Rows that are already split are tracked in #4025.

Merged main, and the #4119 interaction (14 Oct)

Merged main at a3bb5d991 (a merge, not a rebase; earlier SHAs still apply). The head is now cdbab9a87.

  • Merge (034e59036): one conflict, in test/models/snaptrade_account/activities_processor_test.rb, where this branch's trade test and the options tests from #3744 and #4145 were both added at the end of the file. Both are kept. Option trades go through resolve_security, so they are covered.
  • #4119 interaction, fixed in 7049f15ca. #4119 copies a remap and a locked cost basis to each new day's holding row. It finds the previous day's row by provider_security_id = <incoming security>. The held-position step returned the row the user remapped to, so the next day's row dropped security_locked, pointed provider_security_id at the chosen row, and replaced a manual cost basis. Now, for holdings only (resolve_security(..., provider_row: true)), the held-position step answers a locked holding with the provider's original row, matched on that row's ticker, so a remap to another ticker is followed too. Trades still go to the row the user chose, because Holding#remap_security! moves the trades there. update_holding_cost_basis now writes to the row import_holding returned, not to whichever row the resolved security points at.
  • Tests (7049f15ca, 82781c016, cdbab9a87): 4 holdings-processor tests (same-ticker remap stays locked, its locked cost basis is copied forward, a remap to another ticker stays locked, the provider's cost basis still lands on the remapped row), 1 activities-processor test (a trade for a remapped position lands on the chosen row), and 3 helper tests (provider row only when asked for and only for a locked holding, an unlocked holding stays where it is, the race retry keeps the provider row). The three lock tests failed before the fix. Six deliberate breaks of the fix were each caught by a test, and the PR's earlier mutations, re-run on the merged code, were all still caught.
  • Known, separate: #4221. Without an external_id, ProviderImportAdapter#import_holding finds today's row only by security. So for a remapped position, a second sync on the same day raises RecordNotUnique, which the processor catches and logs, and the quantity waits for the next day. main has the same error today, for SnapTrade when find_by(ticker:) returns the provider's row, and for Plaid and Indexa Capital. The fix belongs in the adapter.

bin/rails test on cdbab9a87 (Ruby 3.4.9): 11,849 runs, 54,617 assertions, 0 failures, 0 errors, 34 skips. bin/rubocop on the changed files: no offenses. bin/brakeman: 0 warnings.

Summary by CodeRabbit

  • Bug Fixes
    • Improved security matching during trade and holdings sync when multiple securities share a ticker. Syncs prioritize securities already held in the account, then consider the reported exchange and use a consistent fallback when needed, helping prevent trades and holdings from being associated with the wrong security.
    • Matching remains consistent when a security is renamed or a sync retries after a conflict. Holdings from other providers remain separate, while providerless holdings can still be matched.