Skip to main content

Bank8:Lending - Detailed Design Document

1. Scope & Context​

Bank8:Lending owns: the lending schema (schema-per-service - domain tables + lending.outbox / lending.audit_journal producer tables), lending products, versioned schedule templates, origination, disbursement, repayment allocation, the accrual and due cycle, the delinquency ladder and collections queue, restructure and write-off, collateral and guarantors, and the bank8:lending:* event family.

It does NOT own: money movement or balances (Bank8:Ledger), payment orchestration (Bank8:Payments), the book of account (Bank8:Accounting), prudential measurement (Bank8:Risk), AML detection (Bank8:Compliance), tenant-authored hooks (Sentin8:Func), schedule timing (Sentin8:Cron), or document bytes (Sentin8:Storage).

A loan is a ledger.accounts row (tside = 'ASSET'). Lending owns the contract - what is owed, when, and what happens when it is not paid - and the ledger owns the position.

2. Runtime Architecture​

Boot is shell-owned. build_state adds wiring and spawns the embedded cycle worker - a Bus SSE consumer that reacts to cycle events from Sentin8:Cron and drives accrual, due marking, and the delinquency ladder.

Money movement is always a ledger call. Lending builds a posting batch and submits it to POST /v1/postings. It never writes ledger.*; it holds no grant on that schema.

2.1 Posting mapping (normative)​

The ledger classifies an instruction by its type, not by arithmetic: debits_source() (bank8-ledger/src/handlers/postings.rs) treats WITHDRAWAL | FEE_APPLICATION | TRANSFER_OUT | REVERSAL_DEBIT | ADJUSTMENT_DEBIT as debit-direction, and the balance update applies debit -= amount, credit += amount. On an asset (loan) account a credit therefore increases the outstanding debt. The mapping below is the only correct one and must not be inverted:

Business eventBatch legsEffect
DisburseWITHDRAWAL: customer DDA → loan accountDDA down, loan debt up
Principal repaymentWITHDRAWAL: customer DDA → loan accountDDA down, loan debt down
Interest repaymentWITHDRAWAL: customer DDA → Interest Received internal acctDDA down, income up
Fee at disbursementWITHDRAWAL: loan account → Upfront Fee IncomeDebt up, income up
Accrual (daily)ACCRUAL: loan account at address ACCRUEDAccrual bucket up, debt unchanged
Interest applicationTRANSFER_OUT: loan ACCRUED → loan DEFAULTAccrual bucket down, debt up
Overpayment refundWITHDRAWAL: loan account → customer DDADebt reduced to credit, cash out
Write-offWITHDRAWAL: loan account → Principal Write-off / Interest Write-offDebt down, loss recognised

Accrual and application require address-scoped instructions (CAP-2); until that lands, accrual is recorded in loan_accruals and applied at cycle end as a single interest repayment.

3. Data Model​

TablePurposeRLS tier
loan_products / loan_product_versionsLending product definitions, versioned; a loan pins its opening versionenv
schedule_templates / schedule_template_versionsVersioned, simulatable amortization definitions (the WASM-referencable unit)env
loan_applicationsOrigination state machine (draft, submitted, approved, rejected)env
loansThe contract: ledger account binding, commitment, principal, term, status, schedule revisionholder + env
loan_schedules / loan_schedule_periodsRevisioned schedules and their per-period principal/interest/fee split and paid stateholder + env
loan_transactionsEvery movement with its ledger posting id and idempotency keyholder + env
loan_accrualsPer (loan, date) accrual recordsenv
payment_allocationsHow each repayment split across penalty/fee/interest/principalholder + env
delinquency_state / delinquency_actionsCurrent ageing state and pause/restore actionsenv
restructuresReschedule and re-age records with the superseded revisionholder + env
write_offsWrite-off and charge-off records with the posting idholder + env
collateral / guarantorsSecurity with valuation and coverageholder + env
rate_changesFloating-rate repricing eventsenv
lending.outbox / lending.audit_journalProducer tablesFORCE

