Attribute a portfolio's income to the securities that paid it
Part of #121 (IP2, the performance engine, under epic #118). Part of we-promise/sure#4078 and we-promise/sure#3494.
Fork pre-flight for we-promise/sure#5094 (same commits), which replaces we-promise/sure#4218.
Replaces jaysbeekay/sure#454 (same changes, rebased and native-stacked).
Stacked on jaysbeekay/sure#712 in a fork native stack.
Rebased 2026-11-15 onto main at dbeebf14c. Rebuilt as one commit whose message lists the slice's original commits: they no longer replay one by one onto the newer slice below, which the old branch had merged in. Its tree equals the old head with main merged in. The commission change in the slice below is included. test/models/portfolio and test/models/balance at this slice: 394 runs, 0 failures. Full suite at the top of the stack: 16,441 runs, 0 failures (8 ReleaseNotesWorkflowTest errors: no node in the test image). Rubocop and Brakeman clean.
Light-review fixes (2026-11-15). bcc570abf gives the v9 refutation in performance_test.rb its own message (it had copied the v8 line's). 753f669d9 fixes a sibling: "an income entry cached before by_security existed is not served" still planted its stale entry under a v8 key after the rebase, so with CACHE_VERSION left at v9 it passed by reading a cache miss. Under the v9 key it fails when the version is not moved, and passes at v10. test/models/portfolio at the top: 288 runs, 0 failures.
Problem
The income PR reports a portfolio's income by month, but not which holdings paid it. A provider records the paying security in different places depending on how it shapes a dividend, and some dividends name no security at all, so a per-security table either has to say what it could not attribute or it will not add up.
Change
app/models/portfolio/daily_returns.rb(+58):#income_by_security. One grouped query over the same entries as the daily rows. It goes through the same classifier, FX conversion, cut-off window and split-parent rule (since14b956621; excluded entries count, as in the rows).- A Trade-shaped dividend names its security in a column.
- A Transaction-shaped one names it only when the provider recorded it in
extra, under the two keysTransaction#activity_security_idreads. - 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, 65 lines).- Rows are sorted largest first, then by ticker.
- An id that matches no security joins
unattributed, andunattributed = total - attributed. So the table always adds up to the income total, and a reversal with no security can make the remainder negative. amount_fortakes a Security or its id.
app/models/portfolio/income.rb.#to_hcarries the raw{ security_id => amount }asby_security, as plain values, so they survive the cache. The query runs only when income is asked for.app/models/portfolio/performance.rb.CACHE_VERSIONgoes from v9 to v10 (the slice below already carries v9), so an income entry cached beforeby_securityexisted is not served.
Income attribution binds the same way (3711b51cd). DailyReturns#income_by_security sanitized income_by_security_query, with the classifier's CASE and joins interpolated, as one string, the same hazard. It now goes through bind_and_splice like the daily query, which arrives here from we-promise/sure#4197 through the stack. The test "a colon word inside the classifier's sql is not read as a bind" in income_by_security_test.rb stubs sql_case with a ':probe' literal and asserts the attribution is unchanged; it raised before the fix, and raises again if the query is sanitized whole.
Updated 2026-10-14. be56fa0d8 merges we-promise/sure#4217 at b786df777, which includes we-promise/sure#4197's one-row-per-entry join and so covers this slice's own SUM over the classifier joins. 14b956621 then makes income_by_security_query share the rows' FX joins (entry_fx_joins) and split-parent predicate (not_split_parent_sql), so attribution still partitions the rows' income now that it counts excluded entries and converts through the account's currency.
Updated 2026-10-15. 31c7e31d8 merges we-promise/sure#4217 at 52031186f; 4d6909c07 then adds "income by security refuses a liability account too": income_by_security runs its own query, so we-promise/sure#4197's liability refusal is asserted on it as well (it holds because the check sits in bind_and_splice; moving the check into raw_rows fails it).
Validation
On 42d2ea086, stacked on 62281704a:
- Full suite (
bin/rails test): 11,974 runs, 55,042 assertions, 0 failures, 0 errors, 34 skips. Run locally on PostgreSQL 16. - After the bind fix, on
3f622bb8f(2026-10-14): full suite 11,978 runs, 0 failures, 0 errors, 34 skips. CI is green. - On
14b956621(2026-10-14): full suite 11,993 runs, 55,099 assertions, 0 failures, 0 errors, 34 skips. Rubocop is clean and Brakeman reports 0 warnings. - On
4d6909c07(2026-10-15): full suite 12,001 runs, 55,132 assertions, 0 failures, 0 errors, 34 skips. Brakeman reports 0 warnings. - Lint and security:
bin/rubocop -f githubon the changed files reports no offenses, andbin/brakeman --no-pager -qreports 0 warnings. No ERB, JS or system-test surface.
Tests
test/models/portfolio/income_by_security_test.rb, income_test.rb and performance_test.rb, on 42d2ea086: 68 runs, 206 assertions, 0 failures.
Fail-first:
- "amount_for takes a Security as readily as its id" failed before the id extraction.
- "an income entry cached before by_security existed is not served" failed at v9 (v8 before the rebase).
- "attributed and unattributed income partition the daily rows' total" is a lock. It covers every storage shape, a fee on a security and a foreign dividend.
- "income attributed to a security counts once when its transaction is a leg of two transfers" (
14b956621): with the join reverted, it reads 60, not 30. - "an excluded dividend and one carrying its own rate partition the daily rows' total" failed before
14b956621. 3 mutations of that change, all caught. - "income by security refuses a liability account too" (
4d6909c07) is a lock: the refusal already holds throughbind_and_splice, and moving the check intoraw_rowsfails it.
Mutations. Each was run on the fork pre-flight, then restored. All were caught:
| Mutation | Tests that catch it |
|---|---|
| Trade security ignored | 9 |
flat extra key ignored | 2 |
| nested key ignored | 1 |
| attribution at the payment date's rate | 1 |
| unconvertible income kept | 1 |
| fees counted as income | 1 |
unattributed forced to zero | 3 |
| rows not sorted | 1 |
by_security dropped from the cached hash | 2 |
| the cut-off ignored | 1 |
any? ignoring the unattributed remainder | 1 |
Re-run on this branch:
CACHE_VERSIONkept at the slice below's version (v9; v8 before the rebase): 1 failure;amount_forwithout the id extraction: 1;unattributedforced to zero: 5;by_securitydropped from the cached hash: 3.
There is one equivalent mutant: fetch with a default in #rows changes nothing, because the rows are built only from securities that exist. The fork pre-flight recorded a second, dropping the excluded filter, which changed nothing then because the classifier returned NULL for excluded entries. Since 14b956621 the query has no excluded filter: it counts excluded entries through the classifier's include_excluded: true and skips split parents with not_split_parent_sql.
The code was byte-identical to the fork pre-flight it supersedes when rebuilt. The bind fix above (3711b51cd) was added afterwards.
Migration notes
None. No schema change.