SENIORPROJECTCHAPTER 57

Project: a sending bank, a switch and a receiving bank, settled and reconciled

Build the three sides of an instant transfer as small services, replay one generated day of the week through them with its timeouts, requeries and settlement sessions, and reconcile every bank's log against the switch

150 MINPAYMENTSUPDATED 2026-11-18

You have met each side one at a time in this module: the sending bank, the receiving bank and the switch. Here you build all three and run one day through them. The sending bank debits the customer and asks the switch to carry the transfer. The switch looks the account up, hands the transfer to the receiving bank, times it out if the answer is late, answers status queries and, at the end, settles the banks in sessions. The receiving bank credits an account or refuses. None of them knows what the others have done unless it asks. Almost every difficulty in the project comes from that.

The lab is a model, not the network run by NIBSS (the Nigeria Inter-Bank Settlement System, the operator of NIP, the NIBSS Instant Payment service: see Nigeria’s rails). Its codes, fees, levy, timeout, requery policy and cut-offs are the generator’s, written to teach, and the chapter never offers them as NIBSS’s, the CBN’s (the Central Bank of Nigeria’s) or any bank’s. The few real rules it leans on are in dated boxes, from search summaries of the regulator’s and the operator’s own documents.

Acceptance

The project is done when all of this holds on your run of Wednesday 17 June:

  1. Every session nets to zero, all five that the day touches. Each of the three sessions wholly inside the day (20260617-2, -3 and -4) also matches the week’s settlement_positions exactly. The first and last sessions the replay touches do not match, and the criterion does not ask them to: Wednesday’s replay holds only the late part of the 04:00 session (the rest is Tuesday evening) and only the early part of Thursday’s 04:00 session (the rest is Thursday’s small hours).
  2. No customer is reversed after a late success. Of the 17 timeouts, the 6 that the receiving bank credited anyway are all completed, and nothing is left in suspense at the end of the day.
  3. Every planted break of that day is found, and none is invented, when the same reconciliation reads the week’s bank_log. Your own services give no findings.

What you build

Eight small files in labs/finance, next to rails.py, whose fee schedule and cut-offs they import so no number is typed twice.

File Job
netkit.py A tiny JSON-over-HTTP server and client, and the replay’s clock (the X-Sim-Time header)
receiver.py The receiving bank (port 8303): name check, credit, refuse, status, idempotent by session id
switch.py The switch (port 8302): name enquiry, transfer, timeout, status query, settlement sessions
sender.py The sending bank (port 8301): debit into suspense, complete or reverse, requery
replay.py Feeds one day of name_enquiries and transfers to the sending bank at the times the data gives
story.py Prints what the day did: enquiries, the outage, the timeouts, the money in suspense
reconcile.py Compares each bank’s own log with the switch’s record of the same sessions
accept.py The three acceptance checks, and the answer key at the end

Each service keeps one book per institution inside one process, so the sending bank is every sender at once and the receiving bank every receiver. That is a shortcut for the lab, and it changes nothing the project teaches.

The day, and why Wednesday

Wednesday 17 June has what the project needs: the outage of one large bank (B07, 11:02 to 11:49), timeouts, refusals for closed and frozen accounts, and three of the week’s planted breaks. About a third of its transfers go to a saved beneficiary and carry no name enquiry of their own, and the replay and the switch must accept that. The replay takes every name enquiry and transfer dated that day, in time order. Because the week is data and not a clock, each request carries the moment it happened in an X-Sim-Time header, and the services read it. A day replays in well under ten seconds.

The replay also plays the world. The data says which accounts are frozen or closed, which bank is down, and which transfers got no answer in time, and the replay makes the services meet those facts through three test headers (X-Sim-Fault, X-Sim-Latency-Ms, X-Sim-Credit-At). A receiving bank told to be slow processes the credit later and answers too late to count. One told lost never receives it. The switch cannot tell the two apart. That is the whole problem.

One rule: ask before you reverse

When the switch gets no answer, the sending bank holds the customer’s money in a suspense account, which belongs to neither side for the moment. Three things can then be true. The receiving bank never got the transfer. It is still working. Or it credited and its answer was lost. The sending bank cannot tell which, and has one safe tool, the status query: ask the switch what happened to this session.

Answer to the status query Meaning in the model The sending bank
00 credited completes: take the fee, clear suspense
09 in progress waits, asks again in 60 seconds (the lab’s policy)
25 no record reverses: money back to the customer
anything else unknown waits, and after 30 asks hands it to a person

Only the 25 reverses. Reverse on 09 and you create the break the week plants four times: a customer reversed, and a beneficiary credited, for one transfer. The status query is also the only way the switch learns a late credit happened. In this model a transfer settles only when its final status is 00, and a late success reaches 00 only through a query. A sender that never asks leaves a credit with no settlement, which is another planted break.

Search summaries of the CBN’s Regulation on Instant (Inter-Bank) Electronic Funds Transfer Services in Nigeria, which sources date to 2018 (effective 2 October 2018; one entry gives 20 October), say that funds delivered within 60 seconds mark a payment as instant; that the sending entity must refund the customer in full for a failed transaction returned by the receiving entity within 10 minutes, and for a transaction it was unable to process within one hour after the next settlement closure; that a wrongly credited transfer is to be reversed by the receiving entity within one business day where funds are available; and that settlement is as agreed among participants but not later than T+1, meaning one business day after the transaction. Press and law-firm reports add a ₦10,000 fine per item for a failed transfer not reversed within 24 hours of a complaintas of 2026-11. Those summaries are all this chapter saw, and they do not settle whether the 10 minutes and the 24 hours are two clocks or one: the sending bank and debited but not credited set out the same figures and the same doubt. Read the regulation itself, and any later circular, before you copy a timeout or a refund time into a real system. The lab’s 30-second switch timeout, 60-second requery and 30-ask limit are not the regulation’s numbers.

Settling in sessions

Each completed transfer lands in a settlement session, a window between two cut-offs (see how banks settle with each other). In the lab the cut-offs are 04:00, 10:00, 14:00 and 18:00 on business days, each settled an hour later. The switch assigns a session from the time the transfer became final, not the time it was sent: a transfer that timed out at 13:58 and was confirmed at 14:01 settles in the 18:00 session. For each session the switch adds up what every participant sent and received. The net positions add to zero, because every kobo one participant sends another receives. A participant sponsored by a bank settles through that bank (see direct or sponsored): the settles_via column names it. On NIP the customer’s credit comes first and the banks settle afterwards.

NIBSS’s NIP page, as search summaries show it, describes NIP as a deferred net settlement system in which funds are available online, in real time, in the beneficiary’s account before settlement takes placeas of 2026-11. Deferred net means the banks settle the difference between what they owe each other at set times, not transfer by transfer. The summaries disagree on how many settlement sessions NIP runs (12 on the operator’s page in one summary, four a day in a 2022 case study), so this chapter gives no schedule as real: the lab’s four cut-offs are the generator’s.

A calendar day is not a settlement day. Wednesday’s replay holds the transfers sent on Wednesday, so the first session it touches (the 04:00 one) is missing Tuesday evening, and the last (Thursday’s 04:00) is missing Thursday’s small hours. Both still net to zero, because any set of completed transfers does. Only the three sessions wholly inside the day can match the week’s settlement_positions exactly, and the acceptance check requires that of those three and nothing of the other two.

