Let a loan accrue on 30/360 on the fork's engine

Draft
JA
2mo ago
+312-27

Summary

Part of #188 (the fork side) and of #184 (phase 4a: "Daily and day-count accrual ... New loans default to thirty_360; existing rows stay actual_365").

#188's upstream change is #191 (we-promise/sure#3639), which targets mirror/upstream-main and adds thirty_360 to upstream's monthly engine. The fork's daily engine still knew only actual_365 and actual_actual, and the database refused anything else. This brings thirty_360 to the fork.

031824d3e, 2026-10-12: the rollback now refuses rather than rewriting loans (nightly review BLOCKER; owner's instruction: "go with your recommendations").

  • Before: down moved every 30/360 loan to actual/365 so the narrower constraint would accept it. That changed those loans' interest and lost the basis their contracts name, and a later re-upgrade could not tell which loans had it.
  • Now: down first counts the loans on 30/360.
    • If there are any, it raises ActiveRecord::IrreversibleMigration and changes nothing. The message names how many loans are on 30/360 and says to set each one's basis before rolling back again.
    • With none, it narrows the constraint as before.
  • What this means in practice: new loans default to 30/360 once commit 2's migration has run, so any loan created since the upgrade blocks this rollback. That is the protection the review asked for.
  • Tests (test/migrations/allow_thirty_360_day_count_on_loans_migration_test.rb, the first for this migration):
    • "down refuses while a loan accrues on 30/360 and leaves every loan's basis as it was" failed first, because nothing was raised.
    • "down restores the two-value constraint when no loan accrues on 30/360" is the negative case and passes both before and after.
  • Mutations caught: the guard removed, refusing always, and counting the wrong basis.
  • Validation: full bin/rails test on 031824d3e gave 12,374 runs and 1 failure, the known Ruby 3.3 Provider::OpenaiTest string. bin/rubocop reports no offenses, and bin/brakeman 0 warnings.
  • Sibling: #398's actual/360 migration had the same rewrite and gets the same change there. It merges this commit.
  • Propagation: merged into claude/loans-integration-base, then #405 and #404 (see #404).

Commit 1: the engine. Loan::InterestAccrual gains :thirty_360:

  • Loan::Simulator calls the accrual once per scheduled period. A period that is one calendar-month step long (how the schedule and the projection step their dates, next_month clamp included) charges exactly (rate / 100) / 12 of the balance, which is the monthly path's own expression. A 30/360 schedule therefore equals the flat-twelfth simulation row for row: the upstream arithmetic.
  • Any other range, meaning the payoff projection's first stub from as_of, counts 30E/360 days.
  • A change part-way through a period (a rate change, an offset movement) splits that period's month by elapsed actual days. 30/360 doesn't say where inside a month a day falls, so this is a choice; it is stated in the code.
  • chk_loans_day_count_convention is replaced to allow thirty_360. A check constraint can't be widened in place. On rollback, down refuses while any loan is on thirty_360 (above), and otherwise restores the two values. This is the widening #184's phase 1 plan listed, moved here because the model can't accept the value before the engine can.
  • Labels and the hint, in every locale that carries them.

Commit 2: the default. New loans start on thirty_360; existing rows keep actual_365 (only the column default moves). The schedule signature now leaves out LEGACY_DAY_COUNT_CONVENTION = "actual_365" rather than "the default", so no existing schedule is restaged on deploy. This commit is separable: drop it if you'd rather new loans stay on actual/365. That's a fair call for an Australian lender, but it isn't the recorded decision.

Scope and dependencies

  • Issues: #188 (fork side), #184 (phase 4a).
  • Parent PR/branch, if stacked: none now. Base main. It was stacked on #396, which merged on 2026-10-12 as 3b1e600e2; retargeted to main the same day.
  • Intentionally out of scope: actual_360 (#284, #398, stacked on this), the upstream PR (#191), and any change to the monthly path.

Blast radius.

  • InterestAccrual has one caller, Simulator#accrue_daily_period, used by the schedule and the projection. actual_365 and actual_actual take the same path as before.
  • Loan::DAY_COUNT_CONVENTIONS, its validation and the form read the accrual's list.
  • After commit 2, every Loan created without a basis starts on 30/360: the new-loan form, Plaid's mortgage and student-loan processors, SimpleFIN and Redbark imports, the demo generator. No provider states the lender's basis (#188 comment 5934087017). The form preselects it and the user can change it.

Siblings. Loan::DEFAULT_DAY_COUNT_CONVENTION was derived from InterestAccrual::DEFAULT_DAY_COUNT_CONVENTION. It now stands alone, and the engine's keyword default stays :actual_365 (only tests rely on it). The signature's use of "default" is split out as LEGACY_DAY_COUNT_CONVENTION. config/loan_contract_mutations.yml anchors are untouched, and its manifest test is green.

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 BigDecimal and 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/thirty_360_test.rb, red on the base first (ArgumentError: unsupported day-count convention / RecordInvalid):

TestAsserts
a full period charges a twelfth whatever its length1,500.00 on 300k at 6% for 31-, 28-, 29- and 30-day months and a Jan 31 → Feb 28 clamp
actual/365 charges the same months differentlyFeb at 1,380.82, so the 1,500.00 is the convention's doing
a change part-way through splits its month by elapsed days14/31 at 6% + 17/31 at 7% = 1,637.10
a part-period counts 30/360 daysJan 10 → Feb 1 = 21 days = 1,050; Jan 20 → Jan 31 = 10 days (31st counts as 30th) = 500
a schedule on thirty_360 equals the flat-twelfth schedule row for rowpayments == simulation(daily_accrual: false).payments, 360 rows
the same loan on actual/365 does notnegative
the database stores itconstraint

Rewritten, not untouched: "rejects an unsupported day-count convention" in loan_test.rb and interest_accrual_test.rb used thirty_360 as their example and now use actual_366.

Mutations, each restored from a copy:

MutationCaught by
M1: no one-month shortcut (30E for every period)full-period test (clamp), row-for-row test
M2: no split by elapsed dayssplit test
M3: drop the thirty_360 branch4 tests
M4: drop the 30E day-31 clamppart-period test. Survived at first; the day-31 boundary was added because of it.

Commit 2 evidence. With the default moved and nothing pinned, 16 tests failed: the golden masters and the fixture-based characterisations, which characterise the fork's actual/365 figures. Fixture loans now carry day_count_convention: actual_365, since they stand for pre-#188 loans, and so does the golden master's builder. The golden-master fixtures do not move. The default and signature tests assert the new default and the legacy baseline separately, including that a 30/360 loan's signature differs from the legacy one.

Migrations on a scratch database loaded from fork main's schema: both migrate, db:rollback STEP=2 reverts both, and they re-migrate. The column default reads 'thirty_360' afterwards. db/schema.rb changes only the constraint line, the column default and the version stamp.

Rollback with 30/360 rows:

  • The original down raised PG::CheckViolation ... chk_loans_day_count_convention ... is violated by some row.
  • d48e3ba's down moved those loans to actual_365 instead.
  • Since 031824d3e, it refuses, with the count, and leaves every loan as it was.

Validation

  • github-advanced-security fails on every push (job 114414646884 on ed57dc6ab). It is GitHub's Copilot code-scanning job, and it stops before analysing anything with 402 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, controller, provider (Plaid, SimpleFIN, Redbark), retirement-plan, demo and helper suites: 1,036 runs, 0 failures, 2 skips.
  • bin/rubocop on changed files: no offenses. Contract mutation manifest test: green.
  • Full suite on 031824d3e: 12,374 runs, 1 failure (the known Provider::OpenaiTest Ruby-version string, unrelated). Earlier, on the integration branch: 12,468 runs, the same 1 failure.
  • Checked against upstream AGENTS.md.

Brought up to date with main after #396 merged (2026-10-12). 5eb8db029 merges main at 3b1e600e2 without conflicts. That merge brings in #338, #413 and #396. Against main, the PR's diff is now only its own 20 files (+312 / −27).

  • Loan model, test/models/loan/, offset, loans controller, loans task and migration tests on 5eb8db029, against a fresh db:schema:load: 424 runs, 0 failures.
  • bin/rubocop on the changed model and migration files: no offenses.
  • CI on 5eb8db029: all 31 checks green.

Review findings

  • cubic, loan.rb comment still called actual_365 the default: fixed in a15c012.

  • cubic, rollback fails once a loan stores thirty_360: valid. Fixed in d48e3ba by moving such loans to actual/365, which the nightly review then rightly called a data-integrity blocker. Superseded by 031824d3e, under which the rollback refuses instead.

  • cubic, the de and uk hint say "every month" though part periods use 30E/360: valid. Fixed in d48e3ba. The en and de hints now say 30/360 charges a twelfth for each full monthly period and counts a part period in 30-day months. ru, tr and uk carry the same English text as en, as they did before this PR.

  • cubic, translate the ru strings: declined. The ru hint and labels were already English on main (as are uk's and tr's). This PR keeps them in step with en; translating the loan form is a separate locale pass.

  • Gatekeeper light review, in three parts: comment 6106522612, 6106538118 and 6106539805, on d48e3ba. DRAFT_ON_TRACK, risk HIGH, confidence HIGH, with no material findings. It re-derived the arithmetic, including the upstream parity row for row, and confirmed the rollback (of that version). It calls the part-month split "a documented decision". Its recommendations:

    • Test-cover the new-loans default where providers create loans: done in ed57dc6ab.
      • "a loan created from SimpleFIN starts on thirty_360".
      • "processing Plaid's mortgage data leaves the day-count basis alone".
      • "processing Redbark's loan details leaves the day-count basis alone".
      • Each fails if its provider writes the column, which was checked by mutation.
      • Plaid and Redbark are the two processors that write loan terms; the other providers only create the account, through the same column default the SimpleFIN test covers.
      • The demo generator's loans are #415's: it makes generator.rb upstream's file.
      • The three test files give 74 runs, 0 failures.
    • Confirm the full suite on the integration branch before merge: to be rerun on #404 once these commits are merged into it.
  • "code master" review (comment 6106216384), hold, on d48e3ba: no defect. One stale doc line the review didn't raise is fixed in 5bc3be942, pushed once this draft's light Gatekeeper review on d48e3ba had landed (above).

    • F1, a write-blocking lock and a constraint-free window: declined.
      • The lock is stated wrongly. DROP and ADD CONSTRAINT both take AccessExclusiveLock (checked on PostgreSQL 16.15); ShareUpdateExclusiveLock is VALIDATE CONSTRAINT's.
      • There is no window. The migration runs in one DDL transaction (BEGIN, DROP, ADD, the version insert, COMMIT), and the DROP's lock holds until COMMIT.
      • It is brief: replacing the constraint over 1,000,000 inserted loan rows took 78 ms, and a household has a handful.
      • 42 migrations on main use add_check_constraint the same way.
    • F2, synced loans switch to 30/360: already decided. #184's decision table says "Day-count default for new loans: thirty_360, as upstream. Existing fork rows keep actual_365". This description states it under Blast radius and Risks.
      • "Silently switches" is wrong: only the column default moves, so existing loans keep actual_365, and no processor writes the column.
      • The Schedule tab always names the basis (day_count_notice), and the form shows its hint.
    • F3, the part-period split deviates from segment-wise 30E/360: declined; not worth its code.
      • The split is the stated choice in interest_accrual.rb:81-96.
      • The review's January-to-March range can't occur: InterestAccrual's one caller accrues one period at a time, at most a month.
      • The total per period is the same either way; only the split between two rates moves. On 400,000 at 6% → 7%, that is +5.38 for a change on 16 January, −11.11 for one on 15 February, and 0 for one on 16 April, about $21 at worst for a change on 28 February.
      • Upstream has no thirty_360 to compare with, and #405 carries the same rule forward. The choice is now written into contract row C2 (below).
    • F4, no test for a change point inside a multi-month range: declined. The review's own suggested mutation (segment_start, segment_end in place of from_date, to_date) already fails "a change part-way through a period splits its month by elapsed days" (expected 1637.0967741935, got 1633.3333333333).
    • F5, rollback rewrites rows without queueing rebuilds: moot since 031824d3e. The rollback no longer rewrites any row: it refuses while a loan is on 30/360.

    Not raised by the review; fixed in 5bc3be942: docs/loans/calculation-contract.md row C2 still said "The default is actual/365" and that every loan keeps it. It now says existing loans keep actual/365 and new loans start on thirty_360, with the part-month split rule. The test column is unchanged, and loans:verify_contract_coverage still verifies all 16 rows. #398 stacks on this branch and inherits it; #405 carries the same stale text and takes it when it next merges its base.

  • Nightly review (comment 6120537805), NOT READY TO MERGE, on ed57dc6ab.

    • BLOCKER, the rollback overwrites the contract basis: confirmed, and fixed in 031824d3e with the second option it named: the rollback fails with a clear error while affected loans exist and overwrites nothing (top of this description).
  • Nightly review (comment 6134292813), READY TO MERGE, on 5eb8db029. No blocking or other material findings. Its summary matches this description: 30/360 is the default only for new loans, and the rollback refuses rather than rewriting loans. Nothing to change.

Review responses are recorded here rather than as thread replies, because replies posted from this session get an assistant footer appended, which this repository's attribution rule forbids.

Risks, blockers, and follow-up

  • Behaviour change for new loans (commit 2), including provider-synced ones: they start on 30/360. That's the recorded decision; easy to drop.
  • Rollback refuses while any loan is on 30/360. After commit 2, that includes every loan created since the upgrade. Whoever rolls back has to choose those loans' basis first; the migration will not choose it for them.
  • When #191 / #3639 merges upstream and syncs in, its migration 20260918210000 will not skip on a fork database. Since a94a53904 it is an unguarded change, so add_column raises "column already exists". The fork has to admit it at sync time, the way #396 admitted 20260908145118: if_not_exists on the column, a name-matched constraint guard and an empty down. The plan is recorded on #184. This PR's constraint already allows all three of its values, and both sides default new loans to thirty_360.
  • Next unblocked: #284 (actual_360, #398), stacked on this.