Retirement planner 8.3: Monte Carlo chance of success, confidence year, fan chart and heatmap

Merged
JA
2mo ago
+1120-3

Summary

8.3 of #127: Monte Carlo. It follows the 8.3 triage plan, and #127 stays open until 8.4.

Before this PR, the planner (#251) answered on expected returns only. A plan that only just lasts on expected returns fails about half the time, and the page could not say so.

After it, the planner shows:

  • The chance the money lasts: the share of 5,000 simulated markets in which the portfolio lasts to the end age.
  • The stress test: the same returns, with each path's retirement-phase years reordered worst-first.
  • In FIRE mode, the earliest year at the confidence target (90% by default, editable), beside 8.2's expected-returns year.
  • A fan chart of the 10th, 25th, 50th, 75th and 90th percentile, in today's money.
  • A 5 × 5 heatmap of success against expected return (± 1 and 2 points) and savings rate (± 5 and 10 points).

The run happens off the request, in RetirementPlan::MonteCarloJob, and is cached. The page shows the cached result, or says it is calculating until the job's broadcast replaces that; while calculating, it also polls, in case the broadcast arrived before the page subscribed.

The owner's decisions, recorded in the 8.2 plan:

  • Distribution: each year's return is drawn independently from a log-normal whose median is the expected return, 1 + r_t = (1 + r) · exp(σ z_t). With σ = 0 every path is #251's deterministic path, to the cent.
  • Volatility: a plan setting, 12% by default, editable.
  • Generator: Random.new(seed) with Box–Muller. The seed is derived from the plan's id, so the same inputs give the same answer on every visit.
  • Common random numbers: the same draws are used in every heatmap cell and every year of the confidence scan, so they differ only by their inputs.
  • Cache key: a SHA-256 digest of every input plus an engine version, so there is no version column (review finding 6).

Commits, in the seam order #118 asks for

CommitLayer
24a3e4ddSchema and model: return_volatility (default 0.12, check 0–1) and success_target (default 0.90, check > 0 and ≤ 1), set in percent like the other rates
0a13b1f4Engine: RetirementPlan::MonteCarlo, pure. Simulation#yearly_flows is the replay it runs each path through
8df47ab6Inputs and job: RetirementPlan#monte_carlo, #monte_carlo_cache_key, #monte_carlo_result, #enqueue_monte_carlo and RetirementPlan::MonteCarloJob
60d72725UI: RetirementPlans::MonteCarloComponent, the planner card, and the two settings fields. Held for Phase C
d8602c90UI: a legend naming the fan chart's lines, since the chart's multi-line mode draws no tooltip
5d5c3248Job, inputs and page: review follow-up (see below)
1afeae6fUI: each heatmap savings rate shown once (review follow-up)
82d179d6Job, inputs and page: a failed run's end state, per-input broadcasts, enqueue clean-up (review follow-up)

The first three are the upstream-bound model layer, the next two are UI, and the review follow-up touches both. Merge with a merge commit.

Where this differs from the triage plan

  1. The engine replays Simulation#yearly_flows in floats rather than giving Simulation a returns: argument. Running 5,000 × 65 years × 26 variants through BigDecimal would take minutes. The σ = 0 test pins the float replay to #251's BigDecimal path to the cent, so the two cannot drift apart unnoticed.
  2. The result carries the return and savings rate it was run with, so the heatmap's axis labels come from the same inputs as its cells rather than being recomputed by the view.

Scope and dependencies

  • Issue: #127 (8.3 only)
  • Parent PR/branch, if stacked: none now. #250 and #251 merged on 2026-09-28, and this PR was retargeted to main.
  • Intentionally out of scope:
    • Correlated or fat-tailed returns, and historical bootstrapping. The model is log-normal and independent year to year, and the page says so.
    • A return per account or an asset mix.
    • Milestones (8.4: #255 and #256). Tax and funding order were deferred to #254.

Blast radius

CallerChange
retirement_plans / 8.1's and 8.2's formsTwo new columns with defaults; existing rows stay valid (tested). The settings modal gains two fields
RetirementPlan::SimulationGains public readers and yearly_flows; rows, survives? and the solver are unchanged. #251's engine tests pass unchanged
RetirementPlansController#showReads the cache and, on a miss, enqueues one run. It still seeds nothing (#251's test), and enqueues nothing for a plan it cannot simulate or a user without preview access (tested). While pending, the page polls itself every 5 s
Rails.cacheNew keys under retirement_plan/monte_carlo/; nothing else reads them. A …/pending marker (10 minutes) stops a reload or a poll enqueueing a second run, and a …/failed marker (a day) stops the page asking again for inputs whose run raised
SidekiqOne job per cache miss, on the existing low_priority queue. It is enqueued only from the preview-gated page, for the signed-in user's own plan, so it is naturally inert for everyone else, as upstream's preview-gating guide describes; it has no gate of its own
TurboThe job broadcasts to [user, :retirement_plan], and the page subscribes to that stream

The reference date, one hop further: the controller captures as_of once. It goes into the cache key, into the job's argument (ISO 8601), and from there into the engine. The job never reads the clock; the "job reads the clock" mutation below is caught.

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 build the plan from what the test adds; the volatility test uses a non-default value so a hard-coded default fails.
  • Financial calculations use BigDecimal and documented rounding points. The deterministic engine stays BigDecimal. The Monte Carlo replay is float by design (see above), pinned to it to the cent at σ = 0, and its outputs are shares and percentiles, rounded 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:

  • Engine: of the first 11 tests, 8 failed against a stub (7 on assertions, 1 error). The other 3, the clock scan among them, pass against a stub by construction, so the mutations are their evidence. The last 2 (the percentile unit test and the ≥ boundary) were added because a mutation first survived without them.
  • Inputs and job: all 6 errored before the implementation.
  • UI: 5 of 8 failed on their assertions (the legend assertion, added later, failed against the chart without a legend). The 3 that passed are guards: the preview gate, "cannot be simulated", and "traditional shows no confident year". The mutations below are their evidence.

Mutations, each caught (41 in all):

LayerMutationCaught by
Settings (6)volatility lower bound dropped; upper bound dropped; target > 0 relaxed to ≥ 0; target upper bound dropped; target ≤ 1 tightened to < 1; percent setters miss the new columnsthe bounds test and the percent test
Engine (11)mean-based parameterisation; unseeded generator; one Box–Muller factor dropped; depleted paths counted as successes; percentile index off; stress sorted best-first; > for ≥; confidence scan starting a year late; fresh draws per heatmap cell; savings step ignored in the heatmap; the clock read seededthe σ = 0, median, seed, normals, success-rate, percentile, stress, confident-year, heatmap and source-scan tests
Inputs and job (12)seed constant; volatility hard-coded; FIRE run on the plan date; key without volatility, the target, the streams, or as_of; job ignores the cache; job does not write it; job broadcasts to the family; job reads the clock; no dedupethe six inputs and job tests
UI (12)availability check dropped; enqueue on a hit; enqueued for tomorrow; dedupe bypassed; volatility not permitted; target not permitted; FIRE-only section shown in traditional mode; no-year branch dropped; stream subscription dropped; subscribed to the family's stream; "calculating" inverted; preview gate droppedthe controller tests

One mutation survived at first: dropping the stream subscription. The test asserted that a turbo-cable-stream-source was present, and the layout already renders one. It now asserts this plan's own signed stream name, and catches both the dropped subscription and a subscription to the wrong stream.

Timing: a full result (5,000 paths to age 90, the stress test, the confidence scan and the 25 heatmap cells) took 5.1 to 6.5 seconds in the job on this container. That is inside the plan's 60-second limit, at the full 5,000 paths.

Commands:

  • The retirement plan model, controller and component suites: 238 runs, 0 failures.
  • Full bin/rails test: 10,780 runs, 47,120 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, OpenAI extra_headers, the Registry anthropic ENV test, and HostingsController anthropic ×3. Nothing else fails.
  • bin/rubocop and erb_lint on the changed files: clean. bin/brakeman: no warnings.
  • The partial was rendered outside a request, with a real engine result, which is how the job's broadcast renders it.
  • db/schema.rb was regenerated on a throwaway database, since dropped; unrelated re-formatting was reverted.

Checked against upstream AGENTS.md:

  • Logic lives in models (the engine, RetirementPlan) and the job; the controller is thin, and the component only formats.
  • Current.user only: the plan is the signed-in user's own, and the stream is theirs.
  • Migration version 8.1. Minitest and fixtures, with Mocha.
  • DS primitives (DS::Card); only functional tokens (text-success, text-warning, text-secondary, text-subdued, border-divider); every string through t().
  • Preview-gated. No new dependency and no JavaScript change: the fan chart is the existing time-series chart's multi-line mode, and the pending poll uses the existing polling controller.

Screenshots: taken with the same demo figures as #251 (420,000 in assets; spending 3,500 and income 6,500 a month; 6% return; 3% inflation; born 1985; end age 90). As UI held for Phase C, the upstream UI PR will carry them.

  • FIRE: retiring in 2036, the expected-returns year, succeeds in 49% to 50% of paths across two demo runs (the demo plan is recreated each run, so its id and seed differ). That is what a median-parameterised engine should give for a plan that only just lasts on expected returns. The earliest year at 90% confidence is 2043, at 58. The heatmap runs from 13% (4% return, 36% saved) to 86% (8%, 56%).
  • Calculating: "Running 5,000 simulations of your plan. This takes a few seconds."

Risks, blockers, and follow-up

  • The stress test is severe by construction. Sorting every retirement-phase year worst-first gives 0% on the FIRE demo against about 50% ordinarily. That is the decided definition, and the page explains it, but a milder variant (for example, only the first five retirement years replaced by the worst five) would read less starkly. For the owner to decide; not changed here.
  • FIRE with no expected-returns year: the run then retires at the end age, and the confident-year panel says no year reaches the target. The headline's "retiring in" year makes this visible.
  • A failed job is recorded in /settings/debug, discarded, and its inputs marked failed for the day. The page then says the simulations could not be run and stops polling; it does not enqueue the same inputs again. Changing a setting is a new key, so it runs.
  • Results are cached for a day. as_of is in the key, so each day's first visit recomputes.
  • #251's planner chart now has a legend too (26887dc1, added after #251's light Gatekeeper review).
  • Two non-blocking notes from the light Gatekeeper review:
    • The 10-minute pending marker is never cleared. Now cleared when a run finishes (5d5c3248) or fails, or when it does not queue (82d179d6).
    • For a plan saving 5 points or less, the heatmap's two leftmost columns both clamp to 0%, so the axis read 0% twice. Fixed in 1afeae6f: steps that clamp to the same rate show as one column.
  • Next: 8.4 is #255 (planner milestones) and #256 (goal chart milestones). Tax and funding order were deferred to #254.

Review follow-up (5d5c3248)

FindingSourceHandling
A broadcast sent before the page's stream subscribes is lost, leaving it on "calculating"CodeRabbitFixed. While pending, the section sits in a turbo frame on the existing polling controller, re-reading the page every 5 s; a page that has the result carries no polling URL, so it stops. No new JavaScript
confident_year searched in every mode, shown only in FIRECodeRabbitFixed. Computed only in FIRE mode; the key stays in the result as nil. mode is already in the cache key, so a cached result never crosses modes
No failure policy on the jobProduction Readiness Review F1Fixed. discard_on StandardError with a DebugLogEntry (category background_jobs, level error, the plan's user and family, plan id, date and error class). No retry: the same inputs fail the same way
CPU cost competes with syncsPRR F2Fixed. queue_as :low_priority, an existing Sidekiq queue
Pending marker never clearedPRR F3 / light GatekeeperCleared on a finished run; superseded by 82d179d6 below
F4, F5PRRAlready disclosed above; no change

Tests (written first, each failing for its stated reason): FIRE-only search (negative and positive), marker cleared on success, failure recorded and discarded, the queue, and the polling frame present only while pending. Mutations caught, 6 of 6: search in every mode, marker not cleared, no discard, marker cleared on failure, never polls, always polls. Retirement model, controller and component suites: 265 runs, 0 failures. rubocop, erb_lint and brakeman clean. Not browser-checked; the polling controller is the one family exports and background jobs already use.

Review follow-up, second round (1afeae6f, 82d179d6)

FindingSourceHandling
A failed run has no end: after the marker expires, a polling page enqueues the same failing run againCodeRabbit on 5d5c3248Fixed in 82d179d6. The discard handler marks the inputs failed (a day, like a result); the page shows "The simulations could not be run for this plan. Changing a setting runs them again.", stops polling and enqueues nothing. A changed setting is a new key and runs
An older run can overwrite a newer page's result: every broadcast targeted the one shared elementCodeRabbit on 5d5c3248Fixed in 82d179d6. The section carries its input digest (data-monte-carlo-key), and the job broadcasts with targets: on that digest, so a run replaces only the section showing its own inputs. Checked with a real broadcast: the stream's targets selector matches the rendered section
A job that raises on enqueue, or is not enqueued, leaves the pending marker holding the pageCodeRabbit on 5d5c3248Fixed in 82d179d6: the marker is taken back and the error re-raised; only a job that reports successfully_enqueued? counts
A plan saved mid-run could have its markers set or cleared by the older runCodeRabbit security review on 5d5c3248Fixed in 82d179d6: every marker and the broadcast use the key the run started with
The heatmap axis reads 0% twiceLight Gatekeeper reviewFixed in 1afeae6f
ci / test_system red at 5d5c3248 on PropertiesEditTestCINot this PR's: see the PR comment. Re-run once; 1afeae6f and 82d179d6 start a fresh run
Docstring coverage below 80%CodeRabbit pre-merge check (warning)Declined. Every non-trivial method this PR adds carries a comment; the uncommented ones are one-line predicates and formatters (fire?, percent, target_met?), and CLAUDE.md asks for the surrounding comment density rather than a comment on each

Tests, each written first and failing at its assertion: failure marked and the pending marker cleared; markers kept to the starting key when the plan changes mid-run (failure and success); enqueue raising or not queuing leaves no marker; the broadcast targets its own digest; the page after a failure shows it and neither polls nor enqueues; the section carries its key (pending and result); one heatmap column per clamped rate, and all five when clear of zero. Mutations, each caught (14): failure not marked; failure keyed by the plan as it is now; pending cleared by a recomputed key; broadcast to the shared target; enqueue despite failure; poll despite failure; marker kept when enqueue raises; a not-enqueued job counted as queued; the section without its key; the failed state not shown; heatmap without dedupe; dedupe on the unclamped step; cells not sliced to match; over-eager dedupe. Retirement model, controller, component and i18n suites: 279 runs, 0 failures (4 i18n skips, environmental). rubocop, erb_lint and brakeman clean.

Summary by CodeRabbit

  • New Features
    • Added Monte Carlo retirement projections with success and stress rates, projected portfolio ranges, and a savings-and-return success heatmap.
    • Added return-volatility and success-target settings to retirement plans.
    • Shows simulation status while results are being prepared, then updates the results automatically.
    • Displays a confidence-based retirement year when available, along with the simulation’s assumptions.