Say which return method an account's data can support
Part of #121 (IP2, the performance engine, under epic #118). Part of we-promise/sure#4078 and we-promise/sure#3494.
Fork pre-flight for we-promise/sure#5090 (same commits), which replaces we-promise/sure#4212.
Replaces jaysbeekay/sure#451 (same changes, rebased and native-stacked).
Stacked on jaysbeekay/sure#708 in a fork native stack.
Rebased 2026-11-15 onto main at dbeebf14c. Placed above journal flows: it needs only Portfolio::FlowClassifier from main, not the drivers slice. Rebuilt as one commit whose message lists the slice's original commits: they no longer replay one by one onto the newer slice below, which the old branch had merged in. Its tree equals the old head with main merged in. Its test helper keeps the newer copy from the slice below. test/models/portfolio and test/models/balance at this slice: 301 runs, 0 failures. Full suite at the top of the stack: 16,441 runs, 0 failures (8 ReleaseNotesWorkflowTest errors: no node in the test image). Rubocop and Brakeman clean.
Problem
Before any return is computed, something has to decide what an account's records can support. A manually valued account has no record of what was paid in, so a money-weighted return over its flows would be invented. An account with one day of history has no return at all. Nothing in the app makes that call today.
Change
app/models/portfolio/return_scope.rb (new, 300 lines) classifies an account over a period:
trade_tracked. The account records trades that moved a quantity (trades.qty <> 0, sinceb07e2bcee; a zero-quantity dividend, interest or fee trade does not count) or external transfers, so both a time-weighted and a money-weighted return hold.valuation_tracked. Balances that no trade or transfer explains, whether valuation entries assert them or nothing does. Its change is a value return, labelled as one (return_label_key), and it has no money-weighted return.insufficient. Fewer than two balance days in the account's own currency.- History. History before the period counts, because flows known from earlier are still known. Excluded entries count for nothing. Every check reads history only up to the earlier of the period end and the account's cut-off, so an account that left the scope is judged on what it held while inside it.
- Batch path.
resolve_all(accounts:, period:, active_until_dates: {})answers for a set in four queries however many accounts it is given. Each account is its own flow-classifier scope, so a transfer to a sibling in the same set is still external for it.
test/models/portfolio/return_scope_test.rb (new, 548 lines) is the only other file. It uses test/support/portfolio_returns_test_helper.rb, which ships in the daily returns slice below (jaysbeekay/sure#707) and is not changed here.
The tracking check no longer re-sanitizes the classifier's SQL (9cd1395af, 603257ae2). ReturnScope#external_transactions? passed a string containing the classifier's CASE through sanitize_sql_array, so a :word in a classifier label or literal would be read as a bind and raise. It is now a relation on live_entries_through_history_end, with the CASE added through Arel.sql, as FlowClassifier#classify_ids does. Its own probe test, "a colon word inside the classifier's sql is not read as a bind", covers it.
The valuations check is gone (20716ccd1). kind returned VALUATION_TRACKED both after elsif valuations? and in its else, so the check never changed the result. Removed: valuations?, the batch path's valuations input, and the Valuation rows the batch entry query fetched only to fill it. That query now reads trades alone. kind is unchanged: fewer than two balance days is insufficient, a trade or external transfer is trade tracked, and anything else is valuation tracked.
Only a trade that moved a quantity counts as trade tracking (b07e2bcee, 2026-10-14). Zero-quantity dividend, interest and fee trades (as Trade::CreateForm writes them) no longer offer a money-weighted return on a manually valued account. Both trades? and the batch resolve_all path use one shared join on trades.qty <> 0.
Validation
On 5170b4940, cut from main at a3bb5d991:
- Full suite (
bin/rails test): 11,845 runs, 54,640 assertions, 0 failures, 0 errors, 34 skips. Run locally on PostgreSQL 16. - After the bind fix, on
603257ae2(2026-10-14): full suite 11,846 runs, 0 failures, 0 errors, 34 skips. Brakeman 0 warnings. CI is green. - After the valuations clean-up, on
20716ccd1(2026-10-14): full suite 11,846 runs, 54,647 assertions, 0 failures, 0 errors, 34 skips. Rubocop reported no offenses on the changed files, and Brakeman reported 0 warnings. - After the trade-quantity fix, on
b07e2bcee(2026-10-14): full suite 11,847 runs, 0 failures, 0 errors, 34 skips. - Lint and security:
bin/rubocop -f githubon the changed files reports no offenses, andbin/brakeman --no-pager -qreports 0 warnings. No ERB, JS or system-test surface.
Tests
test/models/portfolio/return_scope_test.rb: 29 runs, 0 failures at this head (fbaf4c78d); 25 runs on 20716ccd1, before b07e2bcee added one.
A new test, 'a valuation entry never decides the kind, on either path', checks on the instance and the batch path that a valuation-only account is valuation tracked, and that a trade beside a valuation still makes it trade tracked. Mutations on 20716ccd1: the fallback returning TRADE_TRACKED causes 9 failures; the batch entry query counting a Valuation as a trade causes 1, caught only by the new test; the batch query reading Valuation instead of Trade causes 4.
One new test for b07e2bcee, through both paths, fails on 20716ccd1; 3 mutations, all caught.
Cash-only Contribution and Withdrawal trades (41849b565, fbaf4c78d). A zero-quantity Contribution or Withdrawal trade that moved cash counts as a known flow. One test for each side, through both paths. Reading the shared CASH_FLOW_ENTRY_SQL as entries.amount < 0 fails the withdrawal test at the direct assertion; changing only the batch fragment fails it at the batch assertion.
Fail-first. The cut-off tests failed on the unknown active_until_date / active_until_dates keywords, then at the trade and transfer checks once the keywords existed. The helper's scale test failed before the scale check.
Mutations. Each was run against this file's tests on the fork pre-flight, then restored. All were caught:
| Mutation | Tests that catch it |
|---|---|
| one balance day treated as enough | 2 |
| external transfers ignored | 4 |
| money-weighted allowed for valuation-tracked | 3 |
| excluded trades counted | 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 and batch) | 1 each |
| instance or batch path ignoring the cut-off | 1 to 3 |
| a cut-off extending past the period end | 1 |
< for <= on the cut-off | 1 |
Re-run on this branch, cut from current main:
- one balance day treated as enough: 4 failures;
- instance
balance_daysignoring the cut-off: 2; history_end_dateignoring the cut-off: 3;- batch balance-day cut-off with
<for<=: 4; - the helper's scale check skipped: 1.
Equivalent mutants, recorded rather than tested: excluding excluded entries in the batch query (the classifier already returns NULL for them).
The code was byte-identical to the fork pre-flight it supersedes when rebuilt. The bind fix (9cd1395af, 603257ae2) and the valuations clean-up (20716ccd1) above were added afterwards.
Migration notes
None. No schema change.