Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(factors): key the registry's module cache by zoo root, not by name (#1465)

cgycoreya0854d08385c
diff --git a/agent/src/factors/registry.py b/agent/src/factors/registry.py
index 674d50e83..5ac8a6ac1 100644
--- a/agent/src/factors/registry.py
+++ b/agent/src/factors/registry.py
@@ -378,18 +378,23 @@ class Registry:
if not self._use_filesystem_loader:
return importlib.import_module(alpha.module_path)
py_file = self._py_paths[alpha.id]
- cached = sys.modules.get(alpha.module_path)
+ # A custom zoo_root reuses the bundled module names, so the import cache
+ # is keyed by root as well as by module path: under the bare module path
+ # this module replaced the bundled one process-wide, and the bundled
+ # registry's own import_module then returned the custom code (#1465).
+ cache_key = f"{alpha.module_path}@{self._zoo_root}"
+ cached = sys.modules.get(cache_key)
if cached is not None and getattr(cached, "__file__", None) == str(py_file):
return cached
spec = importlib.util.spec_from_file_location(alpha.module_path, py_file)
if spec is None or spec.loader is None:
raise RegistryError(f"{alpha.id}: could not build import spec for {py_file}")
module = importlib.util.module_from_spec(spec)
- sys.modules[alpha.module_path] = module
+ sys.modules[cache_key] = module
try:
spec.loader.exec_module(module)
except Exception:
- sys.modules.pop(alpha.module_path, None)
+ sys.modules.pop(cache_key, None)
raise
return module
diff --git a/agent/tests/factors/test_registry.py b/agent/tests/factors/test_registry.py
index e0c096475..fe8ffd088 100644
--- a/agent/tests/factors/test_registry.py
+++ b/agent/tests/factors/test_registry.py
@@ -299,3 +299,61 @@ def test_registry_masks_nan_without_close_declared(mini_zoo: Path) -> None:
out = reg.compute("fakezoo_005", panel)
assert np.isnan(out.iloc[2, 0]) # masked, not the fabricated 0.0
assert out.notna().sum().sum() > 0 # mask did not wipe the whole panel
+
+
+# ---------------- filesystem loader vs the bundled module cache ----------------
+
+
+def _wave_panel(n: int = 30) -> dict[str, pd.DataFrame]:
+ """A panel that rises and falls, so cntp5's output is not a constant."""
+ idx = pd.date_range("2024-01-01", periods=n, freq="D")
+ cols = ["X", "Y"]
+ wave = np.sin(np.arange(n, dtype=float)).reshape(n, 1)
+ close = pd.DataFrame(np.repeat(wave, 2, axis=1), index=idx, columns=cols)
+ return {"close": close, "open": close * 0.99}
+
+
+def test_custom_zoo_root_does_not_shadow_the_bundled_module(tmp_path: Path) -> None:
+ """A custom zoo_root must not replace a bundled alpha process-wide (#1465).
+
+ Both roots derive the same ``module_path``
+ (``src.factors.zoo.<zoo>.<short>``), and the filesystem loader registered its
+ module under that bare name in ``sys.modules``. The bundled registry's own
+ ``importlib.import_module`` then returned the custom module, so a default
+ ``Registry()`` silently computed the custom code.
+ """
+ zoo_root = tmp_path / "zoo"
+ (zoo_root / "qlib158").mkdir(parents=True)
+ _write_alpha(
+ zoo_root / "qlib158",
+ "cntp5",
+ "qlib158",
+ body="""
+ import pandas as pd
+
+ def compute(panel):
+ c = panel["close"]
+ return pd.DataFrame(1.0, index=c.index, columns=c.columns)
+ """,
+ )
+
+ module_path = "src.factors.zoo.qlib158.cntp5"
+ previous = sys.modules.get(module_path)
+ try:
+ panel = _wave_panel()
+ # Bundled registry: this imports the real module into sys.modules.
+ bundled = Registry().compute("qlib158_cntp5", panel)
+ # A custom root reusing the same zoo/alpha names must not touch it.
+ # Modules load lazily, so the custom root has to compute for the
+ # collision to happen at all.
+ custom = Registry(zoo_root=zoo_root).compute("qlib158_cntp5", panel)
+ assert (custom.to_numpy() == 1.0).all() # the custom root did load its file
+ again = Registry().compute("qlib158_cntp5", panel)
+ finally:
+ if previous is None:
+ sys.modules.pop(module_path, None)
+ else:
+ sys.modules[module_path] = previous
+
+ assert not (bundled.to_numpy() == 1.0).all() # baseline is the real alpha
+ pd.testing.assert_frame_equal(bundled, again)