Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): stop loading .env when the runner module is merely imported

Haozhe Wu0b91480de21f
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index d3687bf99..f41b83f48 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -21,12 +21,6 @@ from typing import Any, Dict, Iterable, List, Literal, Optional
import pandas as pd
from pydantic import BaseModel, ConfigDict, Field, model_validator, field_validator
-try:
- from dotenv import load_dotenv
- load_dotenv()
-except ImportError:
- pass
-
from backtest.loaders.registry import (
FALLBACK_CHAINS,
LOADER_REGISTRY,
@@ -1146,6 +1140,19 @@ def main(run_dir: Path) -> None:
file is read so an arbitrary filesystem location cannot be used
to source ``code/signal_engine.py``.
"""
+ # Loading `.env` belongs to the process that RUNS a backtest, not to
+ # importing this module. At import time it ran during pytest collection --
+ # before the per-test os.environ snapshot exists -- so a developer's own
+ # LANGCHAIN_MODEL_NAME leaked into every later test and could not be undone
+ # by any fixture, which is how seven redaction tests failed locally while
+ # CI (with no .env checked out) stayed green.
+ try:
+ from dotenv import load_dotenv
+
+ load_dotenv()
+ except ImportError:
+ pass
+
# Guard the CLI entry point with the same root whitelist the MCP
# ``backtest`` tool already uses (src/tools/backtest_tool.py:23). Without
# this, ``python -m backtest.runner /tmp/attacker_path`` would happily
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.py
index dab8f83f3..59efd4b6e 100644
--- a/agent/src/agent/grounding.py
+++ b/agent/src/agent/grounding.py
@@ -239,14 +239,15 @@ _DASH_DATE_RE = re.compile(
r")(?![\d/-])",
re.IGNORECASE,
)
-# A percentage range masks only its upper bound through the "%" tail check
-# below, because the sign touches the second number: "1–2%" left 1 behind
-# (#983). Mask the span as a whole.
# A level stated as a RANGE has the same shape: the separator touches the
# second number, so masking "目标价 10" left "-20" behind and a negative price
# matches no OHLC window at all -- a guaranteed rejection of a correct draft.
# The tail is optional, so a single-value level is unaffected.
_RANGE_TAIL = r"(?:\s*[-–—~~至到]\s*[-+]?\d[\d,]*(?:\.\d+)?)?"
+
+# A percentage range masks only its upper bound through the "%" tail check
+# below, because the sign touches the second number: "1–2%" left 1 behind
+# (#983). Mask the span as a whole.
_PERCENT_RANGE_RE = re.compile(
r"\d[\d,]*(?:\.\d+)?\s*[-–—~至]\s*\d[\d,]*(?:\.\d+)?\s*[%%]"
)
diff --git a/agent/tests/test_runner_import_is_inert.py b/agent/tests/test_runner_import_is_inert.py
new file mode 100644
index 000000000..27447125d
--- /dev/null
+++ b/agent/tests/test_runner_import_is_inert.py
@@ -0,0 +1,54 @@
+"""Importing the backtest runner must not touch the process environment.
+
+``load_dotenv()`` used to run at import scope. pytest imports test modules
+during *collection*, which happens before any per-test ``os.environ`` snapshot
+exists, so a developer's own ``LANGCHAIN_MODEL_NAME`` entered the environment
+and no fixture could undo it — seven redaction tests failed on a machine with
+an ``agent/.env`` while CI, which checks one out, stayed green.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+AGENT_DIR = Path(__file__).resolve().parents[1]
+
+_PROBE = (
+ "import json, os\n"
+ "before = dict(os.environ)\n"
+ "import backtest.runner\n"
+ "print(json.dumps({k: os.environ[k] for k in set(os.environ) - set(before)}))\n"
+)
+
+
+def test_importing_the_runner_adds_no_environment_variables(tmp_path: Path) -> None:
+ """A `.env` beside the working directory must stay unread on import."""
+ (tmp_path / ".env").write_text(
+ "VIBE_TRADING_IMPORT_PROBE=leaked\nLANGCHAIN_MODEL_NAME=leaked-model\n",
+ encoding="utf-8",
+ )
+ env = dict(os.environ)
+ # The suite sandboxes HOME, which also hides the user site-packages this
+ # interpreter's numpy lives in. Hand the child exactly what the parent can
+ # already import rather than making it rediscover any of it.
+ env["PYTHONPATH"] = os.pathsep.join(
+ [str(AGENT_DIR), str(AGENT_DIR / "src"), *(p for p in sys.path if p)]
+ )
+ env.pop("VIBE_TRADING_IMPORT_PROBE", None)
+
+ result = subprocess.run(
+ [sys.executable, "-c", _PROBE],
+ cwd=tmp_path,
+ env=env,
+ capture_output=True,
+ text=True,
+ timeout=180,
+ )
+
+ assert result.returncode == 0, result.stderr
+ added = json.loads(result.stdout.strip().splitlines()[-1])
+ assert added == {}, f"importing backtest.runner set {sorted(added)}"