Let a loan accrue on the basis its lender actually uses

Merged
JA
2mo ago
+918-12

Closes #188 (pre-flight — this targets mirror/upstream-main, not main; see Where this lands below).

What the defect is

Every period is charged as a flat 1/12 of a year regardless of how many days it holds, so a loan written on actual/365 — standard for UK and Australian mortgages — cannot be reconciled against the lender's statement on any row. On 300,000 at 6%:

periodtoday (1/12)actual/365difference
January (31d)1,500.001,528.77+28.77
February (28d)1,500.001,380.82−119.18
April (30d)1,500.001,479.45−20.55
leap February (29d)1,500.001,430.14−69.86

Over a plain year the monthly differences cancel exactly. This is not upstream being wrong — it is that a convention the loan is written under cannot be expressed at all.

The default is the load-bearing decision, not the feature

Loan::Simulator is the single accrual point: Loan::AmortizationSchedule runs through it, and Loan::PayoffProjection will once we-promise/sure#3474 lands. So this touches every loan figure in the product, and a default that moved would silently restate every schedule.

The default is thirty_360, which reduces to a flat 1/12 exactly.

The issue originally proposed actual/actual on the grounds that it reproduces upstream. It does not, and the review of #188 caught it: actual/actual charges 31/365 in January and 28/365 in February, reaching 1/12 only when a whole calendar year is summed. Measured over 30-year lifetimes from sixteen start dates it lands between −£212 and +£241 against flat, because a loan's periods do not align to calendar years and its final period is partial. (actual/365 lands between +£479 and +£1,116; the issue's original "~£366" was outside that range and has been corrected.)

The design decision the plan did not cover

monthly_rate feeds two different things: what a period charges, and what sizes the payment. The day count applies only to the first.

AmortizationMath.level_payment is an annuity formula over one constant periodic rate. A factor that moved with the length of the month would differ every period, so under :reamortize the payment would be rebuilt every month and stop being level. Sizing therefore stays on the nominal monthly rate — which is also what the borrower's contracted payment is set from.

That split forced one more change. The straddle correction asked "did the rate move mid-period?" by comparing the two derived rates:

first_period_interest: (interest if sizing_rate != accrual_rate)

With a day count in play that answers yes every month, because January and February differ by length rather than by rate. It now compares the rates themselves, which is what it always meant and is day-count independent.

Evidence

