Attribute a portfolio's income to the securities that paid it

Closed
JA
21d ago
+6867-36

Part of #118 (IP2, the performance engine; its tracking issue #121 is closed)
Part of we-promise/sure#4078 (returns engine, part 3; under we-promise/sure#3494)

Upstream draft PR: we-promise/sure#4218 (pull/4218), opened 2026-10-14 from this same branch, so it moves with this head (now 58d469e77; the upstream page was not re-read from this session).

Stacked on #453 (up/portfolio-income-v2), which sits on #452 performance, #450 drivers and #451 return scope. The base here is mirror/upstream-main, so until those merge, GitHub shows their commits here as well.

Held for #463. The owner decided on 2026-10-16 (comment 6207728669) that this stack does not merge until #463's trade-fee fix lands.

Supersedes #378 as the upstream pre-flight for income by security. #378 sits on the old up/portfolio-income and is over 120 commits behind. #378 stays open until the owner decides.

  • Base: mirror/upstream-main at bf8d6cc39.
  • Head: up/portfolio-income-by-security-v2 at 58d469e77. This is the top of the stack.

Updated 2026-10-23, merge-down: the head moved from 26ddfeabe to 58d469e77, a merge of #453 at 8cbb31662, which carries #452, #450, #444's fc400f58f, #443's c285e4a49 and upstream main at 2250ba801. Git merged daily_returns.rb without conflict: it keeps this branch's not_split_parent_sql and takes #444's new journal-carry SQL and comments beside it. Full suite on 58d469e77: 13,375 runs, 61,229 assertions, 0 failures, 0 errors, 36 skips, on Ruby 3.4.9.

Updated 2026-10-22, adversarial review round: the head moved from 936ed1556 to 26ddfeabe. This answers the adversarial review of 2026-10-22 and nightly 6328555838, in comment 6349449781.

  • 12899fa6a and 5b1a20d25 merge #453, which carries the #443, #444 and #452 fixes and mirror bf8d6cc39. The conflict in daily_returns.rb was resolved by keeping the shared entry_fx_joins, which now uses #443's SyncCache-window lookup, so income_by_security_query gets the same FX fix.
  • 145e36d15 adds docs: by_security is a period total, and IncomeBySecurity loads Security unscoped because securities are global.
  • 26ddfeabe moves CACHE_VERSION to v10. This branch's v9 (the by-security shape, 42d2ea086) and #452's new v9 (family scoping, the one-day TWR change) meant different things, and the merge kept v9. A test pins it.
  • Evidence. Portfolio tests on 26ddfeabe: 259 runs, 0 failures. Full suite on 145e36d15: 13,138 runs, 60,319 assertions, 1 failure, 0 errors, 36 skips. The one failure is Provider::OpenaiTest's Ruby 3.4 Hash#inspect assertion; the local run used Ruby 3.3.6 against the pinned 3.4.9, and this stack does not touch that test. CI on 26ddfeabe is green.

Updated 2026-10-15: the head moved from 14b956621 to 4d6909c07. 31c7e31d8 merges #453 at 52031186f (the overnight review fixes on #443 and #444). 4d6909c07 adds "income by security refuses a liability account too": income_by_security runs its own query, so #443's liability refusal is asserted here as well; moving the check into raw_rows fails it. Full suite on 4d6909c07: 12,001 runs, 55,132 assertions, 0 failures, 0 errors, 34 skips. Brakeman 0 warnings.

Updated 2026-10-14: the head moved from 42d2ea086 to 3f622bb8f. income_by_security now splices the classifier's SQL in after binding (3711b51cd, with a fail-first probe test), and two merges bring the same fix down from #443, #444 and #451 (full review 6168438106 on #443). The full suite on 3f622bb8f had 11,978 runs, 0 failures and 0 errors; details are in the comment on this PR. The verification below is from 42d2ea086.

Updated 2026-10-14 (2), stack fix pass: the head moved from e18abb034 to 14b956621.

  • be56fa0d8 merges income-v2 at b786df777. It brings #443's one-row-per-entry transfer join, which covers this slice's second SUM site, income_by_security_query (nightly 6172425104).
  • 14b956621, "Attribute income by security from the rows' own entries", adds the test "income attributed to a security counts once when its transaction is a leg of two transfers". With the join reverted it reads 60 instead of 30.
  • It also fixes a sibling. The query must read what the rows' income reads, but after #443 it still dropped excluded entries and converted straight to the family currency. It now shares the rows' FX joins (entry_fx_joins) and split-parent predicate. Fail-first: "an excluded dividend and one carrying its own rate partition the daily rows' total". 3 mutations were all caught.
  • Evidence. Full suite on 14b956621: 11,993 runs, 55,099 assertions, 0 failures, 0 errors, 34 skips. Rubocop is clean and Brakeman reports 0 warnings. The root cause (per-leg unique indexes on transfers) is raised separately as jaysbeekay/sure#459 / we-promise/sure#4225.

