From ef126ccfbc707adb94a1a1bf29ba6f2f2a60d760 Mon Sep 17 00:00:00 2001 From: dongxinwen Date: Fri, 27 Nov 2026 06:18:17 +0800 Subject: [PATCH 1/2] Separate ordinary Harness execution and evaluation Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (author) Signed-off-by: dongxinwen --- CHANGELOG.md | 13 ++ docs/architecture.md | 14 +- docs/guides/module-layout.md | 4 +- .../optimization-workflow-unification.md | 10 +- .../plan/retained-sha256.json | 2 +- .../validator/check.py | 6 +- src/inferrsi/apps/cli/__init__.py | 2 + .../apps/workflows/benchmark_compare.py | 4 +- .../apps/workflows/benchmark_operations.py | 8 +- .../apps/workflows/search_benchmarks.py | 27 ++-- src/inferrsi/harness/README.md | 12 +- src/inferrsi/harness/evaluator/__init__.py | 35 ++++ .../_measurement.py} | 0 .../{project.py => evaluator/_project.py} | 86 ++-------- src/inferrsi/harness/executor/__init__.py | 20 ++- .../harness/executor/_benchmark_child.py | 42 +++++ src/inferrsi/harness/executor/_ordinary.py | 94 +++++++++++ src/inferrsi/harness/executor/_project.py | 68 ++++++++ .../_task_protocol.py} | 27 +++- .../harness/{ => executor}/protocol_child.py | 4 +- src/inferrsi/harness/optimization.py | 3 +- src/inferrsi/harness/optimization_session.py | 151 ++---------------- tests/apps/test_optimization_session.py | 74 +++++---- tests/apps/test_project_explanation.py | 14 +- tests/apps/test_project_optimization.py | 19 ++- tests/apps/test_project_service_reuse.py | 4 +- tests/apps/test_search_benchmarks.py | 7 +- tests/apps/test_session_ranking_policy.py | 6 +- tests/benchmark/test_benchmark_compare.py | 4 +- tests/benchmark/test_benchmark_operations.py | 9 +- tests/campaigns/test_qwen_gvo_diagnostic.py | 2 +- tests/fixtures/session_process.py | 10 +- tests/harness/test_harness_measurement.py | 24 ++- .../harness/test_moe_optimization_protocol.py | 8 +- .../test_service_fingerprint_isolation.py | 7 +- tests/harness/test_task_protocol_child.py | 35 ++-- tests/repository/_gate_policy_support.py | 1 + .../test_first_wave_isolation_policy.py | 2 +- .../test_target_module_import_gate.py | 3 +- tools/measurement_simulation.py | 6 +- 40 files changed, 497 insertions(+), 370 deletions(-) create mode 100644 src/inferrsi/harness/evaluator/__init__.py rename src/inferrsi/harness/{measurement.py => evaluator/_measurement.py} (100%) rename src/inferrsi/harness/{project.py => evaluator/_project.py} (69%) create mode 100644 src/inferrsi/harness/executor/_benchmark_child.py create mode 100644 src/inferrsi/harness/executor/_ordinary.py create mode 100644 src/inferrsi/harness/executor/_project.py rename src/inferrsi/harness/{task_protocol.py => executor/_task_protocol.py} (91%) rename src/inferrsi/harness/{ => executor}/protocol_child.py (97%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f3a87d4e..f497e60d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,19 @@ ### Changed +- For ordinary projects, import `prepare_project` and `execute_ordinary` from + `inferrsi.harness.executor`. The former `inferrsi.harness.project` operations + `prepare`, `steps`, `inspect_step` and `assess` are now `executor.prepare_project`, + `evaluator.project_steps`, `evaluator.inspect_project_step` and `evaluator.assess_project`. + Use `executor.validate_project` and `executor.PROJECT_DECISIONS` for the former + `project.validate` and `project.DECISIONS`. Import paired statistics and explanation helpers from `inferrsi.harness.evaluator` + in place of `inferrsi.harness.measurement`. Packaged tasks retain their own scoring rules. + +- Import `prepare_task_protocol`, `run_task_protocol` and `TaskProtocolError` from + `inferrsi.harness.executor`. They replace `prepare`, `run` and `TaskProtocolError` + in the former `inferrsi.harness.task_protocol` module. Each operation uses the + frozen task resources and the same isolated child process protocol. + - Import the four-port AB/BA loop with `from inferrsi.harness.manager import run_experiment`. The former `inferrsi.harness.runner` module was removed. The `inferrsi run` CLI and `inferrsi.apps.legacy.run.run_experiment` continue to supply the four port bindings. diff --git a/docs/architecture.md b/docs/architecture.md index e384b3d4e..4bad5b540 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -13,17 +13,19 @@ Each task retains its own protocol and task-specific code. The [current-Agent optimization session](benchmarks/optimization-benchmarks.md) assembles the first complete handoff for the Qwen task. `harness/optimization.py` controls budget, attempts, feedback records, selection and independent final execution. -`harness/task_protocol.py` freezes a supplied resource directory and loads its -task-owned assessment protocol. `harness/optimization_session.py` assembles -execution and assessment; the CLI resolves task resources and injects knowledge -access and the capture callback from `apps/workflows/campaign.py`. +Harness Executor freezes a supplied resource directory with `prepare_task_protocol` +and starts its task-owned protocol in an isolated child with `run_task_protocol`. +The CLI resolves task resources and supplies the task assessor, knowledge access and +capture callback to `harness/optimization_session.py`. The external Agent chooses and edits candidates between round submissions. The same controller serves ordinary projects through `campaign start/round/final` and packaged tasks through `benchmarks session`. The [shared workflow and sequence diagram](guides/optimization-workflow-unification.md) describe multi-file candidates, explicit acceptance inputs, stop rules and -dashboard projections from one control record. `harness/project.py` freezes -caller-provided checks and assesses their retained outputs. Ordinary optimization +dashboard projections from one control record. Harness Executor freezes caller-provided +project checks and runs the steps in order. Evaluator inspects each retained step before +execution continues and uses the same rule for the final AB/BA verdict. For packaged +tasks, Evaluator invokes the task assessor supplied by Apps. Ordinary optimization does not import Benchmark. Benchmark supplies task definitions and specialized rules, while Harness manages their execution and the complete optimization lifecycle. Neither infers quality criteria from a natural-language goal. diff --git a/docs/guides/module-layout.md b/docs/guides/module-layout.md index 5ad5a7b7e..a5ef2caf4 100644 --- a/docs/guides/module-layout.md +++ b/docs/guides/module-layout.md @@ -180,8 +180,8 @@ registered consumers; this gate does not scan them. #412 R3 retired the five temporary resource-loader declarations and their `runtime resource loaders` blocker. Three of the five were removed: -- `harness.task_protocol` no longer loads task code. Each protocol operation - (`validate_arguments`, `arguments`, `assess`) runs `harness/protocol_child.py` +- Harness Executor supervises the frozen task protocol. Each operation + (`validate_arguments`, `arguments`, `assess`) runs `harness/executor/protocol_child.py` as `python -I -B` in its own process group or Windows Job under a deadline, and answers with one strict JSON envelope on a private copy of stdout. The child imports only the standard library and compiles the exact protocol bytes it has diff --git a/docs/guides/optimization-workflow-unification.md b/docs/guides/optimization-workflow-unification.md index 3e6ff7b37..00cb44d24 100644 --- a/docs/guides/optimization-workflow-unification.md +++ b/docs/guides/optimization-workflow-unification.md @@ -80,19 +80,19 @@ sequenceDiagram Note over A,H: final 使用留存的最佳版本;工作区未提交修改不参与 end C->>H: session_command:提交 round/final 参数 - H->>H: evaluate_round:使用内部 execute / assess 适配函数 + H->>H: evaluate_round:绑定 Executor 执行和 Evaluator 判定 H->>H: 核验文件、状态和预算,选择提交候选或留存最佳版本 H->>H: 保存到 rounds/… 或 final/…;state.pending 记录本次待完成尝试 - H->>H: _session_execute → _project_execute → project.steps + H->>H: executor.execute_ordinary → evaluator.project_steps Note over H: 根据固定配置生成基线/候选的质量、预热、交替测量命令 loop 按固定步骤采集;拒绝或异常时停止本次采集 H->>H: execute_trial → execute_command:运行质量/计时脚本,保存 result.json 和日志 H->>H: 留存状态、退出码、耗时;核对源码身份并记录 source_checks - H->>H: project.inspect_step:检查结果格式、质量字段和性能值,决定继续或拒绝 + H->>H: evaluator.inspect_project_step:检查结果格式、质量字段和性能值,决定继续或拒绝 end H->>H: 保存 execution.json;各步结果、日志和执行事实已落盘 H->>H: _settle:再次核验固定条件和候选身份 - H->>H: _session_assess → project.assess:读取固定配置与留存结果,不重新测量 + H->>H: evaluator.assess_ordinary → assess_project:读取固定配置与留存结果,不重新测量 H->>H: 核对完整性与质量,重算中位数/提升比例,比较门槛 Note over H: 产生 assessment:判定、指标、质量标记、证据引用和拒绝原因 H->>H: 写 observation.json;round 更新最佳候选,final 记录独立复测结论 @@ -152,7 +152,7 @@ Harness 没有常驻 Agent 驱动。Agent 逐次调用这些操作,代码在 两个优化入口都调用 `harness.optimization_session.session_command`,使用同一个 `harness.optimization` 控制器。AB/BA 与题包使用 `evaluate_round`;显式 service_reuse 使用该控制器内的 `service_command` 和模式分支,共用锁及单一控制记录。执行与评测适配也在 Harness 内;普通项目整个生命周期不导入 Benchmark。 -题库 `start` 由 CLI 经 `benchmark.registry` 定位资源目录,再交给 `harness.task_protocol.prepare` 固化;后续从冻结目录加载题包自己的 `optimization.py`,无需再次查询注册表。专用协议检查仍属于题包。两类 `assess` 都只读留存结果,不重新测量。KnowledgeReader 与 `apps/workflows/campaign.py` 的记录回调由 CLI 注入,Harness 不直接导入 Benchmark 或目标 Knowledge 模块,也不经记录模块间接引入知识实现。 +题库 `start` 由 CLI 经 `benchmark.registry` 定位资源目录,再交给 `harness.executor.prepare_task_protocol` 固化;后续从冻结目录加载题包自己的 `optimization.py`,无需再次查询注册表。专用协议检查仍属于题包。两类 `assess` 都只读留存结果,不重新测量。KnowledgeReader 与 `apps/workflows/campaign.py` 的记录回调由 CLI 注入,Harness 不直接导入 Benchmark 或目标 Knowledge 模块,也不经记录模块间接引入知识实现。 本次交付可以分成三块:**Benchmark 的优化题目、Harness 的优化管理与验收、Harness 与宿主协作的新会话派发和回收**。第三块不改变第二块的生命周期;新会话仍自行 start 到 final。 diff --git a/evidence/qwen-vats-gvo-910b1-20261124/plan/retained-sha256.json b/evidence/qwen-vats-gvo-910b1-20261124/plan/retained-sha256.json index 82ba672ce..feeeee5da 100644 --- a/evidence/qwen-vats-gvo-910b1-20261124/plan/retained-sha256.json +++ b/evidence/qwen-vats-gvo-910b1-20261124/plan/retained-sha256.json @@ -9,5 +9,5 @@ "results/summary.json": "df3029cfcaacb91018b6c931017b059b99a80633116586f9446fe82e31986132", "results/trials.jsonl": "6bd39719a5c0d794b1c5e04403b03789ae5ca42e0c9c74694200bdb6355a0756", "validator/README.md": "c224e3d864829d5c1a2f8bc4e4c89e36834409d4ce78fc1fa7dc59f6f739fdd3", - "validator/check.py": "83b89ce30d89c8dd68e7092403ec5b62d965a9a9587caa65fcd0b541def5d3fd" + "validator/check.py": "33463b8c9ec1a4d845a71cc6711057ecae015dfda602a0735cfe73f2ba031c86" } diff --git a/evidence/qwen-vats-gvo-910b1-20261124/validator/check.py b/evidence/qwen-vats-gvo-910b1-20261124/validator/check.py index a9ade12be..092fac20d 100644 --- a/evidence/qwen-vats-gvo-910b1-20261124/validator/check.py +++ b/evidence/qwen-vats-gvo-910b1-20261124/validator/check.py @@ -9,7 +9,7 @@ from statistics import geometric_mean from inferrsi.benchmark.registry import task_resources -from inferrsi.harness import task_protocol +from inferrsi.harness.executor import run_task_protocol from inferrsi.harness.executor import candidates from inferrsi.harness.manager.search.work_control import WorkControl from inferrsi.harness.records import RunStoreReader @@ -112,7 +112,7 @@ def main(completed, failed, historical_driver=None): path = historical_driver or completed.parent.parent / "config/run.py" require(sha(path) == expected_hash, name) protocol_hash = spec["packaged_task_sha256"]["optimization.py"] - settings = task_protocol.run( + settings = run_task_protocol( task, protocol_hash, "validate_arguments", arguments=plan["sampling"] ) expected = [(arm, seed) for seed, arms in plan["blocks"] for arm in arms] @@ -179,7 +179,7 @@ def main(completed, failed, historical_driver=None): folder = measure.parents[1] raw = read(measure) execution = read(folder / "execution/execution.json") - assessment = task_protocol.run( + assessment = run_task_protocol( task, protocol_hash, "assess", diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index 59106bd5a..c319acb29 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -33,6 +33,7 @@ def _round_provider(plan): def _optimization_session(args, *, task_source=None, report_metadata=None): + from ...harness.executor import assess_packaged_task from ...harness.optimization_session import session_command from ...knowledge.ranking_policy import managed_ranking_policy @@ -47,6 +48,7 @@ def _optimization_session(args, *, task_source=None, report_metadata=None): external_project = freeze_project(args.repo if args.project_task else None) return session_command( args, task_source=task_source, prepare_context=prepare_context, + assess_packaged=assess_packaged_task, ranking_policy_for=managed_ranking_policy, knowledge_reader=KnowledgeReader() if args.session_action == "knowledge" else None, external_knowledge=settings, external_project=external_project, diff --git a/src/inferrsi/apps/workflows/benchmark_compare.py b/src/inferrsi/apps/workflows/benchmark_compare.py index a3f8335b0..82e6b16e5 100644 --- a/src/inferrsi/apps/workflows/benchmark_compare.py +++ b/src/inferrsi/apps/workflows/benchmark_compare.py @@ -30,11 +30,11 @@ from inferrsi.benchmark.summary import POLICY, supported_policy from inferrsi.benchmark.summary import comparison as metrics_comparison from inferrsi.harness import agent_sessions, optimization +from inferrsi.harness.executor import run_task_protocol from inferrsi.harness.optimization_session import _runtime_identity from inferrsi.harness.records.artifact_primitives import digest, file_lock, sha256 from inferrsi.harness.records.atomic_json import atomic_write_json from inferrsi.harness.records.knowledge_capture import verify_capture -from inferrsi.harness.task_protocol import run as protocol_operation from inferrsi.knowledge.catalog import SCENARIO_ALIASES from inferrsi.knowledge.context_projection import assemble_context_text from inferrsi.knowledge.knowledge_operations import KnowledgeReader @@ -237,7 +237,7 @@ def prepare(args): for name in config["tasks"]: resource = Path(str(task_resources(name))) manifest = _object(resource / "task.json") - settings = protocol_operation(resource, sha256(resource / "optimization.py"), + settings = run_task_protocol(resource, sha256(resource / "optimization.py"), "validate_arguments", arguments=shlex.split(config["task_arguments"][name])) task_settings[name] = {"settings": settings, "files": _manifest(resource), diff --git a/src/inferrsi/apps/workflows/benchmark_operations.py b/src/inferrsi/apps/workflows/benchmark_operations.py index 343c929b0..e127ca77a 100644 --- a/src/inferrsi/apps/workflows/benchmark_operations.py +++ b/src/inferrsi/apps/workflows/benchmark_operations.py @@ -1,12 +1,9 @@ """Resolve packaged tasks at the application boundary and launch their entries.""" import subprocess -import sys -from pathlib import Path from inferrsi.benchmark.registry import task_resources -from inferrsi.harness import optimization_session -from inferrsi.harness.executor import runtime_environment +from inferrsi.harness.executor import benchmark_command, runtime_environment def run_task(name: str, arguments: list[str]) -> int: @@ -14,7 +11,6 @@ def run_task(name: str, arguments: list[str]) -> int: if not entry.is_file(): raise ValueError(f"Missing benchmark.py entry for task: {name}") return subprocess.call( - [sys.executable, str(Path(optimization_session.__file__).resolve()), - str(entry), *arguments], + benchmark_command(entry, arguments), env=runtime_environment(), ) diff --git a/src/inferrsi/apps/workflows/search_benchmarks.py b/src/inferrsi/apps/workflows/search_benchmarks.py index f5e0faf57..5809c8804 100644 --- a/src/inferrsi/apps/workflows/search_benchmarks.py +++ b/src/inferrsi/apps/workflows/search_benchmarks.py @@ -13,8 +13,14 @@ from inferrsi.apps.workflows.improvement import assessment from inferrsi.benchmark.improvement import SelectionPolicy, holdout_accepts from inferrsi.benchmark.registry import task_resources -from inferrsi.harness import task_protocol -from inferrsi.harness.executor import candidates, runtime_environment +from inferrsi.harness.executor import ( + TaskProtocolError, + benchmark_command, + candidates, + prepare_task_protocol, + run_task_protocol, + runtime_environment, +) from inferrsi.harness.executor.trials.external import execute_trial from inferrsi.harness.records.artifact_primitives import digest, sha256 from inferrsi.harness.records.atomic_json import atomic_write_json @@ -25,7 +31,7 @@ class EngineEvaluator: def __init__(self, package, frozen, *, arguments, python=sys.executable, prefix=()): self.frozen = Path(frozen).resolve() - self.plan = task_protocol.prepare( + self.plan = prepare_task_protocol( Path(str(task_resources(package))), self.frozen, arguments ) self.python, self.prefix = python, tuple(prefix) @@ -55,12 +61,11 @@ def evaluate(self, candidate, check, output, deadline): self._check_resources() output.mkdir(parents=True) candidates.retain(candidate / "candidate.py", output / "candidate.py") - from inferrsi.harness import optimization_session execution = None cleanup = True try: - args = task_protocol.run( + args = run_task_protocol( self.frozen, self.plan["frozen_files"]["optimization.py"], "arguments", @@ -69,12 +74,8 @@ def evaluate(self, candidate, check, output, deadline): output=output / "measurement", settings=self.plan["evaluation_settings"], ) - command = ( - *self.prefix, - self.python, - str(Path(optimization_session.__file__).resolve()), - str(self.frozen / "benchmark.py"), - *args, + command = benchmark_command( + self.frozen / "benchmark.py", args, python=self.python, prefix=self.prefix, ) environment = runtime_environment() environment["PYTHONDONTWRITEBYTECODE"] = "1" @@ -89,7 +90,7 @@ def evaluate(self, candidate, check, output, deadline): ) cleanup = execution["cleanup_verified"] self._check_resources(during=True) - assessed = task_protocol.run( + assessed = run_task_protocol( self.frozen, self.plan["frozen_files"]["optimization.py"], "assess", @@ -98,7 +99,7 @@ def evaluate(self, candidate, check, output, deadline): settings=self.plan["evaluation_settings"], execution=execution, ) - except task_protocol.TaskProtocolError as error: + except TaskProtocolError as error: if error.kind != "timeout": raise # Retain a real timeout as INCONCLUSIVE even when no time remains diff --git a/src/inferrsi/harness/README.md b/src/inferrsi/harness/README.md index b07574899..1fabf2bfc 100644 --- a/src/inferrsi/harness/README.md +++ b/src/inferrsi/harness/README.md @@ -16,8 +16,11 @@ measurement and assessment rules. [path, JSON and diagnostic limits](records/service_io.py). - [`optimization_session.py`](optimization_session.py) connects session commands to the budget and recovery logic in [`optimization.py`](optimization.py). - [`task_protocol.py`](task_protocol.py) prepares task protocol packages and runs - their operations in a subprocess with source hash and response checks. + [Executor](executor/__init__.py) exposes `prepare_task_protocol` to freeze task resources + and `run_task_protocol` to run their operations in an [isolated child](executor/protocol_child.py). + For an ordinary project, `prepare_project` freezes the checks and `execute_ordinary` runs each + allowed step before the shared deadline. [Evaluator](evaluator/__init__.py) checks each + completed step before Executor launches the next process. - [Skill trials](executor/skill_evaluation.py) execute commands and retain their results. The [artifact sandbox](executor/artifact_sandbox.py) captures and replays submitted artifacts. @@ -66,8 +69,9 @@ The agent chooses a hypothesis and edits a candidate between rounds. - **Executor** owns the retained candidate, task runner and [service lifecycle](project_service.py), including measurement collection, process ownership and cleanup. - **Evaluator** uses the frozen rules and stage receipts to decide the next stage or verdict. - [_session_assess](optimization_session.py) dispatches packaged tasks to their protocol - assessor and project trials to the [AB/BA assessor](project.py). Service screening is + `assess_ordinary` dispatches packaged tasks to the frozen task assessor supplied by Apps. + For AB/BA projects, `assess_project` rereads retained evidence with the same + `inspect_project_step` rule used during execution. Service screening is diagnostic. [Service evaluation](project_service.py) uses formal samples and quality evidence. New plans freeze the ranking ID, scoring version and all effective weights. Ordinary diff --git a/src/inferrsi/harness/evaluator/__init__.py b/src/inferrsi/harness/evaluator/__init__.py new file mode 100644 index 000000000..608c80252 --- /dev/null +++ b/src/inferrsi/harness/evaluator/__init__.py @@ -0,0 +1,35 @@ +"""Assess ordinary attempts against frozen rules and retained evidence.""" + +from ._measurement import ( + CONFIDENCE, + DIRECTIONS, + METHOD, + MIN_PAIRS, + explain, + gate_speedup, + interval_rank, + median_interval, + min_pairs, + paired_speedups, + paired_statistics, + profile_evidence, + relative_mad, + validate_mechanism, +) +from ._project import assess_project, inspect_project_step, project_steps + +__all__ = [ + "CONFIDENCE", "DIRECTIONS", "METHOD", "MIN_PAIRS", "assess_ordinary", "assess_project", + "explain", "gate_speedup", + "inspect_project_step", "interval_rank", "median_interval", "min_pairs", "paired_speedups", + "paired_statistics", "profile_evidence", "project_steps", "relative_mad", "validate_mechanism", +] + + +def assess_ordinary(root, directory, plan, execution, mechanism=None, *, assess_packaged): + """Read project evidence or delegate to the packaged task's supplied assessor.""" + if plan["task_source"] == "project": + return assess_project( + directory, plan["evaluation_settings"], execution, mechanism=mechanism, + ) + return assess_packaged(root, directory, plan, execution) diff --git a/src/inferrsi/harness/measurement.py b/src/inferrsi/harness/evaluator/_measurement.py similarity index 100% rename from src/inferrsi/harness/measurement.py rename to src/inferrsi/harness/evaluator/_measurement.py diff --git a/src/inferrsi/harness/project.py b/src/inferrsi/harness/evaluator/_project.py similarity index 69% rename from src/inferrsi/harness/project.py rename to src/inferrsi/harness/evaluator/_project.py index 0ed639282..ca0c2630a 100644 --- a/src/inferrsi/harness/project.py +++ b/src/inferrsi/harness/evaluator/_project.py @@ -1,80 +1,16 @@ -"""Harness protocol for caller-supplied project checks and retained outputs. - -The caller supplies the workload, measurement and quality meaning. This adapter -does not infer acceptance from natural language or launch any commands. -""" +"""Order AB/BA checks, interpret each receipt and judge the frozen project contract.""" import json import math -import shutil from pathlib import Path from statistics import median -from .measurement import MIN_PAIRS, explain, paired_statistics, profile_evidence, validate_mechanism -from .records.artifact_primitives import sha256 - -DECISIONS = ("point", "paired") - - -def validate(settings: dict) -> None: - for key in ("measure_command", "quality_command"): - command = settings[key] - if not command or not all(isinstance(arg, str) and arg for arg in command): - raise ValueError(f"An explicit {key} argv is required") - if not any("{protocol}" in arg for arg in command): - raise ValueError(f"{key} must use a retained {{protocol}} script") - if not any("{result}" in arg for arg in command): - raise ValueError(f"{key} must write to the supplied {{result}} path") - for key in ("metric_key", "metric_unit", "quality_key", "scope"): - if not isinstance(settings[key], str) or not settings[key].strip(): - raise ValueError(f"An explicit {key} is required") - if settings["direction"] not in ("minimize", "maximize"): - raise ValueError("Metric direction must be explicit") - if type(settings["repetitions"]) is not int or settings["repetitions"] < 1: - raise ValueError("Positive repetitions required") - if type(settings["warmups"]) is not int or settings["warmups"] < 0: - raise ValueError("Nonnegative warmups required") - value = settings["min_improvement_pct"] - if type(value) not in (int, float) or not math.isfinite(value) or value < 0: - raise ValueError("An explicit finite nonnegative improvement gate is required") - if settings.get("decision", "point") not in DECISIONS: - raise ValueError("Decision must be point or paired") - if settings.get("decision") == "paired" and settings["repetitions"] < MIN_PAIRS: - raise ValueError(f"A paired decision needs at least {MIN_PAIRS} repetitions") - if type(settings.get("require_explanation", False)) is not bool: - raise ValueError("require_explanation must be a boolean") - if settings.get("require_explanation") and settings["repetitions"] < MIN_PAIRS: - # Fewer pairs give no interval for any expectation, so every round would be - # unverifiable and no candidate could ever be adopted. - raise ValueError(f"--require-explanation needs at least {MIN_PAIRS} repetitions") +from inferrsi.harness.records.artifact_primitives import sha256 +from ._measurement import explain, paired_statistics, profile_evidence, validate_mechanism -def prepare(destination: Path, protocol: Path, instructions: Path, settings: dict) -> dict: - """Retain the caller's explicit acceptance inputs, without inventing criteria.""" - validate(settings) - if not protocol.is_dir() or protocol.is_symlink() or not instructions.is_file(): - raise ValueError("Existing protocol directory and task instructions are required") - if destination.resolve().is_relative_to(protocol.resolve()): - raise ValueError("Frozen output must be outside the protocol directory") - paths = [p for p in protocol.rglob("*") if p.is_file()] - if not paths or any(p.is_symlink() for p in protocol.rglob("*")): - raise ValueError("Protocol must contain regular retained files") - before = {p.relative_to(protocol).as_posix(): sha256(p) for p in paths} - destination.mkdir(parents=True) - shutil.copytree(protocol, destination / "protocol") - (destination / "TASK.md").write_bytes(instructions.read_bytes()) - after = {p.relative_to(protocol).as_posix(): sha256(p) - for p in protocol.rglob("*") if p.is_file()} - copied = {p.relative_to(destination / "protocol").as_posix(): sha256(p) - for p in (destination / "protocol").rglob("*") if p.is_file()} - if before != after or copied != before: - raise ValueError("Acceptance inputs changed during freeze") - return {"evaluation_settings": settings, - "frozen_files": {p.relative_to(destination).as_posix(): sha256(p) - for p in destination.rglob("*") if p.is_file()}} - -def steps(settings: dict) -> list[dict]: +def project_steps(settings: dict) -> list[dict]: result = [{"id": f"quality-{side}", "phase": "quality", "side": side, "argv": settings["quality_command"]} for side in ("baseline", "candidate")] for phase, count in (("warmup", settings["warmups"]), @@ -97,7 +33,9 @@ def _value(document, key): return value -def inspect_step(directory: Path, settings: dict, definition: dict, execution: dict) -> dict: +def inspect_project_step( + directory: Path, settings: dict, definition: dict, execution: dict, +) -> dict: """Interpret one frozen script's explicit result, never guess a crash's cause.""" failure = {"status": "infrastructure_failure", "reason": "failed_execution"} if execution.get("status") != "completed": @@ -134,10 +72,8 @@ def inspect_step(directory: Path, settings: dict, definition: dict, execution: d "evidence_files": evidence} - - -def assess(directory: Path, settings: dict, execution: dict, *, - mechanism: dict | None = None) -> dict: +def assess_project(directory: Path, settings: dict, execution: dict, *, + mechanism: dict | None = None) -> dict: """Judge one attempt; ``mechanism`` is the declaration bound before execution.""" evidence = {} @@ -146,7 +82,7 @@ def result(status, reason, **fields): "verdict": "FAIL" if status == "candidate_failure" else "INCONCLUSIVE", "reason": reason, "evidence_files": evidence, **fields} - expected = steps(settings) + expected = project_steps(settings) actual = execution.get("steps", []) checks = execution.get("source_checks", []) if (not actual or len(actual) > len(expected) or len(checks) != len(actual) @@ -158,7 +94,7 @@ def result(status, reason, **fields): for definition, record in zip(expected, actual): if record.get("id") != definition["id"]: return result("infrastructure_failure", "failed_or_mismatched_execution") - checked = inspect_step(directory, settings, definition, record) + checked = inspect_project_step(directory, settings, definition, record) evidence.update(checked.get("evidence_files", {})) if checked["status"] != "completed": return result(checked["status"], checked["reason"], diff --git a/src/inferrsi/harness/executor/__init__.py b/src/inferrsi/harness/executor/__init__.py index 9517f7cc4..cecd18390 100644 --- a/src/inferrsi/harness/executor/__init__.py +++ b/src/inferrsi/harness/executor/__init__.py @@ -10,8 +10,11 @@ from inferrsi.contracts import json_v1 __all__ = [ - "LocalCpuTarget", "prepare_generation", "process_group_empty", "project_prepared_binding", - "read_prepared_binding", "request_digest", "runtime_environment", "verify_prepared_binding", + "PROJECT_DECISIONS", "LocalCpuTarget", "TaskProtocolError", "assess_packaged_task", + "benchmark_command", "execute_ordinary", "prepare_generation", "prepare_project", + "prepare_task_protocol", + "process_group_empty", "project_prepared_binding", "read_prepared_binding", "request_digest", + "run_task_protocol", "runtime_environment", "validate_project", "verify_prepared_binding", ] @@ -20,6 +23,19 @@ def __getattr__(name): from ._target import LocalCpuTarget return LocalCpuTarget + if name in ("PROJECT_DECISIONS", "prepare_project", "validate_project"): + from . import _project + + return getattr(_project, name) + if name in ("benchmark_command", "execute_ordinary"): + from . import _ordinary + + return getattr(_ordinary, name) + if name in ("TaskProtocolError", "assess_packaged_task", "prepare_task_protocol", + "run_task_protocol"): + from . import _task_protocol + + return getattr(_task_protocol, name) if name == "prepare_generation": from ._generation import prepare_generation diff --git a/src/inferrsi/harness/executor/_benchmark_child.py b/src/inferrsi/harness/executor/_benchmark_child.py new file mode 100644 index 000000000..972f5e189 --- /dev/null +++ b/src/inferrsi/harness/executor/_benchmark_child.py @@ -0,0 +1,42 @@ +"""Run the selected benchmark entry with the installed trial executor.""" + +import runpy +import sys +from functools import partial +from itertools import count +from pathlib import Path + + +def _nested_trial(execute_trial, directory, sequence, *args, **kwargs): + return execute_trial( + *args, launch_path=directory / f"launch-nested-{next(sequence):04d}.json", **kwargs + ) + + +def _run_entry(entry: str, arguments: list[str], *, launch_directory: Path | None = None) -> None: + # Direct-file launch avoids importing a caller's cwd/inferrsi.py. Once the + # bundled runner is selected, remove its directory so task imports cannot + # resolve generic names such as project or candidates from Harness. + runner = Path(__file__).resolve().parent + sys.path[:] = [path for path in sys.path if Path(path).resolve() != runner] + # Extended-path launches on Windows may leave cwd before PYTHONPATH. Select + # this runner's package root explicitly before importing its executor. + runtime_root = str(runner.parents[2]) + sys.path.insert(0, runtime_root) + try: + from inferrsi.harness.executor.trials.external import execute_trial + finally: + sys.path.remove(runtime_root) + + if launch_directory is not None: + execute_trial = partial(_nested_trial, execute_trial, launch_directory, count(1)) + sys.argv = [entry, *arguments] + sys.path.insert(0, str(Path(entry).parent)) + runpy.run_path(entry, run_name="__main__", init_globals={"execute_trial": execute_trial}) + + +if __name__ == "__main__": + if sys.argv[1] == "--session-launch-directory": + _run_entry(sys.argv[3], sys.argv[4:], launch_directory=Path(sys.argv[2])) + else: + _run_entry(sys.argv[1], sys.argv[2:]) diff --git a/src/inferrsi/harness/executor/_ordinary.py b/src/inferrsi/harness/executor/_ordinary.py new file mode 100644 index 000000000..52ea9db08 --- /dev/null +++ b/src/inferrsi/harness/executor/_ordinary.py @@ -0,0 +1,94 @@ +"""Execute ordinary projects and packaged benchmarks within the frozen attempt budget.""" + +import os +import sys +import time +from pathlib import Path + +from . import _benchmark_child + + +def benchmark_command(entry, arguments, *, python=None, prefix=(), launch_directory=None): + """Build argv for the installed child, including its optional launch-receipt directory.""" + command = [*prefix, sys.executable if python is None else python, + str(Path(_benchmark_child.__file__).resolve())] + if launch_directory is not None: + command.extend(("--session-launch-directory", str(launch_directory))) + return [*command, str(entry), *arguments] + + +def execute_ordinary(root, directory, plan, deadline): + from inferrsi.harness.executor import run_task_protocol + from inferrsi.harness.executor.trials.external import execute_trial + + if plan["task_source"] == "project": + return _project_execute(root, directory, plan, deadline) + task = root / "frozen" + arguments = run_task_protocol( + task, plan["frozen_files"]["optimization.py"], "arguments", + launch_directory=directory, candidate=directory / "candidate.py", + output=directory / "measurement", settings=plan["evaluation_settings"], + ) + execution = directory / "execution" + command = benchmark_command(task / "benchmark.py", arguments, python=plan["python"], + prefix=plan["evaluation_prefix"], launch_directory=execution) + timeout = min(plan["evaluation_timeout_seconds"], max(0, deadline - time.time())) + environment = dict(os.environ) + environment["PYTHONDONTWRITEBYTECODE"] = "1" + return execute_trial(command, root, execution, time.monotonic() + timeout, + None, environment=environment, launch_path=execution / "launch-task.json") + + +def _project_execute(root, directory, plan, deadline): + from inferrsi.harness.evaluator import inspect_project_step, project_steps + from inferrsi.harness.executor.candidates import identity, members, retain + from inferrsi.harness.executor.trials.external import execute_trial + from inferrsi.harness.records.atomic_json import atomic_write_json + + output = directory / "execution" + output.mkdir() + # Programs commonly write logs/caches into cwd. Execute disposable copies, + # keeping the frozen baseline and submitted candidate immutable. + workspace = output / "workspace" + workspace.mkdir() + baseline, candidate = workspace / "baseline", workspace / "candidate" + retain(root / plan["baseline_path"], baseline) + retain(directory / plan["candidate_name"], candidate) + declared = {"baseline": list(members(baseline)), "candidate": list(members(candidate))} + expected = {"baseline": identity(baseline), "candidate": identity(candidate)} + record = {"status": "completed", "returncode": 0, "steps": [], "source_checks": []} + started = time.monotonic() + end = started + min(plan["evaluation_timeout_seconds"], max(0, deadline - time.time())) + for step in project_steps(plan["evaluation_settings"]): + source = baseline if step["side"] == "baseline" else candidate + values = {"candidate": str(source), "baseline": str(baseline), + "protocol": str(root / "frozen/protocol"), "python": plan["python"]} + command = [] + for arg in step["argv"]: + for key, value in values.items(): + arg = arg.replace("{" + key + "}", value) + command.append(arg) + environment = dict(os.environ) + inherited = environment.get("PYTHONPATH") + environment["PYTHONPATH"] = ( + os.pathsep.join((str(source), inherited)) if inherited else str(source) + ) + environment["PYTHONDONTWRITEBYTECODE"] = "1" + execution = execute_trial((*plan["evaluation_prefix"], *command), source, + output / step["id"], end, None, environment=environment, + launch_path=output / f"launch-{step['id']}.json") + record["steps"].append({"id": step["id"], **execution}) + actual = {"baseline": identity(baseline, declared["baseline"]), + "candidate": identity(candidate, declared["candidate"])} + record["source_checks"].append({"step": step["id"], "expected": expected, + "actual": actual, "verified": actual == expected}) + if actual != expected or execution["status"] != "completed": + record["status"] = "failed" if actual != expected else execution["status"] + record["returncode"] = execution["returncode"] + break + decision = inspect_project_step(directory, plan["evaluation_settings"], step, execution) + if decision["status"] != "completed": + break # A frozen check explicitly rejected the candidate or the protocol failed. + record["elapsed_seconds"] = time.monotonic() - started + atomic_write_json(output / "execution.json", record) + return record diff --git a/src/inferrsi/harness/executor/_project.py b/src/inferrsi/harness/executor/_project.py new file mode 100644 index 000000000..b15f773bc --- /dev/null +++ b/src/inferrsi/harness/executor/_project.py @@ -0,0 +1,68 @@ +"""Freeze an ordinary project's commands, instructions and acceptance inputs.""" + +import math +import shutil +from pathlib import Path + +from inferrsi.harness.evaluator import MIN_PAIRS +from inferrsi.harness.records.artifact_primitives import sha256 + +PROJECT_DECISIONS = ("point", "paired") + + +def validate_project(settings: dict) -> None: + for key in ("measure_command", "quality_command"): + command = settings[key] + if not command or not all(isinstance(arg, str) and arg for arg in command): + raise ValueError(f"An explicit {key} argv is required") + if not any("{protocol}" in arg for arg in command): + raise ValueError(f"{key} must use a retained {{protocol}} script") + if not any("{result}" in arg for arg in command): + raise ValueError(f"{key} must write to the supplied {{result}} path") + for key in ("metric_key", "metric_unit", "quality_key", "scope"): + if not isinstance(settings[key], str) or not settings[key].strip(): + raise ValueError(f"An explicit {key} is required") + if settings["direction"] not in ("minimize", "maximize"): + raise ValueError("Metric direction must be explicit") + if type(settings["repetitions"]) is not int or settings["repetitions"] < 1: + raise ValueError("Positive repetitions required") + if type(settings["warmups"]) is not int or settings["warmups"] < 0: + raise ValueError("Nonnegative warmups required") + value = settings["min_improvement_pct"] + if type(value) not in (int, float) or not math.isfinite(value) or value < 0: + raise ValueError("An explicit finite nonnegative improvement gate is required") + if settings.get("decision", "point") not in PROJECT_DECISIONS: + raise ValueError("Decision must be point or paired") + if settings.get("decision") == "paired" and settings["repetitions"] < MIN_PAIRS: + raise ValueError(f"A paired decision needs at least {MIN_PAIRS} repetitions") + if type(settings.get("require_explanation", False)) is not bool: + raise ValueError("require_explanation must be a boolean") + if settings.get("require_explanation") and settings["repetitions"] < MIN_PAIRS: + # Fewer pairs give no interval for any expectation, so every round would be + # unverifiable and no candidate could ever be adopted. + raise ValueError(f"--require-explanation needs at least {MIN_PAIRS} repetitions") + + +def prepare_project(destination: Path, protocol: Path, instructions: Path, settings: dict) -> dict: + """Retain the caller's explicit acceptance inputs, without inventing criteria.""" + validate_project(settings) + if not protocol.is_dir() or protocol.is_symlink() or not instructions.is_file(): + raise ValueError("Existing protocol directory and task instructions are required") + if destination.resolve().is_relative_to(protocol.resolve()): + raise ValueError("Frozen output must be outside the protocol directory") + paths = [p for p in protocol.rglob("*") if p.is_file()] + if not paths or any(p.is_symlink() for p in protocol.rglob("*")): + raise ValueError("Protocol must contain regular retained files") + before = {p.relative_to(protocol).as_posix(): sha256(p) for p in paths} + destination.mkdir(parents=True) + shutil.copytree(protocol, destination / "protocol") + (destination / "TASK.md").write_bytes(instructions.read_bytes()) + after = {p.relative_to(protocol).as_posix(): sha256(p) + for p in protocol.rglob("*") if p.is_file()} + copied = {p.relative_to(destination / "protocol").as_posix(): sha256(p) + for p in (destination / "protocol").rglob("*") if p.is_file()} + if before != after or copied != before: + raise ValueError("Acceptance inputs changed during freeze") + return {"evaluation_settings": settings, + "frozen_files": {p.relative_to(destination).as_posix(): sha256(p) + for p in destination.rglob("*") if p.is_file()}} diff --git a/src/inferrsi/harness/task_protocol.py b/src/inferrsi/harness/executor/_task_protocol.py similarity index 91% rename from src/inferrsi/harness/task_protocol.py rename to src/inferrsi/harness/executor/_task_protocol.py index e523f5ae5..7687ed104 100644 --- a/src/inferrsi/harness/task_protocol.py +++ b/src/inferrsi/harness/executor/_task_protocol.py @@ -15,10 +15,9 @@ import time from pathlib import Path -from . import protocol_child -from .executor import local_process -from .executor.launch_records import LaunchRecord -from .records.artifact_primitives import sha256 +from ..records.artifact_primitives import sha256 +from . import local_process, protocol_child +from .launch_records import LaunchRecord # One protocol operation must finish within this time; the child and every process in # its group or Job are then stopped and the operation fails with kind "timeout". @@ -92,8 +91,10 @@ def _response_problem(response, operation: str) -> str | None: return None -def run(root: Path, protocol_sha256: str, operation: str, *, deadline=None, - launch_directory: Path | None = None, **arguments): +def run_task_protocol( + root: Path, protocol_sha256: str, operation: str, *, deadline=None, + launch_directory: Path | None = None, **arguments, +): """Run one operation of ``root/optimization.py`` whose bytes have ``protocol_sha256``. Path arguments must be absolute. The child's stderr tail is copied to this process's @@ -182,12 +183,13 @@ def run(root: Path, protocol_sha256: str, operation: str, *, deadline=None, raise TaskProtocolError(error["kind"], f"{error['type']}: {error['message']}") -def prepare(source: Path, destination: Path, arguments: list[str]) -> dict: +def prepare_task_protocol(source: Path, destination: Path, arguments: list[str]) -> dict: + """Validate task arguments and freeze the resources used by subsequent operations.""" path = source / "optimization.py" if not path.is_file(): raise ValueError("This task has no iterative evaluation protocol") digest = sha256(path) - settings = run(source, digest, "validate_arguments", arguments=arguments) + settings = run_task_protocol(source, digest, "validate_arguments", arguments=arguments) if any(path.is_symlink() for path in source.rglob("*")): raise ValueError("Task resources must be regular files") shutil.copytree(source, destination, ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) @@ -197,3 +199,12 @@ def prepare(source: Path, destination: Path, arguments: list[str]) -> dict: if frozen["optimization.py"] != digest: raise ValueError("The task protocol changed while its resources were frozen") return {"evaluation_settings": settings, "frozen_files": frozen} + + +def assess_packaged_task(root, directory, plan, execution): + """Invoke the assessor from the task resources originally supplied by Apps.""" + return run_task_protocol( + root / "frozen", plan["frozen_files"]["optimization.py"], "assess", + launch_directory=directory, directory=directory, + settings=plan["evaluation_settings"], execution=execution, + ) diff --git a/src/inferrsi/harness/protocol_child.py b/src/inferrsi/harness/executor/protocol_child.py similarity index 97% rename from src/inferrsi/harness/protocol_child.py rename to src/inferrsi/harness/executor/protocol_child.py index 7fc4b902b..08f73e957 100644 --- a/src/inferrsi/harness/protocol_child.py +++ b/src/inferrsi/harness/executor/protocol_child.py @@ -1,13 +1,13 @@ # Child entry for one operation of a frozen task protocol (#412 R3). # # Harness starts this file as ``python -I -B protocol_child.py REQUEST`` from -# ``task_protocol.run``; nothing executes protocol code in the Harness process. The file +# ``run_task_protocol``; nothing executes protocol code in the Harness process. The file # imports only the standard library, so the child never loads inferrsi. It reads the # protocol bytes once, checks them against the request's SHA-256, compiles exactly those # bytes and calls one protocol function. Descriptor 1 carries only the response envelope: # everything the protocol prints, from Python, native code or its own children, goes to # stderr. This is an interpreter and process boundary, not a filesystem or network sandbox. -# ``task_protocol`` imports this module only for the shared envelope contract below. +# The protocol supervisor imports this module only for the shared envelope contract below. import hashlib import json diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/optimization.py index c43387642..de222b3d3 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -10,13 +10,12 @@ from pathlib import Path from . import analyzer, attempt_recovery, indexer -from .executor import candidates +from .executor import TaskProtocolError, candidates from .records import knowledge_capture, service_io from .records.artifact_primitives import digest, file_lock, sha256 from .records.atomic_json import atomic_write_json, durable_write_json from .records.evidence import sanitized_text from .records.usage import normalize_usage, usage_totals -from .task_protocol import TaskProtocolError def _locked(root): diff --git a/src/inferrsi/harness/optimization_session.py b/src/inferrsi/harness/optimization_session.py index a1376c675..2052ab956 100644 --- a/src/inferrsi/harness/optimization_session.py +++ b/src/inferrsi/harness/optimization_session.py @@ -5,109 +5,12 @@ """ import json -import os -import runpy import shlex -import sys -import time from functools import partial from importlib.resources import files -from itertools import count from pathlib import Path -def _session_execute(root, directory, plan, deadline): - from inferrsi.harness.executor.trials.external import execute_trial - from inferrsi.harness.task_protocol import run as run_protocol - - if plan["task_source"] == "project": - return _project_execute(root, directory, plan, deadline) - task = root / "frozen" - arguments = run_protocol(task, plan["frozen_files"]["optimization.py"], "arguments", - launch_directory=directory, - candidate=directory / "candidate.py", - output=directory / "measurement", - settings=plan["evaluation_settings"]) - execution = directory / "execution" - command = (*plan["evaluation_prefix"], plan["python"], str(Path(__file__).resolve()), - "--session-launch-directory", str(execution), - str(task / "benchmark.py"), *arguments) - timeout = min(plan["evaluation_timeout_seconds"], max(0, deadline - time.time())) - environment = dict(os.environ) - environment["PYTHONDONTWRITEBYTECODE"] = "1" - return execute_trial(command, root, execution, time.monotonic() + timeout, - None, environment=environment, launch_path=execution / "launch-task.json") - - -def _session_assess(root, directory, plan, execution, mechanism=None): - from inferrsi.harness.task_protocol import run as run_protocol - - if plan["task_source"] == "project": - from inferrsi.harness.project import assess - - return assess(directory, plan["evaluation_settings"], execution, mechanism=mechanism) - return run_protocol(root / "frozen", plan["frozen_files"]["optimization.py"], "assess", - launch_directory=directory, directory=directory, - settings=plan["evaluation_settings"], - execution=execution) - - -def _project_execute(root, directory, plan, deadline): - from inferrsi.harness.executor.candidates import identity, members, retain - from inferrsi.harness.executor.trials.external import execute_trial - from inferrsi.harness.project import inspect_step, steps - from inferrsi.harness.records.atomic_json import atomic_write_json - - output = directory / "execution" - output.mkdir() - # Programs commonly write logs/caches into cwd. Execute disposable copies, - # keeping the frozen baseline and submitted candidate immutable. - workspace = output / "workspace" - workspace.mkdir() - baseline, candidate = workspace / "baseline", workspace / "candidate" - retain(root / plan["baseline_path"], baseline) - retain(directory / plan["candidate_name"], candidate) - declared = {"baseline": list(members(baseline)), "candidate": list(members(candidate))} - expected = {"baseline": identity(baseline), "candidate": identity(candidate)} - record = {"status": "completed", "returncode": 0, "steps": [], "source_checks": []} - started = time.monotonic() - end = started + min(plan["evaluation_timeout_seconds"], max(0, deadline - time.time())) - for step in steps(plan["evaluation_settings"]): - source = baseline if step["side"] == "baseline" else candidate - values = {"candidate": str(source), "baseline": str(baseline), - "protocol": str(root / "frozen/protocol"), "python": plan["python"]} - command = [] - for arg in step["argv"]: - for key, value in values.items(): - arg = arg.replace("{" + key + "}", value) - command.append(arg) - environment = dict(os.environ) - inherited = environment.get("PYTHONPATH") - environment["PYTHONPATH"] = ( - os.pathsep.join((str(source), inherited)) if inherited else str(source) - ) - environment["PYTHONDONTWRITEBYTECODE"] = "1" - execution = execute_trial((*plan["evaluation_prefix"], *command), source, - output / step["id"], end, None, environment=environment, - launch_path=output / f"launch-{step['id']}.json") - record["steps"].append({"id": step["id"], **execution}) - actual = {"baseline": identity(baseline, declared["baseline"]), - "candidate": identity(candidate, declared["candidate"])} - record["source_checks"].append({"step": step["id"], "expected": expected, - "actual": actual, "verified": actual == expected}) - if actual != expected or execution["status"] != "completed": - record["status"] = "failed" if actual != expected else execution["status"] - record["returncode"] = execution["returncode"] - break - if inspect_step(directory, plan["evaluation_settings"], step, execution)["status"] != ( - "completed" - ): - break # A frozen check explicitly rejected the candidate or the protocol failed. - record["elapsed_seconds"] = time.monotonic() - started - atomic_write_json(output / "execution.json", record) - return record - - def _runtime_identity(): from inferrsi.harness.records.artifact_primitives import sha256 from inferrsi.harness.session_runtime import source_files @@ -116,21 +19,21 @@ def _runtime_identity(): return {name: sha256(root / name) for name in source_files(root)} -def session_command(args, *, ranking_policy_for, task_source: Path | None = None, +def session_command(args, *, ranking_policy_for, assess_packaged, task_source: Path | None = None, knowledge_reader=None, prepare_context=None, external_knowledge=None, external_provider=None, external_project=None, external_provider_for=None, report_metadata=None) -> dict: """Run one operation; discovery and knowledge access are supplied by the caller.""" - from inferrsi.harness import indexer, optimization + from inferrsi.harness import evaluator, executor, indexer, optimization root = args.session.resolve() if args.session_action == "start": import math + from inferrsi.harness.executor import prepare_task_protocol from inferrsi.harness.executor.candidates import identity, retain from inferrsi.harness.records.artifact_primitives import sha256 - from inferrsi.harness.task_protocol import prepare if args.rounds < 1 or any(not math.isfinite(value) or value <= 0 for value in ( args.max_minutes, args.evaluation_timeout_seconds @@ -213,7 +116,7 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None raise ValueError( "AB/BA requires its existing metric, quality, command and sampling options" ) - from inferrsi.harness.project import prepare as prepare_project + from inferrsi.harness.executor import prepare_project repo = args.repo.resolve() if not repo.is_dir() or root.is_relative_to(repo): @@ -244,7 +147,9 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None else: if task_source is None: raise ValueError("A resolved task resource directory is required to start") - settings = prepare(task_source, root / "frozen", shlex.split(args.evaluation_args)) + settings = prepare_task_protocol( + task_source, root / "frozen", shlex.split(args.evaluation_args) + ) (root / "work").mkdir() (root / "work/candidate.py").write_bytes((root / "frozen/baseline.py").read_bytes()) candidate = {"task": args.task, "task_source": "benchmark", "candidate_kind": "file", @@ -358,16 +263,17 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None root, external_provider, search_ref=args.search_ref, locator=args.locator, page=args.page, external_provider_for=external_provider_for, ) + assess = partial(evaluator.assess_ordinary, assess_packaged=assess_packaged) if args.session_action == "recover": return optimization.recover( - root, _session_assess, confirm_domain_empty=getattr(args, "confirm_domain_empty", False) + root, assess, confirm_domain_empty=getattr(args, "confirm_domain_empty", False) ) final = args.session_action == "final" mechanism = None if not final and getattr(args, "mechanism_file", None) is not None: if plan.get("task_source") != "project": raise ValueError("Mechanism checks apply to project campaign rounds only") - from inferrsi.harness.measurement import CONFIDENCE, min_pairs, validate_mechanism + from inferrsi.harness.evaluator import CONFIDENCE, min_pairs, validate_mechanism mechanism = validate_mechanism( json.loads(Path(args.mechanism_file).read_text(encoding="utf-8"))) @@ -382,7 +288,7 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None return optimization.evaluate_round( root, candidate=None if final else args.candidate, hypothesis="Independent final of the selected candidate" if final else args.hypothesis, - usage=args.usage_export, execute=_session_execute, assess=_session_assess, final=final, + usage=args.usage_export, execute=executor.execute_ordinary, assess=assess, final=final, reason=getattr(args, "reason", None), strategy=getattr(args, "strategy", None), alternatives=getattr(args, "alternative", None), @@ -390,38 +296,3 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None knowledge_refs=getattr(args, "knowledge_ref", None), mechanism=mechanism, ) - - -def _nested_trial(execute_trial, directory, sequence, *args, **kwargs): - return execute_trial( - *args, launch_path=directory / f"launch-nested-{next(sequence):04d}.json", **kwargs - ) - - -def _run_entry(entry: str, arguments: list[str], *, launch_directory: Path | None = None) -> None: - # Direct-file launch avoids importing a caller's cwd/inferrsi.py. Once the - # bundled runner is selected, remove its directory so task imports cannot - # resolve generic names such as project or candidates from Harness. - runner = Path(__file__).resolve().parent - sys.path[:] = [path for path in sys.path if Path(path).resolve() != runner] - # Extended-path launches on Windows may leave cwd before PYTHONPATH. Select - # this runner's package root explicitly before importing its executor. - runtime_root = str(runner.parent.parent) - sys.path.insert(0, runtime_root) - try: - from inferrsi.harness.executor.trials.external import execute_trial - finally: - sys.path.remove(runtime_root) - - if launch_directory is not None: - execute_trial = partial(_nested_trial, execute_trial, launch_directory, count(1)) - sys.argv = [entry, *arguments] - sys.path.insert(0, str(Path(entry).parent)) - runpy.run_path(entry, run_name="__main__", init_globals={"execute_trial": execute_trial}) - - -if __name__ == "__main__": - if sys.argv[1] == "--session-launch-directory": - _run_entry(sys.argv[3], sys.argv[4:], launch_directory=Path(sys.argv[2])) - else: - _run_entry(sys.argv[1], sys.argv[2:]) diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index c9f9b4def..725b1b570 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -14,7 +14,7 @@ from inferrsi.apps.cli import main from inferrsi.benchmark import registry -from inferrsi.harness import optimization, optimization_session +from inferrsi.harness import evaluator, executor, optimization, optimization_session from inferrsi.harness.optimization import _locked from tests.fixtures.diagnosis import diagnosis_args from tests.fixtures.session_process import kill_controller, target_python @@ -106,7 +106,7 @@ def unavailable(*args): def test_packaged_round_uses_target_dependencies(task, tmp_path, capsys, monkeypatch): - python = target_python(tmp_path, monkeypatch, optimization_session) + python = target_python(tmp_path, monkeypatch) benchmark = task / "benchmark.py" benchmark.write_text( "from session_target_dependency import VALUE\nassert VALUE == 2\n" @@ -289,7 +289,7 @@ def test_interrupted_execution_cannot_resume_using_a_written_candidate_rejection session, capsys, monkeypatch, status, code, ): best = submit(session, 2, capsys)["best"] - original = optimization_session._session_execute + original = executor.execute_ordinary def interrupted(*args): record = original(*args) @@ -297,7 +297,7 @@ def interrupted(*args): (args[1] / "execution/execution.json").write_text(json.dumps(record), encoding="utf-8") return record - monkeypatch.setattr(optimization_session, "_session_execute", interrupted) + monkeypatch.setattr(executor, "execute_ordinary", interrupted) candidate = session / "work/candidate.py" candidate.write_text("FACTOR = -1\n", encoding="utf-8") assert main(["benchmarks", "session", "round", "--session", str(session), @@ -381,13 +381,13 @@ def test_os_lock_prevents_concurrent_submissions(session, capsys): def test_recovery_collects_completed_execution_without_running_candidate_twice( session, monkeypatch, capsys, ): - original = optimization_session._session_execute + original = executor.execute_ordinary def crash_after_execution(*args): original(*args) raise KeyboardInterrupt("coordinator interrupted after child completion") - monkeypatch.setattr(optimization_session, "_session_execute", crash_after_execution) + monkeypatch.setattr(executor, "execute_ordinary", crash_after_execution) with pytest.raises(KeyboardInterrupt): submit(session, 2, capsys) with pytest.raises(SystemExit): @@ -486,7 +486,7 @@ def stop_during_second_step(root, attempt, plan, deadline): raise KeyboardInterrupt with monkeypatch.context() as patch: - patch.setattr(optimization_session, "_session_execute", stop_during_second_step) + patch.setattr(executor, "execute_ordinary", stop_during_second_step) with pytest.raises(KeyboardInterrupt): submit(session, 9, capsys) command = ["benchmarks", "session"] @@ -552,20 +552,20 @@ def test_recover_never_spawns_a_second_assessor_with_a_receipt( ): from inferrsi.harness.executor import launch_records - execute = optimization_session._session_execute + execute = executor.execute_ordinary calls = session / "assessor-calls.log" def stop_after_execution(*args): execute(*args) raise KeyboardInterrupt - def stop_after_assessor_spawn(root, attempt, plan, execution): + def stop_after_assessor_spawn(root, attempt, plan, execution, *, assess_packaged): launch_records.LaunchRecord.numbered(attempt, "protocol-assess", ["assess"]) held_child(calls) raise KeyboardInterrupt with monkeypatch.context() as patch: - patch.setattr(optimization_session, "_session_execute", stop_after_execution) + patch.setattr(executor, "execute_ordinary", stop_after_execution) with pytest.raises(KeyboardInterrupt): submit(session, 2, capsys) pending = json.loads((session / "state.json").read_bytes())["pending"] @@ -573,7 +573,7 @@ def stop_after_assessor_spawn(root, attempt, plan, execution): receipt = attempt / "execution/execution.json" before = receipt.read_bytes() command = ["benchmarks", "session", "recover", "--session", str(session)] - monkeypatch.setattr(optimization_session, "_session_assess", stop_after_assessor_spawn) + monkeypatch.setattr(evaluator, "assess_ordinary", stop_after_assessor_spawn) with pytest.raises(KeyboardInterrupt): main(command) launch = attempt / "protocol-assess-0001.json" @@ -604,7 +604,7 @@ def stop(*args): command = ["benchmarks", "session"] target = ["--session", str(session)] with monkeypatch.context() as patch: - patch.setattr(optimization_session, "_session_execute", stop) + patch.setattr(executor, "execute_ordinary", stop) with pytest.raises(KeyboardInterrupt): main([*command, "final", *target]) assert main([*command, "recover", *target]) == 2 @@ -639,18 +639,18 @@ def stop(*args): def test_frozen_drift_settles_a_pending_attempt( session, monkeypatch, capsys, operation, has_receipt, ): - execute = optimization_session._session_execute + execute = executor.execute_ordinary def stop(*args): if has_receipt: execute(*args) raise KeyboardInterrupt - def should_not_assess(*args): + def should_not_assess(*args, **kwargs): pytest.fail("Frozen drift cannot start an assessment") - monkeypatch.setattr(optimization_session, "_session_execute", stop) - monkeypatch.setattr(optimization_session, "_session_assess", should_not_assess) + monkeypatch.setattr(executor, "execute_ordinary", stop) + monkeypatch.setattr(evaluator, "assess_ordinary", should_not_assess) with pytest.raises(KeyboardInterrupt): submit(session, 2, capsys) (session / "frozen/TASK.md").write_text("Changed task\n", encoding="utf-8") @@ -673,7 +673,7 @@ def test_frozen_drift_retains_unconfirmed_launch( ): from inferrsi.harness.executor.launch_records import LaunchRecord - def stop_during_assessment(root, attempt, plan, execution): + def stop_during_assessment(root, attempt, plan, execution, *, assess_packaged): LaunchRecord.numbered(attempt, "protocol-assess", ["assess"]) raise KeyboardInterrupt @@ -681,11 +681,11 @@ def unexpected_restart(*args, **kwargs): pytest.fail("Invalid frozen inputs cannot start an execution or assessment") with monkeypatch.context() as patch: - patch.setattr(optimization_session, "_session_assess", stop_during_assessment) + patch.setattr(evaluator, "assess_ordinary", stop_during_assessment) with pytest.raises(KeyboardInterrupt): submit(session, 2, capsys) - monkeypatch.setattr(optimization_session, "_session_execute", unexpected_restart) - monkeypatch.setattr(optimization_session, "_session_assess", unexpected_restart) + monkeypatch.setattr(executor, "execute_ordinary", unexpected_restart) + monkeypatch.setattr(evaluator, "assess_ordinary", unexpected_restart) state_path = session / "state.json" pending = json.loads(state_path.read_bytes())["pending"] @@ -768,6 +768,7 @@ def test_reserve_status_agrees_with_final_eligibility(task, tmp_path, capsys, mo args.round_mode = mode optimization_session.session_command( args, ranking_policy_for=managed_ranking_policy, task_source=task, + assess_packaged=executor.assess_packaged_task, ) diagnose(root, capsys) for index in range(rounds): @@ -789,7 +790,7 @@ def test_executor_exception_without_receipt_blocks_without_claiming_cleanup( def unavailable(*args): raise OSError("executor unavailable") - monkeypatch.setattr(optimization_session, "_session_execute", unavailable) + monkeypatch.setattr(executor, "execute_ordinary", unavailable) code = main(["benchmarks", "session", "round", "--session", str(session), "--candidate", str(session / "work/candidate.py"), "--hypothesis", "probe"]) view = json.loads(capsys.readouterr().out) @@ -800,23 +801,23 @@ def unavailable(*args): def test_executor_exception_after_receipt_collects_without_relaunch(session, monkeypatch, capsys): - original = optimization_session._session_execute + original = executor.execute_ordinary def failed_after_execution(*args): original(*args) raise OSError("coordinator failed after child completion") - monkeypatch.setattr(optimization_session, "_session_execute", failed_after_execution) + monkeypatch.setattr(executor, "execute_ordinary", failed_after_execution) view = submit(session, 2, capsys) assert view["pending"] is None and view["best"]["score"] == 2 assert (session / "calls.log").read_text().splitlines() == ["2"] def test_assessor_exception_preserves_type_and_settles_failed_attempt(session, monkeypatch, capsys): - def broken_assessor(*args): + def broken_assessor(*args, **kwargs): raise TypeError("invalid task assessment") - monkeypatch.setattr(optimization_session, "_session_assess", broken_assessor) + monkeypatch.setattr(evaluator, "assess_ordinary", broken_assessor) candidate = session / "work/candidate.py" candidate.write_text("FACTOR = 2\n", encoding="utf-8") assert main(["benchmarks", "session", "round", "--session", str(session), @@ -1005,7 +1006,7 @@ def test_legacy_retrieval_is_linked_only_by_matching_submission_snapshots(sessio def test_round_declarations_follow_the_candidate_through_assessment(session, capsys, monkeypatch): from inferrsi.apps.views.dashboard import dashboard_snapshot - execute = optimization_session._session_execute + execute = executor.execute_ordinary expected = {"hypothesis": "Reuse the table", "strategy": "Share across layers", "alternatives": ["Cache across requests", "Precompute at [redacted-path]"], "selection_reason": "Layers use the same positions"} @@ -1015,7 +1016,7 @@ def observe_pending(root, directory, plan, deadline): assert pending["managed_submission"] == expected return execute(root, directory, plan, deadline) - monkeypatch.setattr(optimization_session, "_session_execute", observe_pending) + monkeypatch.setattr(executor, "execute_ordinary", observe_pending) candidate = session / "work/candidate.py" candidate.write_text("FACTOR = 2\n", encoding="utf-8") args = ["benchmarks", "session", "round", "--session", str(session), @@ -1236,7 +1237,7 @@ def read(ref, *, expected_revision, expected_sha256, page, timeout, root, expect with pytest.raises(SystemExit): main([*round_args, "--knowledge-ref", local_path + "#unknown"]) assert "delivered resources" in capsys.readouterr().err - execute = optimization_session._session_execute + execute = executor.execute_ordinary def observe_pending(root, directory, plan, deadline): pending_view = dashboard_snapshot(root)["data"] @@ -1246,7 +1247,7 @@ def observe_pending(root, directory, plan, deadline): assert [use["ref"] for use in current["knowledge_uses"]] == [locator, local_item] return execute(root, directory, plan, deadline) - monkeypatch.setattr(optimization_session, "_session_execute", observe_pending) + monkeypatch.setattr(executor, "execute_ordinary", observe_pending) assert main([*round_args, "--knowledge-ref", receipt_path, "--knowledge-ref", local_path + "#" + local_item]) == 0 capsys.readouterr() @@ -1255,7 +1256,7 @@ def observe_pending(root, directory, plan, deadline): assert "from the current round" in capsys.readouterr().err capsys.readouterr() - monkeypatch.setattr(optimization_session, "_session_execute", execute) + monkeypatch.setattr(executor, "execute_ordinary", execute) phase["items"] = [uncited] assert main(query_args) == 0 later_search = json.loads(capsys.readouterr().out)["external"]["reference"]["path"] @@ -1433,7 +1434,16 @@ def test_runtime_identity_covers_migrated_process_domain_and_not_removed_executo # #412 R2: the Harness-owned primitives replace infra.artifacts in six modules. assert "harness/records/artifact_primitives.py" in identity # #412 R3: the protocol child entry runs every task protocol operation. - assert "harness/protocol_child.py" in identity + assert "harness/executor/_task_protocol.py" in identity + assert "harness/task_protocol.py" not in identity + assert "harness/executor/protocol_child.py" in identity + assert "harness/protocol_child.py" not in identity + assert { + "harness/executor/_ordinary.py", "harness/executor/_project.py", + "harness/executor/_benchmark_child.py", "harness/evaluator/__init__.py", + "harness/evaluator/_project.py", "harness/evaluator/_measurement.py", + } <= identity.keys() + assert {"harness/project.py", "harness/measurement.py"}.isdisjoint(identity) assert "apps/workflows/campaign.py" in identity assert "knowledge/knowledge_find.py" in identity assert "knowledge/ranking_policy.py" in identity @@ -1701,7 +1711,7 @@ def scoreless(*args, **kwargs): return {"status": "completed", "verdict": "INCONCLUSIVE", "reason": "synthetic_missing_score", "eligible": False} - monkeypatch.setattr(optimization_session, "_session_assess", scoreless) + monkeypatch.setattr(evaluator, "assess_ordinary", scoreless) candidate = session / "work/candidate.py" candidate.write_text("FACTOR = 2\n", encoding="utf-8") assert main(["benchmarks", "session", "round", "--session", str(session), diff --git a/tests/apps/test_project_explanation.py b/tests/apps/test_project_explanation.py index aba926adb..1a8621f67 100644 --- a/tests/apps/test_project_explanation.py +++ b/tests/apps/test_project_explanation.py @@ -487,9 +487,9 @@ def test_rewriting_the_bound_declaration_is_detected(project, capsys, target): def test_recovered_attempt_does_not_trust_a_rewritable_declaration(project, capsys, monkeypatch): """After an interruption the bound declaration is unprovable, so it is not adopted.""" - from inferrsi.harness import optimization_session + from inferrsi.harness import executor - original = optimization_session._session_execute + original = executor.execute_ordinary def forge_then_crash(root, directory, plan, deadline): original(root, directory, plan, deadline) @@ -502,12 +502,12 @@ def forge_then_crash(root, directory, plan, deadline): raise KeyboardInterrupt("coordinator interrupted after the candidate ran") assert start(project, capsys, "--require-explanation") == 0 - monkeypatch.setattr(optimization_session, "_session_execute", forge_then_crash) + monkeypatch.setattr(executor, "execute_ordinary", forge_then_crash) wrong = {"mechanism": "Claims the norm got slower", "expect": [ {"region": "norm", "direction": "increase"}]} with pytest.raises(KeyboardInterrupt): submit(project, capsys, FUSED, wrong) - monkeypatch.setattr(optimization_session, "_session_execute", original) + monkeypatch.setattr(executor, "execute_ordinary", original) assert main(["campaign", "recover", "--directory", str(project[3])]) == 0 capsys.readouterr() _, state, _ = read_records(project[3]) @@ -520,7 +520,7 @@ def forge_then_crash(root, directory, plan, deadline): def test_failing_profile_report_does_not_change_the_default_verdict(project, capsys, monkeypatch): """Profile evidence is report-only by default; its failure must not block or flip it.""" - from inferrsi.harness import project as project_protocol + from inferrsi.harness.evaluator import _project as project_protocol def explode(*args, **kwargs): raise OverflowError("synthetic report failure") @@ -558,10 +558,10 @@ def test_overflowing_even_medians_leave_a_recorded_inconclusive_round(project, c def test_point_decision_project_rounds_must_still_be_scored(project, capsys, monkeypatch): """The scoreless exception belongs to the frozen paired decision, not to projects.""" - from inferrsi.harness import optimization_session + from inferrsi.harness import evaluator assert start(project, capsys) == 0 - monkeypatch.setattr(optimization_session, "_session_assess", lambda *args, **kwargs: { + monkeypatch.setattr(evaluator, "assess_ordinary", lambda *args, **kwargs: { "status": "completed", "verdict": "INCONCLUSIVE", "reason": "synthetic", "eligible": False, "baseline_score": 10.0}) # only the score is missing repo, _, _, root = project diff --git a/tests/apps/test_project_optimization.py b/tests/apps/test_project_optimization.py index d6fe65c3c..45fa3771b 100644 --- a/tests/apps/test_project_optimization.py +++ b/tests/apps/test_project_optimization.py @@ -10,7 +10,6 @@ from inferrsi.apps.cli import main from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard -from inferrsi.harness import optimization_session from inferrsi.harness.optimization import read_records from tests.fixtures.diagnosis import diagnosis_args from tests.fixtures.session_process import kill_controller, target_python @@ -77,7 +76,7 @@ def submit(project, capsys, metric): def test_ab_ba_round_uses_target_dependencies(project, tmp_path, capsys, monkeypatch): - python = target_python(tmp_path, monkeypatch, optimization_session) + python = target_python(tmp_path, monkeypatch) for name in ("measure.py", "quality.py"): path = project[1] / name path.write_text( @@ -592,10 +591,10 @@ def test_project_execution_copy_source_changes_are_rejected(project, capsys): {"status": "unexpected"}, None, ]) def test_malformed_assessment_settles_as_blocked(project, capsys, monkeypatch, assessment): - from inferrsi.harness import optimization_session + from inferrsi.harness import evaluator start(project, capsys) - monkeypatch.setattr(optimization_session, "_session_assess", lambda *args: assessment) + monkeypatch.setattr(evaluator, "assess_ordinary", lambda *args, **kwargs: assessment) code, view = submit(project, capsys, 20) assert code == 2 and view["state"] == "blocked" and view["pending"] is None assert view["best"]["kind"] == "baseline" @@ -603,17 +602,17 @@ def test_malformed_assessment_settles_as_blocked(project, capsys, monkeypatch, a def test_post_execution_drift_retains_readable_rejection(project, capsys, monkeypatch): - from inferrsi.harness import optimization_session + from inferrsi.harness import executor start(project, capsys) - original = optimization_session._session_execute + original = executor.execute_ordinary def drift(root, *args): result = original(root, *args) (root / "frozen/protocol/unexpected.py").write_text("drift") return result - monkeypatch.setattr(optimization_session, "_session_execute", drift) + monkeypatch.setattr(executor, "execute_ordinary", drift) code, view = submit(project, capsys, 20) assert code == 2 and view["state"] == "blocked" and view["pending"] is None assert "file set" in view["integrity_error"] and view["summary"] is None @@ -726,16 +725,16 @@ def test_unreachable_gate_keeps_the_original_fail_and_strict_json_records(projec def test_records_without_paired_statistics_remain_readable(project, capsys, monkeypatch): """Assessments retained before this field existed still load in records and dashboard.""" - from inferrsi.harness import project as project_protocol + from inferrsi.harness import evaluator - original = project_protocol.assess + original = evaluator.assess_project def legacy_assess(*args, **kwargs): result = original(*args, **kwargs) result.pop("paired_statistics", None) return result - monkeypatch.setattr(project_protocol, "assess", legacy_assess) + monkeypatch.setattr(evaluator, "assess_project", legacy_assess) start(project, capsys) code, result = submit(project, capsys, 20) assert code == 0 and "paired_statistics" not in result["latest_observation"]["assessment"] diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 09b541b8f..515c16266 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -1057,11 +1057,11 @@ def test_exact_round_policy_and_legacy_argument_validation(campaign): result = call(campaign, "final", "--reason", "Incomplete exact budget") assert result["final"]["assessment"]["reason"] == "incomplete_round_policy" assert result["state"] == "active" - from inferrsi.harness.project import steps + from inferrsi.harness.evaluator import project_steps assert [ step["side"] - for step in steps( + for step in project_steps( { "quality_command": ["quality"], "measure_command": ["measure"], diff --git a/tests/apps/test_search_benchmarks.py b/tests/apps/test_search_benchmarks.py index e8a811582..11d2e2557 100644 --- a/tests/apps/test_search_benchmarks.py +++ b/tests/apps/test_search_benchmarks.py @@ -13,7 +13,7 @@ from inferrsi.apps.workflows.search_roles import Snapshot from inferrsi.apps.workflows.speculative_search import command from inferrsi.benchmark.improvement import SelectionPolicy -from inferrsi.harness.executor import candidates +from inferrsi.harness.executor import TaskProtocolError, candidates from inferrsi.harness.executor.trials.external import execute_trial from inferrsi.harness.manager import EngineSearchPlan, read_engine_search, run_engine_search from inferrsi.harness.manager.search.search_adapter import ArtifactAdapter, Edit @@ -28,7 +28,6 @@ from inferrsi.harness.manager.search.work_control import WorkControl from inferrsi.harness.records import RunStore from inferrsi.harness.records.artifact_primitives import digest -from inferrsi.harness.task_protocol import TaskProtocolError from tests.fixtures.speculative_search import contract @@ -271,7 +270,7 @@ def execute(command, cwd, output, deadline, *args, **kwargs): clock[0] += 3 return {"status": "completed", "returncode": 0, "cleanup_verified": True} - monkeypatch.setattr("inferrsi.apps.workflows.search_benchmarks.task_protocol.run", protocol) + monkeypatch.setattr("inferrsi.apps.workflows.search_benchmarks.run_task_protocol", protocol) monkeypatch.setattr("inferrsi.apps.workflows.search_benchmarks.execute_trial", execute) evaluator.evaluate(source, "evaluation", tmp_path / "output", 110.0) assert observed == [("arguments", 1110.0, 10.0), ("execution", 1110.0, 8.0), @@ -346,7 +345,7 @@ def execute(command, cwd, output, *args, **kwargs): (output / "execution.json").write_text("{}") return {"status": "completed", "returncode": 0, "cleanup_verified": task_cleanup} - monkeypatch.setattr("inferrsi.apps.workflows.search_benchmarks.task_protocol.run", protocol) + monkeypatch.setattr("inferrsi.apps.workflows.search_benchmarks.run_task_protocol", protocol) monkeypatch.setattr("inferrsi.apps.workflows.search_benchmarks.execute_trial", execute) result = evaluator.evaluate(source, "evaluation", tmp_path / "output", time.time() + 10) assert result["verdict"] == "INCONCLUSIVE" and result["objective"] is None diff --git a/tests/apps/test_session_ranking_policy.py b/tests/apps/test_session_ranking_policy.py index 193aea95a..e40a05d71 100644 --- a/tests/apps/test_session_ranking_policy.py +++ b/tests/apps/test_session_ranking_policy.py @@ -9,7 +9,7 @@ from inferrsi.apps import cli from inferrsi.apps.cli import main -from inferrsi.harness import optimization, task_protocol +from inferrsi.harness import executor, optimization from inferrsi.harness.records import service_io from inferrsi.knowledge import ranking_policy from inferrsi.knowledge.knowledge_operations import KnowledgeReader @@ -350,7 +350,7 @@ def refused_without_writes(): def test_packaged_assessor_receives_identical_evidence_across_policies(task, tmp_path, capsys, monkeypatch): calls = [] - real_run = task_protocol.run + real_run = executor.run_task_protocol def observe(frozen, source_hash, operation, *, launch_directory=None, **inputs): if operation == "assess": @@ -361,7 +361,7 @@ def observe(frozen, source_hash, operation, *, launch_directory=None, **inputs): read(directory / "measurement/result.json"))) return real_run(frozen, source_hash, operation, launch_directory=launch_directory, **inputs) - monkeypatch.setattr(task_protocol, "run", observe) + monkeypatch.setattr(executor, "run_task_protocol", observe) outcomes = [] for name in ("default", "applicability"): root = tmp_path / name diff --git a/tests/benchmark/test_benchmark_compare.py b/tests/benchmark/test_benchmark_compare.py index 7d98552ac..a310a665d 100644 --- a/tests/benchmark/test_benchmark_compare.py +++ b/tests/benchmark/test_benchmark_compare.py @@ -193,7 +193,7 @@ def deliver_required_cards(): def test_compare_keeps_interrupted_round_in_the_trace(experiment, monkeypatch): - from inferrsi.harness import optimization_session + from inferrsi.harness import executor _, initial, capsys = experiment @@ -202,7 +202,7 @@ def interrupted(*args): def round_submit(args): with monkeypatch.context() as patch: - patch.setattr(optimization_session, "_session_execute", interrupted) + patch.setattr(executor, "execute_ordinary", interrupted) with pytest.raises(KeyboardInterrupt): main(args) recover = ["benchmarks", "session", "recover", *args[3:5]] diff --git a/tests/benchmark/test_benchmark_operations.py b/tests/benchmark/test_benchmark_operations.py index e7bc287d0..d5006afa8 100644 --- a/tests/benchmark/test_benchmark_operations.py +++ b/tests/benchmark/test_benchmark_operations.py @@ -11,7 +11,7 @@ from inferrsi.apps.cli import main from inferrsi.apps.workflows import benchmark_operations from inferrsi.benchmark import registry -from inferrsi.harness import optimization_session +from inferrsi.harness.executor import _benchmark_child PACKAGED_WORKLOADS = { "moe-forward-npu": "moe-shared-ep2-npu-v1", @@ -121,7 +121,7 @@ def test_application_injects_executor_and_preserves_script_imports(library): @pytest.mark.parametrize("startup_shadow", ["cwd", "other-runtime"]) def test_direct_task_child_uses_the_selected_runtime_before_host_imports(tmp_path, startup_shadow): - runner = Path(benchmark_operations.optimization_session.__file__).resolve() + runner = Path(_benchmark_child.__file__).resolve() shadow = tmp_path / "other-runtime" shadow.mkdir() (shadow / "inferrsi.py").write_text("raise RuntimeError('wrong inherited runtime')\n") @@ -151,7 +151,7 @@ def test_direct_task_child_uses_the_selected_runtime_before_host_imports(tmp_pat result = subprocess.run( [sys.executable, "-I", "-S", "-c", bootstrap, str(runner), str(entry), "" if startup_shadow == "cwd" else str(shadow), - str(runner.parent / "executor/trials/external.py")], + str(runner.parent / "trials/external.py")], cwd=tmp_path, capture_output=True, text=True, encoding="utf-8", timeout=30, ) assert result.returncode == 0, result.stderr @@ -208,6 +208,7 @@ def test_discovery_does_not_import_device_libraries(): script = """ import sys from inferrsi.apps.cli import main +from inferrsi.apps.workflows import benchmark_operations from inferrsi.benchmark.registry import builtin_tasks, describe_task for name in builtin_tasks(): describe_task(name) @@ -241,7 +242,7 @@ def test_generic_launcher_preserves_task_arguments_and_status(name, exit_code, m def call(command, *, env): assert command == [ - sys.executable, str(Path(optimization_session.__file__).resolve()), + sys.executable, str(Path(_benchmark_child.__file__).resolve()), str(registry.task_resources(name).joinpath("benchmark.py")), *arguments ] package = Path(env["PYTHONPATH"].split(os.pathsep)[0]) / "inferrsi" diff --git a/tests/campaigns/test_qwen_gvo_diagnostic.py b/tests/campaigns/test_qwen_gvo_diagnostic.py index e726abf87..c5e8e62cb 100644 --- a/tests/campaigns/test_qwen_gvo_diagnostic.py +++ b/tests/campaigns/test_qwen_gvo_diagnostic.py @@ -83,7 +83,7 @@ def test_protocol_identity_checked_before_loading(tmp_path, monkeypatch): def unexpected_load(*args, **kwargs): pytest.fail("the checker loaded the corrupted protocol") - monkeypatch.setattr(checker.task_protocol, "run", unexpected_load) + monkeypatch.setattr(checker, "run_task_protocol", unexpected_load) (task / "optimization.py").write_text("this is deliberately invalid Python source.") with pytest.raises(ValueError, match=r"^optimization\.py$"): checker.main(tmp_path / "trial", tmp_path / "failed") diff --git a/tests/fixtures/session_process.py b/tests/fixtures/session_process.py index adab54e53..6dd21d02e 100644 --- a/tests/fixtures/session_process.py +++ b/tests/fixtures/session_process.py @@ -8,8 +8,10 @@ from pathlib import Path -def target_python(tmp_path, monkeypatch, runtime): +def target_python(tmp_path, monkeypatch): """Model a coordinator whose site-packages shadow a target-only dependency.""" + from inferrsi.harness import executor + environment = tmp_path / "target" venv.EnvBuilder(with_pip=False, symlinks=os.name != "nt").create(environment) python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python") @@ -21,14 +23,14 @@ def target_python(tmp_path, monkeypatch, runtime): coordinator = tmp_path / "coordinator-site" (coordinator / "inferrsi").mkdir(parents=True) (coordinator / "session_target_dependency.py").write_text("VALUE = 99\n", encoding="utf-8") - execute = runtime._session_execute + execute = executor.execute_ordinary def execute_with_coordinator_site(*args): with monkeypatch.context() as patch: - patch.setattr(runtime, "files", lambda name: coordinator / name) + patch.setattr(executor, "files", lambda name: coordinator / name) return execute(*args) - monkeypatch.setattr(runtime, "_session_execute", execute_with_coordinator_site) + monkeypatch.setattr(executor, "execute_ordinary", execute_with_coordinator_site) return python diff --git a/tests/harness/test_harness_measurement.py b/tests/harness/test_harness_measurement.py index 7cc066d29..2f9980dd0 100644 --- a/tests/harness/test_harness_measurement.py +++ b/tests/harness/test_harness_measurement.py @@ -8,8 +8,9 @@ import pytest from inferrsi.harness import optimization_session -from inferrsi.harness.measurement import ( +from inferrsi.harness.evaluator import ( MIN_PAIRS, + assess_ordinary, explain, gate_speedup, interval_rank, @@ -31,11 +32,28 @@ def report(baseline, candidate, *, direction="minimize", gate_pct=1.0, passed=Tr def point_gate(baseline, candidate, gate_pct): - """The current project.assess rule: independent medians, minimize direction.""" + """The ordinary project assessment rule: independent medians, minimize direction.""" improvement = (median(baseline) - median(candidate)) / median(baseline) * 100 return improvement > 0 and improvement >= gate_pct +def test_packaged_assessment_uses_the_assessor_supplied_by_apps(tmp_path): + plan = {"task_source": "packaged"} + attempt = tmp_path / "attempt" + execution = {"status": "completed", "returncode": 0} + evidence = {"verdict": "INCONCLUSIVE", "score": None} + calls = [] + + def assess_packaged(*inputs): + calls.append(inputs) + return evidence + + result = assess_ordinary(tmp_path, attempt, plan, execution, assess_packaged=assess_packaged) + assert result is evidence + assert calls == [(tmp_path, attempt, plan, execution)] + assert not attempt.exists() + + def test_gate_speedup_matches_improvement_pct_definition(): assert gate_speedup(10, "maximize") == pytest.approx(1.10) # Minimize: a 10% lower latency is a 1/0.9 speedup, not 1.10. @@ -233,7 +251,7 @@ def test_aa_pass_rate_at_the_gate_stays_within_the_exact_bound(pairs): def test_measurement_module_is_part_of_runtime_identity(): - assert "harness/measurement.py" in optimization_session._runtime_identity() + assert "harness/evaluator/_measurement.py" in optimization_session._runtime_identity() def profiles(rows, jitter=None): diff --git a/tests/harness/test_moe_optimization_protocol.py b/tests/harness/test_moe_optimization_protocol.py index 9eb527f32..84cca5bf2 100644 --- a/tests/harness/test_moe_optimization_protocol.py +++ b/tests/harness/test_moe_optimization_protocol.py @@ -8,7 +8,7 @@ import pytest -from inferrsi.harness import task_protocol +from inferrsi.harness.executor import prepare_task_protocol, run_task_protocol from tests.benchmark.engineering_task_support import load_task_module moe = load_task_module("moe-forward-npu", "benchmark") @@ -116,7 +116,7 @@ def rejection(transcript, *, cleanup=True, inner_status="failed", inner_code=1): def test_complete_raw_result_runs_in_isolated_protocol_child(transcript): directory, settings = transcript source = Path(protocol.__file__) - result = task_protocol.run(source.parent, hashlib.sha256(source.read_bytes()).hexdigest(), + result = run_task_protocol(source.parent, hashlib.sha256(source.read_bytes()).hexdigest(), "assess", directory=directory, settings=settings, execution={"status": "completed", "returncode": 0}) assert result["status"] == "completed" and result["score"] == 2.0 @@ -148,11 +148,11 @@ def test_arguments_bind_retained_candidate_and_output(tmp_path): def test_protocol_prepares_without_device_imports_and_reuses_frozen_arguments(tmp_path): frozen = tmp_path / "frozen" - prepared = task_protocol.prepare(Path(protocol.__file__).parent, frozen, + prepared = prepare_task_protocol(Path(protocol.__file__).parent, frozen, ["--pairs", "2", "--timeout-seconds", "900"]) assert prepared["evaluation_settings"] == {"pairs": 2, "timeout_seconds": 900.0} assert set(protocol.TASK_FILES) <= prepared["frozen_files"].keys() - arguments = task_protocol.run( + arguments = run_task_protocol( frozen, prepared["frozen_files"]["optimization.py"], "arguments", candidate=tmp_path / "retained.py", output=tmp_path / "measurement", settings=prepared["evaluation_settings"], diff --git a/tests/harness/test_service_fingerprint_isolation.py b/tests/harness/test_service_fingerprint_isolation.py index 666e5267e..662d3b22e 100644 --- a/tests/harness/test_service_fingerprint_isolation.py +++ b/tests/harness/test_service_fingerprint_isolation.py @@ -13,8 +13,9 @@ def test_service_guard_restores_lazy_import_aliases(tmp_path): check.write_text( "def test_restored_alias():\n" " from inferrsi.harness.records import artifact_primitives\n" - " from inferrsi.harness import project, task_protocol\n" - " assert project.sha256 is task_protocol.sha256 is artifact_primitives.sha256\n" + " from inferrsi.harness.executor import _project as project\n" + " from inferrsi.harness.executor import _task_protocol\n" + " assert project.sha256 is _task_protocol.sha256 is artifact_primitives.sha256\n" " assert project.sha256.__module__ == 'inferrsi.harness.records.artifact_primitives'\n", encoding="utf-8", ) @@ -35,7 +36,7 @@ def test_guard_blocks_lazily_imported_fingerprints_even_when_caught(monkeypatch, guard = no_fingerprints.__wrapped__(monkeypatch) next(guard) - from inferrsi.harness.task_protocol import sha256 + from inferrsi.harness.executor._task_protocol import sha256 with pytest.raises(AssertionError, match="must not calculate"): sha256(tmp_path / "unread-file") diff --git a/tests/harness/test_task_protocol_child.py b/tests/harness/test_task_protocol_child.py index cf4171517..5bf17630a 100644 --- a/tests/harness/test_task_protocol_child.py +++ b/tests/harness/test_task_protocol_child.py @@ -16,8 +16,13 @@ import pytest from inferrsi.benchmark.registry import task_resources -from inferrsi.harness import protocol_child, task_protocol -from inferrsi.harness.task_protocol import TaskProtocolError, run +from inferrsi.harness.executor import ( + TaskProtocolError, + _task_protocol, + prepare_task_protocol, + protocol_child, +) +from inferrsi.harness.executor import run_task_protocol as run SETTINGS = {"pairs": 2, "samples": 1, "warmups": 1} QWEN_ARGUMENTS = ["--pairs", "2", "--samples", "1", "--warmups", "1"] @@ -136,7 +141,7 @@ def test_diagnostics_are_forwarded_when_the_protocol_raises(tmp_path, capsys): def test_only_the_stderr_tail_is_forwarded(tmp_path, capsys, monkeypatch): - monkeypatch.setattr(task_protocol, "STDERR_TAIL_BYTES", 16) + monkeypatch.setattr(_task_protocol, "STDERR_TAIL_BYTES", 16) digest = write_protocol(tmp_path, ( "import sys\n" "def validate_arguments(a):\n" @@ -166,7 +171,7 @@ def test_malformed_or_foreign_envelopes_are_distinct_failures(tmp_path, monkeypa child = tmp_path / "child.py" child.write_text("import os, sys\nsys.stderr.write('child diagnostics')\n" f"os.write(1, {payload!r})\n", encoding="utf-8") - monkeypatch.setattr(task_protocol, "CHILD_ENTRY", child) + monkeypatch.setattr(_task_protocol, "CHILD_ENTRY", child) digest = write_protocol(tmp_path / "task", "def validate_arguments(a):\n return {}\n") assert failure(tmp_path / "task", digest).kind == kind assert "child diagnostics" in capsys.readouterr().err @@ -187,12 +192,12 @@ def test_child_exit_without_an_envelope_is_an_exit_status_failure(tmp_path, caps def test_launch_failure_is_a_transport_failure(tmp_path, monkeypatch): digest = write_protocol(tmp_path, "def validate_arguments(a):\n return {}\n") - monkeypatch.setattr(task_protocol.sys, "executable", str(tmp_path / "missing-python")) + monkeypatch.setattr(_task_protocol.sys, "executable", str(tmp_path / "missing-python")) assert failure(tmp_path, digest).kind == "launch" def test_oversized_envelope_is_rejected(tmp_path, monkeypatch): - monkeypatch.setattr(task_protocol, "STDOUT_LIMIT_BYTES", 64) + monkeypatch.setattr(_task_protocol, "STDOUT_LIMIT_BYTES", 64) digest = write_protocol(tmp_path, "def validate_arguments(a):\n return {'x': 'y' * 100}\n") assert failure(tmp_path, digest).kind == "output_limit" @@ -205,7 +210,7 @@ def _late_writer(marker): def test_deadline_stops_the_child_and_its_descendants(tmp_path, monkeypatch, capsys): marker = tmp_path / "late.txt" - monkeypatch.setattr(task_protocol, "PROTOCOL_TIMEOUT_SECONDS", 3.0) + monkeypatch.setattr(_task_protocol, "PROTOCOL_TIMEOUT_SECONDS", 3.0) digest = write_protocol(tmp_path / "task", ( "import subprocess, sys, time\n" "def validate_arguments(a):\n" + _late_writer(marker) + @@ -231,7 +236,7 @@ def test_campaign_deadline_bounds_the_protocol_timeout(tmp_path): def test_expired_campaign_deadline_never_starts_protocol(tmp_path, monkeypatch): digest = write_protocol(tmp_path, "def validate_arguments(a):\n return {}\n") - monkeypatch.setattr(task_protocol.local_process, "_supervise", + monkeypatch.setattr(_task_protocol.local_process, "_supervise", lambda *a, **k: pytest.fail("expired protocol must not start")) error = failure(tmp_path, digest, deadline=0, arguments=[]) assert error.kind == "timeout" and error.cleanup_verified is True @@ -240,7 +245,7 @@ def test_expired_campaign_deadline_never_starts_protocol(tmp_path, monkeypatch): @pytest.mark.parametrize("cleanup", [False, None]) def test_protocol_timeout_retains_uncertain_cleanup(tmp_path, monkeypatch, cleanup): digest = write_protocol(tmp_path, "def validate_arguments(a):\n return {}\n") - monkeypatch.setattr(task_protocol.local_process, "_supervise", lambda *a, **k: { + monkeypatch.setattr(_task_protocol.local_process, "_supervise", lambda *a, **k: { "status": "timeout", "pid": 123, "domain_empty": cleanup, }) error = failure(tmp_path, digest) @@ -250,7 +255,7 @@ def test_protocol_timeout_retains_uncertain_cleanup(tmp_path, monkeypatch, clean @pytest.mark.parametrize("deadline", [float("nan"), float("inf"), -float("inf"), True, "soon"]) def test_invalid_campaign_deadline_never_starts_protocol(tmp_path, monkeypatch, deadline): digest = write_protocol(tmp_path, "def validate_arguments(a):\n return {}\n") - monkeypatch.setattr(task_protocol.local_process, "_supervise", + monkeypatch.setattr(_task_protocol.local_process, "_supervise", lambda *a, **k: pytest.fail("invalid deadline must not start")) assert failure(tmp_path, digest, deadline=deadline, arguments=[]).kind == "request" @@ -263,7 +268,7 @@ def test_scratch_directory_is_removed_after_every_operation(tmp_path, monkeypatc raises): scratch = tmp_path / "scratch" scratch.mkdir() - monkeypatch.setattr(task_protocol.tempfile, "tempdir", str(scratch)) + monkeypatch.setattr(_task_protocol.tempfile, "tempdir", str(scratch)) digest = write_protocol(tmp_path / "task", "def validate_arguments(a):\n" + body) if raises: assert failure(tmp_path / "task", digest).kind == "protocol_exception" @@ -305,7 +310,7 @@ def test_child_checks_the_digest_of_the_bytes_it_compiles(tmp_path): "protocol": str(tmp_path / "optimization.py"), "protocol_sha256": good, "arguments": {"arguments": []}})) completed = subprocess.run( - [sys.executable, "-I", "-B", str(task_protocol.CHILD_ENTRY), str(request)], + [sys.executable, "-I", "-B", str(_task_protocol.CHILD_ENTRY), str(request)], capture_output=True, check=True, timeout=60) assert json.loads(completed.stdout)["error"]["kind"] == "identity" assert not marker.exists() @@ -350,12 +355,12 @@ def test_harness_never_executes_protocol_code_in_process(tmp_path): digest = write_protocol(tmp_path, "def validate_arguments(a):\n return {}\n") run(tmp_path, digest, "validate_arguments", arguments=[]) assert "task_optimization_protocol" not in sys.modules - source = Path(task_protocol.__file__).read_text(encoding="utf-8") + source = Path(_task_protocol.__file__).read_text(encoding="utf-8") assert "module_from_spec" not in source and "exec(" not in source def test_child_entry_imports_only_the_standard_library(): - tree = ast.parse(task_protocol.CHILD_ENTRY.read_text(encoding="utf-8")) + tree = ast.parse(_task_protocol.CHILD_ENTRY.read_text(encoding="utf-8")) imported = {alias.name.split(".")[0] for node in ast.walk(tree) if isinstance(node, ast.Import) for alias in node.names} imported |= {(node.module or "").split(".")[0] for node in ast.walk(tree) @@ -367,6 +372,6 @@ def test_child_entry_imports_only_the_standard_library(): def test_prepare_freezes_exactly_the_validated_protocol(tmp_path): source, digest = qwen() - settings = task_protocol.prepare(source, tmp_path / "frozen", QWEN_ARGUMENTS) + settings = prepare_task_protocol(source, tmp_path / "frozen", QWEN_ARGUMENTS) assert settings["evaluation_settings"] == SETTINGS assert settings["frozen_files"]["optimization.py"] == digest diff --git a/tests/repository/_gate_policy_support.py b/tests/repository/_gate_policy_support.py index fe5e519a4..8eae3efc3 100644 --- a/tests/repository/_gate_policy_support.py +++ b/tests/repository/_gate_policy_support.py @@ -169,6 +169,7 @@ "inferrsi.harness.api", "inferrsi.contracts._harness_errors", "inferrsi.harness.executor._execution", + "inferrsi.harness.evaluator", "inferrsi.harness.executor", "inferrsi.harness.executor._input_binding", "inferrsi.harness.executor.local_process", diff --git a/tests/repository/test_first_wave_isolation_policy.py b/tests/repository/test_first_wave_isolation_policy.py index f74d600b0..71b665f04 100644 --- a/tests/repository/test_first_wave_isolation_policy.py +++ b/tests/repository/test_first_wave_isolation_policy.py @@ -1254,7 +1254,7 @@ def test_returning_r2_harness_infra_edges_fail(self) -> None: primitives = {"harness/records/artifact_primitives.py": "VALUE = 1\n", "harness/records/atomic_json.py": "VALUE = 1\n"} modules = ("agent_sessions", "executor.candidates", "optimization", "optimization_session", - "project", "task_protocol") + "project", "executor._task_protocol") paths = {name: "harness/" + name.replace(".", "/") + ".py" for name in modules} clean = {path: "from inferrsi.harness.records.artifact_primitives import VALUE\n" for path in paths.values()} diff --git a/tests/repository/test_target_module_import_gate.py b/tests/repository/test_target_module_import_gate.py index 09dbe619a..e827275b5 100644 --- a/tests/repository/test_target_module_import_gate.py +++ b/tests/repository/test_target_module_import_gate.py @@ -142,8 +142,9 @@ def test_only_files_directly_in_a_non_package_bundle_are_bundle_programs(tmp_pat @pytest.mark.parametrize("relative", [ "benchmark/registry.py", "benchmark/tasks.py", - # The Harness protocol loader that R3 retired, and its neighbours. + # Exercise the retired Harness loader location and the current Executor supervisor. "harness/task_protocol.py", + "harness/executor/_task_protocol.py", "harness/other_protocol.py", "apps/benchmark_operations.py", "apps/workflows/benchmark_operations.py", diff --git a/tools/measurement_simulation.py b/tools/measurement_simulation.py index 898c33b01..b6512d87e 100644 --- a/tools/measurement_simulation.py +++ b/tools/measurement_simulation.py @@ -4,11 +4,11 @@ on the same samples, so the contribution of pairing and of the interval can be separated: -* point_rule current project.assess: ratio of independent medians >= gate +* point_rule current evaluator.assess_project: ratio of independent medians >= gate * paired_point median of per-repetition speedups >= gate, no interval * unpaired_interval percentile bootstrap of the ratio of independently resampled medians; lower bound > gate (a comparison rule, not used by the harness) -* paired_interval harness.measurement.paired_statistics: above_gate, using the exact +* paired_interval harness.evaluator.paired_statistics: above_gate, using the exact order-statistic (sign-test) interval The data seed generates samples. Coverage is the fraction of campaigns whose exact @@ -30,7 +30,7 @@ import random from statistics import median -from inferrsi.harness.measurement import ( +from inferrsi.harness.evaluator import ( MIN_PAIRS, gate_speedup, median_interval, From e4a284e0736ceea1b8ae6a50c2e4e55768f4f156 Mon Sep 17 00:00:00 2001 From: dongxinwen Date: Fri, 27 Nov 2026 06:59:42 +0800 Subject: [PATCH 2/2] Check the ordinary assessor and lazy executor imports at their new locations Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (author) Signed-off-by: dongxinwen --- tests/apps/test_session_ranking_policy.py | 7 ++++--- tests/harness/test_harness_execute.py | 22 ++++++++++++++++++++-- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/tests/apps/test_session_ranking_policy.py b/tests/apps/test_session_ranking_policy.py index e40a05d71..ca020fe50 100644 --- a/tests/apps/test_session_ranking_policy.py +++ b/tests/apps/test_session_ranking_policy.py @@ -9,7 +9,8 @@ from inferrsi.apps import cli from inferrsi.apps.cli import main -from inferrsi.harness import executor, optimization +from inferrsi.harness import optimization +from inferrsi.harness.executor import _task_protocol from inferrsi.harness.records import service_io from inferrsi.knowledge import ranking_policy from inferrsi.knowledge.knowledge_operations import KnowledgeReader @@ -350,7 +351,7 @@ def refused_without_writes(): def test_packaged_assessor_receives_identical_evidence_across_policies(task, tmp_path, capsys, monkeypatch): calls = [] - real_run = executor.run_task_protocol + real_run = _task_protocol.run_task_protocol def observe(frozen, source_hash, operation, *, launch_directory=None, **inputs): if operation == "assess": @@ -361,7 +362,7 @@ def observe(frozen, source_hash, operation, *, launch_directory=None, **inputs): read(directory / "measurement/result.json"))) return real_run(frozen, source_hash, operation, launch_directory=launch_directory, **inputs) - monkeypatch.setattr(executor, "run_task_protocol", observe) + monkeypatch.setattr(_task_protocol, "run_task_protocol", observe) outcomes = [] for name in ("default", "applicability"): root = tmp_path / name diff --git a/tests/harness/test_harness_execute.py b/tests/harness/test_harness_execute.py index e9a5fa667..f50772ced 100644 --- a/tests/harness/test_harness_execute.py +++ b/tests/harness/test_harness_execute.py @@ -53,6 +53,23 @@ "inferrsi.harness", "inferrsi.contracts", "inferrsi.contracts.runspec", } +# The static walk also follows optional Executor exports inside __getattr__. Importing +# Harness in a fresh process is still checked against the smaller H01/H02 set above. +ORDINARY_PROTOCOL_MODULES = { + "inferrsi.harness.evaluator", + "inferrsi.harness.evaluator._measurement", + "inferrsi.harness.evaluator._project", + "inferrsi.harness.executor._benchmark_child", + "inferrsi.harness.executor._ordinary", + "inferrsi.harness.executor._project", + "inferrsi.harness.executor._task_protocol", + "inferrsi.harness.executor.candidates", + "inferrsi.harness.executor.launch_records", + "inferrsi.harness.executor.protocol_child", + "inferrsi.harness.executor.trials", + "inferrsi.harness.executor.trials.external", + "inferrsi.harness.records.artifact_primitives", +} # Prints a grandchild's pid, then outlives any test deadline with it. TREE = ( "import os, subprocess, sys, time; " @@ -472,8 +489,9 @@ def test_h02_6_no_device_model_or_network_fallback(h: Harness, tmp_path) -> None # Static and runtime closure: the new H entry loads no device, model or infra module. graph = _scan(ROOT, exact_pairs(load_manifest())) - expanded, hits = _walk("inferrsi.harness.api", graph.edges, lambda n: n not in NEW_H_CLOSURE) - assert hits == [] and set(expanded) == NEW_H_CLOSURE + static_modules = NEW_H_CLOSURE | ORDINARY_PROTOCOL_MODULES + expanded, hits = _walk("inferrsi.harness.api", graph.edges, lambda n: n not in static_modules) + assert hits == [] and set(expanded) == static_modules code = ( "import json, sys, inferrsi.harness.api; " "print(json.dumps(sorted(m for m in sys.modules "