Week 6 practice

Ship + get hired · 9 exercises

The full text of every practice problem that fits week 6, grouped by lecture section. Set up the two sets first: the commands are on the practice problems page. Each reference solution is collapsed under its exercise; run the tests before you open it.

Deploying an OIE channel

Lecture: Deploying an OIE channel.

mellp 31: Mini Interface Engine

Hard · engine · routing · sqlite · threads · python-hl7

Everything from this part in one process: receive over MLLP, route by type, validate, transform, forward, log, and answer the sender. This is the core loop of every interface engine. The interesting part is not any one step but how they interact: what the sender is told when the receiver is down, what the log says afterwards, and what happens when the sender retransmits.

@dataclass(frozen=True)
class Route:
    host: str
    port: int
    receiving_app: str

class Engine:
    def __init__(self, routes: dict[str, Route], db_path: str, *, retries: int = 2, timeout: float = 1.0) -> None
    def serve(self, listener: socket.socket, stop: threading.Event) -> None

Route and the table schema are in the stub. Engine(routes, db_path) creates the messages table (problem 27's) in the SQLite file if it is missing:

CREATE TABLE IF NOT EXISTS messages (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    received_at  TEXT NOT NULL,
    direction    TEXT NOT NULL,
    control_id   TEXT NOT NULL,
    message_type TEXT NOT NULL,
    status       TEXT NOT NULL DEFAULT 'received',
    detail       TEXT NOT NULL DEFAULT '',
    raw          TEXT NOT NULL
)

serve accepts upstream connections on listener until stop is set, and returns within 1 s after that. Upstream connections are long-lived (many messages each) and are served concurrently: a slow downstream for one sender must not hold up another sender. Each inbound message is handled in this order:

  1. Route. Look up the exact type (ADT^A01, from MSH-9.1 and MSH-9.2), then the wildcard (ADT^*), in routes. No route: reply AR with MSA-3 no route for ADT^A01, log status rejected.
  2. Validate. PID-3.1 empty: reply AE with MSA-3 PID-3 is required, log status error. Nothing is forwarded.
  3. Duplicate. If a row with this control ID (MSH-10) and status sent is already in the table, reply AA, log status duplicate, forward nothing.
  4. Transform. The forwarded copy has MSH-5 set to the route's receiving_app and every segment whose name starts with Z removed. Nothing else changes.
  5. Forward. Open a connection to the route's host and port, send the copy as an MLLP block, and wait for the reply block. Connecting and each read use timeout seconds. On TimeoutError, ConnectionError (subclasses included, and a peer that closes before replying counts as one) or a reply with MSA-1 AE, try again on a new connection, up to retries more times. A reply with MSA-1 AR is not retried.
  6. Answer. Downstream AA: log status sent, reply AA. Downstream AR, or retries used up: log status dead with detail = the reason from the last attempt, reply AE with the same reason in MSA-3. A reason is AR: <MSA-3> or AE: <MSA-3> from the downstream reply, or the exception's class name (TimeoutError, ConnectionRefusedError, ...).

The log gets exactly one row per inbound message: direction = in, control_id = MSH-10, message_type like ADT^A01, received_at = UTC time in ISO 8601, the final status, detail (empty unless stated above), and raw = the message exactly as received. The row is committed before the reply goes upstream.

Every upstream reply is an ACK whose MSA-2 is the inbound MSH-10.

Example 1:

routes = {"ADT^A01": Route(host, 2575, "BEDS"), "ADT^*": Route(host, 2576, "ARCHIVE")}
upstream sends ADT^A01 MSG1, with a ZPI segment     -> AA MSG1
    port 2575 received it with MSH-5 = BEDS and no ZPI; row: MSG1 sent
upstream sends ADT^A08 MSG2                         -> AA MSG2      (via ADT^*, to 2576)
upstream sends ORU^R01 MSG3                         -> AR MSG3 "no route for ORU^R01"

Example 2:

retries=2; port 2575 answers AE, closes without replying, then AA
upstream sends ADT^A01 MSG4                         -> AA MSG4      (3 connections downstream)
port 2575 now answers AR "unknown patient"
upstream sends ADT^A01 MSG5                         -> AE MSG5 "AR: unknown patient"; row: dead
upstream sends ADT^A01 MSG4 again                   -> AA MSG4; nothing forwarded; row: duplicate

Constraints:

Follow-up: this engine ACKs upstream only after downstream answered, so a slow lab system slows the registration desk. Problem 30 shows the alternative: ACK once the message is safely queued. What does the sender lose with that design, and what do you gain?

Hint 1

sqlite3 connections may only be used by the thread that created them (unless you pass check_same_thread=False and add your own lock). Opening one connection per upstream connection thread, in autocommit mode with isolation_level=None, sidesteps both problems.

Hint 2

python-hl7 covers most of the message work: msg["MSH.F9.R1.C1"], msg["PID.F3.R1.C1"], msg.assign_field("BEDS", "MSH", 1, 5), and msg.create_ack("AE"), which echoes MSH-10 into MSA-2. create_ack has no MSA-3 parameter, but ack.assign_field(text, "MSA", 1, 3) adds one. Reuse problem 16's client for each forward and problem 20's thread-per-connection server for upstream, with timeouts on accept and recv so stop is noticed.

Write it in problems/31-mini-interface-engine/solution.py, then run:

uv run pytest problems/31-*
Reference solution
import socket
import sqlite3
import threading
from contextlib import closing
from dataclasses import dataclass
from datetime import datetime, timezone

import hl7

SB = b"\x0b"
EB = b"\x1c\x0d"

SCHEMA = """
CREATE TABLE IF NOT EXISTS messages (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    received_at  TEXT NOT NULL,
    direction    TEXT NOT NULL,
    control_id   TEXT NOT NULL,
    message_type TEXT NOT NULL,
    status       TEXT NOT NULL DEFAULT 'received',
    detail       TEXT NOT NULL DEFAULT '',
    raw          TEXT NOT NULL
)
"""


@dataclass(frozen=True)
class Route:
    host: str
    port: int
    receiving_app: str


class Engine:
    def __init__(
        self, routes: dict[str, Route], db_path: str, *, retries: int = 2, timeout: float = 1.0
    ) -> None:
        self.routes = routes
        self.db_path = db_path
        self.retries = retries
        self.timeout = timeout
        with closing(sqlite3.connect(db_path)) as db:
            db.execute(SCHEMA)

    def serve(self, listener: socket.socket, stop: threading.Event) -> None:
        listener.settimeout(0.1)  # wake up regularly to look at `stop`
        while not stop.is_set():
            try:
                conn, _ = listener.accept()
            except TimeoutError:
                continue
            worker = threading.Thread(target=self._serve_connection, args=(conn, stop), daemon=True)
            worker.start()

    def _serve_connection(self, conn: socket.socket, stop: threading.Event) -> None:
        # A sqlite3 connection may only be used by the thread that opened it: one per worker.
        db = sqlite3.connect(self.db_path, isolation_level=None)
        conn.settimeout(0.1)
        buffer = b""
        try:
            while not stop.is_set():
                try:
                    chunk = conn.recv(65536)
                except TimeoutError:
                    continue
                if not chunk:
                    break
                buffer += chunk
                while (end := buffer.find(EB)) != -1:
                    payload = buffer[buffer.find(SB) + 1 : end]
                    buffer = buffer[end + len(EB) :]
                    conn.sendall(SB + self._handle(payload.decode(), db) + EB)
        except OSError:
            pass  # upstream reset the connection
        finally:
            conn.close()
            db.close()

    def _handle(self, raw: str, db: sqlite3.Connection) -> bytes:
        """Processes one inbound message, logs it, and returns the upstream reply."""
        message = hl7.parse(raw)
        control_id = message["MSH.F10"]
        message_type = f"{message['MSH.F9.R1.C1']}^{message['MSH.F9.R1.C2']}"
        status, code, detail = self._process(message, raw, message_type, db)
        db.execute(
            "INSERT INTO messages"
            " (received_at, direction, control_id, message_type, status, detail, raw)"
            " VALUES (?, 'in', ?, ?, ?, ?, ?)",
            (datetime.now(timezone.utc).isoformat(), control_id, message_type, status, detail, raw),
        )
        reply = message.create_ack(code)
        if detail:
            reply.assign_field(detail, "MSA", 1, 3)
        return str(reply).encode()

    def _process(self, message, raw: str, message_type: str, db) -> tuple[str, str, str]:
        """Returns (status to log, upstream ACK code, detail)."""
        wildcard = f"{message['MSH.F9.R1.C1']}^*"
        route = self.routes.get(message_type, self.routes.get(wildcard))
        if route is None:
            return "rejected", "AR", f"no route for {message_type}"
        if not message["PID.F3.R1.C1"]:
            return "error", "AE", "PID-3 is required"
        already_sent = db.execute(
            "SELECT 1 FROM messages WHERE control_id = ? AND status = 'sent'",
            (message["MSH.F10"],),
        ).fetchone()
        if already_sent:
            return "duplicate", "AA", ""
        reason = self._forward(transform(raw, route.receiving_app), route)
        if reason is None:
            return "sent", "AA", ""
        return "dead", "AE", reason

    def _forward(self, payload: bytes, route: Route) -> str | None:
        """None once downstream answers AA, otherwise why it never did."""
        for _ in range(self.retries + 1):
            try:
                with socket.create_connection((route.host, route.port), self.timeout) as sock:
                    sock.sendall(SB + payload + EB)
                    reply = hl7.parse(read_block(sock).decode())
            except (TimeoutError, ConnectionError) as error:
                reason = type(error).__name__
                continue
            if reply["MSA.F1"] == "AA":
                return None
            reason = f"{reply['MSA.F1']}: {reply['MSA.F3']}"
            if reply["MSA.F1"] == "AR":
                break
        return reason


def transform(raw: str, receiving_app: str) -> bytes:
    """MSH-5 becomes the route's receiving application; Z-segments are dropped."""
    message = hl7.parse(raw)
    message.assign_field(receiving_app, "MSH", 1, 5)
    kept = [str(segment) for segment in message if not str(segment[0]).startswith("Z")]
    return "".join(segment + "\r" for segment in kept).encode()


def read_block(sock: socket.socket) -> bytes:
    buffer = b""
    while EB not in buffer:
        chunk = sock.recv(65536)
        if not chunk:
            raise ConnectionError("downstream closed before replying")
        buffer += chunk
    return buffer[buffer.find(SB) + 1 : buffer.find(EB)]

mellp Lab B: Your Python against a real interface engine

Lab · mirth connect · open integration engine · 60 to 90 minutes

So far both ends of every connection were Python. On the job, the other end is an interface engine. This lab puts Mirth Connect between your code and itself, so you can watch a production-grade engine frame, acknowledge, queue and retry, and see which of your earlier solutions survive contact with it.

Every "what you should see" below was observed on Mirth Connect 4.5.2 with the two channels this lab deploys. Change a channel setting and the behaviour changes, which is the point of Part 3.

Setup

Needs Docker.

docker run -d --name mellp-engine \
  -p 8443:8443 -p 6661:6661 -p 6662:6662 \
  --add-host host.docker.internal:host-gateway \
  nextgenhealthcare/connect:4.5.2

uv run python labs/mirth/lab.py deploy     # creates and starts both channels (retry if the engine is still booting)
uv run python labs/mirth/lab.py check      # proves the plumbing with known-good code

deploy talks to the engine's REST API on https://localhost:8443/api with the default admin / admin login. The engine uses a self-signed certificate, so the script does not verify it; it is a local lab container, not something to copy into production code.

Channel Listens on Does
mellp-in 6661 Accepts any message, discards it, replies with a generated ACK
mellp-relay 6662 Forwards each message to host.docker.internal:6671 (your Python) over MLLP, queues on failure, retries every 2 s, waits 5 s for a reply

uv run python labs/mirth/lab.py status prints each channel's state and counters (received, queued, sent, error). Use it after every experiment.

Open Integration Engine is the community fork of Mirth Connect 4.5.2 and takes the same channels: swap the image for openintegrationengine/engine:latest (lab.py deploy and check pass against it unchanged). When this lab was written that image was published for amd64 only, so on Apple Silicon it runs under emulation and needed about 100 seconds to start instead of 20.

The engine's landing page at https://localhost:8443 links to its own Administrator client and web dashboard. This lab does not need them: lab.py status shows the counters that matter here.

Part 1: your sender, their listener (port 6661)

Use your own code from the problems. From a Python prompt in the repo root (uv run python):

import importlib.util

def load(problem):                      # "16-send-and-wait" -> the module with your solution
    spec = importlib.util.spec_from_file_location("s", f"problems/{problem}/solution.py")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

from harness.hl7msg import adt_a01
send = load("16-send-and-wait").send
print(send("127.0.0.1", 6661, adt_a01("LAB1").encode()))
  1. Read the ACK the engine built. Compare it field by field with what your problem 09 build_ack produces for the same message.
  2. Send a block whose payload is b"hello world". Is the reply an AA? Look closely at its MSH.
  3. Send an ADT with an empty PID-3 (adt_a01("LAB2", patient={"mrn": ""})). AA, AE or AR?
  4. With a raw socket or harness.net.Client, try the framing faults from Part 1 of the problems: two blocks in one write; one block in 40-byte pieces; a newline between two blocks; a block whose 0x1C is not followed by \r; a message with no start byte; half a block and then silence.
  5. Open a problem 17 Session and push 500 messages through one connection. Then run problem 22's blast with 1, 4 and 8 connections and write down the rates.
What you should see
  1. MSH|^~\&|LAB|HOSP|EPIC|HOSP|<now>||ACK^A01^ACK|<now>|P|2.5 then MSA|AA|LAB1. Parties swapped, trigger event echoed, MSH-10 is a timestamp, MSA-2 is your control ID.
  2. Yes, an AA. The engine reads "the five characters after the segment name" as delimiters even here, so the ACK comes back as MSHlo wol... with l as the field separator. An AA from a pass-through channel says the bytes arrived in a block. It says nothing about the content.
  3. AA. This channel has no validation. Rules like problem 10 and 13 exist only where somebody configured them.
  4. Two glued blocks: two ACKs. Pieces: one ACK once the block is complete. Newline between blocks: both acknowledged, the newline ignored (problem 04, rule 1). 0x1C without \r, and no start byte: no reply at all, the engine keeps waiting. Half a block: the engine waits, with no timeout on this channel.
  5. One connection carries all 500. Your numbers will be far below what problem 22 measured against a bare Python server: this engine parses, stores and logs every message. On the machine this lab was written on, one connection managed roughly 175 messages per second.

Part 2: their sender, your listener (port 6662 to your port 6671)

Now the engine is the client. Run your problem 20 server where the engine can reach it:

import socket, threading

serve = load("20-many-callers").serve
build_ack = load("09-echo-the-control-id").build_ack

seen = []
def handler(payload: bytes) -> bytes:
    seen.append(payload)
    return build_ack(payload.decode()).encode()

listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("0.0.0.0", 6671))         # not 127.0.0.1: the engine connects from its container
listener.listen()
stop = threading.Event()
threading.Thread(target=serve, args=(listener, handler, stop), daemon=True).start()

