Show how far a user is from financial independence (#127, 8.1)
Summary
8.1 of #127: the simple FIRE tier. It follows the triage plan, and #127 stays open until 8.4.
Before this PR, Sure couldn't tell a user how far they are from financial independence.
After it, a Financial independence card on /plan and a section on /portfolio show:
- FI number = annual spending ÷ safe withdrawal rate. Annual spending is 12 × the median monthly spending, not counting money moved into investments (
103ccd94). - Progress = cash and investments ÷ FI number. The bar stops at 100%. The figure beside it keeps the true value, for example "Financially independent · 112%" (review finding 7).
- Projected total at retirement: annual compounding with the contribution at year end,
V(n+1) = V(n)(1 + r) + C(review finding 1). The contribution is savings rate × annual income. With no saved savings rate, it is derived from income and spending and clamped to 0–100%. - A compound projection chart on
/portfolio, with the FI number as a flat line. - A settings form (a modal) for the withdrawal rate, expected return, savings rate and retirement date.
Whose figures: everything is the viewer's own. It is built from the accounts they count in their finances, using the same scope /portfolio uses. Settings are stored per user. These are decisions A and B in the triage plan.
Commits, in the seam order #118 asks for
| Commit | Layer |
|---|---|
7aad2129 | Schema and model: retirement_plans (one row per user, DB checks mirror the validations), RetirementPlan, User has_one |
b38e1073 | Engine: RetirementPlan::Projection, pure, with the reference date injected |
c56386f4 | Inputs: RetirementPlan#projection(as_of:), which reads balances as of the reference date, the FX rate on that date, and IncomeStatement medians over an explicit account scope |
2bfb9a91 | UI: route, controller, form, RetirementPlans::SummaryComponent, the /plan card, the /portfolio section, and locales |
54eb7c3c | CodeQL fix: IncomeStatement#included_account_ids_hash uses SHA-256 instead of MD5 (see Blast radius) |
44db7513 | Review fix (CodeRabbit): a percent that is not a number is refused, not read as 0% (see Validation) |
103ccd94 | Fix: investment contributions count as saving, not spending, in the FI number (see Validation) |
Every commit except the fourth is upstream-bound model layer. The fourth is UI, held for Phase C. Merge with a merge commit, not a squash, so the seam survives.
Where this differs from the triage plan
- The account scope is
visible.included_in_reports.included_in_finances_for(user), notaccessible_accounts. It is exactly whatInvestmentStatement#investment_accountsuses, and it is stricter: an account shared with the viewer but not counted in their finances doesn't count here either. A test covers that. - The chart is the time-series chart's multi-line mode, not
goal_projection_chart_controller.js. The goal chart draws a straight-line pace (avg_monthly × months), which would misstate a compound projection. The multi-line mode already takes[{ label, values }], so there is no JavaScript change. - The
/portfolioquery ceiling moves from 93 to 101 (measured 95, plus the same 6 of headroom). The section adds a fixed set of reads per request: the plan, oneDISTINCT ONbalances query, and one IncomeStatement median with the account-id lookups it always makes. None of it grows with holdings or accounts. The ceiling's comment records this, alongside the two earlier rises. - Known limitation, not new:
IncomeStatement#median_expensetakes the median over all months on record, not months up toas_of. It never reads the clock, but a future-dated transaction would count. Changing that is a change toIncomeStatementfor every caller, so it isn't done here. IncomeStatementchanges twice, although the plan said it would not change: CodeQL required the digest change (54eb7c3c), and the spending fix needs an optionalexcluding_kinds:onmedian_expense(103ccd94). See the Blast radius table.
Scope and dependencies
- Issue: #127 (8.1 only)
- Parent PR/branch, if stacked: none. Branched from
mainat7d1a359e. - Intentionally out of scope:
- 8.2: phases, inflation, solving for the earliest FI age.
- 8.3: Monte Carlo. 8.4: milestones, funding order and tax.
- An expected-return default taken from realised TWR (#121, optional per the issue).
- Bounding IncomeStatement's median by date (limitation 4 above).
Blast radius
| Caller | Change |
|---|---|
PortfoliosController#update_preferences | Its allow-list is SectionRegistry::KEYS, which gains retirement. The section can be dragged and collapsed, and a saved order from before it existed still shows it. Both are tested |
User#default_portfolio_section_order | Reads KEYS, so retirement is appended |
PlansController#show | Captures one as_of, and now also resolves the budget from it (was Date.current, the same value). It builds one plan and one projection |
User destroy | has_one :retirement_plan, dependent: :destroy, plus on_delete: :cascade on the FK. Tested |
IncomeStatement | Called with user: and an explicit accounts:, as the Goals months-of-expenses reserve does. median_expense gains an optional excluding_kinds: (103ccd94); with the default, SQL, memo and cache key are exactly as before, and every test file that touches IncomeStatement passes (542 runs with the plan and portfolio controllers). One line changed (54eb7c3c): CodeQL flagged the MD5 of account ids in included_account_ids_hash (high: weak hash on sensitive data) once this PR added a new caller. It is only a segment of Rails cache keys (family_stats, category_stats, totals_query, the daily series), so it now uses SHA-256. A rolling deploy that mixes the two digests keeps separate cache entries, each correct. Nothing needs two processes to agree on it, unlike the advisory-lock keys #245 kept on MD5. income_statement tests, goal_test, retirement_plan_test and plans_controller_test: 202 runs, 0 failures |
| Existing tests changed | Only those that pin the section key list (section_registry_test, six tests; portfolios_controller_test, one; user_test, one test with two assertions), which each get retirement appended, and the query ceiling above. No assertion was weakened |
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. P35's four tests were edited (the key list) and keep their names.
portfolio:verify_contract_coveragereports 41 methodology and 18 returns rows verified, andloans:verify_contract_coveragereports 16. - 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 first, so every figure is made only of what the test adds.
- Financial calculations use
BigDecimaland documented rounding points. Everything isBigDecimaluntil display. The chart rounds to cents, and cards round to whole units. - 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 and model: tests written first against stubs returning nil or 0. 16 of 23 failed on their assertions. The 7 that passed were covered by the schema already in place (column defaults, the unique index, the DB check, the FK cascade) or by the stub itself (the clock scan).
- Inputs: 8 of 8 new tests failed on assertions against a stub, for example
Expected: 1000, Actual: 0.0. - UI: the controller and view tests were written before the UI code. Against that commit they error on the missing route. That is not an assertion failure, so the mutations below are the evidence for them.
Mutations, each applied to the finished code and caught:
| Mutation | Caught by |
|---|---|
| FI number = expenses × SWR | 3 engine tests |
| progress inverted | 2 |
| bar not capped at 100% | engine bar test; view "past independence" |
| progress figure capped | view "past independence" (shows 100% not 112%) |
| start-of-year contribution (gives 148,863.75) | "5% matches a hand-computed table to the cent" |
| monthly compounding | same |
| no guard for zero spending | "no expenses gives no FI number" |
| derived savings rate not clamped | "never goes negative" |
| partial years counted as whole | "short of a full year counts only completed years" |
Date.current read in a method body | "nothing reads the clock or the current request" |
| family-wide account scope | 4 input tests, including the finance-share and spending ones |
visible dropped / included_in_reports dropped | disabled-account test / excluded-account test |
| account-type filter dropped or widened (cards, loans, property) | "cash, investments and crypto count; cards, loans and property do not" |
no date <= as_of bound / earliest not latest balance | "latest balance on or before the reference date" |
FX at today, not as_of | conversion test (a later rate of 2.0 is present) |
| balance currency not matched to the account's | "only the balance in the account's own currency counts" |
| IncomeStatement without the explicit scope | disabled-account spending test |
| unconverted accounts not counted | "left out, and the plan says how many" |
| SWR validation loosened | validation test |
RetirementPlan.for writes a row | "defaults, and nothing is written" |
plan chosen by a submitted user_id | "a user id in the request is ignored" |
| percent not divided by 100 / blank percent read as 0 | the save test |
retirement missing from KEYS | "can be dragged and collapsed like the others" |
| section hidden / card not rendered / always the empty state | the view tests |
| preview gate removed | "a user without preview access is turned away" |
Review fix 44db7513 (CodeRabbit, retirement_plan.rb): String#to_d reads "abc" as 0, so a non-numeric savings_rate_percent was saved as an explicit 0%, which switches off the derived rate. The percent setters now parse with BigDecimal(..., exception: false), keep the value already held, and add not_a_number (Rails' own message, no new string) on the percent field. Tests, both failing before the fix: a percent that is not a number is refused rather than read as zero (the plan was valid) and a savings rate that is not a number is refused and nothing is written (a row was written). Mutations caught: not clearing the flag on a later valid entry (the model test), and dropping the validation (both tests). Neighbouring suites: 259 runs, 0 failures; rubocop and brakeman clean.
Fix 103ccd94 (found on self-review): investment contributions were counted as spending. IncomeStatement classifies investment_contribution as expense (ScopedTransactionsQuery#classification_sql), which suits a budget. The FI number took that median, so spending 1,000 a month and investing 2,000 gave 36,000 a year of spending instead of 12,000: the FI number three times too high and the derived savings rate too low. IncomeStatement#median_expense gains excluding_kinds: (default empty, so every other caller is unchanged; bound as a SQL parameter; part of both the memo and the cache key), and RetirementPlan passes investment_contribution. Loan payments stay in: until a loan is paid off they are a real outgoing, and 8.2 end-dates them. Tests: money moved into investments is saving, not spending failed first (Expected 12000, Actual 36000); two IncomeStatement tests pin the default and the cache keys (one swaps in a memory store, since the test cache is a null store). Mutations caught: plan not excluding, memo key without kinds, cache key without kinds, SQL filter dropped. Every test file that touches IncomeStatement, plus the plan and portfolio controllers: 542 runs, 0 failures; rubocop and brakeman clean.
Two tests were tightened when a mutation survived. The two-currency test tied on date, so DISTINCT ON picked a row arbitrarily; the foreign row is now dated later. The spending-scope test now uses a disabled account, because the IncomeStatement SQL already drops accounts excluded from reports.
Commands:
bin/rails test test/models/retirement_plan_test.rb test/models/retirement_plan test/controllers/retirement_plans_controller_test.rb: 44 runs, 0 failures. With the neighbouring suites (section_registry,plans_controller,portfolios_controller,user,i18n): 213 runs, 0 failures, and 4 skips, which are in files this PR doesn't touch.- Full
bin/rails testat2bfb9a91: 10,690 runs, 46,771 assertions, 4 failures, 3 errors, 33 skips. All 7 are the known local Ruby 3.3.6 environment failures, the same set as onmain: ActiveStorage variants, the admin profile picture, OpenAIextra_headers, the Registry anthropic ENV test, and HostingsController anthropic ×3. Nothing else fails. bin/rubocop(16 files): no offences.erb_lint(6 files): clean.bin/brakeman: no warnings.db/schema.rbwas regenerated by running the migration on a throwaway sandbox database, since dropped. One unrelated constraint re-format from the dump was reverted, so the schema diff is only the new table.
Checked against upstream AGENTS.md:
- Logic lives in models and POROs, and the controller is thin.
Current.useronly; tenancy is preserved, with the plan per user inside the family.- Migration version 8.1. Minitest and fixtures.
- DS primitives:
DS::Card,DS::Dialog,DS::Link. Only functional tokens; theiconhelper; every string throught(). - The preview gate follows
gating-a-preview-feature.md: the controller hasrequire_preview_features!, and both host pages are already gated. - No new dependency and no JavaScript change.
Screenshots: taken with demo figures (spending 3,500 a month, income 6,500 a month, 420,000 in assets, 6% return, retiring in 15 years), and shared with the owner in the session. Because this is UI held for Phase C, the upstream UI PR will carry them.
/plan: the card under the budget and goals cards: FI number $1,050,000, 40% of the way, $1,844,489 projected at retirement, 46.2% savings rate (derived)./portfolio: the section with the same figures, and the projection line crossing the FI line in about year 10.- The settings modal.
Risks, blockers, and follow-up
- The median is all-history, as noted above. A follow-up could bound
IncomeStatement's medians by date for every caller. - Next: 8.2's triage plan. Tax is deferred to 8.4 (owner decision, 2026-09-28). The remaining 8.2 and 8.3 design questions await owner decisions before that plan is posted.
- Upstream: every commit except the fourth forms the model slice for a later upstream PR, pre-flighted against
mirror/upstream-mainwhen it is cut.
Summary by CodeRabbit
- New Features
- Added a financial independence summary to the plans page and a financial independence section to portfolios, with progress, savings-rate details, and optional projections.
- Added settings to update withdrawal rate, expected return, savings rate, and retirement date.
- Shows a warning when some accounts can’t be included because their currencies can’t be converted.
- Provides guidance when expenses aren’t available and excludes investment contributions from expense calculations used for projections.
- Bug Fixes
- Uses a consistent reference date for plan projections and budget calculations.