Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(swarm): thread cancel_run() into the in-flight worker

Lanre Shittucb6ec6a58180
diff --git a/agent/src/swarm/models.py b/agent/src/swarm/models.py
index c56bd40f0..4e1205e8d 100644
--- a/agent/src/swarm/models.py
+++ b/agent/src/swarm/models.py
@@ -157,6 +157,10 @@ class WorkerStatus(str, Enum):
fabricated/mock numbers, unparsed tool markup, or a data agent that
made no tool call and wrote no report). It must never be folded into
``completed`` (see P01/P03).
+
+ ``cancelled`` mirrors ``TaskStatus.cancelled``: the worker stopped
+ because ``cancel_run()`` was signalled, not because it failed. It must
+ never be retried (see ``SwarmRuntime._run_worker_with_retries``).
"""
completed = "completed"
@@ -164,6 +168,7 @@ class WorkerStatus(str, Enum):
timeout = "timeout"
token_limit = "token_limit"
incomplete = "incomplete"
+ cancelled = "cancelled"
class SwarmAgentSpec(BaseModel):
diff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.py
index 21c7593be..123d369a9 100644
--- a/agent/src/swarm/runtime.py
+++ b/agent/src/swarm/runtime.py
@@ -919,6 +919,7 @@ class SwarmRuntime:
run_id=run.id,
include_shell_tools=include_shell_tools,
grounding_block=grounding_block,
+ cancel_event=cancel_event,
)
futures[future] = tid
per_task_budget = agent_spec.timeout_seconds * (agent_spec.max_retries + 1)
@@ -977,6 +978,7 @@ class SwarmRuntime:
run_id: str,
include_shell_tools: bool = False,
grounding_block: str = "",
+ cancel_event: threading.Event | None = None,
) -> WorkerResult:
"""Run a worker with automatic retry on failure.
@@ -996,6 +998,10 @@ class SwarmRuntime:
grounding_block: Pre-rendered "Ground Truth" markdown spliced
into the worker's system prompt. Empty string when no
symbols were extracted from user_vars.
+ cancel_event: Optional cancellation signal from cancel_run().
+ Forwarded to run_worker() so a signalled cancellation reaches
+ an already-dispatched worker. A "cancelled" result is never
+ retried (see the status check below).
Returns:
WorkerResult from the last attempt.
@@ -1044,6 +1050,7 @@ class SwarmRuntime:
include_shell_tools=include_shell_tools,
grounding_block=grounding_block,
agent_config=self._agent_config,
+ cancel_event=cancel_event,
)
cumulative_input_tokens += result.input_tokens
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index 6fe8140bc..59329d8de 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import json
import logging
import shutil
+import threading
import time
from datetime import datetime, timezone
from pathlib import Path
@@ -416,6 +417,7 @@ def run_worker(
include_shell_tools: bool = False,
grounding_block: str = "",
agent_config: AgentConfig | None = None,
+ cancel_event: threading.Event | None = None,
) -> WorkerResult:
"""Run one worker task, releasing the per-task LLM client on exit.
@@ -441,6 +443,13 @@ def run_worker(
consumed by :func:`build_swarm_registry` to merge remote MCP
tools with the local-tool pool before applying the agent's
whitelist. ``None`` preserves the prior local-only behavior.
+ cancel_event: Optional cancellation signal from
+ :meth:`SwarmRuntime.cancel_run`. Checked at the top of each
+ ReAct iteration and passed into the LLM stream as
+ ``should_cancel``, mirroring ``AgentLoop``'s cooperative
+ cancellation contract: an in-flight LLM stream stops promptly
+ and that turn's tool calls are skipped; a tool call already
+ executing is not interrupted.
Returns:
WorkerResult with status, summary, artifacts, and iteration count.
@@ -458,6 +467,7 @@ def run_worker(
include_shell_tools=include_shell_tools,
grounding_block=grounding_block,
agent_config=agent_config,
+ cancel_event=cancel_event,
)
finally:
llm.close()
@@ -475,6 +485,7 @@ def _run_worker_impl(
agent_config: AgentConfig | None = None,
*,
llm: ChatLLM,
+ cancel_event: threading.Event | None = None,
) -> WorkerResult:
"""Execute a single worker task using a lightweight ReAct loop.
@@ -504,6 +515,13 @@ def _run_worker_impl(
consumed by :func:`build_swarm_registry` to merge remote MCP
tools with the local-tool pool before applying the agent's
whitelist. ``None`` preserves the prior local-only behavior.
+ cancel_event: Optional cancellation signal from
+ :meth:`SwarmRuntime.cancel_run`. Checked at the top of each
+ ReAct iteration and passed into the LLM stream as
+ ``should_cancel``, mirroring ``AgentLoop``'s cooperative
+ cancellation contract: an in-flight LLM stream stops promptly
+ and that turn's tool calls are skipped; a tool call already
+ executing is not interrupted.
Returns:
WorkerResult with status, summary, artifacts, and iteration count.
@@ -602,6 +620,26 @@ def _run_worker_impl(
),
)
+ # Check cancellation — before dispatching this iteration's LLM call,
+ # so a cancel signalled between iterations never starts new work.
+ if cancel_event is not None and cancel_event.is_set():
+ cancelled_summary = last_assistant_content or f"Cancelled after {iteration} iterations"
+ summary = _resolve_summary(artifact_dir, cancelled_summary)
+ _emit(event_callback, "worker_cancelled", agent_id, task_id, {"iterations": iteration})
+ _write_summary(artifact_dir, summary)
+ _persist_messages(artifact_dir, messages)
+ return WorkerResult(
+ status="cancelled",
+ summary=summary,
+ artifact_paths=_collect_artifacts(artifact_dir),
+ iterations=iteration,
+ input_tokens=total_input_tokens,
+ output_tokens=total_output_tokens,
+ content_filter_warnings=compute_content_filter_warnings(
+ content_filter_count, iteration + 1,
+ ),
+ )
+
# Check token estimate
token_estimate = len(json.dumps(messages, ensure_ascii=False)) // 4
if token_estimate > _MAX_TOKEN_ESTIMATE:
@@ -686,6 +724,9 @@ def _run_worker_impl(
ProviderStreamError: When provider streaming fails.
"""
remaining_timeout = max(10, int(timeout - (time.monotonic() - t0)))
+ stream_kwargs: dict[str, Any] = {}
+ if cancel_event is not None:
+ stream_kwargs["should_cancel"] = cancel_event.is_set
with HeartbeatTimer(
tool_name=f"llm:{agent_spec.model_name or 'default'}",
interval=_HEARTBEAT_INTERVAL_S,
@@ -696,6 +737,7 @@ def _run_worker_impl(
tools=tool_defs,
timeout=remaining_timeout,
on_text_chunk=_on_text_chunk,
+ **stream_kwargs,
)
# A transient mid-stream hiccup (connection reset) used to be
@@ -720,6 +762,27 @@ def _run_worker_impl(
)
time.sleep(_STREAM_RETRY_DELAY_S)
response = _stream_once()
+
+ # Cancelled mid-stream: discard this turn's partial response and
+ # stop now, without executing any of its tool calls — mirrors
+ # AgentLoop's contract for the identical should_cancel signal.
+ if cancel_event is not None and cancel_event.is_set():
+ cancelled_summary = last_assistant_content or f"Cancelled after {iteration} iterations"
+ summary = _resolve_summary(artifact_dir, cancelled_summary)
+ _emit(event_callback, "worker_cancelled", agent_id, task_id, {"iterations": iteration})
+ _write_summary(artifact_dir, summary)
+ _persist_messages(artifact_dir, messages)
+ return WorkerResult(
+ status="cancelled",
+ summary=summary,
+ artifact_paths=_collect_artifacts(artifact_dir),
+ iterations=iteration,
+ input_tokens=total_input_tokens,
+ output_tokens=total_output_tokens,
+ content_filter_warnings=compute_content_filter_warnings(
+ content_filter_count, iteration + 1,
+ ),
+ )
except Exception as exc:
error_msg = f"LLM call failed at iteration {iteration}: {exc}"
logger.warning(error_msg)
diff --git a/agent/tests/test_swarm_cancel_mid_flight_worker.py b/agent/tests/test_swarm_cancel_mid_flight_worker.py
new file mode 100644
index 000000000..23cb9a106
--- /dev/null
+++ b/agent/tests/test_swarm_cancel_mid_flight_worker.py
@@ -0,0 +1,89 @@
+"""Regression: cancel_run() must stop an already-dispatched worker promptly,
+not just skip layers that have not started yet.
+
+Pre-fix: cancel_event was threaded from cancel_run() into _execute_run and
+_execute_layer, and polled between layers, but was never passed into
+_run_worker_with_retries or run_worker. A worker already running when
+cancel_run() fired ran to completion untouched, exactly the gap AgentLoop's
+should_cancel mechanism (agent/src/agent/loop.py) already closed for the
+main, non-swarm agent loop.
+
+Post-fix: cancel_event reaches run_worker(), is passed to
+ChatLLM.stream_chat() as should_cancel (interrupting an in-flight LLM
+stream), and is checked at the top of each ReAct iteration and right after
+the stream returns, mirroring AgentLoop's cooperative-cancellation
+contract: an in-flight stream stops promptly and that turn's tool calls
+are skipped, but a tool call already executing is not interrupted.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from pathlib import Path
+
+import src.swarm.runtime as rt
+from src.swarm.models import SwarmAgentSpec, SwarmRun, SwarmTask, WorkerResult
+from src.swarm.store import SwarmStore
+
+
+def _make_run(tmp_path: Path):
+ store = SwarmStore(base_dir=tmp_path)
+ runtime = rt.SwarmRuntime(store=store)
+ agents = [SwarmAgentSpec(id="a", role="x", system_prompt="x", max_retries=0)]
+ tasks = [SwarmTask(id="t1", agent_id="a", prompt_template="do x")]
+ run = SwarmRun(
+ id="r-cancel",
+ preset_name="demo",
+ created_at="2026-05-27T18:30:56+00:00",
+ agents=agents,
+ tasks=tasks,
+ )
+ store.create_run(run)
+ return store, runtime, run
+
+
+def test_cancel_mid_flight_worker_stops_promptly(tmp_path, monkeypatch):
+ def slow_worker(agent_spec, task, **kwargs):
+ cancel_event = kwargs.get("cancel_event")
+ for _ in range(150):
+ if cancel_event is not None and cancel_event.is_set():
+ return WorkerResult(status="cancelled", summary="cancelled")
+ time.sleep(0.01)
+ return WorkerResult(status="completed", summary="done")
+
+ monkeypatch.setattr(rt, "run_worker", slow_worker)
+ store, runtime, run = _make_run(tmp_path)
+ cancel_event = threading.Event()
+
+ def _cancel_soon():
+ time.sleep(0.1)
+ cancel_event.set()
+
+ threading.Thread(target=_cancel_soon).start()
+ t0 = time.monotonic()
+ runtime._execute_run(run, cancel_event)
+ elapsed = time.monotonic() - t0
+
+ assert elapsed < 0.5, (
+ f"cancel_run() did not reach the in-flight worker promptly: run took "
+ f"{elapsed:.2f}s despite cancel_event being set after 0.1s."
+ )
+
+
+def test_run_worker_receives_cancel_event_kwarg(tmp_path, monkeypatch):
+ """The retry wrapper must actually forward cancel_event to run_worker,
+ not just accept it."""
+ received = {}
+
+ def capture_worker(agent_spec, task, **kwargs):
+ received["cancel_event"] = kwargs.get("cancel_event")
+ return WorkerResult(status="completed", summary="done")
+
+ monkeypatch.setattr(rt, "run_worker", capture_worker)
+ store, runtime, run = _make_run(tmp_path)
+ cancel_event = threading.Event()
+
+ runtime._execute_run(run, cancel_event)
+
+ assert received["cancel_event"] is cancel_event