Context Engineering for Long-Running AI Agents: Async Tasks and Updates
Keep long-running AI agents correct when a user changes the task, an async tool result lands late or approval is revoked, with ordering rules and event replays.
Table of Contents
Take an illustrative support ticket. An agent starts a refund for order A-100 and asks a pricing tool for a quote. While that call runs, the customer writes that the order was really A-200, and a supervisor approves a refund for A-200. Then the A-100 quote comes back, and the supervisor revokes the approval.
Long-running AI agents hold one task open for hours or days and keep working while async tasks finish and updates change the facts under them. This one appended every event to its context as one more message, kept its plan bound to A-100 and read approval once, like a latch. So it refunded 40 on A-100, an order nobody approved.
The fix has three parts: ordering rules for events, validity rules for what sits in context, and an approval re-check at the moment of the side effect. A scripted replay of this ticket shows each part failing and then passing, and the script is shown in full, tested end to end.
TL;DR
- Long-running AI agents go wrong when a new instruction, a late async tool result or a revoked approval arrives while the run continues.
- Give every event a per-run sequence number and every instruction or approval change a new state version, and stamp each tool call with the version it was issued under.
- Treat a result stamped older than the state it depends on as stale: re-run it if the tool only reads, drop or reconcile it if the tool writes, and supersede a changed instruction instead of appending it.
- Read approval from the approval system right before each side-effecting call, send a stable idempotency key, and let the destination check approval too, because a revoke can land during the call.
- A scripted event stream on a counter clock shows the append-only agent failing every case and the versioned agent passing all but one: a revoke during the refund call, which only the destination’s own check stops.
Why long-running AI agents act on stale context
A long-running agent builds its context at one moment and acts on it minutes or hours later. Three events break that context while the run continues: the user sends a new instruction, an async tool result lands after the agent moved on, and an approval gets revoked before the action it covered.
A chat turn ends in seconds, so the facts it read still hold when it answers. A run that waits on a background job or a human approver uses its facts much later. Appending each new event as another message keeps everything visible, but the plan stays bound to the first instruction.
Coding agents show the same shape. In one Claude Code issue report (anthropics/claude-code issue 57568), the agent finished the old prompt’s in-flight tool call and only then read the user’s mid-run correction. The model did read every message, but it acted on the old prompt first. Append-only context never marks an earlier instruction as replaced.
This post covers events that arrive during a run; the discipline is defined in our guide to context engineering, and subagent layout lives in how subagents split and hand off context.

A new user instruction mid-task
At tick 3 of the replay’s counter clock the customer changes the order from A-100 to A-200. The append-only agent adds the message to its context and keeps going, so its notify step at tick 4 told the customer about A-100, the order they had just abandoned. The new instruction was read, but it replaced nothing.
The versioned agent treats the new instruction as a state change. It bumped the state version, marked the A-100 instruction superseded and printed “supersede: instruction now A-200 at v2”. From that tick on, every step read the one active instruction, so its notify step named A-200.
An async tool result that lands after the agent moved on
The quote call c1 went out at tick 2, under state version 1, for A-100. It came back at tick 5, after the instruction had moved to version 2. The append-only agent took the latest result in its context and wrote amount 40 to the ticket.
Arrival order and issue order differ whenever work runs in the background. A slow pricing service, a queued job or a retried request can return after newer events, and the result carries no sign that it is old. Without a stamp taken at issue time, the agent cannot tell fresh from stale.
An approval granted, then revoked
At tick 4 the supervisor approved a refund for A-200, which the run recorded as “approval_granted for A-200 at v3”. At tick 6 the supervisor revoked it, recorded as “approval_revoked for A-200 at v4”. Two approval facts changed inside one run, and the second one cancels the first.
The append-only agent set a flag when the grant arrived and never cleared it. At tick 7 it printed “approval latch set at plan time, called refund for A-100 (ok)”. It refunded an order that was never approved, one tick after the only approval in the run had been withdrawn.
Ordering events in long-running AI agents
Give every event in a run a sequence number from one counter, and give every change to instructions or approvals a new state version. Stamp each tool call with the version it was issued under and an idempotency key. Late then has a precise meaning: a result stamped older than the state it depends on.
One writer per run assigns the numbers, which makes the counter a logical clock. Ordering then never depends on wall-clock time across machines, where clocks drift and two hosts can disagree about which event came first. State versions move only on changes that can invalidate work: a new instruction or an approval change.
OpenAI’s async tool calling guide makes late results a documented feature. With async: true on a function or custom tool, the model keeps working, and the output returns in a later Responses request matched by the original call_id. As of 2026-11-19 it covers GPT-6 Astra and later models.
Duplicate deliveries happen too, so the ID that matches a result to its call doubles as an idempotency key. In replay scenario B, defined below, the same c1 result arrived twice. The versioned agent printed “drop: duplicate delivery of c1, result id already applied”, while the append-only agent appended both copies and kept going.
One sequence counter per run
The counter lives with the run, not with any one worker. It increments on every event the run accepts and on every re-run the agent issues, and your log and spans sort by it. No two events share a number, so a reviewer can rebuild the order exactly.
In the versioned run of scenario A, the counter went from 1 to 6. Sequence 4 was the late c1 result, 5 was the re-run quote for A-200 and 6 was the revoke. The state version reached only 4, because a tool result never changes which instruction or approval is in force.
Idempotency keys on tool calls and results
Two kinds of key do two jobs. The call ID dedupes a second delivery of one result. A side effect needs a stable key per logical action, built from the run and the order, never from the attempt. The append-only agent minted a new key per attempt, and scenario B’s retry refunded 40 twice.
Retries are normal in long runs, so plan for them. Google’s long-running agents codelab says: “ADK’s own ResumabilityConfig docstring warns that a resumed tool call is at-least-once: the platform will retry you.” So the replay’s refund key is the run plus the order.
What late means for async agents
Late means stamped before its dependency last changed, whatever the delay. A result that takes an hour is still valid if nothing it depends on moved in that hour, and a result that returns at once is already stale if the customer changed the order while the call ran.
That gives async agents one rule to run before any result re-enters context: compare the result’s stamp with the version at which its dependency last changed. Equal or newer, accept it. Older means stale, and what happens next depends on whether the tool only reads or also writes.
Context validity rules for instructions, results and approvals
Every item in the agent’s context carries the state version it was produced under. When the state an item depends on has moved past that version, the agent stops treating it as current. It supersedes a changed instruction, re-runs or drops a stale tool result by tool class, and reads approval live.
- New instruction: supersede the old one.
- Result stamped older than its dependency: re-run it if the tool reads, drop and reconcile if it writes.
- Side effect: read approval live, and let the destination check it too.
Each context item is a small record: sequence number, arrival tick, kind, the state it depends on, its stamp, and a status of current, stale, superseded or duplicate. The rules read only the stamp and the dependency, and they write only the status.
Approval is the one input the agent should not trust from context. It is a fact owned by another system, so the versioned agent records approval events for the log and looks the answer up at the act. Its record line says so: “approval is read live at the act, not from here”.

