Give split rows one write path, and a split-aware cost fallback

Merged
JA
2mo ago
+507-4

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

Upstream PR: we-promise/sure#4333 (draft), on upstream issue we-promise/sure#4331. Same branch, same commit: this pre-flight runs the fork's CI and Gatekeeper reviews on up/security-split-foundation against mirror/upstream-main.

Part of we-promise/sure#3781. This is the model-only slice that we-promise/sure#4322 (manual entry) and we-promise/sure#4323 (provider split import) build on.

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.
  • Holding#calculate_avg_cost, the fallback for a holding with no stored cost_basis, divided by SUM(trades.qty). From an ex-date it reported the pre-split cost per share beside a qty the calculators had already scaled: 100 instead of 50 after a 2-for-1 split.
  • The three tasks that merge duplicate securities destroyed the duplicate's splits (dependent: :destroy) instead of moving them.

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 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.
    • While the account has a visible syncing sync, it retries every 30 seconds, 20 attempts, past Sync::VISIBLE_FOR, then materialises once that sync has finished. 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 duplicate's splits at the security that stays. On a shared ex-date, manual beats provider, and between equals the canonical row stays. securities:deduplicate (both paths) and data_migration:migrate_duplicate_securities call it before destroying the duplicate, and report what was moved and dropped.
  • calculate_avg_cost:
    • Its totals query is grouped by trade date.
    • Each day's quantity is scaled exactly (Security::Split.scale) by the splits after it and on or before the holding's date.
    • A buy on the ex-date is already in the new shares.
    • It's still the same two trade queries, and with no split rows the result is unchanged.

No migration, no UI, no strings, no API.

Blast radius

  • avg_cost readers, all corrected by the fallback change:
    • Holding#trend;
    • Trade#realized_gain_loss, through its basis holding;
    • InvestmentStatement;
    • Assistant::Function::GetHoldings;
    • the v1 holdings jbuilder;
    • holdings/_cost_basis_cell and holdings/show.
  • Security::Price::ImportWindows also sums trades.qty, but already treats a zero holding as authoritative after a reverse split, so it's unchanged.
  • 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.
  • Holding#remap_security! moves one account's trades to another security without destroying either, so the new security's own splits apply. That's correct, and it's unchanged.
  • The fallback now reads security.splits once per holding instance. Upstream has no preload for this fallback; with no split rows it's one empty indexed query per holding on a path that already costs two.

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, and handles both collision cases.
  • 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 retry while the sync is still running defers again, and the last attempt materialises (added in ecbf0ee3b after the light review);
    • a pending sync doesn't hold the job back.
  • test/models/holding_test.rb:
    • the fallback reads 100 the day before a 2-for-1 ex-date and 50 on it, with equal total cost;
    • a buy on the ex-date isn't scaled again;
    • a 1-for-10 reverse split scales the other way;
    • without split rows the fallback is unchanged;
    • a post-split holding's trend.previous is qty × 50.
  • test/lib/tasks/securities_rake_test.rb: a duplicate's split survives each of the three merge paths. Two of the paths group on ticker and MIC, which the unique index now rules out, so those tests drop the index inside their transaction to recreate the older data.

Mutations, each caught by a named test:

MutationCaught by
Drop the precedence guard"a provider write never replaces a manual row…" (and 2 more)
Provider logs but still overwrites manualsame three
Log even when terms match"a provider write that matches a manual row logs nothing"
Drop the enqueue"recording a split enqueues…", "removing a split…", "moving a split's ex-date…"
Enqueue on an unchanged write"an unchanged write enqueues nothing"
Job runs during a syncing sync"an account mid-sync is retried…"
attempts lowered so a mid-sync retry exhausts, exhaustion block removed, or materialise before deferring"a retry while the sync is still running…"
Job blocked by a pending sync"a pending sync does not hold the job back"
Drop the scaling in the fallback2:1, ex-date buy, 1:10 and trend tests
Scale a buy on the ex-date"a buy on the ex-date is not scaled again"
Drop move! from each of the three merge pathsthe matching rake test, each one
Invert the collision ruleboth collision tests

Validation

  • Full suite: 12,460 runs, 0 failures, 0 errors, 36 skips, at ecbf0ee3b.
  • RuboCop: no offences. Brakeman: 0 warnings. An earlier draft built the scaled quantity as an interpolated SQL CASE, which Brakeman flagged; the scaling now happens in Ruby.
  • No UI, no migration, no new dependency.