Upstream pre-flight: pick one SnapTrade security when a ticker has duplicate rows

Closed
JA
2mo ago
+558-9

Summary

Part of #333. Fork pre-flight for the upstream fix of we-promise/sure#3988.

Upstream PR: we-promise/sure#3999 (ready for review).

How the two relate: same branch, same commit. As of 14 Oct both are at cdbab9a87: the commits below plus a merge of mirror/upstream-main at a3bb5d991 (034e59036, no rebase) and the follow-up for upstream we-promise/sure#4119 (7049f15ca, 82781c016, cdbab9a87); see the merge comment on this PR for the evidence. Before that, as of 9 Oct, both were at c74d5555a: four commits (1b1bd7ecc, 553c850d1, dda1f44b3 for jjmata's review: logging ambiguous fallback picks, and a test of the known limit; and c74d5555a, which points a code comment at we-promise/sure#3988 instead of this fork's #333) on upstream main ea38fa6a3, so this PR and we-promise/sure#3999 list the same commits. Rows already split are tracked upstream in we-promise/sure#4025. History: the branch was first built as below, at fd2906e. This branch takes #334's two commits (merged to fork main as 4d08917), cherry-picks them onto mirror/upstream-main (eb34c06) and squashes them into one commit, fd2906e. Both picks applied cleanly. The SnapTrade code and tests are identical to 7bb87d0: git diff 7bb87d0 fd2906e on those six files is empty. Only the commit message is new. It drops fork issue numbers and fits upstream's 72-character subject rule.

Before: SnapTrade picked a security for a holding or trade with Security.find_by(ticker:). When a ticker had more than one Security row, each sync could land on a different row, which detached the holding from its trades and cost basis.

After: every sync resolves the same row. resolve_security tries, in order:

  1. The row the account already holds. This tier reads only holdings with SnapTrade's own account provider, or with none (those come from the account's trades, which is also where a user's remap lives). It does not follow another provider's holding (553c850d1).
  2. The row on SnapTrade's reported exchange, including the exchange_mic fallback.
  3. A fixed fallback order: online first, then priced, then oldest. When this tier chooses between more than one row, it records a DebugLogEntry (dda1f44b3).

The race-condition retry uses the same chain.

Commits

CommitWhat it does
1b1bd7eccPick one security deterministically when a ticker has duplicate rows. This is the squash of the original two commits described under History.
553c850d1Held-row tier follows only SnapTrade's own or trade-derived holdings. SnapTrade sends no external_id, so the import adapter matches holdings on security, date and currency alone. If the held-row tier followed another provider's holding onto that provider's row, a SnapTrade sync on the same day overwrote that provider's quantity. held_security_for now filters account_provider_id: [snaptrade_provider_id, nil], and both HoldingsProcessor and ActivitiesProcessor pass @snaptrade_account.account_provider&.id.
dda1f44b3Log ambiguous fallback picks (review request on the upstream PR). The fallback tier runs only when the account holds no position in the ticker and no row matches the reported exchange. The unique index guarantees the candidate rows differ by exchange_operating_mic, and the fallback order says nothing about which market SnapTrade trades. Once a holding is written on the pick, tier 1 keeps it there, so a wrong pick never corrects itself. When the fallback tier has more than one candidate it now records DebugLogEntry (provider_sync, warn, provider_key: "snaptrade"). The entry carries the account and its SnapTrade account provider, and its metadata holds the ticker, the reported exchange, the chosen id, and each candidate's id, exchange_operating_mic, exchange_mic, offline and price_provider. A single candidate logs nothing, and so does a pick made by tier 1 or tier 2. A caller without an account still logs, without family or provider context. A new test documents the known limit: two online, priced rows that differ only by exchange resolve to the older one, on every call.
c74d5555aThe comment above resolve_security now cites we-promise/sure#3988. It cited fork issue #333, which upstream reads as an unrelated issue. Comment only.
034e59036Merge of mirror/upstream-main at a3bb5d991. One conflict, in activities_processor_test.rb (both sides appended tests); both kept.
7049f15caKeep a remapped holding's locks on the next day's row. Upstream we-promise/sure#4119 copies a remap and a locked cost basis to each new day's row by matching provider_security_id. For holdings only (provider_row: true), the held-row tier now answers a locked holding with the provider's original row. Trades still resolve to the chosen row. update_holding_cost_basis writes to the row import_holding returned.
82781c016, cdbab9a87Helper-level tests for the provider row: only when asked for, only for a locked holding, and kept on the race retry.

Tests added by the later commits

553c850d1:

  • HoldingsProcessorTest "a sync leaves another provider's holding of the same ticker alone"
  • SnaptradeDataHelpersTest "resolve_security does not follow another provider's holding"
  • SnaptradeDataHelpersTest "resolve_security still follows a holding with no provider" (negative: trade-derived holdings are still followed)

dda1f44b3:

  • HoldingsProcessorTest "an ambiguous fallback pick is logged against this connection"
  • SnaptradeDataHelpersTest "resolve_security picks the older of two priced rows differing only by exchange, and logs it" (the known limit)
  • SnaptradeDataHelpersTest "resolve_security logs a fallback pick when the reported exchange matches no row, and without an account"
  • Negatives, each asserting nothing is logged: "does not log when the ticker has a single row", "... when the held position decides", "... when the reported exchange decides"

