Late hook completion after Query.close writes twice to closed transport (0.2.163)

Author: marcialfiorentino-cyberCreated Oct 1, 2026Updated Oct 1, 2026
Labelsbugclaude-code-assisted

Summary

In claude-agent-sdk==0.2.163, a hook that finishes after Query.close() can attempt both a success response and an error response on the closed transport. The second write escapes as an unretrieved CLIConnectionError task exception.

This is intentionally an adversarial/cancellation-resistant callback. Applications should make their handlers cancellation-cooperative. The question is SDK shutdown ownership of late control-handler tasks, not permission bypass. Please retain useful diagnostics rather than hiding arbitrary handler errors.

Environment and reproduction

Python3.12.14; Linuxarm64. The same symptom was also observed using the bundled CLI2.1.286 with a synthetic loopback provider and a delayed PreToolUse hook. The reduced repro below needs no CLI invocation, provider, credential, application files or network. It drives the real Query message reader and handler spawning through a synthetic Transport.

Install SDK0.2.163 in a disposable environment and run:

python
"""Synthetic SDK control-task shutdown reproducer: no CLI, model, key or files.

Install claude-agent-sdk==0.2.163 in a disposable environment, then run this file.
The hook deliberately resists cancellation to model a late external completion.
This tests SDK shutdown/error ownership, not permission enforcement.
"""
import asyncio
import importlib.metadata
import json

from claude_agent_sdk import CLIConnectionError
from claude_agent_sdk._internal.query import Query
from claude_agent_sdk._internal.transport import Transport


class SyntheticTransport(Transport):
    def __init__(self):
        self.closed = False
        self.late_writes = []

    async def connect(self):
        pass

    async def write(self, data):
        if self.closed:
            self.late_writes.append(json.loads(data)['response']['subtype'])
            raise CLIConnectionError('ProcessTransport is not ready for writing')

    async def read_messages(self):
        yield {'type': 'control_request', 'request_id': 'synthetic-1',
               'request': {'subtype': 'hook_callback', 'callback_id': 'synthetic-hook',
                           'input': {'hook_event_name': 'PreToolUse'}, 'tool_use_id': 'synthetic-tool'}}
        await asyncio.Event().wait()

    async def close(self):
        self.closed = True

    async def end_input(self):
        pass

    def is_ready(self):
        return not self.closed


async def main():
    entered, release = asyncio.Event(), asyncio.Event()
    errors = []
    loop = asyncio.get_running_loop()
    def observe(loop, context):
        errors.append(type(context.get('exception')).__name__)
        loop.default_exception_handler(context)  # retain the original traceback
    loop.set_exception_handler(observe)

    async def delayed_hook(*args):
        entered.set()
        while not release.is_set():
            try:
                await release.wait()
            except asyncio.CancelledError:
                continue  # intentional adversarial callback
        return {}

    transport = SyntheticTransport()
    query = Query(transport, is_streaming_mode=True)
    query.hook_callbacks['synthetic-hook'] = delayed_hook
    await query.start()
    await asyncio.wait_for(entered.wait(), 2)
    await query.close()
    assert transport.closed
    release.set()
    await asyncio.sleep(.2)
    assert transport.late_writes == ['success', 'error'], transport.late_writes
    assert 'CLIConnectionError' in errors, errors
    print(json.dumps({'sdk': importlib.metadata.version('claude-agent-sdk'),
                     'late_write_attempts': transport.late_writes,
                     'unretrieved_task_errors': errors,
                     'status': 'REPRODUCED'}))


asyncio.run(main())

Observed: late_write_attempts: ["success", "error"], followed by an unretrieved CLIConnectionError. The script delegates to asyncio's default exception handler, so the traceback remains visible. SDK frames are query.py:688 (success write) and :704 (error write).

Expected / analysis

After close, control-handler completion should have an explicit bounded ownership/disposition: no attempt to answer a closed transport and no orphan task exception. This does not require waiting indefinitely for an uncooperative callback. _close_impl cancels child tasks before closing transport; _handle_control_request can continue after a callback resists cancellation and attempts a response without reconciling the closed lifecycle, then retries through the error-response path on that same closed transport.

Related #817 concerns early stdin close during initialization; this report concerns an already running delayed hook after explicit shutdown. No package monkeypatch or exception suppression has been applied.

AI-assisted report; the listed reduced reproducer and actual CLI scenario were executed against the installed package. No application secrets or private data are included.

Source: anthropics/claude-agent-sdk-python