Send to the relay and watch seen:

print(send("127.0.0.1", 6662, adt_a01("LAB10").encode()))
  1. Send five messages through one Session to 6662. How many TCP connections did the engine open to your listener?
  2. Stop your listener (stop.set(), then close listener). Send three messages to 6662. What does the upstream ACK say? Check status. Start the listener again and wait a few seconds.
  3. Make your handler answer AE (then AR) and send one message. What does the upstream sender get? Is the message retried? Check status.
  4. Make your handler return an ACK whose MSA-2 is wrong. Same questions.
  5. Make your handler sleep 6 seconds before answering. How long does the upstream ACK take, what does it say, and how many times does seen receive the same control ID over the next 20 seconds?
  6. Wrap the slow handler in your problem 19 Deduplicator and repeat step 10. Count how many times the real work runs. Then make the sleep 8 seconds, count again, and explain the difference (problem 23 rule 7 exists for this).
What you should see
  1. Five. This channel's sender opens a new connection per message, so your listener must handle connections that carry exactly one message as well as long-lived ones.
  2. Each send gets an immediate AA although your listener is down. status shows queued=3. Within about 2 seconds of the listener returning, all three arrive in order. An AA from an engine means "I have it", not "the destination has it".
  3. The upstream ACK is AE with the text An Error Occurred Processing Message., for your AE and for your AR alike. Your own MSA-3 text does not travel upstream. The message is delivered once and not retried; status shows error up by one.
  4. The same as step 8. This channel validates the control ID of the reply, which is what problem 17 rule 3 and problem 18 rule 2 do on your side.
  5. The upstream ACK arrives after about 5 seconds, the channel's response timeout, and it is an AA: the message was queued. The engine then resends the same message, same control ID, on a new connection roughly every 7 seconds (5 s timeout plus the 2 s retry interval), and each attempt times out again. In the run this was written from, the handler's work ran 4 times in 24 seconds. The message stays at the head of the engine's queue until a listener answers in time, and everything sent meanwhile is acknowledged at once and queued behind it. Run a fast handler for a few seconds to drain the queue before the next step.
  6. With a 6 second sleep the work runs once per control ID: the first attempt finishes before the retry arrives, so the retry gets the remembered reply at once and the engine is satisfied. With 8 seconds the retry arrives while the first attempt is still running, nothing is remembered yet, and the work runs again. Remembering finished work is not enough when duplicates can overlap.

