Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(tests): confine os patches to the module under test

Haozhe Wu0b05671be138
diff --git a/agent/tests/module_os_helpers.py b/agent/tests/module_os_helpers.py
new file mode 100644
index 000000000..cedb540d4
--- /dev/null
+++ b/agent/tests/module_os_helpers.py
@@ -0,0 +1,52 @@
+"""Confine an ``os`` patch to the module under test.
+
+``some_module.os`` is not a per-module copy -- it is the one shared ``os``
+module object, so ``monkeypatch.setattr(some_module.os, "replace", boom)``
+installs ``boom`` for every importer in the process for the duration of the
+test. That is survivable only because monkeypatch undoes it at teardown, and
+teardown ordering is not something a test controls: any ``pytest_runtest_``
+hook that touches the filesystem runs BEFORE fixture finalizers, so it meets
+the replacement, and a replacement that raises takes the teardown chain with
+it -- after which the undo never happens and every later test sees the patched
+function (#1123: ~3000 cascading errors from one such test).
+
+Replacing the module's *reference* to ``os`` instead keeps the substitution
+inside the module being tested, where it was always meant to be.
+"""
+
+from __future__ import annotations
+
+import os
+from types import ModuleType
+from typing import Any
+
+
+class _ModuleOs:
+ """An ``os`` stand-in: overridden names first, the real module behind."""
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(os, name)
+
+
+def patch_module_os(monkeypatch: Any, module: ModuleType, **overrides: Any) -> _ModuleOs:
+ """Point ``module.os`` at a stand-in carrying ``overrides``.
+
+ Args:
+ monkeypatch: The test's ``monkeypatch`` fixture.
+ module: The module whose ``os`` reference should be replaced.
+ **overrides: ``os`` attribute names mapped to their replacements.
+
+ Returns:
+ The stand-in, so a test can add or swap an attribute mid-run.
+
+ Raises:
+ AttributeError: If an override names something ``os`` does not have,
+ which would otherwise silently test a function nobody calls.
+ """
+ for name in overrides:
+ getattr(os, name)
+ stand_in = _ModuleOs()
+ for name, value in overrides.items():
+ setattr(stand_in, name, value)
+ monkeypatch.setattr(module, "os", stand_in)
+ return stand_in
diff --git a/agent/tests/test_factor_api.py b/agent/tests/test_factor_api.py
index 9b1130633..d4a719f9f 100644
--- a/agent/tests/test_factor_api.py
+++ b/agent/tests/test_factor_api.py
@@ -9,6 +9,7 @@ from fastapi.testclient import TestClient
import api_server
from src.api import runs_routes
+from tests.module_os_helpers import patch_module_os
def _client(tmp_path: Path, monkeypatch) -> TestClient:
@@ -246,7 +247,7 @@ def test_factor_scan_caps_directory_entries(tmp_path: Path, monkeypatch) -> None
assert entries_seen <= entry_limit
return entry
- monkeypatch.setattr(runs_routes.os, "scandir", GuardedScandir)
+ patch_module_os(monkeypatch, runs_routes, scandir=GuardedScandir)
assert runs_routes._has_factor_artifacts(run_dir) is False
assert entries_seen == entry_limit
diff --git a/agent/tests/test_module_os_helpers.py b/agent/tests/test_module_os_helpers.py
new file mode 100644
index 000000000..1514b5e9a
--- /dev/null
+++ b/agent/tests/test_module_os_helpers.py
@@ -0,0 +1,57 @@
+"""The module-scoped ``os`` patch must stay inside the module it targets."""
+
+from __future__ import annotations
+
+import os
+import types
+from pathlib import Path
+
+import pytest
+
+from tests.module_os_helpers import patch_module_os
+
+
+def test_patch_module_os_confines_the_replacement(monkeypatch, tmp_path: Path) -> None:
+ """A raising replacement must not reach the interpreter-wide ``os`` (#1123).
+
+ Patching ``module.os`` attributes directly reaches every importer, and
+ pytest's own teardown calls ``os.replace`` / ``os.scandir`` while this
+ test's fixture finalizers are still pending -- so a raiser installed that
+ way aborts the teardown chain and the undo never runs.
+ """
+ victim = types.ModuleType("victim")
+ victim.os = os
+
+ def _boom(*args: object, **kwargs: object) -> None:
+ raise RuntimeError("must never be reachable outside `victim`")
+
+ patch_module_os(monkeypatch, victim, replace=_boom)
+
+ with pytest.raises(RuntimeError):
+ victim.os.replace("a", "b")
+
+ source = tmp_path / "source"
+ source.write_text("x", encoding="utf-8")
+ os.replace(source, tmp_path / "target")
+ assert (tmp_path / "target").read_text(encoding="utf-8") == "x"
+
+
+def test_patch_module_os_forwards_everything_it_does_not_override(monkeypatch) -> None:
+ """The stand-in is an ``os``, not a stub of the one call under test."""
+ victim = types.ModuleType("victim")
+ victim.os = os
+
+ patch_module_os(monkeypatch, victim, fsync=lambda fd: None)
+
+ assert victim.os.path is os.path
+ assert victim.os.sep == os.sep
+ assert victim.os.fsync(0) is None
+
+
+def test_patch_module_os_rejects_a_name_os_does_not_have(monkeypatch) -> None:
+ """A typo'd override would otherwise stub a function nobody calls."""
+ victim = types.ModuleType("victim")
+ victim.os = os
+
+ with pytest.raises(AttributeError):
+ patch_module_os(monkeypatch, victim, raplace=lambda *_: None)
diff --git a/agent/tests/test_onboard_partial_env.py b/agent/tests/test_onboard_partial_env.py
index 67764d55d..fc730d33e 100644
--- a/agent/tests/test_onboard_partial_env.py
+++ b/agent/tests/test_onboard_partial_env.py
@@ -14,6 +14,7 @@ from pathlib import Path
import pytest
from cli import onboard
+from tests.module_os_helpers import patch_module_os
pytestmark = pytest.mark.skipif(
os.name != "posix", reason="POSIX file modes are not meaningful on Windows"
@@ -61,7 +62,7 @@ def test_failed_write_preserves_the_previous_partial(fake_home, monkeypatch):
def explode(*args, **kwargs):
raise OSError(28, "No space left on device")
- monkeypatch.setattr(onboard.os, "fdopen", explode)
+ patch_module_os(monkeypatch, onboard, fdopen=explode)
onboard._save_partial({"TUSHARE_TOKEN": "second-answer"})
# The recovery state survives: a failed save must not leave the user with
diff --git a/agent/tests/test_settings_api.py b/agent/tests/test_settings_api.py
index 7ae9f0889..b42130cc7 100644
--- a/agent/tests/test_settings_api.py
+++ b/agent/tests/test_settings_api.py
@@ -10,6 +10,7 @@ from fastapi.testclient import TestClient
import api_server
from src.api import settings_routes
+from tests.module_os_helpers import patch_module_os
@pytest.fixture
@@ -596,7 +597,7 @@ def test_atomic_write_secret_is_crash_safe(
def _boom(*_args: object, **_kwargs: object) -> None:
raise OSError("simulated crash before commit")
- monkeypatch.setattr(helpers.os, "replace", _boom)
+ patch_module_os(monkeypatch, helpers, replace=_boom)
with pytest.raises(OSError):
helpers._atomic_write_secret(target, "NEW=2\n")
diff --git a/agent/tests/test_state_fsync.py b/agent/tests/test_state_fsync.py
index 4c7a68ba3..532e0de9d 100644
--- a/agent/tests/test_state_fsync.py
+++ b/agent/tests/test_state_fsync.py
@@ -14,6 +14,7 @@ import pytest
import src.core.state as state_mod
from src.core.state import RunStateStore
+from tests.module_os_helpers import patch_module_os
def test_write_json_calls_fsync(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -24,7 +25,7 @@ def test_write_json_calls_fsync(tmp_path: Path, monkeypatch: pytest.MonkeyPatch)
fsynced.append(fd)
real_fsync(fd)
- monkeypatch.setattr(state_mod.os, "fsync", spy)
+ patch_module_os(monkeypatch, state_mod, fsync=spy)
target = tmp_path / "state.json"
RunStateStore._write_json(target, {"status": "success"})
diff --git a/agent/tests/test_swarm_store_atomic_write.py b/agent/tests/test_swarm_store_atomic_write.py
index 927c5c647..ced02187e 100644
--- a/agent/tests/test_swarm_store_atomic_write.py
+++ b/agent/tests/test_swarm_store_atomic_write.py
@@ -22,6 +22,7 @@ import pytest
import src.swarm.store as store_mod
from src.swarm.models import SwarmRun
from src.swarm.store import SwarmStore
+from tests.module_os_helpers import patch_module_os
def _winerr(code: int) -> PermissionError:
@@ -53,7 +54,7 @@ def test_replace_retries_transient_winerror_then_succeeds(tmp_path, monkeypatch)
raise _winerr(5)
return real(src, dst, *a, **k)
- monkeypatch.setattr(store_mod.os, "replace", flaky)
+ patch_module_os(monkeypatch, store_mod, replace=flaky)
upd = _run()
upd.final_report = "RETRIED-OK"
@@ -72,7 +73,7 @@ def test_non_transient_error_reraises_immediately(tmp_path, monkeypatch):
calls["n"] += 1
raise _winerr(2) # ERROR_FILE_NOT_FOUND — NOT in the transient set
- monkeypatch.setattr(store_mod.os, "replace", boom)
+ patch_module_os(monkeypatch, store_mod, replace=boom)
with pytest.raises(OSError):
store.update_run(_run())
assert calls["n"] == 1, "non-transient must not be retried (no masking)"
@@ -87,7 +88,7 @@ def test_transient_budget_is_bounded(tmp_path, monkeypatch):
calls["n"] += 1
raise _winerr(32) # ERROR_SHARING_VIOLATION, forever
- monkeypatch.setattr(store_mod.os, "replace", always)
+ patch_module_os(monkeypatch, store_mod, replace=always)
with pytest.raises(OSError):
store.update_run(_run())
assert calls["n"] == store_mod._REPLACE_ATTEMPTS
diff --git a/agent/tests/test_trace_writer.py b/agent/tests/test_trace_writer.py
index 64e576bc9..e2bdc5a40 100644
--- a/agent/tests/test_trace_writer.py
+++ b/agent/tests/test_trace_writer.py
@@ -12,6 +12,7 @@ import pytest
import src.agent.trace as trace_mod
from src.agent.trace import TraceWriter
+from tests.module_os_helpers import patch_module_os
def _raw_entries(trace_dir: Path) -> list[dict]:
@@ -150,7 +151,7 @@ def test_write_calls_fsync_for_crash_safety(
fsync_fds.append(fd)
real_fsync(fd)
- monkeypatch.setattr(trace_mod.os, "fsync", _tracking_fsync)
+ patch_module_os(monkeypatch, trace_mod, fsync=_tracking_fsync)
try:
trace.write({"type": "answer", "iter": 1, "content": "ok"})
assert fsync_fds == [trace._file.fileno()]
@@ -171,7 +172,7 @@ def test_new_trace_file_fsyncs_parent_directory(
dir_fsyncs.append(fd)
real_fsync(fd)
- monkeypatch.setattr(trace_mod.os, "fsync", _tracking_fsync)
+ patch_module_os(monkeypatch, trace_mod, fsync=_tracking_fsync)
trace = TraceWriter(tmp_path)
trace.close()
assert len(dir_fsyncs) == 1
@@ -193,7 +194,7 @@ def test_fsync_oserror_warns_once_and_keeps_writing(
def _failing_fsync(fd: int) -> None:
raise OSError("fsync unsupported")
- monkeypatch.setattr(trace_mod.os, "fsync", _failing_fsync)
+ patch_module_os(monkeypatch, trace_mod, fsync=_failing_fsync)
with caplog.at_level(logging.WARNING, logger="src.agent.trace"):
trace.write({"type": "answer", "iter": 1, "content": "a"})
trace.write({"type": "answer", "iter": 2, "content": "b"})
@@ -217,7 +218,7 @@ def test_sidecar_write_is_atomic_and_leaves_no_temp_files(
replace_targets.append(str(dst))
real_replace(src, dst)
- monkeypatch.setattr(trace_mod.os, "replace", _tracking_replace)
+ patch_module_os(monkeypatch, trace_mod, replace=_tracking_replace)
trace = TraceWriter(tmp_path)
trace.write_tool_result(
call_id="call-1",
@@ -251,7 +252,7 @@ def test_record_never_references_missing_sidecar_on_crash(
def _failing_replace(src: object, dst: object) -> None:
raise OSError("simulated crash before sidecar rename")
- monkeypatch.setattr(trace_mod.os, "replace", _failing_replace)
+ patch_module_os(monkeypatch, trace_mod, replace=_failing_replace)
with pytest.raises(OSError, match="simulated crash"):
trace.write_tool_result(
call_id="call-1",
@@ -280,7 +281,7 @@ def test_sidecar_survives_a_partial_write(tmp_path, monkeypatch):
return real_write(fd, data[:16])
return real_write(fd, data)
- monkeypatch.setattr(trace_mod.os, "write", _short_write)
+ patch_module_os(monkeypatch, trace_mod, write=_short_write)
writer = TraceWriter(tmp_path)
body = "x" * 5000
@@ -299,7 +300,7 @@ def test_failed_sidecar_write_leaves_no_temp_file(tmp_path, monkeypatch):
def _boom(fd, data):
raise OSError("disk exploded")
- monkeypatch.setattr(trace_mod.os, "write", _boom)
+ patch_module_os(monkeypatch, trace_mod, write=_boom)
writer = TraceWriter(tmp_path)
with pytest.raises(OSError):
writer._attach_text_field({}, field="result", value="y" * 5000,
diff --git a/tools/ci_grep_gates.sh b/tools/ci_grep_gates.sh
index dcaff86fd..1ede52178 100644
--- a/tools/ci_grep_gates.sh
+++ b/tools/ci_grep_gates.sh
@@ -143,6 +143,25 @@ else
echo "${GREEN}ok${NC}"
fi
+# -------------------------------------------------------------- gate (f)
+# `some_module.os` IS the shared os module, so patching an attribute through it
+# reaches every importer in the process. pytest's own teardown calls os.scandir
+# and os.replace while fixture finalizers are still pending, so a replacement
+# that raises aborts the teardown chain and its undo never runs (#1123 -- one
+# such test produced ~3000 cascading errors). Patch the module's REFERENCE
+# instead: tests/module_os_helpers.py::patch_module_os.
+echo "[gate f] no process-wide os patches in tests ..."
+F_OUTPUT=$(grep -rn "setattr([a-zA-Z_][a-zA-Z_0-9]*\.os," agent/tests --include="*.py" \
+ | grep -v "^agent/tests/module_os_helpers.py:" || true)
+if [ -n "$F_OUTPUT" ]; then
+ echo "${RED}FAIL${NC}: patch the module's os reference, not the shared os module:"
+ echo "$F_OUTPUT"
+ echo " use: from tests.module_os_helpers import patch_module_os"
+ FAILED=1
+else
+ echo "${GREEN}ok${NC}"
+fi
+
# --------------------------------------------------------------- result
if [ "$FAILED" -ne 0 ]; then
echo