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

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Idempotency, unknown outcomes, and task recovery

Learn how stable operation IDs, server-side deduplication, and outcome queries help avoid repeated side effects after tool timeouts. Use two independent databases to examine their guarantees and limits.

Learning objectives: Distinguish execution attempts from business operations, recover unknown outcomes using stable operation identities, and explain the limits when a remote service cannot deduplicate.

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

Choose a starting point based on your familiarity with this topic. Current level: Implementation · Build it. 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: Can read SQLite transactions and basic Python.

Idempotency
Repeated requests for the same business operation do not produce duplicate business effects. The guarantee's scope depends on the server implementation and its validity period.
Operation identity
A stable identifier representing the same business intent, which is different from the identifier for each network attempt.
Checkpoint
Computational state saved by the caller. It does not automatically establish what has happened in the external service.
Unknown outcome
The caller lacks a reliable receipt and can assert neither success nor that the action was never executed.

How does the mechanism work?

Response loss: recover with the same operation identity
  1. 1
    Caller

    Saves a prepared intent with stable business key K and parameter digest H.

  2. 2
    Provider

    Receives K/H and atomically commits the business effect and queryable receipt R.

  3. 3
    Network

    The response is lost. The caller knows only that a timeout occurred; the outcome stays unknown.

  4. 4
    Recovering worker

    Looks up or retries using the same K. Identical parameters return R; conflicting parameters are rejected.

  5. 5
    Caller

    Persists R before marking the outcome confirmed; verifies that the provider has only one effect.

Safe retries depend on provider deduplication/lookup, retention periods, and current authorization. If neither capability exists, pause for human verification. A local checkpoint cannot supply a remote guarantee.

Step-by-step explanation
  1. Persist the intent

    Save the stable operation identity and parameters before initiating the action.

  2. Commit at the provider

    The provider executes and deduplicates the operation according to its own contract.

  3. Reconcile at the caller

    If the response is lost, query the outcome or retry using the same operation identity.

  4. Update task status

    Confirm the outcome after obtaining a verifiable receipt. If it cannot be reconciled, retain the unknown state.

Implementation · Build it

Recover from a successful commit with a lost receipt

Objectives of this level: Replay the same receipt using a stable operation identity; reject identity–parameter conflicts.

Visual guide · Unknown is a knowledge state

Unknown is a knowledge state

A provider may commit before the caller confirms. The two-store lab simulates receipt loss; it does not establish arbitrary remote-service guarantees. Select the figure to open it at full size.

Keep facts in two databases

provider.db holds effects and receipts; caller.db holds intent and confirmation state. Commit prepared at the caller, then commit at the provider. Deliberately omit the first receipt from caller.db. The caller remains prepared while the provider already has an effect.

Recover using the provider's deduplication contract

Retry publish-1 with report-v1. Within its local transaction, the provider checks operation identity: matching arguments return the original receipt without another effect; different arguments conflict. The caller becomes confirmed only after receiving the receipt. File-backed databases preserve provider facts beyond the first function invocation.

Define the atomic boundary

The provider uses BEGIN IMMEDIATE to put lookup, comparison, and insertion in one SQLite write transaction, preventing the lab's check-then-write race. It covers no real email, payment, or third-party publishing system; those need their own idempotency and status-query contracts. The script simulates receipt loss without killing a process or interrupting a real network.

Implement ticket recovery on an actual tool path

After this page's two-store demonstration, independently implement recovery_action in the ticket transfer practice; source package: https://ai.lwkjob.com/downloads/agent-workorder-transfer-v1.zip. Its controller actually calls a local HTTP ticket authority, durably saves unknown before a write, drops a response after commit and reopens the controller against the same stores. Only the original key/digest's authoritative receipt completes work; a local success flag is insufficient.

Implement the junior select_sources contract first, then run: python3 verify.py --learner my_workorder.py --level intermediate --out work/after-intermediate.json. The cumulative 29 checks include source contracts, original-key recovery and authority boundaries, not 29 learners or live-model calls.

Separate observations: a known 400/403/409 under this authority's no-new-effect contract records last_denial for caller handling; disconnect/5xx stays unknown; strong authoritative absent permits the unchanged request/key; unavailable requires wait. A committed receipt with a different digest yields conflict, never a replacement-key retry. Lost-before and lost-after look alike to the caller but differ after authoritative lookup.

Keep before/after reports, your diff, agent.sqlite/service.sqlite and authority-facts.json; explain why restart preserved the business ledger. An eventual index, expired deduplication key or cross-system effect changes the contract: not_found no longer proves this lab's absent, so reassess retry and manual reconciliation.

Run experiments and observe counterexamples

Two local SQLite files simulate independent commits and response loss. No real remote service, process termination, or network failure is involved; this does not establish end-to-end exactly-once execution.

