From db436e22d49c3215c9870722527b7191793fcac0 Mon Sep 17 00:00:00 2001 From: zengchuang Date: Mon, 23 Nov 2026 10:54:18 +0800 Subject: [PATCH 1/4] feat(apps): expose saved-request evaluation CLI Agent-assisted-by: Codex (author/integrator) Signed-off-by: zengchuang --- docs/apps-evaluate-cli.md | 120 +++++++++++ docs/operations.md | 1 + src/inferrsi/apps/cli/__init__.py | 4 + src/inferrsi/apps/cli/arguments.py | 3 + src/inferrsi/apps/cli/evaluate.py | 179 ++++++++++++++++ tests/check_installed.py | 6 + tests/test_apps_evaluate_cli.py | 322 +++++++++++++++++++++++++++++ 7 files changed, 635 insertions(+) create mode 100644 docs/apps-evaluate-cli.md create mode 100644 src/inferrsi/apps/cli/evaluate.py create mode 100644 tests/test_apps_evaluate_cli.py diff --git a/docs/apps-evaluate-cli.md b/docs/apps-evaluate-cli.md new file mode 100644 index 000000000..7e73d3794 --- /dev/null +++ b/docs/apps-evaluate-cli.md @@ -0,0 +1,120 @@ +# Saved-request evaluation CLI + +`inferrsi evaluate prepare`, `execute` and `assess` use the same Apps API and +persisted result as Python. They consume already saved requests. A trusted +Python caller or host allocates the Harness attempt before saving an execution +request; the CLI does not allocate one or automatically retry a failed call. + +```bash +inferrsi evaluate prepare --request @ \ + --output-id --workspace \ + --storage-config --runtime-config +inferrsi evaluate execute --request @ \ + --output-id --workspace \ + --storage-config --runtime-config +inferrsi evaluate assess --request @ \ + --output-id --workspace \ + --storage-config +``` + +Missing `--output-id` is a parser error before any port is called. Optional +`--prepared-ref @` / `--record-ref @` must equal the corresponding +complete reference in the request. Optional `--scope` and `--primary-claim` +must agree with its operation/scope and selected claim. They never override +saved fields. The `@file` convention belongs to these new commands; existing +fixed-view `status`, `report`, `dashboard` and `trace` plain-path options retain +their original convention. + +Input files may be formatted JSON. Duplicate keys, non-object input, non-UTF-8, +unsafe integers, non-finite values and floating-point tokens are refused. +Decimal fields follow the existing string contract. Stored outputs and stdout +use the existing canonical result encoder. + +## Trusted local runtime configuration + +The adapter is located only by explicit `--runtime-config`; it is not discovered +from the working directory, storage configuration or saved request. It grants +existing B/H capabilities and is therefore trusted host input. It accepts no +import names, factories, credentials or request-selected authorities. +`StorageConfig` retains its existing schema and independently authorizes Apps +archive/record access. + +```json +{ + "schema_version": 1, + "benchmark": { + "protocol": "", + "worker_role": "worker-code", + "resources": { + "worker-code": "", + "input-data": "" + } + }, + "target": { + "target_id": "", + "config_revision": "", + "work_root": "", + "controller_root": "", + "target_root": null, + "module_root": "" + } +} +``` + +Only `schema_version`, `benchmark` and `target` are recognized at the top level. +The selected operation requires only its section; other sections may be absent. +All configured resource/work/source paths are absolute local paths, with no +network-path or ambient-directory fallback. Output workspace is an existing +absolute local directory without symlink traversal. + +- **prepare:** `benchmark` has exactly `protocol`, `worker_role`, `resources`. + The [existing B PreparationService](contracts/production-prepare.md) validates + the frozen task/rules and exact byte pins. Resource paths grant read-only + role-keyed file openers. Apps independently verifies the returned closure + before archiving it. No target or writable Store is constructed. +- **execute:** `target` requires `target_id`, `config_revision`, `work_root`. + `controller_root`, `target_root`, `module_root` are optional; absent/null means + unauthorized. These configure the existing H `LocalCpuTarget`. The existing + `harness_sqlite` mount selected by `StorageConfig.harness_namespace` configures + the Store. The adapter opens it for writing only when the verified Apps + binding calls H. The request cannot replace this configuration. +- **assess:** no runtime file is required or read. The existing offline B + assessor reads only fixed retained evidence through Apps; it does not prepare + a task, construct an execution target, launch a worker or access a network. + +This first adapter exposes the production task family already supported by B +on main. It does not define a worker/profile or reinterpret frozen rules. +The separate real CPU profile delivery and full three-host integration remain +tracked by the parent Apps issue. + +## Outputs, errors and replay + +Each invocation prints its complete `AppsResultV1` and returns its `exit_code`. +The existing publication writes `output//manifest.json` and +`result.json` in the authorized workspace, refusing overwrite. Consumers verify +the manifest and read fixed references; raw facts and claim verdicts remain +separate. + +| Existing result / error | Exit | +| --- | --- | +| Successful prepare/execute or archived primary `PASS` | 0 | +| Argument/config/ref conflict; other non-persistence public errors | 2 | +| Committed refusal with `process_outcome=not_started` | 3 | +| `AttemptInProgress` | 4 | +| `RecoveryRequired` | 5 | +| `ExecutionPersistenceError` / `ArchivePersistenceError`, including output publication | 6 | +| Committed failed, timed out, cancelled or nonzero worker execution | 7 | +| Archived primary `FAIL` | 8 | +| Archived primary `INCONCLUSIVE` | 9 | + +The [existing Apps result mapping](../src/inferrsi/apps/storage/result.py) +remains authoritative. Publication failures preserve already committed refs +in the printed result. Explicitly resubmitting the original saved execute +request uses the original attempt and digest; H returns its original fixed +record or its existing in-progress/recovery/conflict response. Repeating a +completed call with an already published output ID refuses output overwrite +even though H has replayed the same record. Use another explicit output ID +when publishing a separate receipt. The CLI never substitutes a new attempt, +extends the original deadline or retries a worker. + +These checks establish software behavior, not a service/performance verdict. diff --git a/docs/operations.md b/docs/operations.md index a7186fc76..daa876aa5 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -58,6 +58,7 @@ Effect classes used below: | Verify and execute one frozen source evaluation entry | Python `inferrsi.harness.api.Harness.execute` with trusted `LocalCpuTarget(module_root=...)` | Experiment-executing / record-writing | Fixed preparation and expected code digest; actual source captured after registration; T37 refusals start no worker; [source-entry contract](contracts/harness-entry-verification.md) | | Replay the same saved execution request | Python `inferrsi.harness.api.Harness.execute` | Existing-state query / fixed record-reading | Same attempt and canonical digest; existing state short-circuits fresh binding/execution; [replay and original limits](contracts/harness-evaluation-replay.md) | | Freeze a configured P1 preparation | Python `benchmark.preparation.PreparationService.prepare`; [production prepare](contracts/production-prepare.md) | Read-only resource access / pure encoding | Verifies supplied frozen worker/resource bytes and returns a preparation, protocol and role-keyed closure; Apps separately archives them before publishing a Ref | +| Evaluate saved requests | CLI `evaluate prepare/execute/assess`; [saved-request CLI](apps-evaluate-cli.md) | Local archive/output writing; execute additionally runs the configured H target | Explicit saved request, output ID, storage and trusted runtime configuration; reuses Apps ports and results without allocating attempts, selecting feedback or retrying | | Assess one fixed P1 record offline | Python `benchmark.assessment.assess`; [production assess](contracts/production-assess.md) | Read-only retained evidence / pure encoding | Verifies the frozen protocol, actual capture and proof bytes; returns independent claims without launching a worker or writing an archive; Apps selects the primary key and archives the result | | Seal host-approved generation context | Python `harness.generation.prepare_generation`; [feedback boundary](contracts/generation-feedback.md) | Local context / generation-plan retention | The trusted host authorizes feedback and excludes final-only results before handoff. H seals the supplied material; this port does not execute a worker or prove feedback-policy enforcement | | Visualize a recorded run or campaign | CLI `dashboard`; [dashboard](dashboard.md) | Report-generating / local read-only serving | Writes an offline HTML snapshot or serves an optional live view on loopback; does not run an agent or validate a claim | diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index ee5f4cd43..49dd6feeb 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -343,6 +343,10 @@ def main(argv: list[str] | None = None) -> int: argument_parser = parser() args = argument_parser.parse_args(argv) try: + if args.command == "evaluate": + from .evaluate import dispatch + + return dispatch(args) if args.command == "task": return _task_command(args) if args.command == "export": diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index 380078e7c..92628c1ab 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -205,6 +205,9 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: ) root.add_argument("--version", action="version", version=__version__) commands = root.add_subparsers(dest="command", required=True) + from .evaluate import add_parser as add_evaluate_parser + + add_evaluate_parser(commands) mindie = commands.add_parser("mindie", help="Use project-approved, local MindIE knowledge") mindie_actions = mindie.add_subparsers(dest="mindie_action", required=True) enable = mindie_actions.add_parser("enable", help="Approve a MindIE domain for this checkout") diff --git a/src/inferrsi/apps/cli/evaluate.py b/src/inferrsi/apps/cli/evaluate.py new file mode 100644 index 000000000..336b8e978 --- /dev/null +++ b/src/inferrsi/apps/cli/evaluate.py @@ -0,0 +1,179 @@ +"""Saved-request CLI over the existing Apps ports and explicit host configuration.""" + +import json +from pathlib import Path + +from ...contracts.json_v1 import encode + + +def add_parser(commands) -> None: + evaluate = commands.add_parser("evaluate", help="Prepare, execute or assess a saved request") + actions = evaluate.add_subparsers(dest="evaluate_action", required=True) + for action in ("prepare", "execute", "assess"): + command = actions.add_parser(action) + command.add_argument("--request", required=True, help="@") + command.add_argument("--output-id", required=True) + command.add_argument("--workspace", type=Path, required=True, + help="Existing absolute directory authorized for Apps output") + command.add_argument("--storage-config", type=Path, required=True) + command.add_argument("--runtime-config", type=Path, required=action != "assess", + help="Trusted local B/H configuration; separate from the request") + command.add_argument("--prepared-ref", help="@") + command.add_argument("--record-ref", help="@") + command.add_argument("--scope") + command.add_argument("--primary-claim") + + +def _object_file(path: Path) -> dict: + def unique(pairs): + value = {} + for key, item in pairs: + if key in value: + raise ValueError("Duplicate JSON object key") + value[key] = item + return value + + value = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique) + if not isinstance(value, dict): + raise ValueError("Expected a JSON object") + encode(value) + return value + + +def _request_file(value: str) -> dict: + if not value.startswith("@") or len(value) == 1: + raise ValueError("Requests and references require @") + return _object_file(Path(value[1:])) + + +def _absolute(value) -> Path: + if not isinstance(value, str) or not value or "\0" in value: + raise ValueError("Runtime paths must be explicit absolute local paths") + path = Path(value) + if not path.is_absolute() or path.anchor.startswith(("\\\\", "//")): + raise ValueError("Runtime paths must be explicit absolute local paths") + return path + + +def _runtime(path: Path) -> dict: + value = _object_file(path) + if (type(value.get("schema_version")) is not int or value["schema_version"] != 1 + or not value.keys() <= {"schema_version", "benchmark", "target"}): + raise ValueError("Unsupported evaluate runtime configuration") + return value + + +def _prepare_ports(config: dict) -> dict: + from ...benchmark import preparation + + task = config.get("benchmark") + if not isinstance(task, dict) or task.keys() != {"protocol", "worker_role", "resources"}: + raise ValueError("prepare requires a configured frozen Benchmark task") + sources = task["resources"] + if not isinstance(sources, dict) or not sources: + raise ValueError("Expected role-keyed read-only Benchmark resources") + sources = {role: _absolute(path) for role, path in sources.items()} + protocol = _object_file(_absolute(task["protocol"])) + service = preparation.PreparationService( + protocol, resources=lambda role: sources[role].open("rb"), worker_role=task["worker_role"], + ) + return {"prepare_benchmark": service.prepare, "encode_prepared": preparation.encode, + "validate_prepared": preparation.validate_prepared} + + +def _execute_ports(config: dict, storage: dict) -> dict: + from ...harness.api import Harness, LocalCpuTarget + from ...harness.run_store import RunStore + from ..storage.artifact_reader import ArtifactReader + + target = config.get("target") + required = {"target_id", "config_revision", "work_root"} + optional = {"controller_root", "target_root", "module_root"} + if not isinstance(target, dict) or not required <= target.keys() <= required | optional: + raise ValueError("execute requires a configured local CPU target") + values = dict(target) + values["work_root"] = _absolute(values["work_root"]) + for key in optional: + if key in values and values[key] is not None: + values[key] = _absolute(values[key]) + target = LocalCpuTarget(**values) + reader = ArtifactReader(storage) + mount = next((item for item in storage["mounts"] + if item["namespace"] == storage["harness_namespace"]), None) + if mount is None or mount["kind"] != "harness_sqlite": + raise ValueError("execute requires the configured Harness SQLite mount") + + def execute(spec): + # Opening a writable Store is an execution effect. Defer it until Apps + # has verified the saved request/preparation, and preserve PublicError. + harness = Harness(RunStore.from_mount(mount), target, artifact_reader=reader) + return harness.execute(spec) + + return {"execute_harness": execute} + + +def _assess_ports() -> dict: + from ...benchmark import assessment + + return {"assess_benchmark": assessment.assess, + "encode_assessment": assessment.encode, + "validate_assessment": assessment.validate_assessment} + + +def _check_options(args, request: dict, storage: dict) -> None: + for name in ("prepared_ref", "record_ref"): + option = getattr(args, name) + if option is not None and ( + name not in request or encode(_request_file(option)) != encode(request[name]) + ): + raise ValueError(f"--{name.replace('_', '-')} disagrees with the saved request") + if args.primary_claim is not None and ( + args.evaluate_action != "assess" or args.primary_claim != request.get("primary_claim_id") + ): + raise ValueError("--primary-claim disagrees with the saved request") + if args.scope is not None: + if args.evaluate_action == "prepare": + nested = request.get("request") + scope = nested.get("validation_scope") if isinstance(nested, dict) else None + elif args.evaluate_action == "assess": + scope = request.get("primary_scope") + else: + from ..storage.archive import read_prepared + + ref = request.get("prepared_ref") + if not isinstance(ref, dict): + raise ValueError("execute requires a saved PreparedRef") + scope = read_prepared(storage, ref).get("validation_scope") + if args.scope != scope: + raise ValueError("--scope disagrees with the saved request") + + +def dispatch(args) -> int: + """Print the same result as Python, including committed refs on publication failure.""" + from ...harness.errors import PublicError + from .. import api + from ..storage.archive import validate_output_id + + try: + validate_output_id(args.output_id) + workspace = _absolute(str(args.workspace)) + if not workspace.is_dir() or workspace.resolve() != workspace: + raise ValueError("--workspace requires an existing absolute authorized directory") + request = _request_file(args.request) + storage = _object_file(args.storage_config) + _check_options(args, request, storage) + if args.evaluate_action == "prepare": + ports = _prepare_ports(_runtime(args.runtime_config)) + elif args.evaluate_action == "execute": + ports = _execute_ports(_runtime(args.runtime_config), storage) + else: + # Offline assessment ignores target/worker configuration entirely. + ports = _assess_ports() + output = getattr(api, args.evaluate_action)( + request, workspace=args.workspace, storage_config=storage, + output_id=args.output_id, **ports, + ) + except PublicError as error: + raise ValueError(str(error)) from error + print(encode(output.result).decode("utf-8")) + return output.result["exit_code"] diff --git a/tests/check_installed.py b/tests/check_installed.py index 4a0ce9ad1..f53ca5ab7 100644 --- a/tests/check_installed.py +++ b/tests/check_installed.py @@ -771,6 +771,12 @@ def _inventory(root, prefix): else: raise AssertionError(f"retired module inferrsi.{a1_retired} must not import") assert main.__module__ == "inferrsi.apps.cli" +for evaluate_action in ("prepare", "execute", "assess"): + help_result = subprocess.run( + [sys.executable, "-I", "-m", "inferrsi", "evaluate", evaluate_action, "--help"], + capture_output=True, text=True, check=True, + ) + assert "--request" in help_result.stdout and "--output-id" in help_result.stdout for canonical in ("inferrsi.apps.views.summary_chart", "inferrsi.apps.workflows.benchmark_operations", "inferrsi.apps.integrations.mindie.project", diff --git a/tests/test_apps_evaluate_cli.py b/tests/test_apps_evaluate_cli.py new file mode 100644 index 000000000..c53ff7a4f --- /dev/null +++ b/tests/test_apps_evaluate_cli.py @@ -0,0 +1,322 @@ +"""Saved requests reach production ports, with CLI-only checks before effects.""" + +import json +import os +import sqlite3 +import subprocess +import sys +from copy import deepcopy +from dataclasses import asdict +from pathlib import Path + +import pytest + +from inferrsi.apps.cli import evaluate as cli +from inferrsi.apps.cli import main +from inferrsi.apps.storage import archive +from inferrsi.apps.storage.archive import read_result +from inferrsi.contracts.json_v1 import decode, encode +from inferrsi.harness import execution_service, run_store +from tests.test_benchmark_assessment import remove +from tests.test_benchmark_assessment import retained as retained +from tests.test_benchmark_preparation import preparation as preparation +from tests.test_harness_entry_verification import evaluation as evaluation + + +def save(tmp_path, name, value): + path = tmp_path / name + # Human-readable inputs are allowed; persisted outputs remain canonical. + path.write_text(json.dumps(value, indent=2), encoding="utf-8") + return path + + +def arguments(tmp_path, action, request, config, runtime=None, output="call"): + values = ["evaluate", action, "--request", "@" + str(save(tmp_path, "request.json", request)), + "--storage-config", str(save(tmp_path, "storage.json", config)), + "--workspace", str(tmp_path), "--output-id", output] + if runtime is not None: + values += ["--runtime-config", str(save(tmp_path, "runtime.json", runtime))] + return values + + +def execute_request(case): + spec = case["spec"] + proposal = {key: deepcopy(spec[key]) for key in ("candidate", "generation_record_ref")} + proposal["inputs"] = [deepcopy(item) for item in spec["inputs"] + if item["role"] == spec["candidate"]["input_role"]] + return {"schema_version": 1, "prepared_ref": spec["prepared_ref"], + "attempt": {key: deepcopy(spec[key]) for key in execution_service.ATTEMPT_FIELDS}, + "proposal": proposal, + "output_root": spec["output_root"]} + + +def target_config(case): + values = asdict(case["target"]) + return {"schema_version": 1, "target": { + key: str(value) if isinstance(value, Path) else value for key, value in values.items() + }} + + +def storage_config(case): + # The entry-verification fixture already creates its archive beside the Store. + root = case["store"].root.parent + return {"schema_version": 1, "archive_namespace": "apps", "harness_namespace": "test", + "mounts": [{"prefix": "archives/local", "namespace": "apps", + "root": str(root / "archive"), "kind": "directory"}, + {"prefix": "stores/test", "namespace": "test", + "root": str(case["store"].root), "kind": "harness_sqlite"}]} + + +def test_prepare_uses_real_benchmark_and_publishes_standard_output(preparation, tmp_path, capsys): + _, request, sources, protocol, _, config, _ = preparation + runtime = {"schema_version": 1, "benchmark": { + "protocol": str(save(tmp_path, "protocol.json", protocol)), "worker_role": "worker-code", + "resources": {role: str(path) for role, path in sources.items()}, + }} + command = arguments(tmp_path, "prepare", {"schema_version": 1, "request": request}, + config, runtime) + assert main(command + ["--scope", "p1"]) == 0 + result = json.loads(capsys.readouterr().out) + assert result == read_result(tmp_path, "call").result + assert result["prepared_ref"] is not None + assert not (tmp_path / "store").exists() + manifest = decode((tmp_path / "output/call/manifest.json").read_bytes()) + assert manifest["result"]["size_bytes"] == len(encode(result)) + + +def test_execute_and_cross_process_replay_keep_original_attempt(evaluation, tmp_path, capsys, + monkeypatch): + case = evaluation + request, config, runtime = execute_request(case), storage_config(case), target_config(case) + command = arguments(tmp_path, "execute", request, config, runtime) + ref_file = save(tmp_path, "prepared-ref.json", request["prepared_ref"]) + assert main(command + ["--prepared-ref", "@" + str(ref_file), "--scope", "p1"]) == 0 + original = json.loads(capsys.readouterr().out) + assert original["execution"]["started"] is True + assert original["record_ref"] == read_result(tmp_path, "call").result["record_ref"] + (case["modules"] / "fixture_worker.py").unlink() + runtime["target"].update(target_id="retired", config_revision="2", module_root=None) + command = arguments(tmp_path, "execute", request, config, runtime, output="replay") + env = {**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[1] / "src")} + child = subprocess.run([sys.executable, "-m", "inferrsi", *command], cwd=tmp_path, + env=env, capture_output=True, text=True, timeout=30) + assert child.returncode == 0, child.stderr + replay = json.loads(child.stdout) + assert replay["record_ref"] == original["record_ref"] + assert request == execute_request(case) + with sqlite3.connect(case["store"].root / run_store.INDEX_NAME) as conn: + assert conn.execute("SELECT count(*) FROM attempts").fetchone()[0] == 1 + assert conn.execute("SELECT count(*) FROM records").fetchone()[0] == 1 + + +@pytest.mark.parametrize(("claim", "code"), [("F", 0), ("C", 8), ("M", 9)]) +def test_assess_offline_claim_exits_preserve_all_claims(retained, tmp_path, capsys, monkeypatch, + claim, code): + remove(retained, "grader", "samples", "cleanup") + retained["add"]("grader", "failed") + ref, _ = retained["seal"]() + request = {"schema_version": 1, "record_ref": ref, + "primary_scope": "p1", "primary_claim_id": claim} + + def never(*args): + pytest.fail("offline assessment constructed an execution/prepare runtime") + + monkeypatch.setattr(cli, "_execute_ports", never) + monkeypatch.setattr(cli, "_prepare_ports", never) + command = arguments(tmp_path, "assess", request, retained["config"]) + command += ["--runtime-config", str(tmp_path / "absent-runtime.json"), + "--record-ref", "@" + str(save(tmp_path, "ref.json", ref)), + "--scope", "p1", "--primary-claim", claim] + assert main(command) == code + result = json.loads(capsys.readouterr().out) + assert result["assessment_ref"] is not None + assert result == read_result(tmp_path, "call").result + assert [row["verdict"] for row in result["assessment"]["claims"]] == [ + "PASS", "FAIL", "INCONCLUSIVE", + ] + + +@pytest.mark.parametrize("option", ["--output-id", "--request", "--workspace", "--storage-config", + "--runtime-config"]) +def test_missing_cli_arguments_never_reach_a_port(tmp_path, monkeypatch, option): + monkeypatch.setattr(cli, "dispatch", lambda args: pytest.fail("parser invoked a port")) + command = arguments(tmp_path, "execute", {}, {}, {"schema_version": 1}) + index = command.index(option) + del command[index:index + 2] + with pytest.raises(SystemExit) as error: + main(command) + assert error.value.code == 2 + assert not (tmp_path / "output").exists() + + +@pytest.mark.parametrize("extra", [ + ["--scope", "foreign"], ["--primary-claim", "foreign"], + ["--prepared-ref", "@foreign.json"], ["--record-ref", "@foreign.json"], +]) +def test_conflicting_options_fail_before_configuration_or_effects(retained, tmp_path, monkeypatch, + extra): + ref, _ = retained["seal"]() + request = {"schema_version": 1, "record_ref": ref, + "primary_scope": "p1", "primary_claim_id": "F"} + monkeypatch.setattr(cli, "_assess_ports", lambda: pytest.fail("configured a port")) + command = arguments(tmp_path, "assess", request, retained["config"]) + with pytest.raises(SystemExit) as error: + main(command + extra) + assert error.value.code == 2 + assert not (tmp_path / "output/call").exists() + + +@pytest.mark.parametrize("bad", [b'{"schema_version":1,"schema_version":1}', b'[]', b'{"x":NaN}', + b'{"x":1.5}', b'{"x":9007199254740992}', b'\xff']) +def test_malformed_saved_json_is_refused_before_ports(tmp_path, monkeypatch, bad): + command = arguments(tmp_path, "assess", {}, {}) + (tmp_path / "request.json").write_bytes(bad) + monkeypatch.setattr(cli, "_assess_ports", lambda: pytest.fail("configured a port")) + with pytest.raises(SystemExit) as error: + main(command) + assert error.value.code == 2 + + +def test_publication_failure_keeps_committed_execution_reference(evaluation, tmp_path, capsys, + monkeypatch): + case = evaluation + command = arguments(tmp_path, "execute", execute_request(case), storage_config(case), + target_config(case)) + original = archive._publish_directory + + def fail(source, target): + if target.name == "call": + raise OSError("controlled output publication failure") + return original(source, target) + + monkeypatch.setattr(archive, "_publish_directory", fail) + assert main(command) == 6 + result = json.loads(capsys.readouterr().out) + assert result["record_ref"] == case["store"].read(result["attempt_id"])["record_ref"] + assert result["execution"]["started"] is True + assert not (tmp_path / "output/call").exists() + monkeypatch.setattr(archive, "_publish_directory", original) + assert main(command) == 0 + replay = json.loads(capsys.readouterr().out) + assert replay["record_ref"] == result["record_ref"] + with sqlite3.connect(case["store"].root / run_store.INDEX_NAME) as conn: + assert conn.execute("SELECT count(*) FROM attempts").fetchone()[0] == 1 + assert conn.execute("SELECT count(*) FROM records").fetchone()[0] == 1 + + +@pytest.mark.parametrize("path", ["relative/path", "//remote/share/path", "", None]) +def test_runtime_never_infers_local_authority(tmp_path, path): + runtime = {"schema_version": 1, "benchmark": { + "protocol": path, "worker_role": "worker-code", "resources": {"code": path}, + }} + command = arguments(tmp_path, "prepare", {"schema_version": 1, "request": {}}, {}, runtime) + with pytest.raises(SystemExit) as error: + main(command) + assert error.value.code == 2 + assert not (tmp_path / "store").exists() + + +def test_parser_and_unrelated_commands_do_not_load_new_ports(tmp_path): + script = """ +import sys +from inferrsi.apps.cli.arguments import parser +parser() +assert not any(name in sys.modules for name in ( + 'inferrsi.apps.api', 'inferrsi.harness.api', 'inferrsi.harness.run_store', + 'inferrsi.benchmark.preparation', 'inferrsi.benchmark.assessment')) +""" + child = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, + timeout=30) + assert child.returncode == 0, child.stderr + + +@pytest.mark.parametrize("change", ["version", "unknown", "null-root", "relative-root"]) +def test_invalid_runtime_does_not_open_a_writable_store(evaluation, tmp_path, change): + case = evaluation + config = storage_config(case) + config["mounts"][1]["root"] = str(tmp_path / "never-opened-store") + runtime = target_config(case) + if change == "version": + runtime["schema_version"] = True + elif change == "unknown": + runtime["import"] = "untrusted_module" + else: + runtime["target"]["work_root"] = None if change == "null-root" else "relative" + command = arguments(tmp_path, "execute", execute_request(case), config, runtime) + with pytest.raises(SystemExit) as error: + main(command) + assert error.value.code == 2 + assert not (tmp_path / "never-opened-store").exists() + + +def test_changed_saved_attempt_digest_is_a_persisted_conflict(evaluation, tmp_path, capsys): + case = evaluation + request, config, runtime = execute_request(case), storage_config(case), target_config(case) + assert main(arguments(tmp_path, "execute", request, config, runtime)) == 0 + first = json.loads(capsys.readouterr().out) + request["attempt"]["deadline_utc"] = "2098-01-01T00:00:00Z" + assert main(arguments(tmp_path, "execute", request, config, runtime, output="conflict")) == 2 + result = json.loads(capsys.readouterr().out) + assert result["reason_code"] == "RequestConflict" + assert result["error"]["stage"] == "claim" + assert result == read_result(tmp_path, "conflict").result + assert case["store"].read(first["attempt_id"])["record_ref"] == first["record_ref"] + + +def test_request_tag_is_required_before_runtime_configuration(tmp_path, monkeypatch): + command = arguments(tmp_path, "assess", {}, {}) + index = command.index("--request") + 1 + command[index] = command[index].removeprefix("@") + monkeypatch.setattr(cli, "_assess_ports", lambda: pytest.fail("configured a port")) + with pytest.raises(SystemExit) as error: + main(command) + assert error.value.code == 2 + + +@pytest.mark.parametrize("field", ["runtime_config", "storage_config", "target", "import"]) +def test_request_cannot_supply_runtime_authority(evaluation, tmp_path, capsys, monkeypatch, field): + case = evaluation + request, config, runtime = execute_request(case), storage_config(case), target_config(case) + config["mounts"][1]["root"] = str(tmp_path / "unopened-store") + request[field] = {"work_root": str(tmp_path / "request-selected-root"), + "module_root": str(tmp_path / "request-selected-modules")} + configured = [] + original = cli._execute_ports + + def observe(trusted, storage): + configured.append(deepcopy(trusted)) + return original(trusted, storage) + + monkeypatch.setattr(cli, "_execute_ports", observe) + command = arguments(tmp_path, "execute", request, config, runtime) + assert main(command) == 2 + result = json.loads(capsys.readouterr().out) + assert result["reason_code"] == "InvalidRequest" + assert configured == [runtime] + assert not (tmp_path / "unopened-store").exists() + assert not (tmp_path / "request-selected-root").exists() + assert not (tmp_path / "request-selected-modules").exists() + + +def test_entry_refusal_is_a_committed_exit_three(evaluation, tmp_path, capsys): + case = evaluation + (case["modules"] / "fixture_worker.py").write_bytes(b"raise RuntimeError('changed code')\n") + command = arguments(tmp_path, "execute", execute_request(case), storage_config(case), + target_config(case)) + assert main(command) == 3 + result = json.loads(capsys.readouterr().out) + assert result["execution"]["started"] is False + assert result["execution"]["process_outcome"] == "not_started" + assert result["record_ref"] is not None + + +@pytest.mark.parametrize("evaluation", [{"worker_code": b"raise SystemExit(3)\n"}], indirect=True) +def test_recorded_worker_failure_returns_exit_seven(evaluation, tmp_path, capsys): + case = evaluation + command = arguments(tmp_path, "execute", execute_request(case), storage_config(case), + target_config(case)) + assert main(command) == 7 + result = json.loads(capsys.readouterr().out) + assert result["execution"]["started"] is True + assert result["execution"]["exit_code"] == 3 + assert result["record_ref"] is not None From dcc22904f13b09ce7be0e51f73ca16de0db50909 Mon Sep 17 00:00:00 2001 From: zengchuang Date: Mon, 23 Nov 2026 11:10:17 +0800 Subject: [PATCH 2/4] test(apps): verify malformed CLI storage and clarify command help Agent-assisted-by: Codex (author/integrator) Signed-off-by: zengchuang --- docs/apps-evaluate-cli.md | 4 ++++ src/inferrsi/apps/cli/evaluate.py | 9 +++++++-- tests/test_apps_evaluate_cli.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/docs/apps-evaluate-cli.md b/docs/apps-evaluate-cli.md index 7e73d3794..d188117ef 100644 --- a/docs/apps-evaluate-cli.md +++ b/docs/apps-evaluate-cli.md @@ -24,11 +24,15 @@ must agree with its operation/scope and selected claim. They never override saved fields. The `@file` convention belongs to these new commands; existing fixed-view `status`, `report`, `dashboard` and `trace` plain-path options retain their original convention. +Checking `execute --scope` reads its fixed prepared archive before execution; +an unavailable or invalid archive fails that read-only agreement check. Input files may be formatted JSON. Duplicate keys, non-object input, non-UTF-8, unsafe integers, non-finite values and floating-point tokens are refused. Decimal fields follow the existing string contract. Stored outputs and stdout use the existing canonical result encoder. +Stdout appends a line ending after that JSON value; manifest hashes and byte +comparisons apply to the canonical `result.json` bytes without that line ending. ## Trusted local runtime configuration diff --git a/src/inferrsi/apps/cli/evaluate.py b/src/inferrsi/apps/cli/evaluate.py index 336b8e978..14bd4d5e1 100644 --- a/src/inferrsi/apps/cli/evaluate.py +++ b/src/inferrsi/apps/cli/evaluate.py @@ -9,8 +9,13 @@ def add_parser(commands) -> None: evaluate = commands.add_parser("evaluate", help="Prepare, execute or assess a saved request") actions = evaluate.add_subparsers(dest="evaluate_action", required=True) - for action in ("prepare", "execute", "assess"): - command = actions.add_parser(action) + descriptions = { + "prepare": "Freeze and archive the configured evaluation task", + "execute": "Execute or replay the original saved attempt", + "assess": "Assess a fixed record using retained evidence only", + } + for action, description in descriptions.items(): + command = actions.add_parser(action, help=description, description=description) command.add_argument("--request", required=True, help="@") command.add_argument("--output-id", required=True) command.add_argument("--workspace", type=Path, required=True, diff --git a/tests/test_apps_evaluate_cli.py b/tests/test_apps_evaluate_cli.py index c53ff7a4f..9c656b573 100644 --- a/tests/test_apps_evaluate_cli.py +++ b/tests/test_apps_evaluate_cli.py @@ -320,3 +320,31 @@ def test_recorded_worker_failure_returns_exit_seven(evaluation, tmp_path, capsys assert result["execution"]["started"] is True assert result["execution"]["exit_code"] == 3 assert result["record_ref"] is not None + + +@pytest.mark.parametrize("fault", ["missing", "null-mounts", "missing-namespace", + "list-namespace", "directory-store"]) +def test_malformed_storage_is_exit_two_before_store_open(evaluation, tmp_path, monkeypatch, + fault, capsys): + case = evaluation + config = storage_config(case) + if fault == "missing": + config = {} + elif fault == "null-mounts": + config["mounts"] = None + elif fault == "missing-namespace": + del config["mounts"][1]["namespace"] + elif fault == "list-namespace": + config["harness_namespace"] = [] + else: + config["mounts"][1]["kind"] = "directory" + + def forbidden(*args, **kwargs): + pytest.fail("malformed storage reached a writable Store") + + monkeypatch.setattr(run_store.RunStore, "from_mount", forbidden) + command = arguments(tmp_path, "execute", execute_request(case), config, target_config(case)) + with pytest.raises(SystemExit) as error: + main(command) + assert error.value.code == 2 + assert "Traceback" not in capsys.readouterr().err From 013ab8c1ebd7d0596f0fb947957d9681ce8edd5a Mon Sep 17 00:00:00 2001 From: zengchuang Date: Mon, 23 Nov 2026 11:30:46 +0800 Subject: [PATCH 3/4] fix(apps): register canonical evaluation CLI consumers Agent-assisted-by: Codex (author/integrator) Signed-off-by: zengchuang --- docs/apps-module-migrations.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index 73408ddc9..eebba4ad2 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -22,6 +22,7 @@ "docs/operations.md", "src/inferrsi/apps/api.py", "src/inferrsi/apps/archive.py", + "src/inferrsi/apps/cli/evaluate.py", "src/inferrsi/apps/delivery/__init__.py", "src/inferrsi/apps/handoff/bridge.py", "src/inferrsi/apps/handoff/candidate_provider.py", @@ -30,6 +31,7 @@ "src/inferrsi/apps/workflows/benchmark_compare.py", "tests/check_installed.py", "tests/test_apps_assess.py", + "tests/test_apps_evaluate_cli.py", "tests/test_apps_module_migrations.py", "tests/test_apps_output.py", "tests/test_apps_port_validation.py", @@ -56,6 +58,7 @@ "docs/operations.md", "src/inferrsi/apps/api.py", "src/inferrsi/apps/artifact_reader.py", + "src/inferrsi/apps/cli/evaluate.py", "src/inferrsi/apps/handoff/candidate_provider.py", "src/inferrsi/apps/views/attempt.py", "tests/check_installed.py", From 712551b71aaf4c050770ad3c0a6ce09ba54971e5 Mon Sep 17 00:00:00 2001 From: zengchuang Date: Mon, 23 Nov 2026 12:35:13 +0800 Subject: [PATCH 4/4] fix(apps): refuse excessively nested CLI JSON as invalid input Convert recursion failures from saved JSON parsing and canonical validation into the existing CLI input-error path before port construction. Add a regression for the reported unhandled traceback. Agent-assisted-by: Codex (author/integrator) Signed-off-by: zengchuang --- src/inferrsi/apps/cli/evaluate.py | 11 +++++++---- tests/test_apps_evaluate_cli.py | 7 +++++-- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/inferrsi/apps/cli/evaluate.py b/src/inferrsi/apps/cli/evaluate.py index 14bd4d5e1..86b36dbcb 100644 --- a/src/inferrsi/apps/cli/evaluate.py +++ b/src/inferrsi/apps/cli/evaluate.py @@ -38,10 +38,13 @@ def unique(pairs): value[key] = item return value - value = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique) - if not isinstance(value, dict): - raise ValueError("Expected a JSON object") - encode(value) + try: + value = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique) + if not isinstance(value, dict): + raise ValueError("Expected a JSON object") + encode(value) + except RecursionError as error: + raise ValueError("JSON input nesting is too deep") from error return value diff --git a/tests/test_apps_evaluate_cli.py b/tests/test_apps_evaluate_cli.py index 9c656b573..2f7a5937a 100644 --- a/tests/test_apps_evaluate_cli.py +++ b/tests/test_apps_evaluate_cli.py @@ -167,14 +167,17 @@ def test_conflicting_options_fail_before_configuration_or_effects(retained, tmp_ @pytest.mark.parametrize("bad", [b'{"schema_version":1,"schema_version":1}', b'[]', b'{"x":NaN}', - b'{"x":1.5}', b'{"x":9007199254740992}', b'\xff']) -def test_malformed_saved_json_is_refused_before_ports(tmp_path, monkeypatch, bad): + b'{"x":1.5}', b'{"x":9007199254740992}', b'\xff', + pytest.param(b'{"x":' + b'[' * 2000 + b'0' + b']' * 2000 + b'}', + id="excessive-nesting")]) +def test_malformed_saved_json_is_refused_before_ports(tmp_path, monkeypatch, capsys, bad): command = arguments(tmp_path, "assess", {}, {}) (tmp_path / "request.json").write_bytes(bad) monkeypatch.setattr(cli, "_assess_ports", lambda: pytest.fail("configured a port")) with pytest.raises(SystemExit) as error: main(command) assert error.value.code == 2 + assert "Traceback" not in capsys.readouterr().err def test_publication_failure_keeps_committed_execution_reference(evaluation, tmp_path, capsys,