From 2be157a259042bb26f6079fb449ccb8104fdeffc Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:22:45 +0800 Subject: [PATCH 1/6] Accept a YAML task file in inferrsi plan and run with --task plan and run now take --task , which reads the shared schema v1 task contract. Their value options record each flag the caller supplied, so only supplied mapped flags override the file. Parser defaults such as --backend cpu keep flag-only invocations unchanged but never replace a YAML value. Acceptance flags must equal the file, using the existing merge conflict rule. Field errors and blockers print by field to stderr and exit 2 before any environment probe, task command or file write. A complete task is copied onto the existing arguments, and RunSpec is built through the existing make_spec path. make_spec now accepts normalized argv lists. plan and run --dry-run add a task block equal to task preview --json for the same file and flags. run first requires that a local acceptance.reference exists, before the probe. After inspection it requires that the baseline checkout HEAD matches acceptance.baseline_revision (a 7+ character hex prefix is accepted). It then writes task.json next to args.json. Without --task, --baseline-command and --candidate-command stay required with the same argparse error. Adds tests/test_task_plan_run.py on the shared complete and partial fixtures, and documents the plan/run use in docs/task-input.md and docs/operations.md. Agent-assisted-by: Claude Code / claude-opus-5-5 [effort=xhigh] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/operations.md | 15 +- docs/task-input.md | 66 ++++- src/inferrsi/apps/cli/__init__.py | 99 ++++++- src/inferrsi/apps/cli/arguments.py | 57 +++- src/inferrsi/apps/cli/task_input.py | 41 +++ tests/fixtures/task-input/README.md | 6 +- tests/test_task_plan_run.py | 389 ++++++++++++++++++++++++++++ 7 files changed, 644 insertions(+), 29 deletions(-) create mode 100644 tests/test_task_plan_run.py diff --git a/docs/operations.md b/docs/operations.md index 1db7ef029..fe1bbc5aa 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -408,15 +408,16 @@ delivery and generation handoff. The API still exports the one canonical Explicit flags override YAML values, YAML values override built-in defaults, and an omitted flag never replaces a YAML value. Acceptance fields come from the file. See -[task input](task-input.md). Using a task file with `plan` and `run` is not implemented yet. +[task input](task-input.md). `plan --task` and `run --task` use a complete file with +the same merge (see [use with plan and run](task-input.md#use-with-plan-and-run)). ### Inspect/prepare — `doctor`, `plan`, `--dry-run` -- **Inputs:** repository/backend/device flags; `plan` takes the full experiment specification. +- **Inputs:** repository/backend/device flags; `plan` takes the full experiment specification as flags, or a complete YAML task file with `--task ` plus explicit mapped overrides. - **Scope:** environment inspection and specification preview. -- **Output:** environment facts, or a preview of the RunSpec. +- **Output:** environment facts, or a preview of the RunSpec. With `--task`, the preview adds a `task` block equal to `task preview --json` for the same file and flags. - **Side effects:** `doctor` may invoke bounded read-only probes; `plan`/`--dry-run` persist nothing. -- **Failure behavior:** unavailable devices or invalid flags are reported explicitly. +- **Failure behavior:** unavailable devices or invalid flags are reported explicitly. With `--task`, task field errors, conflicting acceptance flags and blockers are printed by field to stderr, exit 2, before any probe. Without `--task`, `--baseline-command` and `--candidate-command` are required. - **Example:** `inferrsi doctor --repo . --repo-type vllm_omni --backend cpu` `plan` previews a specification. That preview alone does not persist a frozen @@ -425,11 +426,11 @@ compatibility. ### Execute/inspect — `run`, `status`, `report` -- **Inputs:** the full experiment specification (`run`); a run ID and output directory (`status`/`report`). +- **Inputs:** the full experiment specification as flags or as a complete `--task ` (`run`); a run ID and output directory (`status`/`report`). - **Scope:** caller-supplied benchmark, candidate and validation commands under the experiment contract. -- **Output:** a run ID and evidence directory; recorded progress; an HTML report. +- **Output:** a run ID and evidence directory; recorded progress; an HTML report. With `--task`, the run directory also holds `task.json`, the task preview. - **Side effects:** `run` executes the supplied commands and owns child-process cleanup; `report` writes HTML into the run directory. -- **Failure behavior:** exit codes 0 PASS, 1 FAIL, 2 INCONCLUSIVE/input errors; cancellation is recorded. +- **Failure behavior:** exit codes 0 PASS, 1 FAIL, 2 INCONCLUSIVE/input errors; cancellation is recorded. With `--task`, task field errors and blockers exit 2 before any probe. A missing local `acceptance.reference` file also exits 2 before any probe. A baseline checkout `HEAD` that differs from `acceptance.baseline_revision` exits 2 after inspection. In all three cases no command starts and nothing is written. - **Example:** see [quickstart: real remote experiment](quickstart.md#real-remote-experiment) Operation success, recorded execution state and the experiment verdict are diff --git a/docs/task-input.md b/docs/task-input.md index 5468c2120..8e892bc41 100644 --- a/docs/task-input.md +++ b/docs/task-input.md @@ -5,10 +5,10 @@ file from the CLI or hand it to an Agent. Both entry points read it through one shared contract, `inferrsi.apps.cli.task_input`, so the same file gives the same normalized task fields either way. -`inferrsi task validate` and `inferrsi task preview` are available now. They are -read-only. Using a complete task file directly with `inferrsi plan --task` and -`inferrsi run --task` is not implemented yet. Until it is, pass the previewed values -to `plan` and `run` as their existing flags (see the [field table](#fields)). +`inferrsi task validate` and `inferrsi task preview` check a draft or complete file +without side effects. `inferrsi plan --task` and `inferrsi run --task` use a complete +file with the existing plan and run operations (see +[use with plan and run](#use-with-plan-and-run)). | Resource | Location | Print from an installed CLI | | --- | --- | --- | @@ -88,8 +88,8 @@ not invent them. ## Merge order -`task preview` accepts the mapped flags from the table as overrides. The effective -value of each field is: +`task preview`, `plan --task` and `run --task` accept the mapped flags from the table +as overrides. The effective value of each field is: 1. an explicit CLI flag, then 2. the YAML value, then @@ -142,6 +142,54 @@ is present. It does not authorize execution. Running an experiment still require explicit `run` under the existing acceptance, frozen-gate and evidence rules (see [operations](operations.md#validatepreview-a-task-file--task-validate-task-preview)). +## Use with plan and run + +`plan` and `run` take a complete task file with `--task`: + +```bash +inferrsi plan --task task.yaml # preview the RunSpec and the task +inferrsi plan --task task.yaml --repetitions 7 # explicit override +inferrsi run --task task.yaml # explicit execution +``` + +- **Merge order.** `--task` uses the [merge order](#merge-order) of `task preview`. + `plan` and `run` keep their parser defaults, such as `--backend cpu` and + `--repetitions 3`, for flag-only use. In task mode only the mapped flags you supply + are overrides, and a supplied flag wins even when its value equals the parser + default. An acceptance flag must equal the file's value. Flags with no task field, + such as `--agent`, `--output-dir` and `--dry-run`, keep their existing meaning. +- **Field errors first.** `plan` and `run` need a valid, complete task. Errors and + blockers print to stderr, one line per field, for example + `error acceptance.metric_key (cli): ...` or + `blocker environment.repetitions: missing; required for plan/run`. The command + then exits with 2 before any environment probe, task command or file write. +- **Defaults for omitted optional fields.** An omitted `environment.python` uses the + interpreter running InferRSI. An omitted `optimization.candidate_repository` uses + the baseline checkout. An omitted `environment.quality_command` leaves the run + without quality evidence, which gives the existing `INCONCLUSIVE` outcome. +- **`plan` and `run --dry-run`.** They inspect the environment and print the RunSpec + built from the task, as in flag-only use. Their output adds a `task` block, the + same object that `task preview --json` prints for the same file and flags. Without + `--task` the output is unchanged. +- **`run`.** Execution checks that the task agrees with its accepted inputs. + Each check fails with exit 2 before any benchmark command starts or any run + directory is written. + - A local `acceptance.reference` must be an existing file. InferRSI checks this + before the environment probe. An HTTP(S) issue URL is recorded as written. + - After inspection, the baseline checkout's `HEAD` must equal + `acceptance.baseline_revision`. A hexadecimal prefix of at least 7 characters is + also accepted. + + The run directory then holds `task.json`, the task preview, next to `args.json`. + `args.json` records the effective values and the absolute `task_file`. + +RunSpec carries the experiment fields. `optimization.objective`, +`optimization.plane`, `environment.rounds`, `acceptance.reference`, +`acceptance.baseline_revision` and `acceptance.constraints` have no RunSpec field. +They are recorded in the `task` block and in `task.json`. Without `--task`, +`--baseline-command` and `--candidate-command` remain required, with the same +argparse error and exit 2. + ## CLI workflow ```bash @@ -191,11 +239,15 @@ An Agent uses the same installed CLI and the same machine-readable preview: 4. Review the effective values, their sources and the remaining blockers with the user. Ask for the blocking fields instead of guessing them. 5. Use the reviewed task with the existing InferRSI operation the user authorizes, - under the operation's own boundary in [operations](operations.md). + under the operation's own boundary in [operations](operations.md). For example, + run `inferrsi plan --task `, then `inferrsi run --task ` + only after explicit authorization. The CLI and the Agent produce the same normalized task for the same file and flags. `tests/test_task_input.py` checks this by comparing `inferrsi task preview --json` with the Python `task_input.preview` on the shared complete fixture. +`tests/test_task_plan_run.py` checks that `plan --task` gives the same `task` block, +and the expected RunSpec, for that fixture. ## Compatibility with other task formats diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index ee5f4cd43..51e7f9d1c 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -3,6 +3,8 @@ from __future__ import annotations import json +import os +import re import sqlite3 import sys from importlib.resources import files @@ -16,7 +18,7 @@ from ..knowledge import read as read_knowledge from ..legacy.reporting import write_report from ..workflows.campaign import capture_context, create_campaign -from .arguments import device_ids, make_spec, parser +from .arguments import SUPPLIED, command_parser, device_ids, make_spec, parser def _print(value: object) -> None: @@ -339,9 +341,79 @@ def _task_command(args) -> int: return 0 if result["valid"] else 1 +_REQUIRED_COMMANDS = (("--baseline-command", "baseline_command"), + ("--candidate-command", "candidate_command")) + + +def _plan_run_task(command, args, supplied) -> dict | None: + """Apply ``--task`` to plan/run args before any probe; return its preview or None. + + Without ``--task`` the two commands stay required, with argparse's own message. With + it, field errors and blockers exit 2 here, before inspection, commands or writes. + """ + task_file = getattr(args, "task_file", None) + if task_file is None: + missing = [flag for flag, dest in _REQUIRED_COMMANDS if getattr(args, dest) is None] + if missing: + command.error("the following arguments are required: " + ", ".join(missing)) + return None + from . import task_input + + result = task_input.preview( + task_file, task_input.supplied_overrides(args, supplied), cwd=os.getcwd() + ) + if result["errors"] or result["blockers"]: + lines = [f"task file {result['task_file']} is not ready for {args.command}:"] + lines += [f"error {item['field']} ({item['source']}): {item['message']}" + for item in result["errors"]] + lines += [f"blocker {item['field']}: {item['message']}" for item in result["blockers"]] + command.error("\n".join(lines)) + for dest, value in task_input.arguments_from(result["task"]).items(): + setattr(args, dest, value) + if args.python is None: + args.python = sys.executable + args.task_file = result["task_file"] + return result + + +def _revision_matches(head: str, revision: str) -> bool: + if head == revision: + return True + return bool(head) and re.fullmatch(r"[0-9a-fA-F]{7,}", revision) is not None and ( + head.lower().startswith(revision.lower()) + ) + + +def _check_task_reference(task: dict) -> None: + """Require a run's local acceptance plan to exist; an HTTP(S) URL is kept verbatim.""" + from .task_input import is_url + + reference = task["task"]["acceptance"]["reference"] + if not is_url(reference) and not os.path.isfile(reference): + raise ValueError( + "acceptance.reference must be an existing local plan file or an HTTP(S) " + f"issue URL: {reference}" + ) + + +def _check_baseline_revision(task: dict, environment: dict) -> None: + """Require the inspected baseline checkout to be the accepted baseline revision.""" + revision = task["task"]["acceptance"]["baseline_revision"] + head = environment["repository"].get("head", "") + if not _revision_matches(head, revision): + raise ValueError( + f"acceptance.baseline_revision {revision!r} does not match the baseline " + f"checkout HEAD {head}; check out the accepted baseline or fix the task file" + ) + + def main(argv: list[str] | None = None) -> int: argument_parser = parser() args = argument_parser.parse_args(argv) + task = None + if args.command in ("plan", "run"): + supplied = vars(args).pop(SUPPLIED, ()) + task = _plan_run_task(command_parser(argument_parser, args.command), args, supplied) try: if args.command == "task": return _task_command(args) @@ -771,6 +843,8 @@ def main(argv: list[str] | None = None) -> int: _print({"record": str(path)}) return 0 + if task is not None and args.command == "run" and not args.dry_run: + _check_task_reference(task) environment = inspect_environment( args.repo, args.repo_type, @@ -791,14 +865,15 @@ def main(argv: list[str] | None = None) -> int: spec = make_spec(args) if args.command == "plan" or args.dry_run: - _print( - { - "run_spec": spec.to_dict(), - "environment": environment, - "execution": "not started", - "validation": "unverified", - } - ) + preview = { + "run_spec": spec.to_dict(), + "environment": environment, + "execution": "not started", + "validation": "unverified", + } + if task is not None: + preview["task"] = task + _print(preview) return 0 if not environment["repository"].get("available"): raise ValueError("The baseline must be a readable Git checkout for source provenance") @@ -808,6 +883,8 @@ def main(argv: list[str] | None = None) -> int: raise ValueError("Requested device selection is not verified by platform discovery") if not environment["target_python"].get("environment"): raise ValueError("Target Python inspection failed") + if task is not None: + _check_baseline_revision(task, environment) # The old run loads its Benchmark gates. Import it here so that the # other commands, including ordinary optimization, never load Benchmark. @@ -817,6 +894,10 @@ def main(argv: list[str] | None = None) -> int: (directory / "args.json").write_text( json.dumps(vars(args), ensure_ascii=False, indent=2) + "\n", encoding="utf-8" ) + if task is not None: + (directory / "task.json").write_text( + json.dumps(task, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) write_report(directory) status = json.loads((directory / "status.json").read_text(encoding="utf-8")) _print( diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index 380078e7c..815456cb1 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -3,6 +3,12 @@ ``task validate`` and ``task preview`` read a schema v1 task file (``task_input``). Preview accepts the mapped plan/run flags as explicit overrides; only flags the caller supplies reach its namespace, so a parser default never replaces a YAML value. + +``plan`` and ``run`` keep their flag defaults and also accept ``--task``. Their value +options record each dest the caller supplied in the namespace tuple ``_supplied``, so +task mode passes only those flags as overrides. ``--baseline-command`` and +``--candidate-command`` are required without ``--task``; ``main`` enforces that, because +a complete task file may supply them instead. """ from __future__ import annotations @@ -52,6 +58,35 @@ def _fixed_attempt_args( parser.add_argument("--assessment-ref", type=Path, help="Optional AssessmentRef JSON") +SUPPLIED = "_supplied" + + +class _Supplied: + """Store as usual and record the dest, telling an explicit flag from its default.""" + + def __call__(self, parser, namespace, values, option_string=None): + super().__call__(parser, namespace, values, option_string) + supplied = getattr(namespace, SUPPLIED, ()) + if self.dest not in supplied: + setattr(namespace, SUPPLIED, (*supplied, self.dest)) + + +class _SuppliedStore(_Supplied, argparse._StoreAction): + pass + + +class _SuppliedAppend(_Supplied, argparse._AppendAction): + pass + + +def command_parser(root: argparse.ArgumentParser, name: str) -> argparse.ArgumentParser: + """Return a subcommand's parser, so its errors keep that command's usage line.""" + for action in root._actions: + if isinstance(action, argparse._SubParsersAction): + return action.choices[name] + raise KeyError(name) + + def _common(parser: argparse.ArgumentParser) -> None: parser.add_argument("--repo", default=".", help="Prepared target Git checkout") parser.add_argument("--repo-type", choices=REPO_TYPES, default="vllm_omni") @@ -342,7 +377,15 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: if name == "plan" else "Measure baseline and candidate commands", ) + for action in (None, "store"): + child.register("action", action, _SuppliedStore) + child.register("action", "append", _SuppliedAppend) _common(child) + child.add_argument( + "--task", dest="task_file", default=argparse.SUPPRESS, metavar="TASK_YAML", + help="Complete schema v1 task file; supplied mapped flags override it, " + "acceptance flags must match it (docs/task-input.md)", + ) child.add_argument( "--candidate-repo", help="Candidate checkout; defaults to the baseline checkout" ) @@ -364,10 +407,10 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: ) child.add_argument( "--baseline-command", - required=True, - help="Quoted argv command; {result} is replaced with a fresh output path", + help="Quoted argv command; {result} is replaced with a fresh output path; " + "required without --task", ) - child.add_argument("--candidate-command", required=True) + child.add_argument("--candidate-command", help="Required without --task") child.add_argument( "--validation-command", help="Explicit quality/correctness command; missing evidence is INCONCLUSIVE", @@ -734,10 +777,14 @@ def device_ids(args: argparse.Namespace) -> tuple[str, ...]: def make_spec(args: argparse.Namespace) -> RunSpec: - def command(value: str | None) -> tuple[str, ...] | None: + def command(value: str | list[str] | tuple[str, ...] | None) -> tuple[str, ...] | None: if value is None: return None - parsed = tuple(shlex.split(value, posix=True)) + # A task file supplies an already-normalized argv list; a flag gives quoted text. + if isinstance(value, (list, tuple)): + parsed = tuple(value) + else: + parsed = tuple(shlex.split(value, posix=True)) if not parsed: raise ValueError("Commands cannot be empty") return parsed diff --git a/src/inferrsi/apps/cli/task_input.py b/src/inferrsi/apps/cli/task_input.py index 2727824d0..881c65227 100644 --- a/src/inferrsi/apps/cli/task_input.py +++ b/src/inferrsi/apps/cli/task_input.py @@ -6,6 +6,10 @@ the fields a full plan or run still needs. It reads one file and writes nothing: no subprocess, probe, install or workspace file. PyYAML is a core dependency and is imported only when a task file is parsed, so importing the CLI never loads it. + +``plan --task`` and ``run --task`` call ``preview`` with ``supplied_overrides`` before any +probe, then copy a complete task onto their arguments with ``arguments_from``. Both +helpers are pure. """ from __future__ import annotations @@ -552,6 +556,43 @@ def overrides_from(namespace: object) -> dict[str, Any]: if field.dest is not None and field.dest in values} +def supplied_overrides(namespace: object, supplied: object) -> dict[str, Any]: + """Return the mapped flags whose dest is in ``supplied``, the dests the caller gave. + + ``plan``/``run`` keep parser defaults on their namespace, so a dest missing from + ``supplied`` holds a default and never becomes an override. + """ + values = vars(namespace) + names = set(supplied) + return {field.dest: values[field.dest] for field in FIELDS + if field.dest is not None and field.dest in names and field.dest in values} + + +def arguments_from(task: dict) -> dict[str, Any]: + """Return {argparse dest: value} for every mapped field of a complete preview task. + + Device IDs are joined with ``,`` (a task ID cannot contain one); commands and trial + checks are copied as lists. A missing optional value stays None, including + ``environment.python``, which the caller replaces with its own interpreter. + """ + values: dict[str, Any] = {} + for field in FIELDS: + if field.dest is None: + continue + value = task[field.section][field.name] + if field.kind == "ids": + value = ",".join(value or ()) + elif isinstance(value, list): + value = list(value) + values[field.dest] = value + return values + + +def is_url(reference: str) -> bool: + """Whether a valid ``acceptance.reference`` is an HTTP(S) URL, not a local plan path.""" + return bool(_URL_SCHEME.match(reference)) + + def _resource(name: str) -> str: return files("inferrsi.apps.cli").joinpath(RESOURCE, name).read_text(encoding="utf-8") diff --git a/tests/fixtures/task-input/README.md b/tests/fixtures/task-input/README.md index 1de500a99..91bbeda2a 100644 --- a/tests/fixtures/task-input/README.md +++ b/tests/fixtures/task-input/README.md @@ -13,7 +13,11 @@ template under `src/inferrsi/apps/cli/task-input/v1/`). See `tests/test_task_input.py` checks the Python contract and the packaged JSON Schema against these files, and `tests/check_installed.py` reuses `complete.yaml` from an -installed wheel outside the checkout. +installed wheel outside the checkout. `tests/test_task_plan_run.py` uses `complete.yaml` +and `partial.yaml` with `inferrsi plan --task` and `inferrsi run --task`. It checks the +expected RunSpec, the `task` block against `task preview --json`, overrides, conflicting +acceptance flags, field errors before any probe or write, and the run's baseline revision +and local reference checks. Another entry point that reads InferRSI task files, such as the DSH plugin (#152), must consume this contract and match these fixtures (complete and partial tasks, relative diff --git a/tests/test_task_plan_run.py b/tests/test_task_plan_run.py new file mode 100644 index 000000000..8348e71f4 --- /dev/null +++ b/tests/test_task_plan_run.py @@ -0,0 +1,389 @@ +"""``plan --task`` and ``run --task``: the shared YAML task contract on the plan/run path.""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +from inferrsi.apps import cli +from inferrsi.apps.cli import arguments, task_input +from inferrsi.apps.legacy import run as legacy_run +from inferrsi.contracts import RunSpec + +REPO = Path(__file__).resolve().parents[1] +FIXTURES = REPO / "tests" / "fixtures" / "task-input" +COMPLETE = FIXTURES / "complete.yaml" +PARTIAL = FIXTURES / "partial.yaml" +HEAD = "abc1234" + "0" * 33 +REQUIRED = "the following arguments are required: --baseline-command, --candidate-command" + + +def _task(tmp_path: Path, source: Path = COMPLETE, *, replace=(), plan_file=True) -> Path: + """Copy a fixture into tmp_path/task with its repo/ and candidate/ checkouts.""" + directory = tmp_path / "task" + for name in ("repo", "candidate"): + (directory / name).mkdir(parents=True, exist_ok=True) + if plan_file: + (directory / "plan").mkdir(exist_ok=True) + (directory / "plan" / "acceptance.md").write_text("frozen gates\n", encoding="utf-8") + target = directory / source.name + shutil.copyfile(source, target) + text = target.read_text(encoding="utf-8") + for old, new in replace: + assert old in text, old + text = text.replace(old, new) + target.write_text(text, encoding="utf-8") + return target + + +@pytest.fixture +def caller(tmp_path, monkeypatch) -> Path: + directory = tmp_path / "caller" + directory.mkdir() + monkeypatch.chdir(directory) + return directory + + +def _environment(head: str = HEAD) -> dict: + return { + "repository": {"available": True, "head": head}, + "device": {"status": "available", "selection_verified": True}, + "target_python": {"environment": {"python": "stub"}}, + } + + +@pytest.fixture +def inspected(monkeypatch) -> list: + calls = [] + + def fake(repo, repo_type, backend, **kwargs): + calls.append({"repo": repo, "repo_type": repo_type, "backend": backend, **kwargs}) + return _environment() + + monkeypatch.setattr(cli, "inspect_environment", fake) + return calls + + +def _forbid(monkeypatch, *names: str) -> None: + def forbidden(*args, **kwargs): + raise AssertionError("invalid task input must not probe, launch or write") + + for name in names: + target, _, attribute = name.rpartition(".") + module = {"cli": cli, "subprocess": subprocess, "os": os, "legacy": legacy_run}[target] + if hasattr(module, attribute): + monkeypatch.setattr(module, attribute, forbidden) + + +def _plan(capsys, *argv: str) -> dict: + assert cli.main(["plan", *argv]) == 0 + return json.loads(capsys.readouterr().out) + + +def _exit(capsys, *argv: str) -> str: + with pytest.raises(SystemExit) as raised: + cli.main(list(argv)) + assert raised.value.code == 2 + return capsys.readouterr().err + + +def _expected_spec(directory: Path, caller: Path, **changes) -> dict: + values = dict( + repo=str((directory / "repo").resolve()), + candidate_repo=str((directory / "candidate").resolve()), + repo_type="vllm", + backend="cuda", + scenario="llm.decode", + mode="code", + baseline_command=("python", "bench.py", "--variant", "baseline", "--output", + "{result}"), + candidate_command=("python", "bench.py", "--variant", "candidate", "--output", + "{result}"), + validation_command=("python", "quality.py", "--output", "{result}"), + metric_key="metrics.latency_ms", + required_trial_checks=("checks.warm",), + metric_unit="ms", + comparison_scope="external_command", + direction="minimize", + repetitions=5, + min_improvement_pct=2.5, + max_minutes=90.0, + workload_id="fixed-prompts-v1", + model="", + model_revision="", + agent="manual", + device_ids=("0", "1"), + output_dir=str((caller / "runs").resolve()), + ) + values.update(changes) + return json.loads(json.dumps(RunSpec(**values).to_dict())) + + +def test_plan_with_the_complete_fixture_gives_the_expected_run_spec( + tmp_path, caller, inspected, capsys, +): + task_file = _task(tmp_path) + directory = task_file.parent + result = _plan(capsys, "--task", str(task_file)) + assert result["run_spec"] == _expected_spec(directory, caller) + assert inspected == [{ + "repo": str(directory / "repo"), "repo_type": "vllm", "backend": "cuda", + "device_ids": ("0", "1"), "device_model": "", + "python": str(directory / ".venv" / "bin" / "python"), + }] + assert result["execution"] == "not started" + assert result["task"]["complete"] and result["task"]["execution"] == "not started" + for name in ("objective", "plane"): + assert result["task"]["task"]["optimization"][name] + assert result["task"]["task"]["environment"]["rounds"] == 4 + assert result["task"]["task"]["acceptance"]["baseline_revision"] == "" + + +def test_plan_task_block_equals_the_agent_preview_and_the_cli_preview( + tmp_path, caller, inspected, capsys, +): + task_file = _task(tmp_path) + for flags, overrides in (([], None), + (["--repetitions", "7", "--backend", "rocm"], + {"repetitions": 7, "backend": "rocm"})): + block = _plan(capsys, "--task", str(task_file), *flags)["task"] + assert block == task_input.preview(task_file, overrides, cwd=str(caller)) + completed = subprocess.run( + [sys.executable, "-m", "inferrsi", "task", "preview", str(task_file), "--json", + *flags], + capture_output=True, text=True, encoding="utf-8", cwd=caller, check=False, + env=dict(os.environ, PYTHONPATH=str(REPO / "src")), + ) + assert completed.returncode == 0, completed.stderr + assert json.loads(completed.stdout) == block + + +def test_omitted_flags_keep_yaml_and_explicit_default_valued_flags_override( + tmp_path, caller, inspected, capsys, +): + task_file = _task(tmp_path) + directory = task_file.parent + plain = _plan(capsys, "--task", str(task_file)) + assert plain["run_spec"]["backend"] == "cuda" + assert plain["run_spec"]["repetitions"] == 5 + assert plain["run_spec"]["min_improvement_pct"] == 2.5 + assert plain["task"]["sources"]["environment.backend"] == "yaml" + + # The values equal the plan parser defaults, yet they were supplied, so they win. + result = _plan(capsys, "--task", str(task_file), "--backend", "cpu", "--repetitions", "3", + "--baseline-command", "python other.py --output {result}", + "--python", "venv/bin/python", "--min-improvement-pct", "2.5") + assert result["run_spec"] == _expected_spec( + directory, caller, backend="cpu", repetitions=3, + baseline_command=("python", "other.py", "--output", "{result}"), + ) + task = result["task"] + assert task["task"]["environment"]["backend"] == "cpu" + assert task["task"]["environment"]["repetitions"] == 3 + for path in ("environment.backend", "environment.repetitions", + "environment.baseline_command", "environment.python"): + assert task["sources"][path] == "cli", path + assert task["sources"]["acceptance.min_improvement_pct"] == "yaml" + assert task["sources"]["environment.max_minutes"] == "yaml" + assert inspected[-1]["backend"] == "cpu" + assert inspected[-1]["python"] == str(caller / "venv" / "bin" / "python") + + +def test_missing_optional_python_and_candidate_use_the_caller_and_the_baseline( + tmp_path, caller, inspected, capsys, +): + task_file = _task(tmp_path, replace=( + (" candidate_repository: candidate\n", ""), (" python: .venv/bin/python\n", ""), + )) + result = _plan(capsys, "--task", str(task_file)) + assert result["run_spec"]["candidate_repo"] is None + assert inspected[-1]["python"] == sys.executable + assert result["task"]["task"]["environment"]["python"] is None + + +@pytest.mark.parametrize("flags, field", [ + (("--min-improvement-pct", "5"), "acceptance.min_improvement_pct"), + (("--min-improvement-pct", "0"), "acceptance.min_improvement_pct"), + (("--metric-key", "metrics.throughput"), "acceptance.metric_key"), + (("--direction", "maximize"), "acceptance.direction"), + (("--require-trial-check", "checks.other"), "acceptance.required_trial_checks"), +]) +@pytest.mark.parametrize("command", [("plan",), ("run",), ("run", "--dry-run")]) +def test_conflicting_acceptance_flag_exits_before_inspection( + tmp_path, caller, monkeypatch, capsys, flags, field, command, +): + task_file = _task(tmp_path) + _forbid(monkeypatch, "cli.inspect_environment", "legacy.run_experiment") + err = _exit(capsys, *command, "--task", str(task_file), *flags) + assert f"{command[0]}: error: task file {task_file} is not ready" in err + assert f"error {field} (cli): {flags[0]} conflicts with the task file" in err + + +def _tree(root: Path) -> dict[str, bytes | None]: + return {path.relative_to(root).as_posix(): path.read_bytes() if path.is_file() else None + for path in sorted(root.rglob("*"))} + + +@pytest.mark.parametrize("command", [("plan",), ("run",), ("run", "--dry-run")]) +def test_incomplete_or_invalid_task_reports_fields_and_starts_or_writes_nothing( + tmp_path, caller, monkeypatch, capsys, command, +): + partial = _task(tmp_path, PARTIAL) + invalid = _task(tmp_path, replace=(("repetitions: 5", "repetitions: 0"), + (" rounds: 4\n", " rounds: 4\n budget: 1\n"))) + before = _tree(tmp_path) + _forbid(monkeypatch, "subprocess.Popen", "subprocess.run", "os.system", "os.posix_spawn", + "os.posix_spawnp", "os.execv", "os.execve", "os.fork", "os.mkdir", "os.makedirs", + "cli.inspect_environment", "cli.write_report", "legacy.run_experiment") + + err = _exit(capsys, *command, "--task", str(partial)) + assert f"is not ready for {command[0]}" in err + for field in ("optimization.framework", "environment.baseline_command", + "acceptance.baseline_revision", "acceptance.metric_key"): + assert f"blocker {field}: missing; required for plan/run" in err + + err = _exit(capsys, *command, "--task", str(invalid), "--repetitions", "7") + assert "error environment.repetitions (yaml): must be a positive integer" in err + assert "error environment.budget (yaml): is not a v1 task field" in err + + err = _exit(capsys, *command, "--task", str(tmp_path / "missing.yaml")) + assert "error $ (yaml): cannot read the task file" in err + assert _tree(tmp_path) == before + assert list(caller.iterdir()) == [] + + +def _fake_run(monkeypatch, caller: Path) -> list: + specs = [] + + def run_experiment(spec, environment): + specs.append(spec) + directory = caller / "runs" / "run-1" + directory.mkdir(parents=True) + (directory / "status.json").write_text('{"verdict": "FAIL"}', encoding="utf-8") + return directory + + monkeypatch.setattr(legacy_run, "run_experiment", run_experiment) + monkeypatch.setattr(cli, "write_report", lambda directory: None) + return specs + + +def test_run_rejects_a_baseline_revision_that_is_not_the_checkout_head( + tmp_path, caller, inspected, monkeypatch, capsys, +): + task_file = _task(tmp_path, replace=(('""', '"def5678"'),)) + specs = _fake_run(monkeypatch, caller) + err = _exit(capsys, "run", "--task", str(task_file)) + assert "acceptance.baseline_revision 'def5678' does not match" in err + assert len(inspected) == 1 and specs == [] + assert list(caller.iterdir()) == [] + + +def test_run_rejects_a_missing_local_reference_before_inspection( + tmp_path, caller, monkeypatch, capsys, +): + task_file = _task(tmp_path, replace=(('""', f'"{HEAD[:7]}"'),), + plan_file=False) + _forbid(monkeypatch, "cli.inspect_environment", "legacy.run_experiment") + err = _exit(capsys, "run", "--task", str(task_file)) + assert "acceptance.reference must be an existing local plan file" in err + assert str(task_file.parent / "plan" / "acceptance.md") in err + assert list(caller.iterdir()) == [] + + +@pytest.mark.parametrize("revision, reference", [ + (HEAD[:7], None), (HEAD, None), (HEAD[:12].upper(), "https://example.com/issues/1"), +]) +def test_run_with_an_agreeing_task_reaches_the_experiment_and_records_the_task( + tmp_path, caller, inspected, monkeypatch, capsys, revision, reference, +): + replace = [('""', f'"{revision}"')] + if reference: + replace.append(("reference: plan/acceptance.md", f"reference: {reference}")) + task_file = _task(tmp_path, replace=replace, plan_file=reference is None) + specs = _fake_run(monkeypatch, caller) + assert cli.main(["run", "--task", str(task_file), "--repetitions", "7"]) == 1 + out = json.loads(capsys.readouterr().out) + directory = Path(out["run_dir"]) + assert [json.loads(json.dumps(spec.to_dict())) for spec in specs] == [ + _expected_spec(task_file.parent, caller, repetitions=7) + ] + recorded = json.loads((directory / "task.json").read_text(encoding="utf-8")) + assert recorded == task_input.preview(task_file, {"repetitions": 7}, cwd=str(caller)) + assert recorded["task"]["acceptance"]["baseline_revision"] == revision + args = json.loads((directory / "args.json").read_text(encoding="utf-8")) + assert args["task_file"] == str(task_file) + assert args["backend"] == "cuda" and args["repetitions"] == 7 + assert args["baseline_command"] == list(_expected_spec( + task_file.parent, caller)["baseline_command"]) + assert args["device_ids"] == "0,1" + assert arguments.SUPPLIED not in args + + +def test_flag_only_plan_and_run_keep_their_contract(tmp_path, caller, inspected, monkeypatch, + capsys): + for argv, missing in ((["plan"], REQUIRED), + (["run", "--baseline-command", "b"], + "the following arguments are required: --candidate-command")): + err = _exit(capsys, *argv) + assert f"{argv[0]}: error: {missing}\n" in err + assert inspected == [] + + repo = tmp_path / "repo" + repo.mkdir() + flags = ["--repo", str(repo), "--baseline-command", "python b.py", + "--candidate-command", "python c.py"] + result = _plan(capsys, *flags) + assert set(result) == {"run_spec", "environment", "execution", "validation"} + assert result["run_spec"]["backend"] == "cpu" + assert result["run_spec"]["baseline_command"] == ["python", "b.py"] + assert inspected[-1]["python"] == sys.executable + + _fake_run(monkeypatch, caller) + assert cli.main(["run", *flags]) == 1 + directory = Path(json.loads(capsys.readouterr().out)["run_dir"]) + assert not (directory / "task.json").exists() + args = json.loads((directory / "args.json").read_text(encoding="utf-8")) + assert "task_file" not in args and arguments.SUPPLIED not in args + assert args["baseline_command"] == "python b.py" + + +def test_only_supplied_flags_become_overrides(): + for command in ("plan", "run"): + args = arguments.parser().parse_args([command, "--task", "t.yaml"]) + supplied = vars(args).pop(arguments.SUPPLIED, ()) + assert supplied == ("task_file",) + assert task_input.supplied_overrides(args, supplied) == {} + args = arguments.parser().parse_args( + [command, "--task", "t.yaml", "--backend", "cpu", "--require-trial-check", "a", + "--require-trial-check", "b", "--dry-run", "--agent", "codex"]) + supplied = vars(args).pop(arguments.SUPPLIED) + assert task_input.supplied_overrides(args, supplied) == { + "backend": "cpu", "require_trial_check": ["a", "b"]} + + +def test_arguments_from_a_preview_feed_make_spec_like_the_equivalent_flags(tmp_path, caller): + task_file = _task(tmp_path) + values = task_input.arguments_from(task_input.preview(task_file)["task"]) + assert values["device_ids"] == "0,1" + assert values["require_trial_check"] == ["checks.warm"] + assert values["python"] == str(task_file.parent / ".venv" / "bin" / "python") + args = arguments.parser().parse_args(["plan", "--task", str(task_file)]) + vars(args).update(values) + flags = arguments.parser().parse_args([ + "plan", "--repo", values["repo"], "--candidate-repo", values["candidate_repo"], + "--repo-type", "vllm", "--backend", "cuda", "--device-ids", "0,1", + "--scenario", "llm.decode", "--mode", "code", + "--baseline-command", "python bench.py --variant baseline --output {result}", + "--candidate-command", "python bench.py --variant candidate --output {result}", + "--validation-command", "python quality.py --output {result}", + "--require-trial-check", "checks.warm", "--repetitions", "5", + "--min-improvement-pct", "2.5", "--max-minutes", "90", "--workload-id", + "fixed-prompts-v1", "--model", "", "--model-revision", "", + ]) + assert arguments.make_spec(args) == arguments.make_spec(flags) From 41e4ccb4e5fdc8b25fac032ba2724aa44fba0f19 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:52:03 +0800 Subject: [PATCH 2/6] Verify run --task against the referenced frozen gate record run --task checked only that a local acceptance.reference existed (or accepted any HTTP(S) URL) and that the baseline HEAD matched. The YAML's metric, direction, threshold and trial checks then went straight into the RunSpec, so a task that kept the reference and HEAD but changed the agreed threshold ran under a different gate. task_input.frozen_gate now resolves the local acceptance.reference as a frozen gate record: a schema v1 document with an acceptance section, read with the same safe loader and validator. It must state baseline_revision, metric_key, direction, metric_unit and min_improvement_pct. Every acceptance field except reference must equal the task's effective value after the same defaults. The result is agrees, mismatch or unverified, with field-level problems and the record's SHA-256. An HTTP(S) reference is never fetched, so its gate is unverified. The same applies to a missing file, the task file itself, a non-v1 document such as a Markdown plan, or a record that omits a required gate field. run --task requires agrees before the environment probe. A mismatch or an unverified gate exits 2, listing each problem by field, with no command started and nothing written. The run directory records frozen_gate.json next to task.json. plan and run --dry-run add a frozen_gate block and report a mismatch or unverified gate without failing. task validate and task preview are unchanged and read only the task file. Tests cover the reported case (same reference and HEAD, threshold changed only) and a change to each other acceptance field. They also cover a baseline revision that matches HEAD but not the record, the unverifiable reference forms, the plan and dry-run report, and frozen_gate.json on an agreeing run. Agent-assisted-by: Claude Code / claude-opus-5-5 [effort=xhigh] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/operations.md | 6 +- docs/task-input.md | 65 ++++++++++-- src/inferrsi/apps/cli/__init__.py | 34 ++++--- src/inferrsi/apps/cli/task_input.py | 85 +++++++++++++++- tests/fixtures/task-input/README.md | 4 +- tests/test_task_plan_run.py | 153 ++++++++++++++++++++++++---- 6 files changed, 301 insertions(+), 46 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index fe1bbc5aa..0a6e363ab 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -415,7 +415,7 @@ the same merge (see [use with plan and run](task-input.md#use-with-plan-and-run) - **Inputs:** repository/backend/device flags; `plan` takes the full experiment specification as flags, or a complete YAML task file with `--task ` plus explicit mapped overrides. - **Scope:** environment inspection and specification preview. -- **Output:** environment facts, or a preview of the RunSpec. With `--task`, the preview adds a `task` block equal to `task preview --json` for the same file and flags. +- **Output:** environment facts, or a preview of the RunSpec. With `--task`, the preview adds a `task` block equal to `task preview --json` for the same file and flags, and a `frozen_gate` block that reports whether the task's acceptance fields agree with the local frozen gate record named by `acceptance.reference`. - **Side effects:** `doctor` may invoke bounded read-only probes; `plan`/`--dry-run` persist nothing. - **Failure behavior:** unavailable devices or invalid flags are reported explicitly. With `--task`, task field errors, conflicting acceptance flags and blockers are printed by field to stderr, exit 2, before any probe. Without `--task`, `--baseline-command` and `--candidate-command` are required. - **Example:** `inferrsi doctor --repo . --repo-type vllm_omni --backend cpu` @@ -428,9 +428,9 @@ compatibility. - **Inputs:** the full experiment specification as flags or as a complete `--task ` (`run`); a run ID and output directory (`status`/`report`). - **Scope:** caller-supplied benchmark, candidate and validation commands under the experiment contract. -- **Output:** a run ID and evidence directory; recorded progress; an HTML report. With `--task`, the run directory also holds `task.json`, the task preview. +- **Output:** a run ID and evidence directory; recorded progress; an HTML report. With `--task`, the run directory also holds `task.json`, the task preview, and `frozen_gate.json`, the gate result with the record's SHA-256. - **Side effects:** `run` executes the supplied commands and owns child-process cleanup; `report` writes HTML into the run directory. -- **Failure behavior:** exit codes 0 PASS, 1 FAIL, 2 INCONCLUSIVE/input errors; cancellation is recorded. With `--task`, task field errors and blockers exit 2 before any probe. A missing local `acceptance.reference` file also exits 2 before any probe. A baseline checkout `HEAD` that differs from `acceptance.baseline_revision` exits 2 after inspection. In all three cases no command starts and nothing is written. +- **Failure behavior:** exit codes 0 PASS, 1 FAIL, 2 INCONCLUSIVE/input errors; cancellation is recorded. With `--task`, task field errors and blockers exit 2 before any probe. A task whose acceptance fields differ from the frozen gate record (`mismatch`), or whose gate cannot be checked (`unverified`: an HTTP(S) reference, a missing file, or a record that is not a schema v1 `acceptance` section stating the gate), also exits 2 before any probe; see [frozen gate record](task-input.md#frozen-gate-record). A baseline checkout `HEAD` that differs from `acceptance.baseline_revision` exits 2 after inspection. In all three cases no command starts and nothing is written. - **Example:** see [quickstart: real remote experiment](quickstart.md#real-remote-experiment) Operation success, recorded execution state and the experiment verdict are diff --git a/docs/task-input.md b/docs/task-input.md index 8e892bc41..6eb4972e9 100644 --- a/docs/task-input.md +++ b/docs/task-input.md @@ -64,7 +64,7 @@ used when both the file and the flag omit an optional field. | `environment.repetitions` | positive integer | `--repetitions` | yes | — | | `environment.max_minutes` | positive finite number, at most 10080 (seven days) | `--max-minutes` | yes | — | | `environment.rounds` | positive integer (optimization search rounds) | — | — | — | -| `acceptance.reference` | HTTP(S) issue URL or local plan path | — | yes | — | +| `acceptance.reference` | HTTP(S) issue URL or local plan path; `run` needs a local [frozen gate record](#frozen-gate-record) | — | yes | — | | `acceptance.baseline_revision` | quoted string | — | yes | — | | `acceptance.metric_key` | flat or dotted JSON key | `--metric-key` (must match) | yes | — | | `acceptance.direction` | `minimize`, `maximize` | `--direction` (must match) | yes | — | @@ -169,19 +169,23 @@ inferrsi run --task task.yaml # explicit execution without quality evidence, which gives the existing `INCONCLUSIVE` outcome. - **`plan` and `run --dry-run`.** They inspect the environment and print the RunSpec built from the task, as in flag-only use. Their output adds a `task` block, the - same object that `task preview --json` prints for the same file and flags. Without - `--task` the output is unchanged. + same object that `task preview --json` prints for the same file and flags, and a + `frozen_gate` block, the [frozen gate](#frozen-gate-record) result. They report a + `mismatch` or `unverified` gate without failing. Without `--task` the output is + unchanged. - **`run`.** Execution checks that the task agrees with its accepted inputs. Each check fails with exit 2 before any benchmark command starts or any run directory is written. - - A local `acceptance.reference` must be an existing file. InferRSI checks this - before the environment probe. An HTTP(S) issue URL is recorded as written. + - Before the environment probe, the task's acceptance fields must agree with the + [frozen gate record](#frozen-gate-record) that `acceptance.reference` names. + A `mismatch` or `unverified` gate prints each problem by field to stderr. - After inspection, the baseline checkout's `HEAD` must equal `acceptance.baseline_revision`. A hexadecimal prefix of at least 7 characters is also accepted. - The run directory then holds `task.json`, the task preview, next to `args.json`. - `args.json` records the effective values and the absolute `task_file`. + The run directory then holds `task.json`, the task preview, and `frozen_gate.json`, + the gate result with the record's SHA-256, next to `args.json`. `args.json` records + the effective values and the absolute `task_file`. RunSpec carries the experiment fields. `optimization.objective`, `optimization.plane`, `environment.rounds`, `acceptance.reference`, @@ -190,6 +194,49 @@ They are recorded in the `task` block and in `task.json`. Without `--task`, `--baseline-command` and `--candidate-command` remain required, with the same argparse error and exit 2. +### Frozen gate record + +Freeze the agreed gate before candidate search as a local file, for example in the +campaign's `plan/` segment, and point `acceptance.reference` at it. The record is a +schema v1 document with `schema_version: 1` and an `acceptance` section. It is read +and validated like a task file, and other sections are allowed, so a frozen copy of +the reviewed task also works. Its own `acceptance.reference` may cite the acceptance +issue URL; that field is not compared. + +```yaml +schema_version: 1 +acceptance: + reference: "" + baseline_revision: "" + metric_key: metrics.latency_ms + direction: minimize + metric_unit: ms + min_improvement_pct: 2.5 + required_trial_checks: [checks.warm] + constraints: "" +``` + +`frozen_gate` reports one of three statuses, with field-level `problems`: + +- **`agrees`.** The record states `baseline_revision`, `metric_key`, `direction`, + `metric_unit` and `min_improvement_pct`, and every acceptance field except + `reference` equals the task's effective value. Omitted `comparison_scope` and + `required_trial_checks` take their built-in defaults on both sides, and the order + of `required_trial_checks` does not matter. `baseline_revision` must be the same + text. +- **`mismatch`.** The record is readable and complete, and at least one field + differs, for example `acceptance.min_improvement_pct: is 1.0 in the task but 2.5 + in the frozen gate record `. +- **`unverified`.** The gate cannot be checked: the reference is an HTTP(S) URL + (InferRSI does not fetch it), the file is missing or is the task file itself, it + is not a valid schema v1 document (a Markdown plan, for example), it has no + `acceptance` section, or it omits a required gate field. + +The check compares the record with the task. It does not establish that the +record itself is the accepted one; cite the record and its `sha256` from +`frozen_gate.json` in the acceptance issue. A `run --task` that passes this +check still follows the existing acceptance, frozen-gate and evidence rules. + ## CLI workflow ```bash @@ -247,7 +294,9 @@ The CLI and the Agent produce the same normalized task for the same file and fla `tests/test_task_input.py` checks this by comparing `inferrsi task preview --json` with the Python `task_input.preview` on the shared complete fixture. `tests/test_task_plan_run.py` checks that `plan --task` gives the same `task` block, -and the expected RunSpec, for that fixture. +and the expected RunSpec, for that fixture. An Agent checks a task against its frozen +gate record with the Python `task_input.frozen_gate`, the same check `run --task` +applies. ## Compatibility with other task formats diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index 51e7f9d1c..0685ce4ba 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -384,16 +384,13 @@ def _revision_matches(head: str, revision: str) -> bool: ) -def _check_task_reference(task: dict) -> None: - """Require a run's local acceptance plan to exist; an HTTP(S) URL is kept verbatim.""" - from .task_input import is_url - - reference = task["task"]["acceptance"]["reference"] - if not is_url(reference) and not os.path.isfile(reference): - raise ValueError( - "acceptance.reference must be an existing local plan file or an HTTP(S) " - f"issue URL: {reference}" - ) +def _check_frozen_gate(gate: dict) -> None: + """Require a run's task to agree with the frozen gate record it references.""" + if gate["status"] != "agrees": + lines = [f"frozen gate {gate['status']}: run --task needs the task's acceptance " + "fields to agree with the frozen gate record that acceptance.reference names:"] + lines += [f"{item['field']}: {item['message']}" for item in gate["problems"]] + raise ValueError("\n".join(lines)) def _check_baseline_revision(task: dict, environment: dict) -> None: @@ -843,8 +840,13 @@ def main(argv: list[str] | None = None) -> int: _print({"record": str(path)}) return 0 - if task is not None and args.command == "run" and not args.dry_run: - _check_task_reference(task) + gate = None + if task is not None: + from .task_input import frozen_gate + + gate = frozen_gate(task["task"], task["task_file"]) + if args.command == "run" and not args.dry_run: + _check_frozen_gate(gate) environment = inspect_environment( args.repo, args.repo_type, @@ -873,6 +875,7 @@ def main(argv: list[str] | None = None) -> int: } if task is not None: preview["task"] = task + preview["frozen_gate"] = gate _print(preview) return 0 if not environment["repository"].get("available"): @@ -895,9 +898,10 @@ def main(argv: list[str] | None = None) -> int: json.dumps(vars(args), ensure_ascii=False, indent=2) + "\n", encoding="utf-8" ) if task is not None: - (directory / "task.json").write_text( - json.dumps(task, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" - ) + for name, record in (("task.json", task), ("frozen_gate.json", gate)): + (directory / name).write_text( + json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) write_report(directory) status = json.loads((directory / "status.json").read_text(encoding="utf-8")) _print( diff --git a/src/inferrsi/apps/cli/task_input.py b/src/inferrsi/apps/cli/task_input.py index 881c65227..0f7c7c2d0 100644 --- a/src/inferrsi/apps/cli/task_input.py +++ b/src/inferrsi/apps/cli/task_input.py @@ -9,11 +9,15 @@ ``plan --task`` and ``run --task`` call ``preview`` with ``supplied_overrides`` before any probe, then copy a complete task onto their arguments with ``arguments_from``. Both -helpers are pure. +helpers are pure. ``frozen_gate`` also reads the local frozen gate record named by +``acceptance.reference`` and compares its acceptance fields with the task; it writes +nothing either. """ from __future__ import annotations +import hashlib +import json import math import os import re @@ -366,6 +370,11 @@ def load(path: str | os.PathLike) -> tuple[object, list[dict[str, str]]]: raw = handle.read(MAX_BYTES + 1) except OSError as exc: return None, [_error(DOCUMENT, f"cannot read the task file: {exc.strerror or exc}")] + return _parse(raw) + + +def _parse(raw: bytes) -> tuple[object, list[dict[str, str]]]: + """Parse the bytes of one YAML task document; return (data, document errors).""" if len(raw) > MAX_BYTES: return None, [_error(DOCUMENT, "the task file exceeds 64 KiB")] try: @@ -593,6 +602,80 @@ def is_url(reference: str) -> bool: return bool(_URL_SCHEME.match(reference)) +# The acceptance fields compared with a frozen gate record. ``reference`` names the +# record itself, so it is not compared; the required ones must be stated by the record. +GATE_FIELDS = tuple(field for field in FIELDS + if field.section == "acceptance" and field.name != "reference") + + +def _shown(value: object) -> str: + return json.dumps(value, ensure_ascii=False) + + +def frozen_gate(task: dict, task_file: str | os.PathLike) -> dict: + """Compare a task's acceptance fields with the frozen gate record it references. + + The local ``acceptance.reference`` must name a regular file, other than the task file, + holding a valid schema v1 document whose ``acceptance`` section states the agreed gate. + After the same built-in defaults, each acceptance field except the reference must + equal the record's. Only that file is read. An HTTP(S) reference is never fetched, so + its gate stays unverified. Returns the reference, the record's SHA-256, ``status`` + (``agrees``, ``mismatch`` or ``unverified``) and field-level ``problems``. + """ + reference = task["acceptance"]["reference"] + result: dict[str, Any] = { + "reference": reference, "sha256": None, "status": "unverified", "problems": [], + } + + def unverified(message: str) -> dict: + result["problems"].append( + {"field": "acceptance.reference", "message": _printable(message)}) + return result + + if reference is None: + return unverified("is missing, so no frozen gate record can be read") + if is_url(reference): + return unverified( + "is an HTTP(S) URL, which InferRSI does not fetch, so the frozen gate cannot be " + "verified; point it at the local frozen gate record the acceptance issue cites") + if not os.path.isfile(reference): + return unverified(f"is not an existing local frozen gate record file: {reference}") + if os.path.realpath(reference) == os.path.realpath(task_file): + return unverified("names the task file itself, not a separate frozen gate record") + try: + with open(reference, "rb") as handle: + raw = handle.read(MAX_BYTES + 1) + except OSError as exc: + return unverified(f"cannot read the frozen gate record: {exc.strerror or exc}") + data, errors = _parse(raw) + if not errors: + errors = validate(data) + for error in errors: + unverified(f"frozen gate record {reference}: {error['field']} {error['message']}") + if errors: + return result + if not isinstance(data.get("acceptance"), dict): + return unverified(f"frozen gate record {reference} has no acceptance section") + result["sha256"] = hashlib.sha256(raw).hexdigest() + base = os.path.dirname(reference) + gate = merge(data, base=base, cwd=base)[0]["acceptance"] + for field in GATE_FIELDS: + if field.required and gate[field.name] is None: + unverified(f"frozen gate record {reference} does not state {field.path}") + if result["problems"]: + return result + for field in GATE_FIELDS: + mine, frozen = task["acceptance"][field.name], gate[field.name] + if (mine is None) != (frozen is None) or ( + mine is not None and not _same(field, mine, frozen) + ): + result["problems"].append({"field": field.path, "message": _printable( + f"is {_shown(mine)} in the task but {_shown(frozen)} in the frozen gate " + f"record {reference}")}) + result["status"] = "mismatch" if result["problems"] else "agrees" + return result + + def _resource(name: str) -> str: return files("inferrsi.apps.cli").joinpath(RESOURCE, name).read_text(encoding="utf-8") diff --git a/tests/fixtures/task-input/README.md b/tests/fixtures/task-input/README.md index 91bbeda2a..865245aee 100644 --- a/tests/fixtures/task-input/README.md +++ b/tests/fixtures/task-input/README.md @@ -16,8 +16,8 @@ against these files, and `tests/check_installed.py` reuses `complete.yaml` from installed wheel outside the checkout. `tests/test_task_plan_run.py` uses `complete.yaml` and `partial.yaml` with `inferrsi plan --task` and `inferrsi run --task`. It checks the expected RunSpec, the `task` block against `task preview --json`, overrides, conflicting -acceptance flags, field errors before any probe or write, and the run's baseline revision -and local reference checks. +acceptance flags, field errors before any probe or write, and the run's frozen gate and +baseline revision checks. Another entry point that reads InferRSI task files, such as the DSH plugin (#152), must consume this contract and match these fixtures (complete and partial tasks, relative diff --git a/tests/test_task_plan_run.py b/tests/test_task_plan_run.py index 8348e71f4..1a784e39a 100644 --- a/tests/test_task_plan_run.py +++ b/tests/test_task_plan_run.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib import json import os import shutil @@ -10,6 +11,7 @@ from pathlib import Path import pytest +import yaml from inferrsi.apps import cli from inferrsi.apps.cli import arguments, task_input @@ -24,14 +26,24 @@ REQUIRED = "the following arguments are required: --baseline-command, --candidate-command" -def _task(tmp_path: Path, source: Path = COMPLETE, *, replace=(), plan_file=True) -> Path: - """Copy a fixture into tmp_path/task with its repo/ and candidate/ checkouts.""" +def _task(tmp_path: Path, source: Path = COMPLETE, *, replace=(), plan_file=True, + gate=None) -> Path: + """Copy a fixture into tmp_path/task with its repo/ and candidate/ checkouts. + + ``plan_file`` writes the fixture's Markdown plan/acceptance.md. A ``gate`` document is + written to plan/gate.yaml, and the task's acceptance.reference then names it. + """ directory = tmp_path / "task" for name in ("repo", "candidate"): (directory / name).mkdir(parents=True, exist_ok=True) if plan_file: (directory / "plan").mkdir(exist_ok=True) (directory / "plan" / "acceptance.md").write_text("frozen gates\n", encoding="utf-8") + if gate is not None: + (directory / "plan").mkdir(exist_ok=True) + (directory / "plan" / "gate.yaml").write_text( + yaml.safe_dump(gate, sort_keys=False), encoding="utf-8") + replace = (*replace, ("reference: plan/acceptance.md", "reference: plan/gate.yaml")) target = directory / source.name shutil.copyfile(source, target) text = target.read_text(encoding="utf-8") @@ -42,6 +54,23 @@ def _task(tmp_path: Path, source: Path = COMPLETE, *, replace=(), plan_file=True return target +def _gate(**changes) -> dict: + """A frozen gate record: the complete fixture's acceptance section, baseline HEAD[:7].""" + acceptance = yaml.safe_load(COMPLETE.read_text(encoding="utf-8"))["acceptance"] + acceptance.update(reference="https://example.com/issues/1", baseline_revision=HEAD[:7]) + acceptance.update(changes) + return {"schema_version": 1, "acceptance": acceptance} + + +def _agreeing(tmp_path: Path, revision: str = HEAD[:7], *, replace=(), **gate) -> Path: + """The complete fixture at ``revision``, referencing a frozen gate record that agrees. + + ``replace`` edits only the task and ``gate`` changes only the record. + """ + return _task(tmp_path, replace=(('""', f'"{revision}"'), *replace), + gate=_gate(**{"baseline_revision": revision, **gate})) + + @pytest.fixture def caller(tmp_path, monkeypatch) -> Path: directory = tmp_path / "caller" @@ -143,6 +172,11 @@ def test_plan_with_the_complete_fixture_gives_the_expected_run_spec( assert result["task"]["task"]["optimization"][name] assert result["task"]["task"]["environment"]["rounds"] == 4 assert result["task"]["task"]["acceptance"]["baseline_revision"] == "" + # The fixture's Markdown plan states no machine-readable gate: plan says so, still 0. + gate = result["frozen_gate"] + assert gate["status"] == "unverified" and gate["sha256"] is None + assert gate["reference"] == str(directory / "plan" / "acceptance.md") + assert [item["field"] for item in gate["problems"]] == ["acceptance.reference"] def test_plan_task_block_equals_the_agent_preview_and_the_cli_preview( @@ -276,7 +310,7 @@ def run_experiment(spec, environment): def test_run_rejects_a_baseline_revision_that_is_not_the_checkout_head( tmp_path, caller, inspected, monkeypatch, capsys, ): - task_file = _task(tmp_path, replace=(('""', '"def5678"'),)) + task_file = _agreeing(tmp_path, "def5678") specs = _fake_run(monkeypatch, caller) err = _exit(capsys, "run", "--task", str(task_file)) assert "acceptance.baseline_revision 'def5678' does not match" in err @@ -284,28 +318,107 @@ def test_run_rejects_a_baseline_revision_that_is_not_the_checkout_head( assert list(caller.iterdir()) == [] -def test_run_rejects_a_missing_local_reference_before_inspection( - tmp_path, caller, monkeypatch, capsys, +_FORBIDDEN = ("subprocess.Popen", "subprocess.run", "os.system", "os.posix_spawn", + "os.posix_spawnp", "os.execv", "os.execve", "os.fork", "os.mkdir", "os.makedirs", + "cli.inspect_environment", "cli.write_report", "legacy.run_experiment") + + +@pytest.mark.parametrize("old, new, gate, field, shown", [ + # The review case: reference and HEAD agree; only the agreed threshold changed. + ("min_improvement_pct: 2.5", "min_improvement_pct: 1.0", {}, + "acceptance.min_improvement_pct", "is 1.0 in the task but 2.5"), + ("metric_key: metrics.latency_ms", "metric_key: metrics.ttft_ms", {}, + "acceptance.metric_key", '"metrics.ttft_ms" in the task but "metrics.latency_ms"'), + ("direction: minimize", "direction: maximize", {}, + "acceptance.direction", '"maximize" in the task but "minimize"'), + ("metric_unit: ms", "metric_unit: s", {}, "acceptance.metric_unit", '"s" in the task'), + ("comparison_scope: external_command", "comparison_scope: in_process", {}, + "acceptance.comparison_scope", '"in_process" in the task but "external_command"'), + ("required_trial_checks: [checks.warm]", "required_trial_checks: []", {}, + "acceptance.required_trial_checks", 'is [] in the task but ["checks.warm"]'), + (' constraints: "Quality must not regress against the baseline"\n', "", {}, + "acceptance.constraints", "is null in the task but"), + # HEAD matches the task's revision, but the frozen record pins another baseline. + (None, None, {"baseline_revision": "def5678"}, + "acceptance.baseline_revision", f'is "{HEAD[:7]}" in the task but "def5678"'), +]) +def test_run_rejects_a_task_whose_gate_differs_from_its_frozen_record( + tmp_path, caller, monkeypatch, capsys, old, new, gate, field, shown, ): - task_file = _task(tmp_path, replace=(('""', f'"{HEAD[:7]}"'),), - plan_file=False) - _forbid(monkeypatch, "cli.inspect_environment", "legacy.run_experiment") + task_file = _agreeing(tmp_path, replace=((old, new),) if old else (), **gate) + record = task_file.parent / "plan" / "gate.yaml" + before = _tree(tmp_path) + _forbid(monkeypatch, *_FORBIDDEN) err = _exit(capsys, "run", "--task", str(task_file)) - assert "acceptance.reference must be an existing local plan file" in err - assert str(task_file.parent / "plan" / "acceptance.md") in err + assert "frozen gate mismatch: run --task needs" in err + assert f"\n{field}: " in err and shown in err + assert f"in the frozen gate record {record}" in err + assert err.count(" in the frozen gate record ") == 1 + assert _tree(tmp_path) == before assert list(caller.iterdir()) == [] -@pytest.mark.parametrize("revision, reference", [ - (HEAD[:7], None), (HEAD, None), (HEAD[:12].upper(), "https://example.com/issues/1"), +@pytest.mark.parametrize("case, message", [ + ("missing", "is not an existing local frozen gate record file: "), + ("url", "is an HTTP(S) URL, which InferRSI does not fetch, so the frozen gate cannot"), + ("markdown", "frozen gate record {plan}: $ the task file must be a mapping, not string"), + ("itself", "names the task file itself, not a separate frozen gate record"), + ("unstated", "frozen gate record {gate} does not state acceptance.min_improvement_pct"), + ("unknown", "frozen gate record {gate}: acceptance.threshold is not a v1 task field"), + ("no-section", "frozen gate record {gate} has no acceptance section"), ]) +def test_run_rejects_a_frozen_gate_it_cannot_verify_before_inspection( + tmp_path, caller, monkeypatch, capsys, case, message, +): + revision = ('""', f'"{HEAD[:7]}"') + reference = "reference: plan/acceptance.md" + task_file = { + "missing": lambda: _task(tmp_path, replace=(revision,), plan_file=False), + "url": lambda: _task(tmp_path, replace=( + revision, (reference, "reference: https://example.com/issues/1"))), + "markdown": lambda: _task(tmp_path, replace=(revision,)), + "itself": lambda: _task(tmp_path, replace=( + revision, (reference, "reference: complete.yaml"))), + "unstated": lambda: _agreeing(tmp_path, min_improvement_pct=None), + "unknown": lambda: _agreeing(tmp_path, threshold=2.5), + "no-section": lambda: _task(tmp_path, replace=(revision,), + gate={"schema_version": 1}), + }[case]() + plan = task_file.parent / "plan" + before = _tree(tmp_path) + _forbid(monkeypatch, *_FORBIDDEN) + err = _exit(capsys, "run", "--task", str(task_file)) + assert "frozen gate unverified: run --task needs" in err + assert "\nacceptance.reference: " in err + assert message.format(plan=plan / "acceptance.md", gate=plan / "gate.yaml") in err + assert _tree(tmp_path) == before + assert list(caller.iterdir()) == [] + + +@pytest.mark.parametrize("command", [("plan",), ("run", "--dry-run")]) +def test_plan_and_dry_run_report_a_mismatched_frozen_gate_without_running( + tmp_path, caller, inspected, monkeypatch, capsys, command, +): + task_file = _agreeing(tmp_path, replace=(("min_improvement_pct: 2.5", + "min_improvement_pct: 1.0"),)) + _forbid(monkeypatch, "legacy.run_experiment", "cli.write_report") + assert cli.main([*command, "--task", str(task_file)]) == 0 + result = json.loads(capsys.readouterr().out) + assert result["execution"] == "not started" + assert result["run_spec"]["min_improvement_pct"] == 1.0 + gate = result["frozen_gate"] + assert gate["status"] == "mismatch" + assert [item["field"] for item in gate["problems"]] == ["acceptance.min_improvement_pct"] + assert gate == task_input.frozen_gate(result["task"]["task"], task_file) + assert list(caller.iterdir()) == [] + + +@pytest.mark.parametrize("revision", [HEAD[:7], HEAD, HEAD[:12].upper()]) def test_run_with_an_agreeing_task_reaches_the_experiment_and_records_the_task( - tmp_path, caller, inspected, monkeypatch, capsys, revision, reference, + tmp_path, caller, inspected, monkeypatch, capsys, revision, ): - replace = [('""', f'"{revision}"')] - if reference: - replace.append(("reference: plan/acceptance.md", f"reference: {reference}")) - task_file = _task(tmp_path, replace=replace, plan_file=reference is None) + task_file = _agreeing(tmp_path, revision) + record = task_file.parent / "plan" / "gate.yaml" specs = _fake_run(monkeypatch, caller) assert cli.main(["run", "--task", str(task_file), "--repetitions", "7"]) == 1 out = json.loads(capsys.readouterr().out) @@ -316,6 +429,11 @@ def test_run_with_an_agreeing_task_reaches_the_experiment_and_records_the_task( recorded = json.loads((directory / "task.json").read_text(encoding="utf-8")) assert recorded == task_input.preview(task_file, {"repetitions": 7}, cwd=str(caller)) assert recorded["task"]["acceptance"]["baseline_revision"] == revision + gate = json.loads((directory / "frozen_gate.json").read_text(encoding="utf-8")) + assert gate == {"reference": str(record), "status": "agrees", "problems": [], + "sha256": hashlib.sha256(record.read_bytes()).hexdigest()} + # An Agent gets the same result from the shared contract. + assert gate == task_input.frozen_gate(recorded["task"], recorded["task_file"]) args = json.loads((directory / "args.json").read_text(encoding="utf-8")) assert args["task_file"] == str(task_file) assert args["backend"] == "cuda" and args["repetitions"] == 7 @@ -348,6 +466,7 @@ def test_flag_only_plan_and_run_keep_their_contract(tmp_path, caller, inspected, assert cli.main(["run", *flags]) == 1 directory = Path(json.loads(capsys.readouterr().out)["run_dir"]) assert not (directory / "task.json").exists() + assert not (directory / "frozen_gate.json").exists() args = json.loads((directory / "args.json").read_text(encoding="utf-8")) assert "task_file" not in args and arguments.SUPPLIED not in args assert args["baseline_command"] == "python b.py" From 96e54535f88aaeee6f68a16e4da198c7df9fa614 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:26:38 +0800 Subject: [PATCH 3/6] Add a real Git regression for run --task against its frozen gate The frozen gate tests stub or forbid environment inspection, so none of them covers the reported reproduction: a real Git checkout and real CPU benchmark commands, where the reference and baseline HEAD match and only the task's threshold differs from the frozen record. The new test builds a one-commit Git checkout and a frozen gate record stating 21%. Baseline and candidate commands report 100 ms and 80 ms, a 20% gain, and an explicit quality command succeeds. It checks three runs: - The task lowers only its threshold to 0. run --task exits 2 with the min_improvement_pct mismatch before any benchmark command starts or any run directory is written. - The task and the record both state a revision that is not HEAD. The real inspection runs and the baseline check exits 2. No command starts and nothing is written. - The task agrees with the record. The run executes and returns FAIL (exit 1) under the frozen 21% gate. frozen_gate.json records agrees. With the run --task gate check disabled, the test fails at the first case because the run starts, as in the report. No source change. Agent-assisted-by: Claude Code / claude-opus-5-5 [effort=xhigh] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- tests/test_task_plan_run.py | 76 +++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/tests/test_task_plan_run.py b/tests/test_task_plan_run.py index 1a784e39a..7fff04ae3 100644 --- a/tests/test_task_plan_run.py +++ b/tests/test_task_plan_run.py @@ -443,6 +443,82 @@ def test_run_with_an_agreeing_task_reaches_the_experiment_and_records_the_task( assert arguments.SUPPLIED not in args +def _git(repo: Path, *args: str) -> str: + return subprocess.run( + ["git", "-C", str(repo), "-c", "user.name=Synthetic Contributor", + "-c", "user.email=test@example.invalid", "-c", "commit.gpgsign=false", *args], + check=True, capture_output=True, text=True, + ).stdout.strip() + + +def test_real_git_run_keeps_the_frozen_threshold_when_reference_and_head_match( + tmp_path, caller, capsys, +): + """The review reproduction, unstubbed: a real Git checkout and real CPU commands. + + Baseline 100 ms and candidate 80 ms are a 20% gain. The frozen record and the task + both state 21%, so the run is a FAIL. Keeping that reference and HEAD but lowering only + the task's threshold to 0 exits 2 before any benchmark command or run directory. So + does a baseline revision that is not HEAD, even when the record states it too. + """ + directory = tmp_path / "task" + repo = directory / "repo" + repo.mkdir(parents=True) + subprocess.run(["git", "init", "--quiet", str(repo)], check=True) + _git(repo, "commit", "--allow-empty", "--quiet", "-m", "fixture") + head = _git(repo, "rev-parse", "HEAD") + launches = tmp_path / "launches" + script = ("import json, sys; open(sys.argv[3], 'a').write('.'); open(sys.argv[1], 'w')" + ".write(json.dumps({'metrics': {'latency_ms': float(sys.argv[2])}}))") + gate = {"baseline_revision": head, "metric_key": "metrics.latency_ms", + "direction": "minimize", "metric_unit": "ms", "min_improvement_pct": 21} + (directory / "plan").mkdir() + record = directory / "plan" / "gate.yaml" + task_file = directory / "task.yaml" + + def write(frozen=(), **task): + record.write_text(yaml.safe_dump({"schema_version": 1, "acceptance": { + "reference": "https://example.com/issues/1", **gate, **dict(frozen)}}), + encoding="utf-8") + task_file.write_text(yaml.safe_dump({ + "schema_version": 1, + "optimization": {"repository": "repo", "model": "synthetic", "framework": "vllm", + "workload": "synthetic-v1", "objective": "Keep the frozen gate", + "plane": "harness"}, + "environment": { + "backend": "cpu", "repetitions": 1, "max_minutes": 5, + "baseline_command": [sys.executable, "-c", script, "{result}", "100", + str(launches)], + "candidate_command": [sys.executable, "-c", script, "{result}", "80", + str(launches)], + "quality_command": [sys.executable, "-c", "pass"], + }, + "acceptance": {"reference": "plan/gate.yaml", **gate, **task}, + }), encoding="utf-8") + + write(min_improvement_pct=0) + err = _exit(capsys, "run", "--task", str(task_file)) + assert "frozen gate mismatch: run --task needs" in err + assert (f"\nacceptance.min_improvement_pct: is 0.0 in the task but 21.0 in the frozen " + f"gate record {record}") in err + other = "0" * 40 + write({"baseline_revision": other}, baseline_revision=other) + err = _exit(capsys, "run", "--task", str(task_file)) + assert f"acceptance.baseline_revision {other!r} does not match the baseline" in err + assert f"checkout HEAD {head};" in err + assert not launches.exists() and list(caller.iterdir()) == [] + + write() + assert cli.main(["run", "--task", str(task_file)]) == 1 + run = Path(json.loads(capsys.readouterr().out)["run_dir"]) + assert launches.exists() + evaluation = json.loads((run / "evaluation.json").read_text(encoding="utf-8")) + assert evaluation["verdict"] == "FAIL" and evaluation["min_improvement_pct"] == 21.0 + assert evaluation["improvement_pct"] == pytest.approx(20.0) + frozen = json.loads((run / "frozen_gate.json").read_text(encoding="utf-8")) + assert frozen["status"] == "agrees" and frozen["reference"] == str(record) + + def test_flag_only_plan_and_run_keep_their_contract(tmp_path, caller, inspected, monkeypatch, capsys): for argv, missing in ((["plan"], REQUIRED), From 8116a65c7d57cbff871d623c2aec546b9013f453 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:34:19 +0800 Subject: [PATCH 4/6] docs: state that frozen gate agreement does not prove provenance The frozen gate check compares the task with the local record that acceptance.reference names. It does not authenticate that the record is the accepted one. The owner scope decision makes that provenance a caller/host precondition, so the plan/run contract now says so. - operations.md: the plan output defines `agrees` as content agreement only. The run inputs state that the caller/host must first establish that acceptance.reference names the accepted frozen gate record, and that InferRSI takes no expected digest. The run output states that the SHA-256 in frozen_gate.json is for citation. - task-input.md: replace "agrees with its accepted inputs" with content-consistency wording. Say that a task and record replaced together still give `agrees`, and that provenance is a caller/host precondition before run --task. The Agent workflow now has the Agent confirm, before run, that the reference names the accepted record. - task_input.frozen_gate docstring: the same limit, for Agents calling the Python helper. No behavior, interface or test changes. Agent-assisted-by: Claude Code / claude-opus-5-5 [effort=xhigh] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/operations.md | 6 +++--- docs/task-input.md | 27 ++++++++++++++++++--------- src/inferrsi/apps/cli/task_input.py | 4 ++++ 3 files changed, 25 insertions(+), 12 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 0a6e363ab..fb4c0b9b6 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -415,7 +415,7 @@ the same merge (see [use with plan and run](task-input.md#use-with-plan-and-run) - **Inputs:** repository/backend/device flags; `plan` takes the full experiment specification as flags, or a complete YAML task file with `--task ` plus explicit mapped overrides. - **Scope:** environment inspection and specification preview. -- **Output:** environment facts, or a preview of the RunSpec. With `--task`, the preview adds a `task` block equal to `task preview --json` for the same file and flags, and a `frozen_gate` block that reports whether the task's acceptance fields agree with the local frozen gate record named by `acceptance.reference`. +- **Output:** environment facts, or a preview of the RunSpec. With `--task`, the preview adds a `task` block equal to `task preview --json` for the same file and flags, and a `frozen_gate` block that reports whether the task's acceptance fields agree in content with the local frozen gate record named by `acceptance.reference`. `agrees` is content agreement only; it does not authenticate the record's provenance. - **Side effects:** `doctor` may invoke bounded read-only probes; `plan`/`--dry-run` persist nothing. - **Failure behavior:** unavailable devices or invalid flags are reported explicitly. With `--task`, task field errors, conflicting acceptance flags and blockers are printed by field to stderr, exit 2, before any probe. Without `--task`, `--baseline-command` and `--candidate-command` are required. - **Example:** `inferrsi doctor --repo . --repo-type vllm_omni --backend cpu` @@ -426,9 +426,9 @@ compatibility. ### Execute/inspect — `run`, `status`, `report` -- **Inputs:** the full experiment specification as flags or as a complete `--task ` (`run`); a run ID and output directory (`status`/`report`). +- **Inputs:** the full experiment specification as flags or as a complete `--task ` (`run`); a run ID and output directory (`status`/`report`). With `--task`, the caller/host must first establish that `acceptance.reference` names the accepted frozen gate record. InferRSI checks that the task and that local record agree in content (`agrees`); it does not authenticate the record's provenance and takes no expected digest. - **Scope:** caller-supplied benchmark, candidate and validation commands under the experiment contract. -- **Output:** a run ID and evidence directory; recorded progress; an HTML report. With `--task`, the run directory also holds `task.json`, the task preview, and `frozen_gate.json`, the gate result with the record's SHA-256. +- **Output:** a run ID and evidence directory; recorded progress; an HTML report. With `--task`, the run directory also holds `task.json`, the task preview, and `frozen_gate.json`, the gate result with the record's SHA-256 for citation in the acceptance issue. - **Side effects:** `run` executes the supplied commands and owns child-process cleanup; `report` writes HTML into the run directory. - **Failure behavior:** exit codes 0 PASS, 1 FAIL, 2 INCONCLUSIVE/input errors; cancellation is recorded. With `--task`, task field errors and blockers exit 2 before any probe. A task whose acceptance fields differ from the frozen gate record (`mismatch`), or whose gate cannot be checked (`unverified`: an HTTP(S) reference, a missing file, or a record that is not a schema v1 `acceptance` section stating the gate), also exits 2 before any probe; see [frozen gate record](task-input.md#frozen-gate-record). A baseline checkout `HEAD` that differs from `acceptance.baseline_revision` exits 2 after inspection. In all three cases no command starts and nothing is written. - **Example:** see [quickstart: real remote experiment](quickstart.md#real-remote-experiment) diff --git a/docs/task-input.md b/docs/task-input.md index 6eb4972e9..59f404df2 100644 --- a/docs/task-input.md +++ b/docs/task-input.md @@ -173,7 +173,9 @@ inferrsi run --task task.yaml # explicit execution `frozen_gate` block, the [frozen gate](#frozen-gate-record) result. They report a `mismatch` or `unverified` gate without failing. Without `--task` the output is unchanged. -- **`run`.** Execution checks that the task agrees with its accepted inputs. +- **`run`.** Execution checks that the task's content is consistent with the local + record it names and with the baseline checkout. It does not authenticate where the + record came from (see [frozen gate record](#frozen-gate-record)). Each check fails with exit 2 before any benchmark command starts or any run directory is written. - Before the environment probe, the task's acceptance fields must agree with the @@ -232,10 +234,15 @@ acceptance: is not a valid schema v1 document (a Markdown plan, for example), it has no `acceptance` section, or it omits a required gate field. -The check compares the record with the task. It does not establish that the -record itself is the accepted one; cite the record and its `sha256` from -`frozen_gate.json` in the acceptance issue. A `run --task` that passes this -check still follows the existing acceptance, frozen-gate and evidence rules. +`agrees` means content agreement only. The check compares the record the caller +points at with the task. It does not establish that the record is the accepted one, +and InferRSI takes no expected digest to compare it with. A task and record replaced +together with matching values still give `agrees`. Authenticating the record's +provenance, for example confirming that it is the frozen plan the acceptance issue +cites, is a caller/host precondition before `run --task`. `frozen_gate.json` keeps the +record's `sha256` so the acceptance issue can cite it and a reviewer can compare it +with the accepted record. A `run --task` that passes this check still follows the +existing acceptance, frozen-gate and evidence rules. ## CLI workflow @@ -288,15 +295,17 @@ An Agent uses the same installed CLI and the same machine-readable preview: 5. Use the reviewed task with the existing InferRSI operation the user authorizes, under the operation's own boundary in [operations](operations.md). For example, run `inferrsi plan --task `, then `inferrsi run --task ` - only after explicit authorization. + only after explicit authorization. Before `run`, confirm with the user or the + acceptance issue that `acceptance.reference` names the accepted frozen gate + record. InferRSI checks only that the two agree in content. The CLI and the Agent produce the same normalized task for the same file and flags. `tests/test_task_input.py` checks this by comparing `inferrsi task preview --json` with the Python `task_input.preview` on the shared complete fixture. `tests/test_task_plan_run.py` checks that `plan --task` gives the same `task` block, -and the expected RunSpec, for that fixture. An Agent checks a task against its frozen -gate record with the Python `task_input.frozen_gate`, the same check `run --task` -applies. +and the expected RunSpec, for that fixture. An Agent checks a task's content against +its frozen gate record with the Python `task_input.frozen_gate`, the same check +`run --task` applies. ## Compatibility with other task formats diff --git a/src/inferrsi/apps/cli/task_input.py b/src/inferrsi/apps/cli/task_input.py index 0f7c7c2d0..7c7542d7e 100644 --- a/src/inferrsi/apps/cli/task_input.py +++ b/src/inferrsi/apps/cli/task_input.py @@ -621,6 +621,10 @@ def frozen_gate(task: dict, task_file: str | os.PathLike) -> dict: equal the record's. Only that file is read. An HTTP(S) reference is never fetched, so its gate stays unverified. Returns the reference, the record's SHA-256, ``status`` (``agrees``, ``mismatch`` or ``unverified``) and field-level ``problems``. + + ``agrees`` is content agreement only. This does not authenticate that the record is + the accepted one; that provenance is a caller/host precondition, and the SHA-256 is + kept for citation, not compared with an expected digest. """ reference = task["acceptance"]["reference"] result: dict[str, Any] = { From d59b899ae52e5086a95632991b068f2b6af0d9ce Mon Sep 17 00:00:00 2001 From: zengchuang-hw Date: Mon, 23 Nov 2026 00:21:03 +0800 Subject: [PATCH 5/6] Bind task baseline pins to execution snapshots before trials Carry the frozen baseline in RunSpec.revision, verify captured execution snapshots, and reject local task specifications before environment probes. Preserve flags-only defaults and legacy port signatures. Agent-assisted-by: Codex (author) Signed-off-by: zengchuang-hw --- docs/operations.md | 7 ++ docs/task-input.md | 16 +++-- src/inferrsi/apps/cli/__init__.py | 15 ++-- src/inferrsi/apps/cli/arguments.py | 1 + src/inferrsi/apps/cli/task_input.py | 6 +- src/inferrsi/contracts/runspec.py | 11 +++ src/inferrsi/harness/runner.py | 14 ++++ tests/test_task_plan_run.py | 103 +++++++++++++++++++++++++++- 8 files changed, 155 insertions(+), 18 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index fb4c0b9b6..f0090f320 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -431,6 +431,13 @@ compatibility. - **Output:** a run ID and evidence directory; recorded progress; an HTML report. With `--task`, the run directory also holds `task.json`, the task preview, and `frozen_gate.json`, the gate result with the record's SHA-256 for citation in the acceptance issue. - **Side effects:** `run` executes the supplied commands and owns child-process cleanup; `report` writes HTML into the run directory. - **Failure behavior:** exit codes 0 PASS, 1 FAIL, 2 INCONCLUSIVE/input errors; cancellation is recorded. With `--task`, task field errors and blockers exit 2 before any probe. A task whose acceptance fields differ from the frozen gate record (`mismatch`), or whose gate cannot be checked (`unverified`: an HTTP(S) reference, a missing file, or a record that is not a schema v1 `acceptance` section stating the gate), also exits 2 before any probe; see [frozen gate record](task-input.md#frozen-gate-record). A baseline checkout `HEAD` that differs from `acceptance.baseline_revision` exits 2 after inspection. In all three cases no command starts and nothing is written. + +Task-mode RunSpec validation, including local candidate-directory checks, runs before +environment probes. The frozen baseline also binds the execution through the existing +`RunSpec.revision` field: Harness compares the actual initial and pre-trial baseline +snapshots, rather than relying only on the earlier environment observation. A later +checkout mismatch starts no trial from that snapshot and leaves the failed diagnostic +run as `INCONCLUSIVE` with its source/error facts retained. - **Example:** see [quickstart: real remote experiment](quickstart.md#real-remote-experiment) Operation success, recorded execution state and the experiment verdict are diff --git a/docs/task-input.md b/docs/task-input.md index 59f404df2..27c1098c3 100644 --- a/docs/task-input.md +++ b/docs/task-input.md @@ -163,6 +163,8 @@ inferrsi run --task task.yaml # explicit execution `error acceptance.metric_key (cli): ...` or `blocker environment.repetitions: missing; required for plan/run`. The command then exits with 2 before any environment probe, task command or file write. + The RunSpec's local directory/path checks also run before environment probes, + including the optional candidate checkout. - **Defaults for omitted optional fields.** An omitted `environment.python` uses the interpreter running InferRSI. An omitted `optimization.candidate_repository` uses the baseline checkout. An omitted `environment.quality_command` leaves the run @@ -176,22 +178,28 @@ inferrsi run --task task.yaml # explicit execution - **`run`.** Execution checks that the task's content is consistent with the local record it names and with the baseline checkout. It does not authenticate where the record came from (see [frozen gate record](#frozen-gate-record)). - Each check fails with exit 2 before any benchmark command starts or any run - directory is written. + The input, gate and inspection checks fail with exit 2 before any benchmark + command starts or any run directory is written. - Before the environment probe, the task's acceptance fields must agree with the [frozen gate record](#frozen-gate-record) that `acceptance.reference` names. A `mismatch` or `unverified` gate prints each problem by field to stderr. - After inspection, the baseline checkout's `HEAD` must equal `acceptance.baseline_revision`. A hexadecimal prefix of at least 7 characters is also accepted. + - The declared baseline is also carried in the existing `RunSpec.revision` field. + Harness checks it against the initial execution snapshot and each fresh snapshot + of the baseline source before a trial. A checkout switched after inspection + cannot run from a mismatching snapshot. This later refusal retains a failed + diagnostic run with `INCONCLUSIVE`; it does not discard already recorded facts. The run directory then holds `task.json`, the task preview, and `frozen_gate.json`, the gate result with the record's SHA-256, next to `args.json`. `args.json` records the effective values and the absolute `task_file`. -RunSpec carries the experiment fields. `optimization.objective`, +RunSpec carries the experiment fields, including the frozen baseline revision. +`optimization.objective`, `optimization.plane`, `environment.rounds`, `acceptance.reference`, -`acceptance.baseline_revision` and `acceptance.constraints` have no RunSpec field. +and `acceptance.constraints` have no RunSpec field. They are recorded in the `task` block and in `task.json`. Without `--task`, `--baseline-command` and `--candidate-command` remain required, with the same argparse error and exit 2. diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index 0685ce4ba..9fb0ef2eb 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -4,12 +4,12 @@ import json import os -import re import sqlite3 import sys from importlib.resources import files from pathlib import Path +from ...contracts.runspec import revision_matches as _revision_matches from ...knowledge.catalog import get_knowledge, search_knowledge from ...knowledge.knowledge_operations import KnowledgeReader from ...knowledge.research import research_knowledge @@ -376,14 +376,6 @@ def _plan_run_task(command, args, supplied) -> dict | None: return result -def _revision_matches(head: str, revision: str) -> bool: - if head == revision: - return True - return bool(head) and re.fullmatch(r"[0-9a-fA-F]{7,}", revision) is not None and ( - head.lower().startswith(revision.lower()) - ) - - def _check_frozen_gate(gate: dict) -> None: """Require a run's task to agree with the frozen gate record it references.""" if gate["status"] != "agrees": @@ -840,6 +832,8 @@ def main(argv: list[str] | None = None) -> int: _print({"record": str(path)}) return 0 + # Task-local errors must be rejected before running even read-only probes. + spec = make_spec(args) if task is not None else None gate = None if task is not None: from .task_input import frozen_gate @@ -865,7 +859,8 @@ def main(argv: list[str] | None = None) -> int: ].get("environment") return 0 if available and known else 1 - spec = make_spec(args) + if spec is None: + spec = make_spec(args) if args.command == "plan" or args.dry_run: preview = { "run_spec": spec.to_dict(), diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index 815456cb1..578761171 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -791,6 +791,7 @@ def command(value: str | list[str] | tuple[str, ...] | None) -> tuple[str, ...] spec = RunSpec( repo=str(Path(args.repo).resolve()), + revision=getattr(args, "revision", ""), candidate_repo=str(Path(args.candidate_repo).resolve()) if args.candidate_repo else None, repo_type=args.repo_type, backend=args.backend, diff --git a/src/inferrsi/apps/cli/task_input.py b/src/inferrsi/apps/cli/task_input.py index 7c7542d7e..7f5b3f8c0 100644 --- a/src/inferrsi/apps/cli/task_input.py +++ b/src/inferrsi/apps/cli/task_input.py @@ -581,8 +581,9 @@ def arguments_from(task: dict) -> dict[str, Any]: """Return {argparse dest: value} for every mapped field of a complete preview task. Device IDs are joined with ``,`` (a task ID cannot contain one); commands and trial - checks are copied as lists. A missing optional value stays None, including - ``environment.python``, which the caller replaces with its own interpreter. + checks are copied as lists. The frozen baseline is carried in RunSpec's existing + ``revision`` field, without adding a CLI override. A missing optional value stays + None, including ``environment.python``, which the caller replaces with its interpreter. """ values: dict[str, Any] = {} for field in FIELDS: @@ -594,6 +595,7 @@ def arguments_from(task: dict) -> dict[str, Any]: elif isinstance(value, list): value = list(value) values[field.dest] = value + values["revision"] = task["acceptance"]["baseline_revision"] return values diff --git a/src/inferrsi/contracts/runspec.py b/src/inferrsi/contracts/runspec.py index 161408204..330fa9b88 100644 --- a/src/inferrsi/contracts/runspec.py +++ b/src/inferrsi/contracts/runspec.py @@ -1,10 +1,21 @@ """Immutable CLI contracts; no accelerator or Agent runtime dependencies.""" import math +import re from dataclasses import asdict, dataclass from pathlib import Path +def revision_matches(head: object, revision: object) -> bool: + """Match an observed Git HEAD to a fixed revision or a hexadecimal prefix.""" + if not isinstance(head, str) or not isinstance(revision, str) or not head: + return False + return head == revision or ( + re.fullmatch(r"[0-9a-fA-F]{7,}", revision) is not None + and head.lower().startswith(revision.lower()) + ) + + @dataclass(frozen=True) class RunSpec: repo: str diff --git a/src/inferrsi/harness/runner.py b/src/inferrsi/harness/runner.py index ba93f4940..ca1493697 100644 --- a/src/inferrsi/harness/runner.py +++ b/src/inferrsi/harness/runner.py @@ -9,6 +9,7 @@ from pathlib import Path from ..contracts import RunSpec +from ..contracts.runspec import revision_matches from .atomic_json import atomic_write_json as _write_json from .trials.external import collect_trial_checks @@ -68,10 +69,22 @@ def record_status(phase: str, **fields: object) -> None: "candidate": Path(spec.candidate_repo or spec.repo).resolve(), } + def check_baseline_revision(identity: dict) -> None: + if spec.revision and ( + not identity.get("available") + or not revision_matches(identity.get("head"), spec.revision) + ): + raise ValueError( + f"Baseline snapshot does not match RunSpec.revision {spec.revision!r}: " + f"HEAD={identity.get('head')!r}, available={identity.get('available')!r}" + ) + def execute_checked( command: tuple[str, ...], label: str, trial_dir: Path, metric_key: str | None ) -> dict: source_before = snapshot(repos[label], run_dir) + if repos[label] == repos["baseline"]: + check_baseline_revision(source_before) record = execute(command, repos[label], trial_dir, deadline, metric_key) if metric_key is not None and spec.required_trial_checks: record["trial_checks"] = collect_trial_checks(record, spec.required_trial_checks) @@ -164,6 +177,7 @@ def terminate() -> None: event("source_snapshot") before = {label: snapshot(repo, run_dir) for label, repo in repos.items()} _write_json(run_dir / "repositories.lock.json", before) + check_baseline_revision(before["baseline"]) commands = {"baseline": spec.baseline_command, "candidate": spec.candidate_command} for index in range(spec.repetitions): for label in ("baseline", "candidate") if index % 2 == 0 else ("candidate", "baseline"): diff --git a/tests/test_task_plan_run.py b/tests/test_task_plan_run.py index 7fff04ae3..db1bfef7d 100644 --- a/tests/test_task_plan_run.py +++ b/tests/test_task_plan_run.py @@ -8,6 +8,7 @@ import shutil import subprocess import sys +from dataclasses import replace from pathlib import Path import pytest @@ -125,6 +126,7 @@ def _exit(capsys, *argv: str) -> str: def _expected_spec(directory: Path, caller: Path, **changes) -> dict: values = dict( repo=str((directory / "repo").resolve()), + revision="", candidate_repo=str((directory / "candidate").resolve()), repo_type="vllm", backend="cuda", @@ -424,7 +426,7 @@ def test_run_with_an_agreeing_task_reaches_the_experiment_and_records_the_task( out = json.loads(capsys.readouterr().out) directory = Path(out["run_dir"]) assert [json.loads(json.dumps(spec.to_dict())) for spec in specs] == [ - _expected_spec(task_file.parent, caller, repetitions=7) + _expected_spec(task_file.parent, caller, repetitions=7, revision=revision) ] recorded = json.loads((directory / "task.json").read_text(encoding="utf-8")) assert recorded == task_input.preview(task_file, {"repetitions": 7}, cwd=str(caller)) @@ -519,6 +521,101 @@ def write(frozen=(), **task): assert frozen["status"] == "agrees" and frozen["reference"] == str(record) +@pytest.mark.parametrize("command", [("plan",), ("run",), ("run", "--dry-run")]) +def test_missing_candidate_directory_refuses_before_any_probe( + tmp_path, caller, monkeypatch, capsys, command, +): + task_file = _agreeing(tmp_path, replace=( + ("candidate_repository: candidate", "candidate_repository: missing-candidate"), + )) + before = _tree(tmp_path) + _forbid(monkeypatch, *_FORBIDDEN) + error = _exit(capsys, *command, "--task", str(task_file)) + assert "candidate_repo must be an existing directory" in error + assert _tree(tmp_path) == before + + +@pytest.mark.parametrize("switch_at", ["after_inspection", "before_trial"]) +@pytest.mark.parametrize("short_revision", [False, True]) +def test_task_revision_is_bound_to_real_execution_snapshots( + tmp_path, caller, monkeypatch, capsys, switch_at, short_revision, +): + """Only the race is scheduled; Git, inspection, snapshots and runner are real.""" + repo = tmp_path / "repo" + repo.mkdir() + subprocess.run(["git", "init", "--quiet", str(repo)], check=True) + _git(repo, "config", "core.hooksPath", str(tmp_path / "no-hooks")) + (repo / "metric.txt").write_text("100\n", encoding="utf-8") + _git(repo, "add", "metric.txt") + _git(repo, "commit", "--quiet", "-m", "accepted baseline") + accepted = _git(repo, "rev-parse", "HEAD") + (repo / "metric.txt").write_text("200\n", encoding="utf-8") + _git(repo, "commit", "--quiet", "-am", "different baseline") + changed = _git(repo, "rev-parse", "HEAD") + _git(repo, "checkout", "--quiet", accepted) + revision = accepted[:8].upper() if short_revision else accepted + launches = tmp_path / "launches" + script = ( + "import json,sys; from pathlib import Path; " + "Path(sys.argv[2]).open('a').write('.'); " + "value=float(Path('metric.txt').read_text()) if sys.argv[3]=='baseline' else 80; " + "Path(sys.argv[1]).write_text(json.dumps({'metrics':{'latency_ms':value}}))" + ) + record = tmp_path / "gate.yaml" + gate = {"baseline_revision": revision, "metric_key": "metrics.latency_ms", + "direction": "minimize", "metric_unit": "ms", "min_improvement_pct": 30} + record.write_text(yaml.safe_dump({"schema_version": 1, "acceptance": gate}), + encoding="utf-8") + task_file = tmp_path / "task.yaml" + task_file.write_text(yaml.safe_dump({ + "schema_version": 1, + "optimization": {"repository": "repo", "model": "synthetic", "framework": "vllm", + "workload": "snapshot-race", "objective": "Bind the accepted source", + "plane": "harness"}, + "environment": {"backend": "cpu", "python": sys.executable, + "baseline_command": [sys.executable, "-c", script, "{result}", + str(launches), "baseline"], + "candidate_command": [sys.executable, "-c", script, "{result}", + str(launches), "candidate"], + "quality_command": [sys.executable, "-c", "pass"], + "repetitions": 1, "max_minutes": 1}, + "acceptance": {"reference": "gate.yaml", **gate}, + }), encoding="utf-8") + if switch_at == "after_inspection": + inspect = cli.inspect_environment + + def inspection(*args, **kwargs): + environment = inspect(*args, **kwargs) + assert environment["repository"]["head"] == accepted + _git(repo, "checkout", "--quiet", changed) + return environment + + monkeypatch.setattr(cli, "inspect_environment", inspection) + else: + snapshot = legacy_run.repository_identity + calls = [] + + def capture(path, exclude=None): + identity = snapshot(path, exclude) + calls.append(identity) + if len(calls) == 2: # Both initial identities were captured, before the first trial. + _git(repo, "checkout", "--quiet", changed) + return identity + + monkeypatch.setattr(legacy_run, "repository_identity", capture) + + assert cli.main(["run", "--task", str(task_file)]) == 2 + output = json.loads(capsys.readouterr().out) + assert not launches.exists() + assert output["status"]["state"] == "failed" + assert output["status"]["verdict"] == "INCONCLUSIVE" + assert "RunSpec.revision" in output["status"]["error"] + directory = Path(output["run_dir"]) + locked = json.loads((directory / "run.lock.json").read_text(encoding="utf-8")) + assert locked["revision"] == revision + assert not list(directory.glob("*/trial-*/execution.json")) + + def test_flag_only_plan_and_run_keep_their_contract(tmp_path, caller, inspected, monkeypatch, capsys): for argv, missing in ((["plan"], REQUIRED), @@ -581,4 +678,6 @@ def test_arguments_from_a_preview_feed_make_spec_like_the_equivalent_flags(tmp_p "--min-improvement-pct", "2.5", "--max-minutes", "90", "--workload-id", "fixed-prompts-v1", "--model", "", "--model-revision", "", ]) - assert arguments.make_spec(args) == arguments.make_spec(flags) + spec = arguments.make_spec(args) + assert spec.revision == "" + assert replace(spec, revision="") == arguments.make_spec(flags) From ba07f95b55bceb12099bb1d9ac2e56f463e5b5ba Mon Sep 17 00:00:00 2001 From: zengchuang-hw Date: Mon, 23 Nov 2026 00:33:20 +0800 Subject: [PATCH 6/6] Bind task runs to the inspected source fingerprint Use RunSpec.snapshot_id to reject working-tree changes even when Git HEAD stays fixed, retaining diagnostics without starting a mismatching trial. Agent-assisted-by: Codex (author) Signed-off-by: zengchuang-hw --- docs/operations.md | 5 +++-- docs/task-input.md | 6 ++++-- src/inferrsi/apps/cli/__init__.py | 5 +++++ src/inferrsi/harness/runner.py | 7 +++++++ tests/test_task_plan_run.py | 24 ++++++++++++++++++------ 5 files changed, 37 insertions(+), 10 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index f0090f320..f5c2ce63e 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -434,8 +434,9 @@ compatibility. Task-mode RunSpec validation, including local candidate-directory checks, runs before environment probes. The frozen baseline also binds the execution through the existing -`RunSpec.revision` field: Harness compares the actual initial and pre-trial baseline -snapshots, rather than relying only on the earlier environment observation. A later +`RunSpec.revision` field, while the observed source identity binds the existing +`RunSpec.snapshot_id`: Harness compares the actual initial and pre-trial baseline +snapshots, including working-tree changes, with those pins. A later checkout mismatch starts no trial from that snapshot and leaves the failed diagnostic run as `INCONCLUSIVE` with its source/error facts retained. - **Example:** see [quickstart: real remote experiment](quickstart.md#real-remote-experiment) diff --git a/docs/task-input.md b/docs/task-input.md index 27c1098c3..07ae503e3 100644 --- a/docs/task-input.md +++ b/docs/task-input.md @@ -187,8 +187,10 @@ inferrsi run --task task.yaml # explicit execution `acceptance.baseline_revision`. A hexadecimal prefix of at least 7 characters is also accepted. - The declared baseline is also carried in the existing `RunSpec.revision` field. - Harness checks it against the initial execution snapshot and each fresh snapshot - of the baseline source before a trial. A checkout switched after inspection + The source identity observed during inspection binds `RunSpec.snapshot_id`, + including tracked/untracked changes and submodules. Harness checks both pins + against the initial execution snapshot and each fresh snapshot of the baseline + source before a trial. A checkout or working tree changed after inspection cannot run from a mismatching snapshot. This later refusal retains a failed diagnostic run with `INCONCLUSIVE`; it does not discard already recorded facts. diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index 9fb0ef2eb..1c7cbc32e 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -6,6 +6,7 @@ import os import sqlite3 import sys +from dataclasses import replace from importlib.resources import files from pathlib import Path @@ -883,6 +884,10 @@ def main(argv: list[str] | None = None) -> int: raise ValueError("Target Python inspection failed") if task is not None: _check_baseline_revision(task, environment) + snapshot_id = environment["repository"].get("snapshot_hash") + if not isinstance(snapshot_id, str) or not snapshot_id: + raise ValueError("Baseline inspection did not yield a source snapshot identity") + spec = replace(spec, snapshot_id=snapshot_id) # The old run loads its Benchmark gates. Import it here so that the # other commands, including ordinary optimization, never load Benchmark. diff --git a/src/inferrsi/harness/runner.py b/src/inferrsi/harness/runner.py index ca1493697..d4f9de576 100644 --- a/src/inferrsi/harness/runner.py +++ b/src/inferrsi/harness/runner.py @@ -78,6 +78,13 @@ def check_baseline_revision(identity: dict) -> None: f"Baseline snapshot does not match RunSpec.revision {spec.revision!r}: " f"HEAD={identity.get('head')!r}, available={identity.get('available')!r}" ) + if spec.snapshot_id and ( + not identity.get("available") or identity.get("snapshot_hash") != spec.snapshot_id + ): + raise ValueError( + f"Baseline snapshot does not match RunSpec.snapshot_id {spec.snapshot_id!r}: " + f"snapshot_hash={identity.get('snapshot_hash')!r}" + ) def execute_checked( command: tuple[str, ...], label: str, trial_dir: Path, metric_key: str | None diff --git a/tests/test_task_plan_run.py b/tests/test_task_plan_run.py index db1bfef7d..4ae716125 100644 --- a/tests/test_task_plan_run.py +++ b/tests/test_task_plan_run.py @@ -82,7 +82,7 @@ def caller(tmp_path, monkeypatch) -> Path: def _environment(head: str = HEAD) -> dict: return { - "repository": {"available": True, "head": head}, + "repository": {"available": True, "head": head, "snapshot_hash": "f" * 64}, "device": {"status": "available", "selection_verified": True}, "target_python": {"environment": {"python": "stub"}}, } @@ -426,7 +426,8 @@ def test_run_with_an_agreeing_task_reaches_the_experiment_and_records_the_task( out = json.loads(capsys.readouterr().out) directory = Path(out["run_dir"]) assert [json.loads(json.dumps(spec.to_dict())) for spec in specs] == [ - _expected_spec(task_file.parent, caller, repetitions=7, revision=revision) + _expected_spec(task_file.parent, caller, repetitions=7, revision=revision, + snapshot_id="f" * 64) ] recorded = json.loads((directory / "task.json").read_text(encoding="utf-8")) assert recorded == task_input.preview(task_file, {"repetitions": 7}, cwd=str(caller)) @@ -537,8 +538,9 @@ def test_missing_candidate_directory_refuses_before_any_probe( @pytest.mark.parametrize("switch_at", ["after_inspection", "before_trial"]) @pytest.mark.parametrize("short_revision", [False, True]) +@pytest.mark.parametrize("source_change", ["checkout", "working-tree"]) def test_task_revision_is_bound_to_real_execution_snapshots( - tmp_path, caller, monkeypatch, capsys, switch_at, short_revision, + tmp_path, caller, monkeypatch, capsys, switch_at, short_revision, source_change, ): """Only the race is scheduled; Git, inspection, snapshots and runner are real.""" repo = tmp_path / "repo" @@ -581,13 +583,20 @@ def test_task_revision_is_bound_to_real_execution_snapshots( "repetitions": 1, "max_minutes": 1}, "acceptance": {"reference": "gate.yaml", **gate}, }), encoding="utf-8") + + def change_source(): + if source_change == "checkout": + _git(repo, "checkout", "--quiet", changed) + else: + (repo / "metric.txt").write_text("200\n", encoding="utf-8") + if switch_at == "after_inspection": inspect = cli.inspect_environment def inspection(*args, **kwargs): environment = inspect(*args, **kwargs) assert environment["repository"]["head"] == accepted - _git(repo, "checkout", "--quiet", changed) + change_source() return environment monkeypatch.setattr(cli, "inspect_environment", inspection) @@ -599,7 +608,7 @@ def capture(path, exclude=None): identity = snapshot(path, exclude) calls.append(identity) if len(calls) == 2: # Both initial identities were captured, before the first trial. - _git(repo, "checkout", "--quiet", changed) + change_source() return identity monkeypatch.setattr(legacy_run, "repository_identity", capture) @@ -609,10 +618,13 @@ def capture(path, exclude=None): assert not launches.exists() assert output["status"]["state"] == "failed" assert output["status"]["verdict"] == "INCONCLUSIVE" - assert "RunSpec.revision" in output["status"]["error"] + pin = "revision" if source_change == "checkout" else "snapshot_id" + assert f"RunSpec.{pin}" in output["status"]["error"] directory = Path(output["run_dir"]) locked = json.loads((directory / "run.lock.json").read_text(encoding="utf-8")) assert locked["revision"] == revision + inspected = json.loads((directory / "environment.json").read_text(encoding="utf-8")) + assert locked["snapshot_id"] == inspected["repository"]["snapshot_hash"] assert not list(directory.glob("*/trial-*/execution.json"))