SENIORPROJECTCHAPTER 29

Project: a reconciliation engine that finds every planted break

Grow the module 2 matcher into an engine that places every difference in a named kind or stops, closes the balance at any month end, checks the outside records, and scores itself on every seed and scale

120 MINPAYMENTSUPDATED 2026-11-14

You build one engine over the books you already know: Owoleaf’s ledger, the partner bank’s statement, the card processor’s settlement report and the instant-payment switch. It starts from the matcher in the reconciliation chapter of module 2. If you kept recon.py and rules.py from that lab, the engine is their code reorganised, with four changes. A rule for timing differences across a cut. A rule for partial returns. A stop that names any line no rule can place. A balance bridge that you can close at any date. Around it sit two checks against the outside records, and a scorer that runs the whole thing on seeds 1, 2 and 3 at scales 0.01, 0.1 and 1.

The chapter does not re-teach matching keys, value dates or the four original breaks. Read the reconciliation chapter first for those, and for how a posting for each kind is written.

What you build

Seven small files in labs/finance, each with one job.

File Job
engine.py Load both sides, pair, classify every difference or stop, close the bridge at any cut, propose the postings
report.py Run the engine on one data folder and print the findings, the month-end cuts and the postings. It never opens the answer key
timing_check.py Show the month-end cuts with and without the timing rule
stop_test.py Plant a break no rule knows, and check that the engine stops
legs.py Compare the card processor’s report and the switch’s records with what the engine found
score.py Compare the engine with answers/breaks.csv, both ways, and check that the bridge closes on every day
sweep.py Generate each seed and scale, start both mocks on it, run legs.py and score.py, delete the data

All money is integer kobo. The generator’s cut-off, fees and bank codes are illustrative, as in every earlier chapter, and the engine reads no rule from a regulator. The postings it proposes are a policy that a finance lead signs, not the engine.

Two breaks the first engine never saw

python3 generate.py --extra-breaks plants two more kinds on top of the nine you know, from a random stream of its own, so the default data does not change. Neither is a missing or a wrong line, and each defeats a plausible engine.

A month-end timing difference is a payout that the ledger books in the evening of the last day of a month (the generator picks a time from 18:00) and that the bank books soon after midnight on the 1st. Both sides have the line. Over the whole period it pairs on reference, side and amount, and any full-period matcher calls it clean. But the balances on the 31st differ by its amount, and a month-end close is exactly the comparison that sees it. The break is real on one date and gone on the next, so the engine cannot answer “is this a break?” without being told which date it is looking at. It has to answer “what is each line’s effect at this cut?”

A partial return is the beneficiary’s bank sending back part of a payout. The statement gets a credit that quotes the payout’s reference, for a fraction of its amount, and the ledger has no return. An engine that calls every leftover statement credit an unapplied credit files it as money from nowhere. But an unapplied credit carries a reference the ledger has never seen, and this one is a payout’s own. Reading it as an amount mismatch fails too, because there is no ledger line on the credit side left to differ from, and reading it as a duplicate fails because the amount is smaller. It needs a rule of its own that names its three properties.

Six kinds, six rules, in this order

Every rule sees only what the stricter ones left, as in the module 2 chapter.

Pass Rule Places
1 Same reference, side and amount the pairs, nearly every line
1b A pair whose two booking dates differ timing_month_end when the dates fall in different months, else timing
2 Same reference and side, another amount amount_mismatch
3 A statement line equal in reference, side and amount to a line already paired duplicate_on_statement
4 A credit on a payout’s reference, for less than the payout partial_return
5 A ledger line whose reference is nowhere on the statement missing_from_statement
6 A statement line whose reference is nowhere in the ledger unapplied_credit
– Anything left stop

The rules run strictest first, and rule 1 runs before everything. Rules 4 to 6 do not compete here, because each takes lines the others cannot: rule 4 only a credit on a payout’s reference, rule 5 only ledger lines, rule 6 only references the ledger has never seen. Remove rule 4 and the partial return is not misfiled: it is left over, and the engine stops. Rule 1b runs on pairs, not on leftovers, because the lines it names are not left over: they paired. The engine’s timing finding is never a line missing from one side. It is the date on a pair.

A cut: the same books on any date

The module 2 chapter closed a bridge from the ledger balance to the bank balance on every day, by value date, with items in transit. This engine cuts both sides by booking date, which both records carry, and closes the same kind of bridge at any date you give it. One function carries the idea:

a finding’s effect at a cut = the statement’s signed amount, if the bank had booked it by then, minus the ledger’s signed amount, if the ledger had booked it by then

A missing payout has only a ledger line, so its effect is the whole amount from the day the ledger booked it. A duplicate has only a statement line. An amount mismatch has both and the effect is the difference. A timing item has both lines on different days: at a cut between them, the ledger counts it and the bank does not, so its effect is the whole amount for that one cut. On every other cut, both counts are in or both are out, and it nets to zero. Nothing special-cases it. The bridge at the cut is then: bank balance − ledger balance = the sum of every finding’s effect at that cut, and the engine reports what is left over. The left-over must be zero on every day, because every line is then in exactly one bucket: paired, timing, or a named break.

Cutting by booking date is a choice. In the lab, as in the module 2 chapter, the bank’s closing balance for a date is by value date, and a booking after 23:00 (the generator’s cut-off) gets the next day’s value date. The two timing items here are booked by the bank at 00:06 and 00:23, so their value date is the 1st as well and nothing changes for them. To reproduce a bank’s closing balance exactly, cut by value date and carry the chapter’s in-transit term.

Stopping is a feature

