Size a rate-change resize from the interest its period charged
Summary
Part of #184: the live money bug its comment 5738608741 found ("Item 2 verdict — PRESENT"). The reconciliation plan said phase 3's core swap would remove it; this fixes it directly in the fork's engine, which is where every loan figure is computed today.
The defect. The period a rate change resizes accrued, wholly or in part, at the old rate. A change effective on a payment date sizes that payment but belongs to the next accrual window (C7/C8), and a mid-period change splits the period. The fork sized the new repayment with the plain annuity, which assumes that period accrues at the new rate too. The payment mis-covered it, and the error compounded into the final settlement.
Measured on fork main (300k, 360 months, 4.8% from 2020-01-15, actual/365):
| Change in year ten | Final payment − level, main | This branch | Fresh loan from the change (comparator) |
|---|---|---|---|
| none (fixed) | +423.79 | +423.79 | n/a |
| rise to 6.0% on a payment date | −662.09 | +77.83 | ≈ +81 |
| rise to 6.0% mid-period | −293.84 | +80.77 | ≈ +81 |
| cut to 3.6% mid-period | +344.87 | +39.66 | ≈ +41 |
The fix. Loan::Simulator now sizes a re-amortised segment after the first once its opening period's interest is known. It passes that interest to AmortizationMath.level_payment(first_period_interest:) whenever the period accrued at any rate other than the sizing rate. This is upstream's fix (simulator.rb:166 on mirror/upstream-main), in amortization_math.rb, a file the fork already shares byte for byte and never passed the keyword to. Afterwards the loan runs exactly as a fresh loan on what the resized period leaves: the same repayment (to 2 cents) and the same final settlement (to $2). The residual is only the daily actual/365 drift the annuity can't see.
AmortizationSchedule::ALGORITHM_VERSION moves to 4 (second commit), because the calculation changed (#36's rule). Without the bump, persisted rows would still pass the signature check and display_rows would serve the old rows beside cards computed by the new code (risk R21).
Scope and dependencies
- Issue: #184 (comment 5738608741, item 2 of 5731083328).
- Parent PR/branch, if stacked: none. Base
main. - Intentionally out of scope: the daily-accrual drift itself. A fixed actual/365 loan settles hundreds above level after 30 years; that's the fork's existing behaviour and is untouched. Also out: the core swap (phase 3).
Blast radius. Simulator#run is the single accrual point: the schedule, the payoff projection, the extra-repayment comparison and the API schedule all run through it. What changes:
:reamortizesegments after the first, under daily accrual, without a custominterest_for. That's every variable loan's schedule from its first recorded rate change on.- The first segment is sized exactly as before, so a loan with no change keeps its schedule bit for bit (golden master
fixed,offset,actual_actual,leap_february_start,month_end_start,matured,initial_balance_differs…unchanged). - The
first_period_interestkeyword is passed only when present, so a caller's callable that doesn't accept it keeps working (two strict test lambdas exist). - The version bump restages every persisted schedule, fixed loans included, to identical figures for them.
Siblings (grep -rn "payment_amount_for:\|level_payment(" app lib):
AmortizationSchedule#calculate_segment_paymentandPayoffProjection's:reamortizesizer both forward the interest. The projection had the same straddle; its own test is below.:holdsizes once and is unaffected.Loan#current_minimum_payment(onmain) andUI::Loan::RateChangeTablecalllevel_paymentfor a quote, not inside a simulation, so there is no period interest to pass. #394 removes both calls anyway.lib/tasks/loans.rake's benchmark has a single rate and is unaffected.LoanScenario#calculator_versionrecords the version; scenarios are dormant by decision.
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.
- Any gate test has an observed failing mutation transcript attached.
- Fixtures used as evidence assert internal consistency.
- Financial calculations use
BigDecimaland documented rounding points. - De-identification uses token-shape allowlists; no personal data is included.
- Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.
test/models/loan/straddled_resize_test.rb, run against the unfixed engine first (3 failures, the negative passing):
| Test | Unfixed |
|---|---|
| a resize on a payment-date change is sized from the interest that period charged | 1,738.53 ≠ 1,736.93 |
| a resize on a mid-period change is sized from the interest that period charged | 1,738.53 ≠ 1,737.72 |
| after a resize the loan runs as a fresh loan on what the resized period leaves (three schedules: repayment within 2 cents, settlement within $2 of a fresh loan from the next period on the resized row's ending balance) | fails by hundreds |
| a re-amortising projection sizes a resize from the interest that period charged | added after; fails with the projection sizer reverted (mutation) |
| a loan with no change is sized with the plain annuity (negative) | passes on both |
Changed tests, with reasons
- "characterization golden master covers variable rate rows with two changes":
- Row 2 now sizes 334.99, from (666.67 + 0.00) / (1 + 0.990099), for a 12% annuity over the one later payment.
- Row 3 settles 335.06, seven cents off level, where the plain annuity had 338.34 and 331.68.
- The arithmetic is in the test's comment.
- "the persisted schedule accrues daily, and the algorithm version says so": pins version 4 and says what it means.
Golden master (LOAN_GOLDEN_MASTER_WRITE=1, then re-run clean). Only the two rate-change files move, both from their first resize (payment 14):
| File | Change |
|---|---|
variable_change_mid_period.json | schedule total_interest 310,534.55 → 310,403.36; final payment 2,583.64 → 2,281.51 (level 1,670.66) |
variable_change_on_payment_date.json | payoff_date 2053-12-15 → 2054-01-15: the contracted schedule used to finish a month before its own maturity, because the over-sized payment cleared it early; it now runs its 360 payments. total_interest 446,465.89 → 449,488.22. Final payment 3,747.73 against level 2,087.74: +1,659.99, exactly what a fresh 7.5% fixed loan on the same balance over the same 346 months settles at (checked). |
Projection and current_minimum_payment are unchanged in both files.
Mutations, restored from copies:
- simulator and schedule reverted to
main: the 3 tests above fail; - the projection's sizer passes
nil: the projection test fails.
Contract manifest test: green (the C11 anchor payment = if payment_strategy == :hold is kept).
Validation
github-advanced-securityfails on every push (job 114439155056 on7e1e77dca). It is GitHub's Copilot code-scanning job, and it stops before analysing anything with402 You have exceeded your monthly quota(errorType: 'quota'). That is account-side, not this change, and a re-run fails the same way until the quota resets.- Loan, loans/accounts/API controller, loan component, task, job and retirement-plan suites: 840 runs, 0 failures.
bin/rubocopon changed files: no offenses.- Checked against upstream
AGENTS.md.
Review findings
-
"code master" review (comment 6105940181), BLOCK, on
c16d21a: every finding as written is declined. One narrower gap inside finding 6 is real but not a regression, and it was decided on 2026-10-11: left to #405 (Risks). A stale doc line the review didn't raise is fixed in7e1e77dca, pushed on the owner's instruction (2026-10-11: "Push the held commits; go with your recommendations").- The version bump forces full regeneration with no migration: declined.
- Opening a page rebuilds nothing in the request:
display_rowsreturns unsaved rows from the simulation the cards already run (amortization_schedule.rb:169-186), and the controllers only queue the deduplicatedLoanAmortizationRebuildJob. - The rollout path is
loans:rebuild_scheduleswithloans:schedule_version_status(release-evidence.md:240-300), and Deploying below says to run it.
- Opening a page rebuilds nothing in the request:
- A deferred
payment = nilescapes the loop: declined.- The break (
simulator.rb:106) is each pass's first statement, so a pass that breaks never reachesstep. A pass that continues always sets the payment (161-169) beforeAmortizationMath.step(171). - Five temporary edge cases ran clean: the resize as the last payment; paid off before the resize; a custom payment clearing it; an extra clearing it in the opening period; the iteration limit.
- The break (
- The
@interest_for.nil?guard leaves those callers on the old behaviour: declined. No production caller passesinterest_for(amortization_schedule.rb:289,payoff_projection.rb:452,lib/tasks/loans.rake:204); onlysimulator_test.rbdoes. The guard is needed, because the check reads the accrual rate only the daily branch tracks. opening_accrual_ratecan be nil: declined.paymentis nil only on the daily, no-interest_forpath, where line 136 always sets the rate first.- Golden-master changes unexplained: declined. The table above explains both.
variable_change_on_payment_date.jsonnow ends on its maturity date, where the old file finished a month early. - No edge-case tests: mostly not worth its code (a generic list; the cases in 2 behave correctly). One part is real: a rate change inside the loan's first period is not straddle-sized. See Risks.
- No rollback strategy: declined. A rollback was rehearsed and recorded (
release-evidence.md:216-234).
Not raised by the review; fixed in
7e1e77dca:release-evidence.mdstill saidALGORITHM_VERSIONis3. It now says4, notes that G2a was signed at3, and points to the required prebuild. - The version bump forces full regeneration with no migration: declined.
-
Nightly review (comment 6120543262), READY WITH CONDITIONS, on
7e1e77dca: no blocking findings.- MEDIUM, first-segment rate changes remain wrong: agreed. It stays visible under Risks, as the review asks.
- The check it asks for, on #405's engine, now run (a temporary probe on
24746641d, using this PR's helper loan: 300k, 360 months, 4.8% from 2020-01-15):- A change to 6.0% on the first payment date: the first payment is 1,797.00. That is the straddle-sized figure, against 1,798.65 from the plain annuity. The final payment ends +531.08 over level, against the +531.20 "fresh loan" figure in Risks.
- A change mid first period: the first payment is 1,797.82, again the straddle-sized figure, against 1,798.65 plain.
- So the schedule's first-period case is fixed on #405, as recommended.
- Not probed: the projection's own first period (the 1,845.37 / 1,844.34 case). On #405 the projection pays the schedule's repayment period by period rather than sizing its own (#100 decision 1, #401), so it reads that already-fixed row. A test pinning the projection's figure is not part of #405 yet.
- MEDIUM, deployment ordering: agreed; already under Risks ("Deploying"). The prebuild is in
docs/loans/release-evidence.md. #405 then moves the version to 5, which needs the same prebuild.
Review responses are recorded here rather than as comments, because comments posted from this session get an assistant footer appended, which this repository's attribution rule forbids.
Risks, blockers, and follow-up
-
Deploying: run
bin/rails loans:rebuild_schedulesafter the deploy (the prebuild indocs/loans/release-evidence.md), thenbin/rails loans:schedule_version_statusto confirm. Without it, read paths enqueueLoanAmortizationRebuildJobper loan and show in-memory rows until the job runs, which is correct but slower on first view. -
The fork's daily actual/365 drift, now visible in the comparator column, is a separate, pre-existing property and not addressed.
-
The first period isn't straddle-sized (from the "code master" review, finding 6). Decided on 2026-10-11: left to #405, as recommended below.
simulator.rb:95-96adds&& segment_index.positive?, so the first segment always takes the plain annuity, even when its first period accrued at another rate.- On this PR's helper loan, a 6.0% change on the first payment date pays 1,798.65 against 1,797.00 straddle-sized, and the final payment ends 1,127.85 short of the level payment, where a fresh loan's ends 531.20 over.
- The bigger exposure is the payoff projection, whose first segment starts today. A newly announced change before the next payment hits exactly this case: 1,845.37 paid against 1,844.34.
- It is not a regression.
main's files give identical numbers. - The fix is not one line. Removing the guard fixes the rows, but
amortization_schedule_test.rb:191pins the contracted monthly payment card to the first row throughAmortizationSchedule#monthly_payment's plain annuity, so that method would have to change in the same commit. - #405 already handles it: upstream's engine sizes the first period from its actual interest when the rates differ, and #405 has no fork
monthly_payment.