Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
83e5b5c
Guard against scripts and tests changing sys.path for the session
MaxGhenis Oct 15, 2026
10102a4
Set up the import path and environment only in script entry points
MaxGhenis Oct 15, 2026
02a330f
Catch a second src ahead of site-packages; allow PYTHONPATH=src
MaxGhenis Oct 15, 2026
36ca9ce
Merge remote-tracking branch 'refs/remotes/pr/base' into pr-fix
MaxGhenis Nov 30, 2026
317f59c
Keep maintenance script imports isolated after merging main
MaxGhenis Nov 30, 2026
0e7ef21
Keep maintenance command imports tied to their checkout
MaxGhenis Dec 1, 2026
15cf976
Keep maintenance calls isolated during helper dispatch and vector builds
codex Dec 1, 2026
f539061
Preserve in-memory bundle helpers supplied by callers
codex Dec 1, 2026
648f7bc
Share the script import lock across aliases and check bound helper or…
MaxGhenis Dec 2, 2026
f31c235
Wrap the probe exit message and give the reentry subprocess 120 seconds
MaxGhenis Dec 2, 2026
040ad0e
Suppress chained exceptions in the probe's fixed failure messages
MaxGhenis Dec 3, 2026
97c56fe
Merge remote-tracking branch 'origin/main' into fix/script-import-sid…
MaxGhenis Dec 3, 2026
0508cab
Restore sys.path when lazy-importing litellm in narration
MaxGhenis Dec 3, 2026
25b405e
Merge remote-tracking branch 'origin/main' into fix/script-import-sid…
MaxGhenis Dec 3, 2026
308a22a
Serialize LiteLLM cold-import sys.path cleanup and isolate cold probe
MaxGhenis Dec 3, 2026
22a736b
Merge remote-tracking branch 'refs/remotes/origin/main' into fix/scri…
MaxGhenis Dec 3, 2026
5f90a5b
Raise cold LiteLLM import probe timeout to 120s and merge main
MaxGhenis Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/623.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Keep maintenance-script imports from changing `sys.path` or `os.environ` after PolicyEngine loads, preserving the test suite's installed metadata lookup. The import guard also checks that `certify_data_release.py` leaves both unchanged when it first loads PolicyEngine with country imports enabled.
7 changes: 4 additions & 3 deletions scripts/audit_regional_input_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
80 changes: 73 additions & 7 deletions scripts/bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,74 @@
import argparse
import os
import sys
from contextlib import contextmanager
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT / "scripts"))
sys.path.insert(0, str(REPO_ROOT / "src"))
from threading import RLock

SCRIPTS_DIR = Path(__file__).resolve().parent
REPO_ROOT = SCRIPTS_DIR.parent
# Bare, package and file-path imports can create separate dispatcher modules.
# Keep the lock with the interpreter state that every dispatcher shares.
_COMMAND_IMPORT_LOCK = vars(sys).setdefault(
"_policyengine_bundle_command_import_lock", RLock()
)

# These are the bare sibling imports used by the commands and their helpers.
_SIBLING_HELPERS = (
"certify_data_release",
"generate_bundle_artifacts",
"generate_trace_tros",
"prepare_package_bundle_update",
"release_lock",
"spm_bundle",
)
# Eager sibling imports retain the module under its bare name.
_SIBLING_DEPENDENCIES = {
"certify_data_release": "generate_bundle_artifacts",
"generate_trace_tros": "release_lock",
"prepare_package_bundle_update": "generate_bundle_artifacts",
"spm_bundle": "generate_bundle_artifacts",
}


def _is_foreign_helper(name: str, module: object) -> bool:
source = getattr(module, "__file__", None)
# Explicitly injected modules may have no source file.
if not source:
return False
if Path(source).resolve() != SCRIPTS_DIR / f"{name}.py":
return True
# A local helper may still hold a foreign dependency even after that
# dependency has been replaced in sys.modules.
dependency = _SIBLING_DEPENDENCIES.get(name)
return dependency is not None and _is_foreign_helper(
dependency, getattr(module, dependency, None)
)


@contextmanager
def _checkout_imports():
"""Use this checkout's helpers for a command and restore the caller's imports."""
with _COMMAND_IMPORT_LOCK:
original_path = sys.path[:]
cached = {
name: sys.modules[name] for name in _SIBLING_HELPERS if name in sys.modules
}
try:
scripts_dir = str(SCRIPTS_DIR)
if original_path[:1] != [scripts_dir]:
sys.path.insert(0, scripts_dir)
for name, module in cached.items():
if _is_foreign_helper(name, module):
del sys.modules[name]
yield
finally:
sys.path[:] = original_path
for name in _SIBLING_HELPERS:
if name in cached:
sys.modules[name] = cached[name]
else:
sys.modules.pop(name, None)


def _certify_data(args: argparse.Namespace) -> int:
Expand Down Expand Up @@ -150,7 +213,6 @@ def _development_manifest(args: argparse.Namespace) -> int:


