Version the gains series key on holdings, and pin two roll-up decisions (#133 review round 2)

Merged
JA
3mo ago
+211-11

Summary

Second review round on #133 (issue #119), stacked on feat/portfolio-foundations. Every open finding on #133 was checked against the code; the verdict table is posted as a comment there. This PR carries the fixes for the findings that held up:

  • Stale gains_series cache after a manual cost-basis edit (valid). HoldingsController#update → Holding#set_manual_cost_basis! writes the holding alone; Family#build_cache_key reads only latest_sync_completed_at and accounts.maximum(:updated_at), neither of which moves, so the cached gains survived the edit. The gains key now carries a holdings version (count-max(updated_at) over the historical-scope accounts), which also covers unlock, remap and deletion. The value series read balances only, which a sync rewrites, so they keep the cheaper key.
  • Holding collision handler skipped updated_at (cubic, on this PR; valid). Account::ProviderImportAdapter#import_holding's composite-key rescue rewrites qty, price, amount and cost basis with update_columns, which leaves the timestamp alone; if that sync then failed, neither part of the gains key moved. The rescue now stamps updated_at in the same write. The other direct holding writes were checked: Holding::Materializer sets updated_at in its upsert_all payload, and the unlink paths only null account_provider_id.
  • Two roll-up decisions outside the contract (valid): a security whose holdings carry no value is omitted rather than listed at weight 0 (new row P27), and a rolled-up return covers only the holdings with a known cost basis while the amount counts every holding (new row P28). Both now have tests bound by the manifest; the gate verifies 28 rows.
  • Memoization (Codacy): shares_version and holdings_rolled_up_by_security are memoized per instance.
  • allocation N+1 (Codacy / "Jedi" M4): no preload applies (Holding#trades is a method, not an association); the stored-cost-basis path issues no trade queries, now pinned by a query-count test.

Scope and dependencies

  • Issue: #119, via #133
  • Parent PR/branch, if stacked: #133 (feat/portfolio-foundations)
  • Intentionally out of scope: Plaid zero-amount dividends (#123); Balance::ChartSeriesBuilder's b.currency = accounts.currency filter and current_holdings' per-(account, security) selection, both upstream code shared with the net worth chart; taxonomy parent/child mapping (#122); a migrate-from-base CI job; renaming HoldingAllocation#weight (would change the three views kept byte-identical to upstream).

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 (P27, P28 in docs/portfolio/methodology.md and config/portfolio_contract_tests.yml).
  • Any gate test has an observed failing mutation transcript attached (below).
  • Fixtures used as evidence assert internal consistency (the P28 test asserts the row's amount over both holdings before asserting the trend over one).
  • Financial calculations use BigDecimal and documented rounding points (unchanged).
  • De-identification uses token-shape allowlists; no personal data is included.
  • Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.

Mutation transcripts

MutationTests that went red
(holdings_version if kind == :gains) → nil"gains series cache key changes when a holding's cost basis is edited by hand", "… when a holding is deleted" (2 failures / 2 runs)
next if value.zero? removed"a security whose holdings carry no value is omitted from top_holdings and allocation"
next unless trend replaced by a flat trend for holdings without a cost basis"a rolled-up return is measured over the holdings whose cost basis is known"
updates[:updated_at] = Time.current removed from the collision handler"a composite-key collision stamps updated_at on the row it adopts" (1 failure / 1 run)

Validation

Commands and results (run on Ruby 3.3.6 in the session container, since the 3.4.9 tarball host is denied by the egress policy; CI runs 3.4.9):

CommandResult
bin/rails test test/models/investment_statement_test.rb test/models/investment_statement/historical_scope_test.rb test/lib/portfolio/contract_coverage_test.rb test/tasks/portfolio_task_test.rb69 runs, 203 assertions, 0 failures
bin/rails test test/models/account/provider_import_adapter_test.rb test/models/investment_statement_test.rb test/tasks/portfolio_task_test.rb (second commit)110 runs, 385 assertions, 0 failures
bin/rails test test/controllers/pages_controller_test.rb test/controllers/reports_controller_test.rb63 runs, 224 assertions, 0 failures
bin/rails test test/models/portfolio/flow_classifier_test.rb test/models/security_test.rb0 failures
bin/rails portfolio:verify_contract_coverageVerified 28 portfolio contract rows against existing tests
bin/rubocop -f github on changed filesno offenses
bin/brakeman --no-pagerNo warnings found
Fork CI on bf75f99all seven checks green

Risks, blockers, and follow-up

  • The gains key adds two holdings queries per InvestmentStatement instance that asks for a gains series (none today; #120 is the first reader).
  • The verdict comment on #133 lists the findings left unchanged and why; the owner's call on Blocker 2 (allocation kept until #120 wires it) stands as documented in P3.

šŸ¤– Generated with Claude Code

https://claude.ai/code/session_01JqGVXNrELAK5ah6VWymaNK

  • Invalidate gains-series caches after holding changes, including edits, deletions, remaps, unlocks, and collision updates.
  • Preserve value-series cache keys for sync-related data.
  • Memoize portfolio calculations.
  • Add contract coverage for zero-value securities and cost-basis-aware returns.
  • Verify that allocation does not issue per-holding trade queries when cost basis is stored.
  • Extend contract verification to 28 rows.
  • Add a regression test for collision-adopted holdings and updated_at changes.
AuthorLines addedLines removed
Not availableNot availableNot available