claude-agent-sdk-python icon indicating copy to clipboard operation
claude-agent-sdk-python copied to clipboard

Deferred tool approved on resume runs again when the process dies after the tool ran and before its result is saved

Open salahmakboul opened this issue 2 weeks ago • 3 comments

A tool call that was deferred with a PreToolUse hook ("defer") and approved on resume runs again if the process dies after the tool ran but before its result is saved. A second resume re-fires the hook for the same call and the tool runs a second time. I would like to know whether that is intended (at-least-once), and if so whether the docs could say so.

What I measured

Python SDK 0.2.182, bundled Claude Code 2.1.325, Windows 11. No API key and no real model: a local stub plays the Anthropic API (first reply is one tool_use of an in-process SDK MCP tool pay, any reply after a tool_result is "Done."). pay appends one line to a file, so payments are counted by lines.

  1. Run 1: prompt "Pay alice 10". PreToolUse returns defer. Result: stop_reason: tool_deferred, nothing paid.
  2. Run 2 (new process): resume=<session id>, PreToolUse returns allow. pay writes its line, then the whole process tree is killed before the tool returns.
  3. Run 3 (new process): resume again, allow.
payments after run 3
killed after the payment (steps 1 to 3) 2 in 5 of 5 runs
control: not killed (run 2 finishes) 1 in 5 of 5 runs

In the control, a resume after the turn finished does not run the tool again, so the repeat comes from the crash, not from resuming.

Why I think it happens

After the kill the session holds the tool_use but no tool_result, so the next resume sees the same pending call and fires PreToolUse again. That matches the docs: "The same tool call fires PreToolUse again" (hooks, defer a tool call). I did not find anything in the hooks, SDK hooks or sessions pages about a stop between running the tool and saving its result, or about making deferred tools idempotent.

Question and two ideas

  • Is at-least-once intended here? If yes, one sentence in the defer section would help people who defer payments, emails or writes.
  • If a host wants to avoid the repeat today, it can key the side effect on tool_use_id, which the hook receives. I have not tested that against the SDK.
  • A record written before the tool starts (for deferred approvals) would let a later resume tell "approved, never started" from "started, outcome unknown" and stop instead of running it blindly. This is only an idea.

Limits

A stub model, Windows only (the kill step uses taskkill /T; on Linux or macOS kill the process group), one tool, and an in-process tool, so the side effect runs in the host process. I have not tried a Bash call or an external MCP server. This is not the same as #474 in the TypeScript repo (parallel deferred calls).

(I maintain Call4Agents, a library for this problem; this report does not depend on it.)

Script (needs pip install claude-agent-sdk; run python defer_crash.py 1)
"""Claude Agent SDK (Python): a deferred tool approved on resume, a crash right after it runs, a second resume.

No API key and no real model: a local stub Anthropic-compatible server plays the model
(first reply = one tool_use of mcp__shop__pay; any reply after a tool_result = "Done.").
The tool is an in-process SDK MCP tool that appends one line per call to a payments file.

Phases (each a separate process, as a host that restarts would be):
  1. prompt "Pay alice 10"; PreToolUse returns "defer"   -> result tool_deferred, nothing paid
  2. resume; PreToolUse returns "allow"; the tool pays, then (CRASH=1) the process dies
     with os._exit before the tool returns, so no tool_result can be recorded
  3. resume again; PreToolUse returns "allow"            -> does the tool run again?
Control: the same, without the crash in phase 2.

Usage: python defer_crash.py [runs]
"""
import asyncio
import json
import os
import subprocess
import sys
import tempfile
import threading
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

TOOL = "mcp__shop__pay"