Part 3: change the engine

The channel definitions are plain XML built in labs/mirth/lab.py. Change a setting there, run lab.py deploy again (it updates the channels in place), and repeat the experiment it affects.

For each one, write down what you expected before you ran it.

Clean up

docker rm -f mellp-engine

The lab files are in labs/mirth/.

Replaying a day of traffic safely

Lecture: Replaying a day of traffic safely.

hl7-practice 15: Reconcile ACKs

Medium

INT-201: At end of day we need to know which messages the other side received.

reconcile_acks(sent: list[str], acks: list[str]) -> dict[str, str]

Write it in p15_reconcile_acks.py, then run python3 test_practice.py p15.

Reference solution

It imports solutions/_hl7.py.

from collections import Counter

from solutions._hl7 import field, first


def reconcile_acks(sent: list[str], acks: list[str]) -> dict[str, str]:
    sent_ids = [field(first(m, "MSH"), 10) for m in sent]
    counts = Counter(sent_ids)
    latest = {}
    for a in acks:
        msa = first(a, "MSA")
        latest[field(msa, 2)] = field(msa, 1)  # later ACK overwrites earlier one

    result = {}
    for cid in sent_ids:
        result[cid] = "DUPLICATE_ID" if counts[cid] > 1 else latest.get(cid, "MISSING")
    for cid, code in latest.items():
        if cid not in counts:
            result[f"ORPHAN:{cid}"] = code
    return result