Reconciling each bank against the switch

The switch’s record is the middle. Each bank’s own log is checked against it, one session at a time:

  • the sender’s outward row against the switch’s final status: completed and settled agree; reversed and unsettled agree; anything else is a break
  • the sender’s fee against the fee schedule, and the receiver’s levy (in the lab, a flat ₦50 on a receipt of ₦10,000 or more, standing in for the government charge in the receiving bank) against the levy rule
  • the receiver’s inward row against the switch: credited with no settlement, or settled with no credit
  • more than one outward row for a session: a customer debited, or reversed, twice

The same find function reads two sources. Your services’ logs should give nothing, because your sending bank waits for the status query. The week’s bank_log, written by banks the generator made careless, gives the planted breaks of the day. A reconciliation that finds nothing in your banks and three in the week’s has shown something, not only passed.

What the model leaves out

The generator also has a participant hit its collateral limit, but only on Friday, so this replay does not model participant limits. There are no balances, so the sending bank debits without checking funds. A customer’s mistyped number is stopped by the sender’s own NUBAN check digit (the last digit of the ten-digit account number, computed from the others; see account numbers), before the network: you will see 50 such enquiries that never reach the switch, and 18 more answered 07 by the receiving bank because the account is closed. The sender asks again every 60 seconds because in the data a slow receiving bank credits about 90 seconds after the transfer on average, and never later than about two minutes. A real bank’s policy would be tuned to its switch’s rules, and the rules are the real ones, not these. A pass here proves the three sides agree on one generated day. It does not prove a real bank’s.

Where it goes wrong

Reversing on a timeout. The break at the end changes one line so that the sender reverses on anything but 00. Six customers are reversed while their beneficiaries are credited.

Reading a session as a day. The first and last sessions of the replay do not match the week, and a check that expected every session to match would fail on a correct switch.

A second credit for a repeated message. The receiver keys its credits by session id. Without that, a status query arriving after the slow credit would credit twice. Posting twice balances every entry, so the double-entry check cannot catch it. Only the key does.

Counting the money you cannot see. The timeouts hold money in suspense for one or two minutes. A bank that does not post suspense hides it from the books for exactly the interval in which an auditor would ask where it is.

Lab

LAB Build the three services, replay Wednesday, settle it and reconcile it ~90 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with rails.py and check.pyThree terminals for the services, a fourth for the replayAbout 20 MB of free disk; no Docker, no packages

You work in labs/finance. You create eight files there: netkit.py, receiver.py, switch.py, sender.py, replay.py, story.py, reconcile.py and accept.py. They read data/rails.sqlite and write only to a run/ folder. The services keep their state in memory, so stop and restart all three before every replay: a second replay against the same processes would find every session already known. Do not open data/answers/rails_truth.csv until step 9. The outputs below were produced on Python 3.13; the code uses nothing newer than 3.9, and the times are from one machine.

1. Generate the week and check it. rails.py writes a separate world from Owoleaf’s ledger, in about a second. check.py --rails-only proves invariants 21 to 25. The network it models is the one in Nigeria’s rails.

cd labs/finance
python3 rails.py
python3 check.py --rails-only
32 participants, 22,835 accounts, 17,998 transfers, 12,158 name enquiries, 136 status queries
21 settlement sessions, 125 batch files, 193 RTGS payments, 3,412 USSD sessions, 3,453 PSB postings
planted (answers/rails_truth.csv): credited_without_settlement 4, customer_fee_not_charged 6, customer_reversed_twice 3, levy_not_charged 5, mmo_trust_shortfall 1, participant_limit 4, participant_outage 1, psb_cash_out_fee_not_posted 1, psb_cash_out_posted_twice 1, reversed_after_late_success 4, same_number_two_banks 8, switch_incident 1, telco_record_missing 12
rails week: 17,998 transfers, 21 settlement sessions, 22,835 accounts; checks 21-25 run
OK: all invariants hold

The planted line counts the week’s breaks by kind: four reversed_after_late_success, three customer_reversed_twice, five levy_not_charged and others that belong to other chapters. The twelve telco_record_missing concern the telcos’ USSD records and do not touch this chapter. Yours are the ones that fall on Wednesday. The numbers are the generator’s, not any real network’s.

2. Save the plumbing and the receiving bank. netkit.py is the server and client the three share. receiver.py is the side that knows least: it can credit, refuse, or take a credit late, and it never learns whether the sender’s customer was debited. This is the side taught in the receiving bank. Read credit_route before you run anything: the slow and lost branches are the chapter’s problem in code, and the check on sid in credits or sid in pending is why a repeated message credits once (the idea is idempotency, keyed here by session id).

"""Plumbing shared by the three services: a tiny JSON-over-HTTP server and client.

Standard library only. Time in this project is the week's time, not the clock on the wall:
the replay puts the moment an event happened in an X-Sim-Time header and each service
reads it, so a day that took 24 hours in the data replays in under a minute.
"""
import datetime as dt
import http.client
import json
import sqlite3
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

DB = "data/rails.sqlite"
TEST_HOOKS = ("X-Sim-Fault", "X-Sim-Latency-Ms", "X-Sim-Credit-At")   # how the replay makes the world misbehave


def db():
    return sqlite3.connect(DB)


def when(text):
    return dt.datetime.fromisoformat(text)


class Client:
    """One keep-alive connection to one service."""

    def __init__(self, port):
        self.port, self.conn = port, None

    def call(self, method, path, body=None, now=None, headers=None):
        h = {"Content-Type": "application/json"}
        if now:
            h["X-Sim-Time"] = now.isoformat()
        h.update(headers or {})
        data = json.dumps(body).encode() if body is not None else None
        if self.conn is None:
            self.conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30)
        self.conn.request(method, path, data, h)
        r = self.conn.getresponse()
        return r.status, json.loads(r.read() or b"{}")


def serve(name, port, routes):
    """routes maps (method, path) to f(body, now, headers) -> (http_status, dict). One lock: one request at a time."""
    lock = threading.Lock()

    class Handler(BaseHTTPRequestHandler):
        protocol_version = "HTTP/1.1"
        wbufsize = 65536            # headers and body leave in one packet: no 40 ms wait per call

        def log_message(self, *args):
            pass

        def handle_any(self):
            n = int(self.headers.get("Content-Length") or 0)
            body = json.loads(self.rfile.read(n) or b"{}")
            sim = self.headers.get("X-Sim-Time")
            fn = routes.get((self.command, self.path.split("?")[0]))
            with lock:
                status, out = fn(body, when(sim) if sim else None, self.headers) if fn else (404, {"error": "no such route"})
            raw = json.dumps(out).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(raw)))
            self.end_headers()
            self.wfile.write(raw)

        do_GET = do_POST = handle_any

    server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
    server.daemon_threads = True
    print(f"{name} listening on 127.0.0.1:{port}", flush=True)
    server.serve_forever()
"""The receiving bank: credits an account, or refuses, for every institution.

    python3 receiver.py --port 8303

It answers the switch. It never learns whether the sender's customer was debited.
"""
import argparse
import datetime as dt

