Attribute a portfolio's income to the securities that paid it
This is the upstream pre-flight for slice 7 of 7 of the portfolio return engine (drop 2 of #118). The upstream PR on we-promise/sure is NOT YET OPENED (awaiting owner approval). When it is opened it will be from this branch: same branch, same commit.
Base is the parent slice's branch, so this diff shows only this slice's commits. Fork stack: #372 daily returns → #373 journal flows → #374 drivers → #376 performance (carrying #375 return scope, which is also based on up/pending-sql-parity) → #377 income → #378 income by security.
Closes we-promise/sure#4078
Part of we-promise/sure#3494
Slice 7 of 7 of the portfolio returns engine; we-promise/sure#4078 is the issue (part 4, income).
Fork pre-flight PR: jaysbeekay/sure#378 (https://github.com/jaysbeekay/sure/pull/378), same branch, same commit.
Stacked on the income PR. Until that merges, GitHub shows its commits here as well; this PR's own commits are the ones after up/portfolio-income. I will rebase onto main as each parent merges.
Stack, in merge order: we-promise/sure#3557 (flow classifier) → daily returns → journal flows → drivers → return scope → performance → income → income by security. Return scope also stands alone on we-promise/sure#3557.
Summary
Splits the period's income by the security that paid it, with whatever names no security kept as an explicit unattributed remainder, so the table always adds up to the income total.
What changed
app/models/portfolio/daily_returns.rb: #income_by_security, 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 only when the provider recorded it in extra (the two keys Transaction#activity_security_id reads). Ids are compared lower-cased. An entry with no rate is dropped, as the rows drop it.
app/models/portfolio/income_by_security.rb (new): rows largest first, then by ticker; an id that matches no security joins unattributed; unattributed = total - attributed.
app/models/portfolio/income.rb: #to_h carries the raw { security_id => amount } as by_security, plain values, so they survive Performance#income's cache. The by-security query runs only when income is asked for.
Demo data
None needed: model only, no UI. Exercised by the tests below.
Migration notes
None. No schema change; reads existing balances, entries, trades, transactions, holdings and exchange_rates columns.
Verification
income_by_security_test.rb,income_test.rbandperformance_test.rb: 56 runs, 145 assertions, 0 failures.- Mutations, all caught:
- Trade security ignored: 9 tests;
- flat
extrakey ignored: 2; - nested key ignored: 1;
- attribution at the payment date's rate: 1;
- unconvertible income kept: 1;
- fees counted as income: 1;
unattributedforced to zero: 3;- rows not sorted: 1;
by_securitydropped from the cached hash: 2.
- Two mutants survived the original tests and are caught by new ones: the cut-off ignored ("income after an account's cut off date is not attributed") and
any?ignoring the unattributed remainder ("a period whose income is all unattributed still has something to show"). - Equivalent mutants:
- dropping the excluded filter, because the classifier already returns NULL for excluded entries;
fetchwith a default in#rows, because the rows are built only from securities that exist.
- Full suite after the cut-off follow-up, at the top of the stack (
up/portfolio-income-by-securityat 1dc444d54): 10,782 runs, 45,992 assertions, 0 failures, 0 errors, 33 skips (local, PostgreSQL 16, 4 workers). bin/rubocopon the changed files: no offenses.bin/brakeman --no-pager -q: 0 warnings.
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. The cut-off, excluded, rate and classification predicates were each mutated in the new query and caught, apart from the excluded filter, which is redundant.
Engine fix round (2026-10-09)
Cut-off follow-up. up/portfolio-income is merged down again (1dc444d54, --no-ff, clean, no conflicts) to bring in ReturnScope reading its trade, valuation and transfer history only up to each account's cut-off (#375 9d2d58028, cherry-picked onto #376 as 164e38dcd). Nothing in this slice reads ReturnScope directly.
up/portfolio-income is merged down (bc9ac6aa3, --no-ff, no force push). Two conflicts came up, both comment-only: the Income#to_h and Performance#income docs. Both were resolved by keeping both sides.
| Commit | Finding | Test | Fail-first / mutation |
|---|---|---|---|
| 9c0c74d1b | Gatekeeper recommendation: a reconciliation lock | "attributed and unattributed income partition the daily rows' total". Each side is derived on its own: the total from the rows' income, attributed from income_by_security, unattributed from the fixture. It covers every storage shape, a fee on a security and a foreign dividend. | a lock, passes as is. The by-security rate at entries.date is caught (:248); the rows' income without FX is caught (:247). Dropping the by-security cut-off window is not caught by the lock, which has no cut-off, but is caught by the existing "income after an account's cut off date is not attributed" (:154). |
| 9b11cc9d2 | cubic VX4f: amount_for(Security) read 0 | "amount_for takes a Security as readily as its id" | failed at :47; dropping the id extraction caught (:47) |
| d33443696 | cubic VX4b: CACHE_VERSION not bumped for by_security | "an income entry cached before by_security existed is not served" | failed at :231 at v8; keeping v8 caught (:231) |
amount_for: a Security is supported rather than the comment narrowed, because the doc already promised it. Every caller passes an id and is unaffected.CACHE_VERSION: v8 (Performance slice) → v9 here, so each slice's version is above its parent's.
Precision follow-up (2026-10-13). up/portfolio-income is merged down again, as 456fd5542 (--no-ff, clean). It brings in #376's fix that rounds each chained return level to 20 significant digits. Full suite at 456fd5542: 10,783 runs, 45,999 assertions, 0 failures, 0 errors, 33 skips. The ci / test_system failure on 1dc444d54 was the flaky PropertiesEditTest; the re-run of run 37911326515 passed.