An engine that ends with lines nobody placed has two honest outputs: say so, or be wrong. A job that skips them, or files them under the nearest kind, keeps passing its own tests while the books drift. So the engine raises Unplaced and names the first line. The lab plants one in a copy of the data: the bank books a payout as a credit. The ledger line has a reference that is on the statement, so it is not missing. The statement line has a payout’s reference, the payout’s own amount and the wrong side, so it is not partial, a duplicate or an unapplied credit. No rule fits, and none should.

The outside records

Two checks sit beside the bank statement, as in the module 2 chapter. The card processor’s settlement report, GET /settlements?date=, lists each day’s captures and a net. For every CARD SETTLEMENT line on the statement, legs.py asks three things: does the provider’s net equal the statement’s line and the ledger’s card_settlement, and are the captures on the report exactly the card fundings the ledger booked the day before? A card break would show here and nowhere in the cash matching. The switch is asked per finding, by requery (POST /tsq), what it holds under that reference.

Both legs are limited, and the chapter says how. The mocks build their records from the generated ledger, so they agree with the ledger by construction, and a clean provider leg proves the engine reads the settlement report correctly, not that a real processor agrees with a real ledger. The switch’s answers are still worth reading as shapes. It knows the payout behind a missing line, a mismatch and a duplicate, and so corroborates the ledger against the bank. It has no record of an unapplied credit, which fits money that arrived under a reference nobody issued. And it holds the full payout behind a partial return, which lets you say what share came back.

Proving it, not hoping

The score has three parts. The set of (kind, reference) pairs the engine reports must equal the set in answers/breaks.csv: a missed break and an invented one both fail, and comparing sets, not counts, is what catches an engine that misses one and invents another. The bridge must close on every day. And the run must stop on a line it cannot place, which stop_test.py checks once.

Then repeat on other data. Seeds change which payouts break and on which days. Scales change how many lines hide them, and how long the loops take. sweep.py runs seeds 1, 2 and 3 at scales 0.01 and 0.1 in about 16 seconds, and the lab runs scale 1 once, which generates about 715 MB and is deleted afterwards. A pass here proves the engine against the generator’s twelve breaks. It does not prove it against a real bank’s, and that is what the stop is for.

Where it goes wrong

A tolerance on amounts. The break at the end of the lab makes pass 1 ignore the amount. It looks like robustness. It hides the two amount mismatches and opens the bridge for 77 days.

Keying on the reference alone. A dictionary on the reference drops the returns, which quote their payout’s reference, and overwrites the second line of a duplicate. The module 2 chapter ran this, and the pair-set score would catch it at once.

Trusting a narration. The partial return’s narration says NIP RETURN PARTIAL. An engine that reads it works on this generator and nowhere else. The engine reads reference, side and amount, which the bank cannot word differently.

Editing the answer key to agree. If the score disagrees, one of two things is wrong, and the key is the generator’s record. Fix the engine.

Testing on one seed. Seed 42’s nine breaks passed a rule set that had no idea of timing across a cut. Three seeds with the same twelve kinds are only a start. The stop is what covers kinds you have not seen.

A slow bridge. My first version recomputed every day’s balances from every line. It took about 2 seconds at scale 0.1 and about 24 seconds at scale 1 on seed 1. Accumulating daily totals once takes 0.4 and about 5 seconds for the whole score, loading included, and the findings are the same.

Lab

LAB Build the engine, break it on purpose, and score it on every seed and scale ~90 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with generate.py, check.py and the two mocks (mock_provider.py, mock_switch.py)A second terminal for the mocks in step 5About 100 MB of free disk, and about 800 MB more if you run scale 1 in step 7

You work in labs/finance. You create seven files there: engine.py, report.py, timing_check.py, stop_test.py, legs.py, score.py and sweep.py. The data is a new folder, data-s1, generated at seed 1 with the extra breaks, so your numbers match the ones below and your existing data/ is untouched. Everything runs through Python’s sqlite3 module, so no sqlite3 program is needed. Do not open data-s1/answers/breaks.csv until step 6. It is the answer key. The outputs below were produced on Python 3.13. The code uses nothing newer than 3.9.

1. Generate the data and check the books. --extra-breaks adds the month-end timing difference and the partial return. check.py accounts for both in its invariant 6.

cd labs/finance
python3 generate.py --seed 1 --extra-breaks --out data-s1
python3 check.py --db data-s1/finance.sqlite
customers             2,000
accounts              2,005
transactions         85,298
entries             195,723
bank_statement       60,949
planted breaks           12  (answers/breaks.csv)
accounts by type (debit-positive kobo): {'asset': 17424481575, 'equity': -5000000000, 'expense': 103210123, 'income': -215534875, 'liability': -12312156823}
settlement_bank in ledger 17,318,178,775 kobo; on the statement 17,332,943,511 kobo
OK: all invariants hold

Twelve planted breaks, not nine: the nine of the module 2 chapter and the two timing items and one partial return. The ledger and the statement differ by 14,764,736 kobo on the last line (17,332,943,511 less 17,318,178,775), and check.py accepts that because the planted breaks explain it. Your job is to find them and say why. Seed 1 has 60,947 ledger lines on settlement_bank against 60,949 on the statement.

2. Save the engine and run it. engine.py is the module 2 matcher with the four changes. Read reconcile, contribution and bridges before you run anything: they are the chapter’s argument in code.

"""A reconciliation engine: the ledger's settlement_bank lines against the partner bank's statement.

Money is integer kobo. A line's side is CR (money in) or DR (money out), the bank's words; the
ledger debits settlement_bank when money comes in, so its side is flipped. Every difference is
placed in a named kind, or the run stops: nothing is dropped.
"""
import os
import sqlite3
from collections import defaultdict, namedtuple

L = namedtuple("L", "txn kind ref side kobo at")                    # a ledger line
S = namedtuple("S", "line value_date at side kobo ref narration")   # a statement line
Finding = namedtuple("Finding", "kind ref ledger statement")        # a break: a line on one side, or both


class Unplaced(Exception):
    """A line no rule could place. A new kind of break has appeared: stop and say so."""


def signed(side, kobo):
    return kobo if side == "CR" else -kobo


def load(data):
    db = sqlite3.connect(os.path.join(data, "finance.sqlite"))
    ledger = [L(*r) for r in db.execute("""
        SELECT t.id, t.kind, t.external_ref,
               CASE e.direction WHEN 'debit' THEN 'CR' ELSE 'DR' END, e.amount_kobo, e.posted_at
        FROM entries e
        JOIN accounts a ON a.id = e.account_id AND a.code = 'settlement_bank'
        JOIN transactions t ON t.id = e.transaction_id
        ORDER BY e.id""")]
    statement = [S(*r) for r in db.execute("""
        SELECT line, value_date, booked_at, direction, amount_kobo, reference, narration
        FROM bank_statement ORDER BY line""")]
    return ledger, statement


def day(line):
    return line.at[:10]


def reconcile(ledger, statement):
    """Pass 1 pairs on reference, side and amount. Every later rule sees only what is left."""
    free = defaultdict(list)
    for s in statement:
        free[(s.ref, s.side, s.kobo)].append(s)
    pairs, ledger_left = [], []
    for l in ledger:
        bucket = free.get((l.ref, l.side, l.kobo))
        if bucket:
            pairs.append((l, bucket.pop(0)))
        else:
            ledger_left.append(l)
    statement_left = sorted((s for b in free.values() for s in b), key=lambda s: s.line)

    findings, used = [], set()

    # 1b. A pair that agrees on everything but the booking date is a timing difference, not a break.
    for l, s in pairs:
        if day(l) != day(s):
            kind = "timing_month_end" if day(l)[:7] != day(s)[:7] else "timing"
            findings.append(Finding(kind, l.ref, l, s))

    stmt_refs = {s.ref for s in statement}
    ledger_refs = {l.ref for l in ledger}
    paired = {(s.ref, s.side, s.kobo) for _, s in pairs}
    by_ref = {(s.ref, s.side): s for s in statement_left}
    payout = {l.ref: l for l in ledger if l.side == "DR"}

    for l in ledger_left:                               # 2. same reference and side, another amount
        s = by_ref.get((l.ref, l.side))
        if s:
            findings.append(Finding("amount_mismatch", l.ref, l, s))
            used.update([("L", l.txn), ("S", s.line)])
    for s in statement_left:                            # 3. a second line for something already paired
        if ("S", s.line) not in used and (s.ref, s.side, s.kobo) in paired:
            findings.append(Finding("duplicate_on_statement", s.ref, None, s))
            used.add(("S", s.line))
    for s in statement_left:                            # 4. money back on a payout, for less than the payout
        p = payout.get(s.ref)
        if ("S", s.line) not in used and s.side == "CR" and p and s.kobo < p.kobo:
            findings.append(Finding("partial_return", s.ref, None, s))
            used.add(("S", s.line))
    for l in ledger_left:                               # 5. in the ledger, nowhere on the statement
        if ("L", l.txn) not in used and l.ref not in stmt_refs:
            findings.append(Finding("missing_from_statement", l.ref, l, None))
            used.add(("L", l.txn))
    for s in statement_left:                            # 6. on the statement, nowhere in the ledger
        if ("S", s.line) not in used and s.ref not in ledger_refs:
            findings.append(Finding("unapplied_credit", s.ref, None, s))
            used.add(("S", s.line))

    unplaced = [l for l in ledger_left if ("L", l.txn) not in used] + \
               [s for s in statement_left if ("S", s.line) not in used]
    if unplaced:
        u = unplaced[0]
        where = "ledger" if isinstance(u, L) else f"statement line {u.line}"
        raise Unplaced(f"{len(unplaced)} lines no rule could place; first: {where}, {u.ref[:8]}.. {u.side} {u.kobo:,} kobo")
    return pairs, findings


def contribution(f, cut):
    """What a finding does to (bank minus ledger) at the close of the day `cut`: each side counts
    only the lines it had booked by then. A timing item is a break at the cut and nothing later."""
    s = signed(f.statement.side, f.statement.kobo) if f.statement and day(f.statement) <= cut else 0
    l = signed(f.ledger.side, f.ledger.kobo) if f.ledger and day(f.ledger) <= cut else 0
    return s - l


def bridges(ledger, statement, findings):
    """For every day with any movement: (bank balance, ledger balance, what the findings explain, what
    is left) at the close of that day. Left must be 0 on every day: every line is in exactly one bucket."""
    bank_day, book_day = defaultdict(int), defaultdict(int)
    for s in statement:
        bank_day[day(s)] += signed(s.side, s.kobo)
    for l in ledger:
        book_day[day(l)] += signed(l.side, l.kobo)
    out, bank, book = {}, 0, 0
    for d in sorted(set(bank_day) | set(book_day)):
        bank, book = bank + bank_day[d], book + book_day[d]
        explained = sum(contribution(f, d) for f in findings)
        out[d] = (bank, book, explained, (bank - book) - explained)
    return out


def proposal(f):
    """The posting that brings the ledger to the bank's line, or None. The sign decides the accounts;
    the kind decides who is asked. A timing item needs no posting: the bank books it next month."""
    e = contribution(f, "9999")
    if f.kind.startswith("timing") or e == 0:
        return None
    return ("settlement_bank", "suspense", e) if e > 0 else ("bank_receivable", "settlement_bank", -e)


