Amortisation engine and variable-rate loans (#103, #104)

Closed
JA
3mo ago
+2338-187

Closes #103. Closes #104. Part of #108 (M0). PR-1 in docs/plans/loan-chart-upstream-delivery.md §6 — Fixes we-promise/sure#3295 when opened upstream.

Upstream PR: we-promise/sure#3473

Base is base/upstream-2984, not main — upstream/main with we-promise/sure#2984 merged, so
this diff shows only what we add on top of the PR the MVP builds on. Fork main carries 164
commits of epic work that is not going upstream; diffing against it would show nothing useful.

What this is

The first two slices of the upstream MVP: an amortisation engine that can express a rate change,
and variable-rate loans on top of it. The chart (#105, #106) follows in #111.

#103 — replace the calculation loop

we-promise/sure#2984 sizes one level payment up front and loops the term at a single annual_rate.
There is no seam a rate change can enter through, so #104 is impossible without replacing it.

The public API is unchanged: payments, periodic_payment, total_interest, total_paid,
payoff_date, payment_for and the Payment Data type are exactly as reviewed.

#2984's own 133-line test file passes byte-unmodified against the new engine. That was the
acceptance criterion and it is the evidence the swap is transparent. git diff pr-2984 -- test/models/loan/amortization_schedule_test.rb is empty on the #103 commit.

New: Loan::AmortizationMath, Loan::SimulationResult, Loan::Simulator.

#104 — variable rates

Adds loans.variable_rate_schedule (jsonb, effective date => rate) and loans.start_date, a
Loan::RateResolver, and form UI to manage changes. amortizable? widens to any loan with a rate
type, so the Schedule tab appears for variable and adjustable loans and for provider-typed ones
(decision 8 below).

This changes three of #2984's assertions, all of which assert that a variable loan has no
schedule. #103 left their tests untouched; #104 deliberately does not, and the difference is the
point. What is still unbuildable is a loan with no rate type at all.

Two rates, not one

A period is bounded by two dates and on a variable loan they can sit either side of a change.

  • Interest for [previous payment date, this payment date) accrues at the rate in force when
    the period opened.
  • Payment sizing uses the rate in force on the payment date.

Reading one rate for both re-rates the month ending on the boundary — billing the borrower a rate
that applied for none of it. This fork's own engine gets that right only on its daily-accrual path;
its monthly path has the defect. Fixed here rather than carried upstream.

It is also why the second blocking finding on we-promise/sure#3296 is unreachable here. Segment
lengths derived from a ~30.44-day average month made a segment spanning a 30-day month
floor(30 / 30.44) == 0 payments, silently skipped. Nothing here counts days into payments —
segments are real payment dates — so the defect cannot occur rather than being corrected. Pinned
end-to-end on charged interest, because a skipped segment leaves a well-formed schedule and raises
nothing.

Cross-cutting changes that are not the engine

Two changes here touch every account type, not only loans, and are called out so their blast radius is read on its own:

  • AccountableResource#update is transactional. The balance change (set_current_balance, which writes a valuation and the cached balance) and the attribute update now commit or roll back together, and lock_saved_attributes! runs inside the same transaction. Requested by Codex on we-promise/sure#3473, because a rejected loan form had committed its balance half. It changes the update path of depository, credit card, property, crypto and every other accountable; their controller suites pass, and the failure mode it removes (a 422 with a committed valuation) applied to all of them. create gained the matching rescue ActiveRecord::RecordInvalid that re-renders the form instead of the generic 422 page.
  • Account default owner tie-break on id. Ported from fork main (247c9532): two users of one role with the same created_at made the default owner depend on the query plan, which surfaced as a flaky fixture assertion here. Independent of loans; kept in this PR because the test that exposed it is here.

Blast radius

amortizable? is a gate three things read: UI::AccountPage#tabs, AmortizationSchedule.for, and
Loan#monthly_payment.

  • The Schedule tab now appears on variable and adjustable loans. That is the intended change.
  • monthly_payment stays nil for a variable loan. It has a schedule now, but it does not have a
    single monthly payment, and quoting the one it opened with would present a stale figure as a
    current one. The Schedule tab labels that figure "Opening Payment" when the schedule
    re-amortises.
  • amortizable? now requires an account. original_balance reads through it and #2984's
    rate_type == "fixed" guard happened to short-circuit before that read; widening the rate types
    removed the accident, so the requirement is stated rather than relied upon.
  • PlaidAccount::Liabilities::MortgageProcessor writes Plaid's raw interest_rate.type straight
    through. Such a value is now treated as variable (decision 8 below); a blank one is not amortizable
    and gets what it got before schedules existed — no schedule, no tab.

Decision 8 — a provider's own rate type is variable, not unknown (#100, #92)

PlaidAccount::Liabilities::MortgageProcessor writes Plaid's raw interest_rate.type straight
through, so a synced mortgage can carry "arm" or a capitalised "Variable" the form never
offers. Earlier revisions of this PR treated that as "not amortizable — no schedule, no tab". It now
reads as variable: Loan#variable_rate_type? is true for any non-blank rate type other than
"fixed", and amortizable? asks only that a rate type be present. A blank rate type still says
nothing and stays unschedulable. VARIABLE_RATE_TYPES remains the form's vocabulary, which is all
the rate-change editor uses it for; AMORTIZABLE_RATE_TYPES had no reader left and is gone.

Blast radius. The predicate is read by the Schedule tab, the rate-change form, RateResolver
and AmortizationSchedule, all of which already handle a variable loan with no recorded changes.
The Overview tab already used the "present and not fixed" rule, so the model now agrees with the
view. monthly_payment is unchanged and stays nil for anything but "fixed". A capitalised
"Fixed" from a provider therefore amortises as variable with no rate changes: same numbers, no
single monthly payment quoted.

Tests, observed to fail first. "arm" and "Variable" amortize as variable, nil and "" do
not (test/models/loan_test.rb); a Plaid payload typed "arm" yields a schedule
(mortgage_processor_test.rb). Before the change: "arm" should read as variable and Expected
false to be truthy
. The two tests that used "teaser" as the unschedulable case now use a blank
rate type, and the schedule test asserts "teaser" is buildable.

Deliberately not here

Daily accrual, offset accounts, extra repayments, scenarios, day-count conventions, the persisted
loan_amortizations cache, its rebuild pipeline, ALGORITHM_VERSION, the rake tasks, the API
endpoint, and everything in docs/loans/. Convergence state went too — every run in this engine
clears its balance, so "did it converge?" is unreachable and would have shipped as untestable
state. It returns with the projection that can actually fail to converge (#105).

Two items #103 and #104 asked for are declined here rather than omitted silently: monthly accrual
applies a mid-period rate change from the next period (a property of monthly accrual, documented on
Loan::Simulator where it happens; splitting periods at change dates is daily accrual), and there is
no Rails.cache layer or p95 benchmark in this slice — both belong with the persisted cache and its
rebuild pipeline, none of which is in this PR. The issues' expectations should be amended to match.

Carried, unrelated to loans

26ce39fa orders Account#assign_default_owner's candidates by created_at, id. It is a port of fork
main's 247c9532: two admin fixtures share a timestamp, so the default owner depended on the query
plan and #111's CI flaked on it. It no-ops once the base carries the same ordering, and it can be
dropped from the upstream PR if the maintainers would rather take it separately.

Checks

CheckResult
Loan and provider suites (test/models/loan, loan_test.rb, plaid_account, loans_controller_test.rb, accounts_controller_test.rb)162 runs, 830 assertions, 0 failures
Full suite, this head 61576e0a8510 runs, 34197 assertions, 4 failures, 2 errors
Full suite, previous head bd1492ce8507 runs, 34182 assertions, 4 failures, 2 errors
bin/rubocopclean (2539 files)
bundle exec erb_lint --lint-allclean (694 files)
bin/brakeman --no-pager0 warnings

The six failing tests are identical on both heads (three Settings::HostingsControllerTest cases,
ActiveStorageAuthorizationTest, Provider::OpenaiTest on Ruby 3.4's Hash#inspect format,
Provider::RegistryTest on Anthropic endpoint configuration). Run locally on Ruby 3.3.6 with a local
Redis; none is loan-related. The earlier 81-failure figure was the same environment without Redis or
provider credentials.

Reviewing this

The engine is the part worth the attention, and Loan::Simulator#run is where the two rates are
read. Everything else follows from it.

  • Replaced the fixed-rate amortisation loop with Loan::Simulator, Loan::AmortizationMath, and Loan::SimulationResult.
  • Added variable-rate schedules, rate resolution, re-amortisation, and rate-change management UI.
  • Preserved fixed-rate behavior and the Payment data contract.
  • Added coverage for rate changes, payment boundaries, precision, schedule limits, and form validation.
  • Deferred daily accrual splitting, Rails caching, and p95 benchmarking.
AuthorLines addedLines removed
jaysbeekay1,188135