hl7-practice 16: Match results to orders

Medium

INT-203: A doctor reports "ordered 2 days ago, still no result". Reconcile orders vs results.

match_results(orders: list[str], results: list[str]) -> dict[str, list[str]]

Each message (ORM or ORU) has exactly 1 OBR. Join key = placer order number OBR-2; test code = OBR-4.1.

output key contains
matched order has a result with the same test code
code_mismatch order has a result but OBR-4.1 differs
unknown_order result points to an order that doesn't exist
pending order has no result yet

Each list holds placer order numbers, sorted.

Write it in p16_match_results.py, then run python3 test_practice.py p16.

Reference solution

It imports solutions/_hl7.py.

from solutions._hl7 import field, first, part


def _key_and_code(message: str) -> tuple[str, str]:
    obr = first(message, "OBR")
    return field(obr, 2), part(field(obr, 4), "^", 1)


def match_results(orders: list[str], results: list[str]) -> dict[str, list[str]]:
    ordered = dict(_key_and_code(m) for m in orders)
    out = {"matched": [], "code_mismatch": [], "unknown_order": [], "pending": []}
    resulted = set()
    for m in results:
        placer, code = _key_and_code(m)
        resulted.add(placer)
        if placer not in ordered:
            out["unknown_order"].append(placer)
        elif ordered[placer] == code:
            out["matched"].append(placer)
        else:
            out["code_mismatch"].append(placer)
    out["pending"] = [p for p in ordered if p not in resulted]
    return {k: sorted(v) for k, v in out.items()}

mellp 22: Ten Thousand

Medium · load · throughput · threads · stdlib

Before an interface goes live, someone asks how many messages per second it can take. A morning admission rush, a backlog replayed after a downtime, or a lab analyser flushing its queue can all send thousands of messages in minutes. The only honest answer is a measurement, and for that you need a load generator that speaks MLLP the way real senders do: a few long-lived connections, one message in flight on each.

@dataclass
class Stats:
    sent: int
    acked: int
    failed: int
    seconds: float
    per_second: float
    p50_ms: float
    p99_ms: float

def blast(host: str, port: int, payloads: list[bytes], connections: int = 4, timeout: float = 5.0) -> Stats
  1. Open exactly connections TCP connections. They work at the same time, and each stays open for its whole share of the payloads.
  2. On each connection: send one message, wait for its reply, then send the next. Every payload is sent exactly once, on one of the connections.
  3. acked counts replies whose MSA-1 is AA; every other reply counts as failed. sent = acked + failed.
  4. seconds is the wall time of the whole run and per_second = sent / seconds. p50_ms and p99_ms are the 50th and 99th percentiles of per-message latency, measured from just before the send to the complete reply, in milliseconds.

Example 1:

Input:   blast("127.0.0.1", 2575, ten_thousand_admits, connections=4)     the server answers AA to all
Output:  Stats(sent=10000, acked=10000, failed=0, seconds=0.57, per_second=17508.5, p50_ms=0.21, p99_ms=0.46)
Explanation: one run against the tests' server on a laptop. The timings depend on the machine and on what
             else it is doing (the same run took 4.4 s while other jobs were busy); the counts do not.

Example 2:

Input:   blast("127.0.0.1", 2575, two_hundred_admits, connections=4)      every tenth reply is AE
Output:  Stats(sent=200, acked=180, failed=20, ...)

Constraints:

Follow-up: with one message in flight per connection, throughput is capped at connections / latency. Some receivers accept several messages before the first ACK comes back. What would that do to the numbers, and what does it cost when one of the messages in flight fails?

Hint 1

payloads[i::connections] gives connection i its share. A concurrent.futures.ThreadPoolExecutor(max_workers=connections) runs one worker per connection, and future.result() hands back what each worker collected (and re-raises what it raised).

Hint 2

time.perf_counter() is the clock for measuring durations. With the latencies sorted, the nearest-rank percentile p is latencies[round(p * (len(latencies) - 1))]. statistics.quantiles(latencies, n=100) is the interpolating alternative.

Measure it

Point blast at your own servers from problems 20 and 21. Save this as measure.py in the repository root and run uv run python measure.py:

import asyncio
import runpy
import threading

from harness.hl7msg import ack, adt_a01
from harness.net import listener, port_of

blast = runpy.run_path("problems/22-ten-thousand/solution.py")["blast"]
serve = runpy.run_path("problems/20-many-callers/solution.py")["serve"]
start = runpy.run_path("problems/21-async-listener/solution.py")["start"]

payloads = [adt_a01(f"MSG{n:05d}").encode() for n in range(10_000)]


def threaded_server() -> int:
    """Problem 20 on a background thread. Returns its port."""
    sock = listener()
    args = (sock, lambda payload: ack(payload).encode(), threading.Event())
    threading.Thread(target=serve, args=args, daemon=True).start()
    return port_of(sock)


def async_server() -> int:
    """Problem 21 on an event loop in a background thread. Returns its port."""
    loop = asyncio.new_event_loop()
    threading.Thread(target=loop.run_forever, daemon=True).start()

    async def handler(message):
        return message.create_ack()

    server = asyncio.run_coroutine_threadsafe(start(handler), loop).result()
    return server.sockets[0].getsockname()[1]


for name, port in [("problem 20", threaded_server()), ("problem 21", async_server())]:
    for connections in (1, 4, 16):
        stats = blast("127.0.0.1", port, payloads, connections)
        print(
            f"{name}  {connections:>2} connections  {stats.per_second:7.0f} msg/s"
            f"  p50 {stats.p50_ms:6.2f} ms  p99 {stats.p99_ms:6.2f} ms"
        )

Server and load generator share one Python process here, so both compete for the same interpreter. Moving the server into its own process is a good second experiment.

