Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(subagent): 在业务接入层补齐子代理执行超时与失败处理

de484c7decdf7df
diff --git a/jiuwenswarm/agents/harness/common/tools/subagent_executor/execution_timeout.py b/jiuwenswarm/agents/harness/common/tools/subagent_executor/execution_timeout.py
new file mode 100644
index 0000000000..5477fec699
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/tools/subagent_executor/execution_timeout.py
@@ -0,0 +1,174 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""Bound host-side delegation without replacing SDK tool or session handling.
+
+The child's completion_timeout bounds one delegated call, including debug
+stream draining and task-loop children. Normal parent interaction loops and the
+persistent spawn_agent/wait_agent runtime keep their own scheduling policies.
+Cancellation is cooperative: remote work or an OS process may outlive a Python
+task. Pending cleanup stays observed and applies backpressure to new calls.
+
+Failure retirement is instance-scoped and permanent. Retries need a fresh child;
+configuration-based factory paths (e.g. SubAgentConfig) create one per new delegation.
+Integrations registering a prebuilt/shared DeepAgent must replace the failed
+instance themselves; the guard does not reset its unavailable state. Healthy
+or interrupted children may still resume in the same session.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import math
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass
+from typing import Any
+
+logger = logging.getLogger(__name__)
+_STATE_ATTRIBUTE = "_jiuwenswarm_delegation_state"
+_CANCEL_GRACE_SECONDS = 1.0
+# Admission threshold, not an eviction limit: in-flight failures may add more.
+_MAX_PENDING_CLEANUP = 64
+_PENDING_CLEANUP: set[asyncio.Task[Any]] = set()
+
+
+@dataclass
+class _CallState:
+ session_id: str
+ active: bool = False
+ unavailable: bool = False
+
+
+class _CompletionDeadline(Exception):
+ """Distinguish our deadline from a TimeoutError raised inside the child."""
+
+
+def raise_for_subagent_error(result: Any) -> None:
+ """Keep explicit failure reasons; never copy full output into an error.
+
+ When called by TaskTool, raising here intentionally leaves succeeded=False.
+ With KV-cache affinity enabled, SDK cleanup then evicts a failed sticky
+ child's cache instead of offloading it for reuse. Successful/interrupt
+ results retain the SDK's existing cache policy.
+ """
+ if isinstance(result, dict) and result.get("result_type") != "interrupt":
+ if result.get("error") or result.get("result_type") == "error":
+ reason = result.get("error") or result.get("message") or "subagent_error"
+ raise RuntimeError(f"subagent_failed: {reason}")
+
+
+def ensure_subagent_available(child: Any) -> None:
+ """Prevent a cancelled stream from publishing late chunks into debug output."""
+ state = getattr(child, _STATE_ATTRIBUTE, None)
+ if state is not None and state.unavailable:
+ raise RuntimeError("subagent unavailable after failed or cancelled execution")
+
+
+def raise_for_subagent_stream_error(chunk: Any) -> None:
+ """Reject terminal agent errors without rejecting recoverable tool errors."""
+ kind = chunk.get("type") if isinstance(chunk, dict) else getattr(chunk, "type", None)
+ payload = chunk.get("payload") if isinstance(chunk, dict) else getattr(chunk, "payload", None)
+ if kind == "error":
+ error = dict(payload) if isinstance(payload, dict) else {}
+ error["result_type"] = "error"
+ if isinstance(payload, str):
+ error["message"] = payload
+ raise_for_subagent_error(error)
+ elif kind == "answer":
+ raise_for_subagent_error(payload)
+ elif kind is None:
+ raise_for_subagent_error(chunk)
+
+
+def _observe_cleanup(task: asyncio.Task[Any]) -> None:
+ _PENDING_CLEANUP.add(task)
+
+ def finished(done: asyncio.Task[Any]) -> None:
+ _PENDING_CLEANUP.discard(done)
+ if not done.cancelled():
+ error = done.exception()
+ if error is not None:
+ logger.warning("Subagent cleanup ended with %s", type(error).__name__)
+
+ task.add_done_callback(finished)
+
+
+async def _cancel_and_observe(child: Any, task: asyncio.Task[Any], session_id: str) -> str:
+ # Capture this child's controller before cancellation lets SDK finally blocks
+ # clear it. Use public instance APIs; never enumerate another session's tasks.
+ controller = getattr(child, "loop_controller", None)
+ abort = getattr(child, "abort", None)
+ stop = getattr(controller, "stop", None)
+
+ pending = set()
+ if not task.done():
+ task.cancel()
+ pending.add(task)
+ # Start both independently: an uncooperative stream must not prevent the
+ # child's scheduler from receiving its stop request.
+ if callable(abort):
+ pending.add(asyncio.create_task(abort()))
+ if callable(stop):
+ pending.add(asyncio.create_task(stop()))
+ for cleanup in pending:
+ _observe_cleanup(cleanup)
+ if not pending:
+ return "complete"
+ _, unfinished = await asyncio.wait(pending, timeout=_CANCEL_GRACE_SECONDS)
+ if not unfinished:
+ return "complete"
+ logger.warning("Subagent cleanup still pending: session=%s", session_id)
+ return "pending"
+
+
+async def run_subagent_with_timeout(
+ child: Any,
+ *,
+ session_id: str,
+ call: Callable[[], Awaitable[Any]],
+) -> Any:
+ """Run one dispatch, preserving success/interrupt results and failure causes.
+
+ A successful or interrupted child may resume with a fresh time budget.
+ Failed instances cannot be reused, even when their cancellation is delayed.
+ """
+ state = getattr(child, _STATE_ATTRIBUTE, None)
+ if state is None:
+ state = _CallState(session_id=session_id)
+ setattr(child, _STATE_ATTRIBUTE, state)
+ if state.session_id != session_id:
+ raise RuntimeError("subagent instance cannot be reused across sessions")
+ if state.unavailable:
+ raise RuntimeError("subagent unavailable after failed or cancelled execution")
+ if state.active:
+ raise RuntimeError("subagent already has an active invocation")
+ if sum(not task.done() for task in _PENDING_CLEANUP) >= _MAX_PENDING_CLEANUP:
+ raise RuntimeError("subagent_cleanup_backlog: wait for pending cleanup before retrying")
+
+ config = getattr(child, "deep_config", None)
+ timeout = float(getattr(config, "completion_timeout", 1800.0))
+ if not math.isfinite(timeout) or timeout <= 0:
+ raise ValueError("subagent completion_timeout must be finite and positive")
+ state.active = True
+
+ async def execute() -> Any:
+ return await call()
+
+ task = asyncio.create_task(execute())
+ try:
+ done, _ = await asyncio.wait({task}, timeout=timeout)
+ if not done:
+ raise _CompletionDeadline
+ result = task.result()
+ raise_for_subagent_error(result)
+ return result
+ except (Exception, asyncio.CancelledError) as exc:
+ state.unavailable = True
+ cleanup = await _cancel_and_observe(child, task, session_id)
+ if isinstance(exc, _CompletionDeadline):
+ raise RuntimeError(
+ f"completion_timeout: subagent session={session_id}, "
+ f"limit={timeout:g}s, coroutine_cleanup={cleanup}"
+ ) from None
+ raise
+ finally:
+ state.active = False
diff --git a/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py b/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py
index dc9db70315..317b5af97a 100644
--- a/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py
+++ b/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py
@@ -13,7 +13,7 @@ capture is enabled) the subagent is driven through ``stream()`` instead, every
chunk is fed to the active logger under a ``source=subagent:...`` label, and the
chunks are reduced back into an invoke-style result via the SDK's own
``DeepAgent._result_from_stream_chunk``. When no debug run is active, behaviour
-is identical to a plain ``invoke`` (zero regression for normal runs).
+uses ``invoke``. Both paths share the delegation deadline and failure checks.
Only ever reads the ContextVar (never set/reset) — the adapter owns the binding
lifetime, see ``interface_deep.JiuWenSwarmDeepAdapter``.
@@ -24,6 +24,12 @@ from __future__ import annotations
import logging
from typing import Any
+from jiuwenswarm.agents.harness.common.tools.subagent_executor.execution_timeout import (
+ ensure_subagent_available,
+ raise_for_subagent_stream_error,
+ run_subagent_with_timeout,
+)
+
_logger = logging.getLogger(__name__)
@@ -49,6 +55,21 @@ async def invoke_subagent_with_trace(
An invoke-style result dict (``{"output": ..., "result_type": ...}``),
matching what ``subagent.invoke`` would have returned.
"""
+ child_session_id = str(inputs.get("conversation_id") or session_id or "")
+ return await run_subagent_with_timeout(
+ subagent,
+ session_id=child_session_id,
+ call=lambda: _invoke_subagent_with_trace(
+ subagent, inputs=inputs, session=session,
+ source_label=source_label, session_id=session_id,
+ ),
+ )
+
+
+async def _invoke_subagent_with_trace(
+ subagent: Any, *, inputs: dict, session: Any,
+ source_label: str, session_id: str | None,
+) -> dict:
# Safety net for a subagent that reached here without going through the
# create_subagent hook (a host-built instance, say). Idempotent, so the
# normal path — where the hook already attached the rail — pays nothing.
@@ -72,7 +93,7 @@ async def invoke_subagent_with_trace(
if sid:
dbg = get_debug_trace_logger_for_session(sid)
if dbg is None or not dbg.captures_subagent_flow():
- # No debug run, or capture disabled — original path, unchanged.
+ # No debug run, or capture disabled: keep the SDK invoke path.
return await subagent.invoke(inputs, session=session)
output_parts: list[str] = []
@@ -87,11 +108,20 @@ async def invoke_subagent_with_trace(
# subagent's tokens round-robin between source=main and source=subagent.
# The isolated session is drained only by this loop, so tagging is clean
# and nothing leaks into the parent (TUI) stream.
- async for chunk in subagent.stream(inputs, session=None):
- dbg.feed_subagent(source=source_label, chunk=chunk)
- reduced = _reduce_stream_chunk(chunk, output_parts)
- if reduced is not None:
- result = reduced
+ iterator = subagent.stream(inputs, session=None)
+ try:
+ async for chunk in iterator:
+ ensure_subagent_available(subagent)
+ reduced = _reduce_stream_chunk(chunk, output_parts)
+ dbg.feed_subagent(source=source_label, chunk=chunk)
+ if reduced is not None:
+ result = reduced
+ finally:
+ # Close in the same task that iterated the stream so rail ContextVar
+ # tokens are reset in their original context on error/cancellation.
+ close = getattr(iterator, "aclose", None)
+ if close is not None:
+ await close()
finally:
dbg.end_subagent(source=source_label)
@@ -108,6 +138,7 @@ def _reduce_stream_chunk(chunk: Any, output_parts: list[str]) -> dict | None:
``llm_output`` content and finalise on an ``answer`` chunk. Inlined (rather
than calling the SDK staticmethod) to avoid protected-member access.
"""
+ raise_for_subagent_stream_error(chunk)
chunk_type = getattr(chunk, "type", None)
payload = getattr(chunk, "payload", None)
if isinstance(chunk, dict):
@@ -123,6 +154,8 @@ def _reduce_stream_chunk(chunk: Any, output_parts: list[str]) -> dict | None:
elif chunk_type == "answer":
result = dict(payload)
result.setdefault("result_type", "answer")
+ if result["result_type"] == "interrupt":
+ return result
if "output" not in result:
content = result.get("content")
if isinstance(content, str):
diff --git a/jiuwenswarm/server/runtime/debug_trace/task_tool_patch.py b/jiuwenswarm/server/runtime/debug_trace/task_tool_patch.py
index c8e5e36d59..0689b102b0 100644
--- a/jiuwenswarm/server/runtime/debug_trace/task_tool_patch.py
+++ b/jiuwenswarm/server/runtime/debug_trace/task_tool_patch.py
@@ -1,10 +1,12 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""Attach subagent stream capture without replacing SDK TaskTool semantics.
+"""Attach bounded subagent execution and optional stream capture.
The SDK owns input validation, query budgets, focused browser resumes, resource
cleanup, usage attribution, and authoritative result rendering. This patch only
-replaces its narrow subagent dispatch seam while a debug dump is active.
+wraps its narrow dispatch seam for deadlines and failure propagation, selecting
+stream capture only while a debug dump is active. All parent agent modes use
+this hook, including native team members.
"""
from __future__ import annotations
@@ -12,6 +14,9 @@ from __future__ import annotations
import logging
from typing import Any
+from jiuwenswarm.agents.harness.common.tools.subagent_executor.execution_timeout import (
+ run_subagent_with_timeout,
+)
_PATCH_APPLIED = False
_logger = logging.getLogger(__name__)
@@ -26,7 +31,7 @@ def _subagent_source_label(subagent: Any) -> str:
def _wrap_invoke_subagent(original_dispatch: Any):
- """Wrap the SDK dispatch hook; capture only when a debug dump is active."""
+ """Guard delegation in all modes; capture only when a debug dump is active."""
async def _invoke_subagent_with_trace(
self: Any,
@@ -48,12 +53,13 @@ def _wrap_invoke_subagent(original_dispatch: Any):
if debug_logger is None:
debug_logger = get_debug_trace_logger_for_session(parent_session_id)
if debug_logger is None or not debug_logger.captures_subagent_flow():
- return await original_dispatch(
- self,
+ return await run_subagent_with_timeout(
subagent,
- subagent_inputs,
- parent_session_id=parent_session_id,
- session=session,
+ session_id=str(subagent_inputs.get("conversation_id") or parent_session_id),
+ call=lambda: original_dispatch(
+ self, subagent, subagent_inputs,
+ parent_session_id=parent_session_id, session=session,
+ ),
)
return await invoke_subagent_with_trace(
subagent,
diff --git a/tests/unit_tests/agentserver/test_code_agent_rail.py b/tests/unit_tests/agentserver/test_code_agent_rail.py
index fbf87200a1..b0bee93939 100644
--- a/tests/unit_tests/agentserver/test_code_agent_rail.py
+++ b/tests/unit_tests/agentserver/test_code_agent_rail.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import pytest
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
from openjiuwen.core.session.agent import Session
@@ -72,8 +73,10 @@ class TestAgentTool:
@pytest.mark.asyncio
async def test_invoke_sync_creates_and_runs_subagent(self):
- mock_subagent = MagicMock()
- mock_subagent.invoke = AsyncMock(return_value={"output": "done"})
+ mock_subagent = SimpleNamespace(
+ deep_config=SimpleNamespace(completion_timeout=30),
+ invoke=AsyncMock(return_value={"output": "done"}),
+ )
parent = MagicMock()
agent_def = _make_agent_def(
@@ -97,7 +100,10 @@ class TestAgentTool:
@pytest.mark.asyncio
async def test_invoke_background_returns_async_launched(self):
- mock_subagent = MagicMock()
+ mock_subagent = SimpleNamespace(
+ deep_config=SimpleNamespace(completion_timeout=30),
+ invoke=AsyncMock(return_value={"output": "done"}),
+ )
parent = MagicMock()
agent_def = _make_agent_def(name="reviewer")
@@ -135,9 +141,9 @@ class TestAgentTool:
@pytest.mark.asyncio
async def test_invoke_with_subagent_execution_failure_raises(self):
- mock_subagent = MagicMock()
- mock_subagent.invoke = AsyncMock(
- side_effect=RuntimeError("execution failed")
+ mock_subagent = SimpleNamespace(
+ deep_config=SimpleNamespace(completion_timeout=30),
+ invoke=AsyncMock(side_effect=RuntimeError("execution failed")),
)
parent = MagicMock()
@@ -154,6 +160,7 @@ class TestAgentTool:
session=session,
)
assert "execution failed" in str(exc.value)
+ mock_subagent.invoke.assert_awaited_once()
class TestCodeAgentRail:
@@ -417,4 +424,4 @@ def _make_agent_tool(
card=_build_tool_card(),
parent_agent=parent or MagicMock(),
custom_agents=custom_agents or [],
- )
\ No newline at end of file
+ )
diff --git a/tests/unit_tests/agentserver/test_subagent_execution_timeout.py b/tests/unit_tests/agentserver/test_subagent_execution_timeout.py
new file mode 100644
index 0000000000..51fbe32f96
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_subagent_execution_timeout.py
@@ -0,0 +1,445 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""Delegation deadlines and failures through the real SDK TaskTool dispatcher."""
+
+from __future__ import annotations
+
+import asyncio
+from contextvars import ContextVar
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+from openjiuwen.core.common.exception.errors import BaseError
+from openjiuwen.core.foundation.tool import ToolCard
+from openjiuwen.core.session.agent import Session
+from openjiuwen.harness.tools.subagent.task_tool import TaskTool
+
+from jiuwenswarm.server.runtime.debug_trace import context, task_tool_patch
+
+
[email protected](autouse=True)
+def dispatch_hook(monkeypatch):
+ from openjiuwen.extensions.observability import setup
+
+ monkeypatch.setattr(setup, "is_initialized", lambda: False)
+ monkeypatch.setattr(TaskTool, "_invoke_subagent", TaskTool._invoke_subagent)
+ for name in ("debug_trace_patch_applied", "debug_trace_patch_mode"):
+ monkeypatch.setattr(TaskTool, name, getattr(TaskTool, name, False), raising=False)
+ monkeypatch.setattr(task_tool_patch, "_PATCH_APPLIED", task_tool_patch._PATCH_APPLIED)
+ task_tool_patch.apply_task_tool_debug_patch()
+
+
[email protected](params=[False, True], ids=["invoke", "debug-stream"])
+def debug_capture(request):
+ logger = Mock() if request.param else None
+ if logger is not None:
+ logger.captures_subagent_flow.return_value = True
+ token = context.set_debug_trace_logger(logger)
+ try:
+ yield logger
+ finally:
+ context.reset_debug_trace_logger(token)
+
+
+def child_for(run, *, timeout=1.0, task_loop=False):
+ async def stream(*args, **kwargs):
+ yield {"type": "answer", "payload": await run(*args, **kwargs)}
+
+ return SimpleNamespace(
+ card=SimpleNamespace(id="child", name="general-purpose"),
+ deep_config=SimpleNamespace(completion_timeout=timeout, enable_task_loop=task_loop),
+ invoke=run, stream=stream,
+ )
+
+
+async def dispatch(child, *, session_id="parent-A", call_id="call-1"):
+ parent = SimpleNamespace(create_subagent=lambda *args, **kwargs: child)
+ tool = TaskTool(ToolCard(id="test-task", name="task_tool", description="test"), parent)
+ return await tool.invoke(
+ {"subagent_type": "general-purpose", "task_description": "test"},
+ session=Session(session_id=session_id), tool_call_id=call_id,
+ )
+
+
[email protected]("task_loop", [False, True])
+async def test_deadline_returns_failure_and_cancels_only_this_call(debug_capture, task_loop):
+ stopped = asyncio.Event()
+
+ async def run(*args, **kwargs):
+ try:
+ await asyncio.sleep(0.15)
+ return {"output": "late answer"}
+ finally:
+ stopped.set()
+
+ child = child_for(run, timeout=0.02, task_loop=task_loop)
+ with pytest.raises(BaseError, match="completion_timeout"):
+ await asyncio.wait_for(dispatch(child), 2)
+ assert stopped.is_set()
+ with pytest.raises(BaseError, match="unavailable"):
+ await dispatch(child)
+
+
[email protected]("result, reason", [
+ ({"error": "completion_timeout"}, "completion_timeout"),
+ ({"result_type": "error", "message": "provider unavailable"}, "provider unavailable"),
+ ({"result_type": "error", "output": "private output"}, "subagent_error"),
+])
+async def test_error_result_never_becomes_empty_success(debug_capture, result, reason):
+ run = AsyncMock(return_value=result)
+ child = child_for(run)
+ with pytest.raises(BaseError, match=reason) as error:
+ await dispatch(child)
+ assert "private output" not in str(error.value)
+ with pytest.raises(BaseError, match="unavailable"):
+ await dispatch(child)
+ assert run.await_count == 1
+
+
[email protected]("output", ["", "done"])
+async def test_success_including_empty_output_is_preserved(debug_capture, output):
+ child = child_for(AsyncMock(return_value={"output": output}))
+ result = await dispatch(child)
+ assert result.success is True
+ assert result.data["output"] == output
+
+
[email protected]("failure", [RuntimeError, TimeoutError, asyncio.CancelledError])
[email protected]("task_loop", [False, True])
+async def test_child_exception_preserves_cause_and_prevents_reuse(debug_capture, failure, task_loop):
+ run = AsyncMock(side_effect=failure("inner failure"))
+ child = child_for(run, task_loop=task_loop)
+ expected = asyncio.CancelledError if failure is asyncio.CancelledError else BaseError
+ with pytest.raises(expected, match="inner failure"):
+ await dispatch(child)
+ with pytest.raises(BaseError, match="unavailable"):
+ await dispatch(child)
+ assert run.await_count == 1
+
+
+async def test_debug_error_chunk_is_not_reduced_to_empty_success(debug_capture):
+ if debug_capture is None:
+ return
+
+ async def stream(*args, **kwargs):
+ yield {"type": "error", "payload": {"error": "provider unavailable"}}
+
+ child = child_for(AsyncMock())
+ child.stream = stream
+ with pytest.raises(BaseError, match="provider unavailable"):
+ await dispatch(child)
+
+
+async def test_parent_cancellation_stops_child_and_prevents_reuse(debug_capture):
+ entered, stopped = asyncio.Event(), asyncio.Event()
+
+ async def run(*args, **kwargs):
+ entered.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ stopped.set()
+
+ child = child_for(run, timeout=2)
+ task = asyncio.create_task(dispatch(child))
+ await asyncio.wait_for(entered.wait(), 1)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert stopped.is_set()
+ with pytest.raises(BaseError, match="unavailable"):
+ await dispatch(child)
+
+
[email protected]("other_session", ["parent-A", "parent-B"])
+async def test_one_timeout_does_not_cancel_a_parallel_child(debug_capture, other_session):
+ async def slow(*args, **kwargs):
+ await asyncio.sleep(0.1)
+ return {"output": "done"}
+
+ results = await asyncio.gather(
+ dispatch(child_for(slow, timeout=0.01)),
+ dispatch(child_for(slow, timeout=1), session_id=other_session, call_id="call-2"),
+ return_exceptions=True,
+ )
+ assert isinstance(results[0], BaseError)
+ assert "completion_timeout" in str(results[0])
+ assert results[1].success is True
+ assert results[1].data["output"] == "done"
+
+
+async def test_active_call_and_session_binding_prevent_unsafe_reuse(debug_capture):
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def run(*args, **kwargs):
+ entered.set()
+ await release.wait()
+ return {"output": "done"}
+
+ child = child_for(run, timeout=1)
+ running = asyncio.create_task(dispatch(child))
+ try:
+ await asyncio.wait_for(entered.wait(), 1)
+ with pytest.raises(BaseError, match="active invocation"):
+ await dispatch(child)
+ with pytest.raises(BaseError, match="across sessions"):
+ await dispatch(child, session_id="parent-B")
+ finally:
+ release.set()
+ assert (await running).success is True
+
+
+async def test_interrupt_can_resume_with_a_fresh_deadline(debug_capture):
+ interrupt = {"result_type": "interrupt", "interrupt_ids": ["approval-1"]}
+ run = AsyncMock(side_effect=[interrupt, {"output": "resumed"}])
+ child = child_for(run)
+ assert await dispatch(child) == interrupt
+ await asyncio.sleep(0.03) # Human approval waiting does not consume the next budget.
+ assert (await dispatch(child)).data["output"] == "resumed"
+
+
+async def test_pending_cleanup_rejects_new_calls_and_discards_late_output(monkeypatch, debug_capture):
+ from jiuwenswarm.agents.harness.common.tools.subagent_executor import execution_timeout as guard
+
+ pending = set()
+ monkeypatch.setattr(guard, "_PENDING_CLEANUP", pending)
+ monkeypatch.setattr(guard, "_MAX_PENDING_CLEANUP", 1)
+ monkeypatch.setattr(guard, "_CANCEL_GRACE_SECONDS", 0.01)
+ release = asyncio.Event()
+
+ async def stubborn(*args, **kwargs):
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ await release.wait()
+ return {"output": "late answer"}
+
+ child = child_for(stubborn, timeout=0.01)
+ fresh_run = AsyncMock(return_value={"output": "ok"})
+ fresh_child = child_for(fresh_run)
+ try:
+ with pytest.raises(BaseError, match="coroutine_cleanup=pending"):
+ await asyncio.wait_for(dispatch(child), 1)
+ assert pending
+ with pytest.raises(BaseError, match="subagent_cleanup_backlog"):
+ await dispatch(fresh_child, call_id="call-2")
+ fresh_run.assert_not_called()
+ finally:
+ release.set()
+ await asyncio.wait_for(asyncio.gather(*list(pending), return_exceptions=True), 1)
+ await asyncio.sleep(0)
+ assert not pending
+ if debug_capture is not None:
+ debug_capture.feed_subagent.assert_not_called()
+ assert (await dispatch(fresh_child, call_id="call-2")).success is True
+
+
+async def test_runtime_stop_is_requested_even_when_abort_waits(monkeypatch, debug_capture):
+ from jiuwenswarm.agents.harness.common.tools.subagent_executor import execution_timeout as guard
+
+ pending = set()
+ monkeypatch.setattr(guard, "_PENDING_CLEANUP", pending)
+ monkeypatch.setattr(guard, "_CANCEL_GRACE_SECONDS", 0.01)
+ release = asyncio.Event()
+ controller = SimpleNamespace(stop=AsyncMock())
+ child = child_for(AsyncMock(return_value={"error": "completion_timeout"}), task_loop=True)
+ child.abort = release.wait
+ child.loop_controller = controller
+ try:
+ with pytest.raises(BaseError, match="completion_timeout"):
+ await asyncio.wait_for(dispatch(child), 1)
+ controller.stop.assert_awaited_once()
+ assert pending
+ finally:
+ release.set()
+ await asyncio.gather(*list(pending))
+
+
+async def test_debug_stream_closes_context_in_its_original_task():
+ value = ContextVar("child-value", default="parent")
+ stopped = asyncio.Event()
+
+ async def stream(*args, **kwargs):
+ token = value.set("child")
+ try:
+ yield {"type": "tool_result", "payload": {"error": "recoverable"}}
+ await asyncio.Event().wait()
+ finally:
+ value.reset(token)
+ stopped.set()
+
+ logger = Mock()
+ logger.captures_subagent_flow.return_value = True
+ token = context.set_debug_trace_logger(logger)
+ child = child_for(AsyncMock(), timeout=0.02)
+ child.stream = stream
+ try:
+ with pytest.raises(BaseError, match="completion_timeout"):
+ await dispatch(child)
+ finally:
+ context.reset_debug_trace_logger(token)
+ assert stopped.is_set()
+ assert value.get() == "parent"
+ logger.end_subagent.assert_called_once()
+
+
+async def test_direct_custom_subagent_entrypoint_has_same_guard(debug_capture):
+ from jiuwenswarm.server.runtime.debug_trace import invoke_subagent_with_trace
+
+ child = child_for(AsyncMock(return_value={"error": "provider unavailable"}))
+ with pytest.raises(RuntimeError, match="provider unavailable"):
+ await invoke_subagent_with_trace(
+ child, inputs={"query": "test", "conversation_id": "custom-child"},
+ session=None, source_label="subagent:custom:test",
+ )
+
+
+def _build_parent(profile, tmp_path, monkeypatch):
+ """Use real SDK factories and team providers; model I/O is replaced later."""
+ from openjiuwen.core.single_agent.schema.agent_card import AgentCard
+ from openjiuwen.harness import create_deep_agent
+ from openjiuwen.harness.schema.config import SubAgentConfig
+ from openjiuwen.harness.workspace.workspace import Workspace
+
+ kind = "explore_agent" if profile.startswith("code") else "general-purpose"
+ if ":" not in profile:
+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter
+ from jiuwenswarm.server.runtime.agent_adapter.interface_code import JiuwenSwarmCodeAdapter
+ from jiuwenswarm.server.runtime.agent_adapter.interface_flash import JiuwenSwarmFlashAdapter
+
+ cls = {"agent": JiuWenSwarmDeepAdapter, "code": JiuwenSwarmCodeAdapter,
+ "flash": JiuwenSwarmFlashAdapter}[profile]
+ adapter = cls()
+ rail = adapter._build_subagent_rail({})
+ return create_deep_agent(
+ model=None, rails=[rail],
+ subagents=[SubAgentConfig(
+ agent_card=AgentCard(name=kind), system_prompt="test", enable_task_loop=False,
+ )],
+ workspace=Workspace(root_path=str(tmp_path)), auto_create_workspace=False,
+ enable_sys_operation=False, enable_read_image_multimodal=False,
+ ), kind
+
+ from openjiuwen.agent_teams.harness.team_harness import TeamHarness
+ from openjiuwen.agent_teams.schema.blueprint import LeaderSpec, TeamAgentSpec
+ from openjiuwen.agent_teams.schema.deep_agent_spec import DeepAgentSpec, SubAgentSpec, WorkspaceSpec
+ from openjiuwen.agent_teams.schema.team import TeamRole
+ from jiuwenswarm.agents.swarm import enrich_team_spec_for_swarm
+
+ mode, role = profile.split(":")
+ monkeypatch.chdir(tmp_path)
+ base = DeepAgentSpec(
+ card=AgentCard(id=f"parent-{mode}-{role}", name=role),
+ workspace=WorkspaceSpec(root_path=str(tmp_path / role)),
+ enable_sys_operation=False, enable_read_image_multimodal=False,
+ auto_create_workspace=False,
+ subagents=[SubAgentSpec(
+ agent_card=AgentCard(name=kind), system_prompt="test", enable_task_loop=False,
+ )],
+ )
+ spec = TeamAgentSpec(
+ agents={role: base}, team_name=f"timeout-{mode}-{role}",
+ leader=LeaderSpec(member_name="leader"),
+ workspace={"root_path": str(tmp_path / "team")},
+ )
+ enrich_team_spec_for_swarm(
+ spec, session_id="team-parent", mode=mode,
+ config_base={"react": {"subagents": {"general_agent": {"enabled": True}}},
+ "symphony": {"skill_retrieval": {"enabled": False}}},
+ )
+ harness = TeamHarness.build(
+ agent_spec=spec.agents[role], role=TeamRole(role), member_name=role,
+ build_context=spec.build_context.derive(role=role, member_name=role),
+ )
+ return harness._native, kind
+
+
[email protected]("profile", [
+ "agent", "code", "flash", "team:leader", "team:teammate",
+ "team.plan:leader", "team.plan:teammate", "code.team:leader", "code.team:teammate",
+])
[email protected]("behavior", ["success", "deadline", "error"])
+async def test_real_child_factory_dispatch_across_modes(
+ profile, behavior, debug_capture, tmp_path, monkeypatch,
+):
+ parent, kind = _build_parent(profile, tmp_path, monkeypatch)
+ stopped = asyncio.Event()
+ create = parent.create_subagent
+
+ async def react_invoke(*args, **kwargs):
+ try:
+ if behavior == "deadline":
+ await asyncio.Event().wait()
+ if behavior == "error":
+ return {"result_type": "error", "error": "provider unavailable"}
+ return {"output": "child done"}
+ finally:
+ stopped.set()
+
+ async def react_stream(*args, **kwargs):
+ yield {"type": "answer", "payload": await react_invoke()}
+
+ def create_controlled(*args, **kwargs):
+ child = create(*args, **kwargs)
+ assert child.deep_config.enable_task_loop is False
+ child.deep_config.completion_timeout = 0.1 if behavior == "deadline" else 5
+ child._initialized = True
+ child._react_agent = SimpleNamespace(invoke=react_invoke, stream=react_stream)
+ return child
+
+ monkeypatch.setattr(parent, "create_subagent", create_controlled)
+ tool = TaskTool(ToolCard(name="task_tool", description="test"), parent)
+
+ async def invoke():
+ return await tool.invoke(
+ {"subagent_type": kind, "task_description": "test"},
+ session=Session(session_id="mode-test"), tool_call_id="mode-call",
+ )
+
+ if behavior == "success":
+ assert (await invoke()).data["output"] == "child done"
+ else:
+ reason = "completion_timeout" if behavior == "deadline" else "provider unavailable"
+ with pytest.raises(BaseError, match=reason):
+ await asyncio.wait_for(invoke(), 2)
+ assert stopped.is_set()
+
+
+async def test_real_task_loop_scheduler_stops_after_delegation_timeout():
+ from openjiuwen.core.runner import Runner
+ from openjiuwen.core.single_agent.schema.agent_card import AgentCard
+ from openjiuwen.harness.deep_agent import DeepAgent
+ from openjiuwen.harness.schema.config import DeepAgentConfig
+ from jiuwenswarm.agents.harness.common.tools.subagent_executor.execution_timeout import (
+ run_subagent_with_timeout,
+ )
+
+ entered, stopped = asyncio.Event(), asyncio.Event()
+
+ async def react_invoke(*args, **kwargs):
+ entered.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ stopped.set()
+
+ child = DeepAgent(AgentCard(id="task-loop-child", name="child"))
+ child.configure(DeepAgentConfig(model=None, enable_task_loop=True, completion_timeout=0.2))
+ child._initialized = True
+ child._react_agent = SimpleNamespace(invoke=react_invoke)
+ child_session = Session(session_id="isolated-task-loop-child")
+ await Runner.start()
+ try:
+ with pytest.raises(RuntimeError, match="completion_timeout"):
+ await asyncio.wait_for(run_subagent_with_timeout(
+ child, session_id=child_session.get_session_id(),
+ call=lambda: child.invoke({"query": "test"}, session=child_session),
+ ), 3)
+ assert entered.is_set()
+ await asyncio.wait_for(stopped.wait(), 1)
+ assert child.loop_controller is None
+ finally:
+ if child.loop_controller is not None:
+ await child.loop_controller.stop()
+ await Runner.stop()