from netkit import db, serve, when
from rails import LEVY, LEVY_THRESHOLD

accounts, down = {}, {}            # (bank, number) -> (status, holder); bank -> [(start, end)]
credits, pending, log, postings = {}, {}, [], []


def load():
    con = db()
    for bank, no, holder, status in con.execute("SELECT institution, account_no, holder, status FROM accounts"):
        accounts[(bank, no)] = (status, holder)
    for who, start, end in con.execute("SELECT who, start_at, end_at FROM outages WHERE who != 'switch'"):
        down.setdefault(who, []).append((when(start), when(end)))


def is_down(bank, now):
    return any(s <= now < e for s, e in down.get(bank, []))


def post(sid, *lines):
    assert sum(k for _, k in lines) == 0
    postings.extend((sid, acct, kobo) for acct, kobo in lines)


def credit_now(sid, bank, no, amount, at):
    levy = LEVY if amount >= LEVY_THRESHOLD else 0
    credits[sid] = dict(institution=bank, session_id=sid, direction="in", account_no=no, amount_kobo=amount,
                        customer_fee_kobo=0, levy_kobo=levy, status="credited", posted_at=at.isoformat(), reversed_at="")
    log.append(credits[sid])
    post(sid, ("settlement_due", amount), (f"cust:{no}", -amount))
    if levy:
        post(sid, (f"cust:{no}", levy), ("levy_payable", -levy))


def apply_due(now):
    """A slow credit lands when its time comes."""
    for sid in [s for s, p in pending.items() if p["at"] <= now]:
        p = pending.pop(sid)
        credit_now(sid, p["bank"], p["account"], p["amount"], p["at"])


def name_route(body, now, h):
    apply_due(now)
    bank, no = body["bank"], body["account"]
    if is_down(bank, now):
        return 503, {"error": "bank unavailable"}
    status, holder = accounts.get((bank, no), (None, ""))
    if status is None or status == "closed":
        return 200, {"code": "07"}
    return 200, {"code": "00", "name": holder}


def credit_route(body, now, h):
    apply_due(now)
    sid, bank, no, amount = body["session_id"], body["bank"], body["account"], body["amount_kobo"]
    if is_down(bank, now):
        return 503, {"error": "bank unavailable"}
    if sid in credits or sid in pending:                       # the same session twice credits once
        return 200, {"code": "00", "duplicate": True}
    status, _ = accounts.get((bank, no), (None, ""))
    if status is None or status == "closed":
        return 200, {"code": "07"}
    if status == "frozen":
        return 200, {"code": "57"}
    fault = h.get("X-Sim-Fault", "")
    if fault == "slow":                                        # processed, but the answer comes too late to count
        pending[sid] = dict(bank=bank, account=no, amount=amount, at=when(h["X-Sim-Credit-At"]))
        return 504, {"error": "no answer in time"}
    if fault == "lost":                                        # never arrived
        return 504, {"error": "no answer in time"}
    credit_now(sid, bank, no, amount, now)
    return 200, {"code": "00", "latency_ms": int(h.get("X-Sim-Latency-Ms", 900))}


def status_route(body, now, h):
    apply_due(now)
    sid = body["session_id"]
    return 200, {"state": "credited" if sid in credits else "processing" if sid in pending else "unknown"}


def dump_route(body, now, h):
    apply_due(dt.datetime.max.replace(tzinfo=dt.timezone.utc))
    return 200, {"log": log, "postings": postings, "pending": len(pending)}


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=8303)
    load()
    serve("receiving bank", ap.parse_args().port, {("POST", "/name"): name_route, ("POST", "/credit"): credit_route,
                                                   ("POST", "/status"): status_route, ("GET", "/dump"): dump_route})

3. Save the switch. It owns the timeout, the status query and the sessions: see inside a switch and clearing and settlement at the switch. Read transfer_route: a transfer with an empty ne_ref is a saved beneficiary’s, so the switch checks a reference only when there is one. Then read tsq_route: the switch learns a late credit only by asking the receiving bank when a sender asks it, and it closes a session as a timeout only when the receiver says it has no record.

"""The switch: carries name enquiries and transfers, answers status queries, settles in sessions.

    python3 switch.py --port 8302 --receiver-port 8303
"""
import argparse
import datetime as dt

from netkit import Client, TEST_HOOKS, db, serve
from rails import SESSION_CUTOFFS, WAT, is_business, switch_fee

records, ne_log, tsq_log = {}, {}, []
sponsor = {}
receiver = None
TIMEOUT_MS = 30_000            # ILLUSTRATIVE: how long the switch waits for a receiving bank


def session_of(t):
    """The first cut-off after t on a business day (the generator's rule: weekend traffic settles on Monday)."""
    d = t.astimezone(WAT)
    while True:
        if is_business(d.date()):
            for k, h in enumerate(SESSION_CUTOFFS, 1):
                cut = dt.datetime(d.year, d.month, d.day, h, tzinfo=WAT)
                if d < cut:
                    return f"{cut:%Y%m%d}-{k}"
        d = dt.datetime(d.year, d.month, d.day, tzinfo=WAT) + dt.timedelta(days=1)


def name_route(body, now, h):
    st, r = receiver.call("POST", "/name", {"bank": body["dest"], "account": body["account"]}, now)
    code = "91" if st == 503 else r["code"]
    ref = f"NE{len(ne_log) + 1:07d}"
    ne_log[ref] = dict(id=ref, at=now.isoformat(), src=body["src"], dest=body["dest"], account_no=body["account"],
                       response=code)
    return 200, {"code": code, "ne_ref": ref, "name": r.get("name", "")}


def finish(rec, code, now):
    rec["final"], rec["final_at"] = code, now.isoformat()
    if code == "00":
        rec["switch_fee_kobo"] = switch_fee(rec["amount_kobo"])
        rec["session"] = session_of(now)


def transfer_route(body, now, h):
    sid = body["session_id"]
    if sid in records:                                          # a repeat of the same session id
        return 200, {"code": "26", "first": records[sid]["first_response"]}
    if body["ne_ref"] and body["ne_ref"] not in ne_log:         # a saved beneficiary reuses an earlier enquiry: no ref
        return 200, {"code": "25"}
    hooks = {k: h[k] for k in TEST_HOOKS if k in h}
    st, r = receiver.call("POST", "/credit", {k: body[k] for k in ("session_id", "account", "amount_kobo")}
                          | {"bank": body["dest"]}, now, hooks)
    first = "91" if st == 503 else "97" if st == 504 else r["code"]
    rec = dict(session_id=sid, ne_ref=body["ne_ref"], at=now.isoformat(), src=body["src"], dest=body["dest"],
               debit_account=body["from_account"], credit_account=body["account"], amount_kobo=body["amount_kobo"],
               switch_fee_kobo=0, channel=body["channel"], first_response=first,
               latency_ms=TIMEOUT_MS if first == "97" else r.get("latency_ms", 0), final="pending", final_at="", session="")
    records[sid] = rec
    if first != "97":
        finish(rec, first, now)
    return 200, {"code": first, "session_id": sid}