Python 3.10+ · Runs by default using only the standard library · Runs on your computer

  1. Observe the differences between the caller's prepared and the server's submitted
  2. Get the original receipt along the same operation identity
  3. Use the same identity to change content and verify conflicts
Downloadidempotency_recovery.py ↓
python3 idempotency_recovery.py
View the entry-point script
"""Two local SQLite files model independent caller/provider commits.

Not a real remote service, production queue or end-to-end exactly-once proof.
"""
import json
import sqlite3
import tempfile
from pathlib import Path


def provider(path, operation, payload):
    with sqlite3.connect(path) as db:
        db.execute("CREATE TABLE IF NOT EXISTS effects (operation TEXT PRIMARY KEY, payload TEXT NOT NULL, receipt TEXT NOT NULL)")
        # Serializes the read/check/write in this local demonstration.
        db.execute("BEGIN IMMEDIATE")
        existing = db.execute("SELECT payload,receipt FROM effects WHERE operation=?", (operation,)).fetchone()
        if existing:
            if existing[0] != payload:
                raise ValueError("same operation with different payload")
            return existing[1]
        receipt = "receipt:" + operation
        db.execute("INSERT INTO effects VALUES(?,?,?)", (operation, payload, receipt))
        return receipt


def demo():
    with tempfile.TemporaryDirectory() as folder:
        remote, local = Path(folder) / "provider.db", Path(folder) / "caller.db"
        with sqlite3.connect(local) as db:
            db.execute("CREATE TABLE intents(operation TEXT PRIMARY KEY, payload TEXT, status TEXT, receipt TEXT)")
            db.execute("INSERT INTO intents VALUES('publish-1','report-v1','prepared',NULL)")
        first = provider(remote, "publish-1", "report-v1")
        # Simulated response loss: provider committed, caller did not get receipt.
        with sqlite3.connect(local) as db:
            before = db.execute("SELECT status FROM intents").fetchone()[0]
        second = provider(remote, "publish-1", "report-v1")
        with sqlite3.connect(local) as db:
            db.execute("UPDATE intents SET status='confirmed', receipt=?", (second,))
        with sqlite3.connect(remote) as db:
            effects = db.execute("SELECT COUNT(*) FROM effects").fetchone()[0]
        assert before == "prepared" and first == second and effects == 1
        return dict(caller_before_recovery=before, same_receipt=first == second,
                    provider_effects=effects, caller_after_recovery="confirmed")


if __name__ == "__main__":
    print(json.dumps(demo(), sort_keys=True))

Expected output when running locally

{"caller_after_recovery": "confirmed", "caller_before_recovery": "prepared", "provider_effects": 1, "same_receipt": true}
  • There is only one business effect for the server
  • Consent diagram retry receipt consistent
  • Remote capabilities and deduplication deadlines need to be verified separately
View the running environment, output and verification records →

code example

Deduplication of business operations within SQLite transactions

import hashlib
import json
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE publications (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    tenant TEXT NOT NULL,
    title TEXT NOT NULL
);
CREATE TABLE operations (
    tenant TEXT NOT NULL,
    op_key TEXT NOT NULL,
    payload_hash TEXT NOT NULL,
    result_id INTEGER NOT NULL,
    PRIMARY KEY (tenant, op_key)
);
""")

def publish(tenant, op_key, title):
    payload = json.dumps({"title": title}, sort_keys=True).encode()
    digest = hashlib.sha256(payload).hexdigest()
    db.execute("BEGIN IMMEDIATE")
    try:
        old = db.execute(
            "SELECT payload_hash, result_id FROM operations WHERE tenant=? AND op_key=?",
            (tenant, op_key),
        ).fetchone()
        if old:
            if old[0] != digest:
                raise ValueError("IDEMPOTENCY_CONFLICT")
            db.commit()
            return old[1]
        cur = db.execute(
            "INSERT INTO publications(tenant,title) VALUES (?,?)", (tenant, title)
        )
        result_id = cur.lastrowid
        db.execute("INSERT INTO operations VALUES (?,?,?,?)",
                   (tenant, op_key, digest, result_id))
        db.commit()
        return result_id
    except Exception:
        db.rollback()
        raise

print(publish("t1", "task-7:publish:v3", "Agent recovery"))
print(publish("t1", "task-7:publish:v3", "Agent recovery"))
print("rows", db.execute("SELECT COUNT(*) FROM publications").fetchone()[0])
try:
    publish("t1", "task-7:publish:v3", "Changed title")
except ValueError as exc:
    print(str(exc))
db.close()

Python 3 standard library demonstration, using in-memory SQLite; real recovery requires a file or server database, and external actions require remote idempotent capabilities.

Acceptance task for this level

Run idempotency_recovery.py, and then submit report-v2 for the same identity to observe conflicts.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Can a unique constraint in the local database prevent duplicate sends by a remote email system?

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 (5 )

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.