Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(app): stop cancelled background renewal workers (#3968)
qbc0bcf2ad6b95b
diff --git a/src/agentscope/app/_manager/_background_task_manager.py b/src/agentscope/app/_manager/_background_task_manager.pyindex 4fad1d15f..44ed7990d 100644--- a/src/agentscope/app/_manager/_background_task_manager.py+++ b/src/agentscope/app/_manager/_background_task_manager.py@@ -477,7 +477,8 @@ class BackgroundTaskManager:async def renew_pending() -> None:"""Share the queue without creating a worker for every task."""- while pending:+ # An I/O dependency may return despite a pending cancellation.+ while pending and not asyncio.current_task().cancelling():_, task = pending.popitem(last=False)await self._renew_running_record(task)diff --git a/tests/background_task_endpoint_test.py b/tests/background_task_endpoint_test.pyindex f568c8a37..6a57a5b4e 100644--- a/tests/background_task_endpoint_test.py+++ b/tests/background_task_endpoint_test.py@@ -1127,6 +1127,48 @@ class TestBackgroundTaskRecords( # pylint: disable=too-many-public-methodsself.assertEqual(active, set())self.assertTrue(self.owner._renewal_task.done())+ async def test_renewal_stops_after_io_swallows_cancellation(self) -> None:+ """A cancelled worker must not start another queued record."""+ for _ in range(2):+ await self._register(self.owner)+ task_ids = list(self.owner.tasks)+ original_get = self.bus.registry_get+ reading = asyncio.Event()+ seen: list[str] = []++ async def finish_cancelled_read(+ namespace: str,+ field: str,+ ) -> str | None:+ value = await original_get(namespace, field)+ seen.append(field)+ if field == task_ids[0]:+ reading.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ # Model a response winning a Python 3.11 wait_for race.+ return value+ return value++ with (+ patch(f"{_MANAGER_MODULE}._RENEWAL_CONCURRENCY", 1),+ patch.object(+ self.bus,+ "registry_get",+ side_effect=finish_cancelled_read,+ ),+ ):+ scheduler = asyncio.create_task(self._renew_once())+ try:+ await asyncio.wait_for(reading.wait(), timeout=2)+ scheduler.cancel()+ await asyncio.wait_for(scheduler, timeout=2)+ self.assertEqual(seen, task_ids[:1])+ finally:+ scheduler.cancel()+ await asyncio.gather(scheduler, return_exceptions=True)+async def test_registration_during_round_timeout_keeps_one_scheduler(self,) -> None: