Say which return method an account's data can support

JA
7d ago
+864-0

Part of #4078 (part 3, returns engine)

Part of #3494

Replaces #4212 (same changes, rebased and native-stacked; its review history stays there).

What: adds Portfolio::ReturnScope, which says what return an account's records can support over a period: trade_tracked (trades that moved a quantity, or external transfers: time- and money-weighted both hold), valuation_tracked (balances nothing explains: a value return only, no money-weighted return) or insufficient (fewer than two balance days in the account's currency). resolve_all answers for a set of accounts in four queries, honouring each account's cut-off.
Why: 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. Nothing in the app makes that call today.
Start reading: ReturnScope#kind and .resolve_all in app/models/portfolio/return_scope.rb.
Key tests (test/models/portfolio/return_scope_test.rb):

  • "a valuation tracked account does not support money weighted return"
  • "an account whose only trades are dividends, interest or fees is valuation tracked"
  • "a transfer to a sibling account in the same set is still external to its own account"
  • "resolve_all agrees with a directly built scope on every kind"
  • "resolve_all asks the same number of queries however many accounts it is given"

Behaviour change: none; nothing calls this class yet. No migration.

Stack: 4 of 11 in the portfolio returns stack, on #5089. GitHub shows only this slice's diff. Next: #5091 (drivers). Merge order: #5129 → #5088 → #5089 → #5090 → #5091 → #5092 → #5093 → #5094 → #5285 → #5296 → #5297.
Size: +300 outside tests, in one new file.
Fork pre-flight: jaysbeekay/sure#709 (same commits, against a mirror of upstream main). Earlier evidence: jaysbeekay/sure#451.

Full description and evidence

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, since b07e2bcee; 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 (#5088) 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 github on the changed files reports no offenses, and bin/brakeman --no-pager -q reports 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:

MutationTests that catch it
one balance day treated as enough2
external transfers ignored4
money-weighted allowed for valuation-tracked3
excluded trades counted1
the whole batch as one classifier scope1
balance days counted in any currency1
return label inverted1
pre-period transfers ignored (instance and batch)1 each
instance or batch path ignoring the cut-off1 to 3
a cut-off extending past the period end1
< for <= on the cut-off1

Re-run on this branch, cut from current main:

  • one balance day treated as enough: 4 failures;
  • instance balance_days ignoring the cut-off: 2;
  • history_end_date ignoring 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.

Summary by CodeRabbit

  • New Features
    • Return reporting now identifies whether an account has enough balance history to support return calculations.
    • Accounts with qualifying trades or external cash flows can support money-weighted returns; accounts without those flows may be limited to time-weighted, value-based returns.
    • Classification considers the account’s currency, relevant activity, and applicable date cutoff, helping reflect each account’s available history.