From 7d5927fbe2e2ded62ad926243923c89fe27ff937 Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Tue, 10 Nov 2026 06:33:24 -0800 Subject: [PATCH 1/8] fix: supervise observer Awaitables with Task-compatible adapters Preserve Task return and error-handler contracts, caller Task names, cancellation adoption and reentrant shutdown safety through explicit same-supervisor adoption edges. --- src/acp/task/supervisor.py | 56 +++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 4 deletions(-) diff --git a/src/acp/task/supervisor.py b/src/acp/task/supervisor.py index 48765ad8..ec4e3fcf 100644 --- a/src/acp/task/supervisor.py +++ b/src/acp/task/supervisor.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import inspect import logging from collections.abc import Awaitable, Callable from typing import Any @@ -10,6 +11,10 @@ ErrorHandler = Callable[[asyncio.Task[Any], BaseException], None] +async def _await_result(awaitable: Awaitable[Any]) -> Any: + return await awaitable + + class TaskSupervisor: """Track background tasks and provide graceful shutdown semantics. @@ -21,6 +26,7 @@ class TaskSupervisor: def __init__(self, *, source: str) -> None: self._source = source self._tasks: set[asyncio.Task[Any]] = set() + self._adopted: dict[asyncio.Future[Any], asyncio.Future[Any]] = {} self._closed = False self._error_handlers: list[ErrorHandler] = [] @@ -34,16 +40,44 @@ def create( name: str | None = None, on_error: ErrorHandler | None = None, ) -> asyncio.Task[Any]: + """Create a supervised Task, adopting cancellation of its awaitable. + + Existing Futures and Tasks are awaited by a new Task, so their names + remain unchanged and error handlers always receive a Task. Shutdown + cancels an adopted Future or Task even before its adapter starts. + Each registration creates its own Task and completion callback. + """ if self._closed: msg = f"TaskSupervisor for {self._source} already closed" raise RuntimeError(msg) - task = asyncio.create_task(coroutine, name=name) + loop = asyncio.get_running_loop() + if not inspect.isawaitable(coroutine): + raise TypeError("An awaitable is required") + if isinstance(coroutine, asyncio.Future) and coroutine.get_loop() is not loop: + raise ValueError("Awaitable belongs to a different loop") + # Schedule coroutine objects directly: wrapping one would leak it if the + # adapter were cancelled before ever starting. + task = loop.create_task(coroutine if inspect.iscoroutine(coroutine) else _await_result(coroutine), name=name) + if isinstance(coroutine, asyncio.Future): + self._adopted[task] = coroutine + + def cancel_adopted(done: asyncio.Task[Any]) -> None: + if not done.cancelled(): + return + if not coroutine.done(): + coroutine.cancel() + elif not coroutine.cancelled(): + # The adapter may never have started to consume a failure. + coroutine.exception() + + task.add_done_callback(cancel_adopted) self._tasks.add(task) task.add_done_callback(lambda t: self._on_done(t, on_error)) return task def _on_done(self, task: asyncio.Task[Any], on_error: ErrorHandler | None) -> None: self._tasks.discard(task) + self._adopted.pop(task, None) if task.cancelled(): return try: @@ -66,14 +100,28 @@ def _on_done(self, task: asyncio.Task[Any], on_error: ErrorHandler | None) -> No if not handled: logging.exception("Unhandled error in %s task", self._source) + def _awaits_task(self, task: asyncio.Future[Any], target: asyncio.Task[Any] | None) -> bool: + """Follow only explicitly adopted dependencies owned by this supervisor.""" + seen: set[asyncio.Future[Any]] = set() + while task not in seen: + if task is target: + return True + seen.add(task) + adopted = self._adopted.get(task) + if adopted is None: + return False + task = adopted + return False + async def shutdown(self) -> None: self._closed = True if not self._tasks: return - # A handler or async observer may close its own connection. Cancelling - # and gathering that caller would create a self-await cancellation cycle. + # A handler or async observer may close its own connection. Neither the + # caller nor adapters awaiting it may be cancelled or gathered here: + # cancelling an adapter propagates cancellation back into the caller. current = asyncio.current_task() - tasks = [task for task in self._tasks if task is not current] + tasks = [task for task in self._tasks if not self._awaits_task(task, current)] for task in tasks: task.cancel() # Failures were already routed to the error handlers by ``_on_done``; shutdown only From d8e0b8e547a0342494e9ad16d621ae9b26ab0b4c Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Tue, 10 Nov 2026 06:34:44 -0800 Subject: [PATCH 2/8] test: cover observer Awaitable delivery and cancellation Add tests for observer awaitables to ensure proper JSON-RPC delivery and error handling. --- tests/test_observer_awaitables.py | 270 ++++++++++++++++++++++++++++++ 1 file changed, 270 insertions(+) create mode 100644 tests/test_observer_awaitables.py diff --git a/tests/test_observer_awaitables.py b/tests/test_observer_awaitables.py new file mode 100644 index 00000000..a889faac --- /dev/null +++ b/tests/test_observer_awaitables.py @@ -0,0 +1,270 @@ +"""Observer Awaitable results must not break JSON-RPC delivery.""" + +from __future__ import annotations + +import asyncio +import contextlib + +import pytest + +from acp._transport import memory_transport_pair +from acp.connection import Connection + + +class CustomAwaitable: + def __init__(self, future: asyncio.Future[None]) -> None: + self.future = future + + def __await__(self): + return self.future.__await__() + + +def observer_result(kind: str, future: asyncio.Future[None]): + if kind == "done_future": + future.set_result(None) + if kind == "custom": + return CustomAwaitable(future), None + if kind == "task": + + async def observe() -> None: + await future + + task = asyncio.create_task(observe()) + return task, task + return future, None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("direction", ["incoming", "outgoing"]) +@pytest.mark.parametrize("kind", ["done_future", "pending_future", "task", "custom"]) +async def test_awaitable_observer_preserves_delivery(direction: str, kind: str) -> None: + source, peer = memory_transport_pair() + handled = asyncio.Event() + observed = [] + future = asyncio.get_running_loop().create_future() + result, task = observer_result(kind, future) + + def observer(event): + observed.append(event.direction.value) + return result + + async def handler(method, params, notification): + handled.set() + + connection = Connection(handler, source, observers=[observer], listening=direction == "incoming") + error = None + try: + if direction == "outgoing": + try: + await connection.send_notification("example", {"value": 1}) + except TypeError as exc: + error = exc + message = await asyncio.wait_for(peer.receive(), 1) + assert message["method"] == "example" + assert error is None, "a supported observer Awaitable must not fail an already-sent notification" + else: + await peer.send({"jsonrpc": "2.0", "method": "example", "params": {"value": 1}}) + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(handled.wait(), 0.1) + assert handled.is_set(), "a supported observer Awaitable must not disconnect before dispatch" + assert observed == [direction] + if not future.done(): + future.set_result(None) + if task is not None: + await task + await asyncio.sleep(0) + finally: + await connection.close() + await peer.close() + if not future.done(): + future.cancel() + if task is not None: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("direction", ["incoming", "outgoing"]) +@pytest.mark.parametrize("kind", ["sync", "coroutine", "sync_error"]) +async def test_existing_observer_controls(direction: str, kind: str, caplog) -> None: + source, peer = memory_transport_pair() + handled, observed = asyncio.Event(), asyncio.Event() + + async def async_observer(event): + observed.set() + + def sync_observer(event): + observed.set() + if kind == "sync_error": + raise RuntimeError("synthetic observer failure") + + async def handler(method, params, notification): + handled.set() + + observer = async_observer if kind == "coroutine" else sync_observer + connection = Connection(handler, source, observers=[observer], listening=direction == "incoming") + try: + if direction == "outgoing": + await connection.send_notification("example") + assert (await asyncio.wait_for(peer.receive(), 1))["method"] == "example" + else: + await peer.send({"jsonrpc": "2.0", "method": "example"}) + await asyncio.wait_for(handled.wait(), 1) + await asyncio.wait_for(observed.wait(), 1) + if kind == "sync_error": + assert "Stream observer failed" in caplog.text + finally: + await connection.close() + await peer.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["future", "custom", "task"]) +@pytest.mark.parametrize("started", [False, True]) +async def test_shutdown_cancels_pending_observer_awaitable(kind: str, started: bool) -> None: + source, peer = memory_transport_pair() + future = asyncio.get_running_loop().create_future() + result, task = observer_result(kind, future) + + async def handler(method, params, notification): + return None + + connection = Connection(handler, source, observers=[lambda event: result], listening=False) + try: + error = None + try: + await connection.send_notification("example") + except TypeError as exc: + error = exc + assert error is None, "observer Awaitables must be supervised before shutdown" + if started: + await asyncio.sleep(0) + await connection.close() + # An unstarted custom coroutine adapter has not begun awaiting its + # underlying Future, so it cannot propagate cancellation to it yet. + if started or kind == "future": + assert future.cancelled() + if task is not None: + assert task.cancelled() + assert not connection._tasks._tasks + finally: + await connection.close() + if not future.done(): + future.cancel() + if task is not None: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + await peer.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("direction", ["incoming", "outgoing"]) +async def test_failed_future_uses_observer_error_route_not_delivery_failure(direction: str, caplog) -> None: + source, peer = memory_transport_pair() + handled = asyncio.Event() + future = asyncio.get_running_loop().create_future() + future.set_exception(RuntimeError("synthetic observer Future failure")) + + async def handler(method, params, notification): + handled.set() + + connection = Connection(handler, source, observers=[lambda event: future], listening=direction == "incoming") + try: + error = None + if direction == "outgoing": + try: + await connection.send_notification("example") + except TypeError as exc: + error = exc + assert error is None, "a failed observer Future must use the observer error route" + else: + await peer.send({"jsonrpc": "2.0", "method": "example"}) + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(handled.wait(), 0.1) + assert handled.is_set(), "observer Future errors must not disconnect before dispatch" + # Let the task and its done callback run before checking the log. + await asyncio.sleep(0) + await asyncio.sleep(0) + assert "Stream observer coroutine failed" in caplog.text + assert "synthetic observer Future failure" in caplog.text + finally: + await connection.close() + future.exception() # Also consume it on the broken baseline. + await peer.close() + + +@pytest.mark.asyncio +async def test_immediate_close_closes_unstarted_coroutine_observer() -> None: + source, peer = memory_transport_pair() + + async def handler(method, params, notification): + return None + + async def observe(): + await asyncio.sleep(10) + + result = observe() + connection = Connection(handler, source, observers=[lambda event: result], listening=False) + try: + await connection.send_notification("example") + await connection.close() + assert result.cr_frame is None, "an unstarted observer coroutine must be closed, not leaked" + finally: + result.close() + await connection.close() + await peer.close() + + +@pytest.mark.asyncio +async def test_multiple_observer_results_are_bound_independently() -> None: + source, peer = memory_transport_pair() + first, second = asyncio.Event(), asyncio.Event() + + async def handler(method, params, notification): + return None + + async def observe(signal): + signal.set() + + connection = Connection( + handler, + source, + observers=[lambda event: observe(first), lambda event: observe(second)], + listening=False, + ) + try: + await connection.send_notification("example") + await asyncio.sleep(0) + assert first.is_set() and second.is_set() + finally: + await connection.close() + await peer.close() + + +@pytest.mark.asyncio +async def test_supervisor_future_identity_naming_and_error_route() -> None: + from acp.task import TaskSupervisor + + supervisor = TaskSupervisor(source="observer-test") + loop = asyncio.get_running_loop() + future = loop.create_future() + errors = [] + tracked = supervisor.create(future, name="future-name", on_error=lambda task, exc: errors.append((task, exc))) + assert isinstance(tracked, asyncio.Task) + assert tracked is not future + failure = RuntimeError("synthetic future failure") + future.set_exception(failure) + await asyncio.sleep(0) + await asyncio.sleep(0) + assert errors == [(tracked, failure)] + + async def work(): + await asyncio.sleep(10) + + task = asyncio.create_task(work()) + adapter = supervisor.create(task, name="observer-task") + assert adapter is not task + assert adapter.get_name() == "observer-task" + assert task.get_name() != "observer-task" + await supervisor.shutdown() + assert task.cancelled() From 167f5f4c69163f7c9b8a1f5bf29bab2fafe91bd3 Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Tue, 10 Nov 2026 06:35:04 -0800 Subject: [PATCH 3/8] test: verify Task adoption ownership and map cleanup --- tests/test_supervisor_loop_edges.py | 151 ++++++++++++++++++++++++++++ 1 file changed, 151 insertions(+) create mode 100644 tests/test_supervisor_loop_edges.py diff --git a/tests/test_supervisor_loop_edges.py b/tests/test_supervisor_loop_edges.py new file mode 100644 index 00000000..17b8eb8f --- /dev/null +++ b/tests/test_supervisor_loop_edges.py @@ -0,0 +1,151 @@ +"""Private edge qualification, separate from reviewed observer candidate.""" + +from __future__ import annotations + +import asyncio +import gc +import weakref + +import pytest + +from acp.task import TaskSupervisor + + +def test_no_running_loop_does_not_silently_schedule_on_default_loop(): + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + + async def work(): + return None + + coroutine = work() + try: + with pytest.raises(RuntimeError, match="running event loop"): + TaskSupervisor(source="edge").create(coroutine) + finally: + for task in asyncio.all_tasks(loop): + task.cancel() + loop.run_until_complete(asyncio.sleep(0)) + coroutine.close() + loop.close() + asyncio.set_event_loop(None) + + +@pytest.mark.asyncio +async def test_foreign_loop_future_rejected_before_registration(): + foreign_loop = asyncio.new_event_loop() + foreign = foreign_loop.create_future() + supervisor = TaskSupervisor(source="edge") + try: + with pytest.raises(ValueError, match="different loop"): + supervisor.create(foreign) + assert not supervisor._tasks + finally: + foreign.cancel() + foreign_loop.close() + + +@pytest.mark.asyncio +async def test_exception_valued_cancelled_error_does_not_escape_callback(): + loop = asyncio.get_running_loop() + notices = [] + prior = loop.get_exception_handler() + loop.set_exception_handler(lambda loop, context: notices.append(context)) + supervisor = TaskSupervisor(source="edge") + future = loop.create_future() + try: + supervisor.create(future) + future.set_exception(asyncio.CancelledError("exception-valued cancellation")) + await asyncio.sleep(0) + assert not notices + finally: + loop.set_exception_handler(prior) + await supervisor.shutdown() + + +@pytest.mark.asyncio +async def test_repeated_future_registration_has_independent_task_callbacks(): + supervisor = TaskSupervisor(source="edge") + future = asyncio.get_running_loop().create_future() + errors = [] + failure = RuntimeError("registered twice") + try: + first = supervisor.create(future, on_error=lambda task, exc: errors.append(("one", task, exc))) + second = supervisor.create(future, on_error=lambda task, exc: errors.append(("two", task, exc))) + assert first is not second + assert isinstance(first, asyncio.Task) and isinstance(second, asyncio.Task) + assert len(supervisor._tasks) == 2 + future.set_exception(failure) + await asyncio.sleep(0) + await asyncio.sleep(0) + assert errors == [("one", first, failure), ("two", second, failure)] + assert not supervisor._tasks + finally: + await supervisor.shutdown() + + +@pytest.mark.asyncio +async def test_adopted_task_name_is_not_changed_by_adapter_name(): + supervisor = TaskSupervisor(source="edge") + task = asyncio.create_task(asyncio.sleep(60), name="caller-owned") + try: + adapter = supervisor.create(task, name="supervised") + assert adapter is not task + assert adapter.get_name() == "supervised" + assert task.get_name() == "caller-owned" + finally: + await supervisor.shutdown() + assert task.cancelled() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("started", [False, True]) +async def test_shutdown_cancels_task_adopted_from_another_supervisor(started): + first = TaskSupervisor(source="first") + second = TaskSupervisor(source="second") + task = asyncio.create_task(asyncio.sleep(60), name="shared") + try: + first_adapter = first.create(task) + second_adapter = second.create(task) + assert first_adapter is not second_adapter + if started: + await asyncio.sleep(0) + await first.shutdown() + assert task.cancelled() + await asyncio.gather(second_adapter, return_exceptions=True) + await asyncio.sleep(0) + assert not second._tasks + finally: + await first.shutdown() + await second.shutdown() + + +@pytest.mark.asyncio +async def test_immediate_shutdown_retrieves_already_failed_future(): + supervisor = TaskSupervisor(source="edge") + loop = asyncio.get_running_loop() + notices = [] + previous = loop.get_exception_handler() + loop.set_exception_handler(lambda loop, context: notices.append(context)) + try: + future = loop.create_future() + future.set_exception(RuntimeError("failed before adapter starts")) + supervisor.create(future) + await supervisor.shutdown() + reference = weakref.ref(future) + del future + gc.collect() + await asyncio.sleep(0) + assert reference() is None + assert not notices + finally: + loop.set_exception_handler(previous) + await supervisor.shutdown() + + +@pytest.mark.asyncio +async def test_non_awaitable_rejected_before_registration(): + supervisor = TaskSupervisor(source="edge") + with pytest.raises(TypeError): + supervisor.create(object()) # type: ignore[arg-type] + assert not supervisor._tasks From f078a3dc17c97ccf78a263221c085a7567a0a6b2 Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Tue, 10 Nov 2026 06:35:24 -0800 Subject: [PATCH 4/8] test: bound reentrant adopted-Task shutdown regressions Add tests for TaskSupervisor and Connection closure behavior. --- tests/test_supervisor_reentrant_adapters.py | 93 +++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 tests/test_supervisor_reentrant_adapters.py diff --git a/tests/test_supervisor_reentrant_adapters.py b/tests/test_supervisor_reentrant_adapters.py new file mode 100644 index 00000000..a6a79acd --- /dev/null +++ b/tests/test_supervisor_reentrant_adapters.py @@ -0,0 +1,93 @@ +"""Keep cancellation-cycle regressions isolated so a broken loop cannot hang pytest.""" + +from __future__ import annotations + +import subprocess +import sys +import textwrap + +import pytest + + +@pytest.mark.parametrize("nested", [False, True]) +@pytest.mark.parametrize("registrations", [1, 2]) +@pytest.mark.parametrize("started", [False, True]) +def test_adopted_task_can_close_its_supervisor(nested, registrations, started): + code = textwrap.dedent(f""" + import asyncio + from acp.task import TaskSupervisor + + async def run(): + supervisor = TaskSupervisor(source="reentrant-adapter") + start = asyncio.Event() + finished = asyncio.Event() + async def worker(): + await start.wait() + await supervisor.shutdown() + finished.set() + caller = asyncio.create_task(worker(), name="caller") + adapters = [] + for _ in range({registrations}): + adapter = supervisor.create(caller) + adapters.append(adapter) + if {nested}: + adapters.append(supervisor.create(adapter)) + unrelated = supervisor.create(asyncio.sleep(60)) + if {started}: + await asyncio.sleep(0) + start.set() + await asyncio.wait_for(asyncio.gather(caller, *adapters), 1) + assert finished.is_set() + assert not caller.cancelled() + assert unrelated.cancelled() + await asyncio.sleep(0) + assert not supervisor._tasks + assert not supervisor._adopted + await supervisor.shutdown() + + asyncio.run(run()) + """) + result = subprocess.run( # noqa: S603 - fixed local test program, no external input + [sys.executable, "-c", code], capture_output=True, text=True, timeout=5 + ) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize("started", [False, True]) +def test_task_observer_can_close_its_connection(started): + code = textwrap.dedent(f""" + import asyncio + from acp._transport import memory_transport_pair + from acp.connection import Connection + + async def run(): + source, peer = memory_transport_pair() + start = asyncio.Event() + async def handler(method, params, notification): + return None + async def observer_work(): + await start.wait() + await connection.close() + task = asyncio.create_task(observer_work()) + connection = Connection(handler, source, observers=[lambda event: task], listening=False) + try: + await connection.send_notification("example") + assert (await peer.receive())["method"] == "example" + if {started}: + await asyncio.sleep(0) + start.set() + await asyncio.wait_for(task, 1) + await asyncio.sleep(0) + await asyncio.sleep(0) + assert not task.cancelled() + assert not connection._tasks._tasks + finally: + await connection.close() + await peer.close() + + asyncio.run(run()) + """) + result = subprocess.run( # noqa: S603 - fixed local test program, no external input + [sys.executable, "-c", code], capture_output=True, text=True, timeout=5 + ) + assert result.returncode == 0, result.stdout + result.stderr From 444c503336e303b393819d9a7b6714782d77b469 Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Tue, 24 Nov 2026 20:09:42 -0800 Subject: [PATCH 5/8] Update supervisor.py --- src/acp/task/supervisor.py | 51 +++----------------------------------- 1 file changed, 4 insertions(+), 47 deletions(-) diff --git a/src/acp/task/supervisor.py b/src/acp/task/supervisor.py index ec4e3fcf..b4c8aa66 100644 --- a/src/acp/task/supervisor.py +++ b/src/acp/task/supervisor.py @@ -26,7 +26,6 @@ class TaskSupervisor: def __init__(self, *, source: str) -> None: self._source = source self._tasks: set[asyncio.Task[Any]] = set() - self._adopted: dict[asyncio.Future[Any], asyncio.Future[Any]] = {} self._closed = False self._error_handlers: list[ErrorHandler] = [] @@ -40,44 +39,16 @@ def create( name: str | None = None, on_error: ErrorHandler | None = None, ) -> asyncio.Task[Any]: - """Create a supervised Task, adopting cancellation of its awaitable. - - Existing Futures and Tasks are awaited by a new Task, so their names - remain unchanged and error handlers always receive a Task. Shutdown - cancels an adopted Future or Task even before its adapter starts. - Each registration creates its own Task and completion callback. - """ if self._closed: msg = f"TaskSupervisor for {self._source} already closed" raise RuntimeError(msg) - loop = asyncio.get_running_loop() - if not inspect.isawaitable(coroutine): - raise TypeError("An awaitable is required") - if isinstance(coroutine, asyncio.Future) and coroutine.get_loop() is not loop: - raise ValueError("Awaitable belongs to a different loop") - # Schedule coroutine objects directly: wrapping one would leak it if the - # adapter were cancelled before ever starting. - task = loop.create_task(coroutine if inspect.iscoroutine(coroutine) else _await_result(coroutine), name=name) - if isinstance(coroutine, asyncio.Future): - self._adopted[task] = coroutine - - def cancel_adopted(done: asyncio.Task[Any]) -> None: - if not done.cancelled(): - return - if not coroutine.done(): - coroutine.cancel() - elif not coroutine.cancelled(): - # The adapter may never have started to consume a failure. - coroutine.exception() - - task.add_done_callback(cancel_adopted) + task = asyncio.create_task(coroutine if inspect.iscoroutine(coroutine) else _await_result(coroutine), name=name) self._tasks.add(task) task.add_done_callback(lambda t: self._on_done(t, on_error)) return task def _on_done(self, task: asyncio.Task[Any], on_error: ErrorHandler | None) -> None: self._tasks.discard(task) - self._adopted.pop(task, None) if task.cancelled(): return try: @@ -100,28 +71,14 @@ def _on_done(self, task: asyncio.Task[Any], on_error: ErrorHandler | None) -> No if not handled: logging.exception("Unhandled error in %s task", self._source) - def _awaits_task(self, task: asyncio.Future[Any], target: asyncio.Task[Any] | None) -> bool: - """Follow only explicitly adopted dependencies owned by this supervisor.""" - seen: set[asyncio.Future[Any]] = set() - while task not in seen: - if task is target: - return True - seen.add(task) - adopted = self._adopted.get(task) - if adopted is None: - return False - task = adopted - return False - async def shutdown(self) -> None: self._closed = True if not self._tasks: return - # A handler or async observer may close its own connection. Neither the - # caller nor adapters awaiting it may be cancelled or gathered here: - # cancelling an adapter propagates cancellation back into the caller. + # A handler or async observer may close its own connection. Cancelling + # and gathering that caller would create a self-await cancellation cycle. current = asyncio.current_task() - tasks = [task for task in self._tasks if not self._awaits_task(task, current)] + tasks = [task for task in self._tasks if task is not current] for task in tasks: task.cancel() # Failures were already routed to the error handlers by ``_on_done``; shutdown only From d3a6c037aed6ea6de4160264e5d92ec50aeb33d5 Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Tue, 24 Nov 2026 20:09:46 -0800 Subject: [PATCH 6/8] Update test_observer_awaitables.py --- tests/test_observer_awaitables.py | 254 ++---------------------------- 1 file changed, 11 insertions(+), 243 deletions(-) diff --git a/tests/test_observer_awaitables.py b/tests/test_observer_awaitables.py index a889faac..b5703c5c 100644 --- a/tests/test_observer_awaitables.py +++ b/tests/test_observer_awaitables.py @@ -1,9 +1,8 @@ -"""Observer Awaitable results must not break JSON-RPC delivery.""" +"""A Future-returning observer must not interrupt notification delivery.""" from __future__ import annotations import asyncio -import contextlib import pytest @@ -11,260 +10,29 @@ from acp.connection import Connection -class CustomAwaitable: - def __init__(self, future: asyncio.Future[None]) -> None: - self.future = future - - def __await__(self): - return self.future.__await__() - - -def observer_result(kind: str, future: asyncio.Future[None]): - if kind == "done_future": - future.set_result(None) - if kind == "custom": - return CustomAwaitable(future), None - if kind == "task": - - async def observe() -> None: - await future - - task = asyncio.create_task(observe()) - return task, task - return future, None - - @pytest.mark.asyncio -@pytest.mark.parametrize("direction", ["incoming", "outgoing"]) -@pytest.mark.parametrize("kind", ["done_future", "pending_future", "task", "custom"]) -async def test_awaitable_observer_preserves_delivery(direction: str, kind: str) -> None: +async def test_future_returning_observer_preserves_delivery() -> None: source, peer = memory_transport_pair() - handled = asyncio.Event() + future: asyncio.Future[None] = asyncio.get_running_loop().create_future() observed = [] - future = asyncio.get_running_loop().create_future() - result, task = observer_result(kind, future) def observer(event): observed.append(event.direction.value) - return result + return future async def handler(method, params, notification): - handled.set() + return None - connection = Connection(handler, source, observers=[observer], listening=direction == "incoming") - error = None + connection = Connection(handler, source, observers=[observer], listening=False) try: - if direction == "outgoing": - try: - await connection.send_notification("example", {"value": 1}) - except TypeError as exc: - error = exc - message = await asyncio.wait_for(peer.receive(), 1) - assert message["method"] == "example" - assert error is None, "a supported observer Awaitable must not fail an already-sent notification" - else: - await peer.send({"jsonrpc": "2.0", "method": "example", "params": {"value": 1}}) - with contextlib.suppress(asyncio.TimeoutError): - await asyncio.wait_for(handled.wait(), 0.1) - assert handled.is_set(), "a supported observer Awaitable must not disconnect before dispatch" - assert observed == [direction] - if not future.done(): - future.set_result(None) - if task is not None: - await task + await connection.send_notification("example", {"value": 1}) + message = await asyncio.wait_for(peer.receive(), 1) + assert message["method"] == "example" + assert observed == ["outgoing"] + future.set_result(None) await asyncio.sleep(0) finally: await connection.close() await peer.close() if not future.done(): future.cancel() - if task is not None: - task.cancel() - await asyncio.gather(task, return_exceptions=True) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("direction", ["incoming", "outgoing"]) -@pytest.mark.parametrize("kind", ["sync", "coroutine", "sync_error"]) -async def test_existing_observer_controls(direction: str, kind: str, caplog) -> None: - source, peer = memory_transport_pair() - handled, observed = asyncio.Event(), asyncio.Event() - - async def async_observer(event): - observed.set() - - def sync_observer(event): - observed.set() - if kind == "sync_error": - raise RuntimeError("synthetic observer failure") - - async def handler(method, params, notification): - handled.set() - - observer = async_observer if kind == "coroutine" else sync_observer - connection = Connection(handler, source, observers=[observer], listening=direction == "incoming") - try: - if direction == "outgoing": - await connection.send_notification("example") - assert (await asyncio.wait_for(peer.receive(), 1))["method"] == "example" - else: - await peer.send({"jsonrpc": "2.0", "method": "example"}) - await asyncio.wait_for(handled.wait(), 1) - await asyncio.wait_for(observed.wait(), 1) - if kind == "sync_error": - assert "Stream observer failed" in caplog.text - finally: - await connection.close() - await peer.close() - - -@pytest.mark.asyncio -@pytest.mark.parametrize("kind", ["future", "custom", "task"]) -@pytest.mark.parametrize("started", [False, True]) -async def test_shutdown_cancels_pending_observer_awaitable(kind: str, started: bool) -> None: - source, peer = memory_transport_pair() - future = asyncio.get_running_loop().create_future() - result, task = observer_result(kind, future) - - async def handler(method, params, notification): - return None - - connection = Connection(handler, source, observers=[lambda event: result], listening=False) - try: - error = None - try: - await connection.send_notification("example") - except TypeError as exc: - error = exc - assert error is None, "observer Awaitables must be supervised before shutdown" - if started: - await asyncio.sleep(0) - await connection.close() - # An unstarted custom coroutine adapter has not begun awaiting its - # underlying Future, so it cannot propagate cancellation to it yet. - if started or kind == "future": - assert future.cancelled() - if task is not None: - assert task.cancelled() - assert not connection._tasks._tasks - finally: - await connection.close() - if not future.done(): - future.cancel() - if task is not None: - task.cancel() - await asyncio.gather(task, return_exceptions=True) - await peer.close() - - -@pytest.mark.asyncio -@pytest.mark.parametrize("direction", ["incoming", "outgoing"]) -async def test_failed_future_uses_observer_error_route_not_delivery_failure(direction: str, caplog) -> None: - source, peer = memory_transport_pair() - handled = asyncio.Event() - future = asyncio.get_running_loop().create_future() - future.set_exception(RuntimeError("synthetic observer Future failure")) - - async def handler(method, params, notification): - handled.set() - - connection = Connection(handler, source, observers=[lambda event: future], listening=direction == "incoming") - try: - error = None - if direction == "outgoing": - try: - await connection.send_notification("example") - except TypeError as exc: - error = exc - assert error is None, "a failed observer Future must use the observer error route" - else: - await peer.send({"jsonrpc": "2.0", "method": "example"}) - with contextlib.suppress(asyncio.TimeoutError): - await asyncio.wait_for(handled.wait(), 0.1) - assert handled.is_set(), "observer Future errors must not disconnect before dispatch" - # Let the task and its done callback run before checking the log. - await asyncio.sleep(0) - await asyncio.sleep(0) - assert "Stream observer coroutine failed" in caplog.text - assert "synthetic observer Future failure" in caplog.text - finally: - await connection.close() - future.exception() # Also consume it on the broken baseline. - await peer.close() - - -@pytest.mark.asyncio -async def test_immediate_close_closes_unstarted_coroutine_observer() -> None: - source, peer = memory_transport_pair() - - async def handler(method, params, notification): - return None - - async def observe(): - await asyncio.sleep(10) - - result = observe() - connection = Connection(handler, source, observers=[lambda event: result], listening=False) - try: - await connection.send_notification("example") - await connection.close() - assert result.cr_frame is None, "an unstarted observer coroutine must be closed, not leaked" - finally: - result.close() - await connection.close() - await peer.close() - - -@pytest.mark.asyncio -async def test_multiple_observer_results_are_bound_independently() -> None: - source, peer = memory_transport_pair() - first, second = asyncio.Event(), asyncio.Event() - - async def handler(method, params, notification): - return None - - async def observe(signal): - signal.set() - - connection = Connection( - handler, - source, - observers=[lambda event: observe(first), lambda event: observe(second)], - listening=False, - ) - try: - await connection.send_notification("example") - await asyncio.sleep(0) - assert first.is_set() and second.is_set() - finally: - await connection.close() - await peer.close() - - -@pytest.mark.asyncio -async def test_supervisor_future_identity_naming_and_error_route() -> None: - from acp.task import TaskSupervisor - - supervisor = TaskSupervisor(source="observer-test") - loop = asyncio.get_running_loop() - future = loop.create_future() - errors = [] - tracked = supervisor.create(future, name="future-name", on_error=lambda task, exc: errors.append((task, exc))) - assert isinstance(tracked, asyncio.Task) - assert tracked is not future - failure = RuntimeError("synthetic future failure") - future.set_exception(failure) - await asyncio.sleep(0) - await asyncio.sleep(0) - assert errors == [(tracked, failure)] - - async def work(): - await asyncio.sleep(10) - - task = asyncio.create_task(work()) - adapter = supervisor.create(task, name="observer-task") - assert adapter is not task - assert adapter.get_name() == "observer-task" - assert task.get_name() != "observer-task" - await supervisor.shutdown() - assert task.cancelled() From 8384cbf92669e062a88b54a8f538ae666cefc6ef Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Tue, 24 Nov 2026 20:10:15 -0800 Subject: [PATCH 7/8] Delete tests/test_supervisor_loop_edges.py --- tests/test_supervisor_loop_edges.py | 151 ---------------------------- 1 file changed, 151 deletions(-) delete mode 100644 tests/test_supervisor_loop_edges.py diff --git a/tests/test_supervisor_loop_edges.py b/tests/test_supervisor_loop_edges.py deleted file mode 100644 index 17b8eb8f..00000000 --- a/tests/test_supervisor_loop_edges.py +++ /dev/null @@ -1,151 +0,0 @@ -"""Private edge qualification, separate from reviewed observer candidate.""" - -from __future__ import annotations - -import asyncio -import gc -import weakref - -import pytest - -from acp.task import TaskSupervisor - - -def test_no_running_loop_does_not_silently_schedule_on_default_loop(): - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - - async def work(): - return None - - coroutine = work() - try: - with pytest.raises(RuntimeError, match="running event loop"): - TaskSupervisor(source="edge").create(coroutine) - finally: - for task in asyncio.all_tasks(loop): - task.cancel() - loop.run_until_complete(asyncio.sleep(0)) - coroutine.close() - loop.close() - asyncio.set_event_loop(None) - - -@pytest.mark.asyncio -async def test_foreign_loop_future_rejected_before_registration(): - foreign_loop = asyncio.new_event_loop() - foreign = foreign_loop.create_future() - supervisor = TaskSupervisor(source="edge") - try: - with pytest.raises(ValueError, match="different loop"): - supervisor.create(foreign) - assert not supervisor._tasks - finally: - foreign.cancel() - foreign_loop.close() - - -@pytest.mark.asyncio -async def test_exception_valued_cancelled_error_does_not_escape_callback(): - loop = asyncio.get_running_loop() - notices = [] - prior = loop.get_exception_handler() - loop.set_exception_handler(lambda loop, context: notices.append(context)) - supervisor = TaskSupervisor(source="edge") - future = loop.create_future() - try: - supervisor.create(future) - future.set_exception(asyncio.CancelledError("exception-valued cancellation")) - await asyncio.sleep(0) - assert not notices - finally: - loop.set_exception_handler(prior) - await supervisor.shutdown() - - -@pytest.mark.asyncio -async def test_repeated_future_registration_has_independent_task_callbacks(): - supervisor = TaskSupervisor(source="edge") - future = asyncio.get_running_loop().create_future() - errors = [] - failure = RuntimeError("registered twice") - try: - first = supervisor.create(future, on_error=lambda task, exc: errors.append(("one", task, exc))) - second = supervisor.create(future, on_error=lambda task, exc: errors.append(("two", task, exc))) - assert first is not second - assert isinstance(first, asyncio.Task) and isinstance(second, asyncio.Task) - assert len(supervisor._tasks) == 2 - future.set_exception(failure) - await asyncio.sleep(0) - await asyncio.sleep(0) - assert errors == [("one", first, failure), ("two", second, failure)] - assert not supervisor._tasks - finally: - await supervisor.shutdown() - - -@pytest.mark.asyncio -async def test_adopted_task_name_is_not_changed_by_adapter_name(): - supervisor = TaskSupervisor(source="edge") - task = asyncio.create_task(asyncio.sleep(60), name="caller-owned") - try: - adapter = supervisor.create(task, name="supervised") - assert adapter is not task - assert adapter.get_name() == "supervised" - assert task.get_name() == "caller-owned" - finally: - await supervisor.shutdown() - assert task.cancelled() - - -@pytest.mark.asyncio -@pytest.mark.parametrize("started", [False, True]) -async def test_shutdown_cancels_task_adopted_from_another_supervisor(started): - first = TaskSupervisor(source="first") - second = TaskSupervisor(source="second") - task = asyncio.create_task(asyncio.sleep(60), name="shared") - try: - first_adapter = first.create(task) - second_adapter = second.create(task) - assert first_adapter is not second_adapter - if started: - await asyncio.sleep(0) - await first.shutdown() - assert task.cancelled() - await asyncio.gather(second_adapter, return_exceptions=True) - await asyncio.sleep(0) - assert not second._tasks - finally: - await first.shutdown() - await second.shutdown() - - -@pytest.mark.asyncio -async def test_immediate_shutdown_retrieves_already_failed_future(): - supervisor = TaskSupervisor(source="edge") - loop = asyncio.get_running_loop() - notices = [] - previous = loop.get_exception_handler() - loop.set_exception_handler(lambda loop, context: notices.append(context)) - try: - future = loop.create_future() - future.set_exception(RuntimeError("failed before adapter starts")) - supervisor.create(future) - await supervisor.shutdown() - reference = weakref.ref(future) - del future - gc.collect() - await asyncio.sleep(0) - assert reference() is None - assert not notices - finally: - loop.set_exception_handler(previous) - await supervisor.shutdown() - - -@pytest.mark.asyncio -async def test_non_awaitable_rejected_before_registration(): - supervisor = TaskSupervisor(source="edge") - with pytest.raises(TypeError): - supervisor.create(object()) # type: ignore[arg-type] - assert not supervisor._tasks From c3297d60a58f994f67dc46361144ecdc59423703 Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Tue, 24 Nov 2026 20:10:19 -0800 Subject: [PATCH 8/8] Delete tests/test_supervisor_reentrant_adapters.py --- tests/test_supervisor_reentrant_adapters.py | 93 --------------------- 1 file changed, 93 deletions(-) delete mode 100644 tests/test_supervisor_reentrant_adapters.py diff --git a/tests/test_supervisor_reentrant_adapters.py b/tests/test_supervisor_reentrant_adapters.py deleted file mode 100644 index a6a79acd..00000000 --- a/tests/test_supervisor_reentrant_adapters.py +++ /dev/null @@ -1,93 +0,0 @@ -"""Keep cancellation-cycle regressions isolated so a broken loop cannot hang pytest.""" - -from __future__ import annotations - -import subprocess -import sys -import textwrap - -import pytest - - -@pytest.mark.parametrize("nested", [False, True]) -@pytest.mark.parametrize("registrations", [1, 2]) -@pytest.mark.parametrize("started", [False, True]) -def test_adopted_task_can_close_its_supervisor(nested, registrations, started): - code = textwrap.dedent(f""" - import asyncio - from acp.task import TaskSupervisor - - async def run(): - supervisor = TaskSupervisor(source="reentrant-adapter") - start = asyncio.Event() - finished = asyncio.Event() - async def worker(): - await start.wait() - await supervisor.shutdown() - finished.set() - caller = asyncio.create_task(worker(), name="caller") - adapters = [] - for _ in range({registrations}): - adapter = supervisor.create(caller) - adapters.append(adapter) - if {nested}: - adapters.append(supervisor.create(adapter)) - unrelated = supervisor.create(asyncio.sleep(60)) - if {started}: - await asyncio.sleep(0) - start.set() - await asyncio.wait_for(asyncio.gather(caller, *adapters), 1) - assert finished.is_set() - assert not caller.cancelled() - assert unrelated.cancelled() - await asyncio.sleep(0) - assert not supervisor._tasks - assert not supervisor._adopted - await supervisor.shutdown() - - asyncio.run(run()) - """) - result = subprocess.run( # noqa: S603 - fixed local test program, no external input - [sys.executable, "-c", code], capture_output=True, text=True, timeout=5 - ) - assert result.returncode == 0, result.stdout + result.stderr - - -@pytest.mark.parametrize("started", [False, True]) -def test_task_observer_can_close_its_connection(started): - code = textwrap.dedent(f""" - import asyncio - from acp._transport import memory_transport_pair - from acp.connection import Connection - - async def run(): - source, peer = memory_transport_pair() - start = asyncio.Event() - async def handler(method, params, notification): - return None - async def observer_work(): - await start.wait() - await connection.close() - task = asyncio.create_task(observer_work()) - connection = Connection(handler, source, observers=[lambda event: task], listening=False) - try: - await connection.send_notification("example") - assert (await peer.receive())["method"] == "example" - if {started}: - await asyncio.sleep(0) - start.set() - await asyncio.wait_for(task, 1) - await asyncio.sleep(0) - await asyncio.sleep(0) - assert not task.cancelled() - assert not connection._tasks._tasks - finally: - await connection.close() - await peer.close() - - asyncio.run(run()) - """) - result = subprocess.run( # noqa: S603 - fixed local test program, no external input - [sys.executable, "-c", code], capture_output=True, text=True, timeout=5 - ) - assert result.returncode == 0, result.stdout + result.stderr