# ---------------- stub model ----------------
class Stub(BaseHTTPRequestHandler):
    log = None

    def log_message(self, *a):
        pass

    def _json(self, obj, code=200):
        b = json.dumps(obj).encode()
        self.send_response(code)
        self.send_header("content-type", "application/json")
        self.send_header("content-length", str(len(b)))
        self.end_headers()
        self.wfile.write(b)

    def do_GET(self):
        self._json({"data": []})

    def do_HEAD(self):
        self.send_response(200)
        self.end_headers()

    def do_POST(self):
        body = self.rfile.read(int(self.headers.get("content-length", 0) or 0)).decode("utf-8", "replace")
        if "/v1/messages" not in self.path or "count_tokens" in self.path:
            return self._json({"input_tokens": 1} if "count_tokens" in self.path else {})
        req = json.loads(body or "{}")
        tool_names = [t.get("name") for t in req.get("tools", []) or []]
        has_result = '"tool_result"' in body
        want_tool = TOOL in tool_names and not has_result
        if Stub.log:
            with open(Stub.log, "a") as f:
                f.write(json.dumps({"tools": tool_names, "path": self.path, "want_tool": want_tool, "has_result": has_result,
                                    "stream": req.get("stream")}) + "\n")
        if want_tool:
            blocks = [{"type": "tool_use", "id": "toolu_pay_1", "name": TOOL,
                       "input": {"to": "alice", "amount": 10}}]
            stop = "tool_use"
        else:
            blocks = [{"type": "text", "text": "Done."}]
            stop = "end_turn"
        msg = {"id": "msg_" + uuid.uuid4().hex, "type": "message", "role": "assistant",
               "model": req.get("model", "claude-sonnet-5"), "content": [], "stop_reason": None,
               "stop_sequence": None, "usage": {"input_tokens": 1, "output_tokens": 0}}
        if not req.get("stream"):
            msg.update(content=blocks, stop_reason=stop)
            return self._json(msg)
        self.send_response(200)
        self.send_header("content-type", "text/event-stream")
        self.end_headers()

        def sse(t, d):
            self.wfile.write(f"event: {t}\ndata: {json.dumps(d)}\n\n".encode())

        sse("message_start", {"type": "message_start", "message": msg})
        for i, b in enumerate(blocks):
            if b["type"] == "tool_use":
                sse("content_block_start", {"type": "content_block_start", "index": i,
                                            "content_block": {**b, "input": {}}})
                sse("content_block_delta", {"type": "content_block_delta", "index": i,
                                            "delta": {"type": "input_json_delta",
                                                      "partial_json": json.dumps(b["input"])}})
            else:
                sse("content_block_start", {"type": "content_block_start", "index": i,
                                            "content_block": {"type": "text", "text": ""}})
                sse("content_block_delta", {"type": "content_block_delta", "index": i,
                                            "delta": {"type": "text_delta", "text": b["text"]}})
            sse("content_block_stop", {"type": "content_block_stop", "index": i})
        sse("message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": None},
                              "usage": {"output_tokens": 1}})
        sse("message_stop", {"type": "message_stop"})


# ---------------- one phase (child process) ----------------
async def phase(decision, resume, prompt):
    from claude_agent_sdk import (ClaudeAgentOptions, HookMatcher, create_sdk_mcp_server, query,
                                  tool, AssistantMessage, ResultMessage, ToolUseBlock)

    payments = os.environ["PAYMENTS"]

    @tool("pay", "Pay someone", {"to": str, "amount": int})
    async def pay(args):
        with open(payments, "a") as f:
            f.write(f"pay {args['amount']} to {args['to']}\n")
            f.flush()
            os.fsync(f.fileno())
        if os.environ.get("CRASH") == "1":
            # the host dies after the payment, before the tool returns: kill the whole process
            # tree (this Python process and the claude CLI it started), as a machine or container crash would
            subprocess.run(["taskkill", "/F", "/T", "/PID", str(os.getpid())], capture_output=True)
            os._exit(17)
        return {"content": [{"type": "text", "text": "paid"}]}

    events = []

    async def hook(inp, tool_use_id, ctx):
        events.append(f"PreToolUse:{tool_use_id}->{decision}")
        return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": decision}}

    stop = asyncio.Event()

    async def input_stream():
        if prompt:
            yield {"type": "user", "message": {"role": "user", "content": prompt}, "parent_tool_use_id": None}
        await stop.wait()

    opts = ClaudeAgentOptions(
        cwd=os.environ["WORK"], model="claude-sonnet-5", permission_mode="default", setting_sources=[],
        mcp_servers={"shop": create_sdk_mcp_server("shop", tools=[pay])},
        allowed_tools=[TOOL],
        hooks={"PreToolUse": [HookMatcher(matcher=None, hooks=[hook])]},
        resume=resume, env={k: os.environ[k] for k in ("CLAUDE_CONFIG_DIR", "ANTHROPIC_BASE_URL",
                                                         "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN",
                                                         "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC")},
    )
    result = None
    async for m in query(prompt=input_stream(), options=opts):
        if isinstance(m, AssistantMessage):
            for b in m.content:
                if isinstance(b, ToolUseBlock):
                    events.append(f"tool_use:{b.id}")
        if isinstance(m, ResultMessage):
            result = m
            break
    stop.set()
    out = {"events": events, "stop_reason": result.stop_reason if result else None,
           "deferred": result.deferred_tool_use.id if result and result.deferred_tool_use else None,
           "session_id": result.session_id if result else None}
    print("RESULT " + json.dumps(out), flush=True)