server connections msg/s p50 ms p99 ms
problem 20 (threads) 1
problem 20 (threads) 4
problem 20 (threads) 16
problem 21 (asyncio) 1
problem 21 (asyncio) 4
problem 21 (asyncio) 16

Write it in problems/22-ten-thousand/solution.py, then run:

uv run pytest problems/22-*
Reference solution
import socket
import time
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass

SB = b"\x0b"
EB = b"\x1c\x0d"


@dataclass
class Stats:
    sent: int
    acked: int
    failed: int
    seconds: float
    per_second: float
    p50_ms: float
    p99_ms: float


def accepted(reply: bytes) -> bool:
    for segment in reply.split(b"\r"):
        if segment.startswith(b"MSA|"):
            return segment.split(b"|")[1] == b"AA"
    return False


def run_connection(host: str, port: int, share: list[bytes], timeout: float):
    """Sends `share` one message at a time over one connection: (latency, accepted) per message."""
    results = []
    with socket.create_connection((host, port), timeout=timeout) as sock:
        for payload in share:
            started = time.perf_counter()
            sock.sendall(SB + payload + EB)
            reply = b""  # one request in flight, so the reply is everything up to its end marker
            while not reply.endswith(EB):
                chunk = sock.recv(65536)
                if not chunk:
                    raise ConnectionError("the server closed the connection")
                reply += chunk
            results.append((time.perf_counter() - started, accepted(reply)))
    return results


def blast(
    host: str, port: int, payloads: list[bytes], connections: int = 4, timeout: float = 5.0
) -> Stats:
    shares = [payloads[index::connections] for index in range(connections)]
    started = time.perf_counter()
    with ThreadPoolExecutor(max_workers=connections) as pool:
        futures = [pool.submit(run_connection, host, port, share, timeout) for share in shares]
        results = [result for future in futures for result in future.result()]
    seconds = time.perf_counter() - started
    latencies = sorted(latency * 1000 for latency, _ in results)
    acked = sum(ok for _, ok in results)
    return Stats(
        sent=len(results),
        acked=acked,
        failed=len(results) - acked,
        seconds=seconds,
        per_second=len(results) / seconds,
        p50_ms=latencies[round(0.50 * (len(latencies) - 1))],
        p99_ms=latencies[round(0.99 * (len(latencies) - 1))],
    )

mellp 27: Write It Down

Medium · sqlite · logging · stdlib

When a nurse says an admit never showed up, the first question is whether it ever reached the engine. Every engine keeps a message log for that: what came in, when, and what happened to it. This one is a single SQLite table, and problems 28 and 31 use the same table.

class MessageLog:
    def __init__(self, path: str) -> None
    def record(self, raw: str, direction: str = "in") -> int
    def set_status(self, row_id: int, status: str, detail: str = "") -> None
    def get(self, row_id: int) -> dict | None
    def find(self, *, control_id: str | None = None, message_type: str | None = None, status: str | None = None) -> list[dict]
    def close(self) -> None

The table is fixed. It is in the stub as SCHEMA:

CREATE TABLE IF NOT EXISTS messages (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    received_at  TEXT NOT NULL,
    direction    TEXT NOT NULL,
    control_id   TEXT NOT NULL,
    message_type TEXT NOT NULL,
    status       TEXT NOT NULL DEFAULT 'received',
    detail       TEXT NOT NULL DEFAULT '',
    raw          TEXT NOT NULL
)
  1. MessageLog(path) opens the SQLite file at path. A new path gets the table created. An existing file keeps its rows.
  2. record inserts one row and returns its id:
  3. raw stored verbatim, \r included;
  4. control_id = MSH-10;
  5. message_type = MSH-9.1 and MSH-9.2 joined by ^, like ADT^A01 (no MSH-9.3);
  6. received_at = the current UTC time in ISO 8601 with its offset, like 2026-01-05T08:30:00.123456+00:00;
  7. direction as given, status = received, detail = empty.
  8. The same control ID may be recorded more than once. Each call gets its own row.
  9. set_status overwrites status and detail of one row.
  10. Every write is committed before the method returns. The tests check through a second sqlite3 connection while yours is still open.
  11. get returns the row as a dict keyed by column name (all eight columns), or None for an unknown id.
  12. find returns the matching rows as dicts in ascending id. Filters that are given combine with AND. No filters returns every row.
  13. Values go into SQL as parameters, never by string formatting. A test records a message containing ' and ;.

Example 1:

log = MessageLog("engine.db")
log.record(adt_a01("MSG00001"))          -> 1
log.record(oru_r01("MSG00002"))          -> 2
log.set_status(1, "sent")
log.get(1)["status"]                     -> "sent"
log.get(2)["message_type"]               -> "ORU^R01"
log.get(3)                               -> None

Example 2:

log.record(adt_a01("MSG00001"))          -> 3
log.find(control_id="MSG00001")          -> [row 1, row 3]
log.find(control_id="MSG00001", status="received")  -> [row 3]
log.find()                               -> [row 1, row 2, row 3]
Explanation: the sender retransmitted MSG00001. Both copies are logged.

Constraints:

Follow-up: the log grows by tens of thousands of rows a day. Which index would you add first, and what is your retention rule for rows that contain patient data?

Hint 1

sqlite3.connect(path) creates the file if it is missing. Set connection.row_factory = sqlite3.Row and dict(row) gives you column names for free. with connection: commits the block, or rolls it back on an exception. cursor.lastrowid is the new id.

Hint 2

Column names cannot be parameters, values can. Build find's WHERE clause from fixed column names with ? placeholders and pass the values separately. For the timestamp: datetime.now(timezone.utc).isoformat().

Write it in problems/27-write-it-down/solution.py, then run:

uv run pytest problems/27-*
Reference solution
import sqlite3
from datetime import datetime, timezone

SCHEMA = """
CREATE TABLE IF NOT EXISTS messages (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    received_at  TEXT NOT NULL,
    direction    TEXT NOT NULL,
    control_id   TEXT NOT NULL,
    message_type TEXT NOT NULL,
    status       TEXT NOT NULL DEFAULT 'received',
    detail       TEXT NOT NULL DEFAULT '',
    raw          TEXT NOT NULL
)
"""


