Plan retirement year by year, to an end age, with inflation

JA
7d ago
+1900-19

Base: up/retirement-plan-model (stacked) | Head: up/retirement-plan-projection | Draft

Part of #5567
Closes #5643

Fork pre-flight: jaysbeekay/sure#365 (same commits, head 015394db0)

Stacked on #5609

Changed after approval (2026-11-29), re-review needed. @dgilperez found on #5567 that indexed streams were indexed by calendar year while the contribution grows from the reference date, so a line entered on 31 December gained a year's inflation. A stream now stores the date its amount is valued on (valued_on, replacing the integer base_year in the same unmerged migration), grows from that date to the reference date, and from there as the contribution does. The plan carries each stream to the reference date once (Simulation.value_streams_on), so the solver and Monte Carlo don't redo it per simulation.

Second of four. Model only: no route, controller or view.

Problem

The simple figures from #PREV assume one return and one contribution up to a date. Real plans have spending that changes, a pension that starts at a given age, loans that end, inflation, and a question the first slice cannot answer: when is the earliest year the money lasts to the end?

Resulting behaviour

A plan can be run year by year to an end age. It takes inflation, spending and income streams, and a choice of funding accounts, in two modes: traditional (retire on the plan's date) and FIRE (find the earliest year the money lasts).

The design choice to know about: the FIRE solver scans every year rather than bisecting. With dated income and spending, lasting from one year does not guarantee lasting from a later one, and a test pins a case where it doesn't.

  • Migration: birth_year, end_age (default 90), inflation_rate (default 3%), mode (default traditional) and streams_seeded_on on retirement_plans, with check constraints. New tables retirement_plan_streams (kind, name, annual amount, start and end year, indexed, source, optional account) and retirement_plan_accounts (unique per plan and account).
  • RetirementPlan::Simulation (pure) gives one row per calendar year: V(n + 1) = (V(n) - W(n)) * (1 + r) + C(n). The first year counts only the part of it left from the reference date: growth compounds over that fraction, and the contribution and recurring streams are that fraction of a year's (a one-off is paid whole). Before retirement, manual expense and income streams move the contribution, a shortfall is withdrawn, and one-offs come out; seeded streams stay out, since the contribution already pays today's living costs and loans. From the retirement year, W is spending less income, never below zero, and any surplus income is reinvested. The contribution, which is today's money, grows with inflation from the reference date to the start of each year, and each indexed stream from its valued_on date, the day its amount was entered or last changed, to the reference date and then as the contribution does; each row carries a value in today's money. The depletion year is the first year a withdrawal cannot be met.
  • RetirementPlan::Solver (pure) finds the earliest year whose simulation lasts, or none, with the depletion age at the latest start.
  • RetirementPlan::Stream and RetirementPlan::FundingAccount. A funding link must be to a cash, investment or crypto account that the user counts in their finances. When a stream's account changes, it must be one the user counts. If none of the linked accounts is still eligible (hidden, excluded from reports or no longer shared), the default set funds the plan, as it would with no links at all.
  • RetirementPlan#simulation(as_of:, retirement_year:) and #solve(as_of:) return nil when the plan has nothing to run. That is when the owner is born after the reference year, the end age has passed, or (for #simulation) retirement falls after the end-age year.
  • #seed_streams!(as_of:) seeds once per plan, under a row lock. Living costs come from RetirementPlan#annual_living_costs (#5609), the figure the FI number is built from: the median of the months with spending in the last 12 whole months, leaving out contributions and loan payments; a month with no spending is left out of the median, not counted as zero. Each loan gets one unindexed stream at its current repayment (amortization_schedule.payment_in_force(as_of)), in the loan's own currency, ending the year its payoff projection clears it. A loan with no payoff date (its repayment no longer clears it) seeds its repayment until the contract's maturity. Each stream stores the currency it was entered in (the family's when created), and the simulation converts it into the family's current currency at the reference date. A stream with no rate is left out of the simulation and counted by #unconverted_stream_count(as_of:), as #unconverted_account_count counts accounts; the page should warn when it is above zero. A foreign-currency loan is seeded in its own currency like any other stream, so a loan with no rate yet is still seeded: it is left out of the simulation and counted until the rate arrives, and then joins the plan at the reference date's rate. Seeding therefore always marks the plan, and a seeded stream the user deletes never comes back. An unsaved plan raises ArgumentError.
  • Locale: retirement_plans.streams.seeded.living_costs.

Why this is one PR at about 500 lines

There are 502 changed non-test lines outside db/schema.rb (499 added, 3 removed), plus 44 in schema.rb. 75 of the 502 are the migration, mostly comments, and about a third of the model lines are comments that state the recurrence and its edge cases.

The simulation, the solver and the plan wiring that feeds them are one idea: what a year-by-year plan is. Split the engine from its inputs and you get a PR whose classes nothing calls, so its tests could only run the engine with made-up inputs. Split the streams from the simulation and you get a simulation that cannot model a pension or a loan, which is the reason it exists. The period: argument it needs now lands in #5609.

Validation

  • After the valued_on change: full suite bin/rails test at this head 015394db0: 18586 runs, 1 failure, 8 errors. The failure is AccountsControllerTest "credit card overview shows the credit label when a credit outlives the due date", which depends on today's date and fails the same way at the old head 158640ad4; the errors are the usual ReleaseNotesWorkflowTest ones. At the top of the stack (7110d042f): 18749 runs, the same failure and errors. New tests: a stream entered on 31 December grows by a day into the next year (failed before with 11,000 for 10,002.61), a stream valued on the reference date grows as the contribution does, a stored stream reads the same on 31 December and 1 January, and streams carried to the reference date up front give the same rows. Each changed line has a mutation that a test catches.
  • Full suite bin/rails test at the top of the stack (f4b1dbb2e, which includes this PR's head 85d0fb684): 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 simulation and solver are run on two different days under travel_to, inside assert_queries_count(0) and with Current expected never. Both runs must give the same rows, outcome and solved year.
  • Mutations, each caught by a failing assertion unless noted:
MutationCaught by
growth taken before the withdrawala withdrawal comes out at the start of the year, before that year's growth
contribution not indexed3% inflation matches a hand-computed table
surplus income withdrawn as a negativea pension is set against spending, and a surplus is reinvested
one-off paid every yeara one-off amount comes out in its year only
end year exclusivea stream with an end year stops after that year
unindexed streams indexedan indexed stream grows with inflation from today; an unindexed one does not
real value deflated one year short3% inflation matches a hand-computed table, nominal and in today's money
exact withdrawal counted as depletiona withdrawal that takes exactly what is left is met
solver skips the reference yeara plan that can already retire gets this year
living costs not limited to 12 monthsliving costs are the median of the months with spending in the last 12 whole months...
median swapped for the meansame test (months of 1,000, 2,000 and 6,000: 24,000 a year, 36,000 with the mean)
living-costs window ends on the reference month's first dayliving costs take in the window's first and last days...
loan payments counted in living costsliving costs are the median of the months with spending...
seeding runs again, or row lock replaced by a plain transactionstreams are seeded once; two copies of a plan loaded before either seeds do not both seed
seeding left open while a foreign loan has no ratestreams are seeded once: a deleted seeded stream does not come back
foreign loan converted at seeding, or its currency droppedloans in different currencies each seed their repayment in their own currency; a foreign loan seeds its repayment in its own currency, and joins the plan once a rate exists
loan repayment not made yearlya loan seeds its repayment...; a foreign loan ... joins the plan (the year's withdrawal rises by payment x 12 x rate)
unsaved plan allowed to seedan unsaved plan refuses to seed and saves nothing
maturity fallback dropped for a loan with no payoff datea loan its contracted repayment no longer clears seeds its repayment until maturity
loan stream indexeda loan seeds its repayment, ending the year it is paid off
funding links ignored, or link to any family accountlinked accounts replace the default set; an account the user does not count in their finances cannot be linked
stream account not checked, or checked on every savea stream's account must be one the user counts...; a stream whose account has left can still be edited
stream end-before-start alloweda stream needs a known kind...
end age floor moved to 49an end age outside 50 to 120 is refused
inflation not a percent attributeinflation is set and shown in percent (raises NoMethodError on the missing writer)

Blast radius

median_expense's other callers (Budget, Goal#median_monthly_expense, CashFlowWarningGenerator, GetIncomeStatement) pass no period:, so their SQL, memo and cache key are what main builds. avg_expense and median_income pass only interval: and are unchanged. Loan::PayoffProjection and Loan::AmortizationSchedule#payment_in_force are read, not changed. The loan overview tab is the other reader of payment_in_force, and it passes its own date. Account gains no association, because the foreign keys are declared on the new tables only.

Migration notes

20261008150200_add_planner_to_retirement_plans (AddPlannerToRetirementPlans) adds five columns to retirement_plans. Each has a default or is nullable, so existing plans keep validating. It also creates retirement_plan_streams and retirement_plan_accounts. A stream's account_id is nullified when its account is deleted, because the user may have edited the stream; funding links cascade. There is nothing to run after deploy.

Screenshots

None: this PR has no UI.


Summary by cubic

Adds a year-by-year retirement projection to an end age, with inflation, dated spending and income streams, and account funding, beside the existing simple figures. Traditional mode retires on the plan's date; FIRE mode solves for the earliest year the money lasts. Closes #5643: each stream records the date its amount is valued in, so a plan reopened a year later no longer drops a year of inflation. Model only: no route, controller or view.

What changed

  • RetirementPlan::Simulation projects one row per calendar year (withdrawal first, contribution last); the first year counts only the part left from the reference date.
  • RetirementPlan::Solver scans every year, because lasting from one year does not guarantee lasting from a later one.
  • The contribution grows with inflation from the reference date; an indexed stream grows from its valued_on date, day for day, so a stream entered on 31 December gains no extra year.
  • Stream amounts are carried to the reference date once per plan, so the solver does not redo fractional inflation per simulation.
  • Manual streams move the contribution before retirement; what they cannot cover comes out of the portfolio. Seeded streams stay out.
  • seed_streams! seeds once: living costs from the last 12 whole months' median spending, plus one unindexed stream per loan in the loan's currency, ending the year the loan is paid off or at maturity.
  • Streams keep the currency they were entered in and are converted at the reference date; a stream with no rate is left out and counted by unconverted_stream_count.
  • Funding links must be cash, investment or crypto accounts the user counts; if none of the linked accounts is still eligible, the default set funds the plan.

Migration

  • Adds birth_year, end_age (90), inflation_rate (3%), mode (traditional) and streams_seeded_on to retirement_plans, plus retirement_plan_streams (with currency and valued_on) and retirement_plan_accounts.
  • New columns have defaults or are nullable, so existing plans keep saving; nothing to run after deploy.

Summary by CodeRabbit

  • New Features
    • Retirement plans now support traditional and FIRE planning modes, with projections that account for income, expenses, contributions, inflation, investment returns, and funding accounts.
    • View projected retirement outcomes, including the earliest year a plan may sustain retirement and when assets may run out.
    • Plans can include recurring and one-time income or expenses, including loan payments, with amounts converted to the plan’s currency.