Scope and dependencies

  • Issue: #333 (fork), we-promise/sure#3988 (upstream)
  • Parent PR/branch, if stacked: none. Base is mirror/upstream-main.
  • Intentionally out of scope, as in #334: merging existing duplicate rows, the create-path exchange column, and the sibling providers.

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, test/models/snaptrade_account/activities_processor_test.rb, and the new test/models/snaptrade_account/holdings_processor_test.rb.
  • Any gate test has an observed failing mutation transcript attached: see #334. It was re-run on upstream code (below).
  • Fixtures used as evidence assert internal consistency.
  • 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 and in #334.

Validation

All commands ran on dda1f44b3:

  • bin/rails test test/models/snaptrade_data_helpers_test.rb test/models/snaptrade_account/: 93 runs, 325 assertions, 0 failures (it was 84 runs at fd2906e).
  • Mutations on dda1f44b3, each restored afterwards:
Mutation in data_helpers.rbCaught by
Drop the account_provider_id filter in held_security_for"a sync leaves another provider's holding of the same ticker alone" and "resolve_security does not follow another provider's holding" (2 failures)
Replace the capture_ambiguous_security call with nil"picks the older of two priced rows ... and logs it", "logs a fallback pick when the reported exchange matches no row ...", and "an ambiguous fallback pick is logged against this connection" (3 failures)
Log when candidates.size > 0 instead of > 1"does not log when the ticker has a single row" (1 failure)
  • Keep the fd2906e lines (eb34c06 restore, 10 failures; full suite) and label them "at fd2906e". Full suite on dda1f44b3 (2026-10-09, TZ=UTC): 10,597 runs, 45,074 assertions, 0 failures, 0 errors, 33 skips.

CI on dda1f44b3: ci / test_unit passed. ci / test_system failed once (run 37614537987), on AccountsTest#test_can_create_vehicle_account, with Selenium unhandled inspector error: Node with given id does not belong to the document. That is a DOM-detach race in Chrome and is unrelated to this change, for four reasons:

  • The PR touches only SnapTrade models and tests.
  • The same SHA passed test_system on we-promise/sure#3999 (run 37614537689), started at the same minute.
  • The same error hit the same test on unrelated fork PR #356 (run 37734295595), and an upstream run (37678095152) hit it on test_can_create_other_asset_account.
  • test/system/accounts_test.rb passes 3/3 locally on both this head and its merge base ea38fa6a3.

The fix for that failure is a re-run.

  • bin/rails test test/models/snaptrade_data_helpers_test.rb test/models/snaptrade_account/ on c74d5555a: 93 runs, 325 assertions, 0 failures. The re-run of ci / test_system on dda1f44b3 passed (run 37614537987, attempt 2).

At fd2906e (upstream code plus the first commit):

  • bin/rails test test/models/snaptrade_data_helpers_test.rb test/models/snaptrade_account/: 84 runs, 0 failures.
  • With eb34c06's app/models/snaptrade_account/ restored under the new tests: 10 failures, one for each new positive test.
  • bin/rails test: 10576 runs, 1 failure. The failure is Provider::OpenaiTest#test_extra_headers_stringifies_nested_values_Ruby-style. It expects Ruby 3.4's Hash#inspect format, the sandbox runs Ruby 3.3.6, and it failed the same way on #334.
  • bin/rubocop on the changed files: no offenses. bin/brakeman --no-pager: 0 warnings.
  • Checked against upstream AGENTS.md (da3e116). The change is models and tests only, uses Minitest with fixtures, adds no dependency, and has no UI, API or migration change. The commit subject is at most 72 characters.

Risks, blockers, and follow-up

  • A second same-day sync of a remapped position raises RecordNotUnique in ProviderImportAdapter#import_holding, which the processor catches and logs, so the quantity waits for the next day. Upstream main has the same error, and so do Plaid and Indexa Capital. It is tracked separately in #455, a fix in the adapter.

  • The fallback tier is not an identity match. When two online, priced rows differ only by exchange, the older one wins, and the held-row tier then keeps it. The new DebugLogEntry is there so support can find the accounts this affects. It does not correct them.

  • Operator procedure for a logged ambiguous pick. 1) In /settings/debug (super admin), filter provider_key snaptrade, level warn, and the message Resolved <TICKER> to one of N securities by fallback order. The entry names the family, the account and its SnapTrade account provider, and its metadata lists chosen_security_id, the reported_exchange, and every candidate's id, exchange_operating_mic, exchange_mic, offline and price_provider. 2) Compare the chosen row's exchange with the market the position actually trades on. 3) If it is wrong, open the holding and use Remap security (HoldingsController#remap_security, Holding#remap_security!) to move it to the correct row of the same ticker. The remap moves the account's holdings and trades for the old row and sets security_locked, and from then on tier 1 resolves the ticker to the remapped row on every sync. The test resolve_security keeps a holding the user remapped to another row of the same ticker (test/models/snaptrade_data_helpers_test.rb:227) pins that last step.

  • Positions already split across two rows don't self-heal. They need the per-instance merge described in #333 and we-promise/sure#3988.