def month_ends(ledger):
    """The last ledger day of every month except the final one: the cuts a month-end close uses."""
    days = sorted({day(l) for l in ledger})
    return [a for a, b in zip(days, days[1:]) if a[:7] != b[:7]]


def naira(kobo):
    sign = "-" if kobo < 0 else ""
    kobo = abs(kobo)
    return f"{sign}₦{kobo // 100:,}.{kobo % 100:02d}"

Now report.py, which prints what the engine found, the month-end cuts and the postings it proposes.

"""Run the engine on one data folder and print what it found: python3 report.py data-s1
It never opens the answer key."""
import sys

import engine


def main(data):
    ledger, statement = engine.load(data)
    pairs, findings = engine.reconcile(ledger, statement)
    print(f"ledger lines {len(ledger):,}   statement lines {len(statement):,}   paired on pass 1 {len(pairs):,}")
    print(f"{'kind':<24}{'reference':<12}{'ledger':>12}{'statement':>12}{'bank - ledger':>15}  booked by the bank")
    net = gross = 0
    for f in sorted(findings, key=lambda f: (f.kind, f.ref)):
        e = 0 if f.kind.startswith("timing") else engine.contribution(f, "9999-12-31")
        net, gross = net + e, gross + abs(e)
        note = f" (ledger {engine.day(f.ledger)})" if f.kind.startswith("timing") else ""
        print(f"{f.kind:<24}{f.ref[:8] + '..':<12}{f.ledger.kobo if f.ledger else 0:>12,}"
              f"{f.statement.kobo if f.statement else 0:>12,}{e:>15,}  {engine.day(f.statement or f.ledger)}{note}")
    print(f"net over the period {net:,} kobo ({engine.naira(net)}); gross {gross:,} kobo ({engine.naira(gross)})")

    table = engine.bridges(ledger, statement, findings)
    print()
    print(f"{'cut':<12}{'bank - ledger':>15}{'timing':>15}{'breaks':>15}{'left':>6}")
    for cut in engine.month_ends(ledger) + [max(table)]:
        bank, book, explained, left = table[cut]
        timing = sum(engine.contribution(f, cut) for f in findings if f.kind.startswith("timing"))
        print(f"{cut:<12}{bank - book:>15,}{timing:>15,}{explained - timing:>15,}{left:>6}")
    print(f"bridge open on {sum(v[3] != 0 for v in table.values())} of {len(table)} days")

    print()
    print(f"{'proposed posting for':<24}{'debit':<18}{'credit':<18}{'kobo':>12}")
    after = sum(engine.signed(l.side, l.kobo) for l in ledger)
    for f in sorted(findings, key=lambda f: (f.kind, f.ref)):
        p = engine.proposal(f)
        if p:
            print(f"{f.kind:<24}{p[0]:<18}{p[1]:<18}{p[2]:>12,}")
            after += p[2] if p[0] == "settlement_bank" else -p[2]
    closing = sum(engine.signed(s.side, s.kobo) for s in statement)
    print(f"settlement_bank after the postings {after:,}; the bank's closing balance {closing:,}; equal: {after == closing}")


main(sys.argv[1] if len(sys.argv) > 1 else "data")
python3 report.py data-s1
ledger lines 60,947   statement lines 60,949   paired on pass 1 60,942
kind                    reference         ledger   statement  bank - ledger  booked by the bank
amount_mismatch         16404668..       314,324     316,824         -2,500  2026-04-29
amount_mismatch         32153597..     4,413,285   4,415,785         -2,500  2026-04-14
duplicate_on_statement  24732564..             0   1,109,398     -1,109,398  2026-05-21
duplicate_on_statement  99696124..             0   3,841,401     -3,841,401  2026-05-23
missing_from_statement  71686459..    13,184,798           0     13,184,798  2026-03-14
missing_from_statement  76924098..     2,997,500           0      2,997,500  2026-05-07
missing_from_statement  88328278..     1,186,744           0      1,186,744  2026-05-06
partial_return          26563561..             0     292,693        292,693  2026-06-11
timing_month_end        88935726..     2,234,563   2,234,563              0  2026-06-01 (ledger 2026-05-31)
timing_month_end        90350071..    10,754,507  10,754,507              0  2026-06-01 (ledger 2026-05-31)
unapplied_credit        39584520..             0     219,700        219,700  2026-06-06
unapplied_credit        94803682..             0   1,839,100      1,839,100  2026-05-16
net over the period 14,764,736 kobo (₦147,647.36); gross 24,676,334 kobo (₦246,763.34)

cut           bank - ledger         timing         breaks  left
2026-01-31                0              0              0     0
2026-02-28                0              0              0     0
2026-03-31       13,184,798              0     13,184,798     0
2026-04-30       13,179,798              0     13,179,798     0
2026-05-31       27,241,413     12,989,070     14,252,343     0
2026-06-29       14,764,736              0     14,764,736     0
bridge open on 0 of 180 days

proposed posting for    debit             credit                    kobo
amount_mismatch         bank_receivable   settlement_bank          2,500
amount_mismatch         bank_receivable   settlement_bank          2,500
duplicate_on_statement  bank_receivable   settlement_bank      1,109,398
duplicate_on_statement  bank_receivable   settlement_bank      3,841,401
missing_from_statement  settlement_bank   suspense            13,184,798
missing_from_statement  settlement_bank   suspense             2,997,500
missing_from_statement  settlement_bank   suspense             1,186,744
partial_return          settlement_bank   suspense               292,693
unapplied_credit        settlement_bank   suspense               219,700
unapplied_credit        settlement_bank   suspense             1,839,100
settlement_bank after the postings 17,332,943,511; the bank's closing balance 17,332,943,511; equal: True