class MessageLog:
    def __init__(self, path: str) -> None:
        # Autocommit: each statement is its own transaction, durable when execute() returns.
        self._db = sqlite3.connect(path, isolation_level=None)
        self._db.row_factory = sqlite3.Row
        self._db.execute(SCHEMA)

    def record(self, raw: str, direction: str = "in") -> int:
        header = raw.split("\r")[0].split("|")  # MSH-n sits at index n - 1
        message_type = "^".join(header[8].split("^")[:2])
        received_at = datetime.now(timezone.utc).isoformat()
        cursor = self._db.execute(
            "INSERT INTO messages (received_at, direction, control_id, message_type, raw)"
            " VALUES (?, ?, ?, ?, ?)",
            (received_at, direction, header[9], message_type, raw),
        )
        return cursor.lastrowid

    def set_status(self, row_id: int, status: str, detail: str = "") -> None:
        self._db.execute(
            "UPDATE messages SET status = ?, detail = ? WHERE id = ?", (status, detail, row_id)
        )

    def get(self, row_id: int) -> dict | None:
        row = self._db.execute("SELECT * FROM messages WHERE id = ?", (row_id,)).fetchone()
        return None if row is None else dict(row)

    def find(
        self,
        *,
        control_id: str | None = None,
        message_type: str | None = None,
        status: str | None = None,
    ) -> list[dict]:
        filters = {"control_id": control_id, "message_type": message_type, "status": status}
        conditions = [f"{column} = ?" for column, value in filters.items() if value is not None]
        values = [value for value in filters.values() if value is not None]
        where = " WHERE " + " AND ".join(conditions) if conditions else ""
        rows = self._db.execute(f"SELECT * FROM messages{where} ORDER BY id", values)
        return [dict(row) for row in rows]

    def close(self) -> None:
        self._db.close()

mellp 28: Play It Again

Medium · sqlite · replay · stdlib

The lab system was down from 02:00 to 02:40 and every result sent in that window was rejected. Once it is back, someone has to resend exactly those messages, in their original order, and know afterwards which ones made it. That is a replay, and it runs against the message log from problem 27.

def replay(
    path: str,
    send: Callable[[bytes], bytes],
    *,
    message_type: str | None = None,
    status: str | None = None,
    since_id: int = 0,
    stop_on_error: bool = False,
) -> dict

path is an SQLite file with the problem 27 table:

CREATE TABLE IF NOT EXISTS messages (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    received_at  TEXT NOT NULL,
    direction    TEXT NOT NULL,
    control_id   TEXT NOT NULL,
    message_type TEXT NOT NULL,
    status       TEXT NOT NULL DEFAULT 'received',
    detail       TEXT NOT NULL DEFAULT '',
    raw          TEXT NOT NULL
)
  1. Select the rows with direction = 'in' and id > since_id, narrowed by message_type and status when those are given. Process them in ascending id.
  2. For each row call reply = send(raw.encode()). The bytes must be exactly what was logged.
  3. Read MSA-1 and MSA-3 from the reply. MSA-1 AA: set the row's status to replayed. Any other code: status failed. In both cases detail becomes MSA-3 (empty when the reply has none).
  4. If send raises TimeoutError or ConnectionError (subclasses included), the row gets status failed and detail = the exception's class name, such as ConnectionRefusedError. The replay goes on with the next row.
  5. Each row's new status is committed before the next message is sent. If the process dies mid-replay, every row already answered keeps its new status on disk.
  6. With stop_on_error=True, stop right after the first failed row. Later rows are not sent and not changed.
  7. Return {"sent": <rows attempted>, "acked": <AA count>, "failed": [<failed row ids in order>]}.

Example 1:

rows:   1 in  ADT^A01 received
        2 out ACK^A01 received
        3 in  ORU^R01 received
        4 in  ADT^A08 failed
replay(path, send)                          # send answers AA to everything
Output: {"sent": 3, "acked": 3, "failed": []}
Explanation: row 2 is outbound and is skipped. Rows 1, 3 and 4 are now replayed.

Example 2:

Same rows. send answers AE "lab busy" to the ORU.
replay(path, send, status="received", stop_on_error=True)
Output: {"sent": 2, "acked": 1, "failed": [3]}
Explanation: row 1 replayed, row 3 failed with detail "lab busy", row 4 was never selected.

Constraints:

Follow-up: a replay resends the original control IDs. A receiver that deduplicates (problem 19) answers AA without processing them. When is that what you want, and when does it make the replay useless?

Hint 1

sqlite3.connect(path, isolation_level=None) puts the connection in autocommit mode: each statement is committed as it runs. Otherwise call connection.commit() after each UPDATE.

Hint 2

Optional filters can stay in one query: (:status IS NULL OR status = :status) with a dict of named parameters.

Write it in problems/28-play-it-again/solution.py, then run:

uv run pytest problems/28-*
Reference solution
import sqlite3
from collections.abc import Callable
from contextlib import closing


def replay(
    path: str,
    send: Callable[[bytes], bytes],
    *,
    message_type: str | None = None,
    status: str | None = None,
    since_id: int = 0,
    stop_on_error: bool = False,
) -> dict:
    # Autocommit: each UPDATE is durable before the next message goes out.
    with closing(sqlite3.connect(path, isolation_level=None)) as db:
        rows = db.execute(
            "SELECT id, raw FROM messages WHERE direction = 'in' AND id > :since_id"
            " AND (:message_type IS NULL OR message_type = :message_type)"
            " AND (:status IS NULL OR status = :status) ORDER BY id",
            {"since_id": since_id, "message_type": message_type, "status": status},
        ).fetchall()
        failed = []
        sent = 0
        for row_id, raw in rows:
            sent += 1
            try:
                code, detail = acknowledgment(send(raw.encode()))
            except (TimeoutError, ConnectionError) as error:
                code, detail = "", type(error).__name__
            new_status = "replayed" if code == "AA" else "failed"
            db.execute(
                "UPDATE messages SET status = ?, detail = ? WHERE id = ?", (new_status, detail, row_id)
            )
            if new_status == "failed":
                failed.append(row_id)
                if stop_on_error:
                    break
        return {"sent": sent, "acked": sent - len(failed), "failed": failed}