Where this work sits among the prompt, harness and loop layers of context engineering is mapped in our four-layer guide, and recall or forgetting in long-term stores is covered in evaluating agent memory systems.
Stamp each item with the version it was produced under
An instruction or approval event creates a new version, and its stamp is that version: the A-200 instruction is stamped v2 and the grant v3. A tool result creates no version, so it inherits the version its call was issued under. That is how the c1 result arrived at tick 5 stamped v1.
The stamp is taken when the call goes out, not when the result lands. The pending-call table records the order, the version and the tick at issue time, and the result looks itself up there on arrival. Staleness is then one integer comparison, with no clock involved.
Drop, reconcile or re-run a stale result
The script decides by tool class with a two-entry table: read maps to rerun, write maps to drop. The quote tool only reads, so the versioned agent re-ran it under the current instruction, printed “re-ran the read-only quote for A-200 as seq 5”, and then wrote amount 25 to the ticket.
Results from write tools never get a blind re-run, because the first call may already have changed something. Drop the stale result from context and reconcile with the system that owns the write. The same split applies when an agent is interrupted mid-call: a read can finish, and a write waits for confirmation.
Supersede a changed instruction instead of appending it
Keep one active instruction per run. When a new one arrives, mark the old one superseded and mark anything derived from it stale, such as a cached quote. The versioned agent’s supersede line ends with “instead of appending”, and its code invalidates any cached quote older than the new instruction.
Two live instructions in context let the model pick either one, and nothing says which is current. Marking the old one superseded settles that before the model sees it. The step code reads only the active instruction, so a plan built on A-100 cannot survive the switch.
Re-check approval at the moment of the side effect
Check approval when the side-effecting call is about to run, not when the plan was made. Read it from the approval system, pass a stable idempotency key, and let the destination check approval again where it can. A re-check inside the agent narrows the revocation window, and the destination’s own check closes it.
The OpenAI Agents SDK human-in-the-loop guide says: “Approval permits a tool call to execute; it does not guarantee exactly-once execution.” It recommends a stable idempotency key for each logical action, passed to a destination that atomically prevents duplicate effects.
Runtimes already expose the right moment for a live check. The Claude Agent SDK hooks page describes PreToolUse, which fires when a tool is about to be called and receives its input. The Google ADK codelab uses before_tool_callback to re-read the world before spending, and a returned dict short-circuits the tool.
None of the runtime pages checked on 2026-11-19 describes revoking an approval that was already granted. Whether a grant still holds at the act is a rule your own code enforces, so the replay treats revocation as an event with its own version.
The wider map of failures beyond approvals is in our post on where agent setups break in production.
Plan-time approval is a latch
The append-only agent sets a flag when approval_granted arrives and never clears it, because the revoke is just one more appended message. A flag set at plan time answers a question about the past. At tick 7 the flag was still set, so the agent called the refund without asking anyone.
Scenario A’s append-only ledger holds the damage: one refund of 40 for A-100, executed after the only approval in the run was revoked. The revoke sat in context the whole time, and no step ever read it, because the latch answered the question first.
Read approval live at the act
The versioned agent asks the approval system, not its own context, right before the call. When approval is not in force, it blocks, logs the decision and makes no call. In scenario A it printed “blocked: approval for A-200 not in force at the act, no call made”, and its refund ledger stayed empty.
The key is stable per order, so a retry after a lost response cannot refund twice. In scenario B the first refund response was lost, the agent retried at tick 8 with the same key, and the ledger held one refund of 25 for A-200. The append-only agent’s fresh key per attempt refunded A-100 twice.
Let the destination enforce approval too
Scenario C moves the revoke inside the refund call, after the agent’s re-check and before the write. The versioned agent’s live read returned granted, the call went out and the refund executed. Its ledger shows one refund of 25 for A-200, and case C3 printed FAIL for that mode.
With the refund service checking approval on its own side, the same call came back rejected and the ledger stayed empty, so C3 passed. The agent’s check shrinks the gap to the length of one call. Only the destination runs the check and the write as one step.
How agent runtimes queue input that arrives mid-run
OpenAI mid-turn steering, Claude Agent SDK streaming input and the GitHub Copilot SDK accept input mid-run and either inject it into the current turn or hold it for later. They decide when the agent sees it. Validity stays with your code: whether an earlier result, plan or approval still holds.
OpenAI mid-turn steering runs on the GPT-6 model family over a WebSocket connection to the Responses API. It does not “cancel tools that have already started”, so a late result from the old direction still arrives. Queued steering input exists only on the current connection, so keep your own record.
With Claude Agent SDK streaming input, interrupt() stops a response and keeps the session open. Messages sent before the interrupt that Claude had not read “still reach Claude once the interrupted response ends.” Each row of the table comes from the runtime’s own docs, read on 2026-11-19.
| Runtime and feature | What happens to mid-run input or late results | What stays with your code |
|---|---|---|
| OpenAI Responses async tool calling | async: true lets the model keep working; the result returns in a later request matched by call_id; GPT-6 Astra and later, function and custom tools only | Decide whether the result still applies |
| OpenAI mid-turn steering | GPT-6 model family over WebSocket; response.steer queues input; accepted means queued; tools already started are not cancelled; queued input lives only on the connection | Record steering inputs and handle results from the old direction |
| OpenAI Agents SDK (Python) approvals | A tool that needs approval pauses the run with interruptions; decisions are stored per call ID | Approval gives no exactly-once guarantee, so pass a stable idempotency key |
| Claude Agent SDK streaming input | The session stays open for more messages; interrupt() ends the response; unread messages still reach Claude afterwards | Put live checks in the PreToolUse hook |
| GitHub Copilot SDK | Mode immediate steers the current turn; enqueue waits for the turn to end; a send acknowledgement confirms acceptance only | Do not resend, and check validity yourself |
| Google ADK long-running agents codelab | before_tool_callback runs before the tool and a returned dict short-circuits it; the example re-reads inventory and derives an Idempotency-Key | The pattern for a re-check at the act |
Accepted is not the same as acted on
OpenAI’s steering guide says “Acceptance means the input is queued, not that the model has acted on it.” The GitHub Copilot SDK steering and queueing page says a send acknowledgement “confirms acceptance, not that the recipient has consumed the message.”
Both pages lead to one rule: never resend a message that was accepted, even when no reply appears. Record every input with its sequence number when you send it, so the log shows what the agent could have seen, and when.
Replaying the three events with a scripted clock
A scripted event stream reproduces each case the same way on every run. A counter replaces the wall clock, a stub policy replaces the model, and each event lands on a fixed tick. Run one stream against an append-only agent and a versioned agent, then assert one property per case.
The fixture is synthetic: orders A-100 and A-200, refund quotes of 40 and 25, no LLM, no network and no wall clock. Every number it prints is illustrative, not measured customer results. It runs three scenarios in three modes (printed as naive, versioned and versioned+dest): append-only, versioned, and versioned plus a refund service that checks approval itself.
- Scenario A: the instruction changes at t3, the late c1 result lands at t5, approval is revoked at t6 and the refund step runs at t7.
- Scenario B: approval stays valid, c1 is delivered twice, and the first refund response is lost, so the agent retries at t8.
- Scenario C: the revoke lands during the refund call at t7.
The script below is tested end to end on Python 3.12.13. Install with pip install fi-instrumentation-otel==1.4.0 opentelemetry-sdk==1.45.2 and run python event_replay.py. Spans go through FITracer into an in-memory exporter from the OpenTelemetry Python SDK, so no key is needed.
# Python 3.12.13, checked on PyPI 2026-11-18
fi-instrumentation-otel==1.4.0
opentelemetry-sdk==1.45.2
"""Scripted event replay for a long-running agent: naive vs versioned context.
Everything here is a SYNTHETIC fixture: orders, quotes, approvals and events are
invented, the agent is a deterministic policy (no LLM), the clock is a counter
(no wall time) and nothing touches the network. The naive agent models the
append-only pattern (plan bound once, approval kept as a latch); it is a stub,
not a measurement of any product.
Run: python event_replay.py
"""
import importlib.metadata as md
import json
import platform
import sys
from dataclasses import dataclass, field
from fi_instrumentation import FITracer, register, using_metadata, using_session
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
QUOTES = {"A-100": 40, "A-200": 25} # synthetic refund quotes per order
TOOL_CLASS = {"quote_refund": "read"} # read results can be re-run, write results cannot
ACTING = {"notify", "update_ticket", "refund_executed"}
def stale_action(tool_class):
"""What to do with a result that arrives stamped before its dependency changed."""
return {"read": "rerun", "write": "drop"}[tool_class]
class ScriptedClock:
def __init__(self):
self.tick = 0
@dataclass
class Item:
seq: int # position in the run's event log
tick: int # arrival tick on the scripted clock
kind: str
dep: str # which piece of state the item depends on
stamp: int # state version the item was produced under
data: dict
status: str = "current"
@dataclass
class Scenario:
name: str
events: dict # tick -> [(kind, data)] delivered before the agent steps
steps: dict # tick -> [step name]
cases: list
mid_act: dict = field(default_factory=dict) # tick -> events that land during the refund call
lose_first_refund_response: bool = False
class World:
"""Ground truth: state versions, the approval system, the refund service, the action log."""
def __init__(self, scn, enforce):
self.scn, self.enforce = scn, enforce
self.clock = ScriptedClock()
self.version, self.seq = 0, 0
self.changed_at = {"instruction": 0, "approval": 0}
self.instruction_order, self.approved = None, set()
self.pending, self.actions, self.entries, self.keys = {}, [], [], set()
self.deferred, self.lost = [], False
def apply(self, ev):
kind, data = ev
self.seq += 1
if kind == "instruction":
self.version += 1
self.changed_at["instruction"] = self.version
self.instruction_order = data["order"]
return Item(self.seq, self.clock.tick, kind, "instruction", self.version, dict(data))
if kind in ("approval_granted", "approval_revoked"):
self.version += 1
self.changed_at["approval"] = self.version
(self.approved.add if kind == "approval_granted" else self.approved.discard)(data["order"])
return Item(self.seq, self.clock.tick, kind, "approval", self.version, dict(data))
order, stamp, issued = self.pending[data["call_id"]] # tool_result: stamp is the issue-time version
body = {"call_id": data["call_id"], "order": order, "amount": QUOTES[order], "issued_tick": issued}
return Item(self.seq, self.clock.tick, kind, "instruction", stamp, body)
def issue_call(self, order):
cid = f"c{len(self.pending) + 1}"
self.pending[cid] = (order, self.version, self.clock.tick)
return cid
def rerun(self, order, original_id):
self.seq += 1
body = {"call_id": f"{original_id}-rerun", "order": order, "amount": QUOTES[order], "issued_tick": self.clock.tick}
return Item(self.seq, self.clock.tick, "tool_result", "instruction", self.version, body)
def approval_live(self, order):
return order in self.approved
def act(self, name, order, used, **extra):
rec = dict(tick=self.clock.tick, name=name, order=order, instruction_order=self.instruction_order,
stale_inputs=[i.seq for i in used if i.stamp < self.changed_at[i.dep]], **extra)
self.actions.append(rec)
return rec
def refund(self, order, amount, key, used, approval_checked):
for ev in self.scn.mid_act.pop(self.clock.tick, []): # lands during the call
self.deferred.append(self.apply(ev))
live = self.approval_live(order)
if self.enforce and not live:
return "rejected", self.act("refund_rejected", order, used, approval_checked=approval_checked, approval_live=live)
if key in self.keys:
rec = self.act("refund_deduped", order, used, approval_checked=approval_checked, approval_live=live)
else:
self.keys.add(key)
self.entries.append((order, amount))
rec = self.act("refund_executed", order, used, approval_checked=approval_checked, approval_live=live)
if self.scn.lose_first_refund_response and not self.lost:
self.lost = True
return "timeout", rec
return "ok", rec
class Naive:
"""Append-only context, plan bound at the first step, approval kept as a one-time latch."""
def __init__(self, w, run):
self.w, self.run, self.ctx = w, run, []
self.latched, self.plan, self.plan_item, self.attempt, self.confirmed = False, None, None, 0, False
def last(self, kind):
return next((i for i in reversed(self.ctx) if i.kind == kind), None)
def on_item(self, it):
self.ctx.append(it)
self.latched = self.latched or it.kind == "approval_granted"
return "append", f"appended {it.kind} to context, nothing re-evaluated"
def step_quote(self):
self.plan_item = self.last("instruction")
self.plan = self.plan_item.data["order"]
cid = self.w.issue_call(self.plan)
return "quote", f"issued {cid} for {self.plan}, plan bound to {self.plan}", None
def step_notify(self):
rec = self.w.act("notify", self.plan, [self.plan_item], approval_checked=False)
return "notify", f"told the customer about {self.plan} (plan bound earlier)", rec
def step_record(self):
q = self.last("tool_result")
rec = self.w.act("update_ticket", self.plan, [self.plan_item, q], approval_checked=False, amount=q.data["amount"])
return "update_ticket", f"wrote amount {q.data['amount']} from the latest result in context", rec
def step_refund(self):
if self.confirmed or not self.latched:
return "skip", "already confirmed or never approved", None
self.attempt += 1
q = self.last("tool_result")
res, rec = self.w.refund(self.plan, q.data["amount"], f"{self.run}:refund:{self.attempt}", [self.plan_item, q], False)
self.confirmed = res == "ok"
return "refund", f"approval latch set at plan time, called refund for {self.plan} ({res}), new key per attempt", rec
class Versioned:
"""State-version stamps, supersede on change, stale-result policy, approval re-check at the act."""
def __init__(self, w, run):
self.w, self.run, self.ctx = w, run, []
self.changed_at = {"instruction": 0, "approval": 0}
self.active, self.quote, self.seen, self.confirmed = None, None, set(), False
def on_item(self, it):
if it.kind == "tool_result":
rid = it.data["call_id"]
if rid in self.seen:
it.status = "duplicate"
self.ctx.append(it)
return "drop", f"duplicate delivery of {rid}, result id already applied"
self.seen.add(rid)
if it.stamp < self.changed_at[it.dep]:
it.status = "stale"
self.ctx.append(it)
note = (f"{rid} issued at t{it.data['issued_tick']} under v{it.stamp}, arrived t{it.tick} "
f"after the instruction changed at v{self.changed_at['instruction']}")
if stale_action(TOOL_CLASS["quote_refund"]) == "rerun":
new = self.w.rerun(self.active.data["order"], rid)
self.seen.add(new.data["call_id"])
self.ctx.append(new)
self.quote = new
return "rerun", f"{note}; re-ran the read-only quote for {new.data['order']} as seq {new.seq}"
return "drop", note
self.ctx.append(it)
self.quote = it
return "accept", f"{rid} stamped v{it.stamp}, still valid"
self.ctx.append(it)
self.changed_at[it.dep] = it.stamp
if it.kind == "instruction":
note = f"instruction now {it.data['order']} at v{it.stamp}"
had_active = self.active is not None
if self.active:
self.active.status = "superseded"
note += f", replaced the {self.active.data['order']} instruction (v{self.active.stamp}) instead of appending"
self.active = it
if self.quote and self.quote.stamp < it.stamp:
self.quote.status = "stale"
self.quote = None
note += ", cached quote invalidated"
return ("supersede" if had_active else "record"), note
return "record", f"{it.kind} for {it.data['order']} at v{it.stamp}, approval is read live at the act, not from here"
def step_quote(self):
cid = self.w.issue_call(self.active.data["order"])
return "quote", f"issued {cid} for {self.active.data['order']} under v{self.w.version}", None
def step_notify(self):
o = self.active.data["order"]
return "notify", f"told the customer about {o} (active instruction)", self.w.act("notify", o, [self.active], approval_checked=False)
def step_record(self):
if not self.quote:
return "skip", "no valid quote in context, failing closed", None
o = self.active.data["order"]
rec = self.w.act("update_ticket", o, [self.active, self.quote], approval_checked=False, amount=self.quote.data["amount"])
return "update_ticket", f"wrote amount {self.quote.data['amount']} from {self.quote.data['call_id']}", rec
def step_refund(self):
if self.confirmed:
return "skip", "refund already confirmed", None
o = self.active.data["order"]
used = [self.active, self.quote] if self.quote else [self.active]
live = self.w.approval_live(o) # ask the approval system, not the context
if not live or not self.quote:
rec = self.w.act("refund_blocked", o, used, approval_checked=True, approval_live=live)
return "blocked", f"approval for {o} not in force at the act, no call made", rec
res, rec = self.w.refund(o, self.quote.data["amount"], f"{self.run}:refund:{o}", used, True)
self.confirmed = res == "ok"
return "refund", f"approval re-checked live (granted), called refund for {o} ({res}), stable key", rec
def c1(w, a): return all(r["order"] == r["instruction_order"] for r in w.actions if r["name"] in ACTING)
def c2(w, a): return all(not r["stale_inputs"] for r in w.actions)
def c3(w, a): return all(r["approval_live"] for r in w.actions if r["name"] == "refund_executed")
def c4(w, a): return len({o for o, _ in w.entries}) == len(w.entries)
def c5(w, a):
ids = [i.data["call_id"] for i in a.ctx if i.kind == "tool_result" and i.status == "current"]
return len(ids) == len(set(ids))
def control(w, a): return w.entries == [("A-200", 25)]
CASES = {
"C1 new instruction mid-task: every action targets the instruction in force": c1,
"C2 late result: no action consumed a result stamped before its dependency changed": c2,
"C3 approval revoked: every executed refund had an approval in force": c3,
"C4 retry: at most one refund entry per order": c4,
"C5 duplicate delivery: each result id is current at most once": c5,
"CONTROL valid approval: exactly one refund of 25 for A-200": control,
}
K = list(CASES)
BASE = {1: [("instruction", {"order": "A-100"})], 3: [("instruction", {"order": "A-200"})],
4: [("approval_granted", {"order": "A-200"})], 5: [("tool_result", {"call_id": "c1"})]}
SCENARIOS = [
Scenario("A", {**BASE, 6: [("approval_revoked", {"order": "A-200"})]},
{2: ["quote"], 4: ["notify"], 5: ["record"], 7: ["refund"]}, [K[0], K[1], K[2]]),
Scenario("B", {**BASE, 6: [("tool_result", {"call_id": "c1"})]},
{2: ["quote"], 4: ["notify"], 5: ["record"], 7: ["refund"], 8: ["refund"]}, [K[5], K[3], K[4]],
lose_first_refund_response=True),
Scenario("C", dict(BASE), {2: ["quote"], 4: ["notify"], 5: ["record"], 7: ["refund"], 8: ["refund"]}, [K[2]],
mid_act={7: [("approval_revoked", {"order": "A-200"})]}),
]
MODES = ["naive", "versioned", "versioned+dest"]
def span_rule(spans):
"""Local rule over exported spans only: acted on the latest valid state. Not an Observe eval."""
for s in spans:
a = s.attributes
if s.name == "agent.step" and a.get("agent.action") in ACTING:
if a["agent.order"] != a["agent.instruction_order"] or a["agent.stale_inputs"] > 0:
return False
if a["agent.action"] == "refund_executed" and not a["agent.approval_live"]:
return False
return True
def run_case(scn, mode, tracer, exp):
scn = Scenario(**{**scn.__dict__, "mid_act": {k: list(v) for k, v in scn.mid_act.items()}})
w = World(scn, enforce=mode == "versioned+dest")
run = f"{scn.name}-{mode}"
agent = (Naive if mode == "naive" else Versioned)(w, run)
log = []
def meta(seq):
return {"mode": mode, "tick": w.clock.tick, "event_seq": seq, "state_version": w.version}
def deliver(it):
with using_metadata({**meta(it.seq), "event_kind": it.kind, "item_stamp": it.stamp}):
with tracer.start_as_current_span("agent.event") as sp:
decision, reason = agent.on_item(it)
sp.set_attribute("agent.decision", decision)
sp.set_attribute("agent.reason", reason)
log.append(f" t{w.clock.tick} seq={it.seq} {it.kind} v{it.stamp} -> {decision}: {reason}")
with using_session(run):
for tick in range(1, max(scn.steps) + 1):
w.clock.tick = tick
for ev in scn.events.get(tick, []):
deliver(w.apply(ev))
for name in scn.steps.get(tick, []):
with using_metadata({**meta(w.seq), "event_kind": "step_" + name}):
with tracer.start_as_current_span("agent.step") as sp:
decision, reason, rec = getattr(agent, "step_" + name)()
sp.set_attribute("agent.decision", decision)
sp.set_attribute("agent.reason", reason)
sp.set_attribute("agent.action", rec["name"] if rec else "none")
if rec:
sp.set_attribute("agent.order", rec["order"])
sp.set_attribute("agent.instruction_order", rec["instruction_order"])
sp.set_attribute("agent.stale_inputs", len(rec["stale_inputs"]))
sp.set_attribute("agent.approval_checked", rec["approval_checked"])
if "approval_live" in rec:
sp.set_attribute("agent.approval_live", rec["approval_live"])
log.append(f" t{tick} step {name} -> {decision}: {reason}")
for it in w.deferred:
deliver(it)
w.deferred.clear()
spans = list(exp.get_finished_spans())
exp.clear()
return w, agent, spans, log
def main():
exp = InMemorySpanExporter()
provider = register(project_name="event-replay-fixture", batch=False, span_exporter=exp, verbose=False)
tracer = FITracer(provider.get_tracer(__name__)) # plain get_tracer spans are NOT stamped by using_*
print("SYNTHETIC FIXTURE: invented orders, quotes and events; no LLM, no network, no wall clock.")
print(f"python {platform.python_version()} | fi-instrumentation-otel {md.version('fi-instrumentation-otel')} | "
f"opentelemetry-sdk {md.version('opentelemetry-sdk')}")
print("traceAI source for the stamping behavior: future-agi/traceAI 3c00a1dc43b155c00bd2865ade38a9b2fe8c8adf, python/fi_instrumentation/instrumentation/_tracers.py line 246")
assert stale_action("read") == "rerun" and stale_action("write") == "drop"
results, trace_dump = {}, None
for scn in SCENARIOS:
for mode in MODES:
w, agent, spans, log = run_case(scn, mode, tracer, exp)
print(f"\n== scenario {scn.name} | mode {mode} ==")
print("\n".join(log))
print(f" refund ledger: {w.entries}")
for s in spans: # every span must carry the run and the state version
m = json.loads(s.attributes["metadata"])
assert s.attributes["session.id"] == f"{scn.name}-{mode}" and "state_version" in m and "event_seq" in m
assert span_rule(spans) == (c1(w, agent) and c2(w, agent) and c3(w, agent)), "span rule disagrees with the action log"
for case in scn.cases:
results[(scn.name, mode, case)] = CASES[case](w, agent)
if (scn.name, mode) == ("A", "versioned"):
trace_dump = spans
print("\n== spans exported for run A-versioned (what a reviewer reads) ==")
for s in trace_dump:
a = s.attributes
print(f" {s.name} | session {a['session.id']} | metadata {a['metadata']} | decision {a['agent.decision']} | {a['agent.reason']}")
if a.get("agent.action", "").startswith("refund"):
print(f" refund span: action={a['agent.action']} approval_checked={a['agent.approval_checked']} approval_live={a['agent.approval_live']}")
print("\n== results (PASS means the property held) ==")
for (sc, mode, case), ok in results.items():
print(f" scenario {sc} | {mode:<14} | {'PASS' if ok else 'FAIL'} | {case}")
# naive fails everything; re-check alone leaves the revoke-during-the-call window (scenario C) open
expected_fail = {k for k in results if k[1] == "naive"} | {("C", "versioned", K[2])}
wrong = [k for k, ok in results.items() if ok == (k in expected_fail)]
print("\nmatrix matches expectation" if not wrong else f"\nMATRIX MISMATCH: {wrong}")
print("scenario C versioned FAIL is expected: the revoke landed after the agent's re-check and before the write;")
print("only the versioned+dest column, where the refund service checks approval itself, closes that window.")
print("\nnot executed: sending spans to Future AGI (needs a Future AGI API key and an Observe project; spans stay in an in-memory exporter)")
print("not executed: an Observe custom eval for 'acted on the latest valid state' (needs a Future AGI account; the span rule above reads the same stamped attributes locally and is not that eval)")
print("not executed: Evaluator.evaluate from agent-learning-kit 0.3.7 (needs FI_API_KEY and FI_SECRET_KEY; no eval SDK code is shipped in this folder)")
sys.exit(1 if wrong else 0)
if __name__ == "__main__":
main()
The scripted event stream
BASE holds the events every scenario shares: the A-100 instruction at t1, the switch to A-200 at t3, the grant at t4 and the c1 result at t5. Each scenario adds its own events and a steps dict that says which agent step runs on which tick: quote, notify, record or refund.
The mid_act hook lands events during a call. In scenario C it holds the revoke for tick 7, and the refund service applies it inside the call, after the agent’s check ran. To add a case, put a new event on a new tick and write one property for it. The versioned run of scenario A printed:
== scenario A | mode versioned ==
t1 seq=1 instruction v1 -> record: instruction now A-100 at v1
t2 step quote -> quote: issued c1 for A-100 under v1
t3 seq=2 instruction v2 -> supersede: instruction now A-200 at v2, replaced the A-100 instruction (v1) instead of appending
t4 seq=3 approval_granted v3 -> record: approval_granted for A-200 at v3, approval is read live at the act, not from here
t4 step notify -> notify: told the customer about A-200 (active instruction)
t5 seq=4 tool_result v1 -> rerun: c1 issued at t2 under v1, arrived t5 after the instruction changed at v2; re-ran the read-only quote for A-200 as seq 5
t5 step record -> update_ticket: wrote amount 25 from c1-rerun
t6 seq=6 approval_revoked v4 -> record: approval_revoked for A-200 at v4, approval is read live at the act, not from here
t7 step refund -> blocked: approval for A-200 not in force at the act, no call made
refund ledger: []
Append-only versus versioned results
Every append-only row printed FAIL, and every versioned row printed PASS except scenario C’s C3. The append-only agent refunded 40 for A-100 in A and C and twice in B. The table holds the results as printed on 2026-11-19. The fixture is synthetic, so the numbers are illustrative, not measured customer results.
| Scenario | Case | Append-only | Versioned | Versioned plus destination check |
|---|---|---|---|---|
| A | C1 new instruction mid-task | FAIL | PASS | PASS |
| A | C2 late result | FAIL | PASS | PASS |
| A | C3 approval revoked | FAIL | PASS | PASS |
| B | CONTROL valid approval gives exactly one refund of 25 for A-200 | FAIL | PASS | PASS |
| B | C4 retry gives at most one refund per order | FAIL | PASS | PASS |
| B | C5 duplicate delivery | FAIL | PASS | PASS |
| C | C3 approval revoked during the call | FAIL | FAIL | PASS |
The versioned agent refunded nothing in A and 25 for A-200 once each in B and C. The script printed “matrix matches expectation” and exits non-zero on any mismatch. It also asserts that every span carries session.id, state_version and event_seq.
The revoke that lands during the refund call
The script explains its one versioned FAIL: “scenario C versioned FAIL is expected: the revoke landed after the agent’s re-check and before the write;” and “only the versioned+dest column, where the refund service checks approval itself, closes that window.” The gap sits between the check and the write.
Real write APIs close that window in a few ways: a conditional write that fails when the approval record changed, a version check on the approval row inside the same transaction, or a short lease on the approval that the write must present. Each one puts the check and the write in a single step.
Per-event log fields that let a reviewer rebuild the run
For a production adapter, log one record per event and one per action. Event records carry the run ID, sequence number, state version, item stamp, decision and reason. Side-effecting action records should also include whether approval was read live, what that read returned and the idempotency key sent.
- Event records: run or session ID, tick, event_seq, state_version, event_kind, item_stamp, decision, reason.
- Action records should also include: order, instruction_order, stale_inputs count, approval_checked, approval_live, idempotency key.
The fixture omits the idempotency key from its telemetry and records approval_live at the destination, not at the agent’s earlier check.
Take the t5 event span from the A-versioned run below. Its metadata reads state_version 3 and item_stamp 1, and its decision attribute reads rerun. A reviewer can see from the metadata and reason text that the result was stamped v1 after the instruction moved to v2, and that the agent re-ran it instead of using it.
== spans exported for run A-versioned (what a reviewer reads) ==
agent.event | session A-versioned | metadata {"mode": "versioned", "tick": 1, "event_seq": 1, "state_version": 1, "event_kind": "instruction", "item_stamp": 1} | decision record | instruction now A-100 at v1
agent.step | session A-versioned | metadata {"mode": "versioned", "tick": 2, "event_seq": 1, "state_version": 1, "event_kind": "step_quote"} | decision quote | issued c1 for A-100 under v1
agent.event | session A-versioned | metadata {"mode": "versioned", "tick": 3, "event_seq": 2, "state_version": 2, "event_kind": "instruction", "item_stamp": 2} | decision supersede | instruction now A-200 at v2, replaced the A-100 instruction (v1) instead of appending
agent.event | session A-versioned | metadata {"mode": "versioned", "tick": 4, "event_seq": 3, "state_version": 3, "event_kind": "approval_granted", "item_stamp": 3} | decision record | approval_granted for A-200 at v3, approval is read live at the act, not from here
agent.step | session A-versioned | metadata {"mode": "versioned", "tick": 4, "event_seq": 3, "state_version": 3, "event_kind": "step_notify"} | decision notify | told the customer about A-200 (active instruction)
agent.event | session A-versioned | metadata {"mode": "versioned", "tick": 5, "event_seq": 4, "state_version": 3, "event_kind": "tool_result", "item_stamp": 1} | decision rerun | c1 issued at t2 under v1, arrived t5 after the instruction changed at v2; re-ran the read-only quote for A-200 as seq 5
agent.step | session A-versioned | metadata {"mode": "versioned", "tick": 5, "event_seq": 5, "state_version": 3, "event_kind": "step_record"} | decision update_ticket | wrote amount 25 from c1-rerun
agent.event | session A-versioned | metadata {"mode": "versioned", "tick": 6, "event_seq": 6, "state_version": 4, "event_kind": "approval_revoked", "item_stamp": 4} | decision record | approval_revoked for A-200 at v4, approval is read live at the act, not from here
agent.step | session A-versioned | metadata {"mode": "versioned", "tick": 7, "event_seq": 6, "state_version": 4, "event_kind": "step_refund"} | decision blocked | approval for A-200 not in force at the act, no call made
refund span: action=refund_blocked approval_checked=True approval_live=False
To answer “why did it refund?”, read the action spans of a session and check approval_checked and approval_live on each refund step. In A-versioned the refund span reads action refund_blocked, approval_checked True and approval_live False, which explains why no money moved after the revoke.
The script’s span_rule reads only these span attributes, and the script asserts that its verdict matches the action log for every run. Keep these records to explain why one run acted as it did, not as a test suite mined from production traces.
Stamping events and scoring agent actions with Future AGI traceAI and Observe
Future AGI’s traceAI, built on OpenTelemetry, stamps those log fields onto spans through context managers. Wrap your tracer with FITracer, open using_session for the run and using_metadata for each event, and every span carries the session ID plus the sequence number and state version. Future AGI Observe can then score every action span in those sessions.
The setup in event_replay.py takes two lines. register(project_name="event-replay-fixture", batch=False, span_exporter=exp, verbose=False) returns a tracer provider without setting the global one, and FITracer(provider.get_tracer(__name__)) wraps its tracer. The source is in traceAI on GitHub.
Wrap the tracer before the context managers apply
The FITracer and custom spans page shows the pattern: get a tracer from the provider, then wrap it with FITracer. Spans started through FITracer, or through a traceAI instrumentor, pick up the session and metadata attributes, so the script wraps its tracer before the first event.
The traceAI context managers for session and metadata do the stamping. using_session(run) sets session.id for the whole run, and using_metadata sets one JSON-serialized metadata attribute per block. An inner block’s dict takes the place of the outer one.
So build one dict per event that already holds every field, as the script’s meta() helper does. Attributes apply when a span starts, so open using_session before the run’s first span. Values known only after a step, such as agent.decision and the approval fields, go onto the span with set_attribute.
A span eval for acting on the latest valid state
To send these spans to Future AGI, add an API key and an Observe project. In this run they stayed in the in-memory exporter, so the steps follow the docs. To set up evals in Observe, create a task at the Spans level, so each agent step is scored alone.
Map the eval’s variables to span attribute keys such as agent.order and agent.stale_inputs, and use dot notation inside the metadata JSON, such as metadata.state_version. Then save one of your custom evals as a Code Eval with Pass/fail output.
The rule passes a span that took no action. An action span passes when its order equals instruction_order and stale_inputs is 0, and an executed refund also needs approval_live true. session.id groups each run’s traces into one session, so a reviewer opens a failing run whole. The script’s span_rule is the local version of this logic.
A refund agent that follows the latest instruction and approval
Back on the refund ticket, the versioned agent supersedes A-100 when the customer switches to A-200. It re-runs the late quote for the new order and blocks the refund once the supervisor revokes approval, so the order the customer abandoned never gets a refund.
Read the versioned run line by line and the ticket resolves. At t3 it superseded the A-100 instruction, at t4 it told the customer about A-200, and at t5 it re-ran the stale quote and wrote 25. At t7 it found no approval in force and made no call, so nothing was refunded.
When the approval stays in force, as in scenario B, the same agent refunded 25 for A-200 exactly once, even after a lost response forced a retry. The money moves only on the order the customer asked about, and only while a supervisor’s approval holds.
Start with one side-effecting tool in your own agent. Write its three events as a scripted stream on a counter clock, add version stamps and a live approval read, and run both modes until every case passes. Then stamp the same fields on your spans and score the sessions where real events arrive.
Frequently Asked Questions
What are long-running AI agents?
How to build long running agents?
What are async agents?
What is the long running agent problem?
How do long running agents in Claude and OpenAI handle new messages?
Install the A2A Inspector from its Go release, validate agent cards, and debug A2A tasks that stall, stream with no final event, or fail behind an HTTP 200.
Track AI agent token usage per LLM call, then roll it up by step, tool call and run with OpenTelemetry attributes, a dated price table and per-run budgets.
Claude API logging with OpenTelemetry: fields to keep per Messages call, native export vs SDK spans, Agent SDK tracing, cost from usage and prompt redaction.