def tsq_route(body, now, h):
    rec = records.get(body["session_id"])
    if rec is None:
        code = "25"
    elif rec["final"] != "pending":
        code = rec["final"] if rec["final"] != "97" else "25"
    else:
        _, r = receiver.call("POST", "/status", {"session_id": rec["session_id"]}, now)
        code = {"credited": "00", "processing": "09", "unknown": "25"}[r["state"]]
        if code == "00":
            finish(rec, "00", now)
        elif code == "25":
            finish(rec, "97", now)                              # never credited: closed as a timeout
    tsq_log.append(dict(id=f"TQ{len(tsq_log) + 1:07d}", session_id=body["session_id"], at=now.isoformat(),
                        asked_by=body["asker"], response=code))
    return 200, {"code": code}


def settle_route(body, now, h):
    pos = {}
    for r in records.values():
        if r["final"] == "00":
            pos.setdefault(r["session"], {}).setdefault(r["src"], [0, 0])[0] += r["amount_kobo"]
            pos[r["session"]].setdefault(r["dest"], [0, 0])[1] += r["amount_kobo"]
    rows = [dict(session=s, participant=p, settles_via=sponsor.get(p, "") or p, sent_kobo=o, received_kobo=i,
                 net_kobo=i - o) for s, ps in sorted(pos.items()) for p, (o, i) in sorted(ps.items())]
    return 200, {"positions": rows}


def dump_route(body, now, h):
    return 200, {"transfers": list(records.values()), "name_enquiries": list(ne_log.values()), "tsq": tsq_log}


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=8302)
    ap.add_argument("--receiver-port", type=int, default=8303)
    a = ap.parse_args()
    receiver = Client(a.receiver_port)
    sponsor.update({c: s for c, s in db().execute("SELECT code, sponsor FROM participants")})
    serve("switch", a.port, {("POST", "/name-enquiry"): name_route, ("POST", "/transfer"): transfer_route,
                             ("POST", "/tsq"): tsq_route, ("GET", "/settle"): settle_route, ("GET", "/dump"): dump_route})

4. Save the sending bank. This is the side of the sending bank and of debited but not credited. It holds the customer’s money in suspense while it waits. Read requery_route: one answer, 25, reverses.

"""The sending bank: debits the customer, asks the switch, completes or reverses.

    python3 sender.py --port 8301 --switch-port 8302

It reverses at once on a definite refusal (for example 57, a frozen account). After a
timeout it reverses a customer only when the status query says there is no record (25).
On anything else, "in progress" included, it waits and asks again.
"""
import argparse
import datetime as dt

from netkit import Client, TEST_HOOKS, db, serve
from rails import customer_fee, nuban_check

REQUERY_EVERY, MAX_REQUERIES = dt.timedelta(seconds=60), 30     # ILLUSTRATIVE policy
nuban, owners, out, postings = {}, set(), {}, []
suspense = dict(now=0)
counts = dict(refused_locally=0)
switch = None


def post(sid, *lines):
    assert sum(k for _, k in lines) == 0
    postings.extend((sid, acct, kobo) for acct, kobo in lines)
    for acct, kobo in lines:
        if acct == "suspense":
            suspense["now"] -= kobo


def complete(row, now):
    sid, amount, fee = row["session_id"], row["amount_kobo"], customer_fee(row["amount_kobo"])
    post(sid, ("suspense", amount), ("due_to_switch", -amount), (f"cust:{row['account_no']}", fee), ("fee_income", -fee))
    row.update(status="completed", customer_fee_kobo=fee)


def reverse(row, now):
    post(row["session_id"], ("suspense", row["amount_kobo"]), (f"cust:{row['account_no']}", -row["amount_kobo"]))
    row.update(status="reversed", reversed_at=now.isoformat())


def wake(row, now):
    row["requeries"] += 1
    if row["requeries"] > MAX_REQUERIES:
        return {}                                              # stop asking: a person must look at it
    return {"wake_at": (now + REQUERY_EVERY).isoformat()}


def name_route(body, now, h):
    src, dest, no = body["src"], body["dest"], body["account"]
    if nuban_check(nuban[dest], no[:9]) != no[9]:              # the check digit fails: no network call at all
        counts["refused_locally"] += 1
        return 200, {"code": "07", "local": True}
    st, r = switch.call("POST", "/name-enquiry", body, now)
    return 200, r


def transfer_route(body, now, h):
    sid, amount, acct = body["session_id"], body["amount_kobo"], body["from_account"]
    if sid in out:
        return 200, {"session_id": sid, "status": out[sid]["status"]}
    if (body["src"], acct) not in owners:
        return 200, {"code": "07"}
    row = dict(institution=body["src"], session_id=sid, direction="out", account_no=acct, amount_kobo=amount,
               customer_fee_kobo=0, levy_kobo=0, status="pending", posted_at=now.isoformat(), reversed_at="", requeries=0)
    out[sid] = row
    post(sid, (f"cust:{acct}", amount), ("suspense", -amount))
    _, r = switch.call("POST", "/transfer", body, now, {k: h[k] for k in TEST_HOOKS if k in h})
    code = r["code"]
    if code == "00":
        complete(row, now)
        return 200, dict(session_id=sid, code=code, status=row["status"])
    if code == "97":
        return 200, dict(session_id=sid, code=code, status="pending", **wake(row, now))
    reverse(row, now)                                          # a definite refusal: the customer gets the money back
    return 200, dict(session_id=sid, code=code, status="reversed")


def requery_route(body, now, h):
    row = out[body["session_id"]]
    if row["status"] != "pending":
        return 200, {"session_id": row["session_id"], "status": row["status"]}
    _, r = switch.call("POST", "/tsq", {"session_id": row["session_id"], "asker": row["institution"]}, now)
    code = r["code"]
    if code == "00":
        complete(row, now)
    elif code == "25":
        reverse(row, now)
    else:
        return 200, dict(session_id=row["session_id"], code=code, status="pending", **wake(row, now))
    return 200, dict(session_id=row["session_id"], code=code, status=row["status"])


def dump_route(body, now, h):
    return 200, {"log": list(out.values()), "postings": postings, "suspense": suspense, "counts": counts}


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=8301)
    ap.add_argument("--switch-port", type=int, default=8302)
    a = ap.parse_args()
    switch = Client(a.switch_port)
    con = db()
    nuban.update({c: n for c, n in con.execute("SELECT code, nuban_code FROM participants")})
    owners.update(con.execute("SELECT institution, account_no FROM accounts WHERE kind = 'customer'"))
    serve("sending bank", a.port, {("POST", "/name-enquiry"): name_route, ("POST", "/transfer"): transfer_route,
                                   ("POST", "/requery"): requery_route, ("GET", "/dump"): dump_route})

5. Start the three services. Use three terminals, in this order (what a real switch needs to stay up is in running a switch). They listen on 8301 (sending bank), 8302 (switch) and 8303 (receiving bank).

python3 receiver.py     # terminal 1
python3 switch.py       # terminal 2
python3 sender.py       # terminal 3
receiving bank listening on 127.0.0.1:8303
switch listening on 127.0.0.1:8302
sending bank listening on 127.0.0.1:8301

Each prints its line and waits. Nothing happens until the replay sends it something.

