A person approved one payment. The worker charged the card, then crashed before it saved anything. A new worker picked the run back up, and the customer was charged twice. This guide shows why the OpenAI Agents SDK does this and gives you a fix you can paste in, so one approval means one charge even when a worker dies at the worst moment. Everything below was run on openai-agents 0.24.0 and 0.23.1 (Python 3.13.5), Oct 29, 2026.
Why the approved tool runs again
The SDK pauses a needs_approval tool and hands you a RunState to save. Your app saves it, the person approves, and a worker runs it. The saved state only changes when your app saves it again, so there is a gap between "the tool did its job" and "the app wrote that down".
- The person approves. Your worker saves the approved state and calls
Runner.run(agent, state). - The tool charges the card. Then the worker dies (a deploy, an out-of-memory kill, a lost container) before it saves the new state.
- A new worker loads the last saved snapshot. It still says "approved, not run yet", so the tool runs again with the same arguments. Two charges.
This was reported as issue #5409 on Oct 22, 2026 (2 payments in 3 of 3 runs on 0.24.0). It was closed on Oct 26 by a docs change, PR #5424, with no change to how the SDK runs. The human-in-the-loop docs now say: "Approval permits a tool call to execute; it does not guarantee exactly-once execution." So the fix lives in your tool, not in an upgrade.
A crash isn't the only way this happens. A double-clicked approve button or a retried webhook can resume the same saved state twice too; that case is covered in duplicate tool calls after resume.
Reproduce it, then fix it
No model calls and no network. ScriptedModel plays the LLM. A SQLite file plays your database and a payment provider, so both survive the crash. The worker is killed with os._exit(137) right after the charge, and a fresh process resumes the run.
# scripted.py: offline stand-in for the OpenAI model. Everything else is real SDK code.
import json
from agents import Model, ModelResponse, Usage
from openai.types.responses import ResponseFunctionToolCall, ResponseOutputMessage, ResponseOutputText
class ScriptedModel(Model):
"""Turn 1: ask for one tool call. Once the tool output is in the input: reply with text."""
def __init__(self, name, args):
self.name, self.args = name, args
async def get_response(self, system_instructions, input, *a, **kw):
items = input if isinstance(input, list) else []
outs = [i for i in items if isinstance(i, dict) and i.get("type") == "function_call_output"]
if not outs:
out = [ResponseFunctionToolCall(type="function_call", id="fc_1", call_id="call_1",
name=self.name, arguments=json.dumps(self.args))]
else:
out = [ResponseOutputMessage(type="message", id="msg_1", role="assistant", status="completed",
content=[ResponseOutputText(type="output_text", text=str(outs[-1]["output"]), annotations=[])])]
return ModelResponse(output=out, usage=Usage(), response_id=None)
def stream_response(self, *a, **kw):
raise NotImplementedError
# crash_demo.py (pip install openai-agents==0.24.0)
# python crash_demo.py start|approve|resume with TOOL=naive|keyed|ledger and CRASH=1 to kill the worker
import asyncio, os, sqlite3, sys
from agents import Agent, Runner, RunConfig, RunState, function_tool
from agents.tool_context import ToolContext
from scripted import ScriptedModel
db = sqlite3.connect("demo.db", isolation_level=None, check_same_thread=False) # survives the crash, like your real DB
db.executescript("""
CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY, state TEXT);
CREATE TABLE IF NOT EXISTS provider(id INTEGER PRIMARY KEY, amount INT, idem_key TEXT UNIQUE);
CREATE TABLE IF NOT EXISTS ledger(key TEXT PRIMARY KEY, status TEXT, result TEXT);
""")
def provider_charge(amount, idempotency_key=None):
"""Stands in for a payment API. With a key it returns the first charge instead of charging again."""
if idempotency_key:
row = db.execute("SELECT id FROM provider WHERE idem_key=?", (idempotency_key,)).fetchone()
if row:
return f"ch_{row[0]}"
cur = db.execute("INSERT INTO provider(amount, idem_key) VALUES (?, ?)", (amount, idempotency_key))
return f"ch_{cur.lastrowid}"
def maybe_crash():
if os.environ.get("CRASH") == "1":
os._exit(137) # the worker dies after the charge, before the new run state is saved
@function_tool(needs_approval=True)
def pay_naive(amount: int) -> str:
"""Charge the customer."""
cid = provider_charge(amount); maybe_crash(); return cid
@function_tool(needs_approval=True)
def pay_keyed(ctx: ToolContext, amount: int) -> str:
"""Charge the customer."""
key = f"{ctx.context['run_id']}:{ctx.tool_call_id}"
cid = provider_charge(amount, idempotency_key=key); maybe_crash(); return cid
@function_tool(needs_approval=True)
def pay_ledger(ctx: ToolContext, amount: int) -> str:
"""Charge the customer (provider has no idempotency keys)."""
key = f"{ctx.context['run_id']}:{ctx.tool_call_id}"
if db.execute("INSERT OR IGNORE INTO ledger VALUES (?, 'started', NULL)", (key,)).rowcount == 0:
status, result = db.execute("SELECT status, result FROM ledger WHERE key=?", (key,)).fetchone()
if status == "done":
return result
return "UNKNOWN: an earlier attempt may have charged. Check the provider before retrying."
cid = provider_charge(amount); maybe_crash()
db.execute("UPDATE ledger SET status='done', result=? WHERE key=?", (cid, key))
return cid
TOOLS = {"naive": pay_naive, "keyed": pay_keyed, "ledger": pay_ledger}
tool = TOOLS[os.environ.get("TOOL", "naive")]
agent = Agent(name="Billing", instructions="bill", tools=[tool],
model=ScriptedModel(tool.name, {"amount": 79}))
cfg = RunConfig(tracing_disabled=True)
save = lambda s: db.execute("REPLACE INTO runs VALUES ('run_42', ?)", (s.to_string(),))
load = lambda: RunState.from_string(agent, db.execute("SELECT state FROM runs").fetchone()[0])
async def main(step):
if step == "start": # the agent asks to pay and stops for approval
r = await Runner.run(agent, "pay 79", context={"run_id": "run_42"}, run_config=cfg)
print("interruptions:", [i.raw_item.call_id for i in r.interruptions]); save(r.to_state())
elif step == "approve": # a person approves; the worker saves the approved state, then runs it
state = await load()
for item in state.get_interruptions():
state.approve(item)
save(state)
r = await Runner.run(agent, state, run_config=cfg)
save(r.to_state()); print("final:", r.final_output)
elif step == "resume": # a new worker picks up the run after the crash
r = await Runner.run(agent, await load(), run_config=cfg)
save(r.to_state()); print("final:", r.final_output)
print("charges at provider:", db.execute("SELECT count(*) FROM provider").fetchone()[0])
asyncio.run(main(sys.argv[1]))
Run the three steps for each tool. The approve step dies with exit code 137, and a new process runs resume:
for t in naive keyed ledger; do
rm -f demo.db; echo "== $t"
TOOL=$t python crash_demo.py start
TOOL=$t CRASH=1 python crash_demo.py approve; echo "approve exit code: $?" # killed after the charge
TOOL=$t python crash_demo.py resume # a new worker picks it up
done
Actual output on 0.24.0:
== naive
interruptions: ['call_1']
charges at provider: 0
approve exit code: 137
final: ch_2
charges at provider: 2
== keyed
interruptions: ['call_1']
charges at provider: 0
approve exit code: 137
final: ch_1
charges at provider: 1
== ledger
interruptions: ['call_1']
charges at provider: 0
approve exit code: 137
final: UNKNOWN: an earlier attempt may have charged. Check the provider before retrying.
charges at provider: 1
The naive tool charged twice for one approval. The keyed tool's resume got the first charge ch_1 back from the provider. The ledger tool's resume saw a started row and stopped without charging.
We ran each case 20 times on each version, each run in fresh processes with a fresh database:
| Tool | Worker killed after the charge | No kill (control) |
|---|---|---|
pay_naive |
2 charges in 20 of 20 runs | 1 charge in 20 of 20 |
pay_keyed |
1 charge in 20 of 20 | 1 charge in 20 of 20 |
pay_ledger |
1 charge in 20 of 20 | 1 charge in 20 of 20 |
openai-agents 0.24.0 and 0.23.1 gave identical results. The key was run_42:call_1 when the first worker charged, and the new worker built the same key after it loaded the saved state, because the tool call id is stored in the snapshot. That is what makes it a safe key.
The fix in 3 steps
- Send an idempotency key with every side effect. Build it from your own run id plus
ctx.tool_call_id(put the run id in the run context; a dict context is saved with the state). Pass it to a provider that rejects repeats, such as Stripe'sIdempotency-Key. Stripe keys can be up to 255 characters. On Stripe's v1 API a key may be removed once it is 24 hours old, and the same key then makes a new request (Stripe idempotent requests). So if a run can be resumed a day later, keep your own record too. - If the provider has no keys, write down that you started. Insert the key as a
startedrow with a UNIQUE constraint before you act, and mark itdoneafter. On resume, astartedrow that isn'tdonemeans you don't know whether the action happened. Don't retry it automatically. Check the provider in a way you trust, or ask a person. The docs warn that "a missing result in an ordinary lookup is not proof that retrying is safe: reads can lag, and an earlier request can still complete." - Save the state as soon as the run returns. Call
result.to_state()and store it before you send emails, update the UI or tell the user it worked. That makes the gap smaller. It can't close it, which is why steps 1 and 2 matter.
FAQ
Does upgrading the SDK fix it? No. 0.24.0 and 0.23.1 behaved the same, and the issue was closed with a docs change, not a code change. The docs say an approval "does not guarantee exactly-once execution".
Is the tool call id the same after a reload?
Yes. In our runs the key was run_42:call_1 before the crash and again after RunState.from_string in a new process. It comes from the saved model output, so every resume of that snapshot sees the same id.
Doesn't marking the approval as used solve it? It stops a double click or a retried webhook from resuming the same run twice. It can't tell you whether the charge went through before the crash. Either the new worker refuses to resume and the run is stuck, or it resumes and charges again. The docs put it this way: "An approval decision or a local completion flag alone cannot make the external action and the saved run state one atomic operation."
What if my provider has no idempotency keys?
Use the started row from step 2. A crash then leaves a row that says "started, not done", and the resume stops as unknown instead of charging again. Someone still has to check the provider and finish or cancel by hand.
What we did not test
No real OpenAI model, payment provider or production database. We tested the Python SDK with a non-streamed Runner.run, a dict context and to_string() / from_string(). We did not test Runner.run_streamed, Sessions, server-managed conversations, the TypeScript SDK, or a crash in the middle of saving the state.
Get the template
- Free: Side-effect ledger, a Postgres table and Python helper that runs each tool effect once per key, with an OpenAI Agents
needs_approvalexample. A call that crashed is held while its lease is active and runs again after the lease ends, so pass the same key to the provider too. - Pro: Idempotent approved side effects (OpenAI Agents SDK), covering a duplicate resume and a whole-run retry after a crash, in Signal Pro ($7/month or $69/year).
- Done for you: the $79 Agent Approval-Flow Fix. Send a minimal repro. You pay $79 only when our patch passes it.
Check your own agent in 2 minutes
Want to see a repeated side effect happen, then stop? Run the free 2-minute crash test. It kills an agent right after an approved charge, resumes it, and counts how many times the charge runs. Today it runs on LangGraph, and the OpenAI Agents SDK version is in beta, but the fix is the same idea: one key per tool call.