Agent Harness Tutorial · End to end · Zoom level 3
How we take care of it: delivery ledger
delivery ledger catches the same message sent twice.
How we took care of it.
- Insert a ledger row PH-1001:
as in_flight, expiring in 600 seconds. - If the row is already answered, return the stored reply instead of running again.
- If it is still in flight and live, answer 409; if it is stale, take it over.
| It reads | the idempotency-key header the browser makes once per message |
| Kind | rule |
| Provided by | harness |
| If it fails | the stored first answer, or 409 |
| Where in the code | Agent.handle · F entrypoint/__init__.py:141 · H requests/postgres.py |
| Runs at | 1 · Before the loop |
Real exampleFlow 17: the same message sent twice; the second got the same words back in 140 ms, with no turn run.
More on this: Exactly once.
How it is done: the real code
Cut from the live repositories each time the site is built, so it always matches what runs.
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,)
)