def _generate_tros(*, strict: bool = False) -> int:
os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1")
from generate_trace_tros import regenerate_all

written, regressions = regenerate_all(strict=strict)
Expand All @@ -170,7 +232,6 @@ def _generate_tros(*, strict: bool = False) -> int:


def _check_tros(*, strict: bool = False) -> int:
os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1")
from generate_trace_tros import generated_tros

changed = False
Expand Down Expand Up @@ -377,10 +438,15 @@ def main(argv: list[str] | None = None) -> int:
if getattr(args, "strict_tros", False) and not args.include_tros:
parser.error("--strict-tros requires --include-tros")
try:
return args.func(args)
with _checkout_imports():
return args.func(args)
except ValueError as exc:
parser.error(str(exc))


if __name__ == "__main__":
# Use the checkout's policyengine when a subcommand needs it, and default
# to skipping country imports.
os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1")
sys.path[:0] = [str(REPO_ROOT / "src"), str(SCRIPTS_DIR)]
raise SystemExit(main())
15 changes: 12 additions & 3 deletions scripts/certify_data_release.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,25 @@
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT / "src"))
sys.path.insert(0, str(REPO_ROOT / "scripts"))

from generate_bundle_artifacts import generate # noqa: E402
if __name__ == "__main__":
# Certify with the checkout's policyengine and default to skipping country
# imports.
os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1")
sys.path[:0] = [str(REPO_ROOT / "src"), str(REPO_ROOT / "scripts")]

if __package__:
from . import generate_bundle_artifacts
else:
import generate_bundle_artifacts

from policyengine.provenance.certification import ( # noqa: E402
REGIONAL_RELEASE_KINDS,
certify_data_release,
)

generate = generate_bundle_artifacts.generate


def main(argv=None) -> int:
parser = argparse.ArgumentParser(description="Certify a country data release.")
Expand Down
5 changes: 3 additions & 2 deletions scripts/check_uk_candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion scripts/check_uk_uc_floor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 0 additions & 5 deletions scripts/generate_bundle_artifacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import copy
import importlib.util
import json
import os
import re
import sys
from pathlib import Path
Expand All @@ -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.
Expand Down
36 changes: 32 additions & 4 deletions scripts/generate_ordered_scenario_vectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,54 @@

import argparse
import copy
import importlib.util
import json
import os
import sys
from pathlib import Path
from threading import RLock

ROOT = Path(__file__).resolve().parents[1]
os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1")
sys.path.insert(0, str(ROOT / "src"))
sys.path.insert(0, str(ROOT))
if __name__ == "__main__":
os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1")
sys.path.insert(0, str(ROOT / "src"))

from policyengine.provenance.ordered_scenario import ( # noqa: E402
build_ordered_scenario,
)
from tests import ordered_receipt_modifiers as modifiers # noqa: E402

PATH = ROOT / "src/policyengine/data/schemas/ordered_scenario_plan.v1.vectors.json"
REVISION = {"repository": "PolicyEngine/test", "git_sha": "a" * 40}
# Every import alias temporarily uses the same modifier name in sys.modules.
_MODIFIER_IMPORT_LOCK = vars(sys).setdefault(
"_policyengine_ordered_scenario_modifier_import_lock", RLock()
)


def build_vectors():
path = ROOT / "tests" / "ordered_receipt_modifiers.py"
spec = importlib.util.spec_from_file_location(
"tests.ordered_receipt_modifiers", path
)
assert spec is not None and spec.loader is not None
modifiers = importlib.util.module_from_spec(spec)
spec.loader.exec_module(modifiers)

# The receipt binder looks up modifier functions by their module name.
with _MODIFIER_IMPORT_LOCK:
missing = object()
previous = sys.modules.get(spec.name, missing)
sys.modules[spec.name] = modifiers
try:
return _build_vectors(modifiers)
finally:
if previous is missing:
del sys.modules[spec.name]
else:
sys.modules[spec.name] = previous


def _build_vectors(modifiers):
def leaves(*functions):
return [(function, dict(REVISION)) for function in functions]

Expand Down
8 changes: 6 additions & 2 deletions scripts/generate_receipt_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@

REPO_ROOT = Path(__file__).resolve().parents[1]
SCHEMA_DIR = REPO_ROOT / "src" / "policyengine" / "data" / "schemas"
os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1")
sys.path.insert(0, str(REPO_ROOT / "src"))

if __name__ == "__main__":
# Write schemas from the checkout's models and default to skipping country
# imports.
os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1")
sys.path.insert(0, str(REPO_ROOT / "src"))

from policyengine.provenance.ordered_scenario import OrderedScenarioPlan # noqa: E402
from policyengine.provenance.receipt import ExecutionReceipt # noqa: E402
Expand Down
6 changes: 5 additions & 1 deletion scripts/generate_trace_tros.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down
14 changes: 7 additions & 7 deletions scripts/prepare_package_bundle_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
5 changes: 3 additions & 2 deletions scripts/release_consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion scripts/spm_bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading