Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Atomic intent and duplicate delivery with the outbox pattern

Examine double-write issues, transaction outboxes, duplicate deliveries, and recovery scans.

Learning objectives: 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.

Content checked: 2026-10-03 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Debugging · Diagnose failures. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

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
  1. What happens if the sending succeeds but the tag fails?

    Move from atomically committing intent to the second failure window: external delivery.

  2. Does the message ACK mean the business is successful?

    Distinguish between transport-level success and task-level success.

  3. How to avoid deleting undelivered events when cleaning Outbox?

    A reliable delivery chain also needs a retention and cleanup lifecycle.

Debugging · Diagnose failures

Debug · Two transactions strand a queued run

Objectives of this level: Reproduce a persisted orphan after reopening the database, identify the split-commit cause and repair one producer function.

Visual guide · Atomic intent, repeatable delivery

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.

Exact failure experiment

A submission returns or fails near the same two writes. The following faulty producer commits runs first and outbox later. Save the full snippet as an independent outbox_atomic_check.py. It creates a temporary database, deliberately stops between writes using an injected exception, closes/reopens the connection and scans for committed runs with no event. No existing project state is changed. Run it; the orphan assertion is intentionally expected to fail.

import contextlib
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 submit(db, run_id, fail=False):
    # BUG: two transactions leave a durable task without a durable event.
    with transaction(db):
        db.execute("INSERT INTO runs VALUES (?, 'queued')", (run_id,))
    if fail:
        raise RuntimeError("process_stopped_between_writes")
    with transaction(db):
        db.execute("INSERT INTO outbox VALUES (?,?)", (run_id + ":created:1", run_id))

with tempfile.TemporaryDirectory(prefix="outbox-fault-") as tmp:
    path = Path(tmp) / "sender.sqlite"
    db = sqlite3.connect(path, isolation_level=None)
    db.executescript("CREATE TABLE runs(run_id TEXT PRIMARY KEY,status TEXT); CREATE TABLE outbox(event_id TEXT PRIMARY KEY,run_id TEXT);")
    try:
        submit(db, "r-fault", fail=True)
    except RuntimeError as exc:
        assert str(exc) == "process_stopped_between_writes"
    db.close()
    db = sqlite3.connect(path, isolation_level=None)
    try:
        stranded = [r[0] for r in db.execute("SELECT r.run_id FROM runs r LEFT JOIN outbox o ON o.run_id=r.run_id WHERE o.event_id IS NULL ORDER BY r.run_id")]
        counts = [db.execute("SELECT count(*) FROM " + t).fetchone()[0] for t in ["runs", "outbox"]]
        print(json.dumps({"after_reopen": counts, "stranded": stranded}, sort_keys=True), flush=True)
        assert counts == [0, 0], "committed task has no outbox intent"
        assert stranded == []
        submit(db, "r-ok")
        assert [db.execute("SELECT count(*) FROM " + t).fetchone()[0] for t in ["runs", "outbox"]] == [1, 1]
        print("rollback=0/0; normal commit=1/1; no stranded task: passed")
    finally:
        db.close()

Use evidence to locate the root cause

Before repair the output is after_reopen=[1,0], stranded=["r-fault"], followed by AssertionError: committed task has no outbox intent. The orphan remains after reopening, so this is a durable split commit, not a transient missing console message. Catching the injected exception does not undo the already committed first transaction.

Modify only submit in your copied file. Use a single with transaction(db) containing the run INSERT, the failure point and the event INSERT. Keep the failure point, reopen and all assertions unchanged. Rerun from a fresh process. Failure before the event insert must now roll back both writes: after_reopen [0,0], stranded [], then the normal r-ok case commits 1/1 and the final pass message appears. Removing the failure injection or deleting r-fault manually would hide the cause instead of repairing it.

Explain the limit: closing/reopening tests persistence after a simulated operation stop; it is not proof about real power loss, concurrent dispatchers or every queue window. The implementation layer separately verifies duplicate handoff after send-before-mark. A correct atomic producer does not eliminate that later duplicate window.

code example

Mark-before-send creates a different loss

A dispatcher that marks delivered before calling the transport can stop with no pending row and no consumer acceptance. Changing the producer does not repair that dispatcher order. Its failure test needs a pending scan and consumer acceptance evidence, not just task existence.

Acceptance task for this level

Capture the faulty file’s reopened 1/0 orphan result, repair only submit to use one transaction, and rerun the unchanged failure and healthy controls. Submit the minimal diff and evidence→cause→repair explanation.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Would retrying the outbox INSERT in the original request’s except block fix this reliability issue?

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.