← Back to Pull requests

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

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Oct 20, 2026 08:23 UTC
Author

Closes #4331

Fork pre-flight: https://github.com/jaysbeekay/sure/pull/499 (same branch, same commit), where its CI and review history live. Its full review approved ecbf0ee3b with no open findings.

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

Problem

Since #3850 the holding calculators apply security_splits rows, but nothing writes one. Before #4322 or #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;
    - 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:

    | Mutation | Caught by |
    | --- | --- |
    | Drop the precedence guard | "a provider write never replaces a manual row…" (and 2 more) |
    | Provider logs but still overwrites manual | same 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 fallback | 2: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 paths | the matching rake test, each one |
    | Invert the collision rule | both 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.
  • <!-- This is an auto-generated comment: release notes by coderabbit.ai -->
    <!-- coderabbit-ai-generated:v1 -->

    Summary by CodeRabbit

  • New Features

  • - Added support for recording and managing stock splits, including manual adjustments and provider-reported splits.
    - Account holdings and balances are automatically recalculated after split changes.
    - Split-adjusted cost basis now supports forward and reverse splits accurately.

  • Bug Fixes

  • - Improved handling of split updates and conflicts between manual and provider data.
    - Preserved split information when duplicate securities are consolidated.
    - Prevented incorrect cost calculations around split effective dates.
    - Improved recalculation reliability across account time zones and active syncs.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: jaysbeekay Review duration: 2834m
    All Vouch review confidence checks passed
    Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #4333"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 27.7% · Safe to merge
    27.7%