From 500559b37b01ea9b7ab01b75c8285d298a1fc71c Mon Sep 17 00:00:00 2001 From: iyuzhang Date: Sat, 14 Nov 2026 19:48:24 +0800 Subject: [PATCH] fix: clean up cancelled channel wait tasks --- src/bub/utils.py | 15 +++++++++------ tests/test_utils.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/src/bub/utils.py b/src/bub/utils.py index 6af6030ce..d26248dba 100644 --- a/src/bub/utils.py +++ b/src/bub/utils.py @@ -17,14 +17,17 @@ async def wait_until_stopped[T](coro: Coroutine[None, None, T], stop_event: asyn """Run a coroutine until a stop event is set.""" task = asyncio.create_task(coro) waiter = asyncio.create_task(stop_event.wait()) - _ = await asyncio.wait({task, waiter}, return_when=asyncio.FIRST_COMPLETED) - if stop_event.is_set(): + try: + _ = await asyncio.wait({task, waiter}, return_when=asyncio.FIRST_COMPLETED) + if stop_event.is_set(): + task.cancel() + await task + raise asyncio.CancelledError("Operation cancelled due to stop event") + return task.result() + finally: task.cancel() - await task - raise asyncio.CancelledError("Operation cancelled due to stop event") - else: waiter.cancel() - return task.result() + await asyncio.gather(task, waiter, return_exceptions=True) def workspace_from_state(state: TurnState) -> Path: diff --git a/tests/test_utils.py b/tests/test_utils.py index 8fa694691..9ebf3465c 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -66,3 +66,31 @@ def test_workspace_from_state_falls_back_to_current_directory(monkeypatch: pytes workspace = workspace_from_state({"_runtime_workspace": " "}) assert workspace == tmp_path.resolve() + + +@pytest.mark.asyncio +async def test_wait_until_stopped_cleans_up_children_when_caller_is_cancelled() -> None: + stop_event = asyncio.Event() + started = asyncio.Event() + finished = asyncio.Event() + release = asyncio.Event() + + async def operation() -> str: + started.set() + try: + await release.wait() + return "done" + finally: + finished.set() + + runner = asyncio.create_task(wait_until_stopped(operation(), stop_event)) + await started.wait() + runner.cancel() + try: + with pytest.raises(asyncio.CancelledError): + await runner + assert finished.is_set() + finally: + release.set() + stop_event.set() + await asyncio.sleep(0)