Say which return method an account's data can support
Part of #121
This is the upstream pre-flight for slice 4 of 7 of the portfolio return engine (drop 2 of #118). The upstream PR on we-promise/sure is NOT YET OPENED (awaiting owner approval). When it is opened it will be from this branch: same branch, same commit.
Base is the parent slice's branch, so this diff shows only this slice's commits. Fork stack: #372 daily returns → #373 journal flows → #374 drivers → #376 performance (carrying #375 return scope, which is also based on up/pending-sql-parity) → #377 income → #378 income by security.
Part of we-promise/sure#4078
Part of we-promise/sure#3494
Slice 4 of 7 of the portfolio returns engine; we-promise/sure#4078 is the issue (part 3, returns engine).
Fork pre-flight PR: jaysbeekay/sure#375 (https://github.com/jaysbeekay/sure/pull/375), same branch, same commit.
Stacked on we-promise/sure#3557 (up/pending-sql-parity). Until that merges, GitHub shows its commits here as well; this PR's own commits are the ones after up/pending-sql-parity. I will rebase onto main as each parent merges.
Stack, in merge order: we-promise/sure#3557 (flow classifier) → daily returns → journal flows → drivers → return scope → performance → income → income by security. Return scope also stands alone on we-promise/sure#3557.
Nothing calls these classes until Portfolio::Performance (the fifth PR in this stack). Every PR before it adds a model with its tests and no caller, so it changes no page, job or API response.
Summary
Adds Portfolio::ReturnScope, which decides before any figure is computed what an account's records can support over a period: a manually valued account has no record of what was paid in, so a money-weighted return over its flows would be invented, and an account with one day of history has no return at all.
What changed
app/models/portfolio/return_scope.rb (new):
trade_tracked: it records trades or external transfers, so both a time-weighted and a money-weighted return hold.valuation_tracked: its value is asserted by valuations. Its change is a value return, labelled as one (return_label_key).insufficient: fewer than two balance days in the account's own currency.- History before the period counts, because flows known from earlier are still known. Excluded entries count for nothing. History ends at the earlier of the period end and the account's cut-off, for every check.
resolve_all(accounts:, period:)answers for a set in four queries however many accounts it is given. Each account is its own flow-classifier scope there too, so a transfer to a sibling in the same set is still external for it.
test/support/portfolio_returns_test_helper.rb: the same builder file the daily returns PR adds, byte-identical, so either can merge first.
Demo data
None needed: model only, no UI. Exercised by the tests below.
Migration notes
None. No schema change; reads existing balances, entries, trades, transactions, holdings and exchange_rates columns.
Verification
return_scope_test.rb: 15 runs, 44 assertions, 0 failures.- Mutations, all caught:
- one balance day treated as enough: 2 tests;
- external transfers ignored: 4;
- money-weighted for valuation-tracked: 3;
- excluded trades counted: 1;
- a bare
excluded = falsein the transfer check: 1; - the whole batch as one classifier scope: 1;
- balance days counted in any currency: 1;
- return label inverted: 1;
- pre-period transfers ignored (instance path): 1.
- The batch path's pre-period rule survived the original tests. The new "resolve_all reads transfer history as the instance does" catches it.
- Equivalent mutants, recorded rather than tested:
- excluding
excludedentries in the batch query is redundant, because the classifier's CASE already returns NULL for them; - a missing account's
balance_daysdefaulting to nil falls back to the instance query and still answers 0; - the batch
valuationsflag cannot changekind, because both remaining branches givevaluation_tracked.
- excluding
- Full suite after the cut-off follow-up, at the top of the stack (
up/portfolio-income-by-securityat 1dc444d54): 10,782 runs, 45,992 assertions, 0 failures, 0 errors, 33 skips (local, PostgreSQL 16, 4 workers). On this branch, which is not in that stack's ancestry (up/portfolio-return-scopeat 9d2d58028): 10,657 runs, 45,616 assertions, 0 failures, 0 errors, 33 skips. bin/rubocopon the changed files: no offenses.bin/brakeman --no-pager -q: 0 warnings.
Blast radius
Who else hits this line, and what do they pass? No caller in this PR. Portfolio::Performance (later in the stack) passes Account.where(id: account_ids) and, since the fix round, the cut-offs DailyReturns resolved.
What else reads what I just changed the reading of? Nothing is changed outside the new files. It reads Portfolio::FlowClassifier with a one-account scope, as the classifier's own tests do.
Engine fix round (2026-10-09)
| Commit | Finding | Test | Fail-first / mutation |
|---|---|---|---|
| 3d2392d16 | cubic VYFF: lay_balance accepts sub-4dp amounts | "the balance builder refuses an amount finer than balances store" | failed at :270; skipping the scale check caught (:270). The helper is line for line the change on #372 (69236dc31). |
| ab4a52295 | owner decision 6 (for #376's cubic VcEX): eligibility ignores cut-offs | "a cut-off that leaves one balance day in the window is insufficient", "resolve_all counts balance days only up to each account's own cut-off" (including a nil cut-off meaning none), "resolve_all with cut-offs asks no more queries than without" (4) | failed on the unknown keywords active_until_date / active_until_dates; instance path ignoring the cut-off caught (:240, :264); batch path ignoring them caught (:260) |
| 9d2d58028 | owner decision 2026-10-09: the cut-off bounded balance_days only, so a trade, valuation or transfer after it still counted | "a trade after the cut-off does not make the account trade tracked", "an external transfer after the cut-off does not make the account trade tracked", "a valuation after the cut-off is not read as the account's history" (each against the same account with no cut-off, on the instance and the batch path); controls "activity on or before the cut-off still counts" and "a cut-off after the period does not read history past the period end" | failed at :332, :340 and :351 (trade tracked / valuation read with the cut-off). Instance ignoring the cut-off caught (:332, :340, :351); batch entry-kind query ignoring it caught (:332, :351); batch transfer fragment ignoring it caught (:340); a cut-off extending past the period end caught on the instance (:383) and the batch transfer read (:390); < for <= caught (:360) |
ReturnScope.new(account:, period:, active_until_date: nil).ReturnScope.resolve_all(accounts:, period:, active_until_dates: {})is keyed by account id in the shapeDailyReturnstakes, so both paths count balance rows up to the cut-off. Since 9d2d58028 the trade, valuation and transfer checks read only up to the same date, the earlier of the period end and the cut-off. The batch path binds the cut-offs into its entry-kind query and gives each transfer fragment its own end date, soresolve_allstill asks four queries (the query-count tests are unchanged).valuations?is asserted directly becausekindcannot show it: without trades or transfers both remaining branches givevaluation_tracked.- How this reaches #376. It is not by merge: #376 has carried the return scope commits as cherry-picks since it was built. The cut-off commits are cherry-picked there too (bbd5e9ace and 164e38dcd,
-x), andreturn_scope.rbis identical on both branches. The only test difference is the helper test above, which on #376 lives indaily_returns_test.rb. return_scope_test.rb: 24 runs, 87 assertions, 0 failures.- Readers of ReturnScope's predicates (grepped at the top of the stack):
Portfolio::Performance#money_weighted_supported?readssupports_money_weighted_return?andbalance_daysthrough#return_scopes, which already passesDailyReturns' cut-offs, so it picks the fix up unchanged;#time_weighted_supported?readsbalance_daysonly, already cut;Portfolio::Driversnames the class in a comment only. Nothing on this branch calls it.