Twelve findings, of six kinds, and none left over. Redo the totals by hand. The positive breaks are 13,184,798 + 2,997,500 + 1,186,744 + 292,693 + 219,700 + 1,839,100 = 19,720,535 kobo. The negative ones are 2,500 + 2,500 + 1,109,398 + 3,841,401 = 4,955,799. The net is 19,720,535 − 4,955,799 = 14,764,736, which is the gap check.py printed, and the gross is 19,720,535 + 4,955,799 = 24,676,334. The two timing items contribute nothing to either figure, because over the period they net to zero.

The cut table is where they appear. At 31 May the gap is 27,241,413 kobo (₦272,414.13). Of that, 2,234,563 + 10,754,507 = 12,989,070 is the two timing items, and 14,252,343 is the breaks booked by then. On 29 June the timing column is zero again, and the breaks are the whole gap. The bridge has nothing left on any of the 180 days. The last line shows that the proposed postings bring settlement_bank to the bank’s closing balance. The postings are proposals: nothing was written.

3. See what the timing rule does. Save timing_check.py. It runs the month-end cuts twice: once with the engine’s findings, and once with the timing findings removed.

"""Month-end cuts with and without the timing rule. python3 timing_check.py data-s1"""
import sys

import engine

ledger, statement = engine.load(sys.argv[1])
_, findings = engine.reconcile(ledger, statement)
no_timing = [f for f in findings if not f.kind.startswith("timing")]
cuts = engine.month_ends(ledger) + [max(engine.day(l) for l in ledger)]
print(f"{'cut':<12}{'bank - ledger':>15}{'left, no timing rule':>22}{'left, with it':>15}")
without, with_ = engine.bridges(ledger, statement, no_timing), engine.bridges(ledger, statement, findings)
for cut in cuts:
    bank, book, _, left_without = without[cut]
    left_with = with_[cut][3]
    print(f"{cut:<12}{bank - book:>15,}{left_without:>22,}{left_with:>15,}")
for f in findings:
    if f.kind.startswith("timing"):
        print(f"{f.kind}: ledger {f.ledger.at[:16]}, bank {f.statement.at[:16]}, {f.ledger.kobo:,} kobo")
python3 timing_check.py data-s1
cut           bank - ledger  left, no timing rule  left, with it
2026-01-31                0                     0              0
2026-02-28                0                     0              0
2026-03-31       13,184,798                     0              0
2026-04-30       13,179,798                     0              0
2026-05-31       27,241,413            12,989,070              0
2026-06-29       14,764,736                     0              0
timing_month_end: ledger 2026-05-31T22:18, bank 2026-06-01T00:06, 2,234,563 kobo
timing_month_end: ledger 2026-05-31T22:30, bank 2026-06-01T00:23, 10,754,507 kobo

Without the rule, the bridge is out by 12,989,070 kobo at 31 May and at no other cut. That is the month-end close from the Why: a gap that a full-period match cannot see and that is gone by the next date. With the rule, the bridge closes at every cut. The two lines were booked by the ledger at 22:18 and 22:30 on 31 May and by the bank at 00:06 and 00:23 on 1 June.

4. Make the engine stop. Save stop_test.py. It copies the database, flips one payout on the statement from debit to credit, and runs the engine on the copy.

"""A break no rule knows: the bank books one payout as a credit. The engine must stop, not drop it.
python3 stop_test.py data-s1"""
import os
import shutil
import sqlite3
import sys
import tempfile

import engine

work = tempfile.mkdtemp()
shutil.copy(os.path.join(sys.argv[1], "finance.sqlite"), work)
db = sqlite3.connect(os.path.join(work, "finance.sqlite"))
line, ref, kobo = db.execute("SELECT line, reference, amount_kobo FROM bank_statement "
                             "WHERE narration LIKE 'NIP OUTWARD%' ORDER BY line LIMIT 1 OFFSET 100").fetchone()
db.execute("UPDATE bank_statement SET direction = 'CR' WHERE line = ?", (line,))
db.commit()
db.close()
print(f"flipped line {line} ({ref[:8]}.., {kobo:,} kobo) from DR to CR in a copy")
ledger, statement = engine.load(work)
try:
    engine.reconcile(ledger, statement)
    print("the engine said nothing: that is the bug")
except engine.Unplaced as e:
    print("stopped:", e)
shutil.rmtree(work)
python3 stop_test.py data-s1
flipped line 390 (31253619.., 2,052,499 kobo) from DR to CR in a copy
stopped: 2 lines no rule could place; first: ledger, 31253619.. DR 2,052,499 kobo

Two lines are left, the ledger’s payout and the flipped statement line, and the engine stops with the first one named. Nothing was dropped and nothing was filed under a kind it does not belong to. Your own data is untouched, because the script works on a temporary copy.

5. Check the outside records. Start both mocks on the new data, one per terminal, from labs/finance. --fresh clears their state. They read the generated ledger, and they do not need a webhook or callback receiver here.

python3 mock_provider.py --data data-s1 --fresh --quiet
python3 mock_switch.py --data data-s1 --fresh --quiet
mock_provider on http://127.0.0.1:8101  secret sk_test_owoleaf_mock  webhooks -> (none)
mock_switch on http://127.0.0.1:8102  institution P01  key sw_test_owoleaf_mock  callbacks -> (none)

Leave both running for this step. Save legs.py and run it from a third terminal.

"""The two outside records besides the bank: the card processor's settlement report and the
instant-payment switch. Standard library only. Money is integer kobo."""
import datetime as dt
import json
import os
import sqlite3
import urllib.request