def child():
    decision, resume, prompt = sys.argv[2], sys.argv[3] or None, sys.argv[4] or None
    asyncio.run(phase(decision, resume, prompt))
    os._exit(0)


# ---------------- driver ----------------
def run_phase(env, decision, resume="", prompt="", crash=False):
    e = dict(env, CRASH="1" if crash else "0")
    out_path, err_path = tempfile.mktemp(), tempfile.mktemp()
    with open(out_path, "w") as o, open(err_path, "w") as er:
        p = subprocess.Popen([sys.executable, __file__, "child", decision, resume, prompt], env=e,
                             stdout=o, stderr=er)
        try:
            rc = p.wait(timeout=180)
        except subprocess.TimeoutExpired:
            subprocess.run(["taskkill", "/F", "/T", "/PID", str(p.pid)], capture_output=True)
            rc = "timeout"
    out, err = open(out_path).read(), open(err_path).read()
    line = next((l for l in out.splitlines() if l.startswith("RESULT ")), None)
    return rc, (json.loads(line[7:]) if line else None), err[-600:]


def one(crash):
    srv = ThreadingHTTPServer(("127.0.0.1", 0), Stub)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    d = tempfile.mkdtemp(prefix="c4a-sdk-")
    os.makedirs(os.path.join(d, "cfg"))
    os.makedirs(os.path.join(d, "work"))
    Stub.log = os.path.join(d, "stub.log")
    env = dict(os.environ, CLAUDE_CONFIG_DIR=os.path.join(d, "cfg"), WORK=os.path.join(d, "work"),
               PAYMENTS=os.path.join(d, "payments.txt"),
               ANTHROPIC_BASE_URL=f"http://127.0.0.1:{srv.server_port}",
               ANTHROPIC_API_KEY="stub", ANTHROPIC_AUTH_TOKEN="stub",
               CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1", ENABLE_TOOL_SEARCH="false")
    env.pop("PYTHONPATH", None)
    rc1, r1, err1 = run_phase(env, "defer", prompt="Pay alice 10")
    if not r1 or not r1["session_id"]:
        srv.shutdown()
        return {"error": "phase 1", "rc": rc1, "stderr": err1, "r": r1}
    sid = r1["session_id"]
    rc2, r2, err2 = run_phase(env, "allow", resume=sid, crash=crash)
    paid_after_2 = open(env["PAYMENTS"]).read().count("pay") if os.path.exists(env["PAYMENTS"]) else 0
    rc3, r3, err3 = run_phase(env, "allow", resume=sid)
    paid = open(env["PAYMENTS"]).read().count("pay") if os.path.exists(env["PAYMENTS"]) else 0
    srv.shutdown()
    return {"p1": r1, "p2_exit": rc2, "p2": r2, "paid_after_phase2": paid_after_2,
            "p3_exit": rc3, "p3": r3, "payments": paid, "p3_stderr": err3 if not r3 else ""}


if __name__ == "__main__":
    if sys.argv[1:2] == ["child"]:
        child()
    runs = int(sys.argv[1]) if len(sys.argv) > 1 else 1
    for crash in (True, False):
        for i in range(runs):
            r = one(crash)
            print(("CRASH " if crash else "CONTROL ") + json.dumps(r), flush=True)

salahmakboul avatar Nov 17 '26 22:11 salahmakboul

I reproduced this on Windows and Linux with a modified version of your script.

Setup

  • Windows 11, SDK 0.2.182, bundled CLI 2.1.325
  • Linux (WSL Ubuntu), SDK 0.2.187, bundled CLI 2.1.330
  • The same stub model, with one change: the stub gives a new random tool_use id on every reply.

Results (5 runs per row, the same on both platforms)

Kill point in run 2 Payments after run 3
In the tool, after the payment 2 (5 of 5)
In a PostToolUse hook 2 (5 of 5)
No kill (control) 1 (5 of 5)

The stub issued one id per test. The hook received that id in all three runs. So the id comes from the transcript and stays the same across resumes.

What the transcript shows

  • Run 1 writes the tool_use, then an attachment of type hook_deferred_tool with the same toolUseID.
  • Run 2 writes nothing about the call when the tool starts.
  • When PostToolUse fires, the jsonl still has no tool_result (80 of 80 hook calls).

A kill anywhere in that window leaves the transcript as it was after run 1. The next resume cannot tell "approved, not started" from "started, outcome unknown".

The repeat is specific to defer. I also killed a call that was not deferred, at the same point. Run 1 returned allow, the tool paid, then the process tree was killed. A resume without a prompt did not run the tool again (2 of 2 runs, Windows). So a normal call is at-most-once here, and a deferred call is at-least-once.

A SessionStore can make the window larger. With the default session_store_flush="batched", the mirror flushes on the result message. I read this in the source and did not test it.

An idempotency key works. The @tool handler does not receive the tool_use_id, but the PreToolUse hook does. On resume, the hook can pass it to the tool through updatedInput. The defer docs already use updatedInput in the allow step.

async def pre_tool_use(input_data, tool_use_id, context):
    if not approved(tool_use_id):
        return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "defer"}}
    return {"hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "permissionDecision": "allow",
        # updatedInput replaces the whole input, so keep the original fields
        "updatedInput": {**input_data["tool_input"], "idempotency_key": tool_use_id},
    }}

