Add a per-user retirement plan with the simple FIRE figures
Upstream PR: we-promise/sure#5609 (same commits; native stack we-promise/sure#5613).
Part of #127
Upstream pre-flight for the retirement planner's model layer, slice 1 of 4 (simple FIRE figures). The upstream PR is NOT YET OPENED (awaiting owner approval); it will be raised from this branch: same branch, same commit. The upstream issue is drafted, not yet raised.
Fork history this ports: #250 (and the fork-main state of the files after #251, #252, #255).
Base is mirror/upstream-main (rebased 2026-11-22 onto 9e419e7be; earlier 2026-10-23 onto 56105a3b5). From 2026-10-08 to 2026-10-22 this PR targeted ci/upstream-main-exact, a frozen copy of upstream main; the adversarial review of 2026-10-22 found that copy 205 commits behind and the branch conflicting with current upstream in app/models/income_statement.rb and db/schema.rb, so the stack was rebased and retargeted. The conflict was upstream #3952's cache_freshness_key on the same family_stats cache-key line; the resolution keeps that key and appends this PR's segment (see "What changed").
Summary
Part of we-promise/sure#5567. Programme: we-promise/sure#3494.
Fork pre-flight: jaysbeekay/sure#364 (same branch, same commit), where this fork's CI and review history for the change lives.
First of four stacked PRs for a retirement / FIRE planner model (drop 8.1 of jaysbeekay/sure#127). A user gets a per-user RetirementPlan and the simple FIRE figures: an FI number (annual spending over the withdrawal rate), progress towards it, a derived savings rate and a yearly projection. The design choice to know about: the plan is per user, not per family, because every figure is built from the accounts that user counts in their own finances (Account.included_in_finances_for). No UI in this PR.
What changed
IncomeStatement#median_expensegainsexcluding_kinds:(default[]), passed toIncomeStatement::FamilyStatsas a bound SQL parameter and carried in both the per-instance memo and the Rails cache key, after upstream's*cache_freshness_key. With the default, the SQL, memo key and cache key are unchanged for every existing caller.retirement_planstable (one row per user, uniqueuser_id, cascade on user delete) with a safe withdrawal rate, expected annual return, optional savings rate and optional retirement date, and database check constraints mirroring the model validations.RetirementPlan:.for(user)returns the saved plan or an unsaved one with the column defaults (never writes);*_percentreaders and writers, which refuse input that is not a number rather than reading it as zero;#projection(as_of:);#unconverted_account_count(as_of:).RetirementPlan::Projection: pure arithmetic,V(n + 1) = V(n) * (1 + r) + C. The reference date is an argument; nothing reads the clock, the database orCurrent(a test scans the source for it). Every figure is BigDecimal, including clamped and guarded zeros.- Spending is the median month excluding
investment_contribution(money moved into investments is saving), whatever the family'sinvestment_contributions_as_spendingsetting. Assets are each Depository, Investment and Crypto account's latest balance on or before the reference date, in the account's own currency, converted at that date's rate; an account with no rate is counted out and reported. User has_one :retirement_plan, dependent: :destroy.
Divergence from the fork
The code is the fork's, with these differences:
- Migration history. The fork reached this schema through three migrations over three PRs (
20260928090100,20260928120000,20260928140000). Here each PR in the stack carries one migration with only the columns it uses (20261008150100,...150200,...150300). These are older than upstream's newest migration; Rails runs them by version regardless,schema.rb'sdefine(version:)stays at upstream's newest, and the numbers are kept because the fork-sync step records them. IncomeStatement. Onlyexcluding_kinds:is carried here (period:follows in the next PR). The fork also madeincluded_account_idspublic and moved its digest to SHA-256 for unrelated fork work; not carried.- Comments that cited fork issue numbers, drop numbers or a fork-only page are reworded.
Demo data
No demo data needed: nothing renders a plan yet. The planner page follows after the model has been reviewed.
Migration notes
Creates retirement_plans. No existing table or row is changed. Nothing to run after deploy.
Verification
- 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.db/schema.rbregenerated from upstream's schema plus this stack's migrations; it matches the committed file apart from local PostgreSQL rendering of two upstream constraints.- Each behaviour broken on purpose, one at a time, and the test that caught it (every one a failing assertion, none an exception):
| Mutation | Caught by |
|---|---|
excluding_kinds SQL clause removed | IncomeStatementTest: a kind left out of the median expense...; the excluded and default medians are cached under different keys |
| cache key loses the excluded kinds | the excluded and default medians are cached under different keys |
| cache key loses upstream's freshness segments | a cached median follows the family's investing-as-spending setting (and two upstream cache tests) |
| memo keyed by interval only | a kind left out of the median expense is not counted, and the default still counts it |
| contributions counted as spending | RetirementPlanTest: money moved into investments is saving, not spending |
| Crypto dropped from liquid types | cash, investments and crypto count as liquid and investment assets... |
| balance date not bounded by the reference date | each account counts at its latest balance on or before the reference date |
| currency filter on balances removed | only the balance in the account's own currency counts |
| finance scope widened to the whole family | 6 tests, among them assets count only the accounts the viewer counts in their finances |
| FX at today's rate instead of the reference date's | a balance in another currency is converted at the reference date's rate |
non-numeric percent read with to_d | a percent that is not a number is refused rather than read as zero |
| FI number guard on zero spending removed | ProjectionTest: with no expenses there is no FI number to measure against |
| derived savings rate not clamped | a derived savings rate never goes negative when spending exceeds income |
| clamp to Integer bounds | a zero or clamped rate and amount are still BigDecimal |
| contribution added before growth | a 5% return matches a hand-computed table to the cent for three years |
| part year counted as whole | a retirement date short of a full year counts only completed years |
| bar progress not clamped | the bar stops at 100% while the figure beside it does not |
One mutation survives, by design: removing dependent: :destroy from User#retirement_plan leaves "deleting the user deletes their plan" passing, because the foreign key's on_delete: :cascade deletes the plan as well. The association keeps the delete visible to Rails callbacks; the database guarantees it.
Blast radius
Who else hits these lines, and what do they pass? IncomeStatement#median_expense is called by Budget (twice), Goal#median_monthly_expense, Insight::Generators::CashFlowWarningGenerator and Assistant::Function::GetIncomeStatement; none passes excluding_kinds:, so they get the default []. family_stats is also read by avg_expense and median_income, which pass only interval:. With the default, the cache key array is exactly the one upstream main builds today (the new segment splats to nothing), and the SQL fragment renders as an empty line. IncomeStatement::FamilyStats.new has one caller, IncomeStatement#family_stats. The category path (median_expense(category:)) raises ArgumentError if handed excluding_kinds: rather than silently ignoring it.
What else reads what this changed the reading of? grep -n "family_stats(" app/models/income_statement.rb: median_expense, avg_expense, median_income — the last two deliberately unchanged. category_stats is a sibling with the same shape and is deliberately unchanged: no caller asks for a category median without some kinds.
RetirementPlan reads Account.visible.included_in_reports.included_in_finances_for(user) (the scope InvestmentStatement#investment_accounts uses), Balance, Money#exchange_to and IncomeStatement; it changes none of them.
Feedback sweep 2026-10-13
- 24b2ef600: tests for
median_expense(category:)refusingexcluding_kinds, and for the purity scan catchingTime.zone.now/todayandDateTime.current/now. - The Codacy "Not up to standards" check had no finding behind it: 0 issues and 0 files, with no gate evaluated on the old base.
Adversarial review 2026-10-22
- Rebased onto
mirror/upstream-mainand retargeted (owner decision, 2026-10-23).ed0cc8ec7: keeps upstream'scache_freshness_key, says the plan leaves contributions out whatever the family setting, sets the setting explicitly in the tests that depend on it, and pins it off as well.2c1fa78bb's BigDecimal fix and comments carried over. The reply on this PR lists each finding.
Review fixes 2026-11-22
Head: 2dbefad8e. 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.
d53fec3b7: the migration test expects the column defaults as the strings activerecord 8.1.4.1 reports ("0.04","0.05").c51d378c0: the source scan is replaced by a behaviour test.Projectionruns on two days undertravel_to, insideassert_queries_count(0), withCurrent.userandCurrent.familyexpected never, and must give the same figures; the plan's projection is checked never to readCurrent.2dbefad8e: declined passingas_ofthrough the medians; the comment on#projectionnow saysas_ofdates the balances and planning years while the medians are today's.
- Added
IncomeStatement#median_expense(excluding_kinds:)to exclude selected transaction kinds from family-wide medians. Category-specific requests reject exclusions. - Added a per-user
RetirementPlanmodel and a pureRetirementPlan::Projectionfor FIRE figures. Projections use dated account balances, convert assets using the reference date’s exchange rates, and count accounts without a conversion rate. - Added the
retirement_planstable, validations, database constraints, and a dependentUserassociation. - Added tests for median exclusions, plan settings, account and balance selection, currency conversion, and projection calculations.
- Test and merge readiness results are not established by the supplied evidence.
| Contributing author | Lines added | Lines removed |
|---|---|---|
| jaysbeekay | 918 | 74 |
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.