Money precision: all amounts are NUMERIC(28,10). Rounding is applied per period at generation time and the residual is absorbed by the final period, so the schedule closes exactly.

4. API Surface​

AudienceRoutesAuth gateEvents emitted
ProductsGET/POST /v1/loan-products, GET /v1/loan-products/{id}, POST …/{id}/versionsbank8:lending:products:read / :writeproduct:upserted
TemplatesGET/POST /v1/schedule-templates, GET /v1/schedule-templates/{id}, POST …/{id}/versions, POST …/{id}/simulatebank8:lending:schedules:read / :writeschedule:generated
OriginationGET/POST /v1/applications, GET /v1/applications/{id}, POST …/{id}/approve, POST …/{id}/rejectbank8:lending:applications:read / :writeapplication:{submitted,approved,rejected}
LoansGET/POST /v1/loans, GET /v1/loans/{id}, GET …/{id}/schedule, GET …/{id}/transactions, GET …/{id}/arrearsbank8:lending:loans:read / :writeloan:opened
SchedulePOST /v1/loans/schedule/preview, POST /v1/loans/{id}/schedule/regeneratebank8:lending:schedules:writeschedule:regenerated
MoneyPOST /v1/loans/{id}/disburse, POST /v1/loans/{id}/repay, POST /v1/loans/{id}/refund-overpaymentbank8:lending:loans:writeloan:{disbursed,repayment:applied}
LifecyclePOST /v1/loans/{id}/restructure, POST /v1/loans/{id}/write-off, POST /v1/loans/{id}/charge-offbank8:lending:loans:writeloan:{restructured,written_off}
CollectionsGET /v1/collections/queue, POST /v1/loans/{id}/delinquency/pause, POST …/resumebank8:lending:collections:read / :writeloan:delinquent
SecurityGET/POST /v1/loans/{id}/collateral, GET/POST /v1/loans/{id}/guarantorsbank8:lending:collateral:read / :write-
InternalPOST /v1/internal/steps/execute (Flow proxy-back), POST /v1/internal/schedules/run (Cron proxy-back: accrual, due, delinquency)Shield + M2Mloan:accrued, loan:delinquent
Admin/SDUIGET /v1/admin/ui/{page}, GET /v1/admin/overviewbank8:lending:admin-

Schedule preview contract (writes nothing; journaled like /v1/contracts/simulate):

POST /v1/loans/schedule/preview
{ "product_version_id": "...", "principal": "25000.00",
"denomination": "CAD", "start_date": "2026-12-01",
"template_version_id": "..." }

200 { "template_version_id": "...", "periods": [
{ "period_no": 1, "due_date": "2027-01-01",
"principal_due": "…", "interest_due": "…", "fee_due": "…" } ],
"totals": { "principal": "25000.00", "interest": "…" },
"closes_to_zero": true }
422 when the generated schedule does not amortize to zero

Allocation precedence is declared by the product version (allocation_order, default penalty, fee, interest, principal) and is applied per repayment; the split is persisted in payment_allocations so a repayment is always explainable after the fact.

Admin/SDUI pages: overview, products, templates, applications, loans, collections, collateral, config.

5. Cross-Cutting Concerns​

  • Auth: platform token pipeline; Shield is the only gate.
  • Tenant + RLS: set_tenant_context on the same connection as the query; explicit WHERE env_id = $N; every table ENABLE + FORCE ROW LEVEL SECURITY. Loan-level rows additionally carry holder scoping so a customer sees only their own loans.
  • Identity: the cycle worker's certificate-presenting Bus client is the single outbound identity (CERTFREE-4V); a failed mint fails the consume closed.
  • Ledger interaction: posting via POST /v1/postings; reads via the public account, balance, and product APIs. A cross-schema grant on ledger.* is a defect.
  • Idempotency: every movement carries a deterministic key (loan:{id}:{kind}:{reference}); the ledger's partial unique index on (env_id, idempotency_key) absorbs a retry. Accrual is unique per (loan, date); due marking per (loan, period, date); delinquency events per (loan, transition).
  • Event emission: MemBus refresh (fail-soft) → outbox row in the domain transaction → relay → Bus.
  • Audit: lending.audit_journal in the same transaction plus Sys audit push. Approval, restructure, write-off, and delinquency pause all require an audited actor.
  • TLS: PQ-TLS via sentin8-tls.

