diff --git a/meta_harness/runner_materialization.py b/meta_harness/runner_materialization.py index b69efed..fc9df3a 100644 --- a/meta_harness/runner_materialization.py +++ b/meta_harness/runner_materialization.py @@ -2,7 +2,6 @@ from __future__ import annotations -import importlib.util import ast import json import py_compile @@ -15,6 +14,7 @@ RunnerRegistry, runtime_dependencies, ) +from meta_harness.runners.generic_transformers import _load_candidate_module class RunnerMaterializationError(RuntimeError): @@ -111,13 +111,7 @@ def _validate_candidate_adapter(path: Path, requirements: ExperimentRequirements raise RunnerMaterializationError("candidate_adapter_identity") try: py_compile.compile(str(path), doraise=True) - spec = importlib.util.spec_from_file_location( - f"deepgraph_candidate_adapter_{id(path)}", path - ) - if spec is None or spec.loader is None: - raise RunnerMaterializationError("candidate_adapter_unloadable") - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) + module = _load_candidate_module(path) except RunnerMaterializationError: raise except Exception as exc: diff --git a/meta_harness/runners/generic_transformers.py b/meta_harness/runners/generic_transformers.py index 9a79eef..d65f1ff 100644 --- a/meta_harness/runners/generic_transformers.py +++ b/meta_harness/runners/generic_transformers.py @@ -58,14 +58,33 @@ def _clamped_seeds(seeds: Sequence[int]) -> list[int]: return declared -def _load_candidate(path: Path, protocol: str): +def _load_candidate_module(path: Path): if not path.is_file(): raise RunnerContractError("runner_contract_violation", "candidate_adapter_missing") - spec = importlib.util.spec_from_file_location("deepgraph_candidate_adapter", path) + module_name = "deepgraph_candidate_adapter_" + hashlib.sha256( + str(path.resolve()).encode("utf-8") + ).hexdigest() + spec = importlib.util.spec_from_file_location(module_name, path) if spec is None or spec.loader is None: raise RunnerContractError("runner_contract_violation", "candidate_adapter_unloadable") module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) + # Dataclasses and deferred annotations resolve through sys.modules during + # execution. Keep each candidate path in its own module namespace. + previous = sys.modules.get(module_name) + sys.modules[module_name] = module + try: + spec.loader.exec_module(module) + except BaseException: + if previous is None: + sys.modules.pop(module_name, None) + else: + sys.modules[module_name] = previous + raise + return module + + +def _load_candidate(path: Path, protocol: str): + module = _load_candidate_module(path) method_name = str(getattr(module, "CANDIDATE_METHOD", "")).strip() if not method_name: raise RunnerContractError("runner_contract_violation", "candidate_method_missing") diff --git a/tests/test_candidate_module_registration.py b/tests/test_candidate_module_registration.py new file mode 100644 index 0000000..21415de --- /dev/null +++ b/tests/test_candidate_module_registration.py @@ -0,0 +1,87 @@ +import sys +import subprocess +from typing import get_type_hints + +import pytest + +from meta_harness.runners.generic_transformers import _load_candidate +from meta_harness.runner_materialization import materialize_runner_bundle + + +SOURCE = '''from __future__ import annotations +from dataclasses import dataclass +Alias = {alias} +@dataclass +class Settings: + value: Alias +CANDIDATE_METHOD = "candidate" +def candidate_prompt(example, baseline_prompt): + return baseline_prompt + str(Settings(example["value"]).value) +''' + + +def test_candidate_dataclass_can_resolve_its_module(tmp_path): + path = tmp_path / "candidate.py" + path.write_text(SOURCE.format(alias="str")) + module, method, hook = _load_candidate(path, "generative_qa") + assert method == "candidate" + assert getattr(module, hook)({"value": "answer"}, "prefix ") == "prefix answer" + assert get_type_hints(module.Settings) == {"value": str} + + +def test_distinct_candidate_files_keep_distinct_annotation_namespaces(tmp_path): + modules = [] + for name, alias in (("one", "str"), ("two", "int")): + path = tmp_path / (name + ".py") + path.write_text(SOURCE.format(alias=alias)) + modules.append(_load_candidate(path, "generative_qa")[0]) + assert modules[0].__name__ != modules[1].__name__ + assert get_type_hints(modules[0].Settings) == {"value": str} + assert get_type_hints(modules[1].Settings) == {"value": int} + + +def test_failed_execution_does_not_leave_a_partial_registered_module(tmp_path): + path = tmp_path / "broken.py" + path.write_text("raise RuntimeError('broken import')\n") + before = set(sys.modules) + with pytest.raises(RuntimeError, match="broken import"): + _load_candidate(path, "generative_qa") + assert {name for name in set(sys.modules) - before if name.startswith("deepgraph_candidate_adapter")} == set() + + +def test_dataclass_adapter_passes_materialization_and_the_portable_loader(tmp_path): + requirements = { + "schema_version": "experiment_requirements_v1", + "task_protocol": "generative_qa", "candidate_hook": "candidate_prompt", + "dataset": { + "repository_id": "org/data", "revision": "main", "split": "test", + "field_mapping": {"prompt": "question", "target": "answer"}, + }, + "model": { + "repository_id": "org/model", "revision": "main", + "framework": "transformers", "task": "causal_lm", "requires_cuda": True, + }, + "metric": {"name": "exact_match", "direction": "higher"}, + "dependencies": ["torch", "transformers", "datasets"], + "seeds": [7], "sample_cap": 2, + "artifact_contract": ["final_results", "raw_predictions", "environment_manifest", + "dataset_manifest", "model_manifest"], + "preferred_backends": ["ssh_gpu"], + } + materialize_runner_bundle( + workdir=tmp_path, + preflight_row={ + "id": 1, "status": "passed", "adapter_id": "transformers_causal_lm_qa_v1", + "adapter_version": "1.0.0", "dataset_revision": "a" * 40, + "model_revision": "b" * 40, "requirements_json": requirements, + }, + candidate_adapter_source=SOURCE.format(alias="str"), + ) + result = subprocess.run([ + sys.executable, "-c", + "from pathlib import Path; from typing import get_type_hints; " + "from meta_harness.runners.generic_transformers import _load_candidate; " + "m, _, _ = _load_candidate(Path('candidate_adapter.py'), 'generative_qa'); " + "assert get_type_hints(m.Settings) == {'value': str}", + ], cwd=tmp_path / "code", capture_output=True, text=True) + assert result.returncode == 0, result.stderr