diff --git a/changelog.d/623.fixed.md b/changelog.d/623.fixed.md new file mode 100644 index 000000000..ae1c6059d --- /dev/null +++ b/changelog.d/623.fixed.md @@ -0,0 +1 @@ +Keep maintenance-script imports from changing `sys.path` or `os.environ` after PolicyEngine loads, preserving the test suite's installed metadata lookup. The import guard also checks that `certify_data_release.py` leaves both unchanged when it first loads PolicyEngine with country imports enabled. diff --git a/scripts/audit_regional_input_surface.py b/scripts/audit_regional_input_surface.py index 3c851d4d4..26411b45c 100644 --- a/scripts/audit_regional_input_surface.py +++ b/scripts/audit_regional_input_surface.py @@ -23,9 +23,10 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] -# The target model must be auditable before the current bundle certifies it. -os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") -sys.path.insert(0, str(REPO_ROOT / "src")) +if __name__ == "__main__": + # The target model must be auditable before the current bundle certifies it. + os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") + sys.path.insert(0, str(REPO_ROOT / "src")) from policyengine.provenance.regional_input_surface import ( # noqa: E402 measure_regional_input_surface, diff --git a/scripts/bundle.py b/scripts/bundle.py index b05ffa589..5ab10c503 100644 --- a/scripts/bundle.py +++ b/scripts/bundle.py @@ -18,11 +18,74 @@ import argparse import os import sys +from contextlib import contextmanager from pathlib import Path - -REPO_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(REPO_ROOT / "scripts")) -sys.path.insert(0, str(REPO_ROOT / "src")) +from threading import RLock + +SCRIPTS_DIR = Path(__file__).resolve().parent +REPO_ROOT = SCRIPTS_DIR.parent +# Bare, package and file-path imports can create separate dispatcher modules. +# Keep the lock with the interpreter state that every dispatcher shares. +_COMMAND_IMPORT_LOCK = vars(sys).setdefault( + "_policyengine_bundle_command_import_lock", RLock() +) + +# These are the bare sibling imports used by the commands and their helpers. +_SIBLING_HELPERS = ( + "certify_data_release", + "generate_bundle_artifacts", + "generate_trace_tros", + "prepare_package_bundle_update", + "release_lock", + "spm_bundle", +) +# Eager sibling imports retain the module under its bare name. +_SIBLING_DEPENDENCIES = { + "certify_data_release": "generate_bundle_artifacts", + "generate_trace_tros": "release_lock", + "prepare_package_bundle_update": "generate_bundle_artifacts", + "spm_bundle": "generate_bundle_artifacts", +} + + +def _is_foreign_helper(name: str, module: object) -> bool: + source = getattr(module, "__file__", None) + # Explicitly injected modules may have no source file. + if not source: + return False + if Path(source).resolve() != SCRIPTS_DIR / f"{name}.py": + return True + # A local helper may still hold a foreign dependency even after that + # dependency has been replaced in sys.modules. + dependency = _SIBLING_DEPENDENCIES.get(name) + return dependency is not None and _is_foreign_helper( + dependency, getattr(module, dependency, None) + ) + + +@contextmanager +def _checkout_imports(): + """Use this checkout's helpers for a command and restore the caller's imports.""" + with _COMMAND_IMPORT_LOCK: + original_path = sys.path[:] + cached = { + name: sys.modules[name] for name in _SIBLING_HELPERS if name in sys.modules + } + try: + scripts_dir = str(SCRIPTS_DIR) + if original_path[:1] != [scripts_dir]: + sys.path.insert(0, scripts_dir) + for name, module in cached.items(): + if _is_foreign_helper(name, module): + del sys.modules[name] + yield + finally: + sys.path[:] = original_path + for name in _SIBLING_HELPERS: + if name in cached: + sys.modules[name] = cached[name] + else: + sys.modules.pop(name, None) def _certify_data(args: argparse.Namespace) -> int: @@ -150,7 +213,6 @@ def _development_manifest(args: argparse.Namespace) -> int: def _generate_tros(*, strict: bool = False) -> int: - os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") from generate_trace_tros import regenerate_all written, regressions = regenerate_all(strict=strict) @@ -170,7 +232,6 @@ def _generate_tros(*, strict: bool = False) -> int: def _check_tros(*, strict: bool = False) -> int: - os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") from generate_trace_tros import generated_tros changed = False @@ -377,10 +438,15 @@ def main(argv: list[str] | None = None) -> int: if getattr(args, "strict_tros", False) and not args.include_tros: parser.error("--strict-tros requires --include-tros") try: - return args.func(args) + with _checkout_imports(): + return args.func(args) except ValueError as exc: parser.error(str(exc)) if __name__ == "__main__": + # Use the checkout's policyengine when a subcommand needs it, and default + # to skipping country imports. + os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") + sys.path[:0] = [str(REPO_ROOT / "src"), str(SCRIPTS_DIR)] raise SystemExit(main()) diff --git a/scripts/certify_data_release.py b/scripts/certify_data_release.py index 341297457..5cbb51efd 100644 --- a/scripts/certify_data_release.py +++ b/scripts/certify_data_release.py @@ -30,16 +30,25 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(REPO_ROOT / "src")) -sys.path.insert(0, str(REPO_ROOT / "scripts")) -from generate_bundle_artifacts import generate # noqa: E402 +if __name__ == "__main__": + # Certify with the checkout's policyengine and default to skipping country + # imports. + os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") + sys.path[:0] = [str(REPO_ROOT / "src"), str(REPO_ROOT / "scripts")] + +if __package__: + from . import generate_bundle_artifacts +else: + import generate_bundle_artifacts from policyengine.provenance.certification import ( # noqa: E402 REGIONAL_RELEASE_KINDS, certify_data_release, ) +generate = generate_bundle_artifacts.generate + def main(argv=None) -> int: parser = argparse.ArgumentParser(description="Certify a country data release.") diff --git a/scripts/check_uk_candidate.py b/scripts/check_uk_candidate.py index 7920b8c33..6a227237d 100644 --- a/scripts/check_uk_candidate.py +++ b/scripts/check_uk_candidate.py @@ -40,8 +40,9 @@ from typing import Any, Optional REPO_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(REPO_ROOT / "src")) -os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") +if __name__ == "__main__": + sys.path.insert(0, str(REPO_ROOT / "src")) + os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") import requests # noqa: E402 diff --git a/scripts/check_uk_uc_floor.py b/scripts/check_uk_uc_floor.py index d79c62719..1ba9d074e 100644 --- a/scripts/check_uk_uc_floor.py +++ b/scripts/check_uk_uc_floor.py @@ -18,7 +18,8 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(REPO_ROOT / "src")) +if __name__ == "__main__": + sys.path.insert(0, str(REPO_ROOT / "src")) from policyengine.provenance.uk_uc_floor import check_uc_floor # noqa: E402 diff --git a/scripts/generate_bundle_artifacts.py b/scripts/generate_bundle_artifacts.py index e941bb856..de595d018 100644 --- a/scripts/generate_bundle_artifacts.py +++ b/scripts/generate_bundle_artifacts.py @@ -6,7 +6,6 @@ import copy import importlib.util import json -import os import re import sys from pathlib import Path @@ -22,10 +21,6 @@ BUNDLE_MANIFEST = ( REPO_ROOT / "src" / "policyengine" / "data" / "bundle" / "manifest.json" ) -# Other maintenance subcommands explicitly load runtime helpers after this -# module; retain their source-checkout and country-import behavior. -os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") -sys.path.insert(0, str(REPO_ROOT / "src")) # These commands run before dependencies are installed in release/PR CI. Load # the same stdlib-only validator used at runtime without importing policyengine. diff --git a/scripts/generate_ordered_scenario_vectors.py b/scripts/generate_ordered_scenario_vectors.py index bb7c0e23f..2235ff09d 100644 --- a/scripts/generate_ordered_scenario_vectors.py +++ b/scripts/generate_ordered_scenario_vectors.py @@ -8,26 +8,54 @@ import argparse import copy +import importlib.util import json import os import sys from pathlib import Path +from threading import RLock ROOT = Path(__file__).resolve().parents[1] -os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") -sys.path.insert(0, str(ROOT / "src")) -sys.path.insert(0, str(ROOT)) +if __name__ == "__main__": + os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") + sys.path.insert(0, str(ROOT / "src")) from policyengine.provenance.ordered_scenario import ( # noqa: E402 build_ordered_scenario, ) -from tests import ordered_receipt_modifiers as modifiers # noqa: E402 PATH = ROOT / "src/policyengine/data/schemas/ordered_scenario_plan.v1.vectors.json" REVISION = {"repository": "PolicyEngine/test", "git_sha": "a" * 40} +# Every import alias temporarily uses the same modifier name in sys.modules. +_MODIFIER_IMPORT_LOCK = vars(sys).setdefault( + "_policyengine_ordered_scenario_modifier_import_lock", RLock() +) def build_vectors(): + path = ROOT / "tests" / "ordered_receipt_modifiers.py" + spec = importlib.util.spec_from_file_location( + "tests.ordered_receipt_modifiers", path + ) + assert spec is not None and spec.loader is not None + modifiers = importlib.util.module_from_spec(spec) + spec.loader.exec_module(modifiers) + + # The receipt binder looks up modifier functions by their module name. + with _MODIFIER_IMPORT_LOCK: + missing = object() + previous = sys.modules.get(spec.name, missing) + sys.modules[spec.name] = modifiers + try: + return _build_vectors(modifiers) + finally: + if previous is missing: + del sys.modules[spec.name] + else: + sys.modules[spec.name] = previous + + +def _build_vectors(modifiers): def leaves(*functions): return [(function, dict(REVISION)) for function in functions] diff --git a/scripts/generate_receipt_schemas.py b/scripts/generate_receipt_schemas.py index 35adc4905..f9834621a 100644 --- a/scripts/generate_receipt_schemas.py +++ b/scripts/generate_receipt_schemas.py @@ -21,8 +21,12 @@ REPO_ROOT = Path(__file__).resolve().parents[1] SCHEMA_DIR = REPO_ROOT / "src" / "policyengine" / "data" / "schemas" -os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") -sys.path.insert(0, str(REPO_ROOT / "src")) + +if __name__ == "__main__": + # Write schemas from the checkout's models and default to skipping country + # imports. + os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") + sys.path.insert(0, str(REPO_ROOT / "src")) from policyengine.provenance.ordered_scenario import OrderedScenarioPlan # noqa: E402 from policyengine.provenance.receipt import ExecutionReceipt # noqa: E402 diff --git a/scripts/generate_trace_tros.py b/scripts/generate_trace_tros.py index 656d1868b..ba859bd79 100644 --- a/scripts/generate_trace_tros.py +++ b/scripts/generate_trace_tros.py @@ -19,8 +19,8 @@ from importlib.resources import files from pathlib import Path +import release_lock from jsonschema import Draft202012Validator -from release_lock import PYPI, load_toml, validate_registry_artifacts from policyengine.provenance.certification import ( core_claim_warning, @@ -46,6 +46,10 @@ BUNDLE_TRO_DIR = REPO_ROOT / "src" / "policyengine" / "data" / "bundle" BUNDLE_LOCK = REPO_ROOT / "uv.lock" +PYPI = release_lock.PYPI +load_toml = release_lock.load_toml +validate_registry_artifacts = release_lock.validate_registry_artifacts + def regenerate_all( *, strict: bool = False diff --git a/scripts/prepare_package_bundle_update.py b/scripts/prepare_package_bundle_update.py index 16140a473..e777bc51b 100644 --- a/scripts/prepare_package_bundle_update.py +++ b/scripts/prepare_package_bundle_update.py @@ -5,13 +5,13 @@ import argparse from typing import Any, Mapping -from generate_bundle_artifacts import ( - BUNDLE_MANIFEST, - REPO_ROOT, - generate, - load_bundle_manifest, - write_bundle_manifest, -) +import generate_bundle_artifacts + +BUNDLE_MANIFEST = generate_bundle_artifacts.BUNDLE_MANIFEST +REPO_ROOT = generate_bundle_artifacts.REPO_ROOT +generate = generate_bundle_artifacts.generate +load_bundle_manifest = generate_bundle_artifacts.load_bundle_manifest +write_bundle_manifest = generate_bundle_artifacts.write_bundle_manifest PACKAGE_ARGS = { "core": "policyengine-core", diff --git a/scripts/release_consumers.py b/scripts/release_consumers.py index 9c96a06a5..80fc02c92 100644 --- a/scripts/release_consumers.py +++ b/scripts/release_consumers.py @@ -24,8 +24,9 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(REPO_ROOT / "src")) -os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") +if __name__ == "__main__": + sys.path.insert(0, str(REPO_ROOT / "src")) + os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") import requests # noqa: E402 diff --git a/scripts/spm_bundle.py b/scripts/spm_bundle.py index 54e6c3801..1c676b714 100644 --- a/scripts/spm_bundle.py +++ b/scripts/spm_bundle.py @@ -11,13 +11,15 @@ from pathlib import Path from urllib.parse import urlparse +import generate_bundle_artifacts import requests -from generate_bundle_artifacts import normalized_manifest from packaging.version import Version from policyengine.provenance.bundle_validation import validate_bundle_measurements from policyengine.provenance.spm_configuration import SPMMeasurementConfiguration +normalized_manifest = generate_bundle_artifacts.normalized_manifest + def _calculator_component(version: str, sha256: str, wheel_url: str) -> dict: return { diff --git a/src/policyengine/derivations/narrate.py b/src/policyengine/derivations/narrate.py index 3fd7041bd..35f0feb0f 100644 --- a/src/policyengine/derivations/narrate.py +++ b/src/policyengine/derivations/narrate.py @@ -10,10 +10,46 @@ from __future__ import annotations +import os +import sys +from threading import RLock from typing import Any from .trace import Derivation +# Share one reentrant lock across reloads/module aliases so overlapping cold +# imports serialize their import-time ``os.getcwd()`` cleanup. +_LITELLM_IMPORT_LOCK = vars(sys).setdefault( + "_policyengine_derivations_litellm_import_lock", RLock() +) + + +def _import_litellm() -> Any: + """Import LiteLLM without keeping any ``os.getcwd()`` entry it appends.""" + with _LITELLM_IMPORT_LOCK: + try: + cwd: str | None = os.getcwd() + except OSError: + cwd = None + existing_cwd_count = sys.path.count(cwd) if cwd is not None else 0 + try: + import litellm # noqa: PLC0415 — lazy import keeps the base module light + finally: + if cwd is not None: + # LiteLLM's proxy CLI module appends ``os.getcwd()`` to + # ``sys.path`` at import time, leaking checkout paths into + # isolated environments. Remove only extra occurrences so + # unrelated ``sys.path`` edits survive. + extra = sys.path.count(cwd) - existing_cwd_count + while extra > 0: + for idx in range(len(sys.path) - 1, -1, -1): + if sys.path[idx] == cwd: + del sys.path[idx] + break + extra -= 1 + return litellm + + DEFAULT_MODEL = "claude-sonnet-5-5" # Low effort plus a short narrative still needs room for thinking tokens. DEFAULT_MAX_TOKENS = 4096 @@ -134,7 +170,7 @@ def narrate( Returns the model's response text. Raises ``ValueError`` on refusal, an empty response, or incompatible Sonnet options. """ - import litellm # noqa: PLC0415 — lazy import keeps the base module light + litellm = _import_litellm() prompt = _build_prompt( derivation, @@ -169,7 +205,7 @@ async def narrate_async( to LiteLLM by default and passes explicit overrides when supplied. LiteLLM and the selected model must support the supplied values. """ - import litellm # noqa: PLC0415 — lazy import keeps the base module light + litellm = _import_litellm() prompt = _build_prompt( derivation, diff --git a/tests/conftest.py b/tests/conftest.py index 4969579e2..b5929baa8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,5 +1,7 @@ """Pytest configuration and shared fixtures.""" +import sys + import pytest # Import fixtures from fixtures module so pytest can discover them @@ -14,6 +16,12 @@ uk_test_dataset, us_test_dataset, ) +from tests.fixtures.import_path import ( # noqa: F401 + COLLECTION_IMPORT_PATH_CHANGES, + checkout_stays_off_import_path, + import_path_changes, + scripts_on_path, +) from tests.fixtures.parametric_reforms_fixtures import ( # noqa: F401 mock_param_joint, mock_param_single, @@ -32,6 +40,22 @@ married_couple_with_kids, ) +#: The import path before any test module is collected. +_IMPORT_PATH_BEFORE_COLLECTION = list(sys.path) + + +def pytest_collection_finish(session): + """Record how importing the test modules changed ``sys.path``. + + ``tests/test_script_imports.py`` checks for added checkout directories and + changes to the existing entries. + """ + + session.config.stash[COLLECTION_IMPORT_PATH_CHANGES] = import_path_changes( + _IMPORT_PATH_BEFORE_COLLECTION, sys.path + ) + + # Group (non-person) entities per country, and a helper to extract the # entity_data dict a scoping strategy / filter operates on. Shared so the filter # and region-group tests don't each redefine them. diff --git a/tests/fixtures/import_path.py b/tests/fixtures/import_path.py new file mode 100644 index 000000000..aba0af8ae --- /dev/null +++ b/tests/fixtures/import_path.py @@ -0,0 +1,111 @@ +"""Keep this checkout's directories off the interpreter's import path. + +An editable setuptools install leaves ``src/policyengine.egg-info`` in the +checkout, and its ``.pth`` file lists ``src`` after site-packages. If a test +session puts ``src`` ahead of site-packages on ``sys.path``, even as a second +copy, ``importlib.metadata`` reads that egg-info instead of the installed +distribution's metadata for every later test (#623). The scripts under +``scripts/`` import each other by bare module name, as they do when run as +``python scripts/.py``, so tests make ``scripts/`` importable only while +importing one, or only for the length of one test. +""" + +from __future__ import annotations + +import os +import sys +from collections import Counter +from collections.abc import Iterable, Iterator +from contextlib import contextmanager +from pathlib import Path + +import pytest + +CHECKOUT = Path(__file__).resolve().parents[2] +SCRIPTS_DIR = CHECKOUT / "scripts" + +#: Set by the maintenance scripts' entry points; no test may leave it changed. +SKIP_COUNTRY_IMPORTS = "POLICYENGINE_SKIP_COUNTRY_IMPORTS" + +#: How collecting the test modules changed ``sys.path``, recorded by +#: ``tests/conftest.py`` when collection finishes. +COLLECTION_IMPORT_PATH_CHANGES = pytest.StashKey[list[str]]() + + +def _inside_checkout(entry: object) -> bool: + return isinstance(entry, str) and ( + Path(entry or ".").resolve().is_relative_to(CHECKOUT) + ) + + +def import_path_changes(before: Iterable[str], after: Iterable[str]) -> list[str]: + """How ``after`` differs from ``before`` in ways that change what imports find. + + Reported: a new entry inside this checkout, and any change to the number or + order of the entries ``before`` had, such as a second copy of ``src`` put in + front of the one an editable install lists after site-packages. Not + reported: a new entry outside the checkout, which only adds a place to look. + """ + + before, after = list(before), list(after) + known = set(before) + changes = [ + f"added {entry!r}" + for entry in after + if entry not in known and _inside_checkout(entry) + ] + kept = [entry for entry in after if entry in known] + if kept != before: + extra = Counter(kept) - Counter(before) + missing = Counter(before) - Counter(kept) + changes.extend(f"added another {entry!r}" for entry in extra.elements()) + changes.extend(f"removed {entry!r}" for entry in missing.elements()) + if not extra and not missing: + changes.append(f"reordered {before} as {kept}") + return changes + + +@contextmanager +def scripts_importable() -> Iterator[None]: + """Put ``scripts/`` on ``sys.path`` for the block, then restore it exactly.""" + + saved = list(sys.path) + sys.path.insert(0, str(SCRIPTS_DIR)) + try: + yield + finally: + sys.path[:] = saved + + +@pytest.fixture +def scripts_on_path(monkeypatch): + """Keep ``scripts/`` importable for one test. + + Script functions import their sibling scripts when called, as the entry + point does, so a test that calls them needs the directory for its length. + """ + + monkeypatch.syspath_prepend(str(SCRIPTS_DIR)) + + +@pytest.fixture(autouse=True) +def checkout_stays_off_import_path(): + """Fail a test that leaves ``sys.path`` or the country-import switch changed.""" + + path, switch = list(sys.path), os.environ.get(SKIP_COUNTRY_IMPORTS) + yield + problems = import_path_changes(path, sys.path) + if os.environ.get(SKIP_COUNTRY_IMPORTS) != switch: + problems.append( + f"changed {SKIP_COUNTRY_IMPORTS} from {switch!r} to " + f"{os.environ.get(SKIP_COUNTRY_IMPORTS)!r}" + ) + if problems: + pytest.fail( + "The test left the interpreter changed for later tests: " + + "; ".join(problems) + + ". Import scripts inside tests.fixtures.import_path." + "scripts_importable() or use the scripts_on_path fixture, and set " + "environment variables with monkeypatch.", + pytrace=False, + ) diff --git a/tests/test_derivations.py b/tests/test_derivations.py index f7a508cb4..1ffab072c 100644 --- a/tests/test_derivations.py +++ b/tests/test_derivations.py @@ -8,6 +8,13 @@ from __future__ import annotations import asyncio +import importlib.abc +import importlib.util +import os +import subprocess +import sys +import threading +import time import types from pathlib import Path @@ -22,6 +29,7 @@ narrate_async, top_level_contributions, ) +from policyengine.derivations.narrate import _import_litellm def _us_simulation() -> object: @@ -294,7 +302,7 @@ def test_narration_rejects_global_anthropic_sampling( ): """Global provider defaults must be rejected before calling LiteLLM.""" monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") - import litellm + litellm = _import_litellm() monkeypatch.setattr(litellm, "drop_params", False) monkeypatch.setattr(litellm.AnthropicConfig, sampling_parameter, value) @@ -411,7 +419,8 @@ def no_network(*args, **kwargs): monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") import httpx - import litellm + + litellm = _import_litellm() from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler monkeypatch.setattr(litellm, "drop_params", False) @@ -493,3 +502,117 @@ async def acompletion(**kwargs): ) assert len(requests) == 1 assert litellm.AnthropicConfig.get_config() == config_before + + +def test_narrate_cold_litellm_import_leaves_sys_path_unchanged(tmp_path): + """Cold-importing LiteLLM via ``narrate`` must not append cwd to ``sys.path``.""" + if importlib.util.find_spec("litellm") is None: + pytest.skip("litellm is not installed") + env = os.environ.copy() + env["LITELLM_LOCAL_MODEL_COST_MAP"] = "True" + if pythonpath := env.get("PYTHONPATH"): + env["PYTHONPATH"] = os.pathsep.join( + os.path.abspath(entry) for entry in pythonpath.split(os.pathsep) if entry + ) + probe = ( + "import os, sys\n" + "sys.path[:] = [p for p in sys.path if p not in ('', os.getcwd())]\n" + "before = list(sys.path)\n" + "from policyengine.derivations import Derivation, TraceNode, narrate\n" + "assert 'litellm' not in sys.modules\n" + "try:\n" + " narrate(\n" + " Derivation(\n" + " variable='x',\n" + " value=1.0,\n" + " period=2026,\n" + " trace=TraceNode(name='x', value=1.0),\n" + " ),\n" + " temperature=0.0,\n" + " )\n" + "except ValueError as exc:\n" + " assert 'does not support temperature' in str(exc), str(exc)\n" + "else:\n" + " raise AssertionError('Expected ValueError for temperature=0.0')\n" + "assert 'litellm' in sys.modules\n" + "assert sys.path == before, (before, sys.path)\n" + "assert os.getcwd() not in sys.path\n" + ) + result = subprocess.run( + [sys.executable, "-c", probe], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + timeout=30, + check=False, + ) + assert result.returncode == 0, result.stderr or result.stdout + + +def test_import_litellm_serializes_concurrent_cold_imports_and_preserves_edits( + monkeypatch, tmp_path +): + """Overlapping cold imports must serialize cleanup and keep unrelated edits.""" + monkeypatch.chdir(tmp_path) + cwd = os.getcwd() + unrelated = str(tmp_path / "unrelated-import-path-entry") + dirty_seen = threading.Event() + second_entering = threading.Event() + + class FakeLoader(importlib.abc.Loader): + def create_module(self, spec): + return types.ModuleType(spec.name) + + def exec_module(self, module): + sys.path.append(cwd) + dirty_seen.set() + assert second_entering.wait(timeout=5) + # Yield briefly so the second caller blocks on _LITELLM_IMPORT_LOCK + # while cwd is transiently on sys.path. + time.sleep(0.02) + + class FakeFinder(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname == "litellm": + return importlib.util.spec_from_loader(fullname, FakeLoader()) + return None + + monkeypatch.delitem(sys.modules, "litellm", raising=False) + monkeypatch.setattr(sys, "meta_path", [FakeFinder(), *sys.meta_path]) + # Pre-seed one cwd entry to verify only LiteLLM's extra occurrence is removed. + monkeypatch.setattr(sys, "path", [cwd, *sys.path]) + initial_cwd_count = sys.path.count(cwd) + + results: list[object] = [] + errors: list[BaseException] = [] + + def first_caller(): + try: + results.append(_import_litellm()) + except BaseException as exc: # pragma: no cover - surfaced below + errors.append(exc) + + def second_caller(): + try: + assert dirty_seen.wait(timeout=5) + sys.path.append(unrelated) + second_entering.set() + results.append(_import_litellm()) + except BaseException as exc: # pragma: no cover - surfaced below + errors.append(exc) + + t1 = threading.Thread(target=first_caller) + t2 = threading.Thread(target=second_caller) + t1.start() + t2.start() + t1.join(timeout=10) + t2.join(timeout=10) + + assert not t1.is_alive() and not t2.is_alive() + assert errors == [] + assert len(results) == 2 + assert results[0] is results[1] + assert sys.path.count(cwd) == initial_cwd_count + assert sys.path[0] == cwd + assert unrelated in sys.path diff --git a/tests/test_execution_receipt.py b/tests/test_execution_receipt.py index 6b79f3374..7992fadbf 100644 --- a/tests/test_execution_receipt.py +++ b/tests/test_execution_receipt.py @@ -160,12 +160,12 @@ def _build(dataset_file, bundle=None, **kwargs): } -#: The interpreter's import path when this module is collected. Release-script -#: tests import scripts/bundle.py at module level, which puts the checkout's -#: ``src`` first on sys.path. An editable build leaves -#: ``src/policyengine.egg-info`` there, which then shadows the installed -#: distribution's metadata (receipts rightly refuse that), so each receipt test -#: runs with the import path as it was before those modules were collected. +#: The interpreter's import path when this module is collected. An editable +#: build leaves ``src/policyengine.egg-info`` in the checkout, which shadows the +#: installed distribution's metadata (receipts rightly refuse that) whenever +#: ``src`` comes first on sys.path. Release-script tests used to put it there +#: (#623); tests/test_script_imports.py now guards against that, and each +#: receipt test still runs with the import path as it was collected. _COLLECTION_SYS_PATH = list(sys.path) diff --git a/tests/test_generate_trace_tros.py b/tests/test_generate_trace_tros.py index 012b0e3d7..ddeca1150 100644 --- a/tests/test_generate_trace_tros.py +++ b/tests/test_generate_trace_tros.py @@ -1,17 +1,16 @@ """Repository TRO generation must validate complete payloads before any writes.""" import json -import sys from importlib.resources import files -from pathlib import Path import pytest from jsonschema import Draft202012Validator, ValidationError from policyengine.provenance.manifest import DataReleaseManifestUnavailableError +from tests.fixtures.import_path import scripts_importable -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) -import generate_trace_tros as generator # noqa: E402 +with scripts_importable(): + import generate_trace_tros as generator @pytest.fixture diff --git a/tests/test_release_tro_generation.py b/tests/test_release_tro_generation.py index fb4b6b33c..339898eef 100644 --- a/tests/test_release_tro_generation.py +++ b/tests/test_release_tro_generation.py @@ -6,7 +6,6 @@ import importlib.util import json import shutil -import sys from pathlib import Path import pytest @@ -14,12 +13,18 @@ from policyengine.provenance import manifest from policyengine.provenance.trace import compute_trace_composition_fingerprint +from tests.fixtures.import_path import scripts_importable ROOT = Path(__file__).resolve().parents[1] FIXTURES = ROOT / "tests" / "fixtures" / "release_tros" -sys.path.insert(0, str(ROOT / "scripts")) -import bundle as maintenance # noqa: E402 -import generate_trace_tros as generator # noqa: E402 + +with scripts_importable(): + import bundle as maintenance + import generate_trace_tros as generator + +# Tests import sibling scripts, and the maintenance CLI imports them when a +# command runs. +pytestmark = pytest.mark.usefixtures("scripts_on_path") @pytest.mark.parametrize("country", ["us", "uk"]) diff --git a/tests/test_script_imports.py b/tests/test_script_imports.py new file mode 100644 index 000000000..3959679bb --- /dev/null +++ b/tests/test_script_imports.py @@ -0,0 +1,741 @@ +"""Importing a maintenance script leaves the interpreter as it was. + +Tests import the scripts under ``scripts/`` as modules. A script that put the +checkout's ``src`` first on ``sys.path`` when imported made every later test in +the session read ``src/policyengine.egg-info``, which editable setuptools +installs leave behind, as the installed distribution's metadata (#623). +Scripts can configure the interpreter when run directly. Calling an imported +script's entry point must restore any temporary changes to the import path. + +The probe reports a path-change flag and the names of environment variables +that changed. Import failures also report the exception type. A nonzero +subprocess exit reports the exit status. +""" + +import json +import os +import shutil +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor, wait +from importlib import metadata +from importlib.util import module_from_spec, spec_from_file_location +from pathlib import Path +from threading import Event +from types import ModuleType + +import pytest +from hypothesis import given +from hypothesis import strategies as st + +from tests.fixtures.import_path import ( + CHECKOUT, + COLLECTION_IMPORT_PATH_CHANGES, + SCRIPTS_DIR, + SKIP_COUNTRY_IMPORTS, + import_path_changes, +) + +SCRIPT_NAMES = sorted(path.stem for path in SCRIPTS_DIR.glob("*.py")) + +# Run outside pytest. The warm probe shares an already imported policyengine +# package. A cold probe imports one script in a fresh interpreter. +PROBE = """ +import importlib, json, os, sys + +scripts_dir, mode, *names = sys.argv[1:] +if mode == "warm": + # Keep the batch fast and let the snapshots see any skip flag a script sets. + os.environ["POLICYENGINE_SKIP_COUNTRY_IMPORTS"] = "1" + import policyengine + del os.environ["POLICYENGINE_SKIP_COUNTRY_IMPORTS"] +else: + assert len(names) == 1 + assert "policyengine" not in sys.modules + assert "POLICYENGINE_SKIP_COUNTRY_IMPORTS" not in os.environ +sys.path.insert(0, scripts_dir) +results = {} +for name in names: + for script in names: + sys.modules.pop(script, None) + original_path = sys.path + path, environment = list(original_path), dict(os.environ) + outcome = {} + try: + importlib.import_module(name) + except BaseException as error: + outcome["error"] = type(error).__name__ + outcome["path_changed"] = sys.path is not original_path or sys.path != path + outcome["environment_changes"] = [ + key + for key in sorted(set(environment) | set(os.environ)) + if environment.get(key) != os.environ.get(key) + ] + outcome["policyengine_imported"] = "policyengine" in sys.modules + results[name] = outcome + original_path[:] = path + sys.path = original_path + os.environ.clear() + os.environ.update(environment) +print(json.dumps(results)) +""" + + +def _run_import_probe(cwd, scripts_dir, names, *, warm=False): + environment = dict(os.environ) + environment.pop(SKIP_COUNTRY_IMPORTS, None) + # Resolve entries before moving the subprocess outside the checkout. + if pythonpath := environment.get("PYTHONPATH"): + environment["PYTHONPATH"] = os.pathsep.join( + os.path.abspath(entry) for entry in pythonpath.split(os.pathsep) + ) + mode = "warm" if warm else "cold" + try: + result = subprocess.run( + [sys.executable, "-c", PROBE, str(scripts_dir), mode, *names], + cwd=cwd, + env=environment, + capture_output=True, + timeout=300, + check=False, + ) + except subprocess.TimeoutExpired: + raise pytest.fail.Exception( + "Import probe timed out after 300 seconds", pytrace=False + ) from None + if result.returncode: + pytest.fail( + f"Import probe exited with status {result.returncode}", pytrace=False + ) + try: + return json.loads(result.stdout.splitlines()[-1]) + except (IndexError, UnicodeDecodeError, json.JSONDecodeError): + raise pytest.fail.Exception( + "Import probe returned invalid JSON", pytrace=False + ) from None + + +@pytest.fixture(scope="module") +def script_imports(tmp_path_factory): + return _run_import_probe( + tmp_path_factory.mktemp("script-imports"), SCRIPTS_DIR, SCRIPT_NAMES, warm=True + ) + + +def test_the_probe_covers_the_release_scripts(): + assert {"bundle", "certify_data_release", "generate_bundle_artifacts"} <= set( + SCRIPT_NAMES + ) + + +@pytest.mark.parametrize("name", SCRIPT_NAMES) +def test_importing_a_script_leaves_sys_path_alone(script_imports, name): + outcome = script_imports[name] + assert "error" not in outcome, outcome + assert not outcome["path_changed"], f"importing scripts/{name}.py changed sys.path" + + +@pytest.mark.parametrize("name", SCRIPT_NAMES) +def test_importing_a_script_leaves_the_environment_alone(script_imports, name): + outcome = script_imports[name] + assert "error" not in outcome, outcome + assert outcome["environment_changes"] == [] + + +def test_import_probe_resolves_relative_pythonpath(tmp_path, monkeypatch): + source = tmp_path / "src" + source.mkdir() + (source / "probe_dependency.py").touch() + scripts = tmp_path / "scripts" + scripts.mkdir() + (scripts / "probe_script.py").write_text("import probe_dependency\n") + child = tmp_path / "child" + child.mkdir() + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("PYTHONPATH", "src") + + outcome = _run_import_probe(child, scripts, ["probe_script"], warm=True)[ + "probe_script" + ] + assert "error" not in outcome, outcome + + +def test_import_probe_reports_only_changed_environment_names(tmp_path, monkeypatch): + monkeypatch.setenv("PROBE_REMOVED", "fixture-old") + monkeypatch.setenv("PROBE_UPDATED", "fixture-before") + monkeypatch.delenv("PROBE_ADDED", raising=False) + (tmp_path / "probe_script.py").write_text( + "import os\n" + "del os.environ['PROBE_REMOVED']\n" + "os.environ['PROBE_UPDATED'] = 'fixture-after'\n" + "os.environ['PROBE_ADDED'] = ''\n" + ) + + outcome = _run_import_probe(tmp_path, tmp_path, ["probe_script"], warm=True)[ + "probe_script" + ] + assert "error" not in outcome, outcome + assert outcome["environment_changes"] == [ + "PROBE_ADDED", + "PROBE_REMOVED", + "PROBE_UPDATED", + ] + + +def test_import_probe_reports_only_safe_import_failure_details(tmp_path, monkeypatch): + value = "fixture-value" + monkeypatch.setenv("PROBE_DUMMY_TOKEN", value) + (tmp_path / "probe_script.py").write_text( + "import os, sys\n" + "class ProbeError(RuntimeError):\n" + " def __format__(self, spec):\n" + " return 'extra diagnostic'\n" + "value = os.environ.pop('PROBE_DUMMY_TOKEN')\n" + "sys.path.append(value)\n" + "raise ProbeError(value)\n" + ) + + outcome = _run_import_probe(tmp_path, tmp_path, ["probe_script"])["probe_script"] + assert value not in json.dumps(outcome) + assert outcome == { + "error": "ProbeError", + "path_changed": True, + "environment_changes": ["PROBE_DUMMY_TOKEN"], + "policyengine_imported": False, + } + + +def test_import_probe_reports_only_subprocess_exit_status(tmp_path, monkeypatch): + value = "fixture-value" + monkeypatch.setenv("PROBE_DUMMY_TOKEN", value) + (tmp_path / "probe_script.py").write_text( + "import os, sys\n" + "value = os.environ['PROBE_DUMMY_TOKEN']\n" + "print(value, flush=True)\n" + "print(value, file=sys.stderr, flush=True)\n" + "os._exit(17)\n" + ) + + with pytest.raises(pytest.fail.Exception) as failure: + _run_import_probe(tmp_path, tmp_path, ["probe_script"]) + assert value not in str(failure.value) + assert str(failure.value) == "Import probe exited with status 17" + + +def test_cold_import_probe_detects_policyengine_side_effects(tmp_path, monkeypatch): + (tmp_path / "policyengine.py").write_text( + "import os\n" + "if 'POLICYENGINE_SKIP_COUNTRY_IMPORTS' not in os.environ:\n" + " os.environ['PROBE_COLD_IMPORT'] = 'fixture-value'\n" + ) + (tmp_path / "probe_script.py").write_text("import policyengine\n") + monkeypatch.delenv("PROBE_COLD_IMPORT", raising=False) + monkeypatch.setenv(SKIP_COUNTRY_IMPORTS, "1") + + outcome = _run_import_probe(tmp_path, tmp_path, ["probe_script"])["probe_script"] + assert "error" not in outcome, outcome + assert "PROBE_COLD_IMPORT" in outcome["environment_changes"] + + +def test_cold_import_of_certify_data_release_leaves_the_interpreter_alone(tmp_path): + name = "certify_data_release" + outcome = _run_import_probe(tmp_path, SCRIPTS_DIR, [name])[name] + assert "error" not in outcome, outcome + assert outcome["policyengine_imported"] + assert not outcome["path_changed"] + assert outcome["environment_changes"] == [] + + +def test_collecting_tests_leaves_sys_path_alone(pytestconfig): + assert pytestconfig.stash[COLLECTION_IMPORT_PATH_CHANGES] == [] + + +def test_policyengine_metadata_is_read_as_in_a_fresh_interpreter(): + """Nothing in the session changes which policyengine metadata is read. + + A fresh interpreter in the same environment is the baseline, so a setup + that reads ``src``'s egg-info from the start (``PYTHONPATH=src``) passes. + """ + + fresh = subprocess.run( + [ + sys.executable, + "-c", + "from importlib import metadata; " + "print(metadata.distribution('policyengine').locate_file(''))", + ], + cwd=CHECKOUT, + capture_output=True, + text=True, + timeout=120, + check=True, + ) + here = metadata.distribution("policyengine").locate_file("") + assert Path(here).resolve() == Path(fresh.stdout.strip()).resolve() + + +SRC = str(CHECKOUT / "src") +CHECKOUT_ENTRIES = [SRC, str(SCRIPTS_DIR), str(CHECKOUT)] +OUTSIDE_ENTRIES = ["/opt/python/lib", "/opt/python/site-packages", "/opt/vendor"] +paths = st.lists(st.sampled_from(CHECKOUT_ENTRIES + OUTSIDE_ENTRIES), max_size=8) + + +def test_a_second_src_ahead_of_site_packages_is_a_change(): + # An editable install's .pth lists src after site-packages, so prepending + # the same string adds no new entry but changes which metadata is read. + before = ["/opt/python/lib", "/opt/python/site-packages", SRC] + assert import_path_changes(before, [SRC, *before]) == [f"added another {SRC!r}"] + + +@given(paths) +def test_an_unchanged_path_has_no_changes(path): + assert import_path_changes(path, list(path)) == [] + + +@given(paths, st.data()) +def test_adding_a_checkout_entry_anywhere_is_a_change(path, data): + index = data.draw(st.integers(0, len(path))) + entry = data.draw(st.sampled_from(CHECKOUT_ENTRIES)) + assert import_path_changes(path, [*path[:index], entry, *path[index:]]) + + +@given(paths, st.data()) +def test_adding_a_new_entry_outside_the_checkout_is_not_a_change(path, data): + index = data.draw(st.integers(0, len(path))) + after = [*path[:index], "/opt/new", *path[index:]] + assert import_path_changes(path, after) == [] + + +@given(paths.filter(bool), st.data()) +def test_removing_an_entry_is_a_change(path, data): + index = data.draw(st.integers(0, len(path) - 1)) + assert import_path_changes(path, [*path[:index], *path[index + 1 :]]) + + +@given(paths, st.data()) +def test_reordering_entries_is_a_change_exactly_when_the_order_differs(path, data): + after = data.draw(st.permutations(path)) + assert bool(import_path_changes(path, after)) == (list(after) != path) + + +def test_bundle_can_run_when_imported_from_the_checkout(): + code = """ +import os +import sys + +path, environment = list(sys.path), dict(os.environ) +from scripts import bundle, certify_data_release +assert callable(certify_data_release.main) +assert bundle.main(["check"]) == 0 +assert sys.path == path +assert dict(os.environ) == environment +""" + result = subprocess.run( + [sys.executable, "-c", code], + cwd=CHECKOUT, + capture_output=True, + text=True, + timeout=120, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_bundle_main_prefers_this_checkout_scripts(tmp_path): + other_scripts = tmp_path / "scripts" + other_scripts.mkdir() + (other_scripts / "generate_trace_tros.py").touch() + code = """ +import sys +from importlib.util import find_spec +from pathlib import Path + +from scripts import bundle + +other_scripts, scripts_dir = sys.argv[1:] +sys.path[:0] = [other_scripts, scripts_dir] +path = list(sys.path) + +def check_tros(*, strict): + helper = find_spec("generate_trace_tros") + assert helper.origin == str(Path(scripts_dir, "generate_trace_tros.py")), helper.origin + return 0 + +bundle._check_tros = check_tros +assert bundle.main(["check", "--include-tros"]) == 0 +assert sys.path == path +""" + result = subprocess.run( + [sys.executable, "-c", code, str(other_scripts), str(SCRIPTS_DIR)], + cwd=CHECKOUT, + capture_output=True, + text=True, + timeout=120, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + + +def _cache_script(monkeypatch, name, directory): + spec = spec_from_file_location(name, directory / f"{name}.py") + assert spec is not None and spec.loader is not None + module = module_from_spec(spec) + monkeypatch.setitem(sys.modules, name, module) + spec.loader.exec_module(module) + return module + + +@pytest.mark.parametrize( + ("foreign_generator", "cached_dependency"), + [(True, True), (False, True), (False, False)], + ids=["foreign-generator", "local-generator", "evicted-dependency"], +) +def test_bundle_main_replaces_a_cached_foreign_tro_helper( + tmp_path, monkeypatch, foreign_generator, cached_dependency +): + from policyengine.provenance import manifest + from scripts import bundle + + def fetch_data_manifest(country): + helper = sys._getframe(1).f_globals + invoked.append(Path(helper["__file__"]).resolve()) + invoked.append( + Path(helper["validate_registry_artifacts"].__code__.co_filename).resolve() + ) + raise stopped + + invoked = [] + stopped = RuntimeError("Reached the local data-fetch stub") + monkeypatch.setattr(manifest, "get_data_release_manifest", fetch_data_manifest) + + other_scripts = tmp_path / "other" / "scripts" + other_scripts.mkdir(parents=True) + for filename in ("release_lock.py", "generate_trace_tros.py"): + shutil.copyfile(SCRIPTS_DIR / filename, other_scripts / filename) + monkeypatch.syspath_prepend(str(other_scripts)) + release_lock = _cache_script(monkeypatch, "release_lock", other_scripts) + generator = _cache_script( + monkeypatch, + "generate_trace_tros", + other_scripts if foreign_generator else SCRIPTS_DIR, + ) + if not cached_dependency: + monkeypatch.delitem(sys.modules, "release_lock") + path, entries = sys.path, sys.path[:] + + with pytest.raises(RuntimeError) as error: + bundle.main(["check", "--include-tros"]) + + assert error.value is stopped + assert sys.path is path and sys.path == entries + assert sys.modules["generate_trace_tros"] is generator + if cached_dependency: + assert sys.modules["release_lock"] is release_lock + else: + assert "release_lock" not in sys.modules + assert invoked == [ + SCRIPTS_DIR / "generate_trace_tros.py", + SCRIPTS_DIR / "release_lock.py", + ] + + +def test_bundle_main_uses_local_artifacts_for_a_cached_package_updater( + tmp_path, monkeypatch +): + from scripts import bundle + + other = tmp_path / "other" + for filename in ( + "scripts/generate_bundle_artifacts.py", + "src/policyengine/provenance/bundle_validation.py", + ): + target = other / filename + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(CHECKOUT / filename, target) + + invoked = [] + stopped = RuntimeError("Stop before writing the bundle") + + def stop_on_manifest_load(module): + def load(): + invoked.append(Path(module.__file__).resolve()) + raise stopped + + monkeypatch.setattr(module, "load_bundle_manifest", load) + + artifacts_name = "generate_bundle_artifacts" + updater_name = "prepare_package_bundle_update" + local_artifacts = _cache_script(monkeypatch, artifacts_name, SCRIPTS_DIR) + stop_on_manifest_load(local_artifacts) + foreign_artifacts = _cache_script(monkeypatch, artifacts_name, other / "scripts") + stop_on_manifest_load(foreign_artifacts) + updater = _cache_script(monkeypatch, updater_name, SCRIPTS_DIR) + monkeypatch.setitem(sys.modules, artifacts_name, local_artifacts) + + with pytest.raises(RuntimeError) as error: + bundle.main(["update-packages", "--uk", "1.0.0"]) + + assert error.value is stopped + assert invoked == [SCRIPTS_DIR / f"{artifacts_name}.py"] + assert sys.modules[artifacts_name] is local_artifacts + assert sys.modules[updater_name] is updater + + +@pytest.fixture +def overlapping_calls(monkeypatch): + ready = [Event(), Event()] + release = [Event(), Event()] + next_call = iter(range(2)) + + def pause(): + index = next(next_call) + ready[index].set() + assert release[index].wait(30) + + def run(first, second, second_module, lock_name): + lock = getattr(second_module, lock_name) + + class ObservedLock: + def __enter__(self): + if not lock.acquire(blocking=False): + # A holds the lock. Let it finish even though B cannot + # reach the callback yet. + ready[1].set() + lock.acquire() + + def __exit__(self, *exc): + lock.release() + + monkeypatch.setattr(second_module, lock_name, ObservedLock()) + + with ThreadPoolExecutor(max_workers=2) as pool: + first_call = pool.submit(first) + try: + assert ready[0].wait(30) + second_call = pool.submit(second) + assert ready[1].wait(30) + release[0].set() + assert wait([first_call], timeout=30).done + finally: + for event in release: + event.set() + return first_call, second_call + + return pause, run + + +def test_overlapping_bundle_calls_restore_the_import_state( + monkeypatch, overlapping_calls +): + from scripts import bundle + + alias = _cache_script(monkeypatch, "bundle", SCRIPTS_DIR) + pause, run = overlapping_calls + + def check(args): + pause() + return 0 + + monkeypatch.setattr(bundle, "_check", check) + monkeypatch.setattr(alias, "_check", check) + monkeypatch.setattr(sys, "path", [*sys.path, str(SCRIPTS_DIR)]) + name = "generate_trace_tros" + sentinel = ModuleType(name) + sentinel.__file__ = str(SCRIPTS_DIR.parent / "other" / f"{name}.py") + monkeypatch.setitem(sys.modules, name, sentinel) + path, entries = sys.path, sys.path[:] + + calls = run( + lambda: bundle.main(["check"]), + lambda: alias.main(["check"]), + alias, + "_COMMAND_IMPORT_LOCK", + ) + + assert [call.result() for call in calls] == [0, 0] + assert sys.path is path and sys.path == entries + assert sys.modules.get(name) is sentinel + + +def test_overlapping_vector_builds_restore_the_import_state( + monkeypatch, overlapping_calls +): + from scripts import generate_ordered_scenario_vectors as generator + + alias = _cache_script(monkeypatch, "generate_ordered_scenario_vectors", SCRIPTS_DIR) + pause, run = overlapping_calls + build = generator._build_vectors + + def build_after_pause(modifiers): + pause() + return build(modifiers) + + monkeypatch.setattr(generator, "_build_vectors", build_after_pause) + monkeypatch.setattr(alias, "_build_vectors", build_after_pause) + name = "tests.ordered_receipt_modifiers" + sentinel = ModuleType(name) + monkeypatch.setitem(sys.modules, name, sentinel) + path, entries = sys.path, sys.path[:] + expected = json.loads(generator.PATH.read_bytes()) + + calls = run( + generator.build_vectors, alias.build_vectors, alias, "_MODIFIER_IMPORT_LOCK" + ) + + assert sys.path is path and sys.path == entries + assert ([call.exception() for call in calls], sys.modules.get(name)) == ( + [None, None], + sentinel, + ) + assert all(call.result() == expected for call in calls) + + +@pytest.mark.parametrize("script", ["bundle", "generate_ordered_scenario_vectors"]) +def test_maintenance_entry_points_restore_import_state_after_reentry(script): + code = """ +import importlib +import json +import sys +from types import ModuleType + +name = sys.argv[1] +script = importlib.import_module(f"scripts.{name}") +if name == "bundle": + def call(): + return script.main(["check"]) + + def build(args): + return 0 + + callback = "_check" + key = "generate_trace_tros" + expected = 0 +else: + call = script.build_vectors + build = script._build_vectors + callback = "_build_vectors" + key = "tests.ordered_receipt_modifiers" + expected = json.loads(script.PATH.read_bytes()) + +results = [] +entered = False + +def reenter(*args): + global entered + if not entered: + entered = True + original = sys.modules.get(key) + path, entries = sys.path, sys.path[:] + results.append(call()) + assert sys.modules.get(key) is original + assert sys.path is path and sys.path == entries + elif name == "bundle": + sys.modules[key] = ModuleType(key) + return build(*args) + +setattr(script, callback, reenter) +sentinel = sys.modules[key] = ModuleType(key) +path, entries = sys.path, sys.path[:] +results.append(call()) +assert results == [expected, expected] +assert sys.modules[key] is sentinel +assert sys.path is path and sys.path == entries +""" + result = subprocess.run( + [sys.executable, "-c", code, script], + cwd=CHECKOUT, + env={**os.environ, SKIP_COUNTRY_IMPORTS: "1"}, + capture_output=True, + text=True, + timeout=120, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize("seeded", [True, False], ids=["cached", "absent"]) +def test_vector_build_restores_the_modifier_module_after_an_error(monkeypatch, seeded): + from scripts import generate_ordered_scenario_vectors as generator + + name = "tests.ordered_receipt_modifiers" + sentinel = ModuleType(name) + if seeded: + monkeypatch.setitem(sys.modules, name, sentinel) + else: + monkeypatch.delitem(sys.modules, name, raising=False) + failure = RuntimeError("Build failed") + + def fail(modifiers): + assert sys.modules[name] is modifiers + raise failure + + monkeypatch.setattr(generator, "_build_vectors", fail) + with pytest.raises(RuntimeError) as error: + generator.build_vectors() + + assert error.value is failure + if seeded: + assert sys.modules[name] is sentinel + else: + assert name not in sys.modules + + +def test_ordered_scenario_vectors_build_outside_the_checkout(tmp_path): + code = """ +import json +import sys + +import generate_ordered_scenario_vectors as generator + +path = list(sys.path) +assert str(generator.ROOT) not in path +vectors = generator.build_vectors() +assert sys.path == path +content = json.dumps(vectors, indent=2, sort_keys=True) + "\\n" +assert content.encode() == generator.PATH.read_bytes() +assert { + leaf["module"] + for case in vectors["valid"] + for phase in ("before", "after") + for leaf in case["plan"][phase]["modifier_leaves"] +} == {"tests.ordered_receipt_modifiers"} +""" + environment = { + **os.environ, + "PYTHONPATH": os.pathsep.join((str(SCRIPTS_DIR), str(CHECKOUT / "src"))), + "POLICYENGINE_SKIP_COUNTRY_IMPORTS": "1", + } + result = subprocess.run( + [sys.executable, "-c", code], + cwd=tmp_path, + env=environment, + capture_output=True, + text=True, + timeout=120, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize( + "arguments", + [ + ("-S", "scripts/bundle.py", "check"), + ("scripts/certify_data_release.py", "--help"), + ("scripts/generate_receipt_schemas.py", "--check"), + ], +) +def test_entry_points_set_up_their_own_imports(arguments): + environment = { + key: value for key, value in os.environ.items() if key != SKIP_COUNTRY_IMPORTS + } + result = subprocess.run( + [sys.executable, *arguments], + cwd=CHECKOUT, + env=environment, + capture_output=True, + text=True, + timeout=300, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tests/test_spm_bundle_tooling.py b/tests/test_spm_bundle_tooling.py index e5adbe59f..75cabe1b2 100644 --- a/tests/test_spm_bundle_tooling.py +++ b/tests/test_spm_bundle_tooling.py @@ -2,9 +2,7 @@ import copy import hashlib -import sys import zipfile -from pathlib import Path from types import SimpleNamespace import pytest @@ -16,19 +14,23 @@ validate_bundle_measurements, ) from policyengine.provenance.spm_configuration import SPMMeasurementConfiguration +from tests.fixtures.import_path import scripts_importable -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) -import bundle as maintenance # noqa: E402 -from generate_bundle_artifacts import ( # noqa: E402 - load_bundle_manifest, - normalized_manifest, -) -from spm_bundle import ( # noqa: E402 - configure_spm, - development_manifest, - published_calculator_component, - write_development_manifest, -) +with scripts_importable(): + import bundle as maintenance + from generate_bundle_artifacts import ( + load_bundle_manifest, + normalized_manifest, + ) + from spm_bundle import ( + configure_spm, + development_manifest, + published_calculator_component, + write_development_manifest, + ) + +# The maintenance CLI imports its sibling scripts when a command runs. +pytestmark = pytest.mark.usefixtures("scripts_on_path") @pytest.fixture