Merge duplicate securities with Security::Merger in both dedupe tasks

JA
4h ago
+454-127

Closes #5615

Fork pre-flight: jaysbeekay/sure#952 (same branch, same commit 1f4e3afeb)

Builds on #5436's Security::Merger and includes a small fix to it (below). #4333 can drop its rake-task hunk (moving splits in these tasks), since the merger already moves them.

Problem

securities:deduplicate and data_migration:migrate_duplicate_securities re-pointed a duplicate's holdings, trades and prices by hand, then destroyed it. Its holding lots were not moved, so the foreign key's cascade deleted them: a cost basis set by hand and per-lot edits were lost. Other lots whose origin_security_id was the duplicate were nulled.

Resulting behaviour

  • Both tasks merge each group with Security::Merger.merge_group!, which runs merge! for every duplicate in one transaction, so a group merges whole or not at all; the no-MIC pass hands it one duplicate at a time. Each task collects the accounts its merges touched and syncs each one once, after its last merge, with Security::Merger.sync_accounts: a sync queued between merges could be absorbed by one already running, since sync_later reuses a visible sync and expand_window_if_needed only changes a pending one. A dispatch that raises is logged and the remaining accounts are still synced.
  • merge! moves holdings, trades, lots (and other lots' origin_security_id), prices, splits and tags, and deletes the duplicate. It now records counts (holdings moved and removed, trades, lots, re-pointed references) and the accounts it touched, and takes sync: false for a caller that syncs them itself. Moved holdings keep their updated_at, so the collision rule and Holding::CurrentForInvestmentAccounts see the original write time.
  • The tasks print the counts. The dry run also counts lots and the rows that point at a duplicate (lot origins, remapped holdings' provider security).
  • Fix to #5436's merger: it copied a missing name onto the target with update! while the source still existed, so the case-insensitive ticker validation failed for every same-ticker-and-MIC group with an unnamed keeper. The name is now copied after the source is deleted, without re-validating, since another duplicate in the group can still exist.
  • Security#move_taggings_to!, used only by the task, is removed with its unit test; merger tests now cover other families' tags and a tag the target already carries.

Behaviour changes for operators:

  • A colliding holding keeps the more recently written row, and the task output says so. The no-MIC path used to fail on the unique index; the data-migration path deleted the duplicate's row.
  • Prices and splits the canonical already has win.
  • Affected accounts are synced once per task, after every merge has landed; a failed dispatch for one account is logged and does not stop the others, and a task stopped partway (an interrupt, or an error outside the per-group rescue) still syncs the merges that committed.

Validation

  • Red first: lots deleted, a collision aborting the merge, no sync, no lot count in the dry run, an unnamed keeper failing validation, and a multi-source merge keeping the older holding.
  • A mutation per changed line, each caught.
  • Full suite on e48448a3e (upstream main merged in): 19,796 runs, 0 failures; 8 errors, all ReleaseNotesWorkflowTest needing node, which the test image lacks.
  • The migration task test loads every rake task, as the other data_migration task tests do, not just data_migration.rake through RakeTaskTestHelper. Loading that file alone left clear_stale_contribution_categories_test.rb without an environment task when it ran second (5 errors), and a later load_tasks would have defined the file's tasks twice (its batch test then failed under --seed 1). Checked with seeds 1–5 against both tests and rules_rake_test.rb.
  • CI on the fork pre-flight at 1f4e3afeb: all 12 runs pass.
  • rubocop clean on the Ruby and rake files; checked against AGENTS.md.

Migration notes

No migration. The tasks are run by hand; nothing runs on deploy.


Summary by cubic

Fixes securities:deduplicate and data_migration:migrate_duplicate_securities deleting a duplicate's holding lots instead of moving them, losing hand-set cost bases and per-lot edits. Closes #5615.

Both tasks now merge each duplicate group with Security::Merger.merge_group! in one transaction, so a group merges whole or not at all, and sync each affected account once.

Behavior changes

  • A colliding holding keeps the more recently written row; the no-MIC path used to fail on the unique index, and the data-migration path deleted the duplicate's row.
  • Prices and splits the canonical already has win.
  • Moved holdings keep their original write time, which the collision rule and current-provider-holding lookup rely on.
  • The dry run now counts lots and rows pointing at a duplicate.
  • Syncs run after the last merge, in the task's ensure block, so a task that stops partway still syncs its committed groups; a failed dispatch is logged to the debug log and the rest still go out.
  • The merger records what it moved and the accounts it touched, and takes sync: false for callers that sync themselves.

Merger fixes

  • The duplicate's name is copied to the keeper after the source is deleted, without re-validating, so same-ticker-and-MIC groups with an unnamed keeper no longer fail ticker validation.
  • Security#move_taggings_to!, used only by the task, is removed; merger tests now cover other families' tags and tags the target already carries.
  • The new migrate_duplicate_securities_test.rb loads every rake task, so the data_migration tasks aren't defined and run twice when another test loads tasks later.

Summary by CodeRabbit

  • Improvements
    • Duplicate securities are merged as a group, moving related holdings, trades, lots, and references to the canonical security.
    • When holdings collide, the more recently updated holding is retained. A duplicate’s name is copied when the canonical security has no name.
    • Each affected account is synced once after processing, including when processing stops partway through.
    • Sync dispatch continues if an individual account sync fails.
    • Deduplication reports include counts for moved and removed holdings, trades, lots, and references.