Read a NULL excluded flag as live on a security transfer's opposite leg
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:
#classifytreats a NULL row as live, becauseexcluded?is false.- The SQL CASE treats it as live too, because
WHEN entries.excludeddoes not fire on NULL. - The opposite-leg lookup for a
Transfertrade filtered onexcluded = 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 isdab9694b7onup/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.
- No new
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 buildsFlowClassifier.new(scope_account_ids:)and putssql_caseintoflows_by_date, which runs overTradeandTransactionentries.Portfolio::Performance#daily_returnspasses itsscope_account_idsin.- 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,
falseleg could not find its NULL counterpart, so it was classified external. - The NULL leg did find its
falsecounterpart, so it was classified internal.
- The live,
- 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
marketasjournal_flow. - The denominator
value_open + external_flow + composition_flowwas 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_unpricedcould suppress the day.
- The day carried a one-sided
- 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 werefalse.
- When it changes: a multi-account scope contains both legs of a security transfer, and one leg has NULL
Portfolio::ReturnScope(return_scope.rb:125,:223). No change. It usessql_caseonly onentryable_type = 'Transaction'rows. The changed lookup handlesTradecounterparts 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 onlyFlowClassifier.pending_sqlandlabels_for, and neither is touched.- Single-account
DailyReturnsscopes. 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 onlydab9694b7'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_columnsand assertsassert_nil in_leg.reload.excludedas its precondition. - Financial calculations use
BigDecimaland 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 ranbin/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) withExpected: :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
= falsefails at:172, theclassify_idsform: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.
- Reverting only the SQL lookup to
- Blast radius. I ran
test/models/portfolio/(which includesdaily_returns_test,performance_testandreturn_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.rbandtest/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
excludedis 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.