diff --git a/CHANGELOG.md b/CHANGELOG.md index 6384c20ae..9ed27046a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,11 +22,84 @@ ### Changed +- Import `run_session` and its operation-specific requests from `inferrsi.harness.manager`. + The former `inferrsi.harness.optimization_session.session_command` accepted parsed CLI + arguments. Python hosts now pass a request such as `StartProjectSession`, + `EvaluateSessionRound` or `SessionStatus` and supply the same ports as Apps. + For a retained plan, rounds and final assessment, use `manager.read_session_records` + in place of `inferrsi.harness.optimization.read_records`. + +- Import parallel round scheduling from `inferrsi.harness.manager`. The former + `inferrsi.harness.parallel_round` operations `prepare`, `submit`, `ticket_status`, + `serve_ticket` and `close_round` map to `prepare_parallel_round`, + `submit_parallel_ticket`, `parallel_ticket_status`, `serve_parallel_ticket` and + `close_parallel_round`. The command-line subcommands and persisted tickets keep their + existing names. + +- For native agent sessions, import `prepare_agent_session`, `bind_agent_session`, + `dispatch_agent_session`, `record_agent_session`, `agent_session_status` and + `AGENT_TERMINAL_STATES` from `inferrsi.harness.manager`. They replace `prepare`, + `bind`, `dispatch`, `record`, `status` and `TERMINAL` in `inferrsi.harness.agent_sessions`. +- Import `session_runtime_identity` from `inferrsi.harness.manager` to read the installed + source fingerprint used by ordinary sessions and benchmark comparisons. +- 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 `launch_server`, `stop_server`, `post_json` and `ImageProtocol` from + `inferrsi.harness.executor`. This replaces the published + `inferrsi.harness.serving.server` (launch and stop), `inferrsi.harness.serving.http` + (JSON transport) and `inferrsi.harness.serving.image` (image requests) modules. + Managed service callers import `prepare_service` and `execute_service_attempt` from + `inferrsi.harness.executor`, and `service_assessment` and `service_settlement_reason` + from `inferrsi.harness.evaluator`. The former `harness.project_service` and + `harness.service_evidence` modules have been removed. + +- 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. + - Apps module retirement (0.3.4). Use the [documented replacements](docs/apps-module-migrations.json). The public evaluation API remains at `inferrsi.apps.api`. See the [migration instructions](docs/guides/module-layout.md#apps-modules-and-retired-imports) for script entries, retained pickles and frozen runs. +- Harness storage clients now import `RunStore` and `RunStoreReader` from + `inferrsi.harness.records`. Import `request_digest` from + `inferrsi.harness.executor` and `PublicError`, `PartialExecutionFacts` and + `PUBLIC_ERROR_CODES` from `inferrsi.harness.api`. The former `harness.run_store`, + `harness.execution_spec` and `harness.errors` paths have been removed. Existing + store roots retain their namespace, object references and exact record versions. + +- Import `LocalCpuTarget` from `inferrsi.harness.executor`. Its former + `inferrsi.harness.api` entry was removed. Hosts continue to import `Harness` + from `inferrsi.harness.api`. +- Import `prepare_generation`, `read_prepared_binding`, `project_prepared_binding` + and `verify_prepared_binding` from `inferrsi.harness.executor`. These replace + `harness.generation.prepare_generation` and `harness.prepared_binding`'s + `read`, `project` and `verify`. They accept the same specs and artifact readers. +- Hosts execute a prepared spec through `Harness.execute` from `inferrsi.harness.api`. + The former `harness.execution_service`, `harness.entry_code`, `harness.input_binding` + and `harness.evidence_capture` implementations now live inside Executor. + The source modules `candidates`, `confinement`, `skill_evaluation` and `artifact_sandbox` + moved from `inferrsi.harness` to `inferrsi.harness.executor` with their in-tree callers. +- Service recovery uses `process_group_empty` from `inferrsi.harness.executor`. + Local process supervision, launch records and device leases live under + `harness.executor`; the three former root modules were removed. +- The external trial runner moved from `harness.trials.external` to + `harness.executor.trials.external` for apps that inject single-command trials. +- Import `Verdict` and `parse_verdict` from `inferrsi.contracts.claim`. + The former `inferrsi.harness` exports have been removed. + - `inferrsi benchmarks compare` keeps every attempt of an arm (Refs #509, P1.1). The new `--action retry --trial ` opens a fresh attempt with its own job and workspace after a collected, terminal attempt. The collected attempt stays as evidence, and no campaign is renamed. diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index 49ab68810..307564f92 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -228,7 +228,6 @@ "src/inferrsi/apps/cli/__init__.py", "src/inferrsi/apps/views/capture_delivery.py", "src/inferrsi/apps/views/optimization_story.py", - "src/inferrsi/harness/optimization_session.py", "tests/repository/check_installed.py", "tests/fixtures/dashboard_profile_review.py", "tests/fixtures/knowledge_retrieval.py", @@ -591,9 +590,9 @@ "src/inferrsi/apps/delivery/__init__.py", "src/inferrsi/apps/delivery/projection.py", "src/inferrsi/apps/delivery/snapshot.py", - "src/inferrsi/harness/artifact_primitives.py", - "src/inferrsi/harness/atomic_json.py", - "src/inferrsi/harness/input_binding.py", + "src/inferrsi/harness/records/artifact_primitives.py", + "src/inferrsi/harness/records/atomic_json.py", + "src/inferrsi/harness/executor/_input_binding.py", "tests/apps/test_anthropic_agent.py", "tests/apps/test_goal_checkpoint.py", "tests/apps/test_inspection.py", diff --git a/docs/architecture.md b/docs/architecture.md index f98d7dea2..13b50e323 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -11,27 +11,30 @@ and `apps/workflows/benchmark_operations.py` provide application assembly and la 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 +the first complete handoff for the Qwen task. `harness/manager/_state.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/manager/_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. Ordinary projects default to the current Agent conversation. The optional [service-reuse protocol](guides/service-reuse-campaigns.md) adds project -assessment and foreground service ownership within this same controller. Its -protocol and result rules live in `harness.project_service`, with process -lifetime managed by `local_process`. +assessment and foreground service ownership within this same controller. +Executor freezes the inputs, owns the foreground service and records stage receipts. +Evaluator checks the receipts and decides the next stage or formal verdict. Candidate +checkpoints retain that verdict before profiling and service cleanup. The [experimental speculative search](guides/speculative-search.md) composes immutable candidate trees, bounded completion menus, synchronous VATS and CPU GVO roles. Its work controller uses shared RunStore transactions and the existing local @@ -44,7 +47,7 @@ tool and retain the native identity and returned artifacts. The child owns the complete start/knowledge/round/final lifecycle; the parent observes and collects. This path records the handoff; it does not implement a background Agent CLI driver or a native-host deadline. -The application injects `harness.trials.external.execute_trial` into the +The application injects `harness.executor.trials.external.execute_trial` into the [two-rank MoE entry](benchmarks/moe-forward-benchmark.md). The standalone image benchmark and [TTS service protocol](benchmarks/tts-benchmark.md) expose their documented execution boundaries. Apps and Harness callers assemble these operations into optimization @@ -284,7 +287,7 @@ the [import gate](guides/module-layout.md#import-gate) for migration and depende | Add | Main extension locations | Required qualification | | --- | --- | --- | -| Model or scenario | `harness/serving`, `benchmark/metrics.py`, `benchmark/validators`; trials run through the model-independent `harness/trials/external.py` | Frozen request and metric contract; model-specific quality coverage | +| Model or scenario | `harness/executor/serving`, `benchmark/metrics.py`, `benchmark/validators`; trials run through the model-independent `harness/executor/trials/external.py` | Frozen request and metric contract; model-specific quality coverage | | Repository | `apps/host/targets`, a composed scenario, `resources/repo_packs` | Stable source identity; command/result contract; environment isolation | | Hardware | `apps/host/platforms` | Device selection, process exclusivity and independent backend/model evidence; a backend is registered in `apps/host/platforms/__init__.py` and its probe command is defined in the implementing module under `apps/host/platforms/`, not in package data | @@ -298,7 +301,7 @@ synthetic contract fixtures, not accelerator measurements. `apps.legacy.run.run_experiment(spec, environment, *, execute, snapshot)` composes the old run and accepts small callable adapters. It passes them, the Benchmark v0 -gates and the report to `harness.runner.run_experiment`, whose four ports +gates and the report to `harness.manager.run_experiment`, whose four ports (`execute`, `snapshot`, `assess`, `report`) have no defaults. An omitted `execute` or `snapshot` is read from `apps.legacy.run` when the run starts (`execute_trial` and `repository_identity`), which is the two-argument call @@ -332,7 +335,7 @@ float; `benchmark.legacy_run_v0.trial_metric` then applies the one finite, posit metric contract (`benchmark.metrics.validate_metric`) to whatever the reader returns, so a reader that yields `0.0`, a `bool` or a non-finite value records a metric error rather than entering the evaluation. The Harness executor -`harness.trials.external.execute_trial` holds no metric rule: a caller that +`harness.executor.trials.external.execute_trial` holds no metric rule: a caller that passes a metric key also passes `metric=`, its validation function. Run state is written by the termination path, never assumed. `status.json` @@ -380,12 +383,12 @@ change the AB/BA algorithm, process cleanup or evaluator. ## Compatibility and historical evidence -The supervised server helpers (`harness.serving.server.launch_server` / `stop_server`) +The supervised server helpers `launch_server` and `stop_server` in `inferrsi.harness.executor` require Linux with a readable `/proc` process table. They reject other platforms before launch; missing or inaccessible process enumeration raises an error rather than reporting successful cleanup. Workers must remain in their owned process group. Windows Job Object support in the general command executor -(`harness.local_process`) does not extend to these server helpers. These constraints do not restrict read-only knowledge +(`harness.executor.local_process`) does not extend to these server helpers. These constraints do not restrict read-only knowledge operations or the control CLI to Linux. - Existing CLI flags, external JSON metrics, run artifacts, cancellation diff --git a/docs/assets/modular-directory-map-en.svg b/docs/assets/modular-directory-map-en.svg index 4d4113b8d..100a0b224 100644 --- a/docs/assets/modular-directory-map-en.svg +++ b/docs/assets/modular-directory-map-en.svg @@ -26,9 +26,9 @@ harness/ - runner.py + manager/ AB/BA trials - local_process.py + executor/ Deadlines and cleanup records/ Campaign records and traces diff --git a/docs/benchmarks/moe-forward-benchmark.md b/docs/benchmarks/moe-forward-benchmark.md index 6e2e8a574..d4fc4cffc 100644 --- a/docs/benchmarks/moe-forward-benchmark.md +++ b/docs/benchmarks/moe-forward-benchmark.md @@ -47,7 +47,7 @@ inferrsi benchmarks run moe-forward-npu \ `--timeout-seconds` 都必须显式指定;两组配对为每实现每性能 case 16 个计时样本, 四组为 32 个。超时包括入口准备和执行,之后最多有额外的有界进程清理等待。 入口先冻结题目、候选和 grader 的副本及 SHA256,再通过现有 -由应用入口注入的 `harness.trials.external.execute_trial` 执行。 +由应用入口注入的 `harness.executor.trials.external.execute_trial` 执行。 该执行器不含 metric 规则,入口在传 metric key 的同时传入自己的校验函数 (`metric=read_metric`)。 Python 调用 `evaluate` 时须显式传入 `execute_trial`。它额外清理本次唯一环境标记的 diff --git a/docs/contracts/current-design.md b/docs/contracts/current-design.md index de7386493..37d769440 100644 --- a/docs/contracts/current-design.md +++ b/docs/contracts/current-design.md @@ -105,7 +105,7 @@ The corpus lives in `knowledge/data/skill_library/`. Target repository descripto Decision: see [`function-owners.md`](function-owners.md). Target new core layout: - K keeps the seven original file names. -- H: `api.py`, `execution_service.py`, `input_binding.py`, `run_store.py`, `budget.py`, `resources.py`, `records/*`. +- H: `api/`, `execution_service.py`, `input_binding.py`, `budget.py`, `resources.py`, `records/*`. - B: `api.py`, `evaluation.py`, `legacy_run_v0.py`, `sampling.py`, `tasks/*`, `workers/*`, `validators/*`. - Apps: `bridge.py`, `archive.py`, `result.py`, and `views/legacy`. diff --git a/docs/contracts/function-owners.md b/docs/contracts/function-owners.md index 5d81756a9..6e25e2e67 100644 --- a/docs/contracts/function-owners.md +++ b/docs/contracts/function-owners.md @@ -12,18 +12,18 @@ Status: **Proposed baseline**; individually **adopted** entries are identified b | `skill_eval_diagnostic` task definition/`validate_task`/`expected`/`verify` | B task/pure criteria; `main` as a B-defined worker entry | worker started by H; prepare/assess do not execute `main` | | `skill_eval_engineering` task/vectors/`validate_task` | B task-owned definition and pure vector judgment | `verify` must be split from process start; offline assess does not re-measure through an execution port | | same file `materialize_generated_artifact`/`read_regular`/`input_hashes`/`SandboxUnavailable`/`RUNNER`/`sandbox_command`/`_invoke` | H input capture/sandbox execution capability | real capability/control domain tested in the later H02 PR; B consumes fixed output only | -| `harness/runner` execution/termination/directory/state events | H execution and facts; AB/BA/repetitions → B protocol/worker; `write_report` → Apps | old run unchanged; migrating old `evaluate` decouples the runner first; new H scoring cannot be retained by attaching a `legacy` label | +| `harness.manager.run_experiment` execution/termination/directory/state events | H execution and facts; AB/BA/repetitions → B protocol/worker; `write_report` → Apps | old run unchanged; migrating old `evaluate` decouples the runner first; new H scoring cannot be retained by attaching a `legacy` label | | `harness/improvement` `usage_totals`/`assessment`/`holdout_accepts`/`rerun_assessment` | B experiment validity/comparison/acceptance rules; budget admission/reservation/charging reconciliation remains H | read normalized facts only; provider parsing does not move because of import convenience | | same file `choose` | H search progression; `SelectionPolicy` split into B threshold rules and H progression/stop policy | no shared business `Policy` class; Apps does not create a retry loop | | `harness/knowledge_capture` `assemble_context_text`/`_item` | K pure knowledge text projection | Apps connects K/H; Apps gives H the fixed expected text/hash; H stores the actually delivered text/hash; `verify_capture` byte integrity belongs to H and does not call K assembly in reverse; it is not a task-benefit verdict | -| `harness/trials/external` `execute_trial`/`collect_trial_checks` | H: run one command through `execute_command`, retain its record, and collect the trial checks; semantic metric validation (`read_metric`/`validate_metric`) is B and lives in `benchmark/metrics.py` | `execute_trial` applies only the metric callable the caller injects and holds no metric rule; offline assess executes nothing | +| `harness/executor/trials/external` `execute_trial`/`collect_trial_checks` | H: run one command through `execute_command`, retain its record, and collect the trial checks; semantic metric validation (`read_metric`/`validate_metric`) is B and lives in `benchmark/metrics.py` | `execute_trial` applies only the metric callable the caller injects and holds no metric rule; offline assess executes nothing | | `campaign_records` `STAGES`/claim capture/reconciliation | H records; dashboard/report presentation → Apps | first remove the `campaign_records → dashboard_data` reverse dependency; #333 is Proposed and no claim is made that a unified event envelope is accepted | | `catalog.repository_pack`/`REPO_TYPES` | D020 neutral raw-data technical leaf; target interpretation stays H | K does not expose the pack reader publicly; `apps/host/inspection` (the former `infra/inspection`, moved by #498) changes only its same-leaf import; seven K bodies/root entries/tests move together | | `apps/views/dashboard_workflow` `command_state`/`run_workflow`/`validation_progress` (added with the OBS dissolve; **adopted owner: Apps views; RSI-master architecture decision 2026-11-14 Asia/Shanghai, recorded in the [D008 wave-2 ownership decision](d008-wave2-ownership-decision.md#dashboard-workflow); independent PR review remains separate**) | Apps views: read-only presentation projection of workflow and command state | The module imports only the standard library and reads records the caller already loaded; it has no H, K or Benchmark edge. A group `state` such as `completed` is a display state for the run workflow, not a verdict, and must not be read as the legacy `Verdict`. `validation_progress` only validates counters from a snapshot `dashboard_data` has already read; it opens no file. | | `harness/records/profile_timeline` `attach_profile`, `_compile` (builds the bounded dashboard overview stored with the record), fixed-byte verification, and digest reads (`read_profiles`/`profile_event_table`) (added with the OBS dissolve; **adopted owner: H records; RSI-master architecture decision 2026-11-14 Asia/Shanghai, recorded in the [D008 wave-2 ownership decision](d008-wave2-ownership-decision.md#profile-records-and-overview); independent PR review remains separate**) | H records: attach a reviewed profile, compile the stored overview from those bytes, and verify stored bytes | Record, overview-compile and byte-integrity paths stay in H because the overview is record content: it is computed once at attach from a bounded trace and published content-addressed, so the stored bytes cannot depend on who renders them. Its top-lane, longest-event and top-kernel selection reduces one trace for a bounded record; it ranks no candidate, run or claim and produces no verdict. UI route decoration, including `events_url`, belongs to Apps views, not H. Issue #413's broad timeline-to-Apps placement is refined here: persisted factual records and bounded overview encoding stay in H; UI projections and route decoration belong to Apps. The route decoration is removed from H in this PR, preserving stored bytes, digest verification and the external view response. | | `apps/views/profile_searches` `pre_profile_searches` (added with the OBS dissolve; **adopted owner: Apps views; RSI-master architecture decision 2026-11-14 Asia/Shanghai, recorded in the [D008 wave-2 ownership decision](d008-wave2-ownership-decision.md#pre-profile-searches); independent PR review remains separate**) | Apps views: Dashboard-consumed presentation list relating a profile capture to named searches completed before it | It joins an H record with ledger read models, which only Apps may assemble. Its `verified`/`not_before`/`unknown_time` values are display annotations over an existing search state; they are not evidence for a claim, and using them that way needs a new owner decision. | | `benchmark/sampling` `collect_samples` (moved out of `harness/scenarios/media` by the old-run split; **ownership disposition: B sampling; RSI-master [adopted decision, 2026-11-14 Asia/Shanghai](d008-wave2-ownership-decision.md#benchmark-sampling); independent PR review remains separate**) | B sampling: seed ordering, timing records and artifact hashes | Request transport stays with the caller's injected `request(item, path)` callback; Benchmark hashes artifacts with its own `_sha256`, pinned to `apps.artifacts.sha256` by `tests/apps/test_legacy_run_split.py::test_sampling_sha256_matches_the_apps_hasher` (the Infra hasher and its test name were retired by #498), and imports no H or Apps module. The per-group progress line on stdout is the old `run` protocol output kept for D022 and is a protocol constraint, not a presentation owner. | -| `harness/runner` `snapshot` port `(repo, exclude) -> dict` (separated from the runner by the old-run split; **ownership disposition: H port contract, Apps legacy binding, `apps/host/targets` implementation (moved from `infra/targets` by #498); RSI-master [adopted decision, 2026-11-14 Asia/Shanghai](d008-wave2-ownership-decision.md#snapshot-port); independent PR review remains separate**) | H owns the port and its contract; the Apps legacy composition owns the binding; `apps/host/targets` owns the Git identity implementation | H keeps the port required and keyword-only with no default and holds no copy of the implementation. `apps/legacy/run.py` binds `snapshot=repository_identity` for the old run; the root `execution.py` forwarder was deleted by #412 R1, and the CLI imports `apps/legacy/` itself. A change of the binding owner needs its own review. Out-of-tree callers that used the removed H defaults are not covered by this row. | +| `harness.manager.run_experiment` `snapshot` port `(repo, exclude) -> dict` (separated from the runner by the old-run split; **ownership disposition: H port contract, Apps legacy binding, `apps/host/targets` implementation (moved from `infra/targets` by #498); RSI-master [adopted decision, 2026-11-14 Asia/Shanghai](d008-wave2-ownership-decision.md#snapshot-port); independent PR review remains separate**) | H owns the port and its contract; the Apps legacy composition owns the binding; `apps/host/targets` owns the Git identity implementation | H keeps the port required and keyword-only with no default and holds no copy of the implementation. `apps/legacy/run.py` binds `snapshot=repository_identity` for the old run; the root `execution.py` forwarder was deleted by #412 R1, and the CLI imports `apps/legacy/` itself. A change of the binding owner needs its own review. Out-of-tree callers that used the removed H defaults are not covered by this row. | D008 rows are architecture decisions under the delegation recorded at the top of this file. An independent reviewer verifies the cited code, tests and dependency direction and may block on a missing adoption record; a reviewer does not choose the owner, and a PR approval is not the D008 adoption record. The architecture owner records adoption in the governed contract or decision record; the rows cite that decision record, independently of PR approval. @@ -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/executor/skill_evaluation.py`, `harness/executor/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. +- `usage_totals` stays in `harness/records/usage.py`, because `harness/manager/_state.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/contracts/gate-policy-runstore-and-first-prs.md b/docs/contracts/gate-policy-runstore-and-first-prs.md index 50d82f368..9a6fce592 100644 --- a/docs/contracts/gate-policy-runstore-and-first-prs.md +++ b/docs/contracts/gate-policy-runstore-and-first-prs.md @@ -38,7 +38,7 @@ The symbol inventory is AST-derived and does not claim to have found every third 1. The default cross-core prohibition stays. Only the seven leaf→exact-K-module edges above may serve as migration-compatibility exceptions; a module prefix does not authorize adjacent new modules. 2. Shape checks allow only a module docstring, a `future` import, the listed `ImportFrom` lines (alias only as `name as name`), and an `__all__` constant string list. No business definitions, other imports, assignment side effects, or dynamic module hooks. -3. The static graph resolves absolute/relative imports, `from package import name`, and known export edges, and builds the transitive closure. Any target K/B/H core API entry that reaches another core, Apps, or a legacy facade fails. The D020 neutral technical leaf is not a legacy facade and must be independently verified to contain only raw data reading/data constants and no core imports; "only indirectly, so it passes" is not allowed. Target H entry points are the new `harness.api`/`execution_service`/`run_store`; the current mixed `harness` does not automatically count as an isolated core. +3. The static graph resolves absolute/relative imports, `from package import name`, and known export edges, and builds the transitive closure. Any target K/B/H core API entry that reaches another core, Apps, or a legacy facade fails. The D020 neutral technical leaf is not a legacy facade and must be independently verified to contain only raw data reading/data constants and no core imports; "only indirectly, so it passes" is not allowed. Target H entry points are `harness.api`, `harness.executor` and `harness.records`; the current mixed `harness` does not automatically count as an isolated core. 4. The existing `harness/skill_evaluation.py → knowledge_operations → knowledge.*` edge is a registered **exact residual legacy dependency**: retained, and it keeps `overall isolation_complete=false`. It is not erased from the report and no new/expanded H bypass is permitted. It is not an exception available to a target H new entry. The skill-evaluation split (#410) later removed this edge and its exemption; [Module layout](../guides/module-layout.md#first-wave-compatibility-exceptions-proposed) records the current rule. 5. `test_clean_scan_is_not_isolation` becomes a staged-model test. It does not permanently assert that all three package directories are absent. It verifies that `overall` is still false when any target package, any compat exception, or an old H→model/infra transitive residual is missing. Green is not manufactured by deleting assertions. 6. A non-empty allowlist forces `overall isolation_complete=false`; "new core business closure isolated" is reported as a separate verifiable result and cannot impersonate isolation of the whole historical namespace. diff --git a/docs/contracts/generation-bounds.md b/docs/contracts/generation-bounds.md index b513e3284..bc8e91906 100644 --- a/docs/contracts/generation-bounds.md +++ b/docs/contracts/generation-bounds.md @@ -1,6 +1,6 @@ # Internal original generation bounds -`inferrsi.harness.generation.prepare_generation` seals an approved context and +`inferrsi.harness.executor.prepare_generation` seals an approved context and generation plan before execution registration. Its caller supplies the original attempt, context request, candidate context and provider ports. It writes the authorized RunStore and returns the ordinary execution specification; it does diff --git a/docs/contracts/generation-feedback-policy.md b/docs/contracts/generation-feedback-policy.md index aea3471ef..79ca9ab1c 100644 --- a/docs/contracts/generation-feedback-policy.md +++ b/docs/contracts/generation-feedback-policy.md @@ -7,7 +7,7 @@ It is separate from a search/loop controller and does not grade evidence. ## Host entry -`inferrsi.harness.generation.prepare_generation` keeps its existing required +`inferrsi.harness.executor.prepare_generation` keeps its existing required arguments and accepts three keyword-only options: | Option | Value | diff --git a/docs/contracts/generation-feedback.md b/docs/contracts/generation-feedback.md index ec97df548..3548b684e 100644 --- a/docs/contracts/generation-feedback.md +++ b/docs/contracts/generation-feedback.md @@ -3,7 +3,7 @@ This documents the first-phase boundary accepted in [#371, decision 7084973960](https://github.com/InferMatrixLab/InferRSI/issues/371#issuecomment-7084973960). V25 assigns frozen feedback policy to Harness. The current -`inferrsi.harness.generation.prepare_generation`, when called without an explicit +`inferrsi.harness.executor.prepare_generation`, when called without an explicit `feedback_policy_ref`, does not enforce that policy: it receives a host-built `candidate_context`, retains the delivered context and seals the generation plan. There is no automatic next round on this path. diff --git a/docs/contracts/harness-entry-verification.md b/docs/contracts/harness-entry-verification.md index e345a1fb0..e8818c82e 100644 --- a/docs/contracts/harness-entry-verification.md +++ b/docs/contracts/harness-entry-verification.md @@ -1,7 +1,8 @@ # Harness source-entry verification The local CPU target can opt into the first frozen evaluation task with -`LocalCpuTarget(..., module_root=)`. The host owns +`LocalCpuTarget(..., module_root=)` from +`inferrsi.harness.executor`. The host owns this configuration. Requests cannot supply the root. Existing targets with no module root retain their ordinary-command behavior and refuse evaluation mode before registration. diff --git a/docs/contracts/harness-evaluation-replay.md b/docs/contracts/harness-evaluation-replay.md index d6ac213d2..770688a60 100644 --- a/docs/contracts/harness-evaluation-replay.md +++ b/docs/contracts/harness-evaluation-replay.md @@ -55,7 +55,7 @@ caller cancellation with a descendant, fixed cleanup facts, commit failure after a real start, cross-process replay and registration races. Execution facts do not provide a complete Benchmark F/C/M proof or a service-gain claim. -The [local process supervisor](../../src/inferrsi/harness/local_process.py) +The [local process supervisor](../../src/inferrsi/harness/executor/local_process.py) rechecks cancellation and the attempt deadline or step timeout after opening logs and before starting the worker. The [launch-boundary test](../../tests/harness/test_harness_execute.py) covers this diff --git a/docs/contracts/harness-prepared-binding.md b/docs/contracts/harness-prepared-binding.md index 16b39589f..7a32430f0 100644 --- a/docs/contracts/harness-prepared-binding.md +++ b/docs/contracts/harness-prepared-binding.md @@ -1,17 +1,17 @@ # Harness preparation binding before registration The Harness evaluation path checks declarations before registering an attempt. -`inferrsi.harness.prepared_binding.verify(spec, artifact_reader)` returns a +`inferrsi.harness.executor.verify_prepared_binding(spec, artifact_reader)` returns a `FixedPreparation` projection or raises a Harness `PublicError`. The spec must first pass `execution_service.validate`'s static shape checks; `Harness.execute` performs both checks in that order. Ordinary command mode reads no preparation. -The projection's `read(ref, reader)` port obtains a binary stream through +The projection's `read_prepared_binding(ref, reader)` port obtains a binary stream through `reader.open(ArtifactRef)`, closes it, bounds reads by the declared size plus one byte, and independently checks size and SHA-256. Missing bytes or a missing reader produce `ArtifactUnavailable`; changed bytes or noncanonical JSON produce `ArtifactIntegrityError`. Unknown host programming errors propagate. -`project(bytes)` is pure: it parses the canonical v1 envelope and validates the +`project_prepared_binding(bytes)` is pure: it parses the canonical v1 envelope and validates the fields used by Harness. It does not read a protocol, resolve an entry or start a process. A schema version other than v1 is explicitly unsupported. diff --git a/docs/contributing.md b/docs/contributing.md index 2864f2afd..052b626fa 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -35,9 +35,9 @@ policy does not renormalize existing blobs or authorize edits to frozen files. Nightly checks cover Linux and Windows checkouts with `core.autocrlf` set to `false`, `true` and `input`. -Use `harness/serving` for a new model's server and request protocol and +Use `harness/executor/serving` for a new model's server and request protocol and `benchmark/metrics.py` with `benchmark/validators` for its metric and quality checks. -`harness/trials/external.py` runs any external command as one trial and is the +`harness/executor/trials/external.py` runs any external command as one trial and is the same for every model. Use `apps/host/targets` with `resources/repo_packs` for repositories, and `apps/host/platforms` for hardware. A backend is registered in diff --git a/docs/guides/apps-output.md b/docs/guides/apps-output.md index dee9831ba..21160db32 100644 --- a/docs/guides/apps-output.md +++ b/docs/guides/apps-output.md @@ -70,10 +70,11 @@ error. A consumer must use an authorized storage reader and verify the bytes, size and digest before treating a referenced artifact as evidence. Validating the result.json digest does not validate all referenced artifacts. -The Apps design decision selects `inferrsi.harness.execution_spec.request_digest` -as the public Harness digest entry point. `inferrsi.harness.run_store.request_digest` -remains a compatibility export of the same function. Apps can compute the -canonical digest without loading the RunStore implementation. +Use `from inferrsi.harness.executor import request_digest` to compute the +canonical digest of a complete execution request. The import loads only the +canonical encoder and its package dependencies. Callers of the former +`inferrsi.harness.execution_spec.request_digest` and +`inferrsi.harness.run_store.request_digest` entries should use this import. ## Prepare archive diff --git a/docs/guides/harness-improvement.md b/docs/guides/harness-improvement.md index 5cb258255..874924039 100644 --- a/docs/guides/harness-improvement.md +++ b/docs/guides/harness-improvement.md @@ -45,8 +45,8 @@ 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/usage.py` usage accounting; `src/inferrsi/apps/workflows/improvement.py` +`src/inferrsi/harness/manager/search/improvement.py` the search progression and +`src/inferrsi/harness/records/usage.py` usage accounting; `src/inferrsi/apps/workflows/improvement.py` composes them. `tools/skill_eval_improve.py` owns freezing, declarative snapshot materialization and orchestration through `tools/skill_eval_compare.py`. There is no second diff --git a/docs/guides/module-layout.md b/docs/guides/module-layout.md index 2a51b1eba..83dcdde14 100644 --- a/docs/guides/module-layout.md +++ b/docs/guides/module-layout.md @@ -67,6 +67,21 @@ into runs by file path. ### Core and technical packages +Import `ImageProtocol`, `post_json`, `launch_server` and `stop_server` from +`inferrsi.harness.executor` for image requests, JSON transport and supervised servers. + +Service-reuse callers prepare the frozen plan and run an attempt through +`prepare_service` and `execute_service_attempt` from the same package. The +`inferrsi.harness.evaluator` package evaluates the retained measurement and quality +receipts. The campaign controller uses those results to commit the round. + +Use `inferrsi.harness.executor.request_digest` for the execution request's +semantic ID. Mount an existing store with `RunStore` or `RunStoreReader` from +`inferrsi.harness.records`, using the original root and namespace. A read by +the recorded version returns that version's original bytes. Catch `PublicError` +from `inferrsi.harness.api` for both store and execution operations. For ordinary +optimization sessions, status and recovery still require the frozen runtime. + The four target modules are peers: `knowledge`, `harness`, `benchmark`, and `apps`. Knowledge, Harness, and Benchmark do not import one another. Apps is the only assembler. `src/inferrsi/contracts/__init__.py` re-exports only @@ -173,8 +188,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 @@ -246,8 +261,8 @@ the `temporary leaf importers` blocker that R1 left for root `arguments.py`. R2 cleared `harness reaches model/infra` (12 hits): `agent_sessions`, `candidates`, `optimization`, `optimization_session`, `project` and `task_protocol` each reached `inferrsi.infra` and `inferrsi.infra.artifacts`. They now take `digest`, `sha256` -and `file_lock` from `harness/artifact_primitives.py` and `atomic_write_json` from -`harness/atomic_json.py`, whose function bodies equal those in `infra/artifacts.py`. +and `file_lock` from `harness/records/artifact_primitives.py` and `atomic_write_json` from +`harness/records/atomic_json.py`, whose function bodies equal those in `infra/artifacts.py`. `infra/artifacts.py` stayed for its other users until #498 removed `infra/`. No Harness module reaches `inferrsi.infra` or `inferrsi.model`. R3 cleared `runtime resource loaders: 5`. @@ -332,22 +347,24 @@ 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`, - `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. +- **Harness entries.** The registered component packages are + `inferrsi.harness.manager` and `inferrsi.harness.executor`. The gate also + tracks `inferrsi.harness.api`, `inferrsi.harness.executor._execution`, + `inferrsi.harness.executor._input_binding`, `inferrsi.harness.executor.local_process`, + `inferrsi.harness.records`, its `_run_store` backend and `inferrsi.contracts._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 former root-level runner and ten search modules, and any + file that restores one of those paths. Import the four-port AB/BA loop with + `from inferrsi.harness.manager import run_experiment`. - **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 module is walked on the full graph. A harness module that reaches an old 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` + path in `harness_model_infra`; the split modules `harness.executor.skill_evaluation`, + `harness.manager.search.improvement`, `harness.executor.artifact_sandbox` and `harness.records.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..babb4499c 100644 --- a/docs/guides/operations.md +++ b/docs/guides/operations.md @@ -40,8 +40,8 @@ Effect classes used below: | Rebuild scoped legacy evidence views | `python tools/rebuild_model_evidence.py --archive --output ` | CPU-only; creates a new output directory | Authenticates original bytes and pinned projection/code; no extraction, network, archived-code execution or campaign qualification | | Inspect evidence inventory / generate budget input | `python tools/validate_evidence.py [--budget-assets]` | Read-only | Offline layout/hash/schema checks; optional disposable #328 metadata view derived from campaign authority; no downloads | | Execute one ordinary local CPU command with a fixed record | Python `inferrsi.harness.api.Harness.allocate` / `execute` / `read` | Experiment-executing / record-writing | One explicit RunStore root and one trusted local CPU target; ordinary command mode only; a record holds execution facts, so exit 0 is not a verdict; no device, model or network fallback | -| Seal a generation request before execution | Python `inferrsi.harness.generation.prepare_generation`; [original bounds](../contracts/generation-bounds.md) | Local record-writing | Seals approved context, plan and original deadline/budget metadata; allocates no attempt, starts no process and does not enable generation-lineage evaluation | -| Verify a frozen preparation binding before registration | Python `inferrsi.harness.prepared_binding.verify` / `read` / `project` | Read-only / pure projection | Fixed ArtifactRef and read-only stream capability; no registration, entry resolution or execution; [binding contract](../contracts/harness-prepared-binding.md) | +| Seal a generation request before execution | Python `inferrsi.harness.executor.prepare_generation`; [original bounds](../contracts/generation-bounds.md) | Local record-writing | Seals approved context, plan and original deadline/budget metadata; allocates no attempt, starts no process and does not enable generation-lineage evaluation | +| Verify a frozen preparation binding before registration | Python `verify_prepared_binding`, `read_prepared_binding` and `project_prepared_binding` from `inferrsi.harness.executor` | Read-only / pure projection | Fixed ArtifactRef and read-only stream capability; no registration, entry resolution or execution; [binding contract](../contracts/harness-prepared-binding.md) | | Verify and execute one frozen source evaluation entry | Python `inferrsi.harness.api.Harness.execute` with trusted `LocalCpuTarget(module_root=...)` | Experiment-executing / record-writing | Fixed preparation and expected code digest; actual source captured after registration; T37 refusals start no worker; [source-entry contract](../contracts/harness-entry-verification.md) | | Evaluate one retained generated candidate | Python `inferrsi.harness.api.Harness.execute` with `generation_record_ref`; [same-Store lineage](../contracts/generation-lineage.md) | Experiment-executing / record-writing | Same authorized Store, sealed successful generation and exact retained candidate; distinct attempt, original deadline/budget scope and policy; registered replay precedes fresh source reads; no worker-manifest parsing or automatic rerun | | Capture and seal evaluation proofs | Python `Harness(..., evidence_capture=...)`; [capture contract](../contracts/harness-evidence-capture.md) | Read-only capture callback / record-writing | H authorizes attempt bytes, seals actual provenance and retains drafts before one commit; ordinary mode and replay never call the observer | @@ -52,8 +52,8 @@ Effect classes used below: | Assess one fixed P1 record offline | Python `benchmark.assessment.assess`; [production assess](../contracts/production-assess.md) | Read-only retained evidence / pure encoding | Verifies the frozen protocol, actual capture and proof bytes; returns independent claims without launching a worker or writing an archive; Apps selects the primary key and archives the result | | Project P1 worker reports into capture drafts | Python `benchmark.proofs` codecs / `ProofProjector.project`; [proof drafts](../contracts/production-proofs.md) | Pure computation | Produces proof bytes from supplied capture facts and reports; H must authenticate, retain and seal them before commit; no worker or grader execution | | Configure the CPU evidence-smoke task | Python `benchmark.cpu_smoke.prepare_service`; [task contract](../contracts/p1-cpu-smoke.md) | Read-only owned resource configuration | Freezes the standalone worker and same-source baseline for the existing prepare port; actual execution/retention stays in H; no performance-gain claim | -| Seal a generation with frozen feedback authorization | Python `harness.generation.prepare_generation`; [opt-in feedback profile](../contracts/generation-feedback-policy.md) | Local context / policy / generation-plan retention | Optional fixed policy and source record Refs authorize original scope/check proofs before provider calls. Absent-policy calls remain a trusted-host path; no automatic execution or policy-approval authentication | -| Seal host-approved generation context without a policy Ref | Python `harness.generation.prepare_generation`; [feedback boundary](../contracts/generation-feedback.md) | Local context / generation-plan retention | The trusted host authorizes feedback and excludes final-only results before handoff. Without the opt-in policy Ref, H seals supplied material and does not prove feedback-policy enforcement or execute a worker | +| Seal a generation with frozen feedback authorization | Python `harness.executor.prepare_generation`; [opt-in feedback profile](../contracts/generation-feedback-policy.md) | Local context / policy / generation-plan retention | Optional fixed policy and source record Refs authorize original scope/check proofs before provider calls. Absent-policy calls remain a trusted-host path; no automatic execution or policy-approval authentication | +| Seal host-approved generation context without a policy Ref | Python `harness.executor.prepare_generation`; [feedback boundary](../contracts/generation-feedback.md) | Local context / generation-plan retention | The trusted host authorizes feedback and excludes final-only results before handoff. Without the opt-in policy Ref, H seals supplied material and does not prove feedback-policy enforcement or execute a worker | | Visualize a recorded run or campaign | CLI `dashboard`; [dashboard](../dashboard.md) | Report-generating / local read-only serving | Writes an offline HTML snapshot or serves an optional live view on loopback; does not run an agent or validate a claim | | Capture a knowledge context | CLI `campaign capture-context`; [offline dashboard](../dashboard.md#record-the-optimization-story-campaign-trace) | Local evidence-writing | Saves assembled context and resource hashes in a new `knowledge/.json`. Supports ordinary questions and explicit IDs. The only accepted explicit `--relevance-method` value is `find-lexical-v1` | | Retain an executed retrieval | Python `apps.workflows.campaign.save_retrieval`; [capture contract](knowledge/knowledge-retrieval-trace.md#retain-a-standalone-result) | Local evidence-writing | Saves an existing catalog/collect result under a fresh campaign capture ID; no new search or automatic publication | @@ -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/optimization-workflow-unification.md b/docs/guides/optimization-workflow-unification.md index 09d2465f9..850341470 100644 --- a/docs/guides/optimization-workflow-unification.md +++ b/docs/guides/optimization-workflow-unification.md @@ -32,7 +32,7 @@ CLI `final` 返回后自动生成 `delivery//report.md`、离线 `rep ## 时序图 -以下是普通项目默认 AB/BA 模式的完整流程。CLI 接入既有入口,调用 Harness 的 `optimization_session.session_command()`。初始化、执行、判定和结算均在 Harness 内;CLI 注入 KnowledgeReader 和已有知识记录回调。知识记录回调在 `apps/workflows/campaign.py`,展示在 `apps/views`,记录由 `harness/records` 写入;Harness 仍负责优化状态与预算。 +以下是普通项目默认 AB/BA 模式的完整流程。CLI 将参数转为会话请求,调用 `inferrsi.harness.manager.run_session`。Manager 负责初始化、预算和结算,Executor 执行,Evaluator 判定。CLI 注入 KnowledgeReader 和 `apps/workflows/campaign.py` 的知识捕获回调。`apps/views` 展示结果,`harness/records` 保存记录。 先准备任务条件,再调用 start。start 内复制任务、脚本和基线并写入计划/状态,不执行测量。Agent 逐次调用 round,最后调用 final 独立重测已保存的最佳版本。 @@ -49,7 +49,7 @@ sequenceDiagram A->>A: 先读 RSI 入口,准备任务说明、输入、质量/性能脚本、指标和门槛 Note over A,H: 第一阶段:start 内保存任务与基线,初始化本次运行;此时不测量性能 A->>C: campaign start:提交文件、条件、源码范围、预算和停止规则 - C->>H: session_command:提交解析后的启动参数 + C->>H: run_session(StartProjectSession) H->>H: 检查新目录、项目范围及参数;project.prepare 保存 TASK.md、protocol 和文件哈希 H->>H: candidates.retain:保存 frozen/baseline/ 和源码身份 H->>H: initialize:建立计划、期限、空轮次和初始最佳候选 @@ -63,7 +63,7 @@ sequenceDiagram A->>C: campaign diagnose:记录瓶颈及其测量依据 opt 需要资料且知识开关允许 A->>C: campaign knowledge:提交查询、检索方式和上下文预算 - C->>H: session_command:传入查询、KnowledgeReader 和记录回调 + C->>H: run_session(QuerySessionKnowledge),注入 reader 和捕获回调 H->>H: 检查运行状态、预算和知识开关 H->>O: 调用注入的 capture_context,传入 reader 和查询 O->>K: reader.collect 检索 @@ -79,20 +79,20 @@ sequenceDiagram A->>C: campaign final:提交停止原因和可用用量 Note over A,H: final 使用留存的最佳版本;工作区未提交修改不参与 end - C->>H: session_command:提交 round/final 参数 - H->>H: evaluate_round:使用内部 execute / assess 适配函数 + C->>H: run_session(EvaluateSessionRound 或 FinalizeSession) + 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 记录独立复测结论 @@ -104,7 +104,7 @@ sequenceDiagram Note over A,H: 第三阶段:读取实际完成的记录,展示并交付 A->>C: dashboard:读取实验目录 C->>O: Dashboard 读取实验目录 - O->>H: read_records:核验并读取同一套计划、轮次和 final + O->>H: read_session_records,核验并读取同一套计划、轮次和 final H-->>O: 返回验证后的记录与摘要 O-->>C: 页面/离线 HTML,含优化曲线、已观测用量与 final 结果 C-->>A: 返回展示产物;缺失数据保持未知 @@ -150,9 +150,9 @@ Harness 没有常驻 Agent 驱动。Agent 逐次调用这些操作,代码在 | 一次测量 | 原有 `run` 或 `benchmarks run` | 保留独立使用方式;不会自动生成多轮候选 | | 旧式手动 campaign | 原有 `campaign init/record/decide` | 兼容已有记录;不允许写进新控制器管理的 campaign 形成第二套状态 | -两个优化入口都调用 `harness.optimization_session.session_command`,使用同一个 `harness.optimization` 控制器。AB/BA 与题包使用 `evaluate_round`;显式 service_reuse 使用该控制器内的 `service_command` 和模式分支,共用锁及单一控制记录。执行与评测适配也在 Harness 内;普通项目整个生命周期不导入 Benchmark。 +两个优化入口和直接调用的 Python 程序都向 `inferrsi.harness.manager.run_session` 提交同一组请求。Manager 在会话锁内登记轮次、预算和待恢复操作。AB/BA 与题包按普通会话指纹验收,service_reuse 按冻结的包版本和服务清理凭据恢复。普通项目从准备到判定均可独立于 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。 @@ -217,6 +217,13 @@ profile 或测量确定瓶颈,提交包含 workload 和观测值的 UTF-8 摘 继续使用,瓶颈变化时重新运行 `diagnose`。service-reuse 的 reference epoch 改变后 需要记录新诊断。已有会话按其冻结计划继续。 +每次主动查询都有独立的请求 ID。相同交付再次返回时只登记一次。Manager 在会话锁内 +核对诊断 ID 和条件轮次,同一条件下重新诊断也会使先前派发的回执失效。 +普通会话保留捕获文件的摘要,service-reuse 保留标明已准备交付的记录。 +Python 调用者从 `inferrsi.harness.analyzer` 导入 `diagnosis_draft`,从 +`inferrsi.harness.indexer` 导入 `resolve_frozen_ranking`。此前后者位于 +`inferrsi.harness.optimization`。[组件接口与会话时序](../../src/inferrsi/harness/README.md#managed-session-interfaces) + ### 用 profile 解释改进(可选) 端到端时间会随时钟、温度和共享负载整体漂移,单凭数值很难区分真实改进与波动。测量脚本可以在结果 JSON 中额外输出同一步骤的分区域耗时和工作量计数,单位由脚本自定并在各步骤保持一致: diff --git a/docs/guides/service-reuse-campaigns.md b/docs/guides/service-reuse-campaigns.md index 4bcbf1246..2ef4e82d6 100644 --- a/docs/guides/service-reuse-campaigns.md +++ b/docs/guides/service-reuse-campaigns.md @@ -6,9 +6,9 @@ existing protocol. Before search, supply the model, workload, quality task and numerical acceptance thresholds. To collect supplementary profiling evidence, include a profiler in the same protocol. -The existing `optimization_session` entry assembles the mode inside the shared -`harness.optimization` controller. There is one campaign lock, plan and state; -Apps projects those records without writing selection decisions. +The CLI sends typed operations to `inferrsi.harness.manager.run_session`. +Manager owns the campaign lock, frozen plan and session state. Apps reads these +records to present progress and results. ## Prepare the protocol diff --git a/docs/guides/skill-evaluation/README.md b/docs/guides/skill-evaluation/README.md index acfea003c..ddf108107 100644 --- a/docs/guides/skill-evaluation/README.md +++ b/docs/guides/skill-evaluation/README.md @@ -14,12 +14,12 @@ are observations with order/cache/provider-drift confounding, not causal skill effects; a time-effect study needs a separately authorized frozen plan and budget. The small report-audit driver reuses `KnowledgeReader` bundles, the real Codex -CLI and `harness.local_process.execute_command`. It adapts the sibling pilot's +CLI and `harness.executor.local_process.execute_command`. It adapts the sibling pilot's fresh-session, event and independent-verifier methods; its old fixed no-skill/human/distilled controller is not imported. No external evaluation platform source is copied. Existing knowledge retains its source/license limits. -Ownership follows the module split. `inferrsi.harness.skill_evaluation` adapts the +Ownership follows the module split. `inferrsi.harness.executor.skill_evaluation` adapts the client, executes each trial and retains its facts. `inferrsi.benchmark.skill_evaluation` holds check validity, the task verdict and condition statistics. `inferrsi.apps.workflows.skill_evaluation` composes both with the bundle export behind the diff --git a/docs/guides/skill-evaluation/local-skill-evaluation.md b/docs/guides/skill-evaluation/local-skill-evaluation.md index 630697436..bf68d53b6 100644 --- a/docs/guides/skill-evaluation/local-skill-evaluation.md +++ b/docs/guides/skill-evaluation/local-skill-evaluation.md @@ -21,7 +21,7 @@ flowchart LR `tools/skill_eval_compare.py` still owns prepare/execute/report and paired snapshots. `tools/skill_eval_local.py` adds manual stage/capture, without launching an agent. `src/inferrsi/benchmark/skill_eval_engineering.py` owns the one task, its -19 public behavior probes and their judgment. `src/inferrsi/harness/artifact_sandbox.py` +19 public behavior probes and their judgment. `src/inferrsi/harness/executor/artifact_sandbox.py` replays the retained artifact under bubblewrap and separates the single writable artifact from frozen inputs; `src/inferrsi/apps/workflows/skill_eval_engineering.py` composes the two. The existing cloud read/submit route is unchanged; diff --git a/docs/guides/skill-evaluation/skill-eval-cloud-replay.md b/docs/guides/skill-evaluation/skill-eval-cloud-replay.md index ed9c482c7..8242613c6 100644 --- a/docs/guides/skill-evaluation/skill-eval-cloud-replay.md +++ b/docs/guides/skill-evaluation/skill-eval-cloud-replay.md @@ -26,7 +26,7 @@ The UTF-8 JSON object has exactly these keys (duplicate keys are rejected): - `grader_sha256`: SHA256 of the trusted `src/inferrsi/benchmark/skill_eval_engineering.py` file bytes: the task, its vectors and their judgment. The replay sandbox - (`src/inferrsi/harness/artifact_sandbox.py`) is not part of this digest; the + (`src/inferrsi/harness/executor/artifact_sandbox.py`) is not part of this digest; the receipt's qualification records the exact revision that ran it. - `inputs_sha256`, `protocol_sha256`: lowercase 64-character provenance digests. These are retained, **not independently authenticated by this receipt**. diff --git a/docs/guides/speculative-search.md b/docs/guides/speculative-search.md index a7786795c..98bfe6561 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 | -| Execution | Existing `trials.external` and `local_process` | Absolute deadline and process-domain cleanup; no new subprocess runner | +| Work/state authority | `harness.manager.search.work_control` | Transactions in the shared `RunStore` SQLite database | +| Execution | Existing `executor.trials.external` and `executor.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..feeeee5da 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": "4222d9944a02ee6b7a79d314749f73b8d9421ff0a8d95d6c680ce426fb44a533", "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": "33463b8c9ec1a4d845a71cc6711057ecae015dfda602a0735cfe73f2ba031c86" } diff --git a/evidence/qwen-vats-gvo-910b1-20261124/plan/run.py b/evidence/qwen-vats-gvo-910b1-20261124/plan/run.py index 15af73b00..23126a1cf 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.records import RunStore +from inferrsi.harness.records.artifact_primitives import digest, sha256 +from inferrsi.harness.records.atomic_json import atomic_write_json 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..092fac20d 100644 --- a/evidence/qwen-vats-gvo-910b1-20261124/validator/check.py +++ b/evidence/qwen-vats-gvo-910b1-20261124/validator/check.py @@ -9,11 +9,13 @@ from statistics import geometric_mean from inferrsi.benchmark.registry import task_resources -from inferrsi.harness import candidates, task_protocol -from inferrsi.harness.run_store import RunStoreReader -from inferrsi.harness.work_control import WorkControl +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 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 +37,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,22 +99,20 @@ 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" 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] @@ -133,7 +140,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) @@ -172,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/examples/qwen21_turbo_b300.py b/examples/qwen21_turbo_b300.py index 8ab4fa391..0fb613361 100644 --- a/examples/qwen21_turbo_b300.py +++ b/examples/qwen21_turbo_b300.py @@ -18,8 +18,7 @@ import inferrsi from inferrsi.benchmark.sampling import collect_samples -from inferrsi.harness.serving.image import ImageProtocol -from inferrsi.harness.serving.server import launch_server, stop_server +from inferrsi.harness.executor import ImageProtocol, launch_server, stop_server from inferrsi.apps.host import environment, targets from inferrsi.apps.host.platforms.cuda import qualify_devices from inferrsi.apps.storage import artifacts diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index c76418009..f5b12cdf7 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -6,7 +6,7 @@ import os import sqlite3 import sys -from dataclasses import replace +from dataclasses import fields, replace from importlib.resources import files from pathlib import Path @@ -16,7 +16,7 @@ from ...knowledge.research import research_knowledge from ..host.prepared_environment import inspect_environment from ..legacy.reporting import write_report -from ..workflows.campaign import capture_context, create_campaign +from ..workflows.campaign import capture_context, create_campaign, prepare_context from ..workflows.knowledge import knowledge_reader from ..workflows.knowledge import read as read_knowledge from .arguments import SUPPLIED, command_parser, device_ids, make_spec, parser @@ -32,8 +32,28 @@ def _round_provider(plan): return round_provider(plan) +def _session_request(args): + from ...harness import manager + + if args.session_action == "start": + operation = (manager.StartProjectSession if args.project_task + else manager.StartBenchmarkSession) + else: + operations = ( + manager.BaselineSession, manager.DiagnoseSession, manager.EvaluateSessionRound, + manager.FinalizeSession, manager.ProfileSession, manager.QuerySessionKnowledge, + manager.ReadSessionKnowledge, manager.RecoverSession, manager.RefreshSessionReferences, + manager.ResumeSession, manager.SessionStatus, + ) + operation = {request.action: request for request in operations}[args.session_action] + values = vars(args) + return operation(**{field.name: values[field.name] for field in fields(operation) + if field.name in values}) + + def _optimization_session(args, *, task_source=None, report_metadata=None): - from ...harness.optimization_session import session_command + from ...harness.executor import assess_packaged_task + from ...harness.manager import run_session from ...knowledge.ranking_policy import managed_ranking_policy settings = None @@ -45,8 +65,9 @@ def _optimization_session(args, *, task_source=None, report_metadata=None): settings = {"channel": CHANNEL_NAME, "backend": "ascend", "platform": args.cannbot_platform} external_project = freeze_project(args.repo if args.project_task else None) - return session_command( - args, task_source=task_source, retain_context=capture_context, + return run_session( + _session_request(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, @@ -56,7 +77,7 @@ def _optimization_session(args, *, task_source=None, report_metadata=None): def _fixed_attempt_command(args) -> int: - from ...harness.errors import PublicError + from ...harness.api import PublicError from ..api import read_attempt_view if args.storage_config is None: @@ -490,25 +511,27 @@ def main(argv: list[str] | None = None) -> int: _print(result) return 0 if args.command == "agents": - from ...harness import agent_sessions + from ...harness import manager if args.agent_action == "prepare": - result = agent_sessions.prepare( + result = manager.prepare_agent_session( args.job, prompt=args.prompt_file.read_text(encoding="utf-8"), workspace=args.workspace, title=args.title, max_seconds=args.max_minutes * 60, model=args.model, effort=args.effort, plugin_ref=args.plugin_ref, ) elif args.agent_action == "bind": - result = agent_sessions.bind( + result = manager.bind_agent_session( args.job, host=args.host, session_id=args.session_id, host_id=args.host_id, receipt=args.receipt, ) elif args.agent_action == "record": - result = agent_sessions.record( + result = manager.record_agent_session( args.job, observation=args.observation, artifacts=args.artifact, ) + elif args.agent_action == "dispatch": + result = manager.dispatch_agent_session(args.job) else: - result = getattr(agent_sessions, args.agent_action)(args.job) + result = manager.agent_session_status(args.job) _print(result) return 0 if args.command == "search": diff --git a/src/inferrsi/apps/cli/evaluate.py b/src/inferrsi/apps/cli/evaluate.py index cb50a7bef..8a5eccfac 100644 --- a/src/inferrsi/apps/cli/evaluate.py +++ b/src/inferrsi/apps/cli/evaluate.py @@ -93,8 +93,9 @@ def _prepare_ports(config: dict) -> dict: def _execute_ports(config: dict, storage: dict, *, capture_evidence: bool = False) -> dict: - from ...harness.api import Harness, LocalCpuTarget - from ...harness.run_store import RunStore + from ...harness.api import Harness + from ...harness.executor import LocalCpuTarget + from ...harness.records import RunStore from ..storage.artifact_reader import ArtifactReader target = config.get("target") @@ -167,7 +168,7 @@ def _check_options(args, request: dict, storage: dict) -> None: def dispatch(args) -> int: """Print the same result as Python, including committed refs on publication failure.""" - from ...harness.errors import PublicError + from ...harness.api import PublicError from .. import api from ..storage.archive import validate_output_id diff --git a/src/inferrsi/apps/delivery/benchmark_usage.py b/src/inferrsi/apps/delivery/benchmark_usage.py index 38d8d5a4f..aa4fc9ed6 100644 --- a/src/inferrsi/apps/delivery/benchmark_usage.py +++ b/src/inferrsi/apps/delivery/benchmark_usage.py @@ -3,8 +3,8 @@ from pathlib import Path from ...benchmark.summary import POLICY, supported_policy, token_usage -from ...harness import agent_sessions -from ...harness.usage import normalize_usage +from ...harness import manager +from ...harness.records.usage import normalize_usage from .schema import number from .snapshot import Snapshot, SnapshotChanged @@ -67,7 +67,7 @@ def attach_native_usage(snapshot, result, job): dependency.file(path.name, "native_frozen_input", record["sha256"]) # Include alongside the job: each source keeps its own root and stability probe. snapshot.include(dependency, f"agent-input-{index}:") - host = agent_sessions.status(job) + host = manager.agent_session_status(job) if (host["request"] != request or host["last_observation"] != state["last_observation"] or host["usage"] != state["usage"] or host["state"] != state["state"] or host["native_session"] != state["native_session"]): diff --git a/src/inferrsi/apps/delivery/projection.py b/src/inferrsi/apps/delivery/projection.py index 9b6bf120b..b82c8125d 100644 --- a/src/inferrsi/apps/delivery/projection.py +++ b/src/inferrsi/apps/delivery/projection.py @@ -2,7 +2,7 @@ import re -from ...harness.usage import normalize_usage +from ...harness.records.usage import normalize_usage from ..storage.artifacts import digest from .schema import gap, number, timestamp diff --git a/src/inferrsi/apps/delivery/snapshot.py b/src/inferrsi/apps/delivery/snapshot.py index 22a2733c0..811553e90 100644 --- a/src/inferrsi/apps/delivery/snapshot.py +++ b/src/inferrsi/apps/delivery/snapshot.py @@ -5,7 +5,7 @@ import stat from pathlib import Path, PurePosixPath -from ...harness import candidates +from ...harness.executor import candidates from ..storage.artifacts import sha256 from .schema import decode diff --git a/src/inferrsi/apps/handoff/bridge.py b/src/inferrsi/apps/handoff/bridge.py index 2c609943b..7ba70ac1c 100644 --- a/src/inferrsi/apps/handoff/bridge.py +++ b/src/inferrsi/apps/handoff/bridge.py @@ -5,7 +5,7 @@ from hashlib import sha256 from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import PublicError from ..storage.archive import _logical_path from ..storage.result import validate_artifact_ref diff --git a/src/inferrsi/apps/handoff/candidate_provider.py b/src/inferrsi/apps/handoff/candidate_provider.py index d4234f168..1d9dcf4a8 100644 --- a/src/inferrsi/apps/handoff/candidate_provider.py +++ b/src/inferrsi/apps/handoff/candidate_provider.py @@ -5,7 +5,7 @@ from hashlib import sha256 from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import PublicError from ..storage.archive import _logical_path from ..storage.artifact_reader import ArtifactReader diff --git a/src/inferrsi/apps/handoff/evidence_capture.py b/src/inferrsi/apps/handoff/evidence_capture.py index fe1a6c9be..753d4e97d 100644 --- a/src/inferrsi/apps/handoff/evidence_capture.py +++ b/src/inferrsi/apps/handoff/evidence_capture.py @@ -5,7 +5,7 @@ from copy import deepcopy from hashlib import sha256 -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import PublicError from ..storage.result import validate_artifact_ref diff --git a/src/inferrsi/apps/handoff/production_capture.py b/src/inferrsi/apps/handoff/production_capture.py index 5d99a31cd..a4c0710fb 100644 --- a/src/inferrsi/apps/handoff/production_capture.py +++ b/src/inferrsi/apps/handoff/production_capture.py @@ -2,7 +2,7 @@ from copy import deepcopy -from ...harness.errors import PublicError +from ...harness.api import PublicError from ..storage.archive import read_prepared from ..storage.artifact_reader import ArtifactReader from .evidence_capture import EvidenceCapture diff --git a/src/inferrsi/apps/legacy/run.py b/src/inferrsi/apps/legacy/run.py index f4e2a5bc9..28055f0cb 100644 --- a/src/inferrsi/apps/legacy/run.py +++ b/src/inferrsi/apps/legacy/run.py @@ -9,8 +9,8 @@ from inferrsi.benchmark.legacy_run_v0 import evaluate as _evaluate from inferrsi.benchmark.legacy_run_v0 import read_metric, trial_metric from inferrsi.contracts import RunSpec -from inferrsi.harness.runner import run_experiment as _run_experiment -from inferrsi.harness.trials.external import execute_trial as _execute_trial +from inferrsi.harness.executor.trials.external import execute_trial as _execute_trial +from inferrsi.harness.manager import run_experiment as _run_experiment from .evaluation import run_rules from .reporting import write_report diff --git a/src/inferrsi/apps/storage/archive.py b/src/inferrsi/apps/storage/archive.py index 6ca423a48..1aceb7447 100644 --- a/src/inferrsi/apps/storage/archive.py +++ b/src/inferrsi/apps/storage/archive.py @@ -17,7 +17,7 @@ from uuid import uuid4 from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import PublicError from .result import publication_error, validate_artifact_ref, validate_result diff --git a/src/inferrsi/apps/storage/artifact_reader.py b/src/inferrsi/apps/storage/artifact_reader.py index e07ac63a8..e4f36e4ad 100644 --- a/src/inferrsi/apps/storage/artifact_reader.py +++ b/src/inferrsi/apps/storage/artifact_reader.py @@ -3,7 +3,7 @@ from io import BytesIO from inferrsi.contracts.json_v1 import encode -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import PublicError from .archive import _logical_path, _read_directory_artifact, _storage_mounts from .result import validate_artifact_ref @@ -45,7 +45,7 @@ def open(self, ref: dict) -> BytesIO: if kind == "directory": return BytesIO(_read_directory_artifact(prefix, root, ref, stage="open")) # Archive-only consumers never load the SQLite implementation. - from inferrsi.harness.run_store import RunStoreReader + from inferrsi.harness.records import RunStoreReader return RunStoreReader.from_mount({ "prefix": prefix, "kind": kind, "root": str(root), "namespace": namespace, diff --git a/src/inferrsi/apps/storage/result.py b/src/inferrsi/apps/storage/result.py index 23b3eebbf..50cc52c58 100644 --- a/src/inferrsi/apps/storage/result.py +++ b/src/inferrsi/apps/storage/result.py @@ -5,7 +5,7 @@ from hashlib import sha256 from inferrsi.contracts.json_v1 import encode -from inferrsi.harness.errors import PUBLIC_ERROR_CODES, PartialExecutionFacts +from inferrsi.harness.api import PUBLIC_ERROR_CODES, PartialExecutionFacts _EXIT_CODES = { "success": 0, diff --git a/src/inferrsi/apps/views/attempt.py b/src/inferrsi/apps/views/attempt.py index fe55a84c6..c53605404 100644 --- a/src/inferrsi/apps/views/attempt.py +++ b/src/inferrsi/apps/views/attempt.py @@ -3,7 +3,7 @@ from copy import deepcopy from inferrsi.contracts.json_v1 import decode -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import PublicError from ..handoff.bridge import check_assessment_identity from ..storage.archive import read_assessment diff --git a/src/inferrsi/apps/views/dashboard_data.py b/src/inferrsi/apps/views/dashboard_data.py index cf5e3b24d..8922b33eb 100644 --- a/src/inferrsi/apps/views/dashboard_data.py +++ b/src/inferrsi/apps/views/dashboard_data.py @@ -724,12 +724,12 @@ def _managed_diagnoses(state: dict, submissions: list) -> list[dict]: def _managed_dashboard(root: Path, campaign: dict) -> dict: """Project the shared control record; do not manufacture legacy AB/BA runs.""" - from inferrsi.harness.optimization import read_records + from inferrsi.harness.manager import read_session_records from .optimization_story import build_story from .retrieval_projection import managed_knowledge - plan, state, summary = read_records(root) + plan, state, summary = read_session_records(root) pending = state["pending"] submissions = list(state["rounds"]) if pending and pending["kind"] == "round": @@ -854,11 +854,11 @@ def load_dashboard(source: Path) -> dict: or plan_header.get("schema_version") == 3 ) if service_mode: - from inferrsi.harness.optimization import read_records + from inferrsi.harness.manager import read_session_records from .retrieval_projection import public_value - _, _, summary = read_records(root) + _, _, summary = read_session_records(root) return { "campaign_id": sanitized_text(header["campaign_id"]), "evaluation_mode": "service_reuse", diff --git a/src/inferrsi/apps/views/round_citations.py b/src/inferrsi/apps/views/round_citations.py index ce1e5918f..0690133b9 100644 --- a/src/inferrsi/apps/views/round_citations.py +++ b/src/inferrsi/apps/views/round_citations.py @@ -40,11 +40,11 @@ def _managed_citations(root, number): citations = list(_citations([reason])) if isinstance(reason, str) else [] if not citations: return None - from inferrsi.harness.optimization import read_records + from inferrsi.harness.manager import read_session_records notes = {"citations": citations, "receipts": [], "hypothesis": reason} try: - plan, verified, _ = read_records(root) + plan, verified, _ = read_session_records(root) observation = verified["rounds"][number - 1] if observation["hypothesis"] == reason: notes["command"] = (("campaign", "round") if plan["task_source"] == "project" diff --git a/src/inferrsi/apps/workflows/benchmark_compare.py b/src/inferrsi/apps/workflows/benchmark_compare.py index a385a3e0e..5a0c41323 100644 --- a/src/inferrsi/apps/workflows/benchmark_compare.py +++ b/src/inferrsi/apps/workflows/benchmark_compare.py @@ -29,12 +29,12 @@ from inferrsi.benchmark.registry import has_iterative_protocol, task_resources 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.artifact_primitives import digest, file_lock, sha256 -from inferrsi.harness.atomic_json import atomic_write_json -from inferrsi.harness.optimization_session import _runtime_identity +from inferrsi.harness import manager +from inferrsi.harness.executor import run_task_protocol +from inferrsi.harness.manager import session_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), @@ -275,7 +275,7 @@ def _prepare_at(config, sources, runtime, task_settings, root): "parameter_sources": sources, "task_settings": task_settings, "runtime_files": {key: value for key, value in runtime_files.items() if key not in knowledge_files}, - "session_runtime_identity": _runtime_identity(), + "session_runtime_identity": session_runtime_identity(), "knowledge_files": knowledge_files, "trials": trials, "knowledge_boundary": "isolated runtime corpus and session gate; native host " @@ -540,7 +540,7 @@ def _status(root, plan, state, *, host_views=None): job = _job(root, trial, number) if host_views is None: try: - view = agent_sessions.status(job) if job.exists() else None + view = manager.agent_session_status(job) if job.exists() else None except (OSError, ValueError) as error: # As in report: unverifiable job evidence blocks only this trial. view = {"state": "blocked", "native_session": None, @@ -575,7 +575,7 @@ def _status(root, plan, state, *, host_views=None): elif active["state"] == "blocked": action = {"operation": "inspect_retained_host_evidence", "trial": active["id"], "instructions": "Verify the original native job receipts before collection."} - elif active["state"] in agent_sessions.TERMINAL: + elif active["state"] in manager.AGENT_TERMINAL_STATES: action = {"operation": "collect", "trial": active["id"], "instructions": "Retain actual host metadata and campaign tree; collect. " "Host completion is separate from independent final acceptance."} @@ -617,7 +617,7 @@ def dispatch(root, trial_id, *, parallel=False): if current.get("trial") != trial_id or current["operation"] != "dispatch": raise ValueError("Dispatch the next declared trial or pass --parallel") job.parent.mkdir(exist_ok=True) - agent_sessions.prepare( + manager.prepare_agent_session( job, prompt=_prompt(root, plan, trial, workspace), workspace=workspace, title=trial_id if number == 1 else f"{trial_id} attempt {number}", max_seconds=plan["config"]["job_max_minutes"] * 60, @@ -625,11 +625,11 @@ def dispatch(root, trial_id, *, parallel=False): task_reference={"comparison": digest(plan), "trial": trial_id, "attempt": number}, frozen_inputs=(root / "experiment.json",), ) - return agent_sessions.dispatch(job) + return manager.dispatch_agent_session(job) def _host_payload(job, host): - if host is None or host["state"] not in agent_sessions.TERMINAL: + if host is None or host["state"] not in manager.AGENT_TERMINAL_STATES: return None receipt = host["last_observation"] return _object(job / receipt["path"]) if receipt else None @@ -706,7 +706,7 @@ def _trial_result(root, plan, trial, host, payload, *, workspace, host_error=Non result["attempt_window_missing"] = "native_job_evidence_not_verifiable" return result campaign = workspace / "campaign" - if host is None or host["state"] not in agent_sessions.TERMINAL: + if host is None or host["state"] not in manager.AGENT_TERMINAL_STATES: result["status"] = "pending" if host is None else "running" result["gaps"].append("Native execution has not terminated") result["attempt_window_missing"] = "native_execution_not_terminated" @@ -742,7 +742,7 @@ def _trial_result(root, plan, trial, host, payload, *, workspace, host_error=Non return result try: snapshot, delivery, _ = project(campaign, export_id="comparison-read") - campaign_plan, control, _ = optimization.read_records(campaign) + campaign_plan, control, _ = manager.read_session_records(campaign) result["campaign_window"] = {"started_at": control.get("started_at"), "ended_at": control.get("settled_at")} window = result["attempt_window"] @@ -863,8 +863,8 @@ def collect(root, trial_id): return {"trial": _retained(root, reference, trial_id, number), "already_collected": True, "collection": reference, "next": _status(root, plan, state)["next_action"]} job = _job(root, trial, number) - host = agent_sessions.status(job) if job.exists() else None - if host is None or host["state"] not in agent_sessions.TERMINAL: + host = manager.agent_session_status(job) if job.exists() else None + if host is None or host["state"] not in manager.AGENT_TERMINAL_STATES: raise ValueError("Collect only after recording a terminal native host observation") result = _trial_result(root, plan, trial, host, _host_payload(job, host), workspace=_workspace(root, trial, number)) @@ -892,8 +892,8 @@ def retry(root, trial_id, *, parallel=False): number = _attempt_number(state, trial) job = _job(root, trial, number) reference = state["collections"].get(trial_id) - host = agent_sessions.status(job) if job.exists() else None - if reference is None or host is None or host["state"] not in agent_sessions.TERMINAL: + host = manager.agent_session_status(job) if job.exists() else None + if reference is None or host is None or host["state"] not in manager.AGENT_TERMINAL_STATES: raise ValueError("Retry only after collecting a terminal attempt of this trial") retained = _retained(root, reference, trial_id, number) if retained.get("status") == "completed" and retained.get("eligible") is True: @@ -944,7 +944,7 @@ def _reverify(root, plan, trial, number, *, collected=False, archived=False): if collected and not job.is_dir(): # A collected attempt had a terminal job: losing it is unverifiable, not "not run". raise FileNotFoundError("Collected native job is missing") - host = agent_sessions.status(job) if job.exists() else None + host = manager.agent_session_status(job) if job.exists() else None payload = _host_payload(job, host) except (OSError, ValueError) as error: host = {"state": "blocked", "native_session": None} @@ -1108,12 +1108,12 @@ def compare_command(args): other_job = _job(root, other, number) if other_job == job or not other_job.exists(): continue - native = agent_sessions.status(other_job)["native_session"] + native = manager.agent_session_status(other_job)["native_session"] if native and _session_key(native) == (args.host, args.session_id): raise ValueError("Native session is already bound to trial " f"{other['id']} attempt {number}") - return agent_sessions.bind(job, host=args.host, session_id=args.session_id, + return manager.bind_agent_session(job, host=args.host, session_id=args.session_id, host_id=args.host_id, receipt=args.receipt) if args.observation is None: raise ValueError("record requires --observation") - return agent_sessions.record(job, observation=args.observation) + return manager.record_agent_session(job, observation=args.observation) diff --git a/src/inferrsi/apps/workflows/benchmark_operations.py b/src/inferrsi/apps/workflows/benchmark_operations.py index 7770c3f53..e127ca77a 100644 --- a/src/inferrsi/apps/workflows/benchmark_operations.py +++ b/src/inferrsi/apps/workflows/benchmark_operations.py @@ -1,11 +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 benchmark_command, runtime_environment def run_task(name: str, arguments: list[str]) -> int: @@ -13,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], - env=optimization_session.runtime_environment(), + benchmark_command(entry, arguments), + env=runtime_environment(), ) diff --git a/src/inferrsi/apps/workflows/campaign.py b/src/inferrsi/apps/workflows/campaign.py index 52dd2cd38..886687925 100644 --- a/src/inferrsi/apps/workflows/campaign.py +++ b/src/inferrsi/apps/workflows/campaign.py @@ -11,7 +11,7 @@ from pathlib import Path from inferrsi import __version__ -from inferrsi.harness import optimization +from inferrsi.harness import executor, indexer, manager from inferrsi.harness.records import atomic_capture, campaign_records, knowledge_capture from inferrsi.knowledge._skill_selection import FIND_RELEVANCE, validate_relevance_method from inferrsi.knowledge.atomic_reader import AtomicReader, PinnedSource @@ -21,6 +21,7 @@ assemble_context_text, context_item, ) +from inferrsi.knowledge.ranking_policy import managed_ranking_policy def create_campaign(root: Path, campaign_id: str, *, target: float | None = None, @@ -36,9 +37,11 @@ def create_campaign(root: Path, campaign_id: str, *, target: float | None = None def capture_selection(root: Path, source: PinnedSource, reference: str, *, permits, **request) -> dict: """Supply the same Reader as an ordinary read to the managed campaign.""" - return optimization.capture_selection(root, AtomicReader(source, permits=permits), - reference=reference, assemble_text=assemble_context_text, - **request) + return manager.run_session( + manager.SelectSessionKnowledge(session=root, reference=reference, **request), + knowledge_reader=AtomicReader(source, permits=permits), assemble_text=assemble_context_text, + ranking_policy_for=managed_ranking_policy, assess_packaged=executor.assess_packaged_task, + ) def capture_context(root: Path, *, context_id: str, reader, query: str = "", @@ -51,12 +54,27 @@ def capture_context(root: Path, *, context_id: str, reader, query: str = "", sources: tuple[str, ...] = ("package",), ranking_policy=None, diagnosis_binding: dict | None = None) -> tuple[Path, str]: - """Run ``collect`` with a context budget and keep its complete envelope. + """Collect and retain a context for a standalone campaign capture.""" + document = prepare_context( + root, context_id=context_id, reader=reader, query=query, relevance=relevance, + relevance_method=relevance_method, ids=ids, revisions=revisions, kind=kind, repo=repo, + tier=tier, backend=backend, scenario=scenario, limit=limit, context_bytes=context_bytes, + sources=sources, ranking_policy=ranking_policy, diagnosis_binding=diagnosis_binding, + ) + return knowledge_capture.store_capture(root, document) - The capture is produced by the same ``collect`` operation the agent uses, - not by a caller narrative. Returns the new campaign-relative file and its - SHA-256. - """ + +def prepare_context(root: Path, *, context_id: str, reader, query: str = "", + relevance: str | None = None, + relevance_method: str | None = None, + ids: list[str] | None = None, revisions: dict[str, str] | None = None, + kind: str | None = None, repo: str | None = None, tier: str | None = None, + backend: str | None = None, scenario: str | None = None, + limit: int = 5, context_bytes: int = 65536, + sources: tuple[str, ...] = ("package",), + ranking_policy=None, + diagnosis_binding: dict | None = None) -> dict: + """Collect and project a context in memory for validation by its caller.""" if revisions and not ids: raise ValueError("Revision pins require explicit IDs (--id-ref)") validate_relevance_method(relevance_method) @@ -86,15 +104,14 @@ def capture_context(root: Path, *, context_id: str, reader, query: str = "", } if ranking_policy is not None: effective = ranking_policy.receipt() - if (observation or {}).get("selection", {}).get("ranking_policy") != effective: - raise ValueError("Delivered ranking policy differs from the frozen session") + indexer.check_returned_ranking(observation, effective) request["ranking_policy"] = effective if _supplies_no_observation(result): # Such a reader gets the record this entry wrote before observations # existed: the same fields, order and bytes, with no empty provenance. contexts = _contexts(result) - return knowledge_capture.store_capture( - root, campaign_id=campaign["campaign_id"], context_id=context_id, + return knowledge_capture.prepare_capture( + campaign_id=campaign["campaign_id"], context_id=context_id, # Only the source categories are kept; store and checkout paths can be private. request={**request, "ids": ids or []}, selection=result.get("selection"), @@ -107,8 +124,8 @@ def capture_context(root: Path, *, context_id: str, reader, query: str = "", assembled_text=assemble_context_text(contexts), diagnosis_binding=diagnosis_binding, ) - return save_retrieval(root, context_id=context_id, result=result, request=request, - wrapper="campaign capture-context", diagnosis_binding=diagnosis_binding) + return _prepare_retrieval(campaign, context_id, result, request, + "campaign capture-context", diagnosis_binding) def _supplies_no_observation(result: dict) -> bool: @@ -143,6 +160,11 @@ def save_retrieval(root: Path, *, context_id: str, result: dict, hashes attest bytes, not publication permission or actual model use. """ campaign = knowledge_capture.capture_campaign(root, context_id) + document = _prepare_retrieval(campaign, context_id, result, request, wrapper, diagnosis_binding) + return knowledge_capture.store_capture(root, document) + + +def _prepare_retrieval(campaign, context_id, result, request, wrapper, diagnosis_binding): retrieval = result.get("retrieval") if isinstance(retrieval, dict): retrieval = {**retrieval} @@ -157,8 +179,8 @@ def save_retrieval(root: Path, *, context_id: str, result: dict, "revision": view.get("revision") or observations.get(ref, {}).get("revision")}) contexts = _contexts(result) - return knowledge_capture.store_capture( - root, campaign_id=campaign["campaign_id"], context_id=context_id, + return knowledge_capture.prepare_capture( + campaign_id=campaign["campaign_id"], context_id=context_id, # Only the source categories are kept; store and checkout paths can be private. request=request, selection=result.get("selection"), diff --git a/src/inferrsi/apps/workflows/evaluation.py b/src/inferrsi/apps/workflows/evaluation.py index 099661409..ed94a890f 100644 --- a/src/inferrsi/apps/workflows/evaluation.py +++ b/src/inferrsi/apps/workflows/evaluation.py @@ -5,8 +5,8 @@ from pathlib import Path from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness.errors import PublicError -from inferrsi.harness.execution_spec import request_digest +from inferrsi.harness.api import PublicError +from inferrsi.harness.executor import request_digest from ..handoff.bridge import bind_execution as _bind_prepared_execution from ..handoff.bridge import ( diff --git a/src/inferrsi/apps/workflows/improvement.py b/src/inferrsi/apps/workflows/improvement.py index 187329e74..995862227 100644 --- a/src/inferrsi/apps/workflows/improvement.py +++ b/src/inferrsi/apps/workflows/improvement.py @@ -1,11 +1,9 @@ -# 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.usage import usage_totals +from inferrsi.harness.manager.search import improvement as progression +from inferrsi.harness.records.usage import usage_totals def assessment(report: dict, policy: SelectionPolicy) -> dict: diff --git a/src/inferrsi/apps/workflows/parallel_round.py b/src/inferrsi/apps/workflows/parallel_round.py index 40ff13fea..af78be966 100644 --- a/src/inferrsi/apps/workflows/parallel_round.py +++ b/src/inferrsi/apps/workflows/parallel_round.py @@ -1,7 +1,7 @@ """Compose Harness parallel-round orchestration with Benchmark v0 gates. Harness owns prepare / submit / serve / close scheduling. This package binds the -legacy assess port so ``inferrsi.harness.parallel_round`` never imports Benchmark. +legacy assess port for the Manager. """ from collections.abc import Callable @@ -36,9 +36,9 @@ def serve_ticket( clock=None, ) -> dict: """Serve one ticket with the v0 assess composition.""" - from inferrsi.harness import parallel_round as harness + from inferrsi.harness.manager import serve_parallel_ticket - return harness.serve_ticket( + return serve_parallel_ticket( round_dir, ticket, incumbent, @@ -59,9 +59,9 @@ def close_round( clock=None, ) -> dict: """Close one round with the v0 assess composition.""" - from inferrsi.harness import parallel_round as harness + from inferrsi.harness.manager import close_parallel_round - return harness.close_round( + return close_parallel_round( round_dir, incumbent, backend=backend, diff --git a/src/inferrsi/apps/workflows/search_benchmarks.py b/src/inferrsi/apps/workflows/search_benchmarks.py index 5a6c92320..5809c8804 100644 --- a/src/inferrsi/apps/workflows/search_benchmarks.py +++ b/src/inferrsi/apps/workflows/search_benchmarks.py @@ -13,11 +13,17 @@ 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 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.trials.external import execute_trial +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 class EngineEvaluator: @@ -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/apps/workflows/skill_eval_engineering.py b/src/inferrsi/apps/workflows/skill_eval_engineering.py index b907e9a53..9cf90f6bc 100644 --- a/src/inferrsi/apps/workflows/skill_eval_engineering.py +++ b/src/inferrsi/apps/workflows/skill_eval_engineering.py @@ -7,7 +7,7 @@ from pathlib import Path from inferrsi.benchmark import skill_eval_engineering as task_rules -from inferrsi.harness import artifact_sandbox +from inferrsi.harness.executor import artifact_sandbox def verify(task, output): diff --git a/src/inferrsi/apps/workflows/skill_evaluation.py b/src/inferrsi/apps/workflows/skill_evaluation.py index 064825104..b93d4cca4 100644 --- a/src/inferrsi/apps/workflows/skill_evaluation.py +++ b/src/inferrsi/apps/workflows/skill_evaluation.py @@ -6,8 +6,8 @@ from inferrsi.benchmark import skill_eval_engineering as engineering_task from inferrsi.benchmark import skill_evaluation as rules -from inferrsi.harness import skill_evaluation as host -from inferrsi.harness.usage import normalize_usage +from inferrsi.harness.executor import skill_evaluation as host +from inferrsi.harness.records.usage import normalize_usage from inferrsi.knowledge.knowledge_operations import KnowledgeReader from . import skill_eval_engineering diff --git a/src/inferrsi/apps/workflows/speculative_search.py b/src/inferrsi/apps/workflows/speculative_search.py index 76783d3f1..2c5d44fc4 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 +from inferrsi.harness.records.atomic_json import atomic_write_json 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/errors.py b/src/inferrsi/contracts/_harness_errors.py similarity index 100% rename from src/inferrsi/harness/errors.py rename to src/inferrsi/contracts/_harness_errors.py diff --git a/src/inferrsi/harness/README.md b/src/inferrsi/harness/README.md index 1e7bc4658..bba49aca8 100644 --- a/src/inferrsi/harness/README.md +++ b/src/inferrsi/harness/README.md @@ -6,48 +6,80 @@ measurement and assessment rules. ## Entry points -- [`api.py`](api.py) exposes `Harness.allocate`, `execute`, and `read` for local - CPU commands. [`local_process.py`](local_process.py) owns the process domain. -- [`run_store.py`](run_store.py) provides `RunStore` and `RunStoreReader` for +- [the public API](api/__init__.py) exposes `Harness.allocate`, `execute`, and `read` for local + CPU commands. The [Executor supervisor](executor/local_process.py) owns the process domain. +- [Records](records/__init__.py) provides `RunStore` and `RunStoreReader` for namespaced records and content-addressed artifacts. Pass `record_version` to read a fixed record and use `open(ref)` to read retained artifact bytes. -- [`runner.py`](runner.py) owns the common AB/BA loop. It calls injected - `execute`, `snapshot`, `assess`, and `report` ports and records the returned - assessment. [`trials/external.py`](trials/external.py) runs and retains a - single command trial with the supplied metric reader. -- [`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. -- [`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. + The [service observation reader](records/service_observations.py) reconstructs settled + rounds, including older embedded profiles. Service readers and writers share the + [path, JSON and diagnostic limits](records/service_io.py). +- [Manager](manager/__init__.py) exposes `run_session` for typed requests such as + `StartProjectSession`, `StartBenchmarkSession`, `EvaluateSessionRound` and `RecoverSession`. + Apps resolves task resources and supplies the ranking policy, knowledge reader and assessor. + Hosts use `read_session_records` to read the retained plan, rounds and final assessment. + [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. +- [Manager](manager/__init__.py) exposes the common AB/BA loop as + `from inferrsi.harness.manager import run_experiment`. Apps supplies the + `execute`, `snapshot`, `assess` and `report` ports. Manager records the + returned assessment. [External trials](executor/trials/external.py) run and retain + each command with the supplied metric reader. +- Manager also 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 the host's `LocalCpuTarget`, the + canonical `request_digest` and `runtime_environment`. Child processes use the + same InferRSI installation as their parent. Manager calls `process_group_empty` + on Executor when verifying a recorded service's process group. + Import `launch_server` and `stop_server` from Executor to supervise a Linux server. + The same package supplies `post_json` and `ImageProtocol` for sending requests. + Hosts import `prepare_generation` here to seal the context and plan before + registration. `read_prepared_binding` verifies the fixed artifact bytes, + `project_prepared_binding` reads the execution fields from those bytes, and + `verify_prepared_binding` compares them with the requested execution spec. + [Local execution](executor/_execution.py) snapshots inputs and the trusted entry before + starting a child. It seals captured evidence before the RunStore commits the attempt. + [Candidate retention](executor/candidates.py) fixes the input bytes for execution. + The [command supervisor](executor/confinement.py) runs commands within the selected backend. ## Managed optimization loop -`campaign` and `benchmarks session` enter through [session_command](optimization_session.py). +`campaign` and `benchmarks session` construct the same requests a Python host passes to +[`manager.run_session`](manager/__init__.py). The agent chooses a hypothesis and edits a candidate between rounds. -- **Analyzer.** The agent supplies the measured bottleneck and its evidence. - [record_diagnosis](optimization.py) retains that evidence and binds later deliveries - and rounds to the diagnosis. -- **Indexer.** Knowledge [ranks matches](../knowledge/knowledge_find.py) and assembles - context within the requested byte budget. Inspect the capture for delivered material, - source revisions and omissions. Start a fresh session with `--ranking-policy applicability` - to raise the applicability weight from 2 to 3. The default keeps the original six weights. -- **Executor.** [The round controller](optimization.py) owns attempts, time and round - budgets, pending work, recovery and final retests. It dispatches the retained candidate - to the task runner or the [service lifecycle](project_service.py). -- **Evaluator.** [_session_assess](optimization_session.py) dispatches packaged tasks to - their frozen assessment protocol and projects to [the AB/BA assessor](project.py). - In service mode, the optional screening report is diagnostic. Formal performance - and quality measurements in [evaluate](project_service.py) determine acceptance. +- **Manager** owns the session ledger, round and time budgets, pending work, recovery and final + retests. These operations share the [round controller](manager/_state.py). +- **Analyzer** [validates the reported bottleneck and measurement summary](analyzer/__init__.py). + [Manager](manager/__init__.py) records the diagnosis ID, time and condition epoch. The performance-ceiling + analysis skill lives in Knowledge. +- **Indexer** [checks managed deliveries](indexer/__init__.py) against the frozen ranking. + Apps injects the ordinary in-memory capture callback or the service context reader. + Knowledge [ranks matches](../knowledge/knowledge_find.py) + and assembles context within the requested byte budget. The capture records delivered material, + revisions and omissions. A new session can use `--ranking-policy applicability` to raise the + applicability weight from 2 to 3. The default keeps the original six weights. +- **Executor** owns the retained candidate, task runner and [service lifecycle](executor/serving/_attempt.py), + including measurement collection, process ownership and cleanup. +- **Evaluator** uses the frozen rules and stage receipts to decide the next stage or verdict. + `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](evaluator/_service.py) reads formal samples and quality evidence. + Its decision tells Executor which stages to skip, whether to collect or reuse a quality receipt, + and when the candidate has a formal verdict that can be checkpointed before cleanup. New plans freeze the ranking ID, scoring version and all effective weights. Ordinary plans and delivery receipts include a configuration digest. Service plans, manifests @@ -61,6 +93,102 @@ runs both policies against the same [complete corpus](../../../tests/fixtures/in at that Git revision. It also verifies an old capture after an undelivered entry changes the score in a fresh search. +## Managed session interfaces + +This diagram describes the component boundaries accepted for the [Harness migration](https://github.com/InferMatrixLab/InferRSI/issues/702). +The loop runs synchronously. Manager alone commits session state. Executor owns live processes +and leases. Evaluator reads frozen criteria, references and stage receipts. + +```mermaid +sequenceDiagram + participant C as Apps (host) + participant M as Manager (session and budget) + participant A as Analyzer + participant I as Indexer + participant K as Knowledge (injected reader) + participant X as Executor (service and lease) + participant V as Evaluator + C->>M: Operation, options and dependencies + opt Register a diagnosis + M->>A: Reported bottleneck and measurement evidence + A-->>M: Diagnosis draft for Manager to bind and record + end + opt Request a managed knowledge delivery + M->>I: Request ID, diagnosis ID, condition epoch and frozen ranking + I->>K: Read via the injected capture callback or service reader + K-->>I: Prepared content, observed request and ranking + I-->>M: Checked request, content and receipt + M->>M: Check ID, diagnosis and epoch under lock, retain context and register once + end + alt Recover an existing attempt + alt Ordinary session + M->>M: Check the runtime fingerprint and retained execution + else Service-reuse session + M->>M: Check the plan version before writing + M->>M: Match the checkpoint and cleanup proof to the original attempt and service + end + else Execute a new attempt + M->>M: Record pending work and its budget under the lock + M->>X: Frozen candidate, execution identity, protocol and deadline + alt Service-reuse evaluation + X->>V: Functional precheck receipt + alt Precheck rejects or evidence is incomplete + X-->>M: Return FAIL or INCONCLUSIVE before service start + else Precheck passes + X->>X: Start the service and verify readiness and binding + opt Configured candidate performance screening + X->>V: Screening samples for a diagnostic estimate + end + X->>V: Role, binding, frozen references and formal measurements + V-->>X: Performance decision and required quality evidence + opt Quality required + X->>V: Live quality receipt or retained baseline reference + V-->>X: Quality decision or incompatible evidence + end + opt Candidate reached a formal verdict + X->>X: Persist the candidate checkpoint + opt Eligible verdict and configured inline profiling + X->>X: Capture profile on this service and record the result or interruption + end + end + X->>X: Stop the service and capture cleanup proof + X-->>M: Stage receipts, any checkpoint and cleanup proof for this attempt + end + else Ordinary project steps or packaged task + opt Per-step check for an ordinary project + loop Until the first rejected step or the end of the plan + X->>V: Inspect the completed step through the injected check + V-->>X: Continue or stop before the next step + end + end + X-->>M: Execution, measurement and cleanup receipts + M->>V: Frozen protocol, execution receipts and injected assessor if applicable + V-->>M: Verdict and evidence references + end + end + M->>M: Under the lock, validate identity and evidence, then settle or retain pending work + M-->>C: Status, verdict and receipts +``` + +Each deliberate dispatch receives a new request ID. Redelivery of the same request can +commit once. A fresh diagnosis invalidates an outstanding result, even within the same +condition epoch. If these calls move to worker threads, Manager will persist pending work +under the lock before waiting and recheck request identity, deadline and cleanup on return. +Workers can exchange immutable inputs and evidence references. Live processes, leases and +storage connections stay with their owners. + +The ordinary project runner inspects each completed step before starting the next one. +Final assessment reuses the same inspection rules. A service candidate proceeds from +screening to formal measurements even when the screening estimate is low. A formal +performance failure skips quality. A baseline may reuse a matching quality receipt. +An incompatible scorer yields INCONCLUSIVE. Refreshing the parent performance reference +skips both quality and profiling. In a service-reuse candidate, a +successful gate check or formal performance failure permits inline profiling after the +checkpoint and before cleanup. A quality failure skips profiling. If that capture is +interrupted, recovery uses the checkpoint and retained capture progress. The separate +profile backfill operation uses its own live service, capture allowance and cleanup +receipt. Evaluator consumes the recorded results. Executor owns each live capture. + ## Evaluate retained runs With the Apps saved-request CLI, a trusted caller allocates the attempt before @@ -78,3 +206,5 @@ For extension points, see the [architecture](../../../docs/architecture.md#where The [RunStore tests](../../../tests/harness/test_harness_run_store.py) and [task protocol tests](../../../tests/benchmark/test_qwen_optimization_protocol.py) cover the storage and execution boundaries. + +The [pre-migration session fixtures and replay instructions](../../../tests/fixtures/optimization-session/component-freeze/README.md) record the ordinary and service-reuse contracts at the start of the component migration. diff --git a/src/inferrsi/harness/__init__.py b/src/inferrsi/harness/__init__.py index ccfcd35ed..9e0149b66 100644 --- a/src/inferrsi/harness/__init__.py +++ b/src/inferrsi/harness/__init__.py @@ -1,6 +1 @@ -"""Harness: command execution and RunStore records, the AB/BA runner, optimization -sessions and their records. Verdict labels come from contracts; reports are injected.""" - -from inferrsi.contracts.claim import Verdict, parse_verdict - -__all__ = ["Verdict", "parse_verdict"] +"""Harness execution, evidence records and managed optimization sessions.""" diff --git a/src/inferrsi/harness/analyzer/__init__.py b/src/inferrsi/harness/analyzer/__init__.py new file mode 100644 index 000000000..334aca892 --- /dev/null +++ b/src/inferrsi/harness/analyzer/__init__.py @@ -0,0 +1,20 @@ +"""Validate measured bottleneck evidence supplied to a managed session.""" + +from pathlib import Path + + +def diagnosis_draft(bottleneck: str, evidence: Path) -> dict: + """Read the caller's measurement summary before Manager records a diagnosis.""" + bottleneck = bottleneck.strip() + if not bottleneck or len(bottleneck) > 4096: + raise ValueError("Bottleneck must be a nonempty description of at most 4096 characters") + if evidence.is_symlink() or not evidence.is_file(): + raise ValueError("Diagnosis evidence must be a regular UTF-8 measurement summary") + with evidence.open("rb") as stream: + raw = stream.read(65537) + if len(raw) > 65536: + raise ValueError("Diagnosis evidence exceeds 64 KiB; provide a measurement summary") + summary = raw.decode("utf-8").strip() + if not summary or "\x00" in summary: + raise ValueError("Diagnosis evidence must contain a nonempty UTF-8 measurement summary") + return {"bottleneck": bottleneck, "measurement_summary": summary} diff --git a/src/inferrsi/harness/api/__init__.py b/src/inferrsi/harness/api/__init__.py new file mode 100644 index 000000000..5b3d419c2 --- /dev/null +++ b/src/inferrsi/harness/api/__init__.py @@ -0,0 +1,19 @@ +"""Public Harness execution ports and their shared error types.""" + +from inferrsi.contracts._harness_errors import ( + PUBLIC_ERROR_CODES, + PartialExecutionFacts, + PublicError, +) + +__all__ = [ + "PUBLIC_ERROR_CODES", "Harness", "PartialExecutionFacts", "PublicError", +] + + +def __getattr__(name): + if name == "Harness": + from ._harness import Harness + + return Harness + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/inferrsi/harness/api.py b/src/inferrsi/harness/api/_harness.py similarity index 86% rename from src/inferrsi/harness/api.py rename to src/inferrsi/harness/api/_harness.py index 523890c3a..eb450db79 100644 --- a/src/inferrsi/harness/api.py +++ b/src/inferrsi/harness/api/_harness.py @@ -2,10 +2,10 @@ from collections.abc import Mapping -from inferrsi.harness import execution_service, run_store -from inferrsi.harness.execution_service import LocalCpuTarget - -__all__ = ["Harness", "LocalCpuTarget"] +from inferrsi.harness.executor import LocalCpuTarget +from inferrsi.harness.executor import _execution as execution_service +from inferrsi.harness.records import RunStore +from inferrsi.harness.records import _run_store as run_store class Harness: @@ -16,7 +16,7 @@ class Harness: """ def __init__( - self, store: run_store.RunStore, target: LocalCpuTarget, *, artifact_reader=None, + self, store: RunStore, target: LocalCpuTarget, *, artifact_reader=None, evidence_capture=None, ): self._store = store diff --git a/src/inferrsi/harness/evaluator/__init__.py b/src/inferrsi/harness/evaluator/__init__.py new file mode 100644 index 000000000..2eee432cf --- /dev/null +++ b/src/inferrsi/harness/evaluator/__init__.py @@ -0,0 +1,89 @@ +"""Assess ordinary and service 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 +from ._service import ( + ServiceStageDecision, + aggregate_service_measurements, + assess_service_performance, + check_service_quality_reference, + prefer_service_measurements, + service_assessment, + service_measurement_decision, + service_metric_change, + service_precheck_passed, + service_profile_eligible, + service_quality_decision, + service_quality_passed, + service_quality_score, + service_ready, +) +from ._service_evidence import ( + service_choice, + service_reference_snapshot, + service_references_reason, + service_settlement_reason, +) + +__all__ = [ + "CONFIDENCE", + "DIRECTIONS", + "METHOD", + "MIN_PAIRS", + "ServiceStageDecision", + "aggregate_service_measurements", + "assess_ordinary", + "assess_project", + "assess_service_performance", + "check_service_quality_reference", + "explain", + "gate_speedup", + "inspect_project_step", + "interval_rank", + "median_interval", + "min_pairs", + "paired_speedups", + "paired_statistics", + "prefer_service_measurements", + "profile_evidence", + "project_steps", + "relative_mad", + "service_assessment", + "service_choice", + "service_measurement_decision", + "service_metric_change", + "service_precheck_passed", + "service_profile_eligible", + "service_quality_decision", + "service_quality_passed", + "service_quality_score", + "service_ready", + "service_reference_snapshot", + "service_references_reason", + "service_settlement_reason", + "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 da27f389f..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 .artifact_primitives import sha256 -from .measurement import MIN_PAIRS, explain, paired_statistics, profile_evidence, validate_mechanism - -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/evaluator/_service.py b/src/inferrsi/harness/evaluator/_service.py new file mode 100644 index 000000000..040fab1d9 --- /dev/null +++ b/src/inferrsi/harness/evaluator/_service.py @@ -0,0 +1,220 @@ +"""Decide service stages from frozen rules and already collected receipts.""" + +from dataclasses import dataclass +from statistics import mean, median + +from ..records import service_io + + +def _metric_value(document, key): + for part in key.split("."): + if not isinstance(document, dict) or part not in document: + raise ValueError(f"Missing metric: {key}") + document = document[part] + return document + + +def aggregate_service_measurements(settings, documents, role): + if len(documents) != settings["sampling"][role]["repetitions"]: + raise ValueError("Incomplete performance repetitions") + samples = {obj["id"]: [] for obj in settings["objectives"]} + for document in documents: + for scenario in settings["scenarios"]: + result = document.get("scenarios", {}).get(scenario["id"], {}) + if ( + result.get("workload") != scenario["workload"] + or type(result.get("requests")) is not int + or result["requests"] != scenario["requests"] + or type(result.get("successes")) is not int + or not scenario["required_successes"] <= result["successes"] <= (result["requests"]) + ): + raise ValueError("Incomplete or incompatible scenario requests") + for obj in settings["objectives"]: + result = document["scenarios"][obj["scenario"]] + metric = _metric_value(result, obj["key"]) + if ( + result.get("units", {}).get(obj["id"]) != obj["unit"] + or not service_io.finite_number(metric) + or not (obj["domain"]["min"] <= metric <= obj["domain"]["max"]) + ): + raise ValueError(f"Invalid metric domain or unit: {obj['id']}") + samples[obj["id"]].append(metric) + aggregates = { + obj["id"]: (median if obj["aggregate"] == "median" else mean)(samples[obj["id"]]) + for obj in settings["objectives"] + } + if not all(service_io.finite_number(v) for v in aggregates.values()): + raise ValueError("Nonfinite aggregate") + return {"values": aggregates, "samples": samples} + + +def service_metric_change(obj, candidate, reference): + sign = 1 if obj["direction"] == "maximize" else -1 + delta = sign * (candidate - reference) + if obj["threshold_type"] == "relative_percent": + if reference == 0: + if candidate != 0: + raise ValueError(f"Undefined relative change from zero: {obj['id']}") + return 0 + delta = 100 * delta / abs(reference) + if not service_io.finite_number(delta): + raise ValueError("Nonfinite derived change") + return delta + + +def assess_service_performance(settings, measured, parent, initial, *, screening=False): + metrics, limits, gain, actual_gain = {}, True, False, False + for obj in settings["objectives"]: + name = obj["id"] + p = service_metric_change(obj, measured["values"][name], parent["values"][name]) + b = service_metric_change(obj, measured["values"][name], initial["values"][name]) + bounded = p >= -obj["parent_regression_limit"] and b >= -obj["cumulative_regression_limit"] + improved = obj["gain"] and p > 0 + metrics[name] = { + "value": measured["values"][name], + "unit": obj["unit"], + "parent_change": p, + "initial_change": b, + "limits_passed": bounded, + "gain_passed": improved and p >= obj["gain_threshold"], + "thresholds": { + key: obj[key] + for key in ( + "threshold_type", + "gain_threshold", + "parent_regression_limit", + "cumulative_regression_limit", + ) + }, + } + limits &= bounded + actual_gain |= improved + gain |= metrics[name]["gain_passed"] + passed = limits and (actual_gain if screening else gain) + return { + "passed": passed, + "metrics": metrics, + "reason": "performance_gate_satisfied" if passed else "performance_gate_not_met", + } + + +def prefer_service_measurements(settings, left, right): + by_id = {obj["id"]: obj for obj in settings["objectives"]} + for name in settings["ranking"]: + if left[name] != right[name]: + return ( + left[name] < right[name] + if by_id[name]["direction"] == "minimize" + else left[name] > right[name] + ) + return False + + +def service_quality_score(settings, document): + config = settings["quality"] + if document.get("dataset") != config["dataset"] or document.get("scorer") != config["scorer"]: + raise ValueError("Incompatible quality dataset/scorer") + score = _metric_value(document, config["key"]) + if ( + not service_io.finite_number(score) + or type(document.get("samples")) is not int + or document["samples"] != config["samples"] + ): + raise ValueError("Missing numerical quality evidence") + return score + + +def service_quality_passed(settings, score, reference=None): + config = settings["quality"] + sign = 1 if config["direction"] == "maximize" else -1 + if config["mode"] == "absolute": + return sign * (score - config["threshold"]) >= 0 + if reference is None or not service_io.finite_number(reference): + raise ValueError("Missing compatible baseline quality reference") + return sign * (score - reference) >= -config["tolerance"] + + +def service_assessment(verdict, reason, **fields): + return { + "status": "infrastructure_failure" if verdict == "INCONCLUSIVE" else "completed", + "verdict": verdict, + "eligible": verdict == "PASS", + "reason": reason, + **fields, + } + + +def service_ready(ready, *, revision, pid): + return ( + ready.get("ready") is True + and ready.get("ownership") == "local_process_domain" + and ready.get("owner_pid") == pid + and ready.get("loaded_revision") == revision + ) + + +@dataclass(frozen=True) +class ServiceStageDecision: + """Ordered groups of skipped steps, followed by a verdict or a quality evidence request.""" + + assessment: dict | None + skipped: tuple[tuple[tuple[str, ...], str], ...] = () + quality_reference: str | None = None + + +def service_precheck_passed(receipt): + if receipt.get("status") == "candidate_failure" or receipt.get("passed") is False: + return False + if receipt.get("passed") is not True: + raise ValueError("Missing functional/numerical check evidence") + return True + + +def service_measurement_decision(role, reference_kind, gate, quality): + if not gate["passed"]: + skipped = ((("quality",), "performance_gate_not_met"),) + if role != "candidate": + skipped += ((("profile",), "not_required"),) + return ServiceStageDecision( + service_assessment("FAIL", "performance_gate_not_met", performance=gate), + skipped, + ) + if reference_kind == "parent": + return ServiceStageDecision( + service_assessment( + "PASS", "performance_reference_refreshed", performance=gate, eligible=False + ), + ((("quality", "profile"), "performance_reference_only"),), + ) + reference = quality.get("reference_path") if role == "baseline" else None + return ServiceStageDecision(None, quality_reference=reference) + + +def check_service_quality_reference(settings, receipt, revision, conditions): + if ( + receipt.get("revision") != revision + or receipt.get("conditions") != conditions + or not receipt.get("service_id") + or not receipt.get("run_id") + ): + raise ValueError("quality: missing/stale/incompatible baseline reference") + service_quality_score(settings, receipt) + + +def service_quality_decision(role, gate, passed): + if not passed: + return ServiceStageDecision( + service_assessment( + "FAIL", "quality_gate_not_met", quality_passed=False, performance=gate + ), + ((("profile",), "quality_gate_not_met"),), + ) + skipped = ((("profile",), "not_required"),) if role != "candidate" else () + return ServiceStageDecision( + service_assessment("PASS", "fixed_checks_satisfied", quality_passed=True, performance=gate), + skipped, + ) + + +def service_profile_eligible(reason): + return reason in ("fixed_checks_satisfied", "performance_gate_not_met") diff --git a/src/inferrsi/harness/service_evidence.py b/src/inferrsi/harness/evaluator/_service_evidence.py similarity index 85% rename from src/inferrsi/harness/service_evidence.py rename to src/inferrsi/harness/evaluator/_service_evidence.py index aa2233a0a..830c6320f 100644 --- a/src/inferrsi/harness/service_evidence.py +++ b/src/inferrsi/harness/evaluator/_service_evidence.py @@ -2,23 +2,24 @@ from pathlib import Path -from . import project_service as service +from ..records import service_io +from . import _service -def reference_snapshot(reference): +def service_reference_snapshot(reference): """Retain selection evidence. The source attempt owns its optional inline profile.""" if not reference: return reference snapshot = dict(reference) snapshot.pop("profile", None) if snapshot.get("parent_reference_at_acceptance"): - snapshot["parent_reference_at_acceptance"] = reference_snapshot( + snapshot["parent_reference_at_acceptance"] = service_reference_snapshot( snapshot["parent_reference_at_acceptance"] ) return snapshot -def choice(pending, execution): +def service_choice(pending, execution): return { "kind": "candidate" if pending["role"] == "candidate" else "baseline", "attempt_id": pending["attempt_id"], @@ -49,30 +50,32 @@ def evaluation_reason(root, plan, record): """Recheck the required receipts and gates for a reference, candidate or final run.""" execution, assessed = record["execution"], record["assessment"] try: - directory = service.safe_path(root, record["path"]) + directory = service_io.safe_path(root, record["path"]) expected = execution["binding"] if ( any(expected[key] != record[key] for key in ("attempt_id", "revision", "conditions")) or not expected["service_id"] or not expected["run_id"] - or service.read(directory / "request.json") != expected + or service_io.read(directory / "request.json") != expected ): return "unverifiable_selected_attempt_binding" config = record["conditions"]["effective_config"] try: - actual_config = service.read(directory / "effective-config.json") + actual_config = service_io.read(directory / "effective-config.json") except (ValueError, OSError): return "unverifiable_selected_configuration" if expected["effective_config"] != config or actual_config != config: return "unverifiable_selected_configuration" def receipt(stage): - doc = service.read(service.safe_path(directory, "execution/" + stage + "/result.json")) + path = service_io.safe_path(directory, "execution/" + stage + "/result.json") + doc = service_io.read(path) if doc.get("binding") != expected: raise ValueError("Incompatible stage binding") return doc - precheck = service.read(service.safe_path(directory, "execution/precheck/result.json")) + precheck_path = service_io.safe_path(directory, "execution/precheck/result.json") + precheck = service_io.read(precheck_path) if assessed["reason"] == "functional_check_rejected": status = precheck.get("status") rejected = status == "candidate_failure" or ( @@ -85,13 +88,13 @@ def receipt(stage): if not rejected or retained != precheck or assessed["verdict"] != "FAIL": return "unverifiable_evaluation_evidence" return None - owner = service.read(service.safe_path(directory, "service/owner.json")) + owner = service_io.read(service_io.safe_path(directory, "service/owner.json")) ready = receipt("ready") if ( precheck.get("passed") is not True or precheck.get("status") != "completed" or ready.get("status") != "completed" - or not service.ready_for_service(ready, revision=expected["revision"], pid=owner["pid"]) + or not _service.service_ready(ready, revision=expected["revision"], pid=owner["pid"]) or ready.get("loaded_root") != owner["cwd"] or any(owner.get(k) != v for k, v in expected.items()) ): @@ -105,11 +108,11 @@ def receipt(stage): docs = [receipt(f"measure-{i + 1:03d}") for i in range(sampling["repetitions"])] if any(doc.get("status") != "completed" for doc in docs): return "unverifiable_evaluation_evidence" - measured = service.aggregate(settings, docs, role) + measured = _service.aggregate_service_measurements(settings, docs, role) if measured != execution["measurements"]: return "unverifiable_evaluation_evidence" gate = ( - service.performance( + _service.assess_service_performance( settings, measured, record["parent"]["measurements"], @@ -131,8 +134,8 @@ def receipt(stage): settings["quality"].get("reference_path") if role == "baseline" else None ) if reference_path: - protocol = service.safe_path(root, record["protocol_path"]) - quality = service.read(service.safe_path(protocol, reference_path)) + protocol = service_io.safe_path(root, record["protocol_path"]) + quality = service_io.read(service_io.safe_path(protocol, reference_path)) retained = next((s for s in execution["steps"] if s["id"] == "quality"), {}) if quality != retained.get("result") or retained.get("path") != reference_path: return "unverifiable_evaluation_evidence" @@ -141,11 +144,11 @@ def receipt(stage): if quality.get("status") == "candidate_failure": score, passed = None, False elif reference_path or quality.get("status") == "completed": - score = service.quality_score(settings, quality) + score = _service.service_quality_score(settings, quality) initial_score = ( record["initial"]["quality_score"] if record.get("initial") else score ) - passed = service.quality_passed(settings, score, initial_score) + passed = _service.service_quality_passed(settings, score, initial_score) else: return "unverifiable_evaluation_evidence" if score != execution["quality_score"] or passed != assessed["quality_passed"]: @@ -182,7 +185,7 @@ def _reference_records(state): } -def references_reason(root, plan, state, *references): +def service_references_reason(root, plan, state, *references): """Check the accepted reference chain once per run, including its original measurements.""" records = {r["attempt_id"]: r for r in _reference_records(state)} remaining = [ref for ref in references if ref is not None] @@ -194,7 +197,7 @@ def references_reason(root, plan, state, *references): record = records.get(ref["attempt_id"]) if record is None: return "unverifiable_selected_attempt_binding" - expected = choice(record, record["execution"]) + expected = service_choice(record, record["execution"]) for key, value in expected.items(): if key != "parent_reference_at_acceptance" and ref.get(key) != value: return "unverifiable_selected_attempt_binding" @@ -220,7 +223,7 @@ def references_reason(root, plan, state, *references): return None -def settlement_reason(root, plan, state, record): +def service_settlement_reason(root, plan, state, record): """Recheck the evidence needed to settle this attempt's verdict.""" kind = record["kind"] assessed = record["assessment"] @@ -234,4 +237,6 @@ def settlement_reason(root, plan, state, record): if kind == "baseline": return None selected = state["best"] if kind == "final" else None - return references_reason(root, plan, state, record["parent"], record["initial"], selected) + return service_references_reason( + root, plan, state, record["parent"], record["initial"], selected + ) diff --git a/src/inferrsi/harness/execution_spec.py b/src/inferrsi/harness/execution_spec.py deleted file mode 100644 index 380cba2a2..000000000 --- a/src/inferrsi/harness/execution_spec.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Pure ExecutionSpec encoding helpers shared by H ports and their callers. - -This module has no RunStore or execution side effects. The digest covers the -complete canonical spec; storage implementations must use the same function. -""" - -import hashlib -from collections.abc import Mapping - -from inferrsi.contracts import json_v1 - - -def request_digest(spec: Mapping) -> str: - """Return the D017 semantic identifier of a complete ExecutionSpec.""" - return "sha256:" + hashlib.sha256(json_v1.encode(spec)).hexdigest() diff --git a/src/inferrsi/harness/executor/__init__.py b/src/inferrsi/harness/executor/__init__.py new file mode 100644 index 000000000..a578c7471 --- /dev/null +++ b/src/inferrsi/harness/executor/__init__.py @@ -0,0 +1,127 @@ +"""Local execution targets, serving helpers, generation preparation and input bindings.""" + +import hashlib +import os +import sys +from collections.abc import Mapping +from importlib.resources import files +from pathlib import Path + +from inferrsi.contracts import json_v1 + +__all__ = [ + "ImageProtocol", + "LocalCpuTarget", + "PROJECT_DECISIONS", + "TaskProtocolError", + "assess_packaged_task", + "benchmark_command", + "execute_ordinary", + "execute_service_attempt", + "launch_server", + "post_json", + "prepare_generation", + "prepare_project", + "prepare_service", + "prepare_task_protocol", + "process_group_empty", + "project_prepared_binding", + "read_prepared_binding", + "read_service_attempt_profile", + "request_digest", + "retain_service_revision", + "run_task_protocol", + "runtime_environment", + "service_capture_diagnostic", + "service_capture_elapsed", + "service_revision", + "stop_server", + "validate_project", + "validate_service_conditions", + "validate_service_settings", + "verify_prepared_binding", +] + + +def __getattr__(name): + if name == "execute_service_attempt": + from .serving._attempt import execute_service_attempt + + return execute_service_attempt + if name in ( + "prepare_service", "retain_service_revision", "service_revision", + "validate_service_conditions", "validate_service_settings", + ): + from .serving import _plan + + return getattr(_plan, name) + if name in ( + "read_service_attempt_profile", "service_capture_diagnostic", "service_capture_elapsed", + ): + from .serving import _profile + + return getattr(_profile, name) + if name == "ImageProtocol": + from .serving._image import ImageProtocol + + return ImageProtocol + if name == "post_json": + from .serving._http import post_json + + return post_json + if name in ("launch_server", "stop_server"): + from .serving import _server + + return getattr(_server, name) + if name == "LocalCpuTarget": + 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 + + return prepare_generation + if name in ("project_prepared_binding", "read_prepared_binding", "verify_prepared_binding"): + from . import _prepared_binding + + return getattr(_prepared_binding, name) + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +def process_group_empty(group: int) -> bool | None: + """Return whether the recorded group is empty, or None if it cannot be inspected.""" + from .local_process import _group_empty + + return _group_empty(group) + + +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 + + +def request_digest(spec: Mapping) -> str: + """Return the D017 semantic identifier of a complete ExecutionSpec.""" + return "sha256:" + hashlib.sha256(json_v1.encode(spec)).hexdigest() 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/entry_code.py b/src/inferrsi/harness/executor/_entry_code.py similarity index 97% rename from src/inferrsi/harness/entry_code.py rename to src/inferrsi/harness/executor/_entry_code.py index ef8ed3e6a..ca466553a 100644 --- a/src/inferrsi/harness/entry_code.py +++ b/src/inferrsi/harness/executor/_entry_code.py @@ -6,7 +6,7 @@ from dataclasses import dataclass from pathlib import Path -from . import input_binding +from . import _input_binding as input_binding _MODULE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*", re.ASCII) diff --git a/src/inferrsi/harness/evidence_capture.py b/src/inferrsi/harness/executor/_evidence_capture.py similarity index 98% rename from src/inferrsi/harness/evidence_capture.py rename to src/inferrsi/harness/executor/_evidence_capture.py index 1838148ba..a9e2e7618 100644 --- a/src/inferrsi/harness/evidence_capture.py +++ b/src/inferrsi/harness/executor/_evidence_capture.py @@ -8,8 +8,9 @@ from pathlib import Path from inferrsi.contracts import json_v1 -from inferrsi.harness import input_binding, run_store -from inferrsi.harness.errors import PublicError +from inferrsi.contracts._harness_errors import PublicError +from inferrsi.harness.executor import _input_binding as input_binding +from inferrsi.harness.records import _run_store as run_store CONTEXT_FIELDS = frozenset( "schema_version request_id run_id attempt_id request_digest prepared_ref protocol_digest " diff --git a/src/inferrsi/harness/execution_service.py b/src/inferrsi/harness/executor/_execution.py similarity index 96% rename from src/inferrsi/harness/execution_service.py rename to src/inferrsi/harness/executor/_execution.py index 55af0919f..2f40f6947 100644 --- a/src/inferrsi/harness/execution_service.py +++ b/src/inferrsi/harness/executor/_execution.py @@ -13,18 +13,20 @@ from pathlib import Path, PurePosixPath from inferrsi.contracts import json_v1 -from inferrsi.harness import ( - entry_code, - generation_lineage, - input_binding, +from inferrsi.contracts._harness_errors import PublicError +from inferrsi.harness.executor import ( + LocalCpuTarget, local_process, - prepared_binding, - run_store, + request_digest, + verify_prepared_binding, ) -from inferrsi.harness import ( - evidence_capture as capture_service, -) -from inferrsi.harness.errors import PublicError +from inferrsi.harness.executor import _entry_code as entry_code +from inferrsi.harness.executor import _evidence_capture as capture_service +from inferrsi.harness.executor import _generation_lineage as generation_lineage +from inferrsi.harness.executor import _input_binding as input_binding +from inferrsi.harness.executor import _prepared_binding as prepared_binding +from inferrsi.harness.records import RunStore +from inferrsi.harness.records import _run_store as run_store # The ordinary CPU path preserves V05 null mode. Evaluation requires an explicit trusted # module root, a fixed preparation binding and an actual source-entry snapshot before start. @@ -80,45 +82,6 @@ _USAGE_SOURCE = "harness-local-process" -@dataclass(frozen=True) -class LocalCpuTarget: - """Trusted host configuration of the local CPU target; never read from a request. - - ``work_root`` holds per-attempt workspaces (``workspaces/``) and private - capture snapshots. ``controller_root`` / ``target_root`` authorize input sources of - those namespaces; ``None`` leaves that namespace unauthorized. ``module_root`` - explicitly enables evaluation through standalone source entries under that trusted - root. The retained source is executed directly in an isolated Python interpreter; - package imports and ambient cwd/PYTHONPATH entry resolution are not used. - """ - - target_id: str - config_revision: str - work_root: Path - controller_root: Path | None = None - target_root: Path | None = None - module_root: Path | None = None - - def __post_init__(self) -> None: - errors = [ - f"{name}: not an Id" - for name in ("target_id", "config_revision") - if not run_store._is_id(getattr(self, name)) - ] - for name in ("work_root", "controller_root", "target_root", "module_root"): - value = getattr(self, name) - if value is None: - continue - object.__setattr__(self, name, Path(value)) - if not Path(value).is_absolute(): - errors.append(f"{name}: must be an explicit absolute local path") - if errors: - raise PublicError( - "InvalidRequest", stage="configure", message="illegal local CPU target", - field_errors=errors, - ) - - def _decimal(seconds: float) -> str: """A canonical non-negative Decimal string with microsecond resolution.""" text = f"{max(seconds, 0.0):.6f}".rstrip("0").rstrip(".") @@ -467,7 +430,7 @@ def _validate_fresh(spec, target, artifact_reader, evaluation, *, store=None): if evaluation: # Malformed or inconsistent bindings are refused here, before the RunStore sees the # request. The reader is the read-only port; H does not write or register anything. - prepared_binding.verify(spec, artifact_reader) + verify_prepared_binding(spec, artifact_reader) unsupported = [] if evaluation and target.module_root is None: unsupported.append("this target has no configured evaluation module root") @@ -1169,7 +1132,7 @@ def _run_claimed(ctx, target, digest, reader, deadline, cancellation, evidence_c def execute( - store: run_store.RunStore, + store: RunStore, target: LocalCpuTarget, spec: Mapping, *, @@ -1180,7 +1143,7 @@ def execute( """Execute one request or return its existing state before any new binding or start.""" evaluation = _validate_fields(spec) spec = copy.deepcopy(dict(spec)) - digest = run_store.request_digest(spec) + digest = request_digest(spec) attempt = {name: copy.deepcopy(spec[name]) for name in ATTEMPT_FIELDS} existing = store._reenter_if_registered(spec["attempt_id"], digest) if existing is not None: diff --git a/src/inferrsi/harness/generation.py b/src/inferrsi/harness/executor/_generation.py similarity index 93% rename from src/inferrsi/harness/generation.py rename to src/inferrsi/harness/executor/_generation.py index c80757479..715b9f2a2 100644 --- a/src/inferrsi/harness/generation.py +++ b/src/inferrsi/harness/executor/_generation.py @@ -4,17 +4,20 @@ from hashlib import sha256 from pathlib import PurePosixPath +from inferrsi.contracts._harness_errors import PublicError from inferrsi.contracts.json_v1 import encode -from inferrsi.harness import generation_feedback, run_store -from inferrsi.harness.errors import PublicError -from inferrsi.harness.execution_service import LocalCpuTarget, validate +from inferrsi.harness.executor import LocalCpuTarget, request_digest +from inferrsi.harness.executor import _generation_feedback as generation_feedback +from inferrsi.harness.executor._execution import validate +from inferrsi.harness.records import RunStore +from inferrsi.harness.records import _run_store as run_store _MANIFEST_FIELDS = {"schema_version", "provider", "output_contract", "context_refs", "attempt_id"} _MANIFEST_PATH = PurePosixPath("inputs/generation-plan.json") def prepare_generation( - store: run_store.RunStore, target: LocalCpuTarget, *, context_provider, candidate_provider, + store: RunStore, target: LocalCpuTarget, *, context_provider, candidate_provider, context_request: dict, candidate_context: dict, attempt: dict, feedback_policy_ref=None, feedback_record_refs=(), artifact_reader=None, ) -> dict: @@ -128,7 +131,7 @@ def _bind_generation_plan(store, target, attempt, plan, delivery_ref, *, feedbac }) validate(spec, target) # Commit the binding with the manifest, outside the manifest's own bytes. - digest = run_store.request_digest(spec) + digest = request_digest(spec) bounds = { "schema_version": 1, **{key: deepcopy(spec[key]) for key in ( diff --git a/src/inferrsi/harness/generation_feedback.py b/src/inferrsi/harness/executor/_generation_feedback.py similarity index 98% rename from src/inferrsi/harness/generation_feedback.py rename to src/inferrsi/harness/executor/_generation_feedback.py index 1e1af1819..c8f92e49d 100644 --- a/src/inferrsi/harness/generation_feedback.py +++ b/src/inferrsi/harness/executor/_generation_feedback.py @@ -8,8 +8,9 @@ from hashlib import sha256 from inferrsi.contracts import json_v1 -from inferrsi.harness import prepared_binding, run_store -from inferrsi.harness.errors import PublicError +from inferrsi.contracts._harness_errors import PublicError +from inferrsi.harness.executor import _prepared_binding as prepared_binding +from inferrsi.harness.records import _run_store as run_store ROLE = "generation_feedback_policy" PATH = "inputs/generation-feedback-policy.json" @@ -162,7 +163,7 @@ def _plan(value, context): "policy belongs to another campaign", "IdentityMismatch") _shape(value["starting_point"], {"candidate", "inputs", "generation_record_ref"}) _candidate(value["starting_point"]["candidate"]) - from inferrsi.harness.execution_service import _input_errors + from inferrsi.harness.executor._execution import _input_errors _require(not _input_errors(value["starting_point"]["inputs"]), "invalid starting inputs") _require(sum(item["role"] == value["starting_point"]["candidate"]["input_role"] @@ -192,7 +193,7 @@ def _requirements(reader, scoped): ref = scoped["prepared_ref"] data = _read(reader, ref["artifact"]) try: - fixed = prepared_binding.project(data) + fixed = prepared_binding.project_prepared_binding(data) except PublicError as exc: code = "InvalidRequest" if exc.code == "InvalidExecutionSpec" else exc.code raise _fail(code, exc.message) from exc diff --git a/src/inferrsi/harness/generation_lineage.py b/src/inferrsi/harness/executor/_generation_lineage.py similarity index 97% rename from src/inferrsi/harness/generation_lineage.py rename to src/inferrsi/harness/executor/_generation_lineage.py index 232c765f4..89fafbb04 100644 --- a/src/inferrsi/harness/generation_lineage.py +++ b/src/inferrsi/harness/executor/_generation_lineage.py @@ -5,8 +5,9 @@ from hashlib import sha256 from inferrsi.contracts import json_v1 -from inferrsi.harness import prepared_binding, run_store -from inferrsi.harness.errors import PublicError +from inferrsi.contracts._harness_errors import PublicError +from inferrsi.harness.executor import _prepared_binding as prepared_binding +from inferrsi.harness.records import _run_store as run_store _PLAN_FIELDS = {"schema_version", "provider", "output_contract", "context_refs", "attempt_id"} @@ -75,7 +76,7 @@ def _source(store, spec): _require(bounds["request_digest"] == record["request_digest"] and all(bounds[key] == record[key] for key in ("attempt_id", "run_id", "owner")), "generation differs from its original sealed binding") - from inferrsi.harness.execution_service import _request_errors + from inferrsi.harness.executor._execution import _request_errors _require(not _request_errors({**spec, "budget": bounds["budget"]}), "invalid original budget snapshot", "ArtifactIntegrityError") diff --git a/src/inferrsi/harness/input_binding.py b/src/inferrsi/harness/executor/_input_binding.py similarity index 100% rename from src/inferrsi/harness/input_binding.py rename to src/inferrsi/harness/executor/_input_binding.py 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/prepared_binding.py b/src/inferrsi/harness/executor/_prepared_binding.py similarity index 97% rename from src/inferrsi/harness/prepared_binding.py rename to src/inferrsi/harness/executor/_prepared_binding.py index dbeb6709e..f1098ba0e 100644 --- a/src/inferrsi/harness/prepared_binding.py +++ b/src/inferrsi/harness/executor/_prepared_binding.py @@ -20,8 +20,9 @@ from dataclasses import dataclass from inferrsi.contracts import json_v1 -from inferrsi.harness import input_binding, run_store -from inferrsi.harness.errors import PublicError +from inferrsi.contracts._harness_errors import PublicError +from inferrsi.harness.executor import _input_binding as input_binding +from inferrsi.harness.records import _run_store as run_store STAGE = "prepared_binding" PREPARED_MEDIA_TYPE = "application/json" @@ -150,7 +151,7 @@ def _recipe_errors(recipe: object) -> list[str]: return errors -def read(ref: Mapping, reader) -> bytes: +def read_prepared_binding(ref: Mapping, reader) -> bytes: """The fixed bytes of ``ref`` from the read-only port, verified against the Ref. The port's own verification is not trusted: size and hash are checked here again @@ -196,7 +197,7 @@ def read(ref: Mapping, reader) -> bytes: return b"".join(parts) -def project(data: bytes) -> FixedPreparation: +def project_prepared_binding(data: bytes) -> FixedPreparation: """Parse the identity fields of canonical PreparedEvaluation bytes.""" try: prepared = json_v1.decode(data) @@ -347,13 +348,14 @@ def _worker_errors(spec: Mapping, recipe: dict) -> list[str]: return errors -def verify(spec: Mapping, reader) -> FixedPreparation: +def verify_prepared_binding(spec: Mapping, reader) -> FixedPreparation: """Check an evaluation-mode spec against its fixed preparation before registration. ``spec`` has passed the static ExecutionSpec checks, so its evaluation fields are all set and well formed. Raises a PublicError for any malformed or inconsistent binding. """ - fixed = project(read(spec["prepared_ref"]["artifact"], reader)) + data = read_prepared_binding(spec["prepared_ref"]["artifact"], reader) + fixed = project_prepared_binding(data) if fixed.identity_rule not in (CAPTURED_SHA256, EXPECTED_SHA256): raise _refuse( "UnsupportedRuleVersion", "the frozen candidate identity rule is unsupported" 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/executor/_target.py b/src/inferrsi/harness/executor/_target.py new file mode 100644 index 000000000..10683d7e7 --- /dev/null +++ b/src/inferrsi/harness/executor/_target.py @@ -0,0 +1,48 @@ +"""Trusted local CPU target configuration supplied by the host.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from inferrsi.contracts._harness_errors import PublicError +from inferrsi.harness.records import _run_store as run_store + + +@dataclass(frozen=True) +class LocalCpuTarget: + """Trusted host configuration of the local CPU target; never read from a request. + + ``work_root`` holds per-attempt workspaces (``workspaces/``) and private + capture snapshots. ``controller_root`` / ``target_root`` authorize input sources of + those namespaces; ``None`` leaves that namespace unauthorized. ``module_root`` + explicitly enables evaluation through standalone source entries under that trusted + root. The retained source is executed directly in an isolated Python interpreter; + package imports and ambient cwd/PYTHONPATH entry resolution are not used. + """ + + target_id: str + config_revision: str + work_root: Path + controller_root: Path | None = None + target_root: Path | None = None + module_root: Path | None = None + + def __post_init__(self) -> None: + errors = [ + f"{name}: not an Id" + for name in ("target_id", "config_revision") + if not run_store._is_id(getattr(self, name)) + ] + for name in ("work_root", "controller_root", "target_root", "module_root"): + value = getattr(self, name) + if value is None: + continue + object.__setattr__(self, name, Path(value)) + if not Path(value).is_absolute(): + errors.append(f"{name}: must be an explicit absolute local path") + if errors: + raise PublicError( + "InvalidRequest", stage="configure", message="illegal local CPU target", + field_errors=errors, + ) diff --git a/src/inferrsi/harness/task_protocol.py b/src/inferrsi/harness/executor/_task_protocol.py similarity index 92% rename from src/inferrsi/harness/task_protocol.py rename to src/inferrsi/harness/executor/_task_protocol.py index 83825a654..7687ed104 100644 --- a/src/inferrsi/harness/task_protocol.py +++ b/src/inferrsi/harness/executor/_task_protocol.py @@ -15,8 +15,8 @@ import time from pathlib import Path +from ..records.artifact_primitives import sha256 from . import local_process, protocol_child -from .artifact_primitives import sha256 from .launch_records import LaunchRecord # One protocol operation must finish within this time; the child and every process in @@ -91,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 @@ -181,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")) @@ -196,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/artifact_sandbox.py b/src/inferrsi/harness/executor/artifact_sandbox.py similarity index 100% rename from src/inferrsi/harness/artifact_sandbox.py rename to src/inferrsi/harness/executor/artifact_sandbox.py diff --git a/src/inferrsi/harness/candidates.py b/src/inferrsi/harness/executor/candidates.py similarity index 98% rename from src/inferrsi/harness/candidates.py rename to src/inferrsi/harness/executor/candidates.py index 75772da9c..094e6ad78 100644 --- a/src/inferrsi/harness/candidates.py +++ b/src/inferrsi/harness/executor/candidates.py @@ -4,7 +4,7 @@ import stat from pathlib import Path -from .artifact_primitives import digest, sha256 +from ..records.artifact_primitives import digest, sha256 def members(source: Path, includes: list[str] | None = None) -> dict[str, Path]: diff --git a/src/inferrsi/harness/confinement.py b/src/inferrsi/harness/executor/confinement.py similarity index 99% rename from src/inferrsi/harness/confinement.py rename to src/inferrsi/harness/executor/confinement.py index 7b82da5e1..90a8035a8 100644 --- a/src/inferrsi/harness/confinement.py +++ b/src/inferrsi/harness/executor/confinement.py @@ -26,10 +26,11 @@ from pathlib import Path _ENV_ALLOW = frozenset({"PATH", "LANG", "LC_ALL", "LC_CTYPE", "TZ", "PYTHONIOENCODING"}) -_PACKAGE_ROOT = str(Path(__file__).resolve().parents[2]) +_PACKAGE_ROOT = str(Path(__file__).resolve().parents[3]) _SUPERVISOR = ( "import sys; sys.path.insert(0, sys.argv[1]); " - "from inferrsi.harness.confinement import enter_namespace; enter_namespace(sys.argv[2])" + "from inferrsi.harness.executor.confinement import enter_namespace; " + "enter_namespace(sys.argv[2])" ) _REAP_SECONDS = 10.0 _GUARD = """ diff --git a/src/inferrsi/harness/device_lease.py b/src/inferrsi/harness/executor/device_lease.py similarity index 97% rename from src/inferrsi/harness/device_lease.py rename to src/inferrsi/harness/executor/device_lease.py index 6efe343cc..1ecafd6df 100644 --- a/src/inferrsi/harness/device_lease.py +++ b/src/inferrsi/harness/executor/device_lease.py @@ -4,7 +4,7 @@ from contextlib import AbstractContextManager from pathlib import Path, PureWindowsPath -from .artifact_primitives import file_lock +from ..records.artifact_primitives import file_lock class LeaseError(RuntimeError): diff --git a/src/inferrsi/harness/launch_records.py b/src/inferrsi/harness/executor/launch_records.py similarity index 97% rename from src/inferrsi/harness/launch_records.py rename to src/inferrsi/harness/executor/launch_records.py index 9f5a83fc6..a94b6a390 100644 --- a/src/inferrsi/harness/launch_records.py +++ b/src/inferrsi/harness/executor/launch_records.py @@ -6,8 +6,8 @@ from itertools import count from pathlib import Path -from .artifact_primitives import digest -from .atomic_json import durable_write_json +from ..records.artifact_primitives import digest +from ..records.atomic_json import durable_write_json def linux_process_domain() -> tuple[str | None, str | None]: diff --git a/src/inferrsi/harness/local_process.py b/src/inferrsi/harness/executor/local_process.py similarity index 99% rename from src/inferrsi/harness/local_process.py rename to src/inferrsi/harness/executor/local_process.py index a1e59b16b..dbd1fe29c 100644 --- a/src/inferrsi/harness/local_process.py +++ b/src/inferrsi/harness/executor/local_process.py @@ -6,7 +6,7 @@ from datetime import datetime, timezone from pathlib import Path -from .atomic_json import atomic_write_json +from ..records.atomic_json import atomic_write_json # H local process control domain (moved from infra in H02): one command inside its # Windows Job or POSIX process group, deadline and cancellation, and tree cleanup. @@ -181,10 +181,13 @@ def _stop_tree(process: subprocess.Popen, windows_job: _WindowsJob | None = None def _group_empty(group: int) -> bool | None: """Confirm a POSIX process group has no member left; None when unobservable.""" + killpg = getattr(os, "killpg", None) + if killpg is None: + return None deadline = time.monotonic() + _DRAIN_SECONDS while True: try: - os.killpg(group, 0) + killpg(group, 0) except ProcessLookupError: return True except PermissionError: 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/serving/__init__.py b/src/inferrsi/harness/executor/serving/__init__.py similarity index 100% rename from src/inferrsi/harness/serving/__init__.py rename to src/inferrsi/harness/executor/serving/__init__.py diff --git a/src/inferrsi/harness/executor/serving/_attempt.py b/src/inferrsi/harness/executor/serving/_attempt.py new file mode 100644 index 000000000..c404a21dc --- /dev/null +++ b/src/inferrsi/harness/executor/serving/_attempt.py @@ -0,0 +1,447 @@ +"""Execute the service stages and persist the candidate checkpoint before cleanup.""" + +import os +import time +import uuid + +from ... import evaluator +from ...records import service_io +from ...records.atomic_json import atomic_write_json +from ..candidates import members, retain +from ._plan import retain_service_revision +from ._profile import service_capture_diagnostic, validated_profile + + +def execute_service_attempt(root, directory, plan, pending, deadline): + """One retained attempt, one owned service, ordered client stages, no silent retry.""" + from .. import runtime_environment + from ..local_process import supervised_service + from ..trials.external import execute_trial + + settings = plan["evaluation_settings"] + conditions = pending["conditions"] + config = conditions["effective_config"] + source = directory / "candidate" + workspace = directory / "workspace" + expected = { + "attempt_id": pending["attempt_id"], + "service_id": uuid.uuid4().hex, + "run_id": uuid.uuid4().hex, + "revision": pending["revision"], + "conditions": conditions, + "effective_config": config, + } + atomic_write_json(directory / "request.json", expected) + atomic_write_json(directory / "effective-config.json", config) + receipt = directory / "service.json" + values = { + "python": plan["python"], + "candidate": str(workspace), + "baseline": str(root / plan["baseline_path"]), + "service_receipt": str(receipt), + "effective_config": str(directory / "effective-config.json"), + "attempt_dir": str(directory), + } + environment = runtime_environment() + environment.update( + INFERRSI_ATTEMPT_REQUEST=str(directory / "request.json"), PYTHONDONTWRITEBYTECODE="1" + ) + environment["PYTHONPATH"] = str(workspace) + os.pathsep + environment["PYTHONPATH"] + end = time.monotonic() + min(plan["evaluation_timeout_seconds"], max(0, deadline - time.time())) + record = { + "status": "running", + "steps": [], + "cleanup_verified": None, + "binding": expected, + "assessment": None, + "cleanup_timeout_seconds": settings["sampling"]["stage_timeout_seconds"], + "cleanup_budget_scope": "separate_from_evaluation", + } + output = directory / "execution" + output.mkdir() + started, process, owner = time.monotonic(), None, None + standalone = pending.get("kind") == "profile" + sampling = settings["sampling"] + profile_timeout = sampling.get("profile_timeout_seconds", sampling["stage_timeout_seconds"]) + capture_started = None + + def save(): + atomic_write_json(output / "execution.json", record) + + def begin_capture(): + nonlocal capture_started + capture_started = time.monotonic() + record["capture"] = { + "id": pending["attempt_id"], "started_at": time.time(), "elapsed_seconds": 0.0, + } + save() + + def finish_capture(): + nonlocal capture_started + record["capture"].update( + elapsed_seconds=time.monotonic() - capture_started, ended_at=time.time() + ) + capture_started = None + save() + + def command(argv): + for key, val in values.items(): + argv = [arg.replace("{" + key + "}", val) for arg in argv] + return argv + + def binding(document): + if document.get("binding") != expected: + raise ValueError("Service/revision/configuration binding mismatch") + + def stage(name, *, bound=True, argv=None): + definition = { + "id": name, + "status": "running", + "started_at": time.time(), + "execution_status": "not_started", + } + if capture_started is not None: + offset = time.monotonic() - capture_started + definition["capture_offset_seconds"] = offset + record["capture"]["elapsed_seconds"] = offset + record["steps"].append(definition) + save() + if bound and (process is None or process.poll() is not None): + raise ValueError(f"Service unavailable before {name}") + stage_end = time.monotonic() + sampling["stage_timeout_seconds"] + if name != "stop": + if capture_started is None: + stage_end = min(end, stage_end) + else: + capture_end = capture_started + profile_timeout + stage_end = capture_end if name == "profile" else min(stage_end, capture_end) + executed = execute_trial( + tuple(command(argv or settings["commands"][name.split("-")[0]])), + workspace, + output / name, + stage_end, + None, + environment=environment, + ) + definition.update(executed, execution_status=executed["status"], ended_at=time.time()) + if isinstance(definition.get("error"), str): + definition["error"] = service_io.error_excerpt(definition["error"]) + if capture_started is not None: + record["capture"]["elapsed_seconds"] = time.monotonic() - capture_started + save() + if executed["status"] != "completed": + detail = definition.get("error") or f"exit {executed.get('returncode')}" + if executed["status"] == "cancelled": + raise KeyboardInterrupt(service_io.error_excerpt(f"{name}: {detail}")) + raise ValueError(service_io.error_excerpt(f"{name}: {executed['status']}: {detail}")) + document = service_io.read(output / name / "result.json") + if bound: + binding(document) + if process.poll() is not None: + raise ValueError(f"Service exited during {name}") + candidate_failure = document.get("status") == "candidate_failure" and name.startswith( + ("precheck", "quality") + ) + if not candidate_failure and document.get("status") != "completed": + detail = document.get("error") or document.get("message") + if not detail: + detail = f"expected completed stage evidence, got {document.get('status')!r}" + raise ValueError(service_io.error_excerpt(f"{name}: {detail}")) + if name != "profile" and not standalone: + definition["result"] = document + save() + return document + + def skipped(names, reason): + record["steps"].extend( + {"id": name, "status": "skipped", "reason": reason} for name in names + ) + save() + + measured, gate, score, profile, quality_ok = None, None, None, None, None + + def evaluate(role): + nonlocal measured, gate, score, quality_ok + parent, initial = pending.get("parent"), pending.get("initial") + screen = settings.get("screening") + if role == "candidate" and screen: + try: + docs = [ + stage(f"screening-{i + 1:03d}", argv=screen["command"]) + for i in range(settings["sampling"][role]["repetitions"]) + ] + preview = evaluator.aggregate_service_measurements(settings, docs, role) + record["screening"] = evaluator.assess_service_performance( + settings, + preview, + parent["measurements"], + initial["measurements"], + screening=True, + ) + record["screening"].update( + measurements=preview, estimated_gain=screen["estimated_gain"] + ) + except Exception as error: + # A malformed screening receipt is diagnostic; formal measurements follow. + record["screening"] = {"error": str(error)} + record["steps"][-1].update(status="failed", reason=str(error)) + save() + docs = [] + first_failure = None + for i in range(sampling[role]["repetitions"]): + name = f"measure-{i + 1:03d}" + try: + docs.append(stage(name)) + except (ValueError, TypeError, KeyError, OSError) as error: + if first_failure is None: + first_failure = (name, error) + step = record["steps"][-1] + if step["status"] in ("running", "completed"): + step["status"] = "failed" + step["reason"] = str(error) + save() + if process.poll() is not None or time.monotonic() >= end: + break + if first_failure is not None: + record["failed_stage"], error = first_failure + raise error + measured = evaluator.aggregate_service_measurements(settings, docs, role) + gate = ( + evaluator.assess_service_performance( + settings, measured, parent["measurements"], initial["measurements"] + ) + if parent is not None + else {"passed": True, "metrics": {}} + ) + decision = evaluator.service_measurement_decision( + role, pending.get("reference_kind"), gate, settings["quality"], + ) + if decision.assessment is None: + if decision.quality_reference: + reference_step = { + "id": "quality", + "status": "running", + "source": "retained_baseline_reference", + "path": decision.quality_reference, + "started_at": time.time(), + } + record["steps"].append(reference_step) + save() + quality = service_io.read( + service_io.safe_path( + service_io.safe_path( + root, pending.get("protocol_path", "frozen/protocol") + ), + decision.quality_reference, + ) + ) + evaluator.check_service_quality_reference( + settings, quality, pending["revision"], conditions + ) + reference_step.update( + status="completed", ended_at=time.time(), result=quality + ) + save() + else: + quality = stage("quality") + if quality.get("status") == "candidate_failure": + quality_ok = False + else: + score = evaluator.service_quality_score(settings, quality) + quality_ok = evaluator.service_quality_passed( + settings, + score, + (initial.get("quality_score") if initial else score), + ) + decision = evaluator.service_quality_decision(role, gate, quality_ok) + for stages, reason in decision.skipped: + skipped(stages, reason) + record["assessment"] = decision.assessment + + def checkpoint_candidate(): + quality_step = next(step for step in record["steps"] if step["id"] == "quality") + record["checkpoint"] = { + "assessment": record["assessment"], + "binding": expected, + "measurements": measured, + "measurement_results": [ + (output / step["id"] / "result.json").relative_to(root).as_posix() + for step in record["steps"] if step["id"].startswith("measure-") + ], + "quality": quality_step, + "quality_score": score, + } + save() + + def profile_error(name, error): + step = next((s for s in reversed(record["steps"]) if s["id"] == name), {}) + execution_status = step.get("execution_status") + if isinstance(error, KeyboardInterrupt) or execution_status == "cancelled": + status = "interrupted" + elif isinstance(error, TimeoutError) or execution_status == "timeout": + status = "timed_out" + else: + status = "failed" + diagnostic = service_capture_diagnostic( + root, directory, name, status, str(error) or status, + process_failed=execution_status not in (None, "not_started", "completed"), + ) + record["profiling_error"] = diagnostic + step.pop("result", None) + if step.get("status") in ("running", "completed"): + step.update(status="failed", reason=diagnostic["message"]) + save() + + def capture_profile(): + nonlocal profile + if "profile" not in settings["commands"]: + skipped(("profile",), "not_configured") + return + try: + if not standalone: + begin_capture() + trace = stage("profile") + validated = validated_profile( + root, directory, pending["attempt_id"], conditions, expected, record["steps"][-1], + captured=trace, + ) + if time.monotonic() >= capture_started + profile_timeout: + raise TimeoutError("Profiling timeout during capture validation") + profile = validated + record["profile"] = profile + except (Exception, KeyboardInterrupt) as error: + profile_error("profile", error) + finally: + if not standalone and capture_started is not None: + finish_capture() + + try: + if standalone: + begin_capture() + protocol = service_io.safe_path(root, pending.get("protocol_path", "frozen/protocol")) + values["protocol"] = str(protocol) + if standalone: + members(protocol) + if "profile" not in settings["commands"]: + raise ValueError("No profiler configured in the retained protocol") + # Rebuild from Git objects; retained directories can be replaced after acceptance. + repository = pending.get("source_repo") + if not repository: + raise ValueError("Authoritative source repository is unavailable") + retain_service_revision( + repository, workspace, plan["candidate_includes"], pending["revision"], + deadline=capture_started + profile_timeout if standalone else None, + ) + if not standalone and not source.exists(): + retain(workspace, source, fingerprint=False) + precheck = stage("precheck", bound=False) + if not evaluator.service_precheck_passed(precheck): + skipped(("service", "measurement", "quality", "profile"), "precheck_rejected") + record["assessment"] = evaluator.service_assessment("FAIL", "functional_check_rejected") + if standalone: + detail = precheck.get("error") or precheck.get("message") + profile_error("precheck", ValueError(service_io.error_excerpt( + str(detail or "Functional check rejected") + ))) + record["cleanup_verified"] = True + else: + if standalone and time.monotonic() >= capture_started + profile_timeout: + record["failed_stage"] = "service" + raise TimeoutError("Profiling timeout before service startup") + service_step = {"id": "service", "status": "running", "started_at": time.time()} + record["steps"].append(service_step) + save() + with supervised_service( + [*plan["evaluation_prefix"], *command(settings["commands"]["service"])], + workspace, + environment, + directory / "service", + expected, + ) as (process, owner): + service_step.update(pid=process.pid, owner_path="service/owner.json") + save() + try: + ready = stage("ready") + if ( + not evaluator.service_ready( + ready, revision=expected["revision"], pid=process.pid + ) + or ready.get("loaded_root") != str(workspace.resolve()) + ): + raise ValueError("Service readiness/ownership unverified") + role = pending["role"] + for index in range(sampling[role]["warmups"]): + stage(f"warmup-{index + 1:03d}") + if standalone: + capture_profile() + record["assessment"] = evaluator.service_assessment( + "PASS" if profile else "INCONCLUSIVE", "profile_only", eligible=False + ) + else: + evaluate(role) + if role == "candidate": + checkpoint_candidate() + if evaluator.service_profile_eligible(record["assessment"]["reason"]): + capture_profile() + except BaseException: + record.setdefault("failed_stage", record["steps"][-1]["id"]) + raise + finally: + try: + cleanup = stage("stop", bound=False) + binding(cleanup) + record["external_cleanup_verified"] = ( + cleanup.get("cleanup_complete") is True + ) + except (OSError, ValueError, KeyError) as error: + record["external_cleanup_verified"] = False + record["cleanup_error"] = service_io.error_excerpt(str(error)) + record["cleanup_verified"] = ( + owner["domain_empty"] is True and record.get("external_cleanup_verified") is True + ) + if not record["cleanup_verified"]: + raise ValueError(record.get("cleanup_error") or "Service cleanup is unverified") + except (Exception, KeyboardInterrupt) as error: + failed = record.get( + "failed_stage", record["steps"][-1]["id"] if record["steps"] else "startup" + ) + record["assessment"] = evaluator.service_assessment( + "INCONCLUSIVE", + service_io.error_excerpt(f"{failed}: {type(error).__name__}: {error}"), + performance=gate, + quality_passed=quality_ok, + ) + if standalone and ("profiling_error" not in record or isinstance(error, KeyboardInterrupt)): + profile_error(failed, error) + for definition in record["steps"]: + if definition["id"] == failed: + definition.setdefault("execution_status", definition["status"]) + if definition["status"] in ("running", "completed"): + definition["status"] = "failed" + definition["reason"] = service_io.error_excerpt(str(error)) + if owner is not None: + record["cleanup_verified"] = ( + owner["domain_empty"] is True and record.get("external_cleanup_verified") is True + ) + elif standalone and not any(step["id"] == "service" for step in record["steps"]): + record["cleanup_verified"] = True + for name in ("quality", "profile"): + if not any(step["id"] == name for step in record["steps"]): + skipped((name,), "prerequisite_incomplete") + if capture_started is not None: + finish_capture() + if owner is not None: + service_step.update( + status="completed" if owner["domain_empty"] is True else "failed", + ended_at=time.time(), + returncode=owner["returncode"], + ) + record.update( + status="completed", + measurements=measured, + quality_score=score, + profile=profile, + elapsed_seconds=time.monotonic() - started, + ) + save() + return record diff --git a/src/inferrsi/harness/serving/http.py b/src/inferrsi/harness/executor/serving/_http.py similarity index 100% rename from src/inferrsi/harness/serving/http.py rename to src/inferrsi/harness/executor/serving/_http.py diff --git a/src/inferrsi/harness/serving/image.py b/src/inferrsi/harness/executor/serving/_image.py similarity index 98% rename from src/inferrsi/harness/serving/image.py rename to src/inferrsi/harness/executor/serving/_image.py index d950f2e68..59196d176 100644 --- a/src/inferrsi/harness/serving/image.py +++ b/src/inferrsi/harness/executor/serving/_image.py @@ -5,7 +5,7 @@ from dataclasses import dataclass, field from pathlib import Path -from .http import post_json +from ._http import post_json @dataclass(frozen=True) diff --git a/src/inferrsi/harness/executor/serving/_plan.py b/src/inferrsi/harness/executor/serving/_plan.py new file mode 100644 index 000000000..d7c979f11 --- /dev/null +++ b/src/inferrsi/harness/executor/serving/_plan.py @@ -0,0 +1,268 @@ +"""Freeze service protocol settings and the declared candidate Git files.""" + +import os +import re +import subprocess +import time +from pathlib import Path + +from ...records import service_io +from ...records.atomic_json import atomic_write_json +from ..candidates import members, retain + + +def validate_service_conditions(conditions): + if not isinstance(conditions, dict): + raise ValueError("Explicit test conditions required") + if not isinstance(conditions.get("id"), str) or not conditions["id"].strip(): + raise ValueError("Conditions require a nonempty string ID") + for key in ("id", "workload", "model", "precision", "topology", "runtime", "timing_scope"): + if not conditions.get(key): + raise ValueError(f"conditions.{key} is required") + if not isinstance(conditions.get("effective_config"), dict): + raise ValueError("conditions.effective_config must be an object") + service_io.no_fingerprints(conditions) + + +def validate_service_settings(settings): + service_io.no_fingerprints(settings) + for name in ("conditions", "commands", "sampling", "quality", "stagnation"): + if not isinstance(settings.get(name), dict): + raise ValueError(f"{name} must be an explicit object") + if type(settings.get("schema_version")) is not int or settings["schema_version"] != 1: + raise ValueError("Service evaluation schema_version must be 1") + if not isinstance(settings.get("protocol_id"), str) or not settings["protocol_id"].strip(): + raise ValueError("Explicit protocol_id required") + validate_service_conditions(settings.get("conditions")) + commands = settings.get("commands", {}) + stages = ("precheck", "service", "ready", "warmup", "measure", "quality", "stop") + if "profile" in commands: + stages += ("profile",) + for name in stages: + command = commands.get(name) + if ( + not isinstance(command, list) + or not command + or any(not isinstance(arg, str) or not arg for arg in command) + ): + raise ValueError(f"commands.{name} must be explicit argv") + if not any("{protocol}" in arg for arg in command): + raise ValueError(f"commands.{name} must use a retained protocol script") + if name != "service" and not any("{result}" in arg for arg in command): + raise ValueError(f"commands.{name} must write the supplied result") + sampling = settings.get("sampling", {}) + if not service_io.positive_number(sampling.get("stage_timeout_seconds")): + raise ValueError("Positive stage timeout required") + if "profile_timeout_seconds" in sampling and not service_io.positive_number( + sampling["profile_timeout_seconds"] + ): + raise ValueError("Positive profiling timeout required") + for role in ("baseline", "candidate", "final"): + config = sampling.get(role, {}) + if not isinstance(config, dict): + raise ValueError("Sampling policies must be objects") + if type(config.get("repetitions")) is not int or config["repetitions"] < 1: + raise ValueError(f"Positive {role} repetitions required") + if type(config.get("warmups")) is not int or config["warmups"] < 0: + raise ValueError(f"Nonnegative {role} warmups required") + if config["warmups"] == 0 and not config.get("warmup_reason"): + raise ValueError("Explain why no warmup is necessary") + scenarios = settings.get("scenarios") + if not isinstance(scenarios, list) or not scenarios: + raise ValueError("Declare scenarios") + ids = [] + for item in scenarios: + if not isinstance(item, dict) or not isinstance(item.get("id"), str): + raise ValueError("Scenario must declare a string ID") + if ( + not item.get("id") + or not item.get("workload") + or (type(item.get("requests")) is not int or item["requests"] < 1) + or type(item.get("required_successes")) is not int + or not (0 < item["required_successes"] <= item["requests"]) + ): + raise ValueError("Declare scenario workload, request and success counts") + ids.append(item["id"]) + if len(set(ids)) != len(ids): + raise ValueError("Duplicate scenario") + objectives = settings.get("objectives") + if not isinstance(objectives, list) or not objectives: + raise ValueError("Declare objectives") + names = [] + for obj in objectives: + if not isinstance(obj, dict) or not isinstance(obj.get("domain"), dict): + raise ValueError("Objective and domain must be objects") + for key in ("id", "key", "unit"): + if not isinstance(obj.get(key), str) or not obj[key].strip(): + raise ValueError(f"Objective {key} required") + names.append(obj["id"]) + if obj.get("scenario") not in ids or obj.get("direction") not in ("minimize", "maximize"): + raise ValueError("Invalid objective scenario or direction") + if ( + obj.get("aggregate") not in ("median", "mean") + or obj.get("threshold_type") not in ("relative_percent", "absolute", "percentage_point") + or type(obj.get("gain")) is not bool + ): + raise ValueError("Declare aggregation, threshold type and gain participation") + domain = obj.get("domain", {}) + if ( + not service_io.finite_number(domain.get("min")) + or not service_io.finite_number(domain.get("max")) + or (domain["min"] > domain["max"]) + ): + raise ValueError("Finite ordered objective domain required") + if obj["threshold_type"] == "percentage_point" and obj["unit"] != "%": + raise ValueError("Percentage-point objectives use percent values and unit %") + if obj["threshold_type"] == "relative_percent" and domain["min"] < 0: + raise ValueError("Use absolute thresholds for negative-valued metrics") + for key in ("gain_threshold", "parent_regression_limit", "cumulative_regression_limit"): + if not service_io.finite_number(obj.get(key)) or obj[key] < 0: + raise ValueError(f"Nonnegative finite {key} required") + ranking = settings.get("ranking") + if len(set(names)) != len(names) or not any(obj["gain"] for obj in objectives): + raise ValueError("Unique objectives and at least one gain objective required") + if ( + not isinstance(ranking, list) + or not ranking + or any(not isinstance(name, str) for name in ranking) + or len(set(ranking)) != len(ranking) + or any(name not in names for name in ranking) + ): + raise ValueError("Declare an ordered, unique ranking of known objectives") + quality = settings.get("quality", {}) + if ( + quality.get("mode") not in ("absolute", "baseline_comparison") + or quality.get("direction") not in ("minimize", "maximize") + or not all( + isinstance(quality.get(key), str) and quality[key].strip() + for key in ("key", "dataset", "scorer") + ) + ): + raise ValueError("Declare quality mode, direction, dataset, scorer and key") + gate = "threshold" if quality["mode"] == "absolute" else "tolerance" + if type(quality.get("samples")) is not int or quality["samples"] < 1: + raise ValueError("Declare the required quality sample count") + if not service_io.finite_number(quality.get(gate)) or ( + gate == "tolerance" and quality[gate] < 0 + ): + raise ValueError("Explicit quality gate required") + reminder = settings.get("stagnation", {}) + if reminder != {"disabled": True} and ( + type(reminder.get("rounds")) is not int + or reminder["rounds"] < 1 + or reminder.get("action") not in ("advisory", "pause") + ): + raise ValueError("Explicit stagnation threshold/action or disabled required") + screen = settings.get("screening") + if screen is not None: + if not isinstance(screen, dict) or ( + not isinstance(screen.get("command"), list) + or not screen["command"] + or any(not isinstance(arg, str) or not arg for arg in screen["command"]) + or not service_io.positive_number(screen.get("estimated_gain")) + ): + raise ValueError("Screening command and positive estimated_gain required") + if not any("{result}" in arg for arg in screen["command"]) or not any( + "{protocol}" in arg for arg in screen["command"] + ): + raise ValueError("Screening must use retained protocol and result") + + +def service_revision(source, includes): + """Use an existing commit, never a file fingerprint, for retained project inputs.""" + + def git(*args): + return subprocess.check_output(["git", "-C", str(source), *args], text=True).strip() + + if Path(git("rev-parse", "--show-toplevel")).resolve() != source.resolve(): + raise ValueError("Use the Git checkout root as the service-reuse project") + commit = git("rev-parse", "HEAD") + if not re.fullmatch(r"[a-f0-9]{40,64}", commit): + raise ValueError("Candidate requires an existing Git commit") + selected = members(source, includes) + tracked = set(git("ls-files", "-z").split("\0")) + # Deleted tracked files are absent from members but still belong to the inputs. + if any(name not in tracked for name in selected) or git( + "status", "--porcelain", "--untracked-files=no", "--", *(includes or ["."]) + ): + raise ValueError("Commit declared candidate inputs before service-reuse evaluation") + return commit + + +def retain_service_revision(source, destination, includes, commit, *, deadline=None): + if not isinstance(commit, str) or not re.fullmatch(r"[a-f0-9]{40,64}", commit): + raise ValueError("Candidate requires an existing Git commit") + + def git(*args): + timeout = None if deadline is None else deadline - time.monotonic() + if timeout is not None and timeout <= 0: + raise TimeoutError("Profiling timeout while restoring the recorded revision") + try: + return subprocess.check_output(["git", "-C", str(source), *args], timeout=timeout) + except subprocess.TimeoutExpired as error: + raise TimeoutError("Profiling timeout while restoring the recorded revision") from error + + entries = {} + for name in includes or ["."]: + relative = Path(name) + if relative.is_absolute() or ".." in relative.parts: + raise ValueError("Candidate includes must be relative paths inside the project") + listing = git( + "ls-tree", "-rz", "--full-tree", "--format=%(objectmode) %(objecttype)%x09%(path)", + commit, "--", relative.as_posix(), + ) + if not listing: + raise ValueError("Declared candidate files are missing from the retained commit") + for entry in listing.rstrip(b"\0").split(b"\0"): + metadata, path = entry.split(b"\t", 1) + mode, kind = metadata.split() + if kind != b"blob" or mode not in (b"100644", b"100755"): + raise ValueError("Candidate tree contains symbolic or special files") + entries[os.fsdecode(path)] = int(mode, 8) & 0o555 + destination.mkdir() + for name, mode in entries.items(): + target = service_io.safe_path(destination, name) + target.parent.mkdir(parents=True, exist_ok=True) + # Read raw tree content; archive export attributes can omit or rewrite inputs. + target.write_bytes(git("cat-file", "blob", f"{commit}:{name}")) + target.chmod(mode) + + +def prepare_service(root, args): + from inferrsi import __version__ + + settings = service_io.read(args.evaluation_config) + validate_service_settings(settings) + source, protocol = args.repo.resolve(), args.protocol.resolve() + if args.repo.is_symlink() or args.protocol.is_symlink(): + raise ValueError("Project and protocol roots cannot be symbolic") + if root.exists() or root.is_relative_to(source) or root.is_relative_to(protocol): + raise ValueError("Use a new campaign directory outside project/protocol") + commit = service_revision(source, args.include) + members(protocol) + if not args.instructions.is_file() or args.instructions.is_symlink(): + raise ValueError("Regular task instructions required") + (root / "frozen").mkdir(parents=True) + retain_service_revision(source, root / "frozen/baseline", args.include, commit) + if service_revision(source, args.include) != commit: + raise ValueError("Candidate revision changed while retaining inputs") + retain(protocol, root / "frozen/protocol", fingerprint=False) + (root / "frozen/TASK.md").write_bytes(args.instructions.read_bytes()) + atomic_write_json(root / "frozen/evaluation.json", settings) + for path in (root / "frozen").rglob("*"): + if path.is_file(): + path.chmod(path.stat().st_mode & ~0o222) + return { + "runtime_version": __version__, + "evaluation_settings": settings, + "baseline_revision": commit, + "baseline_path": "frozen/baseline", + "candidate_name": "candidate", + "candidate_kind": "directory", + "candidate_includes": args.include, + "working_candidate": str(source), + "task_source": "project", + "task": "project:" + source.name, + "evaluation_mode": "service_reuse", + "selection": {"ranking": settings["ranking"]}, + } diff --git a/src/inferrsi/harness/executor/serving/_profile.py b/src/inferrsi/harness/executor/serving/_profile.py new file mode 100644 index 000000000..c7a86095f --- /dev/null +++ b/src/inferrsi/harness/executor/serving/_profile.py @@ -0,0 +1,191 @@ +"""Read bound profile receipts and retain service diagnostics.""" + +import json +import re + +from ...records import service_io + +# Round and reference records repeat this metadata. The collector's raw receipt stays on disk. +PROFILE_METADATA_LIMIT = 32 * 1024 + + +def validated_profile(root, directory, attempt_id, conditions, binding, step, *, captured=None): + """Reconstruct a usable profile only from the capture's own bound on-disk evidence.""" + directory = service_io.safe_path(root, directory.relative_to(root).as_posix()) + result = service_io.safe_path(directory, "execution/profile/result.json") + if ( + not isinstance(binding, dict) + or binding.get("attempt_id") != attempt_id + or binding.get("conditions") != conditions + or binding.get("effective_config") != conditions["effective_config"] + or not all(binding.get(key) for key in ("revision", "service_id", "run_id")) + or service_io.read(service_io.safe_path(directory, "request.json")) != binding + or service_io.read(service_io.safe_path(directory, "effective-config.json")) + != conditions["effective_config"] + ): + raise ValueError("profile: incompatible capture binding") + trace = service_io.read(result) + if ( + trace.get("binding") != binding + or trace.get("status") != "completed" + or trace.get("validated") is not True + or (captured is not None and captured != trace) + or not isinstance(step, dict) + or step.get("id") != "profile" + or step.get("status") != "completed" + or ("result" in step and step["result"] != trace) + ): + raise ValueError("profile: missing or incompatible validated receipt") + interval = ( + step.get("started_at"), trace.get("capture_started_at"), + trace.get("capture_ended_at"), step.get("ended_at"), + ) + if not all(service_io.finite_number(t) for t in interval) or not ( + interval[0] <= interval[1] <= interval[2] <= interval[3] + ): + raise ValueError("profile: missing or incompatible capture interval") + artifacts = trace.get("artifacts") + if not isinstance(artifacts, list) or not artifacts: + raise ValueError("profile: missing artifacts") + legacy = "result" in step + locations = [] + metadata = {"artifacts": locations} + if legacy: + # Previously written profiles kept the full receipt in both the step and the profile. + metadata["receipt"] = trace + else: + metadata.update(capture_started_at=interval[1], capture_ended_at=interval[2]) + metadata_bytes = len(json.dumps(metadata, ensure_ascii=False).encode("utf-8")) + for relative in artifacts: + path = service_io.safe_path(directory, relative) + location = path.relative_to(root).as_posix() + if not legacy: + # Account for the encoded path and the JSON list separator between locations. + metadata_bytes += len(json.dumps(location, ensure_ascii=False).encode("utf-8")) + if locations: + metadata_bytes += 2 + if metadata_bytes > PROFILE_METADATA_LIMIT: + raise ValueError(f"profile: metadata exceeds {PROFILE_METADATA_LIMIT} bytes") + if not path.is_file(): + raise ValueError("profile: missing or empty artifact") + with path.open("rb") as artifact: + if not artifact.read(1): + raise ValueError("profile: missing or empty artifact") + locations.append(location) + return { + "attempt_id": attempt_id, + "conditions": conditions, + "binding": binding, + "result": result.relative_to(root).as_posix(), + **metadata, + } + + +def read_service_attempt_profile(root, attempt): + """Return the retained profile, or None if its evidence is missing or disagrees.""" + execution = attempt["execution"] + profile = execution.get("profile") + if not isinstance(profile, dict): + return None + try: + binding = execution["binding"] + if binding["revision"] != attempt["revision"]: + return None + step = next((s for s in execution["steps"] if s.get("id") == "profile"), None) + validated = validated_profile( + root, + service_io.safe_path(root, attempt["path"]), + attempt["attempt_id"], + attempt["conditions"], + binding, + step, + ) + return validated if validated == profile else None + except (OSError, ValueError, KeyError, TypeError, AttributeError, RecursionError): + return None + + +def service_capture_diagnostic(root, directory, stage, status, message, *, process_failed=False): + if not isinstance(stage, str) or not re.fullmatch(r"[a-z][a-z0-9_-]*", stage): + stage = "startup" + diagnostic = {"stage": stage, "status": status, "message": service_io.error_excerpt(message)} + stage_dir = directory / ("service" if stage == "service" else "execution/" + stage) + try: + receipts = ("execution.json", "result.json") if process_failed else ( + "result.json", "execution.json" + ) + for name in receipts: + receipt = service_io.safe_path(root, (stage_dir / name).relative_to(root).as_posix()) + if receipt.is_file(): + diagnostic["details_path"] = receipt.relative_to(root).as_posix() + break + if diagnostic["message"] != message: + # Unexpected coordinator exceptions can lack a stage receipt with the original detail. + relative = (directory / f"{stage}-error.txt").relative_to(root).as_posix() + service_io.safe_path(root, relative).write_text( + message, encoding="utf-8", errors="replace" + ) + diagnostic["details_path"] = relative + log = service_io.safe_path(root, (stage_dir / "stderr.log").relative_to(root).as_posix()) + if log.is_file(): + diagnostic["log"] = log.relative_to(root).as_posix() + with log.open("rb") as stream: + stream.seek(max(0, log.stat().st_size - 1024)) + detail = stream.read(1024).decode("utf-8", errors="replace").strip() + if detail: + diagnostic["message"] += f"\n{detail}" + except (OSError, ValueError): + pass # The stage error remains available even if its log cannot be read. + return diagnostic + + +def service_capture_elapsed(root, pending, execution): + """Recover monotonic capture progress without charging a crash-to-recovery interval.""" + capture = execution.get("capture") + if not isinstance(capture, dict) or capture.get("id") != pending.get("attempt_id"): + return 0.0 + elapsed = capture.get("elapsed_seconds") + if not service_io.finite_number(elapsed) or elapsed < 0: + return 0.0 + steps = execution.get("steps") + if ( + service_io.finite_number(capture.get("ended_at")) + or not isinstance(steps, list) + or not steps + ): + return elapsed + step = steps[-1] + if not isinstance(step, dict): + return elapsed + try: + offset = step["capture_offset_seconds"] + stage = step["id"] + if ( + step.get("status") != "running" + or not service_io.finite_number(offset) + or offset != elapsed + or capture["id"] != execution["binding"]["attempt_id"] + or not re.fullmatch(r"precheck|ready|warmup-[0-9]+|profile|stop", stage) + or (pending["kind"] != "profile" and stage != "profile") + ): + return elapsed + directory = service_io.safe_path(root, pending["path"]) + if service_io.read(service_io.safe_path(directory, "request.json")) != execution["binding"]: + return elapsed + stage_dir = service_io.safe_path(directory, f"execution/{stage}") + receipt = service_io.read(service_io.safe_path(stage_dir, "execution.json")) + duration = receipt["elapsed_seconds"] + if ( + receipt.get("status") not in ("completed", "failed", "cancelled", "timeout", "error") + or receipt.get("cwd") != str(directory / "workspace") + or receipt.get("result_path") != str(stage_dir / "result.json") + or type(receipt.get("pid")) is not int + or receipt["pid"] <= 0 + or not service_io.finite_number(duration) + or duration < 0 + or not service_io.finite_number(offset + duration) + ): + return elapsed + return offset + duration + except (KeyError, TypeError, OSError, ValueError): + return elapsed diff --git a/src/inferrsi/harness/serving/server.py b/src/inferrsi/harness/executor/serving/_server.py similarity index 100% rename from src/inferrsi/harness/serving/server.py rename to src/inferrsi/harness/executor/serving/_server.py diff --git a/src/inferrsi/harness/skill_evaluation.py b/src/inferrsi/harness/executor/skill_evaluation.py similarity index 98% rename from src/inferrsi/harness/skill_evaluation.py rename to src/inferrsi/harness/executor/skill_evaluation.py index f9343d386..4002ffec7 100644 --- a/src/inferrsi/harness/skill_evaluation.py +++ b/src/inferrsi/harness/executor/skill_evaluation.py @@ -5,11 +5,11 @@ from dataclasses import dataclass from pathlib import Path +from ..records.atomic_json import atomic_write_json +from ..records.usage import normalize_usage as normalize_usage from . import artifact_sandbox -from .atomic_json import atomic_write_json -from .input_binding import file_sha256 +from ._input_binding import file_sha256 from .local_process import execute_command -from .usage import normalize_usage as normalize_usage def global_skills() -> list[str]: diff --git a/src/inferrsi/harness/trials/__init__.py b/src/inferrsi/harness/executor/trials/__init__.py similarity index 66% rename from src/inferrsi/harness/trials/__init__.py rename to src/inferrsi/harness/executor/trials/__init__.py index f724ec65a..e21c01b11 100644 --- a/src/inferrsi/harness/trials/__init__.py +++ b/src/inferrsi/harness/executor/trials/__init__.py @@ -1,4 +1,4 @@ """External command trials and their retained checks, independent of model and device. -Experiment scheduling stays in harness.runner. +Harness Manager schedules experiments. """ diff --git a/src/inferrsi/harness/trials/external.py b/src/inferrsi/harness/executor/trials/external.py similarity index 97% rename from src/inferrsi/harness/trials/external.py rename to src/inferrsi/harness/executor/trials/external.py index 26c56e53e..1b6a97728 100644 --- a/src/inferrsi/harness/trials/external.py +++ b/src/inferrsi/harness/executor/trials/external.py @@ -5,7 +5,7 @@ from functools import partial from pathlib import Path -from ..atomic_json import atomic_write_json as _write_json +from ...records.atomic_json import atomic_write_json as _write_json from ..local_process import execute_command diff --git a/src/inferrsi/harness/indexer/__init__.py b/src/inferrsi/harness/indexer/__init__.py new file mode 100644 index 000000000..779d754bb --- /dev/null +++ b/src/inferrsi/harness/indexer/__init__.py @@ -0,0 +1,115 @@ +"""Check the knowledge delivered for a managed request against its frozen policy.""" + +import hashlib + +from ..records import atomic_capture, knowledge_capture + + +def require_ranking_policy(recorded, effective): + if (not isinstance(recorded, dict) or not isinstance(effective, dict) + or type(recorded.get("version")) is not int + or not isinstance(recorded.get("weights"), dict) + or any(type(value) not in (int, float) for value in recorded["weights"].values()) + or recorded != effective): + raise ValueError("Frozen ranking policy changed or is incomplete, use its original runtime") + + +def resolve_frozen_ranking(plan, ranking_policy_for, *, read_only=False): + if read_only and "ranking_policy" not in plan: + return None + recorded = plan.get("ranking_policy") + if not isinstance(recorded, dict) or not isinstance(recorded.get("id"), str): + raise ValueError("Missing frozen ranking policy, use the original runtime to resume") + if ranking_policy_for is None: + raise ValueError("A resolver for the frozen ranking policy is required") + policy = ranking_policy_for(recorded["id"]) + effective = (policy.configuration() if plan.get("evaluation_mode") == "service_reuse" + else policy.receipt()) + require_ranking_policy(recorded, effective) + return policy + + +def check_context_ranking(plan, context): + if "ranking_policy" in plan: + request = context.get("request") if isinstance(context, dict) else None + recorded = request.get("ranking_policy") if isinstance(request, dict) else None + require_ranking_policy(recorded, plan["ranking_policy"]) + + +def check_returned_ranking(observation, effective): + selection = observation.get("selection") if isinstance(observation, dict) else None + recorded = selection.get("ranking_policy") if isinstance(selection, dict) else None + try: + require_ranking_policy(recorded, effective) + except ValueError as error: + raise ValueError("Delivered ranking policy differs from the frozen session") from error + + +def _check_dispatched_request(recorded, expected, lane): + if not isinstance(recorded, dict) or any( + key not in recorded or type(recorded[key]) is not type(value) or recorded[key] != value + for key, value in expected.items() + ): + raise ValueError(f"{lane} knowledge receipt differs from its dispatched request") + + +def ordinary_delivery(root, plan, *, context_id, binding, reader, prepare_context, **request): + """Validate the prepared capture and its underlying retrieval before Manager retains it.""" + context = prepare_context(root, context_id=context_id, reader=reader, + diagnosis_binding=binding, **request) + if (not isinstance(context, dict) or context.get("context_id") != context_id + or context.get("diagnosis_binding") != binding): + raise ValueError("Knowledge capture differs from its dispatched request") + expected = {key: request[key] for key in ("query", "relevance", "scenario", "limit", + "context_bytes")} + expected["relevance_method"] = request["relevance_method"] or "find-lexical-v1" + _check_dispatched_request(context.get("request"), expected, "Ordinary") + observation = context.get("retrieval") + _check_dispatched_request(observation.get("request") if isinstance(observation, dict) else None, + expected, "Ordinary") + check_context_ranking(plan, context) + if "ranking_policy" in plan: + check_returned_ranking(observation, plan["ranking_policy"]) + return _capture_delivery(context_id, context, "delivered_context") + + +def pinned_delivery(root, plan, *, context_id, binding, reader, assemble_text, **request): + """Verify the exact bodies and record refusals against the frozen session policy.""" + context = atomic_capture.prepare_selection( + root, context_id=context_id, reader=reader, assemble_text=assemble_text, + diagnosis_binding=binding, ranking_policy=plan.get("ranking_policy"), **request, + ) + check_context_ranking(plan, context) + delivered = context["selection"]["status"] == "delivered" + return _capture_delivery(context_id, context, + "delivered_context" if delivered else "knowledge_refusal") + + +def _capture_delivery(context_id, context, kind): + reference = {"path": f"knowledge/{context_id}.json", + "sha256": hashlib.sha256(knowledge_capture.capture_bytes(context)).hexdigest(), + "kind": kind} + return {"reference": reference, "context": context} + + +def service_delivery(plan, *, context_id, binding, reader, query, relevance_method, limit, + context_bytes, ranking_policy): + """Validate a fingerprint-free service receipt from the injected reader.""" + method = "find-lexical-v1" if relevance_method is None else relevance_method + context = reader.collect_service_context( + query, relevance_method=method, limit=limit, context_bytes=context_bytes, + ranking_policy=ranking_policy, + ) + check_context_ranking(plan, context) + expected = {"relevance": query, "relevance_method": method, "limit": limit, + "context_bytes": context_bytes} + recorded = context.get("request") if isinstance(context, dict) else None + _check_dispatched_request(recorded, expected, "Service") + if "diagnosis_binding" in context and context["diagnosis_binding"] != binding: + raise ValueError("Knowledge capture differs from its dispatched request") + if context.get("prepared_not_consumed") is not True: + raise ValueError("Service knowledge delivery requires a prepared context") + if binding: + context = {**context, "diagnosis_binding": binding} + return {"reference": {"path": f"knowledge/{context_id}.json", "kind": "delivered_context", + "prepared_not_consumed": True}, "context": context} diff --git a/src/inferrsi/harness/manager/__init__.py b/src/inferrsi/harness/manager/__init__.py new file mode 100644 index 000000000..bc372bd32 --- /dev/null +++ b/src/inferrsi/harness/manager/__init__.py @@ -0,0 +1,53 @@ +"""Manage Harness experiments, session progression and search budgets.""" + +from ._agent_sessions import ( + AGENT_TERMINAL_STATES, + agent_session_status, + bind_agent_session, + dispatch_agent_session, + prepare_agent_session, + record_agent_session, +) +from ._parallel_round import ( + close_parallel_round, + parallel_ticket_status, + prepare_parallel_round, + serve_parallel_ticket, + submit_parallel_ticket, +) +from ._requests import ( + BaselineSession, + DiagnoseSession, + EvaluateSessionRound, + FinalizeSession, + ProfileSession, + QuerySessionKnowledge, + ReadSessionKnowledge, + RecoverSession, + RefreshSessionReferences, + ResumeSession, + SelectSessionKnowledge, + SessionRequest, + SessionStatus, + StartBenchmarkSession, + StartProjectSession, +) +from ._runner import run_experiment +from ._runtime import session_runtime_identity +from ._session import run_session +from ._state import read_session_records +from .search._engine import EngineSearchPlan, read_engine_search, run_engine_search + +__all__ = [ + "BaselineSession", "DiagnoseSession", "EvaluateSessionRound", + "FinalizeSession", "ProfileSession", "QuerySessionKnowledge", + "ReadSessionKnowledge", "RecoverSession", "RefreshSessionReferences", + "ResumeSession", "SelectSessionKnowledge", "SessionRequest", "SessionStatus", + "StartBenchmarkSession", "StartProjectSession", + "read_session_records", "run_session", + "AGENT_TERMINAL_STATES", "agent_session_status", "bind_agent_session", + "dispatch_agent_session", "prepare_agent_session", "record_agent_session", + "EngineSearchPlan", "read_engine_search", "run_engine_search", "run_experiment", + "session_runtime_identity", "close_parallel_round", "parallel_ticket_status", + "prepare_parallel_round", "serve_parallel_ticket", "submit_parallel_ticket", +] diff --git a/src/inferrsi/harness/agent_sessions.py b/src/inferrsi/harness/manager/_agent_sessions.py similarity index 93% rename from src/inferrsi/harness/agent_sessions.py rename to src/inferrsi/harness/manager/_agent_sessions.py index 93c640fed..02d047ace 100644 --- a/src/inferrsi/harness/agent_sessions.py +++ b/src/inferrsi/harness/manager/_agent_sessions.py @@ -10,12 +10,12 @@ import uuid from pathlib import Path -from .artifact_primitives import digest, file_lock, sha256 -from .atomic_json import atomic_write_json -from .usage import normalize_usage +from ..records.artifact_primitives import digest, file_lock, sha256 +from ..records.atomic_json import atomic_write_json +from ..records.usage import normalize_usage -TERMINAL = {"completed", "failed", "cancelled"} -OBSERVED_STATES = {"running", "needs_attention", *TERMINAL} +AGENT_TERMINAL_STATES = {"completed", "failed", "cancelled"} +OBSERVED_STATES = {"running", "needs_attention", *AGENT_TERMINAL_STATES} MAX_EXPORT_BYTES = 2 * 1024 * 1024 @@ -94,7 +94,7 @@ def _view(root, request, state): "cost": None, "task_acceptance": "not_assessed", "next_action": ( "inspect_native_host_and_stop_if_still_running" if expired - and state["state"] not in TERMINAL else { + and state["state"] not in AGENT_TERMINAL_STATES else { "prepared": "dispatch_then_use_native_fresh_session_tool", "dispatching": "inspect_original_host_call_and_bind_without_relaunch", "running": "observe_native_session_and_record_receipt", @@ -107,7 +107,7 @@ def _view(root, request, state): } -def prepare(root: Path, *, prompt: str, workspace: Path, title: str, +def prepare_agent_session(root: Path, *, prompt: str, workspace: Path, title: str, max_seconds: float, model=None, effort=None, plugin_ref=None, task_reference=None, frozen_inputs=()) -> dict: """Freeze explicit task/configuration, without inheriting a parent conversation.""" @@ -145,13 +145,13 @@ def prepare(root: Path, *, prompt: str, workspace: Path, title: str, return _view(root, request, state) -def status(root: Path) -> dict: +def agent_session_status(root: Path) -> dict: root = root.resolve() with _locked(root): return _view(root, *_load(root)) -def dispatch(root: Path) -> dict: +def dispatch_agent_session(root: Path) -> dict: """Reserve exactly one native creation attempt before calling the host tool.""" root = root.resolve() with _locked(root): @@ -181,7 +181,9 @@ def dispatch(root: Path) -> dict: } -def bind(root: Path, *, host: str, session_id: str, receipt: Path, host_id=None) -> dict: +def bind_agent_session( + root: Path, *, host: str, session_id: str, receipt: Path, host_id=None, +) -> dict: """Associate a confirmed native ID with its opaque, caller-exported tool receipt.""" root = root.resolve() native = {"host": _text(host, "host"), "session_id": _text(session_id, "session_id"), @@ -202,7 +204,7 @@ def bind(root: Path, *, host: str, session_id: str, receipt: Path, host_id=None) return _view(root, request, state) -def record(root: Path, *, observation: Path, artifacts=()) -> dict: +def record_agent_session(root: Path, *, observation: Path, artifacts=()) -> dict: """Retain an explicit host observation; completed execution is not task acceptance.""" root = root.resolve() raw, value = _export(observation) @@ -231,7 +233,7 @@ def record(root: Path, *, observation: Path, artifacts=()) -> dict: _text(value.get("host"), "host") elif any(value.get(key) != native[key] for key in ("host", "session_id", "host_id")): raise ValueError("Observation does not identify the bound native session") - if state["state"] in TERMINAL and value["state"] != state["state"]: + if state["state"] in AGENT_TERMINAL_STATES and value["state"] != state["state"]: raise ValueError("A terminal native session cannot change state in this job") previous_usage = (state.get("last_observed_usage") or {}).get("usage") if usage is not None and previous_usage is not None and any( diff --git a/src/inferrsi/harness/attempt_recovery.py b/src/inferrsi/harness/manager/_attempt_recovery.py similarity index 97% rename from src/inferrsi/harness/attempt_recovery.py rename to src/inferrsi/harness/manager/_attempt_recovery.py index c75f8ba4e..0b8de8030 100644 --- a/src/inferrsi/harness/attempt_recovery.py +++ b/src/inferrsi/harness/manager/_attempt_recovery.py @@ -6,9 +6,9 @@ import uuid from pathlib import Path -from .atomic_json import durable_write_json -from .launch_records import observe -from .records.evidence import bounded_record_bytes +from ..executor.launch_records import observe +from ..records.atomic_json import durable_write_json +from ..records.evidence import bounded_record_bytes _CLEAR = {"not_spawned", "recorded_empty", "observed_empty"} _FIELDS = ( diff --git a/src/inferrsi/harness/parallel_round.py b/src/inferrsi/harness/manager/_parallel_round.py similarity index 99% rename from src/inferrsi/harness/parallel_round.py rename to src/inferrsi/harness/manager/_parallel_round.py index d699a76f8..9d7af7062 100644 --- a/src/inferrsi/harness/parallel_round.py +++ b/src/inferrsi/harness/manager/_parallel_round.py @@ -65,14 +65,15 @@ from pathlib import Path from inferrsi.contracts import RunSpec -from inferrsi.harness.artifact_primitives import digest -from inferrsi.harness.confinement import ( +from inferrsi.harness.executor.confinement import ( ConfinementUnavailable, UnreapedCommand, confined_execute, ) -from inferrsi.harness.device_lease import DeviceLease, LeaseError -from inferrsi.harness.round_budget import ( +from inferrsi.harness.executor.device_lease import DeviceLease, LeaseError +from inferrsi.harness.records.artifact_primitives import digest + +from ._round_budget import ( Binding, BudgetError, Entry, @@ -85,7 +86,7 @@ ensure_open, seconds_remaining, ) -from inferrsi.harness.runner import run_experiment as run_experiment_loop +from ._runner import run_experiment as run_experiment_loop _TERMINAL = frozenset({"measured", "rejected", "unsettled", "failed"}) @@ -401,7 +402,7 @@ def _lane(plan: dict, lane_id: str) -> dict: return matches[0] -def prepare(spec: dict, incumbent: Path, round_dir: Path) -> dict: +def prepare_parallel_round(spec: dict, incumbent: Path, round_dir: Path) -> dict: """Validate lane scopes and write ``round-plan.json``. The digest covers the validated body.""" if not isinstance(spec, dict): raise RoundPlanError("round spec must be an object") @@ -545,7 +546,7 @@ def prepare(spec: dict, incumbent: Path, round_dir: Path) -> dict: return body -def submit( +def submit_parallel_ticket( round_dir: Path, lane_id: str, incumbent: Path, work: Path, *, now: datetime | None = None ) -> dict: """Copy in-glob changes to the outbox. The same manifest always returns the same ticket. @@ -1015,7 +1016,7 @@ def hold_devices(round_dir: Path, plan: dict, count: int) -> list[tuple[str, obj return held -def serve_ticket( +def serve_parallel_ticket( round_dir: Path, ticket: str, incumbent: Path, @@ -1244,7 +1245,7 @@ def _measure( ) -def ticket_status(round_dir: Path, ticket: str) -> dict: +def parallel_ticket_status(round_dir: Path, ticket: str) -> dict: path = round_dir / "results" / f"{ticket}.json" if path.exists(): return json.loads(path.read_text(encoding="utf-8")) @@ -1320,7 +1321,7 @@ def _receipts(round_dir: Path) -> dict[str, dict]: return {path.stem: json.loads(path.read_text(encoding="utf-8")) for path in root.glob("*.json")} -def close_round( +def close_parallel_round( round_dir: Path, incumbent: Path, *, diff --git a/src/inferrsi/harness/manager/_requests.py b/src/inferrsi/harness/manager/_requests.py new file mode 100644 index 000000000..14a1b79dc --- /dev/null +++ b/src/inferrsi/harness/manager/_requests.py @@ -0,0 +1,168 @@ +"""Inputs for one managed campaign or packaged benchmark session operation.""" + +import sys +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import ClassVar, Literal + + +@dataclass(frozen=True, kw_only=True) +class _Session: + session: Path + + +@dataclass(frozen=True, kw_only=True) +class _StartSession(_Session): + action: ClassVar[str] = "start" + rounds: int + max_minutes: float + evaluation_timeout_seconds: float + condition: str + python: str = sys.executable + evaluation_prefix: str = "" + final_reserve_seconds: float | None = None + knowledge: Literal["on", "off"] = "on" + ranking_policy: str = "default" + + +@dataclass(frozen=True, kw_only=True) +class StartBenchmarkSession(_StartSession): + task: str + evaluation_args: str + round_mode: Literal["exact", "up_to"] = "exact" + + +@dataclass(frozen=True, kw_only=True) +class StartProjectSession(_StartSession): + repo: Path + include: list[str] + protocol: Path + instructions: Path + round_mode: Literal["exact", "up_to"] = "up_to" + evaluation_mode: Literal["abba", "service_reuse"] = "abba" + evaluation_config: Path | None = None + allow_final_continuation: bool = False + measure_command: str | None = None + quality_command: str | None = None + metric_key: str | None = None + metric_unit: str | None = None + quality_key: str | None = None + scope: str | None = None + direction: Literal["minimize", "maximize"] | None = None + min_improvement_pct: float | None = None + repetitions: int | None = None + warmups: int | None = None + decision: Literal["point", "paired"] = "point" + require_explanation: bool = False + + +@dataclass(frozen=True, kw_only=True) +class SessionStatus(_Session): + action: ClassVar[str] = "status" + + +@dataclass(frozen=True, kw_only=True) +class DiagnoseSession(_Session): + action: ClassVar[str] = "diagnose" + bottleneck: str + evidence: Path + + +@dataclass(frozen=True, kw_only=True) +class QuerySessionKnowledge(_Session): + action: ClassVar[str] = "knowledge" + query: str + context_bytes: int + relevance_method: str | None = None + scenario: str | None = None + limit: int = 5 + + +@dataclass(frozen=True, kw_only=True) +class SelectSessionKnowledge(_Session): + action: ClassVar[str] = "knowledge-select" + reference: str + revision: str + layer: str + max_bytes: int + context: Mapping[str, str] + finding: str | None = None + + +@dataclass(frozen=True, kw_only=True) +class ReadSessionKnowledge(_Session): + action: ClassVar[str] = "knowledge-read" + search_ref: str + locator: str + page: int = 1 + + +@dataclass(frozen=True, kw_only=True) +class _Retryable(_Session): + retry_of: str | None = None + repair_protocol: Path | None = None + repair_reason: str | None = None + cleanup_receipt: Path | None = None + + +@dataclass(frozen=True, kw_only=True) +class BaselineSession(_Retryable): + action: ClassVar[str] = "baseline" + + +@dataclass(frozen=True, kw_only=True) +class EvaluateSessionRound(_Retryable): + action: ClassVar[str] = "round" + candidate: Path + hypothesis: str + strategy: str | None = None + alternative: list[str] | None = None + selection_reason: str | None = None + knowledge_ref: list[str] | None = None + mechanism_file: Path | None = None + usage_export: Path | None = None + continue_after_final: str | None = None + continuation_reason: str | None = None + + +@dataclass(frozen=True, kw_only=True) +class FinalizeSession(_Session): + action: ClassVar[str] = "final" + usage_export: Path | None = None + reason: str | None = None + + +@dataclass(frozen=True, kw_only=True) +class RecoverSession(_Session): + action: ClassVar[str] = "recover" + confirm_domain_empty: bool = False + cleanup_receipt: Path | None = None + + +@dataclass(frozen=True, kw_only=True) +class ProfileSession(_Session): + action: ClassVar[str] = "profile" + round: int + + +@dataclass(frozen=True, kw_only=True) +class RefreshSessionReferences(_Retryable): + action: ClassVar[str] = "refresh-references" + conditions: Path + reason: str + + +@dataclass(frozen=True, kw_only=True) +class ResumeSession(_Session): + action: ClassVar[str] = "resume" + reason: str + cleanup_receipt: Path | None = None + + +SessionRequest = ( + StartProjectSession | StartBenchmarkSession | SessionStatus | DiagnoseSession + | QuerySessionKnowledge | ReadSessionKnowledge | SelectSessionKnowledge + | BaselineSession | EvaluateSessionRound + | FinalizeSession | RecoverSession | ProfileSession | RefreshSessionReferences | ResumeSession +) diff --git a/src/inferrsi/harness/round_budget.py b/src/inferrsi/harness/manager/_round_budget.py similarity index 100% rename from src/inferrsi/harness/round_budget.py rename to src/inferrsi/harness/manager/_round_budget.py diff --git a/src/inferrsi/harness/runner.py b/src/inferrsi/harness/manager/_runner.py similarity index 97% rename from src/inferrsi/harness/runner.py rename to src/inferrsi/harness/manager/_runner.py index d4f9de576..46d34b8ce 100644 --- a/src/inferrsi/harness/runner.py +++ b/src/inferrsi/harness/manager/_runner.py @@ -8,10 +8,10 @@ from datetime import datetime, timezone from pathlib import Path -from ..contracts import RunSpec -from ..contracts.runspec import revision_matches -from .atomic_json import atomic_write_json as _write_json -from .trials.external import collect_trial_checks +from ...contracts import RunSpec +from ...contracts.runspec import revision_matches +from ..executor.trials.external import collect_trial_checks +from ..records.atomic_json import atomic_write_json as _write_json def run_experiment( diff --git a/src/inferrsi/harness/session_runtime.py b/src/inferrsi/harness/manager/_runtime.py similarity index 90% rename from src/inferrsi/harness/session_runtime.py rename to src/inferrsi/harness/manager/_runtime.py index e82a93299..89f665bce 100644 --- a/src/inferrsi/harness/session_runtime.py +++ b/src/inferrsi/harness/manager/_runtime.py @@ -6,7 +6,11 @@ """ import ast +from importlib.resources import files from importlib.util import resolve_name +from pathlib import Path + +from ..records.artifact_primitives import sha256 _KNOWLEDGE_ROOTS = ( "inferrsi.knowledge.context_projection", @@ -14,7 +18,7 @@ "inferrsi.knowledge.ranking_policy", ) _ROOTS = ( - "inferrsi.harness.optimization_session", + "inferrsi.harness.manager._session", "inferrsi.apps.workflows.campaign", *_KNOWLEDGE_ROOTS, ) @@ -90,3 +94,9 @@ def source_files(root): sources.add(relative) pending.extend(_imports(ast.parse(path.read_bytes(), relative), package, relative)) return sorted(sources) + + +def session_runtime_identity() -> dict[str, str]: + """Hash the installed source files that define an ordinary session.""" + root = Path(str(files("inferrsi"))) + return {name: sha256(root / name) for name in source_files(root)} diff --git a/src/inferrsi/harness/service_backfill.py b/src/inferrsi/harness/manager/_service_backfill.py similarity index 87% rename from src/inferrsi/harness/service_backfill.py rename to src/inferrsi/harness/manager/_service_backfill.py index 10d28e56e..470ddcccc 100644 --- a/src/inferrsi/harness/service_backfill.py +++ b/src/inferrsi/harness/manager/_service_backfill.py @@ -4,9 +4,10 @@ import time import uuid -from . import optimization -from . import project_service as service -from .atomic_json import atomic_write_json +from .. import executor +from ..records import service_io +from ..records.atomic_json import atomic_write_json +from . import _state as optimization def _target(state, number): @@ -31,9 +32,9 @@ def _lineage(attempt, capture_id): def _original_binding(root, target): - directory = service.safe_path(root, target["path"]) - binding = service.read(directory / "request.json") - config = service.read(directory / "effective-config.json") + directory = service_io.safe_path(root, target["path"]) + binding = service_io.read(directory / "request.json") + config = service_io.read(directory / "effective-config.json") if ( binding != target["execution"].get("binding") or any(binding.get(k) != target[k] for k in ("attempt_id", "revision", "conditions")) @@ -47,10 +48,10 @@ def _original_binding(root, target): def _index(root, attempt): - path = service.safe_path(root, attempt["path"] + "/backfills/index.json") + path = service_io.safe_path(root, attempt["path"] + "/backfills/index.json") if not path.exists(): return path, [] - document = service.read(path) + document = service_io.read(path) captures = document.get("captures") if document.get("target_attempt_id") != attempt["attempt_id"] or not isinstance(captures, list): raise ValueError("Invalid profile index for the target attempt") @@ -61,10 +62,10 @@ def _validated(root, target, capture_id): if not isinstance(capture_id, str) or not re.fullmatch(r"[0-9a-f]{32}", capture_id): return None relative = target["path"] + "/backfills/" + capture_id - directory = service.safe_path(root, relative) - if service.read(directory / "target.json") != _lineage(target, capture_id): + directory = service_io.safe_path(root, relative) + if service_io.read(directory / "target.json") != _lineage(target, capture_id): return None - execution = service.read(service.safe_path(directory, "execution/execution.json")) + execution = service_io.read(service_io.safe_path(directory, "execution/execution.json")) binding = execution["binding"] original = _original_binding(root, target) if ( @@ -74,7 +75,7 @@ def _validated(root, target, capture_id): or binding["run_id"] == original["run_id"] ): return None - return service.attempt_profile( + return executor.read_service_attempt_profile( root, {**target, "attempt_id": capture_id, "path": relative, "execution": execution} ) @@ -99,8 +100,8 @@ def _diagnostic(root, pending, execution, status, message): steps = execution.get("steps") or [] last = steps[-1] if isinstance(steps, list) and steps and isinstance(steps[-1], dict) else {} stage = execution.get("failed_stage") or last.get("id") or "startup" - return service.capture_diagnostic( - root, service.safe_path(root, pending["path"]), stage, status, message + return executor.service_capture_diagnostic( + root, service_io.safe_path(root, pending["path"]), stage, status, message ) @@ -113,10 +114,10 @@ def _finish(root, plan, state, execution, *, preparation_seconds=None): raise ValueError("Pending capture target disagrees with the settled attempt") cleanup = optimization._service_cleanup_confirmed(state, {**pending, "execution": execution}) error = execution.get("profiling_error") - directory = service.safe_path(root, pending["path"]) + directory = service_io.safe_path(root, pending["path"]) # Each invocation starts a new monotonic interval. Only committed progress survives a crash. previous = execution.get("publication_elapsed_seconds", 0) - if not service.number(previous) or previous < 0: + if not service_io.finite_number(previous) or previous < 0: previous = 0 timed = preparation_seconds is not None or (cleanup and not error) @@ -140,7 +141,7 @@ def settle(): else "Publication interrupted before the capture was published" ) field = "publication_interruption" if committed else "profiling_error" - execution[field] = service.capture_diagnostic( + execution[field] = executor.service_capture_diagnostic( root, directory, "publication", "interrupted", message ) if timed: @@ -183,7 +184,9 @@ def checkpoint(): try: published = _publish(root, target, capture_id, checkpoint) except (KeyError, TypeError, ValueError, OSError) as exc: - error = service.capture_diagnostic(root, directory, "publication", "failed", str(exc)) + error = executor.service_capture_diagnostic( + root, directory, "publication", "failed", str(exc) + ) execution["profiling_error"] = error _write_execution(directory, execution) profiling = optimization._service_profiling(root, target, published=published) @@ -267,7 +270,7 @@ def run(root, args): path=target["path"] + "/backfills/" + capture_id, started_at=time.time(), ) - directory = service.safe_path(root, pending["path"]) + directory = service_io.safe_path(root, pending["path"]) directory.mkdir(parents=True) atomic_write_json(directory / "target.json", _lineage(target, capture_id)) state["pending"] = pending @@ -276,7 +279,9 @@ def run(root, args): try: sampling = plan["evaluation_settings"]["sampling"] timeout = sampling.get("profile_timeout_seconds", sampling["stage_timeout_seconds"]) - execution = service.execute(root, directory, plan, pending, time.time() + timeout) + execution = executor.execute_service_attempt( + root, directory, plan, pending, time.time() + timeout + ) except (Exception, KeyboardInterrupt) as error: execution = _read_execution(directory) status = "interrupted" if isinstance(error, KeyboardInterrupt) else "failed" @@ -289,13 +294,13 @@ def run(root, args): def _read_execution(directory): try: - return service.read(service.safe_path(directory, "execution/execution.json")) + return service_io.read(service_io.safe_path(directory, "execution/execution.json")) except (OSError, ValueError): return {} def _write_execution(directory, execution): - path = service.safe_path(directory, "execution/execution.json") + path = service_io.safe_path(directory, "execution/execution.json") path.parent.mkdir(exist_ok=True) atomic_write_json(path, execution) @@ -303,7 +308,7 @@ def _write_execution(directory, execution): def recover(root, plan, state, args): """Settle a single capture from durable evidence, without restarting its service.""" pending = state["pending"] - directory = service.safe_path(root, pending["path"]) + directory = service_io.safe_path(root, pending["path"]) execution = _read_execution(directory) if execution.get("status") != "completed" and not execution.get("profiling_error"): execution["profiling_error"] = _diagnostic( diff --git a/src/inferrsi/harness/manager/_session.py b/src/inferrsi/harness/manager/_session.py new file mode 100644 index 000000000..c884f60b8 --- /dev/null +++ b/src/inferrsi/harness/manager/_session.py @@ -0,0 +1,320 @@ +"""Assemble the shared Harness lifecycle for project and supplied task protocols. + +The CLI supplies a task directory only when starting a packaged task. Ordinary +projects and all subsequent operations use Harness and the retained inputs. +""" + +import json +import shlex +import sys +from functools import partial +from pathlib import Path + +from ._requests import SessionRequest, StartBenchmarkSession, StartProjectSession + + +def run_session( + request: SessionRequest, *, ranking_policy_for, assess_packaged, + task_source: Path | None = None, + knowledge_reader=None, prepare_context=None, assemble_text=None, + external_knowledge=None, external_provider=None, + external_project=None, external_provider_for=None, report_metadata=None, +) -> dict: + """Run one typed session operation with dependencies supplied by the host.""" + from .. import evaluator, executor, indexer + from . import _state as state + from ._runtime import session_runtime_identity + + if not isinstance(request, SessionRequest): + raise TypeError("run_session requires a managed session request") + root = request.session.resolve() + if isinstance(request, (StartProjectSession, StartBenchmarkSession)): + project = isinstance(request, StartProjectSession) + from inferrsi.harness.executor import prepare_task_protocol + from inferrsi.harness.executor.candidates import identity, retain + from inferrsi.harness.records.artifact_primitives import sha256 + + budgets = (request.max_minutes, request.evaluation_timeout_seconds) + if (type(request.rounds) is not int or request.rounds < 1 + or any(type(value) not in (int, float) or not 0 < value <= sys.float_info.max + for value in budgets) + or not request.condition.strip() or not request.python.strip()): + raise ValueError("A positive round/time budget and condition label are required") + max_seconds = request.max_minutes * 60 + if max_seconds > sys.float_info.max: + raise ValueError("The session time budget must be finite in seconds") + if request.round_mode not in ("exact", "up_to") or request.knowledge not in ("on", "off"): + raise ValueError("Choose a supported round mode and knowledge setting") + if project and (request.evaluation_mode not in ("abba", "service_reuse") + or request.decision not in ("point", "paired") + or type(request.allow_final_continuation) is not bool + or type(request.require_explanation) is not bool): + raise ValueError("Choose valid project evaluation settings") + if root.exists(): + raise ValueError("Session directory must be new") + ranking_policy = ranking_policy_for(request.ranking_policy) + reserve = (request.final_reserve_seconds if request.final_reserve_seconds is not None + else request.evaluation_timeout_seconds) + if type(reserve) not in (int, float) or not 0 < reserve < max_seconds: + raise ValueError("Reserve time for final within the total budget") + evaluation_prefix = shlex.split(request.evaluation_prefix) + if external_knowledge and request.knowledge != "on": + raise ValueError("External knowledge requires --knowledge on") + if (external_knowledge and project + and request.evaluation_mode == "service_reuse"): + raise ValueError("External round knowledge requires a benchmark or AB/BA campaign") + allow_continuation = getattr(request, "allow_final_continuation", False) + if allow_continuation and ( + request.evaluation_mode != "service_reuse" or request.round_mode != "up_to" + ): + raise ValueError("Final continuation requires an up-to-budget service-reuse campaign") + if project: + names = ( + "metric_key", + "metric_unit", + "quality_key", + "scope", + "direction", + "min_improvement_pct", + "repetitions", + "warmups", + "measure_command", + "quality_command", + ) + if request.evaluation_mode == "service_reuse": + from inferrsi.harness.executor import prepare_service + + if request.evaluation_config is None or any( + getattr(request, key) is not None for key in names + ): + raise ValueError( + "Service reuse requires --evaluation-config without AB/BA options" + ) + if request.decision != "point" or request.require_explanation: + # Both switches read AB/BA pairs and per-measurement breakdown/counters; + # this mode's optional profiling stage does not produce those inputs. + raise ValueError( + "--decision paired and --require-explanation apply to AB/BA campaigns" + ) + settings = prepare_service(root, request) + plan = { + "schema_version": 3, + "condition": request.condition, + "round_limit": request.rounds, + "max_seconds": max_seconds, + "round_mode": request.round_mode, + "final_reserve_seconds": reserve, + "knowledge_allowed": request.knowledge == "on", + "ranking_policy": ranking_policy.configuration(), + "evaluation_timeout_seconds": request.evaluation_timeout_seconds, + "evaluation_prefix": evaluation_prefix, + "python": request.python, + **({"allow_final_continuation": True} if allow_continuation else {}), + **settings, + } + result = state.initialize(root, plan) + result["instructions"] = ( + "Run campaign baseline before candidate search. Record the measured " + "bottleneck with campaign diagnose before knowledge or rounds. " + "Use campaign round for each " + "committed candidate; investigate INCONCLUSIVE results before explicit retry. " + "Finish with campaign final; final does not collect a profile." + ) + return result + if request.evaluation_config is not None or any( + getattr(request, key) is None for key in names + ): + raise ValueError( + "AB/BA requires its existing metric, quality, command and sampling options" + ) + from inferrsi.harness.executor import prepare_project + + repo = request.repo.resolve() + if not repo.is_dir() or root.is_relative_to(repo): + raise ValueError("Campaign output must be outside the editable project") + identity(repo, request.include) # Reject invalid inputs before preparation writes. + specification = {key: getattr(request, key) for key in ( + "metric_key", "metric_unit", "quality_key", "scope", "direction", + "min_improvement_pct", "repetitions", "warmups", "decision", + "require_explanation")} + specification.update(measure_command=shlex.split(request.measure_command), + quality_command=shlex.split(request.quality_command)) + settings = prepare_project(root / "frozen", request.protocol.resolve(), + request.instructions.resolve(), specification) + retain(repo, root / "frozen/baseline", request.include) + settings["frozen_files"].update({p.relative_to(root / "frozen").as_posix(): sha256(p) + for p in (root / "frozen/baseline").rglob("*") if p.is_file()}) + candidate = {"task": "project:" + repo.name, "task_source": "project", + "candidate_kind": "directory", "candidate_name": "candidate", + "candidate_includes": request.include, "baseline_path": "frozen/baseline", + "working_candidate": str(repo), + "selection": ( + # Paired mode ranks by the speedup its decision reads. + {"direction": "maximize", "initial_score": 1.0, + "metric": "paired_median_speedup"} + if request.decision == "paired" else + {"direction": request.direction, "initial_score": None, + "metric": request.metric_key})} + else: + if task_source is None: + raise ValueError("A resolved task resource directory is required to start") + settings = prepare_task_protocol( + task_source, root / "frozen", shlex.split(request.evaluation_args) + ) + (root / "work").mkdir() + (root / "work/candidate.py").write_bytes((root / "frozen/baseline.py").read_bytes()) + candidate = {"task": request.task, "task_source": "benchmark", "candidate_kind": "file", + "candidate_name": "candidate.py", "baseline_path": "frozen/baseline.py", + "working_candidate": "work/candidate.py", + "selection": {"direction": "maximize", "initial_score": 1.0, + "metric": "speedup"}} + plan = {"schema_version": 2, "condition": request.condition, + "round_limit": request.rounds, "max_seconds": max_seconds, + "round_mode": request.round_mode, "final_reserve_seconds": reserve, + "knowledge_allowed": request.knowledge == "on", + "ranking_policy": ranking_policy.receipt(), + "evaluation_timeout_seconds": request.evaluation_timeout_seconds, + "evaluation_prefix": evaluation_prefix, "python": request.python, + "runtime_identity": session_runtime_identity(), **candidate, **settings} + if external_knowledge: + plan["external_knowledge"] = external_knowledge + plan["external_knowledge_project"] = external_project + if report_metadata is not None: + plan["report_metadata"] = report_metadata + result = state.initialize(root, plan) + operation = "campaign" if project else "benchmarks session" + result["instructions"] = ( + f"Read the frozen TASK.md. Record the measured bottleneck with {operation} " + f"diagnose first. Use {operation} knowledge when needed and permitted. " + "Edit the returned working_candidate within its declared input scope. " + f"Before each {operation} round, declare its hypothesis. " + "Record other options you considered with --alternative and why you chose the " + "submitted candidate with --selection-reason. " + "Read the observation, keep failures and use feedback for the next change. " + f"Follow the frozen round policy, then run {operation} final to retest independently. " + "Report summary.json and its curve. Import actual usage exports when available." + ) + if external_knowledge: + result["instructions"] += ( + f" Read external hits with {operation} knowledge-read. Cite the delivered " + "item or read receipt with --knowledge-ref when submitting a candidate." + ) + return result + + plan = json.loads((root / "plan.json").read_text(encoding="utf-8")) + manifest = json.loads((root / "campaign.json").read_text(encoding="utf-8")) + if ( + plan.get("evaluation_mode") == "service_reuse" + or plan.get("schema_version") == 3 + or manifest.get("evaluation_mode") == "service_reuse" + ): + if getattr(request, "confirm_domain_empty", False): + raise ValueError("Service-reuse cleanup requires --cleanup-receipt") + if request.action == "profile": + try: + return state.service_command( + root, request, ranking_policy_for=ranking_policy_for, + ) + except (ValueError, OSError) as exc: + message = "Campaign lock is busy" if isinstance(exc, BlockingIOError) else str(exc) + return { + "exit_code": 2, + "round": request.round, + "profiling_error": { + "status": "failed", "stage": "campaign", "message": message, + }, + } + if request.action == "knowledge-select": + raise ValueError("Service-reuse sessions require their fingerprint-free capture format") + if request.action == "knowledge-read": + raise ValueError("External round knowledge requires a benchmark or AB/BA campaign") + if getattr(request, "mechanism_file", None) is not None: + raise ValueError("Mechanism checks apply to AB/BA project campaign rounds only") + if getattr(request, "alternative", None) is not None or getattr( + request, "selection_reason", None) is not None: + raise ValueError("Round decision declarations require a benchmark or AB/BA campaign") + return state.service_command( + root, request, knowledge_reader=knowledge_reader, ranking_policy_for=ranking_policy_for, + ) + if ( + request.action in ("baseline", "refresh-references", "resume", "profile") + or getattr(request, "retry_of", None) + or getattr(request, "repair_reason", None) + or getattr(request, "cleanup_receipt", None) + or getattr(request, "repair_protocol", None) + or getattr(request, "continue_after_final", None) is not None + or getattr(request, "continuation_reason", None) is not None + ): + raise ValueError("Service lifecycle/retry operations require a service-reuse campaign") + if plan["runtime_identity"] != session_runtime_identity(): + raise ValueError("Optimization runtime changed, use its frozen runtime to resume") + ranking_policy = indexer.resolve_frozen_ranking( + plan, ranking_policy_for, read_only=request.action == "status", + ) + if request.action == "status": + return state.status(root) + if request.action == "diagnose": + return state.record_diagnosis(root, request.bottleneck, request.evidence) + if request.action == "knowledge-select": + if knowledge_reader is None or assemble_text is None: + raise ValueError("A pinned knowledge reader and text assembler are required") + return state.capture_selection( + root, knowledge_reader, assemble_text=assemble_text, + reference=request.reference, revision=request.revision, layer=request.layer, + max_bytes=request.max_bytes, context=request.context, finding=request.finding, + ) + if request.action == "knowledge": + if knowledge_reader is None or prepare_context is None: + raise ValueError("A knowledge reader and capture callback are required") + return state.capture_context( + root, + knowledge_reader, + prepare_context=prepare_context, + ranking_policy=ranking_policy, + external_provider=external_provider, + external_provider_for=external_provider_for, + query="", + relevance=request.query, + relevance_method=request.relevance_method, + scenario=getattr(request, "scenario", None), + context_bytes=request.context_bytes, + limit=request.limit, + ) + if request.action == "knowledge-read": + return state.read_external_context( + root, external_provider, search_ref=request.search_ref, locator=request.locator, + page=request.page, external_provider_for=external_provider_for, + ) + assess = partial(evaluator.assess_ordinary, assess_packaged=assess_packaged) + if request.action == "recover": + return state.recover( + root, assess, confirm_domain_empty=getattr(request, "confirm_domain_empty", False) + ) + final = request.action == "final" + mechanism = None + if not final and getattr(request, "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.evaluator import CONFIDENCE, min_pairs, validate_mechanism + + mechanism = validate_mechanism( + json.loads(Path(request.mechanism_file).read_text(encoding="utf-8"))) + settings = plan["evaluation_settings"] + needed = min_pairs(1 - (1 - CONFIDENCE) / len(mechanism["expect"])) + if settings.get("require_explanation") and needed > settings["repetitions"]: + # Reject before execution so an uncheckable declaration spends no round. + raise ValueError( + f"{len(mechanism['expect'])} expectations need {needed} repetitions under " + f"--require-explanation; the campaign froze {settings['repetitions']}. " + "Declare fewer expectations") + return state.evaluate_round( + root, candidate=None if final else request.candidate, + hypothesis="Independent final of the selected candidate" if final else request.hypothesis, + usage=request.usage_export, execute=executor.execute_ordinary, assess=assess, final=final, + reason=getattr(request, "reason", None), + strategy=getattr(request, "strategy", None), + alternatives=getattr(request, "alternative", None), + selection_reason=getattr(request, "selection_reason", None), + knowledge_refs=getattr(request, "knowledge_ref", None), + mechanism=mechanism, + ) diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/manager/_state.py similarity index 85% rename from src/inferrsi/harness/optimization.py rename to src/inferrsi/harness/manager/_state.py index 059a280ba..ed7186117 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/manager/_state.py @@ -5,17 +5,18 @@ import math import time import uuid +from dataclasses import dataclass from functools import cache from pathlib import Path -from . import attempt_recovery, candidates -from .artifact_primitives import digest, file_lock, sha256 -from .atomic_json import atomic_write_json, durable_write_json -from .records import atomic_capture -from .records.evidence import bounded_record_bytes, sanitized_text -from .records.knowledge_capture import MAX_CONTEXT_CAPTURE_BYTES -from .task_protocol import TaskProtocolError -from .usage import normalize_usage, usage_totals +from .. import analyzer, evaluator, indexer +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 . import _attempt_recovery as attempt_recovery def _locked(root): @@ -59,36 +60,6 @@ def initialize(root: Path, plan: dict) -> dict: return status(root) -def _require_ranking_policy(recorded, effective): - if (not isinstance(recorded, dict) or not isinstance(effective, dict) - or type(recorded.get("version")) is not int - or not isinstance(recorded.get("weights"), dict) - or any(type(value) not in (int, float) for value in recorded["weights"].values()) - or recorded != effective): - raise ValueError("Frozen ranking policy changed or is incomplete, use its original runtime") - - -def resolve_frozen_ranking(plan, ranking_policy_for, *, read_only=False): - if read_only and "ranking_policy" not in plan: - return None - recorded = plan.get("ranking_policy") - if not isinstance(recorded, dict) or not isinstance(recorded.get("id"), str): - raise ValueError("Missing frozen ranking policy, use the original runtime to resume") - if ranking_policy_for is None: - raise ValueError("A resolver for the frozen ranking policy is required") - policy = ranking_policy_for(recorded["id"]) - effective = (policy.configuration() if plan.get("evaluation_mode") == "service_reuse" - else policy.receipt()) - _require_ranking_policy(recorded, effective) - return policy - - -def _check_context_ranking(plan, context): - if "ranking_policy" in plan: - _require_ranking_policy(context.get("request", {}).get("ranking_policy"), - plan["ranking_policy"]) - - def _control(root): plan = json.loads((root / "plan.json").read_text(encoding="utf-8")) state = json.loads((root / "state.json").read_text(encoding="utf-8")) @@ -98,9 +69,7 @@ def _control(root): or plan.get("schema_version") == 3 or manifest_header.get("evaluation_mode") == "service_reuse" ): - from . import project_service as service - - manifest = service.read(root / "campaign.json") + manifest = service_io.read(root / "campaign.json") if ( plan.get("evaluation_mode") != "service_reuse" or plan.get("schema_version") != 3 @@ -116,9 +85,11 @@ def _control(root): ): raise ValueError("Incompatible service campaign records") if "ranking_policy" in manifest or "ranking_policy" in plan: - _require_ranking_policy(manifest.get("ranking_policy"), plan.get("ranking_policy")) - service.no_fingerprints(plan) - service.no_fingerprints(state) + indexer.require_ranking_policy( + manifest.get("ranking_policy"), plan.get("ranking_policy") + ) + service_io.no_fingerprints(plan) + service_io.no_fingerprints(state) return plan, state if digest(plan) != state["plan_digest"]: raise ValueError("Frozen optimization plan changed") @@ -128,21 +99,6 @@ def _control(root): return plan, state -def _read_context(root, reference): - raw, state = bounded_record_bytes(root, reference.get("path"), MAX_CONTEXT_CAPTURE_BYTES) - if raw is None: - raise ValueError(f"Invalid delivered knowledge context ({state})") - if hashlib.sha256(raw).hexdigest() != reference.get("sha256"): - raise ValueError("Delivered knowledge context changed") - try: - record = json.loads(raw) - except (ValueError, RecursionError): - raise ValueError("Invalid delivered knowledge context (invalid_format)") from None - if not isinstance(record, dict): - raise ValueError("Invalid delivered knowledge context (invalid_format)") - return record - - class _FrozenInputError(ValueError): pass @@ -175,10 +131,10 @@ def _load(root, *, read_only=False): diagnoses = _diagnosis_index(state) contexts = {} for context in state["contexts"]: - retained = _read_context(root, context) + retained = knowledge_capture.read_retained(root, context) if context.get("kind") not in ("external_search", "external_read"): _check_context_diagnosis(plan, diagnoses, context, retained) - _check_context_ranking(plan, retained) + indexer.check_context_ranking(plan, retained) contexts[context["path"]] = context for record in [*state["rounds"], *state.get("final_attempts", ()), *([state["final"]] if state["final"] else [])]: @@ -369,14 +325,6 @@ def _check_context_diagnosis(plan, diagnoses, reference, capture): _check_activity_diagnosis(plan, diagnoses, binding) -def _context_diagnosis(plan, state): - reference = _diagnosis_reference(plan, state) - if reference: - return {**reference, "reference_epoch": state.get("reference_epoch"), - "started_at": time.time()} - return None - - def _diagnosis_reference(plan, state): diagnosis = _diagnosis(state) if diagnosis: @@ -394,21 +342,9 @@ def _retain_diagnosis(root, plan, state, bottleneck, evidence): "state": "active" if state["state"] == "needs_baseline" else state["state"]}, reserve=plan["final_reserve_seconds"], ) - bottleneck = bottleneck.strip() - if not bottleneck or len(bottleneck) > 4096: - raise ValueError("Bottleneck must be a nonempty description of at most 4096 characters") - if evidence.is_symlink() or not evidence.is_file(): - raise ValueError("Diagnosis evidence must be a regular UTF-8 measurement summary") - with evidence.open("rb") as stream: - raw = stream.read(65537) - if len(raw) > 65536: - raise ValueError("Diagnosis evidence exceeds 64 KiB; provide a measurement summary") - summary = raw.decode("utf-8").strip() - if not summary or "\x00" in summary: - raise ValueError("Diagnosis evidence must contain a nonempty UTF-8 measurement summary") - diagnosis = {"id": "diagnosis-" + uuid.uuid4().hex, "bottleneck": bottleneck, - "measurement_summary": summary, "reference_epoch": state.get("reference_epoch"), - "recorded_at": time.time()} + draft = analyzer.diagnosis_draft(bottleneck, evidence) + diagnosis = {"id": "diagnosis-" + uuid.uuid4().hex, **draft, + "reference_epoch": state.get("reference_epoch"), "recorded_at": time.time()} state.setdefault("diagnoses", []).append(diagnosis) atomic_write_json(root / "state.json", state) return {"diagnosis": diagnosis} @@ -443,38 +379,95 @@ def _store_knowledge(root, kind, number, record): "kind": kind, "round": number} -def _register_context(root, state, number, binding, path, fingerprint, *, selected=False): - reference = {"path": path.relative_to(root).as_posix(), "sha256": fingerprint, - "kind": "delivered_context"} - document = _read_context(root, reference) - if selected and document["selection"]["status"] != "delivered": - reference["kind"] = "knowledge_refusal" - retained = {**reference, "round": number} if number is not None else dict(reference) - if binding: - retained["diagnosis_id"] = binding["diagnosis_id"] +@dataclass(frozen=True) +class _KnowledgeRequest: + context_id: str + diagnosis_id: str | None + reference_epoch: int | None + started_at: float + round_number: int | None + + @property + def binding(self): + if self.diagnosis_id is None: + return None + return {"diagnosis_id": self.diagnosis_id, "reference_epoch": self.reference_epoch, + "started_at": self.started_at} + + +def _knowledge_request(plan, state, *, round_number=None): + diagnosis_id = _diagnosis_reference(plan, state).get("diagnosis_id") + return _KnowledgeRequest("context-" + uuid.uuid4().hex, diagnosis_id, + state.get("reference_epoch"), time.time(), round_number) + + +def _commit_knowledge(root, ticket, delivery, *, external_search=None): + """Register a checked delivery while the caller holds the session lock.""" + plan, state = _control(root) + diagnosis = _diagnosis(state) + reference, context = delivery["reference"], delivery["context"] + if (ticket.reference_epoch != state.get("reference_epoch") + or ticket.diagnosis_id != (diagnosis["id"] if diagnosis else None) + or context.get("diagnosis_binding") != ticket.binding): + raise ValueError("Knowledge delivery belongs to a different diagnosis or condition epoch") + if reference["path"] != f"knowledge/{ticket.context_id}.json": + raise ValueError("Knowledge capture differs from its dispatched request") + retained = dict(reference) + if ticket.round_number is not None: + retained["round"] = ticket.round_number + if ticket.diagnosis_id is not None: + retained["diagnosis_id"] = ticket.diagnosis_id + service_mode = plan.get("evaluation_mode") == "service_reuse" + if service_mode: + service_io.no_fingerprints(context) + path = service_io.safe_path(root, reference["path"]) + previous = next((item for item in state["contexts"] if item["path"] == reference["path"]), None) + if previous is not None: + recorded = (service_io.read(path) if service_mode + else knowledge_capture.read_retained(root, previous)) + if previous != retained or recorded != context: + raise ValueError("Conflicting knowledge delivery for a registered request") + if external_search is not None: + for item in state["contexts"]: + if item.get("kind") == "external_search" and item["round"] == ticket.round_number: + search = knowledge_capture.read_retained(root, item) + if search["context_ref"] == reference["path"]: + return {**delivery, "external": {**search, "reference": item}} + return delivery + if service_mode: + path.parent.mkdir(exist_ok=True) + atomic_write_json(path, context) + else: + if ticket.round_number is not None and ticket.round_number != len(state["rounds"]) + 1: + raise ValueError("Knowledge delivery belongs to an earlier round") + if context.get("context_id") != ticket.context_id: + raise ValueError("Knowledge capture differs from its dispatched request") + knowledge_capture.store_capture(root, context, expected_sha256=reference["sha256"]) state["contexts"].append(retained) - return {"reference": reference, "context": document} + if external_search is not None: + search = {**external_search(plan, state), "context_ref": reference["path"]} + search_ref = _store_knowledge(root, "external_search", ticket.round_number, search) + state["contexts"].append(search_ref) + delivery = {**delivery, "external": {**search, "reference": search_ref}} + atomic_write_json(root / "state.json", state) + return delivery def capture_selection(root: Path, reader, *, assemble_text, **request) -> dict: - """Retain an explicit pin in a managed optimization campaign with its current diagnosis.""" + """Commit an explicit Reader selection against the active round and diagnosis.""" with _locked(root): plan, state = _load(root) if plan.get("evaluation_mode") == "service_reuse": raise ValueError("Service-reuse sessions require their fingerprint-free capture format") - number = _knowledge_round(plan, state) - binding = _context_diagnosis(plan, state) - path, fingerprint = atomic_capture.retain_selection( - root, reader=reader, context_id="context-" + uuid.uuid4().hex, - diagnosis_binding=binding, ranking_policy=plan.get("ranking_policy"), + ticket = _knowledge_request(plan, state, round_number=_knowledge_round(plan, state)) + delivery = indexer.pinned_delivery( + root, plan, context_id=ticket.context_id, binding=ticket.binding, reader=reader, assemble_text=assemble_text, **request, ) - response = _register_context(root, state, number, binding, path, fingerprint, selected=True) - atomic_write_json(root / "state.json", state) - return response + return _commit_knowledge(root, ticket, delivery) -def capture_context(root: Path, reader, *, retain_context, external_provider=None, +def capture_context(root: Path, reader, *, prepare_context, external_provider=None, external_provider_for=None, **request) -> dict: with _locked(root): plan, state = _load(root) @@ -486,25 +479,24 @@ def capture_context(root: Path, reader, *, retain_context, external_provider=Non if external_provider is None and external_provider_for is None: raise ValueError("The frozen external knowledge provider is unavailable") request["relevance"] = sanitized_text(request["relevance"], "", limit=None) - binding = _context_diagnosis(plan, state) - path, fingerprint = retain_context(root, context_id="context-" + uuid.uuid4().hex, - reader=reader, diagnosis_binding=binding, **request) - response = _register_context(root, state, number, binding, path, fingerprint) - if settings: + ticket = _knowledge_request(plan, state, round_number=number) + delivery = indexer.ordinary_delivery( + root, plan, context_id=ticket.context_id, binding=ticket.binding, reader=reader, + prepare_context=prepare_context, **request, + ) + if not settings: + return _commit_knowledge(root, ticket, delivery) + + def search(plan, state): remaining = _knowledge_time(plan, state) - if remaining > 0: - if external_provider_for is not None: - external_provider = external_provider_for(plan) - result = external_provider.search(request["relevance"], settings=settings, - limit=request["limit"], timeout=remaining) - else: - result = {"state": "timeout", "items": [], "count": 0} - search = {**result, **settings, "context_ref": response["reference"]["path"]} - search_ref = _store_knowledge(root, "external_search", number, search) - state["contexts"].append(search_ref) - response["external"] = {**search, "reference": search_ref} - atomic_write_json(root / "state.json", state) - return response + if remaining <= 0: + return {"state": "timeout", "items": [], "count": 0, **settings} + provider = external_provider_for(plan) if external_provider_for else external_provider + result = provider.search(request["relevance"], settings=settings, + limit=request["limit"], timeout=remaining) + return {**result, **settings} + + return _commit_knowledge(root, ticket, delivery, external_search=search) def read_external_context(root: Path, provider, *, search_ref, locator, page, @@ -523,7 +515,7 @@ def read_external_context(root: Path, provider, *, search_ref, locator, page, and entry["round"] == number), None) if reference is None: raise ValueError("Supply a CANNBot search reference from the current round") - search = _read_context(root, reference) + search = knowledge_capture.read_retained(root, reference) hit = next((item for item in search["items"] if item["locator"] == locator), None) if search["state"] != "ok" or not search["revision"] or hit is None: raise ValueError("Supply a versioned CANNBot hit from the recorded search") @@ -556,7 +548,7 @@ def _validate_knowledge_refs(root, contexts, refs): if reference is None or (separator and reference["kind"] != "delivered_context"): raise ValueError("Cite a delivered context or CANNBot read receipt from this session") if separator: - capture = _read_context(root, reference) + capture = knowledge_capture.read_retained(root, reference) if not any(entry["ref"] == item and entry["resources"] for entry in capture["contexts"]): raise ValueError("Cite an item with delivered resources from this context") @@ -570,9 +562,7 @@ def _usage_record(source, *, fingerprint=True): if not isinstance(payload, dict): raise ValueError("Usage export must be a JSON object") if not fingerprint: - from .project_service import no_fingerprints - - no_fingerprints(payload) + service_io.no_fingerprints(payload) usage = normalize_usage(payload) if not usage or usage.get("input_tokens") is None or usage.get("output_tokens") is None: raise ValueError("Usage export requires nonnegative input_tokens and output_tokens") @@ -842,12 +832,12 @@ def evaluate_round(root: Path, *, candidate: Path | None, hypothesis: str, return _settle(root, plan, state, pending, execution, assess) -def read_records(root: Path) -> tuple[dict, dict, dict]: +def read_session_records(root: Path) -> tuple[dict, dict, dict]: """Read one validated state for status, dashboard and reconstructable summaries.""" plan, state = _load(root, read_only=True) summary = _summary(root, plan, state) if plan.get("evaluation_mode") == "service_reuse": - from . import service_observations + from ..records import service_observations state = service_observations.selection_view(state, state["attempts"]) return plan, state, summary @@ -978,17 +968,17 @@ def recover(root: Path, assess, *, confirm_domain_empty=False) -> dict: def _service_initialize(root, plan): - from . import project_service as service + from .. import executor - service.validate(plan["evaluation_settings"]) + executor.validate_service_settings(plan["evaluation_settings"]) if ( type(plan["round_limit"]) is not int or plan["round_limit"] < 1 or ( plan["round_mode"] not in ("up_to", "exact") - or not service.positive(plan["max_seconds"]) - or not service.positive(plan["evaluation_timeout_seconds"]) - or not service.positive(plan["final_reserve_seconds"]) + or not service_io.positive_number(plan["max_seconds"]) + or not service_io.positive_number(plan["evaluation_timeout_seconds"]) + or not service_io.positive_number(plan["final_reserve_seconds"]) or plan["final_reserve_seconds"] >= plan["max_seconds"] ) ): @@ -1041,17 +1031,17 @@ def _service_runtime_matches(plan): def _service_load(root, plan, state, *, read_only=False): - from . import project_service as service - from . import service_observations + from .. import executor + from ..records import service_observations if not read_only and not _service_runtime_matches(plan): raise ValueError("Runtime package version changed; use the recorded version to resume") - service.validate(plan["evaluation_settings"]) - if service.read(root / "frozen/evaluation.json") != plan["evaluation_settings"]: + executor.validate_service_settings(plan["evaluation_settings"]) + if service_io.read(root / "frozen/evaluation.json") != plan["evaluation_settings"]: raise ValueError("Retained protocol and plan disagree") - service.validate_conditions(state["conditions"]) - candidates.members(service.safe_path(root, state["protocol_path"])) - candidates.members(service.safe_path(root, plan["baseline_path"])) + executor.validate_service_conditions(state["conditions"]) + candidates.members(service_io.safe_path(root, state["protocol_path"])) + candidates.members(service_io.safe_path(root, plan["baseline_path"])) diagnoses = _diagnosis_index(state) for attempt in state["attempts"]: if not service_observations.matches_control(root, attempt): @@ -1059,30 +1049,30 @@ def _service_load(root, plan, state, *, read_only=False): if attempt["kind"] == "round": _check_activity_diagnosis(plan, diagnoses, attempt) for context in state["contexts"]: - retained = service.read(service.safe_path(root, context["path"])) - _check_context_ranking(plan, retained) + retained = service_io.read(service_io.safe_path(root, context["path"])) + indexer.check_context_ranking(plan, retained) _check_context_diagnosis(plan, diagnoses, context, retained) for event in state["recovery_events"]: if event["kind"] == "cleanup_inspection": - proof = service.read(service.safe_path(root, event["path"])) + proof = service_io.read(service_io.safe_path(root, event["path"])) if ( proof["attempt_id"] != event["attempt_id"] or proof.get("cleanup_complete") is not True ): raise ValueError("Retained cleanup inspection is incomplete") if state["best"] is not None: - candidates.members(service.safe_path(root, state["best"]["path"])) + candidates.members(service_io.safe_path(root, state["best"]["path"])) return plan, state def _service_profiling(root, attempt, *, published=None): - from . import project_service as service - from . import service_backfill + from .. import executor + from . import _service_backfill as service_backfill profile = ( published or service_backfill.latest(root, attempt) - or service.attempt_profile(root, attempt) + or executor.read_service_attempt_profile(root, attempt) ) if not profile: return {"available": False} @@ -1090,7 +1080,7 @@ def _service_profiling(root, attempt, *, published=None): def _service_round_view(root, attempt, *, profiling=None): - from . import service_observations + from ..records import service_observations if attempt["kind"] == "round": if profiling is None: @@ -1100,7 +1090,7 @@ def _service_round_view(root, attempt, *, profiling=None): def _service_account_capture(root, state, pending, execution): - from . import project_service as service + from .. import executor capture = execution.get("capture") attempt_id = pending["attempt_id"] @@ -1109,14 +1099,14 @@ def _service_account_capture(root, state, pending, execution): or capture.get("id") != attempt_id or not isinstance(execution.get("binding"), dict) or execution["binding"].get("attempt_id") != attempt_id - or not service.number(capture.get("started_at")) + or not service_io.finite_number(capture.get("started_at")) ): return ledger = state.setdefault("profiling_accounting", {}) if attempt_id not in ledger: ledger[attempt_id] = { "started_at": capture["started_at"], - "elapsed_seconds": service.proven_capture_elapsed(root, pending, execution), + "elapsed_seconds": executor.service_capture_elapsed(root, pending, execution), } @@ -1126,7 +1116,6 @@ def _service_deadline(state): def _service_continuation_block_reason(root, plan, state, reference_reason, *, budget_time): - from . import service_evidence if plan.get("allow_final_continuation") is not True or plan["round_mode"] != "up_to": return "continuation_not_enabled" @@ -1154,7 +1143,7 @@ def _service_continuation_block_reason(root, plan, state, reference_reason, *, b return "round_budget_exhausted" if budget_time >= _service_deadline(state) - plan["final_reserve_seconds"]: return "search_time_exhausted" - return service_evidence.settlement_reason(root, plan, state, final) + return evaluator.service_settlement_reason(root, plan, state, final) def _service_final_attempts(state): @@ -1172,7 +1161,6 @@ def _service_final_attempts(state): def _service_selected_evidence_reason(root, plan, state, *, starting_epoch=False): - from . import service_evidence if ( state["initial_reference"] is None or state["comparison_parent"] is None @@ -1181,7 +1169,7 @@ def _service_selected_evidence_reason(root, plan, state, *, starting_epoch=False return "missing_baseline_reference" if state["best"] is not None and "parent_reference_at_acceptance" not in state["best"]: return "unverifiable_selected_attempt_binding" - return service_evidence.references_reason( + return evaluator.service_references_reason( root, plan, state, state["initial_reference"], state["comparison_parent"], state["best"] ) @@ -1215,7 +1203,7 @@ def _service_final_reason(plan, state, reference_reason, *, budget_time=None): def _service_status(root, plan, state): - from . import service_observations + from ..records import service_observations reference_reason = _service_final_reference_reason(root, plan, state) now = time.time() @@ -1283,7 +1271,7 @@ def _service_status(root, plan, state): def _service_summary(root, plan, state, *, attempts=None, budget_time=None): - from . import service_observations + from ..records import service_observations if attempts is None: attempts = [_service_round_view(root, attempt) for attempt in state["attempts"]] @@ -1329,10 +1317,9 @@ def _service_summary(root, plan, state, *, attempts=None, budget_time=None): def _service_settle(root, plan, state, pending, execution): - from . import project_service as service - from . import service_evidence + from .. import executor - directory = service.safe_path(root, pending["path"]) + directory = service_io.safe_path(root, pending["path"]) checkpoint = execution.get("checkpoint") if checkpoint: if not _service_cleanup_confirmed(state, {**pending, "execution": execution}): @@ -1357,9 +1344,9 @@ def _service_settle(root, plan, state, pending, execution): not execution.get("profile") and not execution.get("profiling_error") and "profile" in plan["evaluation_settings"]["commands"] - and checkpoint["assessment"]["reason"] in service.INLINE_PROFILE_REASONS + and evaluator.service_profile_eligible(checkpoint["assessment"]["reason"]) ): - execution["profiling_error"] = service.capture_diagnostic( + execution["profiling_error"] = executor.service_capture_diagnostic( root, directory, "profile", @@ -1369,7 +1356,7 @@ def _service_settle(root, plan, state, pending, execution): atomic_write_json(directory / "execution/execution.json", execution) path = directory / "observation.json" if path.exists(): - record = service.read(path) + record = service_io.read(path) if record["attempt_id"] != pending["attempt_id"]: raise ValueError("Recovery attempt identity mismatch") else: @@ -1382,10 +1369,10 @@ def _service_settle(root, plan, state, pending, execution): if any(item["attempt_id"] == record["attempt_id"] for item in state["attempts"]): state["pending"] = None return _service_status(root, plan, state) - reason = service_evidence.settlement_reason(root, plan, state, record) + reason = evaluator.service_settlement_reason(root, plan, state, record) if reason: record["assessment_before_settlement"] = record["assessment"] - record["assessment"] = service.assessment( + record["assessment"] = evaluator.service_assessment( "INCONCLUSIVE", reason, performance=record["assessment"].get("performance"), @@ -1394,23 +1381,25 @@ def _service_settle(root, plan, state, pending, execution): kind = record["kind"] verdict = record["assessment"]["verdict"] if kind == "round": - choice = service_evidence.choice(record, record["execution"]) if verdict == "PASS" else None + choice = ( + evaluator.service_choice(record, record["execution"]) if verdict == "PASS" else None + ) record["profiling"] = _service_profiling(root, record) record["selected"] = choice is not None and ( state["best"] is None - or service.better( + or evaluator.prefer_service_measurements( plan["evaluation_settings"], choice["measurements"]["values"], state["best"]["measurements"]["values"], ) ) record["best_after"] = ( - choice if record["selected"] else service_evidence.reference_snapshot(state["best"]) + choice if record["selected"] else evaluator.service_reference_snapshot(state["best"]) ) atomic_write_json(path, record) if kind == "baseline": if verdict == "PASS": - choice = service_evidence.choice(record, record["execution"]) + choice = evaluator.service_choice(record, record["execution"]) state.update( initial_reference=choice, comparison_parent=choice, best=choice, state="active" ) @@ -1452,7 +1441,7 @@ def _service_settle(root, plan, state, pending, execution): "id": record["attempt_id"] + "-stagnation", "round": record["round_number"], "consecutive": stagnation["consecutive"], - "best": service_evidence.reference_snapshot(state["best"]), + "best": evaluator.service_reference_snapshot(state["best"]), "attempt_path": record["path"], "action": policy["action"], "message": "Reassess system-wide critical paths, compute, communication, " @@ -1497,12 +1486,12 @@ def _service_command_result(root, plan, state, execution): def _service_execute(root, directory, plan, state, deadline): - from . import project_service as service + from .. import executor pending = state["pending"] if pending["kind"] != "refresh": - return service.execute(root, directory, plan, pending, deadline) - from . import service_evidence, service_observations + return executor.execute_service_attempt(root, directory, plan, pending, deadline) + from ..records import service_observations references, runs = [], [] started = time.monotonic() @@ -1522,7 +1511,7 @@ def _service_execute(root, directory, plan, state, deadline): references.append(references[0]) continue relative = pending["path"] + "/" + label - subdir = service.safe_path(root, relative) + subdir = service_io.safe_path(root, relative) subdir.mkdir() job = { **pending, @@ -1536,21 +1525,23 @@ def _service_execute(root, directory, plan, state, deadline): "parent": None, "initial": None, } - result = service.execute(root, subdir, plan, job, deadline) + result = executor.execute_service_attempt(root, subdir, plan, job, deadline) runs.append(result) if result["assessment"]["verdict"] != "PASS": return { - "assessment": service.assessment("INCONCLUSIVE", "reference_refresh_incomplete"), + "assessment": evaluator.service_assessment( + "INCONCLUSIVE", "reference_refresh_incomplete" + ), "runs": runs, "cleanup_verified": result["cleanup_verified"], "elapsed_seconds": time.monotonic() - started, } - references.append(service_evidence.choice(job, result)) + references.append(evaluator.service_choice(job, result)) parent_profile = service_observations.reference_view( pending["refresh_parent"], service_observations.inline_profiles(state["attempts"]) )["profile"] return { - "assessment": service.assessment( + "assessment": evaluator.service_assessment( "PASS", "references_refreshed_not_candidate_acceptance", eligible=False ), "retained_parent_profile": parent_profile, @@ -1570,18 +1561,17 @@ def _service_cleanup_confirmed(state, attempt): def _service_cleanup_receipt(root, state, path): - from . import project_service as service - from .local_process import _group_empty + from ..executor import process_group_empty latest = state["pending"] or (state["attempts"][-1] if state["attempts"] else None) - proof = service.read(path) + proof = service_io.read(path) if ( latest is None or proof.get("attempt_id") != latest["attempt_id"] or not proof.get("reason") or ( proof.get("cleanup_complete") is not True - or not service.positive(proof.get("observed_at")) + or not service_io.positive_number(proof.get("observed_at")) or not isinstance(proof.get("services"), list) or any(not isinstance(item, dict) for item in proof.get("services", [])) ) @@ -1589,15 +1579,15 @@ def _service_cleanup_receipt(root, state, path): raise ValueError( "Cleanup inspection must identify the attempt, time, reason and all services" ) - directory = service.safe_path(root, latest["path"]) + directory = service_io.safe_path(root, latest["path"]) owners = [ - service.read(service.safe_path(directory, name)) + service_io.read(service_io.safe_path(directory, name)) for name in ( "service/owner.json", "baseline/service/owner.json", "parent/service/owner.json", ) - if service.safe_path(directory, name).is_file() + if service_io.safe_path(directory, name).is_file() ] if len(owners) != len(proof["services"]): raise ValueError("Cleanup inspection must cover every recorded service owner") @@ -1613,41 +1603,41 @@ def _service_cleanup_receipt(root, state, path): raise ValueError("Cleanup inspection service owner mismatch") if ( owner.get("process_group_id") is not None - and _group_empty(owner["process_group_id"]) is not True + and process_group_empty(owner["process_group_id"]) is not True ): raise ValueError("Recorded process domain is still live or unobservable") relative = "recoveries/cleanup-" + uuid.uuid4().hex + ".json" (root / "recoveries").mkdir(exist_ok=True) - atomic_write_json(service.safe_path(root, relative), proof) + atomic_write_json(service_io.safe_path(root, relative), proof) state["recovery_events"].append( {"kind": "cleanup_inspection", "attempt_id": latest["attempt_id"], "path": relative} ) atomic_write_json(root / "state.json", state) -def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=None): +def service_command(root, request, *, ranking_policy_for=None, knowledge_reader=None): """Service-mode operations inside the shared controller's lock and control record.""" - from . import project_service as service - from . import service_evidence + from .. import executor with _locked(root): - action = args.session_action + action = request.action if action == "profile": - from . import service_backfill + from . import _service_backfill as service_backfill plan, _ = _control(root) - resolve_frozen_ranking(plan, ranking_policy_for) - return service_backfill.run(root, args) + indexer.resolve_frozen_ranking(plan, ranking_policy_for) + return service_backfill.run(root, request) plan, state = _load(root, read_only=action == "status") - ranking_policy = resolve_frozen_ranking(plan, ranking_policy_for, - read_only=action == "status") - after_final = getattr(args, "continue_after_final", None) - continuation_reason = getattr(args, "continuation_reason", None) + ranking_policy = indexer.resolve_frozen_ranking( + plan, ranking_policy_for, read_only=action == "status" + ) + after_final = getattr(request, "continue_after_final", None) + continuation_reason = getattr(request, "continuation_reason", None) continuation = None if after_final is not None or continuation_reason is not None: if ( action != "round" or not after_final or not (continuation_reason or "").strip() - or any(getattr(args, name, None) is not None for name in ( + or any(getattr(request, name, None) is not None for name in ( "retry_of", "repair_reason", "repair_protocol", "cleanup_receipt", )) ): @@ -1661,8 +1651,8 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non if after_final != state["final"]["attempt_id"]: raise ValueError("Continuation must name the current failed final") continuation = {"after_final": after_final, "reason": continuation_reason.strip()} - if getattr(args, "cleanup_receipt", None) is not None: - _service_cleanup_receipt(root, state, args.cleanup_receipt) + if getattr(request, "cleanup_receipt", None) is not None: + _service_cleanup_receipt(root, state, request.cleanup_receipt) if action == "status": result = _service_status(root, plan, state) latest_by_round = { @@ -1679,25 +1669,25 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non ] return result if action == "diagnose": - return _retain_diagnosis(root, plan, state, args.bottleneck, args.evidence) + return _retain_diagnosis(root, plan, state, request.bottleneck, request.evidence) if action == "recover": if state["pending"] and state["pending"]["kind"] == "profile": - from . import service_backfill + from . import _service_backfill as service_backfill - return service_backfill.recover(root, plan, state, args) + return service_backfill.recover(root, plan, state, request) if state["pending"] is None: atomic_write_json(root / "summary.json", _service_summary(root, plan, state)) return _service_command_result( root, plan, state, {"profiling_error": state.get("last_profiling_error")} ) pending = state["pending"] - directory = service.safe_path(root, pending["path"]) + directory = service_io.safe_path(root, pending["path"]) observation = directory / "observation.json" if observation.exists(): - result = service.read(observation)["execution"] + result = service_io.read(observation)["execution"] else: try: - result = service.read(directory / "execution/execution.json") + result = service_io.read(directory / "execution/execution.json") except (OSError, ValueError): if not _service_cleanup_confirmed(state, pending): raise ValueError( @@ -1713,7 +1703,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non result.update( status="interrupted", cleanup_verified=True, - assessment=service.assessment( + assessment=evaluator.service_assessment( "INCONCLUSIVE", "interrupted_execution_requires_full_retry" ), ) @@ -1729,32 +1719,15 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non ) if not plan["knowledge_allowed"] or knowledge_reader is None: raise ValueError("Knowledge delivery is disabled or unavailable") - binding = _context_diagnosis(plan, state) - context = knowledge_reader.collect_service_context( - args.query, - relevance_method=args.relevance_method, - limit=args.limit, - context_bytes=args.context_bytes, - ranking_policy=ranking_policy, + ticket = _knowledge_request(plan, state) + delivery = indexer.service_delivery( + plan, context_id=ticket.context_id, binding=ticket.binding, reader=knowledge_reader, + query=request.query, relevance_method=request.relevance_method, limit=request.limit, + context_bytes=request.context_bytes, ranking_policy=ranking_policy, ) - _check_context_ranking(plan, context) - if binding: - context["diagnosis_binding"] = binding - service.no_fingerprints(context) - relative = "knowledge/context-" + uuid.uuid4().hex + ".json" - (root / "knowledge").mkdir(exist_ok=True) - atomic_write_json(service.safe_path(root, relative), context) - reference = { - "path": relative, - "kind": "delivered_context", - "prepared_not_consumed": True, - } - state["contexts"].append( - {**reference, "diagnosis_id": binding["diagnosis_id"]} if binding else reference) - atomic_write_json(root / "state.json", state) - return {"reference": reference, "context": context} + return _commit_knowledge(root, ticket, delivery) if action == "resume": - if not args.reason.strip() or state["pending"] is not None: + if not request.reason.strip() or state["pending"] is not None: raise ValueError( "Record investigation before resume; resolve pending execution first" ) @@ -1764,7 +1737,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non and state["recovery_events"] and ( state["recovery_events"][-1].get("kind") == "resume" - and state["recovery_events"][-1].get("reason") == args.reason + and state["recovery_events"][-1].get("reason") == request.reason ) ): return _service_status(root, plan, state) @@ -1776,14 +1749,14 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non ): raise ValueError("Cannot resume without verified cleanup and usable references") state["recovery_events"].append( - {"kind": "resume", "reason": args.reason, "attempt_id": latest["attempt_id"]} + {"kind": "resume", "reason": request.reason, "attempt_id": latest["attempt_id"]} ) state["state"] = "active" atomic_write_json(root / "state.json", state) return _service_status(root, plan, state) - retry = getattr(args, "retry_of", None) - repair = getattr(args, "repair_reason", None) - repaired_protocol = getattr(args, "repair_protocol", None) + retry = getattr(request, "retry_of", None) + repair = getattr(request, "repair_reason", None) + repaired_protocol = getattr(request, "repair_protocol", None) if repaired_protocol and not retry: raise ValueError("Execution script repairs require an explicit --retry-of") old = next((item for item in state["attempts"] if item["attempt_id"] == retry), None) @@ -1848,22 +1821,22 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non raise ValueError("Refresh both incompatible performance references first") diagnosis = _diagnosis_reference(plan, state) number = old["round_number"] if old else len(state["rounds"]) + 1 - if number > plan["round_limit"] or not args.hypothesis.strip(): + if number > plan["round_limit"] or not request.hypothesis.strip(): raise ValueError("Round budget exhausted or hypothesis missing") - if args.candidate.is_symlink(): + if request.candidate.is_symlink(): raise ValueError("Candidate root cannot be symbolic") - source = args.candidate.resolve() - commit = service.revision(source, plan["candidate_includes"]) + source = request.candidate.resolve() + commit = executor.service_revision(source, plan["candidate_includes"]) candidate_id = f"candidate-{number:03d}" if not old: state["rounds"].append({"number": number, "terminal": False, "attempt_ids": []}) elif kind == "refresh": - if initial is None or parent is None or not args.reason.strip(): + if initial is None or parent is None or not request.reason.strip(): raise ValueError("Initial references and a change reason required") if len(state["rounds"]) >= plan["round_limit"]: raise ValueError("No round budget for current-conditions acceptance") - conditions = service.read(args.conditions) - service.validate_conditions(conditions) + conditions = service_io.read(request.conditions) + executor.validate_service_conditions(conditions) if not old: if conditions == state["conditions"]: raise ValueError("No changed conditions; reuse compatible retained references") @@ -1881,14 +1854,14 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non source, commit = root / plan["baseline_path"], plan["baseline_revision"] candidate_id, number = "reference-refresh", None else: - if plan["round_mode"] == "up_to" and not (args.reason or "").strip(): + if plan["round_mode"] == "up_to" and not (request.reason or "").strip(): raise ValueError("Record why search stopped") admission = _service_final_reason( plan, state, _service_final_reference_reason(root, plan, state), ) selected = state["best"] source = ( - service.safe_path(root, selected["path"]) + service_io.safe_path(root, selected["path"]) if selected else root / plan["baseline_path"] ) @@ -1902,7 +1875,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non else (f"references/epoch-{state['reference_epoch']}" if kind == "refresh" else kind) ) relative = prefix + "/attempt-" + attempt_id - directory = service.safe_path(root, relative) + directory = service_io.safe_path(root, relative) directory.mkdir(parents=True) protocol_path = state["protocol_path"] if kind == "final" and state["best"] is not None: @@ -1911,22 +1884,22 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non candidates.retain(repaired_protocol, directory / "protocol", fingerprint=False) protocol_path = relative + "/protocol" state["protocol_path"] = protocol_path - observations, raw = _usage_record(getattr(args, "usage_export", None), fingerprint=False) + observations, raw = _usage_record(getattr(request, "usage_export", None), fingerprint=False) if raw is not None: (directory / "agent-usage.json").write_bytes(raw) if kind == "round": - service.retain_revision( + executor.retain_service_revision( source, directory / "candidate", plan["candidate_includes"], commit ) - if service.revision(source, plan["candidate_includes"]) != commit: + if executor.service_revision(source, plan["candidate_includes"]) != commit: raise ValueError("Candidate revision changed while retaining inputs") source_repo = str(source) elif kind == "final" and selected: source_repo = selected.get("source_repo") else: source_repo = plan["working_candidate"] - initial = service_evidence.reference_snapshot(initial) - parent = service_evidence.reference_snapshot(parent) + initial = evaluator.service_reference_snapshot(initial) + parent = evaluator.service_reference_snapshot(parent) pending = { "attempt_id": attempt_id, "protocol_path": protocol_path, @@ -1937,8 +1910,8 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non "source_repo": source_repo, "round_number": number, "started_at": time.time(), - "hypothesis": getattr(args, "hypothesis", None) - or getattr(args, "reason", None) + "hypothesis": getattr(request, "hypothesis", None) + or getattr(request, "reason", None) or "Initial baseline", "retry_of": retry, "repair_reason": repair, @@ -1963,7 +1936,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non try: if admission: result = { - "assessment": service.assessment("INCONCLUSIVE", admission), + "assessment": evaluator.service_assessment("INCONCLUSIVE", admission), "cleanup_verified": True, "elapsed_seconds": 0, } @@ -1974,10 +1947,10 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non except (Exception, KeyboardInterrupt) as error: receipt = directory / "execution/execution.json" try: - result = service.read(receipt) + result = service_io.read(receipt) except (OSError, ValueError): result = {"cleanup_verified": None} - result["assessment"] = service.assessment( + result["assessment"] = evaluator.service_assessment( "INCONCLUSIVE", f"coordinator: {error}", performance=(result.get("assessment") or {}).get("performance"), 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..2cea73648 --- /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.records 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.executor import candidates + from inferrsi.harness.records import RunStore + from inferrsi.harness.records.artifact_primitives import digest + from inferrsi.harness.records.atomic_json import atomic_write_json + + 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..4c760afd7 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.records.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..80308b29d 100644 --- a/src/inferrsi/harness/search_adapter.py +++ b/src/inferrsi/harness/manager/search/search_adapter.py @@ -13,14 +13,13 @@ from pathlib import Path, PureWindowsPath from inferrsi.contracts.claim import Verdict +from inferrsi.harness.executor import candidates, 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 -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..8088731ef 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.records.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 98% rename from src/inferrsi/harness/search_continuations.py rename to src/inferrsi/harness/manager/search/search_continuations.py index 533a76686..244dc7c97 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.records.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..0f90fd4f5 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.records.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 97% rename from src/inferrsi/harness/work_control.py rename to src/inferrsi/harness/manager/search/work_control.py index 88f12c2eb..72dd9a424 100644 --- a/src/inferrsi/harness/work_control.py +++ b/src/inferrsi/harness/manager/search/work_control.py @@ -11,8 +11,7 @@ import time from contextlib import contextmanager -from .artifact_primitives import digest, file_lock -from .run_store import _transaction +from inferrsi.harness.records.artifact_primitives import digest, file_lock def _json(value): @@ -30,9 +29,9 @@ class WorkControl: def __init__(self, store): self.store = store - if store._read_only: + if store.read_only: return - with store._connection() as db, _transaction(db): + with store.work_control_connection(write=True) as db: db.execute( "CREATE TABLE IF NOT EXISTS work_campaigns " "(id TEXT PRIMARY KEY, revision INTEGER NOT NULL, body TEXT NOT NULL)" @@ -52,7 +51,7 @@ def __init__(self, store): @contextmanager def _transaction(self, campaign, revision=None): - with self.store._connection() as db, _transaction(db): + with self.store.work_control_connection(write=True) as db: row = db.execute( "SELECT revision, body FROM work_campaigns WHERE id=?", (campaign,) ).fetchone() @@ -91,12 +90,12 @@ def create(self, campaign, contract, state, *, cap_ms, final_reserve_ms, deadlin "final_result": None, "blocked": False, } - with self.store._connection() as db, _transaction(db): + with self.store.work_control_connection(write=True) as db: db.execute("INSERT INTO work_campaigns VALUES (?, 0, ?)", (campaign, _json(body))) return self.read(campaign) def read(self, campaign): - with self.store._connection() as db: + with self.store.work_control_connection() as db: row = db.execute( "SELECT revision, body FROM work_campaigns WHERE id=?", (campaign,) ).fetchone() @@ -110,11 +109,11 @@ def read(self, campaign): @contextmanager def final_owner(self, campaign): """Exclude live finalizers across processes using the same campaign database.""" - if self.store._read_only: + if self.store.read_only: raise ValueError("Recovering a pending final requires a writable RunStore") # SQLite's TEXT key can identify the same row for e.g. 1 and "1". # Derive both the lock and new operation IDs from the stored identity. - with self.store._connection() as db: + with self.store.work_control_connection() as db: row = db.execute("SELECT id FROM work_campaigns WHERE id=?", (campaign,)).fetchone() if row is None: raise ValueError("Unknown campaign") @@ -317,7 +316,7 @@ def settle(self, campaign, operation, receipt, *, actual_ms, cleanup_verified, t def bind_consumed_holdout(self, previous_scope, resolve_scope): """Resolve a consumed claim from archived inputs without reopening a final.""" - with self.store._connection() as db, _transaction(db): + with self.store.work_control_connection(write=True) as db: if not db.execute( "SELECT 1 FROM work_holdouts WHERE scope=?", (previous_scope,) ).fetchone(): diff --git a/src/inferrsi/harness/optimization_session.py b/src/inferrsi/harness/optimization_session.py deleted file mode 100644 index 5cab96bf7..000000000 --- a/src/inferrsi/harness/optimization_session.py +++ /dev/null @@ -1,440 +0,0 @@ -"""Assemble the shared Harness lifecycle for project and supplied task protocols. - -The CLI supplies a task directory only when starting a packaged task. Ordinary -projects and all subsequent operations use Harness and the retained inputs. -""" - -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 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 - - 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.atomic_json import atomic_write_json - from inferrsi.harness.candidates import identity, members, retain - from inferrsi.harness.project import inspect_step, steps - from inferrsi.harness.trials.external import execute_trial - - 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.artifact_primitives import sha256 - from inferrsi.harness.session_runtime import source_files - - root = Path(str(files("inferrsi"))) - return {name: sha256(root / name) for name in source_files(root)} - - -def session_command(args, *, ranking_policy_for, task_source: Path | None = None, - knowledge_reader=None, - retain_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 optimization - - root = args.session.resolve() - if args.session_action == "start": - import math - - from inferrsi.harness.artifact_primitives import sha256 - from inferrsi.harness.candidates import identity, retain - 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 - )) or not args.condition.strip() or not args.python.strip(): - raise ValueError("A positive round/time budget and condition label are required") - if root.exists(): - raise ValueError("Session directory must be new") - ranking_policy = ranking_policy_for(args.ranking_policy) - reserve = (args.final_reserve_seconds if args.final_reserve_seconds is not None - else args.evaluation_timeout_seconds) - if not math.isfinite(reserve) or not 0 < reserve < args.max_minutes * 60: - raise ValueError("Reserve time for final within the total budget") - evaluation_prefix = shlex.split(args.evaluation_prefix) - if external_knowledge and args.knowledge != "on": - raise ValueError("External knowledge requires --knowledge on") - if (external_knowledge and args.project_task - and args.evaluation_mode == "service_reuse"): - raise ValueError("External round knowledge requires a benchmark or AB/BA campaign") - allow_continuation = getattr(args, "allow_final_continuation", False) - if allow_continuation and ( - args.evaluation_mode != "service_reuse" or args.round_mode != "up_to" - ): - raise ValueError("Final continuation requires an up-to-budget service-reuse campaign") - if args.project_task: - names = ( - "metric_key", - "metric_unit", - "quality_key", - "scope", - "direction", - "min_improvement_pct", - "repetitions", - "warmups", - "measure_command", - "quality_command", - ) - if args.evaluation_mode == "service_reuse": - from inferrsi.harness.project_service import prepare as prepare_service - - if args.evaluation_config is None or any( - getattr(args, key) is not None for key in names - ): - raise ValueError( - "Service reuse requires --evaluation-config without AB/BA options" - ) - if args.decision != "point" or args.require_explanation: - # Both switches read AB/BA pairs and per-measurement breakdown/counters; - # this mode's optional profiling stage does not produce those inputs. - raise ValueError( - "--decision paired and --require-explanation apply to AB/BA campaigns" - ) - settings = prepare_service(root, args) - plan = { - "schema_version": 3, - "condition": args.condition, - "round_limit": args.rounds, - "max_seconds": args.max_minutes * 60, - "round_mode": args.round_mode, - "final_reserve_seconds": reserve, - "knowledge_allowed": args.knowledge == "on", - "ranking_policy": ranking_policy.configuration(), - "evaluation_timeout_seconds": args.evaluation_timeout_seconds, - "evaluation_prefix": evaluation_prefix, - "python": args.python, - **({"allow_final_continuation": True} if allow_continuation else {}), - **settings, - } - result = optimization.initialize(root, plan) - result["instructions"] = ( - "Run campaign baseline before candidate search. Record the measured " - "bottleneck with campaign diagnose before knowledge or rounds. " - "Use campaign round for each " - "committed candidate; investigate INCONCLUSIVE results before explicit retry. " - "Finish with campaign final; final does not collect a profile." - ) - return result - if args.evaluation_config is not None or any( - getattr(args, key) is None for key in names - ): - raise ValueError( - "AB/BA requires its existing metric, quality, command and sampling options" - ) - from inferrsi.harness.project import prepare as prepare_project - - repo = args.repo.resolve() - if not repo.is_dir() or root.is_relative_to(repo): - raise ValueError("Campaign output must be outside the editable project") - identity(repo, args.include) # Reject invalid inputs before preparation writes. - specification = {key: getattr(args, key) for key in ( - "metric_key", "metric_unit", "quality_key", "scope", "direction", - "min_improvement_pct", "repetitions", "warmups", "decision", - "require_explanation")} - specification.update(measure_command=shlex.split(args.measure_command), - quality_command=shlex.split(args.quality_command)) - settings = prepare_project(root / "frozen", args.protocol.resolve(), - args.instructions.resolve(), specification) - retain(repo, root / "frozen/baseline", args.include) - settings["frozen_files"].update({p.relative_to(root / "frozen").as_posix(): sha256(p) - for p in (root / "frozen/baseline").rglob("*") if p.is_file()}) - candidate = {"task": "project:" + repo.name, "task_source": "project", - "candidate_kind": "directory", "candidate_name": "candidate", - "candidate_includes": args.include, "baseline_path": "frozen/baseline", - "working_candidate": str(repo), - "selection": ( - # Paired mode ranks by the speedup its decision reads. - {"direction": "maximize", "initial_score": 1.0, - "metric": "paired_median_speedup"} - if args.decision == "paired" else - {"direction": args.direction, "initial_score": None, - "metric": args.metric_key})} - 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)) - (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", - "candidate_name": "candidate.py", "baseline_path": "frozen/baseline.py", - "working_candidate": "work/candidate.py", - "selection": {"direction": "maximize", "initial_score": 1.0, - "metric": "speedup"}} - plan = {"schema_version": 2, "condition": args.condition, - "round_limit": args.rounds, "max_seconds": args.max_minutes * 60, - "round_mode": args.round_mode, "final_reserve_seconds": reserve, - "knowledge_allowed": args.knowledge == "on", - "ranking_policy": ranking_policy.receipt(), - "evaluation_timeout_seconds": args.evaluation_timeout_seconds, - "evaluation_prefix": evaluation_prefix, "python": args.python, - "runtime_identity": _runtime_identity(), **candidate, **settings} - if external_knowledge: - plan["external_knowledge"] = external_knowledge - plan["external_knowledge_project"] = external_project - if report_metadata is not None: - plan["report_metadata"] = report_metadata - result = optimization.initialize(root, plan) - operation = "campaign" if args.project_task else "benchmarks session" - result["instructions"] = ( - f"Read the frozen TASK.md. Record the measured bottleneck with {operation} " - f"diagnose first. Use {operation} knowledge when needed and permitted. " - "Edit the returned working_candidate within its declared input scope. " - f"Before each {operation} round, declare its hypothesis. " - "Record other options you considered with --alternative and why you chose the " - "submitted candidate with --selection-reason. " - "Read the observation, keep failures and use feedback for the next change. " - f"Follow the frozen round policy, then run {operation} final to retest independently. " - "Report summary.json and its curve. Import actual usage exports when available." - ) - if external_knowledge: - result["instructions"] += ( - f" Read external hits with {operation} knowledge-read. Cite the delivered " - "item or read receipt with --knowledge-ref when submitting a candidate." - ) - return result - - plan = json.loads((root / "plan.json").read_text(encoding="utf-8")) - manifest = json.loads((root / "campaign.json").read_text(encoding="utf-8")) - if ( - plan.get("evaluation_mode") == "service_reuse" - or plan.get("schema_version") == 3 - or manifest.get("evaluation_mode") == "service_reuse" - ): - if getattr(args, "confirm_domain_empty", False): - raise ValueError("Service-reuse cleanup requires --cleanup-receipt") - if args.session_action == "profile": - try: - return optimization.service_command( - root, args, ranking_policy_for=ranking_policy_for, - ) - except (ValueError, OSError) as exc: - message = "Campaign lock is busy" if isinstance(exc, BlockingIOError) else str(exc) - return { - "exit_code": 2, - "round": args.round, - "profiling_error": { - "status": "failed", "stage": "campaign", "message": message, - }, - } - if args.session_action == "knowledge-read": - raise ValueError("External round knowledge requires a benchmark or AB/BA campaign") - if getattr(args, "mechanism_file", None) is not None: - raise ValueError("Mechanism checks apply to AB/BA project campaign rounds only") - if getattr(args, "alternative", None) is not None or getattr( - args, "selection_reason", None) is not None: - raise ValueError("Round decision declarations require a benchmark or AB/BA campaign") - return optimization.service_command(root, args, knowledge_reader=knowledge_reader, - ranking_policy_for=ranking_policy_for) - if ( - args.session_action in ("baseline", "refresh-references", "resume", "profile") - or getattr(args, "retry_of", None) - or getattr(args, "repair_reason", None) - or getattr(args, "cleanup_receipt", None) - or getattr(args, "repair_protocol", None) - or getattr(args, "continue_after_final", None) is not None - or getattr(args, "continuation_reason", None) is not None - ): - raise ValueError("Service lifecycle/retry operations require a service-reuse campaign") - if plan["runtime_identity"] != _runtime_identity(): - raise ValueError("Optimization runtime changed, use its frozen runtime to resume") - ranking_policy = optimization.resolve_frozen_ranking( - plan, ranking_policy_for, read_only=args.session_action == "status", - ) - if args.session_action == "status": - return optimization.status(root) - if args.session_action == "diagnose": - return optimization.record_diagnosis(root, args.bottleneck, args.evidence) - if args.session_action == "knowledge": - if knowledge_reader is None or retain_context is None: - raise ValueError("A knowledge reader and capture callback are required") - return optimization.capture_context( - root, - knowledge_reader, - retain_context=retain_context, - ranking_policy=ranking_policy, - external_provider=external_provider, - external_provider_for=external_provider_for, - query="", - relevance=args.query, - relevance_method=args.relevance_method, - scenario=getattr(args, "scenario", None), - context_bytes=args.context_bytes, - limit=args.limit, - ) - if args.session_action == "knowledge-read": - return optimization.read_external_context( - root, external_provider, search_ref=args.search_ref, locator=args.locator, - page=args.page, external_provider_for=external_provider_for, - ) - if args.session_action == "recover": - return optimization.recover( - root, _session_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 - - mechanism = validate_mechanism( - json.loads(Path(args.mechanism_file).read_text(encoding="utf-8"))) - settings = plan["evaluation_settings"] - needed = min_pairs(1 - (1 - CONFIDENCE) / len(mechanism["expect"])) - if settings.get("require_explanation") and needed > settings["repetitions"]: - # Reject before execution so an uncheckable declaration spends no round. - raise ValueError( - f"{len(mechanism['expect'])} expectations need {needed} repetitions under " - f"--require-explanation; the campaign froze {settings['repetitions']}. " - "Declare fewer expectations") - 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, - reason=getattr(args, "reason", None), - strategy=getattr(args, "strategy", None), - alternatives=getattr(args, "alternative", None), - selection_reason=getattr(args, "selection_reason", 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.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/project_service.py b/src/inferrsi/harness/project_service.py deleted file mode 100644 index c1bcde2d3..000000000 --- a/src/inferrsi/harness/project_service.py +++ /dev/null @@ -1,1123 +0,0 @@ -"""Project-owned service protocols and their retained, multi-objective evidence. - -No file/content fingerprints are calculated here. Revision, configuration and -actual service receipts establish the explicitly declared execution binding. -""" - -import json -import math -import os -import re -import subprocess -import time -import uuid -from pathlib import Path -from statistics import mean, median - -from .atomic_json import atomic_write_json -from .candidates import members, retain - -INLINE_PROFILE_REASONS = ("fixed_checks_satisfied", "performance_gate_not_met") - - -def safe_path(root, relative): - if not isinstance(relative, str) or not relative or "\\" in relative or ":" in relative: - raise ValueError("Expected a campaign-relative path") - part = Path(relative) - if part.is_absolute() or ".." in part.parts: - raise ValueError("Path must stay inside the campaign") - target = root / part - if any( - p.is_symlink() for p in (target, *target.parents) if p.is_relative_to(root) - ) or not target.resolve().is_relative_to(root.resolve()): - raise ValueError("Symbolic or escaping campaign path") - return target - - -def no_fingerprints(value): - if isinstance(value, dict): - for key, item in value.items(): - if not isinstance(key, str) or any( - name in key.lower() for name in ("sha256", "fingerprint", "digest") - ): - raise ValueError("File fingerprints are not part of the service-reuse protocol") - no_fingerprints(item) - elif isinstance(value, list): - for item in value: - no_fingerprints(item) - elif isinstance(value, float) and not math.isfinite(value): - raise ValueError("Nonfinite JSON value") - - -JSON_SIZE_LIMIT = 4 * 1024 * 1024 -# Round and reference records repeat this metadata. The collector's raw receipt stays on disk. -PROFILE_METADATA_LIMIT = 32 * 1024 - - -def read(path): - if path.is_symlink() or not path.is_file() or path.stat().st_size > JSON_SIZE_LIMIT: - raise ValueError(f"Missing, symbolic or oversized JSON: {path.name}") - try: - value = json.loads(path.read_text(encoding="utf-8")) - if not isinstance(value, dict): - raise ValueError("Result must be a JSON object") - no_fingerprints(value) - except RecursionError as error: - raise ValueError(f"JSON nesting exceeds the supported depth: {path.name}") from error - return value - - -def number(value): - try: - return type(value) in (int, float) and math.isfinite(value) - except OverflowError: - return False - - -def positive(value): - return number(value) and value > 0 - - -def validate_conditions(conditions): - if not isinstance(conditions, dict): - raise ValueError("Explicit test conditions required") - if not isinstance(conditions.get("id"), str) or not conditions["id"].strip(): - raise ValueError("Conditions require a nonempty string ID") - for key in ("id", "workload", "model", "precision", "topology", "runtime", "timing_scope"): - if not conditions.get(key): - raise ValueError(f"conditions.{key} is required") - if not isinstance(conditions.get("effective_config"), dict): - raise ValueError("conditions.effective_config must be an object") - no_fingerprints(conditions) - - -def validate(settings): - no_fingerprints(settings) - for name in ("conditions", "commands", "sampling", "quality", "stagnation"): - if not isinstance(settings.get(name), dict): - raise ValueError(f"{name} must be an explicit object") - if type(settings.get("schema_version")) is not int or settings["schema_version"] != 1: - raise ValueError("Service evaluation schema_version must be 1") - if not isinstance(settings.get("protocol_id"), str) or not settings["protocol_id"].strip(): - raise ValueError("Explicit protocol_id required") - validate_conditions(settings.get("conditions")) - commands = settings.get("commands", {}) - stages = ("precheck", "service", "ready", "warmup", "measure", "quality", "stop") - if "profile" in commands: - stages += ("profile",) - for name in stages: - command = commands.get(name) - if ( - not isinstance(command, list) - or not command - or any(not isinstance(arg, str) or not arg for arg in command) - ): - raise ValueError(f"commands.{name} must be explicit argv") - if not any("{protocol}" in arg for arg in command): - raise ValueError(f"commands.{name} must use a retained protocol script") - if name != "service" and not any("{result}" in arg for arg in command): - raise ValueError(f"commands.{name} must write the supplied result") - sampling = settings.get("sampling", {}) - if not positive(sampling.get("stage_timeout_seconds")): - raise ValueError("Positive stage timeout required") - if "profile_timeout_seconds" in sampling and not positive(sampling["profile_timeout_seconds"]): - raise ValueError("Positive profiling timeout required") - for role in ("baseline", "candidate", "final"): - config = sampling.get(role, {}) - if not isinstance(config, dict): - raise ValueError("Sampling policies must be objects") - if type(config.get("repetitions")) is not int or config["repetitions"] < 1: - raise ValueError(f"Positive {role} repetitions required") - if type(config.get("warmups")) is not int or config["warmups"] < 0: - raise ValueError(f"Nonnegative {role} warmups required") - if config["warmups"] == 0 and not config.get("warmup_reason"): - raise ValueError("Explain why no warmup is necessary") - scenarios = settings.get("scenarios") - if not isinstance(scenarios, list) or not scenarios: - raise ValueError("Declare scenarios") - ids = [] - for item in scenarios: - if not isinstance(item, dict) or not isinstance(item.get("id"), str): - raise ValueError("Scenario must declare a string ID") - if ( - not item.get("id") - or not item.get("workload") - or (type(item.get("requests")) is not int or item["requests"] < 1) - or type(item.get("required_successes")) is not int - or not (0 < item["required_successes"] <= item["requests"]) - ): - raise ValueError("Declare scenario workload, request and success counts") - ids.append(item["id"]) - if len(set(ids)) != len(ids): - raise ValueError("Duplicate scenario") - objectives = settings.get("objectives") - if not isinstance(objectives, list) or not objectives: - raise ValueError("Declare objectives") - names = [] - for obj in objectives: - if not isinstance(obj, dict) or not isinstance(obj.get("domain"), dict): - raise ValueError("Objective and domain must be objects") - for key in ("id", "key", "unit"): - if not isinstance(obj.get(key), str) or not obj[key].strip(): - raise ValueError(f"Objective {key} required") - names.append(obj["id"]) - if obj.get("scenario") not in ids or obj.get("direction") not in ("minimize", "maximize"): - raise ValueError("Invalid objective scenario or direction") - if ( - obj.get("aggregate") not in ("median", "mean") - or obj.get("threshold_type") not in ("relative_percent", "absolute", "percentage_point") - or type(obj.get("gain")) is not bool - ): - raise ValueError("Declare aggregation, threshold type and gain participation") - domain = obj.get("domain", {}) - if ( - not number(domain.get("min")) - or not number(domain.get("max")) - or (domain["min"] > domain["max"]) - ): - raise ValueError("Finite ordered objective domain required") - if obj["threshold_type"] == "percentage_point" and obj["unit"] != "%": - raise ValueError("Percentage-point objectives use percent values and unit %") - if obj["threshold_type"] == "relative_percent" and domain["min"] < 0: - raise ValueError("Use absolute thresholds for negative-valued metrics") - for key in ("gain_threshold", "parent_regression_limit", "cumulative_regression_limit"): - if not number(obj.get(key)) or obj[key] < 0: - raise ValueError(f"Nonnegative finite {key} required") - ranking = settings.get("ranking") - if len(set(names)) != len(names) or not any(obj["gain"] for obj in objectives): - raise ValueError("Unique objectives and at least one gain objective required") - if ( - not isinstance(ranking, list) - or not ranking - or any(not isinstance(name, str) for name in ranking) - or len(set(ranking)) != len(ranking) - or any(name not in names for name in ranking) - ): - raise ValueError("Declare an ordered, unique ranking of known objectives") - quality = settings.get("quality", {}) - if ( - quality.get("mode") not in ("absolute", "baseline_comparison") - or quality.get("direction") not in ("minimize", "maximize") - or not all( - isinstance(quality.get(key), str) and quality[key].strip() - for key in ("key", "dataset", "scorer") - ) - ): - raise ValueError("Declare quality mode, direction, dataset, scorer and key") - gate = "threshold" if quality["mode"] == "absolute" else "tolerance" - if type(quality.get("samples")) is not int or quality["samples"] < 1: - raise ValueError("Declare the required quality sample count") - if not number(quality.get(gate)) or (gate == "tolerance" and quality[gate] < 0): - raise ValueError("Explicit quality gate required") - reminder = settings.get("stagnation", {}) - if reminder != {"disabled": True} and ( - type(reminder.get("rounds")) is not int - or reminder["rounds"] < 1 - or reminder.get("action") not in ("advisory", "pause") - ): - raise ValueError("Explicit stagnation threshold/action or disabled required") - screen = settings.get("screening") - if screen is not None: - if not isinstance(screen, dict) or ( - not isinstance(screen.get("command"), list) - or not screen["command"] - or any(not isinstance(arg, str) or not arg for arg in screen["command"]) - or not positive(screen.get("estimated_gain")) - ): - raise ValueError("Screening command and positive estimated_gain required") - if not any("{result}" in arg for arg in screen["command"]) or not any( - "{protocol}" in arg for arg in screen["command"] - ): - raise ValueError("Screening must use retained protocol and result") - - -def value(document, key): - for part in key.split("."): - if not isinstance(document, dict) or part not in document: - raise ValueError(f"Missing metric: {key}") - document = document[part] - return document - - -def aggregate(settings, documents, role): - if len(documents) != settings["sampling"][role]["repetitions"]: - raise ValueError("Incomplete performance repetitions") - samples = {obj["id"]: [] for obj in settings["objectives"]} - for document in documents: - for scenario in settings["scenarios"]: - result = document.get("scenarios", {}).get(scenario["id"], {}) - if ( - result.get("workload") != scenario["workload"] - or type(result.get("requests")) is not int - or result["requests"] != scenario["requests"] - or type(result.get("successes")) is not int - or not scenario["required_successes"] <= result["successes"] <= (result["requests"]) - ): - raise ValueError("Incomplete or incompatible scenario requests") - for obj in settings["objectives"]: - result = document["scenarios"][obj["scenario"]] - metric = value(result, obj["key"]) - if ( - result.get("units", {}).get(obj["id"]) != obj["unit"] - or not number(metric) - or not (obj["domain"]["min"] <= metric <= obj["domain"]["max"]) - ): - raise ValueError(f"Invalid metric domain or unit: {obj['id']}") - samples[obj["id"]].append(metric) - aggregates = { - obj["id"]: (median if obj["aggregate"] == "median" else mean)(samples[obj["id"]]) - for obj in settings["objectives"] - } - if not all(number(v) for v in aggregates.values()): - raise ValueError("Nonfinite aggregate") - return {"values": aggregates, "samples": samples} - - -def change(obj, candidate, reference): - sign = 1 if obj["direction"] == "maximize" else -1 - delta = sign * (candidate - reference) - if obj["threshold_type"] == "relative_percent": - if reference == 0: - if candidate != 0: - raise ValueError(f"Undefined relative change from zero: {obj['id']}") - return 0 - delta = 100 * delta / abs(reference) - if not number(delta): - raise ValueError("Nonfinite derived change") - return delta - - -def performance(settings, measured, parent, initial, *, screening=False): - metrics, limits, gain, actual_gain = {}, True, False, False - for obj in settings["objectives"]: - name = obj["id"] - p = change(obj, measured["values"][name], parent["values"][name]) - b = change(obj, measured["values"][name], initial["values"][name]) - bounded = p >= -obj["parent_regression_limit"] and b >= -obj["cumulative_regression_limit"] - improved = obj["gain"] and p > 0 - metrics[name] = { - "value": measured["values"][name], - "unit": obj["unit"], - "parent_change": p, - "initial_change": b, - "limits_passed": bounded, - "gain_passed": improved and p >= obj["gain_threshold"], - "thresholds": { - key: obj[key] - for key in ( - "threshold_type", - "gain_threshold", - "parent_regression_limit", - "cumulative_regression_limit", - ) - }, - } - limits &= bounded - actual_gain |= improved - gain |= metrics[name]["gain_passed"] - passed = limits and (actual_gain if screening else gain) - return { - "passed": passed, - "metrics": metrics, - "reason": "performance_gate_satisfied" if passed else "performance_gate_not_met", - } - - -def better(settings, left, right): - by_id = {obj["id"]: obj for obj in settings["objectives"]} - for name in settings["ranking"]: - if left[name] != right[name]: - return ( - left[name] < right[name] - if by_id[name]["direction"] == "minimize" - else left[name] > right[name] - ) - return False - - -def quality_score(settings, document): - config = settings["quality"] - if document.get("dataset") != config["dataset"] or document.get("scorer") != config["scorer"]: - raise ValueError("Incompatible quality dataset/scorer") - score = value(document, config["key"]) - if ( - not number(score) - or type(document.get("samples")) is not int - or document["samples"] != config["samples"] - ): - raise ValueError("Missing numerical quality evidence") - return score - - -def quality_passed(settings, score, reference=None): - config = settings["quality"] - sign = 1 if config["direction"] == "maximize" else -1 - if config["mode"] == "absolute": - return sign * (score - config["threshold"]) >= 0 - if reference is None or not number(reference): - raise ValueError("Missing compatible baseline quality reference") - return sign * (score - reference) >= -config["tolerance"] - - -def revision(source, includes): - """Use an existing commit, never a file fingerprint, for retained project inputs.""" - - def git(*args): - return subprocess.check_output(["git", "-C", str(source), *args], text=True).strip() - - if Path(git("rev-parse", "--show-toplevel")).resolve() != source.resolve(): - raise ValueError("Use the Git checkout root as the service-reuse project") - commit = git("rev-parse", "HEAD") - if not re.fullmatch(r"[a-f0-9]{40,64}", commit): - raise ValueError("Candidate requires an existing Git commit") - selected = members(source, includes) - tracked = set(git("ls-files", "-z").split("\0")) - # Deleted tracked files are absent from members but still belong to the inputs. - if any(name not in tracked for name in selected) or git( - "status", "--porcelain", "--untracked-files=no", "--", *(includes or ["."]) - ): - raise ValueError("Commit declared candidate inputs before service-reuse evaluation") - return commit - - -def retain_revision(source, destination, includes, commit, *, deadline=None): - if not isinstance(commit, str) or not re.fullmatch(r"[a-f0-9]{40,64}", commit): - raise ValueError("Candidate requires an existing Git commit") - - def git(*args): - timeout = None if deadline is None else deadline - time.monotonic() - if timeout is not None and timeout <= 0: - raise TimeoutError("Profiling timeout while restoring the recorded revision") - try: - return subprocess.check_output(["git", "-C", str(source), *args], timeout=timeout) - except subprocess.TimeoutExpired as error: - raise TimeoutError("Profiling timeout while restoring the recorded revision") from error - - entries = {} - for name in includes or ["."]: - relative = Path(name) - if relative.is_absolute() or ".." in relative.parts: - raise ValueError("Candidate includes must be relative paths inside the project") - listing = git( - "ls-tree", "-rz", "--full-tree", "--format=%(objectmode) %(objecttype)%x09%(path)", - commit, "--", relative.as_posix(), - ) - if not listing: - raise ValueError("Declared candidate files are missing from the retained commit") - for entry in listing.rstrip(b"\0").split(b"\0"): - metadata, path = entry.split(b"\t", 1) - mode, kind = metadata.split() - if kind != b"blob" or mode not in (b"100644", b"100755"): - raise ValueError("Candidate tree contains symbolic or special files") - entries[os.fsdecode(path)] = int(mode, 8) & 0o555 - destination.mkdir() - for name, mode in entries.items(): - target = safe_path(destination, name) - target.parent.mkdir(parents=True, exist_ok=True) - # Read raw tree content; archive export attributes can omit or rewrite inputs. - target.write_bytes(git("cat-file", "blob", f"{commit}:{name}")) - target.chmod(mode) - - -def prepare(root, args): - from inferrsi import __version__ - - settings = read(args.evaluation_config) - validate(settings) - source, protocol = args.repo.resolve(), args.protocol.resolve() - if args.repo.is_symlink() or args.protocol.is_symlink(): - raise ValueError("Project and protocol roots cannot be symbolic") - if root.exists() or root.is_relative_to(source) or root.is_relative_to(protocol): - raise ValueError("Use a new campaign directory outside project/protocol") - commit = revision(source, args.include) - members(protocol) - if not args.instructions.is_file() or args.instructions.is_symlink(): - raise ValueError("Regular task instructions required") - (root / "frozen").mkdir(parents=True) - retain_revision(source, root / "frozen/baseline", args.include, commit) - if revision(source, args.include) != commit: - raise ValueError("Candidate revision changed while retaining inputs") - retain(protocol, root / "frozen/protocol", fingerprint=False) - (root / "frozen/TASK.md").write_bytes(args.instructions.read_bytes()) - atomic_write_json(root / "frozen/evaluation.json", settings) - for path in (root / "frozen").rglob("*"): - if path.is_file(): - path.chmod(path.stat().st_mode & ~0o222) - return { - "runtime_version": __version__, - "evaluation_settings": settings, - "baseline_revision": commit, - "baseline_path": "frozen/baseline", - "candidate_name": "candidate", - "candidate_kind": "directory", - "candidate_includes": args.include, - "working_candidate": str(source), - "task_source": "project", - "task": "project:" + source.name, - "evaluation_mode": "service_reuse", - "selection": {"ranking": settings["ranking"]}, - } - - -def assessment(verdict, reason, **fields): - return { - "status": "infrastructure_failure" if verdict == "INCONCLUSIVE" else "completed", - "verdict": verdict, - "eligible": verdict == "PASS", - "reason": reason, - **fields, - } - - -def ready_for_service(ready, *, revision, pid): - return ( - ready.get("ready") is True - and ready.get("ownership") == "local_process_domain" - and ready.get("owner_pid") == pid - and ready.get("loaded_revision") == revision - ) - - -def validated_profile(root, directory, attempt_id, conditions, binding, step, *, captured=None): - """Reconstruct a usable profile only from the capture's own bound on-disk evidence.""" - directory = safe_path(root, directory.relative_to(root).as_posix()) - result = safe_path(directory, "execution/profile/result.json") - if ( - not isinstance(binding, dict) - or binding.get("attempt_id") != attempt_id - or binding.get("conditions") != conditions - or binding.get("effective_config") != conditions["effective_config"] - or not all(binding.get(key) for key in ("revision", "service_id", "run_id")) - or read(safe_path(directory, "request.json")) != binding - or read(safe_path(directory, "effective-config.json")) != conditions["effective_config"] - ): - raise ValueError("profile: incompatible capture binding") - trace = read(result) - if ( - trace.get("binding") != binding - or trace.get("status") != "completed" - or trace.get("validated") is not True - or (captured is not None and captured != trace) - or not isinstance(step, dict) - or step.get("id") != "profile" - or step.get("status") != "completed" - or ("result" in step and step["result"] != trace) - ): - raise ValueError("profile: missing or incompatible validated receipt") - interval = ( - step.get("started_at"), trace.get("capture_started_at"), - trace.get("capture_ended_at"), step.get("ended_at"), - ) - if not all(number(t) for t in interval) or not ( - interval[0] <= interval[1] <= interval[2] <= interval[3] - ): - raise ValueError("profile: missing or incompatible capture interval") - artifacts = trace.get("artifacts") - if not isinstance(artifacts, list) or not artifacts: - raise ValueError("profile: missing artifacts") - legacy = "result" in step - locations = [] - metadata = {"artifacts": locations} - if legacy: - # Previously written profiles kept the full receipt in both the step and the profile. - metadata["receipt"] = trace - else: - metadata.update(capture_started_at=interval[1], capture_ended_at=interval[2]) - metadata_bytes = len(json.dumps(metadata, ensure_ascii=False).encode("utf-8")) - for relative in artifacts: - path = safe_path(directory, relative) - location = path.relative_to(root).as_posix() - if not legacy: - # Account for the encoded path and the JSON list separator between locations. - metadata_bytes += len(json.dumps(location, ensure_ascii=False).encode("utf-8")) - if locations: - metadata_bytes += 2 - if metadata_bytes > PROFILE_METADATA_LIMIT: - raise ValueError(f"profile: metadata exceeds {PROFILE_METADATA_LIMIT} bytes") - if not path.is_file(): - raise ValueError("profile: missing or empty artifact") - with path.open("rb") as artifact: - if not artifact.read(1): - raise ValueError("profile: missing or empty artifact") - locations.append(location) - return { - "attempt_id": attempt_id, - "conditions": conditions, - "binding": binding, - "result": result.relative_to(root).as_posix(), - **metadata, - } - - -def attempt_profile(root, attempt): - """Return the retained profile, or None if its evidence is missing or disagrees.""" - execution = attempt["execution"] - profile = execution.get("profile") - if not isinstance(profile, dict): - return None - try: - binding = execution["binding"] - if binding["revision"] != attempt["revision"]: - return None - step = next((s for s in execution["steps"] if s.get("id") == "profile"), None) - validated = validated_profile( - root, - safe_path(root, attempt["path"]), - attempt["attempt_id"], - attempt["conditions"], - binding, - step, - ) - return validated if validated == profile else None - except (OSError, ValueError, KeyError, TypeError, AttributeError, RecursionError): - return None - - -def _error_excerpt(message): - return message if len(message) <= 1024 else message[:1021] + "..." - - -def capture_diagnostic(root, directory, stage, status, message, *, process_failed=False): - if not isinstance(stage, str) or not re.fullmatch(r"[a-z][a-z0-9_-]*", stage): - stage = "startup" - diagnostic = {"stage": stage, "status": status, "message": _error_excerpt(message)} - stage_dir = directory / ("service" if stage == "service" else "execution/" + stage) - try: - receipts = ("execution.json", "result.json") if process_failed else ( - "result.json", "execution.json" - ) - for name in receipts: - receipt = safe_path(root, (stage_dir / name).relative_to(root).as_posix()) - if receipt.is_file(): - diagnostic["details_path"] = receipt.relative_to(root).as_posix() - break - if diagnostic["message"] != message: - # Unexpected coordinator exceptions can lack a stage receipt with the original detail. - relative = (directory / f"{stage}-error.txt").relative_to(root).as_posix() - safe_path(root, relative).write_text(message, encoding="utf-8", errors="replace") - diagnostic["details_path"] = relative - log = safe_path(root, (stage_dir / "stderr.log").relative_to(root).as_posix()) - if log.is_file(): - diagnostic["log"] = log.relative_to(root).as_posix() - with log.open("rb") as stream: - stream.seek(max(0, log.stat().st_size - 1024)) - detail = stream.read(1024).decode("utf-8", errors="replace").strip() - if detail: - diagnostic["message"] += f"\n{detail}" - except (OSError, ValueError): - pass # The stage error remains available even if its log cannot be read. - return diagnostic - - -def proven_capture_elapsed(root, pending, execution): - """Recover monotonic capture progress without charging a crash-to-recovery interval.""" - capture = execution.get("capture") - if not isinstance(capture, dict) or capture.get("id") != pending.get("attempt_id"): - return 0.0 - elapsed = capture.get("elapsed_seconds") - if not number(elapsed) or elapsed < 0: - return 0.0 - steps = execution.get("steps") - if number(capture.get("ended_at")) or not isinstance(steps, list) or not steps: - return elapsed - step = steps[-1] - if not isinstance(step, dict): - return elapsed - try: - offset = step["capture_offset_seconds"] - stage = step["id"] - if ( - step.get("status") != "running" - or not number(offset) - or offset != elapsed - or capture["id"] != execution["binding"]["attempt_id"] - or not re.fullmatch(r"precheck|ready|warmup-[0-9]+|profile|stop", stage) - or (pending["kind"] != "profile" and stage != "profile") - ): - return elapsed - directory = safe_path(root, pending["path"]) - if read(safe_path(directory, "request.json")) != execution["binding"]: - return elapsed - stage_dir = safe_path(directory, f"execution/{stage}") - receipt = read(safe_path(stage_dir, "execution.json")) - duration = receipt["elapsed_seconds"] - if ( - receipt.get("status") not in ("completed", "failed", "cancelled", "timeout", "error") - or receipt.get("cwd") != str(directory / "workspace") - or receipt.get("result_path") != str(stage_dir / "result.json") - or type(receipt.get("pid")) is not int - or receipt["pid"] <= 0 - or not number(duration) - or duration < 0 - or not number(offset + duration) - ): - return elapsed - return offset + duration - except (KeyError, TypeError, OSError, ValueError): - return elapsed - - -def execute(root, directory, plan, pending, deadline): - """One retained attempt, one owned service, ordered client stages, no silent retry.""" - from .local_process import supervised_service - from .optimization_session import runtime_environment - from .trials.external import execute_trial - - settings = plan["evaluation_settings"] - conditions = pending["conditions"] - config = conditions["effective_config"] - source = directory / "candidate" - workspace = directory / "workspace" - expected = { - "attempt_id": pending["attempt_id"], - "service_id": uuid.uuid4().hex, - "run_id": uuid.uuid4().hex, - "revision": pending["revision"], - "conditions": conditions, - "effective_config": config, - } - atomic_write_json(directory / "request.json", expected) - atomic_write_json(directory / "effective-config.json", config) - receipt = directory / "service.json" - values = { - "python": plan["python"], - "candidate": str(workspace), - "baseline": str(root / plan["baseline_path"]), - "service_receipt": str(receipt), - "effective_config": str(directory / "effective-config.json"), - "attempt_dir": str(directory), - } - environment = runtime_environment() - environment.update( - INFERRSI_ATTEMPT_REQUEST=str(directory / "request.json"), PYTHONDONTWRITEBYTECODE="1" - ) - environment["PYTHONPATH"] = str(workspace) + os.pathsep + environment["PYTHONPATH"] - end = time.monotonic() + min(plan["evaluation_timeout_seconds"], max(0, deadline - time.time())) - record = { - "status": "running", - "steps": [], - "cleanup_verified": None, - "binding": expected, - "assessment": None, - "cleanup_timeout_seconds": settings["sampling"]["stage_timeout_seconds"], - "cleanup_budget_scope": "separate_from_evaluation", - } - output = directory / "execution" - output.mkdir() - started, process, owner = time.monotonic(), None, None - standalone = pending.get("kind") == "profile" - sampling = settings["sampling"] - profile_timeout = sampling.get("profile_timeout_seconds", sampling["stage_timeout_seconds"]) - capture_started = None - - def save(): - atomic_write_json(output / "execution.json", record) - - def begin_capture(): - nonlocal capture_started - capture_started = time.monotonic() - record["capture"] = { - "id": pending["attempt_id"], "started_at": time.time(), "elapsed_seconds": 0.0, - } - save() - - def finish_capture(): - nonlocal capture_started - record["capture"].update( - elapsed_seconds=time.monotonic() - capture_started, ended_at=time.time() - ) - capture_started = None - save() - - def command(argv): - for key, val in values.items(): - argv = [arg.replace("{" + key + "}", val) for arg in argv] - return argv - - def binding(document): - if document.get("binding") != expected: - raise ValueError("Service/revision/configuration binding mismatch") - - def stage(name, *, bound=True, argv=None): - definition = { - "id": name, - "status": "running", - "started_at": time.time(), - "execution_status": "not_started", - } - if capture_started is not None: - offset = time.monotonic() - capture_started - definition["capture_offset_seconds"] = offset - record["capture"]["elapsed_seconds"] = offset - record["steps"].append(definition) - save() - if bound and (process is None or process.poll() is not None): - raise ValueError(f"Service unavailable before {name}") - stage_end = time.monotonic() + sampling["stage_timeout_seconds"] - if name != "stop": - if capture_started is None: - stage_end = min(end, stage_end) - else: - capture_end = capture_started + profile_timeout - stage_end = capture_end if name == "profile" else min(stage_end, capture_end) - executed = execute_trial( - tuple(command(argv or settings["commands"][name.split("-")[0]])), - workspace, - output / name, - stage_end, - None, - environment=environment, - ) - definition.update(executed, execution_status=executed["status"], ended_at=time.time()) - if isinstance(definition.get("error"), str): - definition["error"] = _error_excerpt(definition["error"]) - if capture_started is not None: - record["capture"]["elapsed_seconds"] = time.monotonic() - capture_started - save() - if executed["status"] != "completed": - detail = definition.get("error") or f"exit {executed.get('returncode')}" - if executed["status"] == "cancelled": - raise KeyboardInterrupt(_error_excerpt(f"{name}: {detail}")) - raise ValueError(_error_excerpt(f"{name}: {executed['status']}: {detail}")) - document = read(output / name / "result.json") - if bound: - binding(document) - if process.poll() is not None: - raise ValueError(f"Service exited during {name}") - candidate_failure = document.get("status") == "candidate_failure" and name.startswith( - ("precheck", "quality") - ) - if not candidate_failure and document.get("status") != "completed": - detail = document.get("error") or document.get("message") - if not detail: - detail = f"expected completed stage evidence, got {document.get('status')!r}" - raise ValueError(_error_excerpt(f"{name}: {detail}")) - if name != "profile" and not standalone: - definition["result"] = document - save() - return document - - def skipped(names, reason): - record["steps"].extend( - {"id": name, "status": "skipped", "reason": reason} for name in names - ) - save() - - measured, gate, score, profile, quality_ok = None, None, None, None, None - - def evaluate(role): - nonlocal measured, gate, score, quality_ok - parent, initial = pending.get("parent"), pending.get("initial") - screen = settings.get("screening") - if role == "candidate" and screen: - try: - docs = [ - stage(f"screening-{i + 1:03d}", argv=screen["command"]) - for i in range(settings["sampling"][role]["repetitions"]) - ] - preview = aggregate(settings, docs, role) - record["screening"] = performance( - settings, - preview, - parent["measurements"], - initial["measurements"], - screening=True, - ) - record["screening"].update( - measurements=preview, estimated_gain=screen["estimated_gain"] - ) - except Exception as error: - # A malformed screening receipt is diagnostic; formal measurements follow. - record["screening"] = {"error": str(error)} - record["steps"][-1].update(status="failed", reason=str(error)) - save() - docs = [] - first_failure = None - for i in range(sampling[role]["repetitions"]): - name = f"measure-{i + 1:03d}" - try: - docs.append(stage(name)) - except (ValueError, TypeError, KeyError, OSError) as error: - if first_failure is None: - first_failure = (name, error) - step = record["steps"][-1] - if step["status"] in ("running", "completed"): - step["status"] = "failed" - step["reason"] = str(error) - save() - if process.poll() is not None or time.monotonic() >= end: - break - if first_failure is not None: - record["failed_stage"], error = first_failure - raise error - measured = aggregate(settings, docs, role) - gate = ( - performance( - settings, measured, parent["measurements"], initial["measurements"] - ) - if parent is not None - else {"passed": True, "metrics": {}} - ) - if not gate["passed"]: - skipped(("quality",), "performance_gate_not_met") - if role != "candidate": - skipped(("profile",), "not_required") - record["assessment"] = assessment( - "FAIL", "performance_gate_not_met", performance=gate - ) - elif pending.get("reference_kind") == "parent": - skipped(("quality", "profile"), "performance_reference_only") - record["assessment"] = assessment( - "PASS", "performance_reference_refreshed", performance=gate, - eligible=False, - ) - else: - reference_path = settings["quality"].get("reference_path") - if role == "baseline" and reference_path: - reference_step = { - "id": "quality", - "status": "running", - "source": "retained_baseline_reference", - "path": reference_path, - "started_at": time.time(), - } - record["steps"].append(reference_step) - save() - quality = read( - safe_path( - safe_path( - root, pending.get("protocol_path", "frozen/protocol") - ), - reference_path, - ) - ) - if ( - quality.get("revision") != pending["revision"] - or quality.get("conditions") != conditions - or not quality.get("service_id") - or not quality.get("run_id") - ): - raise ValueError( - "quality: missing/stale/incompatible baseline reference" - ) - quality_score(settings, quality) - reference_step.update( - status="completed", ended_at=time.time(), result=quality - ) - save() - else: - quality = stage("quality") - if quality.get("status") == "candidate_failure": - quality_ok = False - else: - score = quality_score(settings, quality) - quality_ok = quality_passed( - settings, - score, - (initial.get("quality_score") if initial else score), - ) - if not quality_ok: - skipped(("profile",), "quality_gate_not_met") - record["assessment"] = assessment( - "FAIL", - "quality_gate_not_met", - quality_passed=False, - performance=gate, - ) - else: - if role != "candidate": - skipped(("profile",), "not_required") - record["assessment"] = assessment( - "PASS", - "fixed_checks_satisfied", - quality_passed=True, - performance=gate, - ) - - def checkpoint_candidate(): - quality_step = next(step for step in record["steps"] if step["id"] == "quality") - record["checkpoint"] = { - "assessment": record["assessment"], - "binding": expected, - "measurements": measured, - "measurement_results": [ - (output / step["id"] / "result.json").relative_to(root).as_posix() - for step in record["steps"] if step["id"].startswith("measure-") - ], - "quality": quality_step, - "quality_score": score, - } - save() - - def profile_error(name, error): - step = next((s for s in reversed(record["steps"]) if s["id"] == name), {}) - execution_status = step.get("execution_status") - if isinstance(error, KeyboardInterrupt) or execution_status == "cancelled": - status = "interrupted" - elif isinstance(error, TimeoutError) or execution_status == "timeout": - status = "timed_out" - else: - status = "failed" - diagnostic = capture_diagnostic( - root, directory, name, status, str(error) or status, - process_failed=execution_status not in (None, "not_started", "completed"), - ) - record["profiling_error"] = diagnostic - step.pop("result", None) - if step.get("status") in ("running", "completed"): - step.update(status="failed", reason=diagnostic["message"]) - save() - - def capture_profile(): - nonlocal profile - if "profile" not in settings["commands"]: - skipped(("profile",), "not_configured") - return - try: - if not standalone: - begin_capture() - trace = stage("profile") - validated = validated_profile( - root, directory, pending["attempt_id"], conditions, expected, record["steps"][-1], - captured=trace, - ) - if time.monotonic() >= capture_started + profile_timeout: - raise TimeoutError("Profiling timeout during capture validation") - profile = validated - record["profile"] = profile - except (Exception, KeyboardInterrupt) as error: - profile_error("profile", error) - finally: - if not standalone and capture_started is not None: - finish_capture() - - try: - if standalone: - begin_capture() - protocol = safe_path(root, pending.get("protocol_path", "frozen/protocol")) - values["protocol"] = str(protocol) - if standalone: - members(protocol) - if "profile" not in settings["commands"]: - raise ValueError("No profiler configured in the retained protocol") - # Rebuild from Git objects; retained directories can be replaced after acceptance. - repository = pending.get("source_repo") - if not repository: - raise ValueError("Authoritative source repository is unavailable") - retain_revision( - repository, workspace, plan["candidate_includes"], pending["revision"], - deadline=capture_started + profile_timeout if standalone else None, - ) - if not standalone and not source.exists(): - retain(workspace, source, fingerprint=False) - precheck = stage("precheck", bound=False) - if precheck.get("status") == "candidate_failure" or precheck.get("passed") is False: - skipped(("service", "measurement", "quality", "profile"), "precheck_rejected") - record["assessment"] = assessment("FAIL", "functional_check_rejected") - if standalone: - detail = precheck.get("error") or precheck.get("message") - profile_error("precheck", ValueError(_error_excerpt( - str(detail or "Functional check rejected") - ))) - record["cleanup_verified"] = True - elif precheck.get("passed") is not True: - raise ValueError("Missing functional/numerical check evidence") - else: - if standalone and time.monotonic() >= capture_started + profile_timeout: - record["failed_stage"] = "service" - raise TimeoutError("Profiling timeout before service startup") - service_step = {"id": "service", "status": "running", "started_at": time.time()} - record["steps"].append(service_step) - save() - with supervised_service( - [*plan["evaluation_prefix"], *command(settings["commands"]["service"])], - workspace, - environment, - directory / "service", - expected, - ) as (process, owner): - service_step.update(pid=process.pid, owner_path="service/owner.json") - save() - try: - ready = stage("ready") - if ( - not ready_for_service(ready, revision=expected["revision"], pid=process.pid) - or ready.get("loaded_root") != str(workspace.resolve()) - ): - raise ValueError("Service readiness/ownership unverified") - role = pending["role"] - for index in range(sampling[role]["warmups"]): - stage(f"warmup-{index + 1:03d}") - if standalone: - capture_profile() - record["assessment"] = assessment( - "PASS" if profile else "INCONCLUSIVE", "profile_only", eligible=False - ) - else: - evaluate(role) - if role == "candidate": - checkpoint_candidate() - if record["assessment"]["reason"] in INLINE_PROFILE_REASONS: - capture_profile() - except BaseException: - record.setdefault("failed_stage", record["steps"][-1]["id"]) - raise - finally: - try: - cleanup = stage("stop", bound=False) - binding(cleanup) - record["external_cleanup_verified"] = ( - cleanup.get("cleanup_complete") is True - ) - except (OSError, ValueError, KeyError) as error: - record["external_cleanup_verified"] = False - record["cleanup_error"] = _error_excerpt(str(error)) - record["cleanup_verified"] = ( - owner["domain_empty"] is True and record.get("external_cleanup_verified") is True - ) - if not record["cleanup_verified"]: - raise ValueError(record.get("cleanup_error") or "Service cleanup is unverified") - except (Exception, KeyboardInterrupt) as error: - failed = record.get( - "failed_stage", record["steps"][-1]["id"] if record["steps"] else "startup" - ) - record["assessment"] = assessment( - "INCONCLUSIVE", - _error_excerpt(f"{failed}: {type(error).__name__}: {error}"), - performance=gate, - quality_passed=quality_ok, - ) - if standalone and ("profiling_error" not in record or isinstance(error, KeyboardInterrupt)): - profile_error(failed, error) - for definition in record["steps"]: - if definition["id"] == failed: - definition.setdefault("execution_status", definition["status"]) - if definition["status"] in ("running", "completed"): - definition["status"] = "failed" - definition["reason"] = _error_excerpt(str(error)) - if owner is not None: - record["cleanup_verified"] = ( - owner["domain_empty"] is True and record.get("external_cleanup_verified") is True - ) - elif standalone and not any(step["id"] == "service" for step in record["steps"]): - record["cleanup_verified"] = True - for name in ("quality", "profile"): - if not any(step["id"] == name for step in record["steps"]): - skipped((name,), "prerequisite_incomplete") - if capture_started is not None: - finish_capture() - if owner is not None: - service_step.update( - status="completed" if owner["domain_empty"] is True else "failed", - ended_at=time.time(), - returncode=owner["returncode"], - ) - record.update( - status="completed", - measurements=measured, - quality_score=score, - profile=profile, - elapsed_seconds=time.monotonic() - started, - ) - save() - return record diff --git a/src/inferrsi/harness/records/__init__.py b/src/inferrsi/harness/records/__init__.py index 4c3359090..f55f924d8 100644 --- a/src/inferrsi/harness/records/__init__.py +++ b/src/inferrsi/harness/records/__init__.py @@ -1,5 +1,11 @@ -"""Campaign records: manifests, traces, logs and delivered-context captures. +"""Retained run evidence, fixed-version storage and campaign records.""" -Nothing here runs an experiment or accepts a result. These modules write and -read what a caller recorded. -""" +__all__ = ["RunStore", "RunStoreReader"] + + +def __getattr__(name): + if name in __all__: + from ._run_store import RunStore, RunStoreReader + + return RunStore if name == "RunStore" else RunStoreReader + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/inferrsi/harness/run_store.py b/src/inferrsi/harness/records/_run_store.py similarity index 98% rename from src/inferrsi/harness/run_store.py rename to src/inferrsi/harness/records/_run_store.py index d1dc0c457..56359576b 100644 --- a/src/inferrsi/harness/run_store.py +++ b/src/inferrsi/harness/records/_run_store.py @@ -11,14 +11,13 @@ import uuid import weakref from collections.abc import Iterable, Iterator, Mapping -from contextlib import AbstractContextManager, contextmanager, suppress +from contextlib import AbstractContextManager, contextmanager, nullcontext, suppress from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path from inferrsi.contracts import json_v1 -from inferrsi.harness.errors import PartialExecutionFacts, PublicError -from inferrsi.harness.execution_spec import request_digest as request_digest +from inferrsi.contracts._harness_errors import PartialExecutionFacts, PublicError if os.name == "nt": import msvcrt @@ -716,6 +715,17 @@ def from_mount(cls, mount: Mapping) -> RunStoreReader: def _connection(self) -> AbstractContextManager[sqlite3.Connection]: return _connect(self._index, self._timeout, read_only=self._read_only) + @property + def read_only(self) -> bool: + return self._read_only + + @contextmanager + def work_control_connection(self, *, write: bool = False) -> Iterator[sqlite3.Connection]: + """Access campaign tables in this mount, with an atomic transaction for changes.""" + with self._connection() as connection: + with _transaction(connection) if write else nullcontext(): + yield connection + def committed(self, attempt_id: str, record_version: int | None = None) -> CommittedRecord: """One verified committed version; the latest one when ``record_version`` is None.""" errors = [] if _is_id(attempt_id) else ["attempt_id: not an Id"] diff --git a/src/inferrsi/harness/artifact_primitives.py b/src/inferrsi/harness/records/artifact_primitives.py similarity index 100% rename from src/inferrsi/harness/artifact_primitives.py rename to src/inferrsi/harness/records/artifact_primitives.py diff --git a/src/inferrsi/harness/records/atomic_capture.py b/src/inferrsi/harness/records/atomic_capture.py index c3379f63b..f2ba0969c 100644 --- a/src/inferrsi/harness/records/atomic_capture.py +++ b/src/inferrsi/harness/records/atomic_capture.py @@ -80,9 +80,9 @@ def verify_stored(document): raise ValueError("Atomic capture accounting differs from its request") -def retain_selection(root: Path, *, reader, context_id, reference, revision, layer, max_bytes, - context, assemble_text, finding=None, diagnosis_binding=None, - ranking_policy=None): +def prepare_selection(root: Path, *, reader, context_id, reference, revision, layer, max_bytes, + context, assemble_text, finding=None, diagnosis_binding=None, + ranking_policy=None): campaign = knowledge_capture.capture_campaign(root, context_id) request = {"mode": "pinned_selection", "ref": reference, "revision": revision, "layer": layer, "finding": finding, "max_bytes": max_bytes, "context": dict(context), @@ -97,11 +97,16 @@ def retain_selection(root: Path, *, reader, context_id, reference, revision, lay for record in receipt["delivered"]] contexts = [{**item, "resources": [_resource(body, record)], "omissions": []} for item, body, record in zip(items, bodies, receipt["delivered"])] - return knowledge_capture.store_capture( - root, campaign_id=campaign["campaign_id"], context_id=context_id, request=request, + return knowledge_capture.prepare_capture( + campaign_id=campaign["campaign_id"], context_id=context_id, request=request, selection=receipt, items=items, omissions=receipt.get("omissions", []), context_omissions=[], context_budget=max_bytes, context_bytes_used=receipt["body_bytes"], contexts=contexts, assembled_text=assemble_text(contexts), diagnosis_binding=diagnosis_binding, captured_by=f"inferrsi pinned knowledge read {__version__}", ) + + +def retain_selection(root: Path, **request): + """Retain a verified pinned capture outside the managed commit protocol.""" + return knowledge_capture.store_capture(root, prepare_selection(root, **request)) diff --git a/src/inferrsi/harness/atomic_json.py b/src/inferrsi/harness/records/atomic_json.py similarity index 100% rename from src/inferrsi/harness/atomic_json.py rename to src/inferrsi/harness/records/atomic_json.py diff --git a/src/inferrsi/harness/records/knowledge_capture.py b/src/inferrsi/harness/records/knowledge_capture.py index 8ea7feefa..80274c078 100644 --- a/src/inferrsi/harness/records/knowledge_capture.py +++ b/src/inferrsi/harness/records/knowledge_capture.py @@ -5,8 +5,9 @@ prepared, not that a model read it. Hashes establish internal consistency, not an authenticated capture origin. -This module stores bytes and record facts only. Callers project items and -assemble text; Harness does not interpret ranking, selection or publication. +This module stores and verifies the captured bytes. Knowledge ranks and +assembles the selected material. Harness Indexer checks the returned ranking +against the managed session's frozen policy. """ from __future__ import annotations @@ -22,15 +23,36 @@ from inferrsi import __version__ +from .evidence import bounded_record_bytes + MAX_CONTEXT_CAPTURE_BYTES = 4 * 1024 * 1024 CAPTURE_KIND = "inferrsi.knowledge_context" _IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}") -def capture_campaign(root: Path, context_id: str) -> dict: - """Check a new capture's identifier and return the campaign manifest.""" +def read_retained(root, reference): + raw, state = bounded_record_bytes(root, reference.get("path"), MAX_CONTEXT_CAPTURE_BYTES) + if raw is None: + raise ValueError(f"Invalid delivered knowledge context ({state})") + if hashlib.sha256(raw).hexdigest() != reference.get("sha256"): + raise ValueError("Delivered knowledge context changed") + try: + record = json.loads(raw) + except (ValueError, RecursionError): + raise ValueError("Invalid delivered knowledge context (invalid_format)") from None + if not isinstance(record, dict): + raise ValueError("Invalid delivered knowledge context (invalid_format)") + return record + + +def _validate_context_id(context_id: str) -> None: if not isinstance(context_id, str) or not _IDENTIFIER.fullmatch(context_id): raise ValueError("context id must be a safe single identifier") + + +def capture_campaign(root: Path, context_id: str) -> dict: + """Check a new capture's identifier and return the campaign manifest.""" + _validate_context_id(context_id) try: campaign = json.loads((Path(root).resolve() / "campaign.json").read_text(encoding="utf-8")) except (OSError, ValueError) as exc: @@ -40,22 +62,14 @@ def capture_campaign(root: Path, context_id: str) -> dict: return campaign -def store_capture(root: Path, *, campaign_id: str, context_id: str, request: dict, - selection: object, items: list[dict], omissions: list[dict], - context_omissions: list[dict], context_budget: object, - context_bytes_used: object, contexts: list[dict], - assembled_text: str, retrieval: dict | None = None, - captured_by: str | None = None, - diagnosis_binding: dict | None = None) -> tuple[Path, str]: - """Write the delivered context as one new capture. - - Optional record facts include retrieval provenance and the managed diagnosis - in effect when lookup began. Omitted facts preserve the earlier capture format. - - Returns the new campaign-relative file and its SHA-256. An existing capture - is never overwritten, so a trace can pin the exact bytes it cites. - """ - root = Path(root).resolve() +def prepare_capture(*, campaign_id: str, context_id: str, request: dict, + selection: object, items: list[dict], omissions: list[dict], + context_omissions: list[dict], context_budget: object, + context_bytes_used: object, contexts: list[dict], + assembled_text: str, retrieval: dict | None = None, + captured_by: str | None = None, + diagnosis_binding: dict | None = None) -> dict: + """Assemble the capture to be validated before its bytes are retained.""" document = { "schema_version": 1, "kind": CAPTURE_KIND, "campaign_id": campaign_id, "context_id": context_id, @@ -79,10 +93,28 @@ def store_capture(root: Path, *, campaign_id: str, context_id: str, request: dic "assembled_text": assembled_text, "assembled_sha256": hashlib.sha256(assembled_text.encode("utf-8")).hexdigest(), }) + return document + + +def capture_bytes(document: dict) -> bytes: + """Encode the exact bytes pinned in a retained capture reference.""" payload = (json.dumps(document, ensure_ascii=False, indent=2, allow_nan=False) + "\n").encode("utf-8") if len(payload) > MAX_CONTEXT_CAPTURE_BYTES: raise ValueError("captured context exceeds 4 MiB; lower --context-bytes or --limit") + return payload + + +def store_capture(root: Path, document: dict, *, + expected_sha256: str | None = None) -> tuple[Path, str]: + """Retain a new capture, or finish a managed commit with the exact same bytes.""" + context_id = document["context_id"] + _validate_context_id(context_id) + root = Path(root).resolve() + payload = capture_bytes(document) + digest = hashlib.sha256(payload).hexdigest() + if expected_sha256 is not None and expected_sha256 != digest: + raise ValueError("Knowledge capture differs from its dispatched request") directory = root / "knowledge" if directory.is_symlink() or directory.resolve() != directory: raise ValueError("knowledge directory must not be a symbolic link") @@ -96,11 +128,14 @@ def store_capture(root: Path, *, campaign_id: str, context_id: str, request: dic stream.write(payload) os.link(temporary, target) except FileExistsError as exc: - raise ValueError("a context capture with this id already exists") from exc + if expected_sha256 is None: + raise ValueError("a context capture with this id already exists") from exc + # A prior commit can have linked these bytes before its state write finished. + read_retained(root, {"path": target.relative_to(root).as_posix(), "sha256": digest}) finally: if temporary.exists(): temporary.unlink() - return target, hashlib.sha256(payload).hexdigest() + return target, digest def resource_bytes(resource: dict) -> bytes: diff --git a/src/inferrsi/harness/records/service_io.py b/src/inferrsi/harness/records/service_io.py new file mode 100644 index 000000000..6ef97da8d --- /dev/null +++ b/src/inferrsi/harness/records/service_io.py @@ -0,0 +1,64 @@ +"""Read bounded service-reuse records and validate their retained paths and values.""" + +import json +import math +from pathlib import Path + +JSON_SIZE_LIMIT = 4 * 1024 * 1024 + + +def finite_number(value): + try: + return type(value) in (int, float) and math.isfinite(value) + except OverflowError: + return False + + +def positive_number(value): + return finite_number(value) and value > 0 + + +def safe_path(root, relative): + if not isinstance(relative, str) or not relative or "\\" in relative or ":" in relative: + raise ValueError("Expected a campaign-relative path") + part = Path(relative) + if part.is_absolute() or ".." in part.parts: + raise ValueError("Path must stay inside the campaign") + target = root / part + if any( + p.is_symlink() for p in (target, *target.parents) if p.is_relative_to(root) + ) or not target.resolve().is_relative_to(root.resolve()): + raise ValueError("Symbolic or escaping campaign path") + return target + + +def no_fingerprints(value): + if isinstance(value, dict): + for key, item in value.items(): + if not isinstance(key, str) or any( + name in key.lower() for name in ("sha256", "fingerprint", "digest") + ): + raise ValueError("File fingerprints are not part of the service-reuse protocol") + no_fingerprints(item) + elif isinstance(value, list): + for item in value: + no_fingerprints(item) + elif isinstance(value, float) and not math.isfinite(value): + raise ValueError("Nonfinite JSON value") + + +def read(path): + if path.is_symlink() or not path.is_file() or path.stat().st_size > JSON_SIZE_LIMIT: + raise ValueError(f"Missing, symbolic or oversized JSON: {path.name}") + try: + value = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(value, dict): + raise ValueError("Result must be a JSON object") + no_fingerprints(value) + except RecursionError as error: + raise ValueError(f"JSON nesting exceeds the supported depth: {path.name}") from error + return value + + +def error_excerpt(message): + return message if len(message) <= 1024 else message[:1021] + "..." diff --git a/src/inferrsi/harness/service_observations.py b/src/inferrsi/harness/records/service_observations.py similarity index 90% rename from src/inferrsi/harness/service_observations.py rename to src/inferrsi/harness/records/service_observations.py index b239e0b50..05a334052 100644 --- a/src/inferrsi/harness/service_observations.py +++ b/src/inferrsi/harness/records/service_observations.py @@ -2,7 +2,7 @@ import json -from . import project_service as service +from . import service_io def inline_profiles(attempts): @@ -85,9 +85,9 @@ def _large_profile_error(attempt): def matches_control(root, attempt): - path = service.safe_path(root, attempt["path"] + "/observation.json") - if path.stat().st_size <= service.JSON_SIZE_LIMIT: - return service.read(path) == attempt + path = service_io.safe_path(root, attempt["path"] + "/observation.json") + if path.stat().st_size <= service_io.JSON_SIZE_LIMIT: + return service_io.read(path) == attempt if not path.is_file(): return False # Compare only bytes that the trusted state and the atomic JSON writer can account for. @@ -107,17 +107,19 @@ def display(root, attempt): details = attempt["path"] + "/observation.json" receipt = attempt["path"] + "/execution/profile/result.json" try: - if service.safe_path(root, receipt).is_file(): + if service_io.safe_path(root, receipt).is_file(): details = receipt except (OSError, ValueError): pass - error = {**error, "message": service._error_excerpt(error["message"]), "details_path": details} + error = { + **error, "message": service_io.error_excerpt(error["message"]), "details_path": details + } steps = [] for step in execution["steps"]: if step["id"] == "profile": step = {k: v for k, v in step.items() if k != "result"} for key in ("reason", "error"): if isinstance(step.get(key), str): - step[key] = service._error_excerpt(step[key]) + step[key] = service_io.error_excerpt(step[key]) steps.append(step) return {**attempt, "execution": {**execution, "profiling_error": error, "steps": steps}} diff --git a/src/inferrsi/harness/usage.py b/src/inferrsi/harness/records/usage.py similarity index 100% rename from src/inferrsi/harness/usage.py rename to src/inferrsi/harness/records/usage.py diff --git a/tests/apps/test_agent_sessions.py b/tests/apps/test_agent_sessions.py index c79c366e8..e5063b3e0 100644 --- a/tests/apps/test_agent_sessions.py +++ b/tests/apps/test_agent_sessions.py @@ -1,12 +1,13 @@ """Native handoffs retain identity and evidence without launching a second Agent.""" import json +import time from concurrent.futures import ThreadPoolExecutor import pytest from inferrsi.apps.cli import main -from inferrsi.harness import agent_sessions +from inferrsi.harness import manager @pytest.fixture @@ -14,7 +15,7 @@ def job(tmp_path): workspace = tmp_path / "workspace" workspace.mkdir() root = tmp_path / "job" - agent_sessions.prepare(root, prompt="Read the entry skill and produce a patch.", + manager.prepare_agent_session(root, prompt="Read the entry skill and produce a patch.", workspace=workspace, title="Native session control", max_seconds=120) return root @@ -26,8 +27,8 @@ def export(root, name, value): def bind(job): - agent_sessions.dispatch(job) - return agent_sessions.bind( + manager.dispatch_agent_session(job) + return manager.bind_agent_session( job, host="test-host", session_id="session-1", host_id="host-1", receipt=export(job, "creation.json", {"native_result": "session-1"}), ) @@ -41,12 +42,12 @@ def observation(job, state="running", **fields): def test_dispatch_can_be_consumed_only_once_even_after_interruption(job): - first = agent_sessions.dispatch(job) + first = manager.dispatch_agent_session(job) assert first["may_create"] is True assert first["handoff"]["context_mode"] == "fresh" assert "Read the entry skill" in first["handoff"]["prompt"] # Reopening the job after a caller crash never authorizes another launch. - second = agent_sessions.dispatch(job) + second = manager.dispatch_agent_session(job) assert second["may_create"] is False assert "handoff" not in second assert "without_relaunch" in second["next_action"] @@ -55,7 +56,7 @@ def test_dispatch_can_be_consumed_only_once_even_after_interruption(job): def test_concurrent_dispatch_allows_only_one_creation(job): def attempt(): try: - return agent_sessions.dispatch(job).get("may_create", False) + return manager.dispatch_agent_session(job).get("may_create", False) except OSError: # OS lock contention is an explicit refusal, not another launch. return False with ThreadPoolExecutor(max_workers=2) as executor: @@ -66,53 +67,53 @@ def test_binding_is_idempotent_but_cannot_be_replaced(job): first = bind(job) assert first["state"] == "running" receipt = export(job, "creation.json", {"native_result": "session-1"}) - same = agent_sessions.bind(job, host="test-host", session_id="session-1", + same = manager.bind_agent_session(job, host="test-host", session_id="session-1", host_id="host-1", receipt=receipt) assert same["native_session"] == first["native_session"] with pytest.raises(ValueError, match="another native session"): - agent_sessions.bind(job, host="test-host", session_id="session-2", receipt=receipt) + manager.bind_agent_session(job, host="test-host", session_id="session-2", receipt=receipt) wrong = observation(job, session_id="session-2") with pytest.raises(ValueError, match="bound native session"): - agent_sessions.record(job, observation=wrong) + manager.record_agent_session(job, observation=wrong) def test_definite_creation_failure_is_retained_without_inventing_a_session(job): - agent_sessions.dispatch(job) + manager.dispatch_agent_session(job) receipt = export(job, "creation-error.json", { "host": "test-host", "session_id": None, "state": "failed", "creation_outcome": "not_created", "native_receipt": {"error": "invalid_project"}, }) - result = agent_sessions.record(job, observation=receipt) + result = manager.record_agent_session(job, observation=receipt) assert result["state"] == "failed" and result["native_session"] is None - assert agent_sessions.dispatch(job)["may_create"] is False + assert manager.dispatch_agent_session(job)["may_create"] is False def test_ambiguous_creation_error_cannot_be_treated_as_definite_failure(job): - agent_sessions.dispatch(job) + manager.dispatch_agent_session(job) receipt = export(job, "creation-error.json", { "host": "test-host", "state": "failed", "native_receipt": {"error": "disconnected"}, }) with pytest.raises(ValueError, match="definite not_created"): - agent_sessions.record(job, observation=receipt) - assert agent_sessions.status(job)["state"] == "dispatching" + manager.record_agent_session(job, observation=receipt) + assert manager.agent_session_status(job)["state"] == "dispatching" def test_changed_entry_resource_prevents_dispatch(tmp_path): entry = tmp_path / "SKILL.md" entry.write_text("Original entry", encoding="utf-8") root = tmp_path / "job" - agent_sessions.prepare(root, prompt="Read the entry", workspace=tmp_path, + manager.prepare_agent_session(root, prompt="Read the entry", workspace=tmp_path, title="Frozen entry", max_seconds=120, frozen_inputs=[entry]) entry.write_text("Different procedure", encoding="utf-8") with pytest.raises(ValueError, match="Frozen Agent input"): - agent_sessions.dispatch(root) + manager.dispatch_agent_session(root) def test_native_completion_is_not_acceptance_and_deliverable_is_snapshotted(job): bind(job) artifact = job.parent / "workspace/candidate.py" artifact.write_text("result = 42\n", encoding="utf-8") - result = agent_sessions.record(job, observation=observation(job, "completed"), + result = manager.record_agent_session(job, observation=observation(job, "completed"), artifacts=[artifact]) assert result["state"] == "completed" assert result["task_acceptance"] == "not_assessed" @@ -120,29 +121,29 @@ def test_native_completion_is_not_acceptance_and_deliverable_is_snapshotted(job) retained = job / result["artifacts"][0]["path"] artifact.write_text("changed later", encoding="utf-8") assert retained.read_text() == "result = 42\n" - assert agent_sessions.status(job)["state"] == "completed" + assert manager.agent_session_status(job)["state"] == "completed" with pytest.raises(ValueError, match="terminal"): - agent_sessions.record(job, observation=observation(job)) + manager.record_agent_session(job, observation=observation(job)) retained.write_text("tampered", encoding="utf-8") with pytest.raises(ValueError, match="artifact changed"): - agent_sessions.status(job) + manager.agent_session_status(job) def test_usage_snapshots_are_not_summed_and_cannot_decrease(job): bind(job) for tokens in (100, 100, 120): - result = agent_sessions.record(job, observation=observation( + result = manager.record_agent_session(job, observation=observation( job, usage_scope="session_total", usage={"input_tokens": tokens, "output_tokens": 20, "cached_input_tokens": 10}, )) assert result["usage"]["input_tokens"] == 120 assert result["usage"]["output_tokens"] == 20 with pytest.raises(ValueError, match="cannot decrease"): - agent_sessions.record(job, observation=observation( + manager.record_agent_session(job, observation=observation( job, usage_scope="session_total", usage={"input_tokens": 1, "output_tokens": 1}, )) with pytest.raises(ValueError, match="valid session_total"): - agent_sessions.record(job, observation=observation( + manager.record_agent_session(job, observation=observation( job, usage_scope="turn", usage={"input_tokens": 200, "output_tokens": 40}, )) @@ -153,15 +154,15 @@ def test_terminal_observations_allow_late_usage_and_preserve_deliveries(job): artifact.write_text("first delivery", encoding="utf-8") usage = {"input_tokens": 100, "output_tokens": 20} receipt = observation(job, "completed", usage_scope="session_total", usage=usage) - first = agent_sessions.record(job, observation=receipt, artifacts=[artifact]) - repeated = agent_sessions.record(job, observation=receipt, artifacts=[artifact]) + first = manager.record_agent_session(job, observation=receipt, artifacts=[artifact]) + repeated = manager.record_agent_session(job, observation=receipt, artifacts=[artifact]) assert repeated["usage"] == first["usage"] == usage assert repeated["last_observation"] != first["last_observation"] # Observations append; record is not a deduplication API. assert len(repeated["artifacts"]) == 2 artifact.write_text("later delivery", encoding="utf-8") latest_usage = {"input_tokens": 120, "output_tokens": 25} - result = agent_sessions.record(job, observation=observation( + result = manager.record_agent_session(job, observation=observation( job, "completed", usage_scope="session_total", usage=latest_usage), artifacts=[artifact]) assert result["usage"] == latest_usage assert result["state"] == "completed" and result["task_acceptance"] == "not_assessed" @@ -169,32 +170,32 @@ def test_terminal_observations_allow_late_usage_and_preserve_deliveries(job): assert (job / result["artifacts"][-1]["path"]).read_text() == "later delivery" for state in ("running", "failed", "cancelled"): with pytest.raises(ValueError, match="terminal"): - agent_sessions.record(job, observation=observation(job, state)) + manager.record_agent_session(job, observation=observation(job, state)) with pytest.raises(ValueError, match="cannot decrease"): - agent_sessions.record(job, observation=observation( + manager.record_agent_session(job, observation=observation( job, "completed", usage_scope="session_total", usage=usage)) - missing = agent_sessions.record(job, observation=observation(job, "completed")) + missing = manager.record_agent_session(job, observation=observation(job, "completed")) assert missing["usage"] is None assert missing["last_observed_usage"]["usage"] == latest_usage - assert agent_sessions.dispatch(job)["may_create"] is False + assert manager.dispatch_agent_session(job)["may_create"] is False def test_deadline_does_not_claim_that_native_host_was_stopped(job, monkeypatch): - monkeypatch.setattr(agent_sessions.time, "time", lambda: 10**12) - view = agent_sessions.status(job) + monkeypatch.setattr(time, "time", lambda: 10**12) + view = manager.agent_session_status(job) assert view["deadline_exceeded"] is True assert view["state"] == "prepared" assert view["deadline_enforcement"] == "native_host_not_enforced" with pytest.raises(ValueError, match="deadline exhausted"): - agent_sessions.dispatch(job) + manager.dispatch_agent_session(job) def test_missing_final_usage_does_not_relabel_an_earlier_partial_meter(job): bind(job) - agent_sessions.record(job, observation=observation( + manager.record_agent_session(job, observation=observation( job, usage_scope="session_total", usage={"input_tokens": 100, "output_tokens": 20}, )) - result = agent_sessions.record(job, observation=observation(job, "completed")) + result = manager.record_agent_session(job, observation=observation(job, "completed")) assert result["usage"] is None assert result["last_observed_usage"]["usage"]["input_tokens"] == 100 assert result["last_observed_usage"]["receipt"] != result["last_observation"] @@ -210,7 +211,7 @@ def test_frozen_input_changes_are_rejected(job, name): else: path.write_text("changed", encoding="utf-8") with pytest.raises(ValueError, match="Frozen Agent"): - agent_sessions.dispatch(job) + manager.dispatch_agent_session(job) def test_unrelated_files_cannot_be_collected(job): @@ -218,7 +219,7 @@ def test_unrelated_files_cannot_be_collected(job): outside = job.parent / "outside.txt" outside.write_text("unrelated", encoding="utf-8") with pytest.raises(ValueError, match="declared workspace"): - agent_sessions.record(job, observation=observation(job), artifacts=[outside]) + manager.record_agent_session(job, observation=observation(job), artifacts=[outside]) def test_cli_prepares_and_dispatches_but_does_not_claim_a_launched_session(tmp_path, capsys): diff --git a/tests/apps/test_anthropic_agent.py b/tests/apps/test_anthropic_agent.py index d90059bac..180dd125d 100644 --- a/tests/apps/test_anthropic_agent.py +++ b/tests/apps/test_anthropic_agent.py @@ -9,7 +9,7 @@ from inferrsi.apps.integrations.anthropic import anthropic_agent as agent from inferrsi.apps.storage.artifacts import sha256, write_json from inferrsi.apps.workflows import skill_evaluation as evaluation -from inferrsi.harness import skill_evaluation as harness +from inferrsi.harness.executor import skill_evaluation as harness from tests.fixtures.skill_eval_compare_support import configuration from tools import skill_eval_compare as compare from tools.skill_eval_pilot import SCHEMA diff --git a/tests/apps/test_apps_artifact_reader.py b/tests/apps/test_apps_artifact_reader.py index 3452030b5..7d74a0f6d 100644 --- a/tests/apps/test_apps_artifact_reader.py +++ b/tests/apps/test_apps_artifact_reader.py @@ -5,8 +5,9 @@ import pytest from inferrsi.apps.storage.artifact_reader import ArtifactReader -from inferrsi.harness.errors import PublicError -from inferrsi.harness.run_store import RunStore, artifact_ref +from inferrsi.harness.api import PublicError +from inferrsi.harness.records import RunStore +from inferrsi.harness.records._run_store import artifact_ref from tests.harness.run_store_child import make_attempt, make_digest, make_payload diff --git a/tests/apps/test_apps_assess.py b/tests/apps/test_apps_assess.py index 14395933f..fc14aba85 100644 --- a/tests/apps/test_apps_assess.py +++ b/tests/apps/test_apps_assess.py @@ -18,8 +18,8 @@ from inferrsi.apps.storage.artifact_reader import ArtifactReader from inferrsi.apps.views.dashboard_live import DashboardServer from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness.errors import PublicError -from inferrsi.harness.run_store import RunStore +from inferrsi.harness.api import PublicError +from inferrsi.harness.records import RunStore _FIXTURES = Path(__file__).resolve().parents[2] / "docs/contracts/fixtures/t108-v4" diff --git a/tests/apps/test_apps_capture_adapter.py b/tests/apps/test_apps_capture_adapter.py index cf5042866..17ec7ffc2 100644 --- a/tests/apps/test_apps_capture_adapter.py +++ b/tests/apps/test_apps_capture_adapter.py @@ -7,7 +7,7 @@ import pytest from inferrsi.apps import api -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import PublicError @pytest.fixture diff --git a/tests/apps/test_apps_evaluate_cli.py b/tests/apps/test_apps_evaluate_cli.py index 0a274c02b..6a5b56981 100644 --- a/tests/apps/test_apps_evaluate_cli.py +++ b/tests/apps/test_apps_evaluate_cli.py @@ -18,7 +18,9 @@ from inferrsi.benchmark import cpu_smoke from inferrsi.benchmark.workers import fixture_worker as worker from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness import execution_service, run_store +from inferrsi.harness.executor import _execution as execution_service +from inferrsi.harness.records import RunStore +from inferrsi.harness.records import _run_store as run_store from tests.apps.test_apps_generation_plan import generation as generation from tests.benchmark.test_benchmark_assessment import remove from tests.benchmark.test_benchmark_assessment import retained as retained @@ -269,7 +271,7 @@ def test_parser_and_unrelated_commands_do_not_load_new_ports(tmp_path): from inferrsi.apps.cli.arguments import parser parser() assert not any(name in sys.modules for name in ( - 'inferrsi.apps.api', 'inferrsi.harness.api', 'inferrsi.harness.run_store', + 'inferrsi.apps.api', 'inferrsi.harness.api', 'inferrsi.harness.records._run_store', 'inferrsi.benchmark.preparation', 'inferrsi.benchmark.assessment')) """ child = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, @@ -389,7 +391,7 @@ def test_malformed_storage_is_exit_two_before_store_open(evaluation, tmp_path, m def forbidden(*args, **kwargs): pytest.fail("malformed storage reached a writable Store") - monkeypatch.setattr(run_store.RunStore, "from_mount", forbidden) + monkeypatch.setattr(RunStore, "from_mount", forbidden) command = arguments(tmp_path, "execute", execute_request(case), config, target_config(case)) with pytest.raises(SystemExit) as error: main(command) diff --git a/tests/apps/test_apps_evidence.py b/tests/apps/test_apps_evidence.py index 131113132..ea56a383d 100644 --- a/tests/apps/test_apps_evidence.py +++ b/tests/apps/test_apps_evidence.py @@ -7,7 +7,7 @@ from inferrsi.apps.handoff.bridge import to_evidence from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import PublicError _FIXTURES = Path(__file__).resolve().parents[2] / "docs/contracts/fixtures/t108-v4" diff --git a/tests/apps/test_apps_evidence_capture.py b/tests/apps/test_apps_evidence_capture.py index 5c0ab1090..b0bd5aabc 100644 --- a/tests/apps/test_apps_evidence_capture.py +++ b/tests/apps/test_apps_evidence_capture.py @@ -19,8 +19,11 @@ from inferrsi.benchmark import assessment, proofs from inferrsi.benchmark import preparation as benchmark from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness import execution_service, run_store -from inferrsi.harness.api import Harness, LocalCpuTarget +from inferrsi.harness.api import Harness +from inferrsi.harness.executor import LocalCpuTarget +from inferrsi.harness.executor import _execution as execution_service +from inferrsi.harness.records import RunStore +from inferrsi.harness.records import _run_store as run_store from tests.benchmark.test_benchmark_preparation import preparation as preparation ROOT = Path(__file__).resolve().parents[2] @@ -82,7 +85,7 @@ def test_actual_report_capture_and_assessment_share_runtime_refs( modules = tmp_path / "modules" modules.mkdir() (modules / "fixture_worker.py").write_bytes(worker) - store = run_store.RunStore(tmp_path / "store", "test") + store = RunStore(tmp_path / "store", "test") target = LocalCpuTarget("fixture-cpu", "1", work_root=tmp_path / "work", module_root=modules) reader = ArtifactReader(config) with reader.open(prepared["protocol"]) as stream: diff --git a/tests/apps/test_apps_execution_binding.py b/tests/apps/test_apps_execution_binding.py index 2cdc16cd7..d4578bf47 100644 --- a/tests/apps/test_apps_execution_binding.py +++ b/tests/apps/test_apps_execution_binding.py @@ -9,8 +9,8 @@ from inferrsi.apps.api import execute from inferrsi.apps.handoff.bridge import bind_execution, verify_protocol from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness.errors import PublicError -from inferrsi.harness.execution_spec import request_digest +from inferrsi.harness.api import PublicError +from inferrsi.harness.executor import request_digest _FIXTURES = Path(__file__).resolve().parents[2] / "docs/contracts/fixtures" _ATTEMPT = ( diff --git a/tests/apps/test_apps_fixed_cpu_views.py b/tests/apps/test_apps_fixed_cpu_views.py index 15ea29269..a6ef3fabe 100644 --- a/tests/apps/test_apps_fixed_cpu_views.py +++ b/tests/apps/test_apps_fixed_cpu_views.py @@ -16,8 +16,9 @@ from inferrsi.apps.views.dashboard_live import DashboardServer from inferrsi.contracts.json_v1 import encode from inferrsi.harness.api import Harness -from inferrsi.harness.generation import prepare_generation -from inferrsi.harness.run_store import Claim, RunStore, RunStoreReader +from inferrsi.harness.executor import prepare_generation +from inferrsi.harness.records import RunStore, RunStoreReader +from inferrsi.harness.records._run_store import Claim from tests.apps.test_apps_generation_plan import generation as generation from tests.harness import test_harness_generation_seal as seal_tests from tests.harness.test_harness_generation_seal import cpu_generation as cpu_generation @@ -143,7 +144,8 @@ def fixed_revision_only(reader, attempt_id, record_version=None): from unittest.mock import patch from inferrsi.apps import api from inferrsi.harness.api import Harness -from inferrsi.harness.run_store import Claim, RunStore +from inferrsi.harness.records import RunStore +from inferrsi.harness.records._run_store import Claim def forbidden(*args, **kwargs): raise AssertionError('read-only child attempted execution, assessment or a write') with patch.object(Harness, 'execute', forbidden), patch.object(Harness, 'allocate', forbidden), \ diff --git a/tests/apps/test_apps_generation_plan.py b/tests/apps/test_apps_generation_plan.py index dabd850c6..2c5bc120c 100644 --- a/tests/apps/test_apps_generation_plan.py +++ b/tests/apps/test_apps_generation_plan.py @@ -11,10 +11,10 @@ from inferrsi.apps.handoff.bridge import bind_execution from inferrsi.apps.storage.artifact_reader import ArtifactReader from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness.api import Harness -from inferrsi.harness.errors import PublicError -from inferrsi.harness.execution_service import LocalCpuTarget, validate -from inferrsi.harness.run_store import RunStore +from inferrsi.harness.api import Harness, PublicError +from inferrsi.harness.executor import LocalCpuTarget +from inferrsi.harness.executor._execution import validate +from inferrsi.harness.records import RunStore _FIXTURES = Path(__file__).resolve().parents[2] / "docs/contracts/fixtures/t108-v4" _ATTEMPT_FIELDS = ( diff --git a/tests/apps/test_apps_generation_views.py b/tests/apps/test_apps_generation_views.py index 73998b8f5..eacf5f1a8 100644 --- a/tests/apps/test_apps_generation_views.py +++ b/tests/apps/test_apps_generation_views.py @@ -9,8 +9,8 @@ from inferrsi.apps.api import read_attempt_view from inferrsi.apps.views.attempt_html import render_attempt from inferrsi.contracts.json_v1 import encode -from inferrsi.harness.errors import PublicError -from inferrsi.harness.generation import prepare_generation +from inferrsi.harness.api import PublicError +from inferrsi.harness.executor import prepare_generation from tests.apps.test_apps_generation_plan import generation as generation from tests.harness.test_harness_generation_seal import cpu_generation as cpu_generation diff --git a/tests/apps/test_apps_module_migrations.py b/tests/apps/test_apps_module_migrations.py index 0ac7b6ba1..3bb6180b8 100644 --- a/tests/apps/test_apps_module_migrations.py +++ b/tests/apps/test_apps_module_migrations.py @@ -176,10 +176,14 @@ def test_cold_storage_imports_do_not_load_handoff_or_probe_modules(): blocked = ('inferrsi.apps.handoff', 'inferrsi.apps.api', 'inferrsi.apps.bridge', 'inferrsi.apps.context_provider', 'inferrsi.apps.candidate_provider', 'inferrsi.apps.host', 'inferrsi.knowledge', 'inferrsi.benchmark', - 'inferrsi.harness.api', 'inferrsi.harness.run_store') + 'inferrsi.harness.executor._execution', 'inferrsi.harness.records._run_store', + 'sqlite3', '_sqlite3') class Block(importlib.abc.MetaPathFinder): def find_spec(self, name, path=None, target=None): - if any(name == item or name.startswith(item + '.') for item in blocked): + # Apps imports public error types from the lightweight API package. + if name.startswith('inferrsi.harness.api.') or any( + name == item or name.startswith(item + '.') for item in blocked + ): raise ImportError('unexpected import: ' + name) sys.meta_path.insert(0, Block()) with warnings.catch_warnings(record=True) as caught: @@ -236,13 +240,16 @@ def test_cold_handoff_and_workflow_imports_do_not_read_data_probe_or_launch_serv script = """ import builtins, importlib, importlib.abc, io, json, socket, sqlite3, subprocess, sys, warnings from unittest.mock import patch -blocked = ('inferrsi.apps.api', 'inferrsi.harness.api', 'inferrsi.harness.run_store', - 'inferrsi.harness.generation', 'torch', 'numpy', 'PIL', 'vllm') +blocked = ('inferrsi.apps.api', 'inferrsi.harness.executor._execution', + 'inferrsi.harness.records._run_store', 'inferrsi.harness.executor._generation', + 'torch', 'numpy', 'PIL', 'vllm') if sys.argv[2] == 'handoff': blocked += ('inferrsi.apps.host', 'inferrsi.benchmark', 'inferrsi.apps.integrations') class Block(importlib.abc.MetaPathFinder): def find_spec(self, name, path=None, target=None): - if any(name == item or name.startswith(item + '.') for item in blocked): + if name.startswith('inferrsi.harness.api.') or any( + name == item or name.startswith(item + '.') for item in blocked + ): raise ImportError('unexpected import: ' + name) sys.meta_path.insert(0, Block()) def deny(*args, **kwargs): diff --git a/tests/apps/test_apps_output.py b/tests/apps/test_apps_output.py index a9e8d9a83..ba1d30ee6 100644 --- a/tests/apps/test_apps_output.py +++ b/tests/apps/test_apps_output.py @@ -15,8 +15,10 @@ from inferrsi.apps.storage import archive from inferrsi.apps.storage.archive import publish_result, read_result from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness.errors import PublicError -from inferrsi.harness.run_store import Claim, RunStore, flatten, request_digest, utc_now +from inferrsi.harness.api import PublicError +from inferrsi.harness.executor import request_digest +from inferrsi.harness.records import RunStore +from inferrsi.harness.records._run_store import Claim, flatten, utc_now _ROOT = Path(__file__).resolve().parents[2] _FIXTURES = _ROOT / "docs/contracts/fixtures" diff --git a/tests/apps/test_apps_port_validation.py b/tests/apps/test_apps_port_validation.py index b384adce7..dd79f3c75 100644 --- a/tests/apps/test_apps_port_validation.py +++ b/tests/apps/test_apps_port_validation.py @@ -1,5 +1,7 @@ """Malformed port replies do not become trusted execution facts.""" +import subprocess +import sys from copy import deepcopy from dataclasses import fields @@ -7,10 +9,10 @@ from inferrsi.apps.api import execute from inferrsi.apps.storage.archive import read_result -from inferrsi.harness.errors import PartialExecutionFacts, PublicError -from inferrsi.harness.execution_spec import request_digest -from inferrsi.harness.run_store import request_digest as legacy_digest +from inferrsi.harness.api import PartialExecutionFacts, PublicError +from inferrsi.harness.executor import request_digest from tests.apps.test_apps_output import _bind, _fixture, _request, _submit_to_run_store +from tests.harness.run_store_child import child_env def _run(tmp_path, reply): @@ -65,9 +67,22 @@ def broken(request): assert not (tmp_path / "output").exists() -def test_pure_digest_surface_preserves_legacy_function_and_bytes(): - assert request_digest is legacy_digest - assert request_digest(_bind(_request())) == legacy_digest(_bind(_request())) +def test_importing_the_digest_leaves_storage_and_execution_unloaded(): + probe = """ +import hashlib +import sys +from importlib.util import find_spec + +from inferrsi.harness.executor import request_digest + +assert request_digest({}) == "sha256:" + hashlib.sha256(b"{}").hexdigest() +assert find_spec("inferrsi.harness.execution_spec") is None +assert find_spec("inferrsi.harness.run_store") is None +assert not {"sqlite3", "_sqlite3", + "inferrsi.harness.records._run_store", "inferrsi.harness.executor._execution", + "inferrsi.harness.executor._execution_service"} & sys.modules.keys() +""" + subprocess.run([sys.executable, "-c", probe], env=child_env(), check=True) @pytest.mark.parametrize("key,value", [("started", 1), ("side_effect_unknown", 0), diff --git a/tests/apps/test_apps_prepare.py b/tests/apps/test_apps_prepare.py index fb8fae102..61a38bdee 100644 --- a/tests/apps/test_apps_prepare.py +++ b/tests/apps/test_apps_prepare.py @@ -15,7 +15,7 @@ from inferrsi.apps.storage import archive from inferrsi.apps.storage.archive import read_archive_artifact, read_prepared, read_result from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import PublicError _ROOT = Path(__file__).resolve().parents[2] _FIXTURES = _ROOT / "docs/contracts/fixtures/t108-v4" diff --git a/tests/apps/test_apps_production_cli.py b/tests/apps/test_apps_production_cli.py index 899c1c5bf..1c985b32a 100644 --- a/tests/apps/test_apps_production_cli.py +++ b/tests/apps/test_apps_production_cli.py @@ -17,7 +17,10 @@ from inferrsi.benchmark import cpu_smoke, proofs from inferrsi.benchmark.workers import fixture_worker as worker from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness import execution_service, run_store +from inferrsi.harness.executor import _execution as execution_service +from inferrsi.harness.executor import request_digest +from inferrsi.harness.records import RunStore +from inferrsi.harness.records import _run_store as run_store from tests.apps.test_apps_evaluate_cli import arguments, save ROOT = Path(__file__).resolve().parents[2] @@ -81,7 +84,7 @@ def production_cli(tmp_path, request, capsys): capsys.readouterr() assessed = read_result(tmp_path, "assess") assert [claim["verdict"] for claim in assessed.result["assessment"]["claims"]] == expected - return {"pair": (config, run_store.RunStore(tmp_path / "store", "test"), prepared, executed, + return {"pair": (config, RunStore(tmp_path / "store", "test"), prepared, executed, assessed, expected), "saved": saved, "runtime": runtime, "kind": kind} @@ -220,7 +223,7 @@ def never(*args, **kwargs): assert result["reason_code"] == "RequestConflict" and result["error"]["stage"] == "claim" saved = new_attempt(case) spec = bind_execution(saved, read_prepared(config, saved["prepared_ref"])) - with store.claim(saved["attempt"], run_store.request_digest(spec)): + with store.claim(saved["attempt"], request_digest(spec)): assert main(arguments(tmp_path, "execute", saved, config, case["runtime"], output="live") + ["--capture-evidence"]) == 4 result = json.loads(capsys.readouterr().out) diff --git a/tests/apps/test_apps_replay.py b/tests/apps/test_apps_replay.py index 0f77d83ff..c5d4ebc22 100644 --- a/tests/apps/test_apps_replay.py +++ b/tests/apps/test_apps_replay.py @@ -13,14 +13,17 @@ from inferrsi.apps.api import execute from inferrsi.apps.storage.archive import read_result -from inferrsi.harness.run_store import Claim, RunStore, request_digest +from inferrsi.harness.executor import request_digest +from inferrsi.harness.records import RunStore +from inferrsi.harness.records._run_store import Claim from tests.apps.test_apps_output import _bind, _request, _submit_to_run_store _ROOT = Path(__file__).resolve().parents[2] _HOLDER = """ import json, sys from pathlib import Path -from inferrsi.harness.run_store import Claim, RunStore +from inferrsi.harness.records import RunStore +from inferrsi.harness.records._run_store import Claim root = Path(sys.argv[1]) params = json.loads((root / 'claim.json').read_text()) store = RunStore(root / 'run-store', 'apps-test') diff --git a/tests/apps/test_legacy_run_split.py b/tests/apps/test_legacy_run_split.py index 10eb4c63f..e7ba0641e 100644 --- a/tests/apps/test_legacy_run_split.py +++ b/tests/apps/test_legacy_run_split.py @@ -20,8 +20,8 @@ from inferrsi.apps.storage import artifacts from inferrsi.benchmark import legacy_run_v0, metrics, sampling from inferrsi.contracts import RunSpec, claim -from inferrsi.harness.runner import run_experiment -from inferrsi.harness.trials.external import execute_trial +from inferrsi.harness.executor.trials.external import execute_trial +from inferrsi.harness.manager import run_experiment from tests.repository._gate_policy_support import ROOT, _scan, _walk GRAPH = _scan(ROOT, frozenset()) @@ -38,17 +38,20 @@ def _reached(module: str) -> set[str]: def test_moved_harness_modules_are_gone_without_shells(): - for name in ("evaluation", "reporting", "scenarios.media"): + for name in ("evaluation", "reporting", "runner", "scenarios.media"): assert f"inferrsi.harness.{name}" not in GRAPH.trees + assert importlib.util.find_spec("inferrsi.harness.runner") is None def test_runner_and_external_lost_their_model_artifact_and_target_edges(): - assert _outside("inferrsi.harness.runner", "inferrsi.model", "inferrsi.infra") == set() - assert _outside("inferrsi.harness.trials.external", "inferrsi.model") == set() - assert _outside("inferrsi.harness.trials.external", "inferrsi.infra") <= PROCESS_DOMAIN - assert _outside("inferrsi.harness.atomic_json", "inferrsi.") == {"inferrsi.harness"} + assert _outside("inferrsi.harness.manager._runner", "inferrsi.model", "inferrsi.infra") == set() + assert _outside("inferrsi.harness.executor.trials.external", "inferrsi.model") == set() + assert _outside("inferrsi.harness.executor.trials.external", "inferrsi.infra") <= PROCESS_DOMAIN + assert _outside("inferrsi.harness.records.atomic_json", "inferrsi.") == { + "inferrsi.harness", "inferrsi.harness.records", + } # Transitively the old chain keeps only the process domain, and no new core. - for module in ("inferrsi.harness.runner", "inferrsi.harness.trials.external"): + for module in ("inferrsi.harness.manager._runner", "inferrsi.harness.executor.trials.external"): reached = _reached(module) assert {n for n in reached if n.startswith(("inferrsi.model", "inferrsi.infra"))} <= ( PROCESS_DOMAIN diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index d1886dbf4..7c98b0ba9 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -1,5 +1,6 @@ """Run the current-Agent protocol using real child processes and synthetic work.""" +import errno import hashlib import json import os @@ -14,8 +15,10 @@ from inferrsi.apps.cli import main from inferrsi.benchmark import registry -from inferrsi.harness import optimization, optimization_session -from inferrsi.harness.optimization import _locked +from inferrsi.harness import evaluator, executor, manager +from inferrsi.harness.manager import _runtime, session_runtime_identity +from inferrsi.harness.manager import _state as optimization +from inferrsi.harness.manager._state import _locked from tests.fixtures.diagnosis import diagnosis_args from tests.fixtures.session_process import kill_controller, target_python @@ -90,6 +93,72 @@ def round_arguments(root, factor): "--candidate", str(candidate), "--hypothesis", f"Test factor {factor}"] +def test_manager_round_and_cli_status_share_the_committed_observation(session, capsys, monkeypatch): + from inferrsi.knowledge.ranking_policy import managed_ranking_policy + + command = round_arguments(session, 2) + candidate = session / "work/candidate.py" + + def retained(*, lock_held=False): + return {path.relative_to(session): path.read_bytes() for path in session.rglob("*") + if path.is_file() and not (lock_held and path.name == ".session.lock")} + + def assess_while_cli_competes(root, directory, plan, execution): + before = retained(lock_held=True) + package_root = str(Path(manager.__file__).resolve().parents[3]) + child_path = os.pathsep.join(filter(None, [package_root, os.environ.get("PYTHONPATH")])) + competing = subprocess.run( + [sys.executable, "-m", "inferrsi", *command], cwd=session.parent, + env={**os.environ, "PYTHONPATH": child_path}, + capture_output=True, text=True, timeout=30, + ) + assert competing.returncode == 2, competing.stderr + assert f"[Errno {errno.EAGAIN}]" in competing.stderr, competing.stderr + assert retained(lock_held=True) == before + return executor.assess_packaged_task(root, directory, plan, execution) + + ports = {"assess_packaged": assess_while_cli_competes, + "ranking_policy_for": managed_ranking_policy} + result = manager.run_session( + manager.EvaluateSessionRound( + session=session, candidate=candidate, hypothesis="Test factor 2", + ), + **ports, + ) + observation = result["latest_observation"] + assert observation["assessment"]["score"] == 2 + assert (session / "calls.log").read_text().splitlines() == ["2"] + + before = retained() + instant = time.time() + monkeypatch.setattr(optimization, "time", SimpleNamespace(time=lambda: instant)) + direct = manager.run_session(manager.SessionStatus(session=session), **ports) + assert main(["benchmarks", "session", "status", "--session", str(session)]) == 0 + assert json.loads(capsys.readouterr().out) == direct + plan, state, _ = manager.read_session_records(session) + assert plan["round_limit"] == 3 and len(state["rounds"]) == 1 + assert direct["latest_observation"] == observation + assert retained() == before + + +@pytest.mark.parametrize(("field", "value"), [ + ("rounds", True), ("rounds", False), ("rounds", 1.5), ("rounds", "2"), + ("max_minutes", float("nan")), ("max_minutes", 1e308), + ("evaluation_timeout_seconds", 10**400), ("final_reserve_seconds", -1), +]) +def test_manager_rejects_invalid_budget_before_creating_session(task, tmp_path, field, value): + from inferrsi.knowledge.ranking_policy import managed_ranking_policy + + root = tmp_path / "new-session" + budget = {"rounds": 3, "max_minutes": 5, "evaluation_timeout_seconds": 15, field: value} + request = manager.StartBenchmarkSession(session=root, task=task.name, evaluation_args="", + condition="test", **budget) + with pytest.raises(ValueError, match="budget"): + manager.run_session(request, task_source=task, ranking_policy_for=managed_ranking_policy, + assess_packaged=executor.assess_packaged_task) + assert not root.exists() + + def test_started_task_uses_frozen_protocol_without_registry(session, capsys, monkeypatch): def unavailable(*args): raise AssertionError("The running campaign must not rediscover its task") @@ -106,7 +175,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" @@ -133,7 +202,7 @@ def test_packaged_round_uses_target_dependencies(task, tmp_path, capsys, monkeyp def test_group_observation_requires_the_recorded_boot_and_namespace( monkeypatch, recorded, current, probe, result, ): - from inferrsi.harness import launch_records + from inferrsi.harness.executor import launch_records calls = [] @@ -289,7 +358,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 +366,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 +450,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): @@ -423,7 +492,7 @@ def start(log): def test_launch_intent_appears_only_after_flush_and_cannot_replace_prior_intent( tmp_path, monkeypatch, ): - from inferrsi.harness.launch_records import LaunchRecord + from inferrsi.harness.executor.launch_records import LaunchRecord path = tmp_path / "launch-step.json" @@ -445,8 +514,8 @@ def fail_before_publication(_descriptor): def test_missing_executable_is_recorded_as_never_spawned(tmp_path): - from inferrsi.harness.launch_records import observe - from inferrsi.harness.trials.external import execute_trial + from inferrsi.harness.executor.launch_records import observe + from inferrsi.harness.executor.trials.external import execute_trial execution = tmp_path / "execution" launch_path = execution / "launch-01.json" @@ -467,7 +536,7 @@ def test_recovery_counts_an_interrupted_round_once_and_keeps_every_step( ): from inferrsi.apps.delivery import read_bundle from inferrsi.apps.views.dashboard import dashboard_snapshot - from inferrsi.harness import launch_records + from inferrsi.harness.executor import launch_records best = submit(session, 2, capsys)["best"] calls = session / "step-calls.log" @@ -486,7 +555,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"] @@ -550,22 +619,22 @@ def stop_during_second_step(root, attempt, plan, deadline): def test_recover_never_spawns_a_second_assessor_with_a_receipt( session, capsys, monkeypatch, held_child, ): - from inferrsi.harness import launch_records + 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 +642,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 +673,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 +708,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") @@ -671,9 +740,9 @@ def should_not_assess(*args): def test_frozen_drift_retains_unconfirmed_launch( session, monkeypatch, capsys, operation, recorded_gate, ): - from inferrsi.harness.launch_records import LaunchRecord + 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 +750,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"] @@ -760,14 +829,16 @@ def test_child_system_exit_settles_as_a_protocol_failure( ]) def test_reserve_status_agrees_with_final_eligibility(task, tmp_path, capsys, monkeypatch, mode, rounds, can_finalize): + from inferrsi.apps.cli import _session_request from inferrsi.apps.cli.arguments import parser from inferrsi.knowledge.ranking_policy import managed_ranking_policy root = tmp_path / "session" args = parser().parse_args(start_args(task, root)) args.round_mode = mode - optimization_session.session_command( - args, ranking_policy_for=managed_ranking_policy, task_source=task, + manager.run_session( + _session_request(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 +860,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 +871,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 +1076,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 +1086,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 +1307,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 +1317,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 +1326,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"] @@ -1376,7 +1447,7 @@ def test_unbound_benchmark_cannot_borrow_another_checkout( ): from inferrsi.apps.integrations import external_channels from inferrsi.apps.views.dashboard import dashboard_snapshot - from inferrsi.harness import optimization + from inferrsi.harness.manager import _state as optimization origin = tmp_path / "outside-git" origin.mkdir() @@ -1427,13 +1498,22 @@ def legacy_plan(root, plan): def test_runtime_identity_covers_migrated_process_domain_and_not_removed_executor() -> None: from importlib.resources import files - identity = optimization_session._runtime_identity() + identity = session_runtime_identity() root = Path(str(files("inferrsi"))) - assert "harness/local_process.py" in identity + assert "harness/executor/local_process.py" in identity # #412 R2: the Harness-owned primitives replace infra.artifacts in six modules. - assert "harness/artifact_primitives.py" in identity + 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 @@ -1443,19 +1523,24 @@ def test_runtime_identity_covers_migrated_process_domain_and_not_removed_executo assert (root / name).is_file(), name assert "infra/processes.py" not in identity assert "harness/serving/server.py" not in identity + for module in ("_server", "_http", "_image"): + assert f"harness/executor/serving/{module}.py" in identity + # The explicit prepare_generation import reaches execution validation even before use. + assert "harness/executor/_generation.py" in identity + assert "harness/executor/_execution.py" in identity assert "harness/execution_service.py" not in identity assert "benchmark/assessment.py" not in identity evidence = (root / "harness/records/evidence.py").read_bytes() assert identity["harness/records/evidence.py"] == hashlib.sha256(evidence).hexdigest() - from inferrsi.harness.artifact_primitives import sha256 + from inferrsi.harness.records.artifact_primitives import sha256 assert identity["apps/workflows/campaign.py"] == sha256(root / "apps/workflows/campaign.py") def test_runtime_identity_rejects_computed_dynamic_imports(tmp_path, monkeypatch): - identity = optimization_session._runtime_identity() - installed = Path(str(optimization_session.files("inferrsi"))) + identity = session_runtime_identity() + installed = Path(str(_runtime.files("inferrsi"))) for name in identity: target = tmp_path / name target.parent.mkdir(parents=True, exist_ok=True) @@ -1467,9 +1552,9 @@ def test_runtime_identity_rejects_computed_dynamic_imports(tmp_path, monkeypatch " from importlib import import_module as load\n" " return load('inferrsi.' + name)\n" ) - monkeypatch.setattr(optimization_session, "files", lambda _: tmp_path) + monkeypatch.setattr(_runtime, "files", lambda _: tmp_path) with pytest.raises(ValueError, match="Session runtime import must name a literal module"): - optimization_session._runtime_identity() + session_runtime_identity() PRE_SERVING = (Path(__file__).resolve().parents[1] / "fixtures" / "optimization-session" @@ -1514,7 +1599,7 @@ def _session_bytes(root): @pytest.mark.parametrize("fixture, removed_file", [ # #498 slice 5 removed infra/artifacts.py from the runtime identity. ("pre-infra-removal-session", "infra/artifacts.py"), - # #558 renamed harness/scenarios to harness/trials. + # The pre-#558 session records the original scenarios path. ("pre-trials-rename-session", "harness/scenarios/external.py"), ("pre-recovery-closure-session", "harness/serving/server.py"), ]) @@ -1535,7 +1620,7 @@ def test_a_session_planned_before_a_runtime_change_is_refused_and_left_unchanged assert receipt["status"] == "completed" and receipt["returncode"] == 0 assert before["calls.log"].splitlines() == [b"2"] assert removed_file in json.loads(before["plan.json"])["runtime_identity"] - assert removed_file not in optimization_session._runtime_identity() + assert removed_file not in session_runtime_identity() for action in ("status", "recover"): output = _refused(session, capsys, action) assert "Optimization runtime changed" in output.out + output.err, action @@ -1550,10 +1635,10 @@ def test_changed_transitive_runtime_bytes_refuse_an_untouched_plan( installed = Path(str(files("inferrsi"))) copy = tmp_path / "install" / "inferrsi" - for name in optimization_session._runtime_identity(): + for name in session_runtime_identity(): (copy / name).parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(installed / name, copy / name) - monkeypatch.setattr(optimization_session, "files", lambda package: copy) + monkeypatch.setattr(_runtime, "files", lambda package: copy) path = session / "plan.json" before = path.read_bytes() capsys.readouterr() @@ -1606,10 +1691,10 @@ def test_pinned_pre_move_wheel_recovers_its_original_plan( sys.path.insert(0, sys.argv[1]) from inferrsi.apps.cli import main from inferrsi.benchmark import registry -from inferrsi.harness import optimization_session registry._library_root = lambda: Path(sys.argv[2]) arguments = sys.argv[3:] if arguments[0] == 'interrupt': + from inferrsi.harness import optimization_session # pinned pre-move wheel arguments.pop(0) execute = optimization_session._session_execute def interrupt(*args): @@ -1675,7 +1760,7 @@ def start(root): run(post_move_python, current_source, start(new)) new_identity = json.loads((new / "plan.json").read_bytes())["runtime_identity"] assert "apps/workflows/campaign.py" in new_identity and "apps/campaign.py" not in new_identity - from inferrsi.harness.artifact_primitives import sha256 + from inferrsi.harness.records.artifact_primitives import sha256 canonical = Path(__file__).resolve().parents[2] / "src/inferrsi/apps/workflows/campaign.py" assert new_identity["apps/workflows/campaign.py"] == sha256(canonical) @@ -1698,7 +1783,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 d3a46329c..dcb86c979 100644 --- a/tests/apps/test_project_explanation.py +++ b/tests/apps/test_project_explanation.py @@ -9,8 +9,8 @@ from inferrsi.apps.cli import main from inferrsi.apps.views.dashboard_data import load_dashboard from inferrsi.apps.views.optimization_chart import render_result -from inferrsi.harness.artifact_primitives import digest -from inferrsi.harness.optimization import read_records +from inferrsi.harness.manager import read_session_records +from inferrsi.harness.records.artifact_primitives import digest from tests.fixtures.diagnosis import diagnosis_args # Device-wide factor applied to every timed value of one measurement call, cycling per @@ -121,7 +121,7 @@ def test_confirmed_mechanism_is_adopted_and_rechecked_at_final(project, capsys): assert main(["campaign", "final", "--directory", str(project[3]), "--reason", "Synthetic search done"]) == 0 capsys.readouterr() - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["final"]["assessment"]["explanation"]["status"] == "explained" assert state["final"]["assessment"]["verdict"] == "PASS" @@ -142,7 +142,7 @@ def test_unexplained_gain_is_not_adopted_and_search_continues( assessment = submit(project, capsys, FUSED, mechanism) assert assessment["explanation"]["status"] == status assert assessment["verdict"] == verdict and assessment["eligible"] is False - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["best"]["kind"] == "baseline" and state["state"] == "active" assessment = submit(project, capsys, FUSED, FUSION) assert assessment["verdict"] == "PASS" @@ -167,7 +167,7 @@ def test_paired_decision_is_inconclusive_within_noise_without_blocking(project, assert assessment["verdict"] == "INCONCLUSIVE" and assessment["reason"] == "within_noise" assert assessment["eligible"] is False assert assessment["paired_statistics"]["report_only"] is False - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["state"] == "active" and state["best"]["kind"] == "baseline" assessment = submit(project, capsys, FUSED) assert assessment["verdict"] == "PASS" @@ -262,7 +262,7 @@ def test_paired_decision_also_selects_the_candidate_that_final_retests(project, (repo / "config.json").write_text(json.dumps( {"side": "baseline", "series": [5.0, *baseline]}), encoding="utf-8") assert start(project, capsys, "--decision", "paired", repetitions=9) == 0 - plan, _, _ = read_records(root) + plan, _, _ = read_session_records(root) assert plan["selection"] == {"direction": "maximize", "initial_score": 1.0, "metric": "paired_median_speedup"} first = submit(project, capsys, {"side": "candidate", "series": [5.0, *outlier]}) @@ -270,7 +270,7 @@ def test_paired_decision_also_selects_the_candidate_that_final_retests(project, assert first["point_estimate"]["improvement_pct"] == pytest.approx(-50) assert first["paired_statistics"]["interval"] == pytest.approx([1 / 0.9, 1 / 0.9]) assert first["verdict"] == "PASS" and first["score"] == pytest.approx(1 / 0.9) - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["best"]["kind"] == "candidate" assert state["rounds"][0]["selection"] == { "outcome": "adopted", "metric": "paired_median_speedup", @@ -279,14 +279,14 @@ def test_paired_decision_also_selects_the_candidate_that_final_retests(project, second = submit(project, capsys, {"side": "candidate", "series": [5.0, *(b / 1.05 for b in baseline)]}) assert second["verdict"] == "PASS" and second["score"] == pytest.approx(1.05) - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["rounds"][1]["selection"]["outcome"] == "not_better_than_best" assert state["best"]["candidate_id"] == state["rounds"][0]["candidate_id"] # Final retests the retained copy of the selected candidate, not the working tree. assert main(["campaign", "final", "--directory", str(root), "--reason", "Synthetic search done"]) == 0 capsys.readouterr() - _, state, summary = read_records(root) + _, state, summary = read_session_records(root) assert state["final"]["assessment"]["verdict"] == "PASS" assert summary["selected_candidate"]["candidate_id"] == state["rounds"][0]["candidate_id"] assert summary["optimization_speedup"] == pytest.approx(1 / 0.9) @@ -329,7 +329,7 @@ def test_unavailable_paired_statistics_neither_block_nor_borrow_a_point_score( assert first["score"] is None and first["speedup"] is None assert first["score_basis"] is None assert first["point_estimate"]["speedup"] == pytest.approx(10 / 9) - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["state"] == "active" and state["best"]["kind"] == "baseline" assert state["rounds"][0]["selection"]["outcome"] == "not_eligible" second = submit(project, capsys, {"side": "candidate", "series": [*plain, *plain, *huge]}) @@ -337,7 +337,7 @@ def test_unavailable_paired_statistics_neither_block_nor_borrow_a_point_score( assert main(["campaign", "final", "--directory", str(root), "--reason", "Synthetic search done"]) == 0 capsys.readouterr() - _, state, summary = read_records(root) + _, state, summary = read_session_records(root) final = state["final"]["assessment"] assert state["state"] == "completed" and final["verdict"] == "INCONCLUSIVE" assert final["score"] is None and summary["optimization_speedup"] is None @@ -367,7 +367,7 @@ def test_extreme_paired_speedup_settles_without_a_nonfinite_improvement(project, assert assessment["score"] == pytest.approx(1e-307) assert assessment["improvement_pct"] is None assert assessment["verdict"] == "INCONCLUSIVE" and assessment["reason"] == "within_noise" - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["state"] == "active" and state["pending"] is None @@ -387,7 +387,7 @@ def test_unrepresentable_point_estimate_does_not_block_a_paired_decision(project assessment = submit(project, capsys, {"metric": 1e307}) assert assessment["point_estimate"] == {"improvement_pct": None, "speedup": 1e307} assert assessment["verdict"] == "PASS" and assessment["score"] == pytest.approx(1e307) - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["state"] == "active" and state["best"]["kind"] == "candidate" @@ -413,7 +413,7 @@ def test_uncheckable_declaration_is_rejected_before_it_spends_a_round(project, c assert start(project, capsys, "--require-explanation", repetitions=6) == 0 with pytest.raises(SystemExit): submit(project, capsys, FUSED, FUSION) - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["rounds"] == [] and state["state"] == "active" one = {"mechanism": "Fewer launches", "expect": [ {"counter": "kernel_launches", "direction": "decrease"}]} @@ -434,7 +434,7 @@ def test_invalid_mechanism_is_rejected_before_execution(project, capsys): with pytest.raises(SystemExit): submit(project, capsys, FUSED, {"mechanism": "x", "expect": [ {"region": "norm", "direction": "faster"}]}) - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["rounds"] == [] @@ -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,15 +502,15 @@ 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]) + _, state, _ = read_session_records(project[3]) record = state["rounds"][-1] assert record["mechanism_unverified_after_recovery"] is True assert record["assessment"]["explanation"]["status"] == "not_declared" @@ -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") @@ -531,7 +531,7 @@ def explode(*args, **kwargs): assert assessment["verdict"] == "PASS" and assessment["eligible"] is True assert assessment["profile_evidence"]["status"] == "unavailable" assert assessment["explanation"]["status"] == "unverifiable" - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["state"] == "active" and state["best"]["kind"] == "candidate" @@ -552,16 +552,16 @@ def test_overflowing_even_medians_leave_a_recorded_inconclusive_round(project, c assert assessment["metrics"]["candidate"] is None assert assessment["paired_statistics"]["status"] == "unavailable" assert assessment["verdict"] == "INCONCLUSIVE" and assessment["score"] is None - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["state"] == "active" and state["pending"] is None 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 @@ -569,7 +569,7 @@ def test_point_decision_project_rounds_must_still_be_scored(project, capsys, mon assert main(["campaign", "round", "--directory", str(root), "--candidate", str(repo), "--hypothesis", "Scoreless point-mode control"]) == 2 capsys.readouterr() - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["state"] == "blocked" and state["pending"] is None assessment = state["rounds"][0]["assessment"] assert assessment["status"] == "infrastructure_failure" and assessment["score"] is None @@ -595,7 +595,7 @@ def test_scoreless_baseline_final_reports_no_speedup_in_the_delivery(project, ca assert main(["campaign", "final", "--directory", str(root), "--reason", "Synthetic unavailable statistics control"]) == 0 view = json.loads(capsys.readouterr().out) - _, state, summary = read_records(root) + _, state, summary = read_session_records(root) assert state["best"]["kind"] == "baseline" assert state["final"]["assessment"]["score"] is None assert summary["optimization_speedup"] is None @@ -624,7 +624,7 @@ def test_strategy_knowledge_refs_and_mechanism_are_kept_together(project, capsys "--knowledge-ref", refs[0], "--knowledge-ref", refs[1], "--mechanism-file", str(declaration)]) == 0 capsys.readouterr() - _, state, _ = read_records(root) # Revalidates the round against its observation. + _, state, _ = read_session_records(root) # Revalidates the round against its observation. record = state["rounds"][0] assert record["strategy"] == "Fuse kernels" and record["knowledge_refs"] == refs assert record["diagnosis_id"] == state["diagnoses"][0]["id"] @@ -642,6 +642,6 @@ def test_strategy_knowledge_refs_and_mechanism_are_kept_together(project, capsys assert main(["campaign", "final", "--directory", str(root), "--reason", "Synthetic search completed"]) == 0 capsys.readouterr() - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["final"]["mechanism"] == FUSION assert state["final"]["assessment"]["explanation"]["status"] == "explained" diff --git a/tests/apps/test_project_optimization.py b/tests/apps/test_project_optimization.py index f4f2887d9..a181c91dc 100644 --- a/tests/apps/test_project_optimization.py +++ b/tests/apps/test_project_optimization.py @@ -10,8 +10,7 @@ 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 inferrsi.harness.manager import read_session_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( @@ -144,13 +143,13 @@ def find_spec(self, fullname, path=None, target=None): raise AssertionError('Ordinary optimization imported ' + fullname) sys.meta_path.insert(0, NoBenchmark()) from inferrsi.apps.cli import main -from inferrsi.harness.optimization import read_records +from inferrsi.harness.manager import read_session_records config = json.loads(sys.stdin.read()) assert main(config['start']) == 0 Path(config['repo'], 'config.json').write_text('{"metric":20}', encoding='utf-8') for command in config['commands']: assert main(command) == 0 -plan, state, summary = read_records(Path(config['root'])) +plan, state, summary = read_session_records(Path(config['root'])) assert not any(name.startswith('benchmark/') for name in plan['runtime_identity']) assert state['final']['assessment']['verdict'] == 'PASS' assert summary['optimization_speedup'] == 2 @@ -198,7 +197,7 @@ def test_project_runs_shared_rounds_and_final_from_retained_multifile_candidate( assert delivery["completion"]["status"] == "completed" assert delivery["outcome"]["kind"] == "improved" assert delivery["acceptance"]["delivery_accepted"] is True - plan, state, summary = read_records(root) + plan, state, summary = read_session_records(root) assert plan["round_mode"] == "up_to" and summary["completed_rounds"] == 1 assert state["final"]["assessment"]["verdict"] == "PASS" assert summary["optimization_speedup"] == 2 @@ -279,7 +278,7 @@ def test_dashboard_rejects_identical_bytes_when_earlier_round_remains_best( assert submit(project, capsys, 20)[0] == 0 assert submit(project, capsys, 20)[0] == 0 root = project[3] - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) first, second = state["rounds"] assert first["candidate_sha256"] == second["candidate_sha256"] assert second["assessment"]["quality_passed"] is not quality_failed @@ -346,7 +345,7 @@ def unavailable(*args, **kwargs): def test_cannbot_timeout_keeps_local_ranking_and_final_budget(project, capsys, monkeypatch): from inferrsi.apps.integrations.cannbot import project as channel from inferrsi.apps.integrations.cannbot.read_worker import _WORKER_CLEANUP_SECONDS - from inferrsi.harness import optimization + from inferrsi.harness.manager import _state as optimization source, protocol, instructions, root = project (source / ".git").mkdir() @@ -437,11 +436,11 @@ def test_changed_retained_assessment_is_rejected(project, capsys): path = project[3] / view["latest_observation"]["path"] / "observation.json" path.write_text("{}", encoding="utf-8") with pytest.raises(ValueError, match="assessment record changed"): - read_records(project[3]) + read_session_records(project[3]) def test_candidate_directory_identity_includes_new_files(tmp_path): - from inferrsi.harness.candidates import identity, retain + from inferrsi.harness.executor.candidates import identity, retain source = tmp_path / "source" source.mkdir() @@ -454,7 +453,7 @@ def test_candidate_directory_identity_includes_new_files(tmp_path): @pytest.mark.skipif(os.name == "nt", reason="POSIX executable mode") def test_snapshot_preserves_executable_helper_and_binds_its_mode(tmp_path): - from inferrsi.harness.candidates import identity, retain + from inferrsi.harness.executor.candidates import identity, retain source = tmp_path / "source" source.mkdir() @@ -471,30 +470,30 @@ def test_snapshot_preserves_executable_helper_and_binds_its_mode(tmp_path): def test_record_read_verifies_each_distinct_candidate_again_on_next_read(project, capsys): from unittest.mock import patch - from inferrsi.harness import candidates + from inferrsi.harness.executor import candidates start(project, capsys) root = project[3] with patch.object(candidates, "identity", wraps=candidates.identity) as identity: - read_records(root) + read_session_records(root) assert [call.args[0] for call in identity.call_args_list] == [root / "frozen/baseline"] submit(project, capsys, 20) with patch.object(candidates, "identity", wraps=candidates.identity) as identity: - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) selected = root / state["best"]["path"] paths = [call.args[0] for call in identity.call_args_list] assert paths == [root / "frozen/baseline", selected] (selected / "config.json").write_text("{}") with pytest.raises(ValueError, match="Selected candidate changed"): - read_records(root) + read_session_records(root) def test_shared_candidate_path_still_checks_each_recorded_digest(project, capsys): from unittest.mock import patch - from inferrsi.harness import candidates + from inferrsi.harness.executor import candidates start(project, capsys) root = project[3] @@ -506,7 +505,7 @@ def test_shared_candidate_path_still_checks_each_recorded_digest(project, capsys with patch.object(candidates, "identity", wraps=candidates.identity) as identity: with pytest.raises(ValueError, match="Selected candidate changed"): - read_records(root) + read_session_records(root) identity.assert_called_once_with(root / "frozen/baseline") @@ -516,7 +515,7 @@ def test_frozen_input_additions_are_rejected_even_after_candidate_wins(project, submit(project, capsys, 20) (project[3] / "frozen" / relative).write_text("{}", encoding="utf-8") with pytest.raises(ValueError, match="file set"): - read_records(project[3]) + read_session_records(project[3]) def test_bad_candidate_exception_is_classified_by_frozen_wrapper(project, capsys): @@ -544,7 +543,7 @@ def test_bad_candidate_exception_is_classified_by_frozen_wrapper(project, capsys assert main(["campaign", "final", "--directory", str(project[3]), "--reason", "Keep the measured best after a rejected experiment"]) == 0 capsys.readouterr() - _, state, summary = read_records(project[3]) + _, state, summary = read_session_records(project[3]) assert state["final"]["candidate_sha256"] == before["best"]["sha256"] assert summary["final_assessment"]["verdict"] == "PASS" assert failed_record.read_bytes() == failed_bytes @@ -573,7 +572,7 @@ def test_project_cwd_logs_leave_frozen_inputs_usable(project, capsys): capsys.readouterr() assert main(["campaign", "final", "--directory", str(project[3]), "--reason", "Scratch output control complete"]) == 0 - assert read_records(project[3])[2]["optimization_speedup"] == 2 + assert read_session_records(project[3])[2]["optimization_speedup"] == 2 def test_project_execution_copy_source_changes_are_rejected(project, capsys): @@ -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 @@ -621,13 +620,13 @@ def drift(root, *args): main(["campaign", operation, "--directory", str(project[3])]) assert json.loads(capsys.readouterr().out)["state"] == "blocked" with pytest.raises(ValueError, match="file set"): - read_records(project[3]) # Rejected data cannot become a valid report. + read_session_records(project[3]) # Rejected data cannot become a valid report. def test_final_freezes_elapsed_time_and_dashboard_redacts_private_text( project, capsys, monkeypatch, ): - from inferrsi.harness import optimization + from inferrsi.harness.manager import _state as optimization start(project, capsys, extra=("--condition", "token=condition-secret")) repo, _, _, root = project @@ -638,9 +637,9 @@ def test_final_freezes_elapsed_time_and_dashboard_redacts_private_text( assert main(["campaign", "final", "--directory", str(root), "--reason", "token=stop-secret"]) == 0 assert not json.loads(capsys.readouterr().out)["can_finalize"] - original = read_records(root)[2]["wall_elapsed_seconds"] + original = read_session_records(root)[2]["wall_elapsed_seconds"] monkeypatch.setattr(optimization.time, "time", lambda: 10**12) - assert read_records(root)[2]["wall_elapsed_seconds"] == original + assert read_session_records(root)[2]["wall_elapsed_seconds"] == original html = render_dashboard(dashboard_snapshot(root)) for private in ("condition-secret", "hypothesis-secret", "stop-secret", "C:/private/file"): assert private not in html @@ -671,11 +670,11 @@ def test_dashboard_shows_failed_independent_final_separately_from_search( def test_final_reserve_blocks_search_but_allows_final(project, capsys, monkeypatch): - from inferrsi.harness import optimization + from inferrsi.harness.manager import _state as optimization start(project, capsys) submit(project, capsys, 20) - plan, state, _ = read_records(project[3]) + plan, state, _ = read_session_records(project[3]) monkeypatch.setattr(optimization.time, "time", lambda: state["deadline"] - 10) with pytest.raises(SystemExit): submit(project, capsys, 30) @@ -705,7 +704,7 @@ def test_assessment_reports_paired_statistics_without_changing_the_verdict( assert main(["campaign", "final", "--directory", str(project[3]), "--reason", "Synthetic search done"]) == 0 capsys.readouterr() - _, state, summary = read_records(project[3]) + _, state, summary = read_session_records(project[3]) final = state["final"]["assessment"] assert final["verdict"] == "PASS" and summary["optimization_speedup"] == 2 assert final["paired_statistics"]["gate_relation"] == "above_gate" @@ -721,25 +720,25 @@ def test_unreachable_gate_keeps_the_original_fail_and_strict_json_records(projec assert assessment["verdict"] == "FAIL" and assessment["eligible"] is False paired = assessment["paired_statistics"] assert paired["gate_speedup"] is None and paired["gate_relation"] == "gate_unreachable" - json.dumps(read_records(project[3])[1], allow_nan=False) + json.dumps(read_session_records(project[3])[1], allow_nan=False) 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"] - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["best"]["kind"] == "candidate" snapshot = dashboard_snapshot(project[3]) assert snapshot["data"]["candidates"][0]["verdict"] == "PASS" diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index d426601ee..c6bbff567 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -14,7 +14,10 @@ from inferrsi.apps.cli import main from inferrsi.apps.cli.arguments import parser from inferrsi.apps.delivery import project, read_bundle -from inferrsi.harness import optimization, project_service +from inferrsi.harness import executor, manager +from inferrsi.harness.executor.serving import _attempt +from inferrsi.harness.manager import _state as optimization +from inferrsi.harness.records import service_io from tests.fixtures.service_reuse import begin, call, commit, diagnose, rejected, settings, submit from tests.fixtures.service_reuse import campaign as campaign from tests.fixtures.service_reuse import no_fingerprints as no_fingerprints @@ -61,7 +64,7 @@ def test_diagnosis_gate_applies_to_service_knowledge(campaign, tmp_path): state["contexts"][0]["diagnosis_id"] = new["diagnosis"]["id"] state_path.write_text(json.dumps(state), encoding="utf-8") with pytest.raises(ValueError, match="Knowledge diagnosis differs from the retained capture"): - optimization.read_records(campaign["root"]) + optimization.read_session_records(campaign["root"]) def events(campaign, attempt): @@ -69,6 +72,28 @@ def events(campaign, attempt): return [json.loads(line) for line in path.read_text().splitlines()] +def test_manager_baseline_and_cli_status_share_one_service_attempt(campaign, monkeypatch): + from inferrsi.knowledge.ranking_policy import managed_ranking_policy + + call(campaign, "start") + root = campaign["root"] + ports = {"ranking_policy_for": managed_ranking_policy, + "assess_packaged": executor.assess_packaged_task} + measured = manager.run_session(manager.BaselineSession(session=root), **ports) + attempt = measured["latest_observation"] + assert attempt["kind"] == "baseline" and attempt["assessment"]["verdict"] == "PASS" + retained_events = events(campaign, attempt) + instant = time.time() + monkeypatch.setattr(optimization, "time", SimpleNamespace(time=lambda: instant)) + direct = manager.run_session(manager.SessionStatus(session=root), **ports) + assert direct == call(campaign, "status") + assert direct["latest_observation"] == attempt + assert direct["allocated_rounds"] == 0 + _, state, _ = manager.read_session_records(root) + assert [record["attempt_id"] for record in state["attempts"]] == [attempt["attempt_id"]] + assert events(campaign, attempt) == retained_events + + def test_one_service_order_and_independent_final_ignores_workspace(campaign): begin(campaign) result = submit(campaign, version="accepted", a=95, b=102) @@ -88,14 +113,14 @@ def test_one_service_order_and_independent_final_ignores_workspace(campaign): assert attempt["execution"]["cleanup_verified"] is True profile = attempt["execution"]["profile"] for relative in [profile["result"], *profile["artifacts"]]: - assert project_service.safe_path(campaign["root"], relative).is_file() + assert service_io.safe_path(campaign["root"], relative).is_file() (campaign["repo"] / "engine.py").write_text("raise RuntimeError('unsubmitted workspace')") final = call(campaign, "final", "--reason", "Synthetic search complete") assert final["state"] == "completed" assert final["final"]["assessment"]["verdict"] == "PASS" assert {row["version"] for row in events(campaign, final["final"])} == {"accepted"} assert "profile" not in [row["stage"] for row in events(campaign, final["final"])] - project_service.no_fingerprints(optimization.read_records(campaign["root"])[2]) + service_io.no_fingerprints(optimization.read_session_records(campaign["root"])[2]) assert call(campaign, "status")["state"] == "completed" # Call the projection directly so schema errors are visible before CLI redaction. project(campaign["root"], export_id="service-projection") @@ -157,7 +182,7 @@ def test_continue_after_failed_final_retains_each_final(campaign, second_verdict original_bytes = first_receipt.read_bytes() original_export = Path(first_result["delivery"]["output"]) plan = (root / "plan.json").read_bytes() - deadline = project_service.read(root / "state.json")["deadline"] + deadline = service_io.read(root / "state.json")["deadline"] assert first_result["can_continue"] is True assert first_result["next_action"] == "continue_search_after_failed_final" @@ -187,11 +212,11 @@ def test_continue_after_failed_final_retains_each_final(campaign, second_verdict assert result["final"]["attempt_id"] == selected["attempt_id"] assert result["can_continue"] is False assert (root / "plan.json").read_bytes() == plan - assert project_service.read(root / "state.json")["deadline"] == deadline + assert service_io.read(root / "state.json")["deadline"] == deadline assert first_receipt.read_bytes() == original_bytes status = call(campaign, "status", expected=0 if second_verdict == "PASS" else 2) - summary = project_service.read(root / "summary.json") + summary = service_io.read(root / "summary.json") dashboard = dashboard_snapshot(root) history = status["final_attempts"] for document in (summary, dashboard["data"]["service_optimization"]): @@ -239,9 +264,9 @@ def test_continuation_admission_preserves_state_on_refusal(campaign, monkeypatch campaign["start"][campaign["start"].index("--rounds") + 1] = "1" failed = _failed_final(campaign, opt_in=barrier != "disabled")["final"] root = campaign["root"] - state = project_service.read(root / "state.json") + state = service_io.read(root / "state.json") if barrier == "time": - reserve = project_service.read(root / "plan.json")["final_reserve_seconds"] + reserve = service_io.read(root / "plan.json")["final_reserve_seconds"] now = optimization._service_deadline(state) - reserve monkeypatch.setattr(optimization, "time", SimpleNamespace(time=lambda: now)) args = _continue_args(campaign, failed) @@ -251,7 +276,7 @@ def test_continuation_admission_preserves_state_on_refusal(campaign, monkeypatch args[-1] = " " directories = list(root.glob("rounds/*/attempt-*")) assert rejected(args) == 2 - assert project_service.read(root / "state.json") == state + assert service_io.read(root / "state.json") == state assert list(root.glob("rounds/*/attempt-*")) == directories status = call(campaign, "status") assert status["can_continue"] is (barrier in ("identity", "reason")) @@ -318,13 +343,13 @@ def interrupted(*args): patch.setattr(optimization, "_service_execute", interrupted) with pytest.raises(Interrupted): main(args) - state = project_service.read(root / "state.json") + state = service_io.read(root / "state.json") pending = state["pending"] assert pending["round_number"] == 2 assert pending["continuation"]["after_final"] == first["attempt_id"] assert not (root / pending["path"] / "request.json").exists() assert rejected(args) == 2 - assert project_service.read(root / "state.json") == state + assert service_io.read(root / "state.json") == state assert read_bundle(Path(first_result["delivery"]["output"]))["acceptance"]["verdict"] == "FAIL" cleanup = root.parent / "cleanup.json" @@ -339,10 +364,10 @@ def interrupted(*args): assert recovered["latest_observation"]["attempt_id"] == pending["attempt_id"] assert recovered["latest_observation"]["assessment"]["verdict"] == "INCONCLUSIVE" assert recovered["final"]["attempt_id"] == first["attempt_id"] - settled = project_service.read(root / "state.json") + settled = service_io.read(root / "state.json") assert settled["deadline"] == state["deadline"] assert rejected(args) == 2 - assert project_service.read(root / "state.json") == settled + assert service_io.read(root / "state.json") == settled @pytest.mark.parametrize("failure", ["failed", "missing", "empty"]) @@ -412,7 +437,7 @@ def test_stagnation_is_advisory_and_recover_does_not_retrigger(campaign): assert result["state"] == "active" event, = result["stagnation"]["events"] assert event["best"]["profile"] == best["profile"] - stored, = project_service.read(campaign["root"] / "state.json")["stagnation"]["events"] + stored, = service_io.read(campaign["root"] / "state.json")["stagnation"]["events"] assert stored["best"]["attempt_id"] == best["attempt_id"] and "profile" not in stored["best"] recovered = call(campaign, "recover") assert recovered["stagnation"] == result["stagnation"] @@ -456,7 +481,7 @@ def test_service_knowledge_uses_find_without_file_fingerprints(campaign): assert context["ref"].startswith("package:") path = campaign["root"] / response["reference"]["path"] assert json.loads(path.read_bytes()) == retained - project_service.no_fingerprints(response) + service_io.no_fingerprints(response) def test_knowledge_and_dashboard_never_enter_legacy_fingerprint_readers(campaign): @@ -465,7 +490,7 @@ def test_knowledge_and_dashboard_never_enter_legacy_fingerprint_readers(campaign campaign, "knowledge", "--query", "optimization", "--context-bytes", "65536", "--limit", "1" ) assert context["context"]["contexts"] - project_service.no_fingerprints(context) + service_io.no_fingerprints(context) submit(campaign, version="selected", a=90) from inferrsi.apps.views.dashboard import ( dashboard_snapshot, @@ -474,7 +499,7 @@ def test_knowledge_and_dashboard_never_enter_legacy_fingerprint_readers(campaign ) snapshot = dashboard_snapshot(campaign["root"]) - project_service.no_fingerprints(snapshot) + service_io.no_fingerprints(snapshot) page = render_dashboard(snapshot) assert "Service-reuse optimization" in page and "Objective values" in page assert "sha256" not in page.lower() @@ -536,7 +561,7 @@ def test_profile_timeout_retains_quality_and_stops_without_silent_retry(campaign def test_profile_interruption_retains_verdict_with_verified_cleanup(campaign, monkeypatch): - from inferrsi.harness.trials import external + from inferrsi.harness.executor.trials import external begin(campaign) original = external.execute_trial @@ -679,7 +704,7 @@ def test_recover_commits_existing_observation_once_without_remeasurement( ): begin(campaign) selected = submit(campaign, version="previous-selection", a=95)["best"] - previous = project_service.read( + previous = service_io.read( campaign["root"] / selected["path"].removesuffix("/candidate") / "observation.json" ) original = optimization.atomic_write_json @@ -709,9 +734,9 @@ def fail_state_commit(path, data): ) campaign["capsys"].readouterr() monkeypatch.setattr(optimization, "atomic_write_json", original) - pending = project_service.read(campaign["root"] / "state.json")["pending"] + pending = service_io.read(campaign["root"] / "state.json")["pending"] observation_path = campaign["root"] / pending["path"] / "observation.json" - observation = project_service.read(observation_path) + observation = service_io.read(observation_path) profile = observation["execution"]["profile"] artifact = campaign["root"] / profile["artifacts"][0] if damage == "missing": @@ -723,7 +748,7 @@ def fail_state_commit(path, data): elif damage == "binding": profile["binding"]["service_id"] = "another-service" receipt_path = campaign["root"] / profile["result"] - receipt = project_service.read(receipt_path) + receipt = service_io.read(receipt_path) receipt["binding"] = profile["binding"] receipt_path.write_text(json.dumps(receipt)) observation_path.write_text(json.dumps(observation)) @@ -741,7 +766,7 @@ def fail_state_commit(path, data): assert attempt["profiling"]["available"] is (damage is None) if damage: assert attempt["profiling"] == {"available": False} - assert project_service.read( + assert service_io.read( campaign["root"] / previous["path"] / "observation.json" ) == previous again = call(campaign, "recover") @@ -756,7 +781,7 @@ def test_final_rechecks_selected_evidence_before_settlement( ): begin(campaign) selected = submit(campaign, version="selected", a=90)["best"] - selected_attempt = project_service.read( + selected_attempt = service_io.read( campaign["root"] / selected["path"].removesuffix("/candidate") / "observation.json" ) expected = 2 if damage == "configuration" else 0 @@ -788,8 +813,8 @@ def fail_state_commit(path, data): ) == 2 campaign["capsys"].readouterr() monkeypatch.setattr(optimization, "atomic_write_json", write) - pending = project_service.read(campaign["root"] / "state.json")["pending"] - assert project_service.read( + pending = service_io.read(campaign["root"] / "state.json")["pending"] + assert service_io.read( campaign["root"] / pending["path"] / "observation.json" )["assessment"]["verdict"] == "PASS" damage_evidence() @@ -807,7 +832,7 @@ def fail_state_commit(path, data): assert result["state"] == "completed" assert final["assessment"]["verdict"] == "PASS" assert final["execution"]["assessment"]["verdict"] == "PASS" - assert project_service.read( + assert service_io.read( campaign["root"] / selected_attempt["path"] / "observation.json" ) == selected_attempt log = events(campaign, final) @@ -854,7 +879,7 @@ def test_live_dashboard_state_has_no_content_fingerprint(campaign): try: with urlopen(f"http://127.0.0.1:{server.server_port}/api/state") as response: assert response.status == 200 and response.headers.get("ETag") is None - project_service.no_fingerprints(json.load(response)) + service_io.no_fingerprints(json.load(response)) with urlopen(f"http://127.0.0.1:{server.server_port}/") as response: assert b"Service-reuse optimization" in response.read() finally: @@ -1042,11 +1067,11 @@ def test_round_usage_export_is_retained_without_fingerprint(campaign): "--usage-export", export, ) - summary = optimization.read_records(campaign["root"])[2] + summary = optimization.read_session_records(campaign["root"])[2] assert summary["usage"]["total_tokens"] == 12 assert result["latest_observation"]["observations"]["usage_source"] == {"kind": "caller_export"} call(campaign, "recover") - assert optimization.read_records(campaign["root"])[2]["usage"]["total_tokens"] == 12 + assert optimization.read_session_records(campaign["root"])[2]["usage"]["total_tokens"] == 12 def test_exact_round_policy_and_legacy_argument_validation(campaign): @@ -1056,11 +1081,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"], @@ -1220,7 +1245,7 @@ def test_tree_snapshot_rejects_missing_or_special_declared_input(campaign, inval ).strip() destination = repo.parent / "snapshot" with pytest.raises(ValueError, match="missing|symbolic"): - project_service.retain_revision(repo, destination, ["engine.py", invalid], revision) + executor.retain_service_revision(repo, destination, ["engine.py", invalid], revision) assert not destination.exists() @@ -1235,19 +1260,19 @@ def test_revision_rejects_deleted_files_inside_declared_directory(campaign, stag deleted.write_text("delete") subprocess.run(["git", "-C", str(repo), "add", "inputs"], check=True) commit(repo) - project_service.revision(repo, includes) + executor.service_revision(repo, includes) deleted.unlink() if staged: subprocess.run(["git", "-C", str(repo), "add", "-u"], check=True) with pytest.raises(ValueError, match="Commit declared candidate inputs"): - project_service.revision(repo, includes) + executor.service_revision(repo, includes) subprocess.run(["git", "-C", str(repo), "add", "-u"], check=True) commit(repo) - revision = project_service.revision(repo, includes) + revision = executor.service_revision(repo, includes) destination = repo.parent / "snapshot" - project_service.retain_revision(repo, destination, includes, revision) + executor.retain_service_revision(repo, destination, includes, revision) assert (destination / "inputs/keep.txt").read_text() == "keep" assert not (destination / "inputs/delete.txt").exists() @@ -1259,16 +1284,16 @@ def test_revision_ignores_untracked_cache_but_rejects_untracked_input(campaign): (inputs / "keep.txt").write_text("keep") subprocess.run(["git", "-C", str(repo), "add", "inputs"], check=True) commit(repo) - revision = project_service.revision(repo, ["inputs"]) + revision = executor.service_revision(repo, ["inputs"]) cache = inputs / "__pycache__" cache.mkdir() (cache / "entry").touch() - assert project_service.revision(repo, ["inputs"]) == revision + assert executor.service_revision(repo, ["inputs"]) == revision (inputs / "new.txt").touch() with pytest.raises(ValueError, match="Commit declared candidate inputs"): - project_service.revision(repo, ["inputs"]) + executor.service_revision(repo, ["inputs"]) def test_revision_ignores_deletions_outside_declared_inputs(campaign): @@ -1278,9 +1303,9 @@ def test_revision_ignores_deletions_outside_declared_inputs(campaign): (inputs / "keep.txt").write_text("keep") subprocess.run(["git", "-C", str(repo), "add", "inputs"], check=True) commit(repo) - revision = project_service.revision(repo, ["inputs"]) + revision = executor.service_revision(repo, ["inputs"]) (repo / "engine.py").unlink() - assert project_service.revision(repo, ["inputs"]) == revision + assert executor.service_revision(repo, ["inputs"]) == revision @pytest.mark.parametrize("rejections", [1, 2]) @@ -1309,7 +1334,7 @@ def test_refresh_without_round_capacity_preserves_finalizable_state(campaign, ro campaign["start"] += ["--round-mode", round_mode] begin(campaign) submit(campaign, version="selected", a=90) - before = project_service.read(campaign["root"] / "state.json") + before = service_io.read(campaign["root"] / "state.json") conditions = {**settings()["conditions"], "id": "new-conditions"} path = campaign["root"].parent / "conditions.json" path.write_text(json.dumps(conditions)) @@ -1320,7 +1345,7 @@ def test_refresh_without_round_capacity_preserves_finalizable_state(campaign, ro assert "No round budget for current-conditions acceptance" in ( campaign["capsys"].readouterr().err ) - assert project_service.read(campaign["root"] / "state.json") == before + assert service_io.read(campaign["root"] / "state.json") == before assert not (campaign["root"] / "references").exists() result = call(campaign, "final", "--reason", "Complete original conditions") assert result["final"]["assessment"]["verdict"] == "PASS" @@ -1328,14 +1353,14 @@ def test_refresh_without_round_capacity_preserves_finalizable_state(campaign, ro def test_backfill_after_final_preserves_original_evidence_and_selection(campaign, monkeypatch): from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard - from inferrsi.harness.trials import external + from inferrsi.harness.executor.trials import external baseline = begin(campaign)["best"] attempt = submit(campaign, version="selected", a=90)["latest_observation"] inline = attempt["execution"]["profile"] root = campaign["root"] - state = project_service.read(root / "state.json") - observation = project_service.read(root / attempt["path"] / "observation.json") + state = service_io.read(root / "state.json") + observation = service_io.read(root / attempt["path"] / "observation.json") for choice in (state["best"], state["comparison_parent"], observation["best_after"]): assert choice["attempt_id"] == attempt["attempt_id"] assert "profile" not in choice @@ -1352,14 +1377,14 @@ def test_backfill_after_final_preserves_original_evidence_and_selection(campaign final = call(campaign, "final", "--reason", "Search complete") original_files.append(root / final["final"]["path"] / "observation.json") originals = {p: p.read_bytes() for p in original_files} - usage = optimization.read_records(root)[2]["usage"] + usage = optimization.read_session_records(root)[2]["usage"] published = call(campaign, "profile", "--round", "1") assert published["target_attempt_id"] == attempt["attempt_id"] profile = published["profiling"] assert profile["available"] and profile["result"] != inline["result"] assert all((root / path).is_file() for path in [profile["result"], *profile["artifacts"]]) - binding = project_service.read(root / profile["result"])["binding"] + binding = service_io.read(root / profile["result"])["binding"] for key in ("revision", "conditions", "effective_config"): assert binding[key] == inline["binding"][key] for key in ("service_id", "run_id"): @@ -1412,7 +1437,7 @@ def interrupt_capture(command, *args, **kwargs): assert status["best"] == final["best"] and status["final"] == final["final"] assert status["best"]["profile"] == inline assert status["allocated_rounds"] == final["allocated_rounds"] - _, state_view, summary = optimization.read_records(root) + _, state_view, summary = optimization.read_session_records(root) assert state_view["best"] == status["best"] assert summary["usage"] == usage current = next(r for r in summary["attempts"] if r["attempt_id"] == attempt["attempt_id"]) @@ -1431,7 +1456,7 @@ def test_backfill_targets_last_terminal_retry_after_deadline(campaign, monkeypat result = submit(campaign, version="rejected", a=110, retry=old["attempt_id"]) settled = result["latest_observation"] assert settled["assessment"]["verdict"] == "FAIL" - state = project_service.read(root / "state.json") + state = service_io.read(root / "state.json") monkeypatch.setattr(optimization, "time", SimpleNamespace(time=lambda: state["deadline"] + 300)) assert call(campaign, "status")["remaining_seconds"] == 0 with optimization._locked(root): @@ -1453,11 +1478,11 @@ def test_legacy_round_availability_is_derived_without_changing_history(campaign, attempt = submit(campaign, version="old", a=90)["latest_observation"] root = campaign["root"] state_path = root / "state.json" - state = project_service.read(state_path) + state = service_io.read(state_path) historical = next(a for a in state["attempts"] if a["attempt_id"] == attempt["attempt_id"]) historical.pop("profiling", None) profile = historical["execution"]["profile"] - trace = project_service.read(root / profile["result"]) + trace = service_io.read(root / profile["result"]) profile.pop("capture_started_at") profile.pop("capture_ended_at") profile["receipt"] = trace @@ -1473,7 +1498,7 @@ def test_legacy_round_availability_is_derived_without_changing_history(campaign, obs = root / attempt["path"] / "observation.json" obs.write_text(json.dumps(historical)) old_bytes = obs.read_bytes() - plan = project_service.read(root / "plan.json") + plan = service_io.read(root / "plan.json") plan["runtime_version"] = "older-release" (root / "plan.json").write_text(json.dumps(plan)) status = call(campaign, "status") @@ -1496,7 +1521,9 @@ def test_legacy_round_availability_is_derived_without_changing_history(campaign, ) assert obs.read_bytes() == old_bytes if damage is None: - final = SimpleNamespace(session_action="final", reason="done") + from inferrsi.harness.manager import FinalizeSession + + final = FinalizeSession(session=root, reason="done") with pytest.raises(ValueError, match="Runtime package version changed"): optimization.service_command(root, final) @@ -1538,9 +1565,9 @@ class CoordinatorCrash(BaseException): begin(campaign) root = campaign["root"] - initial = project_service.read(root / "state.json") - plan = project_service.read(root / "plan.json") - original_write = project_service.atomic_write_json + initial = service_io.read(root / "state.json") + plan = service_io.read(root / "plan.json") + original_write = _attempt.atomic_write_json frozen = {} def stop_after_durable_boundary(path, document): @@ -1561,16 +1588,16 @@ def stop_after_durable_boundary(path, document): raise CoordinatorCrash() with monkeypatch.context() as m: - m.setattr(project_service, "atomic_write_json", stop_after_durable_boundary) + m.setattr(_attempt, "atomic_write_json", stop_after_durable_boundary) with pytest.raises(CoordinatorCrash): submit(campaign, version="interrupted", a=latency) - state = project_service.read(root / "state.json") + state = service_io.read(root / "state.json") pending = state["pending"] - retained = project_service.read(frozen["path"]) + retained = service_io.read(frozen["path"]) checkpoint = retained["checkpoint"] assert checkpoint["assessment"]["verdict"] == verdict - assert checkpoint["binding"] == project_service.read(root / pending["path"] / "request.json") + assert checkpoint["binding"] == service_io.read(root / pending["path"] / "request.json") assert checkpoint["measurements"]["values"]["a"] == latency assert checkpoint["quality_score"] == (1 if verdict == "PASS" else None) before_events = events(campaign, pending) @@ -1580,8 +1607,13 @@ def stop_after_durable_boundary(path, document): # The test leaves the managed service context so a real process never leaks. # Recovery must still require the operator's proof for the interrupted receipt. + check_proofs = boundary == "checkpoint" and verdict == "FAIL" + if check_proofs: + original = {p: p.read_bytes() for p in root.rglob("*") if p.is_file()} assert rejected(["campaign", "recover", "--session", str(root)]) == 2 campaign["capsys"].readouterr() + if check_proofs: + assert {p: p.read_bytes() for p in root.rglob("*") if p.is_file()} == original if boundary == "start": denied = call(campaign, "profile", "--round", "1", expected=2) assert "cleanup" in denied["profiling_error"]["message"].lower() @@ -1590,17 +1622,37 @@ def stop_after_durable_boundary(path, document): "--hypothesis", "Unresolved prior cleanup", ]) == 2 campaign["capsys"].readouterr() - assert project_service.read(root / "state.json")["pending"] == pending - owner = project_service.read(root / pending["path"] / "service/owner.json") + assert service_io.read(root / "state.json")["pending"] == pending + owner = service_io.read(root / pending["path"] / "service/owner.json") now = time.time() + 120 monkeypatch.setattr(optimization, "time", SimpleNamespace(time=lambda: now)) inspection = root.parent / "cleanup.json" - inspection.write_text(json.dumps({ + proof = { "attempt_id": pending["attempt_id"], "observed_at": now, "reason": "Inspected owner", "cleanup_complete": True, "services": [{ "service_id": owner["service_id"], "pid": owner["pid"], "domain_empty": True, }], - })) + } + if check_proofs: + baseline = next(row for row in state["attempts"] if row["kind"] == "baseline") + other = service_io.read(root / baseline["path"] / "service/owner.json") + assert baseline["attempt_id"] != pending["attempt_id"] + assert other["service_id"] != owner["service_id"] + other_service = [ + {"service_id": other["service_id"], "pid": other["pid"], "domain_empty": True} + ] + for invalid in ( + {**proof, "attempt_id": baseline["attempt_id"], "services": other_service}, + {**proof, "services": other_service}, + {**proof, "attempt_id": baseline["attempt_id"]}, + ): + inspection.write_text(json.dumps(invalid)) + assert rejected([ + "campaign", "recover", "--session", str(root), "--cleanup-receipt", str(inspection) + ]) == 2 + assert "cleanup" in campaign["capsys"].readouterr().err.lower() + assert {p: p.read_bytes() for p in root.rglob("*") if p.is_file()} == original + inspection.write_text(json.dumps(proof)) first = call(campaign, "recover", "--cleanup-receipt", inspection) assert first["profiling_error"]["status"] == "interrupted" attempt = first["latest_observation"] @@ -1615,25 +1667,25 @@ def stop_after_durable_boundary(path, document): result["remaining_seconds"] - plan["final_reserve_seconds"] ) assert result["latest_observation"]["assessment"] == checkpoint["assessment"] - ledger = project_service.read(root / "state.json").get("profiling_accounting", {}) + ledger = service_io.read(root / "state.json").get("profiling_accounting", {}) if boundary == "checkpoint": assert ledger == {} else: assert set(ledger) == {retained["capture"]["id"]} assert ledger[retained["capture"]["id"]]["elapsed_seconds"] == credited assert (credited > 0) is (boundary == "progress") - assert project_service.read(root / "plan.json")["final_reserve_seconds"] == 30 + assert service_io.read(root / "plan.json")["final_reserve_seconds"] == 30 assert events(campaign, pending) == before_events def advance_clock_during_profile(monkeypatch, seconds): - from inferrsi.harness.trials import external + from inferrsi.harness.executor.trials import external wall_offset = 0 clock = SimpleNamespace( time=lambda: time.time() + wall_offset, monotonic=lambda: time.monotonic() + wall_offset, ) - monkeypatch.setattr(project_service, "time", clock) + monkeypatch.setattr(_attempt, "time", clock) monkeypatch.setattr(optimization, "time", clock) original = external.execute_trial evaluation_limits = [] @@ -1662,9 +1714,9 @@ def test_effective_deadline_after_profiling_crosses_original_wall_deadline(campa assert first["latest_observation"]["assessment"]["verdict"] == "PASS" assert first["latest_observation"]["profiling"]["available"] assert first["latest_observation"]["elapsed_seconds"] >= 620 - state = project_service.read(root / "state.json") + state = service_io.read(root / "state.json") assert clock.time() > state["deadline"] - assert optimization.read_records(root)[2]["wall_elapsed_seconds"] >= 620 + assert optimization.read_session_records(root)[2]["wall_elapsed_seconds"] >= 620 status = call(campaign, "status") assert 0 < status["remaining_search_seconds"] < status["remaining_seconds"] assert status["remaining_seconds"] - status["remaining_search_seconds"] == pytest.approx(30) @@ -1675,7 +1727,7 @@ def test_effective_deadline_after_profiling_crosses_original_wall_deadline(campa assert final["final"]["assessment"]["verdict"] == "PASS" # Both repetitions of the new candidate and both repetitions of final have a live stage budget. assert len(evaluation_limits) == 4 and all(0 < limit <= 8 for limit in evaluation_limits) - reserve = project_service.read(root / "plan.json")["final_reserve_seconds"] + reserve = service_io.read(root / "plan.json")["final_reserve_seconds"] assert reserve == 30 @@ -1700,11 +1752,11 @@ def test_standalone_capture_leaves_search_budget_and_reserve_intact(campaign, mo assert attempt["profiling"] == {"available": False} root = campaign["root"] before = call(campaign, "status") - original = project_service.read(root / "state.json") + original = service_io.read(root / "state.json") clock, measurements = advance_clock_during_profile(monkeypatch, 60) result = call(campaign, "profile", "--round", "1") assert result["profiling"]["available"] and measurements == [] - state = project_service.read(root / "state.json") + state = service_io.read(root / "state.json") capture = state["profiling_accounting"][result["capture_id"]] assert capture["elapsed_seconds"] >= 60 assert state["deadline"] == original["deadline"] @@ -1716,7 +1768,7 @@ def test_standalone_capture_leaves_search_budget_and_reserve_intact(campaign, mo assert after["remaining_seconds"] - after["remaining_search_seconds"] == pytest.approx(30) assert after["allocated_rounds"] == before["allocated_rounds"] assert after["best"] == before["best"] and after["can_finalize"] - assert project_service.read(root / "plan.json")["final_reserve_seconds"] == 30 + assert service_io.read(root / "plan.json")["final_reserve_seconds"] == 30 @pytest.mark.parametrize("switch", [["--decision", "paired"], ["--require-explanation"]]) diff --git a/tests/apps/test_result_delivery.py b/tests/apps/test_result_delivery.py index 34e490929..f7e260cea 100644 --- a/tests/apps/test_result_delivery.py +++ b/tests/apps/test_result_delivery.py @@ -13,7 +13,7 @@ from inferrsi.apps.storage import archive from inferrsi.apps.storage.artifacts import atomic_write_json, sha256 from inferrsi.apps.storage.result import preparation_result -from inferrsi.harness import optimization +from inferrsi.harness.manager import _state as optimization from tests.fixtures.diagnosis import diagnosis_evidence @@ -233,7 +233,7 @@ def test_damaged_evidence_does_not_rewrite_history_or_accept_different_code(tmp_ assert result["completion"]["status"] == "completed" assert "Current gaps" in (output / "report.md").read_text() with pytest.raises((ValueError, FileNotFoundError)): - optimization.read_records(root) # Normal execution reader remains strict. + optimization.read_session_records(root) # Normal execution reader remains strict. @pytest.mark.parametrize("verdict", ["PASS", "FAIL", "INCONCLUSIVE"]) @@ -776,17 +776,17 @@ def test_offline_html_remains_readable_without_scripts_or_network( @pytest.fixture def standalone_native_usage(tmp_path, request): - from inferrsi.harness import agent_sessions + from inferrsi.harness import manager job = tmp_path / "agent-job" frozen_input = tmp_path / "native-task.txt" frozen_input.write_text("Frozen synthetic task", encoding="utf-8") - agent_sessions.prepare(job, prompt="Synthetic Benchmark task", workspace=tmp_path, + manager.prepare_agent_session(job, prompt="Synthetic Benchmark task", workspace=tmp_path, title="Synthetic", max_seconds=600, frozen_inputs=(frozen_input,)) - agent_sessions.dispatch(job) + manager.dispatch_agent_session(job) creation = tmp_path / "creation.json" atomic_write_json(creation, {"synthetic_creation": True}) - agent_sessions.bind(job, host="synthetic", session_id="native-session", receipt=creation) + manager.bind_agent_session(job, host="synthetic", session_id="native-session", receipt=creation) root = make_campaign(tmp_path, benchmark=True, usage=True, metrics_policy=getattr(request, "param", None)) control = state(root) @@ -807,11 +807,11 @@ def standalone_native_usage(tmp_path, request): def record_native_usage(job, observation): - from inferrsi.harness import agent_sessions + from inferrsi.harness import manager path = job.parent / "terminal.json" atomic_write_json(path, observation) - agent_sessions.record(job, observation=path) + manager.record_agent_session(job, observation=path) def test_single_benchmark_complete_native_usage_through_export_cli( @@ -893,14 +893,16 @@ def test_single_benchmark_incomplete_or_mismatched_receipt_stays_unknown( observation["state"] = "running" elif fault == "workspace": # A different valid job cannot lend its counters to this campaign. - from inferrsi.harness import agent_sessions + from inferrsi.harness import manager other = tmp_path / "other" other.mkdir() job = tmp_path / "other-job" - agent_sessions.prepare(job, prompt="Other", workspace=other, title="Other", max_seconds=600) - agent_sessions.dispatch(job) - agent_sessions.bind(job, host="synthetic", session_id="native-session", + manager.prepare_agent_session( + job, prompt="Other", workspace=other, title="Other", max_seconds=600 + ) + manager.dispatch_agent_session(job) + manager.bind_agent_session(job, host="synthetic", session_id="native-session", receipt=tmp_path / "creation.json") record_native_usage(job, observation) _, result, _ = delivery.project(root, export_id="incomplete-usage", agent_job=job) @@ -949,33 +951,33 @@ def test_native_job_preserves_unsupported_policy_reason(standalone_native_usage) def test_native_frozen_input_change_after_status_prevents_complete_export( standalone_native_usage, tmp_path, monkeypatch, ): - from inferrsi.harness import agent_sessions + from inferrsi.harness import manager root, job, observation = standalone_native_usage record_native_usage(job, observation) - original = agent_sessions.status + original = manager.agent_session_status def changed_after_read(path): host = original(path) (tmp_path / "native-task.txt").write_text("Changed after status", encoding="utf-8") return host - monkeypatch.setattr(agent_sessions, "status", changed_after_read) + monkeypatch.setattr(manager, "agent_session_status", changed_after_read) output = tmp_path / "changed-native-input" result = delivery.export_bundle(root, output, agent_job=job) assert result["status"] == "error" and not output.exists() def test_progress_without_native_observation_preserves_campaign_usage_source(tmp_path): - from inferrsi.harness import agent_sessions + from inferrsi.harness import manager job = tmp_path / "job" - agent_sessions.prepare(job, prompt="Synthetic", workspace=tmp_path, + manager.prepare_agent_session(job, prompt="Synthetic", workspace=tmp_path, title="Synthetic", max_seconds=600) - agent_sessions.dispatch(job) + manager.dispatch_agent_session(job) receipt = tmp_path / "creation.json" atomic_write_json(receipt, {"synthetic_creation": True}) - agent_sessions.bind(job, host="synthetic", session_id="native-session", receipt=receipt) + manager.bind_agent_session(job, host="synthetic", session_id="native-session", receipt=receipt) root = make_campaign(tmp_path, benchmark=True, usage=True, final=False) _, original, _ = delivery.project(root, export_id="progress-original") _, result, _ = delivery.project(root, export_id="progress-native", agent_job=job) diff --git a/tests/apps/test_search_benchmarks.py b/tests/apps/test_search_benchmarks.py index a17021cd2..11d2e2557 100644 --- a/tests/apps/test_search_benchmarks.py +++ b/tests/apps/test_search_benchmarks.py @@ -13,20 +13,21 @@ 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.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.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 +from inferrsi.harness.manager.search.search_campaign import ( FinalAcceptance, finalize, import_qualified_root, learn, qualify_root, ) -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 inferrsi.harness.manager.search.vats import Search, Settings +from inferrsi.harness.manager.search.work_control import WorkControl +from inferrsi.harness.records import RunStore +from inferrsi.harness.records.artifact_primitives import digest from tests.fixtures.speculative_search import contract @@ -98,11 +99,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 +188,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 +197,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): @@ -187,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), @@ -262,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 2b5b0b61a..1391378ee 100644 --- a/tests/apps/test_session_ranking_policy.py +++ b/tests/apps/test_session_ranking_policy.py @@ -1,18 +1,26 @@ """Exercise frozen ranking through each managed CLI and its real delivery or assessor.""" +import hashlib import json import sys +from dataclasses import replace import pytest +from inferrsi.apps import cli from inferrsi.apps.cli import main -from inferrsi.harness import project_service, task_protocol +from inferrsi.harness.executor import _task_protocol +from inferrsi.harness.manager import _state as optimization +from inferrsi.harness.records import service_io from inferrsi.knowledge import ranking_policy +from inferrsi.knowledge.knowledge_operations import KnowledgeReader from tests.apps import test_optimization_session as benchmark from tests.apps import test_project_optimization as project_cli +from tests.apps.test_optimization_session import session as session from tests.apps.test_optimization_session import task as task from tests.apps.test_project_optimization import project as project from tests.fixtures import service_reuse as service +from tests.fixtures.diagnosis import diagnosis_args from tests.fixtures.service_reuse import campaign as campaign @@ -20,6 +28,229 @@ def read(path): return json.loads(path.read_text(encoding="utf-8")) +@pytest.fixture(params=["ordinary", "service"]) +def managed_session(request): + if request.param == "ordinary": + return request.getfixturevalue("session"), ["benchmarks", "session"] + campaign = request.getfixturevalue("campaign") + service.call(campaign, "start") + service.diagnose(campaign) + return campaign["root"], ["campaign"] + + +def query_knowledge(root, command, capsys): + assert main([*command, "knowledge", "--session", str(root), "--query", "cgroupv2", + "--limit", "1", "--context-bytes", "65536"]) == 0 + return json.loads(capsys.readouterr().out) + + +def session_bytes(root): + return {p.relative_to(root): p.read_bytes() for p in root.rglob("*") if p.is_file()} + + +def test_managed_redelivery_and_two_intentional_queries(managed_session, capsys, monkeypatch): + root, command = managed_session + dispatched = [] + allocate = optimization._knowledge_request + + def dispatch(*args, **kwargs): + ticket = allocate(*args, **kwargs) + dispatched.append(ticket) + return ticket + + monkeypatch.setattr(optimization, "_knowledge_request", dispatch) + first = query_knowledge(root, command, capsys) + second = query_knowledge(root, command, capsys) + a, b = dispatched + assert a.context_id != b.context_id and a.diagnosis_id == b.diagnosis_id + assert first["reference"]["path"] != second["reference"]["path"] + references = read(root / "state.json")["contexts"] + assert [item["path"] for item in references] == [ + f"knowledge/{a.context_id}.json", f"knowledge/{b.context_id}.json", + ] + assert all(item["diagnosis_id"] == a.diagnosis_id for item in references) + if command == ["campaign"]: + assert first["reference"]["prepared_not_consumed"] is True + service_io.no_fingerprints(first) + else: + assert first["reference"]["sha256"] + assert first["context"]["retrieval"]["selection"]["ranking_policy"] == ( + read(root / "plan.json")["ranking_policy"] + ) + before = session_bytes(root) + with optimization._locked(root): + assert optimization._commit_knowledge(root, a, first) == first + conflicting = {**first, "context": {**first["context"], "contexts": []}} + with pytest.raises(ValueError, match="Conflicting knowledge delivery"): + optimization._commit_knowledge(root, a, conflicting) + assert session_bytes(root) == before + + +def test_uncommitted_delivery_must_match_current_diagnosis_and_epoch(managed_session, capsys, + monkeypatch): + root, command = managed_session + pending = [] + + def defer(root, ticket, delivery): + pending.append((ticket, delivery)) + return delivery + + before_dispatch = session_bytes(root) + with monkeypatch.context() as dispatch: + dispatch.setattr(optimization, "_commit_knowledge", defer) + query_knowledge(root, command, capsys) + (ticket, delivery), = pending + assert session_bytes(root) == before_dispatch + assert not read(root / "state.json")["contexts"] + + def refused(request, binding): + candidate = {**delivery, "context": {**delivery["context"], "diagnosis_binding": binding}} + before = session_bytes(root) + with optimization._locked(root): + with pytest.raises(ValueError, match="diagnosis or condition epoch"): + optimization._commit_knowledge(root, request, candidate) + assert session_bytes(root) == before + + refused(ticket, {**ticket.binding, "diagnosis_id": "different-diagnosis"}) + wrong_epoch = replace(ticket, reference_epoch=(ticket.reference_epoch or 0) + 1) + refused(wrong_epoch, wrong_epoch.binding) + + assert main(diagnosis_args(root, *command)) == 0 + latest = json.loads(capsys.readouterr().out)["diagnosis"] + assert latest["reference_epoch"] == ticket.reference_epoch + assert latest["id"] != ticket.diagnosis_id + refused(ticket, ticket.binding) + + +def test_returned_ranking_mismatch_does_not_register_a_delivery(managed_session, capsys, + monkeypatch): + root, command = managed_session + is_service = command == ["campaign"] + method = "collect_service_context" if is_service else "collect" + collect = getattr(KnowledgeReader, method) + + def changed_ranking(*args, **kwargs): + result = collect(*args, **kwargs) + ranking = result["request"] if is_service else result["retrieval"]["selection"] + ranking["ranking_policy"] = {**ranking["ranking_policy"], "version": True} + return result + + monkeypatch.setattr(KnowledgeReader, method, changed_ranking) + before = session_bytes(root) + with pytest.raises(SystemExit) as error: + query_knowledge(root, command, capsys) + assert error.value.code == 2 and "ranking policy" in capsys.readouterr().err.lower() + assert session_bytes(root) == before + + +def test_ordinary_receipt_matches_dispatch_before_retention(session, capsys, monkeypatch): + root = session + command = ["benchmarks", "session"] + prepare = cli.prepare_context + collect = KnowledgeReader.collect + before = session_bytes(root) + directories = {p.relative_to(root) for p in root.rglob("*") if p.is_dir()} + + def reject(): + with pytest.raises(SystemExit) as rejected: + query_knowledge(root, command, capsys) + assert rejected.value.code == 2 and "dispatched request" in capsys.readouterr().err + assert session_bytes(root) == before + assert {p.relative_to(root) for p in root.rglob("*") if p.is_dir()} == directories + + def different_capture(*args, **kwargs): + context = prepare(*args, **kwargs) + context["request"]["relevance"] = "other cue" + return context + + with monkeypatch.context() as callback: + callback.setattr(cli, "prepare_context", different_capture) + reject() + for attr, value in (("relevance", "other cue"), ("query", "other query"), + ("relevance_method", "other method"), ("scenario", "other scenario"), + ("limit", True), ("context_bytes", 1)): + def different_observation(*args, **kwargs): + result = collect(*args, **kwargs) + result["retrieval"]["request"][attr] = value + return result + + with monkeypatch.context() as reader: + reader.setattr(KnowledgeReader, "collect", different_observation) + reject() + + +def test_retry_after_capture_linked_before_state_commit(session, capsys, monkeypatch): + pending = [] + + def defer(root, ticket, delivery): + pending.append((ticket, delivery)) + return delivery + + with monkeypatch.context() as dispatch: + dispatch.setattr(optimization, "_commit_knowledge", defer) + query_knowledge(session, ["benchmarks", "session"], capsys) + (ticket, delivery), = pending + state = session / "state.json" + original = state.read_bytes() + + def interrupt(path, value): + assert path == state + raise OSError("interrupted state write") + + with optimization._locked(session): + with monkeypatch.context() as write: + write.setattr(optimization, "atomic_write_json", interrupt) + with pytest.raises(OSError, match="interrupted state write"): + optimization._commit_knowledge(session, ticket, delivery) + retained = session / delivery["reference"]["path"] + assert hashlib.sha256(retained.read_bytes()).hexdigest() == delivery["reference"]["sha256"] + assert state.read_bytes() == original + assert optimization._commit_knowledge(session, ticket, delivery) == delivery + assert [r["path"] for r in read(state)["contexts"]] == [delivery["reference"]["path"]] + committed = session_bytes(session) + with optimization._locked(session): + assert optimization._commit_knowledge(session, ticket, delivery) == delivery + assert session_bytes(session) == committed + + +def test_service_receipt_must_match_dispatched_query_and_budget(campaign, capsys, monkeypatch): + service.call(campaign, "start") + service.diagnose(campaign) + root = campaign["root"] + args = ["campaign", "knowledge", "--session", str(root), "--query", "cgroupv2", + "--limit", "1", "--context-bytes", "65536"] + collect = KnowledgeReader.collect_service_context + ranking = read(root / "plan.json")["ranking_policy"] + before = session_bytes(root) + + for changes in ({"relevance": "another query"}, {"relevance_method": "other-method"}, + {"limit": 5}, {"context_bytes": 999}, {"limit": True}, + {"context_bytes": 65536.0}): + def different_request(*args, **kwargs): + context = collect(*args, **kwargs) + assert context["request"]["ranking_policy"] == ranking + context["request"].update(changes) + return context + + with monkeypatch.context() as reader: + reader.setattr(KnowledgeReader, "collect_service_context", different_request) + with pytest.raises(SystemExit) as rejected: + main(args) + assert rejected.value.code == 2 + assert "dispatched request" in capsys.readouterr().err + assert session_bytes(root) == before + + for flags in ([], ["--relevance-method", "find-lexical-v1"]): + assert main([*args, *flags]) == 0 + delivered = json.loads(capsys.readouterr().out) + retained = read(root / delivered["reference"]["path"]) + assert retained["request"] == { + "relevance": "cgroupv2", "relevance_method": "find-lexical-v1", + "ranking_policy": ranking, "limit": 1, "context_bytes": 65536, + } + assert len(read(root / "state.json")["contexts"]) == 2 + + @pytest.mark.parametrize("lane", ["abba", "benchmark", "service_reuse"]) def test_managed_policy_binds_delivery_and_guards_resume(lane, request, tmp_path, capsys, monkeypatch): @@ -67,7 +298,7 @@ def test_managed_policy_binds_delivery_and_guards_resume(lane, request, tmp_path assert retained["retrieval"]["selection"]["ranking_policy"] == expected else: assert read(root / "campaign.json")["ranking_policy"] == expected - project_service.no_fingerprints(retained) + service_io.no_fingerprints(retained) def refused_without_writes(): before = {p: p.read_bytes() for p in root.rglob("*") if p.is_file()} @@ -120,7 +351,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 = _task_protocol.run_task_protocol def observe(frozen, source_hash, operation, *, launch_directory=None, **inputs): if operation == "assess": @@ -131,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(task_protocol, "run", observe) + monkeypatch.setattr(_task_protocol, "run_task_protocol", observe) outcomes = [] for name in ("default", "applicability"): root = tmp_path / name diff --git a/tests/apps/test_trial_checks.py b/tests/apps/test_trial_checks.py index 643858461..ecd4b8a45 100644 --- a/tests/apps/test_trial_checks.py +++ b/tests/apps/test_trial_checks.py @@ -13,7 +13,7 @@ from inferrsi.apps.legacy.run import run_experiment from inferrsi.apps.views.summary_chart import SpecError, spec_from_evaluation from inferrsi.contracts import RunSpec -from inferrsi.harness.trials.external import collect_trial_checks +from inferrsi.harness.executor.trials.external import collect_trial_checks def evaluated_pair(checks, side="candidate"): diff --git a/tests/apps/test_yibuapi_runtime.py b/tests/apps/test_yibuapi_runtime.py index 54264d29a..31df4d2e9 100644 --- a/tests/apps/test_yibuapi_runtime.py +++ b/tests/apps/test_yibuapi_runtime.py @@ -9,7 +9,7 @@ from inferrsi.apps.integrations.anthropic import anthropic_agent as agent from inferrsi.apps.storage.artifacts import write_json -from inferrsi.harness import skill_evaluation as harness +from inferrsi.harness.executor import skill_evaluation as harness from tests.apps.test_anthropic_agent import ANSWER, MODEL, SCHEMA_SMALL, read, submit from tests.fixtures.skill_eval_compare_support import DATA from tests.fixtures.skill_eval_pr_support import SimulatedGitHub, approval, setup diff --git a/tests/benchmark/test_benchmark_assessment.py b/tests/benchmark/test_benchmark_assessment.py index 4efe8c365..247610da5 100644 --- a/tests/benchmark/test_benchmark_assessment.py +++ b/tests/benchmark/test_benchmark_assessment.py @@ -19,7 +19,7 @@ from inferrsi.benchmark import assessment from inferrsi.benchmark import preparation as preparation_port from inferrsi.contracts.json_v1 import CanonicalError, decode, encode -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import PublicError from tests.benchmark.test_benchmark_preparation import preparation as preparation ROOT = Path(__file__).resolve().parents[2] diff --git a/tests/benchmark/test_benchmark_compare.py b/tests/benchmark/test_benchmark_compare.py index 7d98552ac..1e77f936b 100644 --- a/tests/benchmark/test_benchmark_compare.py +++ b/tests/benchmark/test_benchmark_compare.py @@ -14,8 +14,8 @@ from inferrsi.apps.cli import main from inferrsi.apps.workflows import benchmark_compare as compare from inferrsi.benchmark import registry -from inferrsi.harness import agent_sessions -from inferrsi.harness.optimization_session import _runtime_identity +from inferrsi.harness import manager +from inferrsi.harness.manager import session_runtime_identity @pytest.fixture @@ -25,7 +25,7 @@ def experiment(tmp_path, monkeypatch, capsys, request): from importlib.resources import files actual = Path(str(files("inferrsi"))) - for name in _runtime_identity(): + for name in session_runtime_identity(): target = source / name target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(actual / name, target) @@ -106,7 +106,7 @@ def finish(experiment, trial, *, factor=2, final=True, model="synthetic-model", session_id = session_id or legacy_session_id or trial if legacy_session_id: suffix = "" if legacy_attempt == 1 else f"-attempt-{legacy_attempt:03d}" - agent_sessions.bind(root / "jobs" / (trial + suffix), host="synthetic", + manager.bind_agent_session(root / "jobs" / (trial + suffix), host="synthetic", session_id=session_id, receipt=receipt) else: operation(experiment, "bind", trial, "--host", "synthetic", "--session-id", session_id, @@ -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]] @@ -349,18 +349,18 @@ def test_new_metrics_missing_tokens_does_not_remove_valid_performance(experiment def test_boolean_child_schema_cannot_upgrade_unknown_tokens(experiment, monkeypatch): - from inferrsi.harness import optimization_session + from inferrsi.harness import manager - original = optimization_session.session_command + original = manager.run_session - def boolean_policy(args, **kwargs): - if args.session_action == "start": + def boolean_policy(request, **kwargs): + if request.action == "start": metadata = kwargs["report_metadata"]["benchmark_metrics"] kwargs["report_metadata"] = {"benchmark_metrics": { **metadata, "metrics_schema_version": True}} - return original(args, **kwargs) + return original(request, **kwargs) - monkeypatch.setattr(optimization_session, "session_command", boolean_policy) + monkeypatch.setattr(manager, "run_session", boolean_policy) trial = experiment[1]["trials"][0]["id"] _, result = finish(experiment, trial, token_coverage=True) assert result["benchmark_metrics"]["token_usage"]["total_tokens"] is None @@ -1086,7 +1086,8 @@ def test_repeated_collect_keeps_first_record_and_refuses_retry(experiment): snapshots = sorted(path.name for path in (root / "collections").iterdir()) # Campaign evidence is lost while the native job still records a terminal session. shutil.rmtree(campaign) - assert agent_sessions.status(root / "jobs" / on)["state"] in agent_sessions.TERMINAL + state = manager.agent_session_status(root / "jobs" / on)["state"] + assert state in manager.AGENT_TERMINAL_STATES again = operation(experiment, "collect", on) # The first record is returned; no snapshot is written and the pointer is unchanged. assert again["already_collected"] is True and again["trial"] == collected diff --git a/tests/benchmark/test_benchmark_cpu_smoke.py b/tests/benchmark/test_benchmark_cpu_smoke.py index ff0105d59..f3f215812 100644 --- a/tests/benchmark/test_benchmark_cpu_smoke.py +++ b/tests/benchmark/test_benchmark_cpu_smoke.py @@ -18,8 +18,11 @@ from inferrsi.benchmark import preparation as prepare_port from inferrsi.benchmark.workers import fixture_worker as worker from inferrsi.contracts.json_v1 import decode -from inferrsi.harness import execution_service, run_store -from inferrsi.harness.api import Harness, LocalCpuTarget +from inferrsi.harness.api import Harness +from inferrsi.harness.executor import LocalCpuTarget +from inferrsi.harness.executor import _execution as execution_service +from inferrsi.harness.records import RunStore +from inferrsi.harness.records import _run_store as run_store from tests.benchmark.test_benchmark_preparation import preparation as preparation ROOT = Path(__file__).resolve().parents[2] @@ -196,7 +199,7 @@ def project(*args, **kwargs): return projector.project(*args, **kwargs) capture = api.EvidenceCapture(project, candidate_role="candidate", report_role="grader") - store = run_store.RunStore(tmp_path / "store", "test") + store = RunStore(tmp_path / "store", "test") target = LocalCpuTarget("fixture-cpu", "1", work_root=tmp_path / "work", module_root=Path(worker.__file__).parent) harness = Harness(store, target, artifact_reader=reader, evidence_capture=capture) diff --git a/tests/benchmark/test_benchmark_operations.py b/tests/benchmark/test_benchmark_operations.py index 4b37cbcfc..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", @@ -113,7 +113,7 @@ def test_application_injects_executor_and_preserves_script_imports(library): (package / "benchmark.py").write_text( "from helper import VALUE\n" "assert VALUE == 42\n" - "assert execute_trial.__module__ == 'inferrsi.harness.trials.external'\n", + "assert execute_trial.__module__ == 'inferrsi.harness.executor.trials.external'\n", encoding="utf-8", ) assert main(["benchmarks", "run", package.name]) == 0 @@ -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") @@ -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/benchmark/test_image_modules.py b/tests/benchmark/test_image_modules.py index 81a5b3557..733067479 100644 --- a/tests/benchmark/test_image_modules.py +++ b/tests/benchmark/test_image_modules.py @@ -10,7 +10,7 @@ from inferrsi.apps.storage.artifacts import sha256 from inferrsi.benchmark.sampling import collect_samples from inferrsi.benchmark.validators.image import ImageQualityGate, compare_images -from inferrsi.harness.serving.image import ImageProtocol +from inferrsi.harness.executor import ImageProtocol def test_image_protocol_and_sample_collection_use_real_http(tmp_path): diff --git a/tests/benchmark/test_moe_benchmark.py b/tests/benchmark/test_moe_benchmark.py index 82495e285..6f45a8f8e 100644 --- a/tests/benchmark/test_moe_benchmark.py +++ b/tests/benchmark/test_moe_benchmark.py @@ -13,7 +13,7 @@ import pytest from inferrsi.benchmark.metrics import read_metric -from inferrsi.harness.trials.external import execute_trial +from inferrsi.harness.executor.trials.external import execute_trial from tests.benchmark.engineering_task_support import load_task_module moe = load_task_module("moe-forward-npu", "benchmark") diff --git a/tests/campaigns/test_qwen21_task.py b/tests/campaigns/test_qwen21_task.py index 31ccc35bb..fa664dcbb 100644 --- a/tests/campaigns/test_qwen21_task.py +++ b/tests/campaigns/test_qwen21_task.py @@ -983,7 +983,7 @@ def test_harness_continues_only_after_attributed_contract_rejection(tmp_path, fa """Round 1 is the real CPU worker and Qwen assessor; later rows are synthetic stand-ins.""" pytest.importorskip("torch") from inferrsi.apps.storage.artifacts import atomic_write_json, sha256 - from inferrsi.harness import optimization + from inferrsi.harness.manager import _state as optimization from tests.diagnosis_support import diagnosis_evidence root = tmp_path / "campaign" diff --git a/tests/campaigns/test_qwen_gvo_diagnostic.py b/tests/campaigns/test_qwen_gvo_diagnostic.py index c17408b43..c5e8e62cb 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") @@ -73,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") @@ -83,7 +93,7 @@ def unexpected_load(*args, **kwargs): "fault", ["verdict", "promotion", "selection", "receipt", "source", "rule", "operation-rule"] ) def test_offline_checker_requires_bound_durable_promotion(tmp_path, fault): - from inferrsi.harness import candidates + from inferrsi.harness.executor import candidates checker = module("validator/check.py") candidate_dir = tmp_path / "winner" diff --git a/tests/contracts/test_contracts_package.py b/tests/contracts/test_contracts_package.py index 6b66632b4..5b2669eb1 100644 --- a/tests/contracts/test_contracts_package.py +++ b/tests/contracts/test_contracts_package.py @@ -10,6 +10,7 @@ import dataclasses import importlib import importlib.util +import inspect import json import os import pickle @@ -25,7 +26,7 @@ from inferrsi.apps.legacy import evaluation as legacy_evaluation from inferrsi.apps.legacy import run as legacy_run from inferrsi.contracts import RunSpec, claim, json_v1, runspec -from inferrsi.harness import runner +from inferrsi.harness.manager import run_experiment SRC = Path(__file__).resolve().parents[2] / "src" ROOT = SRC / "inferrsi" @@ -125,14 +126,15 @@ def test_initializer_reexports_only_runspec_and_there_is_one_class() -> None: assert contracts.RunSpec is runspec.RunSpec is RunSpec assert (RunSpec.__module__, RunSpec.__qualname__) == ("inferrsi.contracts.runspec", "RunSpec") # Every consumer in the tree holds that same class object. - for consumer in (arguments, legacy_evaluation, legacy_run, runner): + for consumer in (arguments, legacy_evaluation, legacy_run): assert consumer.RunSpec is RunSpec, consumer.__name__ + assert inspect.signature(run_experiment).parameters["spec"].annotation is RunSpec -def test_harness_reexports_the_same_verdict_objects() -> None: - assert harness.__all__ == ["Verdict", "parse_verdict"] - assert harness.Verdict is claim.Verdict - assert harness.parse_verdict is claim.parse_verdict +def test_verdict_types_are_available_from_the_claim_contract() -> None: + assert claim.parse_verdict("pass") is claim.Verdict.PASS + assert not hasattr(harness, "Verdict") + assert not hasattr(harness, "parse_verdict") assert claim.Verdict.__module__ == "inferrsi.contracts.claim" diff --git a/tests/fixtures/optimization-session/component-freeze/README.md b/tests/fixtures/optimization-session/component-freeze/README.md new file mode 100644 index 000000000..78309cf35 --- /dev/null +++ b/tests/fixtures/optimization-session/component-freeze/README.md @@ -0,0 +1,77 @@ +# Harness component migration baseline + +These five session archives were produced with the normal wheel from commit `3efb03ea71356786b19b705e53f65267c17d19bf`, after the runtime-closure and explicit continuation changes. They use synthetic CPU workloads. Keep the archives read-only and replay each case in a fresh directory. The [manifest](manifest.json) records the source archive, wheel and sample SHA-256 values, package version, launch receipts, commands and observed results. The [Harness interface diagram](../../../../src/inferrsi/harness/README.md#managed-session-interfaces) describes the component migration. [Frozen source](https://github.com/InferMatrixLab/InferRSI/archive/3efb03ea71356786b19b705e53f65267c17d19bf.zip) · [Migration and acceptance decisions](https://github.com/InferMatrixLab/InferRSI/issues/702) + +| Frozen input | What the old installed CLI did on a copy | +| --- | --- | +| `ordinary-ab-ba.zip` | Recovered one PASS from the retained project execution. The eight original steps cover quality, warmup and two interleaved measurement pairs, in AB then BA order. Recovery started zero new processes. | +| `ordinary-packaged.zip` | Resumed after the arguments child and benchmark completed. Both `benchmarks session recover` and `campaign recover` started exactly one assessment child and committed one PASS. The original candidate ran once. A second recovery started zero processes. Only the active summary's `wall_elapsed_seconds` could change. | +| `service-pending.zip` | Settled the pending second PASS from the saved observation and recorded its existing profiling allowance once. The original deadline persisted. A second recovery left the state and stage logs byte-identical. | +| `service-settled.zip` | Reported the first PASS with zero launches and zero additional ledger entries across two recoveries. | +| `service-cleanup-pending.zip` | The candidate failed formal performance after two measurements. Quality was skipped. Recovery rejected missing or mismatched cleanup evidence with exit 2 and retained the pending round. A match settled the original FAIL once, with zero launches or measurements. | + +`cleanup-proofs.zip` keeps the candidate's cleanup receipt, the real baseline attempt's receipt with its distinct service identity, and two single-field controls. One pairs the candidate attempt ID with the baseline service identity. The other replaces only the candidate attempt ID with the real baseline attempt ID, keeping the service list, PIDs and every other receipt field exactly as in the valid proof. The manifest hashes each receipt separately. Original synthetic paths, process identities and timestamps remain inside the samples because the session contract binds them. The old wheel's original executions and verification runs were on Windows. + +## Reproduce the old-wheel replay + +From a review checkout, build the archived revision in a clean environment. The archive includes the version information used by setuptools-scm. The commands below use a POSIX shell. On Windows, the virtual environment's Python is under `Scripts`. + +```sh +checkout=$(git rev-parse --show-toplevel) +scratch=$(mktemp -d) +cd "$scratch" +python -m venv env +py="$scratch/env/bin/python" +"$py" -m pip wheel --no-deps -w wheels \ + https://github.com/InferMatrixLab/InferRSI/archive/3efb03ea71356786b19b705e53f65267c17d19bf.zip +"$py" -m pip install wheels/inferrsi-*.whl +"$py" "$checkout/tests/repository/check_harness_freeze.py" --wheel wheels/inferrsi-*.whl +``` + +The driver compares the 1,021 installed package files to the supplied wheel, checks every registered repository pack through its reader, and verifies the [38 frozen runtime sources](runtime-sources.json). It opens independent copies outside the checkout, observes child launches and verifies both ordinary command paths. The manifest identifies the original wheel. A rebuilt wheel may have different archive timestamps. The source, version, static fingerprint and installed payload checks still apply. + +Ordinary plans pin the runtime source bytes. A later slice that changes those bytes must check both refusal on old plans and positive recovery on a matching plan. Service-reuse plans pin the package version. P8 and P9 each supply their own normal-wheel version mismatch and version match results, plus a separate same-declared-version test wheel replay against independent copies of these exact samples. Record the actual build, wheel and sample digests in each case. [Recovery acceptance matrix](https://github.com/InferMatrixLab/InferRSI/issues/702#runtime-replay) + +### Reproduce the service migration checks + +Build a normal wheel from the revision under review and install it in a fresh environment. +Use that environment's Python from outside the checkout to run the shared checker. +Each call verifies the installed wheel contents and extracts the archived samples into +a temporary directory. + +```sh +"$py" "$checkout/tests/repository/check_harness_freeze.py" \ + --wheel "$normal_wheel" --service-replay different-version +``` + +For the positive control on the normal wheel, run +`test_delayed_double_recovery_settles_checkpoint_and_only_proven_time` in +`tests/apps/test_project_service_reuse.py` against the installed package. Its live CPU +service creates a checkpoint with the installed version. Missing proof, a different +attempt, and each individual identity mismatch must preserve the pending FAIL. The +matching proof settles that attempt once. + +For the frozen-version control, build the same source archive in a separate directory +with `SETUPTOOLS_SCM_PRETEND_VERSION_FOR_INFERRSI` set to the manifest's +`runtime_version`. Install that wheel in a second environment and use its interpreter for the replay. + +```sh +"$isolated_py" "$checkout/tests/repository/check_harness_freeze.py" \ + --wheel "$isolated_wheel" --normal-wheel "$normal_wheel" --service-replay frozen-version +``` + +The checker compares both wheels' package members byte for byte, allowing the generated +version module to differ, then replays all three archived service sessions. Keep this +test wheel separate from normal build artifacts. + +## Source inventory and related work + +The [inventory](inventory.tsv) lists all 72 tracked paths under `src/inferrsi/harness/` at the freeze, including 64 Python files, the README and seven resource packs. The importer column resolves absolute and relative Python imports. The other columns record standalone dotted names, embedded Python probes, file paths and documentation references. An entry in the reference columns can be historical documentation or a test that enforces a boundary. Split mixed modules by function, and repeat the caller search on each migration head. + +Some dependencies require a symbol-level review when files move. + +- P2 updates the improvement controller fingerprint in `tools/skill_eval_improve.py`. P5 replaces the work-control import of the private RunStore transaction and moves the bounded observation path and JSON helpers to Records. P6 provides the process-group cleanup check used by Manager. +- P5 and P6 update the concrete controller paths in `tools/skill_eval_compare.py` and its tests. The six `NEW_H_ENTRIES` roots and their replacements must resolve in the static graph. Moved roots join the retired import checks. Update the module-layout guide and the four contract path references with the slice that moves the symbol. +- P7 preserves per-step early stopping in ordinary projects. P8 covers inline profiling after the candidate checkpoint, interrupted capture, and standalone profile backfill. P9 updates the installed session probe's entry and action tracking. The public projection namespace `inferrsi.harness.optimization` and historical evidence paths retain their original values. + +The freeze includes the continuation and runtime fingerprint changes. Concurrent work touched the ordinary and service session implementations, Apps campaign assembly and the repository-pack reader. The P1 changes add evidence and the interface diagram. Later slices should check the current file overlap, and use the D007 package-resource location at the commit being tested. [Runtime fingerprint](https://github.com/InferMatrixLab/InferRSI/pull/693) · [Final continuation](https://github.com/InferMatrixLab/InferRSI/pull/705) · [Performance-target feasibility](https://github.com/InferMatrixLab/InferRSI/pull/699) · [Task intake and project evaluation](https://github.com/InferMatrixLab/InferRSI/pull/706) · [Knowledge and Apps changes](https://github.com/InferMatrixLab/InferRSI/pull/709) · [Repository pack relocation](https://github.com/InferMatrixLab/InferRSI/pull/716) diff --git a/tests/fixtures/optimization-session/component-freeze/cleanup-proofs.zip b/tests/fixtures/optimization-session/component-freeze/cleanup-proofs.zip new file mode 100644 index 000000000..88a801852 Binary files /dev/null and b/tests/fixtures/optimization-session/component-freeze/cleanup-proofs.zip differ diff --git a/tests/fixtures/optimization-session/component-freeze/inventory.tsv b/tests/fixtures/optimization-session/component-freeze/inventory.tsv new file mode 100644 index 000000000..69d9fe0ec --- /dev/null +++ b/tests/fixtures/optimization-session/component-freeze/inventory.tsv @@ -0,0 +1,73 @@ +frozen path relative to src/inferrsi/harness migration destination and slice direct Python importers (repository paths) literal dotted references (repository paths) additional embedded code and documentation references (repository paths) +README.md maintained diagram (P1 onwards) - - docs/architecture.md | docs/benchmarks/engineering-benchmarks.md | docs/guides/module-layout.md | evidence/indexer-255-covered-cue-20261030/plan/source-pins.json | evidence/indexer-255-token-v3-20261030/plan/source-pins.json +__init__.py package initialization (P6/P9) tests/contracts/test_contracts_package.py | tests/repository/check_installed.py docs/reviews/pr437-s01-reproduction/reproduce.py | tests/repository/_gate_policy_support.py | tests/repository/check_installed.py | tests/repository/test_target_module_import_gate.py evidence/indexer-255-20261029/results/import-proof-baseline.json | evidence/indexer-255-20261029/results/import-proof-indexer-evidence.json | evidence/indexer-255-covered-cue-20261030/plan/source-pins.json | evidence/indexer-255-token-v3-20261030/plan/pre-semantic-freeze.json | evidence/indexer-255-token-v3-20261030/plan/source-pins.json | evidence/kv-actor-qualification-20261030/results/hosted-41154288295/qualification.json | evidence/kv-actor-qualification-20261030/results/hosted-41182807900/qualification.json | evidence/kv-live-pilot-20261031/plan/plan.json | evidence/kv-live-pilot-20261031/plan/second-attempt-1200/plan.json | evidence/kv-live-pilot-20261031/plan/second-attempt/plan.json +agent_sessions.py manager / executor (P2/P9) src/inferrsi/apps/cli/__init__.py | src/inferrsi/apps/delivery/benchmark_usage.py | src/inferrsi/apps/workflows/benchmark_compare.py | tests/apps/test_agent_sessions.py | tests/apps/test_result_delivery.py | tests/benchmark/test_benchmark_compare.py - - +api.py api (P6) src/inferrsi/apps/cli/evaluate.py | tests/apps/test_apps_evidence_capture.py | tests/apps/test_apps_fixed_cpu_views.py | tests/apps/test_apps_generation_plan.py | tests/benchmark/test_benchmark_cpu_smoke.py | tests/harness/test_harness_entry_verification.py | tests/harness/test_harness_evaluation_replay.py | tests/harness/test_harness_evidence_capture.py | tests/harness/test_harness_execute.py | tests/harness/test_harness_feedback_policy.py | tests/harness/test_harness_generation_lineage.py | tests/harness/test_harness_generation_seal.py | tests/harness/test_harness_prepared_binding.py tests/harness/test_harness_execute.py | tests/repository/_gate_policy_support.py | tests/repository/test_first_wave_isolation_policy.py docs/contracts/apps-evidence-capture.md | docs/guides/module-layout.md | docs/guides/operations.md | tests/apps/test_apps_evaluate_cli.py | tests/apps/test_apps_module_migrations.py +artifact_primitives.py records (P5) evidence/qwen-vats-gvo-910b1-20261124/plan/run.py | src/inferrsi/apps/workflows/benchmark_compare.py | src/inferrsi/apps/workflows/search_benchmarks.py | src/inferrsi/apps/workflows/speculative_search.py | src/inferrsi/harness/agent_sessions.py | src/inferrsi/harness/candidates.py | src/inferrsi/harness/device_lease.py | src/inferrsi/harness/gvo.py | src/inferrsi/harness/launch_records.py | src/inferrsi/harness/optimization.py | src/inferrsi/harness/optimization_session.py | src/inferrsi/harness/parallel_round.py | src/inferrsi/harness/project.py | src/inferrsi/harness/search_adapter.py | src/inferrsi/harness/search_campaign.py | src/inferrsi/harness/search_continuations.py | src/inferrsi/harness/task_protocol.py | src/inferrsi/harness/vats.py | src/inferrsi/harness/work_control.py | tests/apps/test_optimization_session.py | tests/apps/test_project_explanation.py | tests/apps/test_search_benchmarks.py | tests/fixtures/service_reuse.py | tests/harness/test_vats_runtime.py | tests/skill_eval/test_skill_evaluation.py | tools/speculative_skill.py tests/repository/test_artifact_helper_copies.py docs/apps-module-migrations.json | tests/harness/test_service_fingerprint_isolation.py | tests/harness/test_session_lock_across_processes.py +artifact_sandbox.py executor (P5/P6) docs/reviews/pr437-s01-reproduction/reproduce.py | src/inferrsi/apps/workflows/skill_eval_engineering.py | src/inferrsi/harness/skill_evaluation.py | tests/skill_eval/test_skill_eval_engineering.py | tests/skill_eval/test_skill_eval_generation.py | tests/skill_eval/test_skill_eval_local.py | tools/skill_eval_cloud_export.py | tools/skill_eval_cloud_replay.py | tools/skill_eval_compare.py | tools/skill_eval_historical_job.py | tools/skill_eval_local.py | tools/skill_eval_qualify.py docs/reviews/pr437-s01-reproduction/reproduce.py docs/guides/skill-evaluation/local-skill-evaluation.md | docs/guides/skill-evaluation/skill-eval-cloud-replay.md | docs/reviews/pr437-s01-reproduction/PREFLIGHT-ENVIRONMENT.md | docs/reviews/pr437-s01-reproduction/README.md +atomic_json.py records (P5) evidence/qwen-vats-gvo-910b1-20261124/plan/run.py | src/inferrsi/apps/workflows/benchmark_compare.py | src/inferrsi/apps/workflows/search_benchmarks.py | src/inferrsi/apps/workflows/speculative_search.py | src/inferrsi/harness/agent_sessions.py | src/inferrsi/harness/attempt_recovery.py | src/inferrsi/harness/launch_records.py | src/inferrsi/harness/local_process.py | src/inferrsi/harness/optimization.py | src/inferrsi/harness/optimization_session.py | src/inferrsi/harness/project_service.py | src/inferrsi/harness/runner.py | src/inferrsi/harness/search_adapter.py | src/inferrsi/harness/service_backfill.py | src/inferrsi/harness/skill_evaluation.py | src/inferrsi/harness/trials/external.py | tests/harness/test_service_backfill_recovery.py | tests/harness/test_service_profile_diagnostics.py | tests/skill_eval/test_skill_evaluation.py | tools/speculative_skill.py tests/apps/test_legacy_run_split.py | tests/harness/test_harness_execute.py | tests/repository/test_artifact_helper_copies.py docs/apps-module-migrations.json | tests/repository/test_architecture_closed_loop.py | tools/skill_eval_compare.py +attempt_recovery.py manager (P9) src/inferrsi/harness/optimization.py - - +candidates.py executor (P5/P6) evidence/qwen-vats-gvo-910b1-20261124/validator/check.py | src/inferrsi/apps/delivery/snapshot.py | src/inferrsi/apps/workflows/search_benchmarks.py | src/inferrsi/apps/workflows/speculative_search.py | src/inferrsi/harness/optimization.py | src/inferrsi/harness/optimization_session.py | src/inferrsi/harness/project_service.py | src/inferrsi/harness/search_adapter.py | tests/apps/test_project_optimization.py | tests/campaigns/test_qwen_gvo_diagnostic.py | tests/harness/test_speculative_search.py | tools/speculative_skill.py - - +confinement.py executor (P5/P6) src/inferrsi/harness/parallel_round.py | tests/harness/test_confinement.py | tests/harness/test_parallel_round.py | tools/parallel_round.py tests/harness/test_confinement.py - +data/repo_packs/afd_plugin/pack.json resources/repo_packs (separate D007 handoff) src/inferrsi/resources/repository_packs.py (resource reader) - docs/reviews/issue91-afd-plugin-intake.md +data/repo_packs/sglang/pack.json resources/repo_packs (separate D007 handoff) src/inferrsi/resources/repository_packs.py (resource reader) - - +data/repo_packs/sglang_omni/pack.json resources/repo_packs (separate D007 handoff) src/inferrsi/resources/repository_packs.py (resource reader) - - +data/repo_packs/strata/pack.json resources/repo_packs (separate D007 handoff) src/inferrsi/resources/repository_packs.py (resource reader) - - +data/repo_packs/vllm/pack.json resources/repo_packs (separate D007 handoff) src/inferrsi/resources/repository_packs.py (resource reader) - - +data/repo_packs/vllm_omni/pack.json resources/repo_packs (separate D007 handoff) src/inferrsi/resources/repository_packs.py (resource reader) - - +data/repo_packs/vllm_rlt/pack.json resources/repo_packs (separate D007 handoff) src/inferrsi/resources/repository_packs.py (resource reader) - docs/reviews/issue91-vllm-rlt-intake.md +device_lease.py executor (P5/P6) src/inferrsi/harness/parallel_round.py | tests/harness/test_parallel_round.py - - +entry_code.py executor (P5/P6) src/inferrsi/harness/execution_service.py | tests/harness/test_harness_entry_verification.py tests/harness/test_harness_execute.py tests/repository/check_installed.py +errors.py contracts/_harness_errors, public via api (P5/P6) src/inferrsi/apps/cli/__init__.py | src/inferrsi/apps/cli/evaluate.py | src/inferrsi/apps/handoff/bridge.py | src/inferrsi/apps/handoff/candidate_provider.py | src/inferrsi/apps/handoff/evidence_capture.py | src/inferrsi/apps/handoff/production_capture.py | src/inferrsi/apps/storage/archive.py | src/inferrsi/apps/storage/artifact_reader.py | src/inferrsi/apps/storage/result.py | src/inferrsi/apps/views/attempt.py | src/inferrsi/apps/workflows/evaluation.py | src/inferrsi/harness/evidence_capture.py | src/inferrsi/harness/execution_service.py | src/inferrsi/harness/generation.py | src/inferrsi/harness/generation_feedback.py | src/inferrsi/harness/generation_lineage.py | src/inferrsi/harness/prepared_binding.py | src/inferrsi/harness/run_store.py | tests/apps/test_apps_artifact_reader.py | tests/apps/test_apps_assess.py | tests/apps/test_apps_capture_adapter.py | tests/apps/test_apps_evidence.py | tests/apps/test_apps_execution_binding.py | tests/apps/test_apps_generation_plan.py | tests/apps/test_apps_generation_views.py | tests/apps/test_apps_output.py | tests/apps/test_apps_port_validation.py | tests/apps/test_apps_prepare.py | tests/benchmark/test_benchmark_assessment.py | tests/harness/run_store_child.py | tests/harness/test_harness_entry_verification.py | tests/harness/test_harness_evaluation_replay.py | tests/harness/test_harness_evidence_capture.py | tests/harness/test_harness_execute.py | tests/harness/test_harness_feedback_policy.py | tests/harness/test_harness_generation_bounds.py | tests/harness/test_harness_generation_lineage.py | tests/harness/test_harness_generation_seal.py | tests/harness/test_harness_prepared_binding.py | tests/harness/test_harness_run_store.py tests/harness/test_harness_execute.py | tests/harness/test_harness_run_store.py | tests/repository/_gate_policy_support.py docs/guides/module-layout.md +evidence_capture.py executor (P5/P6) src/inferrsi/harness/execution_service.py | tests/harness/test_harness_evidence_capture.py tests/harness/test_harness_execute.py tests/repository/check_installed.py +execution_service.py executor (P5/P6) src/inferrsi/harness/api.py | src/inferrsi/harness/generation.py | src/inferrsi/harness/generation_feedback.py | src/inferrsi/harness/generation_lineage.py | tests/apps/test_apps_evaluate_cli.py | tests/apps/test_apps_evidence_capture.py | tests/apps/test_apps_generation_plan.py | tests/apps/test_apps_production_cli.py | tests/benchmark/test_benchmark_cpu_smoke.py | tests/harness/test_harness_entry_verification.py | tests/harness/test_harness_evaluation_replay.py | tests/harness/test_harness_evidence_capture.py | tests/harness/test_harness_execute.py | tests/harness/test_harness_feedback_policy.py | tests/harness/test_harness_generation_lineage.py | tests/harness/test_harness_prepared_binding.py tests/harness/test_harness_execute.py | tests/repository/_gate_policy_support.py | tests/repository/test_first_wave_isolation_policy.py docs/guides/module-layout.md +execution_spec.py executor (P5/P6) src/inferrsi/apps/workflows/evaluation.py | src/inferrsi/harness/run_store.py | tests/apps/test_apps_execution_binding.py | tests/apps/test_apps_port_validation.py tests/harness/test_harness_execute.py | tests/harness/test_harness_run_store.py docs/guides/apps-output.md +generation.py executor (P5/P6) tests/apps/test_apps_fixed_cpu_views.py | tests/apps/test_apps_generation_views.py | tests/harness/test_harness_feedback_policy.py | tests/harness/test_harness_generation_bounds.py | tests/harness/test_harness_generation_lineage.py | tests/harness/test_harness_generation_seal.py - docs/contracts/generation-bounds.md | docs/contracts/generation-feedback-policy.md | docs/contracts/generation-feedback.md | docs/guides/operations.md | tests/apps/test_apps_module_migrations.py +generation_feedback.py executor (P5/P6) src/inferrsi/harness/generation.py | tests/harness/test_harness_feedback_policy.py - - +generation_lineage.py executor (P5/P6) src/inferrsi/harness/execution_service.py | tests/harness/test_harness_generation_lineage.py tests/harness/test_harness_execute.py - +gvo.py manager/search (P2) src/inferrsi/harness/search_campaign.py | src/inferrsi/harness/search_continuations.py | tests/harness/test_vats_runtime.py - docs/guides/speculative-search.md +improvement.py manager/search (P2) src/inferrsi/apps/workflows/improvement.py | tests/harness/test_harness_improvement.py docs/reviews/pr437-s01-reproduction/reproduce.py docs/guides/harness-improvement.md | docs/reviews/pr437-s01-reproduction/README.md | evidence/indexer-255-covered-cue-20261030/plan/source-pins.json | evidence/indexer-255-token-v3-20261030/plan/pre-semantic-freeze.json | evidence/indexer-255-token-v3-20261030/plan/source-pins.json | tests/repository/test_first_wave_isolation_policy.py | tools/skill_eval_improve.py +input_binding.py executor (P5/P6) src/inferrsi/harness/entry_code.py | src/inferrsi/harness/evidence_capture.py | src/inferrsi/harness/execution_service.py | src/inferrsi/harness/prepared_binding.py | src/inferrsi/harness/skill_evaluation.py | tests/harness/test_harness_execute.py | tests/skill_eval/test_skill_evaluation.py tests/harness/test_harness_execute.py | tests/repository/_gate_policy_support.py docs/apps-module-migrations.json | docs/guides/module-layout.md | tools/skill_eval_compare.py +launch_records.py executor (P5/P6) src/inferrsi/harness/attempt_recovery.py | src/inferrsi/harness/task_protocol.py | src/inferrsi/harness/trials/external.py | tests/apps/test_optimization_session.py - - +local_process.py executor (P5/P6) src/inferrsi/harness/artifact_sandbox.py | src/inferrsi/harness/execution_service.py | src/inferrsi/harness/optimization.py | src/inferrsi/harness/project_service.py | src/inferrsi/harness/skill_evaluation.py | src/inferrsi/harness/task_protocol.py | src/inferrsi/harness/trials/external.py | tests/harness/test_harness_execute.py tests/harness/test_harness_execute.py | tests/repository/_gate_policy_support.py CHANGELOG.md | docs/contracts/harness-evaluation-replay.md | docs/guides/module-layout.md | tests/harness/test_local_executor.py | tests/skill_eval/test_skill_eval_compare.py | tools/skill_eval_compare.py +measurement.py evaluator (P7/P8) src/inferrsi/harness/optimization_session.py | src/inferrsi/harness/project.py | tests/harness/test_harness_measurement.py | tools/measurement_simulation.py - - +optimization.py analyzer, indexer, executor, evaluator, manager (P4/P7/P8/P9) src/inferrsi/apps/views/dashboard_data.py | src/inferrsi/apps/views/round_citations.py | src/inferrsi/apps/workflows/benchmark_compare.py | src/inferrsi/harness/optimization_session.py | src/inferrsi/harness/service_backfill.py | tests/apps/test_optimization_session.py | tests/apps/test_project_explanation.py | tests/apps/test_project_optimization.py | tests/apps/test_project_service_reuse.py | tests/apps/test_result_delivery.py | tests/campaigns/test_qwen21_task.py | tests/harness/session_lock_probe.py | tests/harness/test_service_backfill_recovery.py | tests/harness/test_service_profile_diagnostics.py | tests/harness/test_service_reference_evidence.py src/inferrsi/apps/delivery/projection.py - +optimization_session.py analyzer, indexer, executor, evaluator, manager (P4/P7/P8/P9) src/inferrsi/apps/cli/__init__.py | src/inferrsi/apps/workflows/benchmark_compare.py | src/inferrsi/apps/workflows/benchmark_operations.py | src/inferrsi/apps/workflows/search_benchmarks.py | src/inferrsi/harness/project_service.py | src/inferrsi/harness/search_adapter.py | tests/apps/test_optimization_session.py | tests/apps/test_project_explanation.py | tests/apps/test_project_optimization.py | tests/benchmark/test_benchmark_compare.py | tests/benchmark/test_benchmark_operations.py | tests/harness/test_harness_measurement.py | tests/repository/check_session_imports.py | tools/speculative_skill.py src/inferrsi/harness/session_runtime.py | tests/repository/check_session_imports.py docs/apps-module-migrations.json | tests/fixtures/optimization-session/pre-infra-removal-session/rounds/round-01/attempt-c8293054fed14a4789d192d1f43787c3/execution/execution.json | tests/fixtures/optimization-session/pre-trials-rename-session/rounds/round-01/attempt-81f9c08f4dde440594a785ec960a5409/execution/execution.json +parallel_round.py manager / executor (P2/P9) src/inferrsi/apps/workflows/parallel_round.py | tests/harness/test_parallel_round.py | tools/parallel_round.py - - +prepared_binding.py executor (P5/P6) src/inferrsi/harness/execution_service.py | src/inferrsi/harness/generation_feedback.py | src/inferrsi/harness/generation_lineage.py | tests/harness/test_harness_prepared_binding.py tests/harness/test_harness_execute.py docs/contracts/harness-prepared-binding.md | docs/guides/operations.md | tests/repository/check_installed.py +project.py analyzer, indexer, executor, evaluator, manager (P4/P7/P8/P9) src/inferrsi/harness/optimization_session.py | tests/apps/test_project_explanation.py | tests/apps/test_project_optimization.py | tests/apps/test_project_service_reuse.py - - +project_service.py analyzer, indexer, executor, evaluator, manager (P4/P7/P8/P9) src/inferrsi/harness/optimization.py | src/inferrsi/harness/optimization_session.py | src/inferrsi/harness/service_backfill.py | src/inferrsi/harness/service_evidence.py | src/inferrsi/harness/service_observations.py | tests/apps/test_project_service_reuse.py | tests/apps/test_session_ranking_policy.py | tests/harness/test_project_objectives.py | tests/harness/test_service_backfill_recovery.py | tests/harness/test_service_capture_accounting.py | tests/harness/test_service_profile_diagnostics.py - - +protocol_child.py executor (P7) src/inferrsi/harness/task_protocol.py | tests/harness/test_task_protocol_child.py - - +records/__init__.py records (P5) - tests/apps/test_campaign_record_injection.py CHANGELOG.md +records/campaign_records.py records (P5) src/inferrsi/apps/cli/__init__.py | src/inferrsi/apps/views/capture_delivery.py | src/inferrsi/apps/views/codex_search.py | src/inferrsi/apps/views/search_archive.py | src/inferrsi/apps/views/search_attribution.py | src/inferrsi/apps/workflows/campaign.py | tests/apps/test_campaign_record_injection.py | tests/apps/test_campaign_records.py | tests/apps/test_mindie_context.py | tests/apps/test_optimization_story.py | tests/apps/test_optimization_trace.py | tests/apps/test_round_decisions_browser.py | tests/fixtures/knowledge_retrieval.py tests/apps/test_campaign_record_injection.py - +records/campaign_trace.py records (P5) tests/harness/test_campaign_trace.py - docs/dashboard.md +records/evidence.py records (P5) src/inferrsi/apps/integrations/cannbot/round_knowledge.py | src/inferrsi/apps/views/capture_delivery.py | src/inferrsi/apps/views/codex_knowledge.py | src/inferrsi/apps/views/codex_search.py | src/inferrsi/apps/views/dashboard.py | src/inferrsi/apps/views/dashboard_data.py | src/inferrsi/apps/views/dashboard_experiments.py | src/inferrsi/apps/views/dashboard_external.py | src/inferrsi/apps/views/dashboard_timeline.py | src/inferrsi/apps/views/experiment_timing.py | src/inferrsi/apps/views/retrieval_projection.py | src/inferrsi/apps/views/round_citations.py | src/inferrsi/apps/views/search_archive.py | src/inferrsi/apps/views/search_attribution.py | src/inferrsi/harness/attempt_recovery.py | src/inferrsi/harness/optimization.py | src/inferrsi/harness/records/campaign_records.py | src/inferrsi/harness/records/campaign_trace.py | tests/apps/dashboard/test_dashboard_data.py | tests/apps/test_optimization_session.py | tests/fixtures/service_reuse.py - - +records/knowledge_capture.py records (P5) src/inferrsi/apps/views/capture_delivery.py | src/inferrsi/apps/views/optimization_story.py | src/inferrsi/apps/views/retrieval_projection.py | src/inferrsi/apps/workflows/benchmark_compare.py | src/inferrsi/apps/workflows/campaign.py | src/inferrsi/harness/optimization.py | tests/apps/test_campaign_record_injection.py | tests/apps/test_optimization_session.py | tests/fixtures/service_reuse.py tests/apps/test_campaign_record_injection.py | tests/fixtures/dashboard_profile_review.py - +records/optimization_log.py records (P5) src/inferrsi/apps/cli/__init__.py | src/inferrsi/apps/views/capture_delivery.py | src/inferrsi/apps/views/experiment_timing.py | src/inferrsi/apps/views/optimization_story.py | src/inferrsi/apps/views/retrieval_projection.py | src/inferrsi/apps/views/round_citations.py | src/inferrsi/apps/views/search_archive.py | src/inferrsi/apps/views/search_attribution.py | src/inferrsi/harness/records/evidence.py | src/inferrsi/harness/records/profile_timeline.py | tests/apps/test_optimization_story.py | tests/apps/test_search_attribution.py | tests/fixtures/dashboard_experiments.py | tests/fixtures/knowledge_retrieval.py tests/fixtures/dashboard_profile_review.py - +records/optimization_trace.py records (P5) src/inferrsi/apps/views/dashboard_data.py | src/inferrsi/harness/records/campaign_records.py | tests/apps/test_optimization_trace.py - - +records/profile_timeline.py records (P5) src/inferrsi/apps/cli/__init__.py | src/inferrsi/apps/views/dashboard.py | src/inferrsi/apps/views/dashboard_live.py | tests/apps/test_profile_story_checks.py | tests/apps/test_profile_timeline.py | tests/fixtures/dashboard_profile_review.py tests/apps/test_campaign_record_injection.py - +records/timing_clock.py records (P5) src/inferrsi/apps/views/experiment_timing.py | src/inferrsi/apps/views/profile_searches.py | src/inferrsi/harness/records/profile_timeline.py - - +round_budget.py manager / executor (P2/P9) src/inferrsi/harness/parallel_round.py | tests/harness/test_round_budget.py - - +run_store.py records (P5) evidence/qwen-vats-gvo-910b1-20261124/plan/run.py | evidence/qwen-vats-gvo-910b1-20261124/validator/check.py | src/inferrsi/apps/cli/evaluate.py | src/inferrsi/apps/storage/artifact_reader.py | src/inferrsi/apps/workflows/speculative_search.py | src/inferrsi/harness/api.py | src/inferrsi/harness/evidence_capture.py | src/inferrsi/harness/execution_service.py | src/inferrsi/harness/generation.py | src/inferrsi/harness/generation_feedback.py | src/inferrsi/harness/generation_lineage.py | src/inferrsi/harness/prepared_binding.py | src/inferrsi/harness/work_control.py | tests/apps/test_apps_artifact_reader.py | tests/apps/test_apps_assess.py | tests/apps/test_apps_evaluate_cli.py | tests/apps/test_apps_evidence_capture.py | tests/apps/test_apps_fixed_cpu_views.py | tests/apps/test_apps_generation_plan.py | tests/apps/test_apps_output.py | tests/apps/test_apps_port_validation.py | tests/apps/test_apps_production_cli.py | tests/apps/test_apps_replay.py | tests/apps/test_search_benchmarks.py | tests/benchmark/test_benchmark_cpu_smoke.py | tests/harness/run_store_child.py | tests/harness/test_harness_entry_verification.py | tests/harness/test_harness_evaluation_replay.py | tests/harness/test_harness_evidence_capture.py | tests/harness/test_harness_execute.py | tests/harness/test_harness_feedback_policy.py | tests/harness/test_harness_generation_bounds.py | tests/harness/test_harness_generation_lineage.py | tests/harness/test_harness_generation_seal.py | tests/harness/test_harness_prepared_binding.py | tests/harness/test_harness_run_store.py | tests/harness/test_vats_runtime.py | tests/harness/test_work_control.py tests/harness/test_harness_execute.py | tests/harness/test_harness_run_store.py | tests/repository/_gate_policy_support.py | tests/repository/test_first_wave_isolation_policy.py docs/guides/apps-output.md | docs/guides/module-layout.md | tests/apps/test_apps_module_migrations.py +runner.py manager (P3) src/inferrsi/apps/legacy/run.py | src/inferrsi/harness/parallel_round.py | tests/apps/test_legacy_run_split.py | tests/contracts/test_contracts_package.py tests/apps/test_legacy_run_split.py | tests/repository/test_architecture_closed_loop.py CHANGELOG.md | evidence/indexer-255-20261029/results/import-proof-baseline.json | evidence/indexer-255-20261029/results/import-proof-indexer-evidence.json | evidence/indexer-255-covered-cue-20261030/plan/source-pins.json | evidence/indexer-255-token-v3-20261030/plan/pre-semantic-freeze.json | evidence/indexer-255-token-v3-20261030/plan/source-pins.json | evidence/kv-actor-qualification-20261030/results/hosted-41154288295/qualification.json | evidence/kv-actor-qualification-20261030/results/hosted-41182807900/qualification.json | evidence/kv-live-pilot-20261031/plan/A2.json | evidence/kv-live-pilot-20261031/plan/A3.json | evidence/kv-live-pilot-20261031/plan/plan.json | evidence/kv-live-pilot-20261031/plan/second-attempt-1200/plan.json | evidence/kv-live-pilot-20261031/plan/second-attempt/A2.json | evidence/kv-live-pilot-20261031/plan/second-attempt/A3.json | evidence/kv-live-pilot-20261031/plan/second-attempt/plan.json | tests/repository/test_first_wave_isolation_policy.py | tests/repository/test_legacy_run_forwarder_gate.py +search_adapter.py manager/search (P2) evidence/qwen-vats-gvo-910b1-20261124/plan/run.py | src/inferrsi/apps/workflows/speculative_search.py | src/inferrsi/harness/search_campaign.py | src/inferrsi/harness/vats.py | tests/apps/test_search_benchmarks.py | tests/harness/test_vats_runtime.py - - +search_campaign.py manager/search (P2) evidence/qwen-vats-gvo-910b1-20261124/plan/run.py | src/inferrsi/apps/workflows/speculative_search.py | tests/apps/test_search_benchmarks.py | tests/harness/test_vats_runtime.py - - +search_continuations.py manager/search (P2) src/inferrsi/harness/gvo.py | tests/harness/test_vats_runtime.py - - +search_records.py manager/search (P2) evidence/qwen-vats-gvo-910b1-20261124/plan/run.py | src/inferrsi/apps/workflows/speculative_search.py | src/inferrsi/harness/gvo.py | src/inferrsi/harness/search_adapter.py | src/inferrsi/harness/search_campaign.py | src/inferrsi/harness/search_continuations.py | src/inferrsi/harness/vats.py | tests/harness/test_vats_runtime.py - - +search_tree.py manager/search (P2) evidence/qwen-vats-gvo-910b1-20261124/plan/run.py | src/inferrsi/apps/workflows/speculative_search.py | src/inferrsi/harness/search_adapter.py | src/inferrsi/harness/search_campaign.py | src/inferrsi/harness/search_records.py | src/inferrsi/harness/vats.py | src/inferrsi/harness/verification_plans.py | tests/fixtures/speculative_search.py | tests/harness/test_speculative_search.py | tests/harness/test_vats_runtime.py | tests/harness/test_verification_plans.py - - +service_backfill.py manager (P9) src/inferrsi/harness/optimization.py | tests/harness/test_service_backfill_recovery.py - - +service_evidence.py evaluator (P7/P8) src/inferrsi/harness/optimization.py - - +service_observations.py records (P5) src/inferrsi/harness/optimization.py - - +serving/__init__.py executor/serving (P8) - tests/repository/check_installed.py CHANGELOG.md +serving/http.py executor/serving (P8) src/inferrsi/harness/serving/image.py tests/repository/check_installed.py CHANGELOG.md | docs/release-notes/v0.3.0.md +serving/image.py executor/serving (P8) examples/qwen21_turbo_b300.py | tests/benchmark/test_image_modules.py tests/repository/check_installed.py CHANGELOG.md | tests/repository/test_target_module_import_gate.py +serving/server.py executor/serving (P8) examples/qwen21_turbo_b300.py | tests/harness/test_server_processes.py tests/repository/check_installed.py CHANGELOG.md +session_runtime.py manager (P9) src/inferrsi/harness/optimization_session.py | tests/repository/check_session_imports.py - - +skill_evaluation.py executor (P5/P6) src/inferrsi/apps/workflows/skill_evaluation.py | tests/apps/test_anthropic_agent.py | tests/apps/test_yibuapi_runtime.py | tests/harness/test_harness_improvement.py | tests/skill_eval/test_skill_eval_generation.py | tests/skill_eval/test_skill_evaluation.py | tools/skill_eval_compare.py | tools/skill_eval_improve.py | tools/skill_eval_pilot.py docs/reviews/pr437-s01-reproduction/reproduce.py docs/guides/skill-evaluation/README.md | docs/reviews/issue148-flare-source-distillation.md | docs/reviews/pr437-s01-reproduction/README.md | evidence/indexer-255-covered-cue-20261030/plan/source-pins.json | evidence/indexer-255-token-v3-20261030/plan/pre-semantic-freeze.json | evidence/indexer-255-token-v3-20261030/plan/source-pins.json | tests/fixtures/skill-comparison/report-example.json | tests/repository/test_first_wave_isolation_policy.py +task_protocol.py executor (P7) evidence/qwen-vats-gvo-910b1-20261124/validator/check.py | src/inferrsi/apps/workflows/benchmark_compare.py | src/inferrsi/apps/workflows/search_benchmarks.py | src/inferrsi/harness/optimization.py | src/inferrsi/harness/optimization_session.py | tests/apps/test_search_benchmarks.py | tests/apps/test_session_ranking_policy.py | tests/harness/test_moe_optimization_protocol.py | tests/harness/test_service_fingerprint_isolation.py | tests/harness/test_task_protocol_child.py - - +trials/__init__.py executor/trials (P6) - tests/repository/check_installed.py CHANGELOG.md +trials/external.py executor/trials (P6) src/inferrsi/apps/legacy/run.py | src/inferrsi/apps/workflows/search_benchmarks.py | src/inferrsi/harness/optimization_session.py | src/inferrsi/harness/project_service.py | src/inferrsi/harness/runner.py | src/inferrsi/harness/search_adapter.py | tests/apps/test_legacy_run_split.py | tests/apps/test_optimization_session.py | tests/apps/test_project_service_reuse.py | tests/apps/test_search_benchmarks.py | tests/apps/test_trial_checks.py | tests/benchmark/test_moe_benchmark.py | tests/repository/architecture_real_ports.py | tools/speculative_skill.py tests/apps/test_legacy_run_split.py | tests/repository/check_installed.py | tests/repository/test_architecture_closed_loop.py tests/benchmark/test_benchmark_operations.py +usage.py records (P5) src/inferrsi/apps/delivery/benchmark_usage.py | src/inferrsi/apps/delivery/projection.py | src/inferrsi/apps/workflows/improvement.py | src/inferrsi/apps/workflows/skill_evaluation.py | src/inferrsi/harness/agent_sessions.py | src/inferrsi/harness/optimization.py | src/inferrsi/harness/skill_evaluation.py | tests/harness/test_harness_improvement.py | tests/skill_eval/test_skill_eval_local.py | tools/skill_eval_compare.py | tools/skill_eval_improve.py | tools/skill_eval_local.py | tools/skill_eval_pilot.py - docs/guides/harness-improvement.md +vats.py manager/search (P2) evidence/qwen-vats-gvo-910b1-20261124/plan/run.py | src/inferrsi/apps/workflows/speculative_search.py | src/inferrsi/harness/search_campaign.py | src/inferrsi/harness/search_continuations.py | tests/apps/test_search_benchmarks.py | tests/harness/test_vats_runtime.py - - +verification_plans.py manager/search (P2) src/inferrsi/harness/search_adapter.py | src/inferrsi/harness/vats.py | tests/harness/test_verification_plans.py - - +work_control.py manager/search (P2) evidence/qwen-vats-gvo-910b1-20261124/plan/run.py | evidence/qwen-vats-gvo-910b1-20261124/validator/check.py | src/inferrsi/apps/workflows/speculative_search.py | tests/apps/test_search_benchmarks.py | tests/harness/test_vats_runtime.py | tests/harness/test_work_control.py tests/harness/test_vats_runtime.py | tests/harness/test_work_control.py - diff --git a/tests/fixtures/optimization-session/component-freeze/manifest.json b/tests/fixtures/optimization-session/component-freeze/manifest.json new file mode 100644 index 000000000..db04c285f --- /dev/null +++ b/tests/fixtures/optimization-session/component-freeze/manifest.json @@ -0,0 +1,512 @@ +{ + "source_commit": "3efb03ea71356786b19b705e53f65267c17d19bf", + "source_archive_sha256": "b754a323fd7668f6116d8048bfe3838a56120239940e46279710456fa43243b2", + "wheel_name": "inferrsi-0.3.5.dev4+g3efb03ea7-py3-none-any.whl", + "wheel_sha256": "3fa6cd9372d75c5dd4575395fb709ef0c243ad52ef8e259137685927156d7944", + "installed_package_files": 1021, + "runtime_version": "0.3.5.dev4+g3efb03ea7", + "samples": { + "ordinary-packaged.zip": "0099080ad8fc5637db2af520dce9510f3aa044eed23ae8ecc5d959e21cb20153", + "ordinary-ab-ba.zip": "b2cab681107e6c2f79d212ebe19745fcc4431e8dd9029a5c8599b385e323c708", + "service-pending.zip": "ecf13a313fce5ee438b9021025ea34d5e9b5ad9c2baab9a4cec7e077bead0a9f", + "service-settled.zip": "4311293f1f106849ebe3e3f530ff54dc2653f47e14696e156e743126fa513dfa", + "service-cleanup-pending.zip": "79f10c1f23222adca935497e0791fd3c96bffe7ab748bf63d2f54f4d2f5a9ec0", + "cleanup-proofs.zip": "5cbfb6c92d0377efcb83f77a95c32428a47e1448ea69b7bd6d4dfba4011fd57a" + }, + "cleanup_proofs": { + "cleanup.json": "bcd5508ef2e7d2f5f23ef3e58b62ccf310e58a74fe3e16c3b32eae2afdd694b9", + "wrong-attempt.json": "9dfbae9e5301c19ecad52f203d77d3c9af980d7d6975dcddf370a2a86eeabe52", + "wrong-owner.json": "662a89d1ce1fb213152b1bdadc6716c6eef1bc8bb51f1c79c34a7adb5c1a3e6c", + "wrong-attempt-only.json": "b2ce3b3a6a9978ba026844c248d3de520ade3522af3e6e098a6fb194b5fd3f77" + }, + "runtime_sources": "runtime-sources.json", + "repository_packs": { + "afd_plugin": "00042abeabdc9c0e24f1a4edaba47e233df398aef0ad4e181fc70191d383da5f", + "sglang": "bce2e0c42796a9ef499d459c37b56d1d56f4b19344841359c534fca29c0359ce", + "sglang_omni": "8e70336bc2aac0c74732a026337813652b5d5c6e1fc60f5571e9442345077b96", + "strata": "643b32defb8db9aa230f624856f4fb4b595b5c23db58d9453091f5420cff71c3", + "vllm": "1705d96710249c4514c15d8d011b43c1a1ae7c15fbc9ddf11ef2d0e6b2ab7d07", + "vllm_omni": "58c971e9dcf6ac15752629ed4d9426aeb5b5d857fc37b5bcf921aa2e81c0cdd5", + "vllm_rlt": "6097041b8d026740060e527f49b1b4e288315b1c3227f7583805b86d8fa415f7" + }, + "packaged_cli": [ + { + "entry": "controlled test child", + "argv": [ + "benchmarks", + "session", + "start", + "test-work", + "--session", + "session", + "--rounds", + "3", + "--max-minutes", + "5", + "--evaluation-timeout-seconds", + "30", + "--condition", + "harness-freeze-control", + "--evaluation-args", + "", + "--python", + "python" + ], + "exit": 0 + }, + { + "entry": "python -m inferrsi", + "argv": [ + "benchmarks", + "session", + "diagnose", + "--session", + "session", + "--bottleneck", + "Reference operation", + "--evidence", + "measurement.txt" + ], + "exit": 0 + }, + { + "entry": "controlled test child", + "argv": [ + "benchmarks", + "session", + "round", + "--session", + "session", + "--candidate", + "session/work/candidate.py", + "--hypothesis", + "Synthetic ordinary recovery" + ], + "exit": 130 + }, + { + "entry": "python -m inferrsi", + "argv": [ + "benchmarks", + "session", + "status", + "--session", + "benchmark" + ], + "exit": 0 + }, + { + "entry": "python -m inferrsi", + "argv": [ + "benchmarks", + "session", + "recover", + "--session", + "benchmark" + ], + "exit": 0 + }, + { + "entry": "python -m inferrsi", + "argv": [ + "benchmarks", + "session", + "recover", + "--session", + "benchmark" + ], + "exit": 0 + }, + { + "entry": "python -m inferrsi", + "argv": [ + "campaign", + "status", + "--session", + "campaign" + ], + "exit": 0 + }, + { + "entry": "python -m inferrsi", + "argv": [ + "campaign", + "recover", + "--session", + "campaign" + ], + "exit": 0 + }, + { + "entry": "python -m inferrsi", + "argv": [ + "campaign", + "recover", + "--session", + "campaign" + ], + "exit": 0 + } + ], + "packaged_replays": [ + { + "entry": "benchmarks session", + "snapshot_files": 17, + "status_read_only": true, + "result": { + "rounds": 1, + "pending": null, + "best": 2, + "candidate_calls": [ + "2" + ] + }, + "repeat_file_delta": [ + "summary.json" + ], + "repeat_summary_delta": [ + "wall_elapsed_seconds" + ], + "ledger_and_deadline_unchanged": true, + "added_launch_records": [ + "protocol-assess-0001.json" + ] + }, + { + "entry": "campaign", + "snapshot_files": 17, + "status_read_only": true, + "result": { + "rounds": 1, + "pending": null, + "best": 2, + "candidate_calls": [ + "2" + ] + }, + "repeat_file_delta": [ + "summary.json" + ], + "repeat_summary_delta": [ + "wall_elapsed_seconds" + ], + "ledger_and_deadline_unchanged": true, + "added_launch_records": [ + "protocol-assess-0001.json" + ] + } + ], + "project_ab_ba": { + "order": [ + "quality-baseline", + "quality-candidate", + "warmup-001-baseline", + "warmup-001-candidate", + "measurement-001-baseline", + "measurement-001-candidate", + "measurement-002-candidate", + "measurement-002-baseline" + ], + "original_files": 56, + "launches": 8, + "new_executions_during_recovery": 0, + "result": "PASS" + }, + "legacy_run_golden": [ + { + "case": "pass", + "exit": 0, + "verdict": "PASS", + "order": [ + [ + 1, + "baseline" + ], + [ + 1, + "candidate" + ], + [ + 2, + "candidate" + ], + [ + 2, + "baseline" + ] + ], + "golden_sha256": "887975c19f74320859c76ccd5be0faf3fbf1a4adb68e2ce10597707de9c0385d", + "raw_sha256": "fba74936c417f5a7c0d8d130f2964b7c67c56edd31d0ea0a9d8510ebdc185d04", + "golden_bytes": 1007 + }, + { + "case": "fail-threshold", + "exit": 1, + "verdict": "FAIL", + "order": [ + [ + 1, + "baseline" + ], + [ + 1, + "candidate" + ] + ], + "golden_sha256": "a69877794dedf2f64e1f14b44ca2696f5b9532addf2686083de6d5636d5a6cbe", + "raw_sha256": "9401ed9d7d22be5dad6b3721da545d89c116de89c6d5106660f06ba5cd3c67e0", + "golden_bytes": 1050 + }, + { + "case": "incomplete-no-validation", + "exit": 2, + "verdict": "INCONCLUSIVE", + "order": [ + [ + 1, + "baseline" + ], + [ + 1, + "candidate" + ] + ], + "golden_sha256": "155ad1134c766cda426f46af1f0cbbe63b33cbb97e8993df1f1b46a225e54f78", + "raw_sha256": "e911d250a9ade8a5317f4c2604370d61ff7399a52e4e174b74484b5b19f7a8f3", + "golden_bytes": 1043 + } + ], + "service_pass": [ + { + "sample": "settled", + "sha256": "4311293f1f106849ebe3e3f530ff54dc2653f47e14696e156e743126fa513dfa", + "source_files": 92, + "existing_stage_logs": 2, + "verdict": "PASS", + "rounds": 1, + "ledger_additions": 0, + "commands": [ + { + "argv": [ + "python", + "-B", + "-m", + "inferrsi", + "campaign", + "status", + "--session", + "" + ], + "exit": 0, + "child_launches": 0 + }, + { + "argv": [ + "python", + "-B", + "-m", + "inferrsi", + "campaign", + "recover", + "--session", + "" + ], + "exit": 0, + "child_launches": 0 + }, + { + "argv": [ + "python", + "-B", + "-m", + "inferrsi", + "campaign", + "recover", + "--session", + "" + ], + "exit": 0, + "child_launches": 0 + } + ] + }, + { + "sample": "pending", + "sha256": "ecf13a313fce5ee438b9021025ea34d5e9b5ad9c2baab9a4cec7e077bead0a9f", + "source_files": 136, + "existing_stage_logs": 3, + "verdict": "PASS", + "rounds": 2, + "ledger_additions": 1, + "commands": [ + { + "argv": [ + "python", + "-B", + "-m", + "inferrsi", + "campaign", + "status", + "--session", + "" + ], + "exit": 0, + "child_launches": 0 + }, + { + "argv": [ + "python", + "-B", + "-m", + "inferrsi", + "campaign", + "recover", + "--session", + "" + ], + "exit": 0, + "child_launches": 0 + }, + { + "argv": [ + "python", + "-B", + "-m", + "inferrsi", + "campaign", + "recover", + "--session", + "" + ], + "exit": 0, + "child_launches": 0 + } + ] + } + ], + "service_cleanup": { + "attempt_id": "13aa0869359b4a1ca42ec78ead627e4a", + "before_recovery_stages": [ + "ready", + "warmup", + "measure", + "measure", + "stop" + ], + "verdict": "FAIL", + "probe": [ + { + "step": "absent", + "returncode": 2, + "launches": [] + }, + { + "step": "wrong", + "returncode": 2, + "launches": [] + }, + { + "step": "wrong-owner", + "returncode": 2, + "launches": [] + }, + { + "step": "wrong-attempt-only", + "returncode": 2, + "launches": [], + "unchanged_files": 82, + "state_sha256": "d7554357f8db9cd65fb7b8f31edcf8291c6d487109c0dd03c328469eed2cda5b", + "observation_written": false + }, + { + "step": "matching", + "returncode": 0, + "launches": [] + }, + { + "step": "repeat", + "returncode": 0, + "launches": [] + } + ], + "repeat_state_identical": true, + "deadline_identical": true + }, + "continuation_regressions": 11, + "packaged_subprocesses": [ + { + "path": "rounds/round-01/attempt-7343fe0f095541c797f2427bdb32c8c5/protocol-arguments-0001.json", + "sha256": "1f3fbdf6e48f58449a32f646372d736417276bb43df3c09be7b15ff9f80347eb", + "stage": "protocol-arguments-0001", + "pid": 1888, + "argv_sha256": "fcc9166889d4cc83180be8c8f18bbccb75037a0cabce574a200849df3797c9a4", + "started_at": "2026-11-26T13:21:28.748695Z", + "ended_at": "2026-11-26T13:21:29.123385Z", + "status": "completed" + }, + { + "path": "rounds/round-01/attempt-7343fe0f095541c797f2427bdb32c8c5/execution/launch-task.json", + "sha256": "45a5788048d44e71b5a3bdc709c456676fb1aafb4bc023d5b306999e7b86c9df", + "stage": "launch-task", + "pid": 19168, + "argv_sha256": "fbce8683e641fac81a274ecb293d1e2d15bb7a6671e3e6a76e08c2c079772111", + "started_at": "2026-11-26T13:21:29.155388Z", + "ended_at": "2026-11-26T13:21:29.712167Z", + "status": "completed" + }, + { + "path": "rounds/round-01/attempt-7343fe0f095541c797f2427bdb32c8c5/protocol-assess-0001.json", + "sha256": "d46e931d3b55ec3546486fcd722843689251d8a0e1bd14e3eebd732c05ac5043", + "stage": "protocol-assess-0001", + "pid": 31684, + "argv_sha256": "1257123a6c4f11a103cf851302c5b84a99d56390ec8d39e519cf603bca8840cc", + "started_at": "2026-11-26T13:21:33.619605Z", + "ended_at": "2026-11-26T13:21:33.954761Z", + "status": "completed" + } + ], + "relocated_replays": [ + { + "kind": "packaged", + "action": "status", + "child_launches": 0, + "reads_from_generator": 0, + "exit": 0 + }, + { + "kind": "packaged", + "action": "recover", + "child_launches": 1, + "reads_from_generator": 0, + "exit": 0 + }, + { + "kind": "packaged", + "action": "recover", + "child_launches": 0, + "reads_from_generator": 0, + "exit": 0 + }, + { + "kind": "project", + "action": "status", + "child_launches": 0, + "reads_from_generator": 0, + "exit": 0 + }, + { + "kind": "project", + "action": "recover", + "child_launches": 0, + "reads_from_generator": 0, + "exit": 0 + }, + { + "kind": "project", + "action": "recover", + "child_launches": 0, + "reads_from_generator": 0, + "exit": 0 + } + ] +} diff --git a/tests/fixtures/optimization-session/component-freeze/ordinary-ab-ba.zip b/tests/fixtures/optimization-session/component-freeze/ordinary-ab-ba.zip new file mode 100644 index 000000000..2368e7033 Binary files /dev/null and b/tests/fixtures/optimization-session/component-freeze/ordinary-ab-ba.zip differ diff --git a/tests/fixtures/optimization-session/component-freeze/ordinary-packaged.zip b/tests/fixtures/optimization-session/component-freeze/ordinary-packaged.zip new file mode 100644 index 000000000..4dc2b2ddd Binary files /dev/null and b/tests/fixtures/optimization-session/component-freeze/ordinary-packaged.zip differ diff --git a/tests/fixtures/optimization-session/component-freeze/runtime-sources.json b/tests/fixtures/optimization-session/component-freeze/runtime-sources.json new file mode 100644 index 000000000..acdb7a2d8 --- /dev/null +++ b/tests/fixtures/optimization-session/component-freeze/runtime-sources.json @@ -0,0 +1,40 @@ +{ + "__init__.py": "60a710d283ff4f5cfa71c6872163aed4d3899145ad736602d35f88ed6ba4b6f2", + "apps/__init__.py": "0548db2140f95890653cfb2cbad1311d8e8be6626f49373b8d950eb23433f7ef", + "apps/workflows/__init__.py": "ea3be88dc5089c6f5b106bcfdcf6da887406a2515983e2ddd510c43ac7960645", + "apps/workflows/campaign.py": "b54ddd6080ddbb75d5e3cf29d4b697fe3be2aee30cf984f4001ddd2f2dfa1245", + "contracts/__init__.py": "86ffd1ae421db93276f81aadfb0b61505d5152c97ef8ffa9eb3b641376ce59f9", + "contracts/claim.py": "5f24c4fa91b48f0bb4d4554531607763fc8fc108e90f332816f06cfb520b5cc1", + "contracts/runspec.py": "2a7608b986d7f0b7962797a5adb3c5c404b35c84f70bf8e8dc18d5215b45b7ac", + "harness/__init__.py": "fdcf16a34e004b7bec987247e4b28bfaf3424d34dfb0ee72c740a5a890b2241b", + "harness/artifact_primitives.py": "f10fde1f28a7e97853cbb379ea058b9bcf0c4786a7d43ea5ec6983f8569c8c99", + "harness/atomic_json.py": "4a061657bb22ec6e24a0e67d735200c894566b4794c458ca8ed60af7b1a19c85", + "harness/attempt_recovery.py": "7a04e9d13c69654094af46b8b41ecf01b4241c3957dce4710637d08b41beebbc", + "harness/candidates.py": "49aad5645c65516093c7e14514f1bd7ec25d25ee082e6188f552ec415f86698a", + "harness/launch_records.py": "2455cfff2dcea09a903ae82184022ff59a1618642eace1dddf287383d1d68811", + "harness/local_process.py": "ae562536b972e1800012fcddb47456f9f3c5507ea85a416a93f0f9df678baa7a", + "harness/measurement.py": "6eee529a46b88e7f2598d0c663624993f96ee1ed30ca257265ed3e3792e07450", + "harness/optimization.py": "c430329d88c1e0ba8d1a61ac0c897ae8a62904346f682cdc90cfa723af619feb", + "harness/optimization_session.py": "2c296a3e670924a3e0cff033a311564eb97137dc2ac95944429e9848df12d735", + "harness/project.py": "568f1f3a389926eab37cc4d6fb7351f4ef76ecc0280af6b2f85868fb323b6276", + "harness/project_service.py": "c0a43401933895a10058c33e4f190d7e80a24ab51d01d22ae7db210e8c4c1ed7", + "harness/protocol_child.py": "2cfd5848e711cedeef181981ec6fa2be453ee061f57c32f74954c82625528c95", + "harness/records/__init__.py": "73870b2cc74b51b996356ecc896cc4002a4b3a2d72ff968025439b91899f7b01", + "harness/records/campaign_records.py": "fe17fbf89f77bc19ef2cb36a139a122298fd272b7f4d500377793fe470236d4e", + "harness/records/evidence.py": "f053f4fb0ac9e11f679d7868acfed0614103e05f5068eeb3807cd15190ae3d75", + "harness/records/knowledge_capture.py": "6a5501d9fdc6bbdc523dc98e59722eae297069a7ad6c024c9d3c7c8f38a42a22", + "harness/records/optimization_log.py": "0d3a5e0a2348a22975084c2d4676372cf9a3eee76da9e706c673d8e45bcc450f", + "harness/records/optimization_trace.py": "6f920211ca346d32e0f2ee835d84a5e043538419ab7f8972c912880ac69f5923", + "harness/service_backfill.py": "dfdc36fb934b0475bba6ecc6d462cd1572a26e51451128148c553619a4d23810", + "harness/service_evidence.py": "fd23d528827724a666b07fa307dc03a605d8127f31c9a1b82a8cdc1876e1775b", + "harness/service_observations.py": "2301cd34b05bd247074ff258749bd5096ddf2b73a926bdc34d815056a8acd38a", + "harness/session_runtime.py": "edccc00faf1fac5bf01419044a754410a48011e6483144e54039715391958793", + "harness/task_protocol.py": "2c3a694bc4227dbaa80f711f9209dd59fedf36de92af69449c5cec278abd00d2", + "harness/trials/__init__.py": "8e222c93c57f49a683171ed065497073c45b4e3e3bda7e8247f8c944d69d0bf8", + "harness/trials/external.py": "33a8e747e0f5ede72a7fb9ef968ebe736ce581c5afb1d0b3539bc57a7f8b9a3f", + "harness/usage.py": "bcb8a35f83e683c1e3343c2438214ad89f35eeb4dd940eccfd54b3489bb70855", + "knowledge/__init__.py": "5afe74ac7574fd575bce561731dffb2aec12c4e2f4b7808507f8914a622f0336", + "knowledge/context_projection.py": "ef89a0b2ecddbb0460573edc65a8b5ef704989e03d3d2fa615ca529ef0debe2a", + "knowledge/knowledge_find.py": "fa00af8fa1e39bb799a2c7d4c81a960137837fd16cf9317635c3f55996add27e", + "knowledge/ranking_policy.py": "425cf29ccb6584541fe1dfe56b20bbbfa3ec436a27da7fba97647b8a413c9506" +} diff --git a/tests/fixtures/optimization-session/component-freeze/service-cleanup-pending.zip b/tests/fixtures/optimization-session/component-freeze/service-cleanup-pending.zip new file mode 100644 index 000000000..16cde0941 Binary files /dev/null and b/tests/fixtures/optimization-session/component-freeze/service-cleanup-pending.zip differ diff --git a/tests/fixtures/optimization-session/component-freeze/service-pending.zip b/tests/fixtures/optimization-session/component-freeze/service-pending.zip new file mode 100644 index 000000000..de6b41e4f Binary files /dev/null and b/tests/fixtures/optimization-session/component-freeze/service-pending.zip differ diff --git a/tests/fixtures/optimization-session/component-freeze/service-settled.zip b/tests/fixtures/optimization-session/component-freeze/service-settled.zip new file mode 100644 index 000000000..2e5de9efa Binary files /dev/null and b/tests/fixtures/optimization-session/component-freeze/service-settled.zip differ diff --git a/tests/fixtures/service_reuse.py b/tests/fixtures/service_reuse.py index ae97d07ad..4e53452f0 100644 --- a/tests/fixtures/service_reuse.py +++ b/tests/fixtures/service_reuse.py @@ -10,8 +10,7 @@ from inferrsi.apps.cli import main from inferrsi.apps.storage import artifacts -from inferrsi.harness import artifact_primitives -from inferrsi.harness.records import evidence, knowledge_capture +from inferrsi.harness.records import artifact_primitives, evidence, knowledge_capture from inferrsi.knowledge import knowledge_operations from tests.fixtures.diagnosis import diagnosis_args 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/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/run_store_child.py b/tests/harness/run_store_child.py index e5a5c8dce..2e88441ab 100644 --- a/tests/harness/run_store_child.py +++ b/tests/harness/run_store_child.py @@ -10,8 +10,10 @@ from pathlib import Path from inferrsi.contracts import json_v1 -from inferrsi.harness import run_store -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import PublicError +from inferrsi.harness.executor import request_digest +from inferrsi.harness.records import RunStore, RunStoreReader +from inferrsi.harness.records import _run_store as run_store # Child process for the H01 RunStore tests: it claims, commits, reads, or dies at one # injected crash point. Crash points replace module helpers inside this child only. @@ -42,7 +44,7 @@ def make_attempt() -> dict: def make_digest(attempt: dict, output_root: str = "out") -> str: # The store treats request_digest as opaque; H execute computes it from a full spec. - return run_store.request_digest({"attempt": attempt, "output_root": output_root}) + return request_digest({"attempt": attempt, "output_root": output_root}) def make_payload( @@ -130,7 +132,7 @@ def _wait_for(path: Path, limit: float = 60.0) -> None: def _read(params: dict) -> int: - reader = run_store.RunStoreReader.from_mount(params["mount"]) + reader = RunStoreReader.from_mount(params["mount"]) committed = reader.committed(params["attempt_id"]) fixed = reader.committed(params["attempt_id"], params["record_version"]) record_bytes = reader.open(committed.record_ref["artifact"]).read() @@ -156,7 +158,7 @@ def main(scenario: str, params_path: str) -> int: return _read(params) work = Path(params["work"]) attempt, digest = params["attempt"], params["digest"] - store = run_store.RunStore(params["root"], params["namespace"]) + store = RunStore(params["root"], params["namespace"]) if scenario == "contend": _wait_for(work / "go") try: @@ -188,7 +190,7 @@ def main(scenario: str, params_path: str) -> int: if scenario == "crash-temp": run_store._publish = _exit elif scenario == "crash-object": - run_store.RunStore._append = _exit + RunStore._append = _exit elif scenario == "crash-record": run_store._transaction = _exit_before_commit else: diff --git a/tests/harness/session_lock_probe.py b/tests/harness/session_lock_probe.py index 709f28883..ec116ccd3 100644 --- a/tests/harness/session_lock_probe.py +++ b/tests/harness/session_lock_probe.py @@ -3,7 +3,7 @@ Run by tests/harness/test_session_lock_across_processes.py once per interpreter: against the checkout in the test run, and against an installed wheel in tests/repository/check_installed.py. It builds a valid managed session that is not final, starts a child process that -holds ``/.session.lock`` through ``harness.optimization``'s own lock, and exports the +holds ``/.session.lock`` through Manager's session lock, and exports the session through the Apps ``export_bundle`` from this process. While the child holds the lock the export must be refused and publish nothing; after it releases, the same export must publish a bundle whose ``export.kind`` is ``progress``. @@ -20,7 +20,7 @@ import inferrsi from inferrsi.apps import delivery from inferrsi.apps.storage.artifacts import atomic_write_json, sha256 -from inferrsi.harness import optimization +from inferrsi.harness.manager import _state as optimization # The child runs with -I and imports inferrsi from the same location as this process. HOLDER = """ @@ -29,7 +29,7 @@ from pathlib import Path sys.path.insert(0, sys.argv[4]) -from inferrsi.harness.optimization import _locked +from inferrsi.harness.manager._state import _locked root, ready, release = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3]) with _locked(root): diff --git a/tests/harness/test_confinement.py b/tests/harness/test_confinement.py index b600eab05..c610d1277 100644 --- a/tests/harness/test_confinement.py +++ b/tests/harness/test_confinement.py @@ -10,8 +10,8 @@ import pytest -from inferrsi.harness import confinement -from inferrsi.harness.confinement import ( +from inferrsi.harness.executor import confinement +from inferrsi.harness.executor.confinement import ( ConfinementUnavailable, FixtureBackend, UnavailableBackend, @@ -68,7 +68,7 @@ def test_missing_backend_refuses_without_running(tmp_path): def test_select_backend_fails_closed_when_namespaces_are_disabled(monkeypatch): - monkeypatch.setattr("inferrsi.harness.confinement.namespaces_available", lambda: False) + monkeypatch.setattr("inferrsi.harness.executor.confinement.namespaces_available", lambda: False) assert isinstance(select_backend(), UnavailableBackend) @@ -93,7 +93,7 @@ def fake_popen(argv, **kwargs): return FailedUnshare(argv) return real_popen(argv, **kwargs) - monkeypatch.setattr("inferrsi.harness.confinement.subprocess.Popen", fake_popen) + monkeypatch.setattr("inferrsi.harness.executor.confinement.subprocess.Popen", fake_popen) with pytest.raises(ConfinementUnavailable, match="unshare failed"): UnshareBackend().run( (sys.executable, "-c", "print('should-not-run')"), @@ -131,7 +131,7 @@ def fake_popen(argv, **kwargs): argv = [sys.executable, "-c", payload] return real_popen(argv, **kwargs) - monkeypatch.setattr("inferrsi.harness.confinement.subprocess.Popen", fake_popen) + monkeypatch.setattr("inferrsi.harness.executor.confinement.subprocess.Popen", fake_popen) with pytest.raises(ConfinementUnavailable, match="timed out"): UnshareBackend().run( (sys.executable, "-c", "print('unused')"), @@ -174,13 +174,15 @@ def killpg(pgid, sig): def test_supervisor_ignores_a_shadow_package_in_the_candidate(tmp_path): shadow = tmp_path / "candidate" - (shadow / "inferrsi" / "infra").mkdir(parents=True) + executor = shadow / "inferrsi" / "harness" / "executor" + executor.mkdir(parents=True) canary = tmp_path / "shadow-imported" (shadow / "inferrsi" / "__init__.py").write_text( f"open({str(canary)!r}, 'w').write('1')\n", encoding="utf-8" ) - (shadow / "inferrsi" / "infra" / "__init__.py").write_text("", encoding="utf-8") - (shadow / "inferrsi" / "infra" / "confinement.py").write_text( + (executor.parent / "__init__.py").touch() + (executor / "__init__.py").touch() + (executor / "confinement.py").write_text( "def enter_namespace(path):\n raise SystemExit('shadow')\n", encoding="utf-8" ) completed = subprocess.run( @@ -273,7 +275,7 @@ def test_runtime_roots_under_system_python_exclude_usr(): script = ( "import json, sys, sysconfig\n" "sys.path[:0] = %r\n" - "from inferrsi.harness.confinement import runtime_roots\n" + "from inferrsi.harness.executor.confinement import runtime_roots\n" "print(json.dumps({\n" " 'roots': [str(p) for p in runtime_roots()],\n" " 'prefix': sys.prefix,\n" @@ -429,7 +431,7 @@ def blocked(argv, **kwargs): return subprocess.CompletedProcess(argv, 1, stderr=b"Operation not permitted") monkeypatch.setattr(Path, "read_text", fake_read) - monkeypatch.setattr("inferrsi.harness.confinement.subprocess.run", blocked) + monkeypatch.setattr("inferrsi.harness.executor.confinement.subprocess.run", blocked) assert namespaces_available() is False diff --git a/tests/harness/test_harness_entry_verification.py b/tests/harness/test_harness_entry_verification.py index 748753f51..7a5dbffeb 100644 --- a/tests/harness/test_harness_entry_verification.py +++ b/tests/harness/test_harness_entry_verification.py @@ -18,9 +18,12 @@ from inferrsi.apps.storage.artifact_reader import ArtifactReader from inferrsi.benchmark import preparation as benchmark from inferrsi.contracts.json_v1 import decode -from inferrsi.harness import entry_code, execution_service, run_store -from inferrsi.harness.api import Harness, LocalCpuTarget -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import Harness, PublicError +from inferrsi.harness.executor import LocalCpuTarget +from inferrsi.harness.executor import _entry_code as entry_code +from inferrsi.harness.executor import _execution as execution_service +from inferrsi.harness.records import RunStore +from inferrsi.harness.records import _run_store as run_store from tests.benchmark.test_benchmark_preparation import preparation as preparation ROOT = Path(__file__).resolve().parents[2] @@ -106,7 +109,7 @@ def evaluation(preparation, tmp_path, request): "proposal": proposal, "output_root": vector["output_root"], } spec = bind_execution(request, prepared) - store = run_store.RunStore(tmp_path / "store", "test") + store = RunStore(tmp_path / "store", "test") target = LocalCpuTarget( "fixture-cpu", "1", work_root=tmp_path / "work", controller_root=controller, module_root=modules, @@ -255,7 +258,7 @@ def test_t37_fixed_mismatch_and_source_bytes_can_be_read_in_a_fresh_process( record = case["harness"].execute(case["spec"]) source.unlink() script = ( - "import sys,json,hashlib; from inferrsi.harness.run_store import RunStore,RunStoreReader; " + "import sys,json,hashlib; from inferrsi.harness.records import RunStore,RunStoreReader; " "s=RunStore(sys.argv[1],'test'); r=s.read(sys.argv[2],1); " "ref=r['checks'][0]['evidence_refs'][0]; " "stream=RunStoreReader(s.root,'test').open(ref); raw=stream.read(); stream.close(); " diff --git a/tests/harness/test_harness_evaluation_replay.py b/tests/harness/test_harness_evaluation_replay.py index cb6eefb3d..fdbf91685 100644 --- a/tests/harness/test_harness_evaluation_replay.py +++ b/tests/harness/test_harness_evaluation_replay.py @@ -12,9 +12,10 @@ import pytest from inferrsi.contracts.json_v1 import encode -from inferrsi.harness import execution_service, run_store -from inferrsi.harness.api import Harness, LocalCpuTarget -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import Harness, PublicError +from inferrsi.harness.executor import LocalCpuTarget, request_digest +from inferrsi.harness.executor import _execution as execution_service +from inferrsi.harness.records import _run_store as run_store from tests.benchmark.test_benchmark_preparation import preparation as preparation from tests.harness.test_harness_entry_verification import evaluation as evaluation @@ -63,7 +64,7 @@ def test_completed_evaluation_replays_the_original_ref_without_rebinding( replayed = replay_only(case, monkeypatch).execute(saved) assert replayed["record_ref"] == record["record_ref"] assert replayed["target_binding"] == record["target_binding"] - assert replayed["request_digest"] == run_store.request_digest(saved) + assert replayed["request_digest"] == request_digest(saved) assert replayed["budget_admission"] == record["budget_admission"] assert saved == case["spec"] assert counts(case) == (1, 1) @@ -116,7 +117,7 @@ def counted(*args, **kwargs): def test_existing_attempt_without_a_record_never_implicitly_starts(evaluation, monkeypatch, live): case = evaluation attempt = {key: case["spec"][key] for key in execution_service.ATTEMPT_FIELDS} - claim = case["store"].claim(attempt, run_store.request_digest(case["spec"])) + claim = case["store"].claim(attempt, request_digest(case["spec"])) try: if not live: claim.release() @@ -143,7 +144,7 @@ def open(self, ref): harness = Harness(case["store"], case["target"], artifact_reader=Mutating()) result = harness.execute(case["spec"]) - assert result["request_digest"] == run_store.request_digest(original) + assert result["request_digest"] == request_digest(original) assert result["budget_admission"]["scope_id"] == original["budget"]["scope_id"] assert result["started"] is True and result["exit_code"] == 0 @@ -177,7 +178,7 @@ def test_null_step_timeout_uses_original_attempt_deadline_and_cleans_the_domain( record = case["harness"].execute(saved) assert record["started"] is True and record["process_outcome"] == "timed_out" assert record["steps"][0]["status"] == "timed_out" - assert record["request_digest"] == run_store.request_digest(saved) + assert record["request_digest"] == request_digest(saved) assert saved["deadline_utc"] == case["spec"]["deadline_utc"] assert record["budget_admission"]["scope_id"] == saved["budget"]["scope_id"] assert_confirmed_cleanup(record) @@ -256,7 +257,7 @@ def forbidden(*args, **kwargs): monkeypatch.setattr(execution_service.local_process, "_supervise", forbidden) record = case["harness"].execute(saved, cancellation=cancellation) assert record["started"] is False and record["process_outcome"] == "not_started" - assert record["request_digest"] == run_store.request_digest(saved) + assert record["request_digest"] == request_digest(saved) assert record["budget_admission"]["scope_id"] == saved["budget"]["scope_id"] if limit == "cancelled": assert record["cancellation"]["requested"] is True @@ -275,12 +276,13 @@ def test_completed_request_replays_in_a_new_controller_without_archive_or_target script = ( "import json,sys; from pathlib import Path; " "from inferrsi.contracts.json_v1 import decode; " - "from inferrsi.harness import execution_service; " - "from inferrsi.harness.api import Harness,LocalCpuTarget; " - "from inferrsi.harness.run_store import RunStore; " + "from inferrsi.harness.executor import _execution as execution_service; " + "from inferrsi.harness.api import Harness; " + "from inferrsi.harness.executor import LocalCpuTarget; " + "from inferrsi.harness.records import RunStore; " "s=RunStore(sys.argv[1],'test'); spec=decode(sys.stdin.buffer.read()); " "target=LocalCpuTarget('retired','2',work_root=Path(sys.argv[1]).parent/'retired'); " - "execution_service.prepared_binding.verify=lambda *a,**k: " + "execution_service.verify_prepared_binding=lambda *a,**k: " "(_ for _ in ()).throw(RuntimeError('replay read preparation')); " "execution_service.local_process._supervise=lambda *a,**k: " "(_ for _ in ()).throw(RuntimeError('replay started a worker')); " @@ -306,7 +308,7 @@ def test_registration_race_after_lookup_still_uses_the_atomic_claim(evaluation, class Racing: def open(self, ref): if not held: - held.append(case["store"].claim(attempt, run_store.request_digest(saved))) + held.append(case["store"].claim(attempt, request_digest(saved))) return case["reader"].open(ref) monkeypatch.setattr(execution_service.local_process, "_supervise", diff --git a/tests/harness/test_harness_evidence_capture.py b/tests/harness/test_harness_evidence_capture.py index d4f31484f..627f43c79 100644 --- a/tests/harness/test_harness_evidence_capture.py +++ b/tests/harness/test_harness_evidence_capture.py @@ -12,9 +12,11 @@ import pytest from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness import evidence_capture, execution_service, run_store -from inferrsi.harness.api import Harness, LocalCpuTarget -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import Harness, PublicError +from inferrsi.harness.executor import LocalCpuTarget +from inferrsi.harness.executor import _evidence_capture as evidence_capture +from inferrsi.harness.executor import _execution as execution_service +from inferrsi.harness.records import _run_store as run_store from tests.benchmark.test_benchmark_preparation import preparation as preparation from tests.harness.test_harness_entry_verification import evaluation as evaluation diff --git a/tests/harness/test_harness_execute.py b/tests/harness/test_harness_execute.py index 795e7064e..c2160fe04 100644 --- a/tests/harness/test_harness_execute.py +++ b/tests/harness/test_harness_execute.py @@ -15,10 +15,12 @@ import pytest from inferrsi.contracts import json_v1 -from inferrsi.harness import execution_service, input_binding, local_process, run_store -from inferrsi.harness.api import Harness, LocalCpuTarget -from inferrsi.harness.errors import PublicError -from inferrsi.harness.run_store import RunStore, RunStoreReader +from inferrsi.harness.api import Harness, PublicError +from inferrsi.harness.executor import LocalCpuTarget, local_process, request_digest +from inferrsi.harness.executor import _execution as execution_service +from inferrsi.harness.executor import _input_binding as input_binding +from inferrsi.harness.records import RunStore, RunStoreReader +from inferrsi.harness.records import _run_store as run_store from tests.harness.run_store_child import REPO, child_env from tests.repository._gate_policy_support import ROOT, _scan, _walk, exact_pairs, load_manifest @@ -31,25 +33,53 @@ SCHEMA = REPO / "docs" / "contracts" / "schemas" / "contract-v1.schema.json" # The new H closure: the H01/H02 modules, the canonical encoder, and the package init # residue (the mixed ``inferrsi.harness`` __init__ loads ``inferrsi.contracts.claim``). -# execution_spec landed on main with the #397 squash 8150ee04, which also -# added it to this H02 closure. Service ownership also uses the Harness-only +# The Executor package computes the execution request digest. Service ownership uses the # atomic JSON writer, whose dependencies are all in the standard library. -# #451 C1: the encoder and the claim types live in the contracts package, so importing -# either runs the ``inferrsi.contracts`` initializer, whose single import is the RunSpec -# module. The last two names are that exact residue; a ``contracts`` prefix is never allowed. +# Importing the encoder runs the contracts initializer and loads RunSpec. The +# LocalCpuTarget leaf is reached through Executor's explicit lazy import. NEW_H_CLOSURE = { - "inferrsi.harness.api", "inferrsi.harness.execution_service", - "inferrsi.harness.input_binding", "inferrsi.harness.local_process", - "inferrsi.harness.prepared_binding", - "inferrsi.harness.entry_code", - "inferrsi.harness.evidence_capture", - "inferrsi.harness.generation_lineage", - "inferrsi.harness.atomic_json", - "inferrsi.harness.run_store", "inferrsi.harness.errors", "inferrsi.harness.execution_spec", + "inferrsi.harness.api", "inferrsi.harness.executor._execution", + "inferrsi.harness.executor._input_binding", "inferrsi.harness.executor.local_process", + "inferrsi.harness.executor._prepared_binding", + "inferrsi.harness.executor._entry_code", + "inferrsi.harness.executor._evidence_capture", + "inferrsi.harness.executor._generation_lineage", + "inferrsi.harness.executor._generation", "inferrsi.harness.executor._generation_feedback", + "inferrsi.harness.records.atomic_json", + "inferrsi.harness.records", "inferrsi.harness.api._harness", + "inferrsi.harness.records._run_store", "inferrsi.contracts._harness_errors", + "inferrsi.harness.executor", "inferrsi.harness.executor._target", "inferrsi.contracts.json_v1", - "inferrsi.harness", "inferrsi.contracts.claim", + "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. +OPTIONAL_PROTOCOL_MODULES = { + "inferrsi.harness.evaluator", + "inferrsi.harness.evaluator._measurement", + "inferrsi.harness.evaluator._project", + "inferrsi.harness.evaluator._service", + "inferrsi.harness.evaluator._service_evidence", + "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.serving", + "inferrsi.harness.executor.serving._attempt", + "inferrsi.harness.executor.serving._http", + "inferrsi.harness.executor.serving._image", + "inferrsi.harness.executor.serving._plan", + "inferrsi.harness.executor.serving._profile", + "inferrsi.harness.executor.serving._server", + "inferrsi.harness.executor.trials", + "inferrsi.harness.executor.trials.external", + "inferrsi.harness.records.artifact_primitives", + "inferrsi.harness.records.service_io", +} # Prints a grandchild's pid, then outlives any test deadline with it. TREE = ( "import os, subprocess, sys, time; " @@ -357,7 +387,7 @@ def test_h02_4_reentry_unknown_owner_and_replay_start_nothing_new(h: Harness, tm # A registration whose owner left without a record is never taken over or rerun. orphan = make_spec(h, [step(counter_code(marker))]) attempt = {name: orphan[name] for name in execution_service.ATTEMPT_FIELDS} - h._store.claim(attempt, run_store.request_digest(orphan)).release() + h._store.claim(attempt, request_digest(orphan)).release() unknown = error_of(h.execute, orphan) assert (unknown.code, unknown.started, unknown.latest_record_ref) == ( "RecoveryRequired", None, None, @@ -469,8 +499,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 | OPTIONAL_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 " diff --git a/tests/harness/test_harness_feedback_policy.py b/tests/harness/test_harness_feedback_policy.py index 4ded5d45d..a4ea054d4 100644 --- a/tests/harness/test_harness_feedback_policy.py +++ b/tests/harness/test_harness_feedback_policy.py @@ -12,9 +12,9 @@ import pytest from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness import run_store -from inferrsi.harness.errors import PublicError -from inferrsi.harness.generation import prepare_generation +from inferrsi.harness.api import PublicError +from inferrsi.harness.executor import prepare_generation, request_digest +from inferrsi.harness.records import _run_store as run_store from tests.apps.test_apps_generation_plan import _fixed_input, _provider from tests.apps.test_apps_generation_plan import generation as generation from tests.harness.test_harness_generation_seal import cpu_generation as cpu_generation @@ -53,7 +53,7 @@ def authorized(cpu_generation, generation, request): payload = decode((FIXTURES / "record-payload.json").read_bytes()) for key in attempt.keys() & payload.keys(): payload[key] = deepcopy(attempt[key]) - payload["request_digest"] = run_store.request_digest(spec) + payload["request_digest"] = request_digest(spec) prepared = decode((FIXTURES / "prepared.json").read_bytes()) protocol_bytes, prepared_bytes = ((FIXTURES / name).read_bytes() for name in ("protocol.json", "prepared.json")) @@ -166,8 +166,10 @@ def test_opt_in_retains_policy_and_allowed_proof_for_real_generation(authorized) def test_registered_policy_generation_replays_before_fresh_authorization( authorized, monkeypatch, tmp_path, fault, ): - from inferrsi.harness import execution_service, generation_feedback - from inferrsi.harness.api import Harness, LocalCpuTarget + from inferrsi.harness.api import Harness + from inferrsi.harness.executor import LocalCpuTarget + from inferrsi.harness.executor import _execution as execution_service + from inferrsi.harness.executor import _generation_feedback as generation_feedback store, _, harness, _, _, _, _, _, _ = authorized spec = prepare(authorized) @@ -375,8 +377,8 @@ def test_authorization_imports_no_other_business_module_in_a_child(authorized, t child = """ import io, json, sys sys.path.insert(0, sys.argv[1]) -from inferrsi.harness.generation_feedback import verify -from inferrsi.harness.run_store import RunStoreReader +from inferrsi.harness.executor._generation_feedback import verify +from inferrsi.harness.records import RunStoreReader data = json.load(open(sys.argv[2], encoding='utf-8')) class Reader: def open(self, ref): diff --git a/tests/harness/test_harness_generation_bounds.py b/tests/harness/test_harness_generation_bounds.py index 7c4db4b75..f60c7682a 100644 --- a/tests/harness/test_harness_generation_bounds.py +++ b/tests/harness/test_harness_generation_bounds.py @@ -12,9 +12,10 @@ import pytest from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness import run_store -from inferrsi.harness.errors import PublicError -from inferrsi.harness.generation import prepare_generation +from inferrsi.harness.api import PublicError +from inferrsi.harness.executor import prepare_generation, request_digest +from inferrsi.harness.records import RunStoreReader +from inferrsi.harness.records import _run_store as run_store from tests.apps.test_apps_generation_plan import generation as generation from tests.harness.test_harness_generation_seal import cpu_generation as cpu_generation @@ -25,7 +26,7 @@ def expected_bounds(spec, plan_ref): **{key: deepcopy(spec[key]) for key in ( "attempt_id", "run_id", "owner", "deadline_utc", "budget", )}, - "generation_plan": plan_ref, "request_digest": run_store.request_digest(spec), + "generation_plan": plan_ref, "request_digest": request_digest(spec), } @@ -33,7 +34,7 @@ def test_bounds_are_committed_with_the_unchanged_plan_and_read_in_a_new_process( cpu_generation, tmp_path, ): store, target, harness, _, inputs = cpu_generation - reader = run_store.RunStoreReader(store.root, store.namespace) + reader = RunStoreReader(store.root, store.namespace) attempt_id = inputs["attempt"]["attempt_id"] assert reader._read_generation_bounds(attempt_id) is None spec = prepare_generation(store, target, **inputs) @@ -57,7 +58,7 @@ def test_bounds_are_committed_with_the_unchanged_plan_and_read_in_a_new_process( import sys sys.path.insert(0, sys.argv[1]) from inferrsi.contracts.json_v1 import encode -from inferrsi.harness.run_store import RunStoreReader +from inferrsi.harness.records import RunStoreReader sys.stdout.buffer.write(encode( RunStoreReader(sys.argv[2], 'generation')._read_generation_bounds(sys.argv[3]) )) @@ -71,7 +72,7 @@ def test_bounds_are_committed_with_the_unchanged_plan_and_read_in_a_new_process( def test_failed_plan_commit_publishes_no_bounds(cpu_generation, monkeypatch): store, target, _, _, inputs = cpu_generation - reader = run_store.RunStoreReader(store.root, store.namespace) + reader = RunStoreReader(store.root, store.namespace) attempt_id = inputs["attempt"]["attempt_id"] original_transaction = run_store._transaction writes = 0 @@ -149,7 +150,7 @@ def legacy_seal(id_, role, data, *, descriptor=None, **kwargs): descriptor = connection.execute( "SELECT descriptor FROM generation_inputs WHERE role = 'generation-plan'", ).fetchone()[0] - assert descriptor == encode({"request_digest": run_store.request_digest(spec)}) + assert descriptor == encode({"request_digest": request_digest(spec)}) assert store._read_generation_bounds(spec["attempt_id"]) == expected assert harness.execute(spec)["exit_code"] == 0 @@ -201,7 +202,7 @@ def test_corrupt_bounds_fail_closed_without_mutating_the_original( if fault == "orphan": connection.execute("DROP TRIGGER generation_inputs_no_delete") connection.execute("DELETE FROM generation_inputs WHERE role = 'generation-plan'") - reader = run_store.RunStoreReader(damaged, store.namespace) + reader = RunStoreReader(damaged, store.namespace) with pytest.raises(PublicError, match="ArtifactIntegrityError") as caught: reader._read_generation_bounds(attempt_id) assert caught.value.stage == "read_generation_bounds" @@ -233,7 +234,7 @@ def test_full_declared_budget_is_retained_without_reserving_or_admitting_it(cpu_ def test_bounds_storage_error_is_not_reported_as_a_missing_snapshot(cpu_generation, monkeypatch): store, _, _, _, inputs = cpu_generation - reader = run_store.RunStoreReader(store.root, store.namespace) + reader = RunStoreReader(store.root, store.namespace) def unavailable(): raise sqlite3.OperationalError("synthetic read failure") @@ -256,4 +257,4 @@ def test_internal_bounds_slot_is_not_a_new_public_artifact_location(cpu_generati "sha256": digest, "size_bytes": len(data), "media_type": "application/json", } with pytest.raises(PublicError, match="UnsafeArtifactPath"): - run_store.RunStoreReader(store.root, store.namespace).open(guess) + RunStoreReader(store.root, store.namespace).open(guess) diff --git a/tests/harness/test_harness_generation_lineage.py b/tests/harness/test_harness_generation_lineage.py index 12575daef..47d0ede7f 100644 --- a/tests/harness/test_harness_generation_lineage.py +++ b/tests/harness/test_harness_generation_lineage.py @@ -18,10 +18,11 @@ from inferrsi.benchmark import assessment, cpu_smoke, preparation, proofs from inferrsi.benchmark.workers import fixture_worker as worker from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness import execution_service, generation_lineage, run_store -from inferrsi.harness.api import Harness -from inferrsi.harness.errors import PublicError -from inferrsi.harness.generation import prepare_generation +from inferrsi.harness.api import Harness, PublicError +from inferrsi.harness.executor import _execution as execution_service +from inferrsi.harness.executor import _generation_lineage as generation_lineage +from inferrsi.harness.executor import prepare_generation, request_digest +from inferrsi.harness.records import _run_store as run_store from tests.apps.test_apps_generation_plan import _fixed_input from tests.apps.test_apps_generation_plan import generation as generation from tests.harness.test_harness_generation_seal import cpu_generation as cpu_generation @@ -537,7 +538,7 @@ def broken_append(*args, **kwargs): def test_registered_lineage_without_record_uses_existing_state(lineage, monkeypatch, live): store, spec = lineage["store"], lineage["spec"] claim = store.claim({key: spec[key] for key in execution_service.ATTEMPT_FIELDS}, - run_store.request_digest(spec)) + request_digest(spec)) try: if not live: claim.release() @@ -602,9 +603,11 @@ def unavailable(*args, **kwargs): sys.path.insert(0, sys.argv[1]) from inferrsi.apps import api from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness import generation_lineage -from inferrsi.harness.api import Harness, LocalCpuTarget -from inferrsi.harness.run_store import Claim, RunStore +from inferrsi.harness.executor import _generation_lineage as generation_lineage +from inferrsi.harness.api import Harness +from inferrsi.harness.executor import LocalCpuTarget +from inferrsi.harness.records import RunStore +from inferrsi.harness.records._run_store import Claim root = Path(sys.argv[2]) load = lambda name: decode((root / name).read_bytes()) store = RunStore(root / 'store', 'generation') diff --git a/tests/harness/test_harness_generation_seal.py b/tests/harness/test_harness_generation_seal.py index d2f03d838..ace262755 100644 --- a/tests/harness/test_harness_generation_seal.py +++ b/tests/harness/test_harness_generation_seal.py @@ -15,10 +15,10 @@ from inferrsi.apps.handoff.context_provider import ContextProvider from inferrsi.apps.workflows.knowledge import knowledge_reader from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness import run_store -from inferrsi.harness.api import Harness, LocalCpuTarget -from inferrsi.harness.errors import PublicError -from inferrsi.harness.generation import prepare_generation +from inferrsi.harness.api import Harness, PublicError +from inferrsi.harness.executor import LocalCpuTarget, prepare_generation, request_digest +from inferrsi.harness.records import RunStore, RunStoreReader +from inferrsi.harness.records import _run_store as run_store from tests.apps.test_apps_generation_plan import _fixed_input, _provider from tests.apps.test_apps_generation_plan import generation as generation @@ -27,7 +27,7 @@ @pytest.fixture def cpu_generation(generation, tmp_path): - store = run_store.RunStore(tmp_path / "store", "generation") + store = RunStore(tmp_path / "store", "generation") target_request = generation["attempt"]["target_request"] target = LocalCpuTarget(target_request["target_id"], target_request["config_revision"], tmp_path / "work") @@ -98,7 +98,7 @@ def test_seal_commits_context_and_plan_before_cpu_execution(cpu_generation): assert prepare_generation(store, target, **inputs) == spec record = harness.execute(spec) - assert record["request_digest"] == run_store.request_digest(spec) + assert record["request_digest"] == request_digest(spec) assert record["attempt_id"] == attempt_id assert record["exit_code"] == 0 proposal = inputs["candidate_provider"].collect_candidate(record, artifacts=store) @@ -108,7 +108,7 @@ def test_seal_commits_context_and_plan_before_cpu_execution(cpu_generation): child = """ import sys -from inferrsi.harness.run_store import RunStoreReader +from inferrsi.harness.records import RunStoreReader from inferrsi.contracts.json_v1 import encode reader = RunStoreReader(sys.argv[1], 'generation') delivery = reader.read_delivered_context(sys.argv[2]) @@ -133,7 +133,7 @@ def test_retention_failure_exposes_neither_context_nor_plan( prospective_ref = run_store._generation_ref( store.namespace, run_store.attempt_hash(attempt_id), "delivered-context", draft.content, ) - reader = run_store.RunStoreReader(store.root, store.namespace) + reader = RunStoreReader(store.root, store.namespace) transact = run_store._transaction @contextmanager @@ -281,4 +281,4 @@ def test_retry_cannot_change_the_final_spec_after_the_manifest_commits(cpu_gener assert "request_digest" not in decode(stream.read()) record = harness.execute(original) assert record["exit_code"] == 0 - assert record["request_digest"] == run_store.request_digest(original) + assert record["request_digest"] == request_digest(original) diff --git a/tests/harness/test_harness_improvement.py b/tests/harness/test_harness_improvement.py index 149d261c1..40d5dac8a 100644 --- a/tests/harness/test_harness_improvement.py +++ b/tests/harness/test_harness_improvement.py @@ -7,8 +7,8 @@ from inferrsi.apps.workflows.improvement import assessment, choose, holdout_accepts from inferrsi.benchmark.improvement import SelectionPolicy -from inferrsi.harness.skill_evaluation import CodexClient -from inferrsi.harness.usage import usage_totals +from inferrsi.harness.executor.skill_evaluation import CodexClient +from inferrsi.harness.records.usage import usage_totals from tests.fixtures.harness_improvement_demo import ScriptedClient, configuration from tests.fixtures.skill_eval_compare_support import git from tools import skill_eval_compare as compare @@ -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_harness_measurement.py b/tests/harness/test_harness_measurement.py index 7cc066d29..dba784118 100644 --- a/tests/harness/test_harness_measurement.py +++ b/tests/harness/test_harness_measurement.py @@ -7,9 +7,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, @@ -20,6 +20,7 @@ profile_evidence, validate_mechanism, ) +from inferrsi.harness.manager import session_runtime_identity BASE = [10.0, 10.1, 9.9, 10.05, 9.95, 10.02] GAIN = [8.0, 8.1, 7.9, 8.02, 7.98, 8.01] @@ -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 session_runtime_identity() def profiles(rows, jitter=None): diff --git a/tests/harness/test_harness_prepared_binding.py b/tests/harness/test_harness_prepared_binding.py index f0d3911de..5af2b5edd 100644 --- a/tests/harness/test_harness_prepared_binding.py +++ b/tests/harness/test_harness_prepared_binding.py @@ -10,9 +10,17 @@ from inferrsi.apps.handoff.bridge import bind_execution, verify_protocol from inferrsi.contracts.json_v1 import decode, encode -from inferrsi.harness import execution_service, prepared_binding, run_store -from inferrsi.harness.api import Harness, LocalCpuTarget -from inferrsi.harness.errors import PublicError +from inferrsi.harness.api import Harness, PublicError +from inferrsi.harness.executor import ( + LocalCpuTarget, + project_prepared_binding, + read_prepared_binding, + request_digest, + verify_prepared_binding, +) +from inferrsi.harness.executor import _execution as execution_service +from inferrsi.harness.records import RunStore +from inferrsi.harness.records import _run_store as run_store ROOT = Path(__file__).resolve().parents[2] GOLDEN = ROOT / "docs/contracts/fixtures/t108-v4" @@ -33,7 +41,7 @@ def test_d023_null_timeout_bytes_match_apps_and_harness(): } assert len(data) == 2069 assert "sha256:" + sha256(data).hexdigest() == DIGEST - assert run_store.request_digest(spec) == DIGEST + assert request_digest(spec) == DIGEST assert encode(bind_execution(request, prepared)) == data assert spec["steps"][0]["timeout_seconds"] is None @@ -54,7 +62,7 @@ def open(self, ref): return BytesIO(self.data) reader = Reader() - store = run_store.RunStore(tmp_path / "store", "binding-tests") + store = RunStore(tmp_path / "store", "binding-tests") target = LocalCpuTarget("fixture-cpu", "1", work_root=tmp_path / "work") harness = Harness(store, target, artifact_reader=reader) @@ -75,10 +83,14 @@ def assert_empty(store): def test_projection_reads_the_fixed_preparation_without_resolving_an_entry(binding): spec, reader, store, harness = binding - fixed = prepared_binding.verify(spec, reader) + fixed = verify_prepared_binding(spec, reader) assert fixed.prepared_id == spec["prepared_ref"]["prepared_id"] assert fixed.code_sha256 == spec["steps"][0]["expected_code_sha256"] assert len(reader.opens) == 1 + data = read_prepared_binding(spec["prepared_ref"]["artifact"], reader) + assert data == reader.data + assert project_prepared_binding(data) == fixed + assert reader.opens == [spec["prepared_ref"]["artifact"]] * 2 # T37 is a later delivery: valid evaluation bindings still cannot start. with pytest.raises(PublicError) as caught: harness.execute(spec) @@ -319,7 +331,7 @@ def open(self, ref): elif mode == "wrong-hash": original["sha256"] = "0" * 64 with pytest.raises(PublicError) as caught: - prepared_binding.verify(spec, None if mode == "missing" else Tracked()) + verify_prepared_binding(spec, None if mode == "missing" else Tracked()) assert caught.value.code == ("ArtifactUnavailable" if mode in {"missing", "os-error"} else "ArtifactIntegrityError") if mode not in {"missing", "os-error"}: @@ -338,7 +350,7 @@ def open(self, ref): return BytesIO(b"{}") with pytest.raises(PublicError) as caught: - prepared_binding.verify(spec, Mutating()) + verify_prepared_binding(spec, Mutating()) assert caught.value.code == "ArtifactIntegrityError" assert spec["prepared_ref"]["artifact"] == original assert_empty(store) @@ -352,5 +364,5 @@ def open(self, ref): raise TypeError("broken host reader") with pytest.raises(TypeError, match="broken host reader"): - prepared_binding.verify(spec, Broken()) + verify_prepared_binding(spec, Broken()) assert_empty(store) diff --git a/tests/harness/test_harness_run_store.py b/tests/harness/test_harness_run_store.py index 3523d1702..10c5333c3 100644 --- a/tests/harness/test_harness_run_store.py +++ b/tests/harness/test_harness_run_store.py @@ -19,9 +19,11 @@ import pytest from inferrsi.contracts import json_v1 -from inferrsi.harness import run_store -from inferrsi.harness.errors import PublicError -from inferrsi.harness.run_store import Claim, CommittedRecord, RunStore, RunStoreReader +from inferrsi.harness.api import PublicError +from inferrsi.harness.executor import request_digest +from inferrsi.harness.records import RunStore, RunStoreReader +from inferrsi.harness.records import _run_store as run_store +from inferrsi.harness.records._run_store import Claim, CommittedRecord from tests.harness.run_store_child import ( ARTIFACT, ARTIFACT_MEDIA_TYPE, @@ -39,17 +41,15 @@ NAMESPACE = "h01-test" SRC = REPO / "src" NEW_H_CLOSURE = { - "inferrsi.harness.run_store", "inferrsi.harness.errors", - "inferrsi.harness.execution_spec", "inferrsi.contracts.json_v1", + "inferrsi.harness.records", "inferrsi.harness.records._run_store", + "inferrsi.contracts._harness_errors", + "inferrsi.contracts.json_v1", } # #451 C1: the canonical encoder lives in the contracts package, so importing it runs the # ``inferrsi.contracts`` initializer, whose single import is the RunSpec module. These are # the two exact names that initializer adds; a ``contracts`` prefix is never allowed. CONTRACTS_INIT = {"inferrsi.contracts", "inferrsi.contracts.runspec"} -# Package initializers run on import: the existing mixed harness __init__ loads -# inferrsi.contracts.claim (the Verdict enum). This is a known residue, not an edge added -# by the new H modules. -PACKAGE_INIT_RESIDUE = {"inferrsi", "inferrsi.harness", "inferrsi.contracts.claim"} +PARENT_PACKAGES = {"inferrsi", "inferrsi.harness"} FORBIDDEN_PREFIXES = ( "inferrsi.knowledge", "inferrsi.benchmark", "inferrsi.apps", "inferrsi.evaluation", "inferrsi.catalog", "inferrsi.research", "inferrsi.knowledge_store", "inferrsi.inspection", @@ -327,7 +327,7 @@ def test_h01_6_new_h_closure_reaches_no_legacy_k_b_or_apps_module() -> None: # Static closure: explicit imports of the new H modules, followed transitively. The # encoder import passes through the contracts initializer and its RunSpec module. closure: set[str] = set() - pending = ["inferrsi.harness.run_store"] + pending = ["inferrsi.harness.records"] while pending: module = pending.pop() if module not in closure: @@ -335,11 +335,9 @@ def test_h01_6_new_h_closure_reaches_no_legacy_k_b_or_apps_module() -> None: pending.extend(_inferrsi_imports(module)) assert closure == NEW_H_CLOSURE | CONTRACTS_INIT - # Runtime: importing a submodule also runs each parent package's __init__. The mixed - # ``inferrsi.harness`` __init__ loads ``inferrsi.contracts.claim`` (the Verdict enum). - # That is a known residue of the existing package, not a legacy, K, B, or Apps module. + # The fresh interpreter also loads the parent packages of Records. code = ( - "import json, sys, inferrsi.harness.run_store; " + "import json, sys; from inferrsi.harness.records import RunStore; " "print(json.dumps(sorted(m for m in sys.modules if m.split('.')[0] == 'inferrsi')))" ) result = subprocess.run( @@ -351,9 +349,8 @@ def test_h01_6_new_h_closure_reaches_no_legacy_k_b_or_apps_module() -> None: assert not [m for m in loaded if m.startswith(FORBIDDEN_PREFIXES)] # Keep the static graph exact. The runtime set may also include inferrsi._version # when setuptools_scm has written the gitignored file after `pip install -e`. - allowed = NEW_H_CLOSURE | CONTRACTS_INIT | PACKAGE_INIT_RESIDUE | {"inferrsi._version"} - assert loaded <= allowed - assert NEW_H_CLOSURE | CONTRACTS_INIT | PACKAGE_INIT_RESIDUE <= loaded + expected = NEW_H_CLOSURE | CONTRACTS_INIT | PARENT_PACKAGES + assert loaded - {"inferrsi._version"} == expected def test_commit_rejects_unbacked_or_foreign_artifact_refs(tmp_path: Path) -> None: @@ -534,7 +531,7 @@ def test_reader_routes_only_its_own_mount_and_locations(tmp_path: Path) -> None: def test_request_digest_matches_the_d023_anchor() -> None: spec = (FIXTURES.parent / "execution-spec-d023.json").read_bytes() manifest = json.loads((FIXTURES.parent / "MANIFEST-d023.json").read_text(encoding="utf-8")) - assert run_store.request_digest(json_v1.decode(spec)) == manifest["files"][0]["request_digest"] + assert request_digest(json_v1.decode(spec)) == manifest["files"][0]["request_digest"] def test_reentry_of_unknown_side_effect_is_recovery_required_even_with_owner_lock( diff --git a/tests/harness/test_local_executor.py b/tests/harness/test_local_executor.py index 311f5e238..3405e34ed 100644 --- a/tests/harness/test_local_executor.py +++ b/tests/harness/test_local_executor.py @@ -3,6 +3,29 @@ import subprocess import sys from pathlib import Path +from types import SimpleNamespace + +import pytest + +from inferrsi.harness.executor import local_process, process_group_empty + + +@pytest.mark.parametrize("error,expected", [(None, False), (ProcessLookupError, True), + (PermissionError, None)]) +def test_process_group_cleanup_receipt(monkeypatch, error, expected): + def killpg(group, signal): + assert (group, signal) == (81, 0) + if error is not None: + raise error() + + monkeypatch.setattr(local_process, "os", SimpleNamespace(killpg=killpg)) + monkeypatch.setattr(local_process, "_DRAIN_SECONDS", 0) + assert process_group_empty(81) is expected + + +def test_process_group_cleanup_without_a_native_probe(monkeypatch): + monkeypatch.setattr(local_process, "os", SimpleNamespace()) + assert process_group_empty(81) is None def test_local_executor_does_not_inherit_parent_stdin(tmp_path): @@ -19,7 +42,7 @@ def test_local_executor_does_not_inherit_parent_stdin(tmp_path): "import sys\n" "import time\n" "from pathlib import Path\n" - "from inferrsi.harness.local_process import execute_command\n" + "from inferrsi.harness.executor.local_process import execute_command\n" "command = (sys.executable, str(Path(__file__).with_name('child.py')))\n" "result = execute_command(command, Path.cwd(), Path('trial'), time.monotonic() + 30)\n" "print(json.dumps({'status': result['status']}))\n", 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_parallel_round.py b/tests/harness/test_parallel_round.py index 4b33ddf08..a3b437fa3 100644 --- a/tests/harness/test_parallel_round.py +++ b/tests/harness/test_parallel_round.py @@ -12,25 +12,33 @@ import pytest from inferrsi.apps.workflows.parallel_round import close_round, serve_ticket -from inferrsi.harness import parallel_round -from inferrsi.harness.confinement import ( +from inferrsi.harness.executor.confinement import ( ConfinementUnavailable, FixtureBackend, UnreapedCommand, UnshareBackend, namespaces_available, ) -from inferrsi.harness.device_lease import DeviceLease, LeaseError -from inferrsi.harness.parallel_round import ( +from inferrsi.harness.executor.device_lease import DeviceLease, LeaseError +from inferrsi.harness.manager import ( + _parallel_round as parallel_round, +) +from inferrsi.harness.manager import ( + parallel_ticket_status as ticket_status, +) +from inferrsi.harness.manager import ( + prepare_parallel_round as prepare, +) +from inferrsi.harness.manager import ( + submit_parallel_ticket as submit, +) +from inferrsi.harness.manager._parallel_round import ( RoundPlanError, _read_nofollow, _ticket_metadata_path, _tree_digest, hold_devices, materialize, - prepare, - submit, - ticket_status, ) WHEN = datetime(2026, 10, 30, tzinfo=timezone.utc) @@ -163,7 +171,7 @@ def test_two_acquires_do_not_share_one_device(self, tmp_path): worker = """ import sys from pathlib import Path -from inferrsi.harness.device_lease import DeviceLease, LeaseError +from inferrsi.harness.executor.device_lease import DeviceLease, LeaseError try: with DeviceLease(Path(sys.argv[1])).acquire("cpu-0"): diff --git a/tests/harness/test_project_objectives.py b/tests/harness/test_project_objectives.py index 1a2c7270f..0a0dccdf7 100644 --- a/tests/harness/test_project_objectives.py +++ b/tests/harness/test_project_objectives.py @@ -4,7 +4,30 @@ import pytest -from inferrsi.harness.project_service import better, change, performance, quality_passed +from inferrsi.harness import evaluator + + +def test_service_decisions_use_the_recorded_role_and_performance_gate(): + gate = {"passed": True} + quality = {"reference_path": "quality/baseline.json"} + baseline = evaluator.service_measurement_decision("baseline", None, gate, quality) + candidate = evaluator.service_measurement_decision("candidate", None, gate, quality) + assert baseline.assessment is candidate.assessment is None + assert baseline.quality_reference == quality["reference_path"] + assert candidate.quality_reference is None + + parent = evaluator.service_measurement_decision("baseline", "parent", gate, quality) + assert parent.assessment["reason"] == "performance_reference_refreshed" + assert parent.assessment["eligible"] is False + assert parent.skipped == ((("quality", "profile"), "performance_reference_only"),) + + missed = evaluator.service_measurement_decision("candidate", None, {"passed": False}, quality) + assert missed.assessment["verdict"] == "FAIL" + assert missed.skipped == ((("quality",), "performance_gate_not_met"),) + assert evaluator.service_profile_eligible(missed.assessment["reason"]) + rejected = evaluator.service_quality_decision("candidate", gate, False) + assert rejected.skipped == ((("profile",), "quality_gate_not_met"),) + assert not evaluator.service_profile_eligible(rejected.assessment["reason"]) def objective(direction="minimize", kind="relative_percent"): @@ -23,16 +46,16 @@ def objective(direction="minimize", kind="relative_percent"): @pytest.mark.parametrize("direction,sign", [("minimize", -1), ("maximize", 1)]) def test_zero_thresholds_and_both_directions(direction, sign): obj = objective(direction) - assert change(obj, 0, 0) == 0 + assert evaluator.service_metric_change(obj, 0, 0) == 0 with pytest.raises(ValueError, match="Undefined"): - change(obj, 1, 0) + evaluator.service_metric_change(obj, 1, 0) for kind in ("absolute", "percentage_point"): obj["threshold_type"] = kind - assert change(obj, 2, 0) == sign * 2 - assert change(obj, 0, 0) == 0 + assert evaluator.service_metric_change(obj, 2, 0) == sign * 2 + assert evaluator.service_metric_change(obj, 0, 0) == 0 obj.update(gain_threshold=0, parent_regression_limit=0, cumulative_regression_limit=0) config = {"objectives": [obj]} - assert not performance( + assert not evaluator.assess_service_performance( config, {"values": {"a": 1}}, {"values": {"a": 1}}, {"values": {"a": 1}} )["passed"] @@ -42,40 +65,48 @@ def test_combined_gain_and_dual_limits_include_exact_boundary(): b["id"] = "b" config = {"objectives": [a, b], "ranking": ["a", "b"]} base = {"values": {"a": 100, "b": 100}} - assert performance(config, {"values": {"a": 95, "b": 103}}, base, base)["passed"] - assert not performance(config, {"values": {"a": 95, "b": 104}}, base, base)["passed"] + assert evaluator.assess_service_performance( + config, {"values": {"a": 95, "b": 103}}, base, base + )["passed"] + assert not evaluator.assess_service_performance( + config, {"values": {"a": 95, "b": 104}}, base, base + )["passed"] parent = {"values": {"a": 95, "b": 102}} - assert not performance(config, {"values": {"a": 90, "b": 104}}, parent, base)["passed"] - assert better(config, {"a": 95, "b": 103}, base["values"]) - assert not better(config, base["values"], base["values"]) - assert not better(config, {"a": 101, "b": 10}, base["values"]) + assert not evaluator.assess_service_performance( + config, {"values": {"a": 90, "b": 104}}, parent, base + )["passed"] + assert evaluator.prefer_service_measurements(config, {"a": 95, "b": 103}, base["values"]) + assert not evaluator.prefer_service_measurements(config, base["values"], base["values"]) + assert not evaluator.prefer_service_measurements(config, {"a": 101, "b": 10}, base["values"]) def test_screening_actual_gain_is_not_an_estimated_or_formal_threshold(): obj = objective() config = {"objectives": [obj]} reference, measured = {"values": {"a": 100}}, {"values": {"a": 99}} - assert performance(config, measured, reference, reference, screening=True)["passed"] - assert not performance(config, measured, reference, reference)["passed"] + assert evaluator.assess_service_performance( + config, measured, reference, reference, screening=True + )["passed"] + assert not evaluator.assess_service_performance(config, measured, reference, reference)[ + "passed" + ] obj["gain_threshold"] = 0 - assert performance(config, measured, reference, reference)["passed"] + assert evaluator.assess_service_performance(config, measured, reference, reference)["passed"] def test_quality_requires_reference_and_has_absolute_semantics(): config = {"quality": {"mode": "absolute", "direction": "maximize", "threshold": 0.9}} - assert quality_passed(config, 0.9) + assert evaluator.service_quality_passed(config, 0.9) comparison = copy.deepcopy(config) comparison["quality"].update(mode="baseline_comparison", tolerance=0) with pytest.raises(ValueError, match="Missing compatible"): - quality_passed(comparison, 0.9) - assert quality_passed(comparison, 0.9, 0.9) - assert not quality_passed(comparison, 0.8, 0.9) + evaluator.service_quality_passed(comparison, 0.9) + assert evaluator.service_quality_passed(comparison, 0.9, 0.9) + assert not evaluator.service_quality_passed(comparison, 0.8, 0.9) @pytest.mark.parametrize("bad", [None, True, float("nan"), float("inf"), -1, 101]) def test_metric_evidence_requires_finite_domain_valid_numbers(bad): - from inferrsi.harness.project_service import aggregate - obj = objective() obj.update(scenario="s", key="metric", aggregate="mean", domain={"min": 0, "max": 100}) config = { @@ -95,4 +126,4 @@ def test_metric_evidence_requires_finite_domain_valid_numbers(bad): } } with pytest.raises(ValueError): - aggregate(config, [doc], "candidate") + evaluator.aggregate_service_measurements(config, [doc], "candidate") diff --git a/tests/harness/test_round_budget.py b/tests/harness/test_round_budget.py index 4f08cb32f..735a7b19a 100644 --- a/tests/harness/test_round_budget.py +++ b/tests/harness/test_round_budget.py @@ -5,7 +5,7 @@ import pytest -from inferrsi.harness.round_budget import ( +from inferrsi.harness.manager._round_budget import ( BudgetError, admit_from_path, advance, diff --git a/tests/harness/test_server_processes.py b/tests/harness/test_server_processes.py index b71c3c6c9..e9f00ebde 100644 --- a/tests/harness/test_server_processes.py +++ b/tests/harness/test_server_processes.py @@ -10,7 +10,8 @@ import pytest -from inferrsi.harness.serving import server as processes +from inferrsi.harness.executor import launch_server, stop_server +from inferrsi.harness.executor.serving import _server as processes @pytest.mark.parametrize("platform", ["win32", "darwin"]) @@ -18,10 +19,10 @@ def test_unsupported_platform_rejected_before_launch_or_cleanup(monkeypatch, pla monkeypatch.setattr(processes.sys, "platform", platform) with patch.object(processes.subprocess, "Popen") as launch: with pytest.raises(OSError, match="require Linux"): - processes.launch_server([], ".", {}, None) + launch_server([], ".", {}, None) launch.assert_not_called() with pytest.raises(OSError, match="require Linux"): - processes.stop_server(Mock(), {}) + stop_server(Mock(), {}) @pytest.mark.parametrize("failure", [FileNotFoundError, PermissionError]) @@ -32,21 +33,22 @@ def test_unavailable_proc_never_means_empty_group(monkeypatch, failure): processes._live_group_members(123) with patch.object(processes.subprocess, "Popen") as launch: with pytest.raises(failure): - processes.launch_server([], ".", {}, None) + launch_server([], ".", {}, None) launch.assert_not_called() with pytest.raises(failure): - processes.stop_server(Mock(), {}) + stop_server(Mock(), {}) def test_unreadable_process_table_fails_before_launch(monkeypatch): monkeypatch.setattr(processes.sys, "platform", "linux") + monkeypatch.setattr(processes.os, "getpgrp", lambda: 123, raising=False) with ( patch.object(Path, "read_text", return_value="synthetic stat"), patch.object(Path, "iterdir", side_effect=PermissionError("proc unavailable")), patch.object(processes.subprocess, "Popen") as launch, ): with pytest.raises(PermissionError): - processes.launch_server([], ".", {}, None) + launch_server([], ".", {}, None) launch.assert_not_called() @@ -67,7 +69,7 @@ def test_cleanup_after_leader_exit_preserves_unrelated_process(tmp_path, supervi # The helper runs in its own group, as it would inside the trial executor. helper = """ import json, os, sys -from inferrsi.harness.serving.server import launch_server, stop_server +from inferrsi.harness.executor import launch_server, stop_server with open(sys.argv[3], 'wb') as log: process, owner = launch_server([sys.executable, sys.argv[1], sys.argv[2]], '.', os.environ.copy(), log) diff --git a/tests/harness/test_service_backfill_recovery.py b/tests/harness/test_service_backfill_recovery.py index 4bb869e6f..67915f92f 100644 --- a/tests/harness/test_service_backfill_recovery.py +++ b/tests/harness/test_service_backfill_recovery.py @@ -6,9 +6,11 @@ import pytest -from inferrsi.harness import optimization, service_backfill -from inferrsi.harness import project_service as service -from inferrsi.harness.atomic_json import atomic_write_json +from inferrsi.harness import executor +from inferrsi.harness.manager import _service_backfill as service_backfill +from inferrsi.harness.manager import _state as optimization +from inferrsi.harness.records import service_io +from inferrsi.harness.records.atomic_json import atomic_write_json from tests.fixtures.service_reuse import begin, call, settings, submit from tests.fixtures.service_reuse import campaign as campaign @@ -18,8 +20,8 @@ def test_delayed_recover_only_accounts_for_durable_backfill_progress(campaign, m begin(campaign) attempt = submit(campaign, version="profile-target", a=90)["latest_observation"] root = campaign["root"] - original = service.read(root / "state.json") - original_plan = service.read(root / "plan.json") + original = service_io.read(root / "state.json") + original_plan = service_io.read(root / "plan.json") now = time.time() def crash(root, directory, plan, pending, deadline): @@ -47,11 +49,11 @@ def crash(root, directory, plan, pending, deadline): ) raise SystemExit(75) - monkeypatch.setattr(service, "execute", crash) + monkeypatch.setattr(executor, "execute_service_attempt", crash) with pytest.raises(SystemExit) as stopped: call(campaign, "profile", "--round", 1) assert stopped.value.code == 75 - pending = service.read(root / "state.json")["pending"] + pending = service_io.read(root / "state.json")["pending"] capture = pending["attempt_id"] evidence = root / "inspection.json" atomic_write_json( @@ -71,7 +73,7 @@ def crash(root, directory, plan, pending, deadline): assert "Profiler driver interrupted" in recovered["profiling_error"]["message"] assert (root / recovered["profiling_error"]["log"]).is_file() status = call(campaign, "recover") - state = service.read(root / "state.json") + state = service_io.read(root / "state.json") assert state["attempts"] == original["attempts"] and state["best"] == original["best"] assert state["pending"] is None assert state["profiling_accounting"] == { @@ -106,7 +108,7 @@ def test_backfill_timeout_in_readiness_preserves_inline_and_runs_cleanup(campaig assert result["profiling_error"]["status"] == "timed_out" assert result["profiling"] == attempt["profiling"] path = campaign["root"] / attempt["path"] / "backfills" / result["capture_id"] - steps = service.read(path / "execution/execution.json")["steps"] + steps = service_io.read(path / "execution/execution.json")["steps"] assert any(step["id"] == "stop" and step["status"] == "completed" for step in steps) @@ -117,11 +119,11 @@ def test_backfill_rejects_incompatible_or_unverifiable_inputs(campaign, input_na root = campaign["root"] if input_name == "conditions": path = root / "state.json" - data = service.read(path) + data = service_io.read(path) data["conditions"]["topology"] = "different topology" else: path = root / target["path"] / input_name - data = service.read(path) + data = service_io.read(path) data["mode" if input_name == "effective-config.json" else "run_id"] = "unexpected" atomic_write_json(path, data) result = call(campaign, "profile", "--round", 1, expected=2) @@ -139,7 +141,7 @@ def test_older_compatible_epoch_can_be_profiled_without_enabling_final(campaign) atomic_write_json(path, conditions) call(campaign, "refresh-references", "--conditions", path, "--reason", "New configuration") capture = call(campaign, "profile", "--round", 1) - receipt = service.read(root / capture["profiling"]["result"]) + receipt = service_io.read(root / capture["profiling"]["result"]) assert receipt["binding"]["conditions"] == target["conditions"] assert receipt["binding"]["effective_config"] == target["conditions"]["effective_config"] status = call(campaign, "status") @@ -153,7 +155,7 @@ def test_damaged_most_recent_capture_falls_back_to_earlier_published_capture(cam second = call(campaign, "profile", "--round", 1) path = campaign["root"] / target["path"] / "backfills" / second["capture_id"] execution = path / "execution/execution.json" - atomic_write_json(execution, {**service.read(execution), "profile": ["invalid"]}) + atomic_write_json(execution, {**service_io.read(execution), "profile": ["invalid"]}) status = call(campaign, "status") assert status["latest_observation"]["profiling"] == first assert status["can_finalize"] is True @@ -174,15 +176,15 @@ def crash_at_state_commit(path, value): with pytest.raises(SystemExit) as stopped: call(campaign, "profile", "--round", 1) assert stopped.value.code == 75 - capture_id = service.read(root / "state.json")["pending"]["attempt_id"] + capture_id = service_io.read(root / "state.json")["pending"]["attempt_id"] index = root / target["path"] / "backfills/index.json" - assert service.read(index)["captures"] == [capture_id] + assert service_io.read(index)["captures"] == [capture_id] recovered = call(campaign, "recover") assert recovered["capture_id"] == capture_id and recovered["profiling"]["available"] call(campaign, "recover") - state = service.read(root / "state.json") + state = service_io.read(root / "state.json") assert state["pending"] is None and capture_id in state["profiling_accounting"] - assert service.read(index)["captures"] == [capture_id] + assert service_io.read(index)["captures"] == [capture_id] @pytest.mark.parametrize("crash", [None, "after_index", "before_commit"]) @@ -190,7 +192,7 @@ def test_backfill_publication_charges_only_proven_work(campaign, monkeypatch, cr begin(campaign) target = submit(campaign, version="publish-clock", a=90)["latest_observation"] root = campaign["root"] - before = service.read(root / "state.json") + before = service_io.read(root / "state.json") if crash is None: before["deadline"] = time.time() + 40 atomic_write_json(root / "state.json", before) @@ -239,7 +241,7 @@ def slow_write(path, document): if crash: with pytest.raises(SystemExit): call(campaign, "profile", "--round", 1) - capture_id = service.read(root / "state.json")["pending"]["attempt_id"] + capture_id = service_io.read(root / "state.json")["pending"]["attempt_id"] offset += 120 # No work ran while the coordinator was offline. hooks.setattr(optimization, "_load", load) hooks.setattr(service_backfill, "atomic_write_json", atomic_write_json) @@ -247,7 +249,7 @@ def slow_write(path, document): assert recovered["capture_id"] == capture_id else: capture_id = call(campaign, "profile", "--round", 1)["capture_id"] - execution = service.read( + execution = service_io.read( root / target["path"] / "backfills" / capture_id / "execution/execution.json" ) # Validation was checkpointed before publication. The index write's duration @@ -255,7 +257,7 @@ def slow_write(path, document): credit = {None: 103, "after_index": 137, "before_commit": 193}[crash] assert execution["publication_elapsed_seconds"] == credit assert validations == [capture_id] * (2 if crash else 1) - state = service.read(root / "state.json") + state = service_io.read(root / "state.json") ledger = state["profiling_accounting"] assert set(ledger) == set(before["profiling_accounting"]) | {capture_id} assert ledger[capture_id]["elapsed_seconds"] == pytest.approx( @@ -264,12 +266,12 @@ def slow_write(path, document): assert state["deadline"] == before["deadline"] if crash is None: assert clock.time() >= before["deadline"] - summary = service.read(root / "summary.json") + summary = service_io.read(root / "summary.json") assert summary["final_block_reason"] is None assert summary["wall_elapsed_seconds"] >= 99 # Includes report evidence verification. assert call(campaign, "status")["can_finalize"] status = call(campaign, "recover") - assert service.read(root / "state.json")["profiling_accounting"] == ledger + assert service_io.read(root / "state.json")["profiling_accounting"] == ledger assert status["remaining_seconds"] == pytest.approx( before["deadline"] + sum(row["elapsed_seconds"] for row in ledger.values()) - clock.time(), abs=0.2, @@ -323,10 +325,10 @@ def write_or_cancel(path, document): assert error["stage"] == "publication" and error["status"] == "interrupted" backfills = root / target["path"] / "backfills" published = phase in ("after_index", "report") - captures = service.read(backfills / "index.json")["captures"] + captures = service_io.read(backfills / "index.json")["captures"] capture = result["capture_id"] assert captures == ([old["capture_id"], capture] if published else [old["capture_id"]]) - execution = service.read(backfills / capture / "execution/execution.json") + execution = service_io.read(backfills / capture / "execution/execution.json") assert execution["publication_interruption" if published else "profiling_error"] == error assert (capture in result["profiling"]["result"]) == published assert call(campaign, "recover")["profiling_error"] == error diff --git a/tests/harness/test_service_capture_accounting.py b/tests/harness/test_service_capture_accounting.py index d2d98bef6..bb029acc5 100644 --- a/tests/harness/test_service_capture_accounting.py +++ b/tests/harness/test_service_capture_accounting.py @@ -5,7 +5,10 @@ import pytest -from inferrsi.harness import project_service as service +from inferrsi.harness.executor import service_capture_elapsed +from inferrsi.harness.executor.serving import _attempt +from inferrsi.harness.records import service_io +from inferrsi.harness.records.atomic_json import atomic_write_json from tests.fixtures.service_reuse import begin, call, submit from tests.fixtures.service_reuse import campaign as campaign @@ -16,7 +19,6 @@ class CoordinatorStopped(BaseException): begin(campaign) root = campaign["root"] - write = service.atomic_write_json stopped_at = None def stop_before_progress_write(path, document): @@ -32,29 +34,29 @@ def stop_before_progress_write(path, document): ): stopped_at = path raise CoordinatorStopped() - write(path, document) + atomic_write_json(path, document) with monkeypatch.context() as m: - m.setattr(service, "atomic_write_json", stop_before_progress_write) + m.setattr(_attempt, "atomic_write_json", stop_before_progress_write) with pytest.raises(CoordinatorStopped): submit(campaign, version="stage-receipt", a=90) - pending = service.read(root / "state.json")["pending"] - execution = service.read(stopped_at) + pending = service_io.read(root / "state.json")["pending"] + execution = service_io.read(stopped_at) capture = execution["capture"] step = execution["steps"][-1] assert step["status"] == "running" and "ended_at" not in capture offset = step["capture_offset_seconds"] assert offset == capture["elapsed_seconds"] path = root / pending["path"] / "execution/profile/execution.json" - receipt = service.read(path) + receipt = service_io.read(path) proven = offset + receipt["elapsed_seconds"] assert proven > offset - assert service.proven_capture_elapsed(root, pending, execution) == proven + assert service_capture_elapsed(root, pending, execution) == proven # Closed captures already include this stage. Never add a second interval. closed = {**execution, "capture": {**capture, "ended_at": 1, "elapsed_seconds": proven}} - assert service.proven_capture_elapsed(root, pending, closed) == proven + assert service_capture_elapsed(root, pending, closed) == proven for invalid in ( {**receipt, "result_path": "another-capture/result.json"}, @@ -63,23 +65,23 @@ def stop_before_progress_write(path, document): {**receipt, "elapsed_seconds": -3}, ): path.write_text(json.dumps(invalid)) - assert service.proven_capture_elapsed(root, pending, execution) == offset + assert service_capture_elapsed(root, pending, execution) == offset path.unlink() - assert service.proven_capture_elapsed(root, pending, execution) == offset + assert service_capture_elapsed(root, pending, execution) == offset start_only = {**execution, "steps": [], "capture": {**capture, "elapsed_seconds": 0}} - assert service.proven_capture_elapsed(root, pending, start_only) == 0 + assert service_capture_elapsed(root, pending, start_only) == 0 path.write_text(json.dumps(receipt)) - owner = service.read(root / pending["path"] / "service/owner.json") + owner = service_io.read(root / pending["path"] / "service/owner.json") inspection = root.parent / "inspection.json" inspected = {"service_id": owner["service_id"], "pid": owner["pid"], "domain_empty": True} - write(inspection, { + atomic_write_json(inspection, { "attempt_id": pending["attempt_id"], "observed_at": time.time(), "reason": "Inspected owner", "cleanup_complete": True, "services": [inspected], }) call(campaign, "recover", "--cleanup-receipt", inspection) call(campaign, "recover") - ledger = service.read(root / "state.json")["profiling_accounting"] + ledger = service_io.read(root / "state.json")["profiling_accounting"] assert ledger == { capture["id"]: {"started_at": capture["started_at"], "elapsed_seconds": proven} } @@ -89,7 +91,7 @@ def test_invalid_capture_progress_cannot_change_the_clock(tmp_path): pending = {"attempt_id": "capture-1"} for progress in ({}, {"elapsed_seconds": float("inf")}, {"elapsed_seconds": -1}): execution = {"capture": {"id": "capture-1", **progress}} - assert service.proven_capture_elapsed(tmp_path, pending, execution) == 0 + assert service_capture_elapsed(tmp_path, pending, execution) == 0 for steps in (None, {}, [None], ["bad stage"]): execution = {"capture": {"id": "capture-1", "elapsed_seconds": 3}, "steps": steps} - assert service.proven_capture_elapsed(tmp_path, pending, execution) == 3 + assert service_capture_elapsed(tmp_path, pending, execution) == 3 diff --git a/tests/harness/test_service_fingerprint_isolation.py b/tests/harness/test_service_fingerprint_isolation.py index 80523cfe9..662d3b22e 100644 --- a/tests/harness/test_service_fingerprint_isolation.py +++ b/tests/harness/test_service_fingerprint_isolation.py @@ -12,9 +12,11 @@ def test_service_guard_restores_lazy_import_aliases(tmp_path): check = tmp_path / "test_aliases.py" check.write_text( "def test_restored_alias():\n" - " from inferrsi.harness import artifact_primitives, project, task_protocol\n" - " assert project.sha256 is task_protocol.sha256 is artifact_primitives.sha256\n" - " assert project.sha256.__module__ == 'inferrsi.harness.artifact_primitives'\n", + " from inferrsi.harness.records import artifact_primitives\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", ) result = subprocess.run( @@ -34,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_service_profile_diagnostics.py b/tests/harness/test_service_profile_diagnostics.py index 9ad3c6a00..a826d7e13 100644 --- a/tests/harness/test_service_profile_diagnostics.py +++ b/tests/harness/test_service_profile_diagnostics.py @@ -4,7 +4,8 @@ import pytest -from inferrsi.harness import project_service as service +from inferrsi.harness.executor import service_capture_diagnostic +from inferrsi.harness.records import service_io from tests.fixtures.service_reuse import begin, call, submit from tests.fixtures.service_reuse import campaign as campaign @@ -19,8 +20,8 @@ def assert_retained_error(root, command, expected_stage): assert "collector detail" in diagnostic["message"] assert len(diagnostic["message"]) <= 2049 receipt = root / diagnostic["details_path"] - assert service.read(receipt)["error"] == ERROR_TEXT - execution = service.read(receipt.parents[1] / "execution.json") + assert service_io.read(receipt)["error"] == ERROR_TEXT + execution = service_io.read(receipt.parents[1] / "execution.json") assert execution["profiling_error"] == diagnostic assert len(json.dumps(execution)) < len(ERROR_TEXT) assert len(json.dumps(command)) < len(ERROR_TEXT) @@ -29,7 +30,7 @@ def assert_retained_error(root, command, expected_stage): def test_coordinator_failure_without_a_stage_receipt_retains_full_exception(tmp_path): directory = tmp_path / "capture" directory.mkdir() - diagnostic = service.capture_diagnostic(tmp_path, directory, "startup", "failed", ERROR_TEXT) + diagnostic = service_capture_diagnostic(tmp_path, directory, "startup", "failed", ERROR_TEXT) assert len(diagnostic["message"]) == 1024 assert (tmp_path / diagnostic["details_path"]).read_text() == ERROR_TEXT @@ -40,7 +41,7 @@ def test_nonzero_exit_links_process_receipt_even_when_script_wrote_a_result(tmp_ stage.mkdir(parents=True) (stage / "result.json").write_text('{"status":"completed"}') (stage / "execution.json").write_text('{"status":"failed","returncode":1}') - diagnostic = service.capture_diagnostic( + diagnostic = service_capture_diagnostic( tmp_path, directory, "profile", "failed", "profile: failed: exit 1", process_failed=True ) assert (tmp_path / diagnostic["details_path"]) == stage / "execution.json" @@ -70,13 +71,13 @@ def test_large_successful_profile_leaves_round_readable(campaign, backfill): assert profile["available"] receipt = root / profile["result"] - trace = service.read(receipt) + trace = service_io.read(receipt) assert trace["collector_metadata"] == "x" * payload_size for record in ( receipt.parents[1] / "execution.json", root / attempt["path"] / "observation.json", ): - assert len(json.dumps(service.read(record))) < payload_size + assert len(json.dumps(service_io.read(record))) < payload_size status = call(campaign, "status") assert status["can_finalize"] and status["rounds"][0]["profiling"] == profile assert status["best"]["attempt_id"] == attempt["attempt_id"] @@ -108,7 +109,7 @@ def test_large_collector_error_retains_round_and_backfill(campaign): def test_large_effective_config_allows_inline_and_backfill_profiles(campaign): - config = service.read(campaign["config"]) + config = service_io.read(campaign["config"]) config["conditions"]["effective_config"].update( {f"engine.option_{i:04d}": i for i in range(1500)} ) @@ -169,8 +170,8 @@ def test_large_backfill_prerequisite_failure_retains_inline_capture(campaign, fa def test_settled_legacy_large_error_is_readable_through_next_round_and_final(campaign): - from inferrsi.harness import optimization - from inferrsi.harness.atomic_json import atomic_write_json + from inferrsi.harness.manager import _state as optimization + from inferrsi.harness.records.atomic_json import atomic_write_json begin(campaign) submit(campaign, a=90, profile_mode="failed") @@ -180,7 +181,7 @@ def test_settled_legacy_large_error_is_readable_through_next_round_and_final(cam execution = old["execution"] error = execution["profiling_error"] receipt = root / error.pop("details_path") - atomic_write_json(receipt, {**service.read(receipt), "error": ERROR_TEXT}) + atomic_write_json(receipt, {**service_io.read(receipt), "error": ERROR_TEXT}) # Recreate the previous writer's settled state, including both copies of the full error. error["message"] = "profile: " + ERROR_TEXT @@ -192,9 +193,9 @@ def test_settled_legacy_large_error_is_readable_through_next_round_and_final(cam atomic_write_json(observation, old) atomic_write_json(root / "state.json", state) original = observation.read_bytes() - assert len(original) > service.JSON_SIZE_LIMIT + assert len(original) > service_io.JSON_SIZE_LIMIT with pytest.raises(ValueError, match="oversized"): - service.read(observation) + service_io.read(observation) old_state = (root / "state.json").read_bytes() status = call(campaign, "status") @@ -213,19 +214,19 @@ def test_settled_legacy_large_error_is_readable_through_next_round_and_final(cam assert ( call(campaign, "final", "--reason", "Complete")["final"]["assessment"]["verdict"] == "PASS" ) - assert len(json.dumps(optimization.read_records(root)[2])) < len(ERROR_TEXT) + assert len(json.dumps(optimization.read_session_records(root)[2])) < len(ERROR_TEXT) assert observation.read_bytes() == original assert json.loads((root / "state.json").read_text())["attempts"][1] == old with observation.open("ab") as stream: stream.write(b" ") with pytest.raises(ValueError, match="control record disagree"): - optimization.read_records(root) + optimization.read_session_records(root) def test_settled_legacy_large_profile_is_readable_through_next_round_and_final(campaign): - from inferrsi.harness import optimization - from inferrsi.harness.atomic_json import atomic_write_json + from inferrsi.harness.manager import _state as optimization + from inferrsi.harness.records.atomic_json import atomic_write_json begin(campaign) submit(campaign, a=90) @@ -235,7 +236,7 @@ def test_settled_legacy_large_profile_is_readable_through_next_round_and_final(c execution = old["execution"] profile = execution["profile"] receipt = root / profile["result"] - trace = {**service.read(receipt), "collector_metadata": "x" * (2560 * 1024)} + trace = {**service_io.read(receipt), "collector_metadata": "x" * (2560 * 1024)} atomic_write_json(receipt, trace) # The old writer embedded the same receipt in the profile step and in every selected reference. @@ -251,27 +252,27 @@ def test_settled_legacy_large_profile_is_readable_through_next_round_and_final(c atomic_write_json(directory / "execution/execution.json", execution) atomic_write_json(observation, old) atomic_write_json(root / "state.json", state) - assert observation.stat().st_size > service.JSON_SIZE_LIMIT + assert observation.stat().st_size > service_io.JSON_SIZE_LIMIT status = call(campaign, "status") assert status["can_finalize"] and status["rounds"][0]["profiling"] == old["profiling"] assert status["best"]["attempt_id"] == old["attempt_id"] assert status["best"]["profile"] == profile rejected = submit(campaign, a=70, b=120)["latest_observation"] - retained = service.read(root / rejected["path"] / "observation.json") + retained = service_io.read(root / rejected["path"] / "observation.json") assert retained["assessment"]["verdict"] == "FAIL" assert retained["best_after"]["attempt_id"] == old["attempt_id"] assert "profile" not in retained["best_after"] assert rejected["best_after"]["profile"] == {"result": old["profiling"]["result"]} accepted = submit(campaign, a=80)["latest_observation"] - selected = service.read(root / accepted["path"] / "observation.json") + selected = service_io.read(root / accepted["path"] / "observation.json") assert selected["assessment"]["verdict"] == "PASS" assert selected["parent"]["attempt_id"] == old["attempt_id"] assert "profile" not in selected["parent"] assert accepted["parent"]["profile"] == rejected["best_after"]["profile"] assert selected["best_after"]["attempt_id"] == accepted["attempt_id"] final = call(campaign, "final", "--reason", "Done")["final"] - completed = service.read(root / final["path"] / "observation.json") + completed = service_io.read(root / final["path"] / "observation.json") assert completed["assessment"]["verdict"] == "PASS" assert completed["revision"] == accepted["revision"] for record in (retained, selected, completed): @@ -280,4 +281,4 @@ def test_settled_legacy_large_profile_is_readable_through_next_round_and_final(c old["selected"] = False atomic_write_json(observation, old) with pytest.raises(ValueError, match="control record disagree"): - optimization.read_records(root) + optimization.read_session_records(root) diff --git a/tests/harness/test_service_reference_evidence.py b/tests/harness/test_service_reference_evidence.py index 1f1e1fbfc..98c9bd33f 100644 --- a/tests/harness/test_service_reference_evidence.py +++ b/tests/harness/test_service_reference_evidence.py @@ -5,7 +5,7 @@ import pytest -from inferrsi.harness import optimization +from inferrsi.harness.manager import _state as optimization from tests.fixtures.service_reuse import begin, call, rejected, settings, submit from tests.fixtures.service_reuse import campaign as campaign diff --git a/tests/harness/test_session_lock_across_processes.py b/tests/harness/test_session_lock_across_processes.py index df4480581..107870152 100644 --- a/tests/harness/test_session_lock_across_processes.py +++ b/tests/harness/test_session_lock_across_processes.py @@ -1,6 +1,6 @@ """The Harness and Apps session locks exclude each other across real processes. -Harness writers hold ``/.session.lock`` through ``harness.artifact_primitives``. +Harness writers hold ``/.session.lock`` through ``harness.records.artifact_primitives``. An Apps export holds it through ``apps.artifacts``. Each side has its own copy of the lock code, so per-copy parity tests can pass while the pair fails to exclude. These tests start a separate process for each holder, so they cover the actual writer and reader on Windows @@ -33,7 +33,7 @@ sys.path.insert(0, sys.argv[1]) side, lock, ready, release = sys.argv[2], Path(sys.argv[3]), Path(sys.argv[4]), Path(sys.argv[5]) if side == "harness": - from inferrsi.harness.artifact_primitives import file_lock + from inferrsi.harness.records.artifact_primitives import file_lock else: from inferrsi.apps.storage.artifacts import file_lock with file_lock(lock): @@ -52,7 +52,7 @@ sys.path.insert(0, sys.argv[1]) side, lock = sys.argv[2], Path(sys.argv[3]) if side == "harness": - from inferrsi.harness.artifact_primitives import file_lock + from inferrsi.harness.records.artifact_primitives import file_lock else: from inferrsi.apps.storage.artifacts import file_lock try: diff --git a/tests/harness/test_speculative_search.py b/tests/harness/test_speculative_search.py index ad686fbf0..db3c4908a 100644 --- a/tests/harness/test_speculative_search.py +++ b/tests/harness/test_speculative_search.py @@ -3,8 +3,8 @@ import pytest from inferrsi.contracts.claim import Verdict -from inferrsi.harness import candidates -from inferrsi.harness import search_tree as tree +from inferrsi.harness.executor import candidates +from inferrsi.harness.manager.search import search_tree as tree from tests.fixtures.speculative_search import ( add, attempt, 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/harness/test_vats_runtime.py b/tests/harness/test_vats_runtime.py index 47e3f1555..5601ae92d 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.records import RunStore +from inferrsi.harness.records.artifact_primitives import digest 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..184816179 100644 --- a/tests/harness/test_work_control.py +++ b/tests/harness/test_work_control.py @@ -1,10 +1,11 @@ +import sqlite3 import time from concurrent.futures import ThreadPoolExecutor import pytest -from inferrsi.harness.run_store import RunStore -from inferrsi.harness.work_control import WorkControl +from inferrsi.harness.manager.search.work_control import WorkControl +from inferrsi.harness.records import RunStore @pytest.fixture @@ -145,7 +146,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") @@ -282,7 +283,11 @@ def test_over_budget_final_is_accounted_but_never_promoted(control): def test_read_only_control_does_not_create_or_change_tables(control): - from inferrsi.harness.run_store import RunStoreReader + from inferrsi.harness.records import RunStoreReader reader = WorkControl(RunStoreReader(control.store.root, control.store.namespace)) - assert reader.read("campaign") == control.read("campaign") + before = control.read("campaign") + assert reader.read("campaign") == before + with pytest.raises(sqlite3.OperationalError, match="readonly"): + reader.update("campaign", before["revision"], lambda _: {"incumbent": "denied"}) + assert control.read("campaign") == before diff --git a/tests/repository/_gate_policy_support.py b/tests/repository/_gate_policy_support.py index 7d34112b1..b430cdd2a 100644 --- a/tests/repository/_gate_policy_support.py +++ b/tests/repository/_gate_policy_support.py @@ -102,7 +102,56 @@ # 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 session, runner and search modules under Manager and service execution under Executor. +RETIRED_MODULES = frozenset({ + "inferrsi.infra", + "inferrsi.model", + "inferrsi.harness.scenarios", + "inferrsi.harness.serving", + "inferrsi.harness.project_service", + "inferrsi.harness.service_evidence", + "inferrsi.harness.runner", + "inferrsi.harness.agent_sessions", + "inferrsi.harness.attempt_recovery", + "inferrsi.harness.optimization", + "inferrsi.harness.optimization_session", + "inferrsi.harness.parallel_round", + "inferrsi.harness.service_backfill", + "inferrsi.harness.session_runtime", + "inferrsi.harness.trials", + "inferrsi.harness.local_process", + "inferrsi.harness.launch_records", + "inferrsi.harness.device_lease", + "inferrsi.harness.generation", + "inferrsi.harness.generation_feedback", + "inferrsi.harness.generation_lineage", + "inferrsi.harness.prepared_binding", + "inferrsi.harness.execution_service", + "inferrsi.harness.entry_code", + "inferrsi.harness.evidence_capture", + "inferrsi.harness.input_binding", + "inferrsi.harness.artifact_sandbox", + "inferrsi.harness.candidates", + "inferrsi.harness.confinement", + "inferrsi.harness.skill_evaluation", + "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", + "inferrsi.harness.run_store", + "inferrsi.harness.errors", + "inferrsi.harness.execution_spec", + "inferrsi.harness.artifact_primitives", + "inferrsi.harness.atomic_json", + "inferrsi.harness.usage", + "inferrsi.harness.service_observations", +}) # #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 @@ -125,15 +174,19 @@ # the moved parser reads the same tuple object through ``inferrsi.knowledge.catalog``, # 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``. +# Cover the public execution and storage entries and their implementation closures. NEW_H_ENTRIES = ( "inferrsi.harness.api", - "inferrsi.harness.errors", - "inferrsi.harness.execution_service", - "inferrsi.harness.input_binding", - "inferrsi.harness.local_process", - "inferrsi.harness.run_store", + "inferrsi.contracts._harness_errors", + "inferrsi.harness.evaluator", + "inferrsi.harness.executor._execution", + "inferrsi.harness.evaluator", + "inferrsi.harness.executor", + "inferrsi.harness.executor._input_binding", + "inferrsi.harness.executor.local_process", + "inferrsi.harness.manager", + "inferrsi.harness.records", + "inferrsi.harness.records._run_store", ) # Shared data/byte contracts (#451 C1). This exact module list is the whole package. A # new module is a reviewed change to this list; an ``inferrsi.contracts.`` prefix never @@ -154,6 +207,7 @@ CONTRACTS_INIT_EXPORT[0], "inferrsi.contracts.claim", CONTRACTS_EVIDENCE, + "inferrsi.contracts._harness_errors", } ) # Names that load or build modules at run time. Any use fails closed. diff --git a/tests/repository/architecture_real_ports.py b/tests/repository/architecture_real_ports.py index 4cb492d6f..e770560e9 100644 --- a/tests/repository/architecture_real_ports.py +++ b/tests/repository/architecture_real_ports.py @@ -18,7 +18,7 @@ from inferrsi.apps.legacy.evaluation import evaluate from inferrsi.contracts import RunSpec -from inferrsi.harness.trials.external import execute_trial +from inferrsi.harness.executor.trials.external import execute_trial from inferrsi.knowledge.knowledge_operations import KnowledgeReader from tests.repository.architecture_closed_loop import _canonical, _digest diff --git a/tests/repository/check_harness_freeze.py b/tests/repository/check_harness_freeze.py new file mode 100644 index 000000000..dc8d7f570 --- /dev/null +++ b/tests/repository/check_harness_freeze.py @@ -0,0 +1,325 @@ +"""Replay the component migration's immutable baseline using its installed wheel.""" + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import tempfile +import zipfile +from email.parser import BytesParser +from importlib import import_module +from importlib.metadata import distribution +from pathlib import Path + +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures/optimization-session/component-freeze" +AUDITED_CLI = """ +import json, runpy, sys +from pathlib import Path +log = Path(sys.argv.pop(1)) +def audit(event, args): + if event == "subprocess.Popen": + with log.open("a", encoding="utf-8") as out: + out.write(json.dumps(str(args[1])) + "\\n") +sys.addaudithook(audit) +runpy.run_module("inferrsi", run_name="__main__", alter_sys=True) +""" + + +def read(path): + return json.loads(path.read_bytes()) + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def files(path, pattern="*"): + return {p.relative_to(path).as_posix(): digest(p) for p in path.rglob(pattern) if p.is_file()} + + +def unpack(name, destination, manifest): + archive = FIXTURES / name + assert digest(archive) == manifest["samples"][name], name + with zipfile.ZipFile(archive) as packed: + for member in packed.namelist(): + assert (destination / member).resolve().is_relative_to(destination), member + packed.extractall(destination) + + +def cli(root, command, action, *args, expected=0, children=0, error=b"cleanup"): + log = root.parent / "child-processes.jsonl" + log.write_bytes(b"") + result = subprocess.run( + [ + sys.executable, + "-B", + "-c", + AUDITED_CLI, + str(log), + *command, + action, + "--session", + str(root), + *map(str, args), + ], + capture_output=True, + cwd=root.parent, + timeout=60, + env={ + **os.environ, + "PYTHONDONTWRITEBYTECODE": "1", + "PATH": str(Path(sys.executable).parent) + os.pathsep + os.environ["PATH"], + }, + ) + launches = [json.loads(line) for line in log.read_bytes().splitlines()] + assert result.returncode == expected, ( + command, + action, + result.stdout[-1200:], + result.stderr[-1500:], + ) + assert len(launches) == children, (action, launches, children) + if children: + assert all("protocol_child.py" in launch for launch in launches), launches + if expected: + assert error in (result.stdout + result.stderr).lower() + return None + return json.loads(result.stdout) + + +def ordinary(root, command, packaged): + original = files(root) + state = read(root / "state.json") + assert state["pending"] and not state["rounds"] + cli(root, command, "status") + assert files(root) == original + outcome = cli(root, command, "recover", children=int(packaged)) + assert outcome["completed_rounds"] == 1 + assert outcome["latest_observation"]["assessment"]["verdict"] == "PASS" + settled = read(root / "state.json") + assert settled["pending"] is None and len(settled["rounds"]) == 1 + assert settled["deadline"] == state["deadline"] + if packaged: + attempt = root / state["pending"]["path"] + for relative in ( + "protocol-arguments-0001.json", + "execution/launch-task.json", + "protocol-assess-0001.json", + ): + receipt = read(attempt / relative) + assert receipt["spawned"] and receipt["pid"] > 0 and receipt["status"] == "completed" + assert receipt["state"] == "ended" and len(receipt["argv_sha256"]) == 64 + assert read(attempt / "execution/execution.json")["returncode"] == 0 + launches = [ + p + for p in files(root).keys() - original.keys() + if Path(p).name.startswith("protocol-") and p.endswith(".json") + ] + assert [Path(p).name for p in launches] == ["protocol-assess-0001.json"], launches + assert (root / "calls.log").read_text().splitlines() == ["2"] + summary = read(root / "summary.json") + before_repeat = files(root) + again = cli(root, command, "recover") + assert again["latest_observation"] == outcome["latest_observation"] + after_repeat = files(root) + assert before_repeat.keys() == after_repeat.keys() + assert {p for p in before_repeat if before_repeat[p] != after_repeat[p]} <= {"summary.json"} + after_summary = read(root / "summary.json") + assert summary.keys() == after_summary.keys() + assert {k for k in summary if summary[k] != after_summary[k]} <= {"wall_elapsed_seconds"} + + +def service(root, name, proofs): + command = ["campaign"] + original = files(root) + state = read(root / "state.json") + events = files(root, "events.jsonl") + cli(root, command, "status") + assert files(root) == original + pending = state["pending"] + if name == "service-cleanup-pending.zip": + attempt = root / pending["path"] + checkpoint = read(attempt / "execution/execution.json")["checkpoint"] + assert checkpoint["assessment"]["verdict"] == "FAIL" and checkpoint["quality_score"] is None + stages = [ + json.loads(line)["stage"] + for line in (attempt / "events.jsonl").read_bytes().splitlines() + ] + assert stages.count("measure") == 2 and "quality" not in stages + for args in ( + [], + ["--cleanup-receipt", proofs / "wrong-attempt.json"], + ["--cleanup-receipt", proofs / "wrong-owner.json"], + ["--cleanup-receipt", proofs / "wrong-attempt-only.json"], + ): + cli(root, command, "recover", *args, expected=2) + assert not (attempt / "observation.json").exists() + assert files(root) == original + outcome = cli(root, command, "recover", "--cleanup-receipt", proofs / "cleanup.json") + obs = outcome["latest_observation"] + assert ( + obs["attempt_id"] == pending["attempt_id"] + and obs["assessment"] == checkpoint["assessment"] + ) + assert ( + read(attempt / "observation.json")["execution"]["checkpoint"]["binding"] + == checkpoint["binding"] + ) + assert outcome["completed_rounds"] == 1 + else: + outcome = cli(root, command, "recover") + assert outcome["latest_observation"]["assessment"]["verdict"] == "PASS" + assert outcome["completed_rounds"] == (2 if pending else 1) + + settled = read(root / "state.json") + accepted = state["accepted_attempt_ids"].copy() + accounting = state.get("profiling_accounting", {}).copy() + if name == "service-pending.zip": + attempt_id = pending["attempt_id"] + accepted.append(attempt_id) + execution = read(root / pending["path"] / "execution/execution.json") + capture = execution["capture"] + assert capture["id"] == attempt_id and attempt_id not in accounting + accounting[attempt_id] = {k: capture[k] for k in ("started_at", "elapsed_seconds")} + assert settled["accepted_attempt_ids"] == accepted + assert settled["pending"] is None and len(settled["attempts"]) == len(state["attempts"]) + bool( + pending + ) + assert settled["deadline"] == state["deadline"] + assert settled.get("profiling_accounting", {}) == accounting + if name == "service-cleanup-pending.zip": + assert len(settled["recovery_events"]) == len(state["recovery_events"]) + 1 + state_digest = digest(root / "state.json") + again = cli(root, command, "recover") + assert again["latest_observation"] == outcome["latest_observation"] + assert digest(root / "state.json") == state_digest + assert files(root, "events.jsonl") == events + + +def package_members(archive): + return {n for n in archive.namelist() if n.startswith("inferrsi/") and not n.endswith("/")} + + +def wheel_version(archive): + metadata, = (n for n in archive.namelist() if n.endswith(".dist-info/METADATA")) + fields = BytesParser().parsebytes(archive.read(metadata), headersonly=True) + assert fields["Name"] == "inferrsi" + return fields["Version"] + + +def check_install(manifest, wheel): + from inferrsi import __file__ as package_file + from inferrsi.resources.repository_packs import REPO_TYPES, repository_pack + + package = Path(package_file).resolve().parent + dist = distribution("inferrsi") + assert package == dist.locate_file("inferrsi").resolve(), "Install a non-editable wheel" + assert dist.version == manifest["runtime_version"], (dist.version, manifest["runtime_version"]) + # The frozen wheel exposes its fingerprint through the original session module. + frozen_session = import_module("inferrsi.harness.optimization_session") + assert frozen_session._runtime_identity() == read(FIXTURES / "runtime-sources.json"), ( + "Ordinary plan fingerprint differs" + ) + packs = manifest["repository_packs"] + assert set(REPO_TYPES) == packs.keys() + for kind in REPO_TYPES: + path = package / "harness/data/repo_packs" / kind / "pack.json" + assert digest(path) == packs[kind] and repository_pack(kind) == read(path) + with zipfile.ZipFile(wheel) as packed: + members = package_members(packed) + assert len(members) == manifest["installed_package_files"] + for name in members: + assert packed.read(name) == (package.parent / name).read_bytes(), name + + +def installed_service_replay(wheel, normal_wheel, mode, manifest): + """Exercise service version checks separately from the ordinary runtime fingerprint.""" + from inferrsi import __file__ as package_file + + dist = distribution("inferrsi") + assert Path(package_file).resolve().parent == dist.locate_file("inferrsi").resolve() + frozen_version = manifest["runtime_version"] + assert (dist.version == frozen_version) == (mode == "frozen-version") + with zipfile.ZipFile(wheel) as archive: + names = package_members(archive) + assert wheel_version(archive) == dist.version + assert "inferrsi/__init__.py" in names + assert all(archive.read(n) == dist.locate_file(n).read_bytes() for n in names) + if normal_wheel: + with zipfile.ZipFile(normal_wheel) as normal: + assert wheel_version(normal) != frozen_version + assert names == package_members(normal) + changed = {n for n in names if archive.read(n) != normal.read(n)} + assert changed == {"inferrsi/_version.py"}, changed + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp).resolve() + proofs = work / "proofs" + unpack("cleanup-proofs.zip", proofs, manifest) + assert files(proofs) == manifest["cleanup_proofs"] + for name in ("service-pending.zip", "service-settled.zip", "service-cleanup-pending.zip"): + root = work / name + unpack(name, root, manifest) + if mode == "frozen-version": + service(root, name, proofs) + continue + original = files(root) + status = cli(root, ["campaign"], "status") + assert status["recorded_runtime_version"] == frozen_version + assert status["next_action"] == "use_recorded_runtime_version" + assert status["final_block_reason"] == "runtime_version_mismatch" + assert files(root) == original + controls = [[]] + if name == "service-cleanup-pending.zip": + controls.append(["--cleanup-receipt", proofs / "cleanup.json"]) + for args in controls: + cli( + root, ["campaign"], "recover", *args, + expected=2, error=b"runtime package version changed", + ) + assert files(root) == original + print(f"Verified {mode} service replay with {wheel.name} (sha256 {digest(wheel)})") + if normal_wheel: + print(f"Compared package payload with {normal_wheel.name} (sha256 {digest(normal_wheel)})") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--wheel", required=True, type=Path, help="The wheel installed in this interpreter" + ) + parser.add_argument("--service-replay", choices=["different-version", "frozen-version"]) + parser.add_argument( + "--normal-wheel", type=Path, help="Normal build from the same source as the isolated wheel" + ) + args = parser.parse_args() + if bool(args.normal_wheel) != (args.service_replay == "frozen-version"): + parser.error("--normal-wheel is required for the frozen-version service replay only") + manifest = read(FIXTURES / "manifest.json") + if args.service_replay: + installed_service_replay(args.wheel, args.normal_wheel, args.service_replay, manifest) + return + check_install(manifest, args.wheel) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp).resolve() + proofs = work / "proofs" + unpack("cleanup-proofs.zip", proofs, manifest) + assert files(proofs) == manifest["cleanup_proofs"] + for name, entry in ( + ("ordinary-packaged.zip", ["benchmarks", "session"]), + ("ordinary-packaged.zip", ["campaign"]), + ("ordinary-ab-ba.zip", ["campaign"]), + ): + root = work / (name + "-" + entry[0]) + unpack(name, root, manifest) + ordinary(root, entry, name == "ordinary-packaged.zip") + for name in ("service-settled.zip", "service-pending.zip", "service-cleanup-pending.zip"): + root = work / name + unpack(name, root, manifest) + service(root, name, proofs) + print(f"Verified six independent replays with {args.wheel.name} (sha256 {digest(args.wheel)})") + + +if __name__ == "__main__": + main() diff --git a/tests/repository/check_installed.py b/tests/repository/check_installed.py index 0ac6842ba..008b28d97 100644 --- a/tests/repository/check_installed.py +++ b/tests/repository/check_installed.py @@ -28,13 +28,60 @@ assert callable(EvidenceCapture) +# Public digest and error imports must work without loading storage or targets. +subprocess.run([sys.executable, "-I", "-B", "-c", """ +import hashlib +import sys +from importlib.util import find_spec +from pathlib import Path +from inferrsi.harness import records +from inferrsi.harness.api import PUBLIC_ERROR_CODES, PartialExecutionFacts, PublicError +from inferrsi.harness.executor import request_digest + +assert request_digest({}) == "sha256:" + hashlib.sha256(b"{}").hexdigest() +assert "InvalidRequest" in PUBLIC_ERROR_CODES +for name in ( + "sqlite3", "inferrsi.harness.records._run_store", "inferrsi.harness.executor._execution", +): + assert name not in sys.modules, name +for old in ( + "run_store", "execution_spec", "errors", "atomic_json", "artifact_primitives", + "service_observations", "usage", "generation", "prepared_binding", + "generation_feedback", "generation_lineage", "execution_service", "entry_code", + "evidence_capture", "input_binding", "artifact_sandbox", "candidates", "confinement", + "skill_evaluation", +): + assert find_spec("inferrsi.harness." + old) is None, old +from inferrsi.harness import api +from inferrsi.harness.executor import LocalCpuTarget +from inferrsi.harness.records import RunStore, RunStoreReader + +assert not hasattr(api, "LocalCpuTarget") +try: + LocalCpuTarget("cpu", "1", Path("relative")) +except PublicError as error: + assert type(error) is PublicError and error.code == "InvalidRequest" +else: + raise AssertionError("LocalCpuTarget accepted a relative root") +assert issubclass(RunStore, RunStoreReader) +try: + RunStore(Path("relative"), "p5") +except PublicError as error: + assert type(error) is PublicError and error.code == "InvalidRequest" +else: + raise AssertionError("RunStore accepted a relative root") +"""], check=True) + # The new Harness binding port ships independently of Apps and Benchmark. subprocess.run([ sys.executable, "-I", "-B", "-c", - "import sys; from inferrsi.harness import prepared_binding as p; " - "from inferrsi.harness import entry_code; assert callable(entry_code.capture_module); " - "from inferrsi.harness import evidence_capture; assert callable(evidence_capture.observe); " - "assert all(callable(getattr(p, n)) for n in ('read', 'project', 'verify')); " + "import sys; from inferrsi.harness import executor; " + "from inferrsi.harness.executor import _entry_code; " + "assert callable(_entry_code.capture_module); " + "from inferrsi.harness.executor import _evidence_capture; " + "assert callable(_evidence_capture.observe); " + "assert all(callable(getattr(executor, n)) for n in ('prepare_generation', " + "'read_prepared_binding', 'project_prepared_binding', 'verify_prepared_binding')); " "assert not any(n == root or n.startswith(root + '.') for n in sys.modules " "for root in ('inferrsi.apps', 'inferrsi.benchmark', 'inferrsi.knowledge'))", ], check=True, capture_output=True, text=True) @@ -649,7 +696,9 @@ def _inventory(root, prefix): # #451 C1: the shared data/byte contracts ship as one package. The four retired root # modules are not in the wheel and have no alias. assert RunSpec.__module__ == "inferrsi.contracts.runspec" -assert inferrsi.harness.Verdict is claim.Verdict +assert claim.parse_verdict("PASS") is claim.Verdict.PASS +assert not hasattr(inferrsi.harness, "Verdict") +assert not hasattr(inferrsi.harness, "parse_verdict") assert json_v1.decode(json_v1.encode({"b": [1, None], "a": "x"})) == {"a": "x", "b": [1, None]} for retired in ("_json_v1", "runspec", "claim"): assert find_spec(f"inferrsi.{retired}") is None, retired @@ -932,6 +981,42 @@ def assert_not_importable(name): raise AssertionError(f"retired module {name} must not import") +def check_installed_abba_runner(): + from inferrsi.apps.legacy.run import execute_trial + from inferrsi.harness.manager import run_experiment + + command = ( + sys.executable, "-c", + "import sys; from pathlib import Path; Path(sys.argv[1]).write_text(sys.argv[2])", + "{result}", '{"metrics":{"latency_ms":1}}', + ) + reported = [] + + def assess(baseline, candidate, validation, integrity, error): + assert [trial["metric"] for trial in baseline] == [1] + assert [trial["metric"] for trial in candidate] == [1] + assert validation is None and integrity["verified"] and error is None + return {"verdict": "INCONCLUSIVE"} + + with tempfile.TemporaryDirectory(prefix="inferrsi-installed-abba-") as cwd: + spec = RunSpec(repo=cwd, baseline_command=command, candidate_command=command, + repetitions=1, output_dir=str(Path(cwd) / "runs"), max_minutes=1) + run_dir = run_experiment( + spec, {}, execute=execute_trial, + snapshot=lambda *_: {"available": True, "snapshot_hash": "fixed"}, + assess=assess, report=reported.append, + ) + assert reported == [run_dir] + assert json.loads((run_dir / "evaluation.json").read_bytes()) == {"verdict": "INCONCLUSIVE"} + + +for retired_name in ( + "runner", "agent_sessions", "attempt_recovery", "optimization", "optimization_session", + "parallel_round", "service_backfill", "session_runtime", +): + assert_not_importable(f"inferrsi.harness.{retired_name}") +check_installed_abba_runner() + # #498 slice 1: the metric contract and the quality validators ship only under # inferrsi.benchmark. The old inferrsi.model paths are not in the wheel and have no alias. # Slice 2 removed the emptied inferrsi.model.protocols package, so it stands for @@ -952,23 +1037,26 @@ def assert_not_importable(name): assert flare_cli.returncode == code, (module, flare_cli.returncode, flare_cli.stderr) # Since #498 the whole inferrsi.model package is gone, so Python stops at its parent. assert "No module named 'inferrsi.model'" in flare_cli.stderr, flare_cli.stderr -# #498 slice 2: the serving helpers ship only under inferrsi.harness.serving, with no -# forwarder for the old Infra and Model paths. Slice 3c deleted the infra.campaign facade, -# slice 3a moved the host bindings to inferrsi.apps.host, and slices 3b, 4 and 5 moved the -# artifact helpers to inferrsi.apps.storage.artifacts and the provider modules to -# inferrsi.apps.integrations.anthropic. Both packages are gone from the wheel. +# #702 exposes the four serving helpers from Executor. The former Infra, Model and +# Harness serving packages are retired. for retired in ("inferrsi.infra", "inferrsi.infra.artifacts", "inferrsi.infra.processes", "inferrsi.infra.http", "inferrsi.infra.campaign", "inferrsi.infra.commands", "inferrsi.infra.inspection", "inferrsi.infra.environment", "inferrsi.infra.platforms", "inferrsi.infra.targets", "inferrsi.model", "inferrsi.model.anthropic_agent", "inferrsi.model.anthropic_edit_agent", "inferrsi.model.request_guard", "inferrsi.harness.scenarios", - "inferrsi.harness.scenarios.external"): + "inferrsi.harness.scenarios.external", "inferrsi.harness.trials", + "inferrsi.harness.trials.external", "inferrsi.harness.local_process", + "inferrsi.harness.launch_records", "inferrsi.harness.device_lease", + "inferrsi.harness.serving", "inferrsi.harness.serving.server", + "inferrsi.harness.serving.http", "inferrsi.harness.serving.image", + "inferrsi.harness.project_service", "inferrsi.harness.service_evidence"): assert_not_importable(retired) assert not {child.name for child in files("inferrsi").iterdir()} & {"infra", "model"} -for canonical in ("inferrsi.harness.trials", "inferrsi.harness.trials.external", - "inferrsi.harness.serving", "inferrsi.harness.serving.server", - "inferrsi.harness.serving.http", "inferrsi.harness.serving.image", +for canonical in ("inferrsi.harness.executor.local_process", + "inferrsi.harness.executor.launch_records", + "inferrsi.harness.executor.device_lease", + "inferrsi.harness.executor.trials", "inferrsi.harness.executor.trials.external", "inferrsi.apps.host.commands", "inferrsi.apps.host.inspection", "inferrsi.apps.host.environment", "inferrsi.apps.host.platforms", "inferrsi.apps.host.targets", "inferrsi.apps.storage.artifacts", @@ -1048,15 +1136,23 @@ def session_bytes(): ) assert provider.returncode == 0, provider.stderr # A fresh isolated interpreter imports the image client without loading the server -# process helpers or any Infra or Model module: the package initializer imports nothing. +# process helpers or the record store. Check the other public helpers afterwards. serving_probe = ( "import sys\n" - "from inferrsi.harness.serving.image import ImageProtocol\n" + "from inferrsi.harness.executor import ImageProtocol\n" "loaded = {name for name in sys.modules if name.startswith('inferrsi.')}\n" - "serving = {name for name in loaded if name.startswith('inferrsi.harness.serving')}\n" - "assert serving == {'inferrsi.harness.serving', 'inferrsi.harness.serving.image',\n" - " 'inferrsi.harness.serving.http'}, sorted(serving)\n" - "assert not [n for n in loaded if n.startswith(('inferrsi.infra', 'inferrsi.model'))]\n" + "prefix = 'inferrsi.harness.executor.serving'\n" + "serving = {name for name in loaded if name.startswith(prefix)}\n" + "assert serving == {prefix, prefix + '._image', prefix + '._http'}, sorted(serving)\n" + "assert 'sqlite3' not in sys.modules and 'inferrsi.harness.records._run_store' not in loaded\n" + "from inferrsi.harness.executor import launch_server, post_json, stop_server\n" + "helpers = (ImageProtocol, launch_server, post_json, stop_server)\n" + "assert all(callable(helper) for helper in helpers)\n" + "from inferrsi.harness.executor import execute_service_attempt, prepare_service\n" + "from inferrsi.harness.evaluator import service_assessment, service_settlement_reason\n" + "assert all(map(callable, (execute_service_attempt, prepare_service)))\n" + "assert all(map(callable, (service_assessment, service_settlement_reason)))\n" + "assert not any(n.startswith(('inferrsi.infra', 'inferrsi.model')) for n in sys.modules)\n" ) with tempfile.TemporaryDirectory(prefix="inferrsi-serving-") as serving_cwd: serving = subprocess.run( diff --git a/tests/repository/check_session_imports.py b/tests/repository/check_session_imports.py index 45dc17bf3..b7e303bfd 100644 --- a/tests/repository/check_session_imports.py +++ b/tests/repository/check_session_imports.py @@ -22,12 +22,12 @@ def observe(case, output): import pytest - from inferrsi.harness import optimization_session - from inferrsi.harness.session_runtime import included_module + from inferrsi.harness.manager import _session + from inferrsi.harness.manager._runtime import included_module - path = Path(optimization_session.__file__).resolve() + path = Path(_session.__file__).resolve() assert path.is_relative_to(sysconfig.get_path("purelib")), path - root = path.parents[1] + root = path.parents[2] modules, phases = set(), set() active = None @@ -39,9 +39,9 @@ def profile(frame, event, _): return name = frame.f_globals.get("__name__", "") function = frame.f_code.co_name - if (name, function) == ("inferrsi.harness.optimization_session", "session_command"): + if (name, function) == ("inferrsi.harness.manager._session", "run_session"): active = frame - phases.add(frame.f_locals["args"].session_action) + phases.add(frame.f_locals["request"].action) if (name, function) == ("inferrsi.apps.delivery", "export_bundle"): phases.add("export") if active is not None and included_module(name): @@ -65,7 +65,7 @@ def profile(frame, event, _): def check(cases): - from inferrsi.harness.optimization_session import _runtime_identity + from inferrsi.harness.manager import session_runtime_identity union = set() with TemporaryDirectory() as directory: @@ -74,7 +74,7 @@ def check(cases): subprocess.run([sys.executable, "-I", __file__, "--observe", case, str(output)], cwd=ROOT, check=True) union.update(json.loads(output.read_text(encoding="utf-8"))) - missing = union.difference(_runtime_identity()) + missing = union.difference(session_runtime_identity()) assert not missing, f"Installed session modules outside the frozen identity: {sorted(missing)}" print(f"{len(union)} observed session modules covered across {', '.join(cases)}") diff --git a/tests/repository/test_architecture_closed_loop.py b/tests/repository/test_architecture_closed_loop.py index 5ff387dd1..71628ba3c 100644 --- a/tests/repository/test_architecture_closed_loop.py +++ b/tests/repository/test_architecture_closed_loop.py @@ -30,6 +30,8 @@ "inferrsi.cli", "inferrsi.arguments", "inferrsi.harness.runner", + "inferrsi.harness.manager._runner", + "inferrsi.harness.manager.run_experiment", "inferrsi.apps", "inferrsi.knowledge", "inferrsi.benchmark", @@ -375,7 +377,7 @@ def test_real_cpu_offline_ports_connect_three_refs(self) -> None: def test_real_ports_stay_on_three_existing_seams(self) -> None: imported = _import_modules(PORTS) self.assertIn("inferrsi.knowledge.knowledge_operations", imported) - self.assertIn("inferrsi.harness.trials.external", imported) + self.assertIn("inferrsi.harness.executor.trials.external", imported) self.assertIn("inferrsi.apps.legacy.evaluation", imported) # The six banned families are unchanged. Two of the three seams are canonical # Knowledge and Apps modules since #412 R1; the guard exempts those two exact @@ -394,7 +396,7 @@ def test_real_ports_stay_on_three_existing_seams(self) -> None: self.assertNotIn("collect", calls) # #412 R1 deleted the root shell; these are the implementation's own imports. knowledge = _import_modules(ROOT / "src/inferrsi/knowledge/knowledge_operations.py") - harness = _import_modules(ROOT / "src/inferrsi/harness/trials/external.py") + harness = _import_modules(ROOT / "src/inferrsi/harness/executor/trials/external.py") self.assertFalse(any("harness" in name or "evaluation" in name for name in knowledge)) self.assertFalse(any("knowledge" in name or "evaluation" in name for name in harness)) text = LAYOUT.read_text(encoding="utf-8") @@ -408,7 +410,7 @@ def test_seam_guard_exempts_only_the_two_exact_seams(self) -> None: "from inferrsi.apps.legacy.evaluation import evaluate\n", "import inferrsi.knowledge.knowledge_operations\n", "import inferrsi.apps.legacy.evaluation as old_evaluate\n", - "from inferrsi.harness.trials.external import execute_trial\n", + "from inferrsi.harness.executor.trials.external import execute_trial\n", "from inferrsi.contracts import RunSpec\n", "import json\nfrom pathlib import Path\n", ) @@ -483,6 +485,10 @@ def test_seam_guard_keeps_the_cli_parser_runner_and_benchmark_bans(self) -> None ("import inferrsi.arguments as options\n", "inferrsi.arguments"), ("from inferrsi import arguments\n", "inferrsi.arguments"), ("from inferrsi.harness.runner import run_experiment\n", "inferrsi.harness.runner"), + ("from inferrsi.harness.manager import run_experiment\n", + "inferrsi.harness.manager.run_experiment"), + ("import inferrsi.harness.manager._runner as loop\n", + "inferrsi.harness.manager._runner"), ("import inferrsi.harness.runner as loop\n", "inferrsi.harness.runner"), ("from inferrsi.harness import runner\n", "inferrsi.harness.runner"), ("from inferrsi.benchmark.legacy_run_v0 import evaluate\n", @@ -496,7 +502,7 @@ def test_seam_guard_keeps_the_cli_parser_runner_and_benchmark_bans(self) -> None with self.subTest(refused=source): self.assertIn(expected, _seam_violations(source)) # Harness is not banned whole: only its runner is, and a lookalike is not it. - self.assertEqual(_seam_violations("from inferrsi.harness import atomic_json\n"), []) + self.assertEqual(_seam_violations("from inferrsi.harness.records import atomic_json\n"), []) self.assertEqual(_seam_violations("import inferrsi.harness.runner_notes\n"), []) def test_real_assembler_fails_the_same_guard_once_a_coupling_is_added(self) -> None: @@ -513,8 +519,8 @@ def test_real_assembler_fails_the_same_guard_once_a_coupling_is_added(self) -> N "inferrsi.knowledge.catalog"), (text + "\nfrom inferrsi.cli import main\n", "inferrsi.cli"), (text + "\nfrom inferrsi.arguments import parser\n", "inferrsi.arguments"), - (text + "\nfrom inferrsi.harness.runner import run_experiment\n", - "inferrsi.harness.runner"), + (text + "\nfrom inferrsi.harness.manager import run_experiment\n", + "inferrsi.harness.manager.run_experiment"), (text + "\nfrom inferrsi.benchmark.legacy_run_v0 import evaluate\n", "inferrsi.benchmark.legacy_run_v0"), ) diff --git a/tests/repository/test_artifact_helper_copies.py b/tests/repository/test_artifact_helper_copies.py index 1ab31ce4f..19b057cb8 100644 --- a/tests/repository/test_artifact_helper_copies.py +++ b/tests/repository/test_artifact_helper_copies.py @@ -19,13 +19,15 @@ # Each helper name and the modules that hold a copy. #498 slice 3b added the Apps copy # and slice 5 deleted the Infra one, so Harness, Benchmark and Apps hold the three. COPIES = { - "sha256": ("inferrsi.apps.storage.artifacts", "inferrsi.harness.artifact_primitives", + "sha256": ("inferrsi.apps.storage.artifacts", "inferrsi.harness.records.artifact_primitives", "inferrsi.benchmark.artifacts"), "write_json": ("inferrsi.apps.storage.artifacts", "inferrsi.benchmark.artifacts"), - "atomic_write_json": ("inferrsi.apps.storage.artifacts", "inferrsi.harness.atomic_json", + "atomic_write_json": ("inferrsi.apps.storage.artifacts", "inferrsi.harness.records.atomic_json", "inferrsi.benchmark.artifacts"), - "digest": ("inferrsi.apps.storage.artifacts", "inferrsi.harness.artifact_primitives"), - "file_lock": ("inferrsi.apps.storage.artifacts", "inferrsi.harness.artifact_primitives"), + "digest": ("inferrsi.apps.storage.artifacts", "inferrsi.harness.records.artifact_primitives"), + "file_lock": ( + "inferrsi.apps.storage.artifacts", "inferrsi.harness.records.artifact_primitives", + ), } CONSTANTS = ("REPLACE_ATTEMPTS", "REPLACE_DELAY_SECONDS") VALUE = {"b": [1.5, None, True, 1e-07, 1e16], "a": "非 ASCII", "nested": {"z": 0.1 + 0.2}} diff --git a/tests/repository/test_first_wave_isolation_policy.py b/tests/repository/test_first_wave_isolation_policy.py index 9f02aa391..2249877d8 100644 --- a/tests/repository/test_first_wave_isolation_policy.py +++ b/tests/repository/test_first_wave_isolation_policy.py @@ -42,8 +42,8 @@ # Module paths assumed for synthetic graphs only; the gate never infers them. SYNTHETIC_H_ENTRIES = ( "inferrsi.harness.api", - "inferrsi.harness.execution_service", - "inferrsi.harness.run_store", + "inferrsi.harness.executor._execution", + "inferrsi.harness.records", ) # #451 C2: the leaf lives in ``inferrsi.resources``, whose initializer imports nothing. LEAF_FILE = "resources/repository_packs.py" @@ -59,9 +59,10 @@ "apps/__init__.py": "", "apps/main.py": "from inferrsi.knowledge import catalog\nfrom inferrsi.harness import api\n", "harness/__init__.py": "", + "harness/executor/__init__.py": "", "harness/api.py": "VALUE = 1\n", } -# The bounded contracts package (#451 C1, C2): the initializer's one export and four +# The bounded contracts package (#451 C1, C2): the initializer's one export and five # standalone modules. CONTRACTS_INIT = ( '"""Shared contracts."""\n\n' @@ -72,6 +73,7 @@ "contracts/__init__.py": CONTRACTS_INIT, "contracts/json_v1.py": "import json\n", "contracts/runspec.py": "import math\n\n\nclass RunSpec:\n pass\n", + "contracts/_harness_errors.py": "from dataclasses import dataclass\n", "contracts/claim.py": "from enum import Enum\n", "contracts/evidence.py": "from pathlib import Path\n", } @@ -420,7 +422,7 @@ def test_another_importer_fails(self) -> None: line = "from inferrsi.resources.repository_packs import repository_pack\n" paths = ( "infra/other.py", "infra/inspection_helpers.py", "infra/__init__.py", - "infra/platforms/__init__.py", "harness/api.py", "harness/runner.py", + "infra/platforms/__init__.py", "harness/api.py", "harness/manager/_parallel_round.py", "benchmark/probe.py", "apps/main.py", "apps/inspection.py", "apps/host/prepared_environment.py", "model/probe.py", "cli.py", "arguments.py", "apps/cli/__init__.py", "apps/cli/arguments.py", @@ -924,9 +926,9 @@ def test_contract_modules_import_no_inferrsi_module(self) -> None: self.assertTrue(_violated(report, expected), report.violations) def test_apps_directory_creation_is_not_a_contracts_module(self) -> None: - # #451 C2: mkdir stays in Apps. The declared set gains evidence and nothing else. + # #451 C2: mkdir stays in Apps. Directory creation belongs to Apps. self.assertIn("inferrsi.contracts.evidence", support.CONTRACTS_MODULES) - self.assertEqual(len(support.CONTRACTS_MODULES), 5) + self.assertEqual(len(support.CONTRACTS_MODULES), 6) self.assertFalse( [name for name in support.CONTRACTS_MODULES if "evidence_layout" in name] ) @@ -974,14 +976,14 @@ def test_new_h_entry_through_old_shell_fails(self) -> None: "inferrsi.harness.api reaches inferrsi.knowledge_operations", ), ( - "harness/run_store/__init__.py", + "harness/records/__init__.py", "from ...catalog import search_knowledge\n", - "inferrsi.harness.run_store reaches inferrsi.catalog", + "inferrsi.harness.records reaches inferrsi.catalog", ), ( - "harness/execution_service.py", + "harness/executor/_execution.py", "from inferrsi.research import research_knowledge\n", - "inferrsi.harness.execution_service reaches inferrsi.research", + "inferrsi.harness.executor._execution reaches inferrsi.research", ), ) for path, source, expected in cases: @@ -994,56 +996,58 @@ def test_entry_labels_are_not_inferred_as_paths(self) -> None: # label exists, but it is still a harness module: importing an old # Knowledge leaf is a violation. report = _report( - {"harness/run_store/__init__.py": "from ...catalog import search_knowledge\n"}, + {"harness/records/__init__.py": "from ...catalog import search_knowledge\n"}, h_entries=("inferrsi.harness.api",), ) self.assertTrue( - _violated(report, "inferrsi.harness.run_store reaches inferrsi.catalog"), + _violated(report, "inferrsi.harness.records reaches inferrsi.catalog"), report.violations, ) def test_non_entry_harness_module_cannot_reach_an_old_leaf(self) -> None: cases = ( ( - "from ..knowledge_operations import KnowledgeReader\n", - "inferrsi.harness.runner reaches inferrsi.knowledge_operations", + "from ...knowledge_operations import KnowledgeReader\n", + "inferrsi.harness.manager._parallel_round reaches inferrsi.knowledge_operations", ), ( "from inferrsi.catalog import search_knowledge\n", - "inferrsi.harness.runner reaches inferrsi.catalog", + "inferrsi.harness.manager._parallel_round reaches inferrsi.catalog", ), ) for source, expected in cases: with self.subTest(expected=expected): - report = _report({"harness/runner.py": source}) + report = _report({"harness/manager/_parallel_round.py": source}) self.assertTrue(_violated(report, expected), report.violations) def test_former_residual_edge_fails_for_its_importer_and_dependents(self) -> None: # The edge that S01 removed has no exemption left: the importer fails, # 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/executor/skill_evaluation.py": ( + "from ...knowledge_operations import KnowledgeReader\n" + ), + "harness/manager/search/improvement.py": "from ...executor import skill_evaluation\n", } report = _report(tree) self.assertIn( - "inferrsi.harness.skill_evaluation reaches inferrsi.knowledge_operations: " - "inferrsi.harness.skill_evaluation -> inferrsi.knowledge_operations", + "inferrsi.harness.executor.skill_evaluation reaches inferrsi.knowledge_operations: " + "inferrsi.harness.executor.skill_evaluation -> inferrsi.knowledge_operations", report.violations, ) self.assertIn( - "inferrsi.harness.improvement reaches inferrsi.knowledge_operations: " - "inferrsi.harness.improvement -> inferrsi.harness.skill_evaluation" - " -> inferrsi.knowledge_operations", + "inferrsi.harness.manager.search.improvement reaches inferrsi.knowledge_operations: " + "inferrsi.harness.manager.search.improvement" + " -> inferrsi.harness.executor.skill_evaluation -> inferrsi.knowledge_operations", report.violations, ) self.assertNotIn("residual", blocker_kinds(report)) self.assertFalse(report.isolation_complete) - entry = "from inferrsi.harness import skill_evaluation\n" + entry = "from inferrsi.harness.executor import skill_evaluation\n" granted = _report({**tree, "harness/api.py": entry}) self.assertIn( "inferrsi.harness.api reaches inferrsi.knowledge_operations: inferrsi.harness.api" - " -> inferrsi.harness.skill_evaluation -> inferrsi.knowledge_operations", + " -> inferrsi.harness.executor.skill_evaluation -> inferrsi.knowledge_operations", granted.violations, ) self.assertFalse(granted.new_core_closure_isolated) @@ -1072,7 +1076,7 @@ def test_submodule_import_traverses_parent_package_init(self) -> None: def test_transitive_path_through_root_helpers_fails(self) -> None: report = _report( { - "harness/runner.py": "from inferrsi import helper_a\n", + "harness/manager/_parallel_round.py": "from inferrsi import helper_a\n", "helper_a.py": "from inferrsi import helper_b\n", "helper_b.py": ( "from inferrsi.knowledge_operations import KnowledgeReader\n" @@ -1080,8 +1084,8 @@ def test_transitive_path_through_root_helpers_fails(self) -> None: } ) self.assertIn( - "inferrsi.harness.runner reaches inferrsi.knowledge_operations: " - "inferrsi.harness.runner -> inferrsi.helper_a -> inferrsi.helper_b" + "inferrsi.harness.manager._parallel_round reaches inferrsi.knowledge_operations: " + "inferrsi.harness.manager._parallel_round -> inferrsi.helper_a -> inferrsi.helper_b" " -> inferrsi.knowledge_operations", report.violations, ) @@ -1089,8 +1093,8 @@ def test_transitive_path_through_root_helpers_fails(self) -> None: def test_old_leaf_detection_is_not_sort_dependent(self) -> None: # A second path to the same leaf is found whichever edge is walked first. direct = { - "harness/skill_evaluation.py": ( - "from ..knowledge_operations import KnowledgeReader\n" + "harness/executor/skill_evaluation.py": ( + "from ...knowledge_operations import KnowledgeReader\n" ) } for name in ("aa_bridge", "zz_bridge"): @@ -1100,12 +1104,12 @@ def test_old_leaf_detection_is_not_sort_dependent(self) -> None: **direct, "knowledge_operations.py": _shell("inferrsi.knowledge_operations"), f"{name}.py": "from . import knowledge_operations\n", - "harness/runner.py": ( - f"from . import skill_evaluation\nfrom .. import {name}\n" + "harness/manager/_parallel_round.py": ( + f"from ..executor import skill_evaluation\nfrom ... import {name}\n" ), } ) - for module in ("runner", "skill_evaluation"): + for module in ("manager._parallel_round", "executor.skill_evaluation"): self.assertTrue( _violated( report, @@ -1118,15 +1122,15 @@ def test_h_entry_own_parent_init_is_walked(self) -> None: # Importing a new H entry executes its package init even when the # entry body has no imports. leak = { - "harness/skill_evaluation.py": ( - "from ..knowledge_operations import KnowledgeReader\n" + "harness/executor/skill_evaluation.py": ( + "from ...knowledge_operations import KnowledgeReader\n" ), - "harness/__init__.py": "from . import skill_evaluation\n", + "harness/__init__.py": "from .executor import skill_evaluation\n", } expected = ( "inferrsi.harness.api reaches inferrsi.knowledge_operations: " "inferrsi.harness.api -> inferrsi.harness -> " - "inferrsi.harness.skill_evaluation -> inferrsi.knowledge_operations" + "inferrsi.harness.executor.skill_evaluation -> inferrsi.knowledge_operations" ) isolated = _report({**leak, "harness/api.py": "VALUE = 1\n"}) self.assertIn(expected, isolated.violations) @@ -1146,19 +1150,19 @@ def test_non_entry_own_parent_init_is_walked(self) -> None: # through the package init, and fails like an entry does. report = _report( { - "harness/skill_evaluation.py": ( - "from ..knowledge_operations import KnowledgeReader\n" + "harness/executor/skill_evaluation.py": ( + "from ...knowledge_operations import KnowledgeReader\n" ), - "harness/__init__.py": "from . import skill_evaluation\n", - "harness/runner.py": "VALUE = 1\n", + "harness/__init__.py": "from .executor import skill_evaluation\n", + "harness/manager/_parallel_round.py": "VALUE = 1\n", "harness/api.py": "VALUE = 1\n", } ) - for module in ("runner", "api"): + for module in ("manager._parallel_round", "api"): self.assertIn( f"inferrsi.harness.{module} reaches inferrsi.knowledge_operations: " f"inferrsi.harness.{module} -> inferrsi.harness -> " - "inferrsi.harness.skill_evaluation -> inferrsi.knowledge_operations", + "inferrsi.harness.executor.skill_evaluation -> inferrsi.knowledge_operations", report.violations, ) @@ -1209,8 +1213,8 @@ def test_returning_skill_evaluation_infra_edge_fails(self) -> None: tree = { "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/executor/skill_evaluation.py": "from ...infra.artifacts import VALUE\n", + "harness/manager/search/improvement.py": "from ...executor import skill_evaluation\n", } cleared = _report({}, manifest=EMPTY_ALLOWLIST, base=CLEARED_TREE) self.assertEqual(cleared.harness_model_infra, ()) @@ -1219,19 +1223,19 @@ def test_returning_skill_evaluation_infra_edge_fails(self) -> None: self.assertEqual( report.harness_model_infra, ( - "inferrsi.harness.improvement -> inferrsi.harness.skill_evaluation" - " -> inferrsi.infra", - "inferrsi.harness.improvement -> inferrsi.harness.skill_evaluation" - " -> inferrsi.infra.artifacts", - "inferrsi.harness.skill_evaluation -> inferrsi.infra", - "inferrsi.harness.skill_evaluation -> inferrsi.infra.artifacts", + "inferrsi.harness.executor.skill_evaluation -> inferrsi.infra", + "inferrsi.harness.executor.skill_evaluation -> inferrsi.infra.artifacts", + "inferrsi.harness.manager.search.improvement" + " -> inferrsi.harness.executor.skill_evaluation -> inferrsi.infra", + "inferrsi.harness.manager.search.improvement" + " -> inferrsi.harness.executor.skill_evaluation -> inferrsi.infra.artifacts", ), ) self.assertEqual( report.blockers, ( - "harness reaches model/infra: inferrsi.harness.improvement -> " - "inferrsi.harness.skill_evaluation -> inferrsi.infra (4 hits)", + "harness reaches model/infra: inferrsi.harness.executor.skill_evaluation" + " -> inferrsi.infra (4 hits)", ), ) self.assertFalse(report.isolation_complete) @@ -1247,29 +1251,31 @@ def test_returning_r2_harness_infra_edges_fail(self) -> None: infra = {"infra/__init__.py": "", "infra/artifacts.py": "VALUE = 1\n", "infra/other.py": "VALUE = 1\n", "model/__init__.py": "", "model/metrics.py": "VALUE = 1\n"} - primitives = {"harness/artifact_primitives.py": "VALUE = 1\n", - "harness/atomic_json.py": "VALUE = 1\n"} - modules = ("agent_sessions", "candidates", "optimization", "optimization_session", - "project", "task_protocol") - clean = {f"harness/{name}.py": "from .artifact_primitives import VALUE\n" - for name in modules} + primitives = {"harness/records/artifact_primitives.py": "VALUE = 1\n", + "harness/records/atomic_json.py": "VALUE = 1\n"} + modules = ("manager._agent_sessions", "executor.candidates", "manager._state", + "manager._session", "executor._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()} cleared = _report({**infra, **primitives, **clean}, manifest=EMPTY_ALLOWLIST, base=CLEARED_TREE) self.assertEqual(cleared.harness_model_infra, ()) self.assertTrue(cleared.isolation_complete) sources = ( - ("from ..infra.artifacts import VALUE\n", "inferrsi.infra.artifacts"), + ("from {prefix}infra.artifacts import VALUE\n", "inferrsi.infra.artifacts"), ("def late():\n from inferrsi.infra.artifacts import VALUE\n", "inferrsi.infra.artifacts"), # #498 retired infra.processes and infra.commands; other is a synthetic Infra module. - ("from ..infra import other\n", "inferrsi.infra.other"), + ("from {prefix}infra import other\n", "inferrsi.infra.other"), ("from inferrsi.model import metrics\n", "inferrsi.model.metrics"), ) for name in modules: + prefix = "." * (2 + name.count(".")) for source, target in sources: with self.subTest(module=name, source=source): report = _report({**infra, **primitives, **clean, - f"harness/{name}.py": source}, + paths[name]: source.format(prefix=prefix)}, manifest=EMPTY_ALLOWLIST, base=CLEARED_TREE) package = target.rsplit(".", 1)[0] self.assertEqual( @@ -1280,7 +1286,10 @@ def test_returning_r2_harness_infra_edges_fail(self) -> None: self.assertFalse(report.isolation_complete) def test_mixed_harness_tree_is_not_an_isolated_core(self) -> None: - tree = {"__init__.py": "", "harness/__init__.py": "", "harness/runner.py": "VALUE = 1\n"} + tree = { + "__init__.py": "", "harness/__init__.py": "", + "harness/manager/_parallel_round.py": "VALUE = 1\n", + } report = _report({}, base=tree) self.assertEqual(report.violations, ()) self.assertFalse(report.new_core_closure_isolated) @@ -1308,33 +1317,37 @@ def test_each_trigger_alone_keeps_overall_false(self) -> None: ("absent: apps/", {"apps/__init__.py": None, "apps/main.py": None}, EMPTY_ALLOWLIST), ("allowlist: 9 compatibility pairs", {}, STAGED), ( - "harness reaches model/infra: inferrsi.harness.skill_evaluation" + "harness reaches model/infra: inferrsi.harness.executor.skill_evaluation" " -> inferrsi.infra", { "infra/__init__.py": "", "infra/artifacts.py": "VALUE = 1\n", - "harness/skill_evaluation.py": "from ..infra.artifacts import VALUE\n", + "harness/executor/skill_evaluation.py": ( + "from ...infra.artifacts import VALUE\n" + ), }, EMPTY_ALLOWLIST, ), ( - "harness reaches model/infra: inferrsi.harness.runner -> inferrsi.infra", + "harness reaches model/infra: inferrsi.harness.manager._parallel_round" + " -> inferrsi.infra", { "infra/__init__.py": "", "infra/local.py": "", - "harness/runner.py": "from inferrsi.infra import local\n", + "harness/manager/_parallel_round.py": "from inferrsi.infra import local\n", }, EMPTY_ALLOWLIST, ), ( - "harness reaches model/infra: inferrsi.harness.runner -> inferrsi.bridge" + "harness reaches model/infra: inferrsi.harness.manager._parallel_round" + " -> inferrsi.bridge" " -> inferrsi.model", { # A root helper that is not a retired name: the path alone blocks. "bridge.py": "from inferrsi.model import metrics\n", "model/__init__.py": "", "model/metrics.py": "", - "harness/runner.py": "from inferrsi import bridge\n", + "harness/manager/_parallel_round.py": "from inferrsi import bridge\n", }, EMPTY_ALLOWLIST, ), diff --git a/tests/repository/test_harness_component_freeze.py b/tests/repository/test_harness_component_freeze.py new file mode 100644 index 000000000..f2138ec6f --- /dev/null +++ b/tests/repository/test_harness_component_freeze.py @@ -0,0 +1,51 @@ +"""Check the immutable pre-migration evidence without requiring the historical wheel.""" + +import hashlib +import json +import zipfile +from pathlib import Path + +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures/optimization-session/component-freeze" + + +def test_frozen_inputs_and_plan_contracts(): + manifest = json.loads((FIXTURES / "manifest.json").read_bytes()) + fingerprint = json.loads((FIXTURES / manifest["runtime_sources"]).read_bytes()) + assert set(manifest["samples"]) == {path.name for path in FIXTURES.glob("*.zip")} + for name, digest in manifest["samples"].items(): + archive = FIXTURES / name + assert hashlib.sha256(archive.read_bytes()).hexdigest() == digest, name + with zipfile.ZipFile(archive) as packed: + if name == "cleanup-proofs.zip": + assert set(packed.namelist()) == set(manifest["cleanup_proofs"]) + for member, expected in manifest["cleanup_proofs"].items(): + assert hashlib.sha256(packed.read(member)).hexdigest() == expected, member + else: + plan = json.loads(packed.read("plan.json")) + if name.startswith("ordinary-"): + assert plan["runtime_identity"] == fingerprint + else: + assert plan["schema_version"] == 3 + assert plan["runtime_version"] == manifest["runtime_version"] + + +def test_cleanup_proofs_distinguish_attempt_and_service_identity(): + with zipfile.ZipFile(FIXTURES / "service-cleanup-pending.zip") as session: + state = json.loads(session.read("state.json")) + pending = state["pending"] + checkpoint = json.loads(session.read(pending["path"] + "/execution/execution.json"))[ + "checkpoint" + ] + assert checkpoint["assessment"]["verdict"] == "FAIL" and checkpoint["quality_score"] is None + assert pending["path"] + "/observation.json" not in session.namelist() + with zipfile.ZipFile(FIXTURES / "cleanup-proofs.zip") as proofs: + original = json.loads(proofs.read("cleanup.json")) + foreign = json.loads(proofs.read("wrong-attempt.json")) + mismatched = json.loads(proofs.read("wrong-owner.json")) + wrong_id = json.loads(proofs.read("wrong-attempt-only.json")) + assert original["attempt_id"] == mismatched["attempt_id"] == pending["attempt_id"] + assert foreign["attempt_id"] in {attempt["attempt_id"] for attempt in state["attempts"]} + assert foreign["attempt_id"] != pending["attempt_id"] + assert original["services"] != foreign["services"] + assert mismatched == {**original, "services": foreign["services"]} + assert wrong_id == {**original, "attempt_id": foreign["attempt_id"]} diff --git a/tests/repository/test_legacy_run_forwarder_gate.py b/tests/repository/test_legacy_run_forwarder_gate.py index 07967d7c5..95b706dea 100644 --- a/tests/repository/test_legacy_run_forwarder_gate.py +++ b/tests/repository/test_legacy_run_forwarder_gate.py @@ -70,15 +70,15 @@ def test_no_former_pair_is_still_registered(name): "helper.py imports inferrsi.apps"), # No core passes through a forwarder: the walk now stops at the retired # module itself, before it reaches Apps. Apps does not loop back. - ({"harness/runner.py": "from ..evaluation import VALUE\n"}, - "inferrsi.harness.runner reaches inferrsi.evaluation"), + ({"harness/manager/_runner.py": "from ...evaluation import VALUE\n"}, + "inferrsi.harness.manager._runner reaches inferrsi.evaluation"), ({"benchmark/rules.py": "from ..evaluation import VALUE\n"}, "inferrsi.benchmark.rules reaches inferrsi.evaluation"), ({"apps/legacy/run.py": "from ...evaluation import VALUE\n"}, "inferrsi.apps.legacy.run reaches inferrsi.evaluation"), # A retired name is refused even with no file behind it. - ({"harness/runner.py": "from ..execution import run_experiment\n"}, - "inferrsi.harness.runner reaches inferrsi.execution"), + ({"harness/manager/_runner.py": "from ...execution import run_experiment\n"}, + "inferrsi.harness.manager._runner reaches inferrsi.execution"), ({"apps/legacy/run.py": "from ...reporting import write_report\n"}, "inferrsi.apps.legacy.run reaches inferrsi.reporting"), ], diff --git a/tests/repository/test_target_module_import_gate.py b/tests/repository/test_target_module_import_gate.py index 0fe9ccaa5..709acc36d 100644 --- a/tests/repository/test_target_module_import_gate.py +++ b/tests/repository/test_target_module_import_gate.py @@ -48,6 +48,15 @@ def _module(relative): return "inferrsi." + relative.removesuffix(".py").replace("/", ".") +def test_harness_root_exposes_the_accepted_component_layout(): + root = ROOT / "harness" + assert {p.name for p in root.iterdir() if p.is_dir() and p.name != "__pycache__"} == { + "analyzer", "api", "evaluator", "executor", "indexer", "manager", "records", + } + assert {p.name for p in root.glob("*.py")} == {"__init__.py"} + assert (root / "README.md").is_file() + + def test_retired_loader_tables_do_not_return(): # R3 admits by file location, so no table names a task, a function or a module. for name in ("RESOURCE_LOADERS", "EVALUATOR_LOADERS"): @@ -142,8 +151,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", @@ -171,11 +181,14 @@ def test_by_path_loading_is_admitted_nowhere_else(tmp_path, relative): "inferrsi.model.validators.flare"), ("model/request_guard.py", "from .protocols.metrics import read_metric\n", "inferrsi.model.protocols.metrics"), - # #498 slice 2: the serving modules moved to inferrsi.harness.serving. + # #702 moves serving to Executor after #498 retired the Infra and Model paths. + ("apps/runner.py", "from inferrsi.harness.serving.image import ImageProtocol\n", + "inferrsi.harness.serving.image"), + ("harness/manager/_runner.py", "from .. import serving\n", "inferrsi.harness.serving"), ("benchmark/runner.py", "from inferrsi.infra.processes import launch_server\n", "inferrsi.infra.processes"), ("apps/runner.py", "from inferrsi.infra import http\n", "inferrsi.infra.http"), - ("harness/runner.py", "from ..model.protocols.image import ImageProtocol\n", + ("harness/manager/_runner.py", "from ...model.protocols.image import ImageProtocol\n", "inferrsi.model.protocols.image"), ("apps/runner.py", "import inferrsi.model.protocols\n", "inferrsi.model.protocols"), # #498 slice 3c: the campaign facade is gone. @@ -191,13 +204,19 @@ def test_by_path_loading_is_admitted_nowhere_else(tmp_path, relative): ("apps/runner.py", "from ..infra.environment import storage_locations\n", "inferrsi.infra.environment"), ("apps/runner.py", "from ..infra.commands import probe_command\n", "inferrsi.infra.commands"), - # #558: the trial runner moved to inferrsi.harness.trials. + # Retired trial package names from #558 and #702. + ("apps/runner.py", "from inferrsi.harness.trials.external import execute_trial\n", + "inferrsi.harness.trials.external"), ("apps/runner.py", "from inferrsi.harness.scenarios.external import execute_trial\n", "inferrsi.harness.scenarios.external"), - ("harness/runner.py", "from .scenarios.external import collect_trial_checks\n", + ("harness/manager/_runner.py", "from ..scenarios.external import collect_trial_checks\n", "inferrsi.harness.scenarios.external"), - ("harness/runner.py", "from .scenarios import external\n", + ("harness/manager/_runner.py", "from ..scenarios import external\n", "inferrsi.harness.scenarios.external"), + ("apps/runner.py", "from inferrsi.harness import runner\n", "inferrsi.harness.runner"), + ("apps/runner.py", "from inferrsi.harness import search_tree\n", + "inferrsi.harness.search_tree"), + ("harness/manager/_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}) @@ -227,6 +246,8 @@ def test_retired_model_paths_fail_from_a_package_initializer(tmp_path, importer, "model/validators/flare.py", "model/protocols/__init__.py", "model/protocols/image.py", + "harness/serving/__init__.py", + "harness/serving/server.py", "infra/processes.py", "infra/http.py", "infra/campaign.py", @@ -235,6 +256,8 @@ 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", + "harness/runner.py", ]) def test_retired_model_files_fail_when_they_return(tmp_path, relative): report = _report(tmp_path, {relative: "VALUE = 1\n"}) @@ -254,12 +277,13 @@ def test_the_modules_that_replaced_the_retired_packages_are_not_retired(tmp_path "from inferrsi.apps.storage.artifacts import sha256\n" "from inferrsi.apps.integrations.anthropic import request_guard\n" ), - "harness/runner.py": ( - "from inferrsi.harness.serving.image import ImageProtocol\n" - "from .trials.external import collect_trial_checks\n" + "harness/manager/_runner.py": ( + "from inferrsi.harness.executor import ImageProtocol\n" + "from ..executor.trials.external import collect_trial_checks\n" ), - "harness/trials/__init__.py": "", - "harness/trials/external.py": "def collect_trial_checks():\n return []\n", + "harness/executor/__init__.py": "", + "harness/executor/trials/__init__.py": "", + "harness/executor/trials/external.py": "def collect_trial_checks():\n return []\n", "benchmark/runner.py": "from inferrsi.benchmark.metrics import read_metric\n", }) assert not [item for item in report.violations if "retired module" in item] @@ -301,6 +325,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()) @@ -309,7 +337,14 @@ def test_clean_scan_is_not_isolation(self) -> None: # these files. The single-file re-export and its three root siblings are retired. self.assertEqual( sorted(path.name for path in (ROOT / "contracts").iterdir() if path.is_file()), - ["__init__.py", "claim.py", "evidence.py", "json_v1.py", "runspec.py"], + [ + "__init__.py", + "_harness_errors.py", + "claim.py", + "evidence.py", + "json_v1.py", + "runspec.py", + ], ) for retired in ("contracts.py", "_json_v1.py", "runspec.py", "claim.py", "_repo_pack_data.py", "evidence_paths.py"): @@ -332,6 +367,7 @@ def test_clean_scan_is_not_isolation(self) -> None: support.CONTRACTS_MODULES, { "inferrsi.contracts", + "inferrsi.contracts._harness_errors", "inferrsi.contracts.claim", "inferrsi.contracts.evidence", "inferrsi.contracts.json_v1", @@ -383,13 +419,14 @@ def test_split_skill_eval_modules_reach_no_model_or_infra(self) -> None: # remaining harness -> model/infra hits belong to other modules. report = first_wave_report() for name in ( - "skill_evaluation", - "improvement", - "artifact_sandbox", - "atomic_json", + "executor.skill_evaluation", + "manager.search.improvement", + "executor.artifact_sandbox", + "records.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/tests/skill_eval/test_skill_eval_compare.py b/tests/skill_eval/test_skill_eval_compare.py index ca15e3090..8ba7fe80c 100644 --- a/tests/skill_eval/test_skill_eval_compare.py +++ b/tests/skill_eval/test_skill_eval_compare.py @@ -1009,16 +1009,16 @@ def test_changed_runtime_controllers_reject_execution_and_report_without_calls(t authorization = module.prepare(config, repo, output) module.report(output) saved = (output / "report.json").read_bytes(), (output / "report.md").read_bytes() - assert "src/inferrsi/harness/local_process.py" in module.CONTROLLERS + assert "src/inferrsi/harness/executor/local_process.py" in module.CONTROLLERS assert "src/inferrsi/apps/storage/artifacts.py" in module.CONTROLLERS assert "src/inferrsi/apps/integrations/anthropic/request_guard.py" in module.CONTROLLERS assert "tools/skill_eval_artifact_guidance.py" in module.CONTROLLERS # Each owner of the split trial path is frozen: composed entry, rules and host. - for owner in ("apps/workflows", "benchmark", "harness"): + for owner in ("apps/workflows", "benchmark", "harness/executor"): assert f"src/inferrsi/{owner}/skill_evaluation.py" in module.CONTROLLERS for name in ("apps/workflows/skill_eval_engineering.py", "benchmark/skill_eval_engineering.py", - "benchmark/skill_eval_diagnostic.py", "harness/artifact_sandbox.py", - "harness/atomic_json.py", "harness/input_binding.py"): + "benchmark/skill_eval_diagnostic.py", "harness/executor/artifact_sandbox.py", + "harness/records/atomic_json.py", "harness/executor/_input_binding.py"): assert "src/inferrsi/" + name in module.CONTROLLERS assert not any("harness/skill_eval_" in name for name in module.CONTROLLERS) client = FixedOutputClient(tmp_path) diff --git a/tests/skill_eval/test_skill_eval_engineering.py b/tests/skill_eval/test_skill_eval_engineering.py index e13bc109f..218483aaf 100644 --- a/tests/skill_eval/test_skill_eval_engineering.py +++ b/tests/skill_eval/test_skill_eval_engineering.py @@ -11,7 +11,7 @@ from inferrsi.apps.workflows import skill_eval_engineering as artifact_check from inferrsi.benchmark import skill_eval_engineering as engineering -from inferrsi.harness import artifact_sandbox as sandbox +from inferrsi.harness.executor import artifact_sandbox as sandbox TASK = {"id": "serving-parser", "split": "development", "request": engineering.REQUEST, "provenance": "Reconstructed public regression fixture"} diff --git a/tests/skill_eval/test_skill_eval_generation.py b/tests/skill_eval/test_skill_eval_generation.py index e68606b57..66044df78 100644 --- a/tests/skill_eval/test_skill_eval_generation.py +++ b/tests/skill_eval/test_skill_eval_generation.py @@ -11,8 +11,8 @@ from inferrsi.apps.workflows import skill_eval_engineering as artifact_check from inferrsi.apps.workflows import skill_evaluation as evaluation from inferrsi.benchmark import skill_eval_engineering as engineering -from inferrsi.harness import artifact_sandbox as sandbox -from inferrsi.harness import skill_evaluation as harness +from inferrsi.harness.executor import artifact_sandbox as sandbox +from inferrsi.harness.executor import skill_evaluation as harness from tests.fixtures.skill_eval_compare_support import configuration from tools import skill_eval_compare as compare diff --git a/tests/skill_eval/test_skill_eval_local.py b/tests/skill_eval/test_skill_eval_local.py index c4db184e2..77610f256 100644 --- a/tests/skill_eval/test_skill_eval_local.py +++ b/tests/skill_eval/test_skill_eval_local.py @@ -9,7 +9,7 @@ from inferrsi.apps.storage.artifacts import sha256, write_json from inferrsi.apps.workflows import skill_eval_engineering as artifact_check from inferrsi.benchmark import skill_eval_engineering as engineering -from inferrsi.harness import artifact_sandbox as sandbox +from inferrsi.harness.executor import artifact_sandbox as sandbox from tests.fixtures.skill_eval_compare_support import configuration from tools import skill_eval_compare as compare from tools import skill_eval_local as local @@ -122,7 +122,7 @@ def test_stale_head_and_missing_logs_are_not_accepted(tmp_path): ]) def test_import_command_count_preserves_unknown_and_observed_zero( tmp_path, monkeypatch, commands, completed_turns, expected): - from inferrsi.harness.usage import usage_totals + from inferrsi.harness.records.usage import usage_totals output, digest, head = prepared(tmp_path) monkeypatch.setattr(artifact_check, "verify", fake_verify) diff --git a/tests/skill_eval/test_skill_evaluation.py b/tests/skill_eval/test_skill_evaluation.py index cfa13f1d4..7744a110a 100644 --- a/tests/skill_eval/test_skill_evaluation.py +++ b/tests/skill_eval/test_skill_evaluation.py @@ -8,7 +8,7 @@ from inferrsi.apps.workflows.skill_evaluation import export_bundle, run_trial, summarize from inferrsi.benchmark.skill_evaluation import task_verdict -from inferrsi.harness.skill_evaluation import CodexClient, toml_value, trace_metrics +from inferrsi.harness.executor.skill_evaluation import CodexClient, toml_value, trace_metrics from inferrsi.knowledge.knowledge_operations import KnowledgeReader ROOT = Path(__file__).resolve().parents[2] @@ -269,7 +269,7 @@ def test_expired_real_executor_deadline_records_missing_events(tmp_path): def test_host_trial_takes_verdict_rules_as_ports(tmp_path): - from inferrsi.harness import skill_evaluation as host + from inferrsi.harness.executor import skill_evaluation as host workspace = tmp_path / "workspace" workspace.mkdir() @@ -300,7 +300,8 @@ def verdict(execution, trace, output, checks): def test_harness_owned_writes_and_digests_match_apps_bytes(tmp_path): from inferrsi.apps.storage import artifacts - from inferrsi.harness import atomic_json, input_binding + from inferrsi.harness.executor import _input_binding as input_binding + from inferrsi.harness.records import atomic_json value = {"b": [1.5, None, True, 1e-07, 1e16], "a": "非 ASCII", "nested": {"z": 0.1 + 0.2}} path = tmp_path / "harness.json" @@ -315,7 +316,7 @@ def test_harness_artifact_primitives_match_apps_bytes_and_semantics(tmp_path): import inspect from inferrsi.apps.storage import artifacts as infra - from inferrsi.harness import artifact_primitives as harness + from inferrsi.harness.records import artifact_primitives as harness for name in ("digest", "sha256", "file_lock"): assert inspect.getsource(getattr(harness, name)) == inspect.getsource( 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, diff --git a/tools/parallel_round.py b/tools/parallel_round.py index 5ac10d2de..083d658f4 100644 --- a/tools/parallel_round.py +++ b/tools/parallel_round.py @@ -7,8 +7,12 @@ from pathlib import Path from inferrsi.apps.workflows.parallel_round import close_round, serve_ticket -from inferrsi.harness.confinement import select_backend -from inferrsi.harness.parallel_round import prepare, submit, ticket_status +from inferrsi.harness.executor.confinement import select_backend +from inferrsi.harness.manager import ( + parallel_ticket_status, + prepare_parallel_round, + submit_parallel_ticket, +) def _load(path: str) -> dict: @@ -48,9 +52,9 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) if args.command == "prepare": - result = prepare(_load(args.spec), args.incumbent, args.round_dir) + result = prepare_parallel_round(_load(args.spec), args.incumbent, args.round_dir) elif args.command == "submit": - result = submit( + result = submit_parallel_ticket( args.round_dir, args.lane, args.incumbent, @@ -71,7 +75,7 @@ def main(argv: list[str] | None = None) -> int: backend=select_backend(), ) else: - result = ticket_status(args.round_dir, args.ticket) + result = parallel_ticket_status(args.round_dir, args.ticket) json.dump(result, sys.stdout, indent=2) sys.stdout.write("\n") return 0 diff --git a/tools/skill_eval_cloud_export.py b/tools/skill_eval_cloud_export.py index c4a605a78..c96731479 100644 --- a/tools/skill_eval_cloud_export.py +++ b/tools/skill_eval_cloud_export.py @@ -6,7 +6,7 @@ from inferrsi.apps.storage.artifacts import sha256 from inferrsi.benchmark import skill_eval_engineering as engineering -from inferrsi.harness import artifact_sandbox +from inferrsi.harness.executor import artifact_sandbox from tools import skill_eval_compare as compare diff --git a/tools/skill_eval_cloud_replay.py b/tools/skill_eval_cloud_replay.py index 230a75533..de0039326 100644 --- a/tools/skill_eval_cloud_replay.py +++ b/tools/skill_eval_cloud_replay.py @@ -8,7 +8,7 @@ from inferrsi.apps.workflows import skill_eval_engineering as artifact_check from inferrsi.benchmark import skill_eval_engineering as engineering -from inferrsi.harness import artifact_sandbox +from inferrsi.harness.executor import artifact_sandbox from tools import skill_eval_artifact_guidance as artifact_guidance from tools.skill_eval_qualify import qualify diff --git a/tools/skill_eval_compare.py b/tools/skill_eval_compare.py index 8530dfc7b..a4be7f5ca 100644 --- a/tools/skill_eval_compare.py +++ b/tools/skill_eval_compare.py @@ -25,9 +25,9 @@ from inferrsi.apps.workflows.skill_evaluation import export_bundle, run_trial, summarize from inferrsi.benchmark import skill_eval_diagnostic as diagnostic from inferrsi.benchmark import skill_eval_engineering as engineering -from inferrsi.harness import artifact_sandbox -from inferrsi.harness.skill_evaluation import CodexClient -from inferrsi.harness.usage import normalize_usage +from inferrsi.harness.executor import artifact_sandbox +from inferrsi.harness.executor.skill_evaluation import CodexClient +from inferrsi.harness.records.usage import normalize_usage from inferrsi.knowledge.knowledge_operations import KnowledgeReader, safe_path from tools import skill_eval_artifact_guidance as artifact_guidance from tools.skill_eval_pilot import PROMPT, SCHEMA, observed_tokens @@ -44,10 +44,12 @@ "src/inferrsi/benchmark/skill_evaluation.py", "src/inferrsi/benchmark/skill_eval_diagnostic.py", "src/inferrsi/benchmark/skill_eval_engineering.py", - "src/inferrsi/harness/skill_evaluation.py", - "src/inferrsi/harness/artifact_sandbox.py", "tools/skill_eval_snapshot.py", - "src/inferrsi/harness/local_process.py", "src/inferrsi/harness/atomic_json.py", - "src/inferrsi/harness/input_binding.py", "src/inferrsi/apps/storage/artifacts.py") + "src/inferrsi/harness/executor/skill_evaluation.py", + "src/inferrsi/harness/executor/artifact_sandbox.py", "tools/skill_eval_snapshot.py", + "src/inferrsi/harness/executor/local_process.py", + "src/inferrsi/harness/records/atomic_json.py", + "src/inferrsi/harness/executor/_input_binding.py", + "src/inferrsi/apps/storage/artifacts.py") EVIDENCE = ("execution.json", "agent/stdout.log", "agent/stderr.log", "verification/result.json", "verification/stdout.log", "verification/stderr.log") NUMBER = (int, float) diff --git a/tools/skill_eval_historical_job.py b/tools/skill_eval_historical_job.py index 57b73056b..d55e403fa 100644 --- a/tools/skill_eval_historical_job.py +++ b/tools/skill_eval_historical_job.py @@ -13,7 +13,7 @@ from inferrsi.apps.storage.artifacts import sha256, write_json from inferrsi.benchmark import skill_eval_engineering as engineering -from inferrsi.harness import artifact_sandbox +from inferrsi.harness.executor import artifact_sandbox from tools import skill_eval_auto as auto from tools import skill_eval_compare as compare from tools import skill_eval_historical_accounting as accounting diff --git a/tools/skill_eval_improve.py b/tools/skill_eval_improve.py index d6a858459..4b679e4e8 100644 --- a/tools/skill_eval_improve.py +++ b/tools/skill_eval_improve.py @@ -20,15 +20,15 @@ rerun_assessment, ) from inferrsi.benchmark.improvement import SelectionPolicy -from inferrsi.harness.skill_evaluation import CodexClient -from inferrsi.harness.usage import usage_totals +from inferrsi.harness.executor.skill_evaluation import CodexClient +from inferrsi.harness.records.usage import usage_totals from inferrsi.knowledge.knowledge_operations import KnowledgeReader, safe_path from tools import skill_eval_compare as compare 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/skill_eval_local.py b/tools/skill_eval_local.py index dce023d33..a9b137178 100644 --- a/tools/skill_eval_local.py +++ b/tools/skill_eval_local.py @@ -15,8 +15,8 @@ from inferrsi.apps.storage.artifacts import sha256, write_json from inferrsi.apps.workflows import skill_eval_engineering as artifact_check from inferrsi.benchmark import skill_eval_engineering as engineering -from inferrsi.harness import artifact_sandbox -from inferrsi.harness.usage import normalize_usage +from inferrsi.harness.executor import artifact_sandbox +from inferrsi.harness.records.usage import normalize_usage def _selection(output, authorization, task_id, condition, repeat, current_head): diff --git a/tools/skill_eval_pilot.py b/tools/skill_eval_pilot.py index a1aefa3fb..8172db748 100644 --- a/tools/skill_eval_pilot.py +++ b/tools/skill_eval_pilot.py @@ -9,8 +9,8 @@ from inferrsi.apps.storage.artifacts import sha256, write_json from inferrsi.apps.workflows.skill_evaluation import export_bundle, run_trial, summarize -from inferrsi.harness.skill_evaluation import CodexClient -from inferrsi.harness.usage import normalize_usage +from inferrsi.harness.executor.skill_evaluation import CodexClient +from inferrsi.harness.records.usage import normalize_usage from inferrsi.knowledge.knowledge_operations import KnowledgeReader ROOT = Path(__file__).resolve().parents[1] @@ -207,7 +207,7 @@ def prepare( source_files = [ ROOT / "src/inferrsi/apps/workflows/skill_evaluation.py", ROOT / "src/inferrsi/benchmark/skill_evaluation.py", - ROOT / "src/inferrsi/harness/skill_evaluation.py", + ROOT / "src/inferrsi/harness/executor/skill_evaluation.py", Path(__file__), ROOT / "tools/skill_eval_verifier.py", ] diff --git a/tools/skill_eval_qualify.py b/tools/skill_eval_qualify.py index fc775de1b..a0efd178f 100644 --- a/tools/skill_eval_qualify.py +++ b/tools/skill_eval_qualify.py @@ -14,7 +14,7 @@ from inferrsi.apps.workflows import skill_eval_engineering as artifact_check from inferrsi.benchmark import skill_eval_engineering as engineering -from inferrsi.harness import artifact_sandbox +from inferrsi.harness.executor import artifact_sandbox ROOT = Path(__file__).resolve().parents[1] CONTROL = ROOT / "tests/fixtures/skill_eval_engineering/correct_parser.py" diff --git a/tools/speculative_skill.py b/tools/speculative_skill.py index 14503bbd4..42658a3cf 100644 --- a/tools/speculative_skill.py +++ b/tools/speculative_skill.py @@ -14,11 +14,10 @@ import time from pathlib import Path -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.trials.external import execute_trial +from inferrsi.harness.executor import candidates, 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 from inferrsi.knowledge.knowledge_operations import KnowledgeReader from tools import skill_eval_compare as compare from tools.skill_eval_improve import materialize