Run loans on upstream's engine behind one interest hook (#184)
Summary
Part of #184: phases 3, 4a–4g and 6 of the owner's 2026-09-30 plan (direction C: upstream's engine as the core, fork features behind adapters, one extension point on Loan::Simulator).
Stacked on claude/loans-integration-base, which holds #404's state before this change (every other open loan PR merged) plus #404's two CI-image commits (now also on main as 513ee49c6, so they drop out of this diff once it is retargeted), so this diff is the swap alone. #404's branch carries these commits too, so a container built from #404 runs on this engine. Retarget to main once the other loan PRs land.
The fork's loans now run on upstream's engine. simulator, amortization_schedule, rate_resolver, simulation_result, payoff_projection and payoff_chart are upstream's; rate_resolver, simulation_result and insurance.rb are byte-identical. Fork behaviour reaches them through:
- The one hook:
Simulatortakesinterest_for:, asked once per period with the opening balance and rate; the simulator rounds its answer once. Without it, upstream's one-twelfth charge runs, and a test runs both ways to the same figures.AmortizationSchedule.for(loan, interest_for: …)passes it through and defaults to the loan's own (a departure beyond the single Simulator seam, stated here);nilgives upstream's monthly run, which the variance rake task and two tests use. Loan::DailyInterest(4a/4b): the adapter overInterestAccrual(actual/365, actual/actual, 30/360, actual/360), carrying event order, half-open windows, offsets and scenario repayments. A 30/360 loan equals upstream's schedule row for row; a fixed actual/365 loan equals the golden master to the cent.Loan::PayoffProjection::ForkAdapters(phase 6): the fork's projection behaviour (#401's:scheduledrepayment, holding the last level repayment past maturity, the extra series) sits outside upstream's file, which now differs only at marked seams.
| Phase | What |
|---|---|
| 3 | Core swap; one as_of reaches Loan#payoff_projection, #next_rate_change_date and OffsetResolver (the three Date.current readers #184's 2026-10-01 note named), tested with a date other than today |
| 4a, 4b | Day count and offsets through DailyInterest |
| 4c | current_minimum_payment and UI::Loan::RateChangeTable on upstream's rows; #392's rule kept (a payment due on as_of has been made). Since 22e65fb03, the caption rate and the table's current rate are the rate that payment is sized at (#394's option A, ported; see "Base refresh" below) |
| 4d | No processor change needed: current_variable_rate goes through RateResolver; Plaid, Redbark and the rule action stay green, and removing the "unchanged rate" check fails 6 of their tests |
| 4e | Persisted rows written by Loan#amortization_rows from upstream's Payment rows; ALGORITHM_VERSION moves to LoanAmortization, 4 → 5; the API answers for one date and reports a projection only when it clears the loan; rswag stays docs-only |
| 4f | The Extra repayments tab and the chart's extra series on upstream's projection |
| 4g | RetirementPlan#seed_loans on the public PayoffProjection#monthly_payment (the payment in force now, as settled on #401), pinned for fixed, past-rise, future-change and never-clears loans |
| 6 | Fork-only engine code replaced by the adapters removed; Loan.monthly_rate gone; payment_ratios on upstream's signature |
git diff --stat origin/mirror/upstream-main HEAD -- app/models/loan.rb app/models/loan/:
| Files | + | − | simulator | amortization_schedule | payoff_projection | |
|---|---|---|---|---|---|---|
| Before | 14 | 3,119 | 841 | 478 | 496 | 720 |
| After | 13 | 2,188 | 281 | 39 | 19 | 51 (+221 in the adapter) |
loan.rb still differs by 1,259 lines: fork features outside the engine (collateral, offsets, the rate-change form, providers, persistence), untouched here.
Base refresh (fc3ea844f, 2026-10-13)
fc3ea844f merges the base at 0a889657b. The merge was clean and has no engine change. The owner approved the follow-ups on 2026-10-13.
- #400 (
636f3fa3b,965f4267e,2e186c335):- The rate-change parser refuses movement wording such as "Rate increase 0.25%" unless a marker names the new rate. Before, it recorded a 0.25% rate.
- "your rate is X%" is read as the new rate, except after a movement noun or a qualifier naming another rate. The owner decided to keep the second exception.
Loan#enrich_reporting_refusalgets direct tests.
- #402 (
e28db9b73): a test that a new principal reprices the memoised insurance premium. On this engine it still fails wheninitial_balance=stops clearing the cache (expected 288, got 144). - On the base,
e345685acresolved a conflict intest/models/loan_test.rb's private helpers by keeping both sides. - Checks:
- migration, loan, insurance, rule and loans-task tests: 671 runs, 0 failures, 0 errors;
- full
bin/rails teston #404's head16f59b96d, which carries this: 12,687 runs, 0 failures, 0 errors, 33 skips.
Offset fix (51a2d260b, 2026-10-12)
The owner's instruction (2026-10-12): "Fix the offset slowdown in #405". It came from measuring the nightly review's page-load finding on #403.
-
The defect. The payoff projection asks one
Loan::OffsetResolveronce per period. Each future period re-ran the offsets' existence check and today's total. The query cache answered them, but building each query cost about 1.6 ms. -
Profiled on #404's head: on a 360-month variable loan with two offset accounts and ten years of daily balances, one loan page made 720 resolver calls and 1,449 cached queries, and spent 1,167 ms of 1,744 ms in the resolver. The interest arithmetic itself took 50 ms.
-
The fix. Within one projection the linked accounts and today's total are fixed, so the resolver now checks the accounts it already loads and keeps the total. Historical ranges still read their balances per call.
-
Measured on that loan, one fresh request each, median of three:
mainbefore after 0 offsets, before Overview 0.48 s 1.74 s 0.56 s 0.61 s Schedule tab 1.99 s 1.88 s 0.71 s 0.84 s resolver per page 1,167 ms 4 ms On #404's head after all merges (
d838e0336): 0.56 s Overview and 0.78 s Schedule tab. -
Test: "resolving many future periods reads the offsets and today's total once", over 60 periods.
- It failed first with 121 queries.
- Re-querying the total (61 queries) or re-checking existence (62) each fail it.
-
Checks:
- Loan model, loans and accounts controller and component suites: 579 runs, 0 failures.
loans:verify_contract_mutations[C3,C15,C16]: all caught.
-
Callers:
OffsetResolver.newhas one caller, the projection's offset source (fork_adapters.rb), which builds one resolver per projection. -
Sibling: #403 had the same per-period checks on the fork engine and is fixed there too (
5732ec466), at the owner's instruction. Merging it here (a344aaa25) left the model unchanged; only the new test's comment conflicted, and this branch's was kept. -
The longest loans: a 1,200-month loan with the same offsets takes 2.2 s on the Overview, against 1.57 s on
main. That cost is upstream's simulation over 1,200 periods, and it is the same without offsets (2.38 s).
Base refresh (185130824, a344aaa25, 2026-10-12)
185130824merges the base at449dd5713, which carries #394's softened minimum-payment caption (16a034187, nightly review; owner's instruction "soften the caption"). The caption now reads "The next repayment your loan's schedule sets, sized at %{rate}. Paying ahead or an offset doesn't change it."- The en, ru, tr and uk loan locales conflicted, because the base changes that line beside the
recalculatingkey this branch removed. Resolved by taking the new caption and keeping the removal. - Caption, i18n, loan and component tests: 514 runs, 0 failures.
- The en, ru, tr and uk loan locales conflicted, because the base changes that line beside the
a344aaa25merges the base atf546ab01b, which carries #403's offset fix (above).- Checks on #404's head
d838e0336, which carries both:- full
bin/rails test: 12,673 runs, 1 failure (the knownProvider::OpenaiTeststring); loans:verify_contract_mutations: 16 rows and 18 mutations, all caught.
- full
Base refresh (24746641d, 2026-10-12)
This branch merges the integration base at f4bb52c52, which carries three nightly-review fixes. The merge was clean, and nothing in this PR's own files changed:
- #397 (
031824d3e) and #398 (a6af757e4): the day-count migrations' rollback now refuses while a loan is on 30/360 or actual/360, instead of moving those loans to actual/365. - #400 (
f21a14a7f): the rate-change parser refuses "Rate change 0.25%"-style wording unless a marker names the new rate.
Checks on 24746641d:
- Migration, parser, rule-action and loan tests: 156 runs, 0 failures.
- On #404's head
6836ad49d, which carries this merge:- full
bin/rails test: 12,671 runs, 1 failure (the knownProvider::OpenaiTeststring); loans:verify_contract_mutations: 16 rows and 18 mutations, all caught.
- full
Base refresh (ddff3639a, 22e65fb03)
The base (c13ca9a17) now carries the reviewed fixes from #393, #394, #397, #398, #399, #400, #401 and #403, and this branch has merged it. Resolutions:
- #394's option A is ported, not taken as written. The base reads
AmortizationSchedule#payment_row_in_force, which this engine doesn't have.Loan#scheduled_payment_in_force(as_of:)now names the paymentcurrent_minimum_paymentquotes: the first due afteras_of, this PR's #392 rule.Loan#minimum_payment_rateand the rate-change table's "already resized" cut both read it.- The rate is
current_variable_rateon that payment's date, which is the rateSimulator#rate_onsizes it at. - Fail first: with the rate as today's and the table as it was here, #394's three incoming tests fail: 6.43 expected and 5.5 given; the already-resized change still listed; the caption on both tabs.
- Mutations, each caught: rate read on
as_of(3 failures); no in-force skip (1);<for<=in the skip (1);>=for>in the in-force lookup (2); the table's current rate back to today's (1). - A fixed-loan guard on the lookup survived its mutation, because a fixed loan has one rate on every date. It was removed rather than kept untestable.
PayoffProjectionand its test keep this PR's rewrite. The base's changes there (#401's sharedPAYMENT_STRATEGIESlist and the strategy comments) concern strategies this projection no longer has.- Locales take #394's caption copy, and keep this PR's removal of the unused
recalculatingkey. release-evidence.mdkeeps theALGORITHM_VERSION5 text.- Contract row C2 takes #397's wording: loans created after #188 start on
thirty_360, and part months are split by elapsed actual days. Checked against this branch:db/schema.rbdefaultsday_count_conventiontothirty_360, andInterestAccrual#thirty_360_interestscales a part period bydays / period_days.
Scope and dependencies
- Issue: #184 (phases 3, 4a–4g, 6). Phases 0, 1 and 2 are #277 (merged), #396 and #402; 4a's migration is #397.
- Parent branch:
claude/loans-integration-base(#404 before this change). - Intentionally out of scope: fork features outside the engine in
loan.rb; proposing the hook upstream (#184 open question 2, still open).
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.
Step 1 of #184, measured.
- Baseline on the integration branch: 1,127 loan-related runs, 0 failures.
- With upstream's six engine files dropped in verbatim: 5 failures and 359 errors.
- The errors: 292, plus 21 template errors, from the missing
ALGORITHM_VERSION; 20 from the fork's simulator keywords; 8 frompayment_strategy:; 7 frommonthly_equivalent. - Worst hit: AmortizationSchedule 48, PayoffProjection 46, AccountsController 37, PayoffChart 33, Simulator 24.
- The errors: 292, plus 21 template errors, from the missing
- With
Loanpointed at upstream's.for, the real API gap was 328 errors: 90 hash-row reads onPayment, 42payment_count, 38variable_ratesreturning strings where the resolver expects dates, 37eligible_for_extra_payment?, and smaller groups. - Upstream's own tests in that state: 133 runs, 8 failures, 64 errors.
Golden master. 4 of 9 scenarios move (+6,639 / −6,599 lines); fixed, offset, actual_actual, matured and initial_balance_differs_from_first_valuation do not. Re-run without LOAN_GOLDEN_MASTER_WRITE: passes.
| Scenario | What moved, and why |
|---|---|
variable_change_on_payment_date | row 14 interest_rate 7.5 → 6.0: the column now holds the rate the period opened on. No money figure changes. |
variable_change_mid_period | rows 14 and 30 interest_rate 7.5 → 6.0 and 5.25 → 7.5, same reason. No money figure changes. |
month_end_start (drawn 31 Jan) | Payments now fall on 31 Mar / 30 Apr rather than staying on the 29th (upstream's calendar): the 31 Mar period gains two days (+98.51), the final settlement +699.07, total interest 347,353.53 → 348,052.60, payoff 2054-01-28 → 2054-01-31. The projection's first period now opens on 31 Dec 2026 and is charged in full on today's balance, not a stub from 15 Jan: first interest 609.04 → 1,452.33, payoff 2053-04-30. |
leap_february_start (29 Feb) | From March 2025 payments return to the 29th, one more day (+48.71); final settlement +258.97; total interest 348,035.08. Projection opens 29 Dec 2026, payoff 2053-04-29. |
Mutations, each restored from a backup and checked with cmp:
- 26 of 27 adapter and hook mutations caught. They cover:
- the hook ignored, the default formula, the straddled resize on the hook's interest, the schedule passing the hook;
- day count, offsets, the 30/360 step,
OffsetResolver's date, the window past maturity; - level and settlement payments, extra payment, projection offsets, scenario principal, the projection hook;
- the chart's extra series and convergence gate, the minimum-payment boundary, the rate-table row, cached rows' rate, the markers;
- the provider "unchanged rate" check, the API and extra-tab gates,
variable_ratesparsing, the max-term guard.
- M27 (max-term guard) survived at first, since validation and a constraint make it unreachable for saved loans; a test now sets an unsaved term.
- M03 survives: moving where the hook's interest is rounded is invisible in the rows, because the amortisation step rounds interest again. It is treated as equivalent; the C3 contract mutation is the one that bites.
loans:verify_contract_mutationspasses for C1–C16, andverify_contract_coveragepasses.51a2d260badds two more: the resolver re-querying today's total, and re-checking existence per period. Both are caught.
Validation
- CI on
22e65fb03:ci / test_unit,ci / test_system,ci / lint,ci / lint_js,ci / scan_rubyandci / scan_jsall pass. Before that, CI was green on64b017f94. On the earlier headebb159e83those jobs died at "Initialize containers" because Docker Hub refused the runner's anonymouspostgres:16pull (toomanyrequests); no test ran. The base carries the two commits pointing CI's service images and the Codacy CLI atpublic.ecr.aws/mirror.gcr.io(the same official images). - CI on
a344aaa25: theci /jobs are green, after one re-run ofci / test_unit.- The failure: the first attempt failed at the "Loan daily-accrual performance gate" (
loans:amortization_benchmark), with p95 239 ms against the 200 ms ceiling, before any test ran. - Why it wasn't the code: nothing on the gate's path changed.
Loan::Simulator,Loan::DailyInterest, the rake task and the workflows are byte-identical to24746641d, where it passed, and the benchmark never reachesOffsetResolver. Alternating runs on one machine gave p95 206 / 238 / 240 ms for24746641dand 211 / 245 / 221 ms fora344aaa25;maingave 250–257 ms there. - Why a re-run:
ci.yml's calibration note puts the gate at p95 93–127 ms on GitHub's runners, and says a reading near the ceiling is the runner's until a second run agrees. The step took 26 s, against 14 s on the last green run. - The re-run passed, with the step at 13 s. #415's
ci / test_unitat95ff79e4c, which runs the same gate on this code, passed on its first attempt. - Codacy Static Code Analysis shows "action required" again, as described below.
- The failure: the first attempt failed at the "Loan daily-accrual performance gate" (
- Local, on
22e65fb03:- full
bin/rails test: 12,620 runs, 1 failure (the knownProvider::OpenaiTestRuby 3.3 vs 3.4 string; passes in CI); loans:verify_contract_mutations: all 16 rows pass unmutated and fail under their mutation;- loan system tests in headless Chromium: 12 runs, 0 failures;
bin/rubocopon the changed Ruby: no offenses.bin/brakeman: 0 warnings.
- full
- Earlier, on
64b017f94: system tests (loan_overview,loan_payoff_chart,accounts) 20 runs, 0 failures;bin/rubocopon 46 changed files: no offenses;erb_lint: clean; API consistency check: OK. No JS changed. - The container: #404's head
ae9292a17carries this PR's code plus the build-verification workflow. There the repository'sDockerfile, unmodified, builds; the image starts through its entrypoint against an empty database; the demo user creates a variable mortgage through the new-loan form and records its rate changes, down payment and insurance through the edit form; and all 31 loan checks pass (run 37997122962). - Two checks are not green, and neither failure is in the code:
github-advanced-securityis GitHub's Copilot "code scanning AI findings" job. It stopped with402 You have exceeded your monthly quotaon the account.- Codacy Static Code Analysis reports "action required", with an empty "Not up to standards" summary and no issues listed. It is not a code finding. Checked through Codacy's public API on 2026-10-13:
- The commit analysis for
61f57c2cdhasquality.isUpToStandards: true, 0 new issues, 0 fixed issues and 0 change in complexity. - At pull-request level, Codacy lists 0 new issues and 0 analysed files. So the verdict was given with no files analysed, which is why the summary is empty.
- The check run (114875401934) has 0 annotations.
- The same diff was rated "Up to standards, 0 new issues" at
ebb159e83. - #404, which carries identical code, is rated "Up to standards, 0 new issues" on its current head.
- A re-analysis from the Codacy dashboard (https://app.codacy.com/gh/jaysbeekay/sure/pull-requests/405) should clear it.
- The commit analysis for
- Checked against upstream
AGENTS.md.
Review findings
-
Gatekeeper light review (comment 6093165959, part 2 6093167207), MODERATE, offset accrual is unit-tested, not lender-verified: agreed that G2b is open, and no code change can close it.
docs/loans/release-gates.mdsays G2b needs linked-account daily balance history, which a loan statement does not carry.- What this PR changes about that risk was checked at
64b017f:- The
offsetgolden master (a variable loan with a 50,000 linked offset, row-by-row schedule and projection) is byte-identical before and after the swap.git diff --stat origin/claude/loans-integration-base HEAD -- test/fixtures/files/loan_golden_master/lists only the four scenarios above. loans:verify_contract_mutations[C15,C16]passes, each row failing under its mutation.
- The
- So the swap moves every loan's charge onto
DailyInterest, but not the offset figures it produces. - G2b stays an owner-side gate. Release reporting must still say C15/C16 are specified and unit-tested, not lender-reconciled.
-
Same review, OBSERVATION, C16's forward-flat half is tested but not in C16's mutation row: correct, and older than this PR.
release-gates.md(G1) already records it onmain.config/loan_contract_tests.ymlbinds one test class per row, andconfig/loan_contract_mutations.ymlone mutation per row.- Gate-verifying
Loan::OffsetResolverTest"holds today's offset total flat for future ranges" would mean changing both manifests, the two rake tasks and the contract and evidence docs. - That is gate tooling, not the engine swap, so it is left out of this PR, which is already the largest in the set. It wants its own issue.
-
Same review, external checks: the Copilot quota and Codacy's empty verdict, described under Validation. Neither can be cleared from this session: re-running the Copilot job fails on the same quota until it resets, and Codacy's reason is only on its dashboard.
-
"code master" review (comment 6106157929), hold, on
64b017f: none of its 15 findings holds up as a defect. For every "external caller" claim, a grep ofapp,lib,config,db,testandspec, and the API's jbuilder, found no caller left. Two stale notes the review didn't raise are fixed in827e15c54, pushed on the owner's instruction (2026-10-11: "Push the held commits; go with your recommendations").-
PayoffProjectionis no longer memoised: declined, measured. A temporary test countedPayoffProjection#initializeandSimulator#runper loan page, on base and on head, with identical results:- plain visit, Overview and Schedule tabs: 1 projection, 2 simulator runs;
- Extra repayments tab with an amount: 2 projections, 3 runs.
The page builds one baseline on the
ExtraRepaymentComparisonand hands it to the chart and the tabs. On base, the memoisedLoan#payoff_projectionwas called only by the API. The real per-page cost was inside the projection, in the offset resolver, and is fixed in51a2d260b(above). -
Loan#monthly_paymentreturns nil for every variable loan: upstream's design; no caller breaks.loan.rb:179-186matches upstream'sloan.rb:66-73, and no caller ofLoan#monthly_paymentexists on head or base. The retirement planner readsPayoffProjection#monthly_payment, and the API reads the saved rows. Tests pin the nil (loan_test.rb:88,amortization_schedule_test.rb:301).- It belongs in decision 5's list of changed behaviours, though, and is added there now.
-
first_calendar_indexloops without bound on an untrustedas_of: declined. Everyas_ofisDate.current(accounts_controller.rb:92,api/v1/loans_controller.rb:29,retirement_plans_controller.rb:7,30); none comes from a parameter. Measured even so: 2024→2200 takes 1.1 ms, and 2024→9999 takes 33 ms. -
The simulator lost its
starting_balancedate guard: already decided (decision 1), and upstream's design. Decision 1 reads "no stub fromas_of, nostarting_balance_as_ofguard". Upstream's simulator has no such parameter, and the old guard would reject this PR's own projection. -
payment_strategy:removed fromPayoffProjection: declined. NoPayoffProjection.new(..., payment_strategy:)remains. The two test uses pass it toLoan::Simulator, which still accepts it. Decision 5 records the removal. -
SimulationResult#total_costremoved: declined; upstream's file, byte for byte. No caller remains, andLoan#total_costusesschedule.total_paid. -
display_rows,stale?and the "recalculating" notice removed: already decided (decision 5). The API still reportscurrent,staleormissing. -
Version 4→5 needs a prebuild: already decided (decision 7). The procedure is in
release-evidence.md. The job is locked per loan and runs on the low-priority queue, so repeat views collapse into one job. -
AmortizationSchedule.forcan return nil: declined as a regression.- Only one nil caller is unguarded:
_schedule.html.erb:8, reachable by a hand-built Schedule-frame request for a loan with no schedule. - That request was a 500 on base too, with a different error (
l(nil)), so it predates this PR and needs its own issue. PayoffChart#payloadchecks first.
- Only one nil caller is unguarded:
-
amortizable?caps the term at 1,200 months: declined; upstream's code. The model validation and the database check already cap saved loans at 1,200. -
A misleading
&&/||comment: declined. The comment is correct, and it is upstream's text. -
A silent, unthrottled rebuild storm: declined. Nothing on the account page reads saved rows any more; only the API does. The enqueue is unchanged from base apart from a comment, behind the same per-loan lock.
-
DailyInterestraisesKeyErroron bad input: not worth its code. Its inputs are built internally, and malformed rate JSON fails earlier, at the model validator. -
calendar_month_step?month-end logic: declined. Every consecutive pair of schedule dates passed, for every start day across eight sample years at 1,201 months each: 3,070,957 pairs. The review's examples can't occur. -
Past maturity the projection repays from the second-to-last row: already decided (decision 4): "past maturity it pays the last level repayment, as #401 requires".
Not raised by the review; fixed in
827e15c54:interest_accrual.rbstill named "the payoff projection's first stub fromas_of" as its non-month range, a stub decision 1 removed.release-evidence.mdstill saidALGORITHM_VERSIONis3. It now says5, gives the history (3 at G2a, 4 for #399, 5 here) and points to the prebuild.- Contract row C2's stale "default is actual/365" was fixed on #397's branch, and arrived here in
22e65fb03.
-
-
Nightly review (comment 6120566351), INSUFFICIENT EVIDENCE, on
22e65fb03: no blocking findings.- MEDIUM, UNVERIFIED lender parity: agreed, and not closable from code.
- The month-end and leap-February movements are calculated from upstream's payment calendar. They are listed under Golden master and are decision 1 below, for the owner.
- No dated lender statement for such a loan exists in this session, so whether a given lender follows that calendar is unverified, as the review says.
- On a migration or correction: none is needed for stored data. Version 5 restages every persisted schedule from the loan's own terms, so no stale row survives.
- The user-visible change is the moved dates and interest for loans drawn on the 29th–31st, stated under Risks.
- Reconciling representative month-end, leap-year, rate-change and offset loans against statements is the owner's G2 work. G2b already tracks the offset half.
- MEDIUM, release sequencing: agreed; this is the existing plan.
- The prebuild is decision 7, in
release-evidence.md. - This PR retargets onto
mainonce the loan PRs below it land, and the combined CI and the contract gate run again at that head. - The current combined state is checked on #404 (see the base refreshes above).
- The prebuild is decision 7, in
- MEDIUM, UNVERIFIED lender parity: agreed, and not closable from code.
-
Nightly review (comment 6134299404), INSUFFICIENT EVIDENCE, on
61f57c2cd. No blocking findings. Its two MEDIUM items repeat the previous nightly review's (above), and the answers there stand. Lender parity for the month-end, leap-February, variable-rate and offset cases can't be closed from code: it needs dated statements, which is the owner's G2 work (G2b already tracks the offset half). Release sequencing: the version-5 prebuild is decision 7, and the combined CI and contract gate run again once this PR is retargeted tomain. Nothing to change in code.
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.
Decisions for the owner
-
Contract rows changed with the engine. Please confirm.
- C5: payments follow upstream's calendar, so loans drawn on the 29th–31st recover their anchor day after a short month.
- C4: a projection opens its first period where the schedule's running period opened, and charges the whole period on today's balance. There is no stub from
as_of, and nostarting_balance_as_ofguard. - The contract document and both manifests are updated to match.
-
Cached and API
interest_ratenow means the rate the period opened on, not the rate the payment was sized at. The rswag description andopenapi.yamlwere edited by hand; regenerating with rswag would also change two loans-endpoint descriptions already out of step with their specs, so that is left to you. -
Upstream tests that conflict with fork decisions.
- Adapted to #401: three projection tests ("too far behind → balloon", "slightly behind never converges", "matured is not applicable") and the held-payment comparison.
- Not adopted:
- "a provider's own rate type is buildable" (#14);
- seven model-layer variable-rate tests, listed in the file's header;
- three
LoanTesttests: non-positive term, any non-fixed rate type, future start date.
-
Kept, please confirm: a matured loan that still owes is projected on its last level repayment (upstream drops it). On the maturity date the projection pays the schedule's own settlement row, as upstream does; past maturity it pays the last level repayment, as #401 requires.
-
Removed:
- the Schedule tab's "recalculating" notice and its key in four locales (the page no longer reads cached rows);
- the projection's
:hold/:reamortizestrategies and their tests (no app caller after #392, which also closes #100's last PR-B deletion); - the old cleanup-payment rule, now
months_saved.abs > 1 || |interest| ≥ 1; - the fork simulator's two-clock and guard tests, replaced by upstream's and the
DailyInteresttests.
Also changed:
Loan#monthly_paymentnow returns nil for a variable loan, as upstream's does; nothing in the app calls it ("code master" review, finding 2). -
Dormant scenarios: a dated repayment's principal is folded into that period's payment. Ending balances match the old engine; the row shape does not. Their tests pass.
-
ALGORITHM_VERSION5 needs the production prebuild indocs/loans/release-evidence.md(updated). -
#184 open question 2 (propose the hook upstream): still open. It is 39 lines in the simulator plus 19 in the schedule.
Risks, blockers, and follow-up
- Every persisted schedule restages on first view after deploy (version 5). Figures move only for the four scenario shapes above, plus loans drawn on the 29th–31st generally.
- Page cost on very long loans: after
51a2d260ba 360-month loan with offsets renders in about 0.56 s (main0.48 s). A 1,200-month loan takes about 2.2 s (main1.57 s), all of it in upstream's simulation over 1,200 periods. - This is the largest loan change in the set; it deserves the Gatekeeper review the owner set aside for this build.