The negative test is the one that matters. A default loan's schedule is identical row for row — asserted both against the explicit default and against the arithmetic itself, so it does not merely compare the engine with itself.

  • Bit-identity, current proof: test/models/loan/default_convention_baseline_test.rb asserts nine scenarios against figures captured from upstream main at 20352e1a0, whose engine has no day-count convention (report: we-promise/sure#3639, comment 5918596750). The original "56 existing engine tests pass untouched" predates #3474.
  • 98 runs / 376 assertions across loans_controller_test, test/models/loan/ and loan_test — 0 failures, 0 errors.
  • 31 tests at 727190944: 18 in test/models/loan/day_count_convention_test.rb (including the full path Loan → AmortizationSchedule.for → Simulator), 7 in default_convention_baseline_test.rb, 2 in loans_controller_test.rb, 3 in loans_helper_test.rb and 1 in payoff_projection_test.rb.
  • Mutation-checked, 8 breakages, all caught. This earned its keep: one test was asserting on :total_payment, a hash key that does not exist, so it compared [nil] to [nil] and passed vacuously. Only the mutation exposed it; it now asserts :payment_amount excluding the settling final row.
  • Rubocop, erb_lint and Brakeman clean.

db/schema.rb carries two lines of this PR's own: the column and the check constraint. It carried a third — the version — until the merge below, which correctly kept main's later version line, because this migration is dated older than commits already on main. Not regenerated wholesale — I ran the migration, dumped, and verified my hand-applied lines are identical to the dump except for one unrelated pre-existing line (chk_simplefin_accounts_balance_sign_override) that flips rendering form on any re-dump.

Refreshed against mirror/upstream-main at ad0a2ba9 on 2026-09-25, which resolved a conflict on db/schema.rb's version line. git diff upstream/main -- db/schema.rb is now exactly the column and the constraint.

Full suite at that head: 9,673 runs, 40,854 assertions, 0 failures, 1 error, 33 skips. (The figure posted earlier was 9,278 runs against the pre-merge base; the suite is larger on the new one.) The one error is RecurringTransaction::PipelineTest — a second connection the test opens falling back to the OS user, reproduced identically on an unrelated branch with none of this change on it (jaysbeekay/sure#168).

The three changes since the draft review

All three came out of the review and all three are in 2156ce73:

  • The select saved nothing. LoansController dropped day_count_convention from the nested parameters, so choosing a convention on the form left the loan on its previous one. Permitted, and covered by "the day-count convention chosen on the form is saved" and its create-path twin (cubic 4050439826, CodeRabbit 4052210960).
  • A label that was missing rendered a fallback rather than failing. raise: true on the lookup, with "a convention with no label fails loudly rather than rendering a fallback" to hold it (CodeRabbit 4052210953).
  • The year boundary was one test doing two jobs. Split into "an actual/actual period crossing New Year uses each year's own denominator" and "actual/365 is indifferent to the year boundary", so a regression names which convention broke (CodeRabbit 4052210963).

Where this lands, and a divergence it exposes

This targets mirror/upstream-main, not main, and that is deliberate.

The fork already ships this feature: loans.day_count_convention, default: "actual_365", constrained to actual_365 and actual_actual, with Loan::InterestAccrual::DEFAULT_DAY_COUNT_CONVENTION = :actual_365. There is no thirty_360 and the default is not upstream's arithmetic. An upstream-shaped change cannot sit on fork main without colliding with it.

So this is a genuine pre-flight of the upstream change rather than a second implementation fighting the fork's — the same pattern as #170 and #176. The divergence itself (fork defaults to actual_365, upstream would default to thirty_360) is recorded against #184 and is not resolved here.

Sequencing

Upstream PR: we-promise/sure#3639 (ready for review) · upstream issue: we-promise/sure#3638

Same branch, same commits — the upstream PR is this branch, not a cherry-pick.

Upstream issue: we-promise/sure#3638 — the case for this change, stated there in borrower terms.

Behind we-promise/sure#3474, which moves the very engine this patches. That PR carries a CHANGES_REQUESTED from a maintainer, but the request was "can you rebase this?" and the rebase landed on 15 September; it is now one commit on current main, MERGEABLE and DS-clean, waiting on a re-review rather than on work.

Before this goes upstream the row-for-row check must be re-run on the post-#3474 engine, not merely on today's. The claim that thirty_360 is bit-identical is the claim this whole change rests on, and it has to be proved against the engine it will actually ship on.

Deliberately left out

Daily accrual, mid-period rate-change precision, offset accounts, scenarios, extra repayments, and any change to PayoffProjection beyond what #3474 carries.

Review follow-up

Pushed on 2026-09-29 with the owner's go-ahead. This branch is the head of we-promise/sure#3639, so that PR carries the same commits (same branch, same commit; 256d1785b when this section was written, 1f91361e0 as of 6 Oct, 11 commits on upstream main ea38fa6a3, which mirror/upstream-main was fast-forwarded to that day). Four commits on top of 10243871d: 8b9ab4d3a (merge of mirror/upstream-main at 1052443aa), 955dfe1f8, 25865103f, 256d1785b.

finding (source)status
Production Readiness Review, blocking 1: Loan::PayoffProjection (we-promise/sure#3474, now on the mirror) builds its own Simulator without the convention, so an actual/365 loan's projection and payoff chart charged a flat twelfth beside an actual/365 scheduleFixed in 955dfe1f8. The projection passes loan.day_count_convention. It is the only other Simulator.new caller, and Loan::PayoffChart reads the projection, so the chart is covered too. Test "a loan on actual/365 is projected on the basis its schedule charges" puts a loan exactly on contract, first asserts the period is one where actual/365 and a flat twelfth differ, then asserts the projection's first period charges what the schedule charges and saves nothing. It failed before the fix (1,182.97 against 1,088.99). Hard-coding the projection's convention makes 3 projection tests fail.
Production Readiness Review, blocking 2: the branch conflicts with the current mirrorFixed in 8b9ab4d3a (a merge commit, no rebase). Against 1052443aa git reported one textual conflict, in Loan::Simulator. The rest auto-merged. Both sides are kept: upstream's payment_amount: and :scheduled strategy, and this branch's day_count_convention:. Both constructor guards are kept. Upstream's restructured run loop is taken whole, and this branch's rate-based straddle test is applied to its level_payment call. db/schema.rb takes the mirror's later version line, 2026_09_25_220151.
Production Readiness Review, must verify: re-run the suites, re-dump db/schema.rb, re-prove bit-identity on the rebased engineDone. db:schema:load on a throwaway database gives the column (thirty_360, NOT NULL) and chk_loans_day_count_convention. db:migrate:redo VERSION=20260918210000 followed by db:schema:dump gives this branch's two lines exactly. The only diff is one unrelated upstream line (financekit_lineage_account_origin), which renders differently on re-dump. Bit-identity on the post-#3474 engine: 1,920 Simulator scenarios produce byte-identical output under the default on the mirror and on this branch. They cover 6 start dates (including month-end and leap day), 5 rates (including 0), terms of 1, 12, 60 and 360, :reamortize, :hold (with and without a seeded amount) and :scheduled, fixed and variable rates with re-amortisation, and settle on and off. The harness does detect a change: moving the default to actual_365 makes the output differ. At loan level, 5 loans (the fixture plus fixed and variable loans from month-end and leap-day starts) give byte-identical amortization_schedule output (1,200 rows) and payoff_projection output (1,023 rows) on the mirror and here.
Production Readiness Review, test adequacy: actual/actual across a year boundary with a leap year on one sideThe existing test already has the leap year on the closing side (2027 to 2028). Added in 25865103f: the opening side, 15 Dec 2028 to 15 Jan 2029 (17/366 + 14/365). It asserts the expected figure differs from both single-denominator answers. Taking either end's denominator for the whole period fails both boundary tests.
Production Readiness Review, test adequacy: the settling row under actual/365 when the residual is negativeAdded in 25865103f, in both directions. A February and March pair (59 days) settles below the contracted payment. A December and January pair (62 days) settles above it. Each asserts the final row pays its opening balance plus a hand-computed actual/365 charge and closes at zero. Removing the schedule-end settlement fails the excess test, and making no row final fails both.
Production Readiness Review, non-blocking 3: provider-imported loans cannot state their basisVerified. The Plaid mortgage and student-loan processors update named columns and never touch day_count_convention. A synced loan starts on thirty_360, and a convention chosen on the form survives later syncs. A note for #188 is drafted; posting it is for the owner.
Production Readiness Review, non-blocking 4: actual_360 is not offeredOwner decision. It is a constraint swap, one branch in accrual_factor and one label. Recommendation: leave it to a follow-up once a lender needs it.
Production Readiness Review, non-blocking 5: only en and de carry the labelsVerified that other locales get the English labels and not an error. raise: true fires only for a key missing in every locale. Pinned in 256d1785b by "a locale without its own labels falls back to English rather than failing", which errors if the lookup's fallback is disabled. The helper comment that said otherwise is corrected. Declined: adding machine translations for 17 locales. Upstream leaves recent loan keys partly translated (rate_changes is in 6 of 19 files) and community passes fill them in.
Production Readiness Review, non-blocking 6: API surfaceVerified at 1052443aa: no /api/v1 view or controller exposes interest_rate, term_months or any other loan term, so there is no serializer or OpenAPI spec to extend. The family export serialises every accountable column, so the new column is included. The importer restores only subtype and locked_attributes, which already applies to every loan term and is not this PR's.
CodeRabbit pre-merge "Linked issues: inconclusive" (post-#3474 row-by-row comparison)Done. See the bit-identity row above.
CodeRabbit pre-merge "Out of scope changes" and "Merge Risk: High" (XIRR, provider ownership)Already addressed in 5757416035. Those files are byte-identical to the mirror. GitHub's diff is against a stale base, which clears once the head moves.
CodeRabbit pre-merge "Docstring coverage"Declined. The engine and this tree document with inline # comments, and the Gatekeeper recorded this as a repo-wide bot policy, not a regression.
Inline threads (11)All were already resolved before this pass. None needed action.
Body: "the row-for-row check must be re-run on the post-#3474 engine"Discharged. #3474 is on the mirror, and the comparison above ran against it.

Tests on the merged head (Ruby 3.3.6 locally, since 3.4.9 is not installed): test/models/loan/, loan_test, loans_controller_test, loans_helper_test and test/components ran 286 runs, 1,067 assertions, 0 failures. The full suite ran 10,052 runs, 42,397 assertions, 4 failures, 3 errors and 33 skips. All 7 are known to fail only in this local Ruby 3.3.6 setup and are unrelated to loans: the admin profile picture, the ActiveStorage variants, OpenAI extra_headers, the Registry Anthropic ENV test and three Anthropic tests in HostingsController. New tests since the draft review: 21 (15 in day_count_convention_test.rb, 2 in loans_controller_test.rb, 3 in loans_helper_test.rb, 1 in payoff_projection_test.rb). Rubocop is clean on the changed files and Brakeman reports 0 warnings.

Sequencing, updated: we-promise/sure#3474 is no longer ahead of this change. Its PayoffProjection is on the mirror and this branch now carries the convention into it.

Since 6 Oct: the migration now owns its column (a94a53904, 2026-10-12)

Head: a94a53904. It is also we-promise/sure#3639's head: same branch, same commit.

  • Nightly 6120614870 (BLOCKER). down dropped a column that a guarded up had skipped. Answered in 6124752813.
    • db/migrate/20260918210000_add_day_count_convention_to_loans.rb is now a plain reversible change: add_column (string, null: false, default thirty_360) plus add_check_constraint, with no guards. Rolling it back removes exactly what it adds.
    • New test file: test/migrations/add_day_count_convention_to_loans_migration_test.rb, with 3 tests. "up refuses a column it did not create rather than adopting it" fails against the guarded 1f91361e0. db/schema.rb is unchanged.
    • Fork consequence: on a fork database, where the column already exists, this migration now raises rather than skipping. The fork admits it at sync time; the plan is on #184.
  • Nightly 6134303265 (MEDIUM: conflicts, red ci / test_unit).
    • There are no conflicts. The merge against mirror/upstream-main (ff51e7e2d) is clean.
    • The one unit failure is SnaptradeAccount::ActivitiesProcessorTest (7000 against 6999.79), in files this branch does not touch. Upstream's #4033 broke it, and upstream's 2b18df230 (we-promise/sure#4145) fixed it; that fix is now on the mirror.
    • The branch is unchanged until the owner decides whether to bring the mirror in. Doing so also moves #3639's head.
  • Adds configurable loan day-count conventions: thirty_360, actual_365, and actual_actual.
  • Preserves existing schedules with thirty_360 as the default.
  • Applies conventions to interest accrual, not payment sizing.
  • Handles leap years and actual_actual periods that cross year boundaries.
  • Persists the convention through loan forms, controllers, models, migrations, and schedules.
  • Adds validation, translations, and end-to-end tests.
  • Includes additional provider ownership, transfer matching, demo cleanup, and XIRR changes.
AuthorLines addedLines removed
UnavailableUnavailableUnavailable