Plan retirement year by year, to an end age, with inflation (#127, 8.2)
Summary
8.2 of #127: the full planner tier. It follows the 8.2 triage plan, and #127 stays open until 8.4.
Before this PR, the plan projected one number to one retirement date: no inflation, no spending after retirement, and no end.
After it, a planner page (/retirement_plan, linked from 8.1's card) shows the portfolio year by year to the plan's end age, in nominal and today's money, and answers one of two questions:
- Traditional mode: retiring on my date, does the money last to my end age, and if not, at what age does it run out?
- FIRE mode: what is the earliest year I can retire and still last to my end age, on expected returns?
The owner's decisions are recorded in the plan. The key ones:
- End age defaults to 90 and inflation to 3%, both editable.
- Withdrawals come out at the start of the year and contributions go in at the end:
V(n+1) = (V(n) − W(n)) × (1 + r) + C(n). - The expected return is the compound annual return before inflation.
- Tax is deferred to 8.4, and every figure is labelled "before tax".
Commits, in the seam order #118 asks for
| Commit | Layer |
|---|---|
bc5b0a63 | Schema and models: retirement_plans gains birth_year, end_age, inflation_rate, mode and streams_seeded_on; new retirement_plan_streams and retirement_plan_accounts. DB checks mirror the validations |
b0282c94 | Engine: RetirementPlan::Simulation (year by year) and RetirementPlan::Solver (the earliest FI year). Pure, with the reference date injected |
03224945 | Inputs: RetirementPlan#simulation, #solve and #seed_streams!, funding accounts, and IncomeStatement#median_expense(period:) |
37f3325f | UI: the planner page and component, stream forms, the settings fields, and the link from 8.1's card. Held for Phase C |
26887dc1 | UI: a legend naming the chart's two lines (nominal and today's money), since the chart's multi-line mode draws no tooltip. Added after the light Gatekeeper review |
8e0665af | UI: a user's first stream saves their plan in the same transaction, so an invalid stream leaves no empty plan behind. From CodeRabbit's review |
47ec8001 | Inputs and UI: seeding takes a row lock, so two racing saves seed once; the settings and the first seeding commit in one transaction. From CodeRabbit's summary |
The first three are the upstream-bound model layer, and the next three are UI. 47ec8001 spans both layers: its model half (seed_streams! and its test) goes upstream with the model layer, and its controller half stays with the UI. Merge with a merge commit.
Where this differs from the triage plan
- Streams are seeded once, recorded in
streams_seeded_on. The plan said "on first save"; a date column is what makes "once" hold after a user deletes a seeded stream. Tested. - Traditional mode keeps 8.1's retirement date rather than adding a target-age column. The table shows ages from the birth year, so a separate age input would duplicate the date.
- Income streams count only once retired. Before that, 8.1's contribution (savings rate × income) already carries what the user earns. This is stated in the engine's comment.
Scope and dependencies
- Issue: #127 (8.2 only)
- Parent PR/branch, if stacked: #250 (
feat/127-fire-simple-tier). This PR's base is that branch; it retargets tomainonce #250 merges. - Intentionally out of scope:
- Tax, milestones and funding order (8.4).
- Monte Carlo, the confidence solver, the heatmap and the stress test (8.3).
- A return per account, separate returns for cash, salary growth above inflation, and flexible spending rules.
Blast radius
| Caller | Change |
|---|---|
retirement_plans / 8.1's form | New columns all have defaults or allow null; a row saved with only 8.1's fields still saves (tested). 8.1's settings modal gains the planner fields |
IncomeStatement#median_expense | Gains optional period:, default nil: SQL, memo and cache key unchanged for every other caller. Every test file that touches IncomeStatement: 592 runs, 0 failures |
Loan::PayoffProjection | Read only, as_of: injected. Not applicable → no stream |
RetirementPlansController#update | Seeds streams after a successful save, once. #show never writes (tested) |
RetirementPlans::SummaryComponent | Gains a link to the planner; its figures are unchanged |
Account destroy | A seeded loan stream's account_id is nullified and the stream kept; funding links cascade (tested) |
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. None are touched.
- Any gate test has an observed failing mutation transcript attached. See Validation.
- Fixtures used as evidence assert internal consistency. The input tests remove the member's fixture shares, and every figure is made only of what the test adds.
- Financial calculations use
BigDecimaland documented rounding points. The engine isBigDecimalthroughout; the table and chart round only for display. - De-identification uses token-shape allowlists; no personal data is included.
- Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.
Validation
Fail-first, layer by layer, each against a stub:
- Schema and models: 7 of 13 failed on their assertions. The 6 that passed are held by the schema already in place: the defaults, the cascades, the DB checks, and 8.1's form saving. No separate mutation pass was run on this layer's validations; the 7 fail-first failures are its evidence.
- Engine: 16 of 17 failed, all on assertions except two where the stub returned integers. The clock scan passes against a stub by construction.
- Inputs: 8 of 11 failed. The 3 that passed are "seeds nothing" guards: the nothing-left loan is shown live by the applicability mutation below, and the page-view guard by the controller's "show seeds" mutation; the no-spending guard has no mutation of its own.
IncomeStatementperiod:: the 2 tests failed on the missing keyword.- UI: 10 of 11 failed on the missing routes. The mutations are the evidence for them.
- Legend (
26887dc1): the assertion for two named lines failed with 0 found before the legend was added.
Hand-computed figures the engine must match, to the cent:
| Case | Figures |
|---|---|
| 5%, no inflation (8.1's table) | 115,000.00 · 130,750.00 · 147,287.50 |
| 5%, 3% inflation, contribution indexed | 115,000.00 · 131,050.00 · 148,211.50 nominal; 111,650.49 · 123,527.19 · 135,634.52 in today's money |
| Withdrawal at the start of the year | 100,000 − 40,000, then 5% → 63,000.00 |
| Solver boundary (0% return, spend 10,000, retire by 60) | Retiring in 2030 runs out; 2031 lasts (70,000 against 60,000) |
Mutations, each caught (31 in all: 11 engine, 12 inputs, 8 UI):
| Layer | Mutation | Caught by |
|---|---|---|
| Engine | contribution compounded; contribution not indexed; deflated by the previous year's factor | the 5% and 3% tables |
| Engine | end-of-year withdrawal | start-of-year test, the solver boundary, depletion |
| Engine | surplus withdrawn as a negative; one-off every year; end year ignored; unindexed streams indexed | their own tests |
| Engine | depletion off by one | depletion and three solver tests |
| Engine | solver skips this year; the clock read seeded | "already FI gets this year"; the source scan |
| Inputs | living costs over all history; loan payments counted; contributions counted; date SQL dropped | the living-costs test (the SQL drop also fails both IncomeStatement period tests) |
| Inputs | reseeds; loan applicability not checked; loan end year not set | seeded-once; nothing-left loan; the loan test |
| Inputs | links ignored; link eligibility not checked; streams not simulated | their own tests |
| Inputs | memo key without the range; cache key without the range | the two IncomeStatement tests (the second under a memory store) |
| UI | show seeds; update does not seed; birth_year not permitted; streams found globally; streams preview gate removed; retired flag inverted; FIRE uses the plan date; birth year not required | the controller tests |
Commands:
- The new and neighbouring suites (plans, portfolios, retirement plans, every
IncomeStatementuser, i18n): 592 runs, 0 failures, 4 skips in files this PR doesn't touch. - Full
bin/rails test: 10,749 runs, 46,905 assertions, 4 failures, 3 errors, 33 skips. All 7 are the known local Ruby 3.3.6 environment failures: ActiveStorage variants, the admin profile picture, OpenAIextra_headers, the Registry anthropic ENV test, and HostingsController anthropic ×3. Nothing else fails. - After the legend: the retirement plan controller and component suites, 139 runs, 0 failures;
erb_lintandrubocopon the two changed files clean. bin/rubocopanderb_linton the changed files: clean.bin/brakeman: no warnings.test/i18n_test.rb: 7 runs, 0 failures.i18n-tasks missingdid not finish inside five minutes locally, so I'm relying on the i18n test rather than claiming it.db/schema.rbwas regenerated on a throwaway database, since dropped; the unrelated financekit constraint re-format was reverted.
Checked against upstream AGENTS.md:
- Logic lives in models and POROs (the engine, the solver,
RetirementPlan); the controllers are thin. Current.useronly: streams are found through the user's own plan, so another user's id is a 404.- Migration version 8.1. Minitest and fixtures.
- DS primitives:
DS::Card,DS::Dialog,DS::Link,DS::Menu,DS::Pill,DS::Toggle. Only functional tokens, and every string throught(). - Preview-gated on both controllers. No new dependency and no JavaScript change: the chart is the existing time-series chart's multi-line mode.
Screenshots: taken with demo figures (420,000 in assets; spending 3,500 and income 6,500 a month; 6% return; 3% inflation; born 1985; retiring in 2045; living costs 42,000; a mortgage of 18,000 until 2040; a pension of 12,000 from 2052). They were shared with the owner in the session; as UI held for Phase C, the upstream UI PR will carry them.
- Traditional: the money lasts to 90. 2026 reads 420,000 × 1.06 + 36,000 = 481,200, and 467,184 in today's money.
- FIRE: the earliest year is 2036, at 51. The mortgage comes out until 2040 and stops, and the pension offsets spending from 2052.
Risks, blockers, and follow-up
- Expected returns only. The page says so, and 8.3 adds the probability of success.
- One pooled return across cash and investments, stated on the page.
- Seeding reads the last 12 whole months' median. A user with less history gets a median over what there is, or no living-costs stream if there's no spending at all.
- CodeRabbit's review (two Minor findings):
- Stream creation order (
streams_controller.rb): fixed in8e0665af. The mechanism it described does not occur, since the plan was already saved before the stream was built. The fix still closes a real gap: a user with no plan who submitted an invalid stream was left with an empty saved plan, which made "an invalid stream is refused and nothing is written" untrue. The plan and the stream now save in one transaction. The test now starts the user without a plan and asserts thatRetirementPlan.countdoes not change either. It failed first ("didn't change by 0, but by 1"), and a mutation removing the rollback is caught. Retirement suites: 100 runs, 0 failures. Rubocop clean, brakeman no warnings. - Stale funding links give a zero total (
RetirementPlan#funding_total): declined here. No route, controller or form creates funding links in this PR, so no user can reach the state. It belongs with the account-selection UI that will create links, where the warning can be tested against a real selection.
- Stream creation order (
- CodeRabbit's summary: two Medium concerns (inferred). Both hold, and both are fixed in
47ec8001.- Racing first saves can seed twice.
seed_streams!checked its in-memory marker, so two copies of the plan loaded before either seeded both seeded. It now runs underwith_lock, which reloads the row. The test "two copies of a plan loaded before either seeds do not both seed" failed first ("didn't change by 0, but by 1"). Putting back the unlocked check fails it again. - Settings saved without their seeding.
updatecommitted the settings, then seeded. Both now commit in one transaction. The test "a failure while seeding leaves the settings unsaved too" failed first (the settings were saved). Moving the seeding back outside the transaction fails it again. - A third test, "an invalid change to a seeded plan is refused and not saved", guards the rollback on an invalid update. It passes on the old code, which had no transaction to roll back. Dropping the rollback makes it error, because
with_lockrefuses a plan with unsaved changes. The existing "end age outside 50 to 120" test did not catch that mutation: with no saved plan, the unsaved plan'supdate!raisedRecordInvalid, which also returns a 422. seed_streams!has one production caller,RetirementPlansController#update, and #252 and #255 change neither method. Retirement, plans and component suites: 240 runs, 0 failures. Rubocop clean, brakeman no warnings.
- Racing first saves can seed twice.
- Next: 8.3 is #252 (Monte Carlo), stacked on this PR. 8.4 is #255 (planner milestones, also stacked on this PR) and #256 (goal chart milestones).
Summary by CodeRabbit
- New Features
- Added a retirement planner with traditional and financial-independence planning modes, configurable assumptions, and projected outcomes through the plan’s end age.
- View yearly portfolio projections, including contributions, withdrawals, growth, inflation-adjusted values, retirement timing, and potential depletion.
- Add and manage annual income, expense, and one-time cash-flow items, with options to set date ranges and inflation indexing.
- Plans can use linked funding accounts; eligible living costs and projected loan payments can be added as streams.