6. Failure Modes & Recovery​

FailureBehaviour
Ledger rejects a posting (module guard, balance, idempotency conflict)Loan state not advanced; the ledger's reason is surfaced verbatim rather than rewritten.
Ledger unreachableThe movement fails closed with a retryable error; no local-only money state is ever recorded.
Local commit fails after the ledger acceptedA compensating reversal posting is issued and an alert raised - the pair is reconciled, never left ambiguous.
Cron retries an accrual runAbsorbed by the (loan, date) unique key.
Duplicate repayment submissionAbsorbed by the ledger's idempotency key; the original result is returned.
Schedule generation cannot close to zeroRejected at preview and at generation (422); no plug, no silent residual.
Cycle worker crashReplays from the Valkey stream; all handlers are idempotent.

7. Concurrency & Performance Model​

Pool capped (3–5). The hot path is the daily cycle: accrual and due marking over the active loan set, batched per environment with a bounded page size, single-writer per environment. Repayment is per-loan row-locked (SELECT … FOR UPDATE on the loan) so two concurrent repayments cannot both allocate against the same unpaid period; the ledger's balance-row serialization handles the money side.

Schedule generation is pure computation and can run concurrently.

8. Invariants​

  1. Loan before money. A loan must be opened and not disbursed before a disbursement; a disbursement cannot exceed the remaining commitment.
  2. Every movement is a posting. No loan balance is ever mutated locally; loan_transactions.ledger_posting_id is mandatory for money rows.
  3. Schedules close to zero. SUM(principal_due) == principal_disbursed within currency scale, with the residual absorbed by the final period.
  4. Allocation is explainable. Every repayment's split is persisted; the sum of allocations equals the repayment amount.
  5. Accrual is per-day unique. One accrual per (loan, date).
  6. Delinquency transitions are idempotent - one event per transition.
  7. History is additive. Restructure creates a new schedule revision and supersedes the previous; nothing is deleted. Write-off is a terminal status with postings.
  8. Product version is pinned. A loan's product version does not change implicitly; migration is explicit and audited.
  9. No cross-service table access. Lending never reads or writes ledger.*, accounting.*, risk.*, or compliance.* tables.

9. Testing Strategy​

  • Contracts crate - shared loan/schedule/allocation shapes for the SDK facade.
  • Policy suite (tests/policy.rs) - seeded scope-mirror text with the handler-action parity matrix.
  • DB invariants (tests/db_invariants.rs, live bank8 DB): FORCE-RLS rejection; (loan, date) accrual uniqueness absorbs a duplicate cycle; payment_allocations sum equals the repayment; schedule principal sums to the disbursed principal; a write-off is terminal and produces a posting id; restructure leaves the prior revision readable; no lending view references ledger.*.
  • Amortization golden tests - hand-calculated schedules for equal-installment and equal-principal over 30/360 and actual/365, asserted to the cent, including the final-period residual.
  • Allocation tests - partial payments, overpayment, penalty-first and principal-first orders.
  • OpenAPI drift (tests/openapi_drift.rs).
  • E2E - UI-only through the BFF: apply → approve → disburse → repay → view schedule, driven from eTeller and eBank.

10. Open Questions​

  • Whether the schedule generator executes as a ledger-side Func module (fully sandboxed) or in-process with a Func hook at the boundaries. Current position: in-process generator with a scheduled_event hook, because the schedule is a pure function of contract data.
  • Tranche disbursement on revolving products.
  • Whether arrears include accrued-but-unapplied interest before the cycle boundary.

Architecture & Design: bank8:lending and its underlying concepts were designed by Hamid Jahanzad.