Portfolio foundations: consolidated holdings, value series, flow classifier, income and fee totals, security taxonomy schema (#119)
Summary
Delivers #119 (IP0 — portfolio foundations) as one PR of separable commits, in the order the
readiness review set: schema (0.6) → holdings roll-up (0.1) → value series (0.2) → flow
classifier with its contract and coverage gate (0.3) → income and fee totals (0.4). 0.5 needs no
code and is closed on the issue (see "0.5 period keys" below): of the issue's three keys,
last_5_years exists under that name, and wtd and today exist as current_week (WTD) and
last_day (1D). No today or wtd key is added.
One visible change, no new page. The three readers of top_holdings (dashboard investment
summary, Reports investment performance, report print) now show one row per security across
accounts (P1), a weight that is the security's share of the whole portfolio rather than of its
account (P2), and a return consolidated over the holdings with a known cost basis (P28, #135).
Nothing else is user-facing. After this PR, family.investment_statement(user:) answers: one row per
security across accounts with one weight denominator; a value / holdings / gains series over any
period; a classification of every entry as external / income / fee / internal at any scope, in
Ruby and in SQL that provably agree; dividend, interest and fee totals over every storage shape
providers write; and securities can hold asset class, sub-class, sector, industry and region.
This PR builds on we-promise/sure#2927 and we-promise/sure#3350, and assumes both are adopted
upstream. Both are open and mergeable today, so the fork cannot wait for them: their five commits
are cherry-picked here with authorship intact (-x trailers carry the upstream SHAs) purely so the
work has something to stand on. When the upstream pull request is prepared those five are dropped
and the rest applies to the merged result — rehearsed and verified, see "Upstream rebase rehearsal"
below.
What is left once they are dropped is not a competing implementation but four corrections to their
work: one weight denominator instead of two (their top_holdings measures against the portfolio
and their allocation against the holdings, so the same security carries two different weights);
a weight that cannot exceed 100 when cash is negative (we-promise/sure#3277) or when a corrupt
holding is negative; fee and income totals that never let trades.price decide the cash; and a
fees figure beside them.
0.5 period keys
Issue #119's 0.5 row asked for today, wtd and last_5_years. Period::PERIODS on base main
(64d81e41) has no key named today or wtd, and this PR adds neither; the row is met by keys
that already exist, as recorded in the closure comment on #119:
| Asked for | Exists as | Label |
|---|---|---|
wtd | current_week | WTD |
last_5_years | last_5_years | 5Y |
today | last_day (yesterday → today) | 1D |
A one-day today period has a single point and cannot drive a series; "today" on the hub is
InvestmentStatement#day_change. Readers (#120, #121) use the existing key names. If a literal
today / wtd key is still wanted, it is a follow-up on #119, not part of this PR.
we-promise/sure#2927 has moved since the cherry-picks. On 2026-09-10 it gained two commits
this branch does not carry as commits:
b8ac8ac7a("Keep portfolio weights within 100 and consistent between views") reaches the same
max(portfolio_value, holdings_total)denominator this branch introduced a day earlier in
d7854a934. The two differ inallocation: upstream lets weights sum to the invested share,
this branch appends a residual cash row so they sum to 100 (D1, P2/P3). A rebase onto the merged
#2927 will conflict intop_holdings,allocationandweight_denominator; resolve to one
denominator and pick oneallocationshape upstream.d2b608d65("Filter negative holdings per row, not after netting") is adopted here as
be93312bd:holdings_rolled_up_by_securityfilters positive rows before summing and carries
them into the trend. Before that commit this branch summed first, the pre-image ofd2b608d,
so a negative row in one account netted against the same security in another (P27).
Scope and dependencies
- Issue: jaysbeekay/sure#119 (part of jaysbeekay/sure#118). Unblocks jaysbeekay/sure#120, #121,
#122, #123, #128. - Upstream: builds on we-promise/sure#2927 and we-promise/sure#3350; corrects
we-promise/sure#3277 (weight above 100 with negative cash) and we-promise/sure#2291 (the
duplicate-security row we-promise/sure#2927 fixes). - Parent PR/branch, if stacked: none; branched from fork
mainatea8627183. jaysbeekay/sure#134
(the portfolio hub) is stacked on this branch. - Intentionally out of scope: any UI or API change (no endpoint, jbuilder or OpenAPI change — the
API check is not needed;app/views/api/v1/securities/_security.json.jbuilderlists its fields
explicitly); indexes on the newsecuritiescolumns (Drop 3 adds them when a query needs
them); populating the classification columns; the Plaid zero-amount dividend fix (#123); FX
rate warnings on series (#121); a JSON golden-master file (S1 is evidenced by reader tests over
the three render paths instead); comments on the upstream PR threads (X4, not blocking — see
follow-up).
Decisions adopted (D1–D8 from the readiness review, recommended assumption in each row)
| Decision | Where | |
|---|---|---|
| D1 | Both top_holdings and allocation divide by max(portfolio_value, holdings_total); allocation appends a residual cash row so weights sum to 100. Also closes the we-promise/sure#3277 case (negative cash → 104 %). | P2, P3 |
| D2 | Series use the historical scope (disabled accounts kept, cut off the day before disabled_at); the divergence from live portfolio_value is documented and tested. | P5–P8 |
| D3 | scope_account_ids: is required; a transfer is internal iff its counterpart account is in scope; a security transfer needs an opposite-quantity Transfer trade in scope. | P9, P15, P16 |
| D4 | Fees = Fee-labelled entries + transfer fee legs + trades.fee, reported beside contributions and withdrawals, never subtracted from them. Amended twice. The readiness review proposed contributions net of the fee; the provider audit showed writers disagree on whether the amount already contains it, and inferring the fee from qty × price was reproduced as wrong three ways (P22). Contributions and withdrawals are the cash the trade entry records (P21), and trades only (P29). | P21–P23, P29 |
| D5 | Reinvestment is internal; income only when a separate Dividend entry exists. | P12 |
| D6 | Unlabelled standard transactions are external by sign. | P17 |
| D7 | region is a stored column (added here, populated in Drop 3). | migration |
| D8 | Exchange is internal for flow purposes at both scopes. | P13 |
Evidence checklist
- Each issue in this PR has its own acceptance criteria and no unrelated issue work is included.
- Contract rows touched by this change name existing tests —
docs/portfolio/methodology.md
P1–P29, bound byconfig/portfolio_contract_tests.yml, verified by
portfolio:verify_contract_coverage(new CI step beside the loans gate) and by
test/tasks/portfolio_task_test.rbsobin/rails testfails on its own. - Any gate test has an observed failing mutation transcript attached (below).
- Fixtures used as evidence assert internal consistency (reader tests assert the two underlying
holdings and the 6 450 combined value before rendering; series tests compute the expected
cut-off table independently of the code). - Financial calculations use
BigDecimaland documented rounding points (weights.round(2)
in family currency; totals are SQL numerics converted at each entry's date). - De-identification uses token-shape allowlists; no personal data is included.
- Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.
Exit criteria (the assertions that fail without the change)
| Assertion | Test | |
|---|---|---|
| E-a | Two accounts holding AAPL → one row with the summed value; weights sum to 100 ± 0.01; holdings 1 000 with cash −40 → weight 100 | InvestmentStatementTest "top_holdings rolls up the same security across accounts", "weights never exceed 100 when cash is negative" |
| E-b | value_series = Σ per-account series on every date, disabled account cut off | "value_series sums the per-account balance series on every date of the period", "a disabled account stops contributing to value_series after its cut-off date" |
| E-c | Three dividend shapes → :income; transfer legs external at account scope / internal at family scope; Buy → :internal | Portfolio::FlowClassifierTest P10, P9, P12 rows |
| E-d | Ruby and SQL agree on every corpus entry at three scopes | "the SQL form agrees with the Ruby form on every corpus entry at both scopes" |
| E-e | Dividends, interest and fees non-zero; buy 10 × 100 fee 5 → contributions are the entry's cash (1 005 from the manual form, 1 000 from a fee-excluded writer), fees 5 each | "contributions and withdrawals are the cash the trade entry records", "fees sum Fee-labelled entries and transfer fee legs alongside trades.fee" |
| E-g | Only trades move contributions and withdrawals: a Contribution / Withdrawal-labelled transaction, an unlabelled investment_contribution and a linked transfer's inflow leg leave them at the buy and the sale | "contributions and withdrawals count trades only, not external cash transactions" |
| E-f | Coverage gate passes and aborts on a renamed test | Portfolio::ContractCoverageTest, manifest rename transcript below |
Mutation transcripts ("break the fix, watch the test fail")
Each mutation was applied to production code, the named tests run, and the file restored.
| Mutation | Tests that went red |
|---|---|
Weight denominator: [portfolio_value, holdings_total].max → portfolio_value | "weights never exceed 100 when cash is negative", "top_holdings and allocation report the same weight for a security", "allocation omits the cash row when account balances are a stale zero" (3 failures / 4 runs) |
Roll-up: top_holdings stubbed to return one row per account | dashboard, Reports index and print reader tests (Expected: 1, Actual: 2) |
HistoricalScope#active_until_dates → {} | "active_until_dates covers only disabled accounts…", "a disabled account stops contributing to value_series after its cut-off date", "value_series sums the per-account balance series on every date of the period" |
| Classifier: transfer resolution ignores scope | "a linked transfer is internal at family scope and external at account scope", "an investment contribution from outside the scope is an external inflow", parity |
Classifier: "Dividend" => :income → nil | three dividend tests, "every activity label has a rule", SQL-literals test (5 failures) |
| Classifier: SQL fee-leg branch removed, Ruby kept | parity only — the two forms diverged and the parity test caught it |
Totals: contributions stop subtracting trades.fee (historical: that rule was replaced by P21/P22 and its test by "contributions and withdrawals are the cash the trade entry records") | "contributions exclude a fee the entry amount already includes", "fees sum Fee-labelled entries…" |
| Totals: label read from trades only | "dividends and interest count the transaction shapes providers write", "fees sum Fee-labelled entries…" |
| Coverage gate: one manifest test renamed | P19: missing test "every activity label has a rule (renamed)" in test/models/portfolio/flow_classifier_test.rb (task aborts) |
| Coverage gate: a test name in the document that exists nowhere | before round 3: task reported "Verified 28 rows"; after: aborts naming the row and the citation |
Totals: restore the qty * price comparison for sells | "a stale, zero or foreign-currency price cannot move contributions or withdrawals" |
Roll-up: next if value.zero? instead of next unless value.positive? | "a holding with a negative value cannot push another security's weight over 100" (["GOOD"] vs ["GOOD", "BAD"]) |
Roll-up (be93312bd): sum the security's rows, then drop a non-positive total | "a negative row does not net against the same security held in another account" (amount 500 vs 1 000; 1 failure / 56 runs) |
Roll-up (be93312bd): per-row value, but the unfiltered rows passed to the trend | same test, trend assertion (1 failure / 56 runs) |
Classifier: ::boolean cast back on the pending flag | "a pending flag that is not a boolean is read the same way by both forms" |
Totals (c11907173, P29): scan every transaction and add non-trade cash to the direction buckets (trades.qty > 0 OR (trades.id IS NULL AND entries.amount < 0)) | "contributions and withdrawals count trades only, not external cash transactions" — "only the buy is a contribution" (1 failure / 2 runs) |
Totals (c11907173, P29): classifier-style — scan every transaction, count only non-trade cash, ignore trades | same test, "only the buy is a contribution"; also "contributions and withdrawals are the cash the trade entry records" (2 failures / 2 runs) |
Validation
Commands and results:
| Command | Result |
|---|---|
bin/rails test | 8783 runs, 36460 assertions, 0 failures, 0 errors, 30 skips (pre-existing skips) |
bin/rails test after the per-row roll-up fix and the merge of main (0b470fb5) | 8805 runs, 36641 assertions, 0 failures, 1 error (environmental: RecurringTransaction::PipelineTest opens its own PG.connect over ::1, which fails password auth on this machine on every branch), 30 skips |
bin/rails portfolio:verify_contract_coverage | Verified 29 portfolio contract rows against existing tests (at c11907173) |
Portfolio, statement, flow-statement and contract tests at c11907173 | 94 runs, 464 assertions, 0 failures, 0 errors |
bin/rails test at c11907173 | 8806 runs, 36648 assertions, 0 failures, 1 error (environmental: RecurringTransaction::PipelineTest opens its own PG.connect, which fails password auth on this machine on every branch), 30 skips; private Postgres/Redis, env -u ANTHROPIC_BASE_URL |
bin/rails loans:verify_contract_coverage | unchanged, still passes in the same job |
bin/rubocop -f github | no offenses |
Fork CI security-scan (Pipelock) | first run flagged the constant name CLASS_TOKEN as an "environment variable secret"; it is a regex for test class names, renamed to TEST_CLASS_PATTERN in the last commit |
bin/brakeman --no-pager | 0 security warnings |
RAILS_ENV=test bin/rails db:migrate → db:rollback → db:migrate | migrated (0.03 s) / reverted (columns and constraints gone) / migrated |
erb_lint, npm run lint | not applicable: no ERB or JS changed |
| System tests | not run: no view or JS change; the three reader paths are covered by integration tests |
Query-count evidence (S6): an integration probe issuing GET / and GET /reports as family_admin
and counting SQL statements, run against this branch and again with fork main's app/, lib/
and locales checked out over it (same test database):
| Page | fork main | this branch |
|---|---|---|
ReportsController#index | 85 | 85 |
PagesController#dashboard (page shell; sections load lazily) | 1 | 1 |
Zero added queries. Totals is still one aggregation; current_holdings is still one
DISTINCT ON; the series methods are not called by either page.
Runtime of the new tests: test/models/portfolio/flow_classifier_test.rb 21 runs in ~3 s;
test/models/investment_statement_test.rb 47 runs in ~4 s.
Upstream rebase rehearsal
Rehearsed twice in scratch worktrees, against both futures.
If the two upstream PRs are adopted first (the assumption above). A tree was built from
we-promise/sure main plus we-promise/sure#2927 plus we-promise/sure#3350 — both cherry-pick onto
current upstream cleanly — and this branch replayed onto it with its five adopted commits dropped:
| Commits to drop | 9fcd57b0a ← 66736a2f3, 33b3a29c9 ← 7c1d48ea9, f49078885 ← 0bc73e4c2 (we-promise/sure#2927); 4a6f071cb ← 6cc721b0c, 95a2108f2 ← 34861b789 (we-promise/sure#3350) |
| Result | 17 commits, 22 files, 2,774 insertions |
| Conflicts | three, all fork-versus-upstream drift outside this change (see below). None in investment_statement.rb or totals.rb — every amendment applied to the merged upstream versions untouched. Rehearsed against #2927 before its 2026-09-10 commits; with b8ac8ac7a on it, expect conflicts in investment_statement.rb as described in the summary. |
| Composition | checked for the failure that matters: holdings_rolled_up_by_security, combined_holding_trend, weight_denominator, top_holdings, allocation and the totals columns each appear exactly once, and the corrected arithmetic is the one that survives |
Note that git rebase will not drop those five for you. A cherry-pick onto the fork produces a
different patch identity from the original onto upstream, so git replays them and they conflict with
themselves. Drop them explicitly (git rebase --onto <adopted-upstream> 95a2108f2).
If they are not adopted first. The branch replays onto we-promise/sure main as it stands
today: 21 commits, same three conflicts.
The three conflicts, in both cases, each resolved mechanically: db/schema.rb (the fork's loan
tables and schema version; take upstream's file plus this PR's securities hunk),
test/controllers/pages_controller_test.rb (neighbouring fork-only spending-trend tests; keep both
sides and close the shared end), .github/workflows/ci.yml (the fork's loans gate step; the
portfolio step goes after "DB setup and smoke test").
One file this PR touches diverges between fork and upstream:
app/models/account/provider_import_adapter.rb, where the fork removed a cc_payment branch at
line ~224 while this PR edits the collision handler at line ~575. They do not overlap.
Migration notes (0.6)
- Additive: seven nullable string columns and one boolean with a constant default (catalog-only on
PostgreSQL 11+, no row rewrite). Check constraints are addedNOT VALIDand then validated under
disable_ddl_transaction!, so the table is never scanned under an exclusive lock. - Explicit
up/downbecausevalidate_check_constrainthas no inverse. Rehearsed locally:
db:migrate→db:rollback(columns and constraints gone, verified in a console) →db:migrate. db/schema.rbnormalised to the committed constraint dump style ('x'::character varying::text).- Rollback plan: revert the PR. The columns may stay (unused, nullable). The totals cache key bump
means a revert also serves fresh totals under the oldv2key.
Cache
totals_query/v2 → totals_query/v4 over the review rounds: the aggregation gains fees, reads
income by label over trades and transactions, and uses the classifier's pending rule (P26). First
read after deploy is a miss. P29 changes no SQL, so the key is not bumped for it.
Series are cached under family.build_cache_key(..., invalidate_on_data_updates: true) like the
net worth series.
Blast radius
top_holdingsrows are duck-typedHoldingAllocation; the four readers (Reports controller,
Reports partial, print, dashboard summary) call.ticker .name .security .weight .amount_money .trendand are covered by the reader tests.allocationhas no reader inapp/today; its
cash row hassecurity: nilandcash?.PeriodTotals#contributions/#withdrawalskeep upstream's trades-only meaning (P29). Their
readers are the Reports investment card (period_contributions,period_withdrawals) and
InvestmentStatement#net_contributions; the Reports flows card readsInvestmentFlowStatement,
and #120's hub reads neither.PeriodTotalsgainsfees(additive).InvestmentStatement#totalsremains one query; it now
LEFT JOINs trades and transactions and narrows transactions to income / fee shapes in the WHERE.Balance::ChartSeriesBuilder,BalanceSheet::HistoricalAccountScope,Securityreaders, and
the API are unchanged in behaviour.Portfolio::FlowClassifieris new; its only in-app reader isTotals(label sets).
Risks, blockers, and follow-up
- Provider fee shapes are read from code, not from live payloads (methodology "Provider
audit"). Trading212's fee-inclusive order amounts plus separateFEErows could double count if
a per-order fee row ever appears; recorded as a known limitation. - Plaid dividends have amount 0 by construction in the processor; they classify as income and
contribute zero to totals until #123 fixes the amount. - Upstream delivery of the adopted commits. we-promise/sure#2927 and #3350 are still open
upstream. Merging this PR into forkmainmeans the fork carries the denominator and totals
logic until they merge; it is not shipped upstream by this PR. When theup/*branch for this
drop is cut (one-branch delivery flow, #141), the five cherry-picks listed under "Upstream rebase
rehearsal" are dropped explicitly (git rebase --onto), the three mechanical conflicts are
resolved as described there, andinvestment_statement.rbis reconciled against #2927's
b8ac8ac7a(one denominator, oneallocationshape). If either upstream PR closes unmerged, its
adopted commits become part of this drop's upstream PR instead of being dropped. - Stacked #134 must be re-merged onto this branch and its suite rerun after every change here,
and again after this PR merges, so the hub's readers still see one denominator. - Upstream engagement (X4): the D1 amendment and the negative-cash test are a concrete proposal
for the we-promise/sure#2927 thread, and the fee arithmetic for #3350's. Not posted from this
PR; the owner may want to do that in their own words. - Next unblocked issues: #120 (hub page:
value_series, rolled-up holdings), #121 (returns:
FlowClassifier#sql_case, historical scope), #122 (classification columns), #123 (income
totals), #128 (external inflows per account).
- Added portfolio foundations for consolidated holdings, portfolio-level weights, residual cash, returns, historical series, and account-aware caching.
- Added Ruby/SQL flow classification with parity checks and CI contract coverage.
- Added dividend, interest, fee, contribution, and withdrawal totals.
- Added security taxonomy fields, validations, constraints, migrations, and tests.
- Added methodology documentation and dashboard/report integration coverage.
- Improved holding-import collision handling to refresh cache timestamps.
| Author | Lines added | Lines removed |
|---|---|---|
| jaysbeekay | Unavailable | Unavailable |