Say which return method an account's data can support

Closed
JA
21d ago
+1032-0

Part of #4078 (part 3, returns engine)
Part of #3494

Fork pre-flight: jaysbeekay/sure#451 (pull/451), same branch, same commit. Its CI and review history are there. The earlier evidence for this code is on jaysbeekay/sure#375, the pre-flight it supersedes.

Updated 2026-11-05. Upstream main (529d7de76) is merged in. It stands alone on main; #4214 merges this branch in. Full suite on af484f862: 14,687 runs, 0 failures, 0 errors.

Not stacked. This branch sits directly on main at a3bb5d991. It needs only Portfolio::FlowClassifier, merged in #3557. Its nine commits:

  • 2671d6847 Say which return method an account's data can support
  • 17a10ad4f Pin the batch path's transfer history rules
  • 0d0ccf59e Refuse balance fixture amounts finer than the stored scale
  • e646a2a5e Count balance days only up to each account's cut-off
  • 5170b4940 Read tracking history only up to each account's cut-off
  • 9cd1395af Quote tracking-check values instead of re-sanitizing
  • 603257ae2 Ask the tracking check through a relation, not raw SQL
  • 20716ccd1 Drop the valuations check that never changes the kind
  • b07e2bcee Count only quantity trades as trade tracking

The performance PR merges this branch in, because it reads the class.

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, 291 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/support/portfolio_returns_test_helper.rb (new) builds balance days for the tests and refuses components that do not add up, or amounts finer than the four decimal places balances stores. It is byte-identical to the file the daily returns PR, #4197, adds, so either PR can merge first.

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, on 20716ccd1: 25 runs, 94 assertions, 0 failures.

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.

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
    • Portfolio return tracking now reflects an account’s balance history and recorded activity. Accounts with insufficient balance history are identified separately, while accounts with qualifying trade or external transaction activity can support money-weighted returns.
    • Time-weighted returns are available when an account has sufficient balance history. Return labels distinguish value-based returns from trade-tracked returns.
    • Return tracking respects account-specific cutoff dates and uses balances in the account’s currency.