Give split rows one write path, with manual over provider

JA
2d ago
+732-15

Closes jaysbeekay/sure#498. Part of jaysbeekay/sure#249.

Fork pre-flight for upstream PR we-promise/sure#4333 (pull/4333): same branch, same commit (up/security-split-foundation at 34a19d9cb). Upstream issue: we-promise/sure#4331. It replaces the earlier pre-flight jaysbeekay/sure#499, which merged at an older commit.

This is the model-only slice that we-promise/sure#4322 (manual entry) and we-promise/sure#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 with DebugLogEntry.capture.
  • SOURCES is validated.
  • Every change enqueues SecuritySplitRematerializeJob for each account holding or trading the security, and the job waits out a running sync.
  • Security::Merger now moves a merged security's splits through Security::Split.move!, so the same precedence holds on a merge and every holder of the target is rebuilt.

Why: since we-promise/sure#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 we-promise/sure#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 we-promise/sure#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. we-promise/sure#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_between refactor. 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 we-promise/sure#5436) is the one merge path. we-promise/sure#5618 rewires the dedupe tasks onto it, and this PR now calls move! from the Merger instead.
Full description and evidence

Problem

Since we-promise/sure#3850 the holding calculators apply security_splits rows, but nothing writes one. Before we-promise/sure#4322 or we-promise/sure#4323 starts writing rows:

  • source was 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::SOURCES is manual and snaptrade, 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 (category security_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::Materializer call HoldingsController#remap_security already 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.clean marks a lost sync stale after Sync::STALE_AFTER, which ends the wait. sync_later wouldn't be enough: Sync#expand_window_if_needed only widens a pending sync, and a running one may have read the splits before the write committed.
    • A pending sync doesn't hold it back.
  • 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! calls move! in place of move_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 by SecurityPlaceholderSettlementJob today, and by both dedupe rake tasks once we-promise/sure#5618 lands (its merge_group! calls merge!). Every one of them now gets split precedence and the wider rebuild. git merge-file of this merger.rb with we-promise/sure#5618's is clean, so either can land first. Until we-promise/sure#5618 lands, main's dedupe tasks still destroy a duplicate's splits; no split rows exist upstream before we-promise/sure#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_later and once by move!'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.

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" (RecordInvalid rolled 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:

MutationCaught 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 splitsboth 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 ruleboth collision tests

Validation

  • Full suite on 34a19d9cb: 19,570 runs, 0 failures, 8 errors, 9 skips. The 8 errors are ReleaseNotesWorkflowTest, because my test image has no node.
  • 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.

Merge note (2026-11-29): this PR and we-promise/sure#5618 both add tests at the same place in test/models/security/merger_test.rb, so the second to land on upstream main conflicts there. Whoever resolves it must keep both sets of tests:

  • from we-promise/sure#4333: "a merge keeps the source's manual split over the target's provider split, and logs the dropped terms", "a split whose source is not listed still moves onto the target", "a split moved onto the target rebuilds an account that only held the target"
  • from we-promise/sure#5618: "counts what it moved and can leave the syncs to its caller", "a keeper with no name takes the duplicate's while another duplicate remains", "a group merges whole or not at all, and leaves the syncs to its caller", "a group keeps the most recently written holding when two sources collide", "moved and repointed holdings keep their original write time", "keeps every family's tags, and one tagging where the target already has the tag"

The edge build keeps both. On that tree the merger and both dedupe task tests pass (32 runs, 0 failures).