@tool("pay", "Pay someone", {"to": str, "amount": int})
async def pay(args):
    key = args["idempotency_key"]
    if ledger.has(key):  # written in the same transaction as the payment
        return {"content": [{"type": "text", "text": "already paid"}]}
    ledger.pay(key, args["to"], args["amount"])
    return {"content": [{"type": "text", "text": "paid"}]}

With this pattern, the tool ran twice in every kill run. The second call found the key and did not pay again. The result was 1 payment in 20 of 20 kill runs (10 per platform) and in 10 of 10 control runs. The key must be saved in the same transaction as the side effect. Otherwise a kill between the two writes still pays twice.

Suggestion

The defer section could say that a deferred call runs at least once, and that tools with side effects should use tool_use_id as an idempotency key.

The hosted docs are not in this repo. In this repo, the DeferredToolUse docstring is a possible place for this note. I have a small change ready that adds it. Do you want a PR for it, or do you prefer to cover this in the hosted docs only?

shaojunying avatar Nov 21 '26 09:11 shaojunying

One addition to the key pattern above. "Same transaction as the side effect" works when the ledger and the effect share a database. With an external payment API they can't, so there is always a window where the charge exists and your row does not. Two things close it: pass the tool_use_id through as the provider's own idempotency key, and write a "started" row before the call. On resume, "started" with no result means look the charge up at the provider before doing anything else.

Also worth a line in the docs: the id only covers a replay of the same call. If the model proposes the payment again in a new turn, it gets a new id, so the key does not help there.

gioherazo avatar Nov 24 '26 03:11 gioherazo

Thanks @gioherazo, both points are right. I added them to the docstring in #1577.

External services. My "same transaction" note holds only when the ledger and the side effect share one database. For an external API, your two steps close the gap: send tool_use_id as the provider's idempotency key, and write a "started" row before the call.

The lookup on resume also covers a second case. A deferred call has no timeout, and the session stays on disk for 30 days by default (hooks docs). Provider keys can expire sooner. For example, Stripe keeps a key for at least 24 hours and can remove it after that. A reused key after removal can run a new request (Stripe docs). So after a long pause, the provider key alone may not stop a second charge.

New turns. Agreed. tool_use_id names one tool call, so it only covers a replay of that call. If the model proposes the payment again in a new turn, the host needs a business key, such as an order or invoice id.

#1577 is a docs-only change to the DeferredToolUse docstring. It does not change behavior.

shaojunying avatar Nov 24 '26 05:11 shaojunying