Agent Harness Tutorial · End to end · Zoom level 3
Doing a write exactly once
Networks fail at the worst moment: the claim was registered, but the reply got lost, so the browser sends the message again. Without care, Rohan now has two claims. The ledger makes every write happen exactly once.
Goes inA write with a key, e.g.
run_fef1…:0:1What happensClaim a row in the ledger before the call; record the result after
Comes outOne effect in the world, however many times it was asked
| Where | The key | What a repeat gets |
|---|---|---|
| The message from the browser | PH-1001 + the id the browser made for this message | The first reply, or 409 if still running |
| A write tool call | run id : step : iteration | The stored result, "replayed" |
| The claims system | the same key, carried in the MCP call | The first answer; no second claim, no second payout |
| An approval | a hash of key + action + arguments | The approval already running |
Notice the key is carried all the way to the claims system, which keeps its own "answered" table. So even if our ledger were lost, the far end still refuses to do the same write twice.
Want every detail? The long version is in the Series: how idempotency works.
Code view: input, process, output, the call stack, the classes
Goes inA message's delivery id, and each write call's idempotency key
What happensEach name is claimed in agent_state.requests before the work runs, then settled with a definite answer or given back so a retry reuses the same name
Comes outOne effect per name; a repeat is handed the first answer
How it is done: the real code
Cut from the live repositories each time the site is built, so it always matches what runs.
agent_harness/requests/postgres.py:37Claim a ledger row: INSERT … ON CONFLICT async def claim(self, name: str, *, scope: Scope, ttl_s: int = CLAIM_TTL_S) -> Claim:
"""Take the name, or say which refusal this is.
One statement. The `WHERE` on the conflict branch is the whole guard: it
matches only a claim that expired, so a live holder and an answered name
both leave zero rows and the second query below says which. Two callers
racing here both attempt the same insert and exactly one changes a row.
"""
async with self._pool.connection() as conn:
taken = await (
await conn.execute(
"""
INSERT INTO agent_state.requests (name, scope, state, expires_at)
VALUES (%s, %s, 'in_flight', now() + make_interval(secs => %s))
ON CONFLICT (name) DO UPDATE
SET scope = EXCLUDED.scope,
state = 'in_flight',
outcome = NULL,
expires_at = EXCLUDED.expires_at,
recorded_at = now()
WHERE agent_state.requests.state = 'in_flight'
AND agent_state.requests.expires_at < now()
RETURNING name
""",
(name, scope.value, ttl_s),
)
).fetchone()
if taken is not None:
return Claim(name=name, scope=scope)
row = await (
await conn.cursor(row_factory=dict_row).execute(
"SELECT state, outcome FROM agent_state.requests WHERE name = %s", (name,)
)Tech choices (what we chose, Azure and open-source options): L8 · Concurrency & flow