def acknowledgment(reply: bytes) -> tuple[str, str]:
    """MSA-1 and MSA-3 of a reply."""
    for segment in reply.decode().split("\r"):
        fields = segment.split("|")
        if fields[0] == "MSA":
            return fields[1], fields[3] if len(fields) > 3 else ""
    return "", ""

When the bridge goes down

Lecture: When the bridge goes down.

mellp 29: Dead Letters

Medium · dead-letter queue · retries · stdlib

Some messages will never be accepted: an order for a patient the lab has never heard of, a result with a code the chart does not know. Retrying them forever blocks everything queued behind them. The usual answer is a dead-letter queue: give up on the message, keep it with the reason, move on, and let a person resend it once the cause is fixed.

@dataclass
class DeadLetter:
    payload: bytes
    reason: str
    attempts: int

class Outbox:
    dead: list[DeadLetter]

    def __init__(self, send: Callable[[bytes], bytes], max_attempts: int = 3) -> None
    def submit(self, payload: bytes) -> bool
    def redrive(self) -> int

send(payload) delivers one message and returns the reply payload, or raises. DeadLetter is defined in the stub.

  1. submit returns True as soon as a reply with MSA-1 AA arrives.
  2. MSA-1 AR: the message is dead at once, reason AR: <MSA-3>. It is not retried.
  3. MSA-1 AE, or send raising TimeoutError or ConnectionError (subclasses included): try again, at most max_attempts attempts in total. When they run out the message is dead, reason AE: <MSA-3> or the exception's class name (TimeoutError, ConnectionRefusedError, ...). Retry immediately, no sleeping.
  4. A dead message goes on the end of dead as a DeadLetter with the payload, the reason from its last attempt, and the number of attempts made. submit returns False for it, and later submits work as usual: one poison message never blocks the queue.
  5. redrive gives every dead letter a fresh round of up to max_attempts attempts, following rules 1 to 3. Delivered letters leave dead. The rest stay in their original order, with attempts added up over all rounds and reason from the latest attempt. It returns how many were delivered.

Example 1:

outbox = Outbox(send, max_attempts=3)
outbox.submit(adt)       -> True       # send answered AE, then AA: 2 attempts
outbox.submit(order)     -> False      # send answered AR "unknown patient"
outbox.submit(result)    -> True
outbox.dead              -> [DeadLetter(order, "AR: unknown patient", 1)]

Example 2:

outbox = Outbox(send, max_attempts=2)
outbox.submit(adt)       -> False      # TimeoutError, TimeoutError
outbox.dead              -> [DeadLetter(adt, "TimeoutError", 2)]
outbox.redrive()         -> 0          # AE "busy", AE "busy"
outbox.dead              -> [DeadLetter(adt, "AE: busy", 4)]
outbox.redrive()         -> 1          # AA
outbox.dead              -> []

Constraints:

Follow-up: this dead-letter queue lives in memory and is gone after a restart. Problem 30 makes it durable. Before that: who gets told when a message lands in dead, and how?

Hint 1

Write one helper that runs a round of up to max_attempts attempts for a single DeadLetter, adding to its attempts and setting its reason as it goes, and returns whether it was delivered. submit and redrive both use it.

Hint 2

MSA by hand: split the reply on \r, find the segment whose first field is MSA, split it on |. MSA-1 is index 1, MSA-3 is index 3 when it exists.

Write it in problems/29-dead-letters/solution.py, then run:

uv run pytest problems/29-*
Reference solution
from collections.abc import Callable
from dataclasses import dataclass


@dataclass
class DeadLetter:
    payload: bytes
    reason: str
    attempts: int


class Outbox:
    def __init__(self, send: Callable[[bytes], bytes], max_attempts: int = 3) -> None:
        self.send = send
        self.max_attempts = max_attempts
        self.dead: list[DeadLetter] = []

    def submit(self, payload: bytes) -> bool:
        letter = DeadLetter(payload, reason="", attempts=0)
        if self._deliver(letter):
            return True
        self.dead.append(letter)
        return False

    def redrive(self) -> int:
        waiting, self.dead = self.dead, []
        for letter in waiting:
            if not self._deliver(letter):
                self.dead.append(letter)
        return len(waiting) - len(self.dead)

    def _deliver(self, letter: DeadLetter) -> bool:
        """One round of up to max_attempts. On failure `letter` holds the last reason."""
        for _ in range(self.max_attempts):
            letter.attempts += 1
            try:
                code, text = acknowledgment(self.send(letter.payload))
            except (TimeoutError, ConnectionError) as error:
                letter.reason = type(error).__name__
                continue
            if code == "AA":
                return True
            letter.reason = f"{code}: {text}"
            if code == "AR":
                return False
        return False


def acknowledgment(reply: bytes) -> tuple[str, str]:
    """MSA-1 and MSA-3 of a reply."""
    for segment in reply.decode().split("\r"):
        fields = segment.split("|")
        if fields[0] == "MSA":
            return fields[1], fields[3] if len(fields) > 3 else ""
    return "", ""

mellp 30: Store and Forward

Hard · sqlite · queue · ordering · crash recovery · stdlib

An engine accepts a message from upstream, ACKs it, and only then delivers it downstream. Between those two moments the message lives in a queue, and that queue has to survive a crash, a restart and a downstream system that is down for an hour. Order matters as well: an A08 update overtaking the A01 admit it belongs to creates a patient the receiver does not expect. Build a durable outbound queue on SQLite. The table design is yours.

