Let a contract row name a test and mutation per behaviour (C11, C16)

Merged
JA
2mo ago
+454-85

Summary

Closes #406.

G1's gate could bind one test class and one mutation to each contract row. C16 specifies two behaviours, so its forward-flat half was tested but never shown by the gate to fail when broken: today's offset total held flat for future days. Since #405 routes every loan's charge through the offset path, that gap matters more than it did when G1 was signed.

Now a row can name a test entry per behaviour and a mutation per entry, and both gates check every one:

  • loans:verify_contract_coverage reads every Loan::...Test class in the row's test column, not just the first backticked name. It requires the manifest to bind exactly that set, and it names the class that is missing or extra.
  • loans:verify_contract_mutations pairs each of a row's mutations with that row's test entries by position, runs each mutation against its own entry's tests, and reports them as C16#1 and C16#2. It now checks every anchor before running anything. Before, a stale anchor was found only when the loop reached it, after the earlier rows had spent minutes running.
  • Manifest shape: a row with one entry keeps its single-hash YAML shape; a list is accepted only where needed.

Decision: C11 needed the same treatment

The plan said no other row would change. Reading every class a row names showed that was wrong: the C11 row names Loan::AmortizationScheduleTest "contract regression" as evidence for its second sentence, "the contracted schedule itself does not track live balance". No test in that class carries that name, and none did at the commit that wrote the row (51573368c). So the reference pointed at nothing, and the stricter coverage gate fails on it.

Of the three options (weaken the parser, delete the reference, or give the half real evidence), I took the last:

  • New test: AmortizationScheduleTest "the contracted schedule is built from the opening principal, not the live balance". It moves the live balance and asserts that the schedule does not change.
  • Second C11 mutation: sizes Loan#original_balance from the live balance. The anchor Money.new(account.first_valuation_amount, account.currency) appears exactly once on main, on #405's branch and on #404's, so merge order doesn't matter.

The issue's triage plan is revised to match.

Siblings checked.

  • grep -n "fetch(\"class\")\|mutations.fetch\|manifest.fetch" lib/tasks/loans.rake test/: every reader of the two manifests now goes through Array.wrap. Those readers are the two tasks and Loan::ContractMutationManifestTest.
  • portfolio:verify_contract_coverage has its own manifest and is untouched.
  • The other 14 rows still bind one class each, and the gate verifies them unchanged (transcript below).

Also fixed in passing: C8's mutation defect contained an unquoted #48, which YAML reads as a comment, so the task printed it cut off at "(the". It is now quoted. The transcript keeps that line as the run printed it, with a note.

Scope and dependencies

  • Issue: #406
  • Parent PR/branch, if stacked: none. Base main.
  • Intentionally out of scope:
    • row renumbering (C16a/C16b), and every row other than C11 and C16;
    • the portfolio contract;
    • any engine change.
  • Blast radius:
    • ci.yml runs bin/rails loans:verify_contract_coverage on every PR. A parser that misread any row would fail every PR, so the task is exercised against the real contract and manifests in test/tasks/loans_task_test.rb.
    • test/tasks/loans_task_test.rb invokes both tasks.
    • #405 rewrites the C8 and C11 mutations and the C11 contract row, and it rebuilds AmortizationScheduleTest on upstream's schedule API. That conflict is real, and it has been resolved in #404 (see Review findings and Risks).

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. (No fixture changed.)
  • Financial calculations use BigDecimal and documented rounding points. (No calculation changed.)
  • De-identification uses token-shape allowlists; no personal data is included. (No data added.)
  • Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.

Files changed

  • lib/tasks/loans.rake: both contract tasks.
  • config/loan_contract_tests.yml, config/loan_contract_mutations.yml: C11 and C16 become two-entry lists; C8's defect is quoted.
  • test/tasks/loans_task_test.rb: 7 new tests.
  • test/models/loan/contract_mutation_manifest_test.rb: iterates both shapes, plus a one-mutation-per-entry check.
  • test/models/loan/amortization_schedule_test.rb: the C11 test.
  • docs/loans/calculation-contract.md (C11, C16 rows), docs/loans/contract-mutation-evidence.md (new transcript), docs/loans/release-gates.md (G1 caveat removed).

Fail first. Seven new task tests ran against the old task code. The wrong-reason failure: Minitest's stub on YAML.load_file loses to Bootsnap's prepended load_file, so the task read the real files. The helper now uses Mocha, and the re-run failed for the right reasons:

  • The two new coverage negatives: the old parser reads only the first class, so the gate passed. Assertion: "a manifest missing a class the contract names must fail the gate".
  • The list-shaped manifests: TypeError: no implicit conversion of String into Integer at loans.rake:75 and :131.
  • The pairing test: two runs instead of four.
  • The C11 test: written as a characterisation, so it passes on today's code, which is correct. It fails under its mutation with Expected: 200000, Actual: 150000.

