Give split rows one write path, and a split-aware cost fallback #4333
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.02 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
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
jaysbeekay
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
ecbf0ee3bwith 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_splitsrows, but nothing writes one. Before #4322 or #4323 starts writing rows:sourcewas required but unconstrained.(security_id, ex_date), or silently overwrite the user's figures.Holding#calculate_avg_cost, the fallback for a holding with no storedcost_basis, divided bySUM(trades.qty). From an ex-date it reported the pre-split cost per share beside aqtythe calculators had already scaled: 100 instead of 50 after a 2-for-1 split.dependent: :destroy) instead of moving them.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 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.- While the account has a visible
syncingsync, it retries every 30 seconds, 20 attempts, pastSync::VISIBLE_FOR, then materialises once that sync has finished.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.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) anddata_migration:migrate_duplicate_securitiescall 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_costreaders, 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_cellandholdings/show.Security::Price::ImportWindowsalso sumstrades.qty, but already treats a zero holding as authoritative after a reverse split, so it's unchanged.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.security.splitsonce 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.previousis 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
syncingsync | "an account mid-sync is retried…" ||
attemptslowered 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
pendingsync | "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
ecbf0ee3b.CASE, which Brakeman flagged; the scaling now happens in Ruby.<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
Summary by CodeRabbit
- 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.
- 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 -->