Review the prerequisites
Suitable for: Junior/mid-level AI application candidates with Python and backend fundamentals.
- Atomic intent and duplicate delivery with the outbox pattern
- The same transaction submits the task and the intention to be delivered, eliminating the double-write window of "task exists but notification is permanently lost"; actual delivery may still be repeated, and consumers must independently ensure that business processing can be reentrant.
How does the mechanism work?
Step-by-step explanation
- What happens if the sending succeeds but the tag fails?
Move from atomically committing intent to the second failure window: external delivery.
- Does the message ACK mean the business is successful?
Distinguish between transport-level success and task-level success.
- How to avoid deleting undelivered events when cleaning Outbox?
A reliable delivery chain also needs a retention and cleanup lifecycle.
Implementation · Build it
Implement · Atomic submission and idempotent handoff
Objectives of this level: Execute a persistent two-database outbox experiment, then deliver independent producer/consumer code and a recovery-audit query.
Visual guide · Atomic intent, repeatable delivery
Sender and consumer have separate local transactions. Duplicate delivery may occur; durable handoff acknowledgement does not prove tool or business completion. Select the figure to open it at full size.
Standalone execution and exact boundaries
Save the reference as outbox_lab.py in a scratch directory and run Python 3. Only json, sqlite3, tempfile and other standard-library modules are needed; no queue, API key or capstone stage is required. It creates sender.sqlite and consumer.sqlite in a temporary directory, reopens the sender to test persisted intent, then removes the directory on exit. Exceptions simulate selected stopped-operation windows; this is not an actual process-kill or distributed load test.
Sender tables are runs and outbox. Consumer tables are processed and handoffs. transaction explicitly begins/commits/rolls back each short local transaction. No sender transaction stays open while calling consume. delivered means the local consumer acknowledged its durable handoff, not that remote business tools succeeded. The single dispatcher here has no concurrent claim lease. SQLite BEGIN IMMEDIATE starts a write transaction; this experiment does not simulate distributed or row-level locks. The producer rejects a repeated run_id by its unique constraint; it does not implement an idempotent client-submission API that returns an existing bound task.
import contextlib
import hashlib
import json
import sqlite3
import tempfile
from pathlib import Path
@contextlib.contextmanager
def transaction(db):
db.execute("BEGIN IMMEDIATE")
try:
yield
except BaseException:
db.rollback()
raise
else:
db.commit()
def open_sender(path):
db = sqlite3.connect(path, isolation_level=None)
db.row_factory = sqlite3.Row
db.executescript("""
CREATE TABLE IF NOT EXISTS runs(run_id TEXT PRIMARY KEY, status TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS outbox(event_id TEXT PRIMARY KEY, run_id TEXT NOT NULL,
payload TEXT NOT NULL, delivered INTEGER NOT NULL DEFAULT 0,
attempts INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY(run_id) REFERENCES runs(run_id));
""")
db.execute("PRAGMA foreign_keys=ON")
return db
def open_consumer(path):
db = sqlite3.connect(path, isolation_level=None)
db.row_factory = sqlite3.Row
db.executescript("""
CREATE TABLE IF NOT EXISTS processed(event_id TEXT PRIMARY KEY, payload_hash TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS handoffs(run_id TEXT PRIMARY KEY, event_id TEXT UNIQUE,
status TEXT NOT NULL);
""")
return db
def submit(db, run_id, fail=False):
payload = json.dumps({"event_id": run_id + ":created:1", "run_id": run_id,
"type": "run.created", "payload_version": 1}, sort_keys=True)
with transaction(db):
db.execute("INSERT INTO runs VALUES (?, 'queued')", (run_id,))
if fail:
raise RuntimeError("before_outbox_insert")
db.execute("INSERT INTO outbox(event_id,run_id,payload) VALUES (?,?,?)",
(run_id + ":created:1", run_id, payload))
def consume(db, payload, fail=False):
event = json.loads(payload)
if not isinstance(event, dict) or set(event) != {"event_id", "run_id", "type", "payload_version"} or not all(type(event[k]) is str and event[k] for k in ["event_id", "run_id", "type"]) or event["type"] != "run.created" or type(event["payload_version"]) is not int or event["payload_version"] != 1:
raise ValueError("event_shape")
canonical = json.dumps(event, sort_keys=True)
fingerprint = hashlib.sha256(canonical.encode()).hexdigest()
with transaction(db):
old = db.execute("SELECT payload_hash FROM processed WHERE event_id=?", (event["event_id"],)).fetchone()
if old:
if old["payload_hash"] != fingerprint:
raise ValueError("event_id_conflict")
return "duplicate"
db.execute("INSERT INTO processed VALUES (?,?)", (event["event_id"], fingerprint))
if fail:
raise RuntimeError("before_handoff_insert")
db.execute("INSERT INTO handoffs VALUES (?,?,'accepted')", (event["run_id"], event["event_id"]))
return "accepted"
def dispatch_once(sender, consumer, fail_after_send=False):
event = sender.execute("SELECT * FROM outbox WHERE delivered=0 ORDER BY event_id LIMIT 1").fetchone()
if event is None:
return "idle"
with transaction(sender):
sender.execute("UPDATE outbox SET attempts=attempts+1 WHERE event_id=?", (event["event_id"],))
outcome = consume(consumer, event["payload"]) # outside the sender transaction
if fail_after_send:
raise RuntimeError("after_consumer_commit_before_sender_mark")
with transaction(sender):
sender.execute("UPDATE outbox SET delivered=1 WHERE event_id=?", (event["event_id"],))
return outcome
with tempfile.TemporaryDirectory(prefix="outbox-course-") as tmp:
folder = Path(tmp)
sender = open_sender(folder / "sender.sqlite")
consumer = open_consumer(folder / "consumer.sqlite")
try:
try:
submit(sender, "r-rollback", fail=True)
except RuntimeError as exc:
assert str(exc) == "before_outbox_insert"
assert sender.execute("SELECT count(*) FROM runs").fetchone()[0] == 0
assert sender.execute("SELECT count(*) FROM outbox").fetchone()[0] == 0
submit(sender, "r1")
sender.close() # committed intent must survive a reopened connection
sender = open_sender(folder / "sender.sqlite")
assert sender.execute("SELECT count(*) FROM outbox WHERE delivered=0").fetchone()[0] == 1
payload = sender.execute("SELECT payload FROM outbox").fetchone()[0]
try:
consume(consumer, payload, fail=True)
except RuntimeError as exc:
assert str(exc) == "before_handoff_insert"
assert consumer.execute("SELECT count(*) FROM processed").fetchone()[0] == 0
assert consumer.execute("SELECT count(*) FROM handoffs").fetchone()[0] == 0
try:
dispatch_once(sender, consumer, fail_after_send=True)
except RuntimeError as exc:
assert str(exc) == "after_consumer_commit_before_sender_mark"
print(json.dumps({"phase": "after_send_unmarked", "pending": sender.execute("SELECT count(*) FROM outbox WHERE delivered=0").fetchone()[0],
"handoffs": consumer.execute("SELECT count(*) FROM handoffs").fetchone()[0]}, sort_keys=True))
sender.close()
sender = open_sender(folder / "sender.sqlite")
assert dispatch_once(sender, consumer) == "duplicate"
changed = json.loads(payload)
changed["run_id"] = "other-run"
try:
consume(consumer, json.dumps(changed))
except ValueError as exc:
assert str(exc) == "event_id_conflict"
else:
raise AssertionError("conflicting replay accepted")
assert consumer.execute("SELECT count(*) FROM handoffs").fetchone()[0] == 1
assert consumer.execute("SELECT count(*) FROM processed").fetchone()[0] == 1
assert sender.execute("SELECT attempts FROM outbox").fetchone()[0] == 2
assert dispatch_once(sender, consumer) == "idle"
print(json.dumps({"phase": "after_replay", "pending": sender.execute("SELECT count(*) FROM outbox WHERE delivered=0").fetchone()[0],
"attempts": 2, "processed": 1, "handoffs": 1, "handoff_state": "accepted",
"remote_business_success": "not_measured"}, sort_keys=True))
finally:
sender.close()
consumer.close()
Expected observations
The first row is phase="after_send_unmarked", pending 1, handoffs 1. The second is phase="after_replay", pending 0, attempts 2, processed 1, handoffs 1, state accepted, with remote business success explicitly not measured.
The assertions also prove sender rollback leaves 0/0, a reopened connection finds the committed pending event, consumer failure before handoff rolls back its processed marker, and the same event ID with changed payload is rejected as event_id_conflict. The one local handoff is a measurable result; do not rename it exactly-once external business processing.
Deliver your own code and audit
Implement submit, consume and dispatch_once against the stated schemas before reading the reference. Retain the failure/reopen/replay assertions as your runnable contract. Then implement audit_intents(sender) in your own file; the reference does not provide it. It returns sorted missing_event_run_ids and pending_event_ids.
Judge the audit on a fresh database containing three runs: a has outbox event a:created:1 delivered=0; b has b:created:1 delivered=1; orphan has no outbox row. Expected missing_event_run_ids is ["orphan"], pending_event_ids is ["a:created:1"]. Marking a delivered makes the pending list empty, but orphan remains. This is deliberately inconsistent audit input, not a state created by correct submit. A task count alone cannot detect that discrepancy.
Submit your code, unchanged contract tests, audit assertions and console output. A production queue, authenticated consumer transport, dispatcher claims, retries/dead letters, ordering and external operation receipts are separate missing work. An event should start/resume durable Agent state; holding a message or SQL transaction across long inference is a different and generally costly boundary.
code example
Transport acceptance has a declared boundary
In this lab consume returns only after its local transaction commits. A real queue ACK can have different semantics, so document whether acknowledgment means broker receipt, durable consumer acceptance or something else. None automatically proves a remote tool effect.
Acceptance task for this level
Write your own submit/consume/dispatch_once and audit_intents, run the rollback/reopen/replay/conflict checks plus the three-run audit fixture, and submit code/tests/output with the handoff-versus-business distinction.
Reading this browser’s record…
Hide the answer and check your understanding
Why put processed and handoff in the same consumer transaction?
Expand reference derivation
If processed commits alone and a crash prevents the handoff, a retry may be discarded even though no durable run was accepted. If handoff commits alone, replay can repeat acceptance. Their local transaction closes that consumer gap; it still cannot atomically include a remote business effect.
Further explanations and practice
When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.
All linked explanations and exercises (1 )
Sources and verification scope
The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.