Resolve return-scope eligibility for a set of accounts
Summary
Closes #154.
Portfolio::ReturnScope answered "what return method can this account's data support?" one account at a time, and every input it reads is its own query. Three callers paid that per account, and a family with twenty investment accounts paid up to eighty round trips on a cache miss to decide which figures it was allowed to quote.
Portfolio::ReturnScope.resolve_all(accounts:, period:) answers the same question for a set in four round trips -- the account load, then three batch queries -- constant in the number of accounts rather than up to four per account. It injects the four inputs into per-account instances that keep deriving kind by the same rules. An instance built directly still queries lazily, so there is one definition of eligibility and the two paths can differ only in how the inputs were fetched — which is what the parity test pins.
A third call site the issue does not name. Performance#time_weighted_supported? (performance.rb:245) also builds one scope per account, reading balance_days. It cost 1 + N rather than 1 + 4N, and it runs on the same uncached path, so a cache miss paid both. It is migrated here and now shares the resolution.
Two things a naive batch gets wrong
Each account must remain its own classifier scope. external_transactions? asks whether money crossed this account's boundary, so a transfer to a sibling is external from where the question is asked. FlowClassifier#scope_ids_sql sanitises the scope into a fixed ARRAY[...]::uuid[] literal inside the CASE — it is not a per-row expression. One classifier over the whole set would reclassify sibling transfers as internal, and an account whose only external flow is a transfer to another account in the set would fall from TRADE_TRACKED to VALUATION_TRACKED, so R16 would withhold a money-weighted return it should quote. The external-flow query is therefore one statement composed of per-account fragments: one round trip, N fragments.
balance_days counts rows in the account's own currency. Grouping over balances alone would count every currency the account holds, so the batch query joins accounts and compares the two. An account with no rows in the period gets no GROUP BY row and defaults to zero rather than going missing, because balance_days.zero? is load-bearing at both Performance call sites.
Scope and dependencies
- Issue: #154 (triage plan: https://github.com/jaysbeekay/sure/issues/154#issuecomment-5690828191)
- Parent PR/branch, if stacked: none — branched from
mainat6ef977d, after #148 and #161 merged - Intentionally out of scope:
- Teaching
FlowClassifiera per-row scope expression (ARRAY[entries.account_id]), which would collapse the N fragments into one self-scoped query. Better end state, but it changes a class with its own parity test and a second consumer, so it belongs in its own issue. - Handing the resolved hash from
InvestmentStatement#performancetoPortfolio::Performance. The issue suggests it, and the triage plan listed it — it is wrong as stated: passing it at construction resolves eagerly on every call, including whenmetricsis served from cache, so it would move the resolution onto the cached path to save it on the uncached one. Sharing would need to be lazy; not attempted here, and noPerformanceconstructor parameter was added, so nothing dead ships. cache_keyandCACHE_VERSION, both untouched.- What
kindmeans. No contract row changes.
- Teaching
Evidence checklist
- Each issue in this PR has its own acceptance criteria and no unrelated issue work is included.
- Contract rows touched by this change name existing tests — R15/R16 behaviour is unchanged and stays covered by the ten existing direct-construction tests in
return_scope_test.rb, which are untouched. - Any gate test has an observed failing mutation transcript attached — not yet done, see Risks. This is the main reason the PR is a draft.
- Fixtures used as evidence assert internal consistency — the new tests build balances through
lay_balance, which refuses a day whose components do not reach the closing figure. - Financial calculations use
BigDecimaland documented rounding points — not applicable; no figure is computed here, only which figures are permitted. - De-identification uses token-shape allowlists; no personal data is included.
- Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.
Files changed
| File | Change |
|---|---|
app/models/portfolio/return_scope.rb | resolve_all plus three private batch queries; initialize accepts pre-resolved inputs |
app/models/portfolio/performance.rb | money_weighted_supported? and time_weighted_supported? read one memoised return_scopes |
app/models/investment_statement.rb | return_scopes resolves once |
test/models/portfolio/return_scope_test.rb | Parity, sibling-transfer, zero-day, currency and empty-set tests |
test/models/portfolio/performance_test.rb | Two query-count assertions |
Validation
Commands and results:
| Check | Result |
|---|---|
ruby -c on all five changed files | Syntax OK |
bin/rails test | Not run locally. The Gemfile pins Ruby 3.4.9; this environment has 3.1.6/3.2.6/3.3.6, so Bundler refuses with Bundler::RubyVersionMismatch |
bin/rubocop | Not run locally, same reason; no standalone rubocop available |
CI is the first real run of these tests, and that is the honest state of this PR. Nothing below is claimed as observed.
Named tests and what each would catch
| Test | Fails if |
|---|---|
resolve_all agrees with a directly built scope on every kind | The batch path drifts from the instance path — the real correctness risk, not the speed |
a transfer to a sibling account in the same set is still external to its own account | The classifier scope is widened to the set; the account reads VALUATION_TRACKED and R16 withholds a figure it should quote |
an account with no balance rows in the period resolves to zero rather than going missing | The GROUP BY row is absent and left missing rather than defaulted |
balance days do not count rows in another currency | The batch groups over balances without the currency join |
resolve_all over no accounts asks nothing | An empty set issues queries or raises |
eligibility for many accounts is resolved in a fixed number of queries | Resolution is per account again; counts ≥ 6 for five accounts |
both supported checks share one eligibility resolution | The memoisation is lost and the second call site pays again |
Risks, blockers, and follow-up
- No test has been observed failing or passing. The mutation transcript the checklist asks for, and the red-then-green evidence, both need a runner with Ruby 3.4.9. Until CI reports, treat every assertion above as reasoned, not demonstrated. If CI is red, that is this PR's to fix.
- The external-flow query grows one fragment per account. One round trip, but the SQL text scales with the account count. The
FlowClassifierper-row-scope change above is the fix for that, deliberately deferred. - Untested interaction: no view currently consumes
InvestmentStatement#return_scopes, so the "a page pays it twice" framing in the issue has no rendering path behind it yet. The duplication was real in the model layer regardless. - Branch name. This is on
claude/review-open-prs-5cbhde, the branch this session was told to develop on, not a descriptive name matching the repo's convention. Say the word and I will move it to something likeperf/return-scope-batch-resolution. - Next unblocked issue: #156, which is waiting on an owner decision (withhold short-period MWR below a minimum, or de-annualise and label it) before it can be implemented.
Summary by CodeRabbit
- Performance Improvements
- Improved investment performance calculations for portfolios with multiple accounts by resolving account eligibility in batches.
- Reduced repeated data lookups when evaluating time-weighted and money-weighted return support.
- Maintained existing return eligibility behavior while improving query efficiency.