diff --git a/autohands/build_util.py b/autohands/build_util.py index c75e1b4e..6ec374e5 100644 --- a/autohands/build_util.py +++ b/autohands/build_util.py @@ -836,6 +836,9 @@ def execute_notebooks_in_folder( def execute_script(f, report=None, env=None, extra_args=None): args = [BUILD_PYTHON_INTERPRETER, f] + effective_env = os.environ if env is None else env + if effective_env.get("PYAUTO_TEST_MODE") == "2": + args = [BUILD_PYTHON_INTERPRETER, str(BUILD_PATH / "smoke_dependencies.py"), f] if extra_args: args.extend(extra_args) script_name = Path(f).relative_to(Path.cwd()) if Path(f).is_relative_to(Path.cwd()) else Path(f).name diff --git a/autohands/smoke_dependencies.py b/autohands/smoke_dependencies.py new file mode 100644 index 00000000..64a677f3 --- /dev/null +++ b/autohands/smoke_dependencies.py @@ -0,0 +1,101 @@ +"""Smoke-only dependency preflight, using autofit's public search manifest. + +Runs in the script interpreter, inside the existing process-group timeout. +Static detection covers imported autofit aliases and directly imported searches; +it does not try to infer dynamically selected constructors. +""" +import ast +import importlib +import json +from pathlib import Path +import runpy +import subprocess +import sys + + +def constructed_names(source): + tree = ast.parse(source) + aliases = set() + direct = {} + plot_aliases = set() + plotters = set() + direct_corner = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for item in node.names: + if item.name == 'autofit': + aliases.add(item.asname or item.name) + elif item.name == 'autofit.plot': + plot_aliases.add(item.asname or item.name) + elif isinstance(node, ast.ImportFrom) and node.module == 'autofit': + for item in node.names: + direct[item.asname or item.name] = item.name + if item.name == 'plot': + plot_aliases.add(item.asname or item.name) + elif isinstance(node, ast.ImportFrom) and node.module == 'autofit.plot': + for item in node.names: + if item.name == 'corner_cornerpy': + direct_corner.add(item.asname or item.name) + names = set() + def plot_constructor(node): + return (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and isinstance(node.func.value, ast.Name) + and node.func.value.id in plot_aliases) + for node in ast.walk(tree): + if isinstance(node, ast.Assign) and plot_constructor(node.value): + plotters.update(t.id for t in node.targets if isinstance(t, ast.Name)) + if not isinstance(node, ast.Call): + continue + fn = node.func + if isinstance(fn, ast.Attribute) and isinstance(fn.value, ast.Name) and fn.value.id in aliases: + names.add(fn.attr) + elif isinstance(fn, ast.Name) and fn.id in direct: + names.add(direct[fn.id]) + corner = any(isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and node.func.attr == 'corner_corner' + and ((isinstance(node.func.value, ast.Name) and node.func.value.id in plotters) + or plot_constructor(node.func.value)) for node in ast.walk(tree)) + corner = corner or any( + isinstance(node, ast.Call) and ( + isinstance(node.func, ast.Name) and node.func.id in direct_corner + or isinstance(node.func, ast.Attribute) and node.func.attr == 'corner_cornerpy' + and isinstance(node.func.value, ast.Name) and node.func.value.id in plot_aliases + ) for node in ast.walk(tree)) + return names, corner + + +def check_script(path): + names, corner = constructed_names(Path(path).read_text(encoding='utf-8')) + requirements = [] + if names: + # Preserve this smoke interpreter's environment and source checkouts. + proc = subprocess.run([sys.executable, '-m', 'autofit', 'search-manifest', '--json'], + capture_output=True, text=True) + if proc.returncode: + raise RuntimeError(f'{path}: cannot read autofit search manifest: {proc.stderr.strip()}') + manifest = json.loads(proc.stdout) + if manifest.get('schema') != 'search-manifest@1': + raise RuntimeError(f'{path}: unsupported autofit search manifest schema') + for search in manifest['searches']: + if search['name'] in names: + requirements.extend((search['name'], module) for module in search['requires']) + if corner: + requirements.append(('corner_corner', 'corner')) + for search, module in sorted(set(requirements)): + try: + importlib.import_module(module) + except Exception as exc: + raise RuntimeError(f'{path}: {search} requires importable module {module}: {exc}') from exc + + +def main(): + path = Path(sys.argv[1]).resolve() + sys.argv = sys.argv[1:] + # Match `python script.py` import resolution before checking or execution. + sys.path[0] = str(path.parent) + check_script(path) + runpy.run_path(str(path), run_name='__main__') + + +if __name__ == '__main__': + main() diff --git a/bin/autohands b/bin/autohands old mode 100755 new mode 100644 index 04d88989..a8e8d433 --- a/bin/autohands +++ b/bin/autohands @@ -110,6 +110,7 @@ INTERNAL_MODULES=( add_notebook_quotes # docstring->cell transform stage; its __main__ is a debug aid run_notebook # per-notebook worker subprocess spawned by run.py navigator # catalogue library behind regenerate_navigator / check_navigator + smoke_dependencies # smoke subprocess dependency preflight build_util # shared py_to_notebook machinery env_config # env-profile resolution library result_collector # per-run JSON result library diff --git a/docs/internals.md b/docs/internals.md index bb2bcf97..4e02c689 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -360,3 +360,19 @@ releasing" is now exactly what `rehearsal` mode is for.) `release.yml` is a **pure executor**: it builds, tests-the-install, publishes to PyPI, tags every library and workspace, and commits generated notebooks + Colab URL bumps to the workspaces (version stamps are build-tree-only since #120 — no `__init__.py` commit-backs to library mains, no workspace version pins). Workspace-integration validation (the old `find_scripts` / `generate_notebooks` / `run_scripts` / `run_notebooks` / `analyze_results` jobs) moved to **PyAutoHeart**'s `workspace-validation.yml`; release readiness is gated upstream by the PyAutoBrain release agent via `pyauto-heart readiness` before this workflow is dispatched. The `script_matrix.py` / `run_python.py` / `run.py` / `aggregate_results.py` primitives remain here and are checked out + reused by the Heart workflow. The never-rewrite-history rules live in [`AGENTS.md`](../AGENTS.md) and apply here as everywhere. + +### Smoke dependency preflight + +At `PYAUTO_TEST_MODE=2`, `execute_script` runs `smoke_dependencies.py` inside the +same script interpreter, environment and process-group timeout. Before executing +the script, it finds direct constructor calls through `import autofit` aliases +and `from autofit import Search` aliases, reads that interpreter's public +`search-manifest@1`, and imports the declared `requires` modules. A missing or +broken backend becomes an ordinary per-script failure with the script, search +and module in the report. Autofit `corner_cornerpy()` and plotter `corner_corner()` calls also require +`corner`. No second sampler dependency registry is maintained in Hands. + +This is conservative static detection: dynamically selected constructors and +alias reassignment are not inferred. Calls in unexecuted branches can therefore +require a backend. Other test modes retain direct script execution. The script's +arguments, working directory and sibling-import path are preserved. diff --git a/tests/test_smoke_dependencies.py b/tests/test_smoke_dependencies.py new file mode 100644 index 00000000..4efaa39e --- /dev/null +++ b/tests/test_smoke_dependencies.py @@ -0,0 +1,108 @@ +import json +import os +from pathlib import Path +import sys + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'autohands')) +import build_util +from result_collector import RunReport, Status +from smoke_dependencies import constructed_names + + +@pytest.mark.parametrize('source', [ + 'import autofit as af\naf.ExampleSearch()', + 'import autofit\nautofit.ExampleSearch()', + 'from autofit import ExampleSearch as Search\nSearch()', +]) +def test_constructor_aliases(source): + assert constructed_names(source) == ({'ExampleSearch'}, False) + + +def test_unrelated_names_and_non_calls_are_not_searches(): + assert constructed_names('import other as af\naf.ExampleSearch()') == (set(), False) + assert constructed_names('import autofit as af\ncls = af.ExampleSearch') == (set(), False) + + +def test_corner_plotter(): + source = 'from autofit import plot as afp\np = afp.MCMCPlotter()\np.corner_corner()' + assert constructed_names(source)[1] + assert not constructed_names('other.corner_corner()')[1] + + +@pytest.fixture +def runner(tmp_path, monkeypatch): + package = tmp_path / 'autofit' + package.mkdir() + (package / '__init__.py').write_text('def ExampleSearch(): pass\n') + manifest = {'schema': 'search-manifest@1', 'searches': [ + {'name': 'ExampleSearch', 'requires': ['example_backend_for_smoke']} ]} + (package / '__main__.py').write_text('import json\nprint(' + repr(json.dumps(manifest)) + ')\n') + monkeypatch.setattr(build_util, 'BUILD_PYTHON_INTERPRETER', sys.executable) + script = tmp_path / 'script.py' + def run(source, mode='2', extra_args=None): + script.write_text(source) + report = RunReport(project='fixture', directory=str(tmp_path), run_type='script') + build_util.execute_script(str(script), report=report, + env=dict(os.environ, PYTHONPATH=str(tmp_path), PYAUTO_TEST_MODE=mode), extra_args=extra_args) + return report.results[0] + return run + + +def test_missing_backend_fails_before_script_then_installed_passes(tmp_path, runner): + source = 'import autofit as af\naf.ExampleSearch()\nopen("' + str(tmp_path / 'ran') + '", "w").close()' + result = runner(source) + assert result.status == Status.FAILED + assert 'ExampleSearch requires importable module example_backend_for_smoke' in result.traceback + assert not (tmp_path / 'ran').exists() + (tmp_path / 'example_backend_for_smoke.py').write_text('') + assert runner(source).status == Status.PASSED + assert (tmp_path / 'ran').exists() + + +def test_broken_import_is_a_failure(tmp_path, runner): + (tmp_path / 'example_backend_for_smoke.py').write_text('raise RuntimeError("broken binary")') + result = runner('import autofit as af\naf.ExampleSearch()') + assert result.status == Status.FAILED + assert 'broken binary' in result.traceback + + +def test_real_mode_does_not_apply_smoke_guard(runner): + assert runner('import autofit as af\naf.ExampleSearch()', mode='1').status == Status.PASSED + + +@pytest.mark.parametrize('source,code', [('if invalid syntax', 1), ('raise SystemExit(7)', 7)]) +def test_script_failures_are_reported(runner, source, code): + result = runner(source) + assert result.status == Status.FAILED + assert result.exit_code == code + + +def test_script_argv_and_local_imports_survive(tmp_path, runner): + (tmp_path / 'sibling.py').write_text('value = 5') + source = 'import sys, sibling\nassert sibling.value == 5\nassert sys.argv[1:] == ["argument"]\nassert __name__ == "__main__"' + assert runner(source, extra_args=['argument']).status == Status.PASSED + + +def test_manifest_failure_is_not_silently_ignored(tmp_path, runner): + (tmp_path / 'autofit/__main__.py').write_text('raise SystemExit(3)') + result = runner('import autofit as af\naf.ExampleSearch()') + assert result.status == Status.FAILED + assert 'cannot read autofit search manifest' in result.traceback + + +@pytest.mark.parametrize('source', [ + 'import autofit.plot as aplt\naplt.corner_cornerpy(samples=None)', + 'from autofit.plot import corner_cornerpy as corner_plot\ncorner_plot(samples=None)', + 'from autofit import plot as aplt\naplt.corner_cornerpy(samples=None)', +]) +def test_public_corner_function(source): + assert constructed_names(source)[1] + + +def test_smoke_preflight_is_inside_process_timeout(tmp_path, runner, monkeypatch): + monkeypatch.setenv('BUILD_SCRIPT_TIMEOUT', '1') + (tmp_path / 'autofit/__main__.py').write_text('import time\ntime.sleep(10)') + result = runner('import autofit as af\naf.ExampleSearch()') + assert result.status == Status.TIMEOUT