The new C16 mutation. It fails the forward-flat test with [{date: 2024-01-10, amount: 0.375e3}] expected and amount: 0.0 produced, which is the issue's "expected 375, got 0".

Full gate run on this branch (bin/rails loans:verify_contract_mutations at 70c31ea76):

C1    baseline=pass  mutated=failed    the accrual denominator stops being 365, so a full non-leap year no longer equals balance x rate
C2    baseline=pass  mutated=failed    leap years silently switch to a 366 denominator instead of 366 elapsed days over 365
C3    baseline=pass  mutated=failed    daily accrual stops receiving offset change points for the period
C4    baseline=pass  mutated=failed    the boundary guard stops rejecting a starting balance dated after accrual start
C5    baseline=pass  mutated=failed    the payment calendar is built one payment short of the loan term
C6    baseline=pass  mutated=failed    an extra repayment landing exactly on a payment date is dropped instead of applied before the payment
C7    baseline=pass  mutated=failed    a mid-period rate change no longer segments the accrual window, so the whole period runs at the old rate
C8    baseline=pass  mutated=failed    the accrual clock is seeded from the payment-sizing rate, re-rating the period that ENDS on the boundary (the
C9    baseline=pass  mutated=failed    same-day event order is reordered so payment precedes accrual
C10   baseline=pass  mutated=failed    the accrual window stops being half-open, so a rate effective ON the window's first day is ignored instead of applied from it
C11#1 baseline=pass  mutated=failed    every run holds the first payment, so re-amortisation stops re-sizing per rate segment
C11#2 baseline=pass  mutated=failed    the contracted schedule is sized from the live balance instead of the opening principal
C12   baseline=pass  mutated=failed    each segment is rounded as it accumulates instead of once at the charge point
C13   baseline=pass  mutated=failed    change points stop splitting the range, so piecewise accrual no longer equals the daily loop
C14   baseline=pass  mutated=failed    the last scheduled payment no longer settles the remaining balance
C15   baseline=pass  mutated=failed    the offset floor is removed, so an offset above the balance produces negative interest
C16#1 baseline=pass  mutated=failed    a change point effective on the first day of the range is ignored rather than applied to the whole range
C16#2 baseline=pass  mutated=failed    a future range no longer holds today's offset total flat
Verified 16 contract rows (18 mutations): every row's tests pass unmutated and fail when its behaviour is broken

After quoting, loans:verify_contract_mutations[C8] prints "(the #48 defect)" in full.

Validation

  • CI on 079cc2c2d: 32 of 33 checks green, including ci / test_unit, which runs loans:verify_contract_coverage.

    The one failure, github-advanced-security, is GitHub's Copilot code-scanning job (job 114273109018). 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.

  • CI on 4e17e3731 (the head before main was merged in): every ci / job, CodeQL and Codacy green. CodeQL's Swift analysis needed its one re-run, after an api.github.com connection timeout. The same quota-bound github-advanced-security failure.

  • Full bin/rails test on 079cc2c2d: 12,371 runs, 53,380 assertions, 1 failure, 0 errors, 35 skips. The failure is the known local-only Provider::OpenaiTest#test_extra_headers_stringifies_nested_values_Ruby-style (Ruby 3.3 here; CI pins 3.4).

  • Brought up to date with main (2026-10-12, 619f23330), as upstream AGENTS.md asks before review. The merge brings in only main's own 3727ee4e0, the mirror schedule (.github/workflows/ and CLAUDE.md). Everything else is byte-identical to 4e17e3731: git diff 4e17e3731 619f23330 -- . ':!.github' ':!CLAUDE.md' is empty.

  • CI on 619f23330 (the current head): all 31 checks green, including github-advanced-security, which now runs past the quota.

  • main has since gained #338 (333e242a3). It changes no file this PR touches (loans_controller.rb, loan_offset_account.rb, the loan form and their tests), so this PR has not merged it again.

  • bin/rails test test/tasks/loans_task_test.rb test/models/loan/contract_mutation_manifest_test.rb: 34 runs, 0 failures.

  • bin/rubocop on the changed Ruby: no offenses.

  • bin/brakeman --no-pager -q: 0 security warnings.

  • erb_lint, Biome: not applicable (no ERB or JavaScript changed).

  • Checked against upstream AGENTS.md (read from the mirror today). This is fork-local gate tooling and is not proposed upstream.

Review findings

  • Gatekeeper light review, parts A and B: comment 6105687637 and comment 6105723742, on 079cc2c2d. The verdict is DRAFT_ON_TRACK, risk HIGH, confidence HIGH. It agrees the C11 work is "a genuine correctness improvement, not scope creep".

    • MODERATE: "Verify the #405 / #404 merge resolution before this leaves draft". The reviewer could only check C11#2's anchor against main and asked for the gate to be re-run where #405 is merged. Done: no change needed, the pairing holds. I ran the full bin/rails loans:verify_contract_mutations on the integration branch #404 at 455385584. That head carries #405's engine, this PR's merge 078c317a7 with the resolution described under Risks, and #414 and #415. It verified 16 rows and 18 mutations, every one baseline=pass mutated=failed:

      C1    baseline=pass  mutated=failed    the accrual denominator stops being 365, so a full non-leap year no longer equals balance x rate
      C2    baseline=pass  mutated=failed    leap years silently switch to a 366 denominator instead of 366 elapsed days over 365
      C3    baseline=pass  mutated=failed    the interest hook is asked for the wrong window, so the period is not what is charged at its payment point
      C4    baseline=pass  mutated=failed    the projection opens its first period on as_of, a stub, instead of where the contract's running period opened
      C5    baseline=pass  mutated=failed    the payment calendar is built one payment short of the loan term
      C6    baseline=pass  mutated=failed    a change point on the period's opening date is dropped, so an extra repayment made on a payment date is deferred
      C7    baseline=pass  mutated=failed    a mid-period rate change no longer segments the accrual window, so the whole period runs at the old rate
      C8    baseline=pass  mutated=failed    a period is charged at the rate in force when it closed, re-rating the period that ENDS on a change (the #48 defect)
      C9    baseline=pass  mutated=failed    same-day event order is reordered so payment precedes accrual
      C10   baseline=pass  mutated=failed    a rate effective on D stops being in force on D, so the window opening on D is not the one it applies to
      C11#1 baseline=pass  mutated=failed    every run holds its first payment, so re-amortisation stops re-sizing when the rate moves
      C11#2 baseline=pass  mutated=failed    the contracted schedule is sized from the live balance instead of the opening principal
      C12   baseline=pass  mutated=failed    each segment is rounded as it accumulates instead of once at the charge point
      C13   baseline=pass  mutated=failed    change points stop splitting the range, so piecewise accrual no longer equals the daily loop
      C14   baseline=pass  mutated=failed    the last scheduled payment no longer settles the remaining balance
      C15   baseline=pass  mutated=failed    the offset floor is removed, so an offset above the balance produces negative interest
      C16#1 baseline=pass  mutated=failed    a change point effective on the first day of the range is ignored rather than applied to the whole range
      C16#2 baseline=pass  mutated=failed    a future range no longer holds today's offset total flat
      Verified 16 contract rows (18 mutations): every row's tests pass unmutated and fail when its behaviour is broken
      

      Three things this run confirms:

      • The anchor still lands. C11#2's anchor exists exactly once on #405's engine, and its mutation still fails the adapted test.
      • C8's quoting held through the merge. It prints "(the #48 defect)" in full.
      • #405's re-anchored rows still bite. C3, C4, C6, C8 and C10 carry #405's descriptions, and they still fail when mutated alongside the new list rows.

      Loan::ContractMutationManifestTest's one-mutation-per-entry check also runs in every suite. If a later merge dropped C11#2, that check would fail rather than let the gate pass silently.

  • "code master" review (comment 6105905139), HOLD, on 079cc2c2d. One fix is in 4e17e3731, pushed once this PR's full Gatekeeper review had landed (below).

    • F1, a pipe in a cell aborts the gate: valid in part; fixed in the held commit.
      • GitHub-flavoured Markdown keeps a pipe inside a table cell only when it is escaped as \|. An unescaped pipe splits the rendered table's row too.
      • But the parser also split on \|, so it refused a correctly escaped row. It now splits only on unescaped pipes.
      • An unescaped pipe is still refused, and the message names the row and the count: "C15: expected 4 columns, found 5".
      • The new test asserts both. It fails if the split reverts and if the column guard is removed; both were tried.
      • No row holds an escaped pipe today, so no row reads differently.
    • F2, positional pairing passes silently: declined, on a run.
      • The gate passes only when every mutation fails its own entry's tests, so a mismatched pair shows up as a survivor.
      • I swapped C16's two mutations without swapping its test entries and ran loans:verify_contract_mutations[C16]. It printed C16#1 baseline=pass mutated=SURVIVED and C16#2 baseline=pass mutated=SURVIVED, and exited 1.
      • So the claim that "both mutations survive, but the gate reports them as caught" is the opposite of what the gate does.
      • The only silent case is a mismatched entry whose tests happen to catch the other mutation as well. Even then the row is still shown to fail when broken, by one of its own tests.
    • F3, semantic no-op mutations: declined. The gate's mutated=failed requirement is exactly that check: a mutation that changes nothing survives, and the gate fails on it. The manifest test's find != replace is only a cheap first check.
    • F4, a nil cells[1]: declined. A line reaches the split only after it matches /^\| C\d+ \|/, so cells[1] is always the row id.
  • Full Gatekeeper review, in three parts: comment 6107569871, 6107594241 and 6107637786, on 079cc2c. APPROVE, risk HIGH, confidence HIGH, CI passing apart from the quota-bound github-advanced-security.

    • The reviewer checked that both new anchors are unique in their production files and that both tests fail under their mutations.
    • Requirements are aligned, and the test evidence is adequate.
    • The light review's MODERATE finding is resolved by the #404 gate run.
    • No blocking findings:
      • MODERATE, the #48 truncation: already fixed here (C8's defect is quoted). The reviewer's note that any future defect string with an inline #NN must stay quoted holds, and contract_mutation_manifest_test.rb reads the defects as YAML loads them.
      • OBSERVATION, positional pairing: it agrees a mismatched pair fails loudly as a survivor, which matches the C16 swap run above.
    • After the review: 4e17e3731 (the escaped-pipe fix from the "code master" review) was pushed on top. It changes only the row parser's split and adds one task test, and it doesn't touch what the review approved. Its CI runs on the new head.
  • Nightly review (comment 6120443724), READY TO MERGE, on 4e17e3731 (the head before main was merged in): no blocking and no other material findings.

    • Its note, that the contract gate must run again at #405's eventual merge head: agreed, and nothing to change here. The gate already ran on #404, which carries this PR merged with #405 (above). Most recently it ran at 8cf45291f: 16 rows and 18 mutations, all caught. The gate runs in CI on every PR, so it runs again at whichever head merges second.
  • CodeRabbit full review (review 5490197672), on 619f23330, requested on 2026-10-12. CodeRabbit gives this repository no automatic reviews (fewer than 10 stars). It rated the merge risk Low and made one inline finding, plus one failed pre-merge check. Both are declined:

    • 🟡 Minor, "count consecutive backslashes before splitting a pipe" (lib/tasks/loans.rake:57): declined; the proposed rule would disagree with GitHub.
      • The finding says \\| is a column break because the two backslashes escape each other.
      • GitHub's own parser (cmark-gfm, through cmarkgfm 2025.10.22) disagrees. It renders | C1 | one \\| two | three | four | as four cells, the first reading one | two, exactly as it renders \|. A pipe after a backslash is escaped whatever the count.
      • The current split, /(?<!\\)\|/, matches that.
      • The proposed odd/even rule would make the gate read a different column from the one GitHub displays, which is the failure the finding set out to prevent.
      • docs/loans/calculation-contract.md contains no escaped pipe today, so no current row depends on it either way.
    • Pre-merge check, docstring coverage 16.67% against an 80% threshold: declined. It is CodeRabbit's generic heuristic. This repository has no docstring convention, and the touched methods follow the comment style of the surrounding rake tasks.

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

  • No Issue Gatekeeper review before building. The owner asked for #406, #408 and #409 to be built today ("Build #406, 408 and 409"). I read that as the override for the issue-review wait. If the Gatekeeper review lands with findings, they get validated against this branch.

  • Merge with #405, already resolved in #404 (merge 078c317a7 on the integration branch). The conflicts and their resolutions:

    • C11: #405's strategy test and its re-anchored mutation become the first entry; this PR's test and mutation are the second.
    • C11 contract row: #405 had already dropped the dangling "contract regression" reference. The row keeps #405's wording and names both halves.
    • C8 mutation: #405's anchor stays. Its defect is quoted too, because it had the same #48 truncation.
    • C11 test: adapted to upstream's schedule API (schedule.principal, Payment rows).

    The full gate on #404 verifies the resolution (Review findings above). Whichever of #405 and this PR merges into main second takes the same resolution.

  • The gate still verifies one defect per behaviour. That is not whole-row coverage; contract-mutation-evidence.md says so.

  • Next unblocked issue: none from this one.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed loan amortization schedules so they remain based on the opening principal when the live balance changes.
    • Corrected forward offset calculations for flat future periods.
  • Tests
    • Added regression coverage for both calculation behaviors.
    • Contract checks now verify each listed behavior against its corresponding test and mutation, and report multi-behavior results separately.
  • Documentation
    • Updated loan calculation and release-gate documentation to reflect the expanded verification coverage.