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

JA
7d ago
+1900-19

Upstream PR: we-promise/sure#5610 (same commits; native stack we-promise/sure#5613).

Part of #127

Upstream pre-flight for the retirement planner's model layer, slice 2 of 4 (year-by-year planner). The upstream PR is NOT YET OPENED (awaiting owner approval); it will be raised from this branch: same branch, same commit.

Stacked on #364 (up/retirement-plan-model): this PR's base is that branch, so the diff here is this slice only. Fork history this ports: #251.


Summary

Part of we-promise/sure#5567. Programme: we-promise/sure#3494.

Fork pre-flight: jaysbeekay/sure#365 (same branch, same commit).

Stacked on we-promise/sure#5609 (up/retirement-plan-model, fork pre-flight jaysbeekay/sure#364) and carries its commits until that merges; review this slice's own commits here (the ones not on up/retirement-plan-model). Second of four (drop 8.2 of jaysbeekay/sure#127).

A plan can now be run year by year to an end age, with 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, because with dated income and spending, lasting from one year does not guarantee lasting from a later one.

What changed

  • IncomeStatement#median_expense gains period: (default nil), bound as SQL parameters and carried in the memo and the cache key; existing callers are unchanged.
  • 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 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): one row per calendar year, V(n + 1) = (V(n) - W(n)) * (1 + r) + C(n). Before retirement W is only one-off amounts; from the retirement year it is spending less income, never below zero, and surplus income is reinvested. Indexed streams and the contribution grow with inflation; each row has a value in today's money. The first year a withdrawal cannot be met is the depletion year.
  • RetirementPlan::Solver (pure): the earliest year whose simulation survives, or none, with the depletion age at the latest start.
  • RetirementPlan::Stream and RetirementPlan::FundingAccount (a link must be to a cash, investment or crypto account the plan's user counts in their own finances; a stream's account, when it changes, must be one the user counts in their finances).
  • RetirementPlan#simulation(as_of:, retirement_year:), #solve(as_of:), #eligible_funding_accounts, and #seed_streams!(as_of:): once per plan, under a row lock, it seeds living costs 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) and one unindexed stream per loan at its repayment in force, ending the year the loan's payoff projection clears it. A loan the projection gives 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. An unsaved plan raises ArgumentError.
  • Locale: retirement_plans.streams.seeded.living_costs (the seeded stream's name).

Commits: Let median_expense take the median over a period, Plan retirement year by year, to an end age, with inflation, Pin that a withdrawal taking exactly what is left is met, Rewrap the simulation's recurrence comment, and the review fixes listed below.

Size. 494 lines of non-test diff (484 before the 2026-11-22 seeding fix), over the 300-line guide. About 45 of them are schema.rb, 73 the migration (mostly comments), and roughly a third of the model lines are comments stating the recurrence and its edge cases. The projection engine and its inputs are one idea, what a year-by-year plan is, so it stays one slice: splitting the engine from its inputs would leave a PR whose classes nothing calls.

Divergence from the fork

  • Loan repayment. The fork seeds a loan's stream from Loan::PayoffProjection#monthly_payment, which main's projection does not have. Here it uses loan.amortization_schedule.payment_in_force(as_of), the figure the loan overview already shows. For a fixed-rate loan the two are the same; for a variable-rate one this is the repayment at today's rate rather than the opening one.
  • Loan test fixture. main's projection gives no payoff date to a loan that is behind its contract, so the fork's 50,000-of-60,000 fixture seeds nothing here. The seeding test uses 45,000 (ahead of the contract), and a separate test pins that a loan behind its contract seeds its repayment until maturity. The repayment is pinned at 1,159.97.
  • One added test (a withdrawal that takes exactly what is left is met) closes a gap a mutation found: nothing pinned that boundary.
  • RetirementPlan::Simulation's readers used by Monte Carlo, and the Monte Carlo settings tests, arrive with the next PR. One comment was moved to the method it describes.
  • Migration: one here for what the fork's 20260928120000 added, at 20261008150200.

Demo data

No demo data needed: nothing renders a plan yet.

Migration notes

Adds five columns to retirement_plans, each with a default or nullable, so plans saved before it keep validating; creates retirement_plan_streams and retirement_plan_accounts. Stream rows nullify their account_id when the account goes (a user may have edited the stream); funding links cascade. Nothing to run after deploy.

Verification

  • bin/rails test test/models/retirement_plan_test.rb test/models/retirement_plan test/models/income_statement_test.rb: 126 runs, 309 assertions, 0 failures, 0 errors.
  • Full suite bin/rails test at the top of the stack (up/retirement-plan-milestones @ ceca83afb, 2026-11-22): 18300 runs, 112996 assertions, 0 failures, 8 errors, 9 skips. The 8 errors are ReleaseNotesWorkflowTest, which needs node, missing from the test runner's image.
  • bin/rubocop on the changed files (2026-11-22): no offenses. bin/brakeman --no-pager -q (2026-10-22 head): 0 warnings.
  • Mutations, each caught by a failing assertion unless noted:
MutationCaught by
period SQL clause removedIncomeStatementTest: a period bounds the months...; the bounded and default medians are cached under different keys
cache key loses the periodthe bounded and default medians are cached under different keys
memo loses the perioda period bounds the months the median expense is taken over...
period loses its first or last day, or takes in the day either sidea period takes in its first and last days and neither day outside it; PlannerInputsTest: living costs take in the window's first and last days...
growth taken before the withdrawalSimulationTest: a 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 yearSolverTest: a plan that can already retire gets this year
living costs not limited to 12 monthsPlannerInputsTest: living costs are the median of the months with spending in the last 12 whole months...
median swapped for the meansame test (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 costssame test
seeding runs againstreams are seeded once...; two copies of a plan loaded before either seeds...
row lock replaced by a plain transactiontwo copies of a plan loaded before either seeds do not both seed
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 ignoredlinked accounts replace the default set of accounts
funding link to any family accountan account the user does not count in their finances cannot be linked
stream account not checkeda stream's account must be one the user counts in their finances
stream account checked on every savea stream whose account has left the user's finances can still be edited
stream end-before-start allowedPlannerSettingsTest: a 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

Who else hits these lines, and what do they pass? As in the previous PR: median_expense's other callers (Budget, Goal#median_monthly_expense, CashFlowWarningGenerator, GetIncomeStatement) pass no period:, so the SQL, memo and cache key are what main builds. The category path raises if given period:. 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 passes its own today. The stream account check's only writer today is seed_loans, which passes a finance_accounts loan, inside the checked scope.

What else reads what this changed the reading of? grep -n "family_stats(" app/models/income_statement.rb: avg_expense and median_income pass only interval: and are deliberately unchanged. grep -rn "payment_in_force\|PayoffProjection.new" app: the overview tab, Loan#payoff_projection, and this seeding; none changed. Accounts gain no association: the stream and funding foreign keys are declared on the new tables only.

Feedback sweep 2026-10-13

  • 5059f73da: #simulation and #solve return nil when the plan has no years to run (owner born after the reference year, or end age already past), and #simulation also when retirement falls after the end-age year. Simulation raises on an end-age year before the reference year. Funding links are limited to cash, investment and crypto accounts (LIQUID_AND_INVESTMENT_TYPES), the only balances the funding total counts. Adds tests for a one-off after retirement, a solver case where lasting is not monotonic in the year, a failed seed marker, and a read-only check that runs a real simulation.
  • bc2e2a23c: the engine purity scan ignores comments and matches DateTime. cc41c77cb: the category median's period guard is tested.
  • Owner decision (2026-10-13), implemented in ae3c9f7e1: when no linked account is still eligible (hidden, excluded from reports or no longer shared), the default set funds the plan, as when the links are deleted. While at least one is eligible, only those count. Fork main tracked in #438.

Adversarial review 2026-10-22

  • 28bc8e27f: both sides of both ends of the living-costs period are pinned; RetirementPlan::Stream checks its account against the user's finances when the account changes; seed_streams! refuses an unsaved plan; comments on the two spending windows and the monthly * 12. 9933f2350 merges #364. Reply on this PR lists each finding. The stale-base blocker waits on the owner's rebase decision.

Review fixes 2026-11-22

Head: 86728d25b. Rebased 2026-11-22 onto mirror/upstream-main @ 9e419e7be as a linear stack: CodeRabbit's merge commit 1fb268b27 is dropped, and five commits are re-authored to the owner. The only conflict resolutions are in IncomeStatement#family_stats: upstream's ExchangeRate::CONVERSION_CACHE_VERSION stays in the cache key and this stack's segments are appended.

  • d92fc65b3: the migration test expects "90" and "0.03" as activerecord 8.1.4.1 reports them.
  • 3b56bc6cb: seeding stays open while a loan is skipped for want of an exchange rate, and a re-seed adds only what is missing (no second living-costs stream, no second stream for a seeded loan). Test: a foreign loan without a rate leaves seeding open and seeds it once a rate exists.
  • e01495fab: the source scan is replaced by a behaviour test of Simulation and Solver (two days under travel_to, no queries, no Current).
  • 86728d25b: the comments now say living costs are the median of the months with spending in the last 12 whole months (the monthly totals are not zero-filled; the query is unchanged), and the living-cost test uses three unequal months so a mean fails it.

Rewritten 2026-11-22 (messages and two migration names only; trees otherwise identical): the two migrations that shared a class name with fork main are now CreateUserRetirementPlans and AddMonteCarloToRetirementPlans, and commit messages no longer cite fork PR numbers.