Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions src/claude_agent_sdk/_internal/transport/subprocess_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,13 +526,21 @@ async def _handle_stderr(self) -> None:
if not line_str:
continue

# Call the stderr callback if provided
# Call the stderr callback if provided. Isolate per-line so a
# raise in the user's callback doesn't terminate the loop and
# silently drop every subsequent line for the rest of the
# session.
if self._options.stderr:
self._options.stderr(line_str)
try:
self._options.stderr(line_str)
except Exception:
logger.debug(
"stderr callback raised; continuing", exc_info=True
)
except anyio.ClosedResourceError:
pass # Stream closed, exit normally
except Exception:
pass # Ignore other errors during stderr reading
logger.debug("stderr stream read failed", exc_info=True)

async def close(self) -> None:
"""Close the transport and clean up resources."""
Expand Down
32 changes: 32 additions & 0 deletions tests/test_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import os
import uuid
from collections.abc import AsyncIterator
from contextlib import nullcontext
from unittest.mock import AsyncMock, MagicMock, patch

Expand Down Expand Up @@ -2071,6 +2072,37 @@ async def _test():

anyio.run(_test)

def test_stderr_callback_raise_does_not_terminate_loop(self) -> None:
"""Regression for issue #929: a raise from ``options.stderr`` must not
kill the read loop. Previously the outer ``except Exception: pass``
caught it, exited the ``async for``, and silently dropped every
subsequent stderr line for the rest of the session."""

async def _test() -> None:
received: list[str] = []

def stderr_cb(line: str) -> None:
received.append(line)
if len(received) == 1:
raise RuntimeError("simulated handler failure")

transport = SubprocessCLITransport(
prompt="x", options=ClaudeAgentOptions(stderr=stderr_cb)
)

async def mock_iter() -> AsyncIterator[str]:
yield "line 1"
yield "line 2"
yield "line 3"

transport._stderr_stream = mock_iter() # type: ignore[assignment]
await transport._handle_stderr()

# All three lines must be delivered despite the first raise.
assert received == ["line 1", "line 2", "line 3"]

anyio.run(_test)


class TestAtexitChildCleanup:
"""Tests for the atexit handler that terminates orphaned CLI subprocesses."""
Expand Down
Loading