diff --git a/docs/contracts/function-owners.md b/docs/contracts/function-owners.md index 5d81756a9..f21630d39 100644 --- a/docs/contracts/function-owners.md +++ b/docs/contracts/function-owners.md @@ -31,7 +31,7 @@ Any later split of a mixed function is accepted by real pytest/host/wheel/record ## Implemented rows -The skill-evaluation split (#410) implements the `skill_evaluation`, `skill_eval_diagnostic`, `skill_eval_engineering` and `improvement` rows. H keeps `harness/skill_evaluation.py`, `harness/artifact_sandbox.py` and `harness/improvement.py`; B holds `benchmark/skill_evaluation.py`, `benchmark/skill_eval_diagnostic.py`, `benchmark/skill_eval_engineering.py` and `benchmark/improvement.py`; Apps composes them in `apps/workflows/skill_evaluation.py`, `apps/workflows/skill_eval_engineering.py` and `apps/workflows/improvement.py`. Two points follow the tree as it stands after #338, not the row text: +The skill-evaluation split (#410) implements the `skill_evaluation`, `skill_eval_diagnostic`, `skill_eval_engineering` and `improvement` rows. H keeps `harness/skill_evaluation.py`, `harness/artifact_sandbox.py` and `harness/manager/search/improvement.py`; B holds `benchmark/skill_evaluation.py`, `benchmark/skill_eval_diagnostic.py`, `benchmark/skill_eval_engineering.py` and `benchmark/improvement.py`; Apps composes them in `apps/workflows/skill_evaluation.py`, `apps/workflows/skill_eval_engineering.py` and `apps/workflows/improvement.py`. Two points follow the tree as it stands after #338, not the row text: - `usage_totals` stays in `harness/usage.py`, because `harness/optimization.py` consumes it for budget accounting. B `assessment` receives the baseline and candidate totals from Apps and does not import H. - `SelectionPolicy` holds only the two thresholds, so it lives whole in B. H `choose` receives the assessments, the validity block and the composition flag; it holds no threshold and no policy class. diff --git a/docs/guides/harness-improvement.md b/docs/guides/harness-improvement.md index 5cb258255..f2465f7af 100644 --- a/docs/guides/harness-improvement.md +++ b/docs/guides/harness-improvement.md @@ -45,7 +45,7 @@ flowchart TB ``` `src/inferrsi/benchmark/improvement.py` owns the thresholds and acceptance rules, -`src/inferrsi/harness/improvement.py` the search progression and +`src/inferrsi/harness/manager/search/improvement.py` the search progression and `src/inferrsi/harness/usage.py` usage accounting; `src/inferrsi/apps/workflows/improvement.py` composes them. `tools/skill_eval_improve.py` owns freezing, declarative snapshot materialization diff --git a/docs/guides/module-layout.md b/docs/guides/module-layout.md index 2a51b1eba..4d54a42bd 100644 --- a/docs/guides/module-layout.md +++ b/docs/guides/module-layout.md @@ -332,14 +332,15 @@ The leaf's own import rule and `REPO_TYPES` object identity govern it. names, with or without a file behind it. Since #498 the names `inferrsi.infra` and `inferrsi.model` are retired as a whole, so any import of either fails. Before that, `inferrsi.infra` reached no Knowledge, Harness, Benchmark, or Apps module. -- **New H entries.** The registered entry modules are - `inferrsi.harness.api`, `inferrsi.harness.execution_service`, +- **Harness entries.** The registered component packages are + `inferrsi.harness.manager` and `inferrsi.harness.executor`. The gate also + tracks `inferrsi.harness.api`, `inferrsi.harness.execution_service`, `inferrsi.harness.input_binding`, `inferrsi.harness.local_process`, - `inferrsi.harness.run_store`, and `inferrsi.harness.errors`. Each entry's - closure is walked on the full graph. The gate does not infer other module - paths from labels. Any `inferrsi.harness.*` module that exists is still - checked against the closure rule above. The current mixed `harness` tree is - not automatically an isolated core. + `inferrsi.harness.run_store`, and `inferrsi.harness.errors`. Each registered + entry must appear in the import graph and satisfy its dependency rules. + The closure rule above applies to every Harness module. The gate rejects + imports of the ten former root-level search modules and any file that + restores one of those paths. - **No residual.** The skill-evaluation split (#410) moved `export_bundle` to Apps and removed the registered `harness.skill_evaluation` → root `knowledge_operations` edge together with its exemption. Every harness @@ -347,7 +348,7 @@ The leaf's own import rule and `REPO_TYPES` object identity govern it. root leaf fails, and so does each harness module that reaches the leaf through it. The report lists every remaining `harness` → Model or Infra path in `harness_model_infra`; the split modules `harness.skill_evaluation`, - `harness.improvement`, `harness.artifact_sandbox` and `harness.atomic_json` + `harness.manager.search.improvement`, `harness.artifact_sandbox` and `harness.atomic_json` have none. The manifest records the base commit, each old leaf's file hash at that diff --git a/docs/guides/operations.md b/docs/guides/operations.md index 24a168e62..5f55d199a 100644 --- a/docs/guides/operations.md +++ b/docs/guides/operations.md @@ -70,7 +70,7 @@ Effect classes used below: | Qualify an artifact verifier host | [Manual reviewer qualification](skill-evaluation/skill-eval-reviewer-qualification.md), `python -m tools.skill_eval_qualify` | Trusted-control execution / report-generating | Manual main-only workflow; fixed software controls, no model or external artifact input; unavailable isolation fails rather than skips | | Replay a cloud-generated parser pair | [Isolated cloud replay](skill-evaluation/skill-eval-cloud-replay.md), `python -m tools.skill_eval_cloud_replay` | Untrusted-artifact execution / report-generating | Manual pinned data ingress; same-host controls before bubblewrap-only replay; no models or credentials | | Validate one harness-improvement step | [Offline improvement](harness-improvement.md), Python `tools.skill_eval_improve.prepare` / `run_offline` | Snapshot-writing / offline experiment-executing | Supplied declarative INV/DOM edits, shared total limits, rerun and one holdout gate; trusted fixed-output clients only; no real-model or Store execution | -| Build an offline candidate tree and completion menu | Python `harness.search_tree` / `harness.verification_plans.completion_menu`; [control contract](speculative-search.md) | Read-only / in-memory transitions | Immutable candidates, scoped caller-supplied receipts and bounded exact plans; execution, durable state, accounting, learned roles and final acceptance require separate adapters | +| Build an offline candidate tree and completion menu | Python `harness.manager.search.search_tree` / `harness.manager.search.verification_plans.completion_menu`; [control contract](speculative-search.md) | Read-only / in-memory transitions | Immutable candidates, scoped caller-supplied receipts and bounded exact plans; execution, durable state, accounting, learned roles and final acceptance require separate adapters | | Run bounded speculative Engine search and role updates | `inferrsi search engine`; [support and configuration](speculative-search.md) | Execution / candidate writes / CPU model updates | Explicit shared RunStore, permissions, checkpoint, budgets, domain and final gate; actual device allocation is caller-owned | | Inspect/export speculative search | `inferrsi search status` / `search export` | Read / output artifact | Reads the existing store; never restarts search, training or final evaluation | | Compose Skill speculative search | Python `apps.workflows.search_benchmarks.SkillEvaluator` and checkout `tools.speculative_skill.Comparator` | Explicit provider execution through existing comparator | Frozen original baseline, split descriptors, independent grader and bounded provider; see campaign accounting limits in the support matrix | diff --git a/docs/guides/speculative-search.md b/docs/guides/speculative-search.md index a7786795c..1efa07e44 100644 --- a/docs/guides/speculative-search.md +++ b/docs/guides/speculative-search.md @@ -9,18 +9,32 @@ paper's language-model training or establish its reported gains. Existing ## Supported profile and authority +Direct callers import `EngineSearchPlan`, `run_engine_search` and `read_engine_search` +from `inferrsi.harness.manager`. Apps parses `inferrsi search engine` arguments and +supplies the checkpoint loader and evaluator factory. Manager checks the campaign cap +and final reserve before either callback runs or any session or RunStore is created. +It selects a candidate using development evidence, binds that candidate to one final +evaluation and returns the stored result. `read_engine_search(session)` reads it back. + +The search implementation moved from the Harness root to `harness/manager/search/`. +This includes `gvo`, `improvement`, `search_adapter`, `search_campaign`, +`search_continuations`, `search_records`, `search_tree`, `vats`, `verification_plans` +and `work_control`. For subprocess environment setup, replace imports of +`runtime_environment` from `inferrsi.harness.optimization_session` with +`from inferrsi.harness.executor import runtime_environment`. + | Component | Implementation | Boundary | | --- | --- | --- | -| Candidate/evidence model | `harness.search_tree`, `search_records` | Immutable artifacts, actual dependency epochs and complete-candidate selection | -| Solver | `harness.verification_plans`, `vats.menu` | Bounded exhaustive completion plans; conservative integer millisecond caps | -| Drafter | `apps.workflows.search_roles`, `harness.search_adapter` | Trainable softmax over supplied exact text edits; actual retained changes, not free-form LLM generation | +| Candidate/evidence model | `harness.manager.search.search_tree`, `search_records` | Immutable artifacts, actual dependency epochs and complete-candidate selection | +| Solver | `harness.manager.search.verification_plans`, `vats.menu` | Bounded exhaustive completion plans; conservative integer millisecond caps | +| Drafter | `apps.workflows.search_roles`, `harness.manager.search.search_adapter` | Trainable softmax over supplied exact text edits; actual retained changes, not free-form LLM generation | | Policy | `apps.workflows.search_roles` | Independent eight-feature linear softmax, recorded behavior probabilities, deterministic deployment actions | | Scorer | `apps.workflows.search_roles` | Separate linear model; actual suffix MSE and optional paid continuation differences | -| Work/state authority | `harness.work_control` | Transactions in the shared `RunStore` SQLite database | +| Work/state authority | `harness.manager.search.work_control` | Transactions in the shared `RunStore` SQLite database | | Execution | Existing `trials.external` and `local_process` | Absolute deadline and process-domain cleanup; no new subprocess runner | | Engine | `apps.workflows.search_benchmarks.EngineEvaluator` | Existing packaged `optimization.py` as one whole check; currently the Qwen denoiser NPU task | | Skill | `apps.workflows.search_benchmarks.SkillEvaluator`, checkout `tools.speculative_skill.Comparator` | Explicit provider configuration, original baseline, independent grader, separate development/holdout descriptors | -| Final | `harness.search_campaign.finalize` | One-time scope claim before access; receipt-only recovery/export; task promotion only | +| Final | `harness.manager.search.search_campaign.finalize` | One-time scope claim before access; receipt-only recovery/export; task promotion only | This is a trusted local host controller. Resource domains exclude **cooperating controllers sharing one RunStore**. They are not scheduler/GPU reservations, @@ -150,7 +164,7 @@ The formal objectives are in [SpecRSI §3.4](https://arxiv.org/html/2610.16491v2 receipts. Final measurements are reserved for independently retesting the selected candidate. -The [collection and target code](../../src/inferrsi/harness/gvo.py) and the +The [collection and target code](../../src/inferrsi/harness/manager/search/gvo.py) and the [CPU role update](../../src/inferrsi/apps/workflows/search_roles.py) implement these steps with finite edit operators, a linear Policy and a linear Scorer. The caller supplies the initial checkpoint and its provenance. diff --git a/evidence/qwen-vats-gvo-910b1-20261124/README.md b/evidence/qwen-vats-gvo-910b1-20261124/README.md index 9ec16981c..0eca55d83 100644 --- a/evidence/qwen-vats-gvo-910b1-20261124/README.md +++ b/evidence/qwen-vats-gvo-910b1-20261124/README.md @@ -4,7 +4,7 @@ This Engine diagnostic for [InferRSI #363](https://github.com/InferMatrixLab/Inf compares a fixed-order serial control, frozen VATS and VATS after one GVO update on the packaged Qwen-Image 2.1 denoiser. The underlying search and task code was [f5b9a18](https://github.com/InferMatrixLab/InferRSI/tree/f5b9a1819d387e0a0a1a219da6dcc0f5504c4069). -The [design document](../../docs/speculative-search.md#measuring-the-contribution-of-gvo) +The [design document](../../docs/guides/speculative-search.md#measuring-the-contribution-of-gvo) explains the comparison and reports the independent-final results. - [Frozen plan](plan/plan.json), [archived measurement driver](https://github.com/InferMatrixLab/InferRSI/blob/1921271c99d1fc3532e882c1ce6dd4e3ce6d74a0/evidence/qwen-vats-gvo-910b1-20261124/plan/run.py) and [RunSpec](plan/runspec.json) identify the exact edits, weights, workload, ordered seeds, evaluation caps, runtime and task file hashes. 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 6d53fa6e5..8b056c668 100644 --- a/evidence/qwen-vats-gvo-910b1-20261124/plan/retained-sha256.json +++ b/evidence/qwen-vats-gvo-910b1-20261124/plan/retained-sha256.json @@ -1,13 +1,13 @@ { - "README.md": "e8ae15c859ecbb15a9c2af8da15c26725886940540f4cdaf9c590b94f2002705", + "README.md": "2f989efc36cef123897f09c8a96855cac9ce64b6c2916fe34a30d9b96d2d9ad0", "patch/README.md": "e2a3af7bd373d9e1637265f3980fd272cbbc181d455d275794bf66f2cc6f8095", "plan/edits.json": "2975fee42370debd80f627ecd58880e45280968f739ca3045c8b388bc9ab4cbb", "plan/plan.json": "66344b1ca1522fd3b38966c243bbb6ec8eb8fecc203ccd171690463569632013", - "plan/run.py": "8c66690aa9bb7b53dcbfe568bfe3654a65436a11ee7a05b21c2d3c0d611e1ad5", + "plan/run.py": "e16382292afc735615c1f21c230aaa4054c68613d084f4a75c61e04295af0d74", "plan/runspec.json": "f3f2ab71d227ee3e7d95233cc3d34e17ab41d086f519f558fb3aca5200515404", "results/local-archive.json": "c5df5dc55feb202e53f28d5b6f4ba28913e893277d9deb5e783a472c686d9ae6", "results/summary.json": "df3029cfcaacb91018b6c931017b059b99a80633116586f9446fe82e31986132", "results/trials.jsonl": "6bd39719a5c0d794b1c5e04403b03789ae5ca42e0c9c74694200bdb6355a0756", - "validator/README.md": "3b2b92982f3e3c377a755972002beaad454451bdc08cd2db68e5d4256337fa3d", - "validator/check.py": "4b408d07d0cdff724312f86746c9de5d6996e9b8925f61c5453dc9761f646f04" + "validator/README.md": "c224e3d864829d5c1a2f8bc4e4c89e36834409d4ce78fc1fa7dc59f6f739fdd3", + "validator/check.py": "6cd0948acf82c6870ac29c2188ede2092dca83e64e73aea2224edeb2f9187e2b" } diff --git a/evidence/qwen-vats-gvo-910b1-20261124/plan/run.py b/evidence/qwen-vats-gvo-910b1-20261124/plan/run.py index 15af73b00..93af4b56b 100644 --- a/evidence/qwen-vats-gvo-910b1-20261124/plan/run.py +++ b/evidence/qwen-vats-gvo-910b1-20261124/plan/run.py @@ -10,21 +10,21 @@ from inferrsi.apps.workflows.search_benchmarks import EngineEvaluator from inferrsi.apps.workflows.search_roles import Snapshot -from inferrsi.harness import search_tree from inferrsi.harness.artifact_primitives import digest, sha256 from inferrsi.harness.atomic_json import atomic_write_json -from inferrsi.harness.run_store import RunStore -from inferrsi.harness.search_adapter import ArtifactAdapter, Edit -from inferrsi.harness.search_campaign import ( +from inferrsi.harness.manager.search import search_tree +from inferrsi.harness.manager.search.search_adapter import ArtifactAdapter, Edit +from inferrsi.harness.manager.search.search_campaign import ( FinalAcceptance, finalize, import_qualified_root, learn, qualify_root, ) -from inferrsi.harness.search_records import decode -from inferrsi.harness.vats import Search, Settings -from inferrsi.harness.work_control import WorkControl +from inferrsi.harness.manager.search.search_records import decode +from inferrsi.harness.manager.search.vats import Search, Settings +from inferrsi.harness.manager.search.work_control import WorkControl +from inferrsi.harness.run_store import RunStore HERE = Path(__file__).resolve().parent diff --git a/evidence/qwen-vats-gvo-910b1-20261124/validator/README.md b/evidence/qwen-vats-gvo-910b1-20261124/validator/README.md index 488a10508..2c5ffa148 100644 --- a/evidence/qwen-vats-gvo-910b1-20261124/validator/README.md +++ b/evidence/qwen-vats-gvo-910b1-20261124/validator/README.md @@ -9,7 +9,7 @@ complete numerical result and verified process cleanup. The VATS final also requires a durable overall PASS and promotion of the selected candidate. Hardware replay uses the command and environment in the -[design document](../../../docs/speculative-search.md#measuring-the-contribution-of-gvo). +[design document](../../../docs/guides/speculative-search.md#measuring-the-contribution-of-gvo). Supply a fresh directory. RunStore operation identities and hardware timings vary between replays. The trial index records the actual files from this run. @@ -33,8 +33,12 @@ the unpacked original archive, preserve its `config/run.py` next to the own bytes in each new trial directory. Its summary also records incomplete and unrun arms, which prevent publication of paired results. -For trials made with the current driver, each VATS claim and its settled final -operation must carry the same rule. It requires every check to pass with verified cleanup -and applies no additional score threshold. The checker also recognizes the pinned driver -from [the previous revision](https://github.com/InferMatrixLab/InferRSI/blob/b974554199cb10759da03a75f333e608c91d7395/evidence/qwen-vats-gvo-910b1-20261124/plan/run.py). -The recorded promotions from older drivers remain historical results. +For trials made with the current driver or the driver immediately before the +Harness search move, each VATS claim and its settled final operation must carry +the same acceptance rule. Every check must pass with verified cleanup, with no +additional score threshold. The checker identifies the driver from its retained +bytes. [Pre-migration driver](https://github.com/InferMatrixLab/InferRSI/blob/54342cc573896c953cb0e2fb8734ef28262b5bda/evidence/qwen-vats-gvo-910b1-20261124/plan/run.py) + +The earlier driver at `b974554` predates the stored acceptance rule. For this +pinned driver the checker verifies the recorded promotion, selected candidate +and settled receipt using the fields available in that run. [Earlier driver](https://github.com/InferMatrixLab/InferRSI/blob/b974554199cb10759da03a75f333e608c91d7395/evidence/qwen-vats-gvo-910b1-20261124/plan/run.py) diff --git a/evidence/qwen-vats-gvo-910b1-20261124/validator/check.py b/evidence/qwen-vats-gvo-910b1-20261124/validator/check.py index 134e3dc82..3ad55b1df 100644 --- a/evidence/qwen-vats-gvo-910b1-20261124/validator/check.py +++ b/evidence/qwen-vats-gvo-910b1-20261124/validator/check.py @@ -10,10 +10,11 @@ from inferrsi.benchmark.registry import task_resources from inferrsi.harness import candidates, task_protocol +from inferrsi.harness.manager.search.work_control import WorkControl from inferrsi.harness.run_store import RunStoreReader -from inferrsi.harness.work_control import WorkControl PLAN = Path(__file__).resolve().parents[1] / "plan" +PRE_MIGRATION_DRIVER_SHA256 = "8c66690aa9bb7b53dcbfe568bfe3654a65436a11ee7a05b21c2d3c0d611e1ad5" # The published driver at b974554 saved its own bytes before rules were stored in claims. PREVIOUS_DRIVER_SHA256 = "548c67815bafa10ab2ff05fe4a09596e2ab99dbae28fc526c01bfa50f8f471ff" @@ -35,6 +36,13 @@ def close(left, right): return math.isclose(left, right, rel_tol=1e-12, abs_tol=1e-12) +def replay_requires_acceptance(driver, current_driver): + if driver == PREVIOUS_DRIVER_SHA256: + return False + require(driver in (current_driver, PRE_MIGRATION_DRIVER_SHA256), "Replay driver identity") + return True + + def promoted_final(doc, campaign, candidate_root, *, require_acceptance=False): final = doc["final_result"] claim = doc["final_claim"] @@ -90,16 +98,14 @@ def main(completed, failed, historical_driver=None): require(sha(task / name) == expected_hash, name) summary = read(completed / "summary.json") current_driver = sha(PLAN / "run.py") + require_acceptance = False for name, expected_hash in spec["input_sha256"].items(): path = PLAN.parent / name if name == "plan/run.py": if "driver_sha256" in summary: path = completed / "driver.py" expected_hash = summary["driver_sha256"] - require( - expected_hash in (current_driver, PREVIOUS_DRIVER_SHA256), - "Replay driver identity", - ) + require_acceptance = replay_requires_acceptance(expected_hash, current_driver) else: # The original archive includes the driver used for the published measurements. path = historical_driver or completed.parent.parent / "config/run.py" @@ -133,7 +139,7 @@ def main(completed, failed, historical_driver=None): doc, campaign, completed / "artifacts/candidates", - require_acceptance=summary.get("driver_sha256") == current_driver, + require_acceptance=require_acceptance, ) for operation, op in doc["operations"].items(): require(op["status"] == "settled", operation) diff --git a/src/inferrsi/apps/workflows/benchmark_operations.py b/src/inferrsi/apps/workflows/benchmark_operations.py index 7770c3f53..343c929b0 100644 --- a/src/inferrsi/apps/workflows/benchmark_operations.py +++ b/src/inferrsi/apps/workflows/benchmark_operations.py @@ -6,6 +6,7 @@ from inferrsi.benchmark.registry import task_resources from inferrsi.harness import optimization_session +from inferrsi.harness.executor import runtime_environment def run_task(name: str, arguments: list[str]) -> int: @@ -15,5 +16,5 @@ def run_task(name: str, arguments: list[str]) -> int: return subprocess.call( [sys.executable, str(Path(optimization_session.__file__).resolve()), str(entry), *arguments], - env=optimization_session.runtime_environment(), + env=runtime_environment(), ) diff --git a/src/inferrsi/apps/workflows/improvement.py b/src/inferrsi/apps/workflows/improvement.py index 187329e74..6d2f499cf 100644 --- a/src/inferrsi/apps/workflows/improvement.py +++ b/src/inferrsi/apps/workflows/improvement.py @@ -1,10 +1,8 @@ -# Composed improvement-step entries: Harness usage totals and search progression -# joined with Benchmark acceptance rules. Signatures and results match the -# functions that harness.improvement held before the ownership split. +# Compose Benchmark acceptance rules with Harness usage totals and search progression. from inferrsi.benchmark import improvement as rules from inferrsi.benchmark.improvement import SelectionPolicy -from inferrsi.harness import improvement as progression +from inferrsi.harness.manager.search import improvement as progression from inferrsi.harness.usage import usage_totals diff --git a/src/inferrsi/apps/workflows/search_benchmarks.py b/src/inferrsi/apps/workflows/search_benchmarks.py index 5a6c92320..2d8ee2d40 100644 --- a/src/inferrsi/apps/workflows/search_benchmarks.py +++ b/src/inferrsi/apps/workflows/search_benchmarks.py @@ -16,7 +16,7 @@ from inferrsi.harness import candidates, task_protocol from inferrsi.harness.artifact_primitives import digest, sha256 from inferrsi.harness.atomic_json import atomic_write_json -from inferrsi.harness.optimization_session import runtime_environment +from inferrsi.harness.executor import runtime_environment from inferrsi.harness.trials.external import execute_trial diff --git a/src/inferrsi/apps/workflows/speculative_search.py b/src/inferrsi/apps/workflows/speculative_search.py index 76783d3f1..cd39bef80 100644 --- a/src/inferrsi/apps/workflows/speculative_search.py +++ b/src/inferrsi/apps/workflows/speculative_search.py @@ -1,171 +1,53 @@ -"""CLI composition for the supported packaged Engine VATS/GVO profile.""" +"""Connect the Engine CLI, role checkpoint and packaged evaluator to Harness.""" import json -import time -from dataclasses import asdict, replace from inferrsi.apps.workflows.search_roles import Snapshot -from inferrsi.harness import candidates, search_tree -from inferrsi.harness.artifact_primitives import digest from inferrsi.harness.atomic_json import atomic_write_json -from inferrsi.harness.run_store import RunStore, RunStoreReader -from inferrsi.harness.search_adapter import ArtifactAdapter, Edit -from inferrsi.harness.search_campaign import ( - FinalAcceptance, - collect_group, - finalize, - learn, - qualify_root, -) -from inferrsi.harness.search_records import decode -from inferrsi.harness.vats import Settings -from inferrsi.harness.work_control import WorkControl +from inferrsi.harness.manager import EngineSearchPlan, read_engine_search, run_engine_search def command(args): - root = args.session.resolve() if args.search_action != "engine": - location = json.loads((root / "control.json").read_text(encoding="utf-8")) - control = WorkControl(RunStoreReader(location["store"], "speculative")) - result = control.read(location["campaign"]) + result = read_engine_search(args.session) if args.search_action == "export": atomic_write_json(args.output, result) return result + from .search_benchmarks import EngineEvaluator - acceptance = FinalAcceptance(minimum_objective=args.minimum_final_score) - if root.exists(): - raise ValueError("Use a new session directory; status/export never restart work") - if args.groups < 2 or args.rounds < 1: - raise ValueError("GVO needs at least two independent searches and one training round") - if args.final_reserve_seconds < args.evaluation_seconds: - raise ValueError("Final reserve must cover the full evaluation cap") - required = ( - args.evaluation_seconds - + args.final_reserve_seconds - + (args.groups * args.rounds + 2) * args.search_seconds - + args.rounds * args.training_seconds - ) - if args.max_seconds < required: - raise ValueError( - "Campaign cap must fund qualification, all search groups, training and final" - ) - snapshot = Snapshot(**json.loads(args.checkpoint.read_text(encoding="utf-8"))) - if ( - len(snapshot.drafter) != len(args.edit) - or len(snapshot.policy) != 8 - or len(snapshot.scorer) != 8 - ): - raise ValueError( - "Checkpoint needs one Drafter weight per edit and eight Policy/Scorer weights" - ) - settings = Settings( - args.steps, - 1, - args.depth, - args.targets, - args.candidates, - args.plans, - args.preparation_seconds * 1000, - args.draft_seconds * 1000, - args.search_seconds * 1000, - ) - root.mkdir(parents=True) - evaluator = EngineEvaluator( - args.task, root / "frozen", arguments=args.arguments, python=args.python - ) - adapter = ArtifactAdapter( - root / "artifacts", - (Edit(*raw) for raw in args.edit), - {"evaluation": args.evaluation_seconds * 1000}, - evaluator, + plan = EngineSearchPlan( + campaign=args.campaign, + task=args.task, domain=args.domain, - ) - source = root / "initial" - source.mkdir() - candidates.retain(root / "frozen/baseline.py", source / "candidate.py") - node = adapter.import_root(source, snapshot=digest(snapshot.document()), context={}) - control = WorkControl(RunStore(args.store.resolve(), "speculative")) - campaign = args.campaign - atomic_write_json( - root / "control.json", {"store": str(args.store.resolve()), "campaign": campaign} - ) - specification = { - "adapter": adapter.identity, - "settings": asdict(settings), - "groups": args.groups, - "rounds": args.rounds, - "mode": args.mode, - "learning_rate": args.learning_rate, - "minimum_final_score": acceptance.minimum_objective, - "initial_snapshot": snapshot.document(), - } - contract = search_tree.Contract( - "qualification", - search_tree.Context( - digest(specification), - digest(specification), - evaluator.identity, - args.domain, - args.task, - node.artifact_digest, - evaluator.identity, - ), - digest(snapshot.document()), - ("evaluation",), - "evaluation", - "maximize", - args.candidates, - args.depth, - args.attempts, - ) - control.create( - campaign, - specification, - {"searches": {}, "checkpoint": snapshot.document(), "stable": asdict(node)}, - cap_ms=args.max_seconds * 1000, - final_reserve_ms=args.final_reserve_seconds * 1000, - deadline=time.time() + args.max_seconds, - ) - initial = qualify_root(control, campaign, adapter, node, contract) - trained = learn( - control, - campaign, - adapter, - initial, - snapshot, - settings, + edits=tuple(tuple(edit) for edit in args.edit), + max_seconds=args.max_seconds, + evaluation_seconds=args.evaluation_seconds, + final_reserve_seconds=args.final_reserve_seconds, + search_seconds=args.search_seconds, + preparation_seconds=args.preparation_seconds, + draft_seconds=args.draft_seconds, + training_seconds=args.training_seconds, + candidates=args.candidates, + depth=args.depth, + attempts=args.attempts, + steps=args.steps, + plans=args.plans, + targets=args.targets, + groups=args.groups, rounds=args.rounds, - group_size=args.groups, - training_cap_ms=args.training_seconds * 1000, learning_rate=args.learning_rate, seed=args.seed, mode=args.mode, + final_scope=args.final_scope, + minimum_final_score=args.minimum_final_score, + ) + return run_engine_search( + plan, + session=args.session, + store=args.store, + load_snapshot=lambda: Snapshot(**json.loads(args.checkpoint.read_text(encoding="utf-8"))), + prepare_evaluator=lambda frozen: EngineEvaluator( + args.task, frozen, arguments=args.arguments, python=args.python + ), ) - # A fresh post-update search demonstrates the new frozen checkpoint. Selection - # is development-only, and never uses final results to choose another version. - records = collect_group( - control, - campaign, - adapter, - initial, - trained, - settings, - group_id="deployment", - size=2, - seed=args.seed, - collect=False, - ) - states = [decode(record["tree"]) for record in records] - selected_state = max(states, key=search_tree.verified_gain) - selected = replace(search_tree.accept(selected_state), parent_id=None) - finalize( - control, - campaign, - adapter, - selected, - deployment_search=selected_state.contract.search_id, - holdout_scope=args.final_scope, - acceptance=acceptance, - ) - return control.read(campaign) diff --git a/src/inferrsi/harness/README.md b/src/inferrsi/harness/README.md index a5377dc33..04d85417f 100644 --- a/src/inferrsi/harness/README.md +++ b/src/inferrsi/harness/README.md @@ -21,13 +21,17 @@ measurement and assessment rules. their operations in a subprocess with source hash and response checks. - [`skill_evaluation.py`](skill_evaluation.py) executes and retains skill-evaluation trials. [`artifact_sandbox.py`](artifact_sandbox.py) captures - and replays submitted artifacts. [`improvement.py`](improvement.py) advances - search using injected assessments. -- [`vats.py`](vats.py) selects candidate edits and verification jobs. - [`search_campaign.py`](search_campaign.py) coordinates VATS, GVO updates, - and final evaluation. [`work_control.py`](work_control.py) persists claims, - receipts and budget accounting in the shared RunStore. See the - [speculative search design](../../../docs/guides/speculative-search.md) for recovery rules. + and replays submitted artifacts. +- [Manager](manager/__init__.py) exposes `EngineSearchPlan`, `run_engine_search` + and `read_engine_search`. It checks the budget before starting a search. + Its [improvement loop](manager/search/improvement.py) uses injected assessments. + [VATS](manager/search/vats.py) selects edits and verification jobs. The + [search campaign](manager/search/search_campaign.py) coordinates GVO updates + and final evaluation, and [work control](manager/search/work_control.py) + records claims, receipts and budget use in the RunStore. + See the [speculative search design](../../../docs/guides/speculative-search.md) for recovery rules. +- [Executor](executor/__init__.py) supplies `runtime_environment` so that child + processes use the same InferRSI installation as their parent. ## Managed optimization loop diff --git a/src/inferrsi/harness/executor/__init__.py b/src/inferrsi/harness/executor/__init__.py new file mode 100644 index 000000000..6b1cbc459 --- /dev/null +++ b/src/inferrsi/harness/executor/__init__.py @@ -0,0 +1,20 @@ +"""The process environment shared by Harness execution paths.""" + +import os +import sys +from importlib.resources import files +from pathlib import Path + + +def runtime_environment() -> dict[str, str]: + """Return a child environment bound to this InferRSI installation.""" + environment = dict(os.environ) + # Children use the same installed/runtime bundle as this process, including + # when a different editable installation is present in site-packages. + import_paths = [str(Path(str(files("inferrsi"))).resolve().parent)] + if inherited := environment.get("PYTHONPATH"): + import_paths.append(inherited) + environment["PYTHONPATH"] = os.pathsep.join(import_paths) + if sys.dont_write_bytecode: + environment["PYTHONDONTWRITEBYTECODE"] = "1" + return environment diff --git a/src/inferrsi/harness/manager/__init__.py b/src/inferrsi/harness/manager/__init__.py new file mode 100644 index 000000000..3a77f0ba0 --- /dev/null +++ b/src/inferrsi/harness/manager/__init__.py @@ -0,0 +1,5 @@ +"""Manage Harness session progression and search budgets.""" + +from .search._engine import EngineSearchPlan, read_engine_search, run_engine_search + +__all__ = ["EngineSearchPlan", "read_engine_search", "run_engine_search"] diff --git a/src/inferrsi/harness/manager/search/__init__.py b/src/inferrsi/harness/manager/search/__init__.py new file mode 100644 index 000000000..09d0c9110 --- /dev/null +++ b/src/inferrsi/harness/manager/search/__init__.py @@ -0,0 +1 @@ +"""Candidate search, verification planning and budget accounting.""" diff --git a/src/inferrsi/harness/manager/search/_engine.py b/src/inferrsi/harness/manager/search/_engine.py new file mode 100644 index 000000000..be669df8b --- /dev/null +++ b/src/inferrsi/harness/manager/search/_engine.py @@ -0,0 +1,221 @@ +"""Admission, candidate selection and final validation for a bounded Engine search.""" + +import json +import time +from dataclasses import asdict, dataclass, replace +from pathlib import Path + + +@dataclass(frozen=True, kw_only=True) +class EngineSearchPlan: + """Inputs frozen by the caller before starting an independent search campaign.""" + + campaign: str + task: str + domain: str + edits: tuple[tuple[str, str, str, str], ...] + max_seconds: int + evaluation_seconds: int + final_reserve_seconds: int + search_seconds: int + preparation_seconds: int + draft_seconds: int + training_seconds: int + candidates: int + depth: int + attempts: int + steps: int + plans: int + targets: int + groups: int + rounds: int + learning_rate: float + seed: int + mode: str + final_scope: str + minimum_final_score: int | float + + def __post_init__(self): + for field in ( + "max_seconds", "evaluation_seconds", "final_reserve_seconds", "search_seconds", + "preparation_seconds", "draft_seconds", "training_seconds", "candidates", + "depth", "attempts", "steps", "plans", "targets", "groups", "rounds", + ): + value = getattr(self, field) + if type(value) is not int or value <= 0: + raise ValueError(f"{field} must be a positive integer") + + +def read_engine_search(session: Path) -> dict: + """Read the durable campaign snapshot through a read-only store.""" + from inferrsi.harness.run_store import RunStoreReader + + from .work_control import WorkControl + + location = json.loads((session.resolve() / "control.json").read_text(encoding="utf-8")) + control = WorkControl(RunStoreReader(location["store"], "speculative")) + return control.read(location["campaign"]) + + +def run_engine_search( + plan: EngineSearchPlan, *, session: Path, store: Path, load_snapshot, prepare_evaluator +) -> dict: + """Admit the plan, train and select using development evidence, then verify the winner. + + Apps supplies a snapshot loader and an evaluator factory. The factory receives the + frozen-input directory and retains the baseline there after budget admission. + """ + from inferrsi.harness import candidates + from inferrsi.harness.artifact_primitives import digest + from inferrsi.harness.atomic_json import atomic_write_json + from inferrsi.harness.run_store import RunStore + + from . import search_tree + from .search_adapter import ArtifactAdapter, Edit + from .search_campaign import ( + FinalAcceptance, + collect_group, + finalize, + learn, + qualify_root, + ) + from .search_records import decode + from .vats import Settings + from .work_control import WorkControl + + root = session.resolve() + store = store.resolve() + acceptance = FinalAcceptance(minimum_objective=plan.minimum_final_score) + if root.exists(): + raise ValueError("Use a new session directory; status/export never restart work") + if plan.groups < 2: + raise ValueError("GVO needs at least two independent searches and one training round") + if plan.final_reserve_seconds < plan.evaluation_seconds: + raise ValueError("Final reserve must cover the full evaluation cap") + required = ( + plan.evaluation_seconds + + plan.final_reserve_seconds + + (plan.groups * plan.rounds + 2) * plan.search_seconds + + plan.rounds * plan.training_seconds + ) + if plan.max_seconds < required: + raise ValueError( + "Campaign cap must fund qualification, all search groups, training and final" + ) + snapshot = load_snapshot() + if ( + len(snapshot.drafter) != len(plan.edits) + or len(snapshot.policy) != 8 + or len(snapshot.scorer) != 8 + ): + raise ValueError( + "Checkpoint needs one Drafter weight per edit and eight Policy/Scorer weights" + ) + settings = Settings( + plan.steps, + 1, + plan.depth, + plan.targets, + plan.candidates, + plan.plans, + plan.preparation_seconds * 1000, + plan.draft_seconds * 1000, + plan.search_seconds * 1000, + ) + root.mkdir(parents=True) + evaluator = prepare_evaluator(root / "frozen") + adapter = ArtifactAdapter( + root / "artifacts", + (Edit(*raw) for raw in plan.edits), + {"evaluation": plan.evaluation_seconds * 1000}, + evaluator, + domain=plan.domain, + ) + source = root / "initial" + source.mkdir() + candidates.retain(root / "frozen/baseline.py", source / "candidate.py") + node = adapter.import_root(source, snapshot=digest(snapshot.document()), context={}) + control = WorkControl(RunStore(store, "speculative")) + campaign = plan.campaign + atomic_write_json( + root / "control.json", {"store": str(store), "campaign": campaign} + ) + specification = { + "adapter": adapter.identity, + "settings": asdict(settings), + "groups": plan.groups, + "rounds": plan.rounds, + "mode": plan.mode, + "learning_rate": plan.learning_rate, + "minimum_final_score": acceptance.minimum_objective, + "initial_snapshot": snapshot.document(), + } + contract = search_tree.Contract( + "qualification", + search_tree.Context( + digest(specification), + digest(specification), + evaluator.identity, + plan.domain, + plan.task, + node.artifact_digest, + evaluator.identity, + ), + digest(snapshot.document()), + ("evaluation",), + "evaluation", + "maximize", + plan.candidates, + plan.depth, + plan.attempts, + ) + control.create( + campaign, + specification, + {"searches": {}, "checkpoint": snapshot.document(), "stable": asdict(node)}, + cap_ms=plan.max_seconds * 1000, + final_reserve_ms=plan.final_reserve_seconds * 1000, + deadline=time.time() + plan.max_seconds, + ) + initial = qualify_root(control, campaign, adapter, node, contract) + trained = learn( + control, + campaign, + adapter, + initial, + snapshot, + settings, + rounds=plan.rounds, + group_size=plan.groups, + training_cap_ms=plan.training_seconds * 1000, + learning_rate=plan.learning_rate, + seed=plan.seed, + mode=plan.mode, + ) + # A fresh post-update search demonstrates the new frozen checkpoint. Selection + # is development-only, and never uses final results to choose another version. + records = collect_group( + control, + campaign, + adapter, + initial, + trained, + settings, + group_id="deployment", + size=2, + seed=plan.seed, + collect=False, + ) + states = [decode(record["tree"]) for record in records] + selected_state = max(states, key=search_tree.verified_gain) + selected = replace(search_tree.accept(selected_state), parent_id=None) + finalize( + control, + campaign, + adapter, + selected, + deployment_search=selected_state.contract.search_id, + holdout_scope=plan.final_scope, + acceptance=acceptance, + ) + return control.read(campaign) diff --git a/src/inferrsi/harness/gvo.py b/src/inferrsi/harness/manager/search/gvo.py similarity index 99% rename from src/inferrsi/harness/gvo.py rename to src/inferrsi/harness/manager/search/gvo.py index ef802256d..98cfb6144 100644 --- a/src/inferrsi/harness/gvo.py +++ b/src/inferrsi/harness/manager/search/gvo.py @@ -5,7 +5,8 @@ import uuid from dataclasses import replace -from .artifact_primitives import digest +from inferrsi.harness.artifact_primitives import digest + from .search_records import decode, initial_conditions diff --git a/src/inferrsi/harness/improvement.py b/src/inferrsi/harness/manager/search/improvement.py similarity index 100% rename from src/inferrsi/harness/improvement.py rename to src/inferrsi/harness/manager/search/improvement.py diff --git a/src/inferrsi/harness/search_adapter.py b/src/inferrsi/harness/manager/search/search_adapter.py similarity index 97% rename from src/inferrsi/harness/search_adapter.py rename to src/inferrsi/harness/manager/search/search_adapter.py index 965b6c78e..87761c403 100644 --- a/src/inferrsi/harness/search_adapter.py +++ b/src/inferrsi/harness/manager/search/search_adapter.py @@ -13,14 +13,14 @@ from pathlib import Path, PureWindowsPath from inferrsi.contracts.claim import Verdict +from inferrsi.harness import candidates +from inferrsi.harness.artifact_primitives import digest, sha256 +from inferrsi.harness.atomic_json import atomic_write_json +from inferrsi.harness.executor import runtime_environment +from inferrsi.harness.trials.external import execute_trial -from . import candidates from . import search_tree as tree -from .artifact_primitives import digest, sha256 -from .atomic_json import atomic_write_json -from .optimization_session import runtime_environment from .search_records import encode -from .trials.external import execute_trial from .verification_plans import Job diff --git a/src/inferrsi/harness/search_campaign.py b/src/inferrsi/harness/manager/search/search_campaign.py similarity index 99% rename from src/inferrsi/harness/search_campaign.py rename to src/inferrsi/harness/manager/search/search_campaign.py index 8f897f368..66c098886 100644 --- a/src/inferrsi/harness/search_campaign.py +++ b/src/inferrsi/harness/manager/search/search_campaign.py @@ -5,9 +5,9 @@ from dataclasses import asdict, dataclass, replace from inferrsi.contracts.claim import Verdict +from inferrsi.harness.artifact_primitives import digest from . import search_tree as tree -from .artifact_primitives import digest from .gvo import train_group from .search_adapter import development_binding, validate_development_evidence from .search_records import decode, encode, initial_conditions diff --git a/src/inferrsi/harness/search_continuations.py b/src/inferrsi/harness/manager/search/search_continuations.py similarity index 99% rename from src/inferrsi/harness/search_continuations.py rename to src/inferrsi/harness/manager/search/search_continuations.py index 533a76686..28fcc8f1d 100644 --- a/src/inferrsi/harness/search_continuations.py +++ b/src/inferrsi/harness/manager/search/search_continuations.py @@ -5,7 +5,8 @@ import time from dataclasses import asdict, replace -from .artifact_primitives import digest +from inferrsi.harness.artifact_primitives import digest + from .search_records import decode, encode from .vats import Action, Search diff --git a/src/inferrsi/harness/search_records.py b/src/inferrsi/harness/manager/search/search_records.py similarity index 100% rename from src/inferrsi/harness/search_records.py rename to src/inferrsi/harness/manager/search/search_records.py diff --git a/src/inferrsi/harness/search_tree.py b/src/inferrsi/harness/manager/search/search_tree.py similarity index 100% rename from src/inferrsi/harness/search_tree.py rename to src/inferrsi/harness/manager/search/search_tree.py diff --git a/src/inferrsi/harness/vats.py b/src/inferrsi/harness/manager/search/vats.py similarity index 99% rename from src/inferrsi/harness/vats.py rename to src/inferrsi/harness/manager/search/vats.py index 59155ce4f..c73e0b646 100644 --- a/src/inferrsi/harness/vats.py +++ b/src/inferrsi/harness/manager/search/vats.py @@ -12,8 +12,9 @@ from dataclasses import asdict, dataclass, replace from itertools import combinations +from inferrsi.harness.artifact_primitives import digest + from . import search_tree as tree -from .artifact_primitives import digest from .search_adapter import development_binding, validate_development_evidence from .search_records import decode, encode, initial_conditions from .verification_plans import completion_menu diff --git a/src/inferrsi/harness/verification_plans.py b/src/inferrsi/harness/manager/search/verification_plans.py similarity index 100% rename from src/inferrsi/harness/verification_plans.py rename to src/inferrsi/harness/manager/search/verification_plans.py diff --git a/src/inferrsi/harness/work_control.py b/src/inferrsi/harness/manager/search/work_control.py similarity index 99% rename from src/inferrsi/harness/work_control.py rename to src/inferrsi/harness/manager/search/work_control.py index 88f12c2eb..7e5b057fe 100644 --- a/src/inferrsi/harness/work_control.py +++ b/src/inferrsi/harness/manager/search/work_control.py @@ -11,8 +11,8 @@ import time from contextlib import contextmanager -from .artifact_primitives import digest, file_lock -from .run_store import _transaction +from inferrsi.harness.artifact_primitives import digest, file_lock +from inferrsi.harness.run_store import _transaction def _json(value): diff --git a/src/inferrsi/harness/optimization_session.py b/src/inferrsi/harness/optimization_session.py index 5cab96bf7..8ff720cb4 100644 --- a/src/inferrsi/harness/optimization_session.py +++ b/src/inferrsi/harness/optimization_session.py @@ -16,19 +16,6 @@ from pathlib import Path -def runtime_environment() -> dict: - environment = dict(os.environ) - # Children use the same installed/runtime bundle as this process, including - # when a different editable installation is present in site-packages. - import_paths = [str(Path(str(files("inferrsi"))).resolve().parent)] - if inherited := environment.get("PYTHONPATH"): - import_paths.append(inherited) - environment["PYTHONPATH"] = os.pathsep.join(import_paths) - if sys.dont_write_bytecode: - environment["PYTHONDONTWRITEBYTECODE"] = "1" - return environment - - def _session_execute(root, directory, plan, deadline): from inferrsi.harness.task_protocol import run as run_protocol from inferrsi.harness.trials.external import execute_trial diff --git a/src/inferrsi/harness/project_service.py b/src/inferrsi/harness/project_service.py index c1bcde2d3..2859c0ea2 100644 --- a/src/inferrsi/harness/project_service.py +++ b/src/inferrsi/harness/project_service.py @@ -659,8 +659,8 @@ def proven_capture_elapsed(root, pending, execution): def execute(root, directory, plan, pending, deadline): """One retained attempt, one owned service, ordered client stages, no silent retry.""" + from .executor import runtime_environment from .local_process import supervised_service - from .optimization_session import runtime_environment from .trials.external import execute_trial settings = plan["evaluation_settings"] diff --git a/tests/apps/test_search_benchmarks.py b/tests/apps/test_search_benchmarks.py index a17021cd2..3ae7cfadd 100644 --- a/tests/apps/test_search_benchmarks.py +++ b/tests/apps/test_search_benchmarks.py @@ -13,20 +13,22 @@ 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 import candidates from inferrsi.harness.artifact_primitives import digest -from inferrsi.harness.run_store import RunStore -from inferrsi.harness.search_adapter import ArtifactAdapter, Edit -from inferrsi.harness.search_campaign import ( +from inferrsi.harness.manager import EngineSearchPlan, read_engine_search, run_engine_search +from inferrsi.harness.manager.search.search_adapter import ArtifactAdapter, Edit +from inferrsi.harness.manager.search.search_campaign import ( FinalAcceptance, finalize, import_qualified_root, learn, qualify_root, ) +from inferrsi.harness.manager.search.vats import Search, Settings +from inferrsi.harness.manager.search.work_control import WorkControl +from inferrsi.harness.run_store import RunStore from inferrsi.harness.task_protocol import TaskProtocolError from inferrsi.harness.trials.external import execute_trial -from inferrsi.harness.vats import Search, Settings -from inferrsi.harness.work_control import WorkControl from tests.fixtures.speculative_search import contract @@ -98,11 +100,87 @@ def test_cli_requires_explicit_shared_store_and_read_commands_do_not_create_one( parser().parse_args(["search", "engine", "--session", str(tmp_path / "run")]) +def engine_args(tmp_path, floor, *, cap=120, reserve=3, training=2): + return parser().parse_args([ + "search", "engine", "--session", str(tmp_path / "session"), + "--store", str(tmp_path / "store"), "--campaign", "cpu", "--task", "cpu", + "--domain", "local", "--checkpoint", str(tmp_path / "initial.json"), + "--edit", "increase", "candidate.py", "value = 1", "value = 2", "--max-seconds", str(cap), + "--evaluation-seconds", "2", "--final-reserve-seconds", str(reserve), + "--search-seconds", "15", + "--preparation-seconds", "1", "--draft-seconds", "1", "--training-seconds", str(training), + "--candidates", "2", "--depth", "1", "--attempts", "2", "--steps", "2", "--plans", "2", + "--targets", "1", "--groups", "2", "--rounds", "1", "--learning-rate", "0.01", + "--final-scope", "held", "--minimum-final-score", floor, + ]) + + +def engine_plan(floor, *, cap=120, reserve=3): + return EngineSearchPlan( + campaign="cpu", task="cpu", domain="local", + edits=(("increase", "candidate.py", "value = 1", "value = 2"),), + max_seconds=cap, evaluation_seconds=2, final_reserve_seconds=reserve, + search_seconds=15, preparation_seconds=1, draft_seconds=1, training_seconds=2, + candidates=2, depth=1, attempts=2, steps=2, plans=2, targets=1, + groups=2, rounds=1, learning_rate=0.01, seed=0, mode="reset", + final_scope="held", minimum_final_score=floor, + ) + + +@pytest.mark.parametrize( + ("cap", "reserve", "error"), + [(66, 3, "Campaign cap must fund"), (120, 1, "Final reserve must cover")], +) +def test_engine_admission_precedes_checkpoint_and_store_creation(tmp_path, cap, reserve, error): + def unexpected(*args): + pytest.fail("the rejected plan touched its checkpoint or evaluator") + + with pytest.raises(ValueError, match=error): + command(engine_args(tmp_path, "1", cap=cap, reserve=reserve)) + with pytest.raises(ValueError, match=error): + run_engine_search( + engine_plan(1, cap=cap, reserve=reserve), session=tmp_path / "direct", + store=tmp_path / "direct-store", load_snapshot=unexpected, prepare_evaluator=unexpected, + ) + assert not list(tmp_path.iterdir()) + + +def test_negative_training_time_cannot_fund_search(tmp_path): + with pytest.raises(ValueError, match="training_seconds"): + command(engine_args(tmp_path, "1", cap=64, training=-1)) + with pytest.raises(ValueError, match="training_seconds"): + run_engine_search( + replace(engine_plan(1, cap=64), training_seconds=-1), + session=tmp_path / "direct", store=tmp_path / "store", + load_snapshot=lambda: pytest.fail("loaded checkpoint"), + prepare_evaluator=lambda path: pytest.fail("created evaluator"), + ) + assert not list(tmp_path.iterdir()) + + +@pytest.mark.parametrize(("field", "value"), [ + ("max_seconds", True), ("evaluation_seconds", 0), ("final_reserve_seconds", 2.5), + ("search_seconds", -1), ("preparation_seconds", False), ("draft_seconds", 0), + ("training_seconds", 0), ("groups", 2.5), ("rounds", True), ("attempts", 0), +]) +def test_invalid_engine_limits_are_rejected_before_io(tmp_path, field, value): + with pytest.raises(ValueError, match=field): + run_engine_search( + replace(engine_plan(1), **{field: value}), + session=tmp_path / "session", store=tmp_path / "store", + load_snapshot=lambda: pytest.fail("loaded checkpoint"), + prepare_evaluator=lambda path: pytest.fail("created evaluator"), + ) + assert not list(tmp_path.iterdir()) + + @pytest.mark.parametrize( ("floor", "expected", "promoted"), [("9007199254740992", 2**53, True), ("9.007199254740993e15", 2**53 + 1, False)], ) def test_engine_cli_freezes_exact_final_score(tmp_path, monkeypatch, floor, expected, promoted): + holdout_candidates = [] + class Evaluator: identity = "cpu-score-fixture" @@ -111,6 +189,8 @@ def __init__(self, task, frozen, **kwargs): (frozen / "baseline.py").write_text("value = 1") def evaluate(self, candidate, check, output, deadline): + if output.name.startswith("final-"): + holdout_candidates.append(candidates.identity(candidate)) output.mkdir(parents=True) return {"verdict": "PASS", "objective": 2**53, "cleanup_verified": True} @@ -118,22 +198,26 @@ def evaluate(self, candidate, check, output, deadline): checkpoint = tmp_path / "initial.json" checkpoint.write_text(json.dumps(Snapshot((0,), (0,) * 8, (0,) * 8, "fixture").document())) session = str(tmp_path / "session") - args = parser().parse_args([ - "search", "engine", "--session", session, "--store", str(tmp_path / "store"), - "--campaign", "cpu", "--task", "cpu", "--domain", "local", "--checkpoint", str(checkpoint), - "--edit", "increase", "candidate.py", "value = 1", "value = 2", "--max-seconds", "120", - "--evaluation-seconds", "2", "--final-reserve-seconds", "3", "--search-seconds", "15", - "--preparation-seconds", "1", "--draft-seconds", "1", "--training-seconds", "2", - "--candidates", "2", "--depth", "1", "--attempts", "2", "--steps", "2", "--plans", "2", - "--targets", "1", "--groups", "2", "--rounds", "1", "--learning-rate", "0.01", - "--final-scope", "held", "--minimum-final-score", floor, - ]) - command(args) + + command(engine_args(tmp_path, floor)) saved = command(parser().parse_args(["search", "status", "--session", session])) binding = saved["final_claim"]["binding"] assert binding["acceptance"] == {"version": 1, "minimum_objective": expected} assert binding["objective_check"] == "evaluation" assert saved["final_result"]["promoted"] is promoted + winner = binding["candidate"]["artifact_digest"] + assert holdout_candidates == [winner] + + direct_session = tmp_path / "direct" + direct = run_engine_search( + engine_plan(expected), session=direct_session, store=tmp_path / "direct-store", + load_snapshot=lambda: Snapshot(**json.loads(checkpoint.read_text())), + prepare_evaluator=lambda frozen: Evaluator("cpu", frozen), + ) + assert direct == read_engine_search(direct_session) + assert direct["final_claim"]["binding"]["candidate"]["artifact_digest"] == winner + assert direct["final_result"]["promoted"] is promoted + assert holdout_candidates == [winner, winner] def test_engine_rejects_frozen_resource_mutation_during_evaluation(tmp_path, monkeypatch): diff --git a/tests/campaigns/test_qwen_gvo_diagnostic.py b/tests/campaigns/test_qwen_gvo_diagnostic.py index c17408b43..319199e0e 100644 --- a/tests/campaigns/test_qwen_gvo_diagnostic.py +++ b/tests/campaigns/test_qwen_gvo_diagnostic.py @@ -19,6 +19,16 @@ def module(relative): return result +def test_replay_driver_retains_its_original_promotion_contract(): + checker = module("validator/check.py") + current = checker.sha(BUNDLE / "plan/run.py") + assert checker.replay_requires_acceptance(current, current) + assert checker.replay_requires_acceptance(checker.PRE_MIGRATION_DRIVER_SHA256, current) + assert not checker.replay_requires_acceptance(checker.PREVIOUS_DRIVER_SHA256, current) + with pytest.raises(ValueError, match="Replay driver identity"): + checker.replay_requires_acceptance("0" * 64, current) + + @pytest.mark.parametrize("verdict,promoted", [("INCONCLUSIVE", False), ("PASS", False)]) def test_inner_pass_cannot_publish_failed_promotion(tmp_path, monkeypatch, verdict, promoted): driver = module("plan/run.py") diff --git a/tests/fixtures/speculative_search.py b/tests/fixtures/speculative_search.py index 104938206..ddc81d8c3 100644 --- a/tests/fixtures/speculative_search.py +++ b/tests/fixtures/speculative_search.py @@ -4,7 +4,7 @@ from hashlib import sha256 from inferrsi.contracts.claim import Verdict -from inferrsi.harness import search_tree as tree +from inferrsi.harness.manager.search import search_tree as tree def digest(text): diff --git a/tests/harness/test_harness_improvement.py b/tests/harness/test_harness_improvement.py index 149d261c1..2ed50b105 100644 --- a/tests/harness/test_harness_improvement.py +++ b/tests/harness/test_harness_improvement.py @@ -308,7 +308,7 @@ def test_policy_unknown_invalid_usage_and_quality_before_cost(): def test_rules_and_progression_meet_only_through_injected_values(): from inferrsi.benchmark import improvement as rules - from inferrsi.harness import improvement as progression + from inferrsi.harness.manager.search import improvement as progression report = {"status": {"execution_state": "completed"}, "pairs": [{ "case_id": "one", "repeat": 1, "outcome": "unchanged_correct", diff --git a/tests/harness/test_speculative_search.py b/tests/harness/test_speculative_search.py index ad686fbf0..9cebfb480 100644 --- a/tests/harness/test_speculative_search.py +++ b/tests/harness/test_speculative_search.py @@ -4,7 +4,7 @@ from inferrsi.contracts.claim import Verdict from inferrsi.harness import candidates -from inferrsi.harness import search_tree as tree +from inferrsi.harness.manager.search import search_tree as tree from tests.fixtures.speculative_search import ( add, attempt, diff --git a/tests/harness/test_vats_runtime.py b/tests/harness/test_vats_runtime.py index 47e3f1555..1a079efea 100644 --- a/tests/harness/test_vats_runtime.py +++ b/tests/harness/test_vats_runtime.py @@ -8,21 +8,21 @@ import pytest from inferrsi.apps.workflows.search_roles import Snapshot -from inferrsi.harness import search_tree as tree from inferrsi.harness.artifact_primitives import digest -from inferrsi.harness.gvo import examples, train_group -from inferrsi.harness.run_store import RunStore -from inferrsi.harness.search_adapter import ArtifactAdapter, CommandEvaluator, Edit -from inferrsi.harness.search_campaign import ( +from inferrsi.harness.manager.search import search_tree as tree +from inferrsi.harness.manager.search.gvo import examples, train_group +from inferrsi.harness.manager.search.search_adapter import ArtifactAdapter, CommandEvaluator, Edit +from inferrsi.harness.manager.search.search_campaign import ( FinalAcceptance, collect_group, finalize, import_qualified_root, qualify_root, ) -from inferrsi.harness.search_records import decode -from inferrsi.harness.vats import Search, Settings -from inferrsi.harness.work_control import WorkControl +from inferrsi.harness.manager.search.search_records import decode +from inferrsi.harness.manager.search.vats import Search, Settings +from inferrsi.harness.manager.search.work_control import WorkControl +from inferrsi.harness.run_store import RunStore from tests.fixtures.speculative_search import contract @@ -754,7 +754,8 @@ def no_adapter_access(*args): with pytest.raises(ValueError, match="awaits launch"): qualify(reopened) monkeypatch.setattr( - "inferrsi.harness.work_control.time.time", lambda: interrupted["deadline"] + 0.01 + "inferrsi.harness.manager.search.work_control.time.time", + lambda: interrupted["deadline"] + 0.01, ) if stage == "root": with pytest.raises(ValueError, match="did not start"): @@ -856,7 +857,7 @@ def expire(campaign, operation): doc["deadline"] if expire_campaign else doc["operations"][operation]["deadline"] ) monkeypatch.setattr( - "inferrsi.harness.work_control.time.time", lambda: deadline + 0.001 + "inferrsi.harness.manager.search.work_control.time.time", lambda: deadline + 0.001 ) if crash_before_launch: raise RuntimeError("interrupted before launch") @@ -991,7 +992,9 @@ def crash_after_intent(campaign, operation): with pytest.raises(RuntimeError, match="lost after launch intent"): search.run() before = control.read("campaign") - monkeypatch.setattr("inferrsi.harness.work_control.time.time", lambda: before["deadline"] + 1) + monkeypatch.setattr( + "inferrsi.harness.manager.search.work_control.time.time", lambda: before["deadline"] + 1 + ) with pytest.raises(ValueError, match="Unknown execution"): search.recover() assert control.read("campaign") == before @@ -1035,7 +1038,7 @@ def legacy(state): @pytest.mark.parametrize("change", ["receipt", "execution", "epoch"]) def test_initial_evidence_digest_ignores_only_receiving_ids(runtime, change): - from inferrsi.harness.search_campaign import import_qualified_root + from inferrsi.harness.manager.search.search_campaign import import_qualified_root control, adapter, snapshot, settings, root = runtime first = Search(control, "campaign", root.contract.search_id, snapshot, settings, adapter) @@ -1097,8 +1100,8 @@ def test_persisted_search_has_only_real_check_results(runtime): def test_paid_continuations_are_metered_matched_and_excluded_from_actors(runtime): - from inferrsi.harness.search_continuations import continue_from, paired_targets - from inferrsi.harness.vats import Action + from inferrsi.harness.manager.search.search_continuations import continue_from, paired_targets + from inferrsi.harness.manager.search.vats import Action control, adapter, snapshot, settings, root = runtime records = collect_group( @@ -1138,9 +1141,9 @@ def test_paid_continuations_are_metered_matched_and_excluded_from_actors(runtime def test_late_continuation_preserves_the_consumed_step_budget(runtime): - from inferrsi.harness.gvo import suffix_examples - from inferrsi.harness.search_continuations import continue_from - from inferrsi.harness.vats import Action + from inferrsi.harness.manager.search.gvo import suffix_examples + from inferrsi.harness.manager.search.search_continuations import continue_from + from inferrsi.harness.manager.search.vats import Action control, adapter, snapshot, settings, root = runtime settings = replace(settings, max_steps=2) @@ -1163,8 +1166,8 @@ def test_late_continuation_preserves_the_consumed_step_budget(runtime): def test_forced_accept_recovers_after_copy_without_dispatch(runtime, monkeypatch): - from inferrsi.harness.search_continuations import continue_from - from inferrsi.harness.vats import Action + from inferrsi.harness.manager.search.search_continuations import continue_from + from inferrsi.harness.manager.search.vats import Action control, adapter, snapshot, settings, root = runtime source = Search(control, "campaign", "search", snapshot, settings, adapter) @@ -1257,7 +1260,7 @@ def test_training_rejects_unretained_search_labels(runtime): @pytest.mark.parametrize("mode", ["reset", "carry"]) def test_outer_loop_resume_reuses_trained_checkpoints_and_frozen_roots(runtime, mode): - from inferrsi.harness.search_campaign import learn + from inferrsi.harness.manager.search.search_campaign import learn control, adapter, snapshot, settings, root = runtime settings = replace(settings, search_ms=10000, max_steps=3) diff --git a/tests/harness/test_verification_plans.py b/tests/harness/test_verification_plans.py index 3ca3a6d35..570eed143 100644 --- a/tests/harness/test_verification_plans.py +++ b/tests/harness/test_verification_plans.py @@ -4,8 +4,8 @@ import pytest from inferrsi.contracts.claim import Verdict -from inferrsi.harness import search_tree as tree -from inferrsi.harness.verification_plans import Job, completion_menu +from inferrsi.harness.manager.search import search_tree as tree +from inferrsi.harness.manager.search.verification_plans import Job, completion_menu from tests.fixtures.speculative_search import add, attempt, contract, observe, start diff --git a/tests/harness/test_work_control.py b/tests/harness/test_work_control.py index f08a26e2b..968866fe3 100644 --- a/tests/harness/test_work_control.py +++ b/tests/harness/test_work_control.py @@ -3,8 +3,8 @@ import pytest +from inferrsi.harness.manager.search.work_control import WorkControl from inferrsi.harness.run_store import RunStore -from inferrsi.harness.work_control import WorkControl @pytest.fixture @@ -145,7 +145,7 @@ def fail(state): def test_expired_claim_cannot_start_and_does_not_charge_unstarted_work(control, monkeypatch): claim(control) - monkeypatch.setattr("inferrsi.harness.work_control.time.time", lambda: 1e12) + monkeypatch.setattr("inferrsi.harness.manager.search.work_control.time.time", lambda: 1e12) with pytest.raises(ValueError, match="expired"): control.launch("campaign", "work") result = control.read("campaign") diff --git a/tests/repository/_gate_policy_support.py b/tests/repository/_gate_policy_support.py index 7d34112b1..f3837a44a 100644 --- a/tests/repository/_gate_policy_support.py +++ b/tests/repository/_gate_policy_support.py @@ -102,7 +102,22 @@ # so the two package names are retired as a whole. # #558 moved ``inferrsi.harness.scenarios`` to ``inferrsi.harness.trials``, with no # forwarder, so the old package name is retired as a whole too. -RETIRED_MODULES = frozenset({"inferrsi.infra", "inferrsi.model", "inferrsi.harness.scenarios"}) +# #702 moved the ten root-level search modules under the Manager. +RETIRED_MODULES = frozenset({ + "inferrsi.infra", + "inferrsi.model", + "inferrsi.harness.scenarios", + "inferrsi.harness.gvo", + "inferrsi.harness.improvement", + "inferrsi.harness.search_adapter", + "inferrsi.harness.search_campaign", + "inferrsi.harness.search_continuations", + "inferrsi.harness.search_records", + "inferrsi.harness.search_tree", + "inferrsi.harness.vats", + "inferrsi.harness.verification_plans", + "inferrsi.harness.work_control", +}) # #412 R1, permanent: the one importer of the neutral data leaf outside # ``inferrsi.knowledge``, with the only name it may bind (D020: Infra reads one pack # description and reaches no Knowledge or Harness). This is not a manifest @@ -126,13 +141,16 @@ # and an Apps module that names the leaf fails as a second importer like any other. # New H entries: module paths whose closures count toward the new-core result. # H01 added ``run_store`` and ``errors``; H02 added the public ``api`` with -# ``execution_service``, ``input_binding`` and ``local_process``. +# ``execution_service``, ``input_binding`` and ``local_process``. #702 adds +# each component's public package when its first entry moves. NEW_H_ENTRIES = ( "inferrsi.harness.api", "inferrsi.harness.errors", "inferrsi.harness.execution_service", + "inferrsi.harness.executor", "inferrsi.harness.input_binding", "inferrsi.harness.local_process", + "inferrsi.harness.manager", "inferrsi.harness.run_store", ) # Shared data/byte contracts (#451 C1). This exact module list is the whole package. A diff --git a/tests/repository/test_first_wave_isolation_policy.py b/tests/repository/test_first_wave_isolation_policy.py index 9f02aa391..a1f826fe5 100644 --- a/tests/repository/test_first_wave_isolation_policy.py +++ b/tests/repository/test_first_wave_isolation_policy.py @@ -1023,7 +1023,7 @@ def test_former_residual_edge_fails_for_its_importer_and_dependents(self) -> Non # and so does every harness module that reaches the leaf through it. tree = { "harness/skill_evaluation.py": "from ..knowledge_operations import KnowledgeReader\n", - "harness/improvement.py": "from . import skill_evaluation\n", + "harness/manager/search/improvement.py": "from ... import skill_evaluation\n", } report = _report(tree) self.assertIn( @@ -1032,8 +1032,8 @@ def test_former_residual_edge_fails_for_its_importer_and_dependents(self) -> Non report.violations, ) self.assertIn( - "inferrsi.harness.improvement reaches inferrsi.knowledge_operations: " - "inferrsi.harness.improvement -> inferrsi.harness.skill_evaluation" + "inferrsi.harness.manager.search.improvement reaches inferrsi.knowledge_operations: " + "inferrsi.harness.manager.search.improvement -> inferrsi.harness.skill_evaluation" " -> inferrsi.knowledge_operations", report.violations, ) @@ -1210,7 +1210,7 @@ def test_returning_skill_evaluation_infra_edge_fails(self) -> None: "infra/__init__.py": "", "infra/artifacts.py": "VALUE = 1\n", "harness/skill_evaluation.py": "from ..infra.artifacts import VALUE\n", - "harness/improvement.py": "from . import skill_evaluation\n", + "harness/manager/search/improvement.py": "from ... import skill_evaluation\n", } cleared = _report({}, manifest=EMPTY_ALLOWLIST, base=CLEARED_TREE) self.assertEqual(cleared.harness_model_infra, ()) @@ -1219,9 +1219,9 @@ def test_returning_skill_evaluation_infra_edge_fails(self) -> None: self.assertEqual( report.harness_model_infra, ( - "inferrsi.harness.improvement -> inferrsi.harness.skill_evaluation" + "inferrsi.harness.manager.search.improvement -> inferrsi.harness.skill_evaluation" " -> inferrsi.infra", - "inferrsi.harness.improvement -> inferrsi.harness.skill_evaluation" + "inferrsi.harness.manager.search.improvement -> inferrsi.harness.skill_evaluation" " -> inferrsi.infra.artifacts", "inferrsi.harness.skill_evaluation -> inferrsi.infra", "inferrsi.harness.skill_evaluation -> inferrsi.infra.artifacts", @@ -1230,7 +1230,7 @@ def test_returning_skill_evaluation_infra_edge_fails(self) -> None: self.assertEqual( report.blockers, ( - "harness reaches model/infra: inferrsi.harness.improvement -> " + "harness reaches model/infra: inferrsi.harness.manager.search.improvement -> " "inferrsi.harness.skill_evaluation -> inferrsi.infra (4 hits)", ), ) diff --git a/tests/repository/test_target_module_import_gate.py b/tests/repository/test_target_module_import_gate.py index 0fe9ccaa5..c76993f0f 100644 --- a/tests/repository/test_target_module_import_gate.py +++ b/tests/repository/test_target_module_import_gate.py @@ -198,6 +198,9 @@ def test_by_path_loading_is_admitted_nowhere_else(tmp_path, relative): "inferrsi.harness.scenarios.external"), ("harness/runner.py", "from .scenarios import external\n", "inferrsi.harness.scenarios.external"), + ("apps/runner.py", "from inferrsi.harness import search_tree\n", + "inferrsi.harness.search_tree"), + ("harness/runner.py", "from .gvo import examples\n", "inferrsi.harness.gvo"), ]) def test_retired_model_paths_fail_to_import(tmp_path, importer, source, target): report = _report(tmp_path, {importer: source}) @@ -235,6 +238,7 @@ def test_retired_model_paths_fail_from_a_package_initializer(tmp_path, importer, "infra/targets/git.py", "harness/scenarios/__init__.py", "harness/scenarios/external.py", + "harness/work_control.py", ]) def test_retired_model_files_fail_when_they_return(tmp_path, relative): report = _report(tmp_path, {relative: "VALUE = 1\n"}) @@ -301,6 +305,10 @@ def test_no_new_cross_core_imports(self) -> None: def test_first_wave_policy_holds_on_current_tree(self) -> None: self.assertEqual(first_wave_report().violations, ()) + def test_registered_harness_entries_are_present_in_the_import_graph(self) -> None: + graph = support._scan(ROOT, exact_pairs(load_manifest())) + self.assertEqual(set(support.NEW_H_ENTRIES) - graph.trees.keys(), set()) + def test_clean_scan_is_not_isolation(self) -> None: # Facts that hold at every stage. self.assertTrue((ROOT / "benchmark" / "registry.py").is_file()) @@ -384,12 +392,13 @@ def test_split_skill_eval_modules_reach_no_model_or_infra(self) -> None: report = first_wave_report() for name in ( "skill_evaluation", - "improvement", + "manager.search.improvement", "artifact_sandbox", "atomic_json", ): with self.subTest(module=name): - self.assertTrue((ROOT / "harness" / f"{name}.py").is_file()) + source = (ROOT / "harness").joinpath(*name.split(".")).with_suffix(".py") + self.assertTrue(source.is_file(), source) self.assertEqual( [ path diff --git a/tools/skill_eval_improve.py b/tools/skill_eval_improve.py index d6a858459..7d4e90243 100644 --- a/tools/skill_eval_improve.py +++ b/tools/skill_eval_improve.py @@ -28,7 +28,7 @@ CONTROLLERS = (*compare.CONTROLLERS, "tools/skill_eval_improve.py", "src/inferrsi/apps/workflows/improvement.py", "src/inferrsi/benchmark/improvement.py", - "src/inferrsi/harness/improvement.py") + "src/inferrsi/harness/manager/search/improvement.py") def frontmatter_prefix(data: bytes) -> bytes: diff --git a/tools/speculative_skill.py b/tools/speculative_skill.py index 14503bbd4..6960b9593 100644 --- a/tools/speculative_skill.py +++ b/tools/speculative_skill.py @@ -17,7 +17,7 @@ from inferrsi.harness import candidates from inferrsi.harness.artifact_primitives import digest, sha256 from inferrsi.harness.atomic_json import atomic_write_json -from inferrsi.harness.optimization_session import runtime_environment +from inferrsi.harness.executor import runtime_environment from inferrsi.harness.trials.external import execute_trial from inferrsi.knowledge.knowledge_operations import KnowledgeReader from tools import skill_eval_compare as compare