6. Save the replay and run it. replay.py reads Wednesday’s name enquiries and transfers, sorts them by time and sends each to the sending bank with the moment it happened. It makes the services meet the data’s frozen accounts, its outage (when a bank or a switch goes down) and its timeouts, and it rings the sending bank’s timer when the bank asks to be woken. Then it saves what each service recorded and compares the switch’s answers with the week’s.

"""Replay one day of the week through the three services, then save what each one recorded.

    python3 replay.py --date 2026-06-17

The day's name enquiries and transfers go to the sending bank at the times the data says. The
replay stands in for the world: a frozen account, an outage and a slow receiving bank are
all in the data, and it makes the services meet them. It also stands in for the sending bank's
timer, calling /requery when the bank asked to be woken.
"""
import argparse
import heapq
import json
import os
import time

from netkit import Client, db, when
from switch import TIMEOUT_MS


def load(date):
    con = db()
    con.row_factory = lambda c, r: {d[0]: r[i] for i, d in enumerate(c.description)}
    transfers = con.execute("SELECT * FROM transfers WHERE substr(at, 1, 10) = ? ORDER BY at", (date,)).fetchall()
    needed = {t["name_enquiry_id"] for t in transfers}
    enquiries = [e for e in con.execute("SELECT * FROM name_enquiries ORDER BY at")
                 if e["at"][:10] == date or e["id"] in needed]
    credit_at = {r["session_id"]: r["posted_at"] for r in
                 con.execute("SELECT session_id, posted_at FROM bank_log WHERE direction = 'in'")}
    return transfers, enquiries, credit_at, con


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--date", default="2026-06-17")
    ap.add_argument("--sender-port", type=int, default=8301)
    ap.add_argument("--switch-port", type=int, default=8302)
    ap.add_argument("--receiver-port", type=int, default=8303)
    ap.add_argument("--out", default="run")
    a = ap.parse_args()
    sender, switch, receiver = Client(a.sender_port), Client(a.switch_port), Client(a.receiver_port)
    transfers, enquiries, credit_at, con = load(a.date)
    heap, seq = [], 0
    for kind, rows in (("ne", enquiries), ("send", transfers)):
        for r in rows:
            seq += 1
            heapq.heappush(heap, (when(r["at"]), seq, kind, r))
    ne_ref, started, calls = {}, time.time(), 0
    while heap:
        now, _, kind, r = heapq.heappop(heap)
        calls += 1
        if kind == "ne":
            _, res = sender.call("POST", "/name-enquiry", dict(src=r["src"], dest=r["dest"], account=r["account_no"]), now)
            ne_ref[r["id"]] = res.get("ne_ref", "")
            continue
        if kind == "send":
            hooks = {"X-Sim-Latency-Ms": str(r["latency_ms"])}
            if r["first_response"] == "97":                      # the receiving bank is slow, or never got it
                if r["session_id"] in credit_at:
                    hooks.update({"X-Sim-Fault": "slow", "X-Sim-Credit-At": credit_at[r["session_id"]]})
                else:
                    hooks["X-Sim-Fault"] = "lost"
            body = dict(session_id=r["session_id"], ne_ref=ne_ref.get(r["name_enquiry_id"], ""), src=r["src"],
                        dest=r["dest"], from_account=r["debit_account"], account=r["credit_account"],
                        amount_kobo=r["amount_kobo"], channel=r["channel"])
            _, res = sender.call("POST", "/transfer", body, now, hooks)
        else:                                                  # "requery": the sending bank's timer rings
            _, res = sender.call("POST", "/requery", {"session_id": r}, now)
        if res.get("wake_at"):
            seq += 1
            heapq.heappush(heap, (when(res["wake_at"]), seq, "requery", res["session_id"]))
    os.makedirs(a.out, exist_ok=True)
    dumps = {"sender": sender.call("GET", "/dump")[1], "receiver": receiver.call("GET", "/dump")[1]}
    dumps["switch"] = switch.call("GET", "/dump")[1]
    dumps["switch"]["positions"] = switch.call("GET", "/settle")[1]["positions"]
    for name, d in dumps.items():
        with open(os.path.join(a.out, f"{name}.json"), "w") as f:
            json.dump(d, f)
    print(f"{a.date}: {len(enquiries)} name enquiries, {len(transfers)} transfers, {calls} events in {time.time() - started:.1f} s")
    first, final = {}, {}
    for t in dumps["switch"]["transfers"]:
        first[t["session_id"]], final[t["session_id"]] = t["first_response"], t["final"]
    same_first = sum(first.get(t["session_id"]) == t["first_response"] for t in transfers)
    same_final = sum(final.get(t["session_id"]) == t["final_status"] for t in transfers)
    print(f"first response agrees with the week: {same_first} of {len(transfers)}")
    print(f"final status agrees with the week:   {same_final} of {len(transfers)}")


if __name__ == "__main__":
    main()
python3 replay.py
2026-06-17: 2008 name enquiries, 2980 transfers, 5011 events in 3.3 s
first response agrees with the week: 2980 of 2980
final status agrees with the week:   2980 of 2980

Of the 5,011 events, 23 are the sending bank’s own wake-ups for requeries. The 2,008 name enquiries are fewer than the 2,980 transfers because 1,051 transfers (about a third) reuse a saved beneficiary’s earlier enquiry and have none of their own. All 2,980 transfers get the first response and the final status the week recorded, so your three services reproduce the day. The time on your machine will differ.

7. See what the day did. What a customer sees during a timeout is in debited but not credited. story.py prints the first responses, the enquiries and the seventeen timeouts, with what each cost.

"""What your run did on the day: name enquiries, the outage, the timeouts and the money in suspense."""
from collections import Counter

from netkit import when
from reconcile import load

run = load("run")
sw = run["switch"]
print("transfers by first response:", dict(sorted(Counter(t["first_response"] for t in sw["transfers"]).items())))
print(f"transfers with no name enquiry (a saved beneficiary's earlier one is reused): {sum(t['ne_ref'] == '' for t in sw['transfers'])}")
print("name enquiries that reached the switch:", dict(sorted(Counter(n["response"] for n in sw["name_enquiries"]).items())))
print(f"refused by the sending bank itself on the check digit, no network call: {run['sender']['counts']['refused_locally']}")
b07 = [n for n in sw["name_enquiries"] if n["response"] == "91"]
print("name enquiries answered 91 (the bank unreachable):", [f"{n['dest']} at {n['at'][11:19]}" for n in b07])
print("timeouts (first response 97):")
asks = Counter(q["session_id"] for q in sw["tsq"])
log = {r["session_id"]: r for r in run["sender"]["log"]}
for t in sw["transfers"]:
    if t["first_response"] == "97":
        secs = int((when(t["final_at"]) - when(t["at"])).total_seconds())
        print(f"  {t['src']}->{t['dest']} {t['amount_kobo']:>10} kobo  asked {asks[t['session_id']]}x  switch {t['final']}  customer {log[t['session_id']]['status']}  after {secs} s")
