From 88f0cbd63be48e64c6ac38f0dbcab8f2752c40a0 Mon Sep 17 00:00:00 2001 From: dongxinwen Date: Fri, 27 Nov 2026 06:02:07 +0800 Subject: [PATCH 1/4] Move published serving helpers into Executor --- CHANGELOG.md | 5 ++++ docs/architecture.md | 4 +-- docs/contributing.md | 2 +- docs/guides/module-layout.md | 3 +++ examples/qwen21_turbo_b300.py | 3 +-- src/inferrsi/harness/README.md | 2 ++ src/inferrsi/harness/executor/__init__.py | 19 ++++++++++--- .../{ => executor}/serving/__init__.py | 0 .../http.py => executor/serving/_http.py} | 0 .../image.py => executor/serving/_image.py} | 2 +- .../server.py => executor/serving/_server.py} | 0 tests/apps/test_optimization_session.py | 2 ++ tests/benchmark/test_image_modules.py | 2 +- tests/harness/test_server_processes.py | 16 ++++++----- tests/repository/_gate_policy_support.py | 3 ++- tests/repository/check_installed.py | 27 ++++++++++--------- .../test_target_module_import_gate.py | 9 +++++-- 17 files changed, 66 insertions(+), 33 deletions(-) rename src/inferrsi/harness/{ => executor}/serving/__init__.py (100%) rename src/inferrsi/harness/{serving/http.py => executor/serving/_http.py} (100%) rename src/inferrsi/harness/{serving/image.py => executor/serving/_image.py} (98%) rename src/inferrsi/harness/{serving/server.py => executor/serving/_server.py} (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f3a87d4e..2b14fbb25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,11 @@ ### Changed +- 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. + - Import the four-port AB/BA loop with `from inferrsi.harness.manager import run_experiment`. The former `inferrsi.harness.runner` module was removed. The `inferrsi run` CLI and `inferrsi.apps.legacy.run.run_experiment` continue to supply the four port bindings. diff --git a/docs/architecture.md b/docs/architecture.md index e384b3d4e..02ff57be3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -284,7 +284,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/executor/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 | @@ -380,7 +380,7 @@ 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 diff --git a/docs/contributing.md b/docs/contributing.md index 7e69fbfb4..052b626fa 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -35,7 +35,7 @@ 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/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 diff --git a/docs/guides/module-layout.md b/docs/guides/module-layout.md index 5ad5a7b7e..358b5536b 100644 --- a/docs/guides/module-layout.md +++ b/docs/guides/module-layout.md @@ -67,6 +67,9 @@ 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. + 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 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/harness/README.md b/src/inferrsi/harness/README.md index b07574899..278136147 100644 --- a/src/inferrsi/harness/README.md +++ b/src/inferrsi/harness/README.md @@ -38,6 +38,8 @@ measurement and assessment rules. 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 diff --git a/src/inferrsi/harness/executor/__init__.py b/src/inferrsi/harness/executor/__init__.py index 9517f7cc4..4ef2999b0 100644 --- a/src/inferrsi/harness/executor/__init__.py +++ b/src/inferrsi/harness/executor/__init__.py @@ -1,4 +1,4 @@ -"""Local execution targets, generation preparation and verified input bindings.""" +"""Local execution targets, serving helpers, generation preparation and input bindings.""" import hashlib import os @@ -10,12 +10,25 @@ from inferrsi.contracts import json_v1 __all__ = [ - "LocalCpuTarget", "prepare_generation", "process_group_empty", "project_prepared_binding", - "read_prepared_binding", "request_digest", "runtime_environment", "verify_prepared_binding", + "ImageProtocol", "LocalCpuTarget", "launch_server", "post_json", "prepare_generation", + "process_group_empty", "project_prepared_binding", "read_prepared_binding", "request_digest", + "runtime_environment", "stop_server", "verify_prepared_binding", ] def __getattr__(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 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/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/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/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index c9f9b4def..5bdf01c0c 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -1443,6 +1443,8 @@ 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 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/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/repository/_gate_policy_support.py b/tests/repository/_gate_policy_support.py index fe5e519a4..db7409b72 100644 --- a/tests/repository/_gate_policy_support.py +++ b/tests/repository/_gate_policy_support.py @@ -102,11 +102,12 @@ # 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. -# #702 moved the root-level runner and ten search modules under the Manager. +# #702 moved the root-level runner and ten search modules under Manager and serving under Executor. RETIRED_MODULES = frozenset({ "inferrsi.infra", "inferrsi.model", "inferrsi.harness.scenarios", + "inferrsi.harness.serving", "inferrsi.harness.runner", "inferrsi.harness.trials", "inferrsi.harness.local_process", diff --git a/tests/repository/check_installed.py b/tests/repository/check_installed.py index f5669a890..b31efa82c 100644 --- a/tests/repository/check_installed.py +++ b/tests/repository/check_installed.py @@ -1033,11 +1033,8 @@ def assess(baseline, candidate, validation, integrity, error): 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", @@ -1046,15 +1043,15 @@ def assess(baseline, candidate, validation, integrity, error): "inferrsi.model.request_guard", "inferrsi.harness.scenarios", "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.launch_records", "inferrsi.harness.device_lease", + "inferrsi.harness.serving", "inferrsi.harness.serving.server", + "inferrsi.harness.serving.http", "inferrsi.harness.serving.image"): assert_not_importable(retired) assert not {child.name for child in files("inferrsi").iterdir()} & {"infra", "model"} 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.harness.serving", "inferrsi.harness.serving.server", - "inferrsi.harness.serving.http", "inferrsi.harness.serving.image", "inferrsi.apps.host.commands", "inferrsi.apps.host.inspection", "inferrsi.apps.host.environment", "inferrsi.apps.host.platforms", "inferrsi.apps.host.targets", "inferrsi.apps.storage.artifacts", @@ -1134,14 +1131,18 @@ 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" + "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" "assert not [n for n in loaded if n.startswith(('inferrsi.infra', 'inferrsi.model'))]\n" ) with tempfile.TemporaryDirectory(prefix="inferrsi-serving-") as serving_cwd: diff --git a/tests/repository/test_target_module_import_gate.py b/tests/repository/test_target_module_import_gate.py index 09dbe619a..ff4b893a5 100644 --- a/tests/repository/test_target_module_import_gate.py +++ b/tests/repository/test_target_module_import_gate.py @@ -171,7 +171,10 @@ 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"), @@ -233,6 +236,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", @@ -263,7 +268,7 @@ def test_the_modules_that_replaced_the_retired_packages_are_not_retired(tmp_path "from inferrsi.apps.integrations.anthropic import request_guard\n" ), "harness/manager/_runner.py": ( - "from inferrsi.harness.serving.image import ImageProtocol\n" + "from inferrsi.harness.executor import ImageProtocol\n" "from ..executor.trials.external import collect_trial_checks\n" ), "harness/executor/__init__.py": "", From d4243c35fcb5c9765f403a554a96f96a25f3994a Mon Sep 17 00:00:00 2001 From: dongxinwen Date: Fri, 27 Nov 2026 06:12:39 +0800 Subject: [PATCH 2/4] Decide service stages and validate retained receipts in Evaluator --- src/inferrsi/harness/README.md | 4 +- src/inferrsi/harness/evaluator/__init__.py | 45 +++ src/inferrsi/harness/evaluator/_service.py | 220 ++++++++++++++ .../_service_evidence.py} | 30 +- src/inferrsi/harness/optimization.py | 58 ++-- src/inferrsi/harness/project_service.py | 283 ++++-------------- src/inferrsi/harness/records/service_io.py | 11 + src/inferrsi/harness/service_backfill.py | 2 +- tests/harness/test_project_objectives.py | 75 +++-- 9 files changed, 427 insertions(+), 301 deletions(-) create mode 100644 src/inferrsi/harness/evaluator/__init__.py create mode 100644 src/inferrsi/harness/evaluator/_service.py rename src/inferrsi/harness/{service_evidence.py => evaluator/_service_evidence.py} (91%) diff --git a/src/inferrsi/harness/README.md b/src/inferrsi/harness/README.md index 278136147..eff9d5076 100644 --- a/src/inferrsi/harness/README.md +++ b/src/inferrsi/harness/README.md @@ -70,7 +70,9 @@ The agent chooses a hypothesis and edits a candidate between rounds. - **Evaluator** uses the frozen rules and stage receipts to decide the next stage or verdict. [_session_assess](optimization_session.py) dispatches packaged tasks to their protocol assessor and project trials to the [AB/BA assessor](project.py). Service screening is - diagnostic. [Service evaluation](project_service.py) uses formal samples and quality evidence. + 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 diff --git a/src/inferrsi/harness/evaluator/__init__.py b/src/inferrsi/harness/evaluator/__init__.py new file mode 100644 index 000000000..1140101d8 --- /dev/null +++ b/src/inferrsi/harness/evaluator/__init__.py @@ -0,0 +1,45 @@ +"""Evaluate service stage receipts and retained comparison evidence.""" + +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__ = [ + "ServiceStageDecision", + "aggregate_service_measurements", + "assess_service_performance", + "check_service_quality_reference", + "prefer_service_measurements", + "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", +] 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 91% rename from src/inferrsi/harness/service_evidence.py rename to src/inferrsi/harness/evaluator/_service_evidence.py index c3d85c94d..830c6320f 100644 --- a/src/inferrsi/harness/service_evidence.py +++ b/src/inferrsi/harness/evaluator/_service_evidence.py @@ -2,24 +2,24 @@ from pathlib import Path -from . import project_service as service -from .records import service_io +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"], @@ -94,7 +94,7 @@ def receipt(stage): 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()) ): @@ -108,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"], @@ -144,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"]: @@ -185,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] @@ -197,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" @@ -223,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"] @@ -237,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/optimization.py b/src/inferrsi/harness/optimization.py index c43387642..8e444fd6f 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -9,7 +9,7 @@ from functools import cache from pathlib import Path -from . import analyzer, attempt_recovery, indexer +from . import analyzer, attempt_recovery, evaluator, indexer from .executor import candidates from .records import knowledge_capture, service_io from .records.artifact_primitives import digest, file_lock, sha256 @@ -962,9 +962,9 @@ def _service_initialize(root, plan): 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"] ) ): @@ -1085,7 +1085,7 @@ 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", {}) @@ -1102,7 +1102,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" @@ -1130,7 +1129,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): @@ -1148,7 +1147,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 @@ -1157,7 +1155,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"] ) @@ -1306,7 +1304,6 @@ 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 directory = service_io.safe_path(root, pending["path"]) checkpoint = execution.get("checkpoint") @@ -1333,7 +1330,7 @@ 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( root, @@ -1358,10 +1355,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"), @@ -1370,23 +1367,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" ) @@ -1428,7 +1427,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, " @@ -1478,7 +1477,6 @@ def _service_execute(root, directory, plan, state, deadline): pending = state["pending"] if pending["kind"] != "refresh": return service.execute(root, directory, plan, pending, deadline) - from . import service_evidence from .records import service_observations references, runs = [], [] @@ -1517,17 +1515,19 @@ def _service_execute(root, directory, plan, state, 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, @@ -1547,7 +1547,6 @@ def _service_cleanup_confirmed(state, attempt): def _service_cleanup_receipt(root, state, path): - from . import project_service as service from .executor import process_group_empty latest = state["pending"] or (state["attempts"][-1] if state["attempts"] else None) @@ -1558,7 +1557,7 @@ def _service_cleanup_receipt(root, state, path): 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", [])) ) @@ -1605,7 +1604,6 @@ def _service_cleanup_receipt(root, state, path): def service_command(root, args, *, 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 with _locked(root): action = args.session_action @@ -1691,7 +1689,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" ), ) @@ -1886,8 +1884,8 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non 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, @@ -1924,7 +1922,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, } @@ -1938,7 +1936,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non 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/project_service.py b/src/inferrsi/harness/project_service.py index 74d1ffdde..d3db5f57f 100644 --- a/src/inferrsi/harness/project_service.py +++ b/src/inferrsi/harness/project_service.py @@ -5,35 +5,22 @@ """ import json -import math import os import re import subprocess import time import uuid from pathlib import Path -from statistics import mean, median +from . import evaluator from .executor.candidates import members, retain from .records import service_io from .records.atomic_json import atomic_write_json -INLINE_PROFILE_REASONS = ("fixed_checks_satisfied", "performance_gate_not_met") # Round and reference records repeat this metadata. The collector's raw receipt stays on disk. PROFILE_METADATA_LIMIT = 32 * 1024 -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") @@ -74,9 +61,11 @@ def validate(settings): 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")): + 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 positive(sampling["profile_timeout_seconds"]): + 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, {}) @@ -127,8 +116,8 @@ def validate(settings): 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")) + 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") @@ -137,7 +126,7 @@ def validate(settings): 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: + 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): @@ -163,7 +152,9 @@ def validate(settings): 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): + 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 ( @@ -178,7 +169,7 @@ def validate(settings): 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")) + 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( @@ -187,134 +178,6 @@ def validate(settings): 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.""" @@ -415,25 +278,6 @@ def prepare(root, args): } -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 = service_io.safe_path(root, directory.relative_to(root).as_posix()) @@ -465,7 +309,7 @@ def validated_profile(root, directory, attempt_id, conditions, binding, step, *, 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 ( + 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") @@ -570,10 +414,14 @@ def proven_capture_elapsed(root, pending, execution): 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: + if not service_io.finite_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: + 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): @@ -583,7 +431,7 @@ def proven_capture_elapsed(root, pending, execution): stage = step["id"] if ( step.get("status") != "running" - or not number(offset) + 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) @@ -602,9 +450,9 @@ def proven_capture_elapsed(root, pending, execution): 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 not service_io.finite_number(duration) or duration < 0 - or not number(offset + duration) + or not service_io.finite_number(offset + duration) ): return elapsed return offset + duration @@ -770,8 +618,8 @@ def evaluate(role): 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( + preview = evaluator.aggregate_service_measurements(settings, docs, role) + record["screening"] = evaluator.assess_service_performance( settings, preview, parent["measurements"], @@ -805,35 +653,24 @@ def evaluate(role): if first_failure is not None: record["failed_stage"], error = first_failure raise error - measured = aggregate(settings, docs, role) + measured = evaluator.aggregate_service_measurements(settings, docs, role) gate = ( - performance( + evaluator.assess_service_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: + 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": reference_path, + "path": decision.quality_reference, "started_at": time.time(), } record["steps"].append(reference_step) @@ -843,19 +680,12 @@ def evaluate(role): service_io.safe_path( root, pending.get("protocol_path", "frozen/protocol") ), - reference_path, + decision.quality_reference, ) ) - 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) + evaluator.check_service_quality_reference( + settings, quality, pending["revision"], conditions + ) reference_step.update( status="completed", ended_at=time.time(), result=quality ) @@ -865,29 +695,16 @@ def evaluate(role): if quality.get("status") == "candidate_failure": quality_ok = False else: - score = quality_score(settings, quality) - quality_ok = quality_passed( + score = evaluator.service_quality_score(settings, quality) + quality_ok = evaluator.service_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, - ) + 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") @@ -966,17 +783,15 @@ def capture_profile(): 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: + if not evaluator.service_precheck_passed(precheck): skipped(("service", "measurement", "quality", "profile"), "precheck_rejected") - record["assessment"] = assessment("FAIL", "functional_check_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 - 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" @@ -996,7 +811,9 @@ def capture_profile(): try: ready = stage("ready") if ( - not ready_for_service(ready, revision=expected["revision"], pid=process.pid) + 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") @@ -1005,14 +822,14 @@ def capture_profile(): stage(f"warmup-{index + 1:03d}") if standalone: capture_profile() - record["assessment"] = assessment( + record["assessment"] = evaluator.service_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: + if evaluator.service_profile_eligible(record["assessment"]["reason"]): capture_profile() except BaseException: record.setdefault("failed_stage", record["steps"][-1]["id"]) @@ -1036,7 +853,7 @@ def capture_profile(): failed = record.get( "failed_stage", record["steps"][-1]["id"] if record["steps"] else "startup" ) - record["assessment"] = assessment( + record["assessment"] = evaluator.service_assessment( "INCONCLUSIVE", service_io.error_excerpt(f"{failed}: {type(error).__name__}: {error}"), performance=gate, diff --git a/src/inferrsi/harness/records/service_io.py b/src/inferrsi/harness/records/service_io.py index f6e630533..6ef97da8d 100644 --- a/src/inferrsi/harness/records/service_io.py +++ b/src/inferrsi/harness/records/service_io.py @@ -7,6 +7,17 @@ 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") diff --git a/src/inferrsi/harness/service_backfill.py b/src/inferrsi/harness/service_backfill.py index 272da2df0..9bd989f3c 100644 --- a/src/inferrsi/harness/service_backfill.py +++ b/src/inferrsi/harness/service_backfill.py @@ -117,7 +117,7 @@ def _finish(root, plan, state, execution, *, preparation_seconds=None): 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) 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") From cf96584ee46060e8a6c941cc81d9608a6dfa62bc Mon Sep 17 00:00:00 2001 From: dongxinwen Date: Fri, 27 Nov 2026 06:35:09 +0800 Subject: [PATCH 3/4] Move the supervised service lifecycle into Harness Executor Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (author) Signed-off-by: dongxinwen --- CHANGELOG.md | 4 + docs/architecture.md | 7 +- docs/guides/module-layout.md | 5 + src/inferrsi/harness/README.md | 2 +- src/inferrsi/harness/executor/__init__.py | 41 +- .../harness/executor/serving/_attempt.py | 447 +++++++++ .../harness/executor/serving/_plan.py | 268 ++++++ .../harness/executor/serving/_profile.py | 191 ++++ src/inferrsi/harness/optimization.py | 39 +- src/inferrsi/harness/optimization_session.py | 2 +- src/inferrsi/harness/project_service.py | 895 ------------------ src/inferrsi/harness/service_backfill.py | 17 +- tests/apps/test_project_service_reuse.py | 29 +- .../harness/test_service_backfill_recovery.py | 5 +- .../test_service_capture_accounting.py | 25 +- .../test_service_profile_diagnostics.py | 6 +- tests/repository/_gate_policy_support.py | 3 + tests/repository/check_installed.py | 6 +- 18 files changed, 1029 insertions(+), 963 deletions(-) create mode 100644 src/inferrsi/harness/executor/serving/_attempt.py create mode 100644 src/inferrsi/harness/executor/serving/_plan.py create mode 100644 src/inferrsi/harness/executor/serving/_profile.py delete mode 100644 src/inferrsi/harness/project_service.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b14fbb25..9e133e7c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,10 @@ `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 diff --git a/docs/architecture.md b/docs/architecture.md index 02ff57be3..e94f99f90 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -29,9 +29,10 @@ rules, while Harness manages their execution and the complete optimization lifec 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 diff --git a/docs/guides/module-layout.md b/docs/guides/module-layout.md index 358b5536b..b4e577ca4 100644 --- a/docs/guides/module-layout.md +++ b/docs/guides/module-layout.md @@ -70,6 +70,11 @@ into runs by file path. 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 diff --git a/src/inferrsi/harness/README.md b/src/inferrsi/harness/README.md index eff9d5076..270db72ad 100644 --- a/src/inferrsi/harness/README.md +++ b/src/inferrsi/harness/README.md @@ -65,7 +65,7 @@ The agent chooses a hypothesis and edits a candidate between rounds. 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](project_service.py), +- **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. [_session_assess](optimization_session.py) dispatches packaged tasks to their protocol diff --git a/src/inferrsi/harness/executor/__init__.py b/src/inferrsi/harness/executor/__init__.py index 4ef2999b0..ae272ca05 100644 --- a/src/inferrsi/harness/executor/__init__.py +++ b/src/inferrsi/harness/executor/__init__.py @@ -10,13 +10,48 @@ from inferrsi.contracts import json_v1 __all__ = [ - "ImageProtocol", "LocalCpuTarget", "launch_server", "post_json", "prepare_generation", - "process_group_empty", "project_prepared_binding", "read_prepared_binding", "request_digest", - "runtime_environment", "stop_server", "verify_prepared_binding", + "ImageProtocol", + "LocalCpuTarget", + "execute_service_attempt", + "launch_server", + "post_json", + "prepare_generation", + "prepare_service", + "process_group_empty", + "project_prepared_binding", + "read_prepared_binding", + "read_service_attempt_profile", + "request_digest", + "retain_service_revision", + "runtime_environment", + "service_capture_diagnostic", + "service_capture_elapsed", + "service_revision", + "stop_server", + "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 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/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/optimization.py b/src/inferrsi/harness/optimization.py index 8e444fd6f..be3a3e97c 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -954,9 +954,9 @@ 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 @@ -1017,15 +1017,15 @@ def _service_runtime_matches(plan): def _service_load(root, plan, state, *, read_only=False): - from . import project_service as service + 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"]) + 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"]) + 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) @@ -1052,13 +1052,12 @@ def _service_load(root, plan, state, *, read_only=False): def _service_profiling(root, attempt, *, published=None): - from . import project_service as service - from . import service_backfill + from . import executor, 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} @@ -1076,7 +1075,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"] @@ -1092,7 +1091,7 @@ def _service_account_capture(root, state, pending, execution): 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), } @@ -1303,7 +1302,7 @@ 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 executor directory = service_io.safe_path(root, pending["path"]) checkpoint = execution.get("checkpoint") @@ -1332,7 +1331,7 @@ def _service_settle(root, plan, state, pending, execution): and "profile" in plan["evaluation_settings"]["commands"] and evaluator.service_profile_eligible(checkpoint["assessment"]["reason"]) ): - execution["profiling_error"] = service.capture_diagnostic( + execution["profiling_error"] = executor.service_capture_diagnostic( root, directory, "profile", @@ -1472,11 +1471,11 @@ 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) + return executor.execute_service_attempt(root, directory, plan, pending, deadline) from .records import service_observations references, runs = [], [] @@ -1511,7 +1510,7 @@ 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 { @@ -1603,7 +1602,7 @@ def _service_cleanup_receipt(root, state, path): def service_command(root, args, *, 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 executor with _locked(root): action = args.session_action @@ -1812,7 +1811,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non if args.candidate.is_symlink(): raise ValueError("Candidate root cannot be symbolic") source = args.candidate.resolve() - commit = service.revision(source, plan["candidate_includes"]) + 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": []}) @@ -1822,7 +1821,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non if len(state["rounds"]) >= plan["round_limit"]: raise ValueError("No round budget for current-conditions acceptance") conditions = service_io.read(args.conditions) - service.validate_conditions(conditions) + executor.validate_service_conditions(conditions) if not old: if conditions == state["conditions"]: raise ValueError("No changed conditions; reuse compatible retained references") @@ -1874,10 +1873,10 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non 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: diff --git a/src/inferrsi/harness/optimization_session.py b/src/inferrsi/harness/optimization_session.py index a1376c675..d21b47f7f 100644 --- a/src/inferrsi/harness/optimization_session.py +++ b/src/inferrsi/harness/optimization_session.py @@ -168,7 +168,7 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None "quality_command", ) if args.evaluation_mode == "service_reuse": - from inferrsi.harness.project_service import prepare as prepare_service + from inferrsi.harness.executor import prepare_service if args.evaluation_config is None or any( getattr(args, key) is not None for key in names diff --git a/src/inferrsi/harness/project_service.py b/src/inferrsi/harness/project_service.py deleted file mode 100644 index d3db5f57f..000000000 --- a/src/inferrsi/harness/project_service.py +++ /dev/null @@ -1,895 +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 os -import re -import subprocess -import time -import uuid -from pathlib import Path - -from . import evaluator -from .executor.candidates import members, retain -from .records import service_io -from .records.atomic_json import atomic_write_json - -# Round and reference records repeat this metadata. The collector's raw receipt stays on disk. -PROFILE_METADATA_LIMIT = 32 * 1024 - - -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") - service_io.no_fingerprints(conditions) - - -def validate(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_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 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 = 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(root, args): - from inferrsi import __version__ - - settings = service_io.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 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 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 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 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 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 - - -def execute(root, directory, plan, pending, deadline): - """One retained attempt, one owned service, ordered client stages, no silent retry.""" - from .executor import runtime_environment - from .executor.local_process import supervised_service - from .executor.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 = 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_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/service_backfill.py b/src/inferrsi/harness/service_backfill.py index 9bd989f3c..3be0ac3e9 100644 --- a/src/inferrsi/harness/service_backfill.py +++ b/src/inferrsi/harness/service_backfill.py @@ -4,8 +4,7 @@ import time import uuid -from . import optimization -from . import project_service as service +from . import executor, optimization from .records import service_io from .records.atomic_json import atomic_write_json @@ -75,7 +74,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} ) @@ -100,7 +99,7 @@ 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( + return executor.service_capture_diagnostic( root, service_io.safe_path(root, pending["path"]), stage, status, message ) @@ -141,7 +140,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: @@ -184,7 +183,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) @@ -277,7 +278,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" diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 09b541b8f..2d98f8aa8 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -14,7 +14,8 @@ 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, optimization +from inferrsi.harness.executor.serving import _attempt 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 @@ -1221,7 +1222,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() @@ -1236,19 +1237,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() @@ -1260,16 +1261,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): @@ -1279,9 +1280,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]) @@ -1541,7 +1542,7 @@ class CoordinatorCrash(BaseException): root = campaign["root"] initial = service_io.read(root / "state.json") plan = service_io.read(root / "plan.json") - original_write = project_service.atomic_write_json + original_write = _attempt.atomic_write_json frozen = {} def stop_after_durable_boundary(path, document): @@ -1562,7 +1563,7 @@ 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) @@ -1634,7 +1635,7 @@ def advance_clock_during_profile(monkeypatch, seconds): 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 = [] diff --git a/tests/harness/test_service_backfill_recovery.py b/tests/harness/test_service_backfill_recovery.py index 44707dd28..3ca563999 100644 --- a/tests/harness/test_service_backfill_recovery.py +++ b/tests/harness/test_service_backfill_recovery.py @@ -6,8 +6,7 @@ import pytest -from inferrsi.harness import optimization, service_backfill -from inferrsi.harness import project_service as service +from inferrsi.harness import executor, optimization, service_backfill 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 @@ -48,7 +47,7 @@ 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 diff --git a/tests/harness/test_service_capture_accounting.py b/tests/harness/test_service_capture_accounting.py index 7ac0f9986..bb029acc5 100644 --- a/tests/harness/test_service_capture_accounting.py +++ b/tests/harness/test_service_capture_accounting.py @@ -5,8 +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 @@ -17,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): @@ -33,10 +34,10 @@ 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) @@ -51,11 +52,11 @@ def stop_before_progress_write(path, document): 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"}, @@ -64,17 +65,17 @@ 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_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], }) @@ -90,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_profile_diagnostics.py b/tests/harness/test_service_profile_diagnostics.py index 460de2414..48d8f5010 100644 --- a/tests/harness/test_service_profile_diagnostics.py +++ b/tests/harness/test_service_profile_diagnostics.py @@ -4,7 +4,7 @@ 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 @@ -30,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 @@ -41,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" diff --git a/tests/repository/_gate_policy_support.py b/tests/repository/_gate_policy_support.py index db7409b72..fef0b758e 100644 --- a/tests/repository/_gate_policy_support.py +++ b/tests/repository/_gate_policy_support.py @@ -108,6 +108,8 @@ "inferrsi.model", "inferrsi.harness.scenarios", "inferrsi.harness.serving", + "inferrsi.harness.project_service", + "inferrsi.harness.service_evidence", "inferrsi.harness.runner", "inferrsi.harness.trials", "inferrsi.harness.local_process", @@ -169,6 +171,7 @@ NEW_H_ENTRIES = ( "inferrsi.harness.api", "inferrsi.contracts._harness_errors", + "inferrsi.harness.evaluator", "inferrsi.harness.executor._execution", "inferrsi.harness.executor", "inferrsi.harness.executor._input_binding", diff --git a/tests/repository/check_installed.py b/tests/repository/check_installed.py index b31efa82c..51467c1c4 100644 --- a/tests/repository/check_installed.py +++ b/tests/repository/check_installed.py @@ -1045,7 +1045,8 @@ def assess(baseline, candidate, validation, integrity, error): "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.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.executor.local_process", @@ -1143,6 +1144,9 @@ def session_bytes(): "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, service_assessment, service_settlement_reason)))\n" "assert not [n for n in loaded if n.startswith(('inferrsi.infra', 'inferrsi.model'))]\n" ) with tempfile.TemporaryDirectory(prefix="inferrsi-serving-") as serving_cwd: From 66e02207a8b7a1320334b23646d9e6add5c7c8c2 Mon Sep 17 00:00:00 2001 From: dongxinwen Date: Fri, 27 Nov 2026 06:59:13 +0800 Subject: [PATCH 4/4] Verify installed service recovery against version and cleanup boundaries Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (author) Signed-off-by: dongxinwen --- src/inferrsi/harness/README.md | 41 +++++++--- tests/apps/test_project_service_reuse.py | 29 ++++++- .../component-freeze/README.md | 32 ++++++++ tests/harness/test_harness_execute.py | 25 +++++- tests/repository/check_harness_freeze.py | 81 +++++++++++++++++-- tests/repository/check_installed.py | 5 +- 6 files changed, 189 insertions(+), 24 deletions(-) diff --git a/src/inferrsi/harness/README.md b/src/inferrsi/harness/README.md index 270db72ad..ff2e2290c 100644 --- a/src/inferrsi/harness/README.md +++ b/src/inferrsi/harness/README.md @@ -117,23 +117,36 @@ sequenceDiagram alt Ordinary session M->>M: Check the runtime fingerprint and retained execution else Service-reuse session - M->>M: Check the plan version, checkpoint and cleanup for this attempt + 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->>X: Pass precheck, start the service and measure - X->>V: Role, reference type, frozen gates and formal samples - V-->>X: Next stage or reason to skip - X->>V: Stage receipts, quality source or reason for skipping quality - V-->>X: Formal verdict and evidence references - X->>X: Save the candidate checkpoint - opt Eligible verdict and configured inline profiling - X->>X: Capture profile on this service and record the result or interruption + 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 - X->>X: Stop the service and capture cleanup proof - X-->>M: Checkpoint and cleanup proof bound to the original attempt 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 @@ -158,7 +171,11 @@ Workers can exchange immutable inputs and evidence references. Live processes, l 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. In a service-reuse candidate, a +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 diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 2d98f8aa8..7e43b439a 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -1582,8 +1582,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() @@ -1597,12 +1602,32 @@ def stop_after_durable_boundary(path, document): 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"] diff --git a/tests/fixtures/optimization-session/component-freeze/README.md b/tests/fixtures/optimization-session/component-freeze/README.md index 0124ee72b..78309cf35 100644 --- a/tests/fixtures/optimization-session/component-freeze/README.md +++ b/tests/fixtures/optimization-session/component-freeze/README.md @@ -32,6 +32,38 @@ The driver compares the 1,021 installed package files to the supplied wheel, che 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. diff --git a/tests/harness/test_harness_execute.py b/tests/harness/test_harness_execute.py index e9a5fa667..e718cdadc 100644 --- a/tests/harness/test_harness_execute.py +++ b/tests/harness/test_harness_execute.py @@ -53,6 +53,26 @@ "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. +SERVICE_PROTOCOL_MODULES = { + "inferrsi.harness.evaluator", + "inferrsi.harness.evaluator._service", + "inferrsi.harness.evaluator._service_evidence", + "inferrsi.harness.executor.candidates", + "inferrsi.harness.executor.launch_records", + "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; " @@ -472,8 +492,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 | SERVICE_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/repository/check_harness_freeze.py b/tests/repository/check_harness_freeze.py index 6be249019..cf281ba32 100644 --- a/tests/repository/check_harness_freeze.py +++ b/tests/repository/check_harness_freeze.py @@ -8,6 +8,7 @@ import sys import tempfile import zipfile +from email.parser import BytesParser from importlib.metadata import distribution from pathlib import Path @@ -46,7 +47,7 @@ def unpack(name, destination, manifest): packed.extractall(destination) -def cli(root, command, action, *args, expected=0, children=0): +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( @@ -82,7 +83,7 @@ def cli(root, command, action, *args, expected=0, children=0): if children: assert all("protocol_child.py" in launch for launch in launches), launches if expected: - assert b"cleanup" in (result.stdout + result.stderr).lower() + assert error in (result.stdout + result.stderr).lower() return None return json.loads(result.stdout) @@ -196,6 +197,17 @@ def service(root, name, proofs): 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.harness.optimization_session import _runtime_identity @@ -214,21 +226,78 @@ def check_install(manifest, wheel): 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 = [ - n for n in packed.namelist() if n.startswith("inferrsi/") and not n.endswith("/") - ] + 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 baseline wheel installed in this interpreter" + "--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() diff --git a/tests/repository/check_installed.py b/tests/repository/check_installed.py index 51467c1c4..153ff80aa 100644 --- a/tests/repository/check_installed.py +++ b/tests/repository/check_installed.py @@ -1146,8 +1146,9 @@ def session_bytes(): "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, service_assessment, service_settlement_reason)))\n" - "assert not [n for n in loaded if n.startswith(('inferrsi.infra', 'inferrsi.model'))]\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(