Settle resolution_pending placeholders instead of duplicating them

Merged
JA
15d ago
+449-1

Fixes #5190.

Problem

When the provider search fails technically for a ticker that has no exchange (the usual SimpleFIN case), Security::Resolver stores a blank-MIC placeholder marked offline_reason: "resolution_pending" so a later run can retry. A later successful search, though, never matches that placeholder. find_or_create_provider_match! looks up the ticker with the search result's MIC and creates a second row. After that, each sync puts its holdings on the listed row if the search worked and on the placeholder if it failed. Each row backfills its own history, so past holdings are counted twice.

A third, smaller issue: without an exchange, the DB fast path returns whichever row for the ticker sorts first by UUID. When the listed row comes first, the provider is never asked again and the placeholder is never cleaned up.

Change

  • Upgrade in place. When a provider match has an exchange, no row exists yet for that ticker and exchange, and a blank-MIC resolution_pending placeholder exists for the same ticker, the placeholder becomes the listed security. The existing code then sets its MIC, country, name and provider and brings it back online.
  • Merge. When both rows already exist (installs that hit this before), the resolver returns the listed row and enqueues SecurityPlaceholderSettlementJob, which runs after the resolving transaction commits and merges the placeholder into the listed row with a new Security::Merger, then deletes it. Deferring it matters for TradeImport, which builds every trade in memory before one bulk insert: deleting the placeholder mid-import would leave an earlier buffered trade pointing at a missing row. The job rechecks under the row lock that the placeholder is still a blank-MIC resolution_pending row. It moves holdings (including provider_security_id), trades, holding lots (opening lots are combined through HoldingLot.move!), lot origins, prices, splits and taggings. Where a unique key collides, the listed row's prices, splits and tags win. For holdings, the most recently written row per (account, date, currency) is kept, as the issue's workaround does. A remap whose provider security turns into the security itself is cleared. Both security rows are locked in id order, so concurrent merges are safe; a merge that finds the placeholder already gone does nothing. Accounts that referenced the placeholder get sync_later, so their holdings and balances are rebuilt on a single row.
  • Fast path. For a lookup without an exchange, the fast path is skipped while a pending placeholder exists for the ticker. The next successful search therefore always settles the placeholder, whatever the UUID order. If that search fails or finds nothing, the lookup falls back to the listed row instead of the placeholder.
  • Scope. Only exchange-less lookups settle a placeholder. They are the kind that created it, so a lookup for an explicit exchange leaves it alone.

Unchanged:

  • Blank-MIC rows without resolution_pending (a confirmed no-match, or a more specific reason such as health_check_failed).
  • Placeholders for a ticker other than the one the search matched.
  • Lookups that pass an explicit exchange (they never settle a placeholder).

Tests

  • test/models/security/resolver_test.rb: in-place upgrade, merge into an existing listed row, the UUID-order case, the fallback to the listed row when the retry fails, keeping the exact-ticker row when the search only offers other tickers, the issue's fail → succeed → fail sequence staying on one security, and the three negative cases above. The four positive tests fail on main.
  • test/models/security/merger_test.rb: holdings with collisions on both sides, trades, prices, splits, tags, provider remaps, opening lots and origins, the self-merge no-op, the already-merged case and a condition that no longer holds under the lock.
  • test/jobs/security_placeholder_settlement_job_test.rb: merges a pending placeholder, skips one settled some other way, and tolerates either row being gone.

Validation

  • bin/rails test test/models/security/merger_test.rb test/models/security/resolver_test.rb: 40 runs, 0 failures. Every test that touches the resolver, plus the holding and lot tests: 438 runs, 0 failures.
  • bin/rails test: 18,013 runs, 2 failures and 9 errors. All 11 are in Active Storage variants, Onchain::BitcoinPublicKey and Postgres regex-complexity tests, and the same 11 fail on main on this machine (libvips, RIPEMD-160 under OpenSSL 3, Postgres 14 regex limits).
  • bin/rubocop, erb_lint --lint-all, npm run lint (Biome) and bin/brakeman: clean.
  • No system tests apply; this change has no UI.

Summary by CodeRabbit

  • New Features
    • Security records can now be consolidated when a pending placeholder is matched to a listed security. Related holdings, trades, prices, splits, and tags are retained or deduplicated, and affected accounts are scheduled to sync.
  • Bug Fixes
    • Security lookups without an exchange now preserve pending placeholders while checking provider results. A matching listed security can resolve the placeholder; unsuccessful or mismatched searches leave it unchanged. Explicit-exchange lookups do not settle pending placeholders.