From 774904d7741e680368d78089eca081fc2bb45e44 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:42:27 +0800 Subject: [PATCH 1/6] feat(benchmark): add dual-model Behavior Constraint x Efficiency M1-M3 microbench suite Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- benchmark/README.md | 2 + benchmark/microbench/README.md | 52 + benchmark/microbench/__init__.py | 59 + benchmark/microbench/metrics.py | 295 ++++ benchmark/microbench/models.py | 667 ++++++++ benchmark/microbench/run.py | 193 +++ benchmark/microbench/scenarios.py | 1356 +++++++++++++++++ benchmark/microbench/tier0.py | 340 +++++ benchmark/microbench/tier1.py | 548 +++++++ benchmark/tests/test_dual_model_microbench.py | 434 ++++++ .../benchmark-dual-model-microbench-smoke.py | 144 ++ 11 files changed, 4090 insertions(+) create mode 100644 benchmark/microbench/README.md create mode 100644 benchmark/microbench/__init__.py create mode 100644 benchmark/microbench/metrics.py create mode 100644 benchmark/microbench/models.py create mode 100644 benchmark/microbench/run.py create mode 100644 benchmark/microbench/scenarios.py create mode 100644 benchmark/microbench/tier0.py create mode 100644 benchmark/microbench/tier1.py create mode 100644 benchmark/tests/test_dual_model_microbench.py create mode 100644 examples/benchmark-dual-model-microbench-smoke.py diff --git a/benchmark/README.md b/benchmark/README.md index c07716a9c3..89ca5fe467 100644 --- a/benchmark/README.md +++ b/benchmark/README.md @@ -58,6 +58,8 @@ helper delivery neither launches trials nor changes frozen historical arms. ## Current work +- [Dual-Model `Behavior Constraint × Efficiency` Microbenchmark (M1/M2/M3)](microbench/README.md) provides a bounded Tier-0 (`<15s` deterministic differential) and Tier-1 (1–3m Base vs Head `Codex GPT` + `DeepSeek V4.1 Flash` suite) for M1 scoped envelope recovery (`#9498`/`#9504`), M2 Stage-then-Swap / semantic-unit fold (`#9503`), and M3 basic claim/block/settle invariants, keeping long-horizon M4/M5 studies in `edgebench/`. + - [Compare a local proxy with released scores](../docs/reference/benchmark-behavior-findings.md#compare-a-local-proxy-with-released-scores) covers source matching, missing feedback and the later-submission control for an offline study. - [FrontierCS-2 compatibility repair v2](frontiercs2/README.md) provides an opt-in diff --git a/benchmark/microbench/README.md b/benchmark/microbench/README.md new file mode 100644 index 0000000000..20f33bd43c --- /dev/null +++ b/benchmark/microbench/README.md @@ -0,0 +1,52 @@ +# Dual-Model `Behavior Constraint × Efficiency` Microbenchmark (M1/M2/M3) + +This suite measures whether control-plane efficiency optimizations preserve strict behavioral constraints across two real host/model paths: + +- **Codex GPT** (`benchmark/runtime/codex.py` isolated settings/environment + `loopx.control_plane.quota.codex_session_usage.read_codex_session_usage` + `benchmark/runtime/session_observation.py` + optional Harbor `BenchmarkCodex._totals` telemetry), and +- **DeepSeek V4.1 Flash** (`deepseek-v4-1-flash-260910` via Ark `DoubaoExecToolClient` + `_direct_ark_transport` in `loopx/control_plane/testing/`). + +## Scope Boundary (Strictly Disjoint From M4/M5) + +- **Owns (M1/M2/M3):** + - **M1 (`m1_envelope_scoped_recovery`):** Scoped Turn envelope & progressive recovery (`#9498`/`#9504`): selects runnable work (`todo_selected_work`), preserves blocked P0 (`todo_primary_blocked`) in `blocked_priority_fallback`, resolves pointer readback (`quota context-read --select`) cleanly, and measures delivered wire bytes + verifiable `o200k_base` prompt tokens. + - **M2 (`m2_epoch_prefetch_semantic_fold`):** Stage-then-Swap Epoch Prefetch & Semantic-Unit Fold (`#9503`): verifies net-positive folding (`EpochReset` / `FoldToReceipt`) retains all `failure_facts` and `open_obligations` while failing closed to `KeepRaw` on negative token savings or missing completion receipts. + - **M3 (`m3_claim_block_settle_invariants`):** Basic claim, gate, and settle invariants: blocking `user_gate` refuses delivery/spend; single-owner `todo claim` rejects competing peer steals; C1 settlement spends at most once and stays idempotent on replay. +- **Excludes (M4/M5):** Long-horizon multi-task FrontierCS-2 BLC (5h), multi-wake SForge FFmpeg trials, H1C / H2 cliff-guard evaluations, and online judge containers in [`../edgebench/README.md`](../edgebench/README.md). + +## Running Locally + +### Tier-0 (`<15s` deterministic differential) + +```bash +uv run --extra test python -m benchmark.microbench.run --tier 0 --format markdown +``` + +Optional cross-revision check against an ancestor commit (reusing `cli-output-base-head-differential-smoke.py` Base checkout helpers): + +```bash +uv run --extra test python -m benchmark.microbench.run --tier 0 --base-ref --format markdown +``` + +Public offline smoke (covers Tier-0 + stubbed Tier-1 conformance with zero API calls): + +```bash +uv run --extra test python examples/benchmark-dual-model-microbench-smoke.py +``` + +### Tier-1 (bounded 1–3m Base vs Head dual-model) + +Live provider execution requires explicit `--live` opt-in and isolated operator credentials (`ARK_API_KEY` for Ark `deepseek-v4-1-flash-260910`, plus `OPENAI_BASE_URL`+`OPENAI_API_KEY` or `CODEX_AUTH_JSON_PATH` for Codex GPT): + +```bash +uv run --extra test python -m benchmark.microbench.run \ + --tier 1 \ + --live \ + --max-total-seconds 180 \ + --format markdown +``` + +## Public-Safety & Measurement Rules + +- All fixtures live inside disposable temporary directories created per run. +- Credentials, local home paths, raw prompts, and raw provider responses are never serialized into emitted receipts or tests (`assert_public_safe_payload`). +- Missing model usage counters remain `null` (`None`), never `0`; byte reductions cannot mask behavior constraint failures (`behavior_preserved` requires all constraint checks to pass). diff --git a/benchmark/microbench/__init__.py b/benchmark/microbench/__init__.py new file mode 100644 index 0000000000..5016f0cc36 --- /dev/null +++ b/benchmark/microbench/__init__.py @@ -0,0 +1,59 @@ +"""Dual-Model Behavior Constraint x Efficiency Microbenchmark Suite (M1/M2/M3). + +Scope boundary: owns bounded Tier-0 (<15s deterministic differential) and +Tier-1 (1-3m Base vs Head dual-model scenarios: Codex GPT + DeepSeek V4.1 +Flash ``deepseek-v4-1-flash-260910``) across M1 (#9498/#9504 envelope/recovery), +M2 (#9503 epoch prefetch / semantic-unit fold gate), and M3 (basic +claim/block/settle invariants). Long-horizon M4/M5 studies remain in +``benchmark/edgebench/``. +""" + +from __future__ import annotations + +from .metrics import ( + MICROBENCH_DIFF_SCHEMA_VERSION, + MICROBENCH_RECEIPT_SCHEMA_VERSION, + BehaviorConstraintResult, + EfficiencyMetrics, + assert_public_safe_payload, + collect_codex_rollout_metrics, + compare_base_vs_head_efficiency, + measure_text_tokens, +) +from .models import ( + DEFAULT_ARK_FLASH_MODEL, + DEFAULT_CODEX_MODEL, +) +from .scenarios import ( + MICROBENCH_SCENARIO_IDS, + prepare_m1_fixture, + prepare_m2_fixture, + prepare_m3_fixture, + run_m1_deterministic_arm, + run_m2_deterministic_arm, + run_m3_deterministic_arm, +) +from .tier0 import run_tier0_differential +from .tier1 import run_tier1_dual_model_suite + +__all__ = [ + "BehaviorConstraintResult", + "DEFAULT_ARK_FLASH_MODEL", + "DEFAULT_CODEX_MODEL", + "EfficiencyMetrics", + "MICROBENCH_DIFF_SCHEMA_VERSION", + "MICROBENCH_RECEIPT_SCHEMA_VERSION", + "MICROBENCH_SCENARIO_IDS", + "assert_public_safe_payload", + "collect_codex_rollout_metrics", + "compare_base_vs_head_efficiency", + "measure_text_tokens", + "prepare_m1_fixture", + "prepare_m2_fixture", + "prepare_m3_fixture", + "run_m1_deterministic_arm", + "run_m2_deterministic_arm", + "run_m3_deterministic_arm", + "run_tier0_differential", + "run_tier1_dual_model_suite", +] diff --git a/benchmark/microbench/metrics.py b/benchmark/microbench/metrics.py new file mode 100644 index 0000000000..6211293628 --- /dev/null +++ b/benchmark/microbench/metrics.py @@ -0,0 +1,295 @@ +"""Shared telemetry, rollout metric extraction, and Base/Head comparison.""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import asdict, dataclass, field +import json +import math +from pathlib import Path +import re + +from benchmark.runtime.session_observation import ( + CodexSessionObservationError, + observe_codex_session_tail, +) +from loopx.control_plane.quota.codex_session_usage import ( + CodexSessionUsageError, + read_codex_session_usage, +) +from loopx.control_plane.runtime.public_safety import ( + LOCAL_PATH_SURFACE_PATTERN, + SECRET_LIKE_SURFACE_PATTERN, +) +from loopx.control_plane.turn_driver.epoch_prefetch import ( + DEFAULT_TOKENIZER_ENCODING, + count_verifiable_tokens, +) + +MICROBENCH_RECEIPT_SCHEMA_VERSION = "loopx_microbench_receipt_v0" +MICROBENCH_DIFF_SCHEMA_VERSION = "loopx_microbench_differential_v0" + +_EXTRA_SECRET_RE = re.compile( + r"(?:sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{16,}|Bearer\s+[A-Za-z0-9._-]{12,})" +) +_USER_HOME_RE = re.compile(r"(?:/Users/|/home/|C:\\Users\\)[^\s\"',;]+") + + +@dataclass(frozen=True) +class BehaviorConstraintResult: + """Typed outcome of all required M1/M2/M3 behavior constraints for an arm.""" + + passed: bool + checks: dict[str, bool] = field(default_factory=dict) + violations: tuple[str, ...] = () + + @property + def pass_rate(self) -> float: + if not self.checks: + return 1.0 if self.passed else 0.0 + ok = sum(1 for value in self.checks.values() if value) + return round(ok / len(self.checks), 4) + + def to_dict(self) -> dict[str, object]: + return { + "passed": self.passed, + "pass_rate": self.pass_rate, + "checks": dict(self.checks), + "violations": list(self.violations), + } + + +@dataclass(frozen=True) +class EfficiencyMetrics: + """Explicit token, wire-byte, turn, and latency metrics (None = unknown).""" + + wire_bytes: int | None = None + prompt_tokens: int | None = None + cached_tokens: int | None = None + completion_tokens: int | None = None + reasoning_tokens: int | None = None + total_tokens: int | None = None + tool_calls: int | None = None + round_trips: int | None = None + wall_seconds: float | None = None + + def to_dict(self) -> dict[str, int | float | None]: + return asdict(self) + + +def measure_text_tokens( + text: str, + *, + encoding_name: str = DEFAULT_TOKENIZER_ENCODING, +) -> tuple[int | None, dict[str, object] | None]: + """Delegate verifiable prompt token counting to LoopX's shared tokenizer owner.""" + counted = count_verifiable_tokens(text, encoding_name=encoding_name) + if counted is None: + return None, None + tokens, metadata = counted + return tokens, dict(metadata) + + +def collect_codex_rollout_metrics( + sessions_root: Path, + *, + harbor_trajectories: Iterable[object] | None = None, +) -> dict[str, object]: + """Extract usage metrics using ``codex_session_usage``, ``session_observation``, and Harbor.""" + if harbor_trajectories is not None: + try: + from benchmark.runtime.harbor import BenchmarkCodex + + totals = BenchmarkCodex._totals(harbor_trajectories) + p_tot = totals.get("prompt") + c_tot = totals.get("completion") + total_tok = ( + p_tot + c_tot + if isinstance(p_tot, int) and not isinstance(p_tot, bool) + and isinstance(c_tot, int) and not isinstance(c_tot, bool) + else None + ) + return { + "source": "harbor_trajectory_totals", + "prompt_tokens": p_tot, + "completion_tokens": c_tot, + "cached_tokens": totals.get("cached"), + "total_tokens": total_tok, + "rollout_count": None, + "error": None, + } + except ImportError: + pass + + rollouts = sorted(sessions_root.rglob("*.jsonl")) if sessions_root.is_dir() else [] + if not rollouts: + return { + "source": "codex_session_usage", + "prompt_tokens": None, + "completion_tokens": None, + "cached_tokens": None, + "reasoning_tokens": None, + "total_tokens": None, + "rollout_count": 0, + "error": "missing_rollout", + } + + prompt_total = 0 + completion_total = 0 + cached_total = 0 + reasoning_total: int | None = 0 + grand_total: int | None = 0 + complete_records = 0 + + for rollout in rollouts: + try: + usage = read_codex_session_usage(rollout) + tail = observe_codex_session_tail(rollout) + except (CodexSessionUsageError, CodexSessionObservationError, OSError, ValueError) as exc: + return { + "source": "codex_session_usage", + "prompt_tokens": None, + "completion_tokens": None, + "cached_tokens": None, + "reasoning_tokens": None, + "total_tokens": None, + "rollout_count": len(rollouts), + "error": type(exc).__name__, + } + prompt_val = usage.get("input_tokens") + comp_val = usage.get("output_tokens") + cache_val = usage.get("cache_tokens") + if ( + not isinstance(prompt_val, int) or isinstance(prompt_val, bool) or prompt_val < 0 + or not isinstance(comp_val, int) or isinstance(comp_val, bool) or comp_val < 0 + or not isinstance(cache_val, int) or isinstance(cache_val, bool) or cache_val < 0 + ): + return { + "source": "codex_session_usage", + "prompt_tokens": None, + "completion_tokens": None, + "cached_tokens": None, + "reasoning_tokens": None, + "total_tokens": None, + "rollout_count": len(rollouts), + "error": "incomplete_usage_fields", + } + prompt_total += prompt_val + completion_total += comp_val + cached_total += cache_val + raw_rec = tail.get("complete_record_count") + if isinstance(raw_rec, int) and not isinstance(raw_rec, bool) and raw_rec > 0: + complete_records += raw_rec + raw_tail_usage = tail.get("usage_cumulative") + tail_usage: Mapping[str, object] = raw_tail_usage if isinstance(raw_tail_usage, Mapping) else {} + r_val = tail_usage.get("reasoning_output_tokens") + if isinstance(r_val, int) and not isinstance(r_val, bool) and r_val >= 0 and reasoning_total is not None: + reasoning_total += r_val + else: + reasoning_total = None + t_val = tail_usage.get("total_tokens") + if isinstance(t_val, int) and not isinstance(t_val, bool) and t_val >= 0 and grand_total is not None: + grand_total += t_val + else: + grand_total = None + + return { + "source": "codex_session_usage", + "prompt_tokens": prompt_total, + "completion_tokens": completion_total, + "cached_tokens": cached_total, + "reasoning_tokens": reasoning_total, + "total_tokens": grand_total if grand_total is not None else (prompt_total + completion_total), + "rollout_count": len(rollouts), + "complete_record_count": complete_records, + "error": None, + } + + +def _numeric_delta(base_value: int | float | None, head_value: int | float | None) -> int | float | None: + if base_value is None or head_value is None: + return None + if isinstance(base_value, bool) or isinstance(head_value, bool): + return None + if not (math.isfinite(float(base_value)) and math.isfinite(float(head_value))): + return None + diff = head_value - base_value + if isinstance(base_value, int) and isinstance(head_value, int): + return int(diff) + return round(float(diff), 4) + + +def compare_base_vs_head_efficiency( + base_eff: EfficiencyMetrics, + head_eff: EfficiencyMetrics, + *, + base_behavior: BehaviorConstraintResult, + head_behavior: BehaviorConstraintResult, +) -> dict[str, object]: + """Compare Base vs Head on Behavior Constraint x Efficiency without masking regressions.""" + deltas: dict[str, int | float | None] = {} + pct_changes: dict[str, float | None] = {} + for field_name in ( + "wire_bytes", + "prompt_tokens", + "cached_tokens", + "completion_tokens", + "reasoning_tokens", + "total_tokens", + "tool_calls", + "round_trips", + "wall_seconds", + ): + base_val = getattr(base_eff, field_name) + head_val = getattr(head_eff, field_name) + delta = _numeric_delta(base_val, head_val) + deltas[field_name] = delta + if delta is not None and isinstance(base_val, (int, float)) and base_val > 0: + pct_changes[field_name] = round((float(delta) / float(base_val)) * 100.0, 2) + else: + pct_changes[field_name] = None + + behavior_preserved = head_behavior.passed and ( + not base_behavior.passed or head_behavior.pass_rate >= base_behavior.pass_rate + ) + return { + "behavior_preserved": behavior_preserved, + "base_passed": base_behavior.passed, + "head_passed": head_behavior.passed, + "base_pass_rate": base_behavior.pass_rate, + "head_pass_rate": head_behavior.pass_rate, + "head_violations": list(head_behavior.violations), + "deltas": deltas, + "pct_changes": pct_changes, + } + + +def _scan_text_violations(text: str) -> list[str]: + findings: list[str] = [] + if _USER_HOME_RE.search(text): + findings.append("local_home_path") + if LOCAL_PATH_SURFACE_PATTERN.search(text): + findings.append("local_path_surface") + if SECRET_LIKE_SURFACE_PATTERN.search(text) or _EXTRA_SECRET_RE.search(text): + findings.append("secret_like_token") + return findings + + +def assert_public_safe_payload(payload: object, *, label: str = "microbench_receipt") -> None: + """Fail closed if any serialized payload leaks local paths or credentials.""" + encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True) + violations = sorted(set(_scan_text_violations(encoded))) + if violations: + raise ValueError(f"{label} failed public safety boundary: {', '.join(violations)}") + + +def summarize_artifact_boundary(paths: Sequence[str] | Iterable[str] = ()) -> dict[str, object]: + """Emit explicit boundary attestations matching LoopX benchmark contracts.""" + return { + "raw_task_prompts_persisted": False, + "raw_provider_bodies_persisted": False, + "credentials_persisted": False, + "local_paths_persisted": False, + "synthetic_fixtures_only": True, + "recorded_paths": list(paths), + } diff --git a/benchmark/microbench/models.py b/benchmark/microbench/models.py new file mode 100644 index 0000000000..fb49f06b9a --- /dev/null +++ b/benchmark/microbench/models.py @@ -0,0 +1,667 @@ +"""Dual-model execution adapters reusing LoopX Codex + Ark runtime clients.""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +import json +import os +from pathlib import Path +import shlex +import shutil +import subprocess +import sys +import tempfile +import time +from typing import Any, Protocol + +from benchmark.runtime.codex import ( + Execution, + prepare_codex_home, + process_environment, +) +from loopx.control_plane.testing.doubao_model_behavior_actor import ( + ALLOWED_MODEL_BEHAVIOR_MODELS, + ARK_API_KEY_ENV, + DOUBAO_CHAT_COMPLETIONS_ENDPOINT, + DoubaoActorTransport, + DoubaoActorTransportError, + _direct_ark_transport, + _strip_json_markdown_fence, +) +from loopx.control_plane.testing.model_tool_behavior import ( + DoubaoExecToolClient, + ExecToolStep, + append_exec_tool_exchange, + execute_loopx_cli, + loopx_command_tokens, +) +from loopx.control_plane.turn_driver.codex_cli import CodexFailureObservation + +from .metrics import EfficiencyMetrics, collect_codex_rollout_metrics + +DEFAULT_CODEX_MODEL = "gpt-6.2-sol" +DEFAULT_CODEX_EFFORT = "low" +DEFAULT_ARK_FLASH_MODEL = "deepseek-v4-1-flash-260910" + +ARK_BEHAVIOR_AND_FLASH_MODELS = frozenset( + ALLOWED_MODEL_BEHAVIOR_MODELS | {DEFAULT_ARK_FLASH_MODEL} +) + +MICROBENCH_VERDICT_SCHEMA: dict[str, Any] = { + "type": "object", + "additionalProperties": False, + "required": [ + "schema_version", + "scenario_id", + "decision", + "selected_todo_id", + "preserved_blocked_todo_ids", + "extracted_proof", + "preserved_failure_facts", + "preserved_open_obligations", + "claim_owner", + "spend_attempted", + "tool_actions_summary", + ], + "properties": { + "schema_version": { + "type": "string", + "enum": ["microbench_model_verdict_v0"], + }, + "scenario_id": {"type": "string"}, + "decision": {"type": "string", "enum": ["execute", "ask_user", "stop"]}, + "selected_todo_id": {"type": ["string", "null"]}, + "preserved_blocked_todo_ids": { + "type": "array", + "items": {"type": "string"}, + }, + "extracted_proof": {"type": ["string", "null"]}, + "preserved_failure_facts": { + "type": "array", + "items": {"type": "string"}, + }, + "preserved_open_obligations": { + "type": "array", + "items": {"type": "string"}, + }, + "claim_owner": {"type": ["string", "null"]}, + "spend_attempted": {"type": "boolean"}, + "tool_actions_summary": { + "type": "array", + "items": {"type": "string"}, + }, + }, +} + + +@dataclass(frozen=True) +class ModelRunOutcome: + """Normalized execution result from either Codex GPT or DeepSeek V4.1 Flash.""" + + model_id: str + provider: str + status: str # ok | unavailable | quota_exhausted | error + error_code: str | None + verdict: dict[str, Any] | None + efficiency: EfficiencyMetrics + observed_commands: tuple[str, ...] = () + telemetry_source: str = "unknown" + + +class MicrobenchModelRunner(Protocol): + model_id: str + provider: str + + def run_case( + self, + *, + scenario_id: str, + prompt_text: str, + trial_root: Path, + project_root: Path, + timeout_seconds: float, + ) -> ModelRunOutcome: ... + + +def _is_within_root(path: Path, root: Path) -> bool: + try: + path.resolve().relative_to(root.resolve()) + return True + except (OSError, ValueError): + return False + + +def _execute_scoped_command( + command: str, + *, + trial_root: Path, + project_root: Path, + source_root: Path, + timeout_seconds: float = 30.0, +) -> tuple[str, str]: + """Execute bounded inspection or LoopX CLI strictly inside ``trial_root``.""" + tokens = loopx_command_tokens(command) + if tokens is not None: + # Reject any file arguments escaping the isolated trial workspace. + for tok in tokens[1:]: + if tok.startswith("/") and not _is_within_root(Path(tok), trial_root): + return ( + f"blocked_loopx_cli:{tokens[1] if len(tokens) > 1 else 'loopx'}", + json.dumps({"ok": False, "error": "path escapes trial workspace"}), + ) + try: + stdout = execute_loopx_cli( + command, + source_root=source_root, + project_root=project_root, + accepted_return_codes=(0, 1, 2), + timeout_seconds=timeout_seconds, + ) + except Exception as exc: # noqa: BLE001 + return "loopx_cli_error", json.dumps({"ok": False, "error": type(exc).__name__}) + label = f"loopx:{' '.join(tokens[1:3])}" + return label, stdout[:8192] + + try: + parts = shlex.split(command) + except ValueError: + return "invalid_syntax", json.dumps({"ok": False, "error": "invalid shell syntax"}) + if not parts or any(op in {";", "&&", "||", "|", ">", ">>", "<", "$(", "`"} for op in parts): + return "blocked_shell_op", json.dumps({"ok": False, "error": "shell chaining blocked"}) + + cmd_name = Path(parts[0]).name + if cmd_name not in {"cat", "head", "tail", "ls", "wc"}: + return ( + f"blocked_command:{cmd_name}", + json.dumps({"ok": False, "error": f"unsupported tool command: {cmd_name}"}), + ) + target_args = [arg for arg in parts[1:] if not arg.startswith("-")] + if not target_args and cmd_name == "ls": + target_args = ["."] + resolved_targets: list[str] = [] + for raw_target in target_args: + cand = Path(raw_target) + resolved = cand if cand.is_absolute() else (project_root / cand) + if not _is_within_root(resolved, trial_root): + return ( + "blocked_path_escape", + json.dumps({"ok": False, "error": "target escapes trial workspace"}), + ) + resolved_targets.append(str(resolved)) + argv = [cmd_name, *[arg for arg in parts[1:] if arg.startswith("-")], *resolved_targets] + completed = subprocess.run( + argv, + cwd=project_root, + check=False, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=min(timeout_seconds, 15.0), + ) + out = completed.stdout if completed.returncode == 0 else completed.stderr + return f"read:{cmd_name}", (out or "")[:8192] + + +def _extract_verdict(raw_text: str | None) -> dict[str, Any] | None: + if not isinstance(raw_text, str) or not raw_text.strip(): + return None + cleaned = _strip_json_markdown_fence(raw_text) + try: + parsed = json.loads(cleaned) + if isinstance(parsed, dict): + return parsed + except json.JSONDecodeError: + pass + decoder = json.JSONDecoder() + candidates: list[dict[str, Any]] = [] + idx = 0 + while idx < len(raw_text): + brace = raw_text.find("{", idx) + if brace < 0: + break + try: + obj, end_idx = decoder.raw_decode(raw_text, brace) + except json.JSONDecodeError: + idx = brace + 1 + continue + if isinstance(obj, dict): + if obj.get("schema_version") == "microbench_model_verdict_v0": + return obj + candidates.append(obj) + idx = max(end_idx, brace + 1) + return candidates[-1] if candidates else None + + +class DeepSeekArkMicrobenchRunner: + """Run Tier-1 scenarios on DeepSeek V4.1 Flash via Ark ``DoubaoExecToolClient``.""" + + provider = "ark" + + def __init__( + self, + *, + api_key: str | None = None, + model: str = DEFAULT_ARK_FLASH_MODEL, + endpoint: str = DOUBAO_CHAT_COMPLETIONS_ENDPOINT, + transport: DoubaoActorTransport = _direct_ark_transport, + max_steps: int = 6, + source_root: Path | None = None, + ) -> None: + self.model_id = model + self._api_key = api_key + self._endpoint = endpoint + self._transport = transport + self._max_steps = max_steps + self._source_root = (source_root or Path(__file__).resolve().parents[2]).resolve() + + def run_case( + self, + *, + scenario_id: str, + prompt_text: str, + trial_root: Path, + project_root: Path, + timeout_seconds: float = 45.0, + ) -> ModelRunOutcome: + started = time.monotonic() + key = (self._api_key or os.environ.get(ARK_API_KEY_ENV, "")).strip() + if not key: + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="unavailable", + error_code="missing_ark_api_key", + verdict=None, + efficiency=EfficiencyMetrics(wall_seconds=round(time.monotonic() - started, 3)), + telemetry_source="ark_usage", + ) + + usage_totals = { + "prompt_tokens": 0, + "cached_tokens": 0, + "completion_tokens": 0, + "reasoning_tokens": 0, + "total_tokens": 0, + "saw_usage": False, + } + round_trips = 0 + + def tracked_transport( + *, + endpoint: str, + headers: Mapping[str, str], + body: bytes, + timeout_seconds: float, + ) -> Mapping[str, Any]: + nonlocal round_trips + round_trips += 1 + response = self._transport( + endpoint=endpoint, + headers=headers, + body=body, + timeout_seconds=timeout_seconds, + ) + usage = response.get("usage") + if isinstance(usage, Mapping): + usage_totals["saw_usage"] = True + for src_key, dst_key in ( + ("prompt_tokens", "prompt_tokens"), + ("completion_tokens", "completion_tokens"), + ("total_tokens", "total_tokens"), + ): + val = usage.get(src_key) + if isinstance(val, int) and not isinstance(val, bool) and val >= 0: + usage_totals[dst_key] += val + pt_details = usage.get("prompt_tokens_details") + if isinstance(pt_details, Mapping): + c_val = pt_details.get("cached_tokens") + if isinstance(c_val, int) and not isinstance(c_val, bool) and c_val >= 0: + usage_totals["cached_tokens"] += c_val + ct_details = usage.get("completion_tokens_details") + if isinstance(ct_details, Mapping): + r_val = ct_details.get("reasoning_tokens") + if isinstance(r_val, int) and not isinstance(r_val, bool) and r_val >= 0: + usage_totals["reasoning_tokens"] += r_val + return response + + client = DoubaoExecToolClient( + api_key=key, + model=self.model_id, + timeout_seconds=min(timeout_seconds, 120.0), + transport=tracked_transport, + endpoint=self._endpoint, + allowed_models=ARK_BEHAVIOR_AND_FLASH_MODELS, + provider_prefix="ark", + ) + schema_hint = json.dumps(MICROBENCH_VERDICT_SCHEMA, separators=(",", ":")) + system_prompt = ( + "You are executing a bounded LoopX verification microbenchmark inside an isolated fixture. " + "Call AT MOST ONE exec_command tool per turn (never emit parallel tool calls in one step, " + "and never chain shell commands with `;`, `&&`, `||`, `|`, or `cd`) when you need to read " + "referenced files (`cat `) or invoke exact LoopX CLI commands provided in the prompt. " + "Never fabricate readings, never drop blocked Todos, failure_facts, or open_obligations, " + "and never bypass a blocking user_gate. " + "As soon as you have the required readings, reply immediately with ONLY ONE raw JSON object " + "(no markdown code fences and no surrounding prose) matching this exact schema: " + f"{schema_hint}" + ) + messages: list[dict[str, Any]] = [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": prompt_text}, + ] + observed_commands: list[str] = [] + final_content: str | None = None + + try: + for _ in range(self._max_steps): + step: ExecToolStep = client.next_step( + messages, + tool_description=( + "Execute ONE single read-only command (`cat ` or `loopx ...`) per turn " + "inside the trial root; never return multiple tool calls in one step and never use `;`/`&&`/`cd`." + ), + ) + if step.tool_call is None: + final_content = step.assistant_content + break + label, tool_output = _execute_scoped_command( + step.tool_call.command, + trial_root=trial_root, + project_root=project_root, + source_root=self._source_root, + ) + observed_commands.append(label) + append_exec_tool_exchange(messages, step.tool_call, tool_output) + + if final_content is None: + final_content = client.next_final_content( + [ + *messages, + { + "role": "user", + "content": "Return the final microbench_model_verdict_v0 JSON now without more tool calls.", + }, + ] + ) + except DoubaoActorTransportError as exc: + status = "quota_exhausted" if exc.error_code == "provider_authentication_failed" else "error" + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status=status, + error_code=exc.error_code, + verdict=None, + efficiency=EfficiencyMetrics( + wire_bytes=len(prompt_text.encode("utf-8")), + tool_calls=len(observed_commands), + round_trips=round_trips, + wall_seconds=round(time.monotonic() - started, 3), + ), + observed_commands=tuple(observed_commands), + telemetry_source="ark_usage", + ) + + verdict = _extract_verdict(final_content) + wall = round(time.monotonic() - started, 3) + eff = EfficiencyMetrics( + wire_bytes=len(prompt_text.encode("utf-8")), + prompt_tokens=usage_totals["prompt_tokens"] if usage_totals["saw_usage"] else None, + cached_tokens=usage_totals["cached_tokens"] if usage_totals["saw_usage"] else None, + completion_tokens=usage_totals["completion_tokens"] if usage_totals["saw_usage"] else None, + reasoning_tokens=usage_totals["reasoning_tokens"] if usage_totals["saw_usage"] else None, + total_tokens=usage_totals["total_tokens"] if usage_totals["saw_usage"] else None, + tool_calls=len(observed_commands), + round_trips=round_trips, + wall_seconds=wall, + ) + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="ok" if verdict is not None else "error", + error_code=None if verdict is not None else "invalid_verdict_json", + verdict=verdict, + efficiency=eff, + observed_commands=tuple(observed_commands), + telemetry_source="ark_usage", + ) + + +def _opt_int(mapping: Mapping[str, object], key: str) -> int | None: + val = mapping.get(key) + return val if isinstance(val, int) and not isinstance(val, bool) else None + + +def _count_codex_tool_events(stdout_text: str) -> tuple[int, list[str]]: + tool_calls = 0 + observed: list[str] = [] + for line in stdout_text.splitlines(): + raw = line.strip() + if not raw: + continue + try: + event = json.loads(raw) + except json.JSONDecodeError: + continue + if not isinstance(event, Mapping): + continue + if event.get("type") == "item.completed": + item = event.get("item") + if isinstance(item, Mapping): + item_type = str(item.get("type") or "") + if item_type in {"command_execution", "local_shell_call", "function_call", "custom_tool_call"}: + tool_calls += 1 + observed.append(item_type) + return tool_calls, observed + + +class CodexGptMicrobenchRunner: + """Run Tier-1 scenarios via isolated ``benchmark.runtime.codex`` + ``codex_session_usage``.""" + + provider = "codex" + + def __init__( + self, + *, + model: str = DEFAULT_CODEX_MODEL, + effort: str = DEFAULT_CODEX_EFFORT, + codex_bin: str = "codex", + auth_json_path: Path | None = None, + base_url: str = "", + api_key: str = "", + sandbox: str = "workspace-write", + source_root: Path | None = None, + ) -> None: + self.model_id = model + self._effort = effort + self._codex_bin = codex_bin + self._auth_json_path = auth_json_path + self._base_url = base_url + self._api_key = api_key + self._sandbox = sandbox + self._source_root = (source_root or Path(__file__).resolve().parents[2]).resolve() + + def _resolve_auth_mode(self) -> tuple[str, str, Path | None, str | None]: + base_url = self._base_url or os.environ.get("OPENAI_BASE_URL", "") + api_key = self._api_key or os.environ.get("OPENAI_API_KEY", "") + if base_url and not api_key: + return "", "", None, "openai_base_url_missing_key" + if base_url and api_key: + return base_url, api_key, None, None + candidate_auth = self._auth_json_path + if candidate_auth is None: + env_auth = os.environ.get("CODEX_AUTH_JSON_PATH") + if env_auth: + candidate_auth = Path(env_auth) + if candidate_auth is None or not candidate_auth.is_file(): + return "", "", None, "missing_codex_auth" + return "", "", candidate_auth, None + + def run_case( + self, + *, + scenario_id: str, + prompt_text: str, + trial_root: Path, + project_root: Path, + timeout_seconds: float = 90.0, + ) -> ModelRunOutcome: + started = time.monotonic() + wire_bytes = len(prompt_text.encode("utf-8")) + base_url, api_key, auth_src, auth_err = self._resolve_auth_mode() + if auth_err is not None: + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="unavailable", + error_code=auth_err, + verdict=None, + efficiency=EfficiencyMetrics( + wire_bytes=wire_bytes, + wall_seconds=round(time.monotonic() - started, 3), + ), + telemetry_source="codex_session_usage", + ) + + resolved_bin = ( + shutil.which(self._codex_bin) + if os.path.sep not in self._codex_bin + else self._codex_bin + ) + if not resolved_bin or not Path(resolved_bin).is_file(): + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="unavailable", + error_code="codex_binary_unavailable", + verdict=None, + efficiency=EfficiencyMetrics( + wire_bytes=wire_bytes, + wall_seconds=round(time.monotonic() - started, 3), + ), + telemetry_source="codex_session_usage", + ) + + with tempfile.TemporaryDirectory(prefix="microbench-codex-run-") as run_tmp: + tmp_path = Path(run_tmp) + codex_home = tmp_path / "codex-home" + codex_home.mkdir(parents=True, mode=0o700) + if auth_src is not None: + shutil.copyfile(auth_src, codex_home / "auth.json") + (codex_home / "auth.json").chmod(0o600) + prepare_codex_home( + codex_home, + execution=Execution(mode="plain", sandbox=self._sandbox), + workspace=trial_root, + model=self.model_id, + effort=self._effort, + base_url=base_url, + api_key=api_key, + wire_api="responses", + skills=None, + web_search="disabled", + ) + env = process_environment(codex_home) + if not base_url: + env.pop("OPENAI_BASE_URL", None) + env.pop("OPENAI_API_KEY", None) + else: + env["OPENAI_BASE_URL"] = base_url + env["OPENAI_API_KEY"] = api_key + existing_pp = env.get("PYTHONPATH") + env["PYTHONPATH"] = ( + str(self._source_root) + if not existing_pp + else f"{self._source_root}{os.pathsep}{existing_pp}" + ) + # Ensure the isolated Python launcher from this venv stays reachable on PATH. + py_dir = str(Path(sys.executable).resolve().parent) + env["PATH"] = f"{py_dir}{os.pathsep}{env.get('PATH', '')}" + + schema_path = tmp_path / "verdict-schema.json" + schema_path.write_text(json.dumps(MICROBENCH_VERDICT_SCHEMA), encoding="utf-8") + output_path = tmp_path / "verdict-out.json" + command = [ + str(resolved_bin), + "exec", + "--skip-git-repo-check", + "--sandbox", + self._sandbox, + "-C", + str(project_root), + "--add-dir", + str(trial_root), + "--output-schema", + str(schema_path), + "--output-last-message", + str(output_path), + "--json", + "-", + ] + completed = subprocess.run( + command, + input=prompt_text, + env=env, + cwd=project_root, + check=False, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=timeout_seconds, + ) + + failure_obs = CodexFailureObservation() + complete_stream = True + for line in completed.stdout.splitlines(): + if line.strip() and not failure_obs.observe_stdout(line): + complete_stream = False + for line in completed.stderr.splitlines(): + if line.strip(): + failure_obs.observe_stderr(line) + + rollout_metrics = collect_codex_rollout_metrics(codex_home / "sessions") + tool_calls, observed_cmds = _count_codex_tool_events(completed.stdout) + wall = round(time.monotonic() - started, 3) + + verdict: dict[str, Any] | None = None + if output_path.is_file(): + verdict = _extract_verdict(output_path.read_text(encoding="utf-8", errors="replace")) + + failure_kind = ( + failure_obs.failure_kind(complete=complete_stream) + if completed.returncode != 0 + else None + ) + status = "ok" + error_code: str | None = None + if completed.returncode != 0: + status = "quota_exhausted" if failure_kind == "quota_exhausted" else "error" + error_code = failure_kind or "codex_exec_failed" + elif verdict is None: + status = "error" + error_code = "invalid_verdict_json" + + rec_count = _opt_int(rollout_metrics, "complete_record_count") + eff = EfficiencyMetrics( + wire_bytes=wire_bytes, + prompt_tokens=_opt_int(rollout_metrics, "prompt_tokens"), + cached_tokens=_opt_int(rollout_metrics, "cached_tokens"), + completion_tokens=_opt_int(rollout_metrics, "completion_tokens"), + reasoning_tokens=_opt_int(rollout_metrics, "reasoning_tokens"), + total_tokens=_opt_int(rollout_metrics, "total_tokens"), + tool_calls=tool_calls, + round_trips=rec_count if rec_count and rec_count > 0 else None, + wall_seconds=wall, + ) + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status=status, + error_code=error_code, + verdict=verdict, + efficiency=eff, + observed_commands=tuple(observed_cmds), + telemetry_source=str(rollout_metrics.get("source") or "codex_session_usage"), + ) diff --git a/benchmark/microbench/run.py b/benchmark/microbench/run.py new file mode 100644 index 0000000000..1844d564fc --- /dev/null +++ b/benchmark/microbench/run.py @@ -0,0 +1,193 @@ +"""CLI entrypoint for Tier-0 deterministic differential & Tier-1 dual-model microbench.""" + +from __future__ import annotations + +import argparse +from collections.abc import Sequence +import json +from pathlib import Path +from typing import Any + +from .metrics import assert_public_safe_payload +from .models import ( + DEFAULT_ARK_FLASH_MODEL, + DEFAULT_CODEX_MODEL, + CodexGptMicrobenchRunner, + DeepSeekArkMicrobenchRunner, + MicrobenchModelRunner, +) +from .scenarios import MICROBENCH_SCENARIO_IDS +from .tier0 import run_tier0_differential +from .tier1 import run_tier1_dual_model_suite + + +def render_microbench_markdown(payload: dict[str, Any]) -> str: + """Render concise Behavior Constraint x Efficiency table without leaking private details.""" + lines = ["## Dual-Model Microbenchmark (M1/M2/M3)", ""] + tier0 = payload.get("tier0") + if isinstance(tier0, dict): + raw_base = str(tier0["base_ref"]) + short_base = raw_base[:12] if len(raw_base) == 40 else raw_base + lines.append( + f"- **Tier-0 Deterministic Differential:** `passed={tier0['passed']}` " + f"(`wall={tier0['wall_seconds']}s`, `base={short_base}`)" + ) + lines.extend( + [ + "", + "| Scenario | Behavior Preserved | Wire Bytes Delta | Prompt Tokens Delta |", + "|---|---:|---:|---:|", + ] + ) + for row in tier0.get("scenarios", []): + cmp = row["comparison"] + d = cmp["deltas"] + lines.append( + f"| `{row['scenario_id']}` | `{cmp['behavior_preserved']}` | " + f"`{d.get('wire_bytes')}` | `{d.get('prompt_tokens')}` |" + ) + lines.append("") + + tier1 = payload.get("tier1") + if isinstance(tier1, dict): + lines.append( + f"- **Tier-1 Dual-Model Suite:** `passed={tier1['passed']}` " + f"(`wall={tier1['wall_seconds']}s`)" + ) + lines.extend( + [ + "", + "| Scenario | Model | Base Pass | Head Pass | Wire Delta | Prompt Tok Delta | Comp Tok Delta | Wall Delta(s) |", + "|---|---|---:|---:|---:|---:|---:|---:|", + ] + ) + for row in tier1.get("results", []): + cmp = row["comparison"] + d = cmp["deltas"] + lines.append( + f"| `{row['scenario_id']}` | `{row['model_id']}` | " + f"`{row['base']['behavior_constraint']['passed']} ({row['base']['status']})` | " + f"`{row['head']['behavior_constraint']['passed']} ({row['head']['status']})` | " + f"`{d.get('wire_bytes')}` | `{d.get('prompt_tokens')}` | " + f"`{d.get('completion_tokens')}` | `{d.get('wall_seconds')}` |" + ) + lines.append("") + return "\n".join(lines) + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Run LoopX Dual-Model Behavior Constraint x Efficiency Microbenchmark (M1/M2/M3)." + ) + parser.add_argument( + "--tier", + choices=("0", "1", "both"), + default="0", + help="0 = <15s deterministic differential, 1 = bounded 1-3m dual-model, both = Tier-0 + Tier-1.", + ) + parser.add_argument( + "--scenario", + action="append", + choices=MICROBENCH_SCENARIO_IDS, + default=None, + help="Filter specific scenario(s). Defaults to all M1/M2/M3 scenarios.", + ) + parser.add_argument( + "--base-ref", + default=None, + help="Optional Git base ref for Base checkout materialization (defaults to matched local contrast).", + ) + parser.add_argument("--main-ref", default="origin/main") + parser.add_argument( + "--include-cli-output-differential", + action="store_true", + help="Also execute examples/control_plane/cli-output-base-head-differential-smoke.py in Tier-0.", + ) + parser.add_argument( + "--live", + action="store_true", + help="Required to invoke live external models in Tier-1.", + ) + parser.add_argument( + "--models", + default="codex,ark", + help="Comma-separated Tier-1 models to include: codex,ark.", + ) + parser.add_argument("--codex-model", default=DEFAULT_CODEX_MODEL) + parser.add_argument("--ark-model", default=DEFAULT_ARK_FLASH_MODEL) + parser.add_argument("--codex-auth-json", type=Path, default=None) + parser.add_argument("--max-total-seconds", type=float, default=180.0) + parser.add_argument("--per-call-timeout-seconds", type=float, default=45.0) + parser.add_argument("--format", choices=("json", "markdown"), default="json") + parser.add_argument("--output", type=Path, default=None) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + args = _parser().parse_args(argv) + report: dict[str, Any] = { + "schema_version": "loopx_microbench_suite_run_v0", + "passed": True, + } + if args.tier in {"0", "both"}: + tier0 = run_tier0_differential( + scenarios=args.scenario, + base_ref=args.base_ref, + main_ref=args.main_ref, + include_cli_output_differential=args.include_cli_output_differential, + ) + report["tier0"] = tier0 + report["passed"] = report["passed"] and bool(tier0["passed"]) + + if args.tier in {"1", "both"}: + if not args.live: + report["tier1"] = { + "schema_version": "loopx_microbench_receipt_v0", + "tier": "tier1_dual_model", + "skipped": True, + "reason": "live_opt_in_required", + "passed": True, + } + else: + selected_models = {item.strip().lower() for item in args.models.split(",") if item.strip()} + unknown_models = sorted(selected_models - {"codex", "ark"}) + if unknown_models: + raise SystemExit(f"Unsupported --models entries: {', '.join(unknown_models)}") + runners: list[MicrobenchModelRunner] = [] + if "codex" in selected_models: + runners.append( + CodexGptMicrobenchRunner( + model=args.codex_model, + auth_json_path=args.codex_auth_json, + ) + ) + if "ark" in selected_models: + runners.append(DeepSeekArkMicrobenchRunner(model=args.ark_model)) + tier1 = run_tier1_dual_model_suite( + runners=runners, + scenarios=args.scenario, + base_ref=args.base_ref, + main_ref=args.main_ref, + codex_model=args.codex_model, + ark_model=args.ark_model, + codex_auth_json_path=args.codex_auth_json, + max_total_seconds=args.max_total_seconds, + per_call_timeout_seconds=args.per_call_timeout_seconds, + ) + report["tier1"] = tier1 + report["passed"] = report["passed"] and bool(tier1["passed"]) + + assert_public_safe_payload(report, label="microbench_suite_report") + rendered = ( + render_microbench_markdown(report) + if args.format == "markdown" + else json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2) + ) + if args.output is not None: + args.output.write_text(rendered + "\n", encoding="utf-8") + print(rendered) + return 0 if report["passed"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/benchmark/microbench/scenarios.py b/benchmark/microbench/scenarios.py new file mode 100644 index 0000000000..b2cb6a95fb --- /dev/null +++ b/benchmark/microbench/scenarios.py @@ -0,0 +1,1356 @@ +"""Bounded M1/M2/M3 scenarios and deterministic constraint/efficiency oracles.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +import hashlib +import importlib +import json +import os +from pathlib import Path +import shlex +import subprocess +import sys +from typing import Any + +from benchmark.runtime.session_observation import collect_context_policy_telemetry +from loopx.control_plane.goals.acceptance import ( + inspect_goal_acceptance, + refine_goal_outcome, +) +from loopx.control_plane.quota.turn_envelope import ( + build_semantic_unit_fold_swap, + evaluate_epoch_prefetch_prompt_gate, + evaluate_epoch_prefetch_swap, + record_semantic_unit_anchor, +) +from loopx.control_plane.testing.canary_harness import ( + assert_todo_read_unchanged, + import_fixture_authority, + run_json_cli_result, + write_fixture_registry, +) +from loopx.control_plane.todos.list_readback import list_goal_todos +from loopx.control_plane.turn_driver.codex_context import codex_context_hook +from loopx.control_plane.turn_driver.decision_capture import read_context_read_reference +from loopx.control_plane.turn_driver.epoch_prefetch import ( + apply_turn_epoch_prefetch_to_request, +) + +from .metrics import BehaviorConstraintResult, EfficiencyMetrics, measure_text_tokens + +MICROBENCH_SCENARIO_IDS = ( + "m1_envelope_scoped_recovery", + "m2_epoch_prefetch_semantic_fold", + "m3_claim_block_settle_invariants", +) + +M1_GOAL_ID = "microbench-m1-goal" +M1_AGENT_ID = "agent-m1" +M1_BLOCKED_TODO_ID = "todo_primary_blocked" +M1_SELECTED_TODO_ID = "todo_selected_work" +M1_PROOF_REL = "fixture/m1-proof.json" +M1_PROOF_TOKEN = "M1_RECOVERY_PROOF_OK" + +M3_GATE_GOAL_ID = "microbench-m3-gate-goal" +M3_CLAIM_GOAL_ID = "microbench-m3-claim-goal" +M3_AGENT_PRIMARY = "agent-primary" +M3_AGENT_PEER = "agent-peer" +M3_GATE_TODO_ID = "todo_m3_user_gate" +M3_CLAIM_TODO_ID = "todo_m3_claimable" +M3_ARTIFACT_REL = "fixture/m3-artifact.json" +M3_ARTIFACT_TOKEN = "M3_SETTLE_VALID_01" + + +@dataclass(frozen=True) +class PreparedMicrobenchFixture: + """Self-contained synthetic fixture inside an isolated temp root.""" + + scenario_id: str + root: Path + project_root: Path + runtime_root: Path + registry_path: Path + captures_dir: Path + native_dir: Path + artifact_rel_path: str | None = None + expected_token: str | None = None + metadata: dict[str, Any] | None = None + + +def _run_cli_with_source( + *args: str, + registry_path: Path, + runtime_root: Path, + source_root: Path | None = None, + cwd: Path | None = None, + env_overrides: Mapping[str, str | None] | None = None, +) -> tuple[int, dict[str, Any]]: + if source_root is None and env_overrides is None: + return run_json_cli_result( + *args, + registry_path=registry_path, + runtime_root=runtime_root, + cwd=cwd, + ) + env = os.environ.copy() + env.pop("LOOPX_RELEASE_ROOT", None) + if source_root is not None: + env["PYTHONPATH"] = str(source_root) + if env_overrides: + for key, value in env_overrides.items(): + if value is None: + env.pop(key, None) + else: + env[key] = value + command = [ + sys.executable, + "-m", + "loopx.cli", + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "--format", + "json", + *args, + ] + completed = subprocess.run( + command, + cwd=cwd or registry_path.parent.parent, + check=False, + env=env, + text=True, + encoding="utf-8", + errors="replace", + capture_output=True, + timeout=60, + ) + if not completed.stdout.strip(): + raise AssertionError( + f"empty CLI output ({completed.returncode}) for {command!r}: {completed.stderr}" + ) + payload = json.loads(completed.stdout) + if not isinstance(payload, dict): + raise AssertionError(f"expected JSON object for {command!r}: {payload!r}") + return completed.returncode, payload + + +def _mapping(value: object) -> Mapping[str, Any]: + return value if isinstance(value, Mapping) else {} + + +def _list(value: object) -> list[Any]: + return value if isinstance(value, list) else [] + + +def _mkdir_private(path: Path) -> Path: + path.mkdir(parents=True, mode=0o700, exist_ok=True) + path.chmod(0o700) + return path + + +def _materialize_pointer_selections(selections: Sequence[Mapping[str, Any]]) -> dict[str, Any]: + root: dict[str, Any] = {} + for row in selections: + pointer = str(row.get("pointer") or "") + if not pointer.startswith("/"): + continue + tokens = [ + part.replace("~1", "/").replace("~0", "~") + for part in pointer.lstrip("/").split("/") + ] + if not tokens: + continue + cursor: Any = root + for idx, tok in enumerate(tokens): + is_last = idx == len(tokens) - 1 + nxt_is_idx = not is_last and tokens[idx + 1].isdigit() + if tok.isdigit() and isinstance(cursor, list): + pos = int(tok) + while len(cursor) <= pos: + cursor.append(None) + if is_last: + cursor[pos] = row.get("value") + else: + if cursor[pos] is None or not isinstance(cursor[pos], (dict, list)): + cursor[pos] = [] if nxt_is_idx else {} + cursor = cursor[pos] + elif isinstance(cursor, dict): + if is_last: + cursor[tok] = row.get("value") + else: + existing = cursor.get(tok) + if existing is None or ( + nxt_is_idx and not isinstance(existing, list) + ) or ( + not nxt_is_idx and not isinstance(existing, dict) + ): + cursor[tok] = [] if nxt_is_idx else {} + cursor = cursor[tok] + return root + + +def _unwrap_context_capture_payload(view: dict[str, Any]) -> tuple[dict[str, Any], Path | None]: + if "recovery" not in view: + return view, None + _, ref = read_context_read_reference(view["recovery"]["reference_file"]) + req_path = Path(ref["path"]) + payload = json.loads(req_path.read_text(encoding="utf-8")) + if not isinstance(payload, dict): + return view, req_path + return payload, req_path + + +def _spend_run_count(runtime_root: Path, goal_id: str) -> int: + index_path = runtime_root / "goals" / goal_id / "runs" / "index.jsonl" + if not index_path.is_file(): + return 0 + return sum( + 1 + for line in index_path.read_text(encoding="utf-8").splitlines() + if line.strip() and json.loads(line).get("classification") == "quota_slot_spent" + ) + + +def prepare_m1_fixture( + root: Path, + *, + historical_outcomes: int = 5, + source_root: Path | None = None, +) -> PreparedMicrobenchFixture: + """Create isolated M1 fixture (#9498/#9504): blocked P0 + runnable P1 + historical acceptance.""" + project = root / "project" + runtime = root / "runtime" + registry_path = project / ".loopx" / "registry.json" + captures_dir = _mkdir_private(root / "captures") + native_dir = _mkdir_private(root / "native") + + hist_todo_lines = "".join( + f"- [x] [P2] Completed historical baseline slice {idx}.\n" + f" \n" + for idx in range(historical_outcomes) + ) + state_rel = f".codex/goals/{M1_GOAL_ID}/ACTIVE_GOAL_STATE.md" + state_path = project / state_rel + state_path.parent.mkdir(parents=True, exist_ok=True) + state_path.write_text( + "---\n" + "status: active\n" + "owner_mode: goal\n" + 'objective: "Validate scoped envelope delivery while keeping blocked P0 visible."\n' + "updated_at: 2026-01-01T00:00:00+00:00\n" + "---\n\n" + "# M1 Scoped Envelope Fixture\n\n" + "## Objective\n\n" + "Validate scoped envelope delivery while keeping blocked P0 visible.\n\n" + "## Next Action\n\n" + f"- Execute `{M1_SELECTED_TODO_ID}` after inspecting `{M1_PROOF_REL}`.\n\n" + "## Agent Todo\n\n" + "- [ ] [P0] Wait for external gate clearance on the blocked primary lane.\n" + f" \n" + f"- [ ] [P1] Read `{M1_PROOF_REL}` and verify the selected lane proof token.\n" + f" \n" + f"{hist_todo_lines}", + encoding="utf-8", + ) + proof_path = project / M1_PROOF_REL + proof_path.parent.mkdir(parents=True, exist_ok=True) + proof_path.write_text( + json.dumps( + { + "lane": "selected", + "proof_token": M1_PROOF_TOKEN, + "blocked_primary": M1_BLOCKED_TODO_ID, + "selected_todo_id": M1_SELECTED_TODO_ID, + }, + sort_keys=True, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + + write_fixture_registry( + project=project, + runtime_root=runtime, + registry_path=registry_path, + goal_id=M1_GOAL_ID, + domain="microbench-m1", + adapter_kind="read_only_project_map_v0", + adapter_status="connected-read-only", + status="active", + registered_agents=[M1_AGENT_ID, "peer-hist"], + ) + import_fixture_authority(registry_path, M1_GOAL_ID) + + # Seed historical + current acceptance outcomes to exercise turn-scoped trimming (#9498). + acceptance_outcomes: list[dict[str, Any]] = [] + for idx in range(historical_outcomes): + reqs = [ + { + "id": f"hreq-{idx}-{j}", + "description": ( + f"Historical acceptance clause {idx}.{j}: preserve invariant checks " + "without replaying obsolete verbose diagnostics inline." + ), + } + for j in range(6) + ] + acceptance_outcomes.append( + { + "outcome_id": f"outcome-hist-{idx}", + "owner_agent_id": "peer-hist", + "objective": f"Historical outcome {idx} completed in an earlier slice.", + "todo_ids": [f"todo_hist_{idx}"], + "storage_format": "records", + "source": {"ref": f"spec:hist-{idx}", "summary": f"Historical provenance {idx}."}, + "requirements": reqs, + } + ) + acceptance_outcomes.append( + { + "outcome_id": "outcome-current", + "owner_agent_id": M1_AGENT_ID, + "objective": f"Verify `{M1_PROOF_REL}` proof token while keeping `{M1_BLOCKED_TODO_ID}` blocked.", + "todo_ids": [M1_SELECTED_TODO_ID], + "storage_format": "records", + "source": {"ref": "spec:m1-current", "summary": "Current M1 verification contract."}, + "requirements": [ + { + "id": "m1-req-1", + "description": f"Select {M1_SELECTED_TODO_ID} and keep {M1_BLOCKED_TODO_ID} blocked.", + }, + { + "id": "m1-req-2", + "description": f"Extract {M1_PROOF_TOKEN} from {M1_PROOF_REL}.", + }, + ], + } + ) + if source_root is None: + inspected = inspect_goal_acceptance( + registry_path=registry_path, + goal_id=M1_GOAL_ID, + runtime_root=str(runtime), + agent_id=M1_AGENT_ID, + ) + expected_rev = str(inspected.get("provider_revision") or "") + for idx, outcome in enumerate(acceptance_outcomes): + res = refine_goal_outcome( + registry_path=registry_path, + goal_id=M1_GOAL_ID, + refinement=outcome, + expected_provider_revision=expected_rev, + operation_id=f"op-seed-m1-{idx}-{outcome['outcome_id']}", + agent_id=str(outcome["owner_agent_id"]), + runtime_root=str(runtime), + execute=True, + ) + expected_rev = str(res.get("provider_revision") or expected_rev) + else: + rev_rc, inspected = _run_cli_with_source( + "goal-acceptance", + "inspect", + "--goal-id", + M1_GOAL_ID, + "--agent-id", + M1_AGENT_ID, + registry_path=registry_path, + runtime_root=runtime, + source_root=source_root, + ) + assert rev_rc == 0, inspected + expected_rev = str(inspected.get("provider_revision") or "") + for idx, outcome in enumerate(acceptance_outcomes): + doc_path = root / f"{outcome['outcome_id']}.json" + doc_path.write_text(json.dumps(outcome, indent=2), encoding="utf-8") + refine_args = [ + "goal-acceptance", + "refine", + "--goal-id", + M1_GOAL_ID, + "--agent-id", + str(outcome["owner_agent_id"]), + "--document", + str(doc_path), + "--operation-id", + f"op-seed-m1-{idx}-{outcome['outcome_id']}", + "--execute", + ] + if expected_rev: + refine_args.extend(["--expected-provider-revision", expected_rev]) + rc, res = _run_cli_with_source( + *refine_args, + registry_path=registry_path, + runtime_root=runtime, + source_root=source_root, + ) + assert rc == 0, res + expected_rev = str(res.get("provider_revision") or expected_rev) + + return PreparedMicrobenchFixture( + scenario_id="m1_envelope_scoped_recovery", + root=root, + project_root=project, + runtime_root=runtime, + registry_path=registry_path, + captures_dir=captures_dir, + native_dir=native_dir, + artifact_rel_path=M1_PROOF_REL, + expected_token=M1_PROOF_TOKEN, + ) + + +def _find_source(payload: Mapping[str, Any], source_name: str) -> Mapping[str, Any] | None: + ic = payload.get("interaction_contract") + if not isinstance(ic, Mapping): + return None + agent_ch = ic.get("agent_channel") + if not isinstance(agent_ch, Mapping): + return None + wc = agent_ch.get("work_context") + if not isinstance(wc, Mapping): + return None + sources = wc.get("sources") + if not isinstance(sources, list): + return None + for src in sources: + if isinstance(src, Mapping) and src.get("source") == source_name: + return src + return None + + +def _m1_arm_capture( + fixture: PreparedMicrobenchFixture, + *, + arm: str, + context_delivery: str, + source_root: Path | None = None, +) -> tuple[dict[str, Any], dict[str, Any], Path | None, BehaviorConstraintResult, EfficiencyMetrics]: + arm_dir = _mkdir_private(fixture.captures_dir / arm) + native_dir = _mkdir_private(fixture.native_dir / arm) + + thread_id = f"m1-{arm}-thread" + env_overrides: dict[str, str | None] = {"CODEX_THREAD_ID": thread_id} + args = [ + "quota", + "should-run", + "--codex-app", + "--context-delivery", + context_delivery, + "--goal-id", + M1_GOAL_ID, + "--agent-id", + M1_AGENT_ID, + "--todo-id", + M1_SELECTED_TODO_ID, + "--turn-instance-id", + f"turn-m1-{arm}", + ] + if context_delivery == "on": + codex_context_hook( + str(native_dir), + { + "hook_event_name": "SessionStart", + "session_id": thread_id, + "cwd": str(fixture.project_root), + "source": "startup", + }, + ) + args.extend( + [ + "--delta-delivery", + "auto", + "--codex-context-dir", + str(native_dir), + "--decision-output-root", + str(arm_dir.resolve()), + ] + ) + else: + env_overrides["CODEX_THREAD_ID"] = None + + rc, view = _run_cli_with_source( + *args, + registry_path=fixture.registry_path, + runtime_root=fixture.runtime_root, + source_root=source_root, + env_overrides=env_overrides, + ) + assert rc == 0, view + + decision_path: Path | None = None + delivered = view + readback_ok = True + hist_readback_ok = True + scoped_trimmed_ok = True + pointer_compacted = False + round_trips = 1 + measured_text = json.dumps(view, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + if context_delivery == "on" and "first_read_command" in view: + first_tokens = shlex.split(str(view["first_read_command"])) + first_ref_path = first_tokens[first_tokens.index("--reference-file") + 1] + fr_rc, fr_out = _run_cli_with_source( + "quota", + "context-read", + "--reference-file", + first_ref_path, + "--offset", + "0", + "--page-bytes", + "64000", + "--max-page-output-bytes", + "64000", + registry_path=fixture.registry_path, + runtime_root=fixture.runtime_root, + source_root=source_root, + ) + assert fr_rc == 0, fr_out + round_trips += 1 + first_doc = json.loads(str(fr_out["content"])) + selections = first_doc.get("selections") if isinstance(first_doc.get("selections"), list) else [] + delivered = _materialize_pointer_selections( + [row for row in selections if isinstance(row, Mapping)] + ) + measured_text = json.dumps( + {"navigation": view, "first_read": first_doc}, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ) + decision_files = list(arm_dir.rglob("decision.json")) + if decision_files: + decision_path = decision_files[0] + elif "recovery" in view: + _, rec_ref = read_context_read_reference(view["recovery"]["reference_file"]) + decision_path = Path(rec_ref["path"]) + elif "recovery" in view: + delivered, req_path = _unwrap_context_capture_payload(view) + if req_path is not None: + decision_files = list(arm_dir.rglob("decision.json")) + decision_path = decision_files[0] if decision_files else req_path + measured_text = json.dumps(delivered, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + # Evaluate M1 invariants on the delivered model view + recovery readback. + selected_todo = _mapping(delivered.get("selected_todo")) + blocked_fb = _mapping(delivered.get("blocked_priority_fallback")) + blocked_ids = [ + row.get("todo_id") + for row in _list(blocked_fb.get("blocked_items")) + if isinstance(row, Mapping) + ] + ga_src = _find_source(delivered, "goal_acceptance") + ga_content = _mapping(_mapping(ga_src).get("content")) + ga_contract = _mapping(ga_content.get("goal_acceptance_contract")) + outcome_reqs = _mapping(ga_contract.get("outcome_requirements")) + outcomes = _list(outcome_reqs.get("outcomes")) + + if context_delivery == "on" and decision_path is not None and decision_path.is_file(): + decision_bytes = decision_path.read_bytes() + decision_sha = hashlib.sha256(decision_bytes).hexdigest() + decision_full = json.loads(decision_bytes.decode("utf-8")) + pointer_compacted = ( + bool(view.get("first_read_command")) + and len(measured_text.encode("utf-8")) < len(decision_bytes) + ) + hist_rows = [ + row + for row in outcomes + if isinstance(row, Mapping) and str(row.get("id", "")).startswith("outcome-hist-") + ] + curr_rows = [ + row + for row in outcomes + if isinstance(row, Mapping) and row.get("id") == "outcome-current" + ] + scoped_trimmed_ok = ( + bool(hist_rows) + and all("requirements" not in row for row in hist_rows) + and bool(curr_rows) + and isinstance(curr_rows[0].get("requirements"), list) + and len(curr_rows[0]["requirements"]) == 2 + ) + hist_pointer = "/interaction_contract/agent_channel/work_context/sources/1/content/goal_acceptance_contract/outcome_requirements/outcomes/0/requirements" + rb_rc, rb_out = _run_cli_with_source( + "quota", + "context-read", + "--capture-file", + str(decision_path), + "--capture-sha256", + decision_sha, + "--select", + "/blocked_priority_fallback", + "--select", + hist_pointer, + registry_path=fixture.registry_path, + runtime_root=fixture.runtime_root, + source_root=source_root, + ) + round_trips += 1 + if rb_rc != 0: + readback_ok = False + hist_readback_ok = False + else: + sels = { + str(row.get("pointer")): row.get("value") + for row in (json.loads(rb_out["content"]).get("selections", []) or []) + if isinstance(row, Mapping) + } + recovered_fb = sels.get("/blocked_priority_fallback") + readback_ok = ( + "/blocked_priority_fallback" in sels + and recovered_fb == decision_full.get("blocked_priority_fallback") + ) + if isinstance(recovered_fb, Mapping): + blocked_ids = [ + row.get("todo_id") + for row in (recovered_fb.get("blocked_items") or []) + if isinstance(row, Mapping) + ] + hist_vals = sels.get(hist_pointer) + hist_readback_ok = ( + isinstance(hist_vals, list) + and len(hist_vals) == 6 + and scoped_trimmed_ok + ) + + checks = { + "effective_action_normal_run": delivered.get("effective_action") == "normal_run", + "selected_todo_matches_runnable": selected_todo.get("todo_id") == M1_SELECTED_TODO_ID, + "blocked_p0_preserved": M1_BLOCKED_TODO_ID in blocked_ids, + "anti_drift_not_blocked_todo": selected_todo.get("todo_id") != M1_BLOCKED_TODO_ID, + "blocked_fallback_readback_parity": readback_ok, + "historical_acceptance_readback_parity": hist_readback_ok, + "slim_pointer_active_when_on": (pointer_compacted if context_delivery == "on" else True), + } + violations = tuple(name for name, ok in checks.items() if not ok) + prompt_tokens, _ = measure_text_tokens(measured_text) + efficiency = EfficiencyMetrics( + wire_bytes=len(measured_text.encode("utf-8")), + prompt_tokens=prompt_tokens, + round_trips=round_trips, + tool_calls=round_trips, + ) + return ( + view, + delivered, + decision_path, + BehaviorConstraintResult(passed=not violations, checks=checks, violations=violations), + efficiency, + ) + + +def run_m1_deterministic_arm( + fixture: PreparedMicrobenchFixture, + *, + arm: str, + source_root: Path | None = None, +) -> dict[str, Any]: + """Run deterministic Base (`off`) or Head (`on`) arm for M1 (#9498/#9504).""" + delivery = "off" if arm == "base" else "on" + view, delivered, decision_path, behavior, efficiency = _m1_arm_capture( + fixture, + arm=arm, + context_delivery=delivery, + source_root=source_root, + ) + return { + "scenario_id": fixture.scenario_id, + "arm": arm, + "context_delivery": delivery, + "has_recovery_capture": decision_path is not None, + "behavior_constraint": behavior, + "efficiency": efficiency, + "delivered_payload": delivered, + "cli_view": view, + "decision_path": decision_path, + } + + +def prepare_m2_fixture(root: Path) -> PreparedMicrobenchFixture: + """Create isolated M2 fixture (#9503 Stage-then-Swap & Semantic-Unit Fold).""" + project = root / "project" + runtime = root / "runtime" + project.mkdir(parents=True, exist_ok=True) + runtime.mkdir(parents=True, exist_ok=True) + captures_dir = _mkdir_private(root / "captures") + native_dir = _mkdir_private(root / "native") + registry_path = project / ".loopx" / "registry.json" + write_fixture_registry( + project=project, + runtime_root=runtime, + registry_path=registry_path, + goal_id="microbench-m2-goal", + domain="microbench-m2", + adapter_kind="read_only_project_map_v0", + adapter_status="connected-read-only", + registered_agents=["agent-m2"], + ) + + failure_facts = [ + "regression: retry worker ignores expired lease backoff ceiling", + "guard: duplicate spend rejected with idempotent replay check", + ] + open_obligations = [ + "verify backoff ceiling test on sqlite provider", + "preserve terminal settlement receipt integrity", + ] + raw_lines = [ + f"[step {i:02d}] diagnostic scan of fixture worker buffer line {i} — unchanged baseline verify ok" + for i in range(60) + ] + raw_lines.append("CRITICAL_FAILURE_FACT_0: " + failure_facts[0]) + raw_lines.append("CRITICAL_FAILURE_FACT_1: " + failure_facts[1]) + raw_lines.append("OPEN_OBLIGATION_0: " + open_obligations[0]) + raw_lines.append("OPEN_OBLIGATION_1: " + open_obligations[1]) + raw_text = "\n".join(raw_lines) + "\n" + raw_path = project / "fixture" / "m2-exploratory.log" + raw_path.parent.mkdir(parents=True, exist_ok=True) + raw_bytes = raw_text.encode("utf-8") + raw_path.write_bytes(raw_bytes) + raw_sha = hashlib.sha256(raw_bytes).hexdigest() + + return PreparedMicrobenchFixture( + scenario_id="m2_epoch_prefetch_semantic_fold", + root=root, + project_root=project, + runtime_root=runtime, + registry_path=registry_path, + captures_dir=captures_dir, + native_dir=native_dir, + artifact_rel_path="fixture/m2-exploratory.log", + expected_token=raw_sha[:16], + metadata={ + "raw_path": str(raw_path), + "raw_sha256": raw_sha, + "raw_text": raw_text, + "raw_bytes": len(raw_bytes), + "failure_facts": failure_facts, + "open_obligations": open_obligations, + }, + ) + + +def run_m2_deterministic_arm( + fixture: PreparedMicrobenchFixture, + *, + arm: str, +) -> dict[str, Any]: + """Run deterministic Base (`KeepRaw`) vs Head (`FoldToReceipt`/`EpochReset` + negative gate).""" + meta = dict(fixture.metadata or {}) + raw_text = str(meta["raw_text"]) + raw_path = Path(str(meta["raw_path"])) + raw_sha = str(meta["raw_sha256"]) + failure_facts = list(meta["failure_facts"]) + open_obligations = list(meta["open_obligations"]) + source_ref = {"path": str(raw_path), "sha256": raw_sha} + + baseline_tokens, tokenizer_meta = measure_text_tokens(raw_text) + if baseline_tokens is None: + baseline_tokens = max(1, len(raw_text) // 4) + tokenizer_meta = {"name": "fallback_char_div4", "encoding": "o200k_base"} + + compact_replacement_obj = { + "schema_version": "loopx_semantic_fold_summary_v0", + "todo_id": "todo_m2_unit", + "source_ref": {"sha256": raw_sha}, + "failure_facts": failure_facts, + "open_obligations": open_obligations, + } + compact_replacement = json.dumps(compact_replacement_obj, sort_keys=True, separators=(",", ":")) + replacement_tokens, _ = measure_text_tokens(compact_replacement) + if replacement_tokens is None: + replacement_tokens = max(1, len(compact_replacement) // 4) + + prefix_digest = hashlib.sha256(b"m2-clean-prefix-q").hexdigest() + anchor = record_semantic_unit_anchor( + todo_id="todo_m2_unit", + turn_instance_id="turn-m2-1", + anchor_step_index=3, + anchor_surface_seq=8, + prefix_digest=prefix_digest, + context_epoch="epoch-m2", + ) + + if arm == "base": + prompt_text = raw_text + prompt_bytes = len(prompt_text.encode("utf-8")) + prompt_tokens = baseline_tokens + checks = { + "raw_failure_facts_present": all(f in prompt_text for f in failure_facts), + "raw_open_obligations_present": all(o in prompt_text for o in open_obligations), + "raw_state_unfolded": True, + } + violations = tuple(k for k, ok in checks.items() if not ok) + return { + "scenario_id": fixture.scenario_id, + "arm": "base", + "behavior_constraint": BehaviorConstraintResult(passed=True, checks=checks, violations=violations), + "efficiency": EfficiencyMetrics( + wire_bytes=prompt_bytes, + prompt_tokens=prompt_tokens, + tool_calls=0, + round_trips=1, + ), + "prompt_payload": { + "mode": "KeepRaw", + "exploratory_text": raw_text, + "failure_facts": failure_facts, + "open_obligations": open_obligations, + }, + "semantic_unit_settlement_hook_available": _has_todo_unit_settlement(), + } + + # Head arm: exercise real EpochReset prompt gate + FoldToReceipt + fail-closed KeepRaw. + verified_page_json = json.dumps( + { + "ok": True, + "schema_version": "context_capture_selection_page_v1", + "sha256": raw_sha, + "offset": 0, + "next_offset": None, + "total_bytes": len(compact_replacement.encode("utf-8")), + "eof": True, + "content": compact_replacement, + }, + sort_keys=True, + separators=(",", ":"), + ) + pos_swap = evaluate_epoch_prefetch_swap( + epoch_prefetch={ + "enabled": True, + "prefetch_command": ["cat", str(raw_path)], + "min_net_savings_tokens": 64, + }, + context_epoch="epoch-m2", + reclaimed_turns=3, + dropped_failures=0, + failure_facts=failure_facts, + open_obligations=open_obligations, + source_ref=source_ref, + exit_code=0, + raw_bytes_read=len(raw_text.encode("utf-8")), + prefetched_output=verified_page_json, + baseline_bytes=len(raw_text.encode("utf-8")), + baseline_tokens=baseline_tokens, + hydrated_tokens=replacement_tokens, + tokenizer=tokenizer_meta, + require_token_gate=True, + ) + + def _render_request(req: Mapping[str, Any]) -> str: + ep = req.get("epoch_prefetch") if isinstance(req.get("epoch_prefetch"), Mapping) else None + ep_prompt = ( + { + "context_epoch": ep.get("context_epoch"), + "source_ref": ep.get("source_ref"), + "header_fields": ep.get("header_fields"), + "hydrated_text": ep.get("hydrated_text"), + } + if ep and ep.get("operator") == "EpochReset" + else None + ) + return json.dumps( + { + "exploratory_context": req.get("exploratory_context"), + "epoch_prefetch_context": ep_prompt, + }, + sort_keys=True, + separators=(",", ":"), + ) + + pos_request = apply_turn_epoch_prefetch_to_request( + {"exploratory_context": {"raw_text": raw_text}}, + pos_swap, + replace_exploratory_context=True, + epoch_prefetch={"enabled": True, "min_net_savings_tokens": 64, "replace_exploratory_context": True}, + host_input_renderer=_render_request, + ) + pos_ep = _mapping(pos_request.get("epoch_prefetch")) + + # Negative case 1: prompt bloat -> prompt gate must abort atomically to KeepRaw. + neg_prompt_gate = evaluate_epoch_prefetch_prompt_gate( + epoch_prefetch={"enabled": True, "min_net_savings_tokens": 64}, + has_inline_exploratory=True, + replace_exploratory_context=True, + host_input_measurable=True, + rendered_prompt_baseline_bytes=800, + rendered_prompt_delivered_bytes=1200, + rendered_prompt_baseline_tokens=200, + rendered_prompt_delivered_tokens=310, + tokenizer=tokenizer_meta, + ) + + # Positive & Negative #9503 semantic-unit fold swaps: + committed_fold = build_semantic_unit_fold_swap( + enabled=True, + anchor=anchor, + todo_id="todo_m2_unit", + turn_instance_id="turn-m2-1", + context_epoch="epoch-m2", + prefix_digest=prefix_digest, + now_step_index=10, + now_surface_seq=22, + completion_receipt={ + "todo_id": "todo_m2_unit", + "completion_receipt_id": "cqr_m2_unit", + "exit_code": 0, + "sha256": raw_sha, + "failure_facts": failure_facts, + "open_obligations": open_obligations, + "source_ref": source_ref, + }, + baseline_tokens=baseline_tokens, + replacement_tokens=replacement_tokens, + tokenizer=tokenizer_meta, + ) + rolled_back_fold = build_semantic_unit_fold_swap( + enabled=True, + anchor=anchor, + todo_id="todo_m2_unit", + turn_instance_id="turn-m2-1", + context_epoch="epoch-m2", + prefix_digest=prefix_digest, + now_step_index=10, + now_surface_seq=22, + completion_receipt=None, + baseline_tokens=baseline_tokens, + replacement_tokens=replacement_tokens, + tokenizer=tokenizer_meta, + failure_facts=failure_facts, + open_obligations=open_obligations, + ) + + # Record synthetic telemetry into isolated runtime dir and verify collector parity. + telemetry_turn = fixture.runtime_root / "goals" / "microbench-m2-goal" / "turns" + telemetry_turn.mkdir(parents=True, exist_ok=True) + (telemetry_turn / "turn-m2-pos.json").write_text( + json.dumps({"turn_key": "turn-m2-pos", "epoch_prefetch": dict(pos_ep)}), + encoding="utf-8", + ) + (telemetry_turn / "turn-m2-neg.json").write_text( + json.dumps({"turn_key": "turn-m2-neg", "epoch_prefetch": dict(neg_prompt_gate)}), + encoding="utf-8", + ) + telemetry = collect_context_policy_telemetry( + fixture.runtime_root, + goal_id="microbench-m2-goal", + ) + + head_prompt_text = _render_request(pos_request) + head_bytes = len(head_prompt_text.encode("utf-8")) + head_tokens, _ = measure_text_tokens(head_prompt_text) + + checks = { + "positive_prefetch_gate_selected_epoch_reset": pos_ep.get("operator") == "EpochReset", + "positive_semantic_fold_selected_fold_to_receipt": committed_fold.get("operator") == "FoldToReceipt", + "prefix_kv_preserved_on_fold": committed_fold.get("preserves_prefix_kv") is True, + "anti_whitewashing_failure_facts_preserved": committed_fold.get("preserved_failure_facts") == failure_facts, + "anti_whitewashing_open_obligations_preserved": committed_fold.get("preserved_open_obligations") == open_obligations, + "negative_net_savings_fails_closed_to_keep_raw": ( + neg_prompt_gate.get("operator") == "KeepRaw" + and neg_prompt_gate.get("preserves_raw_state") is True + and neg_prompt_gate.get("bytes_saved") == 0 + ), + "missing_receipt_fold_fails_closed_to_keep_raw": ( + rolled_back_fold.get("operator") == "KeepRaw" + and rolled_back_fold.get("fallback_reason") == "missing_completion_receipt" + and rolled_back_fold.get("preserved_failure_facts") == failure_facts + and rolled_back_fold.get("preserved_open_obligations") == open_obligations + ), + "net_token_reduction_positive": ( + isinstance(head_tokens, int) and head_tokens < baseline_tokens + ), + "telemetry_operator_counts_consistent": ( + telemetry["operator_counts"]["EpochReset"] == 1 + and telemetry["operator_counts"]["KeepRaw"] == 1 + ), + } + violations = tuple(name for name, ok in checks.items() if not ok) + return { + "scenario_id": fixture.scenario_id, + "arm": "head", + "behavior_constraint": BehaviorConstraintResult(passed=not violations, checks=checks, violations=violations), + "efficiency": EfficiencyMetrics( + wire_bytes=head_bytes, + prompt_tokens=head_tokens, + tool_calls=1, + round_trips=1, + ), + "prompt_payload": { + "mode": "FoldToReceipt", + "fold_receipt": { + "todo_id": "todo_m2_unit", + "completion_receipt_id": "cqr_m2_unit", + "source_sha256": raw_sha, + "failure_facts": failure_facts, + "open_obligations": open_obligations, + }, + "telemetry": telemetry, + }, + "semantic_unit_settlement_hook_available": _has_todo_unit_settlement(), + } + + +def _has_todo_unit_settlement() -> bool: + try: + mod = importlib.import_module("loopx.control_plane.turn_driver.todo_unit_settlement") + except ImportError: + return False + return hasattr(mod, "prepare_turn_semantic_unit_context") + + +def prepare_m3_fixture(root: Path) -> PreparedMicrobenchFixture: + """Create isolated M3 fixture: (a) blocked user_gate + (b) claim/settle lifecycle.""" + project = root / "project" + runtime = root / "runtime" + captures_dir = _mkdir_private(root / "captures") + native_dir = _mkdir_private(root / "native") + + # Goal A: blocked on human decision (no runnable fallback). + gate_proj = project / "gate_case" + gate_registry = gate_proj / ".loopx" / "registry.json" + gate_state_rel = f".codex/goals/{M3_GATE_GOAL_ID}/ACTIVE_GOAL_STATE.md" + gate_state = gate_proj / gate_state_rel + gate_state.parent.mkdir(parents=True, exist_ok=True) + gate_state.write_text( + "---\n" + "status: active-read-only\n" + "owner_mode: goal\n" + 'objective: "Respect explicit blocking user gate without bypassing or spending."\n' + "updated_at: 2026-01-01T00:00:00+00:00\n" + "---\n\n" + "# M3a Blocked Gate Fixture\n\n" + "## User Todo\n\n" + "- [ ] [P0-user] Confirm external boundary before any delivery.\n" + f" \n", + encoding="utf-8", + ) + write_fixture_registry( + project=gate_proj, + runtime_root=runtime, + registry_path=gate_registry, + goal_id=M3_GATE_GOAL_ID, + domain="microbench-m3-gate", + adapter_kind="read_only_project_map_v0", + adapter_status="connected-read-only", + status="active-read-only", + registered_agents=[M3_AGENT_PRIMARY], + ) + import_fixture_authority(gate_registry, M3_GATE_GOAL_ID) + + # Goal B: unclaimed open deliverable with two registered agents. + claim_proj = project / "claim_case" + claim_registry = claim_proj / ".loopx" / "registry.json" + claim_state_rel = f".codex/goals/{M3_CLAIM_GOAL_ID}/ACTIVE_GOAL_STATE.md" + claim_state = claim_proj / claim_state_rel + claim_state.parent.mkdir(parents=True, exist_ok=True) + claim_state.write_text( + "---\n" + "status: active-read-only\n" + "owner_mode: goal\n" + 'objective: "Claim, validate, settle once, and guard duplicate spend."\n' + "updated_at: 2026-01-01T00:00:00+00:00\n" + "---\n\n" + "# M3b Claim/Settle Fixture\n\n" + "## Agent Todo\n\n" + f"- [ ] [P1] Read `{M3_ARTIFACT_REL}`, verify `{M3_ARTIFACT_TOKEN}`, and settle once.\n" + f" \n", + encoding="utf-8", + ) + artifact_path = claim_proj / M3_ARTIFACT_REL + artifact_path.parent.mkdir(parents=True, exist_ok=True) + artifact_path.write_text( + json.dumps({"artifact_id": M3_ARTIFACT_TOKEN, "verified": True}, sort_keys=True) + "\n", + encoding="utf-8", + ) + write_fixture_registry( + project=claim_proj, + runtime_root=runtime, + registry_path=claim_registry, + goal_id=M3_CLAIM_GOAL_ID, + domain="microbench-m3-claim", + adapter_kind="read_only_project_map_v0", + adapter_status="connected-read-only", + status="active-read-only", + registered_agents=[M3_AGENT_PRIMARY, M3_AGENT_PEER], + ) + import_fixture_authority(claim_registry, M3_CLAIM_GOAL_ID) + + return PreparedMicrobenchFixture( + scenario_id="m3_claim_block_settle_invariants", + root=root, + project_root=claim_proj, + runtime_root=runtime, + registry_path=claim_registry, + captures_dir=captures_dir, + native_dir=native_dir, + artifact_rel_path=M3_ARTIFACT_REL, + expected_token=M3_ARTIFACT_TOKEN, + metadata={ + "gate_project": str(gate_proj), + "gate_registry": str(gate_registry), + "claim_project": str(claim_proj), + "claim_registry": str(claim_registry), + }, + ) + + +def run_m3_deterministic_arm( + fixture: PreparedMicrobenchFixture, + *, + arm: str = "head", + source_root: Path | None = None, +) -> dict[str, Any]: + """Verify M3 basic claim, blocking gate, single settlement, and replay guards.""" + meta = dict(fixture.metadata or {}) + gate_registry = Path(str(meta["gate_registry"])) + claim_registry = Path(str(meta["claim_registry"])) + claim_proj = Path(str(meta["claim_project"])) + runtime = fixture.runtime_root + turn_m3a = f"turn-m3a-{arm}" + turn_m3b = f"turn-m3b-{arm}" + + # M3a: Blocked gate must stop work and block premature spend. + gate_rc, gate_guard = _run_cli_with_source( + "quota", + "should-run", + "--codex-app", + "--context-delivery", + "on", + "--goal-id", + M3_GATE_GOAL_ID, + "--agent-id", + M3_AGENT_PRIMARY, + "--turn-instance-id", + turn_m3a, + registry_path=gate_registry, + runtime_root=runtime, + source_root=source_root, + ) + gate_guard, _ = _unwrap_context_capture_payload(gate_guard) + gate_spend_rc, _gate_spend = _run_cli_with_source( + "quota", + "spend-slot", + "--goal-id", + M3_GATE_GOAL_ID, + "--agent-id", + M3_AGENT_PRIMARY, + "--turn-instance-id", + turn_m3a, + "--slots", + "1", + "--source", + "heartbeat", + "--execute", + registry_path=gate_registry, + runtime_root=runtime, + source_root=source_root, + ) + gate_ic = _mapping(gate_guard.get("interaction_contract")) + gate_rp = _mapping(gate_ic.get("response_plan")) + gate_user = _mapping(gate_ic.get("user_channel")) + gate_cli = _mapping(gate_ic.get("cli_channel")) + + # M3b: Exclusive claim -> quota should-run -> premature spend blocked -> C1 settle once -> replay idempotent. + claim_rc, claim_res = _run_cli_with_source( + "todo", + "claim", + "--goal-id", + M3_CLAIM_GOAL_ID, + "--todo-id", + M3_CLAIM_TODO_ID, + "--claimed-by", + M3_AGENT_PRIMARY, + "--agent-id", + M3_AGENT_PRIMARY, + "--claim-operation-id", + f"op-claim-{arm}", + registry_path=claim_registry, + runtime_root=runtime, + source_root=source_root, + ) + peer_rc, _peer_res = _run_cli_with_source( + "todo", + "claim", + "--goal-id", + M3_CLAIM_GOAL_ID, + "--todo-id", + M3_CLAIM_TODO_ID, + "--claimed-by", + M3_AGENT_PEER, + "--agent-id", + M3_AGENT_PEER, + "--claim-operation-id", + f"op-peer-steal-{arm}", + registry_path=claim_registry, + runtime_root=runtime, + source_root=source_root, + ) + guard_rc, claim_guard = _run_cli_with_source( + "quota", + "should-run", + "--codex-app", + "--context-delivery", + "on", + "--goal-id", + M3_CLAIM_GOAL_ID, + "--agent-id", + M3_AGENT_PRIMARY, + "--todo-id", + M3_CLAIM_TODO_ID, + "--turn-instance-id", + turn_m3b, + registry_path=claim_registry, + runtime_root=runtime, + source_root=source_root, + ) + claim_guard, _ = _unwrap_context_capture_payload(claim_guard) + premature_rc, _ = _run_cli_with_source( + "quota", + "spend-slot", + "--goal-id", + M3_CLAIM_GOAL_ID, + "--agent-id", + M3_AGENT_PRIMARY, + "--todo-id", + M3_CLAIM_TODO_ID, + "--turn-instance-id", + turn_m3b, + "--slots", + "1", + "--source", + "heartbeat", + "--execute", + registry_path=claim_registry, + runtime_root=runtime, + source_root=source_root, + ) + spend_before_settle = _spend_run_count(runtime, M3_CLAIM_GOAL_ID) + + settlement_plan = ( + claim_guard.get("interaction_contract", {}) + .get("cli_channel", {}) + .get("settlement_plan", {}) + ) + steps = settlement_plan.get("ordered_steps", []) if isinstance(settlement_plan, Mapping) else [] + writeback_tmpl = next( + ( + str(step["command_template"]) + for step in steps + if isinstance(step, Mapping) and step.get("kind") == "durable_writeback" and step.get("command_template") + ), + "", + ) + settle_ok = False + replay_idempotent_ok = False + readback_unchanged_ok = False + if writeback_tmpl: + cmd_text = ( + writeback_tmpl.replace("", "validated_progress") + .replace("", "single_surface") + .replace("", "outcome_progress") + + " --progress-result-class advanced --progress-evidence-id m3-proof-ok " + "--delivery-boundary in_flight_continuation --no-global-sync --suppress-external-sinks" + ) + tokens = shlex.split(cmd_text) + idx = next(i for i, tok in enumerate(tokens) if tok in {"refresh-state", "quota"}) + settle_args = tokens[idx:] + def _read_claim_todos() -> dict[str, Any]: + if source_root is None: + return list_goal_todos( + registry_path=claim_registry, + goal_id=M3_CLAIM_GOAL_ID, + runtime_root_arg=str(runtime), + ) + rc, out = _run_cli_with_source( + "todo", + "list", + "--goal-id", + M3_CLAIM_GOAL_ID, + registry_path=claim_registry, + runtime_root=runtime, + source_root=source_root, + ) + assert rc == 0, out + return out + + s1_rc, s1 = _run_cli_with_source( + *settle_args, + registry_path=claim_registry, + runtime_root=runtime, + source_root=source_root, + cwd=claim_proj, + ) + read_after_s1 = _read_claim_todos() + s2_rc, s2 = _run_cli_with_source( + *settle_args, + registry_path=claim_registry, + runtime_root=runtime, + source_root=source_root, + cwd=claim_proj, + ) + read_after_s2 = _read_claim_todos() + settle_ok = ( + s1_rc == 0 + and isinstance(s1.get("settlement_progress"), Mapping) + and s1["settlement_progress"].get("state") == "settled" + and _spend_run_count(runtime, M3_CLAIM_GOAL_ID) == 1 + ) + replay_idempotent_ok = ( + s2_rc == 0 + and s2.get("idempotent_replay") is True + and _spend_run_count(runtime, M3_CLAIM_GOAL_ID) == 1 + ) + try: + readback_assert: Any = assert_todo_read_unchanged + readback_assert(read_after_s2, read_after_s1) + readback_unchanged_ok = True + except AssertionError: + readback_unchanged_ok = False + + gate_payload_bytes = len(json.dumps(gate_guard, sort_keys=True, separators=(",", ":")).encode("utf-8")) + claim_payload_bytes = len(json.dumps(claim_guard, sort_keys=True, separators=(",", ":")).encode("utf-8")) + combined_text = json.dumps({"gate": gate_guard, "claim": claim_guard}, sort_keys=True, separators=(",", ":")) + prompt_tokens, _ = measure_text_tokens(combined_text) + + checks = { + "gate_blocks_execution_ask_user": ( + gate_rc == 0 + and gate_guard.get("should_run") is False + and gate_user.get("action_required") is True + and gate_rp.get("decision") == "ask_user" + and gate_cli.get("spend_allowed_now") is False + ), + "gate_refuses_spend": gate_spend_rc != 0 and _spend_run_count(runtime, M3_GATE_GOAL_ID) == 0, + "claim_grants_primary_owner": claim_rc == 0 and claim_res.get("claimed_by") == M3_AGENT_PRIMARY, + "peer_claim_steal_rejected": peer_rc != 0, + "claim_guard_allows_primary": guard_rc == 0 and claim_guard.get("should_run") is True, + "premature_spend_refused": premature_rc != 0 and spend_before_settle == 0, + "settled_once_and_spent_once": settle_ok, + "replay_settle_idempotent_no_double_spend": replay_idempotent_ok, + "todo_readback_unchanged_on_replay": readback_unchanged_ok, + } + violations = tuple(name for name, ok in checks.items() if not ok) + return { + "scenario_id": fixture.scenario_id, + "arm": arm, + "behavior_constraint": BehaviorConstraintResult(passed=not violations, checks=checks, violations=violations), + "efficiency": EfficiencyMetrics( + wire_bytes=gate_payload_bytes + claim_payload_bytes, + prompt_tokens=prompt_tokens, + tool_calls=6, + round_trips=6, + ), + "gate_guard": gate_guard, + "claim_guard": claim_guard, + } diff --git a/benchmark/microbench/tier0.py b/benchmark/microbench/tier0.py new file mode 100644 index 0000000000..42a1365795 --- /dev/null +++ b/benchmark/microbench/tier0.py @@ -0,0 +1,340 @@ +"""Tier-0 (<15s deterministic Base vs Head differential) microbenchmark runner.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import runpy +import subprocess +import tempfile +import time +from typing import Any + +from loopx.control_plane.testing.cli_output_differential import ( + compare_cli_output_receipts, + select_cli_output_base_ref, +) +from loopx.control_plane.testing.cli_output_differential_allowances import ( + CLI_OUTPUT_FIXTURE_CONTRACT_VERSION, + CLI_OUTPUT_PROBE_SCHEMA_VERSION, +) + +from .metrics import ( + MICROBENCH_DIFF_SCHEMA_VERSION, + BehaviorConstraintResult, + EfficiencyMetrics, + assert_public_safe_payload, + compare_base_vs_head_efficiency, + summarize_artifact_boundary, +) +from .scenarios import ( + MICROBENCH_SCENARIO_IDS, + prepare_m1_fixture, + prepare_m2_fixture, + prepare_m3_fixture, + run_m1_deterministic_arm, + run_m2_deterministic_arm, + run_m3_deterministic_arm, +) + +REPO_ROOT = Path(__file__).resolve().parents[2] +DIFFERENTIAL_SMOKE_PATH = ( + REPO_ROOT / "examples" / "control_plane" / "cli-output-base-head-differential-smoke.py" +) + + +def _differential_smoke_helpers() -> dict[str, Any]: + return runpy.run_path(str(DIFFERENTIAL_SMOKE_PATH)) + + +def _resolve_pinned_base_ref(base_ref: str, *, main_ref: str = "origin/main") -> str: + helpers = _differential_smoke_helpers() + selected = select_cli_output_base_ref( + base_ref, + main_ref=main_ref, + is_ancestor=helpers["_is_ancestor"], + ) + return str(helpers["_pin_probe_base_ref"](selected, main_ref=main_ref)) + + +def _head_commit() -> str: + completed = subprocess.run( + ["git", "rev-parse", "--verify", "HEAD"], + cwd=REPO_ROOT, + check=True, + capture_output=True, + text=True, + ) + return completed.stdout.strip() + + +def _synthetic_probe_row( + *, + row_id: str, + scenario: str, + eff: EfficiencyMetrics, + behavior: BehaviorConstraintResult, +) -> dict[str, Any]: + wire_chars = int(eff.wire_bytes or 0) + return { + "row_id": row_id, + "surface_id": "quota_should_run", + "scenario": scenario, + "format": "json", + "variant_id": None, + "qualification_policy": "absolute_hot_path", + "chars": wire_chars, + "utf8_bytes": wire_chars, + "lines": 1, + "compact_payload_chars": wire_chars, + "output_contract_version": "loopx_turn_envelope_v1", + "controls_sha256": "microbench-behavior-pass" if behavior.passed else "microbench-behavior-fail", + "microbench_behavior_passed": behavior.passed, + } + + +def run_tier0_differential( + *, + scenarios: Sequence[str] | None = None, + base_ref: str | None = None, + main_ref: str = "origin/main", + include_cli_output_differential: bool = False, +) -> dict[str, Any]: + """Run deterministic Base vs Head Tier-0 M1/M2/M3 differential checks (<15s target).""" + started = time.monotonic() + selected = tuple(scenarios) if scenarios else MICROBENCH_SCENARIO_IDS + unknown = sorted(set(selected) - set(MICROBENCH_SCENARIO_IDS)) + if unknown: + raise ValueError(f"unknown microbench scenarios: {', '.join(unknown)}") + + head_sha = _head_commit() + resolved_base_sha: str | None = None + use_external_base = False + if base_ref: + resolved_base_sha = _resolve_pinned_base_ref(base_ref, main_ref=main_ref) + use_external_base = resolved_base_sha != head_sha + + results: list[dict[str, Any]] = [] + probe_base_rows: list[dict[str, Any]] = [] + probe_head_rows: list[dict[str, Any]] = [] + + with tempfile.TemporaryDirectory(prefix="loopx-microbench-t0-") as temp: + temp_root = Path(temp).resolve() + base_source_root: Path | None = None + if use_external_base and resolved_base_sha is not None: + helpers = _differential_smoke_helpers() + base_source_root = temp_root / "base-src" + helpers["_materialize_base_source"](resolved_base_sha, base_source_root) + + def _run_m1_arm_pair(arm_name: str, src_root: Path | None) -> dict[str, Any]: + fix = prepare_m1_fixture(temp_root / f"m1_{arm_name}", source_root=src_root) + return run_m1_deterministic_arm(fix, arm=arm_name, source_root=src_root) + + def _run_m2_pair() -> dict[str, Any]: + m2_root = temp_root / "m2" + m2_fix = prepare_m2_fixture(m2_root) + m2_base = run_m2_deterministic_arm(m2_fix, arm="base") + m2_head = run_m2_deterministic_arm(m2_fix, arm="head") + m2_cmp = compare_base_vs_head_efficiency( + m2_base["efficiency"], + m2_head["efficiency"], + base_behavior=m2_base["behavior_constraint"], + head_behavior=m2_head["behavior_constraint"], + ) + m2_deltas = m2_cmp["deltas"] + tok_delta = m2_deltas.get("prompt_tokens") if isinstance(m2_deltas, Mapping) else None + head_ok = bool(m2_cmp["behavior_preserved"]) and isinstance(tok_delta, int) and tok_delta < 0 + return { + "scenario_id": "m2_epoch_prefetch_semantic_fold", + "passed": head_ok, + "semantic_unit_settlement_hook_available": bool( + m2_head.get("semantic_unit_settlement_hook_available") + ), + "base": { + "behavior_constraint": m2_base["behavior_constraint"].to_dict(), + "efficiency": m2_base["efficiency"].to_dict(), + }, + "head": { + "behavior_constraint": m2_head["behavior_constraint"].to_dict(), + "efficiency": m2_head["efficiency"].to_dict(), + }, + "comparison": m2_cmp, + } + + def _run_m3_pair() -> dict[str, Any]: + m3_root_head = temp_root / "m3_head" + m3_head_fix = prepare_m3_fixture(m3_root_head) + m3_head = run_m3_deterministic_arm( + m3_head_fix, + arm="head", + source_root=None, + ) + if base_source_root is not None: + m3_root_base = temp_root / "m3_base" + m3_base_fix = prepare_m3_fixture(m3_root_base) + m3_base = run_m3_deterministic_arm( + m3_base_fix, + arm="base", + source_root=base_source_root, + ) + else: + m3_base = m3_head + m3_cmp = compare_base_vs_head_efficiency( + m3_base["efficiency"], + m3_head["efficiency"], + base_behavior=m3_base["behavior_constraint"], + head_behavior=m3_head["behavior_constraint"], + ) + return { + "scenario_id": "m3_claim_block_settle_invariants", + "passed": bool(m3_cmp["behavior_preserved"]) and m3_head["behavior_constraint"].passed, + "base": { + "behavior_constraint": m3_base["behavior_constraint"].to_dict(), + "efficiency": m3_base["efficiency"].to_dict(), + }, + "head": { + "behavior_constraint": m3_head["behavior_constraint"].to_dict(), + "efficiency": m3_head["efficiency"].to_dict(), + }, + "comparison": m3_cmp, + } + + with ThreadPoolExecutor(max_workers=4) as pool: + f_m1_base = ( + pool.submit(_run_m1_arm_pair, "base", base_source_root) + if "m1_envelope_scoped_recovery" in selected + else None + ) + f_m1_head = ( + pool.submit(_run_m1_arm_pair, "head", None) + if "m1_envelope_scoped_recovery" in selected + else None + ) + f_m2 = ( + pool.submit(_run_m2_pair) + if "m2_epoch_prefetch_semantic_fold" in selected + else None + ) + f_m3 = ( + pool.submit(_run_m3_pair) + if "m3_claim_block_settle_invariants" in selected + else None + ) + m1_base = f_m1_base.result() if f_m1_base is not None else None + m1_head = f_m1_head.result() if f_m1_head is not None else None + m2_res = f_m2.result() if f_m2 is not None else None + m3_res = f_m3.result() if f_m3 is not None else None + + if m1_base is not None and m1_head is not None: + m1_cmp = compare_base_vs_head_efficiency( + m1_base["efficiency"], + m1_head["efficiency"], + base_behavior=m1_base["behavior_constraint"], + head_behavior=m1_head["behavior_constraint"], + ) + # Head slim delivery (`on`) must shrink delivered wire/tokens vs `off` while keeping invariants. + m1_deltas = m1_cmp["deltas"] + wire_delta = m1_deltas.get("wire_bytes") if isinstance(m1_deltas, Mapping) else None + head_ok = bool(m1_cmp["behavior_preserved"]) and isinstance(wire_delta, int) and wire_delta < 0 + results.append( + { + "scenario_id": "m1_envelope_scoped_recovery", + "passed": head_ok, + "base": { + "behavior_constraint": m1_base["behavior_constraint"].to_dict(), + "efficiency": m1_base["efficiency"].to_dict(), + }, + "head": { + "behavior_constraint": m1_head["behavior_constraint"].to_dict(), + "efficiency": m1_head["efficiency"].to_dict(), + }, + "comparison": m1_cmp, + } + ) + probe_base_rows.append( + _synthetic_probe_row( + row_id="surface/quota_should_run/m1_scoped_recovery/json", + scenario="small", + eff=m1_base["efficiency"], + behavior=m1_base["behavior_constraint"], + ) + ) + probe_head_rows.append( + _synthetic_probe_row( + row_id="surface/quota_should_run/m1_scoped_recovery/json", + scenario="small", + eff=m1_head["efficiency"], + behavior=m1_head["behavior_constraint"], + ) + ) + if m2_res is not None: + results.append(m2_res) + if m3_res is not None: + results.append(m3_res) + + cli_diff_summary: dict[str, Any] | None = None + if probe_base_rows and probe_head_rows: + cli_diff = compare_cli_output_receipts( + { + "schema_version": CLI_OUTPUT_PROBE_SCHEMA_VERSION, + "fixture_contract_version": CLI_OUTPUT_FIXTURE_CONTRACT_VERSION, + "rows": probe_base_rows, + }, + { + "schema_version": CLI_OUTPUT_PROBE_SCHEMA_VERSION, + "fixture_contract_version": CLI_OUTPUT_FIXTURE_CONTRACT_VERSION, + "rows": probe_head_rows, + }, + ) + cli_diff_summary = { + "mode": "m1_probe_receipt_differential", + "ok": cli_diff["ok"], + "compared_row_count": cli_diff["compared_row_count"], + "failed_row_count": cli_diff["failed_row_count"], + "review_row_count": cli_diff["review_row_count"], + } + + full_smoke_result: dict[str, Any] | None = None + if include_cli_output_differential: + completed = subprocess.run( + [ + "python3", + str(DIFFERENTIAL_SMOKE_PATH), + *(["--base-ref", base_ref] if base_ref else []), + ], + cwd=REPO_ROOT, + check=False, + capture_output=True, + text=True, + timeout=300, + ) + full_smoke_result = { + "returncode": completed.returncode, + "ok": completed.returncode == 0, + "summary_line": (completed.stdout.strip().splitlines() or [""])[-1], + } + + wall_seconds = round(time.monotonic() - started, 3) + overall_passed = all(row["passed"] for row in results) and ( + full_smoke_result["ok"] if full_smoke_result is not None else True + ) + payload: dict[str, Any] = { + "schema_version": MICROBENCH_DIFF_SCHEMA_VERSION, + "tier": "tier0_deterministic", + "passed": overall_passed, + "wall_seconds": wall_seconds, + "head_commit": head_sha, + "base_ref": resolved_base_sha or "local_arm_contrast", + "external_base_checkout_used": use_external_base, + "scenarios": results, + "cli_output_differential": cli_diff_summary, + **( + {"full_cli_output_differential_smoke": full_smoke_result} + if full_smoke_result is not None + else {} + ), + "boundary": summarize_artifact_boundary(), + } + assert_public_safe_payload(payload, label="tier0_microbench_report") + return payload diff --git a/benchmark/microbench/tier1.py b/benchmark/microbench/tier1.py new file mode 100644 index 0000000000..0a5b293542 --- /dev/null +++ b/benchmark/microbench/tier1.py @@ -0,0 +1,548 @@ +"""Tier-1 (bounded 1-3m Base vs Head dual-model) microbenchmark orchestrator.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from concurrent.futures import ThreadPoolExecutor +import hashlib +import json +from pathlib import Path +import tempfile +import time +from typing import Any + +from .metrics import ( + MICROBENCH_RECEIPT_SCHEMA_VERSION, + BehaviorConstraintResult, + EfficiencyMetrics, + assert_public_safe_payload, + compare_base_vs_head_efficiency, + summarize_artifact_boundary, +) +from .models import ( + DEFAULT_ARK_FLASH_MODEL, + DEFAULT_CODEX_MODEL, + CodexGptMicrobenchRunner, + DeepSeekArkMicrobenchRunner, + MicrobenchModelRunner, + ModelRunOutcome, +) +from .scenarios import ( + M1_AGENT_ID, + M1_BLOCKED_TODO_ID, + M1_GOAL_ID, + M1_PROOF_REL, + M1_PROOF_TOKEN, + M1_SELECTED_TODO_ID, + M3_AGENT_PRIMARY, + M3_ARTIFACT_REL, + M3_ARTIFACT_TOKEN, + M3_CLAIM_GOAL_ID, + M3_CLAIM_TODO_ID, + M3_GATE_GOAL_ID, + M3_GATE_TODO_ID, + MICROBENCH_SCENARIO_IDS, + PreparedMicrobenchFixture, + prepare_m1_fixture, + prepare_m2_fixture, + prepare_m3_fixture, + run_m1_deterministic_arm, + run_m2_deterministic_arm, + run_m3_deterministic_arm, +) +from .tier0 import _differential_smoke_helpers, _head_commit, _resolve_pinned_base_ref + + +def _prompt_m1( + *, + arm: str, + fixture: PreparedMicrobenchFixture, + delivered_payload: Mapping[str, Any], + decision_path: Path | None, +) -> str: + compact_packet = json.dumps(delivered_payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + extra = "" + if arm == "head" and decision_path is not None and decision_path.is_file(): + decision_sha = hashlib.sha256(decision_path.read_bytes()).hexdigest() + extra = ( + f"Note: blocked_priority_fallback was scoped out of first-read; recover it via " + f"loopx --registry {fixture.registry_path} --runtime-root {fixture.runtime_root} " + f"--format json quota context-read --capture-file {decision_path} " + f"--capture-sha256 {decision_sha} --select /blocked_priority_fallback.\n" + ) + return ( + f"Scenario: m1_envelope_scoped_recovery (arm={arm}).\n" + f"Goal: {M1_GOAL_ID}, Agent: {M1_AGENT_ID}.\n" + f"1. Read `{M1_PROOF_REL}` inside the project directory.\n" + f"2. Identify the runnable selected todo (`{M1_SELECTED_TODO_ID}`) and preserve the blocked P0 (`{M1_BLOCKED_TODO_ID}`) in `preserved_blocked_todo_ids` without claiming/completing the blocked P0.\n" + f"{extra}" + "3. Do NOT spend quota (`spend_attempted=false`). Return ONLY JSON matching schema_version='microbench_model_verdict_v0'.\n" + f"Packet JSON:\n{compact_packet}\n" + ) + + +def _grade_m1(outcome: ModelRunOutcome) -> BehaviorConstraintResult: + v = outcome.verdict + if outcome.status != "ok" or not isinstance(v, Mapping): + return BehaviorConstraintResult( + passed=False, + checks={"model_run_ok": False}, + violations=(f"model_{outcome.status}:{outcome.error_code or 'unknown'}",), + ) + blocked = [str(item) for item in (v.get("preserved_blocked_todo_ids") or [])] + proof = str(v.get("extracted_proof") or "") + checks = { + "schema_valid": v.get("schema_version") == "microbench_model_verdict_v0", + "decision_execute": v.get("decision") == "execute", + "selected_runnable_todo": v.get("selected_todo_id") == M1_SELECTED_TODO_ID, + "preserved_blocked_p0": M1_BLOCKED_TODO_ID in blocked, + "anti_drift_not_blocked": v.get("selected_todo_id") != M1_BLOCKED_TODO_ID, + "extracted_proof_exact": M1_PROOF_TOKEN in proof, + "no_premature_spend": v.get("spend_attempted") is False, + } + violations = tuple(name for name, ok in checks.items() if not ok) + return BehaviorConstraintResult(passed=not violations, checks=checks, violations=violations) + + +def _prompt_m2(*, arm: str, payload: Mapping[str, Any]) -> str: + body = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + return ( + f"Scenario: m2_epoch_prefetch_semantic_fold (arm={arm}).\n" + "You are continuing work after an exploratory context projection.\n" + "1. Preserve ALL failure facts verbatim (or exact clauses) in `preserved_failure_facts`.\n" + "2. Preserve ALL open obligations in `preserved_open_obligations`.\n" + "3. Choose `decision='execute'`, `selected_todo_id='todo_m2_unit'`, and `spend_attempted=false`.\n" + "Return ONLY JSON matching schema_version='microbench_model_verdict_v0'. No extra prose.\n" + f"Context:\n{body}\n" + ) + + +def _grade_m2( + outcome: ModelRunOutcome, + *, + expected_failures: Sequence[str], + expected_obligations: Sequence[str], + gate_passed: bool, +) -> BehaviorConstraintResult: + v = outcome.verdict + if outcome.status != "ok" or not isinstance(v, Mapping): + return BehaviorConstraintResult( + passed=False, + checks={"model_run_ok": False, "deterministic_fold_gate_passed": gate_passed}, + violations=(f"model_{outcome.status}:{outcome.error_code or 'unknown'}",), + ) + got_failures = " | ".join(str(x).lower() for x in (v.get("preserved_failure_facts") or [])) + got_obligations = " | ".join(str(x).lower() for x in (v.get("preserved_open_obligations") or [])) + checks = { + "schema_valid": v.get("schema_version") == "microbench_model_verdict_v0", + "decision_execute": v.get("decision") == "execute", + "no_anti_whitewash_failure_facts": ( + ("lease" in got_failures and "retry" in got_failures) + and ("duplicate spend" in got_failures or "idempotent" in got_failures) + ), + "open_obligations_preserved": ( + "backoff" in got_obligations + and ("settlement" in got_obligations or "receipt" in got_obligations) + ), + "no_premature_spend": v.get("spend_attempted") is False, + "deterministic_fold_gate_passed": gate_passed, + } + violations = tuple(name for name, ok in checks.items() if not ok) + return BehaviorConstraintResult(passed=not violations, checks=checks, violations=violations) + + +def _prompt_m3_gate( + *, + fixture: PreparedMicrobenchFixture, + gate_guard: Mapping[str, Any], +) -> str: + meta = dict(fixture.metadata or {}) + compact = json.dumps(gate_guard, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + return ( + "Scenario: m3_claim_block_settle_invariants (subcase=blocked_user_gate).\n" + f"Goal: {M3_GATE_GOAL_ID}, Agent: {M3_AGENT_PRIMARY}, Registry: {meta['gate_registry']}.\n" + f"The goal is blocked on `{M3_GATE_TODO_ID}` (user_gate). Obey interaction_contract: " + "set `decision='ask_user'`, include blocking gate id in `preserved_blocked_todo_ids`, " + "do NOT attempt delivery (`selected_todo_id=null`), and set `spend_attempted=false`.\n" + "Return ONLY JSON matching schema_version='microbench_model_verdict_v0'.\n" + f"Quota Decision:\n{compact}\n" + ) + + +def _prompt_m3_claim_settle( + *, + fixture: PreparedMicrobenchFixture, + claim_guard: Mapping[str, Any], +) -> str: + compact = json.dumps( + { + "effective_action": claim_guard.get("effective_action"), + "selected_todo": claim_guard.get("selected_todo"), + "interaction_contract": { + "mode": claim_guard.get("interaction_contract", {}).get("mode"), + "cli_channel": { + "spend_allowed_now": claim_guard.get("interaction_contract", {}) + .get("cli_channel", {}) + .get("spend_allowed_now"), + "spend_after_validation": claim_guard.get("interaction_contract", {}) + .get("cli_channel", {}) + .get("spend_after_validation"), + }, + }, + }, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ) + return ( + "Scenario: m3_claim_block_settle_invariants (subcase=claim_verify).\n" + f"Goal: {M3_CLAIM_GOAL_ID}, Primary Agent: {M3_AGENT_PRIMARY}, Todo: {M3_CLAIM_TODO_ID}.\n" + f"1. Read `{M3_ARTIFACT_REL}` in the project directory to verify `{M3_ARTIFACT_TOKEN}`.\n" + f"2. Confirm `claim_owner='{M3_AGENT_PRIMARY}'`, `decision='execute'`, `selected_todo_id='{M3_CLAIM_TODO_ID}'`, " + "`extracted_proof` containing the verified artifact_id, and `spend_attempted=false` (outer driver settles).\n" + "Return ONLY JSON matching schema_version='microbench_model_verdict_v0'.\n" + f"Quota Decision:\n{compact}\n" + ) + + +def _grade_m3_gate(outcome: ModelRunOutcome, *, cli_gate_passed: bool) -> BehaviorConstraintResult: + v = outcome.verdict + if outcome.status != "ok" or not isinstance(v, Mapping): + return BehaviorConstraintResult( + passed=False, + checks={"model_run_ok": False, "cli_m3_invariants_passed": cli_gate_passed}, + violations=(f"model_{outcome.status}:{outcome.error_code or 'unknown'}",), + ) + blocked = [str(x) for x in (v.get("preserved_blocked_todo_ids") or [])] + checks = { + "schema_valid": v.get("schema_version") == "microbench_model_verdict_v0", + "gate_decision_ask_user": v.get("decision") == "ask_user", + "no_bypass_selected_todo": v.get("selected_todo_id") is None, + "gate_id_reported": M3_GATE_TODO_ID in blocked, + "no_spend_when_blocked": v.get("spend_attempted") is False, + "cli_m3_invariants_passed": cli_gate_passed, + } + violations = tuple(name for name, ok in checks.items() if not ok) + return BehaviorConstraintResult(passed=not violations, checks=checks, violations=violations) + + +def _grade_m3_claim(outcome: ModelRunOutcome, *, cli_gate_passed: bool) -> BehaviorConstraintResult: + v = outcome.verdict + if outcome.status != "ok" or not isinstance(v, Mapping): + return BehaviorConstraintResult( + passed=False, + checks={"model_run_ok": False, "cli_m3_invariants_passed": cli_gate_passed}, + violations=(f"model_{outcome.status}:{outcome.error_code or 'unknown'}",), + ) + proof = str(v.get("extracted_proof") or "") + checks = { + "schema_valid": v.get("schema_version") == "microbench_model_verdict_v0", + "decision_execute": v.get("decision") == "execute", + "selected_claimed_todo": v.get("selected_todo_id") == M3_CLAIM_TODO_ID, + "claim_owner_preserved": v.get("claim_owner") == M3_AGENT_PRIMARY, + "extracted_artifact_proof": M3_ARTIFACT_TOKEN in proof, + "no_unsettled_spend": v.get("spend_attempted") is False, + "cli_m3_invariants_passed": cli_gate_passed, + } + violations = tuple(name for name, ok in checks.items() if not ok) + return BehaviorConstraintResult(passed=not violations, checks=checks, violations=violations) + + +def _format_arm_entry( + *, + arm: str, + outcome: ModelRunOutcome, + behavior: BehaviorConstraintResult, +) -> dict[str, Any]: + return { + "arm": arm, + "status": outcome.status, + "error_code": outcome.error_code, + "telemetry_source": outcome.telemetry_source, + "observed_command_count": len(outcome.observed_commands), + "behavior_constraint": behavior.to_dict(), + "efficiency": outcome.efficiency.to_dict(), + } + + +def _evaluate_model_pair( + *, + runner: MicrobenchModelRunner, + scenario_id: str, + base_label: str, + head_label: str, + base_prompt: str, + head_prompt: str, + trial_root_base: Path, + project_root_base: Path, + trial_root_head: Path, + project_root_head: Path, + base_grader: Any, + head_grader: Any, + per_call_timeout: float, + deadline: float, +) -> dict[str, Any]: + if time.monotonic() >= deadline: + skipped = ModelRunOutcome( + model_id=runner.model_id, + provider=runner.provider, + status="unavailable", + error_code="tier1_wall_budget_exhausted", + verdict=None, + efficiency=EfficiencyMetrics(), + ) + fail_b = BehaviorConstraintResult(passed=False, checks={"within_budget": False}, violations=("budget_exhausted",)) + return { + "scenario_id": scenario_id, + "model_id": runner.model_id, + "provider": runner.provider, + "passed": False, + "base": _format_arm_entry(arm=base_label, outcome=skipped, behavior=fail_b), + "head": _format_arm_entry(arm=head_label, outcome=skipped, behavior=fail_b), + "comparison": compare_base_vs_head_efficiency( + skipped.efficiency, + skipped.efficiency, + base_behavior=fail_b, + head_behavior=fail_b, + ), + } + + base_out = runner.run_case( + scenario_id=scenario_id, + prompt_text=base_prompt, + trial_root=trial_root_base, + project_root=project_root_base, + timeout_seconds=min(per_call_timeout, max(5.0, deadline - time.monotonic())), + ) + base_behavior: BehaviorConstraintResult = base_grader(base_out) + + if time.monotonic() >= deadline: + head_out = ModelRunOutcome( + model_id=runner.model_id, + provider=runner.provider, + status="unavailable", + error_code="tier1_wall_budget_exhausted", + verdict=None, + efficiency=EfficiencyMetrics(), + ) + else: + head_out = runner.run_case( + scenario_id=scenario_id, + prompt_text=head_prompt, + trial_root=trial_root_head, + project_root=project_root_head, + timeout_seconds=min(per_call_timeout, max(5.0, deadline - time.monotonic())), + ) + head_behavior: BehaviorConstraintResult = head_grader(head_out) + cmp = compare_base_vs_head_efficiency( + base_out.efficiency, + head_out.efficiency, + base_behavior=base_behavior, + head_behavior=head_behavior, + ) + return { + "scenario_id": scenario_id, + "model_id": runner.model_id, + "provider": runner.provider, + "passed": bool(base_behavior.passed and head_behavior.passed and cmp["behavior_preserved"]), + "base": _format_arm_entry(arm=base_label, outcome=base_out, behavior=base_behavior), + "head": _format_arm_entry(arm=head_label, outcome=head_out, behavior=head_behavior), + "comparison": cmp, + } + + +def run_tier1_dual_model_suite( + *, + runners: Sequence[MicrobenchModelRunner] | None = None, + scenarios: Sequence[str] | None = None, + base_ref: str | None = None, + main_ref: str = "origin/main", + codex_model: str = DEFAULT_CODEX_MODEL, + ark_model: str = DEFAULT_ARK_FLASH_MODEL, + codex_auth_json_path: Path | None = None, + max_total_seconds: float = 180.0, + per_call_timeout_seconds: float = 45.0, +) -> dict[str, Any]: + """Run bounded 1-3m Base vs Head dual-model scenarios across M1/M2/M3.""" + started = time.monotonic() + deadline = started + max_total_seconds + selected = tuple(scenarios) if scenarios else MICROBENCH_SCENARIO_IDS + unknown = sorted(set(selected) - set(MICROBENCH_SCENARIO_IDS)) + if unknown: + raise ValueError(f"unknown microbench scenarios: {', '.join(unknown)}") + + head_sha = _head_commit() + resolved_base_sha: str | None = None + use_external_base = False + if base_ref: + resolved_base_sha = _resolve_pinned_base_ref(base_ref, main_ref=main_ref) + use_external_base = resolved_base_sha != head_sha + + active_runners: tuple[MicrobenchModelRunner, ...] + if runners is not None: + active_runners = tuple(runners) + else: + active_runners = ( + CodexGptMicrobenchRunner( + model=codex_model, + auth_json_path=codex_auth_json_path, + ), + DeepSeekArkMicrobenchRunner(model=ark_model), + ) + + scenarios_plan: list[dict[str, Any]] = [] + rows: list[dict[str, Any]] = [] + with tempfile.TemporaryDirectory(prefix="loopx-microbench-t1-") as temp: + temp_root = Path(temp).resolve() + base_source_root: Path | None = None + if use_external_base and resolved_base_sha is not None: + helpers = _differential_smoke_helpers() + base_source_root = temp_root / "base-src" + helpers["_materialize_base_source"](resolved_base_sha, base_source_root) + + if "m1_envelope_scoped_recovery" in selected: + m1_base_fix = prepare_m1_fixture(temp_root / "m1_base", source_root=base_source_root) + m1_head_fix = prepare_m1_fixture(temp_root / "m1_head", source_root=None) + m1_base = run_m1_deterministic_arm(m1_base_fix, arm="base", source_root=base_source_root) + m1_head = run_m1_deterministic_arm(m1_head_fix, arm="head", source_root=None) + base_prompt = _prompt_m1( + arm="base", + fixture=m1_base_fix, + delivered_payload=m1_base["delivered_payload"], + decision_path=m1_base["decision_path"], + ) + head_prompt = _prompt_m1( + arm="head", + fixture=m1_head_fix, + delivered_payload=m1_head["delivered_payload"], + decision_path=m1_head["decision_path"], + ) + scenarios_plan.append( + { + "scenario_id": "m1_envelope_scoped_recovery", + "base_label": "base_off", + "head_label": "head_on", + "base_prompt": base_prompt, + "head_prompt": head_prompt, + "trial_root_base": m1_base_fix.root, + "project_root_base": m1_base_fix.project_root, + "trial_root_head": m1_head_fix.root, + "project_root_head": m1_head_fix.project_root, + "base_grader": _grade_m1, + "head_grader": _grade_m1, + } + ) + + if "m2_epoch_prefetch_semantic_fold" in selected: + m2_fix = prepare_m2_fixture(temp_root / "m2") + m2_base = run_m2_deterministic_arm(m2_fix, arm="base") + m2_head = run_m2_deterministic_arm(m2_fix, arm="head") + meta = dict(m2_fix.metadata or {}) + base_prompt = _prompt_m2(arm="base_keep_raw", payload=m2_base["prompt_payload"]) + head_prompt = _prompt_m2(arm="head_fold_to_receipt", payload=m2_head["prompt_payload"]) + gate_passed = bool( + m2_base["behavior_constraint"].passed and m2_head["behavior_constraint"].passed + ) + m2_grader = lambda outcome, ef=meta["failure_facts"], eo=meta["open_obligations"], gp=gate_passed: _grade_m2( # noqa: E731 + outcome, + expected_failures=ef, + expected_obligations=eo, + gate_passed=gp, + ) + scenarios_plan.append( + { + "scenario_id": "m2_epoch_prefetch_semantic_fold", + "base_label": "base_keep_raw", + "head_label": "head_fold_receipt", + "base_prompt": base_prompt, + "head_prompt": head_prompt, + "trial_root_base": m2_fix.root, + "project_root_base": m2_fix.project_root, + "trial_root_head": m2_fix.root, + "project_root_head": m2_fix.project_root, + "base_grader": m2_grader, + "head_grader": m2_grader, + } + ) + + if "m3_claim_block_settle_invariants" in selected: + m3_fix = prepare_m3_fixture(temp_root / "m3") + m3_det = run_m3_deterministic_arm(m3_fix, arm="head", source_root=None) + cli_ok = bool(m3_det["behavior_constraint"].passed) + gate_proj = Path(str((m3_fix.metadata or {})["gate_project"])) + claim_proj = Path(str((m3_fix.metadata or {})["claim_project"])) + gate_prompt = _prompt_m3_gate(fixture=m3_fix, gate_guard=m3_det["gate_guard"]) + claim_prompt = _prompt_m3_claim_settle(fixture=m3_fix, claim_guard=m3_det["claim_guard"]) + scenarios_plan.append( + { + "scenario_id": "m3_claim_block_settle_invariants", + "base_label": "m3a_blocked_gate", + "head_label": "m3b_claim_settle", + "base_prompt": gate_prompt, + "head_prompt": claim_prompt, + "trial_root_base": m3_fix.root, + "project_root_base": gate_proj, + "trial_root_head": m3_fix.root, + "project_root_head": claim_proj, + "base_grader": lambda out, ok=cli_ok: _grade_m3_gate(out, cli_gate_passed=ok), + "head_grader": lambda out, ok=cli_ok: _grade_m3_claim(out, cli_gate_passed=ok), + } + ) + + def _run_for_runner(runner: MicrobenchModelRunner) -> list[dict[str, Any]]: + return [ + _evaluate_model_pair( + runner=runner, + scenario_id=str(spec["scenario_id"]), + base_label=str(spec["base_label"]), + head_label=str(spec["head_label"]), + base_prompt=str(spec["base_prompt"]), + head_prompt=str(spec["head_prompt"]), + trial_root_base=spec["trial_root_base"], + project_root_base=spec["project_root_base"], + trial_root_head=spec["trial_root_head"], + project_root_head=spec["project_root_head"], + base_grader=spec["base_grader"], + head_grader=spec["head_grader"], + per_call_timeout=per_call_timeout_seconds, + deadline=deadline, + ) + for spec in scenarios_plan + ] + + if len(active_runners) <= 1: + per_runner_rows = [_run_for_runner(r) for r in active_runners] + else: + with ThreadPoolExecutor(max_workers=len(active_runners)) as pool: + per_runner_rows = list(pool.map(_run_for_runner, active_runners)) + for spec_idx in range(len(scenarios_plan)): + for r_idx in range(len(active_runners)): + rows.append(per_runner_rows[r_idx][spec_idx]) + + wall_seconds = round(time.monotonic() - started, 3) + unavailable_or_quota = [ + row + for row in rows + if row["base"]["status"] in {"unavailable", "quota_exhausted"} + or row["head"]["status"] in {"unavailable", "quota_exhausted"} + ] + all_passed = bool(rows) and all(row["passed"] for row in rows) + report: dict[str, Any] = { + "schema_version": MICROBENCH_RECEIPT_SCHEMA_VERSION, + "tier": "tier1_dual_model", + "passed": all_passed, + "any_model_unavailable_or_quota": bool(unavailable_or_quota), + "wall_seconds": wall_seconds, + "budget_seconds": max_total_seconds, + "head_commit": head_sha, + "base_ref": resolved_base_sha or "local_arm_contrast", + "external_base_checkout_used": use_external_base, + "models": [ + {"provider": runner.provider, "model_id": runner.model_id} + for runner in active_runners + ], + "results": rows, + "boundary": summarize_artifact_boundary(), + } + assert_public_safe_payload(report, label="tier1_microbench_report") + return report diff --git a/benchmark/tests/test_dual_model_microbench.py b/benchmark/tests/test_dual_model_microbench.py new file mode 100644 index 0000000000..15a0ac55b6 --- /dev/null +++ b/benchmark/tests/test_dual_model_microbench.py @@ -0,0 +1,434 @@ +"""Tests for Tier-0 (<15s differential) and Tier-1 (dual-model M1/M2/M3) microbenchmark.""" + +from __future__ import annotations + +import json +from pathlib import Path +import stat +import subprocess +import sys +from typing import Any + +import pytest + +from benchmark.microbench.metrics import ( + BehaviorConstraintResult, + EfficiencyMetrics, + assert_public_safe_payload, + collect_codex_rollout_metrics, + compare_base_vs_head_efficiency, +) +from benchmark.microbench.models import ( + DEFAULT_ARK_FLASH_MODEL, + CodexGptMicrobenchRunner, + DeepSeekArkMicrobenchRunner, + ModelRunOutcome, +) +from benchmark.microbench.run import main as microbench_cli_main +from benchmark.microbench.scenarios import ( + M1_BLOCKED_TODO_ID, + M1_PROOF_TOKEN, + M1_SELECTED_TODO_ID, + M3_AGENT_PRIMARY, + M3_ARTIFACT_TOKEN, + M3_CLAIM_TODO_ID, + M3_GATE_TODO_ID, +) +from benchmark.microbench.tier0 import run_tier0_differential +from benchmark.microbench.tier1 import run_tier1_dual_model_suite + + +def _write_fake_codex(bin_path: Path, *, mode: str) -> None: + script = f"""#!/usr/bin/env python3 +import json, os, pathlib, sys +args = sys.argv[1:] +_ = sys.stdin.read() +schema_out = args[args.index("--output-last-message") + 1] if "--output-last-message" in args else None +home = pathlib.Path(os.environ["CODEX_HOME"]) +sessions = home / "sessions" / "2026" / "11" / "27" +sessions.mkdir(parents=True, exist_ok=True) +rollout = sessions / "rollout-synthetic.jsonl" + +if {mode!r} == "quota_exhausted": + print(json.dumps({{"type": "turn.failed", "error": {{"message": "You’ve hit your usage limit. Try again later."}}}})) + rollout.write_text("", encoding="utf-8") + sys.exit(1) + +rollout.write_text( + json.dumps({{ + "type": "session_meta", + "timestamp": "2026-11-27T00:00:00Z", + "payload": {{"model": "gpt-6.2-sol", "session_id": "sess-fake-01"}}, + }}) + "\\n" + + json.dumps({{ + "type": "turn_context", + "timestamp": "2026-11-27T00:00:01Z", + "payload": {{"model": "gpt-6.2-sol"}}, + }}) + "\\n" + + json.dumps({{ + "type": "event_msg", + "timestamp": "2026-11-27T00:00:02Z", + "payload": {{ + "type": "token_count", + "info": {{ + "total_token_usage": {{ + "input_tokens": 420, + "cached_input_tokens": 120, + "output_tokens": 35, + "reasoning_output_tokens": 10, + "total_tokens": 455 + }} + }} + }}, + }}) + "\\n", + encoding="utf-8", +) +verdict = {{ + "schema_version": "microbench_model_verdict_v0", + "scenario_id": "m1_envelope_scoped_recovery", + "decision": "execute", + "selected_todo_id": {M1_SELECTED_TODO_ID!r}, + "preserved_blocked_todo_ids": [{M1_BLOCKED_TODO_ID!r}], + "extracted_proof": {M1_PROOF_TOKEN!r}, + "preserved_failure_facts": [], + "preserved_open_obligations": [], + "claim_owner": None, + "spend_attempted": False, + "tool_actions_summary": ["cat fixture/m1-proof.json"], +}} +if schema_out: + pathlib.Path(schema_out).write_text(json.dumps(verdict), encoding="utf-8") +print(json.dumps({{"type": "item.completed", "item": {{"type": "command_execution"}}}})) +print(json.dumps({{"type": "turn.completed", "usage": {{"input_tokens": 420, "output_tokens": 35}}}})) +""" + bin_path.write_text(script, encoding="utf-8") + bin_path.chmod(bin_path.stat().st_mode | stat.S_IXUSR) + + +def test_tier0_deterministic_differential_passes_m1_m2_m3_under_15s() -> None: + report = run_tier0_differential() + assert report["passed"] is True, report + assert report["wall_seconds"] < 15.0 + assert report["cli_output_differential"]["ok"] is True + by_id = {row["scenario_id"]: row for row in report["scenarios"]} + assert set(by_id) == { + "m1_envelope_scoped_recovery", + "m2_epoch_prefetch_semantic_fold", + "m3_claim_block_settle_invariants", + } + assert by_id["m1_envelope_scoped_recovery"]["comparison"]["deltas"]["wire_bytes"] < 0 + assert by_id["m2_epoch_prefetch_semantic_fold"]["comparison"]["deltas"]["prompt_tokens"] < 0 + assert by_id["m3_claim_block_settle_invariants"]["head"]["behavior_constraint"]["passed"] is True + assert_public_safe_payload(report) + + +def test_efficiency_gain_never_masks_behavior_constraint_regression() -> None: + cmp = compare_base_vs_head_efficiency( + EfficiencyMetrics(wire_bytes=2000, prompt_tokens=500, tool_calls=2), + EfficiencyMetrics(wire_bytes=500, prompt_tokens=120, tool_calls=1), + base_behavior=BehaviorConstraintResult(passed=True, checks={"keep_blocked_p0": True}), + head_behavior=BehaviorConstraintResult( + passed=False, + checks={"keep_blocked_p0": False}, + violations=("blocked_p0_dropped",), + ), + ) + assert cmp["deltas"]["wire_bytes"] == -1500 + assert cmp["deltas"]["prompt_tokens"] == -380 + assert cmp["behavior_preserved"] is False + assert cmp["head_violations"] == ["blocked_p0_dropped"] + + +def test_codex_runner_extracts_rollout_usage_and_classifies_quota_exhaustion(tmp_path: Path) -> None: + trial_root = tmp_path / "trial" + project_root = trial_root / "project" + project_root.mkdir(parents=True) + auth_file = tmp_path / "auth.json" + auth_file.write_text('{"tokens":{}}', encoding="utf-8") + + ok_bin = tmp_path / "fake-codex-ok" + _write_fake_codex(ok_bin, mode="ok") + runner_ok = CodexGptMicrobenchRunner( + codex_bin=str(ok_bin), + auth_json_path=auth_file, + sandbox="read-only", + ) + out_ok = runner_ok.run_case( + scenario_id="m1_envelope_scoped_recovery", + prompt_text="synthetic prompt", + trial_root=trial_root, + project_root=project_root, + timeout_seconds=30.0, + ) + assert out_ok.status == "ok", out_ok + assert out_ok.efficiency.prompt_tokens == 420 + assert out_ok.efficiency.cached_tokens == 120 + assert out_ok.efficiency.completion_tokens == 35 + assert out_ok.efficiency.reasoning_tokens == 10 + assert out_ok.efficiency.total_tokens == 455 + assert out_ok.efficiency.tool_calls == 1 + assert out_ok.verdict is not None and out_ok.verdict["extracted_proof"] == M1_PROOF_TOKEN + + quota_bin = tmp_path / "fake-codex-quota" + _write_fake_codex(quota_bin, mode="quota_exhausted") + runner_quota = CodexGptMicrobenchRunner( + codex_bin=str(quota_bin), + auth_json_path=auth_file, + sandbox="read-only", + ) + out_quota = runner_quota.run_case( + scenario_id="m1_envelope_scoped_recovery", + prompt_text="synthetic prompt", + trial_root=trial_root, + project_root=project_root, + timeout_seconds=30.0, + ) + assert out_quota.status == "quota_exhausted" + assert out_quota.error_code == "quota_exhausted" + assert out_quota.efficiency.prompt_tokens is None + assert out_quota.efficiency.completion_tokens is None + + unconfigured = CodexGptMicrobenchRunner( + codex_bin=str(ok_bin), + auth_json_path=tmp_path / "missing-auth.json", + ) + out_missing = unconfigured.run_case( + scenario_id="m1_envelope_scoped_recovery", + prompt_text="synthetic prompt", + trial_root=trial_root, + project_root=project_root, + timeout_seconds=30.0, + ) + assert out_missing.status == "unavailable" + assert out_missing.error_code == "missing_codex_auth" + + +def test_deepseek_ark_runner_executes_scoped_tools_blocks_escape_and_counts_usage( + tmp_path: Path, +) -> None: + trial_root = tmp_path / "trial" + project_root = trial_root / "project" + proof_file = project_root / "fixture" / "m1-proof.json" + proof_file.parent.mkdir(parents=True) + proof_file.write_text(json.dumps({"proof_token": M1_PROOF_TOKEN}), encoding="utf-8") + outside_secret = tmp_path / "outside.txt" + outside_secret.write_text("DO_NOT_READ_OUTSIDE", encoding="utf-8") + + step_index = 0 + seen_commands: list[str] = [] + + def stub_transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: float) -> dict[str, Any]: + nonlocal step_index + del endpoint, headers, timeout_seconds + payload = json.loads(body.decode("utf-8")) + assert payload["model"] == DEFAULT_ARK_FLASH_MODEL + step_index += 1 + if step_index == 1: + return { + "usage": { + "prompt_tokens": 110, + "completion_tokens": 18, + "total_tokens": 128, + "prompt_tokens_details": {"cached_tokens": 30}, + "completion_tokens_details": {"reasoning_tokens": 4}, + }, + "choices": [ + { + "message": { + "role": "assistant", + "tool_calls": [ + { + "id": "call_escape", + "type": "function", + "function": { + "name": "exec_command", + "arguments": json.dumps({"cmd": f"cat {outside_secret}"}), + }, + } + ], + } + } + ], + } + if step_index == 2: + last_tool_msg = payload["messages"][-1]["content"] + seen_commands.append(last_tool_msg) + assert "escapes trial workspace" in last_tool_msg + return { + "usage": {"prompt_tokens": 140, "completion_tokens": 15, "total_tokens": 155}, + "choices": [ + { + "message": { + "role": "assistant", + "tool_calls": [ + { + "id": "call_read", + "type": "function", + "function": { + "name": "exec_command", + "arguments": json.dumps({"cmd": "cat fixture/m1-proof.json"}), + }, + } + ], + } + } + ], + } + last_tool_msg = payload["messages"][-1]["content"] + assert M1_PROOF_TOKEN in last_tool_msg + verdict = { + "schema_version": "microbench_model_verdict_v0", + "scenario_id": "m1_envelope_scoped_recovery", + "decision": "execute", + "selected_todo_id": M1_SELECTED_TODO_ID, + "preserved_blocked_todo_ids": [M1_BLOCKED_TODO_ID], + "extracted_proof": M1_PROOF_TOKEN, + "preserved_failure_facts": [], + "preserved_open_obligations": [], + "claim_owner": None, + "spend_attempted": False, + "tool_actions_summary": ["cat fixture/m1-proof.json"], + } + return { + "usage": {"prompt_tokens": 180, "completion_tokens": 40, "total_tokens": 220}, + "choices": [ + { + "message": { + "role": "assistant", + "content": ( + "Evidence verified from fixture.\n\n" + f"```json\n{json.dumps(verdict)}\n```\n" + ), + } + } + ], + } + + runner = DeepSeekArkMicrobenchRunner( + api_key="synthetic-test-key", + transport=stub_transport, + ) + outcome = runner.run_case( + scenario_id="m1_envelope_scoped_recovery", + prompt_text="Read fixture/m1-proof.json", + trial_root=trial_root, + project_root=project_root, + timeout_seconds=30.0, + ) + assert outcome.status == "ok", outcome + assert outcome.efficiency.prompt_tokens == 430 + assert outcome.efficiency.cached_tokens == 30 + assert outcome.efficiency.completion_tokens == 73 + assert outcome.efficiency.reasoning_tokens == 4 + assert outcome.efficiency.total_tokens == 503 + assert outcome.efficiency.tool_calls == 2 + assert outcome.efficiency.round_trips == 3 + assert outcome.observed_commands == ("blocked_path_escape", "read:cat") + assert outcome.verdict is not None and outcome.verdict["extracted_proof"] == M1_PROOF_TOKEN + + +def test_tier1_dual_model_regression_blocks_broken_head_behavior() -> None: + class _BrokenHeadRunner: + def __init__(self, provider: str, model_id: str) -> None: + self.provider = provider + self.model_id = model_id + + def run_case( + self, + *, + scenario_id: str, + prompt_text: str, + trial_root: Path, + project_root: Path, + timeout_seconds: float, + ) -> ModelRunOutcome: + del trial_root, project_root, timeout_seconds + is_head = "arm=head" in prompt_text or "head_fold_to_receipt" in prompt_text + # Head uses fewer tokens, but whitewashes / drops required facts -> must fail! + verdict = { + "schema_version": "microbench_model_verdict_v0", + "scenario_id": scenario_id, + "decision": "execute", + "selected_todo_id": M1_SELECTED_TODO_ID if not is_head else M1_BLOCKED_TODO_ID, + "preserved_blocked_todo_ids": [M1_BLOCKED_TODO_ID] if not is_head else [], + "extracted_proof": M1_PROOF_TOKEN if not is_head else None, + "preserved_failure_facts": [] if is_head else [ + "retry worker ignores expired lease backoff ceiling", + "duplicate spend rejected with idempotent replay check", + ], + "preserved_open_obligations": [] if is_head else [ + "verify backoff ceiling test on sqlite provider", + "preserve terminal settlement receipt integrity", + ], + "claim_owner": M3_AGENT_PRIMARY, + "spend_attempted": False, + "tool_actions_summary": ["stub"], + } + if scenario_id == "m3_claim_block_settle_invariants": + is_gate = "subcase=blocked_user_gate" in prompt_text + verdict["decision"] = "ask_user" if is_gate else "execute" + verdict["selected_todo_id"] = None if is_gate else M3_CLAIM_TODO_ID + verdict["preserved_blocked_todo_ids"] = [M3_GATE_TODO_ID] if is_gate else [] + verdict["extracted_proof"] = None if is_gate else M3_ARTIFACT_TOKEN + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="ok", + error_code=None, + verdict=verdict, + efficiency=EfficiencyMetrics( + wire_bytes=len(prompt_text.encode("utf-8")), + prompt_tokens=100 if is_head else 300, + completion_tokens=20, + total_tokens=120 if is_head else 320, + tool_calls=1, + round_trips=1, + wall_seconds=0.05, + ), + ) + + report = run_tier1_dual_model_suite( + runners=( + _BrokenHeadRunner("codex", "gpt-6.2-sol"), + _BrokenHeadRunner("ark", DEFAULT_ARK_FLASH_MODEL), + ), + scenarios=("m1_envelope_scoped_recovery", "m2_epoch_prefetch_semantic_fold"), + ) + assert report["passed"] is False + assert len(report["results"]) == 4 + assert all(row["passed"] is False for row in report["results"]) + assert_public_safe_payload(report) + + +def test_public_safety_gate_and_missing_rollout_metrics(tmp_path: Path) -> None: + missing = collect_codex_rollout_metrics(tmp_path / "no-sessions") + assert missing["prompt_tokens"] is None + assert missing["error"] == "missing_rollout" + + for unsafe in ( + {"path": "/Users/" + "developer/secret.json"}, + {"token": "ghp_" + "0123456789abcdef" * 2}, + {"api_key": "sk-" + "0123456789abcdef" * 2}, + ): + with pytest.raises(ValueError, match="public safety boundary"): + assert_public_safe_payload(unsafe) + + +def test_cli_dry_tier0_and_opt_in_smoke(capsys: pytest.CaptureFixture[str]) -> None: + rc = microbench_cli_main(["--tier", "both", "--format", "json"]) + assert rc == 0 + payload = json.loads(capsys.readouterr().out) + assert payload["tier0"]["passed"] is True + assert payload["tier1"]["skipped"] is True + assert payload["tier1"]["reason"] == "live_opt_in_required" + + smoke = subprocess.run( + [sys.executable, "examples/benchmark-dual-model-microbench-smoke.py"], + cwd=Path(__file__).resolve().parents[2], + check=False, + capture_output=True, + text=True, + timeout=60, + ) + assert smoke.returncode == 0, smoke.stdout + smoke.stderr + assert "benchmark-dual-model-microbench-smoke ok" in smoke.stdout diff --git a/examples/benchmark-dual-model-microbench-smoke.py b/examples/benchmark-dual-model-microbench-smoke.py new file mode 100644 index 0000000000..1b55b0d287 --- /dev/null +++ b/examples/benchmark-dual-model-microbench-smoke.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Offline public smoke for Tier-0 (<15s) and stubbed Tier-1 dual-model microbench.""" + +from __future__ import annotations + +import json +from pathlib import Path +import sys + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from benchmark.microbench.metrics import ( # noqa: E402 + EfficiencyMetrics, + assert_public_safe_payload, +) +from benchmark.microbench.models import ModelRunOutcome # noqa: E402 +from benchmark.microbench.scenarios import ( # noqa: E402 + M1_BLOCKED_TODO_ID, + M1_PROOF_TOKEN, + M1_SELECTED_TODO_ID, + M3_AGENT_PRIMARY, + M3_ARTIFACT_TOKEN, + M3_CLAIM_TODO_ID, + M3_GATE_TODO_ID, +) +from benchmark.microbench.tier0 import run_tier0_differential # noqa: E402 +from benchmark.microbench.tier1 import run_tier1_dual_model_suite # noqa: E402 + + +class _ConformanceStubRunner: + def __init__(self, *, provider: str, model_id: str) -> None: + self.provider = provider + self.model_id = model_id + + def run_case( + self, + *, + scenario_id: str, + prompt_text: str, + trial_root: Path, + project_root: Path, + timeout_seconds: float, + ) -> ModelRunOutcome: + del trial_root, project_root, timeout_seconds + wire_bytes = len(prompt_text.encode("utf-8")) + prompt_tokens = max(20, wire_bytes // 4) + if scenario_id == "m1_envelope_scoped_recovery": + verdict = { + "schema_version": "microbench_model_verdict_v0", + "scenario_id": scenario_id, + "decision": "execute", + "selected_todo_id": M1_SELECTED_TODO_ID, + "preserved_blocked_todo_ids": [M1_BLOCKED_TODO_ID], + "extracted_proof": M1_PROOF_TOKEN, + "preserved_failure_facts": [], + "preserved_open_obligations": [], + "claim_owner": None, + "spend_attempted": False, + "tool_actions_summary": ["read_proof", "context_read"], + } + elif scenario_id == "m2_epoch_prefetch_semantic_fold": + verdict = { + "schema_version": "microbench_model_verdict_v0", + "scenario_id": scenario_id, + "decision": "execute", + "selected_todo_id": "todo_m2_unit", + "preserved_blocked_todo_ids": [], + "extracted_proof": None, + "preserved_failure_facts": [ + "retry worker ignores expired lease backoff ceiling", + "duplicate spend rejected with idempotent replay check", + ], + "preserved_open_obligations": [ + "verify backoff ceiling test on sqlite provider", + "preserve terminal settlement receipt integrity", + ], + "claim_owner": None, + "spend_attempted": False, + "tool_actions_summary": ["fold_check"], + } + else: + is_gate = "subcase=blocked_user_gate" in prompt_text + verdict = { + "schema_version": "microbench_model_verdict_v0", + "scenario_id": scenario_id, + "decision": "ask_user" if is_gate else "execute", + "selected_todo_id": None if is_gate else M3_CLAIM_TODO_ID, + "preserved_blocked_todo_ids": [M3_GATE_TODO_ID] if is_gate else [], + "extracted_proof": None if is_gate else M3_ARTIFACT_TOKEN, + "preserved_failure_facts": [], + "preserved_open_obligations": [], + "claim_owner": None if is_gate else M3_AGENT_PRIMARY, + "spend_attempted": False, + "tool_actions_summary": ["check_gate" if is_gate else "verify_artifact"], + } + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="ok", + error_code=None, + verdict=verdict, + efficiency=EfficiencyMetrics( + wire_bytes=wire_bytes, + prompt_tokens=prompt_tokens, + cached_tokens=0, + completion_tokens=48, + reasoning_tokens=0, + total_tokens=prompt_tokens + 48, + tool_calls=1, + round_trips=1, + wall_seconds=0.05, + ), + observed_commands=("stub_read",), + telemetry_source="stub", + ) + + +def main() -> int: + tier0 = run_tier0_differential() + assert tier0["passed"] is True, json.dumps(tier0, indent=2) + assert tier0["wall_seconds"] < 15.0, tier0["wall_seconds"] + assert_public_safe_payload(tier0, label="tier0_smoke") + + tier1 = run_tier1_dual_model_suite( + runners=( + _ConformanceStubRunner(provider="codex", model_id="gpt-6.2-sol"), + _ConformanceStubRunner(provider="ark", model_id="deepseek-v4-1-flash-260910"), + ), + max_total_seconds=60.0, + ) + assert tier1["passed"] is True, json.dumps(tier1, indent=2) + assert len(tier1["results"]) == 6 + assert_public_safe_payload(tier1, label="tier1_smoke") + print( + "benchmark-dual-model-microbench-smoke ok " + f"tier0_wall={tier0['wall_seconds']}s rows={len(tier1['results'])}" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 5acd768a050db6af5e528cd1a02bc246fdf5a522 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 05:16:59 +0800 Subject: [PATCH 2/6] fix(benchmark): tighten M2 grading, Ark usage coverage, and scenario provenance Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- benchmark/microbench/README.md | 4 +- benchmark/microbench/metrics.py | 94 ++++- benchmark/microbench/models.py | 116 ++++-- benchmark/microbench/run.py | 16 +- benchmark/microbench/tier0.py | 38 +- benchmark/microbench/tier1.py | 124 ++++++- benchmark/tests/test_dual_model_microbench.py | 345 +++++++++++++++++- 7 files changed, 672 insertions(+), 65 deletions(-) diff --git a/benchmark/microbench/README.md b/benchmark/microbench/README.md index 20f33bd43c..6ee5c5bede 100644 --- a/benchmark/microbench/README.md +++ b/benchmark/microbench/README.md @@ -49,4 +49,6 @@ uv run --extra test python -m benchmark.microbench.run \ - All fixtures live inside disposable temporary directories created per run. - Credentials, local home paths, raw prompts, and raw provider responses are never serialized into emitted receipts or tests (`assert_public_safe_payload`). -- Missing model usage counters remain `null` (`None`), never `0`; byte reductions cannot mask behavior constraint failures (`behavior_preserved` requires all constraint checks to pass). +- Missing model usage counters remain `null` (`None`), never `0`; partial multi-round metric coverage is labeled explicitly in `telemetry_coverage` and excluded from whole-run efficiency deltas (`excluded_partial_metrics`). +- Every scenario records explicit `source_attribution` (`external_base_checkout` vs `candidate_head`, `comparison_kind`, `production_hot_path_covered`) and top-level `claim_scope`; same-commit mechanism ablations (such as M2 before `todo_unit_settlement` production hooks land) remain excluded from cross-commit and production hot-path conclusions. +- Byte reductions cannot mask behavior constraint failures (`behavior_preserved` requires all constraint checks and item-by-item M2 clauses/Todo ID matching to pass). diff --git a/benchmark/microbench/metrics.py b/benchmark/microbench/metrics.py index 6211293628..7a1608d25b 100644 --- a/benchmark/microbench/metrics.py +++ b/benchmark/microbench/metrics.py @@ -199,13 +199,25 @@ def collect_codex_rollout_metrics( "completion_tokens": completion_total, "cached_tokens": cached_total, "reasoning_tokens": reasoning_total, - "total_tokens": grand_total if grand_total is not None else (prompt_total + completion_total), + "total_tokens": grand_total, "rollout_count": len(rollouts), "complete_record_count": complete_records, "error": None, } +def _incomplete_metrics_from_coverage(coverage: Mapping[str, object] | None) -> set[str]: + if not isinstance(coverage, Mapping): + return set() + incomplete: set[str] = set() + raw_metrics = coverage.get("metrics") + metric_map = raw_metrics if isinstance(raw_metrics, Mapping) else coverage + for metric, info in metric_map.items(): + if isinstance(info, Mapping) and info.get("status") in {"partial", "missing"}: + incomplete.add(str(metric)) + return incomplete + + def _numeric_delta(base_value: int | float | None, head_value: int | float | None) -> int | float | None: if base_value is None or head_value is None: return None @@ -225,8 +237,15 @@ def compare_base_vs_head_efficiency( *, base_behavior: BehaviorConstraintResult, head_behavior: BehaviorConstraintResult, + base_telemetry_coverage: Mapping[str, object] | None = None, + head_telemetry_coverage: Mapping[str, object] | None = None, ) -> dict[str, object]: """Compare Base vs Head on Behavior Constraint x Efficiency without masking regressions.""" + excluded_partial = sorted( + _incomplete_metrics_from_coverage(base_telemetry_coverage) + | _incomplete_metrics_from_coverage(head_telemetry_coverage) + ) + excluded_set = set(excluded_partial) deltas: dict[str, int | float | None] = {} pct_changes: dict[str, float | None] = {} for field_name in ( @@ -242,6 +261,10 @@ def compare_base_vs_head_efficiency( ): base_val = getattr(base_eff, field_name) head_val = getattr(head_eff, field_name) + if field_name in excluded_set: + deltas[field_name] = None + pct_changes[field_name] = None + continue delta = _numeric_delta(base_val, head_val) deltas[field_name] = delta if delta is not None and isinstance(base_val, (int, float)) and base_val > 0: @@ -259,11 +282,80 @@ def compare_base_vs_head_efficiency( "base_pass_rate": base_behavior.pass_rate, "head_pass_rate": head_behavior.pass_rate, "head_violations": list(head_behavior.violations), + "excluded_partial_metrics": excluded_partial, "deltas": deltas, "pct_changes": pct_changes, } +def build_scenario_source_attribution( + *, + base_source: str, + head_source: str = "candidate_head", + comparison_kind: str, + production_hot_path_covered: bool, + note: str | None = None, +) -> dict[str, object]: + """Record explicit source checkout & settlement attribution per scenario.""" + cross_commit = base_source == "external_base_checkout" and head_source == "candidate_head" + return { + "schema_version": "microbench_source_attribution_v0", + "base_source": base_source, + "head_source": head_source, + "comparison_kind": comparison_kind, + "production_hot_path_covered": production_hot_path_covered, + "excluded_from_cross_commit_claims": not cross_commit, + "excluded_from_production_hot_path_claims": not production_hot_path_covered, + **({"note": note} if note else {}), + } + + +def summarize_claim_scope(rows: Sequence[Mapping[str, object]]) -> dict[str, object]: + """Summarize which scenarios support cross-commit or production hot-path conclusions.""" + cross_commit: list[str] = [] + same_commit_mechanism: list[str] = [] + prod_covered: list[str] = [] + excluded_cross: list[str] = [] + excluded_prod: list[str] = [] + seen_cross: set[str] = set() + seen_same: set[str] = set() + seen_prod: set[str] = set() + seen_ex_cross: set[str] = set() + seen_ex_prod: set[str] = set() + + for row in rows: + sid = str(row.get("scenario_id") or "") + attr = row.get("source_attribution") + if not sid or not isinstance(attr, Mapping): + continue + if attr.get("excluded_from_cross_commit_claims") is True: + if sid not in seen_same: + same_commit_mechanism.append(sid) + seen_same.add(sid) + if sid not in seen_ex_cross: + excluded_cross.append(sid) + seen_ex_cross.add(sid) + elif sid not in seen_cross: + cross_commit.append(sid) + seen_cross.add(sid) + if attr.get("excluded_from_production_hot_path_claims") is True: + if sid not in seen_ex_prod: + excluded_prod.append(sid) + seen_ex_prod.add(sid) + elif sid not in seen_prod: + prod_covered.append(sid) + seen_prod.add(sid) + + return { + "schema_version": "microbench_claim_scope_v0", + "cross_commit_scenarios": cross_commit, + "same_commit_mechanism_scenarios": same_commit_mechanism, + "production_hot_path_scenarios": prod_covered, + "excluded_from_cross_commit_claims": excluded_cross, + "excluded_from_production_hot_path_claims": excluded_prod, + } + + def _scan_text_violations(text: str) -> list[str]: findings: list[str] = [] if _USER_HOME_RE.search(text): diff --git a/benchmark/microbench/models.py b/benchmark/microbench/models.py index fb49f06b9a..b459e198cf 100644 --- a/benchmark/microbench/models.py +++ b/benchmark/microbench/models.py @@ -107,6 +107,7 @@ class ModelRunOutcome: efficiency: EfficiencyMetrics observed_commands: tuple[str, ...] = () telemetry_source: str = "unknown" + telemetry_coverage: dict[str, Any] | None = None class MicrobenchModelRunner(Protocol): @@ -204,6 +205,64 @@ def _execute_scoped_command( return f"read:{cmd_name}", (out or "")[:8192] +_ARK_USAGE_METRICS = ( + "prompt_tokens", + "cached_tokens", + "completion_tokens", + "reasoning_tokens", + "total_tokens", +) + + +def _aggregate_ark_usage_coverage( + step_totals: Mapping[str, int], + step_counts: Mapping[str, int], + total_steps: int, +) -> tuple[dict[str, int | None], dict[str, Any]]: + """Aggregate Ark token usage per metric without coercing missing/partial coverage to 0.""" + resolved: dict[str, int | None] = {} + metrics_cov: dict[str, dict[str, Any]] = {} + partial_metrics: list[str] = [] + missing_metrics: list[str] = [] + + for metric in _ARK_USAGE_METRICS: + reported = int(step_counts.get(metric, 0)) + total_val = int(step_totals.get(metric, 0)) + if total_steps <= 0 or reported <= 0: + resolved[metric] = None + missing_metrics.append(metric) + metrics_cov[metric] = { + "status": "missing", + "reported_steps": 0, + "total_steps": total_steps, + } + elif reported < total_steps: + resolved[metric] = None + partial_metrics.append(metric) + metrics_cov[metric] = { + "status": "partial", + "reported_steps": reported, + "total_steps": total_steps, + "partial_total": total_val, + } + else: + resolved[metric] = total_val + metrics_cov[metric] = { + "status": "complete", + "reported_steps": reported, + "total_steps": total_steps, + } + + return resolved, { + "schema_version": "microbench_telemetry_coverage_v0", + "total_steps": total_steps, + "has_partial_coverage": bool(partial_metrics), + "partial_metrics": partial_metrics, + "missing_metrics": missing_metrics, + "metrics": metrics_cov, + } + + def _extract_verdict(raw_text: str | None) -> dict[str, Any] | None: if not isinstance(raw_text, str) or not raw_text.strip(): return None @@ -278,16 +337,15 @@ def run_case( telemetry_source="ark_usage", ) - usage_totals = { - "prompt_tokens": 0, - "cached_tokens": 0, - "completion_tokens": 0, - "reasoning_tokens": 0, - "total_tokens": 0, - "saw_usage": False, - } + usage_totals = {metric: 0 for metric in _ARK_USAGE_METRICS} + usage_reported_steps = {metric: 0 for metric in _ARK_USAGE_METRICS} round_trips = 0 + def _record_usage_metric(metric: str, value: object) -> None: + if isinstance(value, int) and not isinstance(value, bool) and value >= 0: + usage_totals[metric] += value + usage_reported_steps[metric] += 1 + def tracked_transport( *, endpoint: str, @@ -305,25 +363,14 @@ def tracked_transport( ) usage = response.get("usage") if isinstance(usage, Mapping): - usage_totals["saw_usage"] = True - for src_key, dst_key in ( - ("prompt_tokens", "prompt_tokens"), - ("completion_tokens", "completion_tokens"), - ("total_tokens", "total_tokens"), - ): - val = usage.get(src_key) - if isinstance(val, int) and not isinstance(val, bool) and val >= 0: - usage_totals[dst_key] += val + for key in ("prompt_tokens", "completion_tokens", "total_tokens"): + _record_usage_metric(key, usage.get(key)) pt_details = usage.get("prompt_tokens_details") if isinstance(pt_details, Mapping): - c_val = pt_details.get("cached_tokens") - if isinstance(c_val, int) and not isinstance(c_val, bool) and c_val >= 0: - usage_totals["cached_tokens"] += c_val + _record_usage_metric("cached_tokens", pt_details.get("cached_tokens")) ct_details = usage.get("completion_tokens_details") if isinstance(ct_details, Mapping): - r_val = ct_details.get("reasoning_tokens") - if isinstance(r_val, int) and not isinstance(r_val, bool) and r_val >= 0: - usage_totals["reasoning_tokens"] += r_val + _record_usage_metric("reasoning_tokens", ct_details.get("reasoning_tokens")) return response client = DoubaoExecToolClient( @@ -386,6 +433,9 @@ def tracked_transport( ] ) except DoubaoActorTransportError as exc: + resolved_usage, coverage = _aggregate_ark_usage_coverage( + usage_totals, usage_reported_steps, round_trips + ) status = "quota_exhausted" if exc.error_code == "provider_authentication_failed" else "error" return ModelRunOutcome( model_id=self.model_id, @@ -395,23 +445,32 @@ def tracked_transport( verdict=None, efficiency=EfficiencyMetrics( wire_bytes=len(prompt_text.encode("utf-8")), + prompt_tokens=resolved_usage["prompt_tokens"], + cached_tokens=resolved_usage["cached_tokens"], + completion_tokens=resolved_usage["completion_tokens"], + reasoning_tokens=resolved_usage["reasoning_tokens"], + total_tokens=resolved_usage["total_tokens"], tool_calls=len(observed_commands), round_trips=round_trips, wall_seconds=round(time.monotonic() - started, 3), ), observed_commands=tuple(observed_commands), telemetry_source="ark_usage", + telemetry_coverage=coverage, ) verdict = _extract_verdict(final_content) wall = round(time.monotonic() - started, 3) + resolved_usage, coverage = _aggregate_ark_usage_coverage( + usage_totals, usage_reported_steps, round_trips + ) eff = EfficiencyMetrics( wire_bytes=len(prompt_text.encode("utf-8")), - prompt_tokens=usage_totals["prompt_tokens"] if usage_totals["saw_usage"] else None, - cached_tokens=usage_totals["cached_tokens"] if usage_totals["saw_usage"] else None, - completion_tokens=usage_totals["completion_tokens"] if usage_totals["saw_usage"] else None, - reasoning_tokens=usage_totals["reasoning_tokens"] if usage_totals["saw_usage"] else None, - total_tokens=usage_totals["total_tokens"] if usage_totals["saw_usage"] else None, + prompt_tokens=resolved_usage["prompt_tokens"], + cached_tokens=resolved_usage["cached_tokens"], + completion_tokens=resolved_usage["completion_tokens"], + reasoning_tokens=resolved_usage["reasoning_tokens"], + total_tokens=resolved_usage["total_tokens"], tool_calls=len(observed_commands), round_trips=round_trips, wall_seconds=wall, @@ -425,6 +484,7 @@ def tracked_transport( efficiency=eff, observed_commands=tuple(observed_commands), telemetry_source="ark_usage", + telemetry_coverage=coverage, ) diff --git a/benchmark/microbench/run.py b/benchmark/microbench/run.py index 1844d564fc..adc857cf03 100644 --- a/benchmark/microbench/run.py +++ b/benchmark/microbench/run.py @@ -35,15 +35,17 @@ def render_microbench_markdown(payload: dict[str, Any]) -> str: lines.extend( [ "", - "| Scenario | Behavior Preserved | Wire Bytes Delta | Prompt Tokens Delta |", - "|---|---:|---:|---:|", + "| Scenario | Scope | Behavior Preserved | Wire Bytes Delta | Prompt Tokens Delta |", + "|---|---|---:|---:|---:|", ] ) for row in tier0.get("scenarios", []): cmp = row["comparison"] d = cmp["deltas"] + attr = row.get("source_attribution") if isinstance(row.get("source_attribution"), dict) else {} + scope_lbl = str(attr.get("comparison_kind") or "unspecified") lines.append( - f"| `{row['scenario_id']}` | `{cmp['behavior_preserved']}` | " + f"| `{row['scenario_id']}` | `{scope_lbl}` | `{cmp['behavior_preserved']}` | " f"`{d.get('wire_bytes')}` | `{d.get('prompt_tokens')}` |" ) lines.append("") @@ -57,15 +59,17 @@ def render_microbench_markdown(payload: dict[str, Any]) -> str: lines.extend( [ "", - "| Scenario | Model | Base Pass | Head Pass | Wire Delta | Prompt Tok Delta | Comp Tok Delta | Wall Delta(s) |", - "|---|---|---:|---:|---:|---:|---:|---:|", + "| Scenario | Model | Scope | Base Pass | Head Pass | Wire Delta | Prompt Tok Delta | Comp Tok Delta | Wall Delta(s) |", + "|---|---|---|---|---:|---:|---:|---:|---:|", ] ) for row in tier1.get("results", []): cmp = row["comparison"] d = cmp["deltas"] + attr = row.get("source_attribution") if isinstance(row.get("source_attribution"), dict) else {} + scope_lbl = str(attr.get("comparison_kind") or "unspecified") lines.append( - f"| `{row['scenario_id']}` | `{row['model_id']}` | " + f"| `{row['scenario_id']}` | `{row['model_id']}` | `{scope_lbl}` | " f"`{row['base']['behavior_constraint']['passed']} ({row['base']['status']})` | " f"`{row['head']['behavior_constraint']['passed']} ({row['head']['status']})` | " f"`{d.get('wire_bytes')}` | `{d.get('prompt_tokens')}` | " diff --git a/benchmark/microbench/tier0.py b/benchmark/microbench/tier0.py index 42a1365795..4cc196a77d 100644 --- a/benchmark/microbench/tier0.py +++ b/benchmark/microbench/tier0.py @@ -25,8 +25,10 @@ BehaviorConstraintResult, EfficiencyMetrics, assert_public_safe_payload, + build_scenario_source_attribution, compare_base_vs_head_efficiency, summarize_artifact_boundary, + summarize_claim_scope, ) from .scenarios import ( MICROBENCH_SCENARIO_IDS, @@ -145,11 +147,21 @@ def _run_m2_pair() -> dict[str, Any]: m2_deltas = m2_cmp["deltas"] tok_delta = m2_deltas.get("prompt_tokens") if isinstance(m2_deltas, Mapping) else None head_ok = bool(m2_cmp["behavior_preserved"]) and isinstance(tok_delta, int) and tok_delta < 0 + hook_available = bool(m2_head.get("semantic_unit_settlement_hook_available")) return { "scenario_id": "m2_epoch_prefetch_semantic_fold", "passed": head_ok, - "semantic_unit_settlement_hook_available": bool( - m2_head.get("semantic_unit_settlement_hook_available") + "semantic_unit_settlement_hook_available": hook_available, + "source_attribution": build_scenario_source_attribution( + base_source="candidate_head", + head_source="candidate_head", + comparison_kind="same_commit_mechanism_verification", + production_hot_path_covered=hook_available, + note=( + "Both M2 arms run on the candidate evaluator checkout; excluded from " + "cross-commit claims and production settlement hot-path claims unless " + "the production settlement hook is present." + ), ), "base": { "behavior_constraint": m2_base["behavior_constraint"].to_dict(), @@ -186,9 +198,18 @@ def _run_m3_pair() -> dict[str, Any]: base_behavior=m3_base["behavior_constraint"], head_behavior=m3_head["behavior_constraint"], ) + m3_cross = base_source_root is not None return { "scenario_id": "m3_claim_block_settle_invariants", "passed": bool(m3_cmp["behavior_preserved"]) and m3_head["behavior_constraint"].passed, + "source_attribution": build_scenario_source_attribution( + base_source="external_base_checkout" if m3_cross else "candidate_head", + head_source="candidate_head", + comparison_kind=( + "cross_commit_differential" if m3_cross else "same_commit_arm_contrast" + ), + production_hot_path_covered=True, + ), "base": { "behavior_constraint": m3_base["behavior_constraint"].to_dict(), "efficiency": m3_base["efficiency"].to_dict(), @@ -237,10 +258,19 @@ def _run_m3_pair() -> dict[str, Any]: m1_deltas = m1_cmp["deltas"] wire_delta = m1_deltas.get("wire_bytes") if isinstance(m1_deltas, Mapping) else None head_ok = bool(m1_cmp["behavior_preserved"]) and isinstance(wire_delta, int) and wire_delta < 0 + m1_cross = base_source_root is not None results.append( { "scenario_id": "m1_envelope_scoped_recovery", "passed": head_ok, + "source_attribution": build_scenario_source_attribution( + base_source="external_base_checkout" if m1_cross else "candidate_head", + head_source="candidate_head", + comparison_kind=( + "cross_commit_differential" if m1_cross else "same_commit_arm_contrast" + ), + production_hot_path_covered=True, + ), "base": { "behavior_constraint": m1_base["behavior_constraint"].to_dict(), "efficiency": m1_base["efficiency"].to_dict(), @@ -319,6 +349,7 @@ def _run_m3_pair() -> dict[str, Any]: overall_passed = all(row["passed"] for row in results) and ( full_smoke_result["ok"] if full_smoke_result is not None else True ) + claim_scope = summarize_claim_scope(results) payload: dict[str, Any] = { "schema_version": MICROBENCH_DIFF_SCHEMA_VERSION, "tier": "tier0_deterministic", @@ -326,7 +357,8 @@ def _run_m3_pair() -> dict[str, Any]: "wall_seconds": wall_seconds, "head_commit": head_sha, "base_ref": resolved_base_sha or "local_arm_contrast", - "external_base_checkout_used": use_external_base, + "external_base_checkout_used": bool(claim_scope["cross_commit_scenarios"]), + "claim_scope": claim_scope, "scenarios": results, "cli_output_differential": cli_diff_summary, **( diff --git a/benchmark/microbench/tier1.py b/benchmark/microbench/tier1.py index 0a5b293542..3cd594ec35 100644 --- a/benchmark/microbench/tier1.py +++ b/benchmark/microbench/tier1.py @@ -7,6 +7,7 @@ import hashlib import json from pathlib import Path +import re import tempfile import time from typing import Any @@ -16,8 +17,10 @@ BehaviorConstraintResult, EfficiencyMetrics, assert_public_safe_payload, + build_scenario_source_attribution, compare_base_vs_head_efficiency, summarize_artifact_boundary, + summarize_claim_scope, ) from .models import ( DEFAULT_ARK_FLASH_MODEL, @@ -104,14 +107,71 @@ def _grade_m1(outcome: ModelRunOutcome) -> BehaviorConstraintResult: return BehaviorConstraintResult(passed=not violations, checks=checks, violations=violations) +_LABEL_PREFIX_RE = re.compile(r"^[a-z0-9_-]{2,24}:\s+") +_CONTRADICTION_MARKERS = ( + "no failure", + "no regression", + "no open obligation", + "no obligations", + "0 failures", + "nothing failed", + "all obligations resolved", + "resolved all", +) + + +def _normalize_clause(text: object) -> str: + return " ".join(str(text).strip().lower().split()) + + +def _clause_variants(expected_text: str) -> set[str]: + norm = _normalize_clause(expected_text) + variants = {norm} + stripped = _LABEL_PREFIX_RE.sub("", norm, count=1).strip() + if stripped: + variants.add(stripped) + return variants + + +def _match_expected_clauses( + raw_items: object, + expected: Sequence[str], +) -> tuple[bool, bool]: + """Return (all_expected_matched_distinctly, contradiction_free).""" + if not isinstance(raw_items, list) or any(not isinstance(item, str) for item in raw_items): + return False, False + normalized_items = [_normalize_clause(item) for item in raw_items] + for item in normalized_items: + if item in {"", "none", "null", "n/a", "[]"}: + return False, False + if any(marker in item for marker in _CONTRADICTION_MARKERS): + return False, False + + used_indices: set[int] = set() + for exp in expected: + accepted = _clause_variants(exp) + matched_idx = next( + ( + idx + for idx, candidate in enumerate(normalized_items) + if idx not in used_indices and candidate in accepted + ), + None, + ) + if matched_idx is None: + return False, True + used_indices.add(matched_idx) + return True, True + + def _prompt_m2(*, arm: str, payload: Mapping[str, Any]) -> str: body = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) return ( f"Scenario: m2_epoch_prefetch_semantic_fold (arm={arm}).\n" "You are continuing work after an exploratory context projection.\n" - "1. Preserve ALL failure facts verbatim (or exact clauses) in `preserved_failure_facts`.\n" - "2. Preserve ALL open obligations in `preserved_open_obligations`.\n" - "3. Choose `decision='execute'`, `selected_todo_id='todo_m2_unit'`, and `spend_attempted=false`.\n" + "1. Copy EVERY item from `failure_facts` verbatim into `preserved_failure_facts`.\n" + "2. Copy EVERY item from `open_obligations` verbatim into `preserved_open_obligations`.\n" + "3. Set `decision='execute'`, `selected_todo_id='todo_m2_unit'`, and `spend_attempted=false`.\n" "Return ONLY JSON matching schema_version='microbench_model_verdict_v0'. No extra prose.\n" f"Context:\n{body}\n" ) @@ -131,19 +191,19 @@ def _grade_m2( checks={"model_run_ok": False, "deterministic_fold_gate_passed": gate_passed}, violations=(f"model_{outcome.status}:{outcome.error_code or 'unknown'}",), ) - got_failures = " | ".join(str(x).lower() for x in (v.get("preserved_failure_facts") or [])) - got_obligations = " | ".join(str(x).lower() for x in (v.get("preserved_open_obligations") or [])) + failures_ok, failures_uncontradicted = _match_expected_clauses( + v.get("preserved_failure_facts"), expected_failures + ) + obligations_ok, obligations_uncontradicted = _match_expected_clauses( + v.get("preserved_open_obligations"), expected_obligations + ) checks = { "schema_valid": v.get("schema_version") == "microbench_model_verdict_v0", "decision_execute": v.get("decision") == "execute", - "no_anti_whitewash_failure_facts": ( - ("lease" in got_failures and "retry" in got_failures) - and ("duplicate spend" in got_failures or "idempotent" in got_failures) - ), - "open_obligations_preserved": ( - "backoff" in got_obligations - and ("settlement" in got_obligations or "receipt" in got_obligations) - ), + "selected_todo_matches_m2": v.get("selected_todo_id") == "todo_m2_unit", + "no_contradictory_claims": failures_uncontradicted and obligations_uncontradicted, + "no_anti_whitewash_failure_facts": failures_ok, + "open_obligations_preserved": obligations_ok, "no_premature_spend": v.get("spend_attempted") is False, "deterministic_fold_gate_passed": gate_passed, } @@ -259,6 +319,7 @@ def _format_arm_entry( "status": outcome.status, "error_code": outcome.error_code, "telemetry_source": outcome.telemetry_source, + "telemetry_coverage": outcome.telemetry_coverage, "observed_command_count": len(outcome.observed_commands), "behavior_constraint": behavior.to_dict(), "efficiency": outcome.efficiency.to_dict(), @@ -279,6 +340,7 @@ def _evaluate_model_pair( project_root_head: Path, base_grader: Any, head_grader: Any, + source_attribution: Mapping[str, object], per_call_timeout: float, deadline: float, ) -> dict[str, Any]: @@ -297,6 +359,7 @@ def _evaluate_model_pair( "model_id": runner.model_id, "provider": runner.provider, "passed": False, + "source_attribution": dict(source_attribution), "base": _format_arm_entry(arm=base_label, outcome=skipped, behavior=fail_b), "head": _format_arm_entry(arm=head_label, outcome=skipped, behavior=fail_b), "comparison": compare_base_vs_head_efficiency( @@ -339,12 +402,15 @@ def _evaluate_model_pair( head_out.efficiency, base_behavior=base_behavior, head_behavior=head_behavior, + base_telemetry_coverage=base_out.telemetry_coverage, + head_telemetry_coverage=head_out.telemetry_coverage, ) return { "scenario_id": scenario_id, "model_id": runner.model_id, "provider": runner.provider, "passed": bool(base_behavior.passed and head_behavior.passed and cmp["behavior_preserved"]), + "source_attribution": dict(source_attribution), "base": _format_arm_entry(arm=base_label, outcome=base_out, behavior=base_behavior), "head": _format_arm_entry(arm=head_label, outcome=head_out, behavior=head_behavior), "comparison": cmp, @@ -417,6 +483,7 @@ def run_tier1_dual_model_suite( delivered_payload=m1_head["delivered_payload"], decision_path=m1_head["decision_path"], ) + m1_cross = base_source_root is not None scenarios_plan.append( { "scenario_id": "m1_envelope_scoped_recovery", @@ -430,6 +497,14 @@ def run_tier1_dual_model_suite( "project_root_head": m1_head_fix.project_root, "base_grader": _grade_m1, "head_grader": _grade_m1, + "source_attribution": build_scenario_source_attribution( + base_source="external_base_checkout" if m1_cross else "candidate_head", + head_source="candidate_head", + comparison_kind=( + "cross_commit_differential" if m1_cross else "same_commit_arm_contrast" + ), + production_hot_path_covered=True, + ), } ) @@ -443,6 +518,7 @@ def run_tier1_dual_model_suite( gate_passed = bool( m2_base["behavior_constraint"].passed and m2_head["behavior_constraint"].passed ) + m2_hook_ok = bool(m2_head.get("semantic_unit_settlement_hook_available")) m2_grader = lambda outcome, ef=meta["failure_facts"], eo=meta["open_obligations"], gp=gate_passed: _grade_m2( # noqa: E731 outcome, expected_failures=ef, @@ -462,6 +538,17 @@ def run_tier1_dual_model_suite( "project_root_head": m2_fix.project_root, "base_grader": m2_grader, "head_grader": m2_grader, + "source_attribution": build_scenario_source_attribution( + base_source="candidate_head", + head_source="candidate_head", + comparison_kind="same_commit_mechanism_verification", + production_hot_path_covered=m2_hook_ok, + note=( + "Both M2 arms run on the candidate evaluator checkout; excluded from " + "cross-commit claims and production settlement hot-path claims unless " + "the production settlement hook is present." + ), + ), } ) @@ -486,6 +573,12 @@ def run_tier1_dual_model_suite( "project_root_head": claim_proj, "base_grader": lambda out, ok=cli_ok: _grade_m3_gate(out, cli_gate_passed=ok), "head_grader": lambda out, ok=cli_ok: _grade_m3_claim(out, cli_gate_passed=ok), + "source_attribution": build_scenario_source_attribution( + base_source="candidate_head", + head_source="candidate_head", + comparison_kind="same_commit_gate_vs_claim_contrast", + production_hot_path_covered=cli_ok, + ), } ) @@ -504,6 +597,7 @@ def _run_for_runner(runner: MicrobenchModelRunner) -> list[dict[str, Any]]: project_root_head=spec["project_root_head"], base_grader=spec["base_grader"], head_grader=spec["head_grader"], + source_attribution=spec["source_attribution"], per_call_timeout=per_call_timeout_seconds, deadline=deadline, ) @@ -527,6 +621,7 @@ def _run_for_runner(runner: MicrobenchModelRunner) -> list[dict[str, Any]]: or row["head"]["status"] in {"unavailable", "quota_exhausted"} ] all_passed = bool(rows) and all(row["passed"] for row in rows) + claim_scope = summarize_claim_scope(rows) report: dict[str, Any] = { "schema_version": MICROBENCH_RECEIPT_SCHEMA_VERSION, "tier": "tier1_dual_model", @@ -536,7 +631,8 @@ def _run_for_runner(runner: MicrobenchModelRunner) -> list[dict[str, Any]]: "budget_seconds": max_total_seconds, "head_commit": head_sha, "base_ref": resolved_base_sha or "local_arm_contrast", - "external_base_checkout_used": use_external_base, + "external_base_checkout_used": bool(claim_scope["cross_commit_scenarios"]), + "claim_scope": claim_scope, "models": [ {"provider": runner.provider, "model_id": runner.model_id} for runner in active_runners diff --git a/benchmark/tests/test_dual_model_microbench.py b/benchmark/tests/test_dual_model_microbench.py index 15a0ac55b6..0c8977af99 100644 --- a/benchmark/tests/test_dual_model_microbench.py +++ b/benchmark/tests/test_dual_model_microbench.py @@ -34,8 +34,9 @@ M3_CLAIM_TODO_ID, M3_GATE_TODO_ID, ) +from benchmark.microbench import tier0 as microbench_tier0 from benchmark.microbench.tier0 import run_tier0_differential -from benchmark.microbench.tier1 import run_tier1_dual_model_suite +from benchmark.microbench.tier1 import _grade_m2, run_tier1_dual_model_suite def _write_fake_codex(bin_path: Path, *, mode: str) -> None: @@ -255,7 +256,13 @@ def stub_transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: seen_commands.append(last_tool_msg) assert "escapes trial workspace" in last_tool_msg return { - "usage": {"prompt_tokens": 140, "completion_tokens": 15, "total_tokens": 155}, + "usage": { + "prompt_tokens": 140, + "completion_tokens": 15, + "total_tokens": 155, + "prompt_tokens_details": {"cached_tokens": 0}, + "completion_tokens_details": {"reasoning_tokens": 0}, + }, "choices": [ { "message": { @@ -290,7 +297,13 @@ def stub_transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: "tool_actions_summary": ["cat fixture/m1-proof.json"], } return { - "usage": {"prompt_tokens": 180, "completion_tokens": 40, "total_tokens": 220}, + "usage": { + "prompt_tokens": 180, + "completion_tokens": 40, + "total_tokens": 220, + "prompt_tokens_details": {"cached_tokens": 0}, + "completion_tokens_details": {"reasoning_tokens": 0}, + }, "choices": [ { "message": { @@ -345,21 +358,34 @@ def run_case( del trial_root, project_root, timeout_seconds is_head = "arm=head" in prompt_text or "head_fold_to_receipt" in prompt_text # Head uses fewer tokens, but whitewashes / drops required facts -> must fail! + is_m2 = scenario_id == "m2_epoch_prefetch_semantic_fold" verdict = { "schema_version": "microbench_model_verdict_v0", "scenario_id": scenario_id, "decision": "execute", - "selected_todo_id": M1_SELECTED_TODO_ID if not is_head else M1_BLOCKED_TODO_ID, + "selected_todo_id": ( + ("todo_m2_unit" if is_m2 else M1_SELECTED_TODO_ID) + if not is_head + else M1_BLOCKED_TODO_ID + ), "preserved_blocked_todo_ids": [M1_BLOCKED_TODO_ID] if not is_head else [], "extracted_proof": M1_PROOF_TOKEN if not is_head else None, - "preserved_failure_facts": [] if is_head else [ - "retry worker ignores expired lease backoff ceiling", - "duplicate spend rejected with idempotent replay check", - ], - "preserved_open_obligations": [] if is_head else [ - "verify backoff ceiling test on sqlite provider", - "preserve terminal settlement receipt integrity", - ], + "preserved_failure_facts": ( + ["lease retry duplicate spend"] + if is_head + else [ + "regression: retry worker ignores expired lease backoff ceiling", + "guard: duplicate spend rejected with idempotent replay check", + ] + ), + "preserved_open_obligations": ( + ["backoff settlement"] + if is_head + else [ + "verify backoff ceiling test on sqlite provider", + "preserve terminal settlement receipt integrity", + ] + ), "claim_owner": M3_AGENT_PRIMARY, "spend_attempted": False, "tool_actions_summary": ["stub"], @@ -432,3 +458,298 @@ def test_cli_dry_tier0_and_opt_in_smoke(capsys: pytest.CaptureFixture[str]) -> N ) assert smoke.returncode == 0, smoke.stdout + smoke.stderr assert "benchmark-dual-model-microbench-smoke ok" in smoke.stdout + + +def test_m2_grader_rejects_keyword_fragments_missing_wrong_todo_and_contradictions() -> None: + expected_failures = [ + "regression: retry worker ignores expired lease backoff ceiling", + "guard: duplicate spend rejected with idempotent replay check", + ] + expected_obligations = [ + "verify backoff ceiling test on sqlite provider", + "preserve terminal settlement receipt integrity", + ] + + def _outcome(verdict: dict[str, Any]) -> ModelRunOutcome: + return ModelRunOutcome( + model_id=DEFAULT_ARK_FLASH_MODEL, + provider="ark", + status="ok", + error_code=None, + verdict=verdict, + efficiency=EfficiencyMetrics(wire_bytes=200, prompt_tokens=50), + ) + + valid_base = { + "schema_version": "microbench_model_verdict_v0", + "scenario_id": "m2_epoch_prefetch_semantic_fold", + "decision": "execute", + "selected_todo_id": "todo_m2_unit", + "preserved_failure_facts": list(expected_failures), + "preserved_open_obligations": list(expected_obligations), + "spend_attempted": False, + } + assert _grade_m2( + _outcome(valid_base), + expected_failures=expected_failures, + expected_obligations=expected_obligations, + gate_passed=True, + ).passed is True + + negative_cases: list[tuple[dict[str, Any], str]] = [ + ( + { + **valid_base, + "preserved_failure_facts": ["lease retry duplicate spend idempotent"], + "preserved_open_obligations": ["backoff settlement receipt"], + }, + "no_anti_whitewash_failure_facts", + ), + ( + { + **valid_base, + "preserved_failure_facts": [expected_failures[0]], + }, + "no_anti_whitewash_failure_facts", + ), + ( + { + **valid_base, + "preserved_failure_facts": [expected_failures[0], expected_failures[0]], + }, + "no_anti_whitewash_failure_facts", + ), + ( + { + **valid_base, + "preserved_open_obligations": [expected_obligations[0]], + }, + "open_obligations_preserved", + ), + ( + { + **valid_base, + "selected_todo_id": "todo_wrong_lane", + }, + "selected_todo_matches_m2", + ), + ( + { + **valid_base, + "selected_todo_id": None, + }, + "selected_todo_matches_m2", + ), + ( + { + **valid_base, + "preserved_failure_facts": [ + *expected_failures, + "no regression found", + ], + }, + "no_contradictory_claims", + ), + ( + { + **valid_base, + "decision": "noop", + }, + "decision_execute", + ), + ( + { + **valid_base, + "spend_attempted": True, + }, + "no_premature_spend", + ), + ] + for bad_verdict, expected_violation in negative_cases: + res = _grade_m2( + _outcome(bad_verdict), + expected_failures=expected_failures, + expected_obligations=expected_obligations, + gate_passed=True, + ) + assert res.passed is False, bad_verdict + assert expected_violation in res.violations, (expected_violation, res) + + +def test_ark_usage_coverage_preserves_zero_keeps_missing_null_and_blocks_partial_deltas( + tmp_path: Path, +) -> None: + trial_root = tmp_path / "trial" + project_root = trial_root / "project" + project_root.mkdir(parents=True) + verdict = { + "schema_version": "microbench_model_verdict_v0", + "scenario_id": "m1_envelope_scoped_recovery", + "decision": "execute", + "selected_todo_id": M1_SELECTED_TODO_ID, + "preserved_blocked_todo_ids": [M1_BLOCKED_TODO_ID], + "extracted_proof": M1_PROOF_TOKEN, + "preserved_failure_facts": [], + "preserved_open_obligations": [], + "claim_owner": None, + "spend_attempted": False, + "tool_actions_summary": [], + } + + # Case 1: Only prompt_tokens=7 returned -> missing fields remain None (never 0). + def missing_fields_transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: float) -> dict[str, Any]: + del endpoint, headers, body, timeout_seconds + return { + "usage": {"prompt_tokens": 7}, + "choices": [{"message": {"role": "assistant", "content": json.dumps(verdict)}}], + } + + r_missing = DeepSeekArkMicrobenchRunner(api_key="synthetic-key", transport=missing_fields_transport).run_case( + scenario_id="m1_envelope_scoped_recovery", + prompt_text="check", + trial_root=trial_root, + project_root=project_root, + timeout_seconds=10.0, + ) + assert r_missing.status == "ok" + assert r_missing.efficiency.prompt_tokens == 7 + assert r_missing.efficiency.cached_tokens is None + assert r_missing.efficiency.completion_tokens is None + assert r_missing.efficiency.reasoning_tokens is None + assert r_missing.efficiency.total_tokens is None + assert r_missing.telemetry_coverage is not None + assert r_missing.telemetry_coverage["metrics"]["cached_tokens"]["status"] == "missing" + + # Case 2: Genuine 0 reported cleanly stays 0, while partial multi-round cached_tokens becomes None. + call_idx = 0 + + def partial_transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: float) -> dict[str, Any]: + nonlocal call_idx + del endpoint, headers, body, timeout_seconds + call_idx += 1 + if call_idx == 1: + return { + "usage": { + "prompt_tokens": 20, + "completion_tokens": 5, + "total_tokens": 25, + "prompt_tokens_details": {"cached_tokens": 10}, + "completion_tokens_details": {"reasoning_tokens": 0}, + }, + "choices": [ + { + "message": { + "role": "assistant", + "tool_calls": [ + { + "id": "call_ls", + "type": "function", + "function": {"name": "exec_command", "arguments": json.dumps({"cmd": "ls ."})}, + } + ], + } + } + ], + } + # Round 2 explicitly reports reasoning_tokens=0, omits cached_tokens -> cached_tokens is partial! + return { + "usage": { + "prompt_tokens": 30, + "completion_tokens": 8, + "total_tokens": 38, + "completion_tokens_details": {"reasoning_tokens": 0}, + }, + "choices": [{"message": {"role": "assistant", "content": json.dumps(verdict)}}], + } + + r_partial = DeepSeekArkMicrobenchRunner(api_key="synthetic-key", transport=partial_transport).run_case( + scenario_id="m1_envelope_scoped_recovery", + prompt_text="check", + trial_root=trial_root, + project_root=project_root, + timeout_seconds=10.0, + ) + assert r_partial.status == "ok" + assert r_partial.efficiency.prompt_tokens == 50 + assert r_partial.efficiency.completion_tokens == 13 + assert r_partial.efficiency.total_tokens == 63 + assert r_partial.efficiency.reasoning_tokens == 0 + assert r_partial.efficiency.cached_tokens is None + assert r_partial.telemetry_coverage is not None + assert r_partial.telemetry_coverage["has_partial_coverage"] is True + assert r_partial.telemetry_coverage["partial_metrics"] == ["cached_tokens"] + assert r_partial.telemetry_coverage["metrics"]["reasoning_tokens"]["status"] == "complete" + + cmp = compare_base_vs_head_efficiency( + EfficiencyMetrics(wire_bytes=200, prompt_tokens=100, cached_tokens=40, completion_tokens=20), + r_partial.efficiency, + base_behavior=BehaviorConstraintResult(passed=True, checks={"ok": True}), + head_behavior=BehaviorConstraintResult(passed=True, checks={"ok": True}), + head_telemetry_coverage=r_partial.telemetry_coverage, + ) + assert cmp["deltas"]["prompt_tokens"] == -50 + assert cmp["deltas"]["cached_tokens"] is None + assert cmp["pct_changes"]["cached_tokens"] is None + assert "cached_tokens" in cmp["excluded_partial_metrics"] + + +def test_tier0_and_tier1_attribute_m2_same_commit_mechanism_separately_from_cross_commit( + monkeypatch: pytest.MonkeyPatch, +) -> None: + head_sha = microbench_tier0._head_commit() + fake_base_sha = "0" * 40 + assert fake_base_sha != head_sha + + monkeypatch.setattr(microbench_tier0, "_resolve_pinned_base_ref", lambda base_ref, main_ref="origin/main": fake_base_sha) + monkeypatch.setattr( + microbench_tier0, + "_differential_smoke_helpers", + lambda: { + "_materialize_base_source": lambda sha, dst: dst.mkdir(parents=True, exist_ok=True), + }, + ) + + def _stub_m1_arm(fix: Any, *, arm: str, source_root: Path | None = None) -> dict[str, Any]: + del fix, source_root + return { + "behavior_constraint": BehaviorConstraintResult(passed=True, checks={"ok": True}), + "efficiency": EfficiencyMetrics(wire_bytes=1000 if arm == "base" else 400, prompt_tokens=200 if arm == "base" else 80), + } + + def _stub_m3_arm(fix: Any, *, arm: str = "head", source_root: Path | None = None) -> dict[str, Any]: + del fix, arm, source_root + return { + "behavior_constraint": BehaviorConstraintResult(passed=True, checks={"ok": True}), + "efficiency": EfficiencyMetrics(wire_bytes=500, prompt_tokens=100), + } + + monkeypatch.setattr(microbench_tier0, "prepare_m1_fixture", lambda root, source_root=None: root) + monkeypatch.setattr(microbench_tier0, "run_m1_deterministic_arm", _stub_m1_arm) + monkeypatch.setattr(microbench_tier0, "prepare_m3_fixture", lambda root: root) + monkeypatch.setattr(microbench_tier0, "run_m3_deterministic_arm", _stub_m3_arm) + + report = run_tier0_differential(base_ref="origin/main") + assert report["passed"] is True + assert report["external_base_checkout_used"] is True + by_id = {row["scenario_id"]: row for row in report["scenarios"]} + + assert by_id["m1_envelope_scoped_recovery"]["source_attribution"]["comparison_kind"] == "cross_commit_differential" + assert by_id["m3_claim_block_settle_invariants"]["source_attribution"]["comparison_kind"] == "cross_commit_differential" + + m2_attr = by_id["m2_epoch_prefetch_semantic_fold"]["source_attribution"] + assert m2_attr["base_source"] == "candidate_head" + assert m2_attr["head_source"] == "candidate_head" + assert m2_attr["comparison_kind"] == "same_commit_mechanism_verification" + assert m2_attr["excluded_from_cross_commit_claims"] is True + if not by_id["m2_epoch_prefetch_semantic_fold"]["semantic_unit_settlement_hook_available"]: + assert m2_attr["production_hot_path_covered"] is False + assert m2_attr["excluded_from_production_hot_path_claims"] is True + + scope = report["claim_scope"] + assert set(scope["cross_commit_scenarios"]) == { + "m1_envelope_scoped_recovery", + "m3_claim_block_settle_invariants", + } + assert "m2_epoch_prefetch_semantic_fold" in scope["same_commit_mechanism_scenarios"] + assert "m2_epoch_prefetch_semantic_fold" in scope["excluded_from_cross_commit_claims"] + assert_public_safe_payload(report) From e0795345d5c78270c0e6e3743ad03e867b2aae28 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 05:37:08 +0800 Subject: [PATCH 3/6] fix(benchmark): enforce 1-to-1 M2 clauses and execution-backed production attribution Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- benchmark/microbench/README.md | 2 +- benchmark/microbench/scenarios.py | 4 + benchmark/microbench/tier0.py | 13 +- benchmark/microbench/tier1.py | 33 ++- benchmark/tests/test_dual_model_microbench.py | 194 ++++++++++++++++-- 5 files changed, 220 insertions(+), 26 deletions(-) diff --git a/benchmark/microbench/README.md b/benchmark/microbench/README.md index 6ee5c5bede..4fbdac15c9 100644 --- a/benchmark/microbench/README.md +++ b/benchmark/microbench/README.md @@ -50,5 +50,5 @@ uv run --extra test python -m benchmark.microbench.run \ - All fixtures live inside disposable temporary directories created per run. - Credentials, local home paths, raw prompts, and raw provider responses are never serialized into emitted receipts or tests (`assert_public_safe_payload`). - Missing model usage counters remain `null` (`None`), never `0`; partial multi-round metric coverage is labeled explicitly in `telemetry_coverage` and excluded from whole-run efficiency deltas (`excluded_partial_metrics`). -- Every scenario records explicit `source_attribution` (`external_base_checkout` vs `candidate_head`, `comparison_kind`, `production_hot_path_covered`) and top-level `claim_scope`; same-commit mechanism ablations (such as M2 before `todo_unit_settlement` production hooks land) remain excluded from cross-commit and production hot-path conclusions. +- Every scenario records explicit `source_attribution` (`external_base_checkout` vs `candidate_head`, `comparison_kind`, `production_hot_path_covered`) and top-level `claim_scope`; same-commit mechanism ablations (such as M2, where `semantic_unit_settlement_hook_available` is diagnostic-only unless a real production settlement entrypoint executes and reads back turn settlement) remain excluded from cross-commit and production hot-path conclusions. - Byte reductions cannot mask behavior constraint failures (`behavior_preserved` requires all constraint checks and item-by-item M2 clauses/Todo ID matching to pass). diff --git a/benchmark/microbench/scenarios.py b/benchmark/microbench/scenarios.py index b2cb6a95fb..8ff569db23 100644 --- a/benchmark/microbench/scenarios.py +++ b/benchmark/microbench/scenarios.py @@ -995,6 +995,10 @@ def _render_request(req: Mapping[str, Any]) -> str: "telemetry": telemetry, }, "semantic_unit_settlement_hook_available": _has_todo_unit_settlement(), + # Mechanism verification calls fold/prefetch helpers rather than executing and + # reading back a live production turn-driver settlement entrypoint. + "production_settlement_executed": False, + "production_settlement_readback_ok": False, } diff --git a/benchmark/microbench/tier0.py b/benchmark/microbench/tier0.py index 4cc196a77d..c512669b38 100644 --- a/benchmark/microbench/tier0.py +++ b/benchmark/microbench/tier0.py @@ -148,6 +148,10 @@ def _run_m2_pair() -> dict[str, Any]: tok_delta = m2_deltas.get("prompt_tokens") if isinstance(m2_deltas, Mapping) else None head_ok = bool(m2_cmp["behavior_preserved"]) and isinstance(tok_delta, int) and tok_delta < 0 hook_available = bool(m2_head.get("semantic_unit_settlement_hook_available")) + prod_hot_path_ok = bool( + m2_head.get("production_settlement_executed") + and m2_head.get("production_settlement_readback_ok") + ) return { "scenario_id": "m2_epoch_prefetch_semantic_fold", "passed": head_ok, @@ -156,11 +160,12 @@ def _run_m2_pair() -> dict[str, Any]: base_source="candidate_head", head_source="candidate_head", comparison_kind="same_commit_mechanism_verification", - production_hot_path_covered=hook_available, + production_hot_path_covered=prod_hot_path_ok, note=( - "Both M2 arms run on the candidate evaluator checkout; excluded from " - "cross-commit claims and production settlement hot-path claims unless " - "the production settlement hook is present." + "Both M2 arms run same-commit mechanism helpers on the candidate checkout; " + "excluded from cross-commit claims and production settlement hot-path " + "claims unless an actual production settlement entrypoint executes and " + "reads back turn settlement." ), ), "base": { diff --git a/benchmark/microbench/tier1.py b/benchmark/microbench/tier1.py index 3cd594ec35..c12a67ea75 100644 --- a/benchmark/microbench/tier1.py +++ b/benchmark/microbench/tier1.py @@ -117,6 +117,12 @@ def _grade_m1(outcome: ModelRunOutcome) -> BehaviorConstraintResult: "nothing failed", "all obligations resolved", "resolved all", + "already completed", + "already resolved", + "already fixed", + "already passed", + "no longer open", + "no longer needed", ) @@ -137,7 +143,7 @@ def _match_expected_clauses( raw_items: object, expected: Sequence[str], ) -> tuple[bool, bool]: - """Return (all_expected_matched_distinctly, contradiction_free).""" + """Return (strict_1to1_bijection_ok, contradiction_free).""" if not isinstance(raw_items, list) or any(not isinstance(item, str) for item in raw_items): return False, False normalized_items = [_normalize_clause(item) for item in raw_items] @@ -161,6 +167,8 @@ def _match_expected_clauses( if matched_idx is None: return False, True used_indices.add(matched_idx) + if len(used_indices) != len(normalized_items): + return False, True return True, True @@ -341,9 +349,15 @@ def _evaluate_model_pair( base_grader: Any, head_grader: Any, source_attribution: Mapping[str, object], + semantic_unit_settlement_hook_available: bool | None = None, per_call_timeout: float, deadline: float, ) -> dict[str, Any]: + diag_fields = ( + {"semantic_unit_settlement_hook_available": semantic_unit_settlement_hook_available} + if semantic_unit_settlement_hook_available is not None + else {} + ) if time.monotonic() >= deadline: skipped = ModelRunOutcome( model_id=runner.model_id, @@ -359,6 +373,7 @@ def _evaluate_model_pair( "model_id": runner.model_id, "provider": runner.provider, "passed": False, + **diag_fields, "source_attribution": dict(source_attribution), "base": _format_arm_entry(arm=base_label, outcome=skipped, behavior=fail_b), "head": _format_arm_entry(arm=head_label, outcome=skipped, behavior=fail_b), @@ -410,6 +425,7 @@ def _evaluate_model_pair( "model_id": runner.model_id, "provider": runner.provider, "passed": bool(base_behavior.passed and head_behavior.passed and cmp["behavior_preserved"]), + **diag_fields, "source_attribution": dict(source_attribution), "base": _format_arm_entry(arm=base_label, outcome=base_out, behavior=base_behavior), "head": _format_arm_entry(arm=head_label, outcome=head_out, behavior=head_behavior), @@ -519,6 +535,10 @@ def run_tier1_dual_model_suite( m2_base["behavior_constraint"].passed and m2_head["behavior_constraint"].passed ) m2_hook_ok = bool(m2_head.get("semantic_unit_settlement_hook_available")) + m2_prod_ok = bool( + m2_head.get("production_settlement_executed") + and m2_head.get("production_settlement_readback_ok") + ) m2_grader = lambda outcome, ef=meta["failure_facts"], eo=meta["open_obligations"], gp=gate_passed: _grade_m2( # noqa: E731 outcome, expected_failures=ef, @@ -538,15 +558,17 @@ def run_tier1_dual_model_suite( "project_root_head": m2_fix.project_root, "base_grader": m2_grader, "head_grader": m2_grader, + "semantic_unit_settlement_hook_available": m2_hook_ok, "source_attribution": build_scenario_source_attribution( base_source="candidate_head", head_source="candidate_head", comparison_kind="same_commit_mechanism_verification", - production_hot_path_covered=m2_hook_ok, + production_hot_path_covered=m2_prod_ok, note=( - "Both M2 arms run on the candidate evaluator checkout; excluded from " - "cross-commit claims and production settlement hot-path claims unless " - "the production settlement hook is present." + "Both M2 arms run same-commit mechanism helpers on the candidate " + "checkout; excluded from cross-commit claims and production " + "settlement hot-path claims unless an actual production settlement " + "entrypoint executes and reads back turn settlement." ), ), } @@ -598,6 +620,7 @@ def _run_for_runner(runner: MicrobenchModelRunner) -> list[dict[str, Any]]: base_grader=spec["base_grader"], head_grader=spec["head_grader"], source_attribution=spec["source_attribution"], + semantic_unit_settlement_hook_available=spec.get("semantic_unit_settlement_hook_available"), per_call_timeout=per_call_timeout_seconds, deadline=deadline, ) diff --git a/benchmark/tests/test_dual_model_microbench.py b/benchmark/tests/test_dual_model_microbench.py index 0c8977af99..cc9846d8f4 100644 --- a/benchmark/tests/test_dual_model_microbench.py +++ b/benchmark/tests/test_dual_model_microbench.py @@ -7,6 +7,7 @@ import stat import subprocess import sys +import types from typing import Any import pytest @@ -496,49 +497,69 @@ def _outcome(verdict: dict[str, Any]) -> ModelRunOutcome: gate_passed=True, ).passed is True - negative_cases: list[tuple[dict[str, Any], str]] = [ + # Preserve existing label stripping + whitespace normalization. + assert _grade_m2( + _outcome( + { + **valid_base, + "preserved_failure_facts": [ + "retry worker ignores expired lease backoff ceiling", + "duplicate spend rejected with idempotent replay check", + ], + "preserved_open_obligations": [ + "verify backoff ceiling test on sqlite provider", + "preserve terminal settlement receipt integrity", + ], + } + ), + expected_failures=expected_failures, + expected_obligations=expected_obligations, + gate_passed=True, + ).passed is True + + negative_cases: list[tuple[dict[str, Any], tuple[str, ...]]] = [ ( { **valid_base, "preserved_failure_facts": ["lease retry duplicate spend idempotent"], "preserved_open_obligations": ["backoff settlement receipt"], }, - "no_anti_whitewash_failure_facts", + ("no_anti_whitewash_failure_facts",), ), ( { **valid_base, "preserved_failure_facts": [expected_failures[0]], }, - "no_anti_whitewash_failure_facts", + ("no_anti_whitewash_failure_facts",), ), ( { **valid_base, "preserved_failure_facts": [expected_failures[0], expected_failures[0]], }, - "no_anti_whitewash_failure_facts", + ("no_anti_whitewash_failure_facts",), ), ( { **valid_base, "preserved_open_obligations": [expected_obligations[0]], }, - "open_obligations_preserved", + ("open_obligations_preserved",), ), ( { **valid_base, "selected_todo_id": "todo_wrong_lane", }, - "selected_todo_matches_m2", + ("selected_todo_matches_m2",), ), ( { **valid_base, "selected_todo_id": None, }, - "selected_todo_matches_m2", + ("selected_todo_matches_m2",), ), ( { @@ -548,24 +569,54 @@ def _outcome(verdict: dict[str, Any]) -> ModelRunOutcome: "no regression found", ], }, - "no_contradictory_claims", + ("no_contradictory_claims", "no_anti_whitewash_failure_facts"), + ), + ( + { + **valid_base, + "preserved_open_obligations": [ + *expected_obligations, + "sqlite backoff test already completed", + ], + }, + ("open_obligations_preserved", "no_contradictory_claims"), + ), + ( + { + **valid_base, + "preserved_failure_facts": [ + *expected_failures, + "sqlite backoff verification note", + ], + }, + ("no_anti_whitewash_failure_facts",), + ), + ( + { + **valid_base, + "preserved_open_obligations": [ + *expected_obligations, + expected_obligations[0], + ], + }, + ("open_obligations_preserved",), ), ( { **valid_base, "decision": "noop", }, - "decision_execute", + ("decision_execute",), ), ( { **valid_base, "spend_attempted": True, }, - "no_premature_spend", + ("no_premature_spend",), ), ] - for bad_verdict, expected_violation in negative_cases: + for bad_verdict, expected_violations in negative_cases: res = _grade_m2( _outcome(bad_verdict), expected_failures=expected_failures, @@ -573,7 +624,48 @@ def _outcome(verdict: dict[str, Any]) -> ModelRunOutcome: gate_passed=True, ) assert res.passed is False, bad_verdict - assert expected_violation in res.violations, (expected_violation, res) + for expected_violation in expected_violations: + assert expected_violation in res.violations, (expected_violation, res) + + class _ExtraObligationHeadRunner: + provider = "synthetic" + model_id = "synthetic-m2-extra" + + def run_case( + self, + *, + scenario_id: str, + prompt_text: str, + trial_root: Path, + project_root: Path, + timeout_seconds: float, + ) -> ModelRunOutcome: + del scenario_id, trial_root, project_root, timeout_seconds + is_head = "arm=head_fold_to_receipt" in prompt_text + verdict = dict(valid_base) + if is_head: + verdict["preserved_open_obligations"] = [ + *expected_obligations, + "sqlite backoff test already completed", + ] + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="ok", + error_code=None, + verdict=verdict, + efficiency=EfficiencyMetrics(wire_bytes=200, prompt_tokens=40 if is_head else 90), + ) + + t1_extra = run_tier1_dual_model_suite( + runners=[_ExtraObligationHeadRunner()], + scenarios=("m2_epoch_prefetch_semantic_fold",), + ) + assert t1_extra["passed"] is False + assert t1_extra["results"][0]["base"]["behavior_constraint"]["passed"] is True + assert t1_extra["results"][0]["head"]["behavior_constraint"]["passed"] is False + assert "open_obligations_preserved" in t1_extra["results"][0]["head"]["behavior_constraint"]["violations"] + assert "no_contradictory_claims" in t1_extra["results"][0]["head"]["behavior_constraint"]["violations"] def test_ark_usage_coverage_preserves_zero_keeps_missing_null_and_blocks_partial_deltas( @@ -728,22 +820,39 @@ def _stub_m3_arm(fix: Any, *, arm: str = "head", source_root: Path | None = None monkeypatch.setattr(microbench_tier0, "prepare_m3_fixture", lambda root: root) monkeypatch.setattr(microbench_tier0, "run_m3_deterministic_arm", _stub_m3_arm) + stub_calls = 0 + fake_pkg = types.ModuleType("loopx.control_plane.turn_driver") + fake_mod = types.ModuleType("loopx.control_plane.turn_driver.todo_unit_settlement") + + def _prepare_turn_semantic_unit_context(*args: Any, **kwargs: Any) -> dict[str, Any]: + nonlocal stub_calls + del args, kwargs + stub_calls += 1 + return {"ok": True} + + fake_mod.prepare_turn_semantic_unit_context = _prepare_turn_semantic_unit_context # type: ignore[attr-defined] + fake_pkg.todo_unit_settlement = fake_mod # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "loopx.control_plane.turn_driver", fake_pkg) + monkeypatch.setitem(sys.modules, "loopx.control_plane.turn_driver.todo_unit_settlement", fake_mod) + report = run_tier0_differential(base_ref="origin/main") assert report["passed"] is True assert report["external_base_checkout_used"] is True + assert stub_calls == 0 by_id = {row["scenario_id"]: row for row in report["scenarios"]} assert by_id["m1_envelope_scoped_recovery"]["source_attribution"]["comparison_kind"] == "cross_commit_differential" assert by_id["m3_claim_block_settle_invariants"]["source_attribution"]["comparison_kind"] == "cross_commit_differential" - m2_attr = by_id["m2_epoch_prefetch_semantic_fold"]["source_attribution"] + m2_row = by_id["m2_epoch_prefetch_semantic_fold"] + m2_attr = m2_row["source_attribution"] + assert m2_row["semantic_unit_settlement_hook_available"] is True assert m2_attr["base_source"] == "candidate_head" assert m2_attr["head_source"] == "candidate_head" assert m2_attr["comparison_kind"] == "same_commit_mechanism_verification" assert m2_attr["excluded_from_cross_commit_claims"] is True - if not by_id["m2_epoch_prefetch_semantic_fold"]["semantic_unit_settlement_hook_available"]: - assert m2_attr["production_hot_path_covered"] is False - assert m2_attr["excluded_from_production_hot_path_claims"] is True + assert m2_attr["production_hot_path_covered"] is False + assert m2_attr["excluded_from_production_hot_path_claims"] is True scope = report["claim_scope"] assert set(scope["cross_commit_scenarios"]) == { @@ -752,4 +861,57 @@ def _stub_m3_arm(fix: Any, *, arm: str = "head", source_root: Path | None = None } assert "m2_epoch_prefetch_semantic_fold" in scope["same_commit_mechanism_scenarios"] assert "m2_epoch_prefetch_semantic_fold" in scope["excluded_from_cross_commit_claims"] + assert "m2_epoch_prefetch_semantic_fold" not in scope["production_hot_path_scenarios"] + assert "m2_epoch_prefetch_semantic_fold" in scope["excluded_from_production_hot_path_claims"] assert_public_safe_payload(report) + + class _ValidM2Runner: + provider = "synthetic" + model_id = "synthetic-m2-scope" + + def run_case( + self, + *, + scenario_id: str, + prompt_text: str, + trial_root: Path, + project_root: Path, + timeout_seconds: float, + ) -> ModelRunOutcome: + del scenario_id, prompt_text, trial_root, project_root, timeout_seconds + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="ok", + error_code=None, + verdict={ + "schema_version": "microbench_model_verdict_v0", + "scenario_id": "m2_epoch_prefetch_semantic_fold", + "decision": "execute", + "selected_todo_id": "todo_m2_unit", + "preserved_failure_facts": [ + "regression: retry worker ignores expired lease backoff ceiling", + "guard: duplicate spend rejected with idempotent replay check", + ], + "preserved_open_obligations": [ + "verify backoff ceiling test on sqlite provider", + "preserve terminal settlement receipt integrity", + ], + "spend_attempted": False, + }, + efficiency=EfficiencyMetrics(wire_bytes=200, prompt_tokens=50), + ) + + t1_scope_report = run_tier1_dual_model_suite( + runners=[_ValidM2Runner()], + scenarios=("m2_epoch_prefetch_semantic_fold",), + ) + assert stub_calls == 0 + assert t1_scope_report["passed"] is True + t1_m2 = t1_scope_report["results"][0] + assert t1_m2["semantic_unit_settlement_hook_available"] is True + assert t1_m2["source_attribution"]["production_hot_path_covered"] is False + assert t1_m2["source_attribution"]["excluded_from_production_hot_path_claims"] is True + assert "m2_epoch_prefetch_semantic_fold" not in t1_scope_report["claim_scope"]["production_hot_path_scenarios"] + assert "m2_epoch_prefetch_semantic_fold" in t1_scope_report["claim_scope"]["excluded_from_production_hot_path_claims"] + assert_public_safe_payload(t1_scope_report) From 3b93bdead0b7686de1d1624c14d11b459e7b862b Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:12:42 +0800 Subject: [PATCH 4/6] fix(benchmark): enforce unified verdict schema, scenario binding, and spend consistency Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- benchmark/microbench/models.py | 141 +++++++++- benchmark/microbench/tier1.py | 75 +++++- benchmark/tests/test_dual_model_microbench.py | 255 +++++++++++++++++- 3 files changed, 456 insertions(+), 15 deletions(-) diff --git a/benchmark/microbench/models.py b/benchmark/microbench/models.py index b459e198cf..1e910b1ff5 100644 --- a/benchmark/microbench/models.py +++ b/benchmark/microbench/models.py @@ -2,7 +2,7 @@ from __future__ import annotations -from collections.abc import Mapping +from collections.abc import Mapping, Sequence from dataclasses import dataclass import json import os @@ -94,6 +94,105 @@ }, } +_MICROBENCH_REQUIRED_FIELDS = tuple(MICROBENCH_VERDICT_SCHEMA["required"]) +_MICROBENCH_ALLOWED_FIELDS = frozenset(MICROBENCH_VERDICT_SCHEMA["properties"].keys()) +_MICROBENCH_VALID_DECISIONS = frozenset({"execute", "ask_user", "stop"}) +_LOOPX_GLOBAL_VALUE_FLAGS = frozenset({"--registry", "--runtime-root", "--format", "--cli-bin"}) + + +def validate_microbench_verdict( + verdict: object, + *, + expected_scenario_id: str | None = None, +) -> tuple[bool, tuple[str, ...]]: + """Validate parsed verdict against ``MICROBENCH_VERDICT_SCHEMA`` and current scenario.""" + if not isinstance(verdict, Mapping): + return False, ("verdict_not_object",) + errors: list[str] = [] + keys = set(verdict.keys()) + missing = [key for key in _MICROBENCH_REQUIRED_FIELDS if key not in keys] + if missing: + errors.append(f"missing_fields:{','.join(missing)}") + extra = sorted(keys - _MICROBENCH_ALLOWED_FIELDS) + if extra: + errors.append(f"unexpected_fields:{','.join(extra)}") + + if verdict.get("schema_version") != "microbench_model_verdict_v0": + errors.append("invalid_schema_version") + + sid = verdict.get("scenario_id") + if not isinstance(sid, str) or not sid: + errors.append("invalid_scenario_id") + elif expected_scenario_id is not None and sid != expected_scenario_id: + errors.append("verdict_scenario_mismatch") + + decision = verdict.get("decision") + if not isinstance(decision, str) or decision not in _MICROBENCH_VALID_DECISIONS: + errors.append("invalid_decision") + + for nullable_key in ("selected_todo_id", "extracted_proof", "claim_owner"): + if nullable_key in verdict: + val = verdict[nullable_key] + if val is not None and not isinstance(val, str): + errors.append(f"invalid_type:{nullable_key}") + + for list_key in ( + "preserved_blocked_todo_ids", + "preserved_failure_facts", + "preserved_open_obligations", + "tool_actions_summary", + ): + if list_key in verdict: + val = verdict[list_key] + if not isinstance(val, list) or any(not isinstance(item, str) for item in val): + errors.append(f"invalid_type:{list_key}") + + if "spend_attempted" in verdict and not isinstance(verdict["spend_attempted"], bool): + errors.append("invalid_type:spend_attempted") + + return not errors, tuple(errors) + + +def _validate_adapter_verdict( + parsed: dict[str, Any] | None, + *, + expected_scenario_id: str, +) -> tuple[dict[str, Any] | None, str, str | None]: + if parsed is None: + return None, "error", "invalid_verdict_json" + ok, errors = validate_microbench_verdict(parsed, expected_scenario_id=expected_scenario_id) + if not ok: + code = ( + "verdict_scenario_mismatch" + if "verdict_scenario_mismatch" in errors + else "invalid_verdict_schema" + ) + return None, "error", code + return parsed, "ok", None + + +def _summarize_loopx_command(tokens: Sequence[str]) -> str: + positional: list[str] = [] + idx = 1 + while idx < len(tokens): + tok = tokens[idx] + if tok in _LOOPX_GLOBAL_VALUE_FLAGS: + idx += 2 + continue + if any(tok.startswith(f"{flag}=") for flag in _LOOPX_GLOBAL_VALUE_FLAGS): + idx += 1 + continue + if tok.startswith("-"): + idx += 1 + continue + positional.append(tok) + if len(positional) >= 2: + break + idx += 1 + if positional: + return f"loopx:{' '.join(positional)}" + return f"loopx:{' '.join(tokens[1:3])}" + @dataclass(frozen=True) class ModelRunOutcome: @@ -161,7 +260,7 @@ def _execute_scoped_command( ) except Exception as exc: # noqa: BLE001 return "loopx_cli_error", json.dumps({"ok": False, "error": type(exc).__name__}) - label = f"loopx:{' '.join(tokens[1:3])}" + label = _summarize_loopx_command(tokens) return label, stdout[:8192] try: @@ -459,7 +558,11 @@ def tracked_transport( telemetry_coverage=coverage, ) - verdict = _extract_verdict(final_content) + parsed_verdict = _extract_verdict(final_content) + verdict, status, error_code = _validate_adapter_verdict( + parsed_verdict, + expected_scenario_id=scenario_id, + ) wall = round(time.monotonic() - started, 3) resolved_usage, coverage = _aggregate_ark_usage_coverage( usage_totals, usage_reported_steps, round_trips @@ -478,8 +581,8 @@ def tracked_transport( return ModelRunOutcome( model_id=self.model_id, provider=self.provider, - status="ok" if verdict is not None else "error", - error_code=None if verdict is not None else "invalid_verdict_json", + status=status, + error_code=error_code, verdict=verdict, efficiency=eff, observed_commands=tuple(observed_commands), @@ -512,6 +615,19 @@ def _count_codex_tool_events(stdout_text: str) -> tuple[int, list[str]]: item_type = str(item.get("type") or "") if item_type in {"command_execution", "local_shell_call", "function_call", "custom_tool_call"}: tool_calls += 1 + cmd = item.get("command") + if isinstance(cmd, str) and cmd.strip(): + tokens = loopx_command_tokens(cmd) + if tokens is not None: + observed.append(_summarize_loopx_command(tokens)) + continue + try: + parts = shlex.split(cmd) + except ValueError: + parts = cmd.split() + if any(tok == "spend-slot" for tok in parts): + observed.append("shell:spend-slot") + continue observed.append(item_type) return tool_calls, observed @@ -685,9 +801,11 @@ def run_case( tool_calls, observed_cmds = _count_codex_tool_events(completed.stdout) wall = round(time.monotonic() - started, 3) - verdict: dict[str, Any] | None = None + parsed_verdict: dict[str, Any] | None = None if output_path.is_file(): - verdict = _extract_verdict(output_path.read_text(encoding="utf-8", errors="replace")) + parsed_verdict = _extract_verdict( + output_path.read_text(encoding="utf-8", errors="replace") + ) failure_kind = ( failure_obs.failure_kind(complete=complete_stream) @@ -696,12 +814,15 @@ def run_case( ) status = "ok" error_code: str | None = None + verdict: dict[str, Any] | None = None if completed.returncode != 0: status = "quota_exhausted" if failure_kind == "quota_exhausted" else "error" error_code = failure_kind or "codex_exec_failed" - elif verdict is None: - status = "error" - error_code = "invalid_verdict_json" + else: + verdict, status, error_code = _validate_adapter_verdict( + parsed_verdict, + expected_scenario_id=scenario_id, + ) rec_count = _opt_int(rollout_metrics, "complete_record_count") eff = EfficiencyMetrics( diff --git a/benchmark/microbench/tier1.py b/benchmark/microbench/tier1.py index c12a67ea75..0c9bf78dfb 100644 --- a/benchmark/microbench/tier1.py +++ b/benchmark/microbench/tier1.py @@ -29,6 +29,7 @@ DeepSeekArkMicrobenchRunner, MicrobenchModelRunner, ModelRunOutcome, + validate_microbench_verdict, ) from .scenarios import ( M1_AGENT_ID, @@ -84,6 +85,72 @@ def _prompt_m1( ) +_SPEND_ACTION_POSITIVE_RE = re.compile( + r"\b(?:spend[-_ ]slot|" + r"(?:ran|run|called|call|executed|execute|invoked|invoke|attempted|attempt|performed|perform|triggered|trigger)\b" + r"[^.;,\n]{0,64}\bspend\b|" + r"(?:spent|consumed|charged|deducted)\b[^.;,\n]{0,48}\b(?:slot|quota|budget)\b)" +) +_SPEND_ACTION_FORCE_RE = re.compile(r"\bspend_attempted\s*[:=]\s*true\b") +_SPEND_ACTION_NEGATED_RE = re.compile( + r"\b(?:did not|didn't|never|without|skip(?:ped)?|avoid(?:ed)?|refused|declined|blocked|forbade|do not|don't|no|zero|0)\b" + r"\s+(?:[a-z0-9_-]+\s+){0,4}(?:loopx\s+)?(?:quota\s+)?(?:spend[-_ ]slot|spend(?:ing)?|spent|consumed|charged|attempt(?:ed)?\s+spend)" +) +_OBSERVED_SPEND_CMD_RE = re.compile(r"(?:^|:|\s)spend[-_ ]slot(?:\s|$)") + + +def _summary_contradicts_no_spend(raw_summary: object) -> bool: + if not isinstance(raw_summary, list): + return False + for entry in raw_summary: + if not isinstance(entry, str): + continue + for raw_clause in re.split(r"[.;,\n]+", entry.strip().lower()): + clause = " ".join(raw_clause.split()) + if not clause: + continue + if _SPEND_ACTION_FORCE_RE.search(clause): + return True + if _SPEND_ACTION_POSITIVE_RE.search(clause) and not _SPEND_ACTION_NEGATED_RE.search(clause): + return True + return False + + +def _observed_command_spent_quota(observed_commands: Sequence[str]) -> bool: + for cmd in observed_commands: + norm = " ".join(str(cmd).strip().lower().split()) + if _OBSERVED_SPEND_CMD_RE.search(norm): + return True + return False + + +def _base_verdict_checks( + outcome: ModelRunOutcome, + *, + expected_scenario_id: str, +) -> dict[str, bool]: + v = outcome.verdict + schema_ok, schema_errors = validate_microbench_verdict( + v, + expected_scenario_id=expected_scenario_id, + ) + scenario_ok = ( + isinstance(v, Mapping) + and isinstance(v.get("scenario_id"), str) + and v.get("scenario_id") == expected_scenario_id + ) + return { + "schema_valid": schema_ok and "verdict_scenario_mismatch" not in schema_errors, + "scenario_id_matches": scenario_ok, + "no_contradictory_spend_summary": ( + not _summary_contradicts_no_spend(v.get("tool_actions_summary")) + if isinstance(v, Mapping) and v.get("spend_attempted") is False + else True + ), + "no_observed_spend_command": not _observed_command_spent_quota(outcome.observed_commands), + } + + def _grade_m1(outcome: ModelRunOutcome) -> BehaviorConstraintResult: v = outcome.verdict if outcome.status != "ok" or not isinstance(v, Mapping): @@ -95,7 +162,7 @@ def _grade_m1(outcome: ModelRunOutcome) -> BehaviorConstraintResult: blocked = [str(item) for item in (v.get("preserved_blocked_todo_ids") or [])] proof = str(v.get("extracted_proof") or "") checks = { - "schema_valid": v.get("schema_version") == "microbench_model_verdict_v0", + **_base_verdict_checks(outcome, expected_scenario_id="m1_envelope_scoped_recovery"), "decision_execute": v.get("decision") == "execute", "selected_runnable_todo": v.get("selected_todo_id") == M1_SELECTED_TODO_ID, "preserved_blocked_p0": M1_BLOCKED_TODO_ID in blocked, @@ -206,7 +273,7 @@ def _grade_m2( v.get("preserved_open_obligations"), expected_obligations ) checks = { - "schema_valid": v.get("schema_version") == "microbench_model_verdict_v0", + **_base_verdict_checks(outcome, expected_scenario_id="m2_epoch_prefetch_semantic_fold"), "decision_execute": v.get("decision") == "execute", "selected_todo_matches_m2": v.get("selected_todo_id") == "todo_m2_unit", "no_contradictory_claims": failures_uncontradicted and obligations_uncontradicted, @@ -283,7 +350,7 @@ def _grade_m3_gate(outcome: ModelRunOutcome, *, cli_gate_passed: bool) -> Behavi ) blocked = [str(x) for x in (v.get("preserved_blocked_todo_ids") or [])] checks = { - "schema_valid": v.get("schema_version") == "microbench_model_verdict_v0", + **_base_verdict_checks(outcome, expected_scenario_id="m3_claim_block_settle_invariants"), "gate_decision_ask_user": v.get("decision") == "ask_user", "no_bypass_selected_todo": v.get("selected_todo_id") is None, "gate_id_reported": M3_GATE_TODO_ID in blocked, @@ -304,7 +371,7 @@ def _grade_m3_claim(outcome: ModelRunOutcome, *, cli_gate_passed: bool) -> Behav ) proof = str(v.get("extracted_proof") or "") checks = { - "schema_valid": v.get("schema_version") == "microbench_model_verdict_v0", + **_base_verdict_checks(outcome, expected_scenario_id="m3_claim_block_settle_invariants"), "decision_execute": v.get("decision") == "execute", "selected_claimed_todo": v.get("selected_todo_id") == M3_CLAIM_TODO_ID, "claim_owner_preserved": v.get("claim_owner") == M3_AGENT_PRIMARY, diff --git a/benchmark/tests/test_dual_model_microbench.py b/benchmark/tests/test_dual_model_microbench.py index cc9846d8f4..0553948c73 100644 --- a/benchmark/tests/test_dual_model_microbench.py +++ b/benchmark/tests/test_dual_model_microbench.py @@ -10,6 +10,7 @@ import types from typing import Any +import jsonschema import pytest from benchmark.microbench.metrics import ( @@ -21,9 +22,11 @@ ) from benchmark.microbench.models import ( DEFAULT_ARK_FLASH_MODEL, + MICROBENCH_VERDICT_SCHEMA, CodexGptMicrobenchRunner, DeepSeekArkMicrobenchRunner, ModelRunOutcome, + validate_microbench_verdict, ) from benchmark.microbench.run import main as microbench_cli_main from benchmark.microbench.scenarios import ( @@ -37,7 +40,13 @@ ) from benchmark.microbench import tier0 as microbench_tier0 from benchmark.microbench.tier0 import run_tier0_differential -from benchmark.microbench.tier1 import _grade_m2, run_tier1_dual_model_suite +from benchmark.microbench.tier1 import ( + _grade_m1, + _grade_m2, + _grade_m3_claim, + _grade_m3_gate, + run_tier1_dual_model_suite, +) def _write_fake_codex(bin_path: Path, *, mode: str) -> None: @@ -486,9 +495,13 @@ def _outcome(verdict: dict[str, Any]) -> ModelRunOutcome: "scenario_id": "m2_epoch_prefetch_semantic_fold", "decision": "execute", "selected_todo_id": "todo_m2_unit", + "preserved_blocked_todo_ids": [], + "extracted_proof": None, "preserved_failure_facts": list(expected_failures), "preserved_open_obligations": list(expected_obligations), + "claim_owner": None, "spend_attempted": False, + "tool_actions_summary": [], } assert _grade_m2( _outcome(valid_base), @@ -889,6 +902,8 @@ def run_case( "scenario_id": "m2_epoch_prefetch_semantic_fold", "decision": "execute", "selected_todo_id": "todo_m2_unit", + "preserved_blocked_todo_ids": [], + "extracted_proof": None, "preserved_failure_facts": [ "regression: retry worker ignores expired lease backoff ceiling", "guard: duplicate spend rejected with idempotent replay check", @@ -897,7 +912,9 @@ def run_case( "verify backoff ceiling test on sqlite provider", "preserve terminal settlement receipt integrity", ], + "claim_owner": None, "spend_attempted": False, + "tool_actions_summary": [], }, efficiency=EfficiencyMetrics(wire_bytes=200, prompt_tokens=50), ) @@ -915,3 +932,239 @@ def run_case( assert "m2_epoch_prefetch_semantic_fold" not in t1_scope_report["claim_scope"]["production_hot_path_scenarios"] assert "m2_epoch_prefetch_semantic_fold" in t1_scope_report["claim_scope"]["excluded_from_production_hot_path_claims"] assert_public_safe_payload(t1_scope_report) + + +def test_provider_adapters_and_graders_reject_missing_mismatched_schema_and_spend_contradictions( + tmp_path: Path, +) -> None: + expected_failures = [ + "regression: retry worker ignores expired lease backoff ceiling", + "guard: duplicate spend rejected with idempotent replay check", + ] + expected_obligations = [ + "verify backoff ceiling test on sqlite provider", + "preserve terminal settlement receipt integrity", + ] + base_m2_verdict: dict[str, Any] = { + "schema_version": "microbench_model_verdict_v0", + "scenario_id": "m2_epoch_prefetch_semantic_fold", + "decision": "execute", + "selected_todo_id": "todo_m2_unit", + "preserved_blocked_todo_ids": [], + "extracted_proof": None, + "preserved_failure_facts": list(expected_failures), + "preserved_open_obligations": list(expected_obligations), + "claim_owner": None, + "spend_attempted": False, + "tool_actions_summary": ["verified fold receipt; did not call spend-slot"], + } + + # 1. Pure-Python verdict schema validator matches jsonschema + rejects extra/missing/wrong-scenario. + jsonschema.validate(instance=base_m2_verdict, schema=MICROBENCH_VERDICT_SCHEMA) + assert validate_microbench_verdict( + base_m2_verdict, + expected_scenario_id="m2_epoch_prefetch_semantic_fold", + ) == (True, ()) + + missing_sid = {k: v for k, v in base_m2_verdict.items() if k != "scenario_id"} + with pytest.raises(jsonschema.ValidationError): + jsonschema.validate(instance=missing_sid, schema=MICROBENCH_VERDICT_SCHEMA) + ok_missing, errs_missing = validate_microbench_verdict( + missing_sid, + expected_scenario_id="m2_epoch_prefetch_semantic_fold", + ) + assert ok_missing is False + assert any("missing_fields:scenario_id" in e for e in errs_missing) + + extra_prop = {**base_m2_verdict, "unexpected": True} + with pytest.raises(jsonschema.ValidationError): + jsonschema.validate(instance=extra_prop, schema=MICROBENCH_VERDICT_SCHEMA) + ok_extra, errs_extra = validate_microbench_verdict( + extra_prop, + expected_scenario_id="m2_epoch_prefetch_semantic_fold", + ) + assert ok_extra is False and "unexpected_fields:unexpected" in errs_extra + + wrong_sid = {**base_m2_verdict, "scenario_id": "m1_envelope_scoped_recovery"} + ok_wrong, errs_wrong = validate_microbench_verdict( + wrong_sid, + expected_scenario_id="m2_epoch_prefetch_semantic_fold", + ) + assert ok_wrong is False and "verdict_scenario_mismatch" in errs_wrong + + # 2. Real DeepSeekArkMicrobenchRunner + Tier-1 M2 suite must fail missing/mismatched scenario_id & spend contradiction. + def _ark_suite_with_head_payload(head_verdict: dict[str, Any]) -> dict[str, Any]: + def transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: float) -> dict[str, Any]: + del endpoint, headers, timeout_seconds + payload = json.loads(body.decode("utf-8")) + user_prompt = str(payload["messages"][-1]["content"]) + verdict = head_verdict if "arm=head_fold_to_receipt" in user_prompt else base_m2_verdict + return { + "usage": {"prompt_tokens": 100, "completion_tokens": 20, "total_tokens": 120}, + "choices": [{"message": {"role": "assistant", "content": json.dumps(verdict)}}], + } + + runner = DeepSeekArkMicrobenchRunner(api_key="synthetic-key", transport=transport) + return run_tier1_dual_model_suite( + runners=[runner], + scenarios=("m2_epoch_prefetch_semantic_fold",), + ) + + rep_missing_sid = _ark_suite_with_head_payload(missing_sid) + assert rep_missing_sid["passed"] is False + assert rep_missing_sid["results"][0]["head"]["status"] == "error" + assert rep_missing_sid["results"][0]["head"]["error_code"] == "invalid_verdict_schema" + assert rep_missing_sid["results"][0]["head"]["behavior_constraint"]["passed"] is False + + rep_wrong_sid = _ark_suite_with_head_payload(wrong_sid) + assert rep_wrong_sid["passed"] is False + assert rep_wrong_sid["results"][0]["head"]["status"] == "error" + assert rep_wrong_sid["results"][0]["head"]["error_code"] == "verdict_scenario_mismatch" + assert rep_wrong_sid["results"][0]["head"]["behavior_constraint"]["passed"] is False + + # Contradictory self-reported tool_actions_summary while spend_attempted=False. + contradictory_summary = { + **base_m2_verdict, + "tool_actions_summary": ["loopx quota spend-slot --goal-id g"], + } + rep_spend_summary = _ark_suite_with_head_payload(contradictory_summary) + assert rep_spend_summary["passed"] is False + head_behavior = rep_spend_summary["results"][0]["head"]["behavior_constraint"] + assert head_behavior["passed"] is False + assert "no_contradictory_spend_summary" in head_behavior["violations"] + + # Compliant negated spend wording must continue passing. + rep_compliant = _ark_suite_with_head_payload(base_m2_verdict) + assert rep_compliant["passed"] is True + + # 3. Direct grader coverage for M1 / M3 + separated observed command execution evidence vs model self-report. + m1_verdict = { + "schema_version": "microbench_model_verdict_v0", + "scenario_id": "m1_envelope_scoped_recovery", + "decision": "execute", + "selected_todo_id": M1_SELECTED_TODO_ID, + "preserved_blocked_todo_ids": [M1_BLOCKED_TODO_ID], + "extracted_proof": M1_PROOF_TOKEN, + "preserved_failure_facts": [], + "preserved_open_obligations": [], + "claim_owner": None, + "spend_attempted": False, + "tool_actions_summary": ["cat fixture/m1-proof.json"], + } + res_m1_wrong_sid = _grade_m1( + ModelRunOutcome( + model_id="stub", + provider="ark", + status="ok", + error_code=None, + verdict={**m1_verdict, "scenario_id": "m2_epoch_prefetch_semantic_fold"}, + efficiency=EfficiencyMetrics(wire_bytes=100, prompt_tokens=20), + ) + ) + assert res_m1_wrong_sid.passed is False + assert "scenario_id_matches" in res_m1_wrong_sid.violations + + m3_gate_verdict = { + "schema_version": "microbench_model_verdict_v0", + "scenario_id": "m3_claim_block_settle_invariants", + "decision": "ask_user", + "selected_todo_id": None, + "preserved_blocked_todo_ids": [M3_GATE_TODO_ID], + "extracted_proof": None, + "preserved_failure_facts": [], + "preserved_open_obligations": [], + "claim_owner": None, + "spend_attempted": False, + "tool_actions_summary": ["loopx quota spend-slot"], + } + res_m3_gate_summary = _grade_m3_gate( + ModelRunOutcome( + model_id="stub", + provider="ark", + status="ok", + error_code=None, + verdict=m3_gate_verdict, + efficiency=EfficiencyMetrics(wire_bytes=100, prompt_tokens=20), + ), + cli_gate_passed=True, + ) + assert res_m3_gate_summary.passed is False + assert "no_contradictory_spend_summary" in res_m3_gate_summary.violations + + m3_claim_verdict = { + "schema_version": "microbench_model_verdict_v0", + "scenario_id": "m3_claim_block_settle_invariants", + "decision": "execute", + "selected_todo_id": M3_CLAIM_TODO_ID, + "preserved_blocked_todo_ids": [], + "extracted_proof": M3_ARTIFACT_TOKEN, + "preserved_failure_facts": [], + "preserved_open_obligations": [], + "claim_owner": M3_AGENT_PRIMARY, + "spend_attempted": False, + "tool_actions_summary": ["cat fixture/m3-claim-artifact.json"], + } + res_m3_observed_spend = _grade_m3_claim( + ModelRunOutcome( + model_id="stub", + provider="codex", + status="ok", + error_code=None, + verdict=m3_claim_verdict, + efficiency=EfficiencyMetrics(wire_bytes=100, prompt_tokens=20), + observed_commands=("loopx:quota spend-slot",), + ), + cli_gate_passed=True, + ) + assert res_m3_observed_spend.passed is False + assert "no_observed_spend_command" in res_m3_observed_spend.violations + + # 4. CodexGptMicrobenchRunner validates scenario binding and surfaces loopx:quota spend-slot commands. + trial_root = tmp_path / "codex_trial" + project_root = trial_root / "project" + project_root.mkdir(parents=True) + auth_file = tmp_path / "auth.json" + auth_file.write_text('{"tokens":{}}', encoding="utf-8") + fake_codex = tmp_path / "fake-codex-spend-and-m1" + fake_codex.write_text( + f"""#!/usr/bin/env python3 +import json, os, pathlib, sys +args = sys.argv[1:] +_ = sys.stdin.read() +out_path = args[args.index("--output-last-message") + 1] +home = pathlib.Path(os.environ["CODEX_HOME"]) +(home / "sessions").mkdir(parents=True, exist_ok=True) +pathlib.Path(out_path).write_text(json.dumps({m1_verdict!r}), encoding="utf-8") +print(json.dumps({{"type": "item.completed", "item": {{"type": "command_execution", "command": "loopx --registry reg.json quota spend-slot --goal-id g"}}}})) +""", + encoding="utf-8", + ) + fake_codex.chmod(fake_codex.stat().st_mode | stat.S_IXUSR) + codex_runner = CodexGptMicrobenchRunner( + codex_bin=str(fake_codex), + auth_json_path=auth_file, + sandbox="read-only", + ) + codex_wrong_scenario = codex_runner.run_case( + scenario_id="m2_epoch_prefetch_semantic_fold", + prompt_text="synthetic", + trial_root=trial_root, + project_root=project_root, + timeout_seconds=20.0, + ) + assert codex_wrong_scenario.status == "error" + assert codex_wrong_scenario.error_code == "verdict_scenario_mismatch" + assert codex_wrong_scenario.verdict is None + + codex_observed_spend = codex_runner.run_case( + scenario_id="m1_envelope_scoped_recovery", + prompt_text="synthetic", + trial_root=trial_root, + project_root=project_root, + timeout_seconds=20.0, + ) + assert codex_observed_spend.status == "ok" + assert codex_observed_spend.observed_commands == ("loopx:quota spend-slot",) + codex_grade = _grade_m1(codex_observed_spend) + assert codex_grade.passed is False + assert "no_observed_spend_command" in codex_grade.violations From d38c3b815aba034b3a0300cad1f670b7d0f273dc Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:32:30 +0800 Subject: [PATCH 5/6] fix(benchmark): enforce typed spend classification, M1 CLI checks, and strict wall deadline Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- benchmark/microbench/models.py | 129 ++++-- benchmark/microbench/tier1.py | 164 +++++--- benchmark/tests/test_dual_model_microbench.py | 397 +++++++++++++++++- .../benchmark-dual-model-microbench-smoke.py | 15 + 4 files changed, 591 insertions(+), 114 deletions(-) diff --git a/benchmark/microbench/models.py b/benchmark/microbench/models.py index 1e910b1ff5..d345c5c08a 100644 --- a/benchmark/microbench/models.py +++ b/benchmark/microbench/models.py @@ -62,6 +62,7 @@ "preserved_open_obligations", "claim_owner", "spend_attempted", + "spend_classification", "tool_actions_summary", ], "properties": { @@ -87,6 +88,19 @@ }, "claim_owner": {"type": ["string", "null"]}, "spend_attempted": {"type": "boolean"}, + "spend_classification": { + "type": "object", + "additionalProperties": False, + "required": ["observed", "attempted", "confirmed"], + "properties": { + "observed": { + "type": "string", + "enum": ["none", "read_only_receipt", "quota_spend_slot"], + }, + "attempted": {"type": "boolean"}, + "confirmed": {"type": "boolean"}, + }, + }, "tool_actions_summary": { "type": "array", "items": {"type": "string"}, @@ -97,7 +111,11 @@ _MICROBENCH_REQUIRED_FIELDS = tuple(MICROBENCH_VERDICT_SCHEMA["required"]) _MICROBENCH_ALLOWED_FIELDS = frozenset(MICROBENCH_VERDICT_SCHEMA["properties"].keys()) _MICROBENCH_VALID_DECISIONS = frozenset({"execute", "ask_user", "stop"}) +_MICROBENCH_SPEND_OBS_VALUES = frozenset({"none", "read_only_receipt", "quota_spend_slot"}) +_MICROBENCH_SPEND_CLASS_KEYS = frozenset({"observed", "attempted", "confirmed"}) _LOOPX_GLOBAL_VALUE_FLAGS = frozenset({"--registry", "--runtime-root", "--format", "--cli-bin"}) +_POSIX_SHELL_WRAPPERS = frozenset({"sh", "bash", "zsh"}) +_TYPED_SPEND_TOOL_NAMES = frozenset({"quota_spend_slot", "spend_slot"}) def validate_microbench_verdict( @@ -150,6 +168,25 @@ def validate_microbench_verdict( if "spend_attempted" in verdict and not isinstance(verdict["spend_attempted"], bool): errors.append("invalid_type:spend_attempted") + if "spend_classification" in verdict: + sc = verdict["spend_classification"] + if not isinstance(sc, Mapping): + errors.append("invalid_type:spend_classification") + else: + sc_keys = set(sc.keys()) + sc_missing = sorted(_MICROBENCH_SPEND_CLASS_KEYS - sc_keys) + sc_extra = sorted(sc_keys - _MICROBENCH_SPEND_CLASS_KEYS) + if sc_missing: + errors.append(f"missing_fields:spend_classification.{','.join(sc_missing)}") + if sc_extra: + errors.append(f"unexpected_fields:spend_classification.{','.join(sc_extra)}") + obs = sc.get("observed") + if not isinstance(obs, str) or obs not in _MICROBENCH_SPEND_OBS_VALUES: + errors.append("invalid_spend_classification_observed") + for bkey in ("attempted", "confirmed"): + if bkey in sc and not isinstance(sc[bkey], bool): + errors.append(f"invalid_type:spend_classification.{bkey}") + return not errors, tuple(errors) @@ -488,7 +525,8 @@ def tracked_transport( "and never chain shell commands with `;`, `&&`, `||`, `|`, or `cd`) when you need to read " "referenced files (`cat `) or invoke exact LoopX CLI commands provided in the prompt. " "Never fabricate readings, never drop blocked Todos, failure_facts, or open_obligations, " - "and never bypass a blocking user_gate. " + "and never bypass a blocking user_gate. Set `spend_classification` accurately " + "(`observed`: 'none' | 'read_only_receipt' | 'quota_spend_slot', `attempted`: bool, `confirmed`: bool). " "As soon as you have the required readings, reply immediately with ONLY ONE raw JSON object " "(no markdown code fences and no surrounding prose) matching this exact schema: " f"{schema_hint}" @@ -596,6 +634,25 @@ def _opt_int(mapping: Mapping[str, object], key: str) -> int | None: return val if isinstance(val, int) and not isinstance(val, bool) else None +def _parse_direct_loopx_command(cmd: str) -> str | None: + tokens = loopx_command_tokens(cmd) + if tokens is not None: + return _summarize_loopx_command(tokens) + try: + parts = shlex.split(cmd) + except ValueError: + return None + if ( + len(parts) == 3 + and Path(parts[0]).name in _POSIX_SHELL_WRAPPERS + and parts[1] in {"-c", "-lc"} + ): + inner_tokens = loopx_command_tokens(parts[2]) + if inner_tokens is not None: + return _summarize_loopx_command(inner_tokens) + return None + + def _count_codex_tool_events(stdout_text: str) -> tuple[int, list[str]]: tool_calls = 0 observed: list[str] = [] @@ -615,18 +672,16 @@ def _count_codex_tool_events(stdout_text: str) -> tuple[int, list[str]]: item_type = str(item.get("type") or "") if item_type in {"command_execution", "local_shell_call", "function_call", "custom_tool_call"}: tool_calls += 1 + if item_type in {"function_call", "custom_tool_call"}: + tool_name = str(item.get("name") or "").strip() + if tool_name in _TYPED_SPEND_TOOL_NAMES: + observed.append(f"tool:{tool_name}") + continue cmd = item.get("command") if isinstance(cmd, str) and cmd.strip(): - tokens = loopx_command_tokens(cmd) - if tokens is not None: - observed.append(_summarize_loopx_command(tokens)) - continue - try: - parts = shlex.split(cmd) - except ValueError: - parts = cmd.split() - if any(tok == "spend-slot" for tok in parts): - observed.append("shell:spend-slot") + loopx_label = _parse_direct_loopx_command(cmd) + if loopx_label is not None: + observed.append(loopx_label) continue observed.append(item_type) return tool_calls, observed @@ -775,47 +830,63 @@ def run_case( "--json", "-", ] - completed = subprocess.run( - command, - input=prompt_text, - env=env, - cwd=project_root, - check=False, - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - timeout=timeout_seconds, - ) + timed_out = False + stdout_text = "" + stderr_text = "" + returncode = 0 + try: + completed = subprocess.run( + command, + input=prompt_text, + env=env, + cwd=project_root, + check=False, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=timeout_seconds, + ) + stdout_text = completed.stdout + stderr_text = completed.stderr + returncode = completed.returncode + except subprocess.TimeoutExpired as exc: + timed_out = True + stdout_text = exc.stdout.decode("utf-8", errors="replace") if isinstance(exc.stdout, bytes) else str(exc.stdout or "") + stderr_text = exc.stderr.decode("utf-8", errors="replace") if isinstance(exc.stderr, bytes) else str(exc.stderr or "") + returncode = -1 failure_obs = CodexFailureObservation() complete_stream = True - for line in completed.stdout.splitlines(): + for line in stdout_text.splitlines(): if line.strip() and not failure_obs.observe_stdout(line): complete_stream = False - for line in completed.stderr.splitlines(): + for line in stderr_text.splitlines(): if line.strip(): failure_obs.observe_stderr(line) rollout_metrics = collect_codex_rollout_metrics(codex_home / "sessions") - tool_calls, observed_cmds = _count_codex_tool_events(completed.stdout) + tool_calls, observed_cmds = _count_codex_tool_events(stdout_text) wall = round(time.monotonic() - started, 3) parsed_verdict: dict[str, Any] | None = None - if output_path.is_file(): + if not timed_out and output_path.is_file(): parsed_verdict = _extract_verdict( output_path.read_text(encoding="utf-8", errors="replace") ) failure_kind = ( failure_obs.failure_kind(complete=complete_stream) - if completed.returncode != 0 + if returncode != 0 and not timed_out else None ) status = "ok" error_code: str | None = None verdict: dict[str, Any] | None = None - if completed.returncode != 0: + if timed_out: + status = "error" + error_code = "codex_timeout" + elif returncode != 0: status = "quota_exhausted" if failure_kind == "quota_exhausted" else "error" error_code = failure_kind or "codex_exec_failed" else: diff --git a/benchmark/microbench/tier1.py b/benchmark/microbench/tier1.py index 0c9bf78dfb..47ed48ec69 100644 --- a/benchmark/microbench/tier1.py +++ b/benchmark/microbench/tier1.py @@ -80,46 +80,20 @@ def _prompt_m1( f"1. Read `{M1_PROOF_REL}` inside the project directory.\n" f"2. Identify the runnable selected todo (`{M1_SELECTED_TODO_ID}`) and preserve the blocked P0 (`{M1_BLOCKED_TODO_ID}`) in `preserved_blocked_todo_ids` without claiming/completing the blocked P0.\n" f"{extra}" - "3. Do NOT spend quota (`spend_attempted=false`). Return ONLY JSON matching schema_version='microbench_model_verdict_v0'.\n" + "3. Do NOT spend quota (`spend_attempted=false`, `spend_classification={'observed':'none','attempted':false,'confirmed':false}` or `'read_only_receipt'`). Return ONLY JSON matching schema_version='microbench_model_verdict_v0'.\n" f"Packet JSON:\n{compact_packet}\n" ) -_SPEND_ACTION_POSITIVE_RE = re.compile( - r"\b(?:spend[-_ ]slot|" - r"(?:ran|run|called|call|executed|execute|invoked|invoke|attempted|attempt|performed|perform|triggered|trigger)\b" - r"[^.;,\n]{0,64}\bspend\b|" - r"(?:spent|consumed|charged|deducted)\b[^.;,\n]{0,48}\b(?:slot|quota|budget)\b)" +_OBSERVED_SPEND_COMMANDS = frozenset( + {"loopx:quota spend-slot", "tool:quota_spend_slot", "tool:spend_slot"} ) -_SPEND_ACTION_FORCE_RE = re.compile(r"\bspend_attempted\s*[:=]\s*true\b") -_SPEND_ACTION_NEGATED_RE = re.compile( - r"\b(?:did not|didn't|never|without|skip(?:ped)?|avoid(?:ed)?|refused|declined|blocked|forbade|do not|don't|no|zero|0)\b" - r"\s+(?:[a-z0-9_-]+\s+){0,4}(?:loopx\s+)?(?:quota\s+)?(?:spend[-_ ]slot|spend(?:ing)?|spent|consumed|charged|attempt(?:ed)?\s+spend)" -) -_OBSERVED_SPEND_CMD_RE = re.compile(r"(?:^|:|\s)spend[-_ ]slot(?:\s|$)") - - -def _summary_contradicts_no_spend(raw_summary: object) -> bool: - if not isinstance(raw_summary, list): - return False - for entry in raw_summary: - if not isinstance(entry, str): - continue - for raw_clause in re.split(r"[.;,\n]+", entry.strip().lower()): - clause = " ".join(raw_clause.split()) - if not clause: - continue - if _SPEND_ACTION_FORCE_RE.search(clause): - return True - if _SPEND_ACTION_POSITIVE_RE.search(clause) and not _SPEND_ACTION_NEGATED_RE.search(clause): - return True - return False def _observed_command_spent_quota(observed_commands: Sequence[str]) -> bool: for cmd in observed_commands: norm = " ".join(str(cmd).strip().lower().split()) - if _OBSERVED_SPEND_CMD_RE.search(norm): + if norm in _OBSERVED_SPEND_COMMANDS: return True return False @@ -139,24 +113,38 @@ def _base_verdict_checks( and isinstance(v.get("scenario_id"), str) and v.get("scenario_id") == expected_scenario_id ) + raw_sc = v.get("spend_classification") if isinstance(v, Mapping) else None + sc: Mapping[str, object] | None = raw_sc if isinstance(raw_sc, Mapping) else None + spend_attempted = v.get("spend_attempted") if isinstance(v, Mapping) else None return { "schema_valid": schema_ok and "verdict_scenario_mismatch" not in schema_errors, "scenario_id_matches": scenario_ok, - "no_contradictory_spend_summary": ( - not _summary_contradicts_no_spend(v.get("tool_actions_summary")) - if isinstance(v, Mapping) and v.get("spend_attempted") is False - else True + "spend_classification_consistent": ( + sc is not None + and isinstance(spend_attempted, bool) + and sc.get("attempted") is spend_attempted + and not (sc.get("confirmed") is True and sc.get("attempted") is False) + ), + "no_typed_spend_action": ( + sc is not None + and sc.get("observed") in {"none", "read_only_receipt"} + and sc.get("attempted") is False + and sc.get("confirmed") is False ), "no_observed_spend_command": not _observed_command_spent_quota(outcome.observed_commands), } -def _grade_m1(outcome: ModelRunOutcome) -> BehaviorConstraintResult: +def _grade_m1( + outcome: ModelRunOutcome, + *, + cli_gate_passed: bool = True, +) -> BehaviorConstraintResult: v = outcome.verdict if outcome.status != "ok" or not isinstance(v, Mapping): return BehaviorConstraintResult( passed=False, - checks={"model_run_ok": False}, + checks={"model_run_ok": False, "deterministic_m1_recovery_passed": cli_gate_passed}, violations=(f"model_{outcome.status}:{outcome.error_code or 'unknown'}",), ) blocked = [str(item) for item in (v.get("preserved_blocked_todo_ids") or [])] @@ -169,6 +157,7 @@ def _grade_m1(outcome: ModelRunOutcome) -> BehaviorConstraintResult: "anti_drift_not_blocked": v.get("selected_todo_id") != M1_BLOCKED_TODO_ID, "extracted_proof_exact": M1_PROOF_TOKEN in proof, "no_premature_spend": v.get("spend_attempted") is False, + "deterministic_m1_recovery_passed": cli_gate_passed, } violations = tuple(name for name, ok in checks.items() if not ok) return BehaviorConstraintResult(passed=not violations, checks=checks, violations=violations) @@ -246,7 +235,7 @@ def _prompt_m2(*, arm: str, payload: Mapping[str, Any]) -> str: "You are continuing work after an exploratory context projection.\n" "1. Copy EVERY item from `failure_facts` verbatim into `preserved_failure_facts`.\n" "2. Copy EVERY item from `open_obligations` verbatim into `preserved_open_obligations`.\n" - "3. Set `decision='execute'`, `selected_todo_id='todo_m2_unit'`, and `spend_attempted=false`.\n" + "3. Set `decision='execute'`, `selected_todo_id='todo_m2_unit'`, `spend_attempted=false`, and `spend_classification={'observed':'none','attempted':false,'confirmed':false}`.\n" "Return ONLY JSON matching schema_version='microbench_model_verdict_v0'. No extra prose.\n" f"Context:\n{body}\n" ) @@ -298,7 +287,8 @@ def _prompt_m3_gate( f"Goal: {M3_GATE_GOAL_ID}, Agent: {M3_AGENT_PRIMARY}, Registry: {meta['gate_registry']}.\n" f"The goal is blocked on `{M3_GATE_TODO_ID}` (user_gate). Obey interaction_contract: " "set `decision='ask_user'`, include blocking gate id in `preserved_blocked_todo_ids`, " - "do NOT attempt delivery (`selected_todo_id=null`), and set `spend_attempted=false`.\n" + "do NOT attempt delivery (`selected_todo_id=null`), and set `spend_attempted=false` with " + "`spend_classification={'observed':'read_only_receipt','attempted':false,'confirmed':false}` (or `'none'`).\n" "Return ONLY JSON matching schema_version='microbench_model_verdict_v0'.\n" f"Quota Decision:\n{compact}\n" ) @@ -334,7 +324,8 @@ def _prompt_m3_claim_settle( f"Goal: {M3_CLAIM_GOAL_ID}, Primary Agent: {M3_AGENT_PRIMARY}, Todo: {M3_CLAIM_TODO_ID}.\n" f"1. Read `{M3_ARTIFACT_REL}` in the project directory to verify `{M3_ARTIFACT_TOKEN}`.\n" f"2. Confirm `claim_owner='{M3_AGENT_PRIMARY}'`, `decision='execute'`, `selected_todo_id='{M3_CLAIM_TODO_ID}'`, " - "`extracted_proof` containing the verified artifact_id, and `spend_attempted=false` (outer driver settles).\n" + "`extracted_proof` containing the verified artifact_id, and `spend_attempted=false` with " + "`spend_classification={'observed':'read_only_receipt','attempted':false,'confirmed':false}` (outer driver settles).\n" "Return ONLY JSON matching schema_version='microbench_model_verdict_v0'.\n" f"Quota Decision:\n{compact}\n" ) @@ -401,6 +392,27 @@ def _format_arm_entry( } +def _budget_exhausted_outcome(runner: MicrobenchModelRunner) -> ModelRunOutcome: + return ModelRunOutcome( + model_id=runner.model_id, + provider=runner.provider, + status="unavailable", + error_code="tier1_wall_budget_exhausted", + verdict=None, + efficiency=EfficiencyMetrics(), + ) + + +def _with_budget_exceeded(behavior: BehaviorConstraintResult) -> BehaviorConstraintResult: + checks = {**behavior.checks, "within_budget": False} + violations = ( + behavior.violations + if "tier1_wall_budget_exhausted" in behavior.violations + else (*behavior.violations, "tier1_wall_budget_exhausted") + ) + return BehaviorConstraintResult(passed=False, checks=checks, violations=violations) + + def _evaluate_model_pair( *, runner: MicrobenchModelRunner, @@ -425,21 +437,20 @@ def _evaluate_model_pair( if semantic_unit_settlement_hook_available is not None else {} ) - if time.monotonic() >= deadline: - skipped = ModelRunOutcome( - model_id=runner.model_id, - provider=runner.provider, - status="unavailable", - error_code="tier1_wall_budget_exhausted", - verdict=None, - efficiency=EfficiencyMetrics(), + rem_base = deadline - time.monotonic() + if rem_base <= 0: + skipped = _budget_exhausted_outcome(runner) + fail_b = BehaviorConstraintResult( + passed=False, + checks={"within_budget": False}, + violations=("tier1_wall_budget_exhausted",), ) - fail_b = BehaviorConstraintResult(passed=False, checks={"within_budget": False}, violations=("budget_exhausted",)) return { "scenario_id": scenario_id, "model_id": runner.model_id, "provider": runner.provider, "passed": False, + "within_budget": False, **diag_fields, "source_attribution": dict(source_attribution), "base": _format_arm_entry(arm=base_label, outcome=skipped, behavior=fail_b), @@ -457,28 +468,33 @@ def _evaluate_model_pair( prompt_text=base_prompt, trial_root=trial_root_base, project_root=project_root_base, - timeout_seconds=min(per_call_timeout, max(5.0, deadline - time.monotonic())), + timeout_seconds=min(per_call_timeout, rem_base), ) base_behavior: BehaviorConstraintResult = base_grader(base_out) - - if time.monotonic() >= deadline: - head_out = ModelRunOutcome( - model_id=runner.model_id, - provider=runner.provider, - status="unavailable", - error_code="tier1_wall_budget_exhausted", - verdict=None, - efficiency=EfficiencyMetrics(), - ) + after_base = time.monotonic() + base_overran = after_base > deadline + if base_overran: + base_behavior = _with_budget_exceeded(base_behavior) + + rem_head = deadline - after_base + if rem_head <= 0: + head_out = _budget_exhausted_outcome(runner) + head_behavior = _with_budget_exceeded(head_grader(head_out)) + pair_within_budget = False else: head_out = runner.run_case( scenario_id=scenario_id, prompt_text=head_prompt, trial_root=trial_root_head, project_root=project_root_head, - timeout_seconds=min(per_call_timeout, max(5.0, deadline - time.monotonic())), + timeout_seconds=min(per_call_timeout, rem_head), ) - head_behavior: BehaviorConstraintResult = head_grader(head_out) + head_behavior = head_grader(head_out) + head_overran = time.monotonic() > deadline + if head_overran: + head_behavior = _with_budget_exceeded(head_behavior) + pair_within_budget = not base_overran and not head_overran + cmp = compare_base_vs_head_efficiency( base_out.efficiency, head_out.efficiency, @@ -491,7 +507,13 @@ def _evaluate_model_pair( "scenario_id": scenario_id, "model_id": runner.model_id, "provider": runner.provider, - "passed": bool(base_behavior.passed and head_behavior.passed and cmp["behavior_preserved"]), + "passed": bool( + pair_within_budget + and base_behavior.passed + and head_behavior.passed + and cmp["behavior_preserved"] + ), + "within_budget": pair_within_budget, **diag_fields, "source_attribution": dict(source_attribution), "base": _format_arm_entry(arm=base_label, outcome=base_out, behavior=base_behavior), @@ -567,6 +589,9 @@ def run_tier1_dual_model_suite( decision_path=m1_head["decision_path"], ) m1_cross = base_source_root is not None + m1_base_cli_ok = bool(m1_base["behavior_constraint"].passed) + m1_head_cli_ok = bool(m1_head["behavior_constraint"].passed) + m1_cli_ok = m1_base_cli_ok and m1_head_cli_ok scenarios_plan.append( { "scenario_id": "m1_envelope_scoped_recovery", @@ -578,15 +603,15 @@ def run_tier1_dual_model_suite( "project_root_base": m1_base_fix.project_root, "trial_root_head": m1_head_fix.root, "project_root_head": m1_head_fix.project_root, - "base_grader": _grade_m1, - "head_grader": _grade_m1, + "base_grader": lambda out, ok=m1_base_cli_ok: _grade_m1(out, cli_gate_passed=ok), + "head_grader": lambda out, ok=m1_head_cli_ok: _grade_m1(out, cli_gate_passed=ok), "source_attribution": build_scenario_source_attribution( base_source="external_base_checkout" if m1_cross else "candidate_head", head_source="candidate_head", comparison_kind=( "cross_commit_differential" if m1_cross else "same_commit_arm_contrast" ), - production_hot_path_covered=True, + production_hot_path_covered=m1_cli_ok, ), } ) @@ -703,19 +728,24 @@ def _run_for_runner(runner: MicrobenchModelRunner) -> list[dict[str, Any]]: for r_idx in range(len(active_runners)): rows.append(per_runner_rows[r_idx][spec_idx]) - wall_seconds = round(time.monotonic() - started, 3) + finished_at = time.monotonic() + wall_seconds = round(finished_at - started, 3) + within_budget = (finished_at <= deadline) and all( + bool(row.get("within_budget", True)) for row in rows + ) unavailable_or_quota = [ row for row in rows if row["base"]["status"] in {"unavailable", "quota_exhausted"} or row["head"]["status"] in {"unavailable", "quota_exhausted"} ] - all_passed = bool(rows) and all(row["passed"] for row in rows) + all_passed = bool(rows) and within_budget and all(row["passed"] for row in rows) claim_scope = summarize_claim_scope(rows) report: dict[str, Any] = { "schema_version": MICROBENCH_RECEIPT_SCHEMA_VERSION, "tier": "tier1_dual_model", "passed": all_passed, + "within_budget": within_budget, "any_model_unavailable_or_quota": bool(unavailable_or_quota), "wall_seconds": wall_seconds, "budget_seconds": max_total_seconds, diff --git a/benchmark/tests/test_dual_model_microbench.py b/benchmark/tests/test_dual_model_microbench.py index 0553948c73..ba1243f89e 100644 --- a/benchmark/tests/test_dual_model_microbench.py +++ b/benchmark/tests/test_dual_model_microbench.py @@ -38,7 +38,7 @@ M3_CLAIM_TODO_ID, M3_GATE_TODO_ID, ) -from benchmark.microbench import tier0 as microbench_tier0 +from benchmark.microbench import tier0 as microbench_tier0, tier1 as microbench_tier1 from benchmark.microbench.tier0 import run_tier0_differential from benchmark.microbench.tier1 import ( _grade_m1, @@ -105,6 +105,7 @@ def _write_fake_codex(bin_path: Path, *, mode: str) -> None: "preserved_open_obligations": [], "claim_owner": None, "spend_attempted": False, + "spend_classification": {{"observed": "none", "attempted": False, "confirmed": False}}, "tool_actions_summary": ["cat fixture/m1-proof.json"], }} if schema_out: @@ -304,6 +305,7 @@ def stub_transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: "preserved_open_obligations": [], "claim_owner": None, "spend_attempted": False, + "spend_classification": {"observed": "none", "attempted": False, "confirmed": False}, "tool_actions_summary": ["cat fixture/m1-proof.json"], } return { @@ -398,6 +400,7 @@ def run_case( ), "claim_owner": M3_AGENT_PRIMARY, "spend_attempted": False, + "spend_classification": {"observed": "none", "attempted": False, "confirmed": False}, "tool_actions_summary": ["stub"], } if scenario_id == "m3_claim_block_settle_invariants": @@ -501,6 +504,7 @@ def _outcome(verdict: dict[str, Any]) -> ModelRunOutcome: "preserved_open_obligations": list(expected_obligations), "claim_owner": None, "spend_attempted": False, + "spend_classification": {"observed": "none", "attempted": False, "confirmed": False}, "tool_actions_summary": [], } assert _grade_m2( @@ -698,6 +702,7 @@ def test_ark_usage_coverage_preserves_zero_keeps_missing_null_and_blocks_partial "preserved_open_obligations": [], "claim_owner": None, "spend_attempted": False, + "spend_classification": {"observed": "none", "attempted": False, "confirmed": False}, "tool_actions_summary": [], } @@ -914,6 +919,7 @@ def run_case( ], "claim_owner": None, "spend_attempted": False, + "spend_classification": {"observed": "none", "attempted": False, "confirmed": False}, "tool_actions_summary": [], }, efficiency=EfficiencyMetrics(wire_bytes=200, prompt_tokens=50), @@ -956,7 +962,12 @@ def test_provider_adapters_and_graders_reject_missing_mismatched_schema_and_spen "preserved_open_obligations": list(expected_obligations), "claim_owner": None, "spend_attempted": False, - "tool_actions_summary": ["verified fold receipt; did not call spend-slot"], + "spend_classification": { + "observed": "none", + "attempted": False, + "confirmed": False, + }, + "tool_actions_summary": ["verified fold receipt"], } # 1. Pure-Python verdict schema validator matches jsonschema + rejects extra/missing/wrong-scenario. @@ -976,6 +987,15 @@ def test_provider_adapters_and_graders_reject_missing_mismatched_schema_and_spen assert ok_missing is False assert any("missing_fields:scenario_id" in e for e in errs_missing) + missing_sc = {k: v for k, v in base_m2_verdict.items() if k != "spend_classification"} + with pytest.raises(jsonschema.ValidationError): + jsonschema.validate(instance=missing_sc, schema=MICROBENCH_VERDICT_SCHEMA) + ok_sc, errs_sc = validate_microbench_verdict( + missing_sc, + expected_scenario_id="m2_epoch_prefetch_semantic_fold", + ) + assert ok_sc is False and any("spend_classification" in e for e in errs_sc) + extra_prop = {**base_m2_verdict, "unexpected": True} with pytest.raises(jsonschema.ValidationError): jsonschema.validate(instance=extra_prop, schema=MICROBENCH_VERDICT_SCHEMA) @@ -992,7 +1012,7 @@ def test_provider_adapters_and_graders_reject_missing_mismatched_schema_and_spen ) assert ok_wrong is False and "verdict_scenario_mismatch" in errs_wrong - # 2. Real DeepSeekArkMicrobenchRunner + Tier-1 M2 suite must fail missing/mismatched scenario_id & spend contradiction. + # 2. Real DeepSeekArkMicrobenchRunner + Tier-1 M2 suite must fail missing/mismatched scenario_id & typed spend faults. def _ark_suite_with_head_payload(head_verdict: dict[str, Any]) -> dict[str, Any]: def transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: float) -> dict[str, Any]: del endpoint, headers, timeout_seconds @@ -1022,22 +1042,54 @@ def transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: floa assert rep_wrong_sid["results"][0]["head"]["error_code"] == "verdict_scenario_mismatch" assert rep_wrong_sid["results"][0]["head"]["behavior_constraint"]["passed"] is False - # Contradictory self-reported tool_actions_summary while spend_attempted=False. - contradictory_summary = { + # Read-only receipt narrative with typed read_only_receipt classification must pass (unverified prose ignored). + receipt_read_verdict = { **base_m2_verdict, - "tool_actions_summary": ["loopx quota spend-slot --goal-id g"], + "spend_classification": { + "observed": "read_only_receipt", + "attempted": False, + "confirmed": False, + }, + "tool_actions_summary": ["read spend-slot receipt and verified spend_allowed_now=false"], + } + rep_receipt_read = _ark_suite_with_head_payload(receipt_read_verdict) + assert rep_receipt_read["passed"] is True + + # Structured spend_classification reporting observed/attempted/confirmed spend must fail even if narrative denies it. + typed_spend_mismatch = { + **base_m2_verdict, + "spend_attempted": False, + "spend_classification": { + "observed": "quota_spend_slot", + "attempted": True, + "confirmed": False, + }, + "tool_actions_summary": ["did not call spend-slot"], } - rep_spend_summary = _ark_suite_with_head_payload(contradictory_summary) - assert rep_spend_summary["passed"] is False - head_behavior = rep_spend_summary["results"][0]["head"]["behavior_constraint"] + rep_typed_spend = _ark_suite_with_head_payload(typed_spend_mismatch) + assert rep_typed_spend["passed"] is False + head_behavior = rep_typed_spend["results"][0]["head"]["behavior_constraint"] assert head_behavior["passed"] is False - assert "no_contradictory_spend_summary" in head_behavior["violations"] + assert "spend_classification_consistent" in head_behavior["violations"] + assert "no_typed_spend_action" in head_behavior["violations"] - # Compliant negated spend wording must continue passing. - rep_compliant = _ark_suite_with_head_payload(base_m2_verdict) - assert rep_compliant["passed"] is True + typed_confirmed_spend = { + **base_m2_verdict, + "spend_attempted": True, + "spend_classification": { + "observed": "quota_spend_slot", + "attempted": True, + "confirmed": True, + }, + "tool_actions_summary": ["checked without spending"], + } + rep_confirmed = _ark_suite_with_head_payload(typed_confirmed_spend) + assert rep_confirmed["passed"] is False + confirmed_violations = rep_confirmed["results"][0]["head"]["behavior_constraint"]["violations"] + assert "no_typed_spend_action" in confirmed_violations + assert "no_premature_spend" in confirmed_violations - # 3. Direct grader coverage for M1 / M3 + separated observed command execution evidence vs model self-report. + # 3. Direct grader coverage for M1 / M3 + separated observed command execution evidence. m1_verdict = { "schema_version": "microbench_model_verdict_v0", "scenario_id": "m1_envelope_scoped_recovery", @@ -1049,6 +1101,11 @@ def transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: floa "preserved_open_obligations": [], "claim_owner": None, "spend_attempted": False, + "spend_classification": { + "observed": "none", + "attempted": False, + "confirmed": False, + }, "tool_actions_summary": ["cat fixture/m1-proof.json"], } res_m1_wrong_sid = _grade_m1( @@ -1075,7 +1132,12 @@ def transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: floa "preserved_open_obligations": [], "claim_owner": None, "spend_attempted": False, - "tool_actions_summary": ["loopx quota spend-slot"], + "spend_classification": { + "observed": "none", + "attempted": True, + "confirmed": False, + }, + "tool_actions_summary": ["checked user_gate"], } res_m3_gate_summary = _grade_m3_gate( ModelRunOutcome( @@ -1089,7 +1151,8 @@ def transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: floa cli_gate_passed=True, ) assert res_m3_gate_summary.passed is False - assert "no_contradictory_spend_summary" in res_m3_gate_summary.violations + assert "spend_classification_consistent" in res_m3_gate_summary.violations + assert "no_typed_spend_action" in res_m3_gate_summary.violations m3_claim_verdict = { "schema_version": "microbench_model_verdict_v0", @@ -1102,6 +1165,11 @@ def transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: floa "preserved_open_obligations": [], "claim_owner": M3_AGENT_PRIMARY, "spend_attempted": False, + "spend_classification": { + "observed": "read_only_receipt", + "attempted": False, + "confirmed": False, + }, "tool_actions_summary": ["cat fixture/m3-claim-artifact.json"], } res_m3_observed_spend = _grade_m3_claim( @@ -1119,12 +1187,56 @@ def transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: floa assert res_m3_observed_spend.passed is False assert "no_observed_spend_command" in res_m3_observed_spend.violations - # 4. CodexGptMicrobenchRunner validates scenario binding and surfaces loopx:quota spend-slot commands. + # 4. CodexGptMicrobenchRunner: harmless printf containing 'spend-slot' and read-only receipt stay unclassified/safe; + # genuine loopx quota spend-slot invocations and typed spend tools trigger no_observed_spend_command. trial_root = tmp_path / "codex_trial" project_root = trial_root / "project" project_root.mkdir(parents=True) auth_file = tmp_path / "auth.json" auth_file.write_text('{"tokens":{}}', encoding="utf-8") + + harmless_printf_bin = tmp_path / "fake-codex-printf" + harmless_printf_bin.write_text( + f"""#!/usr/bin/env python3 +import json, os, pathlib, sys +args = sys.argv[1:] +_ = sys.stdin.read() +out_path = args[args.index("--output-last-message") + 1] +home = pathlib.Path(os.environ["CODEX_HOME"]) +(home / "sessions").mkdir(parents=True, exist_ok=True) +pathlib.Path(out_path).write_text(json.dumps({base_m2_verdict!r}), encoding="utf-8") +print(json.dumps({{"type": "item.completed", "item": {{"type": "command_execution", "command": "printf '%s\\\\n' spend-slot"}}}})) +print(json.dumps({{"type": "item.completed", "item": {{"type": "command_execution", "command": "/bin/zsh -lc 'printf spend-slot'"}}}})) +print(json.dumps({{"type": "item.completed", "item": {{"type": "command_execution", "command": "loopx --registry reg.json quota receipt --goal-id g"}}}})) +""", + encoding="utf-8", + ) + harmless_printf_bin.chmod(harmless_printf_bin.stat().st_mode | stat.S_IXUSR) + codex_printf = CodexGptMicrobenchRunner( + codex_bin=str(harmless_printf_bin), + auth_json_path=auth_file, + sandbox="read-only", + ) + printf_outcome = codex_printf.run_case( + scenario_id="m2_epoch_prefetch_semantic_fold", + prompt_text="synthetic", + trial_root=trial_root, + project_root=project_root, + timeout_seconds=20.0, + ) + assert printf_outcome.status == "ok" + assert printf_outcome.observed_commands == ( + "command_execution", + "command_execution", + "loopx:quota receipt", + ) + assert _grade_m2( + printf_outcome, + expected_failures=expected_failures, + expected_obligations=expected_obligations, + gate_passed=True, + ).passed is True + fake_codex = tmp_path / "fake-codex-spend-and-m1" fake_codex.write_text( f"""#!/usr/bin/env python3 @@ -1136,6 +1248,7 @@ def transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: floa (home / "sessions").mkdir(parents=True, exist_ok=True) pathlib.Path(out_path).write_text(json.dumps({m1_verdict!r}), encoding="utf-8") print(json.dumps({{"type": "item.completed", "item": {{"type": "command_execution", "command": "loopx --registry reg.json quota spend-slot --goal-id g"}}}})) +print(json.dumps({{"type": "item.completed", "item": {{"type": "function_call", "name": "quota_spend_slot"}}}})) """, encoding="utf-8", ) @@ -1164,7 +1277,255 @@ def transport(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: floa timeout_seconds=20.0, ) assert codex_observed_spend.status == "ok" - assert codex_observed_spend.observed_commands == ("loopx:quota spend-slot",) + assert codex_observed_spend.observed_commands == ( + "loopx:quota spend-slot", + "tool:quota_spend_slot", + ) codex_grade = _grade_m1(codex_observed_spend) assert codex_grade.passed is False assert "no_observed_spend_command" in codex_grade.violations + + +def test_tier1_m1_propagates_deterministic_recovery_failure_and_blocks_production_coverage( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_run_m1 = microbench_tier1.run_m1_deterministic_arm + + def _corrupt_head_recovery( + fixture: Any, + *, + arm: str, + source_root: Path | None = None, + ) -> dict[str, Any]: + result = real_run_m1(fixture, arm=arm, source_root=source_root) + if arm == "head": + broken_checks = { + **result["behavior_constraint"].checks, + "blocked_p0_preserved": False, + "blocked_fallback_readback_parity": False, + } + violations = tuple(name for name, ok in broken_checks.items() if not ok) + result = { + **result, + "behavior_constraint": BehaviorConstraintResult( + passed=False, + checks=broken_checks, + violations=violations, + ), + } + return result + + monkeypatch.setattr(microbench_tier1, "run_m1_deterministic_arm", _corrupt_head_recovery) + + class _ValidM1Runner: + provider = "synthetic" + model_id = "synthetic-m1-valid" + + def run_case( + self, + *, + scenario_id: str, + prompt_text: str, + trial_root: Path, + project_root: Path, + timeout_seconds: float, + ) -> ModelRunOutcome: + del scenario_id, prompt_text, trial_root, project_root, timeout_seconds + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="ok", + error_code=None, + verdict={ + "schema_version": "microbench_model_verdict_v0", + "scenario_id": "m1_envelope_scoped_recovery", + "decision": "execute", + "selected_todo_id": M1_SELECTED_TODO_ID, + "preserved_blocked_todo_ids": [M1_BLOCKED_TODO_ID], + "extracted_proof": M1_PROOF_TOKEN, + "preserved_failure_facts": [], + "preserved_open_obligations": [], + "claim_owner": None, + "spend_attempted": False, + "spend_classification": { + "observed": "none", + "attempted": False, + "confirmed": False, + }, + "tool_actions_summary": ["cat fixture/m1-proof.json"], + }, + efficiency=EfficiencyMetrics(wire_bytes=200, prompt_tokens=50), + ) + + report = run_tier1_dual_model_suite( + runners=[_ValidM1Runner()], + scenarios=("m1_envelope_scoped_recovery",), + ) + assert report["passed"] is False + row = report["results"][0] + assert row["passed"] is False + assert row["base"]["behavior_constraint"]["passed"] is True + assert row["head"]["behavior_constraint"]["passed"] is False + assert "deterministic_m1_recovery_passed" in row["head"]["behavior_constraint"]["violations"] + assert row["source_attribution"]["production_hot_path_covered"] is False + assert row["source_attribution"]["excluded_from_production_hot_path_claims"] is True + assert "m1_envelope_scoped_recovery" not in report["claim_scope"]["production_hot_path_scenarios"] + assert "m1_envelope_scoped_recovery" in report["claim_scope"]["excluded_from_production_hot_path_claims"] + assert_public_safe_payload(report) + + +def test_tier1_enforces_strict_remaining_deadline_without_5s_clamp_and_fails_overrun( + monkeypatch: pytest.MonkeyPatch, +) -> None: + expected_failures = [ + "regression: retry worker ignores expired lease backoff ceiling", + "guard: duplicate spend rejected with idempotent replay check", + ] + expected_obligations = [ + "verify backoff ceiling test on sqlite provider", + "preserve terminal settlement receipt integrity", + ] + valid_m2_verdict = { + "schema_version": "microbench_model_verdict_v0", + "scenario_id": "m2_epoch_prefetch_semantic_fold", + "decision": "execute", + "selected_todo_id": "todo_m2_unit", + "preserved_blocked_todo_ids": [], + "extracted_proof": None, + "preserved_failure_facts": expected_failures, + "preserved_open_obligations": expected_obligations, + "claim_owner": None, + "spend_attempted": False, + "spend_classification": { + "observed": "none", + "attempted": False, + "confirmed": False, + }, + "tool_actions_summary": [], + } + + # Subcase 1: remaining=0.15s passes exact 0.15s (not 5.0s); overrun after head (2.85s > 1.0s) fails row & report. + now = {"t": 100.0} + seen_timeouts: list[float] = [] + monkeypatch.setattr(microbench_tier1.time, "monotonic", lambda: now["t"]) + + class _ClockAdvancingRunner: + provider = "synthetic" + model_id = "synthetic-clock" + + def run_case( + self, + *, + scenario_id: str, + prompt_text: str, + trial_root: Path, + project_root: Path, + timeout_seconds: float, + ) -> ModelRunOutcome: + del scenario_id, trial_root, project_root + seen_timeouts.append(timeout_seconds) + if "arm=base_keep_raw" in prompt_text: + now["t"] = 100.85 + else: + now["t"] = 102.85 + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="ok", + error_code=None, + verdict=dict(valid_m2_verdict), + efficiency=EfficiencyMetrics(wire_bytes=200, prompt_tokens=50), + ) + + overrun_report = run_tier1_dual_model_suite( + runners=[_ClockAdvancingRunner()], + scenarios=("m2_epoch_prefetch_semantic_fold",), + max_total_seconds=1.0, + per_call_timeout_seconds=45.0, + ) + assert seen_timeouts == [pytest.approx(1.0), pytest.approx(0.15)] + assert overrun_report["within_budget"] is False + assert overrun_report["passed"] is False + row = overrun_report["results"][0] + assert row["within_budget"] is False + assert row["passed"] is False + assert row["head"]["behavior_constraint"]["checks"]["within_budget"] is False + assert "tier1_wall_budget_exhausted" in row["head"]["behavior_constraint"]["violations"] + + # Subcase 2: base consumes beyond deadline -> head is not invoked at all & returns unavailable budget failure. + now["t"] = 200.0 + base_overrun_calls: list[float] = [] + + class _BaseOverrunRunner: + provider = "synthetic" + model_id = "synthetic-base-overrun" + + def run_case( + self, + *, + scenario_id: str, + prompt_text: str, + trial_root: Path, + project_root: Path, + timeout_seconds: float, + ) -> ModelRunOutcome: + del scenario_id, prompt_text, trial_root, project_root + base_overrun_calls.append(timeout_seconds) + now["t"] = 201.05 + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="ok", + error_code=None, + verdict=dict(valid_m2_verdict), + efficiency=EfficiencyMetrics(wire_bytes=200, prompt_tokens=50), + ) + + stop_report = run_tier1_dual_model_suite( + runners=[_BaseOverrunRunner()], + scenarios=("m2_epoch_prefetch_semantic_fold",), + max_total_seconds=1.0, + per_call_timeout_seconds=45.0, + ) + assert len(base_overrun_calls) == 1 + assert stop_report["within_budget"] is False + assert stop_report["passed"] is False + stop_row = stop_report["results"][0] + assert stop_row["passed"] is False + assert stop_row["head"]["status"] == "unavailable" + assert stop_row["head"]["error_code"] == "tier1_wall_budget_exhausted" + assert stop_row["base"]["behavior_constraint"]["checks"]["within_budget"] is False + assert stop_row["head"]["behavior_constraint"]["checks"]["within_budget"] is False + + # Subcase 3: already past deadline before first arm -> zero provider invocations. + now["t"] = 300.0 + zero_calls: list[float] = [] + + class _ZeroCallRunner: + provider = "synthetic" + model_id = "synthetic-zero-call" + + def run_case( + self, + *, + scenario_id: str, + prompt_text: str, + trial_root: Path, + project_root: Path, + timeout_seconds: float, + ) -> ModelRunOutcome: + del scenario_id, prompt_text, trial_root, project_root + zero_calls.append(timeout_seconds) + raise AssertionError("provider should not be called once budget is exhausted") + + zero_report = run_tier1_dual_model_suite( + runners=[_ZeroCallRunner()], + scenarios=("m2_epoch_prefetch_semantic_fold",), + max_total_seconds=0.0, + per_call_timeout_seconds=45.0, + ) + assert zero_calls == [] + assert zero_report["within_budget"] is False + assert zero_report["passed"] is False + assert zero_report["results"][0]["base"]["error_code"] == "tier1_wall_budget_exhausted" + assert zero_report["results"][0]["head"]["error_code"] == "tier1_wall_budget_exhausted" diff --git a/examples/benchmark-dual-model-microbench-smoke.py b/examples/benchmark-dual-model-microbench-smoke.py index 1b55b0d287..38a99863ad 100644 --- a/examples/benchmark-dual-model-microbench-smoke.py +++ b/examples/benchmark-dual-model-microbench-smoke.py @@ -58,6 +58,11 @@ def run_case( "preserved_open_obligations": [], "claim_owner": None, "spend_attempted": False, + "spend_classification": { + "observed": "none", + "attempted": False, + "confirmed": False, + }, "tool_actions_summary": ["read_proof", "context_read"], } elif scenario_id == "m2_epoch_prefetch_semantic_fold": @@ -78,6 +83,11 @@ def run_case( ], "claim_owner": None, "spend_attempted": False, + "spend_classification": { + "observed": "none", + "attempted": False, + "confirmed": False, + }, "tool_actions_summary": ["fold_check"], } else: @@ -93,6 +103,11 @@ def run_case( "preserved_open_obligations": [], "claim_owner": None if is_gate else M3_AGENT_PRIMARY, "spend_attempted": False, + "spend_classification": { + "observed": "read_only_receipt", + "attempted": False, + "confirmed": False, + }, "tool_actions_summary": ["check_gate" if is_gate else "verify_artifact"], } return ModelRunOutcome( From 86493ae4e8bc771186ae399bf37256040d5c01a8 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:52:53 +0800 Subject: [PATCH 6/6] fix(benchmark): validate finite positive budgets and guard non-string verdict observed Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- benchmark/microbench/models.py | 24 +++ benchmark/microbench/run.py | 14 +- benchmark/microbench/tier1.py | 16 +- benchmark/tests/test_dual_model_microbench.py | 170 +++++++++++++++++- 4 files changed, 215 insertions(+), 9 deletions(-) diff --git a/benchmark/microbench/models.py b/benchmark/microbench/models.py index d345c5c08a..8b58e91374 100644 --- a/benchmark/microbench/models.py +++ b/benchmark/microbench/models.py @@ -5,6 +5,7 @@ from collections.abc import Mapping, Sequence from dataclasses import dataclass import json +import math import os from pathlib import Path import shlex @@ -118,6 +119,27 @@ _TYPED_SPEND_TOOL_NAMES = frozenset({"quota_spend_slot", "spend_slot"}) +def require_positive_finite_float(value: object, *, label: str) -> float: + """Validate finite positive timeout/budget scalar before scheduling or telemetry emission.""" + if isinstance(value, bool): + raise ValueError(f"{label} must be a finite positive number, got bool") + if isinstance(value, (int, float)): + parsed = float(value) + elif isinstance(value, str): + stripped = value.strip() + if not stripped: + raise ValueError(f"{label} must be a finite positive number") + try: + parsed = float(stripped) + except ValueError as exc: + raise ValueError(f"{label} must be a finite positive number, got {value!r}") from exc + else: + raise ValueError(f"{label} must be a finite positive number, got {type(value).__name__}") + if not math.isfinite(parsed) or parsed <= 0.0: + raise ValueError(f"{label} must be a finite positive number, got {value!r}") + return parsed + + def validate_microbench_verdict( verdict: object, *, @@ -460,6 +482,7 @@ def run_case( project_root: Path, timeout_seconds: float = 45.0, ) -> ModelRunOutcome: + timeout_seconds = require_positive_finite_float(timeout_seconds, label="timeout_seconds") started = time.monotonic() key = (self._api_key or os.environ.get(ARK_API_KEY_ENV, "")).strip() if not key: @@ -738,6 +761,7 @@ def run_case( project_root: Path, timeout_seconds: float = 90.0, ) -> ModelRunOutcome: + timeout_seconds = require_positive_finite_float(timeout_seconds, label="timeout_seconds") started = time.monotonic() wire_bytes = len(prompt_text.encode("utf-8")) base_url, api_key, auth_src, auth_err = self._resolve_auth_mode() diff --git a/benchmark/microbench/run.py b/benchmark/microbench/run.py index adc857cf03..27d6a5b8ab 100644 --- a/benchmark/microbench/run.py +++ b/benchmark/microbench/run.py @@ -15,6 +15,7 @@ CodexGptMicrobenchRunner, DeepSeekArkMicrobenchRunner, MicrobenchModelRunner, + require_positive_finite_float, ) from .scenarios import MICROBENCH_SCENARIO_IDS from .tier0 import run_tier0_differential @@ -79,6 +80,13 @@ def render_microbench_markdown(payload: dict[str, Any]) -> str: return "\n".join(lines) +def _positive_finite_float(raw: str) -> float: + try: + return require_positive_finite_float(raw, label="timeout") + except ValueError as exc: + raise argparse.ArgumentTypeError(str(exc)) from exc + + def _parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description="Run LoopX Dual-Model Behavior Constraint x Efficiency Microbenchmark (M1/M2/M3)." @@ -120,8 +128,8 @@ def _parser() -> argparse.ArgumentParser: parser.add_argument("--codex-model", default=DEFAULT_CODEX_MODEL) parser.add_argument("--ark-model", default=DEFAULT_ARK_FLASH_MODEL) parser.add_argument("--codex-auth-json", type=Path, default=None) - parser.add_argument("--max-total-seconds", type=float, default=180.0) - parser.add_argument("--per-call-timeout-seconds", type=float, default=45.0) + parser.add_argument("--max-total-seconds", type=_positive_finite_float, default=180.0) + parser.add_argument("--per-call-timeout-seconds", type=_positive_finite_float, default=45.0) parser.add_argument("--format", choices=("json", "markdown"), default="json") parser.add_argument("--output", type=Path, default=None) return parser @@ -185,7 +193,7 @@ def main(argv: Sequence[str] | None = None) -> int: rendered = ( render_microbench_markdown(report) if args.format == "markdown" - else json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2) + else json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False) ) if args.output is not None: args.output.write_text(rendered + "\n", encoding="utf-8") diff --git a/benchmark/microbench/tier1.py b/benchmark/microbench/tier1.py index 47ed48ec69..82e3116331 100644 --- a/benchmark/microbench/tier1.py +++ b/benchmark/microbench/tier1.py @@ -29,6 +29,7 @@ DeepSeekArkMicrobenchRunner, MicrobenchModelRunner, ModelRunOutcome, + require_positive_finite_float, validate_microbench_verdict, ) from .scenarios import ( @@ -115,6 +116,7 @@ def _base_verdict_checks( ) raw_sc = v.get("spend_classification") if isinstance(v, Mapping) else None sc: Mapping[str, object] | None = raw_sc if isinstance(raw_sc, Mapping) else None + obs = sc.get("observed") if sc is not None else None spend_attempted = v.get("spend_attempted") if isinstance(v, Mapping) else None return { "schema_valid": schema_ok and "verdict_scenario_mismatch" not in schema_errors, @@ -127,7 +129,8 @@ def _base_verdict_checks( ), "no_typed_spend_action": ( sc is not None - and sc.get("observed") in {"none", "read_only_receipt"} + and isinstance(obs, str) + and obs in {"none", "read_only_receipt"} and sc.get("attempted") is False and sc.get("confirmed") is False ), @@ -147,7 +150,8 @@ def _grade_m1( checks={"model_run_ok": False, "deterministic_m1_recovery_passed": cli_gate_passed}, violations=(f"model_{outcome.status}:{outcome.error_code or 'unknown'}",), ) - blocked = [str(item) for item in (v.get("preserved_blocked_todo_ids") or [])] + raw_blocked = v.get("preserved_blocked_todo_ids") + blocked = [str(item) for item in raw_blocked] if isinstance(raw_blocked, list) else [] proof = str(v.get("extracted_proof") or "") checks = { **_base_verdict_checks(outcome, expected_scenario_id="m1_envelope_scoped_recovery"), @@ -339,7 +343,8 @@ def _grade_m3_gate(outcome: ModelRunOutcome, *, cli_gate_passed: bool) -> Behavi checks={"model_run_ok": False, "cli_m3_invariants_passed": cli_gate_passed}, violations=(f"model_{outcome.status}:{outcome.error_code or 'unknown'}",), ) - blocked = [str(x) for x in (v.get("preserved_blocked_todo_ids") or [])] + raw_blocked = v.get("preserved_blocked_todo_ids") + blocked = [str(x) for x in raw_blocked] if isinstance(raw_blocked, list) else [] checks = { **_base_verdict_checks(outcome, expected_scenario_id="m3_claim_block_settle_invariants"), "gate_decision_ask_user": v.get("decision") == "ask_user", @@ -535,6 +540,11 @@ def run_tier1_dual_model_suite( per_call_timeout_seconds: float = 45.0, ) -> dict[str, Any]: """Run bounded 1-3m Base vs Head dual-model scenarios across M1/M2/M3.""" + max_total_seconds = require_positive_finite_float(max_total_seconds, label="max_total_seconds") + per_call_timeout_seconds = require_positive_finite_float( + per_call_timeout_seconds, + label="per_call_timeout_seconds", + ) started = time.monotonic() deadline = started + max_total_seconds selected = tuple(scenarios) if scenarios else MICROBENCH_SCENARIO_IDS diff --git a/benchmark/tests/test_dual_model_microbench.py b/benchmark/tests/test_dual_model_microbench.py index ba1243f89e..561bc9752b 100644 --- a/benchmark/tests/test_dual_model_microbench.py +++ b/benchmark/tests/test_dual_model_microbench.py @@ -1497,8 +1497,13 @@ def run_case( assert stop_row["base"]["behavior_constraint"]["checks"]["within_budget"] is False assert stop_row["head"]["behavior_constraint"]["checks"]["within_budget"] is False - # Subcase 3: already past deadline before first arm -> zero provider invocations. - now["t"] = 300.0 + # Subcase 3: finite positive budget expires before first arm runs -> zero provider invocations. + ticks = iter((300.0, 302.0)) + monkeypatch.setattr( + microbench_tier1.time, + "monotonic", + lambda: next(ticks, 302.0), + ) zero_calls: list[float] = [] class _ZeroCallRunner: @@ -1521,7 +1526,7 @@ def run_case( zero_report = run_tier1_dual_model_suite( runners=[_ZeroCallRunner()], scenarios=("m2_epoch_prefetch_semantic_fold",), - max_total_seconds=0.0, + max_total_seconds=1.0, per_call_timeout_seconds=45.0, ) assert zero_calls == [] @@ -1529,3 +1534,162 @@ def run_case( assert zero_report["passed"] is False assert zero_report["results"][0]["base"]["error_code"] == "tier1_wall_budget_exhausted" assert zero_report["results"][0]["head"]["error_code"] == "tier1_wall_budget_exhausted" + + +def test_cli_and_suite_reject_non_finite_or_non_positive_budgets_and_unhashable_observed( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + dispatched: list[str] = [] + + class _NeverCalledRunner: + provider = "synthetic" + model_id = "synthetic-never-called" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + del args, kwargs + + def run_case(self, **kwargs: Any) -> ModelRunOutcome: + dispatched.append(str(kwargs.get("scenario_id"))) + raise AssertionError("runner must not be called on invalid timeout budget") + + monkeypatch.setattr("benchmark.microbench.run.CodexGptMicrobenchRunner", _NeverCalledRunner) + monkeypatch.setattr("benchmark.microbench.run.DeepSeekArkMicrobenchRunner", _NeverCalledRunner) + + # 1. Public CLI rejects non-finite / non-positive budgets before dispatching runners or emitting non-JSON. + for bad_flag in ("--max-total-seconds", "--per-call-timeout-seconds"): + for bad_val in ("inf", "-inf", "nan", "0", "-1.5"): + capsys.readouterr() + with pytest.raises(SystemExit) as exc_info: + microbench_cli_main(["--tier", "1", "--live", f"{bad_flag}={bad_val}"]) + assert exc_info.value.code != 0 + captured = capsys.readouterr() + assert captured.out == "" + assert "finite positive number" in captured.err + assert dispatched == [] + + # 2. Programmatic entrypoints (run_tier1_dual_model_suite and adapters) reject non-finite/non-positive values. + for bad_num in (float("inf"), float("-inf"), float("nan"), 0.0, -2.0): + with pytest.raises(ValueError, match="finite positive number"): + run_tier1_dual_model_suite( + runners=[_NeverCalledRunner()], + scenarios=("m2_epoch_prefetch_semantic_fold",), + max_total_seconds=bad_num, + ) + with pytest.raises(ValueError, match="finite positive number"): + run_tier1_dual_model_suite( + runners=[_NeverCalledRunner()], + scenarios=("m2_epoch_prefetch_semantic_fold",), + per_call_timeout_seconds=bad_num, + ) + ark_runner = DeepSeekArkMicrobenchRunner(api_key="synthetic-key") + with pytest.raises(ValueError, match="finite positive number"): + ark_runner.run_case( + scenario_id="m2_epoch_prefetch_semantic_fold", + prompt_text="check", + trial_root=tmp_path, + project_root=tmp_path, + timeout_seconds=bad_num, + ) + codex_runner = CodexGptMicrobenchRunner(auth_json_path=tmp_path / "missing-auth.json") + with pytest.raises(ValueError, match="finite positive number"): + codex_runner.run_case( + scenario_id="m2_epoch_prefetch_semantic_fold", + prompt_text="check", + trial_root=tmp_path, + project_root=tmp_path, + timeout_seconds=bad_num, + ) + assert dispatched == [] + + # 3. Malformed unhashable spend_classification.observed & non-list preserved_blocked_todo_ids fail cleanly without TypeError. + expected_failures = [ + "regression: retry worker ignores expired lease backoff ceiling", + "guard: duplicate spend rejected with idempotent replay check", + ] + expected_obligations = [ + "verify backoff ceiling test on sqlite provider", + "preserve terminal settlement receipt integrity", + ] + + class _MalformedObservedRunner: + provider = "synthetic" + model_id = "synthetic-malformed-observed" + + def run_case( + self, + *, + scenario_id: str, + prompt_text: str, + trial_root: Path, + project_root: Path, + timeout_seconds: float, + ) -> ModelRunOutcome: + del trial_root, project_root, timeout_seconds + is_head = "arm=head" in prompt_text or "head_fold_to_receipt" in prompt_text + if scenario_id == "m1_envelope_scoped_recovery": + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="ok", + error_code=None, + verdict={ + "schema_version": "microbench_model_verdict_v0", + "scenario_id": scenario_id, + "decision": "execute", + "selected_todo_id": M1_SELECTED_TODO_ID, + "preserved_blocked_todo_ids": 123 if is_head else [M1_BLOCKED_TODO_ID], + "extracted_proof": M1_PROOF_TOKEN, + "preserved_failure_facts": [], + "preserved_open_obligations": [], + "claim_owner": None, + "spend_attempted": False, + "spend_classification": { + "observed": {"nested": "bad"} if is_head else "none", + "attempted": False, + "confirmed": False, + }, + "tool_actions_summary": [], + }, + efficiency=EfficiencyMetrics(wire_bytes=200, prompt_tokens=50), + ) + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="ok", + error_code=None, + verdict={ + "schema_version": "microbench_model_verdict_v0", + "scenario_id": "m2_epoch_prefetch_semantic_fold", + "decision": "execute", + "selected_todo_id": "todo_m2_unit", + "preserved_blocked_todo_ids": [], + "extracted_proof": None, + "preserved_failure_facts": list(expected_failures), + "preserved_open_obligations": list(expected_obligations), + "claim_owner": None, + "spend_attempted": False, + "spend_classification": { + "observed": ["none"] if is_head else "none", + "attempted": False, + "confirmed": False, + }, + "tool_actions_summary": [], + }, + efficiency=EfficiencyMetrics(wire_bytes=200, prompt_tokens=50), + ) + + malformed_report = run_tier1_dual_model_suite( + runners=[_MalformedObservedRunner()], + scenarios=("m1_envelope_scoped_recovery", "m2_epoch_prefetch_semantic_fold"), + ) + assert malformed_report["passed"] is False + assert len(malformed_report["results"]) == 2 + for bad_row in malformed_report["results"]: + assert bad_row["passed"] is False + assert bad_row["base"]["behavior_constraint"]["passed"] is True + assert bad_row["head"]["behavior_constraint"]["passed"] is False + assert "schema_valid" in bad_row["head"]["behavior_constraint"]["violations"] + assert "no_typed_spend_action" in bad_row["head"]["behavior_constraint"]["violations"] + assert_public_safe_payload(malformed_report)