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

ClaudeSDKClient.interrupt() is ignored silently when called immediately after query()

Open vadhavka-deshaw opened this issue 4 months ago • 2 comments

Bug description: Calling interrupt() immediately (less than roughly 2 seconds) after query() has no observable effect. Claude continues generating a full response as if interrupt() was never called. The issue disappears if there is a slight delay between the two calls, suggesting a race condition.

Steps to reproduce:

import time
from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient
from claude_agent_sdk.types import ResultMessage, StreamEvent

options = ClaudeAgentOptions(
    cli_path="/path/to/claude",
    include_partial_messages=True,
)

ts = lambda: time.strftime("%H:%M:%S")

async with ClaudeSDKClient(options=options) as client:
    await client.query("Write a 300 word essay on machine learning")
    print(f"[{ts()}] query sent")
    await client.interrupt()
    print(f"[{ts()}] interrupt acknowledged")
    t0 = time.monotonic()

    chars_after = 0
    async for msg in client.receive_response():
        if isinstance(msg, StreamEvent):
            d = msg.event.get("delta", {})
            chars_after += len(d.get("text", "") + d.get("thinking", ""))
        elif isinstance(msg, ResultMessage):
            dt = time.monotonic() - t0
            verdict = "BUG" if chars_after else "OK"
            print(
                f"{verdict}: {chars_after} chars in {dt:.1f}s after interrupt (stop_reason={msg.stop_reason})"
            )
            break

The output shows:

[15:20:49] query sent
[15:20:49] interrupt acknowledged
BUG: 2464 chars in 23.6s after interrupt (stop_reason=end_turn)

Even after interrupt() resolves without errors, Claude continues to generate the full response. The stop_reason is end_turn, not a signal indicating early termination. Adding a time.sleep() of a few seconds before the interrupt() call causes the interrupt to work correctly.

vadhavka-deshaw avatar Jul 30 '26 12:07 vadhavka-deshaw

I traced this through the current Python SDK and the bundled CLI protocol. The race is real, but the apparently small SDK fix has an API-semantics tradeoff that I do not want to hide in a PR.

Findings

  • On current main (f8b9ec9, SDK 0.2.128), ClaudeSDKClient.query(str) writes a UUID-less user frame, then interrupt() sends only { "subtype": "interrupt" }.
  • A successful control response means the interrupt request was processed; it does not mean the just-written command was already reachable by the active turn's abort controller.
  • The bundled CLI is 2.1.220. Its protocol supports interrupt_receipt_v1 (still_queued UUIDs) and, since 2.1.219, the opt-in interrupt_cancel_queued_v1 / cancel_queued: true path that covers the queue and first-command pre-dispatch window.
  • A deterministic regression test for the reported query() -> interrupt() ordering fails on main: the user message has no UUID and the interrupt does not cover queued/pre-dispatch work.

I prototyped UUID-stamping SDK user messages plus cancel_queued: true; the focused test passed, as did the full suite (1,291 passed, 5 skipped), ruff, and mypy. However, that must not be submitted as an implicit fix: cancel_queued also cancels every other queued/pending-dispatch main-thread command. That changes existing interrupt() semantics from “interrupt the current turn” to “stop the turn and clear the queue.” The TypeScript SDK 0.3.220 still sends the ordinary interrupt by default and exposes the receipt rather than silently opting into queue cancellation.

Could a maintainer confirm the intended Python API direction?

  1. Add an explicit interrupt(cancel_queued: bool = False) option, stamp user-message UUIDs, and document that callers needing Stop-button semantics should pass True.
  2. Deliberately make Python's no-argument interrupt() stop-and-clear, with the behavioral change documented and tested.
  3. Keep current semantics and add a narrower CLI/protocol primitive that targets the just-submitted command UUID without cancelling unrelated queued work.

Once the direction is confirmed, I can provide the minimal implementation with tests for immediate interrupt, active-turn + queued-follow-up behavior, explicit queue cancellation, preservation of caller-supplied UUIDs, and older-CLI compatibility.

AI assistance disclosure: I used an AI coding assistant during protocol and code analysis. I manually reviewed the Python sources, the published TypeScript SDK 0.3.220 declarations/changelog, the protocol semantics, and all reported test results.

kinKingen avatar Aug 01 '26 06:08 kinKingen

I’m interested in contributing the deterministic regression-test slice for this issue, while avoiding duplication with @kinKingen’s protocol work. I confirmed on current main that the public client writes the user frame and then sends the ordinary interrupt request; an SDK-only mock cannot prove queued/pre-dispatch cancellation without first choosing one of the API semantics above. Once a maintainer selects the intended behavior, I can add focused coverage for immediate query→interrupt, active-turn plus queued follow-up, caller-supplied UUID preservation, and older-CLI compatibility. @kinKingen, please let me know if you already plan to own those tests.

GtechGovind avatar Aug 04 '26 17:08 GtechGovind