"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(agent): stop the backtest archive from mixing two runs' artifacts
Haozhe Wub79690f81f6a
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 9b2215e0f..2c04df827 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -579,6 +579,37 @@ def _normalize_tool_run_dir(args: dict[str, Any], memory_run_dir: str | None) ->return normalized+#: Names the backtest an archived run currently describes, and the files that+#: archive placed there, so the next one can replace exactly its own output.+_ARCHIVE_MANIFEST = ".archived_backtest.json"+++def _previously_archived(target: Path) -> set[str]:+ """Return the run-relative files the previous archive copied into ``target``.++ The caller deletes what this returns, and the names are read back off disk,+ so each one is confined to ``target`` here — a manifest carrying ``..`` must+ not become a way to delete a file elsewhere. An unreadable or malformed+ manifest yields an empty set: the worst case is the pre-#1094 merge for one+ turn, which beats refusing to archive a backtest the user is waiting for.+ """+ try:+ payload = json.loads((target / _ARCHIVE_MANIFEST).read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return set()+ files = payload.get("files") if isinstance(payload, dict) else None+ if not isinstance(files, list):+ return set()+ root = target.resolve()+ return {+ str(name)+ for name in files+ if isinstance(name, str)+ and (root / name).resolve().is_relative_to(root)+ and (root / name).resolve() != root+ }++def _archive_backtest_result(result: str, active_run_dir: str | None) -> bool:"""Copy a successful detached backtest into the active, reportable run.@@ -592,6 +623,16 @@ def _archive_backtest_result(result: str, active_run_dir: str | None) -> bool:that invariant lives in another module and this function reads its path backout of a *tool result* rather than from the validated arguments. Checkinglocally keeps a copy loop from depending on a guarantee made elsewhere.++ The copy REPLACES the previous archive rather than merging with it (#1094).+ An agent may backtest more than once in a turn, and the copy is a plain+ merge, so a file only the earlier backtest produced used to survive+ alongside the later one's output — one artifacts directory describing two+ different runs, which ``/runs/{id}`` then lists as artifacts of the current+ one. Only files a previous archive placed here are removed, recorded in+ :data:`_ARCHIVE_MANIFEST`; anything the active run wrote itself (notably+ ``code/signal_engine.py``, written before ``backtest`` is called) is+ untouched, which is why the manifest exists instead of a blanket wipe."""if not active_run_dir:return False@@ -615,10 +656,23 @@ def _archive_backtest_result(result: str, active_run_dir: str | None) -> bool:return Falsetarget.mkdir(parents=True, exist_ok=True)+ previously_archived = _previously_archived(target)+ archived: list[str] = []for directory in ("artifacts", "code", "logs"):source_dir = source / directoryif source_dir.is_dir():shutil.copytree(source_dir, target / directory, dirs_exist_ok=True)+ archived += [+ str(path.relative_to(source))+ for path in source_dir.rglob("*")+ if path.is_file()+ ]+ for stale in previously_archived - set(archived):+ (target / stale).unlink(missing_ok=True)+ (target / _ARCHIVE_MANIFEST).write_text(+ json.dumps({"source_run": source.name, "files": sorted(archived)}, indent=2),+ encoding="utf-8",+ )for filename in ("config.json","design_spec.json",diff --git a/agent/tests/test_loop_helpers.py b/agent/tests/test_loop_helpers.pyindex dca845b16..62e819f2e 100644--- a/agent/tests/test_loop_helpers.py+++ b/agent/tests/test_loop_helpers.py@@ -356,6 +356,86 @@ class TestArchiveBacktestResult:assert (active / "code" / "signal_engine.py").is_file()assert (active / "config.json").is_file()+ def test_two_backtests_in_one_turn_do_not_mix_artifacts(+ self, tmp_path: Path, monkeypatch+ ) -> None:+ """The active run must describe ONE backtest, not the union of two (#1094).++ The archive used to be a plain merge, so a file only the first backtest+ produced survived next to the second one's output, and ``/runs/{id}``+ listed it as an artifact of the current run.+ """+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))+ active = tmp_path / "active"+ (active / "code").mkdir(parents=True)+ # Written by the agent into the ACTIVE run before backtest is called;+ # it is the reason a blanket wipe of the target is not the fix.+ (active / "code" / "signal_engine.py").write_text("own\n", encoding="utf-8")++ def _backtest(name: str, extra: str | None) -> Path:+ source = tmp_path / name+ (source / "artifacts").mkdir(parents=True)+ (source / "artifacts" / "metrics.csv").write_text(+ f"total_return\n{name}\n", encoding="utf-8"+ )+ if extra:+ (source / "artifacts" / extra).write_text("stale\n", encoding="utf-8")+ return source++ first = _backtest("run-a", "extra.csv")+ assert _archive_backtest_result(+ json.dumps({"status": "ok", "run_dir": str(first)}), str(active)+ )+ assert (active / "artifacts" / "extra.csv").is_file()++ second = _backtest("run-b", None)+ assert _archive_backtest_result(+ json.dumps({"status": "ok", "run_dir": str(second)}), str(active)+ )++ # run-a's file is gone; run-b's output is what the run reports.+ assert not (active / "artifacts" / "extra.csv").exists()+ assert (active / "artifacts" / "metrics.csv").read_text(+ encoding="utf-8"+ ) == "total_return\nrun-b\n"+ # The active run's own code survives — only prior ARCHIVE output is dropped.+ assert (active / "code" / "signal_engine.py").read_text(encoding="utf-8") == "own\n"+ # Provenance records which backtest the artifacts describe.+ manifest = json.loads(+ (active / ".archived_backtest.json").read_text(encoding="utf-8")+ )+ assert manifest["source_run"] == "run-b"+ assert "artifacts/metrics.csv" in manifest["files"]++ def test_manifest_cannot_delete_outside_the_active_run(+ self, tmp_path: Path, monkeypatch+ ) -> None:+ """A manifest is read back off disk, so its names must stay contained.++ Without the containment check the delete step is an arbitrary-file-unlink+ primitive driven by a file inside a run directory.+ """+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))+ victim = tmp_path / "victim.txt"+ victim.write_text("keep me\n", encoding="utf-8")+ active = tmp_path / "active"+ active.mkdir()+ (active / ".archived_backtest.json").write_text(+ json.dumps({"source_run": "spoofed", "files": ["../victim.txt"]}),+ encoding="utf-8",+ )+ source = tmp_path / "detached"+ (source / "artifacts").mkdir(parents=True)+ (source / "artifacts" / "metrics.csv").write_text(+ "total_return\n0.1\n", encoding="utf-8"+ )++ assert _archive_backtest_result(+ json.dumps({"status": "ok", "run_dir": str(source)}), str(active)+ )++ assert victim.read_text(encoding="utf-8") == "keep me\n"+def test_ignores_result_without_metrics(self, tmp_path: Path, monkeypatch) -> None:monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))source = tmp_path / "not-a-backtest"