diff --git a/backend/packages/harness/deerflow/subagents/AGENTS.md b/backend/packages/harness/deerflow/subagents/AGENTS.md index 3213d59867..85a2d5a6b1 100644 --- a/backend/packages/harness/deerflow/subagents/AGENTS.md +++ b/backend/packages/harness/deerflow/subagents/AGENTS.md @@ -23,9 +23,9 @@ from `deerflow.utils.messages`. Keep delayed Steer reports as sanitized history. ## Terminal state -- **The first terminal write wins.** Cancellation, timeout and completion race. - A late cancellation must not replace a recorded timeout, and a cancelled or - stale attempt must not publish a result or evidence. +- **The first terminal write wins.** Check the deadline under the result lock + before publishing success. Cancelled or stale attempts cannot publish + results or evidence. - **Clean up before you notify.** Stream cleanup and the final usage snapshot come before the terminal notification, because callbacks can arrive before the last values chunk. diff --git a/backend/packages/harness/deerflow/subagents/capacity.py b/backend/packages/harness/deerflow/subagents/capacity.py index a313be339d..9085671a72 100644 --- a/backend/packages/harness/deerflow/subagents/capacity.py +++ b/backend/packages/harness/deerflow/subagents/capacity.py @@ -43,6 +43,16 @@ class SubagentExecutionCapacity: self._running = 0 self._waiters: deque[asyncio.Future[None]] = deque() + @property + def queue_timeout_seconds(self) -> int: + """The queue bound this controller applies to waiting executions. + + Exposed so a caller that injects its own controller (the SDK runtime + does not install a process-wide one) can size its wait budget from the + capacity it actually waits on instead of the startup snapshot. + """ + return self._config.queue_timeout_seconds + def snapshot(self) -> SubagentCapacitySnapshot: # snapshot() is read from non-loop threads (notably # configure_subagent_execution_capacity), while the loop thread mutates @@ -198,3 +208,14 @@ def configured_subagent_max_running() -> int: """Return the startup snapshot without requiring an event loop.""" with _state_lock: return _config.max_running + + +def configured_subagent_queue_timeout_seconds() -> int: + """Return the queue bound without requiring an event loop. + + Pollers live on the parent loop and must size their wait budget for the + queue stage, but reading it through ``get_subagent_execution_capacity()`` + would bind or rebind the controller to the parent loop. + """ + with _state_lock: + return _config.queue_timeout_seconds diff --git a/backend/packages/harness/deerflow/subagents/executor.py b/backend/packages/harness/deerflow/subagents/executor.py index e0bce3cd0c..e9ead677d4 100644 --- a/backend/packages/harness/deerflow/subagents/executor.py +++ b/backend/packages/harness/deerflow/subagents/executor.py @@ -7,6 +7,7 @@ import logging import os import sys import threading +import time import uuid from collections.abc import Awaitable, Callable, Coroutine, Mapping from concurrent.futures import Future @@ -45,6 +46,7 @@ from deerflow.skills.types import Skill from deerflow.subagents.capacity import ( SubagentCapacityError, SubagentExecutionCapacity, + configured_subagent_queue_timeout_seconds, get_subagent_execution_capacity, ) from deerflow.subagents.config import SubagentConfig, resolve_subagent_model_name @@ -119,6 +121,15 @@ class SubagentStatus(Enum): } +@dataclass +class _ExecutionTimeout: + seconds: float + status: SubagentStatus + error: str + admitted: asyncio.Event = field(default_factory=asyncio.Event) + deadline: float | None = None + + @dataclass class SubagentResult: """Result of a subagent execution. @@ -184,6 +195,7 @@ class SubagentResult: bash_executions: list[dict[str, Any]] | None = field(default=None, kw_only=True) knowledge_sources: list[dict[str, Any]] = field(default_factory=list, kw_only=True) _knowledge_messages: list[Any] = field(default_factory=list, init=False, repr=False) + _execution_timeout: _ExecutionTimeout | None = field(default=None, init=False, repr=False, compare=False) cancel_event: threading.Event = field(default_factory=threading.Event, repr=False) execution_done_event: threading.Event = field(default_factory=threading.Event, init=False, repr=False) _state_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False) @@ -291,6 +303,13 @@ class SubagentResult: if self.status.is_terminal: return False + # Finalization can run past the deadline without yielding to the + # watcher. Decide before publishing a success or its payload. + timeout = self._execution_timeout + if status is SubagentStatus.COMPLETED and timeout is not None and timeout.deadline is not None and time.monotonic() >= timeout.deadline: + status, error = timeout.status, timeout.error + result, stop_reason = None, None + if result is not None: self.result = result if error is not None: @@ -1782,6 +1801,10 @@ class SubagentExecutor: from deerflow.subagents.checkpoints import SubagentCheckpointError, subagent_checkpoint_scope with ensure_trace_context(self.deerflow_trace_id): + # Read the handoff before the first await: the delegating wrapper + # clears the field as soon as it stops waiting, while this + # execution may still be running under supervision. + timeout = result._execution_timeout try: capacity = self.execution_capacity or get_subagent_execution_capacity() slot = capacity.slot(wait=False) if self.input_gate is not None and not self.input_gate.can_queue else capacity.slot() @@ -1789,6 +1812,11 @@ class SubagentExecutor: subagent_checkpoint_scope(execution_id=result.task_id, run_id=self.run_id, tool_call_id=result.external_task_id, agent_name=self.config.name), slot, ): + if timeout is not None: + # The deadline starts at slot grant and includes + # principal revalidation and any time before the watcher wakes. + timeout.deadline = time.monotonic() + timeout.seconds + timeout.admitted.set() if self._principal_resolver is not None: # Durable work can wait behind ordinary subagents after # its worker-side check. Revalidate before marking it @@ -1826,6 +1854,12 @@ class SubagentExecutor: ) return result finally: + # Cover every path that never reached admission (capacity + # rejection, terminal short-circuit, cancellation): the + # delegating wrapper must not wait for an event that will + # never fire. + if timeout is not None: + timeout.admitted.set() if self.input_gate is not None: self.input_gate.close() result.execution_done_event.set() @@ -2328,6 +2362,80 @@ class SubagentExecutor: return result + async def _await_admitted_execution( + self, + execution_task: asyncio.Task[SubagentResult], + result: SubagentResult, + timeout: _ExecutionTimeout, + *, + execution_id: str, + ) -> tuple[SubagentResult, bool]: + """Wait for admission, then apply the execution timeout. + + The capacity controller already bounds queue wait with + ``queue_timeout_seconds``; the execution clock must start only once a + slot is granted. That start is recorded on the result at admission, not + when this watcher is scheduled: synchronous work between the two still + consumes the execution budget. Completion is accepted in place of + admission so executions supplied by wrappers that never signal + admission still return normally. + + Returns the outcome and whether a timed-out execution was detached to + the background supervisor for teardown. + """ + admission_waiter = asyncio.create_task(timeout.admitted.wait()) + try: + done, _ = await asyncio.wait( + {execution_task, admission_waiter}, + return_when=asyncio.FIRST_COMPLETED, + ) + if execution_task in done: + return execution_task.result(), False + finally: + if not admission_waiter.done(): + try: + admission_waiter.cancel() + except RuntimeError: + # The isolated loop can close while a detached sync + # wrapper is still being reclaimed; there is no loop left + # to schedule the waiter's cancellation on. + pass + + remaining = timeout.seconds if timeout.deadline is None else timeout.deadline - time.monotonic() + if remaining > 0: + await asyncio.wait({execution_task}, timeout=remaining) + + if execution_task.done(): + return execution_task.result(), False + + # Publish the configured hard timeout without waiting for + # cancellation-resistant stream cleanup. The detached execution still + # owns its capacity slot and sandbox lease until its supervisor + # observes full teardown. + result.try_set_terminal( + timeout.status, + error=timeout.error, + tool_receipts=result.snapshot_tool_receipts(), + ) + result.cancel_event.set() + execution_task.cancel() + _supervise_background_execution(execution_id, result, execution_task) + return result, True + + def _sync_timeout_backstop_seconds(self) -> int: + """Outer bound on the synchronous wait for the isolated loop. + + The admission-aware wrapper owns the execution timeout; this bound + exists only for a loop that never settles, so it allows the queue stage + and the execution stage plus the same cleanup margin as the poller. + The injected capacity's queue bound wins over the process-wide + snapshot because it is the controller this executor waits on. + """ + queue_timeout_seconds = getattr(self.execution_capacity, "queue_timeout_seconds", None) + if queue_timeout_seconds is None: + queue_timeout_seconds = configured_subagent_queue_timeout_seconds() + return queue_timeout_seconds + self.config.timeout_seconds + 60 + def _execute_in_isolated_loop(self, task: str, result_holder: SubagentResult | None = None) -> SubagentResult: """Execute the subagent on the persistent isolated event loop. @@ -2341,12 +2449,40 @@ class SubagentExecutor: result_holder = SubagentResult(task_id=str(uuid.uuid4())[:8], trace_id=self.trace_id, status=SubagentStatus.PENDING) future: Future[SubagentResult] | None = None parent_context = _copy_isolated_subagent_context() - try: - future = _submit_to_isolated_loop_in_context( - parent_context, - lambda: self._aexecute(task, result_holder), + timeout = _ExecutionTimeout(self.config.timeout_seconds, SubagentStatus.FAILED, "") + result_holder._execution_timeout = timeout + + async def run_with_admission_timeout() -> SubagentResult: + execution_task = asyncio.create_task( + self._aexecute(task, result_holder), + name=f"subagent-{self.config.name}-sync-execution", ) - return future.result(timeout=self.config.timeout_seconds) + try: + outcome, _ = await self._await_admitted_execution( + execution_task, + result_holder, + timeout, + execution_id=result_holder.task_id, + ) + return outcome + except asyncio.CancelledError: + if not execution_task.done(): + execution_task.cancel() + try: + await execution_task + except (asyncio.CancelledError, Exception): + pass + raise + finally: + result_holder._execution_timeout = None + + try: + future = _submit_to_isolated_loop_in_context(parent_context, run_with_admission_timeout) + # Backstop only: the admission-aware wrapper owns the execution + # timeout. Reaching this bound means the isolated loop itself is + # stuck, so allow both stages plus the same cleanup margin as the + # poller before giving up on the synchronous call. + return future.result(timeout=self._sync_timeout_backstop_seconds()) except FuturesTimeoutError as exc: # Publish the synchronous API's failure before cancellation can # reach task-stop observers or win the terminal-state race. @@ -2367,6 +2503,11 @@ class SubagentExecutor: exc_info=True, ) raise + finally: + # Also covers a wrapper that never started (submit failure or a + # synchronous raise before its own cleanup), so a reused holder + # cannot inherit a stale, already-set admission signal or clock. + result_holder._execution_timeout = None def execute(self, task: str, result_holder: SubagentResult | None = None) -> SubagentResult: """Execute a task synchronously (wrapper around async execution). @@ -2463,46 +2604,39 @@ class SubagentExecutor: ) _mark_background_execution_done(execution_id, result) return result - execution_task = asyncio.create_task( - self._aexecute(task, result), - name=f"subagent-{self.config.name}-execution", + timeout = _ExecutionTimeout( + self.config.timeout_seconds, + SubagentStatus.TIMED_OUT, + f"Execution timed out after {self.config.timeout_seconds} seconds", ) + result._execution_timeout = timeout + execution_task = None + execution_detached = False try: - done, _ = await asyncio.wait( - {execution_task}, - timeout=self.config.timeout_seconds, + execution_task = asyncio.create_task( + self._aexecute(task, result), + name=f"subagent-{self.config.name}-execution", ) - if execution_task in done: - return execution_task.result() - - # Publish the configured hard timeout without waiting for - # cancellation-resistant stream cleanup. The detached execution - # still owns its capacity slot and sandbox lease until its - # supervisor observes full teardown. - result.cancel_event.set() - result.try_set_terminal( - SubagentStatus.TIMED_OUT, - error=f"Execution timed out after {self.config.timeout_seconds} seconds", - tool_receipts=result.snapshot_tool_receipts(), - ) - execution_task.cancel() - _supervise_background_execution( - execution_id, - result, + outcome, supervised = await self._await_admitted_execution( execution_task, + result, + timeout, + execution_id=execution_id, ) - execution_task = None - return result + if supervised: + execution_detached = True + return outcome except asyncio.CancelledError: result.cancel_event.set() - if not execution_task.done(): - execution_task.cancel() - try: - await execution_task - except (asyncio.CancelledError, Exception): - # The child can fail before cancellation reaches it. Keep - # its terminal write, or publish cancellation below. - pass + if execution_task is not None: + if not execution_task.done(): + execution_task.cancel() + try: + await execution_task + except (asyncio.CancelledError, Exception): + # The child can fail before cancellation reaches it. Keep + # its terminal write, or publish cancellation below. + pass result.try_set_terminal( SubagentStatus.CANCELLED, error="Cancelled by user", @@ -2511,18 +2645,19 @@ class SubagentExecutor: return result except Exception as exc: logger.exception("[trace=%s] Subagent %s async execution failed", self.trace_id, self.config.name) - if not execution_task.done(): + if execution_task is not None and not execution_task.done(): execution_task.cancel() _supervise_background_execution( execution_id, result, execution_task, ) - execution_task = None + execution_detached = True result.try_set_terminal(SubagentStatus.FAILED, error=str(exc)) return result finally: - if execution_task is not None: + result._execution_timeout = None + if not execution_detached: _mark_background_execution_done(execution_id, result) try: diff --git a/backend/packages/harness/deerflow/tools/builtins/task_tool.py b/backend/packages/harness/deerflow/tools/builtins/task_tool.py index 41cea9019c..92ef9aab7b 100644 --- a/backend/packages/harness/deerflow/tools/builtins/task_tool.py +++ b/backend/packages/harness/deerflow/tools/builtins/task_tool.py @@ -34,7 +34,7 @@ from deerflow.runtime.user_context import resolve_runtime_user_id from deerflow.sandbox.security import LOCAL_BASH_SUBAGENT_DISABLED_MESSAGE, is_host_bash_allowed from deerflow.subagents import SubagentExecutor, get_available_subagent_names, get_subagent_config from deerflow.subagents.acceptance_checks import check_acceptance_criteria, render_acceptance_section -from deerflow.subagents.capacity import SubagentExecutionCapacity +from deerflow.subagents.capacity import SubagentExecutionCapacity, configured_subagent_queue_timeout_seconds from deerflow.subagents.config import resolve_subagent_model_name from deerflow.subagents.context_snapshot import ParentContextSnapshot from deerflow.subagents.executor import ( @@ -80,6 +80,12 @@ _UNEXPECTED_EXIT_GRACE_SECONDS = 5.0 # window so callbacks emitted during cleanup are not lost. _TERMINAL_USAGE_TAIL_POLLS = 12 +# Completion margin for the main wait. The executor's execution timeout starts +# at admission, so the main wait covers queue wait plus execution time; the +# cancellation/deferred-cleanup unwinds run after admission and stay bounded by +# execution time alone. +_POLL_COMPLETION_MARGIN_SECONDS = 60 + # Sentinel returned by ``_peek_subagent_result`` when the registry entry exists # but cannot be read (persistent status-lookup / status-object failure). _STATUS_UNREADABLE = object() @@ -306,6 +312,32 @@ async def _await_subagent_terminal(execution_id: str, max_polls: int, *, trace_i polls += 1 +def _main_wait_poll_budget(timeout_seconds: int, queue_timeout_seconds: int | None = None) -> int: + """Polls the tool waits for a queued execution and its execution. + + A subagent can wait in the capacity queue before its execution clock + starts; ``queue_timeout_seconds`` bounds that stage separately. Waiting only + ``timeout_seconds`` would report a healthy queued subagent as + ``polling_timed_out`` before it ran a turn. + + The bound comes from the injected capacity when there is one, because the + SDK runtime builds its own controller and never installs a process-wide + snapshot. Without an injected capacity the startup snapshot applies. + """ + if queue_timeout_seconds is None: + queue_timeout_seconds = configured_subagent_queue_timeout_seconds() + return int((queue_timeout_seconds + timeout_seconds + _POLL_COMPLETION_MARGIN_SECONDS) // _SUBAGENT_POLL_INTERVAL_SECONDS) + + +def _cleanup_poll_budget(timeout_seconds: int) -> int: + """Polls available to cancellation and deferred cleanup. + + These paths run after admission, so they wait for execution teardown only + and must not inherit the queue-wait allowance. + """ + return int((timeout_seconds + _POLL_COMPLETION_MARGIN_SECONDS) // _SUBAGENT_POLL_INTERVAL_SECONDS) + + async def _finalize_interrupted_subagent( runtime: Runtime, execution_id: str, @@ -1183,8 +1215,11 @@ async def task_tool( poll_count = 0 last_status = None last_message_count = 0 # Track how many AI messages we've already sent - # Polling timeout: execution timeout + 60s buffer, checked every 5s - max_poll_count = (config.timeout_seconds + 60) // 5 + # Polling timeout: queue wait + execution timeout + 60s buffer, checked every 5s + max_poll_count = _main_wait_poll_budget( + config.timeout_seconds, + getattr(explicit_capacity, "queue_timeout_seconds", None), + ) logger.info(f"[trace={trace_id}] Started background task {tool_call_id} (execution_id={execution_id}, subagent={subagent_type}, timeout={config.timeout_seconds}s, polling_limit={max_poll_count} polls)") @@ -1396,10 +1431,21 @@ async def task_tool( poll_count += 1 # Polling timeout as a safety net (in case thread pool timeout doesn't work) - # Set to execution timeout + 60s buffer, in 5s poll intervals + # Set to queue wait + execution timeout + 60s buffer, in 5s poll intervals # This catches edge cases where the background task gets stuck if poll_count > max_poll_count: - timeout_minutes = config.timeout_seconds // 60 + result = get_background_task_result(execution_id) + if result is None: + continue + # Report the window this poller actually waited: the execution + # timeout alone understates it by the whole queue allowance. + timeout_minutes = int(max_poll_count * _SUBAGENT_POLL_INTERVAL_SECONDS // 60) + message = f"Task polling timed out after {timeout_minutes} minutes. This may indicate the background task is stuck. Status: {result.status.value}" + # Use the executor's terminal write to decide the race before + # emitting an event. If it already finished, handle its result. + if not result.try_set_terminal(SubagentStatus.TIMED_OUT, error=message): + continue + request_cancel_background_task(execution_id) logger.error(f"[trace={trace_id}] Task {tool_call_id} polling timed out after {poll_count} polls (should have been caught by thread pool timeout)") _report_subagent_usage(runtime, result) usage = _summarize_usage(getattr(result, "token_usage_records", None)) @@ -1412,12 +1458,9 @@ async def task_tool( }, writer=writer, ) - # The task may still be running in the background. Signal cooperative - # cancellation and schedule deferred cleanup to remove the entry from - # _background_tasks once the background thread reaches a terminal state. - request_cancel_background_task(execution_id) - _schedule_deferred_subagent_cleanup(runtime, execution_id, trace_id, max_poll_count) - message = f"Task polling timed out after {timeout_minutes} minutes. This may indicate the background task is stuck. Status: {result.status.value}" + # Keep the entry until the background execution settles and + # deferred cleanup can report its final usage. + _schedule_deferred_subagent_cleanup(runtime, execution_id, trace_id, _cleanup_poll_budget(config.timeout_seconds)) return result_command( tool_call_id=tool_call_id, status="polling_timed_out", @@ -1440,7 +1483,7 @@ async def task_tool( f"[trace={trace_id}] Failed to request cancellation for background task {execution_id} during unwind", exc_info=True, ) - await _finalize_interrupted_subagent(runtime, execution_id, trace_id, max_poll_count) + await _finalize_interrupted_subagent(runtime, execution_id, trace_id, _cleanup_poll_budget(config.timeout_seconds)) raise except Exception: # Unexpected poller failure (emit error, status-lookup bug, writer @@ -1459,7 +1502,7 @@ async def task_tool( f"[trace={trace_id}] Failed to request cancellation for background task {execution_id} during unwind", exc_info=True, ) - await _finalize_interrupted_subagent(runtime, execution_id, trace_id, max_poll_count, grace_seconds=_UNEXPECTED_EXIT_GRACE_SECONDS) + await _finalize_interrupted_subagent(runtime, execution_id, trace_id, _cleanup_poll_budget(config.timeout_seconds), grace_seconds=_UNEXPECTED_EXIT_GRACE_SECONDS) current_task = asyncio.current_task() if current_task is not None and current_task.cancelling(): # A graph-node cancellation landed inside the grace wait and was diff --git a/backend/tests/test_subagent_capacity.py b/backend/tests/test_subagent_capacity.py index c18fd8448e..91114e3f6e 100644 --- a/backend/tests/test_subagent_capacity.py +++ b/backend/tests/test_subagent_capacity.py @@ -59,6 +59,21 @@ async def test_snapshot_reports_running_and_queued_waiters(): await asyncio.gather(queued, holder, return_exceptions=True) +def test_capacity_exposes_the_queue_bound_it_applies(): + """An injected controller reports its own bound, not the startup snapshot.""" + capacity = SubagentExecutionCapacity(SubagentRuntimeConfig(queue_timeout_seconds=42)) + + assert capacity.queue_timeout_seconds == 42 + + +def test_configured_queue_timeout_reads_startup_snapshot(monkeypatch): + """The poller derives its budget without binding the controller to a loop.""" + from deerflow.subagents import capacity as capacity_module + + monkeypatch.setattr(capacity_module, "_config", SubagentRuntimeConfig(queue_timeout_seconds=42)) + assert capacity_module.configured_subagent_queue_timeout_seconds() == 42 + + @pytest.mark.asyncio async def test_repeated_cancellation_cannot_leak_running_slot(monkeypatch): """A second cancellation during cleanup must not strand process capacity.""" diff --git a/backend/tests/test_subagent_executor.py b/backend/tests/test_subagent_executor.py index 2dfed26121..608fdb76c8 100644 --- a/backend/tests/test_subagent_executor.py +++ b/backend/tests/test_subagent_executor.py @@ -35,10 +35,11 @@ from packaging.version import Version from deerflow.agents.middlewares.summarization_middleware import DeerFlowSummarizationMiddleware from deerflow.agents.middlewares.tool_receipt_middleware import ToolReceiptMiddleware +from deerflow.config.subagent_runtime_config import SubagentRuntimeConfig from deerflow.runtime.journal import RunJournal from deerflow.sandbox.lease import SandboxLeaseManager from deerflow.skills.types import Skill -from deerflow.subagents.capacity import SubagentCapacityRejected +from deerflow.subagents.capacity import SubagentCapacityRejected, SubagentExecutionCapacity from deerflow.trace_context import request_trace_context # Module names that need to be mocked to break circular imports @@ -5008,8 +5009,8 @@ class TestCooperativeCancellation: """Test that the real timeout handler does not overwrite CANCELLED status. This exercises the actual execute_async → run_task → FuturesTimeoutError - code path in executor.py. We make execute() block so the timeout fires - deterministically, pre-set the task to CANCELLED, and verify the RUNNING + code path in executor.py. We block after admission so the execution + timeout runs, pre-set the task to CANCELLED, and verify the RUNNING guard preserves it. Uses threading.Event for synchronisation instead of wall-clock sleeps. """ @@ -5021,13 +5022,14 @@ class TestCooperativeCancellation: description="Test agent", system_prompt="You are a test agent.", max_turns=10, - timeout_seconds=0.05, # 50ms – just enough for the future to time out + timeout_seconds=0.2, # long enough for admission, short enough for the test ) # Synchronisation primitives - execute_entered = threading.Event() # signals that _aexecute() has started + execute_entered = threading.Event() # signals that admission has happened - # A blocking _aexecute() replacement so we control the timing exactly. + # Block inside the admitted execution so the timeout still fires; the + # admission clock needs the real _aexecute() to acquire its slot first. async def blocking_aexecute(task, result_holder=None): execute_entered.set() await asyncio.Event().wait() @@ -5039,14 +5041,14 @@ class TestCooperativeCancellation: trace_id="test-trace", ) - with patch.object(executor, "_aexecute", side_effect=blocking_aexecute): + with patch.object(executor, "_aexecute_admitted", side_effect=blocking_aexecute): task_id = executor.execute_async("Task") - # Wait until _aexecute() is entered on the persistent loop. - assert execute_entered.wait(timeout=3), "_aexecute() was never called" + # Wait until the admitted execution is entered on the persistent loop. + assert execute_entered.wait(timeout=3), "_aexecute_admitted() was never called" # Set CANCELLED on the result before the timeout handler runs. - # The 50ms timeout will fire while execute() is blocked. + # The 200ms timeout will fire while the admitted execution is blocked. with executor_module._background_tasks_lock: executor_module._background_tasks[task_id].status = SubagentStatus.CANCELLED executor_module._background_tasks[task_id].error = "Cancelled by user" @@ -7757,7 +7759,6 @@ class TestSubagentCancellationLifecycle: executor = classes["SubagentExecutor"](config=replace(base_config, timeout_seconds=0.2), tools=[], run_id="run", extensions=lifecycle.extensions) holder = classes["SubagentResult"](task_id="sync-timeout", trace_id="trace", status=classes["SubagentStatus"].PENDING) if shared_holder else None original_execute = executor._aexecute - original_submit = module._submit_to_isolated_loop_in_context async def initial_state(task): if stage == "setup": @@ -7777,24 +7778,9 @@ class TestSubagentCancellationLifecycle: worker_holders.append(result_holder) return await original_execute(task, result_holder) - def submit(context, factory): - future = original_submit(context, factory) - original_cancel = future.cancel - - def cancel_and_drain(): - cancelled = original_cancel() - # Force cancellation handling to finish before execute() catches - # the timeout, so a shared-holder race cannot pass by scheduling luck. - assert lifecycle.stopped.wait(timeout=5) - return cancelled - - monkeypatch.setattr(future, "cancel", cancel_and_drain) - return future - monkeypatch.setattr(executor, "_build_initial_state", initial_state) monkeypatch.setattr(executor, "_create_agent", AsyncMock(return_value=SimpleNamespace(astream=stream))) monkeypatch.setattr(executor, "_aexecute", track_worker) - monkeypatch.setattr(module, "_submit_to_isolated_loop_in_context", submit) monkeypatch.setattr(module, "build_tracing_callbacks", lambda: []) monkeypatch.setattr(module, "inject_langfuse_metadata", lambda *args, **kwargs: None) try: @@ -8047,3 +8033,468 @@ class TestSubagentCompactionIdentity: info = store.get(TaskInfo) assert info == TaskInfo(task_id="exec-1", run_id=run_id, thread_id="sub-thread", kind="subagent", parent_task_id=run_id, agent_name=base_config.name) assert (event.task_id, event.run_id, event.thread_id) == (info.task_id, info.run_id, info.thread_id) + + +class TestExecutionTimeoutStartsAtAdmission: + """Execution time is bounded separately from time spent queued for a slot. + + The execution clock must not start at delegation: the capacity controller + already bounds queue wait with ``queue_timeout_seconds``, and charging that + wait against the execution timeout ends queued subagents with ``timed_out`` + before they run a single turn. + """ + + @staticmethod + def _capacity() -> SubagentExecutionCapacity: + return SubagentExecutionCapacity( + SubagentRuntimeConfig( + max_running=1, + max_queued=4, + queue_timeout_seconds=5, + ) + ) + + @staticmethod + def _executor(classes, config, *, thread_id, capacity, stream, monkeypatch): + executor = classes["SubagentExecutor"]( + config=config, + tools=[], + thread_id=thread_id, + execution_capacity=capacity, + ) + monkeypatch.setattr(executor, "_build_initial_state", AsyncMock(return_value=({}, [], None))) + monkeypatch.setattr(executor, "_create_agent", AsyncMock(return_value=SimpleNamespace(astream=stream))) + return executor + + @pytest.mark.anyio + async def test_async_queue_wait_does_not_consume_execution_timeout(self, classes, base_config, monkeypatch): + from dataclasses import replace + + module = importlib.import_module("deerflow.subagents.executor") + monkeypatch.setattr(module, "build_tracing_callbacks", lambda: []) + monkeypatch.setattr(module, "inject_langfuse_metadata", lambda *args, **kwargs: None) + capacity = self._capacity() + holder_started, release_holder, queued_started = threading.Event(), threading.Event(), threading.Event() + + async def holding_stream(*args, **kwargs): + holder_started.set() + while not release_holder.is_set(): + await asyncio.sleep(0.01) + yield {"messages": [classes["AIMessage"](content="held")]} + + async def queued_stream(*args, **kwargs): + queued_started.set() + yield {"messages": [classes["AIMessage"](content="queued done")]} + + holder = self._executor( + classes, + replace(base_config, timeout_seconds=5), + thread_id="slot-holder", + capacity=capacity, + stream=holding_stream, + monkeypatch=monkeypatch, + ) + queued = self._executor( + classes, + replace(base_config, timeout_seconds=0.2), + thread_id="slot-waiter", + capacity=capacity, + stream=queued_stream, + monkeypatch=monkeypatch, + ) + + holder_id = holder.execute_async("hold the slot") + queued_id = queued.execute_async("wait for the slot") + holder_result = module.get_background_task_result(holder_id) + queued_result = module.get_background_task_result(queued_id) + try: + assert holder_result is not None + assert queued_result is not None + assert holder_started.wait(timeout=5), "the slot holder never started" + + # Stay queued for longer than the waiting execution's own timeout. + await asyncio.sleep(0.6) + assert queued_result.status is classes["SubagentStatus"].PENDING + assert not queued_started.is_set() + + release_holder.set() + assert queued_result.execution_done_event.wait(timeout=5), "queued execution never settled" + assert queued_started.is_set(), "queued execution never got a slot after the holder released it" + assert queued_result.status is classes["SubagentStatus"].COMPLETED + assert holder_result.execution_done_event.wait(timeout=5), "slot holder never settled" + assert holder_result.status is classes["SubagentStatus"].COMPLETED + finally: + release_holder.set() + module.request_cancel_background_task(holder_id) + module.request_cancel_background_task(queued_id) + module.force_cleanup_background_task(holder_id) + module.force_cleanup_background_task(queued_id) + + @pytest.mark.anyio + async def test_queue_timeout_still_bounds_waiting_executions(self, classes, base_config, monkeypatch): + from dataclasses import replace + + module = importlib.import_module("deerflow.subagents.executor") + monkeypatch.setattr(module, "build_tracing_callbacks", lambda: []) + monkeypatch.setattr(module, "inject_langfuse_metadata", lambda *args, **kwargs: None) + capacity = SubagentExecutionCapacity(SubagentRuntimeConfig(max_running=1, max_queued=4, queue_timeout_seconds=1)) + holder_started, release_holder, queued_started = threading.Event(), threading.Event(), threading.Event() + + async def holding_stream(*args, **kwargs): + holder_started.set() + while not release_holder.is_set(): + await asyncio.sleep(0.01) + yield {"messages": [classes["AIMessage"](content="held")]} + + async def queued_stream(*args, **kwargs): + queued_started.set() + yield {"messages": [classes["AIMessage"](content="queued done")]} + + holder = self._executor( + classes, + replace(base_config, timeout_seconds=5), + thread_id="queue-timeout-holder", + capacity=capacity, + stream=holding_stream, + monkeypatch=monkeypatch, + ) + queued = self._executor( + classes, + replace(base_config, timeout_seconds=5), + thread_id="queue-timeout-waiter", + capacity=capacity, + stream=queued_stream, + monkeypatch=monkeypatch, + ) + + holder_id = holder.execute_async("hold the slot") + queued_id = queued.execute_async("wait for the slot") + queued_result = module.get_background_task_result(queued_id) + try: + assert queued_result is not None + assert holder_started.wait(timeout=5), "the slot holder never started" + assert queued_result.execution_done_event.wait(timeout=5), "queued execution never settled" + finally: + release_holder.set() + module.request_cancel_background_task(holder_id) + module.request_cancel_background_task(queued_id) + module.force_cleanup_background_task(holder_id) + module.force_cleanup_background_task(queued_id) + + assert not queued_started.is_set() + assert queued_result.status is classes["SubagentStatus"].FAILED + assert queued_result.admission_failure is True + assert queued_result.error == "Timed out after 1s waiting for a subagent execution slot" + + @pytest.mark.anyio + async def test_execution_timeout_still_fires_after_admission(self, classes, base_config, monkeypatch): + from dataclasses import replace + + module = importlib.import_module("deerflow.subagents.executor") + monkeypatch.setattr(module, "build_tracing_callbacks", lambda: []) + monkeypatch.setattr(module, "inject_langfuse_metadata", lambda *args, **kwargs: None) + capacity = self._capacity() + entered = threading.Event() + + async def blocked_stream(*args, **kwargs): + entered.set() + await asyncio.Event().wait() + yield {} + + executor = self._executor( + classes, + replace(base_config, timeout_seconds=0.2), + thread_id="execution-timeout", + capacity=capacity, + stream=blocked_stream, + monkeypatch=monkeypatch, + ) + + execution_id = executor.execute_async("run forever") + result = module.get_background_task_result(execution_id) + try: + assert result is not None + assert entered.wait(timeout=5), "admitted execution never reached the agent" + + deadline = time.monotonic() + 5 + while not result.status.is_terminal and time.monotonic() < deadline: + time.sleep(0.01) + + assert result.status is classes["SubagentStatus"].TIMED_OUT + assert result.error == "Execution timed out after 0.2 seconds" + assert result.execution_done_event.wait(timeout=5) + finally: + module.request_cancel_background_task(execution_id) + module.force_cleanup_background_task(execution_id) + + def test_sync_queue_wait_does_not_consume_execution_timeout(self, classes, base_config, monkeypatch): + import concurrent.futures + from dataclasses import replace + + module = importlib.import_module("deerflow.subagents.executor") + monkeypatch.setattr(module, "build_tracing_callbacks", lambda: []) + monkeypatch.setattr(module, "inject_langfuse_metadata", lambda *args, **kwargs: None) + capacity = self._capacity() + holder_started, release_holder = threading.Event(), threading.Event() + + async def holding_stream(*args, **kwargs): + holder_started.set() + while not release_holder.is_set(): + await asyncio.sleep(0.01) + yield {"messages": [classes["AIMessage"](content="held")]} + + async def queued_stream(*args, **kwargs): + yield {"messages": [classes["AIMessage"](content="queued done")]} + + holder = self._executor( + classes, + replace(base_config, timeout_seconds=5), + thread_id="sync-slot-holder", + capacity=capacity, + stream=holding_stream, + monkeypatch=monkeypatch, + ) + queued = self._executor( + classes, + replace(base_config, timeout_seconds=0.2), + thread_id="sync-slot-waiter", + capacity=capacity, + stream=queued_stream, + monkeypatch=monkeypatch, + ) + + pool = concurrent.futures.ThreadPoolExecutor(max_workers=2) + try: + holder_future = pool.submit(holder.execute, "hold the slot") + assert holder_started.wait(timeout=5), "the sync slot holder never started" + + queued_future = pool.submit(queued.execute, "wait for the slot") + # Stay queued for longer than the waiting execution's own timeout. + time.sleep(0.6) + assert not queued_future.done(), "queued sync execution timed out before admission" + + release_holder.set() + queued_result = queued_future.result(timeout=5) + holder_result = holder_future.result(timeout=5) + finally: + release_holder.set() + pool.shutdown(wait=True) + + assert queued_result.status is classes["SubagentStatus"].COMPLETED + assert holder_result.status is classes["SubagentStatus"].COMPLETED + + def test_sync_backstop_uses_injected_capacity_queue_timeout(self, classes, base_config, monkeypatch): + from dataclasses import replace + + module = importlib.import_module("deerflow.subagents.executor") + monkeypatch.setattr(module, "configured_subagent_queue_timeout_seconds", lambda: 300) + capacity = SubagentExecutionCapacity(SubagentRuntimeConfig(queue_timeout_seconds=1800)) + executor = classes["SubagentExecutor"]( + config=replace(base_config, timeout_seconds=10), + tools=[], + execution_capacity=capacity, + ) + + assert executor._sync_timeout_backstop_seconds() == 1870 + + # Without an injected controller the startup snapshot applies. + global_only = classes["SubagentExecutor"](config=replace(base_config, timeout_seconds=10), tools=[]) + assert global_only._sync_timeout_backstop_seconds() == 370 + + def test_sync_backstop_fails_when_admission_never_settles(self, classes, base_config, monkeypatch): + """The outer bound still terminates a synchronous call stuck before admission.""" + from dataclasses import replace + + module = importlib.import_module("deerflow.subagents.executor") + executor = classes["SubagentExecutor"](config=replace(base_config, timeout_seconds=60), tools=[]) + + async def never_admitted(task, result_holder=None): + await asyncio.Event().wait() + + monkeypatch.setattr(executor, "_aexecute", never_admitted) + monkeypatch.setattr(executor, "_sync_timeout_backstop_seconds", lambda: 0.2) + try: + result = executor.execute("wait forever") + finally: + module._shutdown_isolated_subagent_loop() + + assert result.status is classes["SubagentStatus"].FAILED + assert result.error == "" # Preserve the synchronous TimeoutError result. + assert result.cancel_event.is_set() + + @pytest.mark.anyio + async def test_principal_revalidation_runs_inside_the_execution_timeout(self, classes, base_config, monkeypatch): + """A resolver that never returns must not hang the delegation. + + The execution clock starts at slot admission, which is before the + durable batch principal revalidation. Otherwise that await sits outside + every timeout the delegating wrapper applies. + """ + from dataclasses import replace + + module = importlib.import_module("deerflow.subagents.executor") + monkeypatch.setattr(module, "build_tracing_callbacks", lambda: []) + monkeypatch.setattr(module, "inject_langfuse_metadata", lambda *args, **kwargs: None) + resolver_entered = threading.Event() + + async def hanging_resolver(): + resolver_entered.set() + await asyncio.Event().wait() + + executor = classes["SubagentExecutor"]( + config=replace(base_config, timeout_seconds=0.2), + tools=[], + thread_id="principal-timeout", + execution_capacity=self._capacity(), + principal_resolver=hanging_resolver, + ) + + execution_id = executor.execute_async("hold in revalidation") + result = module.get_background_task_result(execution_id) + try: + assert result is not None + assert resolver_entered.wait(timeout=5), "principal revalidation never started" + + deadline = time.monotonic() + 5 + while not result.status.is_terminal and time.monotonic() < deadline: + time.sleep(0.01) + + assert result.status is classes["SubagentStatus"].TIMED_OUT + assert result.error == "Execution timed out after 0.2 seconds" + assert result.execution_done_event.wait(timeout=5) + finally: + module.request_cancel_background_task(execution_id) + module.force_cleanup_background_task(execution_id) + + @pytest.mark.anyio + async def test_admission_gap_counts_against_the_execution_timeout(self, classes, base_config, monkeypatch): + """Synchronous work after admission must not extend the execution clock. + + The admission signal is set immediately before the principal resolver + is awaited. Blocking the loop there keeps the supervisor from running + until the budget is already spent; the deadline must therefore come + from the admission timestamp, not from the supervisor's wakeup. + """ + from dataclasses import replace + + from deerflow.authz.provider import Principal + + module = importlib.import_module("deerflow.subagents.executor") + monkeypatch.setattr(module, "build_tracing_callbacks", lambda: []) + monkeypatch.setattr(module, "inject_langfuse_metadata", lambda *args, **kwargs: None) + + async def blocking_resolver(): + time.sleep(0.4) + return Principal(user_id="alice", role="user") + + async def never_reached_stream(*args, **kwargs): + yield {"messages": [classes["AIMessage"](content="should not run")]} + + executor = classes["SubagentExecutor"]( + config=replace(base_config, timeout_seconds=0.2), + tools=[], + thread_id="admission-gap", + user_id="alice", + execution_capacity=self._capacity(), + principal_resolver=blocking_resolver, + ) + monkeypatch.setattr(executor, "_build_initial_state", AsyncMock(return_value=({}, [], None))) + monkeypatch.setattr(executor, "_create_agent", AsyncMock(return_value=SimpleNamespace(astream=never_reached_stream))) + + execution_id = executor.execute_async("block after admission") + result = module.get_background_task_result(execution_id) + try: + assert result is not None + assert result.execution_done_event.wait(timeout=5) + assert result.status is classes["SubagentStatus"].TIMED_OUT + assert result.error == "Execution timed out after 0.2 seconds" + finally: + module.request_cancel_background_task(execution_id) + module.force_cleanup_background_task(execution_id) + + def test_sync_admission_gap_counts_against_the_execution_timeout(self, classes, base_config, monkeypatch): + """The synchronous wrapper uses the same admission deadline.""" + from dataclasses import replace + + from deerflow.authz.provider import Principal + + module = importlib.import_module("deerflow.subagents.executor") + monkeypatch.setattr(module, "build_tracing_callbacks", lambda: []) + monkeypatch.setattr(module, "inject_langfuse_metadata", lambda *args, **kwargs: None) + + async def blocking_resolver(): + time.sleep(0.4) + return Principal(user_id="alice", role="user") + + async def never_reached_stream(*args, **kwargs): + yield {"messages": [classes["AIMessage"](content="should not run")]} + + executor = classes["SubagentExecutor"]( + config=replace(base_config, timeout_seconds=0.2), + tools=[], + thread_id="sync-admission-gap", + user_id="alice", + execution_capacity=self._capacity(), + principal_resolver=blocking_resolver, + ) + monkeypatch.setattr(executor, "_build_initial_state", AsyncMock(return_value=({}, [], None))) + monkeypatch.setattr(executor, "_create_agent", AsyncMock(return_value=SimpleNamespace(astream=never_reached_stream))) + + result = executor.execute("block after admission") + + assert result.status is classes["SubagentStatus"].FAILED + assert result.error == "" # Preserve the synchronous timeout result. + assert result.execution_done_event.wait(timeout=5) + + @pytest.mark.parametrize("background", [False, True], ids=["sync", "background"]) + @pytest.mark.parametrize("finalization_seconds", [0.5, 1.5], ids=["within-budget", "after-deadline"]) + def test_execution_deadline_fences_success_during_finalization(self, classes, base_config, monkeypatch, background, finalization_seconds): + from dataclasses import replace + + module = importlib.import_module("deerflow.subagents.executor") + monkeypatch.setattr(module, "build_tracing_callbacks", lambda: []) + monkeypatch.setattr(module, "inject_langfuse_metadata", lambda *args, **kwargs: None) + clock = 100.0 + monkeypatch.setattr(module, "time", SimpleNamespace(monotonic=lambda: clock)) + extract = module._extract_final_result + + def finalize(*args, **kwargs): + nonlocal clock + clock += finalization_seconds + return extract(*args, **kwargs) + + async def stream(*args, **kwargs): + yield {"messages": [classes["AIMessage"](content="finished answer")]} + + monkeypatch.setattr(module, "_extract_final_result", finalize) + executor = self._executor( + classes, + replace(base_config, timeout_seconds=1), + thread_id="finalization-deadline", + capacity=self._capacity(), + stream=stream, + monkeypatch=monkeypatch, + ) + if background: + execution_id = executor.execute_async("finish at the deadline") + result = module.get_background_task_result(execution_id) + else: + execution_id = None + result = executor.execute("finish at the deadline") + + try: + assert result is not None + assert result.execution_done_event.wait(timeout=5) + assert clock == 100 + finalization_seconds + if finalization_seconds < 1: + assert result.status is classes["SubagentStatus"].COMPLETED + assert result.result == "finished answer" + else: + expected = classes["SubagentStatus"].TIMED_OUT if background else classes["SubagentStatus"].FAILED + assert result.status is expected + assert result.result is None + assert result.error == ("Execution timed out after 1 seconds" if background else "") + finally: + if execution_id is not None: + module.request_cancel_background_task(execution_id) + module.force_cleanup_background_task(execution_id) diff --git a/backend/tests/test_subagent_timeout_config.py b/backend/tests/test_subagent_timeout_config.py index cb7f39c08a..825ce20590 100644 --- a/backend/tests/test_subagent_timeout_config.py +++ b/backend/tests/test_subagent_timeout_config.py @@ -19,7 +19,6 @@ from deerflow.config.subagents_config import ( get_subagents_app_config, load_subagents_config_from_dict, ) -from deerflow.subagents.config import SubagentConfig # --------------------------------------------------------------------------- # Helpers @@ -619,37 +618,36 @@ class TestRegistryListSubagents: class TestPollingTimeoutCalculation: - """Verify the formula (timeout_seconds + 60) // 5 is correct for various inputs.""" + """Verify the main-wait budget also covers the queue wait before admission. + + The execution timeout starts at admission, and the capacity controller + bounds queue wait separately; the poller must allow for both stages or it + reports ``polling_timed_out`` for an execution that is still queued. + """ @pytest.mark.parametrize( "timeout_seconds, expected_max_polls", [ - (900, 192), # default 15 min → (900+60)//5 = 192 - (300, 72), # 5 min → (300+60)//5 = 72 - (1800, 372), # 30 min → (1800+60)//5 = 372 - (60, 24), # 1 min → (60+60)//5 = 24 - (1, 12), # minimum → (1+60)//5 = 12 + (900, 252), # (300+900+60)//5 = 252 + (300, 132), # (300+300+60)//5 = 132 + (1800, 432), # (300+1800+60)//5 = 432 + (60, 84), # (300+60+60)//5 = 84 + (1, 72), # minimum → (300+1+60)//5 = 72 ], ) - def test_polling_timeout_formula(self, timeout_seconds: int, expected_max_polls: int): - dummy_config = SubagentConfig( - name="test", - description="test", - system_prompt="test", - timeout_seconds=timeout_seconds, - ) - max_poll_count = (dummy_config.timeout_seconds + 60) // 5 - assert max_poll_count == expected_max_polls + def test_polling_timeout_formula(self, timeout_seconds: int, expected_max_polls: int, monkeypatch): + import importlib - def test_polling_timeout_exceeds_execution_timeout(self): - """Safety-net polling window must always be longer than the execution timeout.""" + task_tool = importlib.import_module("deerflow.tools.builtins.task_tool") + monkeypatch.setattr(task_tool, "configured_subagent_queue_timeout_seconds", lambda: 300) + assert task_tool._main_wait_poll_budget(timeout_seconds) == expected_max_polls + + def test_polling_timeout_exceeds_execution_and_queue_timeout(self, monkeypatch): + """The safety-net window must outlast queue wait plus execution time.""" + import importlib + + task_tool = importlib.import_module("deerflow.tools.builtins.task_tool") + monkeypatch.setattr(task_tool, "configured_subagent_queue_timeout_seconds", lambda: 300) for timeout_seconds in [60, 300, 900, 1800]: - dummy_config = SubagentConfig( - name="test", - description="test", - system_prompt="test", - timeout_seconds=timeout_seconds, - ) - max_poll_count = (dummy_config.timeout_seconds + 60) // 5 - polling_window_seconds = max_poll_count * 5 - assert polling_window_seconds > timeout_seconds + polling_window_seconds = task_tool._main_wait_poll_budget(timeout_seconds) * 5 + assert polling_window_seconds > 300 + timeout_seconds diff --git a/backend/tests/test_task_tool_core_logic.py b/backend/tests/test_task_tool_core_logic.py index 14c4d39eb6..0518af698b 100644 --- a/backend/tests/test_task_tool_core_logic.py +++ b/backend/tests/test_task_tool_core_logic.py @@ -137,6 +137,15 @@ class FakeSubagentStatus(Enum): TIMED_OUT = "timed_out" +class FakeSubagentResult(SimpleNamespace): + def try_set_terminal(self, status, *, error): + if self.status not in {FakeSubagentStatus.PENDING, FakeSubagentStatus.RUNNING}: + return False + self.error = error + self.status = status + return True + + def _make_runtime(*, app_config=None) -> SimpleNamespace: # Minimal ToolRuntime-like object; task_tool only reads these three attributes. context = {"thread_id": "thread-1"} @@ -176,8 +185,8 @@ def _make_result( token_usage_records: list[dict] | None = None, tool_receipts: list[dict] | None = None, bash_executions: list[dict] | None = None, -) -> SimpleNamespace: - return SimpleNamespace( +) -> FakeSubagentResult: + return FakeSubagentResult( status=status, ai_messages=ai_messages or [], result=result, @@ -560,6 +569,59 @@ def test_bound_task_tool_forwards_explicit_execution_capacity(monkeypatch): assert captured["executor_kwargs"]["app_config"] is app_config +def test_bound_task_tool_sizes_poll_budget_from_its_capacity(monkeypatch): + """The poller waits on the injected controller, so it uses that bound. + + The SDK runtime builds its own capacity and never installs a process-wide + snapshot; reading the startup bound here under-budgets the wait and reports + a healthy queued subagent as ``polling_timed_out``. + """ + runtime = _make_runtime() + config = _make_subagent_config() + capacity = SubagentExecutionCapacity(SubagentRuntimeConfig(queue_timeout_seconds=1800)) + budget_calls = [] + + def fake_budget(timeout_seconds, queue_timeout_seconds=None): + budget_calls.append((timeout_seconds, queue_timeout_seconds)) + return 1 + + class DummyExecutor: + def __init__(self, **kwargs): + pass + + def execute_async(self, prompt, task_id=None): + return task_id or "generated-task-id" + + monkeypatch.setattr(task_tool_module, "_main_wait_poll_budget", fake_budget) + monkeypatch.setattr(task_tool_module, "SubagentStatus", FakeSubagentStatus) + monkeypatch.setattr(task_tool_module, "SubagentExecutor", DummyExecutor) + monkeypatch.setattr(task_tool_module, "get_available_subagent_names", lambda **_kwargs: ["general-purpose"]) + monkeypatch.setattr(task_tool_module, "get_subagent_config", lambda _name, **_kwargs: config) + monkeypatch.setattr( + task_tool_module, + "get_background_task_result", + lambda _: _make_result(FakeSubagentStatus.COMPLETED, result="done"), + ) + monkeypatch.setattr(task_tool_module, "get_stream_writer", lambda: lambda _event: None) + monkeypatch.setattr(task_tool_module.asyncio, "sleep", _no_sleep) + monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: []) + + bound_tool = task_tool_module.bind_task_tool(capacity) + coroutine = getattr(bound_tool, "coroutine", None) + assert coroutine is not None + asyncio.run( + coroutine( + runtime=runtime, + description="test", + prompt="p", + subagent_type="general-purpose", + tool_call_id="tc-capacity-budget", + ) + ) + + assert budget_calls == [(config.timeout_seconds, 1800)] + + def test_bound_task_tool_sync_path_uses_the_explicit_capacity(monkeypatch): """Sync invocation of the bound copy must not bypass the explicit capacity. @@ -1587,9 +1649,72 @@ def test_task_tool_surfaces_stop_reason_for_capped_run(monkeypatch): assert events[-1]["type"] == "task_completed" +def test_main_wait_poll_budget_includes_queue_wait(monkeypatch): + """Queue wait is bounded separately from execution; the poller allows for both.""" + monkeypatch.setattr(task_tool_module, "configured_subagent_queue_timeout_seconds", lambda: 300) + + assert task_tool_module._main_wait_poll_budget(900) == 252 + assert task_tool_module._main_wait_poll_budget(1) == 72 + # An injected controller's bound wins over the process-wide snapshot. + assert task_tool_module._main_wait_poll_budget(900, 1800) == 552 + + +def test_cleanup_poll_budget_stays_execution_only(monkeypatch): + """Cancellation and deferred cleanup must not inherit the queue-wait allowance.""" + monkeypatch.setattr(task_tool_module, "configured_subagent_queue_timeout_seconds", lambda: 300) + + assert task_tool_module._cleanup_poll_budget(900) == 192 + assert task_tool_module._cleanup_poll_budget(1) == 12 + + +def test_pending_polls_do_not_exhaust_the_main_wait_budget(monkeypatch): + """A queued (PENDING) subagent may outlive its execution timeout and still run.""" + config = _make_subagent_config() + config.timeout_seconds = 1 + old_budget = (1 + 60) // 5 # 12 polls before the queue allowance + polls = 0 + events = [] + + class DummyExecutor: + def __init__(self, **kwargs): + pass + + def execute_async(self, prompt, task_id=None): + return task_id + + def status_lookup(_execution_id): + nonlocal polls + polls += 1 + if polls <= old_budget + 4: + return _make_result(FakeSubagentStatus.PENDING, ai_messages=[]) + return _make_result(FakeSubagentStatus.COMPLETED, result="done") + + monkeypatch.setattr(task_tool_module, "SubagentStatus", FakeSubagentStatus) + monkeypatch.setattr(task_tool_module, "SubagentExecutor", DummyExecutor) + monkeypatch.setattr(task_tool_module, "get_subagent_config", lambda _name, **_kwargs: config) + monkeypatch.setattr(task_tool_module, "get_background_task_result", status_lookup) + monkeypatch.setattr(task_tool_module, "get_stream_writer", lambda: events.append) + monkeypatch.setattr(task_tool_module.asyncio, "sleep", _no_sleep) + monkeypatch.setattr(task_tool_module, "cleanup_background_task", lambda _task_id: None) + monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: []) + + output = _run_task_tool( + runtime=_make_runtime(), + description="执行任务", + prompt="wait in the queue", + subagent_type="general-purpose", + tool_call_id="tc-pending-budget", + ) + + message = _task_tool_message(output) + assert polls > old_budget, "test setup did not outlast the old poll budget" + assert message.additional_kwargs[SUBAGENT_STATUS_KEY] == "completed" + assert message.content == "Task Succeeded. Result: done" + + def test_task_tool_polling_safety_timeout(monkeypatch): config = _make_subagent_config() - # Keep max_poll_count small for test speed: (1 + 60) // 5 = 12 + # Keep the main-wait budget small for test speed: (300 + 1 + 60) // 5 = 72 config.timeout_seconds = 1 events = [] @@ -1632,7 +1757,7 @@ def test_task_tool_polling_safety_timeout(monkeypatch): message = _task_tool_message(output) assert isinstance(message.content, str) - assert message.content.startswith("Task polling timed out after 0 minutes") + assert message.content.startswith("Task polling timed out after 6 minutes") assert message.additional_kwargs[SUBAGENT_STATUS_KEY] == "polling_timed_out" assert message.additional_kwargs[SUBAGENT_ERROR_KEY] == message.content assert message.additional_kwargs[SUBAGENT_TOOL_RECEIPTS_KEY] == receipts @@ -1640,6 +1765,75 @@ def test_task_tool_polling_safety_timeout(monkeypatch): assert events[-1]["type"] == "task_timed_out" +@pytest.mark.parametrize("completion_point", ["final_sleep", "timeout_event"]) +def test_polling_timeout_races_with_completion(monkeypatch, completion_point): + """Completion and polling timeout compete before emitting a terminal event.""" + config = _make_subagent_config() + config.timeout_seconds = 1 + events = [] + cancel_requests = [] + cancel_requests_at_emit = [] + poll_sleeps = 0 + holder = _make_result(FakeSubagentStatus.RUNNING) + + monkeypatch.setattr(task_tool_module, "configured_subagent_queue_timeout_seconds", lambda: 300) + budget = task_tool_module._main_wait_poll_budget(config.timeout_seconds) + + def finish(): + if holder.try_set_terminal(FakeSubagentStatus.COMPLETED, error=None): + holder.result = "done" + + async def poll_sleep(seconds): + nonlocal poll_sleeps + if seconds == 5: + poll_sleeps += 1 + if poll_sleeps == budget + 1 and completion_point == "final_sleep": + finish() + + async def emit_event(event, **_kwargs): + if event["type"] == "task_timed_out" and completion_point == "timeout_event": + cancel_requests_at_emit.extend(cancel_requests) + finish() + events.append(event) + + monkeypatch.setattr(task_tool_module, "SubagentStatus", FakeSubagentStatus) + monkeypatch.setattr( + task_tool_module, + "SubagentExecutor", + type("DummyExecutor", (), {"__init__": lambda self, **kwargs: None, "execute_async": lambda self, prompt, task_id=None: task_id}), + ) + monkeypatch.setattr(task_tool_module, "get_subagent_config", lambda _name, **_kwargs: config) + monkeypatch.setattr(task_tool_module, "get_background_task_result", lambda _: holder) + monkeypatch.setattr(task_tool_module, "get_stream_writer", lambda: events.append) + monkeypatch.setattr(task_tool_module, "aemit_custom_event", emit_event) + monkeypatch.setattr(task_tool_module, "request_cancel_background_task", cancel_requests.append) + monkeypatch.setattr(task_tool_module, "_schedule_deferred_subagent_cleanup", MagicMock()) + monkeypatch.setattr(task_tool_module.asyncio, "sleep", poll_sleep) + monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: []) + + output = _run_task_tool( + runtime=_make_runtime(), + description="finish at the polling boundary", + prompt="complete at the boundary", + subagent_type="general-purpose", + tool_call_id="tc-poll-timeout-race", + ) + + message = _task_tool_message(output) + assert poll_sleeps == budget + 1 + if completion_point == "final_sleep": + assert message.additional_kwargs[SUBAGENT_STATUS_KEY] == "completed" + assert message.content == "Task Succeeded. Result: done" + assert events[-1]["type"] == "task_completed" + assert cancel_requests == [] + else: + assert holder.status is FakeSubagentStatus.TIMED_OUT + assert message.additional_kwargs[SUBAGENT_STATUS_KEY] == "polling_timed_out" + assert events[-1]["type"] == "task_timed_out" + assert cancel_requests == ["tc-poll-timeout-race"] + assert cancel_requests_at_emit == cancel_requests + + def test_cleanup_called_on_completed(monkeypatch): """Verify cleanup_background_task is called when task completes.""" config = _make_subagent_config() @@ -1790,7 +1984,7 @@ def test_cleanup_not_called_on_polling_safety_timeout(monkeypatch): cooperative cancellation is requested and a deferred cleanup is scheduled. """ config = _make_subagent_config() - # Keep max_poll_count small for test speed: (1 + 60) // 5 = 12 + # Keep the main-wait budget small for test speed: (300 + 1 + 60) // 5 = 72 config.timeout_seconds = 1 events = [] cleanup_calls = [] @@ -1844,7 +2038,7 @@ def test_cleanup_not_called_on_polling_safety_timeout(monkeypatch): message = _task_tool_message(output) assert isinstance(message.content, str) - assert message.content.startswith("Task polling timed out after 0 minutes") + assert message.content.startswith("Task polling timed out after 6 minutes") # cleanup_background_task must NOT be called directly (task is still RUNNING) assert cleanup_calls == [] # cooperative cancellation must be requested @@ -1853,6 +2047,49 @@ def test_cleanup_not_called_on_polling_safety_timeout(monkeypatch): assert len(scheduled_cleanups) == 1 +def test_polling_timeout_schedules_cleanup_without_queue_allowance(monkeypatch): + """Deferred cleanup starts after admission, so it gets the execution-only budget.""" + config = _make_subagent_config() + config.timeout_seconds = 1 + captured_budgets = [] + + monkeypatch.setattr(task_tool_module, "SubagentStatus", FakeSubagentStatus) + monkeypatch.setattr( + task_tool_module, + "SubagentExecutor", + type("DummyExecutor", (), {"__init__": lambda self, **kwargs: None, "execute_async": lambda self, prompt, task_id=None: task_id}), + ) + monkeypatch.setattr(task_tool_module, "get_subagent_config", lambda _name, **_kwargs: config) + monkeypatch.setattr( + task_tool_module, + "get_background_task_result", + lambda _: _make_result(FakeSubagentStatus.RUNNING, ai_messages=[]), + ) + monkeypatch.setattr(task_tool_module, "get_stream_writer", lambda: lambda _event: None) + monkeypatch.setattr(task_tool_module.asyncio, "sleep", _no_sleep) + monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: []) + monkeypatch.setattr(task_tool_module, "_cleanup_poll_budget", lambda timeout_seconds: 7) + monkeypatch.setattr( + task_tool_module, + "_schedule_deferred_subagent_cleanup", + lambda runtime, execution_id, trace_id, max_polls: captured_budgets.append(max_polls), + ) + monkeypatch.setattr(task_tool_module, "request_cancel_background_task", lambda _task_id: None) + monkeypatch.setattr(task_tool_module, "_report_subagent_usage", lambda *args, **kwargs: None) + + output = _run_task_tool( + runtime=_make_runtime(), + description="执行任务", + prompt="never finish", + subagent_type="general-purpose", + tool_call_id="tc-cleanup-budget", + ) + + message = _task_tool_message(output) + assert message.additional_kwargs[SUBAGENT_STATUS_KEY] == "polling_timed_out" + assert captured_budgets == [7] + + def test_cleanup_scheduled_on_cancellation(monkeypatch): """Verify cancellation handler synchronously cleans up after shielded wait.""" config = _make_subagent_config() @@ -2619,14 +2856,11 @@ async def test_unexpected_error_grace_wait_cancellation_is_honored(monkeypatch): instead of an interrupted run.""" config = _make_subagent_config() cancel_calls: list[str] = [] - emit_calls = 0 unwind_entered = asyncio.Event() execution_id = "exec-grace-cancel" async def fail_on_status_emit(event, *, writer=None): - nonlocal emit_calls - emit_calls += 1 - if emit_calls >= 2: + if event["type"] == "task_running": raise RuntimeError("status emit boom") return None @@ -2647,7 +2881,7 @@ async def test_unexpected_error_grace_wait_cancellation_is_honored(monkeypatch): type("DummyExecutor", (), {"__init__": lambda self, **kwargs: None, "execute_async": lambda self, prompt, task_id=None: execution_id}), ) monkeypatch.setattr(task_tool_module, "get_subagent_config", lambda _name, **_kwargs: config) - monkeypatch.setattr(task_tool_module, "get_background_task_result", lambda _: _make_result(FakeSubagentStatus.RUNNING, ai_messages=[])) + monkeypatch.setattr(task_tool_module, "get_background_task_result", lambda _: _make_result(FakeSubagentStatus.RUNNING, ai_messages=[{"content": "working"}])) monkeypatch.setattr(task_tool_module, "get_stream_writer", lambda: lambda _event: None) monkeypatch.setattr(task_tool_module, "aemit_custom_event", fail_on_status_emit) monkeypatch.setattr(task_tool_module, "request_cancel_background_task", lambda execution_id_arg: cancel_calls.append(execution_id_arg)) diff --git a/frontend/src/content/en/harness/subagents/limits.mdx b/frontend/src/content/en/harness/subagents/limits.mdx index f69764cc81..5394333c83 100644 --- a/frontend/src/content/en/harness/subagents/limits.mdx +++ b/frontend/src/content/en/harness/subagents/limits.mdx @@ -16,15 +16,15 @@ A subagent runs its own agent loop, so it needs the same backstops the Lead Agen | Per-response concurrency | request context `max_concurrent_subagents` | `subagent_runtime.max_running` (3) | 1 to 64, capped by `subagent_runtime.max_running` | Excess `task` calls are dropped and only logged | | Per-run total | `subagents.max_total_per_run`; request context `max_total_subagents` overrides it | 6 | 1 to 50 | Excess calls are dropped. If the total was already used up before the response, `[SUBAGENT LIMIT REACHED] ...` is appended to the assistant message and the run's `stop_reason` becomes `subagent_limit_capped`; a response that only crosses the cap is trimmed with a log line | | Turns | `subagents.max_turns` (built-ins only), `subagents.agents..max_turns` | general-purpose 150, bash 60, custom 50 | at least 1 | Partial result kept and marked `turn_capped`; `failed` when no usable text exists | -| Timeout | `subagents.timeout_seconds` (built-ins only), `subagents.agents..timeout_seconds` | built-ins 1800 s, custom and managed 900 s | at least 1 | Status `timed_out` | -| Polling attempts | Derived from the timeout: `(timeout_seconds + 60) / 5` polls, every 5 seconds | follows the timeout | | Status `polling_timed_out`; the runtime requests cancellation and schedules deferred cleanup | +| Timeout | `subagents.timeout_seconds` (built-ins only), `subagents.agents..timeout_seconds` | built-ins 1800 s, custom and managed 900 s | at least 1 | Status `timed_out`; the execution clock starts when a capacity slot is granted | +| Polling attempts | Derived from both waits: `(queue_timeout_seconds + timeout_seconds + 60) / 5` polls, every 5 seconds | follows the timeout | | Status `polling_timed_out`; the runtime requests cancellation and schedules deferred cleanup | | Token budget | `subagents.token_budget`, `subagents.agents..token_budget` | enabled; `max_tokens` 2,000,000, or 1,000,000 when summarization is on; `warn_threshold` 0.7 | `max_tokens` at least 1000 | The in-flight turn is capped and forced to finish: `completed` + `token_capped` | | Loop detection | `loop_detection` (shared with the Lead Agent) | enabled; `warn_threshold` 3, `hard_limit` 5, `window_size` 20; frequency metrics at 30 and 50 calls | | Identical no-progress calls can produce `completed` + `loop_capped`; frequency thresholds only log metrics | | Summarization | `summarization` (shared with the Lead Agent) | example config: enabled, trigger at 32,000 tokens, keep the last 10 messages | | System prompt and latest user message survive; the summary goes into `summary_text` and is re-injected every call | | Process-wide capacity | `subagent_runtime.max_running` | 3 | 1 to 64 | When full, queue or reject per `admission_policy` | | Queue bound | `subagent_runtime.max_queued` | 64 | 0 to 10,000 | Rejected when the queue is full: `Subagent execution capacity is full (3 running, 64 queued)` | | Admission policy | `subagent_runtime.admission_policy` | `queue` | `queue` / `reject` | With `reject`, a full slot set fails immediately | -| Queue timeout | `subagent_runtime.queue_timeout_seconds` | 300 | 1 to 86,400 | `Timed out after 300s waiting for a subagent execution slot`, status `failed` | +| Queue timeout | `subagent_runtime.queue_timeout_seconds` | 300 | 1 to 86,400 | `Timed out after 300s waiting for a subagent execution slot`, status `failed`; this wait does not consume the execution timeout | | AIO shell sessions | `sandbox.environment.MAX_SHELL_SESSIONS` | image default 10; auto-set to `max_running + 1` when needed | not below `max_running + 1` | Startup error when too low; see [Sandbox and Isolation](/docs/harness/subagents/sandbox) | The four `subagent_runtime` fields are frozen at Gateway startup and need a restart to change. They bound ordinary `task` calls and durable batches alike. Queued delegations wait asynchronously without holding an execution thread. A capacity rejection or queue timeout becomes a `failed` result for an ordinary `task`; durable batch items are requeued instead. @@ -56,7 +56,7 @@ Nodes per turn is the number of `before_model` / `after_model` hooks implemented When the turns run out the executor catches `GraphRecursionError`, keeps the last assistant text as a partial result, and marks it `turn_capped`. -The timeout is wall-clock. Once it elapses the subagent is cancelled with status `timed_out`. Turns and timeout are independent axes: when you raise `max_turns`, usually raise `timeout_seconds` too, or the failure merely moves from turns to timeout. +The execution timeout starts when the capacity controller grants a slot and includes result finalization. Queue wait has its own limit, `queue_timeout_seconds`. Once the execution timeout elapses, the subagent reports `timed_out` even if it was about to publish a successful result. Turns and timeout are independent axes: when you raise `max_turns`, usually raise `timeout_seconds` too, or the failure merely moves from turns to timeout. ## Runaway guards diff --git a/frontend/src/content/en/harness/subagents/results.mdx b/frontend/src/content/en/harness/subagents/results.mdx index 13f92611a7..7ec2fb78d3 100644 --- a/frontend/src/content/en/harness/subagents/results.mdx +++ b/frontend/src/content/en/harness/subagents/results.mdx @@ -16,7 +16,7 @@ A subagent's report is its **self-report**. DeerFlow layers three kinds of check | `completed` | The subgraph ended normally | Completed | `Task Succeeded. Result:` | | `failed` | The model call failed after retries, capacity was rejected, or a runtime error occurred | Failed | `Task failed.` or `Task failed (capped: