"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(swarm): isolate worker artifacts between retry attempts
Lanre Shittu9018b6775efa
diff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.pyindex bfee0461e..815df2488 100644--- a/agent/src/swarm/runtime.py+++ b/agent/src/swarm/runtime.py@@ -41,7 +41,7 @@ from src.swarm.task_store import ()from src.tools.mcp import invalidate_mcp_specs_cachefrom src.tools.redaction import redact_internal_paths-from src.swarm.worker import run_worker+from src.swarm.worker import agent_artifact_dir, clear_agent_artifacts, run_workerlogger = logging.getLogger(__name__)@@ -693,6 +693,13 @@ class SwarmRuntime:attempt + 1,max_retries + 1,)+ # A retry re-invokes run_worker against the same artifact+ # directory. Without clearing it first, a failed attempt's+ # report.md (or any other tool-written file) would still be+ # there when the retried attempt reads the directory back,+ # silently substituting stale content for the new attempt's+ # real result.+ clear_agent_artifacts(agent_artifact_dir(run_dir, agent_spec.id))result = run_worker(agent_spec=agent_spec,diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.pyindex e4303bd52..feb1f5414 100644--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@ -8,6 +8,7 @@ from __future__ import annotationsimport jsonimport logging+import shutilimport timefrom datetime import datetime, timezonefrom pathlib import Path@@ -294,6 +295,35 @@ def build_worker_prompt(return "\n\n".join(prompt_parts)+def agent_artifact_dir(run_dir: Path, agent_id: str) -> Path:+ """Return the canonical artifacts directory for one agent within a run.++ The single source of truth for this path — shared with the retry loop+ in ``runtime.py`` so the two can never compute it differently and drift+ apart.+ """+ return run_dir / "artifacts" / agent_id+++def clear_agent_artifacts(artifact_dir: Path) -> None:+ """Remove *artifact_dir* and everything in it, before a retry attempt.++ A retry re-invokes :func:`run_worker` against the same ``artifact_dir``.+ Without this, a failed attempt's ``report.md`` (or any other file a tool+ wrote) would still be sitting there when the retried attempt reads the+ directory back via ``_resolve_summary``/``_report_written``/+ ``_collect_artifacts``, silently substituting stale content for the new+ attempt's real result.++ Raises on failure rather than swallowing it: proceeding with a retry+ while known-stale artifacts remain would recreate the exact bug this+ exists to prevent. ``run_worker`` recreates the directory itself+ (``mkdir(parents=True, exist_ok=True)``) on its next invocation.+ """+ if artifact_dir.exists():+ shutil.rmtree(artifact_dir)++def run_worker(agent_spec: SwarmAgentSpec,task: SwarmTask,@@ -386,7 +416,7 @@ def run_worker(]# 6. ReAct loop- artifact_dir = run_dir / "artifacts" / agent_id+ artifact_dir = agent_artifact_dir(run_dir, agent_id)artifact_dir.mkdir(parents=True, exist_ok=True)t0 = time.monotonic()diff --git a/agent/tests/test_swarm_retry_artifact_isolation.py b/agent/tests/test_swarm_retry_artifact_isolation.pynew file mode 100644index 000000000..264790dbb--- /dev/null+++ b/agent/tests/test_swarm_retry_artifact_isolation.py@@ -0,0 +1,257 @@+"""Regression tests: a retried worker attempt must not inherit stale+artifacts (report.md, or any other tool-written file) from a prior failed+attempt for the same task.++``_run_worker_with_retries`` re-invokes ``run_worker`` against the *same*+``artifact_dir`` on every attempt (``mkdir(parents=True, exist_ok=True)``,+no cleanup). ``_resolve_summary``/``_report_written``/``_collect_artifacts``+all read whatever is currently sitting in that directory, with no way to+tell which attempt wrote it. Without isolation, a worker that fails after+writing report.md, followed by a retry that fails immediately (a realistic+sequence of two ordinary transient LLM/provider errors), silently returns+the discarded first attempt's stale content as the retried attempt's real+result.++The real ``_resolve_summary``/``_report_written``/``_collect_artifacts``+are exercised for real inside the mocked ``run_worker`` below (only the+expensive LLM/tool-loop internals are mocked out), so these tests prove the+actual interaction between the retry loop's cleanup and worker.py's+artifact-reading functions, not just one function in isolation.+"""++from __future__ import annotations++from pathlib import Path+from unittest.mock import patch++from src.swarm.models import SwarmAgentSpec, SwarmTask, WorkerResult+from src.swarm.runtime import SwarmRuntime+from src.swarm.store import SwarmStore+from src.swarm.worker import (+ _collect_artifacts,+ _resolve_summary,+ agent_artifact_dir,+ clear_agent_artifacts,+)+++def _make_runtime(tmp_path: Path) -> SwarmRuntime:+ store = SwarmStore(base_dir=tmp_path / "swarm_runs")+ return SwarmRuntime(store=store)+++def _make_agent_spec(max_retries: int) -> SwarmAgentSpec:+ return SwarmAgentSpec(+ id="analyst",+ role="Analyst",+ system_prompt="x",+ tools=["read_file"],+ skills=[],+ max_iterations=1,+ timeout_seconds=5,+ max_retries=max_retries,+ )+++def _make_task() -> SwarmTask:+ return SwarmTask(id="task-1", agent_id="analyst", prompt_template="do x")+++# --------------------------------------------------------------------------- #+# Unit tests: the two new helpers themselves+# --------------------------------------------------------------------------- #+++def test_agent_artifact_dir_matches_run_worker_construction(tmp_path: Path) -> None:+ """The shared helper must resolve to the exact path run_worker() writes+ to, or the retry loop would clear the wrong directory entirely."""+ run_dir = tmp_path / "run-x"+ assert agent_artifact_dir(run_dir, "analyst") == run_dir / "artifacts" / "analyst"+++def test_clear_agent_artifacts_removes_nested_files_and_dirs(tmp_path: Path) -> None:+ artifact_dir = tmp_path / "artifacts" / "analyst"+ (artifact_dir / "charts").mkdir(parents=True)+ (artifact_dir / "report.md").write_text("stale", encoding="utf-8")+ (artifact_dir / "charts" / "plot.png").write_text("stale-binary", encoding="utf-8")++ clear_agent_artifacts(artifact_dir)++ assert not artifact_dir.exists()+++def test_clear_agent_artifacts_is_noop_when_directory_absent(tmp_path: Path) -> None:+ """Nothing to clean up before the very first attempt — must not raise."""+ artifact_dir = tmp_path / "artifacts" / "analyst"+ assert not artifact_dir.exists()+ clear_agent_artifacts(artifact_dir) # must not raise+ assert not artifact_dir.exists()+++# --------------------------------------------------------------------------- #+# Integration: the real retry loop + the real artifact-reading functions+# --------------------------------------------------------------------------- #+++def test_stale_report_not_returned_after_retry(tmp_path: Path) -> None:+ """Attempt 1 writes report.md then fails; attempt 2 fails before writing+ anything. Attempt 1's report must not become attempt 2's result."""+ runtime = _make_runtime(tmp_path)+ agent_spec = _make_agent_spec(max_retries=1)+ task = _make_task()+ run_dir = tmp_path / "run-stale-report"+ run_dir.mkdir()+ artifact_dir = agent_artifact_dir(run_dir, "analyst")++ calls = {"n": 0}++ def fake_run_worker(**kwargs):+ calls["n"] += 1+ artifact_dir.mkdir(parents=True, exist_ok=True)+ if calls["n"] == 1:+ (artifact_dir / "report.md").write_text(+ "# Attempt 1 (discarded)\nSHORT thesis on stale data.",+ encoding="utf-8",+ )+ return WorkerResult(+ status="failed",+ summary=_resolve_summary(artifact_dir, "attempt 1 raw fallback"),+ error="attempt 1: provider error",+ )+ # Attempt 2 fails immediately — no report.md written this attempt.+ return WorkerResult(+ status="failed",+ summary=_resolve_summary(artifact_dir, "attempt 2 real fallback"),+ error="attempt 2: provider error",+ )++ with patch("src.swarm.runtime.run_worker", side_effect=fake_run_worker):+ result = runtime._run_worker_with_retries(+ agent_spec=agent_spec,+ task=task,+ upstream_summaries={},+ user_vars={},+ run_dir=run_dir,+ event_callback=None,+ run_id="run-stale-report",+ include_shell_tools=False,+ grounding_block="",+ )++ assert calls["n"] == 2+ assert result.summary == "attempt 2 real fallback"+ assert "Attempt 1" not in result.summary+ assert not (artifact_dir / "report.md").exists()+++def test_stale_non_report_artifact_not_leaked_after_retry(tmp_path: Path) -> None:+ """Attempt 1 writes a non-report file (e.g. a chart/CSV a tool+ produced) then fails; attempt 2 writes nothing and fails too. The final+ artifact_paths must not contain attempt 1's file — proves the fix+ clears the whole directory, not just report.md."""+ runtime = _make_runtime(tmp_path)+ agent_spec = _make_agent_spec(max_retries=1)+ task = _make_task()+ run_dir = tmp_path / "run-stale-artifact"+ run_dir.mkdir()+ artifact_dir = agent_artifact_dir(run_dir, "analyst")++ calls = {"n": 0}++ def fake_run_worker(**kwargs):+ calls["n"] += 1+ artifact_dir.mkdir(parents=True, exist_ok=True)+ if calls["n"] == 1:+ (artifact_dir / "analysis.csv").write_text(+ "date,close\n2026-01-01,100\n", encoding="utf-8"+ )+ return WorkerResult(+ status="failed",+ summary="attempt 1 raw fallback",+ artifact_paths=_collect_artifacts(artifact_dir),+ error="attempt 1: tool error",+ )+ return WorkerResult(+ status="failed",+ summary="attempt 2 real fallback",+ artifact_paths=_collect_artifacts(artifact_dir),+ error="attempt 2: provider error",+ )++ with patch("src.swarm.runtime.run_worker", side_effect=fake_run_worker):+ result = runtime._run_worker_with_retries(+ agent_spec=agent_spec,+ task=task,+ upstream_summaries={},+ user_vars={},+ run_dir=run_dir,+ event_callback=None,+ run_id="run-stale-artifact",+ include_shell_tools=False,+ grounding_block="",+ )++ assert calls["n"] == 2+ assert result.artifact_paths == []+ assert not (artifact_dir / "analysis.csv").exists()+++def test_successful_retry_only_reflects_current_attempt_artifacts(+ tmp_path: Path,+) -> None:+ """Control: attempt 1 fails with artifacts on disk; attempt 2 succeeds+ with its own, different report/artifact. Only attempt 2's content and+ files must be returned — failed-attempt artifacts disappear,+ successful-attempt artifacts remain."""+ runtime = _make_runtime(tmp_path)+ agent_spec = _make_agent_spec(max_retries=1)+ task = _make_task()+ run_dir = tmp_path / "run-successful-retry"+ run_dir.mkdir()+ artifact_dir = agent_artifact_dir(run_dir, "analyst")++ calls = {"n": 0}++ def fake_run_worker(**kwargs):+ calls["n"] += 1+ artifact_dir.mkdir(parents=True, exist_ok=True)+ if calls["n"] == 1:+ (artifact_dir / "report.md").write_text(+ "Attempt 1 (discarded)", encoding="utf-8"+ )+ (artifact_dir / "chart.png").write_text(+ "stale-chart-bytes", encoding="utf-8"+ )+ return WorkerResult(+ status="failed",+ summary=_resolve_summary(artifact_dir, "attempt 1 raw fallback"),+ artifact_paths=_collect_artifacts(artifact_dir),+ error="attempt 1: provider error",+ )+ (artifact_dir / "report.md").write_text(+ "# Attempt 2 (real result)\nLONG thesis.", encoding="utf-8"+ )+ return WorkerResult(+ status="completed",+ summary=_resolve_summary(artifact_dir, "attempt 2 raw fallback"),+ artifact_paths=_collect_artifacts(artifact_dir),+ )++ with patch("src.swarm.runtime.run_worker", side_effect=fake_run_worker):+ result = runtime._run_worker_with_retries(+ agent_spec=agent_spec,+ task=task,+ upstream_summaries={},+ user_vars={},+ run_dir=run_dir,+ event_callback=None,+ run_id="run-successful-retry",+ include_shell_tools=False,+ grounding_block="",+ )++ assert calls["n"] == 2+ assert result.status == "completed"+ assert "Attempt 2" in result.summary+ assert "Attempt 1" not in result.summary+ assert result.artifact_paths == ["artifacts/analyst/report.md"]