Give split rows one write path, with manual over provider
Closes #4331
This is the model-only slice that #4322 (manual entry) and #4323 (provider split import) build on.
What: gives security_splits rows one write path before anything writes them.
Security::Split.record!upserts under the security's row lock, with precedence: manual beats a provider, a provider replaces a provider, and a provider that disagrees with a manual row is logged withDebugLogEntry.capture.SOURCESis validated.- Every change enqueues
SecuritySplitRematerializeJobfor each account holding or trading the security, and the job waits out a running sync. Security::Mergernow moves a merged security's splits throughSecurity::Split.move!, so the same precedence holds on a merge and every holder of the target is rebuilt.
Why: since #3850 the calculators apply split rows, but nothing writes one. Without a single path:
- a provider import would hit the unique index or overwrite a user's split;
- a split written outside a sync changed no holding;
- a merge kept the target's split over a user's manual one, and rebuilt only the accounts that referenced the merged row.
Start reading: Security::Split.record! and .move! in app/models/security/split.rb, then app/jobs/security_split_rematerialize_job.rb, then the one changed line in Security::Merger#merge!.
Key tests (test/models/security/split_test.rb, test/jobs/security_split_rematerialize_job_test.rb, test/models/security/merger_test.rb):
- "a provider write never replaces a manual row, and logs when its terms differ"
- "recording a split enqueues a rematerialize job for every account holding the security, in every family, and none for an unrelated account"
- "an account mid-sync is retried, not materialised, until its sync finishes"
- "a merge keeps the source's manual split over the target's provider split, and logs the dropped terms"
- "a split moved onto the target rebuilds an account that only held the target"
Behaviour change: no production code writes a split row yet, so nothing changes until #4322/#4323 land. The exception is a merge (SecurityPlaceholderSettlementJob today), which now applies split precedence. No migration, no UI, no API.
Size: +208 / −2 outside tests, across 3 files (split.rb, the job, one line of merger.rb plus its header comment). Tests +407 / −1.
Reworked on 2026-11-29 against main, after #4151 merged. Main's side won every conflict, and what main now covers was dropped:
- The split-aware cost fallback, its batch variant, and the reload line, with their six holding tests. #4151's replay (
Holding#calculate_avg_cost,.preload_avg_costs) already reads split rows. All six tests passed on main's code unchanged. - The
Security::Split.factor_betweenrefactor. It only served the fallback, and main's replay keeps its own boundary. - The dedupe rake-task hunks and their three tests.
Security::Merger(on main since #5436) is the one merge path. #5618 rewires the dedupe tasks onto it, and this PR now callsmove!from the Merger instead.
Fork pre-flight: jaysbeekay/sure#1033 (pull/1033), same branch, same commit (up/security-split-foundation at 34a19d9cb). It replaces jaysbeekay/sure#499, which merged at an older commit.
Full description and evidence
Problem
Since #3850 the holding calculators apply security_splits rows, but nothing writes one. Before #4322 or #4323 starts writing rows:
sourcewas required but unconstrained.- There was no precedence and no single write path. A provider import arriving on a day a user had already recorded a split would hit the unique index on
(security_id, ex_date), or silently overwrite the user's figures. - Nothing re-materialised accounts after a write, so a split written outside a sync changed no holding.
Security::Merger#merge!moved splits with the target-wins rule (move_unless_target_has): a duplicate's manual split lost to the target's provider split on the same ex-date. It also synced only the accounts that referenced the source, so an account holding only the target kept share counts built without the moved split.
Change
Security::Split::SOURCESismanualandsnaptrade, validated. Each provider adds itself when it gets a writer.Security::Split.record!upserts on security and ex-date under the security's row lock.- A manual write replaces anything.
- A provider write replaces a provider row but never a manual one. A provider whose terms differ from the manual row is recorded with
DebugLogEntry.capture(categorysecurity_split, provider key, both ratios). Matching terms log nothing. An unknown provider is still refused by the validations. - An unchanged write does nothing.
#revise!edits a row in place, a moved ex-date included.#remove!deletes it.SecuritySplitRematerializeJob: every change enqueues one per account with a holding or trade in the security, in any family.- It runs the
Balance::MaterializercallHoldingsController#remap_securityalready makes, scoped to that security, in the account's own family time zone. - While the account has a sync in
syncing, however old and even if asked to cancel, it retries every 30 seconds for 20 attempts. If the sync is still running when the attempts run out, it enqueues itself again in five minutes rather than materialise under the sync.Sync.cleanmarks a lost sync stale afterSync::STALE_AFTER, which ends the wait.sync_laterwouldn't be enough:Sync#expand_window_if_neededonly widens apendingsync, and a running one may have read the splits before the write committed. - A
pendingsync doesn't hold it back.
- It runs the
Security::Split.move!re-points a merged security's splits at the one that stays. On a shared ex-date, manual beats provider, and between equals the target's row stays. A dropped row whose terms differ is logged. A row whose source isn't listed still moves (re-pointed without validations), so it can't roll a merge back. Whenever either side has a split, every holder of the target is rebuilt after the merge commits.Security::Merger#merge!callsmove!in place ofmove_unless_target_has(Security::Split, :ex_date). Prices keep the target-wins rule.
No migration, no UI, no strings, no API.
Blast radius
Security::Merger#merge!is called bySecurityPlaceholderSettlementJobtoday, and by both dedupe rake tasks once #5618 lands (itsmerge_group!callsmerge!). Every one of them now gets split precedence and the wider rebuild.git merge-fileof thismerger.rbwith #5618's is clean, so either can land first. Until #5618 lands, main's dedupe tasks still destroy a duplicate's splits; no split rows exist upstream before #4322/#4323, so no data is at risk.- An account that both referenced the source and holds the target is rebuilt twice: once by the Merger's
sync_laterand once bymove!'s job. Both are correct, and it happens only on a merge where a split exists. - No production code writes a split row yet. The calculator and materializer tests create splits with
create!, and no callback is added, so they enqueue nothing. - After a split rebuild,
SecuritySplitRematerializeJobreapplies an IBKR account's reported equity-summary balances, asAccount::Syncerdoes after a sync (apply_provider_balance_overrides, now public). Five existing rebuild paths onmaincallBalance::Materializerwithout that step and are left as they are, because they are outside this PR:holdings_controller.rb:109,:148and:170,holding_lots_controller.rb:79andsnaptrade_account/split_security_repair.rb:85. On an IBKR account each shows rebuilt balances until the next sync. Security::Split#revise!and#remove!take the security lock thatrecord!takes, andrevise!re-reads the row under it, so a provider write between loading and revising can't leave a manual row carrying the provider's ratio.
Tests
Each test was written first and failed for the stated reason before the fix:
test/models/security/split_test.rb:- unknown source refused; manual and snaptrade accepted;
- manual replaces provider;
- provider never replaces manual, and logs exactly one entry when its terms differ; matching terms log nothing;
- provider replaces provider;
- recording enqueues a job for each holder and trader in every family, and none for an unrelated account;
- an unchanged write enqueues nothing; removing enqueues the same jobs; moving an ex-date enqueues once;
move!moves, handles both collision cases, and rebuilds every holder of the target.
test/jobs/security_split_rematerialize_job_test.rb:- the job rebuilds holdings from the ex-date: 10 shares on both days before it runs, then 10 the day before and 20 on the ex-date;
- an account mid-sync is retried without materialising until its sync completes;
- a sync started seven minutes ago and still running holds the job back (no job before);
- a retry while the sync is still running defers again, and so does the last attempt: it enqueues itself five minutes later and leaves the holdings alone (it materialised before);
- a running sync asked to cancel still holds it back; a pending sync doesn't;
- it materialises in the account's family zone.
test/models/security/merger_test.rb:- "a merge keeps the source's manual split over the target's provider split, and logs the dropped terms" (target-wins kept the provider row and logged nothing);
- "a split moved onto the target rebuilds an account that only held the target" (no job before);
- "a split whose source is not listed still moves onto the target" (
RecordInvalidrolled the merge back); - main's own "moves holdings, trades, prices, splits and tags onto the target" still passes: its equal-source collision keeps the target's row, as
move!does between equals.
Mutations, each caught by a named test:
| Mutation | Caught by |
|---|---|
| Drop the precedence guard; let a provider overwrite manual | "a provider write never replaces a manual row…" (and 2 more) |
| Log even when terms match | "a provider write that matches a manual row logs nothing" |
Drop the enqueue in record! | "recording a split enqueues…" |
| Enqueue on an unchanged write | "an unchanged write enqueues nothing" |
Job runs during a syncing sync | "an account mid-sync is retried…" |
Restore the Sync::VISIBLE_FOR age bound on the wait | "a sync started seven minutes ago…" |
| Materialise when the attempts run out | "a retry while the sync is still running defers again, and so does the last attempt" |
Job blocked by a pending sync | "a pending sync does not hold the job back" |
Merger back to move_unless_target_has for splits | both new merger tests |
Drop move!'s rebuild of the target's holders | "a split moved onto the target rebuilds…" and two split tests |
Re-point with a validating update! | "a split whose source is not listed still moves…" |
| Invert the collision rule | both collision tests |
Validation
- Full suite on
34a19d9cb: 19,570 runs, 0 failures, 8 errors, 9 skips. The 8 errors areReleaseNotesWorkflowTest, because my test image has nonode. - Security models, both split jobs, the placeholder settlement job, holding and
test/models/holding/*, and the SnapTrade split repair: 549 runs, 0 failures. - RuboCop: no offences.
- No UI, no migration, no new dependency.