Skip to content

Agent Zero AI framework

Serialize shared event-loop initialization

Alessandroa58868ce2f71
diff --git a/helpers/defer.py b/helpers/defer.py
index 07118f9a4..7cbff7c23 100644
--- a/helpers/defer.py
+++ b/helpers/defer.py
@@ -26,13 +26,14 @@ class EventLoopThread:
return cls._instances[thread_name]
def _start(self):
- if not hasattr(self, "loop") or not self.loop:
- self.loop = asyncio.new_event_loop()
- if not hasattr(self, "thread") or not self.thread:
- self.thread = threading.Thread(
- target=self._run_event_loop, daemon=True, name=self.thread_name
- )
- self.thread.start()
+ with self._lock:
+ if not hasattr(self, "loop") or not self.loop:
+ self.loop = asyncio.new_event_loop()
+ if not hasattr(self, "thread") or not self.thread:
+ self.thread = threading.Thread(
+ target=self._run_event_loop, daemon=True, name=self.thread_name
+ )
+ self.thread.start()
def _run_event_loop(self):
if not self.loop:
diff --git a/helpers/defer.py.dox.md b/helpers/defer.py.dox.md
index 103435d10..449e9ac6e 100644
--- a/helpers/defer.py.dox.md
+++ b/helpers/defer.py.dox.md
@@ -29,6 +29,7 @@
## Runtime Contracts
+- Named event-loop instances serialize loop and thread creation under the registry lock, including concurrent first use and lazy starts through `run_coroutine`. Cancelling a consumer task must not terminate its shared loop.
- 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.
- `add_done_callback()` forwards to the current invocation's concurrent future and rejects calls before `start_task()`; callbacks observe `is_alive() == False` and must remain lightweight.
@@ -52,6 +53,7 @@
- Run targeted tests for changed helper behavior; run security regressions for auth, filesystem, WebSocket, tunnel, upload, or secret-handling helpers.
- Related tests observed by source search:
+ - `tests/test_defer_lifecycle.py`
- `tests/test_office_document_store.py`
## Child DOX Index
diff --git a/tests/test_defer_lifecycle.py b/tests/test_defer_lifecycle.py
index 0f92e77a4..de7936468 100644
--- a/tests/test_defer_lifecycle.py
+++ b/tests/test_defer_lifecycle.py
@@ -1,4 +1,7 @@
import asyncio
+from pathlib import Path
+import subprocess
+import sys
import threading
import uuid
import weakref
@@ -8,6 +11,56 @@ import pytest
from helpers.defer import DeferredTask
+def test_concurrent_first_use_shares_one_running_loop():
+ # Isolate a broken cold start so stranded loop threads cannot leak into pytest.
+ script = """
+import asyncio
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from helpers.defer import DeferredTask
+
+start = threading.Barrier(2)
+creation = threading.Barrier(2)
+new_event_loop = asyncio.new_event_loop
+loops = []
+
+def create_loop():
+ loop = new_event_loop()
+ loops.append(loop)
+ try:
+ creation.wait(timeout=0.2)
+ except threading.BrokenBarrierError:
+ pass # With serialized creation, a second caller never enters here.
+ return loop
+
+def create_task(_):
+ start.wait(timeout=2)
+ return DeferredTask('concurrent-first-use')
+
+asyncio.new_event_loop = create_loop
+with ThreadPoolExecutor(max_workers=2) as pool:
+ tasks = list(pool.map(create_task, range(2)))
+asyncio.new_event_loop = new_event_loop
+assert len(loops) == 1, f'Created {len(loops)} loops for one name'
+assert tasks[0].event_loop_thread is tasks[1].event_loop_thread
+
+async def current_loop():
+ return asyncio.get_running_loop()
+
+try:
+ for task in tasks:
+ task.start_task(current_loop)
+ assert all(task.result_sync(timeout=2) is loops[0] for task in tasks)
+finally:
+ tasks[0].kill(terminate_thread=True)
+"""
+ result = subprocess.run(
+ [sys.executable, "-c", script], timeout=10,
+ cwd=Path(__file__).resolve().parents[1], capture_output=True, text=True,
+ )
+ assert result.returncode == 0, result.stderr
+
+
class Owner:
pass