Commits (this PR's own)

Cherry-picked from #378.

Commit#378 originalSubject
ef3ae45cd824e76737Attribute a portfolio's income to the securities that paid it
201243fd0418e9ebbcPin the cut-off and the unattributed-only case for attribution
b3a5792c89c0c74d1bLock attribution to the daily rows' total with a partition test
c2ffeb7119b11cc9d2Look a Security up by its id in IncomeBySecurity#amount_for
42d2ea086d33443696Move the performance cache version past the by-security shape
3711b51cd(new)Splice classifier SQL into income attribution after binding
14b956621(new)Attribute income by security from the rows' own entries
145e36d15(new)Say that income by security is a period total and why it is unscoped
26ddfeabe(new)Move the performance cache past both v9 meanings
  • Two comment-only conflicts, resolved as #378 resolved them. ef3ae45cd conflicted in the Income#to_h doc comment and the Performance#income doc comment, because #377's fix round rewrote both after 824e76737 was written. Each keeps both sides, word for word as #378's merge bc9ac6aa3 did. The other four patches are identical to their originals (same git patch-id).
  • Not carried: #378's three --no-ff merges of the income branch.
  • Files against #378's head 375dfe216: every portfolio model and test file was byte-identical (as rebuilt; later changes are in the updates above), except the 18-line helper test in return_scope_test.rb, which arrives with #451 (see #452).

No commit message carries a fork reference.

Summary

Splits the period's income by the security that paid it. Whatever names no security is kept as an explicit unattributed remainder, so the table always adds up to the income total.

What changed

  • app/models/portfolio/daily_returns.rb (+58): #income_by_security. It is one grouped query over the same entries as the daily rows, through the same classifier, rate lookup, cut-off window and excluded rule. A Trade-shaped dividend names its security as a column. A Transaction-shaped one names it only when the provider recorded it in extra, under the two keys Transaction#activity_security_id reads.
  • app/models/portfolio/income_by_security.rb (new, 65 lines): rows largest first, then by ticker. An id that matches no security joins unattributed, and unattributed = total - attributed. amount_for takes a Security or its id.
  • app/models/portfolio/income.rb: #to_h carries the raw { security_id => amount } as by_security, plain values, so they survive the cache. It is a period total, beside the monthly buckets.
  • app/models/portfolio/performance.rb: CACHE_VERSION moves past every earlier meaning (now v10), so an income entry cached before by_security existed is not served.

Demo data

None needed: model only, no UI.

Migration notes

None. No schema change.

Blast radius

Who else hits this line, and what do they pass? Portfolio::Income#to_h is read by Portfolio::Performance#income only. #income_by_security has that one caller.

What else reads what I just changed the reading of? The new query reads the same fragments as flows_by_date. On #378, the cut-off, excluded, rate and classification predicates were each mutated in the new query and caught, apart from the excluded filter, which was redundant then. Since 14b956621 the query has no excluded filter: it counts excluded entries and skips split parents, as flows_by_date does.

Verification (on 42d2ea086; later rounds are in the updates above)

  • income_by_security_test.rb, income_test.rb and performance_test.rb: 68 runs, 206 assertions, 0 failures.
  • Full suite: 11,974 runs, 55,042 assertions, 0 failures, 0 errors, 34 skips. Run locally on PostgreSQL 16.
  • Lint and security: bin/rubocop -f github on the portfolio files reports no offenses, and bin/brakeman --no-pager -q reports 0 warnings. No ERB or JS changed.
  • Mutations re-run on this base, each restored after. All are caught:
    • CACHE_VERSION kept at v8: 1 failure;
    • amount_for without the id extraction: 1;
    • unattributed forced to zero: 5;
    • by_security dropped from the cached hash: 3.
  • Carried from #378. This slice's code was unchanged until 14b956621, so its full mutation list and the fix-round table (cubic VX4f and VX4b; the Gatekeeper partition lock) still apply.

Review history carried from #378

Every review on #378 is answered there (6075798085, 6140346412, the latter declining all eight code-master findings in 6105957783 with evidence), and its two cubic threads are resolved. The nightly review 6157135476 (2026-10-13, MEDIUM: merge the stack in order, retarget to the resulting base and rerun the attribution tests and full CI) is what this rebuild does.