test(s31): close 1 review MAJOR — guard the sole-numpy-importer premise the BLAS pin rests on

This commit is contained in:
Kjell Tore Guttormsen 2026-07-25 19:56:39 +02:00
commit 5a6ee03955

View file

@ -167,6 +167,46 @@ def test_blas_thread_pins_are_set_before_numpy_is_imported() -> None:
assert result.returncode == 0, result.stderr
def test_semretrieval_is_the_sole_numpy_importer() -> None:
"""The PREMISE the pin above rests on, guarded — it was prose until now.
``semretrieval.py`` can pin the BLAS thread variables at import time only because it is the
first and only place numpy enters the package. A second importer elsewhere under ``src/``
would very likely be imported FIRST (``run.py``, ``verdicts.py`` and friends load long before
the opt-in retrieval seam), numpy would latch its backend's thread count before these
``setdefault`` calls ever run, and the pin would become a silent no-op in the real process
while ``test_blas_thread_pins_are_set_before_numpy_is_imported`` stayed green, because that
probe execs THIS module standalone in a fresh interpreter and can never observe the collision.
AST, not substring: a docstring mentioning numpy must not trip the guard, exactly as
``test_okf_is_maf_free`` reasons about the MAF-free claim.
Deliberate limit, stated rather than oversold: this covers ``src/`` code, which is what the
premise actually claims. A third-party dependency importing numpy transitively is out of
scope the pins are defence-in-depth for byte-identical artifacts, never the basis of the
ranking guarantee (see the module docstring).
Detach point: add ``import numpy`` to any other module under ``src/portfolio_optimiser/``
RED, while the rest of the suite stays green."""
package = Path(__file__).resolve().parents[1] / "src" / "portfolio_optimiser"
importers: set[str] = set()
for path in sorted(package.glob("*.py")):
roots: set[str] = set()
for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
if isinstance(node, ast.Import):
roots.update(alias.name.split(".")[0] for alias in node.names)
elif isinstance(node, ast.ImportFrom) and node.module:
roots.add(node.module.split(".")[0])
if "numpy" in roots:
importers.add(path.name)
assert importers == {"semretrieval.py"}, (
f"numpy is imported by {sorted(importers)}; the import-time BLAS pin in semretrieval.py "
"is only viable while that module is the SOLE numpy importer. Another importer loaded "
"earlier makes the pin a no-op in the real process and no existing test can see it."
)
def test_semretrieval_imports_no_network_modules() -> None:
"""SC8 — the offline default must not be able to reach the network. Detach point: add
``import urllib.request`` (or any ``_NETWORK_ROOTS`` member) to semretrieval.py RED."""