Agent Zero AI framework
fix: release deferred task resources
Alessandro21c62f6716d0
diff --git a/helpers/defer.py b/helpers/defer.pyindex 0be8c0a5e..052c264af 100644--- a/helpers/defer.py+++ b/helpers/defer.py@@ -88,6 +88,9 @@ class DeferredTask:self.event_loop_thread = EventLoopThread(thread_name)self._future: Optional[Future] = Noneself.children: list[ChildTask] = []+ self.func: Optional[Callable[..., Coroutine[Any, Any, Any]]] = None+ self.args: tuple[Any, ...] = ()+ self.kwargs: dict[str, Any] = {}def start_task(self, func: Callable[..., Coroutine[Any, Any, Any]], *args: Any, **kwargs: Any@@ -102,16 +105,29 @@ class DeferredTask:self.kill()def _start_task(self):- self._future = self.event_loop_thread.run_coroutine(self._run())+ if self.func is None:+ raise RuntimeError("Task callable is no longer available")++ self._future = self.event_loop_thread.run_coroutine(+ self._run(self.func, self.args, self.kwargs)+ )if self._future:self._future.add_done_callback(self._on_task_done)- def _on_task_done(self, _future: Future):+ def _on_task_done(self, future: Future):# Ensure child background tasks are always cleaned up once the parent finishes- self.kill_children()+ if future is self._future:+ self.kill_children()+ self._clear_call()- async def _run(self):- return await self.func(*self.args, **self.kwargs)+ def _clear_call(self) -> None:+ self.func = None+ self.args = ()+ self.kwargs = {}++ @staticmethod+ async def _run(func, args, kwargs):+ return await func(*args, **kwargs)def is_ready(self) -> bool:return self._future.done() if self._future else False@@ -149,6 +165,7 @@ class DeferredTask:self.kill_children()if self._future and not self._future.done():self._future.cancel()+ self._clear_call()if terminate_thread and self.event_loop_thread.loop:if self.event_loop_thread.loop.is_running():@@ -171,8 +188,11 @@ class DeferredTask:return self._future and not self._future.done() # type: ignoredef restart(self, terminate_thread: bool = False) -> None:+ if self.func is None:+ raise RuntimeError("Completed task cannot be restarted")+ func, args, kwargs = self.func, self.args, self.kwargsself.kill(terminate_thread=terminate_thread)- self._start_task()+ self.start_task(func, *args, **kwargs)def add_child_task(self, task: "DeferredTask", terminate_thread: bool = Falsediff --git a/helpers/defer.py.dox.md b/helpers/defer.py.dox.mdindex cccc3da9f..4e234c89f 100644--- a/helpers/defer.py.dox.md+++ b/helpers/defer.py.dox.md@@ -29,6 +29,8 @@## Runtime Contracts- Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together.+- `DeferredTask` retains its callable and arguments only while an invocation is active; completion and `kill()` clear those references after the running coroutine has taken its own snapshot.+- Task results remain available after completion. `restart()` can restart an active invocation, but a completed invocation has no retained call recipe and must be started again explicitly.- Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change.- Observed side-effect areas: scheduler state.- Imported dependency areas include: `asyncio`, `concurrent.futures`, `dataclasses`, `threading`, `typing`.diff --git a/plugins/_code_execution/AGENTS.md b/plugins/_code_execution/AGENTS.mdindex 015852174..d29c02f4a 100644--- a/plugins/_code_execution/AGENTS.md+++ b/plugins/_code_execution/AGENTS.md@@ -17,6 +17,7 @@- Execute multi-line terminal input as one current-shell compound so intermediate prompts cannot mark queued work complete; preserve `cd`, exports, and other shell state.- Treat local process exit and SSH channel termination as definitive command completion even when no final prompt is emitted; recreate terminated sessions before their next command.- Terminal reset/close must not hang on foreground commands or shells that ignore SIGTERM.+- Local and SSH session wrappers must synchronously release their owned process or connection resources when discarded.- Explicitly target local versus SSH execution runtimes.- Do not hardcode secrets, SSH credentials, or local user paths.diff --git a/plugins/_code_execution/helpers/shell_local.py b/plugins/_code_execution/helpers/shell_local.pyindex 99a56efbe..7727bc92d 100644--- a/plugins/_code_execution/helpers/shell_local.py+++ b/plugins/_code_execution/helpers/shell_local.py@@ -31,6 +31,13 @@ class LocalInteractiveSession:self.full_output = ''self.cwd = cwd+ def __del__(self):+ try:+ if self.session:+ self.session.kill()+ except Exception:+ pass+async def connect(self):self.session = tty_session.TTYSession(runtime.get_terminal_executable(),diff --git a/plugins/_code_execution/helpers/shell_ssh.py b/plugins/_code_execution/helpers/shell_ssh.pyindex 99945f7d8..fd035d233 100644--- a/plugins/_code_execution/helpers/shell_ssh.py+++ b/plugins/_code_execution/helpers/shell_ssh.py@@ -36,6 +36,14 @@ class SSHInteractiveSession:self.cwd = cwdself._exit_code: int | None = None+ def __del__(self):+ for resource in (getattr(self, "shell", None), getattr(self, "client", None)):+ try:+ if resource:+ resource.close()+ except Exception:+ pass+async def connect(self, keepalive_interval: int = 5):"""Establish the SSH connection and start an interactive shell.diff --git a/tests/test_defer_lifecycle.py b/tests/test_defer_lifecycle.pynew file mode 100644index 000000000..879029aaf--- /dev/null+++ b/tests/test_defer_lifecycle.py@@ -0,0 +1,115 @@+import asyncio+import threading+import uuid+import weakref++import pytest++from helpers.defer import DeferredTask+++class Owner:+ pass+++def make_task() -> DeferredTask:+ return DeferredTask(f"defer-lifecycle-{uuid.uuid4()}")+++def test_completed_task_releases_call_references_and_children():+ task = make_task()+ owner = Owner()+ owner_ref = weakref.ref(owner)+ child_killed = threading.Event()++ class Child:+ def kill(self, terminate_thread: bool = False) -> None:+ assert terminate_thread+ child_killed.set()++ async def run(captured_owner):+ return "done"++ try:+ task.add_child_task(Child(), terminate_thread=True) # type: ignore[arg-type]+ task.start_task(run, owner)+ assert task.result_sync(timeout=2) == "done"+ assert child_killed.wait(2)+ assert task.func is None+ assert task.args == ()+ assert task.kwargs == {}++ del owner+ assert owner_ref() is None+ assert task.result_sync(timeout=2) == "done"+ with pytest.raises(RuntimeError, match="Completed task cannot be restarted"):+ task.restart()+ finally:+ task.kill(terminate_thread=True)+++def test_kill_clears_stored_call_without_clearing_running_arguments():+ task = make_task()+ owner = Owner()+ owner_ref = weakref.ref(owner)+ started = threading.Event()+ cancelled = threading.Event()+ finished = threading.Event()+ release: list[asyncio.Event] = []++ async def run(captured_owner):+ release.append(asyncio.Event())+ started.set()+ try:+ await asyncio.Future()+ except asyncio.CancelledError:+ cancelled.set()+ await release[0].wait()+ finally:+ finished.set()++ try:+ task.start_task(run, owner)+ assert started.wait(2)+ task.kill()+ assert cancelled.wait(2)+ assert task.func is None+ assert task.args == ()+ assert task.kwargs == {}++ del owner+ assert owner_ref() is not None+ task.event_loop_thread.loop.call_soon_threadsafe(release[0].set)+ assert finished.wait(2)+ asyncio.run_coroutine_threadsafe(+ asyncio.sleep(0), task.event_loop_thread.loop+ ).result(2)+ assert owner_ref() is None+ finally:+ if release and task.event_loop_thread.loop:+ task.event_loop_thread.loop.call_soon_threadsafe(release[0].set)+ task.kill(terminate_thread=True)+++def test_active_task_can_restart_from_its_snapshot():+ task = make_task()+ starts = [threading.Event(), threading.Event()]+ run_count = 0++ async def run(value):+ nonlocal run_count+ current_run = run_count+ run_count += 1+ assert value == "argument"+ starts[current_run].set()+ await asyncio.Future()++ try:+ task.start_task(run, "argument")+ assert starts[0].wait(2)+ task.restart()+ assert starts[1].wait(2)+ assert task.func is run+ assert task.args == ("argument",)+ finally:+ task.kill(terminate_thread=True)