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

JA
7d ago
+680-64

Updated 2026-11-20 (head c2180bfcb). A split dividend is now attributed to the security its parent names. Entry#split! copies neither the label nor extra to the parts; the classifier already read the parent's label, and the attribution now reads the parent's extra too (flat or nested), so known income no longer lands in the unattributed remainder. Test "a split dividend is attributed to the security its parent names" (before: Expected 20, Actual 0).

Part of #4078 (part 3, returns engine)

Part of #3494

Replaces #4218 (same changes, rebased and native-stacked; its review history stays there).

What: attributes a portfolio's income to the securities that paid it. DailyReturns#income_by_security runs one grouped query over the same entries, classifier, FX and cut-offs as the daily rows. The new Portfolio::IncomeBySecurity sorts the rows largest first and reports what it could not attribute as unattributed = total - attributed, so the table always adds up. Income#to_h carries the amounts as by_security.
Why: providers record the paying security in different places (a Trade column, or two keys in a Transaction's extra), and some dividends name none, so a per-security table either says what it could not attribute or it does not add up.
Start reading: #income_by_security and income_by_security_query in app/models/portfolio/daily_returns.rb, then app/models/portfolio/income_by_security.rb.
Key tests (test/models/portfolio/income_by_security_test.rb, performance_test.rb):

  • "every shape that records a security is attributed to it"
  • "attributed and unattributed income partition the daily rows' total"
  • "a reversal with no security makes the unattributed remainder negative, and the table still adds up"
  • "a foreign currency dividend is converted exactly as the daily rows convert it"
  • "an income entry cached before by_security existed is not served"

Behaviour change: none for users; model only. The performance cache version moves to v11. No migration.

Stack: 8 of 11 in the portfolio returns stack, on #5093. GitHub shows only this slice's diff. Next: #5285 (returns engine deferrals). Merge order: #5129 → #5088 → #5089 → #5090 → #5091 → #5092 → #5093 → #5094 → #5285 → #5296 → #5297.
Size: +195 / −54 outside tests, across 4 files.
Fork pre-flight: jaysbeekay/sure#713 (same commits, against a mirror of upstream main). Earlier evidence: jaysbeekay/sure#454.

Full description and evidence

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, plus the commission change in the slice below. 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.

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 (since 14b956621; 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 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, 65 lines).
    • Rows are sorted largest first, then by ticker.
    • An id that matches no security joins unattributed, and unattributed = total - attributed. So the table always adds up to the income total, and a reversal with no security can make the remainder negative.
    • amount_for takes a Security or its id.
  • app/models/portfolio/income.rb. #to_h carries the raw { security_id => amount } as by_security, as plain values, so they survive the cache. The query runs only when income is asked for.
  • app/models/portfolio/performance.rb. CACHE_VERSION goes from v9 to v10 (the slice below already carries v9), so an income entry cached before by_security existed 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 #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 #4217 at b786df777, which includes #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 #4217 at 52031186f; 4d6909c07 then adds "income by security refuses a liability account too": income_by_security runs its own query, so #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 github on the changed files reports no offenses, and bin/brakeman --no-pager -q reports 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 through bind_and_splice, and moving the check into raw_rows fails it.

Mutations. Each was run on the fork pre-flight, then restored. All were caught:

MutationTests that catch it
Trade security ignored9
flat extra key ignored2
nested key ignored1
attribution at the payment date's rate1
unconvertible income kept1
fees counted as income1
unattributed forced to zero3
rows not sorted1
by_security dropped from the cached hash2
the cut-off ignored1
any? ignoring the unattributed remainder1

Re-run on this branch:

  • CACHE_VERSION kept at the slice below's version (v9; v8 before the rebase): 1 failure;
  • amount_for without the id extraction: 1;
  • unattributed forced to zero: 5;
  • by_security dropped 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.

Summary by CodeRabbit

  • New Features
    • Portfolio income now includes dividend and interest amounts attributed to individual securities for the selected period.
    • Income with missing or unrecognized security IDs is reported as unattributed; this amount may be negative when reversals cannot be matched.
    • Attribution supports security-bearing trades, provider-supplied security metadata, currency conversion, and applicable date ranges.
  • Bug Fixes
    • Fees, split-parent transactions, future-dated entries, and entries without required currency conversion rates are excluded from security-attributed income.
    • Security attribution is unavailable for periods that include liability accounts.