Build the G2b offset reconciliation, to run on a private statement

Draft
JA
2mo ago
+743-4

Summary

Part of #409. The private run remains, and that needs your data.

G2b means reconciling offset-reduced interest (contract rows C15 and C16) against a real lender. It needs:

  • a loan statement;
  • the linked offset accounts' daily balances.

Only you hold either, and neither may enter this public repository. This PR builds everything short of that data, so the private run is one command, and it leaves G2b open.

  • Loan::StatementReconciliation reads a normalised statement with the columns date,category,amount,balance,annual_rate,offset:

    • It walks the statement into charge windows. Balance, rate and offset change points are merged per date, so a repayment and an offset move on one day reach the engine as one point.
    • It charges each window through Loan::InterestAccrual, the call every offset-reduced charge ends in: on main through the simulator's daily accrual, and after #405 through Loan::DailyInterest.
    • It first checks the statement's own arithmetic: rows in date order, every movement summing to the running balance, every rate and offset move declared by its row, no negative rate or offset, and every interest row adding to what is owed. A later loan_disbursal is a further drawdown inside its window.
    • problems and summary carry row numbers and counts only, never amounts or dates.
  • loans:reconcile_statement[path,day_count_convention] runs it on a file outside the repository; it refuses a path inside the working tree.

    • It reconciles nothing when the statement's own arithmetic fails.
    • It prints exact, within-one-cent, the largest deviation and the basis, and it exits non-zero when any charge is more than a cent out.
    • VERBOSE=1 adds per-charge figures, for local investigation only.
    • It lives in its own rake file, so it doesn't collide with #406's edits to loans.rake.
  • A synthetic oracle, test/fixtures/loan_offset_reconciliation.csv. It has:

    • drawdown, repayments, a fee, a rate change inside a window, and three charges;
    • daily offset totals, including a day the offset exceeds the balance (C15) and offset changes on two windows' first days (C16);
    • an offset move on the same day as a repayment.

    Its charges (237.90, 93.68, 246.70) were computed by a day-by-day loop over the formula, written in Python independently of the engine, and rounded once half-up. They are not the engine's own output played back.

  • Docs: docs/loans/methodology.md gains "Running the offset reconciliation (G2b, #409)": how to normalise, run and record, and what may be recorded. G2b's evidence stays none in both gate tables (Loan::ReleaseGatesTest pins it). The tooling is described as tooling, in the next-action column.

Decisions made:

  • A separate fixture, not an extension of G2a's. G2a's fixture is the evidence behind a signed gate, so I left it untouched.
  • Six category tokens in the allowlist: loan_disbursal, repayment, fee, interest, rate_change, offset_balance. A real statement has scheduled repayments and fees, not only extra repayments.
  • Offsets are end-of-day totals, effective from their own date, which is what Loan::OffsetResolver already does with stored balances (group_by(date).last).
  • A tool for the private run. The plan only asked for the method and a fixture. A tool makes the private run use the same walker the oracle proves, rather than a hand calculation.
  • G2b's owner is now recorded as "repository owner (holds the data)" instead of unassigned. Change it if you meant someone else.