held = sum(x["amount_kobo"] for x in sw["transfers"] if x["first_response"] == "97")
n = sum(t["first_response"] == "97" for t in sw["transfers"])
print(f"held in suspense by the {n} timeouts: {held} kobo; left in suspense at the end of the day: {run['sender']['suspense']['now']} kobo")
print("transfers answered 91:", [f"{t['src']}->{t['dest']} at {t['at'][11:19]}" for t in sw["transfers"] if t["first_response"] == "91"])
print("B07 as a sender, 11:00 to 12:00:", [t["at"][11:19] for t in sw["transfers"] if t["src"] == "B07" and t["at"][11:13] == "11"])
python3 story.py
transfers by first response: {'00': 2932, '07': 11, '57': 16, '91': 4, '97': 17}
transfers with no name enquiry (a saved beneficiary's earlier one is reused): 1051
name enquiries that reached the switch: {'00': 1929, '07': 18, '91': 11}
refused by the sending bank itself on the check digit, no network call: 50
name enquiries answered 91 (the bank unreachable): ['B07 at 11:07:38', 'B07 at 11:09:18', 'B07 at 11:21:33', 'B07 at 11:28:14', 'B07 at 11:31:43', 'B07 at 11:32:51', 'B07 at 11:38:06', 'B07 at 11:40:07', 'B07 at 11:40:30', 'B07 at 11:43:19', 'B07 at 11:48:31']
timeouts (first response 97):
  B22->B24    8369900 kobo  asked 1x  switch 97  customer reversed  after 60 s
  B12->B18     113800 kobo  asked 2x  switch 00  customer completed  after 120 s
  B12->B17    1171800 kobo  asked 2x  switch 00  customer completed  after 120 s
  B17->F02    1041700 kobo  asked 1x  switch 97  customer reversed  after 60 s
  B20->P01    1239600 kobo  asked 1x  switch 97  customer reversed  after 60 s
  B01->B12    2328100 kobo  asked 1x  switch 97  customer reversed  after 60 s
  B20->F02     648000 kobo  asked 2x  switch 00  customer completed  after 120 s
  B20->B02     791200 kobo  asked 1x  switch 97  customer reversed  after 60 s
  B11->B19      29100 kobo  asked 2x  switch 00  customer completed  after 120 s
  B20->B12     631400 kobo  asked 1x  switch 97  customer reversed  after 60 s
  B07->P01    6621900 kobo  asked 1x  switch 97  customer reversed  after 60 s
  B06->B03    1733900 kobo  asked 1x  switch 97  customer reversed  after 60 s
  B03->B17    7175200 kobo  asked 1x  switch 97  customer reversed  after 60 s
  B04->B10      98400 kobo  asked 1x  switch 97  customer reversed  after 60 s
  B12->B21     592900 kobo  asked 1x  switch 97  customer reversed  after 60 s
  B11->B05    1629500 kobo  asked 2x  switch 00  customer completed  after 120 s
  B05->B13    4787000 kobo  asked 2x  switch 00  customer completed  after 120 s
held in suspense by the 17 timeouts: 39003400 kobo; left in suspense at the end of the day: 0 kobo
transfers answered 91: ['B03->B07 at 11:29:37', 'B17->B07 at 11:34:21', 'B12->B07 at 11:37:03', 'B10->B07 at 11:39:05']
B07 as a sender, 11:00 to 12:00: ['11:02:45', '11:03:26', '11:49:11', '11:59:57']

Read it as a story. Of 17 timeouts, 6 were credited anyway: the sender asked twice, 60 seconds apart, the first answer was 09, the second 00, and the customer’s transfer completed after 120 seconds. Those six moved 8,379,200 kobo (₦83,792). The other 11, 30,624,200 kobo (₦306,242), never reached the receiving bank: the first query answered 25 and the customer was reversed after 60 seconds. Together the 17 held 39,003,400 kobo (₦390,034) in suspense for one or two minutes: money that was the customer’s no longer and the receiver’s not yet. A bank that reversed all 17 at the first sign of trouble would have reversed 6 customers whose beneficiaries were paid. The other refusals are definite, so the sender reverses at once and holds nothing: 11 answered 07 at transfer (every one a closed account, reached with no name enquiry of its own), 16 answered 57 (frozen) and 4 answered 91.

The outage shows twice. Eleven name enquiries for B07 get 91, between 11:07 and 11:48, and four transfers to it get 91 (₦98,995 in all, reversed at once), all between 11:29 and 11:39. All four, like the eleven 07s, are saved-beneficiary transfers with an empty name_enquiry_id: nothing asked the bank before the money moved, so the first sign of trouble is the transfer itself. As a sender B07 is silent from 11:03:26 to 11:49:11; the two sends in the minute after 11:02 are the generator’s, left as it wrote them. The enquiry counts also add up: 1,929 answered 00, 18 answered 07 because the account is closed and 11 answered 91, which with the 50 stopped by the check digit make the 2,008.

8. Save the reconciliation and the acceptance checks, and run them. The method is reconciliation and the sessions are those of how banks settle with each other. reconcile.py compares each bank’s log with the switch. accept.py runs the three acceptance checks: every session nets to zero, your banks agree with the switch and no customer was reversed after a late success, and the same reconciliation, run on the week’s bank_log, finds breaks.

"""Reconcile each bank's own log against the switch's record of the same sessions.

    python3 reconcile.py                  # your sending and receiving bank services (run/)
    python3 reconcile.py --source week    # the week's bank_log, for the sessions in run/switch.json

A finding is (kind, session_id, institution). Kinds use the names the answer key uses.
"""
import argparse
import json
import os
from collections import defaultdict

from netkit import db
from rails import LEVY, LEVY_THRESHOLD, customer_fee


def load(folder):
    return {n: json.load(open(os.path.join(folder, f"{n}.json"))) for n in ("sender", "switch", "receiver")}


def week_log(sids):
    con = db()
    rows = [dict(institution=i, session_id=s, direction=d, account_no=a, amount_kobo=amt, customer_fee_kobo=f,
                 levy_kobo=l, status=st, posted_at=p, reversed_at=r) for i, s, d, a, amt, f, l, st, p, r in
            con.execute("SELECT institution, session_id, direction, account_no, amount_kobo, customer_fee_kobo, levy_kobo, "
                        "status, posted_at, reversed_at FROM bank_log")]
    return [r for r in rows if r["session_id"] in sids]


def find(run, source="services"):
    sw = {t["session_id"]: t for t in run["switch"]["transfers"]}
    if source == "week":
        log = week_log(set(sw))
        outs = [r for r in log if r["direction"] == "out"]
        ins = [r for r in log if r["direction"] == "in"]
    else:
        outs, ins = run["sender"]["log"], run["receiver"]["log"]
    sent, got = defaultdict(list), defaultdict(list)
    for r in outs:
        sent[r["session_id"]].append(r)
    for r in ins:
        got[r["session_id"]].append(r)
    found = []

    def add(kind, sid, inst, detail=""):
        found.append((kind, sid, inst, detail))

    for sid, t in sw.items():
        ok = t["final"] == "00"
        rows = sent.get(sid, [])
        if len(rows) > 1 or sum(r["status"] == "reversed" for r in rows) > 1:
            add("customer_reversed_twice", sid, t["src"], f"{len(rows)} outward rows")
        row = rows[0] if rows else None
        if row is None:
            add("no_sender_record", sid, t["src"])
        elif ok and row["status"] == "reversed":
            add("reversed_after_late_success", sid, t["src"], f"reversed at {row['reversed_at'][11:19]}")
        elif not ok and row["status"] == "completed":
            add("completed_but_not_settled", sid, t["src"])
        elif ok and row["customer_fee_kobo"] != customer_fee(t["amount_kobo"]):
            add("customer_fee_not_charged", sid, t["src"], f"{row['customer_fee_kobo']} of {customer_fee(t['amount_kobo'])} kobo")
        if row and row["amount_kobo"] != t["amount_kobo"]:
            add("amount_mismatch", sid, t["src"])
        credit = got.get(sid, [])
        if ok and not credit:
            add("settled_but_not_credited", sid, t["dest"])
        if credit and not ok:
            add("credited_without_settlement", sid, t["dest"], f"switch final {t['final']}")
        for c in credit:
            want = LEVY if c["amount_kobo"] >= LEVY_THRESHOLD else 0
            if ok and c["levy_kobo"] != want:
                add("levy_not_charged", sid, t["dest"], f"{c['levy_kobo']} of {want} kobo")
    for sid in set(sent) - set(sw):
        add("sender_record_unknown_to_switch", sid, sent[sid][0]["institution"])
    return sorted(found)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--run", default="run")
    ap.add_argument("--source", choices=["services", "week"], default="services")
    a = ap.parse_args()
    found = find(load(a.run), a.source)
    print(f"source: {a.source}")
    for kind, sid, inst, detail in found:
        print(f"  {kind:28} {inst}  {sid}  {detail}")
    kinds = defaultdict(int)
    for f in found:
        kinds[f[0]] += 1
    print(f"{len(found)} findings", dict(kinds) if kinds else "")


if __name__ == "__main__":
    main()
"""The acceptance checks for the project. Run after replay.py.

    python3 accept.py                     # reads run/
    python3 accept.py --answers           # step 9 only: opens answers/rails_truth.csv
"""
import argparse
import csv
import json
from collections import defaultdict

from netkit import db
from reconcile import find, load

ap = argparse.ArgumentParser()
ap.add_argument("--run", default="run")
ap.add_argument("--date", default="2026-06-17")
ap.add_argument("--answers", action="store_true")
a = ap.parse_args()
run = load(a.run)
problems = 0

# 1. every session nets to zero, and the books of both banks balance
net, count = defaultdict(int), defaultdict(int)
for p in run["switch"]["positions"]:
    net[p["session"]] += p["net_kobo"]
    count[p["session"]] += 1
con = db()
print("1. sessions")
for s in sorted(net):
    week = {p: (o, i) for p, o, i in con.execute("SELECT participant, sent_kobo, received_kobo FROM settlement_positions WHERE session = ?", (s,))}
    got = {p["participant"]: (p["sent_kobo"], p["received_kobo"]) for p in run["switch"]["positions"] if p["session"] == s}
    differ = sum(week.get(p) != got.get(p) for p in set(week) | set(got))
    inside = s.startswith(a.date.replace("-", "")) and not s.endswith("-1")      # wholly inside the day: must match
    print(f"   {s}  {count[s]:2} participants  net {net[s]} kobo  positions differing from the week's: {differ}"
          + ("" if inside else "  (edge session: not expected to match)"))
    problems += differ if inside else 0
problems += sum(v != 0 for v in net.values())
for who in ("sender", "receiver"):
    per = defaultdict(int)
    for sid, acct, kobo in run[who]["postings"]:
        per[sid] += kobo
    bad = sum(v != 0 for v in per.values())
    problems += bad
    print(f"   {who} postings: {len(run[who]['postings'])} lines, {bad} unbalanced sessions")
print(f"   sender suspense left at the end of the day: {run['sender']['suspense']['now']} kobo")
problems += run["sender"]["suspense"]["now"] != 0

# 2. your own banks agree with the switch, and nobody was reversed after a late success
mine = find(run, "services")
print(f"2. your services against the switch: {len(mine)} findings")
problems += len(mine)
credited = {r["session_id"] for r in run["receiver"]["log"]}
late = [t["session_id"] for t in run["switch"]["transfers"] if t["first_response"] == "97" and t["session_id"] in credited]
rev = {r["session_id"]: r for r in run["sender"]["log"]}
back = sum(rev[sid]["status"] == "reversed" for sid in late)
print(f"   timeouts that the receiving bank credited anyway: {len(late)}; customer reversed afterwards: {back}")
problems += back

# 3. the week's own banks: the breaks the same reconciliation finds in the week's bank_log
week = find(run, "week")
print(f"3. the week's bank_log against the switch: {len(week)} findings")
for k, sid, inst, d in week:
    print(f"   {k:28} {inst}  {sid}")

if a.answers:
    sids = {t["session_id"] for t in run["switch"]["transfers"]}
    kinds = {"reversed_after_late_success", "customer_reversed_twice", "levy_not_charged",
             "customer_fee_not_charged", "credited_without_settlement"}
    key = {(r["kind"], r["ref"]) for r in csv.DictReader(open("data/answers/rails_truth.csv")) if r["ref"] in sids}
    got = {(k, sid) for k, sid, _, _ in week}
    print(f"4. answer key for {a.date}: {len(key)} planted, {len(got)} found, {len(key - got)} missed, {len(got - key)} invented")
    problems += len(key ^ got)
print("PASS" if problems == 0 else f"{problems} problems")
python3 accept.py
1. sessions
   20260617-1  29 participants  net 0 kobo  positions differing from the week's: 32  (edge session: not expected to match)
   20260617-2  32 participants  net 0 kobo  positions differing from the week's: 0
   20260617-3  32 participants  net 0 kobo  positions differing from the week's: 0
   20260617-4  32 participants  net 0 kobo  positions differing from the week's: 0
   20260618-1  32 participants  net 0 kobo  positions differing from the week's: 29  (edge session: not expected to match)
   sender postings: 17796 lines, 0 unbalanced sessions
   receiver postings: 8316 lines, 0 unbalanced sessions
   sender suspense left at the end of the day: 0 kobo
2. your services against the switch: 0 findings
   timeouts that the receiving bank credited anyway: 6; customer reversed afterwards: 0
3. the week's bank_log against the switch: 3 findings
   customer_reversed_twice      B10  900846260617085841739492353100
   levy_not_charged             B14  900758260617090440793866373252
   reversed_after_late_success  B11  900998260617152952529806270881
PASS

Every session nets to zero, the partial ones too. Only 20260617-2, -3 and -4 sit wholly inside Wednesday, so only they must match the week’s positions exactly (0 differing) and accept.py counts a difference there as a problem; the first and last are the day’s edges, and a difference there is the correct result. Neither bank’s books show an unbalanced session, nothing is left in suspense, and your services find nothing wrong with themselves. The week’s own banks give three findings on the same day.

9. Reconcile by hand, then open the key. Mule chains and recalls are another matter, in fraud between banks; the breaks here are bank errors. reconcile.py alone checks your services; with --source week it checks the week’s bank_log against the same switch record. Read each finding, then score it against the answer key.

python3 reconcile.py
python3 reconcile.py --source week
python3 accept.py --answers | tail -2
source: services
0 findings 
source: week
  customer_reversed_twice      B10  900846260617085841739492353100  2 outward rows
  levy_not_charged             B14  900758260617090440793866373252  0 of 5000 kobo
  reversed_after_late_success  B11  900998260617152952529806270881  reversed at 15:30:37
3 findings {'customer_reversed_twice': 1, 'levy_not_charged': 1, 'reversed_after_late_success': 1}
4. answer key for 2026-06-17: 3 planted, 3 found, 0 missed, 0 invented
PASS

B10 reversed a customer twice, at full amount (₦6,794 each time), for a transfer to a closed account refused with 07: the first reversal at 08:59:21, a second at 11:58:41. B14 took no levy on a receipt of ₦13,449 (the lab’s levy is ₦50 from ₦10,000, illustrative). B11 reversed a customer at 15:30:37, 45 seconds after a transfer timed out at 15:29:52, although the receiving bank credited the beneficiary at 15:31:11 and the switch settled the transfer once B11’s status query answered 00 at 15:59:52. Three planted, three found, none invented or missed. The week’s four planted reversed_after_late_success are spread over the week, and only B11’s fell on Wednesday. The answer key also lists four telco_record_missing rows on that day; they belong to the USSD chapters, and accept.py leaves them out.

Make the sender reverse on any answer except 00. Stop all three services, and in sender.py change elif code == "25": in requery_route to elif code != "00":. Start the three services again, replay into a second folder, and look only at the summary:

python3 replay.py --out run-break
python3 accept.py --run run-break | grep -E "^[0-9]\.|differing|timeouts|PASS|problems"
python3 reconcile.py --run run-break
2026-06-17: 2008 name enquiries, 2980 transfers, 5005 events in 3.1 s
first response agrees with the week: 2980 of 2980
final status agrees with the week:   2974 of 2980
1. sessions
   20260617-1  29 participants  net 0 kobo  positions differing from the week's: 32  (edge session: not expected to match)
   20260617-2  32 participants  net 0 kobo  positions differing from the week's: 3
   20260617-3  32 participants  net 0 kobo  positions differing from the week's: 4
   20260617-4  32 participants  net 0 kobo  positions differing from the week's: 3
   20260618-1  32 participants  net 0 kobo  positions differing from the week's: 29  (edge session: not expected to match)
2. your services against the switch: 6 findings
   timeouts that the receiving bank credited anyway: 6; customer reversed afterwards: 6
3. the week's bank_log against the switch: 13 findings
22 problems
source: services
  credited_without_settlement  F02  900769260617111112219327031477  switch final pending
  credited_without_settlement  B18  900806260617070500037228802662  switch final pending
  credited_without_settlement  B17  900806260617080004446662512785  switch final pending
  credited_without_settlement  B13  900938260617161309499909139366  switch final pending
  credited_without_settlement  B19  900998260617120641686985989739  switch final pending
  credited_without_settlement  B05  900998260617152952529806270881  switch final pending
6 findings {'credited_without_settlement': 6}

The first query at 60 seconds answers 09 for the six slow credits, and the changed rule reverses the customer on it. The six beneficiaries are credited and the six customers are paid back: ₦83,792 twice. The sender never asks again, so the switch never learns of the credit and never settles it, which is why its final status disagrees with the week on 6 transfers and the six sessions are credited without settlement. The 22 problems are 10 participant positions that differ from the week’s in the three inside sessions (3, 4 and 3), the 6 findings and the 6 customers reversed after a late success. Every session still nets to zero, and so does every posting: double entry balances a double payment, so only the reconciliation, the position match and the acceptance check see it. Restore the line and run the replay on fresh services to see PASS again.

ARTEFACT Write the integration test report ~50 MIN
YOU PRODUCEIntegration test report

Template

# Integration test report: <system under test>
Written by <integration lead> · Signed by <head of engineering> and <head of payments operations> · <date> · Version tested: <commit or tag>

## Verdict
<Go / conditional go / no-go> for <pilot scope: who, what volume, how long>. <One sentence why.>

## What was tested, and how
- System under test: <services, versions, how started>
- Data: <the replayed day, how many events of each kind>
- Faults injected: <each fault, how the replay makes it happen>
- Repeatability: <fresh services each run, command to rerun>

## Acceptance results
| Criterion | Target | Result | Evidence (command, line printed) | Pass / fail |
|---|---|---|---|---|

## Planted breaks
| Break | Where it lay | How it was found | Found / missed / invented |
|---|---|---|---|

## Defects in our own code
| Defect | How found | Effect if shipped | Fixed and retested? |
|---|---|---|---|

## What was not tested
| Gap | Why it matters | Who closes it, by when |
|---|---|---|

## How this report could be wrong
<One way, and what would show it.>

## Conditions and decision
| Condition for the pilot | Owner | Date |
|---|---|---|

## Sign-off
<Name, role, date, go or no-go. A signer who disagrees writes why.>
WORKED EXAMPLE

At a real company the integration lead writes this report and the head of engineering and the head of payments operations sign it. Here Imade writes it for Ikponmwosa’s platform team, to say whether the three services may go to a pilot.

Header. Integration test report: sender, switch and receiving-bank services. Written by Imade, 20 November 2026. For signature by Ikponmwosa and the head of payments operations. Version tested: the build tagged for this run (an assumption: name your own commit). Decision needed: may a staff-only pilot start?

Verdict. Conditional go for a pilot of staff-only transfers, once the three conditions below are closed. The evidence covers one generated day, and the report says no more than that.

Tested. Wednesday 17 June, replayed through fresh services: 2,008 name enquiries and 2,980 transfers, 5,011 events in all. Faults injected from the data: B07 down from 11:02 to 11:49, closed and frozen accounts, and 17 timeouts. All 2,980 first responses and 2,980 final statuses agree with the week.

Acceptance. All three pass (python3 accept.py prints PASS). The five sessions net to zero, and sessions 20260617-2, -3 and -4 show 0 positions differing from the week’s. Of 17 timeouts, 6 were credited anyway; none of those six customers was reversed, and suspense ends the day at 0 kobo.

Planted breaks. The week’s bank_log gave 3 findings (B10 reversed a customer twice, B14 took no levy, B11 reversed after a late success); the key lists 3 planted, 0 missed, 0 invented. Our own services gave 0 findings.

Defects in our code. None unplanted. The seeded change (reverse on anything but 00) produced 22 problems and 6 customers paid back while their beneficiaries were credited, ₦83,792 twice. Every posting still balanced, so only reconciliation caught it.

Not tested. Other days, participant limits, balances, a restart mid-day and any real network.

Could be wrong. One day is thin: a second day with a different fault mix would show it.

Conditions. Replay the other six days (Imade, 27 November); read the regulation itself for the refund clock (Ikponmwosa, 4 December).

Now you

You are the integration lead at Owoleaf, a month after this project. Your three services have passed Wednesday. The head of payments operations wants the pilot to include name enquiries to a bank that goes quiet for 47 minutes, and the head of engineering wants to know whether the tests would notice if a developer weakened the requery rule. Run your replay and accept.py on fresh services, then make the one-line break and run it again into run-break. Use story.py, accept.py and reconcile.py for your figures. Take your not-tested list from the chapter’s section on what the model leaves out, and add anything you did not run yourself. Write the report. The two heads of department will read it and sign it, and it decides whether a staff-only pilot may start and on what conditions.

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: Payment service banks: what the licence allows and forbids →