Add a per-user retirement plan with the simple FIRE figures

JA
7d ago
+964-8

Base: main | Head: up/retirement-plan-model | Draft

Part of #5567

Fork pre-flight: jaysbeekay/sure#364 (same commits, head 83148edb1)

First of four stacked PRs for the retirement / FIRE planner (#5567). Model only: no route, controller or view.

Problem

Sure has a user's monthly spending and account balances, but nothing turns them into an FI number, progress towards it, or a projection to a retirement date.

Resulting behaviour

A user gets a RetirementPlan and the simple FIRE figures: an FI number (annual spending divided by the safe withdrawal rate), progress towards it and a derived savings rate.

The design choice to know about: the plan is per user, not per family. Every figure is built from the accounts that user counts in their own finances (Account.visible.included_in_reports.included_in_finances_for(user), the scope InvestmentStatement#investment_accounts uses).

  • IncomeStatement#median_expense gains excluding_kinds: (default []) and period: (default: all history). It is passed to IncomeStatement::FamilyStats as a bound SQL parameter and carried, with the period, in both the per-instance memo and the cache key, after the existing *cache_freshness_key. With the default, the SQL, memo key and cache key are exactly what main builds today. The category path (median_expense(category:)) raises ArgumentError if it is given excluding_kinds:, rather than ignoring it.
  • retirement_plans table: one row per user (unique user_id, cascade on user delete). It holds the safe withdrawal rate, expected annual return, an optional savings rate and an optional retirement date, with check constraints that mirror the validations.
  • RetirementPlan.for(user) returns the saved plan, or an unsaved one with the column defaults; it never writes. It also has *_percent readers and writers, which refuse input that is not a number rather than reading it as zero, plus #projection(as_of:) and #unconverted_account_count(as_of:).
  • RetirementPlan::Projection is pure arithmetic over the FI number, progress and the savings rate; the year-by-year plan is #5610's simulation. The reference date is an argument, and it reads neither the clock, the database nor Current. Every figure is a BigDecimal, including clamped and guarded zeros.
  • The FI number is built from living costs: the median month over the 12 whole months before the reference month, without investment_contribution or loan_payment, whatever the family's investment_contributions_as_spending setting. Money moved into investments is saving, and a loan payment ends when the loan does, so neither is spending to fund in retirement. #5610 seeds the plan's living-costs stream from the same method, so one figure drives both. The derived savings rate still uses the all-history median with loan payments in, because until a loan is paid off that money isn't being saved. Assets are each Depository, Investment and Crypto account's latest balance on or before the reference date, in the account's currency, converted at that date's rate. An account with no rate is left out and counted.
  • User has_one :retirement_plan, dependent: :destroy.

as_of sets the date of the balances and the planning years. The income median and the savings rate's spending median come from IncomeStatement over history up to today, so a past as_of is not a historical forecast. The planner is meant to run for today.

Size: 319 non-test lines (311 added, 8 removed), not counting db/schema.rb (15 lines).

Validation

  • Full suite bin/rails test at 83148edb1: 18499 runs, 0 failures; at the top of the stack (f4b1dbb2e): 18698 runs, 0 failures. The 8 errors are ReleaseNotesWorkflowTest, which needs node, missing from the test image.
  • CI at this head: lint (bin/rubocop), Brakeman, and the unit and system test jobs pass.
  • The engine is run on two different days under travel_to, inside assert_queries_count(0) and with Current.user and Current.family expected never. Both runs must give the same figures.
  • Each behaviour was broken on purpose, one at a time. Each mutation was caught by a failing assertion:
MutationCaught by
excluding_kinds SQL clause removeda kind left out of the median expense is not counted...; the excluded and default medians are cached under different keys
cache key loses the excluded kindsthe excluded and default medians are cached under different keys
cache key loses the freshness segmentsa cached median follows the family's investing-as-spending setting
memo keyed by interval onlya kind left out of the median expense is not counted, and the default still counts it
contributions counted as spendingmoney moved into investments is saving, not spending
Crypto dropped from liquid typescash, investments and crypto count as liquid and investment assets
balance date not bounded by the reference dateeach account counts at its latest balance on or before the reference date
currency filter on balances removedonly the balance in the account's own currency counts
finance scope widened to the whole familyassets count only the accounts the viewer counts in their finances (and 5 more)
FX at today's rate instead of the reference date'sa balance in another currency is converted at the reference date's rate
non-numeric percent read with to_da percent that is not a number is refused rather than read as zero
FI number guard on zero spending removedwith no expenses there is no FI number to measure against
derived savings rate not clampeda derived savings rate never goes negative when spending exceeds income
clamp to Integer boundsa zero or clamped rate and amount are still BigDecimal
FI number built from all-history spending with loan paymentsthe FI number leaves out loan payments, which the savings rate still counts
living-costs window end moved into the reference monththe FI number reads the 12 whole months before the reference month
bar progress not clampedthe bar stops at 100% while the figure beside it does not

One mutation survives, by design. Removing dependent: :destroy leaves "deleting the user deletes their plan" passing, because the foreign key's on_delete: :cascade deletes it as well.

Blast radius

IncomeStatement#median_expense is called by Budget (twice), Goal#median_monthly_expense, Insight::Generators::CashFlowWarningGenerator and Assistant::Function::GetIncomeStatement. None of them passes excluding_kinds:. family_stats is also read by avg_expense and median_income, which pass only interval: and are deliberately unchanged. IncomeStatement::FamilyStats.new has one caller, IncomeStatement#family_stats. category_stats is deliberately unchanged.

Migration notes

20261008150100_create_user_retirement_plans (CreateUserRetirementPlans) creates retirement_plans. No existing table or row changes, and there is nothing to run after deploy. The timestamp is older than main's newest migration. Rails runs it by version, and schema.rb's define(version:) stays at main's newest.

Screenshots

None: this PR has no UI.


Summary by cubic

Adds a per-user retirement plan model that computes simple FIRE figures: an FI number, progress, and savings rate, built from the user's own account balances and income/expense medians. This is the first of four stacked PRs for the retirement planner (#5567).

  • The plan is per user, not per family: figures are built only from accounts the user counts in their own finances.
  • The FI number reads the median of the 12 whole months before the reference month, excluding investment contributions and loan payments; the derived savings rate uses the all-history median with loan payments included.
  • Assets are converted to the family currency before the spending and income medians are read, because converting can fetch and store a missing exchange rate that those medians rely on.
  • RetirementPlan::Projection is pure arithmetic that reads neither the clock, the database, nor Current.
  • IncomeStatement#median_expense gains excluding_kinds: and period: parameters (both default off) that leave existing callers unchanged. The memo and cache key carry the kinds and period, so excluded, bounded, and default figures never share an entry.
  • A new retirement_plans table stores the user's safe withdrawal rate, expected return, savings rate, and optional retirement date. RetirementPlan.for(user) reads the saved plan or an unsaved one with defaults, never writes. The expected return and retirement date are stored for later PRs; the projection itself doesn't read them.
  • The migration is a plain reversible create_table; a migration test verifies that down restores the schema exactly, drops only this table, and that up over an existing table fails loudly instead of adopting it. No manual steps after deploy.

Summary by CodeRabbit

  • New Features
    • Added retirement planning estimates with configurable safe withdrawal rate, expected return, savings rate, and retirement date.
    • Calculate financial independence targets and progress using eligible account balances and financial activity.
    • Filter family-level median expenses by spending type and date range.
  • Bug Fixes
    • Expense calculations now remain distinct when exclusion settings or date ranges differ, ensuring cached results reflect the selected options.