Add a seeded Monte Carlo run to the retirement planner
Upstream PR: we-promise/sure#5611 (same commits; native stack we-promise/sure#5613).
Part of #127
Upstream pre-flight for the retirement planner's model layer, slice 3 of 4 (Monte Carlo). The upstream PR is NOT YET OPENED (awaiting owner approval); it will be raised from this branch: same branch, same commit.
Stacked on #365 (up/retirement-plan-projection), itself on #364. Fork history this ports: #252 (engine and plan methods only; the job, cache and page stay on fork main).
Summary
Part of we-promise/sure#5567. Programme: we-promise/sure#3494.
Fork pre-flight: jaysbeekay/sure#369 (same branch, same commit).
Stacked on we-promise/sure#5610 (up/retirement-plan-projection, fork pre-flight jaysbeekay/sure#365), and through it on we-promise/sure#5609; it carries their commits until they merge, so review this slice's own commits here (the ones not on up/retirement-plan-projection). Third of four (drop 8.3 of jaysbeekay/sure#127).
A plan can now say how likely it is to last, not only whether it lasts on expected returns: a Monte Carlo run over 5,000 paths reports the success rate, percentile paths in today's money, a worst-sequence stress rate, the first year that reaches the plan's success target, and a 5 x 5 grid over return and savings rate. The design choice to know about: the run is deterministic. Its draws come from a seed fixed by the plan's id, so the same inputs always give the same answer, and every question asked of one run shares the same draws.
What changed
- Migration:
return_volatility(default 12%) andsuccess_target(default 90%) onretirement_plans, with check constraints. RetirementPlan::MonteCarlo(pure). Each year's return is log-normal around the expected return,1 + r_t = (1 + r) * exp(sigma * z_t), so the median path is the expected-returns path and withsigma = 0every path isRetirementPlan::Simulation, to the cent. Normals by Box-Muller fromRandom.new(seed). The yearly contributions and withdrawals come from the simulation (#yearly_flows), so the two engines cannot disagree on them; only the growth varies. Nearest-rank percentiles. The stress rate reorders each path's retirement-year returns worst first.RetirementPlan::Simulationgains the readers Monte Carlo uses:#yearly_flows,#inflation_rate,#current_assets,#return_rate.RetirementPlan#monte_carlo_seed(CRC32 of the id),#monte_carlo(as_of:)(retiring on the plan's date, or in FIRE mode in the solved year; nil for an unsaved or unsimulatable plan), and#monte_carlo_result(as_of:), the answers as plain values. The confident-year search, a full run per candidate year, runs only in FIRE mode, the one mode that shows it.
Commit: Add a seeded Monte Carlo run to the retirement planner.
Divergence from the fork
- Not carried: the background job and its cache. On the fork,
RetirementPlan::MonteCarloJobruns this off the request, caches the result under a digest of the inputs (#monte_carlo_cache_key,MONTE_CARLO_ENGINE_VERSION), tracks pending and failed markers, and broadcasts a page partial. All of that serves the planner page, which is not part of this stack, so it goes with the page.#monte_carlo_result's comment is reworded accordingly, and the job and cache tests stay on the fork. One test adapted from them pins the result's shape here. MonteCarloInputsTestis anActiveSupport::TestCasehere (the fork's is anActiveJob::TestCasefor the job).- Migration: one here for what the fork's
20260928140000added, at20261008150300.
Demo data
No demo data needed: nothing renders a plan yet.
Migration notes
Adds two non-null columns with defaults to retirement_plans; existing rows take the defaults. On a fresh database there is nothing to run after deploy.
Fork sync: the migration is deliberately unguarded. Fork main already has both columns and both constraint names from 20260928140000_add_monte_carlo_settings_to_retirement_plans.rb. The first fork sync that brings this stack in retires fork main's three earlier retirement migrations (20260928090100, 20260928120000, 20260928140000), which this stack replaces with 20261008150100, 20261008150200 and 20261008150300, and reconciles db/schema.rb. Run on fork main without that step, this migration fails on the existing columns.
Verification
bin/rails test test/models/retirement_plan_test.rb test/models/retirement_plan: 102 runs, 365 assertions, 0 failures, 0 errors. The Monte Carlo tests use their own fixed seeds and pass on every run.- Full suite
bin/rails testat the top of the stack (up/retirement-plan-milestones@3615a89bd, 2026-11-22; the pushed head3ec02b8dcdiffers from it only in one comment line): 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:
| Mutation | Caught by |
|---|---|
mean-based log-normal (- sigma^2 / 2) | MonteCarloTest: the median path is the expected-returns path |
seed ignored (Random.new) | the same seed gives the same result, and a different seed a different one |
| plan seed not fixed by its id | MonteCarloInputsTest: the run uses the plan's own volatility, a seed fixed by the plan... |
| plan volatility not passed through | same test |
| FIRE mode not solved for its year | in FIRE mode the run retires in the expected-returns year |
| confident year searched outside FIRE mode | outside FIRE mode the result has no confident year and the search never runs |
| confident year needs to beat the target | a year whose success rate equals the target exactly is confident |
| stress run not reordered | the worst-first ordering of the same returns never succeeds more often |
| percentile off by one | a percentile is the smallest value with at least that share at or below it |
| percentiles not deflated | with no volatility every path is the deterministic projection, to the cent |
| heatmap ignores the savings step | the heatmap never lowers success for a higher return or savings rate... |
| withdrawal taken after growth | with no volatility every path is the deterministic projection, to the cent |
| Box-Muller cosine used twice | the median path is the expected-returns path |
| volatility upper bound removed | PlannerSettingsTest: volatility outside 0 to 100% and a target of 0 or above 100% are refused |
| FIRE end-age fallback dropped | MonteCarloInputsTest: in FIRE mode a plan that never lasts is run retiring in its end-age year |
Blast radius
Who else hits these lines, and what do they pass? RetirementPlan::Simulation's new readers are read only by RetirementPlan::MonteCarlo; nothing in Simulation's existing behaviour changes (#yearly_flows calls the same private flows_for the rows use). RetirementPlan::Solver is called by #monte_carlo in FIRE mode with the same inputs #solve passes.
What else reads what this changed the reading of? grep -rn "Simulation.new" app/models/retirement_plan*: RetirementPlan#simulation, Solver#simulation and MonteCarlo#simulation, all with the same simulation_inputs hash, so the three cannot drift on inputs. Nothing outside RetirementPlan changes.
Feedback sweep 2026-10-13
- 9e9a75fff:
#monte_carloreturns nil on the same terms as#simulation(unsaved, no years to plan, no retirement year, retirement after the end age), checked before anything is computed. This also fixes aNoMethodErrorin FIRE mode that merging #365's horizon guard would otherwise have introduced. The stress run reorders every modelled year when retirement is before the reference year. The growth factor is floored at 0, so a heatmap step past -100% empties the portfolio rather than flipping its sign. - Owner decision (2026-10-13): the confident-year search cost is declined. Lasting is not monotonic in the year, the search runs in the job behind a cache, and a full 5,000-path result costs about 0.64s. 208a914e8 merges #365's funding fallback.
Adversarial review 2026-10-22
- 4a893381f: a test pins the FIRE never-lasts fallback (the run retires in the end-age year); the result-shape test checks every key and value;
confident_year's comment says why it is uncapped. ca150d8ac merges #365. Reply on this PR lists each finding, including the three nits declined. The stale-base blocker waits on the owner's rebase decision.
Review fixes 2026-11-22
Head: d15e7f99c. 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.
95b1cafda: the migration test expects"0.12"and"0.9"as activerecord 8.1.4.1 reports them.d85a99931: a Monte Carlo path meets a withdrawal within half a cent of its value, so a plan funded to the cent lasts asSimulationsays; a plan a cent short still fails.d15e7f99c: the source scan is replaced by a behaviour test of the Monte Carlo run (two days undertravel_to, no queries, noCurrent).
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.