From 83e5b5c0948d54a1522b6a4ebedd3b8f3670e2e2 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 15 Oct 2026 05:18:53 -0400 Subject: [PATCH 01/13] Guard against scripts and tests changing sys.path for the session Importing scripts/bundle.py, certify_data_release.py, generate_bundle_artifacts.py or generate_receipt_schemas.py puts the checkout's src first on sys.path, and the last two also set POLICYENGINE_SKIP_COUNTRY_IMPORTS. Three test modules import those scripts at module level, so the changes outlive collection, and with an editable setuptools install importlib.metadata then reads src/policyengine.egg-info for every later test (#623). These tests fail on main and pass once the next commit lands: - each script, imported in a fresh interpreter, must leave sys.path and os.environ as they were; - collecting the test modules must add no checkout directory to sys.path (recorded by conftest at collection finish); - policyengine's metadata must not come from the source tree when it is installed elsewhere; - an autouse fixture fails any test that leaves a checkout directory on sys.path; - the entry points that import at module level still start. Co-Authored-By: Claude Opus 5.5 --- changelog.d/623.fixed.md | 1 + tests/conftest.py | 24 ++++++ tests/fixtures/import_path.py | 78 +++++++++++++++++++ tests/test_script_imports.py | 141 ++++++++++++++++++++++++++++++++++ 4 files changed, 244 insertions(+) create mode 100644 changelog.d/623.fixed.md create mode 100644 tests/fixtures/import_path.py create mode 100644 tests/test_script_imports.py diff --git a/changelog.d/623.fixed.md b/changelog.d/623.fixed.md new file mode 100644 index 000000000..08836483f --- /dev/null +++ b/changelog.d/623.fixed.md @@ -0,0 +1 @@ +Maintenance scripts no longer change `sys.path` or `os.environ` when imported; only their entry points set up the import path and environment they run with. Tests import the scripts without leaving the checkout's `src` or `scripts` on `sys.path`, so `importlib.metadata` no longer reads `src/policyengine.egg-info` as the installed distribution for the rest of a test session. diff --git a/tests/conftest.py b/tests/conftest.py index 0f7300054..469070964 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 @@ -9,6 +11,12 @@ uk_test_dataset, us_test_dataset, ) +from tests.fixtures.import_path import ( # noqa: F401 + ADDED_BY_COLLECTION, + checkout_entries_added, + checkout_stays_off_import_path, + scripts_on_path, +) from tests.fixtures.parametric_reforms_fixtures import ( # noqa: F401 mock_param_joint, mock_param_single, @@ -27,6 +35,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 any checkout directory that importing the test modules added. + + ``tests/test_script_imports.py`` fails on it; a test module that put + ``src`` or ``scripts`` on ``sys.path`` would leave it there for the session. + """ + + session.config.stash[ADDED_BY_COLLECTION] = checkout_entries_added( + _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..d5a9e2f6f --- /dev/null +++ b/tests/fixtures/import_path.py @@ -0,0 +1,78 @@ +"""Keep this checkout's directories off the interpreter's import path. + +An editable setuptools install leaves ``src/policyengine.egg-info`` in the +checkout. If a test session puts ``src`` ahead of site-packages on +``sys.path``, ``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 sys +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" + +#: Entries inside this checkout that collecting the test modules added to +#: ``sys.path``, recorded by ``tests/conftest.py`` when collection finishes. +ADDED_BY_COLLECTION = pytest.StashKey[list[str]]() + + +def checkout_entries_added(before: Iterable[str], after: Iterable[str]) -> list[str]: + """Entries of ``after`` that ``before`` lacks and that point into this checkout.""" + + known = set(before) + added = [] + for entry in after: + if entry in known or not isinstance(entry, str): + continue + if Path(entry or ".").resolve().is_relative_to(CHECKOUT): + added.append(entry) + return added + + +@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 a checkout directory on ``sys.path``.""" + + before = list(sys.path) + yield + added = checkout_entries_added(before, sys.path) + if added: + pytest.fail( + f"The test left {added} on sys.path. Import scripts inside " + "tests.fixtures.import_path.scripts_importable() or use the " + "scripts_on_path fixture, which restore the import path.", + pytrace=False, + ) diff --git a/tests/test_script_imports.py b/tests/test_script_imports.py new file mode 100644 index 000000000..896d719c5 --- /dev/null +++ b/tests/test_script_imports.py @@ -0,0 +1,141 @@ +"""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). Only a +script's entry point, under ``if __name__ == "__main__":``, sets up the import +path or environment it runs with. +""" + +import json +import os +import subprocess +import sys +from importlib import metadata +from pathlib import Path + +import pytest + +from tests.fixtures.import_path import ADDED_BY_COLLECTION, CHECKOUT, SCRIPTS_DIR + +SCRIPT_NAMES = sorted(path.stem for path in SCRIPTS_DIR.glob("*.py")) +SKIP_COUNTRY_IMPORTS = "POLICYENGINE_SKIP_COUNTRY_IMPORTS" + +# Runs in a fresh interpreter, so no earlier import is cached and each script's +# module code (and its sibling scripts') runs again for every name. +PROBE = """ +import importlib, json, os, sys + +scripts_dir, names = sys.argv[1], sys.argv[2:] +# Import policyengine once without the country models: the scripts' imports of +# it are then cheap, and an environment default a script sets stays visible. +os.environ["POLICYENGINE_SKIP_COUNTRY_IMPORTS"] = "1" +import policyengine +del os.environ["POLICYENGINE_SKIP_COUNTRY_IMPORTS"] +sys.path.insert(0, scripts_dir) +results = {} +for name in names: + for script in names: + sys.modules.pop(script, None) + path, environment = list(sys.path), dict(os.environ) + try: + importlib.import_module(name) + except BaseException as error: + results[name] = {"error": f"{type(error).__name__}: {error}"} + else: + results[name] = { + "path_before": path, + "path_after": list(sys.path), + "environment_changes": { + key: [environment.get(key), os.environ.get(key)] + for key in sorted(set(environment) | set(os.environ)) + if environment.get(key) != os.environ.get(key) + }, + } + sys.path[:] = path + os.environ.clear() + os.environ.update(environment) +print(json.dumps(results)) +""" + + +@pytest.fixture(scope="module") +def script_imports(tmp_path_factory): + environment = { + key: value for key, value in os.environ.items() if key != SKIP_COUNTRY_IMPORTS + } + result = subprocess.run( + [sys.executable, "-c", PROBE, str(SCRIPTS_DIR), *SCRIPT_NAMES], + cwd=tmp_path_factory.mktemp("script-imports"), + env=environment, + capture_output=True, + text=True, + timeout=300, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + return json.loads(result.stdout.splitlines()[-1]) + + +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.get("error") + before, after = outcome["path_before"], outcome["path_after"] + assert after == before, ( + f"importing scripts/{name}.py added {[e for e in after if e not in before]} " + f"and removed {[e for e in before if e not in after]}" + ) + + +@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.get("error") + assert outcome["environment_changes"] == {} + + +def test_collecting_tests_adds_no_checkout_directory_to_sys_path(pytestconfig): + assert pytestconfig.stash[ADDED_BY_COLLECTION] == [] + + +def test_policyengine_metadata_is_not_read_from_the_source_tree(): + src = (CHECKOUT / "src").resolve() + locations = [ + Path(distribution.locate_file("")).resolve() + for distribution in metadata.distributions(name="policyengine") + ] + if all(location == src for location in locations): + pytest.skip("policyengine is installed only from the checkout's src") + # importlib.metadata.distribution() returns the first one on sys.path. + assert locations[0] != src + + +@pytest.mark.parametrize( + "arguments", + [ + ("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 From 10102a4a38f08e2d8b4297306bb7da7a9a832d40 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 15 Oct 2026 05:22:03 -0400 Subject: [PATCH 02/13] Set up the import path and environment only in script entry points bundle.py, certify_data_release.py and generate_receipt_schemas.py now put the checkout's src (and scripts) on sys.path and default POLICYENGINE_SKIP_COUNTRY_IMPORTS=1 only under `if __name__ == "__main__":`, which is the setup they already ran with: every bundle.py subcommand and certify_data_release.py imported generate_bundle_artifacts, which set both, before importing policyengine. generate_bundle_artifacts.py imports nothing from policyengine, so it now sets up nothing; bundle.py's _generate_tros and _check_tros stop setting the variable when called, which leaked it into later tests' subprocesses. The three test modules that imported scripts after a module-level sys.path.insert now import them inside scripts_importable(), which restores sys.path exactly, and use the scripts_on_path fixture for tests whose code imports sibling scripts when it runs. The receipt tests' _import_path_as_collected fixture stays as defence in depth; its comment now says so. Fixes #623 Co-Authored-By: Claude Opus 5.5 --- scripts/bundle.py | 10 ++++++---- scripts/certify_data_release.py | 10 ++++++++-- scripts/generate_bundle_artifacts.py | 5 ----- scripts/generate_receipt_schemas.py | 9 +++++++-- tests/test_execution_receipt.py | 12 +++++------ tests/test_generate_trace_tros.py | 7 +++---- tests/test_release_tro_generation.py | 13 ++++++++---- tests/test_spm_bundle_tooling.py | 30 +++++++++++++++------------- 8 files changed, 55 insertions(+), 41 deletions(-) diff --git a/scripts/bundle.py b/scripts/bundle.py index 121ab8e29..43ba2b5c2 100644 --- a/scripts/bundle.py +++ b/scripts/bundle.py @@ -21,8 +21,6 @@ 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")) def _certify_data(args: argparse.Namespace) -> int: @@ -133,7 +131,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) @@ -153,7 +150,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 @@ -328,4 +324,10 @@ def main(argv: list[str] | None = None) -> int: if __name__ == "__main__": + # Every subcommand runs on this checkout's policyengine, whatever is + # installed, without importing the country models. Only the entry point + # sets this up, so importing this module (as tests do) leaves the import + # path and environment alone. + os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") + sys.path[:0] = [str(REPO_ROOT / "src"), str(REPO_ROOT / "scripts")] raise SystemExit(main()) diff --git a/scripts/certify_data_release.py b/scripts/certify_data_release.py index 8842adbb0..9b42bc6d8 100644 --- a/scripts/certify_data_release.py +++ b/scripts/certify_data_release.py @@ -25,8 +25,14 @@ 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")) + +if __name__ == "__main__": + # Certify with this checkout's policyengine, whatever is installed, without + # importing the country models. Only the entry point sets this up, so + # importing this module (as tests do) leaves the import path and + # environment alone. + os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") + sys.path[:0] = [str(REPO_ROOT / "src"), str(REPO_ROOT / "scripts")] from generate_bundle_artifacts import generate # noqa: E402 diff --git a/scripts/generate_bundle_artifacts.py b/scripts/generate_bundle_artifacts.py index cdbfaea79..22a0d7e66 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_receipt_schemas.py b/scripts/generate_receipt_schemas.py index 8340948ec..418d83aac 100644 --- a/scripts/generate_receipt_schemas.py +++ b/scripts/generate_receipt_schemas.py @@ -21,8 +21,13 @@ 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 the schemas from this checkout's models, whatever is installed, + # without importing the country models. Only the entry point sets this up, + # so importing this module leaves the import path and environment alone. + os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") + sys.path.insert(0, str(REPO_ROOT / "src")) from policyengine.provenance.receipt import ExecutionReceipt # noqa: E402 diff --git a/tests/test_execution_receipt.py b/tests/test_execution_receipt.py index e9a96ba53..f8e531329 100644 --- a/tests/test_execution_receipt.py +++ b/tests/test_execution_receipt.py @@ -150,12 +150,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 69ffd6a82..4a913e954 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_spm_bundle_tooling.py b/tests/test_spm_bundle_tooling.py index ea3c00973..978e377b1 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 From 02a330f8e4f41e0527de29ab90047269c953e975 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 15 Oct 2026 07:35:23 -0400 Subject: [PATCH 03/13] Catch a second src ahead of site-packages; allow PYTHONPATH=src Review findings on the guards: - The collection check and the per-test fixture compared sys.path as sets, so prepending a second copy of src went unseen. An editable install's .pth already lists src after site-packages, and that copy in front is exactly what makes importlib.metadata read src/policyengine.egg-info. import_path_changes() now also reports any change to the number or order of the entries sys.path already had, and still ignores new entries outside the checkout. Hypothesis properties pin it down: no change reports nothing; adding a checkout entry anywhere, removing an entry, or reordering is reported; adding a new outside entry is not. - The metadata test failed a deliberate PYTHONPATH=src setup. It now compares the metadata the session reads with what a fresh interpreter in the same environment reads, so only a change made during the session fails it. The per-test fixture also fails a test that leaves POLICYENGINE_SKIP_COUNTRY_IMPORTS changed. Co-Authored-By: Claude Opus 5.5 --- tests/conftest.py | 10 ++-- tests/fixtures/import_path.py | 83 +++++++++++++++++++++---------- tests/test_script_imports.py | 93 +++++++++++++++++++++++++++++------ 3 files changed, 141 insertions(+), 45 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 469070964..f6522b111 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -12,9 +12,9 @@ us_test_dataset, ) from tests.fixtures.import_path import ( # noqa: F401 - ADDED_BY_COLLECTION, - checkout_entries_added, + COLLECTION_IMPORT_PATH_CHANGES, checkout_stays_off_import_path, + import_path_changes, scripts_on_path, ) from tests.fixtures.parametric_reforms_fixtures import ( # noqa: F401 @@ -40,13 +40,13 @@ def pytest_collection_finish(session): - """Record any checkout directory that importing the test modules added. + """Record how importing the test modules changed ``sys.path``. - ``tests/test_script_imports.py`` fails on it; a test module that put + ``tests/test_script_imports.py`` fails on any change; a test module that put ``src`` or ``scripts`` on ``sys.path`` would leave it there for the session. """ - session.config.stash[ADDED_BY_COLLECTION] = checkout_entries_added( + session.config.stash[COLLECTION_IMPORT_PATH_CHANGES] = import_path_changes( _IMPORT_PATH_BEFORE_COLLECTION, sys.path ) diff --git a/tests/fixtures/import_path.py b/tests/fixtures/import_path.py index d5a9e2f6f..aba0af8ae 100644 --- a/tests/fixtures/import_path.py +++ b/tests/fixtures/import_path.py @@ -1,17 +1,20 @@ """Keep this checkout's directories off the interpreter's import path. An editable setuptools install leaves ``src/policyengine.egg-info`` in the -checkout. If a test session puts ``src`` ahead of site-packages on -``sys.path``, ``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. +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 @@ -21,22 +24,45 @@ CHECKOUT = Path(__file__).resolve().parents[2] SCRIPTS_DIR = CHECKOUT / "scripts" -#: Entries inside this checkout that collecting the test modules added to -#: ``sys.path``, recorded by ``tests/conftest.py`` when collection finishes. -ADDED_BY_COLLECTION = pytest.StashKey[list[str]]() +#: 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 checkout_entries_added(before: Iterable[str], after: Iterable[str]) -> list[str]: - """Entries of ``after`` that ``before`` lacks and that point into this checkout.""" +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) - added = [] - for entry in after: - if entry in known or not isinstance(entry, str): - continue - if Path(entry or ".").resolve().is_relative_to(CHECKOUT): - added.append(entry) - return added + 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 @@ -64,15 +90,22 @@ def scripts_on_path(monkeypatch): @pytest.fixture(autouse=True) def checkout_stays_off_import_path(): - """Fail a test that leaves a checkout directory on ``sys.path``.""" + """Fail a test that leaves ``sys.path`` or the country-import switch changed.""" - before = list(sys.path) + path, switch = list(sys.path), os.environ.get(SKIP_COUNTRY_IMPORTS) yield - added = checkout_entries_added(before, sys.path) - if added: + 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( - f"The test left {added} on sys.path. Import scripts inside " - "tests.fixtures.import_path.scripts_importable() or use the " - "scripts_on_path fixture, which restore the import path.", + "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_script_imports.py b/tests/test_script_imports.py index 896d719c5..935951ba1 100644 --- a/tests/test_script_imports.py +++ b/tests/test_script_imports.py @@ -16,11 +16,18 @@ from pathlib import Path import pytest - -from tests.fixtures.import_path import ADDED_BY_COLLECTION, CHECKOUT, SCRIPTS_DIR +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")) -SKIP_COUNTRY_IMPORTS = "POLICYENGINE_SKIP_COUNTRY_IMPORTS" # Runs in a fresh interpreter, so no earlier import is cached and each script's # module code (and its sibling scripts') runs again for every name. @@ -102,20 +109,76 @@ def test_importing_a_script_leaves_the_environment_alone(script_imports, name): assert outcome["environment_changes"] == {} -def test_collecting_tests_adds_no_checkout_directory_to_sys_path(pytestconfig): - assert pytestconfig.stash[ADDED_BY_COLLECTION] == [] +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 :]]) -def test_policyengine_metadata_is_not_read_from_the_source_tree(): - src = (CHECKOUT / "src").resolve() - locations = [ - Path(distribution.locate_file("")).resolve() - for distribution in metadata.distributions(name="policyengine") - ] - if all(location == src for location in locations): - pytest.skip("policyengine is installed only from the checkout's src") - # importlib.metadata.distribution() returns the first one on sys.path. - assert locations[0] != src +@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) @pytest.mark.parametrize( From 317f59c97fa80ab32e3ee8d5d32495af328fc1ac Mon Sep 17 00:00:00 2001 From: Max Ghenis <6076111+MaxGhenis@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:27:17 -0500 Subject: [PATCH 04/13] Keep maintenance script imports isolated after merging main --- changelog.d/623.fixed.md | 2 +- scripts/audit_regional_input_surface.py | 7 ++-- scripts/bundle.py | 13 +++++-- scripts/certify_data_release.py | 11 +++--- scripts/check_uk_candidate.py | 5 ++- scripts/check_uk_uc_floor.py | 3 +- scripts/generate_ordered_scenario_vectors.py | 9 +++-- scripts/generate_receipt_schemas.py | 5 +-- scripts/release_consumers.py | 5 ++- tests/conftest.py | 4 +- tests/test_script_imports.py | 39 +++++++++++++++----- 11 files changed, 67 insertions(+), 36 deletions(-) diff --git a/changelog.d/623.fixed.md b/changelog.d/623.fixed.md index 08836483f..8356fabb6 100644 --- a/changelog.d/623.fixed.md +++ b/changelog.d/623.fixed.md @@ -1 +1 @@ -Maintenance scripts no longer change `sys.path` or `os.environ` when imported; only their entry points set up the import path and environment they run with. Tests import the scripts without leaving the checkout's `src` or `scripts` on `sys.path`, so `importlib.metadata` no longer reads `src/policyengine.egg-info` as the installed distribution for the rest of a test session. +Maintenance scripts leave `sys.path` and `os.environ` unchanged on import. Tests make scripts importable temporarily, so they preserve the import order used to resolve the installed distribution's metadata. 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 6cc49d4b0..3bc7581c8 100644 --- a/scripts/bundle.py +++ b/scripts/bundle.py @@ -372,17 +372,22 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) if getattr(args, "strict_tros", False) and not args.include_tros: parser.error("--strict-tros requires --include-tros") + # Commands use the sibling imports of direct script execution. + original_path = sys.path[:] + scripts_dir = str(REPO_ROOT / "scripts") + if scripts_dir not in original_path: + sys.path.insert(0, scripts_dir) try: return args.func(args) except ValueError as exc: parser.error(str(exc)) + finally: + sys.path[:] = original_path if __name__ == "__main__": - # Every subcommand runs on this checkout's policyengine, whatever is - # installed, without importing the country models. Only the entry point - # sets this up, so importing this module (as tests do) leaves the import - # path and environment alone. + # 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(REPO_ROOT / "scripts")] raise SystemExit(main()) diff --git a/scripts/certify_data_release.py b/scripts/certify_data_release.py index cb48f147d..22cee39d9 100644 --- a/scripts/certify_data_release.py +++ b/scripts/certify_data_release.py @@ -32,14 +32,15 @@ REPO_ROOT = Path(__file__).resolve().parents[1] if __name__ == "__main__": - # Certify with this checkout's policyengine, whatever is installed, without - # importing the country models. Only the entry point sets this up, so - # importing this module (as tests do) leaves the import path and - # environment alone. + # 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")] -from generate_bundle_artifacts import generate # noqa: E402 +if __package__: + from .generate_bundle_artifacts import generate +else: + from generate_bundle_artifacts import generate from policyengine.provenance.certification import ( # noqa: E402 REGIONAL_RELEASE_KINDS, 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_ordered_scenario_vectors.py b/scripts/generate_ordered_scenario_vectors.py index bb7c0e23f..9ce8fb9d0 100644 --- a/scripts/generate_ordered_scenario_vectors.py +++ b/scripts/generate_ordered_scenario_vectors.py @@ -14,20 +14,21 @@ from pathlib import Path 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[:0] = [str(ROOT), 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} def build_vectors(): + from tests import ordered_receipt_modifiers as 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 0313dea29..f9834621a 100644 --- a/scripts/generate_receipt_schemas.py +++ b/scripts/generate_receipt_schemas.py @@ -23,9 +23,8 @@ SCHEMA_DIR = REPO_ROOT / "src" / "policyengine" / "data" / "schemas" if __name__ == "__main__": - # Write the schemas from this checkout's models, whatever is installed, - # without importing the country models. Only the entry point sets this up, - # so importing this module leaves the import path and environment alone. + # 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")) 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/tests/conftest.py b/tests/conftest.py index fc7fd52a1..b5929baa8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -47,8 +47,8 @@ def pytest_collection_finish(session): """Record how importing the test modules changed ``sys.path``. - ``tests/test_script_imports.py`` fails on any change; a test module that put - ``src`` or ``scripts`` on ``sys.path`` would leave it there for the session. + ``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( diff --git a/tests/test_script_imports.py b/tests/test_script_imports.py index 935951ba1..82cbb4746 100644 --- a/tests/test_script_imports.py +++ b/tests/test_script_imports.py @@ -3,9 +3,9 @@ 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). Only a -script's entry point, under ``if __name__ == "__main__":``, sets up the import -path or environment it runs with. +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. """ import json @@ -29,8 +29,8 @@ SCRIPT_NAMES = sorted(path.stem for path in SCRIPTS_DIR.glob("*.py")) -# Runs in a fresh interpreter, so no earlier import is cached and each script's -# module code (and its sibling scripts') runs again for every name. +# Runs outside pytest, with sibling scripts removed from the module cache +# before each import. The installed policyengine package is shared. PROBE = """ import importlib, json, os, sys @@ -96,10 +96,7 @@ def test_importing_a_script_leaves_sys_path_alone(script_imports, name): outcome = script_imports[name] assert "error" not in outcome, outcome.get("error") before, after = outcome["path_before"], outcome["path_after"] - assert after == before, ( - f"importing scripts/{name}.py added {[e for e in after if e not in before]} " - f"and removed {[e for e in before if e not in after]}" - ) + assert after == before, f"importing scripts/{name}.py changed sys.path" @pytest.mark.parametrize("name", SCRIPT_NAMES) @@ -181,9 +178,33 @@ def test_reordering_entries_is_a_change_exactly_when_the_order_differs(path, dat 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 + + @pytest.mark.parametrize( "arguments", [ + ("-S", "scripts/bundle.py", "check"), ("scripts/certify_data_release.py", "--help"), ("scripts/generate_receipt_schemas.py", "--check"), ], From 0e7ef21555668410b7cc4330947ce58ccb82c90d Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 21:54:38 -0500 Subject: [PATCH 05/13] Keep maintenance command imports tied to their checkout Prefer the checkout scripts during bundle commands and load ordered scenario modifiers by file path. Resolve the parent Python path, report changed environment names and probe a cold PolicyEngine import. Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- changelog.d/623.fixed.md | 2 +- scripts/bundle.py | 4 +- scripts/generate_ordered_scenario_vectors.py | 25 ++- tests/test_script_imports.py | 190 +++++++++++++++++-- 4 files changed, 197 insertions(+), 24 deletions(-) diff --git a/changelog.d/623.fixed.md b/changelog.d/623.fixed.md index 8356fabb6..ae1c6059d 100644 --- a/changelog.d/623.fixed.md +++ b/changelog.d/623.fixed.md @@ -1 +1 @@ -Maintenance scripts leave `sys.path` and `os.environ` unchanged on import. Tests make scripts importable temporarily, so they preserve the import order used to resolve the installed distribution's metadata. +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/bundle.py b/scripts/bundle.py index 3bc7581c8..d7f671e4d 100644 --- a/scripts/bundle.py +++ b/scripts/bundle.py @@ -372,10 +372,10 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) if getattr(args, "strict_tros", False) and not args.include_tros: parser.error("--strict-tros requires --include-tros") - # Commands use the sibling imports of direct script execution. + # Prefer this checkout for sibling imports during the command. original_path = sys.path[:] scripts_dir = str(REPO_ROOT / "scripts") - if scripts_dir not in original_path: + if original_path[:1] != [scripts_dir]: sys.path.insert(0, scripts_dir) try: return args.func(args) diff --git a/scripts/generate_ordered_scenario_vectors.py b/scripts/generate_ordered_scenario_vectors.py index 9ce8fb9d0..f67521be2 100644 --- a/scripts/generate_ordered_scenario_vectors.py +++ b/scripts/generate_ordered_scenario_vectors.py @@ -8,6 +8,7 @@ import argparse import copy +import importlib.util import json import os import sys @@ -16,7 +17,7 @@ ROOT = Path(__file__).resolve().parents[1] if __name__ == "__main__": os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") - sys.path[:0] = [str(ROOT), str(ROOT / "src")] + sys.path.insert(0, str(ROOT / "src")) from policyengine.provenance.ordered_scenario import ( # noqa: E402 build_ordered_scenario, @@ -27,8 +28,28 @@ def build_vectors(): - from tests import ordered_receipt_modifiers as modifiers + 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. + 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/tests/test_script_imports.py b/tests/test_script_imports.py index 82cbb4746..e777c2718 100644 --- a/tests/test_script_imports.py +++ b/tests/test_script_imports.py @@ -29,17 +29,21 @@ SCRIPT_NAMES = sorted(path.stem for path in SCRIPTS_DIR.glob("*.py")) -# Runs outside pytest, with sibling scripts removed from the module cache -# before each import. The installed policyengine package is shared. +# 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, names = sys.argv[1], sys.argv[2:] -# Import policyengine once without the country models: the scripts' imports of -# it are then cheap, and an environment default a script sets stays visible. -os.environ["POLICYENGINE_SKIP_COUNTRY_IMPORTS"] = "1" -import policyengine -del os.environ["POLICYENGINE_SKIP_COUNTRY_IMPORTS"] +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: @@ -54,11 +58,12 @@ results[name] = { "path_before": path, "path_after": list(sys.path), - "environment_changes": { - key: [environment.get(key), os.environ.get(key)] + "environment_changes": [ + key for key in sorted(set(environment) | set(os.environ)) if environment.get(key) != os.environ.get(key) - }, + ], + "policyengine_imported": "policyengine" in sys.modules, } sys.path[:] = path os.environ.clear() @@ -67,14 +72,18 @@ """ -@pytest.fixture(scope="module") -def script_imports(tmp_path_factory): - environment = { - key: value for key, value in os.environ.items() if key != SKIP_COUNTRY_IMPORTS - } +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" result = subprocess.run( - [sys.executable, "-c", PROBE, str(SCRIPTS_DIR), *SCRIPT_NAMES], - cwd=tmp_path_factory.mktemp("script-imports"), + [sys.executable, "-c", PROBE, str(scripts_dir), mode, *names], + cwd=cwd, env=environment, capture_output=True, text=True, @@ -85,6 +94,13 @@ def script_imports(tmp_path_factory): return json.loads(result.stdout.splitlines()[-1]) +@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 @@ -103,7 +119,71 @@ def test_importing_a_script_leaves_sys_path_alone(script_imports, name): def test_importing_a_script_leaves_the_environment_alone(script_imports, name): outcome = script_imports[name] assert "error" not in outcome, outcome.get("error") - assert outcome["environment_changes"] == {} + 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.get("error") + + +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.get("error") + assert outcome["environment_changes"] == [ + "PROBE_ADDED", + "PROBE_REMOVED", + "PROBE_UPDATED", + ] + + +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.get("error") + 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.get("error") + assert outcome["policyengine_imported"] + assert outcome["path_after"] == outcome["path_before"] + assert outcome["environment_changes"] == [] def test_collecting_tests_leaves_sys_path_alone(pytestconfig): @@ -201,6 +281,78 @@ def test_bundle_can_run_when_imported_from_the_checkout(): 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 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", [ From 15cf976ac5aa4c4bfc5ae305d2036d48f423d7f4 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 1 Dec 2026 07:03:35 -0500 Subject: [PATCH 06/13] Keep maintenance calls isolated during helper dispatch and vector builds Resolve bundle helpers against the dispatcher checkout and restore its temporary import state after each call. Serialise modifier registration and use the exception message for import probe reports. Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- scripts/bundle.py | 56 ++++-- scripts/generate_ordered_scenario_vectors.py | 23 ++- tests/test_script_imports.py | 194 ++++++++++++++++++- 3 files changed, 251 insertions(+), 22 deletions(-) diff --git a/scripts/bundle.py b/scripts/bundle.py index d7f671e4d..183ade737 100644 --- a/scripts/bundle.py +++ b/scripts/bundle.py @@ -18,9 +18,49 @@ import argparse import os import sys +from contextlib import contextmanager from pathlib import Path - -REPO_ROOT = Path(__file__).resolve().parents[1] +from threading import RLock + +SCRIPTS_DIR = Path(__file__).resolve().parent +REPO_ROOT = SCRIPTS_DIR.parent +_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", +) + + +@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(): + source = getattr(module, "__file__", None) + if not source or Path(source).resolve() != SCRIPTS_DIR / f"{name}.py": + 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: @@ -372,22 +412,16 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) if getattr(args, "strict_tros", False) and not args.include_tros: parser.error("--strict-tros requires --include-tros") - # Prefer this checkout for sibling imports during the command. - original_path = sys.path[:] - scripts_dir = str(REPO_ROOT / "scripts") - if original_path[:1] != [scripts_dir]: - sys.path.insert(0, scripts_dir) try: - return args.func(args) + with _checkout_imports(): + return args.func(args) except ValueError as exc: parser.error(str(exc)) - finally: - sys.path[:] = original_path 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(REPO_ROOT / "scripts")] + sys.path[:0] = [str(REPO_ROOT / "src"), str(SCRIPTS_DIR)] raise SystemExit(main()) diff --git a/scripts/generate_ordered_scenario_vectors.py b/scripts/generate_ordered_scenario_vectors.py index f67521be2..b1ff00cf8 100644 --- a/scripts/generate_ordered_scenario_vectors.py +++ b/scripts/generate_ordered_scenario_vectors.py @@ -13,6 +13,7 @@ import os import sys from pathlib import Path +from threading import RLock ROOT = Path(__file__).resolve().parents[1] if __name__ == "__main__": @@ -25,6 +26,7 @@ PATH = ROOT / "src/policyengine/data/schemas/ordered_scenario_plan.v1.vectors.json" REVISION = {"repository": "PolicyEngine/test", "git_sha": "a" * 40} +_MODIFIER_IMPORT_LOCK = RLock() def build_vectors(): @@ -37,16 +39,17 @@ def build_vectors(): spec.loader.exec_module(modifiers) # The receipt binder looks up modifier functions by their module name. - 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 + 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): diff --git a/tests/test_script_imports.py b/tests/test_script_imports.py index e777c2718..84ab19137 100644 --- a/tests/test_script_imports.py +++ b/tests/test_script_imports.py @@ -6,14 +6,22 @@ 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. + +For successful imports, the probe reports only the names of environment +variables that changed. Import failures report the exception type and message. +Subprocess failures report captured output. """ import json import os 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 @@ -53,7 +61,7 @@ try: importlib.import_module(name) except BaseException as error: - results[name] = {"error": f"{type(error).__name__}: {error}"} + results[name] = {"error": f"{type(error).__name__}: {error!s}"} else: results[name] = { "path_before": path, @@ -162,6 +170,20 @@ def test_import_probe_reports_only_changed_environment_names(tmp_path, monkeypat ] +def test_import_probe_reports_exception_type_and_message(tmp_path, monkeypatch): + monkeypatch.setenv("PROBE_DUMMY_TOKEN", "fixture-value") + (tmp_path / "probe_script.py").write_text( + "import os\n" + "class ProbeError(RuntimeError):\n" + " def __format__(self, spec):\n" + " return 'extra diagnostic'\n" + "raise ProbeError(os.environ.pop('PROBE_DUMMY_TOKEN'))\n" + ) + + outcome = _run_import_probe(tmp_path, tmp_path, ["probe_script"])["probe_script"] + assert outcome == {"error": "ProbeError: fixture-value"} + + def test_cold_import_probe_detects_policyengine_side_effects(tmp_path, monkeypatch): (tmp_path / "policyengine.py").write_text( "import os\n" @@ -316,6 +338,176 @@ def check_tros(*, strict): assert result.returncode == 0, result.stdout + result.stderr +def test_bundle_main_replaces_a_cached_foreign_tro_helper(tmp_path, monkeypatch): + 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 = tmp_path / "other" + subprocess.run( + ["git", "worktree", "add", "--quiet", "--detach", str(other), "HEAD"], + cwd=CHECKOUT, + check=True, + timeout=60, + ) + try: + monkeypatch.syspath_prepend(str(other / "scripts")) + foreign = {} + for name in ("release_lock", "generate_trace_tros"): + spec = spec_from_file_location(name, other / "scripts" / f"{name}.py") + module = module_from_spec(spec) + monkeypatch.setitem(sys.modules, name, module) + spec.loader.exec_module(module) + foreign[name] = module + path = sys.path[:] + + with pytest.raises(RuntimeError) as error: + bundle.main(["check", "--include-tros"]) + + assert error.value is stopped + assert sys.path == path + assert all(sys.modules[name] is module for name, module in foreign.items()) + assert invoked == [ + SCRIPTS_DIR / "generate_trace_tros.py", + SCRIPTS_DIR / "release_lock.py", + ] + finally: + subprocess.run( + ["git", "worktree", "remove", "--force", str(other)], + cwd=CHECKOUT, + check=True, + timeout=60, + ) + + +@pytest.fixture +def overlapping_calls(): + entered = [Event(), Event()] + release = [Event(), Event()] + next_call = iter(range(2)) + + def pause(): + index = next(next_call) + entered[index].set() + assert release[index].wait(30) + + def run(call): + second_started = Event() + + def second(): + second_started.set() + return call() + + with ThreadPoolExecutor(max_workers=2) as pool: + first_call = pool.submit(call) + try: + assert entered[0].wait(30) + second_call = pool.submit(second) + assert second_started.wait(30) + # Give an unguarded B time to reach its body before A exits. + entered[1].wait(2) + 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 + + pause, run = overlapping_calls + + def check(args): + pause() + return 0 + + monkeypatch.setattr(bundle, "_check", check) + monkeypatch.setattr(sys, "path", [*sys.path, str(SCRIPTS_DIR)]) + name = "generate_trace_tros" + sentinel = ModuleType(name) + monkeypatch.setitem(sys.modules, name, sentinel) + path, entries = sys.path, sys.path[:] + + calls = run(lambda: bundle.main(["check"])) + + assert [call.result() for call in calls] == [0, 0] + assert sys.modules[name] is sentinel + assert sys.path is path and sys.path == entries + + +def test_overlapping_vector_builds_restore_the_import_state( + monkeypatch, overlapping_calls +): + from scripts import generate_ordered_scenario_vectors as generator + + 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) + 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) + + 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("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 From f5390618efb8b9558b665ef4f36ef6d9e8284613 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 1 Dec 2026 07:24:07 -0500 Subject: [PATCH 07/13] Preserve in-memory bundle helpers supplied by callers Replace cached helpers when their source path belongs outside the dispatcher checkout. Retain explicitly supplied in-memory modules so callers can substitute a certifier. Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- scripts/bundle.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/bundle.py b/scripts/bundle.py index 183ade737..dbf84de22 100644 --- a/scripts/bundle.py +++ b/scripts/bundle.py @@ -51,7 +51,8 @@ def _checkout_imports(): sys.path.insert(0, scripts_dir) for name, module in cached.items(): source = getattr(module, "__file__", None) - if not source or Path(source).resolve() != SCRIPTS_DIR / f"{name}.py": + # Preserve explicitly injected modules that have no source file. + if source and Path(source).resolve() != SCRIPTS_DIR / f"{name}.py": del sys.modules[name] yield finally: From 648f7bc4f21968ada726fe9a5b4c57fcce7681f6 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 16:03:11 -0500 Subject: [PATCH 08/13] Share the script import lock across aliases and check bound helper origins Round 3 found that a local helper could keep a foreign cached dependency, that overlapping calls through different import aliases each took their own lock, that probe errors printed environment values, and that the cached-helper test needed writable git metadata. Dispatch now checks where cached helpers and the sibling modules they bound came from. Each entry point shares one reentrant lock across its module instances. The probe reports the exception type, the names of changed variables and whether the path changed, never their values. The cached-helper test copies the two helper files instead of adding a git worktree. New tests cover reentry for both entry points, and the overlap fixture waits until the second call meets the held lock. Co-Authored-By: Claude Opus 5.5 --- scripts/bundle.py | 32 +- scripts/certify_data_release.py | 6 +- scripts/generate_ordered_scenario_vectors.py | 5 +- scripts/generate_trace_tros.py | 6 +- scripts/prepare_package_bundle_update.py | 14 +- scripts/spm_bundle.py | 4 +- tests/test_script_imports.py | 352 ++++++++++++++----- 7 files changed, 310 insertions(+), 109 deletions(-) diff --git a/scripts/bundle.py b/scripts/bundle.py index dbf84de22..5ab10c503 100644 --- a/scripts/bundle.py +++ b/scripts/bundle.py @@ -24,7 +24,11 @@ SCRIPTS_DIR = Path(__file__).resolve().parent REPO_ROOT = SCRIPTS_DIR.parent -_COMMAND_IMPORT_LOCK = RLock() +# 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 = ( @@ -35,6 +39,28 @@ "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 @@ -50,9 +76,7 @@ def _checkout_imports(): if original_path[:1] != [scripts_dir]: sys.path.insert(0, scripts_dir) for name, module in cached.items(): - source = getattr(module, "__file__", None) - # Preserve explicitly injected modules that have no source file. - if source and Path(source).resolve() != SCRIPTS_DIR / f"{name}.py": + if _is_foreign_helper(name, module): del sys.modules[name] yield finally: diff --git a/scripts/certify_data_release.py b/scripts/certify_data_release.py index 22cee39d9..5cbb51efd 100644 --- a/scripts/certify_data_release.py +++ b/scripts/certify_data_release.py @@ -38,15 +38,17 @@ sys.path[:0] = [str(REPO_ROOT / "src"), str(REPO_ROOT / "scripts")] if __package__: - from .generate_bundle_artifacts import generate + from . import generate_bundle_artifacts else: - from generate_bundle_artifacts import generate + 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/generate_ordered_scenario_vectors.py b/scripts/generate_ordered_scenario_vectors.py index b1ff00cf8..2235ff09d 100644 --- a/scripts/generate_ordered_scenario_vectors.py +++ b/scripts/generate_ordered_scenario_vectors.py @@ -26,7 +26,10 @@ PATH = ROOT / "src/policyengine/data/schemas/ordered_scenario_plan.v1.vectors.json" REVISION = {"repository": "PolicyEngine/test", "git_sha": "a" * 40} -_MODIFIER_IMPORT_LOCK = RLock() +# 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(): 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/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/tests/test_script_imports.py b/tests/test_script_imports.py index 84ab19137..ca38f5487 100644 --- a/tests/test_script_imports.py +++ b/tests/test_script_imports.py @@ -7,13 +7,14 @@ Scripts can configure the interpreter when run directly. Calling an imported script's entry point must restore any temporary changes to the import path. -For successful imports, the probe reports only the names of environment -variables that changed. Import failures report the exception type and message. -Subprocess failures report captured output. +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 @@ -57,23 +58,23 @@ for name in names: for script in names: sys.modules.pop(script, None) - path, environment = list(sys.path), dict(os.environ) + original_path = sys.path + path, environment = list(original_path), dict(os.environ) + outcome = {} try: importlib.import_module(name) except BaseException as error: - results[name] = {"error": f"{type(error).__name__}: {error!s}"} - else: - results[name] = { - "path_before": path, - "path_after": list(sys.path), - "environment_changes": [ - key - for key in sorted(set(environment) | set(os.environ)) - if environment.get(key) != os.environ.get(key) - ], - "policyengine_imported": "policyengine" in sys.modules, - } - sys.path[:] = path + 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)) @@ -89,17 +90,23 @@ def _run_import_probe(cwd, scripts_dir, names, *, warm=False): os.path.abspath(entry) for entry in pythonpath.split(os.pathsep) ) mode = "warm" if warm else "cold" - result = subprocess.run( - [sys.executable, "-c", PROBE, str(scripts_dir), mode, *names], - cwd=cwd, - env=environment, - capture_output=True, - text=True, - timeout=300, - check=False, - ) - assert result.returncode == 0, result.stdout + result.stderr - return json.loads(result.stdout.splitlines()[-1]) + 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: + pytest.fail("Import probe timed out after 300 seconds", pytrace=False) + 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): + pytest.fail("Import probe returned invalid JSON", pytrace=False) @pytest.fixture(scope="module") @@ -118,15 +125,14 @@ def test_the_probe_covers_the_release_scripts(): @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.get("error") - before, after = outcome["path_before"], outcome["path_after"] - assert after == before, f"importing scripts/{name}.py changed sys.path" + 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.get("error") + assert "error" not in outcome, outcome assert outcome["environment_changes"] == [] @@ -145,7 +151,7 @@ def test_import_probe_resolves_relative_pythonpath(tmp_path, monkeypatch): outcome = _run_import_probe(child, scripts, ["probe_script"], warm=True)[ "probe_script" ] - assert "error" not in outcome, outcome.get("error") + assert "error" not in outcome, outcome def test_import_probe_reports_only_changed_environment_names(tmp_path, monkeypatch): @@ -162,7 +168,7 @@ def test_import_probe_reports_only_changed_environment_names(tmp_path, monkeypat outcome = _run_import_probe(tmp_path, tmp_path, ["probe_script"], warm=True)[ "probe_script" ] - assert "error" not in outcome, outcome.get("error") + assert "error" not in outcome, outcome assert outcome["environment_changes"] == [ "PROBE_ADDED", "PROBE_REMOVED", @@ -170,18 +176,44 @@ def test_import_probe_reports_only_changed_environment_names(tmp_path, monkeypat ] -def test_import_probe_reports_exception_type_and_message(tmp_path, monkeypatch): - monkeypatch.setenv("PROBE_DUMMY_TOKEN", "fixture-value") +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\n" + "import os, sys\n" "class ProbeError(RuntimeError):\n" " def __format__(self, spec):\n" " return 'extra diagnostic'\n" - "raise ProbeError(os.environ.pop('PROBE_DUMMY_TOKEN'))\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 outcome == {"error": "ProbeError: fixture-value"} + 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): @@ -195,16 +227,16 @@ def test_cold_import_probe_detects_policyengine_side_effects(tmp_path, monkeypat monkeypatch.setenv(SKIP_COUNTRY_IMPORTS, "1") outcome = _run_import_probe(tmp_path, tmp_path, ["probe_script"])["probe_script"] - assert "error" not in outcome, outcome.get("error") + 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.get("error") + assert "error" not in outcome, outcome assert outcome["policyengine_imported"] - assert outcome["path_after"] == outcome["path_before"] + assert not outcome["path_changed"] assert outcome["environment_changes"] == [] @@ -338,7 +370,23 @@ def check_tros(*, strict): assert result.returncode == 0, result.stdout + result.stderr -def test_bundle_main_replaces_a_cached_foreign_tro_helper(tmp_path, monkeypatch): +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 @@ -354,69 +402,112 @@ def fetch_data_manifest(country): stopped = RuntimeError("Reached the local data-fetch stub") monkeypatch.setattr(manifest, "get_data_release_manifest", fetch_data_manifest) - other = tmp_path / "other" - subprocess.run( - ["git", "worktree", "add", "--quiet", "--detach", str(other), "HEAD"], - cwd=CHECKOUT, - check=True, - timeout=60, + 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, ) - try: - monkeypatch.syspath_prepend(str(other / "scripts")) - foreign = {} - for name in ("release_lock", "generate_trace_tros"): - spec = spec_from_file_location(name, other / "scripts" / f"{name}.py") - module = module_from_spec(spec) - monkeypatch.setitem(sys.modules, name, module) - spec.loader.exec_module(module) - foreign[name] = module - path = sys.path[:] - - with pytest.raises(RuntimeError) as error: - bundle.main(["check", "--include-tros"]) - - assert error.value is stopped - assert sys.path == path - assert all(sys.modules[name] is module for name, module in foreign.items()) - assert invoked == [ - SCRIPTS_DIR / "generate_trace_tros.py", - SCRIPTS_DIR / "release_lock.py", - ] - finally: - subprocess.run( - ["git", "worktree", "remove", "--force", str(other)], - cwd=CHECKOUT, - check=True, - timeout=60, - ) + 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(): - entered = [Event(), Event()] +def overlapping_calls(monkeypatch): + ready = [Event(), Event()] release = [Event(), Event()] next_call = iter(range(2)) def pause(): index = next(next_call) - entered[index].set() + ready[index].set() assert release[index].wait(30) - def run(call): - second_started = Event() + 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 second(): - second_started.set() - return call() + def __exit__(self, *exc): + lock.release() + + monkeypatch.setattr(second_module, lock_name, ObservedLock()) with ThreadPoolExecutor(max_workers=2) as pool: - first_call = pool.submit(call) + first_call = pool.submit(first) try: - assert entered[0].wait(30) + assert ready[0].wait(30) second_call = pool.submit(second) - assert second_started.wait(30) - # Give an unguarded B time to reach its body before A exits. - entered[1].wait(2) + assert ready[1].wait(30) release[0].set() assert wait([first_call], timeout=30).done finally: @@ -432,6 +523,7 @@ def test_overlapping_bundle_calls_restore_the_import_state( ): from scripts import bundle + alias = _cache_script(monkeypatch, "bundle", SCRIPTS_DIR) pause, run = overlapping_calls def check(args): @@ -439,17 +531,24 @@ def check(args): 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"])) + 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.modules[name] is sentinel 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( @@ -457,6 +556,7 @@ def test_overlapping_vector_builds_restore_the_import_state( ): 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 @@ -465,13 +565,16 @@ def build_after_pause(modifiers): 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) + 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)) == ( @@ -481,6 +584,69 @@ def build_after_pause(modifiers): 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=30, + 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 From f31c235827af8e842f53e7fa0334c06eb8660178 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 16:40:25 -0500 Subject: [PATCH 09/13] Wrap the probe exit message and give the reentry subprocess 120 seconds Ruff's 88-character limit failed the Lint job on the probe's exit message. The reentry test's subprocess imports policyengine and builds the vectors twice, so it now gets the 120 seconds the file's other build subprocess uses; a deadlock still fails it. Co-Authored-By: Claude Opus 5.5 --- tests/test_script_imports.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/test_script_imports.py b/tests/test_script_imports.py index ca38f5487..7a5b7d4aa 100644 --- a/tests/test_script_imports.py +++ b/tests/test_script_imports.py @@ -102,7 +102,9 @@ def _run_import_probe(cwd, scripts_dir, names, *, warm=False): except subprocess.TimeoutExpired: pytest.fail("Import probe timed out after 300 seconds", pytrace=False) if result.returncode: - pytest.fail(f"Import probe exited with status {result.returncode}", pytrace=False) + 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): @@ -641,7 +643,7 @@ def reenter(*args): env={**os.environ, SKIP_COUNTRY_IMPORTS: "1"}, capture_output=True, text=True, - timeout=30, + timeout=120, check=False, ) assert result.returncode == 0, result.stdout + result.stderr From 040ad0e21b90394fadb88c958e0a2bbbb20f8d31 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 22:27:57 -0500 Subject: [PATCH 10/13] Suppress chained exceptions in the probe's fixed failure messages The timeout and invalid-JSON handlers now raise pytest.fail.Exception from None, so pytest prints only the fixed message. Co-Authored-By: Claude Opus 5.5 --- tests/test_script_imports.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/test_script_imports.py b/tests/test_script_imports.py index 7a5b7d4aa..3959679bb 100644 --- a/tests/test_script_imports.py +++ b/tests/test_script_imports.py @@ -100,7 +100,9 @@ def _run_import_probe(cwd, scripts_dir, names, *, warm=False): check=False, ) except subprocess.TimeoutExpired: - pytest.fail("Import probe timed out after 300 seconds", pytrace=False) + 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 @@ -108,7 +110,9 @@ def _run_import_probe(cwd, scripts_dir, names, *, warm=False): try: return json.loads(result.stdout.splitlines()[-1]) except (IndexError, UnicodeDecodeError, json.JSONDecodeError): - pytest.fail("Import probe returned invalid JSON", pytrace=False) + raise pytest.fail.Exception( + "Import probe returned invalid JSON", pytrace=False + ) from None @pytest.fixture(scope="module") From 0508cab8c0599e930a20f82ec86d9370c144be20 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 3 Dec 2026 08:01:44 -0500 Subject: [PATCH 11/13] Restore sys.path when lazy-importing litellm in narration --- src/policyengine/derivations/narrate.py | 18 ++++++++- tests/test_derivations.py | 50 ++++++++++++++++++++++++- 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/src/policyengine/derivations/narrate.py b/src/policyengine/derivations/narrate.py index 3fd7041bd..74c9ba4ad 100644 --- a/src/policyengine/derivations/narrate.py +++ b/src/policyengine/derivations/narrate.py @@ -10,10 +10,24 @@ from __future__ import annotations +import sys from typing import Any from .trace import Derivation + +def _import_litellm() -> Any: + """Import LiteLLM without keeping any ``sys.path`` entries it appends.""" + saved_path = list(sys.path) + try: + import litellm # noqa: PLC0415 — lazy import keeps the base module light + finally: + # LiteLLM's proxy CLI module appends ``os.getcwd()`` to ``sys.path`` at + # import time, leaking checkout paths into isolated environments. + sys.path[:] = saved_path + 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 +148,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 +183,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/test_derivations.py b/tests/test_derivations.py index f7a508cb4..8fbcde626 100644 --- a/tests/test_derivations.py +++ b/tests/test_derivations.py @@ -8,6 +8,9 @@ from __future__ import annotations import asyncio +import os +import subprocess +import sys import types from pathlib import Path @@ -22,6 +25,7 @@ narrate_async, top_level_contributions, ) +from policyengine.derivations.narrate import _import_litellm def _us_simulation() -> object: @@ -294,7 +298,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 +415,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 +498,44 @@ 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``.""" + pytest.importorskip("litellm") + env = os.environ.copy() + 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" + "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 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, + check=False, + ) + assert result.returncode == 0, result.stderr or result.stdout From 308a22a8cdce99f43390bb857dbb29f2c1bf4aba Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 3 Dec 2026 08:49:31 -0500 Subject: [PATCH 12/13] Serialize LiteLLM cold-import sys.path cleanup and isolate cold probe --- src/policyengine/derivations/narrate.py | 40 ++++++++++--- tests/test_derivations.py | 79 ++++++++++++++++++++++++- 2 files changed, 109 insertions(+), 10 deletions(-) diff --git a/src/policyengine/derivations/narrate.py b/src/policyengine/derivations/narrate.py index 74c9ba4ad..35f0feb0f 100644 --- a/src/policyengine/derivations/narrate.py +++ b/src/policyengine/derivations/narrate.py @@ -10,22 +10,44 @@ 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 ``sys.path`` entries it appends.""" - saved_path = list(sys.path) - try: - import litellm # noqa: PLC0415 — lazy import keeps the base module light - finally: - # LiteLLM's proxy CLI module appends ``os.getcwd()`` to ``sys.path`` at - # import time, leaking checkout paths into isolated environments. - sys.path[:] = saved_path - return litellm + """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" diff --git a/tests/test_derivations.py b/tests/test_derivations.py index 8fbcde626..1ffab072c 100644 --- a/tests/test_derivations.py +++ b/tests/test_derivations.py @@ -8,9 +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 @@ -502,8 +506,10 @@ async def acompletion(**kwargs): def test_narrate_cold_litellm_import_leaves_sys_path_unchanged(tmp_path): """Cold-importing LiteLLM via ``narrate`` must not append cwd to ``sys.path``.""" - pytest.importorskip("litellm") + 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 @@ -513,6 +519,7 @@ def test_narrate_cold_litellm_import_leaves_sys_path_unchanged(tmp_path): "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" @@ -527,6 +534,7 @@ def test_narrate_cold_litellm_import_leaves_sys_path_unchanged(tmp_path): " 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" ) @@ -536,6 +544,75 @@ def test_narrate_cold_litellm_import_leaves_sys_path_unchanged(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 From 5f90a5bc0a5fb97f540d947cde88829a20a79bd8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 3 Dec 2026 10:49:36 -0500 Subject: [PATCH 13/13] Raise cold LiteLLM import probe timeout to 120s and merge main --- tests/test_derivations.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_derivations.py b/tests/test_derivations.py index 1ffab072c..eb2d3eaa1 100644 --- a/tests/test_derivations.py +++ b/tests/test_derivations.py @@ -544,7 +544,7 @@ def test_narrate_cold_litellm_import_leaves_sys_path_unchanged(tmp_path): env=env, capture_output=True, text=True, - timeout=30, + timeout=120, check=False, ) assert result.returncode == 0, result.stderr or result.stdout