Plan retirement year by year, to an end age, with inflation
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_expensegainsperiod:(defaultnil), 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(defaulttraditional) andstreams_seeded_ononretirement_plans, with check constraints; newretirement_plan_streams(kind, name, annual amount, start and end year, indexed, source, optional account) andretirement_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::StreamandRetirementPlan::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_countcounts accounts; the page should warn when it is above zero. An unsaved plan raisesArgumentError.- 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, whichmain's projection does not have. Here it usesloan.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
20260928120000added, at20261008150200.
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 testat 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 areReleaseNotesWorkflowTest, which needsnode, missing from the test runner's image. bin/rubocopon 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:
| Mutation | Caught by |
|---|---|
period SQL clause removed | IncomeStatementTest: a period bounds the months...; the bounded and default medians are cached under different keys |
| cache key loses the period | the bounded and default medians are cached under different keys |
| memo loses the period | a period bounds the months the median expense is taken over... |
| period loses its first or last day, or takes in the day either side | a 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 withdrawal | SimulationTest: a withdrawal comes out at the start of the year, before that year's growth |
| contribution not indexed | 3% inflation matches a hand-computed table |
| surplus income withdrawn as a negative | a pension is set against spending, and a surplus is reinvested... |
| one-off paid every year | a one-off amount comes out in its year only |
| end year exclusive | a stream with an end year stops after that year |
| unindexed streams indexed | an indexed stream grows with inflation from today; an unindexed one does not |
| real value deflated one year short | 3% inflation matches a hand-computed table, nominal and in today's money |
| exact withdrawal counted as depletion | a withdrawal that takes exactly what is left is met |
| solver skips the reference year | SolverTest: a plan that can already retire gets this year |
| living costs not limited to 12 months | PlannerInputsTest: living costs are the median of the months with spending in the last 12 whole months... |
| median swapped for the mean | same 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 day | living costs take in the window's first and last days... |
| loan payments counted in living costs | same test |
| seeding runs again | streams are seeded once...; two copies of a plan loaded before either seeds... |
| row lock replaced by a plain transaction | two copies of a plan loaded before either seeds do not both seed |
| unsaved plan allowed to seed | an unsaved plan refuses to seed and saves nothing |
| maturity fallback dropped for a loan with no payoff date | a loan its contracted repayment no longer clears seeds its repayment until maturity |
| loan stream indexed | a loan seeds its repayment, ending the year it is paid off |
| funding links ignored | linked accounts replace the default set of accounts |
| funding link to any family account | an account the user does not count in their finances cannot be linked |
| stream account not checked | a stream's account must be one the user counts in their finances |
| stream account checked on every save | a stream whose account has left the user's finances can still be edited |
| stream end-before-start allowed | PlannerSettingsTest: a stream needs a known kind... |
| end age floor moved to 49 | an end age outside 50 to 120 is refused... |
| inflation not a percent attribute | inflation 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:
#simulationand#solvereturn nil when the plan has no years to run (owner born after the reference year, or end age already past), and#simulationalso when retirement falls after the end-age year.Simulationraises 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'speriodguard 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
maintracked in #438.
Adversarial review 2026-10-22
- 28bc8e27f: both sides of both ends of the living-costs period are pinned;
RetirementPlan::Streamchecks 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 ofSimulationandSolver(two days undertravel_to, no queries, noCurrent).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.