Scope and dependencies

  • Issue: #409 (Part of, so it stays open for the private run and sign-off).
  • Parent PR/branch, if stacked: none. Base main. Merged into #404 cleanly (e423d9f44, then ab69c1874 for the evidence-column fix; 943023e03 as f10217ebb).
  • Intentionally out of scope:
    • the private run itself;
    • the forward-flat projection (C16's second half), which no statement can show;
    • any engine change (a disagreement gets its own bug issue);
    • multiple lenders.
  • Blast radius: a new class, a new rake file, a new fixture and two new test files. Nothing existing calls the new code. The docs edits touch only the G2b rows and add a section. release-gates.md's G2b row is two lines below the G1 row #406 edits; #404 merged both cleanly.

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. (No contract row changed.)
  • 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.

Tests

  • test/models/loan/offset_reconciliation_test.rb (12):
    • the de-identification allowlist, and four free-text and shape rejections;
    • the fixture's arithmetic, and that it covers C15, C16, a rate change and a same-day move;
    • every charge equals the engine;
    • the same charges with the offsets read from stored balances through Loan::OffsetResolver, the production path;
    • every charge is higher with no offsets, so the oracle can't pass on offsets that don't matter;
    • problems reported by row number only;
    • deviation counting, the basis passed through, and refusal of wrong headers.
  • test/tasks/loan_reconciliation_task_test.rb (7): the report carries no fixture date or amount; a charge two cents out fails the task; a broken statement is not reconciled; the basis argument works; an unknown basis is refused; a path inside the repository is refused; a missing path gets usage.
  • Added in 943023e03, each failing first:
    • offset_reconciliation_test.rb (3): a row dated before the row above it is reported; negative rates and offsets, and an interest row that reduces what is owed, are reported; a later loan_disbursal is a drawdown inside its window.
    • loan_reconciliation_task_test.rb (4): problems are reported before the engine sees the statement; unreadable CSV is refused; a statement with no interest charge fails; a repository root of / refuses every statement.

Fail first. All 12 model tests failed before the class existed (11 NameError, 1 failure).

Mutations. Each one was applied, the two test files were run, and the file was restored; git status was clean afterwards:

mutationresult
C15: offset floor removed6 failures; charges 237.90, 89.55, 246.70 instead of 237.90, 93.68, 246.70
C16: change on the range's first day ignored6 failures; charges 263.97, 232.28, 284.20
OffsetResolver keeps a day's first stored balance, not its end-of-day onestored-balance test fails
reconciler drops the offset a window opens on5 failures
reconciler stops merging same-day changes6 failures
running-balance check removed2 failures
task reads a statement inside the repositoryrefusal test fails
task stops failing on a charge outside tolerancetolerance test fails

On #404 (#405's engine), the C15 and C16 mutations fail the same six tests each.

Validation

  • CI on 61f681fef: 32 of 33 checks green, including ci / test_unit and ci / test_system.

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

  • Full bin/rails test on 943023e03: 12,388 runs, 1 failure, 0 errors, 35 skips. The failure is the known local-only Provider::OpenaiTest Ruby 3.3 string.

  • Full bin/rails test on 8c53d5571: 12,381 runs, 2 failures, 0 errors, 35 skips.

    • The known local-only Provider::OpenaiTest Ruby 3.3 string.
    • Loan::ReleaseGatesTest "the two halves of G2 keep the scope that was actually signed". It pins G2b's evidence column to none so the open half can't drift into looking evidenced, and I had described the new tooling in that column. Fixed in 61f681fef, which moves the description to the next-action column. After the fix: release_gates_test.rb, offset_reconciliation_test.rb and reconciliation_test.rb give 23 runs, 0 failures. No code changed after the full run.
  • bin/rails test test/models/loan/offset_reconciliation_test.rb test/tasks/loan_reconciliation_task_test.rb test/models/loan/reconciliation_test.rb: 26 runs, 0 failures, both here and on #404's merge.

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

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

  • erb_lint, Biome: not applicable.

  • Checked against upstream AGENTS.md. G2b is fork-local, and this is not proposed upstream.

Review findings

  • Gatekeeper light review, in three parts: comment 6106316248, 6106332189 and 6106346678, on 61f681f. DRAFT_CONCERNS, risk HIGH. It checked two of the earlier automated review's claims against the engine and found both answered by normalize_change_points and historical_points, as finding 3 below records. Both of its material findings, and its suggested enhancement, are fixed in 943023e03:

    • MODERATE, charges computed before the statement's own arithmetic is checked: fixed (code master finding 1). The task now reads problems first, and charges only a statement that passes.
    • MODERATE, a zero-charge statement exits 0: fixed (code master finding 8). It now fails with "it holds no interest charge to compare".
    • Enhancement, a sign check on annual_rate and offset: done (code master finding 6). It is in problems, not parse, so it is reported by row number, like the other arithmetic checks.
  • "code master" review (comment 6105905025), hold, on 61f681fef. The fixes are in 943023e03, pushed once this draft's light Gatekeeper review had landed (above). Each fix was written test-first, with 7 new tests that failed for the right reason. Each was then broken deliberately, and a test caught it: 9 of 9. Locally, the reconciliation, task, G2a and release-gate tests give 37 runs, 0 failures.

    1. Charges are computed before problems are checked: valid; fixed.
      • The task now checks the statement's own arithmetic first, and charges only afterwards.
      • A malformed CSV (CSV::MalformedCSVError) is refused with a message instead of a backtrace.
    2. No date-order check: valid, though not for the reason given; fixed.
      • Order within a window was never the problem: Loan::InterestAccrual#normalize_change_points sorts change points by date.
      • But a row dated before the row above it falls outside its window's range, and that same filter drops it. Or it closes a window before the window opens, which the engine raises on.
      • problems now reports "row N: dated before the row above it".
    3. A zero offset is forced at the window's start on the offset_for: path: declined.
      • When the loan has countable offset accounts, Loan::OffsetResolver#change_points always emits a point on from_date. historical_points starts with one, carrying each account's latest balance from before that date forward, and the future branch returns one.
      • With no offset accounts it returns nothing, and zero is then the right offset.
      • So the zero is either always overwritten or correct.
    4. A second loan_disbursal discards the first window: valid; fixed. A later disbursal is now a further drawdown: a balance point inside its window.
    5. Unbounded input: declined. The task reads one statement that the owner normalises by hand on their own machine, and G2b needs six or more charges. A row cap would add code for a case no caller reaches.
    6. No sign checks on rate or offset: fixed. A negative rate or offset is reported in problems.
    7. A Rails.root of /: fixed. The check now walks the path's ancestors (realpath.ascend.include?(Rails.root.realpath)), so a root of / refuses every path.
    8. A statement with no interest rows exits 0: valid; fixed. The task now fails with "it holds no interest charge to compare".
    9. %.2f hides sub-cent deviations: declined.
      • The counts are computed on exact BigDecimals. A sub-cent deviation is not counted as exact, so the exact: line shows it even when the printed largest deviation reads 0.00.
      • The engine rounds to cents, so against a statement in cents a deviation can only be whole cents.
    10. Interest amount.abs hides the sign: valid; fixed. An interest row that reduces what is owed is now reported in problems.

    Siblings: problems, windows and change_points are the only readers of the parsed rows. docs/loans/methodology.md and the class header gain the new checks and the drawdown rule.

  • Nightly review (comment 6120443950), READY WITH CONDITIONS, on 943023e03 (the current head): no blocking findings.

    • MEDIUM, the evidence gate: agreed, and already how this PR is set up. The synthetic oracle proves the tool and the engine agree on the cases it covers. It is not lender evidence: G2b's evidence column stays none, pinned by Loan::ReleaseGatesTest. The review itself says this is a condition on release claims about offset accrual, not a defect in the tool.
    • Closing it needs the private run on your data, as under "Risks" below. Record only the non-sensitive summary lines, and leave G2b open if any difference stays unexplained. Nothing in this branch changes for it.

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

  • Blocked on you for what closes #409: a statement with six or more charges for one offset-linked loan, plus every linked offset account's end-of-day balances over the same period. Normalise them outside the repository as methodology.md describes, then run:

    bin/rails 'loans:reconcile_statement[/path/outside/the/repo.csv,<basis>]'

    Send me the summary lines (counts, largest deviation, basis), and I'll record them and the G2b row for your sign-off.

  • The normalisation is manual. Offset accounts already in Sure have their daily balances stored, and offset_for: can read them through Loan::OffsetResolver. A future option is to reconcile against the offset account as Sure holds it. I didn't build that, because it means trusting Sure's stored balances as the oracle's input.

  • No Issue Gatekeeper review before building: your "Build #406, 408 and 409" is the override I acted on.

  • Next unblocked issue: none.