class Spool:
    def __init__(self, path: str) -> None
    def enqueue(self, destination: str, payload: bytes) -> int
    def pump(self, senders: dict[str, Callable[[bytes], bytes]], max_attempts: int = 3) -> int
    def pending(self, destination: str | None = None) -> list[int]
    def dead(self) -> list[tuple[int, str]]
    def redrive(self, message_id: int) -> None
  1. enqueue stores the message as pending and returns its id. Ids ascend in enqueue order. The message is committed before enqueue returns.
  2. pump makes one pass. For each destination in senders, it sends that destination's pending messages one at a time, strictly in id order, with senders[destination](payload), which returns the reply payload or raises. It returns the number of messages delivered in this pass.
  3. MSA-1 AA: delivered, it is never sent again. MSA-1 AR: dead at once with reason AR: <MSA-3>, and the pass goes on with the destination's next message.
  4. MSA-1 AE, or the sender raising TimeoutError or ConnectionError (subclasses included): the message's attempt count goes up by one.
  5. If the count has reached max_attempts, the message is dead with reason AE: <MSA-3> or the exception's class name, and the pass goes on with the destination's next message.
  6. Otherwise the message stays pending and the pass stops for this destination, so nothing overtakes it. The next pump starts with it. Other destinations are not affected.
  7. Messages for a destination that is not in senders stay pending, untouched.
  8. Everything is on disk as it happens. A new Spool(path) on the same file sees the same pending ids, attempt counts and dead letters.
  9. If anything else is raised while a message is being sent (tests raise a BaseException subclass to simulate the process dying), it propagates out of pump and that message is still pending with its attempt count unchanged. Messages delivered earlier in the pass stay delivered. Delivery is at-least-once: the interrupted message is sent again by a later pass.
  10. pending(destination) lists pending ids in ascending order; pending() lists them for every destination. dead() lists (id, reason) in ascending id.
  11. redrive(id) makes a dead message pending again with its attempt count back at 0. It takes its original place in the order, because order is by id. On an id that is not dead it does nothing.

Example 1:

spool = Spool("spool.db")
spool.enqueue("lab", a)          -> 1
spool.enqueue("lab", b)          -> 2
spool.enqueue("chart", c)        -> 3
spool.pump({"lab": lab, "chart": chart})   -> 1
Explanation: lab answered AE to message 1, so message 2 waits behind it. chart took message 3.
spool.pending()                  -> [1, 2]
spool.pump({"lab": lab, "chart": chart})   -> 2
spool.pending()                  -> []

Example 2:

spool.enqueue("lab", order)      -> 4
spool.enqueue("lab", result)     -> 5
spool.pump({"lab": lab})         -> 1     # AR "unknown patient" for 4, AA for 5
spool.dead()                     -> [(4, "AR: unknown patient")]
spool.redrive(4)
spool.pending("lab")             -> [4]

Example 3:

spool.enqueue("lab", a)          -> 6
spool.pump({"lab": crashing})    # the process dies while 6 is in flight
Spool("spool.db").pending()      -> [6]

Constraints:

Follow-up: at-least-once means the receiver may see message 6 twice. What in the message lets it notice, and what would you have to add to make the whole path exactly-once?

Hint 1

One table with a state column (pending, delivered, dead), an attempt count and a reason is enough. BLOB columns take and return bytes. sqlite3.connect(path, isolation_level=None) commits each statement as it runs.

Hint 2

Write the outcome of an attempt only after send has returned or raised one of the expected errors. Then a crash in the middle leaves nothing half-written, and there is nothing to recover on startup.

Write it in problems/30-store-and-forward/solution.py, then run:

uv run pytest problems/30-*
Reference solution
import sqlite3
from collections.abc import Callable

SCHEMA = """
CREATE TABLE IF NOT EXISTS spool (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    destination TEXT NOT NULL,
    payload     BLOB NOT NULL,
    state       TEXT NOT NULL DEFAULT 'pending',
    attempts    INTEGER NOT NULL DEFAULT 0,
    reason      TEXT NOT NULL DEFAULT ''
)
"""


class Spool:
    def __init__(self, path: str) -> None:
        # Autocommit: every state change is on disk before the next message is sent.
        self._db = sqlite3.connect(path, isolation_level=None)
        self._db.execute(SCHEMA)

    def enqueue(self, destination: str, payload: bytes) -> int:
        cursor = self._db.execute(
            "INSERT INTO spool (destination, payload) VALUES (?, ?)", (destination, payload)
        )
        return cursor.lastrowid

    def pump(self, senders: dict[str, Callable[[bytes], bytes]], max_attempts: int = 3) -> int:
        delivered = 0
        for destination, send in senders.items():
            for message_id in self.pending(destination):
                outcome = self._attempt(message_id, send, max_attempts)
                if outcome == "delivered":
                    delivered += 1
                elif outcome == "retry":
                    break  # nothing for this destination may overtake the stuck message
        return delivered

    def _attempt(self, message_id: int, send: Callable[[bytes], bytes], max_attempts: int) -> str:
        """Sends one message and records the outcome: 'delivered', 'dead' or 'retry'."""
        payload, attempts = self._db.execute(
            "SELECT payload, attempts FROM spool WHERE id = ?", (message_id,)
        ).fetchone()
        # A crash inside send() leaves the row exactly as it was: still pending.
        try:
            code, text = acknowledgment(send(payload))
            reason = f"{code}: {text}"
        except (TimeoutError, ConnectionError) as error:
            code, reason = "", type(error).__name__
        attempts += 1
        if code == "AA":
            outcome, state, reason = "delivered", "delivered", ""
        elif code == "AR" or attempts >= max_attempts:
            outcome, state = "dead", "dead"
        else:
            outcome, state = "retry", "pending"
        self._db.execute(
            "UPDATE spool SET state = ?, attempts = ?, reason = ? WHERE id = ?",
            (state, attempts, reason, message_id),
        )
        return outcome

    def pending(self, destination: str | None = None) -> list[int]:
        rows = self._db.execute(
            "SELECT id FROM spool WHERE state = 'pending'"
            " AND (:destination IS NULL OR destination = :destination) ORDER BY id",
            {"destination": destination},
        )
        return [message_id for (message_id,) in rows]

    def dead(self) -> list[tuple[int, str]]:
        return self._db.execute(
            "SELECT id, reason FROM spool WHERE state = 'dead' ORDER BY id"
        ).fetchall()

    def redrive(self, message_id: int) -> None:
        self._db.execute(
            "UPDATE spool SET state = 'pending', attempts = 0, reason = ''"
            " WHERE id = ? AND state = 'dead'",
            (message_id,),
        )


def acknowledgment(reply: bytes) -> tuple[str, str]:
    """MSA-1 and MSA-3 of a reply."""
    for segment in reply.decode().split("\r"):
        fields = segment.split("|")
        if fields[0] == "MSA":
            return fields[1], fields[3] if len(fields) > 3 else ""
    return "", ""

mellp statements and solutions are copied from mellp at commit 5d8e459.


Course content © 2026 HeyItWorked. All rights reserved.

Site design adapted from The Missing Semester of Your CS Education under CC BY-NC-SA 4.0. See copyright and license.