← Back to Pull requests

Carry holding locks forward without an external_id #4260

Closed
unknown closed this pull request without merging on Oct 18, 2026 02:03 UTC
View on GitHub
unknown unknown commented on Oct 16, 2026 06:58 UTC
Author

Summary

Since #4119, Account::ProviderImportAdapter#import_holding copies a user's remap and cost-basis lock from the previous day's holding onto each new day's row. For a provider that sends no external_id (Plaid, Indexa Capital, SnapTrade securities), a remapped position has two security ids, and each lookup matched only one of them. So the second sync of the day raises a duplicate-key error and leaves the holding stale, or the new day's row drops the user's lock and manual cost basis. This PR makes both lookups recognise both ids, without touching the external_id path.

Fixes #4221

Fork pre-flight: jaysbeekay/sure#458 (pull/458). Same branch, same commit; its CI and review history are there.

What changed

app/models/account/provider_import_adapter.rb only:

  • (a) Today's row. In the no-external_id branch, look up today's row by provider_security first, scoped by account_provider_id when one is given. This mirrors fallback 1a on the external_id path. If nothing matches, it falls back to the existing find_or_initialize_by(security:, date:, currency:).

  • - Before: importing the provider's original security missed today's row, which already sits on the user's chosen security. The second sync of the day built a new row, copied the remap onto it and hit the unique index (account_id, security_id, date, currency). The collision handler looked up the incoming security too, found nothing and re-raised. The processors rescue each holding, so its quantity, price and amount stayed stale until the next day.
  • (b) The copy-forward source. previous_holding_for also accepts an earlier row the user locked to the incoming security (security_locked AND security_id = incoming).

  • - Before: importing the chosen security missed yesterday's row. The new day's row lost security_locked, recorded the chosen row as the provider's (so "reset to provider" loses the original), and had its manual cost basis replaced.
    - Within the latest earlier date, a row recording the incoming security as its provider security wins, then an unremapped row on it, then a correction locked to it, with id last. With chained remaps (A onto B, B onto C) an incoming B matches both the B→C row and the A→B row on the same date; ordering by date alone left the choice to the query plan (Codex review, confirmed by @jjmata).

    Left out on purpose: the collision handler (with (a) it is no longer reached for this case), moving providers onto external_ids, SnapTrade and Indexa Capital security resolution, and merging existing duplicate rows.

    Also left out: the external_id path's fallback 1b (matching by the provider security's ticker) in the no-external_id branch. 1b covers Security::Resolver returning a different security for the same ticker. In this branch that case does not hit the unique index, because the incoming security's id differs from both rows'. It builds a second row for the same ticker, a resolver-stability problem that predates #4119 and belongs with the security-resolution work above.

    Demo data

    No demo data needed: Demo::Generator builds investment holdings from trades, never through import_holding, so the demo never reaches this path.

    Migration notes

    No migration. Existing rows are not rewritten; the fix applies from the next sync.

    Verification

    Tests in test/models/account/provider_import_adapter_test.rb, every case without an external_id:

    | Test | Before the fix | Guards |
    |---|---|---|
    | a second same-day import of a remapped position's provider row updates today's row | PG::UniqueViolation on the second call | (a) |
    | a remapped position's chosen row carries the lock and the original provider row forward | security_locked false | (b) |
    | another provider's same-day row with that provider security is not claimed | passes (negative) | the account_provider_id scope in (a) |
    | an unlocked earlier row on the chosen security is not treated as a correction | passes (negative) | the security_locked condition in (b) |
    | a chained remap carries forward the row the provider security came from | the A→B row carried forward (security B, not C) | the same-date ordering in (b) |

    Each part of the fix was removed in turn, and a test caught it:

    | Mutation | Caught by |
    |---|---|
    | drop (a) | same-day test: PG::UniqueViolation |
    | drop (b) | chosen-row test: security_locked false |
    | drop the provider scope in (a) | cross-provider test: the other provider's row is claimed |
    | drop security_locked from (b) | unlocked-row test: cost basis 42 copied |
    | order by date alone, as before | chained-remap test |
    | drop the match ranking, keep the id tiebreak | chained-remap test (its ids are fixed so the wrong row sorts first) |
    | rank a locked correction above the provider-security match | chained-remap test |

    The #4119 tests, including "does not revive a correction the user has since undone", pass unchanged, as do the Plaid, Indexa Capital, SnapTrade and Holding model tests.

    At 4d66402fc (Ruby 3.4.9, PostgreSQL 16, Redis):

  • bin/rails test: 11,902 runs, 55,515 assertions, 0 failures, 0 errors, 34 skips.

  • bin/rubocop on the changed files: no offenses. bin/brakeman --no-pager -q: 0 warnings.

  • No ERB or JavaScript changes, so erb_lint and npm run lint do not apply.
  • Blast radius

  • Only Plaid, Indexa Capital and SnapTrade securities reach the no-external_id branch. Each passes security: from its own resolver along with its account_provider_id, so (a) can only claim a row from the same provider connection.

  • previous_holding_for runs for all 19 import_holding call sites, including the provider generator template, but only when a new day's row is built. (b) works at account level, like the existing lookup and Holding#reset_security_to_provider!, and only matches rows the user locked.

  • Siblings: previous_holding_for has one call site. The collision handler and the external_id composite guard still look up by security; with (a) the handler is no longer reached for this case, and the guard runs only when there is an external_id. The delete_future_holdings query also reads by security, but every caller passes false. All three are left unchanged.
  • Interaction with #3999

    #3999 (SnapTrade duplicate security rows) works around the dropped-lock case inside SnapTrade by handing the provider's original row to import_holding. That sends every remapped SnapTrade position into the duplicate-key case this PR fixes.

  • The two branches touch disjoint files and merge cleanly in either order.

  • With both applied, a remapped SnapTrade position synced twice in one day refreshes to the provider's quantity; with #3999 alone it stays at the earlier value.

  • Order: this PR should land first, or together with #3999. With this PR in, #3999's hand-off is still correct, but no longer needed for carrying the lock forward.
  • <!-- This is an auto-generated comment: release notes by coderabbit.ai -->

    Summary by CodeRabbit

    Bug Fixes
    Same-day imports without an external ID now update the matching remapped holding instead of creating a duplicate.
    Manual security choices and cost basis are preserved when matching corrections are imported.
    When multiple earlier holdings could match, imports now select the most relevant source, including across chained security remaps.
    * Holdings from another provider and unlocked earlier holdings are not treated as corrections.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: jaysbeekay Review duration: 2584m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #4260"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%