Read a NULL excluded flag as live on a security transfer's opposite leg

Merged
JA
2mo ago
+26-3

Summary

This ports #225's fix dab9694b7 onto fork main. It restores the single copy of Portfolio::FlowClassifier required by #118, duty 3, and #119.

The problem is that entries.excluded can be NULL (default: false, with no null: false), and one lookup reads NULL differently from the rest of the classifier:

  • #classify treats a NULL row as live, because excluded? is false.
  • The SQL CASE treats it as live too, because WHEN entries.excluded does not fire on NULL.
  • The opposite-leg lookup for a Transfer trade filtered on excluded = false. That drops NULL rows.

So when a position moved between two accounts inside the scope and one leg's excluded was NULL, the other leg found no counterpart and was classified external_outflow (or external_inflow) instead of internal. This happened in both the Ruby and the SQL forms.

The fix changes both lookups to IS NOT TRUE. A leg that is explicitly excluded (true) still does not count.

After this PR, the classifier file and its test on main are byte-identical to #225's head again:

git diff origin/up/portfolio-flow-classifier -- app/models/portfolio/flow_classifier.rb \
  test/models/portfolio/flow_classifier_test.rb test/support/portfolio_flow_test_helper.rb
# (empty)

Before the port, main's copies were identical to dab9694b7^ (the diff was empty). The only difference was the fix itself, so this is a straight cherry-pick with nothing reconciled by hand.

Scope and dependencies

  • Issue: #119 (single-copy rule), under the programme #118. It comes from the cubic finding recorded as thread 4 in #225's disposition comment.
  • Parent PR/branch, if stacked: none. Branched from origin/main. The source commit is dab9694b7 on up/portfolio-flow-classifier (#225, which is the same branch as we-promise/sure#3617).
  • Intentionally out of scope:
    • No new Portfolio::DailyReturns-level test. The classifier test pins both forms, and this PR is a like-for-like port.
    • The other open #225 thread (the test header naming fork-only docs) is left alone, so both copies stay identical.

Blast radius on fork main

Who reads the classifier on main, and what do they pass? main has callers that the upstream branch does not have.

  • Portfolio::DailyReturns (daily_returns.rb:538-570). This is the only caller whose result changes. It builds FlowClassifier.new(scope_account_ids:) and puts sql_case into flows_by_date, which runs over Trade and Transaction entries. Portfolio::Performance#daily_returns passes its scope_account_ids in.
    • When it changes: a multi-account scope contains both legs of a security transfer, and one leg has NULL excluded.
    • Before this fix, the two legs disagreed.
      • The live, false leg could not find its NULL counterpart, so it was classified external.
      • The NULL leg did find its false counterpart, so it was classified internal.
    • The effect on returns before the fix:
      • The day carried a one-sided external_flow. For a journal (amount = 0), that flow was valued at qty × the holding price. For an ordinary transfer trade, it was -amount.
      • For a journal, the same value was also subtracted from market as journal_flow.
      • The denominator value_open + external_flow + composition_flow was therefore off by the position's value. An internal move that should not affect returns read as a contribution or withdrawal, which distorted that day's time-weighted return.
      • If the holding had no price that day, journal_unpriced could suppress the day.
    • After this fix: both legs are internal. No external flow is counted and no journal adjustment is made. The two accounts' balance movements cancel out inside the scope, as they already did when both flags were false.
  • Portfolio::ReturnScope (return_scope.rb:125, :223). No change. It uses sql_case only on entryable_type = 'Transaction' rows. The changed lookup handles Trade counterparts only, and each account is its own scope here, so a counterpart in another account is outside the scope either way.
  • InvestmentStatement::Totals (totals.rb:141-149). No change. It reads only FlowClassifier.pending_sql and labels_for, and neither is touched.
  • Single-account DailyReturns scopes. No change. The opposite leg is always in another account, so it is outside the scope, and the leg is external both before and after the fix.

I have not measured how common NULL excluded rows are. The column defaults to false, so NULL comes only from writes that bypass the default: raw SQL, update_columns(excluded: nil), or an importer that writes nil.

Evidence checklist

  • Each issue in this PR has its own acceptance criteria and no unrelated
    issue work is included. The change is only dab9694b7's two files.
  • Contract rows touched by this change name existing tests. No contract row changed. test/lib/portfolio/ passes.
  • Any gate test has an observed failing mutation transcript attached. See Validation below.
  • Fixtures used as evidence assert internal consistency. The test sets NULL with update_columns and asserts assert_nil in_leg.reload.excluded as its precondition.
  • Financial calculations use BigDecimal and documented rounding points. Not applicable: no arithmetic changed.
  • De-identification uses token-shape allowlists; no personal data is
    included.
  • Files changed, decisions, tests/runtime, risks, and next unblocked issue
    are documented below.

Validation

Commands and results (run locally on Ruby 3.3.6):

  • Fail-first. I applied only the new test to main's unfixed classifier and ran bin/rails test test/models/portfolio/flow_classifier_test.rb -n "/NULL excluded flag/". The NULL precondition passed, then the test failed at :171 (the Ruby form) with Expected: :internal / Actual: :external_outflow.
  • With the fix, it passes: 1 run, 5 assertions, 0 failures.
  • Mutations. Each change was made on top of the fix, and each was caught:
    • Reverting only the SQL lookup to = false fails at :172, the classify_ids form: Expected :internal, Actual :external_outflow.
    • Reverting only the Ruby lookup to where(excluded: false) fails at :171: Expected :internal, Actual :external_outflow.
    • Dropping the excluded filter from both lookups fails at :176, the other side of the boundary: Expected :external_outflow, Actual :internal.
  • Blast radius. I ran test/models/portfolio/ (which includes daily_returns_test, performance_test and return_scope_test), test/lib/portfolio/, test/models/investment_statement_test.rb, test/models/investment_statement/, test/controllers/portfolios_controller_test.rb, pages_controller_test.rb, reports_controller_test.rb, test/helpers/portfolios_helper_test.rb and test/models/family_test.rb. Result: 529 runs, 2003 assertions, 0 failures, 0 errors.
  • bin/rubocop app/models/portfolio/flow_classifier.rb test/models/portfolio/flow_classifier_test.rb: no offences.

Risks, blockers, and follow-up

  • Returns can change for affected data. Multi-account performance figures change on any day where a security moved between two in-scope accounts and one leg's excluded is NULL. The change is towards the correct figure: such a move is no longer counted as a flow into or out of the scope.
  • Still to do before merge:
    • The draft-gate Gatekeeper review.
    • CI on this head.
    • After the port, #225's body should drop its declared "single-copy divergence" once this PR lands.