Carry holding locks forward without an external_id #4260
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
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
jaysbeekay
Summary
Since #4119,
Account::ProviderImportAdapter#import_holdingcopies 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 noexternal_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 theexternal_idpath.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.rbonly:external_idbranch, look up today's row byprovider_securityfirst, scoped byaccount_provider_idwhen one is given. This mirrors fallback 1a on theexternal_idpath. If nothing matches, it falls back to the existingfind_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.previous_holding_foralso 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
idlast. 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_idpath's fallback 1b (matching by the provider security's ticker) in the no-external_idbranch. 1b coversSecurity::Resolverreturning 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::Generatorbuilds investment holdings from trades, never throughimport_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 anexternal_id:| Test | Before the fix | Guards |
|---|---|---|
| a second same-day import of a remapped position's provider row updates today's row |
PG::UniqueViolationon the second call | (a) || a remapped position's chosen row carries the lock and the original provider row forward |
security_lockedfalse | (b) || another provider's same-day row with that provider security is not claimed | passes (negative) | the
account_provider_idscope in (a) || an unlocked earlier row on the chosen security is not treated as a correction | passes (negative) | the
security_lockedcondition 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_lockedfalse || drop the provider scope in (a) | cross-provider test: the other provider's row is claimed |
| drop
security_lockedfrom (b) | unlocked-row test: cost basis 42 copied || order by date alone, as before | chained-remap test |
| drop the match ranking, keep the
idtiebreak | 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
Holdingmodel 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/rubocopon the changed files: no offenses.bin/brakeman --no-pager -q: 0 warnings.erb_lintandnpm run lintdo not apply.Blast radius
external_idbranch. Each passessecurity:from its own resolver along with itsaccount_provider_id, so (a) can only claim a row from the same provider connection.previous_holding_forruns for all 19import_holdingcall 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 andHolding#reset_security_to_provider!, and only matches rows the user locked.previous_holding_forhas one call site. The collision handler and theexternal_idcomposite 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 anexternal_id. Thedelete_future_holdingsquery also reads by security, but every caller passesfalse. 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.<!-- 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 -->