Attribute a portfolio's income to the securities that paid it
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-mainatbf8d6cc39. - Head:
up/portfolio-income-by-security-v2at58d469e77. 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.
12899fa6aand5b1a20d25merge #453, which carries the #443, #444 and #452 fixes and mirrorbf8d6cc39. The conflict indaily_returns.rbwas resolved by keeping the sharedentry_fx_joins, which now uses #443's SyncCache-window lookup, soincome_by_security_querygets the same FX fix.145e36d15adds docs:by_securityis a period total, andIncomeBySecurityloadsSecurityunscoped because securities are global.26ddfeabemovesCACHE_VERSIONto 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 on145e36d15: 13,138 runs, 60,319 assertions, 1 failure, 0 errors, 36 skips. The one failure isProvider::OpenaiTest's Ruby 3.4Hash#inspectassertion; the local run used Ruby 3.3.6 against the pinned 3.4.9, and this stack does not touch that test. CI on26ddfeabeis 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.
be56fa0d8merges income-v2 atb786df777. 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'
incomereads, 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 ontransfers) is raised separately as jaysbeekay/sure#459 / we-promise/sure#4225.
Commits (this PR's own)
Cherry-picked from #378.
| Commit | #378 original | Subject |
|---|---|---|
ef3ae45cd | 824e76737 | Attribute a portfolio's income to the securities that paid it |
201243fd0 | 418e9ebbc | Pin the cut-off and the unattributed-only case for attribution |
b3a5792c8 | 9c0c74d1b | Lock attribution to the daily rows' total with a partition test |
c2ffeb711 | 9b11cc9d2 | Look a Security up by its id in IncomeBySecurity#amount_for |
42d2ea086 | d33443696 | Move 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.
ef3ae45cdconflicted in theIncome#to_hdoc comment and thePerformance#incomedoc comment, because #377's fix round rewrote both after824e76737was written. Each keeps both sides, word for word as #378's mergebc9ac6aa3did. The other four patches are identical to their originals (samegit patch-id). - Not carried: #378's three
--no-ffmerges 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 inreturn_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 inextra, under the two keysTransaction#activity_security_idreads.app/models/portfolio/income_by_security.rb(new, 65 lines): rows largest first, then by ticker. An id that matches no security joinsunattributed, andunattributed = total - attributed.amount_fortakes a Security or its id.app/models/portfolio/income.rb:#to_hcarries the raw{ security_id => amount }asby_security, plain values, so they survive the cache. It is a period total, beside the monthly buckets.app/models/portfolio/performance.rb:CACHE_VERSIONmoves past every earlier meaning (now v10), so an income entry cached beforeby_securityexisted 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.rbandperformance_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 githubon the portfolio files reports no offenses, andbin/brakeman --no-pager -qreports 0 warnings. No ERB or JS changed. - Mutations re-run on this base, each restored after. All are caught:
CACHE_VERSIONkept at v8: 1 failure;amount_forwithout the id extraction: 1;unattributedforced to zero: 5;by_securitydropped 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.