PROVIDER = ("http://127.0.0.1:8101", "sk_test_owoleaf_mock")
SWITCH = ("http://127.0.0.1:8102", "sw_test_owoleaf_mock")


def call(service, method, path, body=None):
    base, key = service
    req = urllib.request.Request(base + path, method=method, data=None if body is None else json.dumps(body).encode(),
                                 headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.loads(r.read())


def provider_leg(data, provider=PROVIDER):
    """Compare, for every statement line CARD SETTLEMENT: the provider's net for that date, the
    ledger's card_settlement for that date, and the captures on the report against the ledger's
    card fundings of the day before. Returns a dict of counts and a list of differences."""
    db = sqlite3.connect(os.path.join(data, "finance.sqlite"))
    stmt = dict(db.execute("SELECT substr(booked_at, 1, 10), amount_kobo FROM bank_statement "
                           "WHERE narration = 'CARD SETTLEMENT'"))
    book = dict(db.execute("""SELECT substr(e.posted_at, 1, 10), e.amount_kobo FROM entries e
                              JOIN accounts a ON a.id = e.account_id AND a.code = 'settlement_bank'
                              JOIN transactions t ON t.id = e.transaction_id AND t.kind = 'card_settlement'"""))
    captures = {}
    for ref, at in db.execute("SELECT external_ref, created_at FROM transactions "
                              "WHERE kind = 'funding_card' AND status = 'succeeded'"):
        captures.setdefault(at[:10], set()).add(ref)
    out = {"days": 0, "captures": 0, "differences": [], "owed": []}
    days = sorted(stmt)
    for d in days:
        rep = call(provider, "GET", f"/settlements?date={d}")
        refs = {x["reference"] for x in rep["lines"]}
        out["days"] += 1
        out["captures"] += len(refs)
        if not (rep["net_kobo"] == stmt[d] == book.get(d)):
            out["differences"].append((d, "net", rep["net_kobo"], stmt[d], book.get(d)))
        if refs != captures.get(rep["captured_on"], set()):
            out["differences"].append((d, "captures", len(refs), len(captures.get(rep["captured_on"], set()))))
    settled = {(dt.date.fromisoformat(d) - dt.timedelta(days=1)).isoformat() for d in days}
    out["owed"] = [(d, len(r)) for d, r in sorted(captures.items()) if d not in settled]
    return out


def switch_view(findings, switch=SWITCH):
    """Ask the switch about each reference a finding names. 25 means it has no record."""
    rows = []
    for f in findings:
        a = call(switch, "POST", "/tsq", {"payment_reference": f.ref})
        rows.append((f, a.get("response_code"), a.get("status"), a.get("amount_kobo")))
    return rows


if __name__ == "__main__":
    import sys
    import engine
    data = sys.argv[1] if len(sys.argv) > 1 else "data"
    ledger, statement = engine.load(data)
    findings = engine.reconcile(ledger, statement)[1]
    leg = provider_leg(data)
    print(f"provider: {leg['days']} settlement days, {leg['captures']:,} captures; {len(leg['differences'])} differences")
    print(f"          captures the provider has not yet paid for: {leg['owed']}")
    for f, code, status, amount in switch_view(sorted(findings, key=lambda f: (f.kind, f.ref))):
        print(f"switch:   {f.kind:<24}{f.ref[:8]}..  code {code}  status {status}  amount {amount}")
python3 legs.py data-s1
provider: 178 settlement days, 9,023 captures; 0 differences
          captures the provider has not yet paid for: [('2026-06-29', 96)]
switch:   amount_mismatch         16404668..  code 00  status successful  amount 314324
switch:   amount_mismatch         32153597..  code 00  status successful  amount 4413285
switch:   duplicate_on_statement  24732564..  code 00  status successful  amount 1109398
switch:   duplicate_on_statement  99696124..  code 00  status successful  amount 3841401
switch:   missing_from_statement  71686459..  code 00  status successful  amount 13184798
switch:   missing_from_statement  76924098..  code 00  status successful  amount 2997500
switch:   missing_from_statement  88328278..  code 00  status successful  amount 1186744
switch:   partial_return          26563561..  code 00  status successful  amount 1170773
switch:   timing_month_end        88935726..  code 00  status successful  amount 2234563
switch:   timing_month_end        90350071..  code 00  status successful  amount 10754507
switch:   unapplied_credit        39584520..  code 25  status None  amount None
switch:   unapplied_credit        94803682..  code 25  status None  amount None

The card leg is clean: on 178 settlement days the provider’s net equals the statement’s CARD SETTLEMENT line and the ledger’s card_settlement, and its 9,023 captures are exactly the card fundings of the day before. The 96 captures on 29 June are not paid for yet: the data stops there, so the next day’s report does not exist, which is a cut-off and not a break.

The switch answers per finding. It holds the payouts behind the three missing lines, the two mismatches, the two duplicates and the two timing items, each for the ledger’s amount, so on those it sides with the ledger against the bank. For the two unapplied credits it answers 25, no record. The partial return’s payout is ₦11,707.73 (1,170,773 kobo) and the return is 292,693 kobo: 1,170,773 × 0.25 = 292,693.25, so the bank returned a quarter, rounded to the nearest kobo (the generator picks a quarter, two fifths or a half). The mocks build these answers from the ledger, so agreeing with it is a property of the lab. A real switch’s report would disagree now and then.

Stop both mocks with Ctrl-C before the next step, so that step 7 can use their ports.

6. Score it against the key. Now you may open the answer key, and the scorer does. Save score.py.

"""Score the engine against the answer key: every planted break found, none invented, the bridge
closed on every day. python3 score.py data-s1"""
import csv
import os
import sys
import time

import engine


def score(data):
    """Returns (findings, answer key, problems, seconds the engine took). Problems must be empty."""
    t0 = time.time()
    ledger, statement = engine.load(data)
    _, findings = engine.reconcile(ledger, statement)
    table = engine.bridges(ledger, statement, findings)
    seconds = time.time() - t0
    key = {(r["kind"], r["reference"]) for r in csv.DictReader(open(os.path.join(data, "answers", "breaks.csv")))}
    found = {(f.kind, f.ref) for f in findings}
    problems = [f"MISSED   {k[0]} {k[1][:8]}.." for k in sorted(key - found)]
    problems += [f"INVENTED {k[0]} {k[1][:8]}.." for k in sorted(found - key)]
    problems += [f"BRIDGE   open on {d}" for d in sorted(table) if table[d][3] != 0]
    return findings, key, problems, seconds


if __name__ == "__main__":
    findings, key, problems, seconds = score(sys.argv[1])
    print(f"answer key: {len(key)} breaks; engine: {len(findings)} findings; {len(problems)} problems")
    for p in problems:
        print("  " + p)
    print(f"engine time {seconds:.2f} s")
    sys.exit(1 if problems else 0)
python3 score.py data-s1
answer key: 12 breaks; engine: 12 findings; 0 problems
engine time 0.39 s

All twelve breaks found, none invented, and the bridge closed on every day: the three parts of the score. The run takes about 0.4 seconds on 60,947 and 60,949 lines. Open data-s1/answers/breaks.csv now and compare it with step 2’s table by eye. It lists the same twelve references, each with the generator’s story: for the timing items, “booked by the bank on the 1st of the next month; nets to zero over the period”.

7. Run it on every seed and scale. Save sweep.py. For each seed and scale it generates the data, starts both mocks on it, runs the card and switch checks and the score, and deletes the data. It uses the default ports 8101 and 8102, so both mocks must be stopped.

"""Generate each seed and scale with --extra-breaks, start both mocks on that data, run the engine,
and score it against answers/breaks.csv. Deletes each dataset afterwards.

    python3 sweep.py --seeds 1 2 3 --scales 0.01 0.1
"""
import argparse
import collections
import shutil
import subprocess
import sys
import time
import urllib.request

import legs
import score


def wait(url):
    for _ in range(100):
        try:
            urllib.request.urlopen(url, timeout=1)
            return
        except Exception:
            time.sleep(0.1)
    raise SystemExit(f"nothing answered on {url}")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--seeds", type=int, nargs="+", default=[1, 2, 3])
    ap.add_argument("--scales", type=float, nargs="+", default=[0.01, 0.1])
    ap.add_argument("--provider-port", type=int, default=8101)
    ap.add_argument("--switch-port", type=int, default=8102)
    a = ap.parse_args()
    provider = (f"http://127.0.0.1:{a.provider_port}", legs.PROVIDER[1])
    switch = (f"http://127.0.0.1:{a.switch_port}", legs.SWITCH[1])
    cols = ["amount_mismatch", "duplicate_on_statement", "missing_from_statement", "unapplied_credit",
            "timing_month_end", "partial_return"]
    print(f"{'seed':>4} {'scale':>6} {'planted':>8} {'found':>6} {'invented':>9} {'missed':>7}   amt  dup  mis  una  tme  par {'engine s':>9} {'total s':>8}")
    bad = 0
    for scale in a.scales:
        for seed in a.seeds:
            t0 = time.time()
            data = f"sweep-s{seed}-x{scale}"
            subprocess.run([sys.executable, "generate.py", "--seed", str(seed), "--scale", str(scale),
                            "--extra-breaks", "--out", data], check=True, stdout=subprocess.DEVNULL)
            procs = [subprocess.Popen([sys.executable, "mock_provider.py", "--port", str(a.provider_port),
                                       "--data", data, "--fresh", "--quiet"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL),
                     subprocess.Popen([sys.executable, "mock_switch.py", "--port", str(a.switch_port),
                                       "--data", data, "--fresh", "--quiet"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)]
            try:
                wait(f"{provider[0]}/health")
                wait(f"{switch[0]}/health")
                findings, key, problems, engine_s = score.score(data)
                leg = legs.provider_leg(data, provider)
                if leg["differences"]:
                    problems.append(f"PROVIDER {len(leg['differences'])} differences")
                seen = legs.switch_view(findings, switch)
                if any(code == "25" for f, code, _, _ in seen if f.kind != "unapplied_credit"):
                    problems.append("SWITCH   has no record of a payout the engine named")
            finally:
                for p in procs:
                    p.terminate()
                    p.wait()
            kinds = collections.Counter(f.kind for f in findings)
            invented = sum(p.startswith("INVENTED") for p in problems)
            missed = sum(p.startswith("MISSED") for p in problems)
            bad += bool(problems)
            print(f"{seed:>4} {scale:>6} {len(key):>8} {len(findings):>6} {invented:>9} {missed:>7}  "
                  + " ".join(f"{kinds[c]:>4}" for c in cols) + f" {engine_s:>9.2f} {time.time() - t0:>8.1f}")
            for p in problems:
                print("     " + p)
            shutil.rmtree(data)
    print("ALL CLEAN" if not bad else f"{bad} run(s) with problems")
    sys.exit(1 if bad else 0)


main()
python3 sweep.py --seeds 1 2 3 --scales 0.01 0.1
seed  scale  planted  found  invented  missed   amt  dup  mis  una  tme  par  engine s  total s
   1   0.01       12     12         0       0     2    2    3    2    2    1      0.04      0.7
   2   0.01       12     12         0       0     2    2    3    2    2    1      0.03      0.6
   3   0.01       12     12         0       0     2    2    3    2    2    1      0.03      0.7
   1    0.1       12     12         0       0     2    2    3    2    2    1      0.40      4.7
   2    0.1       12     12         0       0     2    2    3    2    2    1      0.40      4.6
   3    0.1       12     12         0       0     2    2    3    2    2    1      0.39      4.6
ALL CLEAN

Twelve planted, twelve found, none invented or missed, on all six runs; each seed has two timing items, one partial return and the nine others (the columns are the six kinds). The whole sweep takes about 16 seconds, of which the engine is under a second per run.

Now scale 1, once. It generates about 715 MB and takes about a minute, and sweep.py deletes the folder at the end. Skip it if the disk is tight: scale 0.1 proves the same thing.

python3 sweep.py --seeds 1 --scales 1
seed  scale  planted  found  invented  missed   amt  dup  mis  una  tme  par  engine s  total s
   1    1.0       12     12         0       0     2    2    3    2    2    1      4.46     55.2
ALL CLEAN

The engine takes about 4.5 seconds for ten times the lines, and the whole run, with generation and the mocks, takes about 55 seconds. The twelve breaks are found among ten times as many lines, and the score is the same.

Make pass 1 forgiving. In engine.py change the key to ignore the amount, a tolerance of any size: make free[(s.ref, s.side, s.kobo)].append(s) read free[(s.ref, s.side)].append(s), and free.get((l.ref, l.side, l.kobo)) read free.get((l.ref, l.side)). Then run the score and show only its summary:

python3 score.py data-s1 | grep -E "MISSED|INVENTED|answer key|engine time"
answer key: 12 breaks; engine: 10 findings; 79 problems
  MISSED   amount_mismatch 16404668..
  MISSED   amount_mismatch 32153597..
engine time 0.43 s

The 79 problems are the two missed mismatches and the bridge, open on 77 days. Pass 1 now pairs the two lines whose amounts differ by ₦25, so no later rule sees them, and the bridge is out by ₦25 from 14 April and by ₦50 from 29 April. Everything else still passes: the tolerance changed no other finding. A job that counted only matches would call this change a harmless improvement, and the sweep, which compares both sets and closes the bridge on every day, rejects it on the first run. Put the two lines back and run the score again to see 0 problems.

ARTEFACT Write the month-end close sign-off with a suspense register ~50 MIN
YOU PRODUCEMonth-end close sign-off with suspense register

Template

# Month-end close sign-off: <month>, cut at <date>
Prepared by <finance operations lead> · Signs: <finance controller> · Written <date>

## Bridge at the cut
Bank minus ledger: <kobo> (<₦>)
Timing items (no posting): <kobo>, <what they are>
Open breaks: <kobo>
Left over: <kobo>. Days with the bridge open: <n of n>

## Open breaks
| Reference | Kind | Amount | Age at cut | Owner | Next action |
|---|---|---|---|---|---|

## Suspense register
| Reference | Amount | Why parked | Clear by (proposal) | Owner |
|---|---|---|---|---|

## What the engine stopped on
<line named, or 'nothing'; how it was resolved; what changed in the rules>

## What this cannot see
<one way this could be wrong, and what would show it>

## Decision and sign-off
Postings proposed, none written: <list>. Decision needed: <what, by when>
Signed: <name, role, date>
WORKED EXAMPLE

Chisom, who leads finance operations at Owoleaf, writes this; the finance controller signs it. Close of 31 May 2026 on seed 1, written 2 June.

Bridge. The bank is ₦272,414.13 (27,241,413 kobo) above the ledger. Two timing items explain ₦129,890.70: payouts the ledger booked at 22:18 and 22:30 and the bank at 00:06 and 00:23 on 1 June. They need no posting. Eight open breaks, netted, explain ₦142,523.43. Left over: 0, and the bridge is open on 0 of the 180 days. Ages are derived: days from the booked date the report prints to 31 May.

Reference Kind Amount Age Owner Next action
71686459.. missing ₦131,847.98 78 days Chisom ask Northmere Bank; the switch holds the payout
76924098.. missing ₦29,975.00 24 days Chisom same request
88328278.. missing ₦11,867.44 25 days Chisom same request
24732564.. duplicate ₦11,093.98 10 days Chisom claim back
99696124.. duplicate ₦38,414.01 8 days Chisom claim back
32153597.. mismatch ₦25.00 47 days Zuwaira find why the amount differs by ₦25
16404668.. mismatch ₦25.00 32 days Zuwaira same
94803682.. unapplied ₦18,391.00 15 days Chisom find the sender

Suspense. The three missing lines and the unapplied credit, ₦192,081.42 (derived: the four report amounts added), would be parked, as the lab’s proposed postings do. Missing: the ledger says paid, the bank has no line. Unapplied: money under a reference nobody issued (switch code 25). Clear-by dates are my proposal: 15 June for the credit, 30 June for the three missing lines.

Stops. None on May. The drill stopped on line 390, flipped on a copy.

Cannot see. The mocks agree with the ledger by construction, so a clean switch answer is weak proof.

Decision. Approve the postings, none yet written.

Now you

You lead finance operations at Owoleaf and it is 30 June. Write the June close sign-off for the same books, cut at 29 June, the last day the data holds. The finance controller signs it. Run report.py data-s1 and legs.py data-s1 (with the mocks started) and stop_test.py data-s1, then use their outputs. Three things have changed since May: the timing items have gone, the 11 June partial return has appeared, and the 6 June unapplied credit is new. Work out each break’s age at 29 June yourself, and decide which items belong in suspense and by when they should clear. Say which of the proposed postings you want signed now and which you would hold. The controller reads it to decide whether the books can close with those items still open.

Self-check

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Licences in Nigeria and what each one allows →