Skip to content

Stop maintenance scripts and their tests changing sys.path for the test session - #624

Draft
MaxGhenis wants to merge 17 commits into
mainfrom
fix/script-import-side-effects
Draft

MaxGhenis wants to merge 17 commits into
mainfrom
fix/script-import-side-effects

Conversation

@MaxGhenis

@MaxGhenis MaxGhenis commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #623

Problem

Nine maintenance scripts on main changed process state on import, not only when run (#623 lists four of them): each put the checkout's src (and sometimes scripts or the repository root) first on sys.path, and most set POLICYENGINE_SKIP_COUNTRY_IMPORTS=1. The scripts are audit_regional_input_surface.py, bundle.py, certify_data_release.py, check_uk_candidate.py, check_uk_uc_floor.py, generate_bundle_artifacts.py, generate_ordered_scenario_vectors.py, generate_receipt_schemas.py and release_consumers.py.

tests/test_spm_bundle_tooling.py, tests/test_generate_trace_tros.py and tests/test_release_tro_generation.py put scripts/ first on sys.path at module level, then imported bundle.py, generate_bundle_artifacts.py, generate_trace_tros.py and spm_bundle.py at module scope, so the tests' scripts/ entry and the scripts' src entry both stayed on sys.path for the whole test session. CI installs the checkout editable with setuptools, which leaves src/policyengine.egg-info; once src was first on sys.path, importlib.metadata.distribution("policyengine") returned that egg-info instead of the installed dist-info, so any test that read installed metadata could fail, depending on test order. #571 worked around this inside tests/test_execution_receipt.py with its _import_path_as_collected fixture. bundle.py's _generate_tros and _check_tros also set POLICYENGINE_SKIP_COUNTRY_IMPORTS when called, so tests that called them leaked it into later tests' subprocesses.

Change

Running a script directly still sets up the imports it needs. Importing a script, or collecting and running the tests, leaves sys.path and POLICYENGINE_SKIP_COUNTRY_IMPORTS as they were, so test order no longer decides where policyengine's metadata comes from.

  • Scripts set up only in their entry point. generate_bundle_artifacts.py imports nothing from policyengine (it loads the standard-library-only bundle_validation.py by file path), so it now sets up nothing. The other eight prepend checkout directories only under if __name__ == "__main__":, before the imports that need them. Seven of those also default POLICYENGINE_SKIP_COUNTRY_IMPORTS to 1; check_uk_uc_floor.py sets up only the import path. _generate_tros and _check_tros no longer set POLICYENGINE_SKIP_COUNTRY_IMPORTS.
  • Imported commands use their own checkout's helpers. bundle.main() runs each command inside _checkout_imports(), which holds a reentrant lock until it has restored the caller's imports. bundle.py stores that lock on sys, so every import of bundle.py in the interpreter shares it, whether bare, as scripts.bundle or from its file path. Overlapping calls from different threads therefore run one at a time. _checkout_imports() puts bundle.py's own scripts/ directory first unless it already is, and removes from sys.modules any cached sibling helper (certify_data_release, generate_bundle_artifacts, generate_trace_tros, prepare_package_bundle_update, release_lock, spm_bundle) whose source file is not this checkout's copy. Four helpers hold a sibling module as an attribute: certify_data_release, prepare_package_bundle_update and spm_bundle hold generate_bundle_artifacts, and generate_trace_tros holds release_lock. _checkout_imports() also removes a cached helper whose held module is not this checkout's copy. It reads that module from the helper's attribute, so it catches another checkout's module even when sys.modules no longer holds it. A command therefore runs this checkout's copy of each helper and of each sibling module a helper holds, even when another checkout's copy is cached. _checkout_imports() treats a module with no source file as this checkout's copy, so it keeps a test double a caller put in sys.modules. In finally, it restores the caller's sys.path, puts back the caller's sys.modules entries for those six names, and removes any of the six that the command added. The directory comes from bundle.py's own location, not REPO_ROOT, which some tests point at fixture data.
  • Vector builds register their modifiers only while building. generate_ordered_scenario_vectors.build_vectors() loads the checkout's tests/ordered_receipt_modifiers.py by file path. Holding a reentrant lock that every import of the script in the interpreter shares, it registers that module under tests.ordered_receipt_modifiers while it builds the vectors, then puts back the caller's entry, or removes the name if the caller had none, whether the build returns or raises. Because it loads the file by path, a caller outside the checkout can build the vectors.
  • Tests import scripts without leaving sys.path changed. New tests/fixtures/import_path.py: scripts_importable() is a context manager for module-level imports; each block temporarily puts scripts/ first and restores the exact sys.path when it exits. The scripts_on_path fixture (monkeypatch.syspath_prepend) serves tests whose code imports sibling scripts while running. The three modules import their four scripts inside scripts_importable() blocks.
  • Guards (tests/test_script_imports.py plus conftest.py):
    • a fresh interpreter imports every top-level scripts/*.py (17 at f31c23582, found by glob, with script modules purged from sys.modules before each import) after loading policyengine with country imports skipped, and reports whether sys.path changed and the names of any os.environ variables added, removed or changed;
    • a second fresh interpreter imports certify_data_release.py first, with country imports enabled, and checks that it leaves both unchanged;
    • the probe reports a path_changed flag and the names of changed environment variables, and for a failed import it adds only the exception type. When the probe subprocess exits nonzero, _run_import_probe() fails the test with a fixed message that adds the exit status. If the probe times out or its last stdout line is missing or invalid JSON, _run_import_probe() fails with a fixed message. None of these reports an environment value, a sys.path entry the imported script added, that script's exception message or the subprocess's captured output;
    • the probe resolves relative PYTHONPATH entries against the caller's working directory before it starts in a temporary directory, so PYTHONPATH=src loads the same checkout in the probe;
    • conftest.py records, at collection finish, any checkout directory that collecting the test modules added to sys.path and any change to the count or order of the entries already there, and test_collecting_tests_leaves_sys_path_alone asserts that the record is empty;
    • an autouse fixture fails any test that leaves sys.path changed in those ways or leaves POLICYENGINE_SKIP_COUNTRY_IMPORTS changed;
    • test_policyengine_metadata_is_read_as_in_a_fresh_interpreter checks that the session reads policyengine's metadata from the same place a fresh interpreter does, so an explicit PYTHONPATH=src still passes;
    • with POLICYENGINE_SKIP_COUNTRY_IMPORTS unset, python -S scripts/bundle.py check (-S skips site-packages, as in the push workflow), python scripts/certify_data_release.py --help and python scripts/generate_receipt_schemas.py --check each exit 0, so each entry point still sets up its own imports.
  • tests/test_execution_receipt.py's _import_path_as_collected fixture from #571 stays as defense in depth; its comment now says the release-script tests used to put src first on sys.path and that tests/test_script_imports.py now guards against that.

Changes since 0e7ef2155

  • 15cf976ac makes bundle.main() run each command inside a new _checkout_imports(), which takes the helper directory from bundle.py's own location instead of REPO_ROOT, checks each cached sibling helper's source path, and restores the saved sys.modules entries afterward. It adds a module-level RLock to bundle.py and to generate_ordered_scenario_vectors.py, and bundle.main() and build_vectors() each hold their module's lock until they finish restoring, so two overlapping calls through the same module object run one after the other and leave the caller's sys.path and modules as they were. It changes the probe to report an import failure's exception type and str() message. It adds six tests:
    • test_bundle_main_replaces_a_cached_foreign_tro_helper preloads another worktree's generate_trace_tros and release_lock, runs the real bundle.main(["check", "--include-tros"]) up to a local data-fetch stub, and checks that the helpers that ran came from this checkout and that the caller's modules and sys.path are back afterward;
    • test_overlapping_bundle_calls_restore_the_import_state and test_overlapping_vector_builds_restore_the_import_state start call A, start call B while A holds its temporary state, let A finish first, and check that both calls succeed and leave the caller's sys.path and modules as they were;
    • test_vector_build_restores_the_modifier_module_after_an_error[cached] and [absent] force the build to raise and check that the original exception propagates and that the caller's entry is back, or that the name is gone when the caller had none;
    • test_import_probe_reports_exception_type_and_message raises an exception with a custom __format__ and checks that the report shows only its type and str() message.
  • f5390618e keeps cached helpers that have no source file, such as the certifier doubles that tests/test_certify_data_release.py puts in sys.modules.
  • 648f7bc4f makes _checkout_imports() also remove a cached helper that holds another checkout's sibling module, through the new _SIBLING_DEPENDENCIES map and _is_foreign_helper(). Before this commit, _checkout_imports() kept a local prepare_package_bundle_update that had imported another checkout's generate_bundle_artifacts, so update-packages could write that checkout's manifest, generated artifacts and changelog fragment. It likewise kept a local generate_trace_tros that had imported another checkout's release_lock, so bundle.py could call that checkout's registry validator under --strict-tros. To expose the sibling module, certify_data_release.py, prepare_package_bundle_update.py and spm_bundle.py now import generate_bundle_artifacts as a module, generate_trace_tros.py imports release_lock the same way, and each binds the names it uses from that module. bundle.py and generate_ordered_scenario_vectors.py now store their RLock on sys, under _policyengine_bundle_command_import_lock and _policyengine_ordered_scenario_modifier_import_lock, so bare, scripts.* and file-path imports of each script share one lock. The probe now reports a failed import's exception type without its message, and it reports a path_changed flag in place of the paths before and after the import. _run_import_probe() drops a failed subprocess's captured output and reports its exit status, and it reports a timeout or invalid JSON with a fixed message. It changes and adds the tests below in tests/test_script_imports.py, six more test items in all:
    • test_bundle_main_replaces_a_cached_foreign_tro_helper copies release_lock.py and generate_trace_tros.py into a temporary directory instead of adding a git worktree, and runs in three cases. In foreign-generator it caches both copies, as the earlier test did. In local-generator it caches this checkout's generate_trace_tros holding the copied release_lock, and in evicted-dependency it also removes that release_lock from sys.modules. Each case checks that bundle.main() ran this checkout's generate_trace_tros and release_lock and restored the caller's sys.path and module entries;
    • test_bundle_main_uses_local_artifacts_for_a_cached_package_updater caches this checkout's prepare_package_bundle_update holding a copied generate_bundle_artifacts, runs bundle.main(["update-packages", "--uk", "1.0.0"]) and stops it at the manifest load, before any write, to check that this checkout's generate_bundle_artifacts ran;
    • the two overlap tests now run call B through a second module object loaded from the same file, and the fixture releases call A only after call B meets the held lock or reaches its callback. In the bundle test, the seeded generate_trace_tros now carries a __file__ outside scripts/, so call A removes it and has to put it back;
    • test_import_probe_reports_only_safe_import_failure_details replaces test_import_probe_reports_exception_type_and_message. Its probe script pops a dummy environment value, appends it to sys.path and raises an exception with the value as its message, and the test checks that the value appears nowhere in the report. In test_import_probe_reports_only_subprocess_exit_status, the probe subprocess prints a dummy value to stdout and stderr and exits with status 17, and the test checks that the failure message reads exactly Import probe exited with status 17;
    • test_maintenance_entry_points_restore_import_state_after_reentry[bundle] and [generate_ordered_scenario_vectors] call each entry point again from inside its own callback on the same thread, in a subprocess, and check both results and the restored state. A non-reentrant lock would block the nested call until the subprocess timeout.
  • f31c23582 wraps the probe's exit-status pytest.fail() call to fit Ruff's 88-character line limit. It raises the reentry test's subprocess timeout from 30 to 120 seconds because the vector case imports policyengine and builds the vectors twice; test_ordered_scenario_vectors_build_outside_the_checkout gives its single build the same 120 seconds.
  • 040ad0e2 makes the timeout and invalid-JSON handlers raise pytest.fail.Exception(..., pytrace=False) from None. Without from None, pytest prints the caught exception before the fixed message, even with pytrace=False, and a timeout's exception includes the subprocess command.
  • 97c56fe8 merges origin/main at 5d9bb345 (#581).
  • 25b405e3 merges origin/main through deb2ede2 (including 6.20.6 and #774).
  • 308a22a8 answers round 5's review findings: _import_litellm() holds a shared RLock (_policyengine_derivations_litellm_import_lock on sys) across the lazy import and cleanup and removes only extra os.getcwd() occurrences so pre-existing and unrelated sys.path edits survive; test_narrate_cold_litellm_import_leaves_sys_path_unchanged skips via importlib.util.find_spec("litellm") is None so the child process performs the cold import, asserts litellm is absent from sys.modules before narrate() and present after, sets LITELLM_LOCAL_MODEL_COST_MAP=True, and sets a 30s subprocess timeout; and test_import_litellm_serializes_concurrent_cold_imports_and_preserves_edits exercises two overlapping cold-import threads.
  • 5f90a5bc merges origin/main through ba6c1b59 (#761) and raises test_narrate_cold_litellm_import_leaves_sys_path_unchanged's cold subprocess timeout from 30 to 120 seconds after 308a22a8's CI run 47119821040 timed out at 30s on Ubuntu Python 3.13 (5,089 passed, 16 skipped, 1 failed while Test (3.12) and Test (3.14) passed).
  • 0508cab8 isolates LiteLLM's import-time sys.path side effect surfaced by #581 (whose litellm==1.103.0 dependency runs sys.path.append(os.getcwd()) in litellm/proxy/proxy_cli.py on cold import). src/policyengine/derivations/narrate.py adds _import_litellm(), which saves list(sys.path) and restores sys.path[:] = saved_path in finally around the lazy import litellm, used by both narrate() and narrate_async(). tests/test_derivations.py uses _import_litellm() in test_narration_rejects_global_anthropic_sampling and test_narration_litellm_provider_translation_offline, and adds test_narrate_cold_litellm_import_leaves_sys_path_unchanged to check in a fresh subprocess that cold-importing litellm via narrate() leaves sys.path unchanged and keeps os.getcwd() off sys.path.

Invariants

  • Importing any top-level module under scripts/ after policyengine has loaded (with country imports skipped) leaves sys.path and os.environ unchanged. Checked for all 17 top-level scripts at f5390618e. A cold import of certify_data_release.py with country imports enabled also leaves both unchanged.
  • Collecting the test suite, and running each test, adds no checkout directory to sys.path and keeps the count and order of the entries already there. No test leaves POLICYENGINE_SKIP_COUNTRY_IMPORTS changed.
  • An imported bundle.main() loads its sibling helpers, and the sibling modules those helpers hold, from its own checkout, apart from in-memory modules a caller supplies. After each command, including one that raises, it restores the caller's exact sys.path and the caller's sys.modules entries for the six helpers. Overlapping calls from different threads run one at a time and both restore that state, whether the callers import bundle.py bare, as scripts.bundle or from its file path. A nested call on the same thread restores the state it found.
  • An imported build_vectors() works outside the checkout, reproduces the committed vectors byte for byte, and leaves tests.ordered_receipt_modifiers in sys.modules exactly as the caller had it, present or absent, after a success or an error. Overlapping calls from different threads register, build and restore one at a time, and both restore the caller's entry, whether the callers import the script bare, as scripts.generate_ordered_scenario_vectors or from its file path. A nested call on the same thread restores the entry it found.

Verification

At 5f90a5bc, static checks (ruff format --check ., ruff check ., git diff --check, .github/check-agent-notes.sh HEAD, and mypy --follow-imports=silent on src/policyengine/derivations/narrate.py and tests/test_derivations.py) passed. Checkout-root runs with checkout_stays_off_import_path active and --noconftest (policyengine_us/policyengine_uk masked) passed tests/test_derivations.py (Python 3.14.0 with litellm: 81 passed, 2 skipped where policyengine_us is masked), tests/test_inequality_properties.py (Python 3.13: 26 passed), and 59 tests in tests/test_script_imports.py -k "not ordered_scenario_vectors" (2 expected isolated-harness failures from absent tests/conftest.py stash and masked policyengine_uk, 4 deselected). Full CI 47143310989 is running at 5f90a5bc. Earlier CI run 46976935702 recorded 12 passing code checks at f31c23582, including Test on Python 3.11 through 3.14 (and No agent or job notes in the tree passed separately in Agent notes), before origin/main merged #581.

None of the results below covers 648f7bc4f, f31c23582, 040ad0e2, 97c56fe8, 0508cab8, 25b405e3, or 308a22a8. Each result names the commit it covers, most often f5390618e. Python 3.14.10, uv pip install -e '.[dev]', no credentials.

File Full tree at f5390618e
tests/test_script_imports.py 59 passed
tests/test_spm_bundle_tooling.py 56 passed
tests/test_generate_trace_tros.py 9 passed
tests/test_release_tro_generation.py 40 passed
tests/test_ordered_scenario_receipt.py 57 passed
tests/test_execution_receipt.py 888 passed, 8 skipped
Total 1,109 passed, 8 skipped
  • We withdraw the comparison column this table showed earlier. That column described the f5390618e test files run against scripts/ from 0e7ef2155 and reported 1,105 passed, 4 failed and 8 skipped, with 55 passed and 4 failed in tests/test_script_imports.py. One of its four failing tests, the probe-message test, exercised the probe formatter in tests/test_script_imports.py rather than code in scripts/. Under the method the column described, that test would have passed. The saved record of the run does not show which formatter it used.
  • The two forced-error vector tests passed at f5390618e. Against a copy of 0e7ef2155 that restores the modifier module only after a successful build, both failed.
  • At f5390618e, tests/test_script_imports.py also gave 59 passed with PYTHONPATH=src, and tests/test_certify_data_release.py gave 70 passed.
  • Whole suite at f5390618e: 4,979 tests in 145 files. Counting each test once, at its first recorded outcome across the parallel run, its serial completion and the focused file runs above, gives 4,952 passed, 6 failed and 21 skipped.
    • Stalled workers: a memory-limit kill stalled the parallel workers. The 15 tests it left without an outcome ran serially (14 passed, 1 skipped), and the counts above include them. Two of the 6 failures came from the parallel run and passed in isolated reruns: test_uk_qualification_pipeline.py::test_the_certification_environment_falls_back_to_the_packaged_certificate hit its 60-second subprocess timeout there, and test_us_managed_scope.py::test_real_managed_scope_keeps_all_supplied_inputs_and_releases_source[True] was running when its worker was killed. With those reruns, the suite gives 4,954 passed, 4 failed and 21 skipped.
    • Credentialed registry: the 4 remaining failures are test_uk_qualification_pipeline.py::test_preparation_generates_new_sidecars_and_verifies_the_exact_pair in its four parameter sets ([False-uk-data main], [False-main routed to Microcosm], [True-uk-data main], [True-main routed to Microcosm]). Each looks up a Hugging Face release registry that needs a credential, which the credential-free run lacked. They gave 4 failed the same way at 0e7ef2155, and 4 passed at f5390618e with a local stub that answers the lookup with a 404 EntryNotFound response. Counting those four stubbed passes gives 4,958 passed and 21 skipped. CI's Test jobs run the four with network access and HUGGING_FACE_TOKEN.
    • Skips, 21 at f5390618e and the same 21 at 0e7ef2155: in test_execution_receipt.py, eight: six for Python 3.14 behavior changes, one for the missing optional rdflib and one for the absent certified 1.58.0 UK dataset (POLICYENGINE_UK_CERTIFIED_DATASET); in test_be_axiom_pilot.py, three need the unpublished microcosm-frame and one the opt-in source stack (RUN_BE_AXIOM_INTEGRATION=1); in test_replay_exception_probe.py, three need policyengine-uk 2.134.x; in test_spm_development_authentication.py, five need an explicit local-wheel development manifest; in test_us_managed_scope.py, one needs a country pin with the supplied-history fallback. In separate runs at f5390618e, the five development-manifest tests passed with a manifest built from public PyPI wheels, and the rdflib test passed.
  • Without Add execution receipt schema v1 for published results #571's workaround. With _import_path_as_collected disabled, test_spm_bundle_tooling.py, test_generate_trace_tros.py, test_release_tro_generation.py and test_execution_receipt.py gave 993 passed and 8 skipped at f5390618e, and 823 passed, 100 failed, 9 skipped and 69 setup errors at main's ddfef2a8, including failures to locate the installed policyengine metadata.
  • Differential against main. Thirteen offline entry-point invocations ran at f5390618e and at ddfef2a8. All 13 matched in exit code and stderr, and 12 matched in stdout. Which one differed in stdout is unconfirmed; export_bundle_release_assets.py is the likely one, since it prints the exported file names and those names carry the bundle version. Release assets exported at f5390618e matched those from 0e7ef2155 byte for byte, and matched those from ddfef2a8 in names and bytes after normalizing main's version, 6.20.4, to this branch's 6.20.3. bundle.py generate left both trees clean. generate_bundle_artifacts.py no longer sets POLICYENGINE_SKIP_COUNTRY_IMPORTS, so neither do export_bundle_release_assets.py and prepare_package_bundle_update.py, which import it. None of the three imports policyengine or starts a subprocess, so the variable had nothing to affect.
  • Ruff lint and format and git diff --check passed at f5390618e, and so did CI's Lint job.

CI's Verify release inputs and bundle packages job checked the committed TRACE Transparent Research Objects (TROs) against the live release data at f5390618e (scripts/bundle.py check --published-spm --include-tros --strict-tros with HUGGING_FACE_TOKEN), and it passed. The credential-free runs above did not cover live TRO generation, the four registry tests against the real registry, or the certified 1.58.0 dataset test. CI's Test jobs (Python 3.11 to 3.14) ran the full suite with HUGGING_FACE_TOKEN at f5390618e and passed in run 46657892038.

axiom: n/a: test and maintenance-script infrastructure, no policy change

🤖 Generated with Claude Code

MaxGhenis and others added 15 commits October 15, 2026 05:18
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…igins

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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
@MaxGhenis

Copy link
Copy Markdown
Contributor Author

Round 5 scoped review (20261203-080345-ukhub-r5-7141, ~/reviews/uk-hub/jobs/lanes-1202/7141/r5/out.md at 0508cab8) returned VERDICT: REQUEST_CHANGES with 2 P1s in the #581 LiteLLM import-isolation change, 1 P2 (behind origin/main at deb2ede2), and 1 P3 (body counts).

Review rounds on #624

  • Round 1 (317f59c97) -> fix 5801 -> 0e7ef2155
  • Round 2 (6611 at 0e7ef2155) -> REQUEST_CHANGES -> fix 6791 -> f5390618e
  • Round 3 (7141 at f5390618e, ~/reviews/uk-hub/jobs/lanes-1202/7141/out.md) -> REQUEST_CHANGES (5 P1s) -> fix 648f7bc4f / f31c23582
  • Round 4 (7141/r4/out.md at f31c23582) -> VERDICT: APPROVE (all 5 round-3 P1s closed, 0 new P0/P1)
  • Round 5 (20261203-080345-ukhub-r5-7141, 7141/r5/out.md at 0508cab8, triggered after merging origin/main #581/litellm) -> REQUEST_CHANGES (2 new P1s, 1 P2, 1 P3)

Fixes pushed at 308a22a8cdce99f43390bb857dbb29f2c1bf4aba

  • P2 (behind deb2ede2): Merged origin/main through deb2ede2 (#774 + 6.20.6) in 25b405e3. Verified _gini([0, 1], [3, 1]) == 0.75 and tests/test_inequality_properties.py (26 passed).
  • P1 (src/policyengine/derivations/narrate.py:21): _import_litellm() now holds a shared RLock (_policyengine_derivations_litellm_import_lock on sys) across the lazy import and cleanup, counts pre-existing os.getcwd() entries, and removes only extra os.getcwd() occurrences so pre-existing and unrelated sys.path edits survive.
  • P1 (tests/test_derivations.py:505): test_narrate_cold_litellm_import_leaves_sys_path_unchanged skips via importlib.util.find_spec("litellm") is None instead of pytest.importorskip("litellm"), asserts litellm is absent from sys.modules before narrate() and present after, sets LITELLM_LOCAL_MODEL_COST_MAP=True, and sets timeout=30. Added deterministic two-thread cold-import test test_import_litellm_serializes_concurrent_cold_imports_and_preserves_edits.
  • P3 (body counts): Updated PR description to state 24 parametrized variants, exact run 46976935702 (12 passing code checks at f31c23582 + separate Agent notes check), 97c56fe8 merging 5d9bb345 (#581), 25b405e3 merging deb2ede2, and updated verification runs at 308a22a8.

Local checks at 308a22a8

  • ruff format --check ., ruff check ., git diff --check, .github/check-agent-notes.sh HEAD, and mypy --follow-imports=silent src/policyengine/derivations/narrate.py tests/test_derivations.py: all pass.
  • Separate checkout-root runs of tests/test_derivations.py (--noconftest, checkout_stays_off_import_path active, policyengine_us/policyengine_uk masked): cold regression 1 passed; global Anthropic sampling 24 passed; offline provider translation (mocked sync + async) 24 passed; concurrent two-thread cold import 1 passed; full tests/test_derivations.py 81 passed, 2 skipped.
  • Python 3.13.15 (--noconftest, checkout_stays_off_import_path active): tests/test_inequality_properties.py 26 passed; tests/test_script_imports.py (with ordered_scenario_vectors cases deselected for missing policyengine_uk in that venv) 59 passed.
  • Full CI matrix (Python 3.11–3.14, test_script_imports.py, test_inequality.py, TRO checks) running at 308a22a8 (run 47119821040).

Next (4-round cap per pr-lifecycle.md)

Round 5 was already past the 4-round review cap and returned REQUEST_CHANGES, so per pr-lifecycle.md no round 6 is opened and the PR remains draft while Max's decision is queued via cos add-decision.

@MaxGhenis

Copy link
Copy Markdown
Contributor Author

Agent-written for Max, by Claude Code for Max Ghenis.

CI run 47119821040 at 308a22a8 passed Lint, Mypy, Check changelog fragment, Verify release inputs and bundle packages, all four Install + smoke-import jobs, Test (3.12), and Test (3.14), while Test (3.13) (144300733084) failed only tests/test_derivations.py::test_narrate_cold_litellm_import_leaves_sys_path_unchanged (5,089 passed, 16 skipped, 1 failed): the fresh subprocess hit timeout=30 (30.96s elapsed) because 308a22a8 predated #761's lazy country imports.

Commit 5f90a5bc merges origin/main through ba6c1b59 (#761) and raises test_narrate_cold_litellm_import_leaves_sys_path_unchanged's subprocess timeout in tests/test_derivations.py:547 from 30 to 120 seconds (matching the subprocess probes in tests/test_script_imports.py).

Local verification at 5f90a5bc:

  • ruff format --check ., ruff check ., git diff --check, .github/check-agent-notes.sh HEAD, and mypy --follow-imports=silent src/policyengine/derivations/narrate.py tests/test_derivations.py all passed (0 issues).
  • tests/test_derivations.py (Python 3.14.0 with litellm, --noconftest, checkout_stays_off_import_path, and policyengine_us/policyengine_uk masked): 81 passed, 2 skipped (2.76s).
  • tests/test_inequality_properties.py (Python 3.13 --noconftest, checkout_stays_off_import_path): 26 passed.
  • tests/test_script_imports.py -k 'not ordered_scenario_vectors' (Python 3.13 --noconftest, checkout_stays_off_import_path, policyengine_uk masked): 59 passed (2 failures expected in that isolated harness from absent tests/conftest.py collection stash and masked policyengine_uk; 4 deselected).

Updated PR body and queued 47143310989 (Agent notes 47143309915 passed; watching Code changes), plus updated decision card d3779.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Maintenance scripts and their tests change sys.path for the whole test session

2 participants