"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(swarm): block downstream tasks when upstream fails (#145)
omcdecor-cyber5a6780be2b6c
diff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.pyindex 051a85b56..989ca7cb9 100644--- a/agent/src/swarm/runtime.py+++ b/agent/src/swarm/runtime.py@@ -328,6 +328,15 @@ class SwarmRuntime:),)+ # Tasks blocked by a failed upstream are never dispatched and+ # therefore not present in layer_results — they were already+ # marked TaskStatus.blocked in _execute_layer and emitted+ # task_blocked. Account for them in run-level status so the+ # run is marked failed, not silently completed.+ for tid in layer_task_ids:+ if tid not in layer_results:+ all_succeeded = False+# Snapshot run.json at the layer boundary so list_runs and any# client that reads run.json directly sees fresh task statuses# without per-task I/O spam. One write per layer is cheap.@@ -483,6 +492,46 @@ class SwarmRuntime:try:for tid in layer_task_ids:task = task_store.load_task(tid)++ # Dependency-aware gating: without this check, a failed upstream+ # silently produces an empty task_summaries entry (the worker+ # upstream loop below only copies summaries that exist) and the+ # downstream worker runs with no upstream context. For an+ # investment-committee preset where portfolio_manager+ # depends_on=["task-risk"], a failed risk_officer would let PM+ # produce a "decision" with no risk input — which is+ # safety-critical. Mark blocked and skip dispatch; same-layer+ # peers with no shared upstream are unaffected.+ blocked_upstreams: list[tuple[str, str]] = []+ for dep_id in task.depends_on:+ try:+ dep_task = task_store.load_task(dep_id)+ except FileNotFoundError:+ blocked_upstreams.append((dep_id, "missing"))+ continue+ if dep_task.status != TaskStatus.completed:+ blocked_upstreams.append((dep_id, dep_task.status.value))++ if blocked_upstreams:+ reason = ", ".join(f"{d}={s}" for d, s in blocked_upstreams)+ blocked_by_ids = [d for d, _ in blocked_upstreams]+ task_store.update_status(+ tid,+ TaskStatus.blocked,+ error=f"Blocked: upstream not completed ({reason})",+ blocked_by=blocked_by_ids,+ completed_at=datetime.now(timezone.utc).isoformat(),+ )+ self._emit_event(+ run.id,+ self._make_event(+ "task_blocked",+ task_id=tid,+ data={"blocked_by": blocked_by_ids, "reason": reason},+ ),+ )+ continue+agent_spec = agent_map.get(task.agent_id)if agent_spec is None:results[tid] = WorkerResult(diff --git a/agent/tests/test_swarm_dag_gating.py b/agent/tests/test_swarm_dag_gating.pynew file mode 100644index 000000000..33c396fbc--- /dev/null+++ b/agent/tests/test_swarm_dag_gating.py@@ -0,0 +1,132 @@+"""P0-A regression: a DAG with a failed upstream must NOT silently launch+downstream tasks with empty upstream summaries.++Original 5/27 incident: swarm-20260527-183056-2d91b0f2 (investment_committee+preset). risk_officer correctly failed grounding (mock VaR), then portfolio_manager+started 2 ms later with task_summaries['task-risk'] missing — produced a+"decision" with no risk input. This is safety-critical because matt-invest is+wired to a live Questrade account.++Pre-fix: ``test_failed_upstream_blocks_downstream`` FAILS because PM/B runs.+Post-fix: B is marked ``TaskStatus.blocked``, no ``task_started`` for B, and+``task_blocked`` event is emitted.+"""++from __future__ import annotations++import json+import threading+from pathlib import Path++import pytest++import src.swarm.runtime as rt+from src.swarm.models import (+ SwarmAgentSpec,+ SwarmRun,+ SwarmTask,+ TaskStatus,+ WorkerResult,+)+from src.swarm.store import SwarmStore+++def _make_run(tmp_path: Path) -> tuple[SwarmStore, rt.SwarmRuntime, SwarmRun]:+ store = SwarmStore(base_dir=tmp_path)+ runtime = rt.SwarmRuntime(store=store)+ agents = [+ SwarmAgentSpec(id="risk", role="risk", system_prompt="x", max_retries=0),+ SwarmAgentSpec(id="pm", role="pm", system_prompt="x", max_retries=0),+ ]+ tasks = [+ SwarmTask(id="task-risk", agent_id="risk", prompt_template="do risk"),+ SwarmTask(+ id="task-pm",+ agent_id="pm",+ prompt_template="do pm",+ depends_on=["task-risk"],+ blocked_by=["task-risk"],+ input_from={"risk": "task-risk"},+ ),+ ]+ run = SwarmRun(+ id="r-p0a",+ 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 risk_fails(monkeypatch):+ """Make every worker invocation return status=failed."""++ def fake_worker(agent_spec, task, **kwargs):+ return WorkerResult(+ status="failed",+ summary="",+ error="output contract not met: explicitly fabricated / mock data",+ )++ monkeypatch.setattr(rt, "run_worker", fake_worker)+++def test_failed_upstream_blocks_downstream(tmp_path, risk_fails):+ """When task-risk FAILS, task-pm MUST be blocked, not started."""+ store, runtime, run = _make_run(tmp_path)+ runtime._execute_run(run, threading.Event())++ reloaded = store.load_run(run.id)+ assert reloaded is not None++ by_id = {t.id: t for t in reloaded.tasks}+ assert by_id["task-risk"].status == TaskStatus.failed, (+ f"risk should be failed, got {by_id['task-risk'].status}"+ )+ assert by_id["task-pm"].status == TaskStatus.blocked, (+ f"PM must be blocked when risk fails, got {by_id['task-pm'].status} — "+ "this is the 5/27 incident pattern"+ )+ assert by_id["task-pm"].started_at is None, (+ f"PM must NOT have a start timestamp when blocked, got "+ f"{by_id['task-pm'].started_at}"+ )+++def test_blocked_downstream_emits_task_blocked_event(tmp_path, risk_fails):+ """Blocked downstream tasks must emit task_blocked, not task_started."""+ store, runtime, run = _make_run(tmp_path)+ runtime._execute_run(run, threading.Event())++ events_file = tmp_path / run.id / "events.jsonl"+ events = [json.loads(line) for line in events_file.read_text().splitlines() if line.strip()]++ pm_events = [e for e in events if e.get("task_id") == "task-pm"]+ types = [e["type"] for e in pm_events]+ assert "task_started" not in types, (+ f"PM must never emit task_started when upstream failed; events: {types}"+ )+ assert "task_blocked" in types, (+ f"PM must emit task_blocked when upstream failed; events: {types}"+ )++ blocked_evt = next(e for e in pm_events if e["type"] == "task_blocked")+ assert "task-risk" in blocked_evt.get("data", {}).get("blocked_by", []), (+ f"task_blocked.data.blocked_by must reference upstream task; got {blocked_evt['data']}"+ )+++def test_run_marked_failed_when_downstream_blocked(tmp_path, risk_fails):+ """The whole run must be RunStatus.failed when any task is blocked."""+ from src.swarm.models import RunStatus++ store, runtime, run = _make_run(tmp_path)+ runtime._execute_run(run, threading.Event())++ reloaded = store.load_run(run.id)+ assert reloaded.status == RunStatus.failed, (+ f"run must be failed when downstream blocked, got {reloaded.status}"+ )