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..e941cfd70a --- /dev/null +++ b/benchmark/microbench/README.md @@ -0,0 +1,59 @@ +# 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, and Tier-1 **Peak Context Window Occupancy** (`initial_turn_context_tokens`, `per_turn_context_tokens`, `peak_context_tokens`, `effective_context_window`, `min_headroom_tokens`, `peak_window_ratio`, `compaction_events`, `truncation_events`, `occupancy_measurement_kind`). Use `--context-delivery {auto,off,on}` to run `off` vs `on` contrast (`auto`) or pin both arms to one setting (`off`/`on`) for same-config version diffs or A/A baselines. + - **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, optionally pinning `--context-delivery on` and saving sanitized JSON via `--output-json`): + +```bash +uv run --extra test python -m benchmark.microbench.run \ + --tier 0 \ + --base-ref \ + --context-delivery on \ + --format markdown \ + --output-json .local/microbench-runs/tier0.json +``` + +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`; 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, 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/__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..bc1537b1b8 --- /dev/null +++ b/benchmark/microbench/metrics.py @@ -0,0 +1,784 @@ +"""Shared telemetry, rollout metric extraction, and Base/Head comparison.""" + +from __future__ import annotations + +from collections.abc import Iterable, Iterator, Mapping, Sequence +from contextlib import contextmanager +import contextvars +from dataclasses import asdict, dataclass, field +import json +import math +from pathlib import Path +import re +import time + +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\"',;]+") +_CODEX_COUNTER_KEYS = ("input_tokens", "cached_input_tokens", "output_tokens") +_TRUNCATION_EVENT_TYPES = frozenset( + {"truncated", "context_truncated", "history_truncated", "prompt_truncated"} +) +_ACTIVE_DEADLINE_MONOTONIC: contextvars.ContextVar[float | None] = contextvars.ContextVar( + "microbench_active_deadline_monotonic", + default=None, +) + + +class MicrobenchDeadlineExpired(TimeoutError): + """Raised when a bounded microbenchmark phase exceeds its monotonic deadline.""" + + def __init__(self, stage: str) -> None: + self.stage = stage + super().__init__(f"tier1_wall_budget_exhausted:{stage}") + + +@contextmanager +def microbench_deadline_scope(deadline_monotonic: float | None) -> Iterator[None]: + """Bind an active monotonic wall deadline across nested scenario/CLI helpers.""" + token = _ACTIVE_DEADLINE_MONOTONIC.set(deadline_monotonic) + try: + yield + finally: + _ACTIVE_DEADLINE_MONOTONIC.reset(token) + + +def resolve_deadline(deadline_monotonic: float | None) -> float | None: + """Return the tighter of an explicit deadline and any active context deadline.""" + active = _ACTIVE_DEADLINE_MONOTONIC.get() + if deadline_monotonic is None: + return active + if active is None: + return deadline_monotonic + return min(deadline_monotonic, active) + + +def require_remaining_budget(deadline_monotonic: float, *, stage: str) -> float: + """Return positive seconds remaining before ``deadline_monotonic`` or fail closed.""" + remaining = float(deadline_monotonic) - time.monotonic() + if remaining <= 0.0: + raise MicrobenchDeadlineExpired(stage) + return remaining + + +@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, context-window occupancy, byte, turn, and latency metrics.""" + + 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 + initial_turn_context_tokens: int | None = None + per_turn_context_tokens: tuple[int, ...] | None = None + peak_context_tokens: int | None = None + effective_context_window: int | None = None + min_headroom_tokens: int | None = None + peak_window_ratio: float | None = None + compaction_events: int | None = None + truncation_events: int | None = None + occupancy_measurement_kind: str = "unknown" + occupancy_window_source: str | None = None + + def to_dict(self) -> dict[str, object]: + payload = asdict(self) + per_turn = payload.get("per_turn_context_tokens") + if isinstance(per_turn, tuple): + payload["per_turn_context_tokens"] = list(per_turn) + return payload + + +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 _valid_counter_map(raw: object) -> dict[str, int] | None: + if not isinstance(raw, Mapping): + return None + parsed: dict[str, int] = {} + for key in _CODEX_COUNTER_KEYS: + val = raw.get(key) + if not isinstance(val, int) or isinstance(val, bool) or val < 0: + return None + parsed[key] = val + return parsed + + +def compute_occupancy_summary( + *, + per_turn_context_tokens: Sequence[int] | None, + effective_context_window: int | None = None, + occupancy_measurement_kind: str | None = None, + occupancy_window_source: str | None = None, + compaction_events: int | None = None, + truncation_events: int | None = None, +) -> dict[str, object]: + """Compute typed initial/peak context-window occupancy and headroom summary.""" + valid_window = ( + effective_context_window + if isinstance(effective_context_window, int) + and not isinstance(effective_context_window, bool) + and effective_context_window > 0 + else None + ) + resolved_window_source = occupancy_window_source if valid_window is not None else None + per_turn_tuple: tuple[int, ...] | None = None + if per_turn_context_tokens: + cleaned: list[int] = [] + valid_seq = True + for val in per_turn_context_tokens: + if not isinstance(val, int) or isinstance(val, bool) or val < 0: + valid_seq = False + break + cleaned.append(val) + if valid_seq and cleaned: + per_turn_tuple = tuple(cleaned) + + if per_turn_tuple is None: + return { + "initial_turn_context_tokens": None, + "per_turn_context_tokens": None, + "peak_context_tokens": None, + "effective_context_window": valid_window, + "min_headroom_tokens": None, + "peak_window_ratio": None, + "compaction_events": compaction_events, + "truncation_events": truncation_events, + "occupancy_measurement_kind": "unknown", + "occupancy_window_source": resolved_window_source, + } + + initial_ctx = per_turn_tuple[0] + peak_ctx = max(per_turn_tuple) + min_headroom = (valid_window - peak_ctx) if valid_window is not None else None + peak_ratio = round(peak_ctx / valid_window, 6) if valid_window is not None else None + return { + "initial_turn_context_tokens": initial_ctx, + "per_turn_context_tokens": per_turn_tuple, + "peak_context_tokens": peak_ctx, + "effective_context_window": valid_window, + "min_headroom_tokens": min_headroom, + "peak_window_ratio": peak_ratio, + "compaction_events": compaction_events, + "truncation_events": truncation_events, + "occupancy_measurement_kind": occupancy_measurement_kind or "per_request_input_proxy", + "occupancy_window_source": resolved_window_source, + } + + +def _build_codex_telemetry_coverage( + *, + total_rollouts: int, + verified_request_rollouts: int, + verified_requests: int | None, + complete_record_count: int | None, + round_trips_reason: str | None = None, +) -> dict[str, object]: + if ( + total_rollouts > 0 + and verified_request_rollouts == total_rollouts + and verified_requests is not None + and verified_requests > 0 + ): + round_trips_cov: dict[str, object] = { + "status": "complete", + "reported_rollouts": verified_request_rollouts, + "total_rollouts": total_rollouts, + "verified_requests": verified_requests, + } + partial_metrics: list[str] = [] + missing_metrics: list[str] = [] + elif 0 < verified_request_rollouts < total_rollouts: + round_trips_cov = { + "status": "partial", + "reported_rollouts": verified_request_rollouts, + "total_rollouts": total_rollouts, + **({"reason": round_trips_reason} if round_trips_reason else {}), + } + partial_metrics = ["round_trips"] + missing_metrics = [] + else: + round_trips_cov = { + "status": "missing", + "reported_rollouts": 0, + "total_rollouts": total_rollouts, + **({"reason": round_trips_reason} if round_trips_reason else {}), + } + partial_metrics = [] + missing_metrics = ["round_trips"] + + diagnostics: dict[str, object] = { + "complete_record_count": complete_record_count, + "complete_record_count_scope": "bounded_tail", + "rollout_count": total_rollouts, + } + if round_trips_reason: + diagnostics["round_trips_reason"] = round_trips_reason + + return { + "schema_version": "microbench_telemetry_coverage_v0", + "total_rollouts": total_rollouts, + "has_partial_coverage": bool(partial_metrics), + "partial_metrics": partial_metrics, + "missing_metrics": missing_metrics, + "metrics": {"round_trips": round_trips_cov}, + "diagnostics": diagnostics, + } + + +def _parse_codex_rollout_occupancy(rollout: Path) -> dict[str, object]: + """Validate per-request ``last_token_usage`` against ``total_token_usage`` deltas.""" + per_turn_inputs: list[int] = [] + windows: set[int] = set() + compaction_events = 0 + truncation_events = 0 + previous = {key: 0 for key in _CODEX_COUNTER_KEYS} + samples = 0 + per_request_valid = True + token_count_events = 0 + occupancy_error: str | None = None + + with rollout.open("r", encoding="utf-8", errors="replace") as stream: + for raw_line in stream: + stripped = raw_line.strip() + if not stripped: + continue + try: + item = json.loads(stripped) + except json.JSONDecodeError: + per_request_valid = False + occupancy_error = occupancy_error or "invalid_rollout_json" + continue + if not isinstance(item, Mapping): + per_request_valid = False + occupancy_error = occupancy_error or "non_object_rollout_record" + continue + kind = str(item.get("type") or "") + raw_payload = item.get("payload") + payload = raw_payload if isinstance(raw_payload, Mapping) else {} + ptype = str(payload.get("type") or "") + if kind == "compacted" or (kind == "event_msg" and ptype == "compacted"): + compaction_events += 1 + continue + if ( + kind in _TRUNCATION_EVENT_TYPES + or (kind == "event_msg" and ptype in _TRUNCATION_EVENT_TYPES) + or payload.get("truncated") is True + ): + truncation_events += 1 + if kind != "event_msg" or ptype != "token_count": + continue + token_count_events += 1 + raw_info = payload.get("info") + info = raw_info if isinstance(raw_info, Mapping) else {} + win = info.get("model_context_window") + if isinstance(win, int) and not isinstance(win, bool) and win > 0: + windows.add(win) + total = _valid_counter_map(info.get("total_token_usage")) + last = _valid_counter_map(info.get("last_token_usage")) + if total is None or last is None: + per_request_valid = False + occupancy_error = occupancy_error or "missing_last_token_usage" + continue + delta = {key: total[key] - previous[key] for key in _CODEX_COUNTER_KEYS} + if samples == 0 and any(total[key] != last[key] for key in _CODEX_COUNTER_KEYS): + per_request_valid = False + occupancy_error = occupancy_error or "missing_initial_usage_prefix" + continue + if any(delta[key] < 0 for key in _CODEX_COUNTER_KEYS): + per_request_valid = False + occupancy_error = occupancy_error or "counter_reset" + continue + if any(delta[key] != 0 for key in _CODEX_COUNTER_KEYS): + if any(delta[key] != last[key] for key in _CODEX_COUNTER_KEYS): + per_request_valid = False + occupancy_error = occupancy_error or "counter_gap" + continue + per_turn_inputs.append(last["input_tokens"]) + previous = total + samples += 1 + + verified_all = per_request_valid and token_count_events > 0 and bool(per_turn_inputs) + if token_count_events == 0: + occupancy_error = occupancy_error or "missing_token_count_events" + elif per_request_valid and not per_turn_inputs: + occupancy_error = occupancy_error or "no_nonempty_token_count_delta" + + return { + "per_turn_inputs": per_turn_inputs if verified_all else [], + "verified_request_count": len(per_turn_inputs) if verified_all else None, + "windows": windows, + "compaction_events": compaction_events, + "truncation_events": truncation_events, + "per_request_valid": verified_all, + "occupancy_error": occupancy_error if not verified_all else None, + } + + +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, + "round_trips": None, + "rollout_count": None, + "complete_record_count": None, + "telemetry_coverage": _build_codex_telemetry_coverage( + total_rollouts=0, + verified_request_rollouts=0, + verified_requests=None, + complete_record_count=None, + round_trips_reason="harbor_trajectory_totals", + ), + "error": None, + **compute_occupancy_summary(per_turn_context_tokens=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, + "round_trips": None, + "rollout_count": 0, + "complete_record_count": 0, + "telemetry_coverage": _build_codex_telemetry_coverage( + total_rollouts=0, + verified_request_rollouts=0, + verified_requests=None, + complete_record_count=0, + round_trips_reason="missing_rollout", + ), + "error": "missing_rollout", + **compute_occupancy_summary(per_turn_context_tokens=None), + } + + prompt_total = 0 + completion_total = 0 + cached_total = 0 + reasoning_total: int | None = 0 + grand_total: int | None = 0 + complete_records = 0 + all_per_turn_inputs: list[int] = [] + all_windows: set[int] = set() + total_compactions = 0 + total_truncations = 0 + occupancy_valid = True + occupancy_error: str | None = None + verified_request_rollouts = 0 + + for rollout in rollouts: + try: + usage = read_codex_session_usage(rollout) + tail = observe_codex_session_tail(rollout) + occ = _parse_codex_rollout_occupancy(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, + "round_trips": None, + "rollout_count": len(rollouts), + "complete_record_count": None, + "telemetry_coverage": _build_codex_telemetry_coverage( + total_rollouts=len(rollouts), + verified_request_rollouts=0, + verified_requests=None, + complete_record_count=None, + round_trips_reason=type(exc).__name__, + ), + "error": type(exc).__name__, + **compute_occupancy_summary(per_turn_context_tokens=None), + } + 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, + "round_trips": None, + "rollout_count": len(rollouts), + "complete_record_count": None, + "telemetry_coverage": _build_codex_telemetry_coverage( + total_rollouts=len(rollouts), + verified_request_rollouts=0, + verified_requests=None, + complete_record_count=None, + round_trips_reason="incomplete_usage_fields", + ), + "error": "incomplete_usage_fields", + **compute_occupancy_summary(per_turn_context_tokens=None), + } + 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 + raw_comp = occ.get("compaction_events") + raw_trunc = occ.get("truncation_events") + if isinstance(raw_comp, int): + total_compactions += raw_comp + if isinstance(raw_trunc, int): + total_truncations += raw_trunc + raw_wins = occ.get("windows") + if isinstance(raw_wins, set): + all_windows.update(w for w in raw_wins if isinstance(w, int)) + raw_inputs = occ.get("per_turn_inputs") + if occ.get("per_request_valid") and isinstance(raw_inputs, list) and raw_inputs: + verified_request_rollouts += 1 + all_per_turn_inputs.extend(int(x) for x in raw_inputs) + else: + occupancy_valid = False + if occupancy_error is None: + raw_err = occ.get("occupancy_error") + occupancy_error = str(raw_err) if raw_err else "invalid_per_request_usage" + + single_window = next(iter(all_windows)) if len(all_windows) == 1 else None + all_requests_verified = ( + occupancy_valid + and verified_request_rollouts == len(rollouts) + and bool(all_per_turn_inputs) + ) + verified_round_trips = len(all_per_turn_inputs) if all_requests_verified else None + occ_summary = compute_occupancy_summary( + per_turn_context_tokens=all_per_turn_inputs if all_requests_verified else None, + effective_context_window=single_window, + occupancy_measurement_kind="per_request_input_proxy", + occupancy_window_source="codex_model_context_window" if single_window is not None else None, + compaction_events=total_compactions, + truncation_events=total_truncations, + ) + coverage = _build_codex_telemetry_coverage( + total_rollouts=len(rollouts), + verified_request_rollouts=verified_request_rollouts, + verified_requests=verified_round_trips, + complete_record_count=complete_records, + round_trips_reason=None if all_requests_verified else (occupancy_error or "invalid_per_request_usage"), + ) + 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, + "round_trips": verified_round_trips, + "rollout_count": len(rollouts), + "complete_record_count": complete_records, + "telemetry_coverage": coverage, + "error": None, + **({"occupancy_error": occupancy_error} if occupancy_error and not occupancy_valid else {}), + **occ_summary, + } + + +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 + 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, + 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) + if "prompt_tokens" in excluded_set: + excluded_set.update( + { + "initial_turn_context_tokens", + "peak_context_tokens", + "min_headroom_tokens", + "peak_window_ratio", + } + ) + 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", + "initial_turn_context_tokens", + "peak_context_tokens", + "effective_context_window", + "min_headroom_tokens", + "peak_window_ratio", + "compaction_events", + "truncation_events", + ): + 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: + pct_changes[field_name] = round((float(delta) / float(base_val)) * 100.0, 2) + else: + pct_changes[field_name] = None + + baseline_valid = bool(base_behavior.passed) + behavior_preserved = bool( + baseline_valid + and head_behavior.passed + and head_behavior.pass_rate >= base_behavior.pass_rate + ) + return { + "behavior_preserved": behavior_preserved, + "baseline_valid": baseline_valid, + "base_passed": base_behavior.passed, + "head_passed": head_behavior.passed, + "base_pass_rate": base_behavior.pass_rate, + "head_pass_rate": head_behavior.pass_rate, + "base_violations": list(base_behavior.violations), + "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): + 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..a90968e215 --- /dev/null +++ b/benchmark/microbench/models.py @@ -0,0 +1,1104 @@ +"""Dual-model execution adapters reusing LoopX Codex + Ark runtime clients.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +import json +import math +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, + compute_occupancy_summary, + resolve_deadline, +) + +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", + "spend_classification", + "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"}, + "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"}, + }, + }, +} + +_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 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, + *, + 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") + + 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) + + +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: + """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" + telemetry_coverage: dict[str, Any] | None = None + + +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 = _summarize_loopx_command(tokens) + 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] + try: + 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), + ) + except subprocess.TimeoutExpired: + return "tool_timeout", json.dumps({"ok": False, "error": "tool_timeout"}) + out = completed.stdout if completed.returncode == 0 else completed.stderr + 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 + 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 _build_ark_outcome( + self, + *, + status: str, + error_code: str | None, + verdict: dict[str, Any] | None, + wire_bytes: int, + usage_totals: Mapping[str, int], + usage_reported_steps: Mapping[str, int], + round_trips: int, + per_round_prompt_tokens: Sequence[int | None], + compaction_events: int, + truncation_events: int, + observed_commands: Sequence[str], + started: float, + ) -> ModelRunOutcome: + resolved_usage, coverage = _aggregate_ark_usage_coverage( + usage_totals, usage_reported_steps, round_trips + ) + all_rounds_have_prompt = ( + round_trips > 0 + and len(per_round_prompt_tokens) == round_trips + and all(isinstance(val, int) and not isinstance(val, bool) for val in per_round_prompt_tokens) + ) + occ_summary = compute_occupancy_summary( + per_turn_context_tokens=( + [int(val) for val in per_round_prompt_tokens if isinstance(val, int)] + if all_rounds_have_prompt + else None + ), + effective_context_window=None, + occupancy_measurement_kind="per_request_input_proxy", + occupancy_window_source=None, + compaction_events=compaction_events, + truncation_events=truncation_events, + ) + raw_per_turn = occ_summary.get("per_turn_context_tokens") + per_turn_tuple = ( + tuple(int(v) for v in raw_per_turn if isinstance(v, int) and not isinstance(v, bool)) + if isinstance(raw_per_turn, (list, tuple)) and raw_per_turn + else None + ) + raw_ratio = occ_summary.get("peak_window_ratio") + peak_ratio = ( + float(raw_ratio) + if isinstance(raw_ratio, (int, float)) and not isinstance(raw_ratio, bool) + else None + ) + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status=status, + error_code=error_code, + verdict=verdict, + efficiency=EfficiencyMetrics( + wire_bytes=wire_bytes, + 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), + initial_turn_context_tokens=_opt_int(occ_summary, "initial_turn_context_tokens"), + per_turn_context_tokens=per_turn_tuple, + peak_context_tokens=_opt_int(occ_summary, "peak_context_tokens"), + effective_context_window=_opt_int(occ_summary, "effective_context_window"), + min_headroom_tokens=_opt_int(occ_summary, "min_headroom_tokens"), + peak_window_ratio=peak_ratio, + compaction_events=_opt_int(occ_summary, "compaction_events"), + truncation_events=_opt_int(occ_summary, "truncation_events"), + occupancy_measurement_kind=str(occ_summary["occupancy_measurement_kind"]), + occupancy_window_source=( + str(occ_summary["occupancy_window_source"]) + if occ_summary.get("occupancy_window_source") is not None + else None + ), + ), + observed_commands=tuple(observed_commands), + telemetry_source="ark_usage", + telemetry_coverage=coverage, + ) + + def run_case( + self, + *, + scenario_id: str, + prompt_text: str, + trial_root: Path, + project_root: Path, + timeout_seconds: float = 45.0, + ) -> ModelRunOutcome: + timeout_seconds = require_positive_finite_float(timeout_seconds, label="timeout_seconds") + started = time.monotonic() + deadline = started + timeout_seconds + wire_bytes = len(prompt_text.encode("utf-8")) + 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( + wire_bytes=wire_bytes, + wall_seconds=round(time.monotonic() - started, 3), + ), + telemetry_source="ark_usage", + ) + + usage_totals = {metric: 0 for metric in _ARK_USAGE_METRICS} + usage_reported_steps = {metric: 0 for metric in _ARK_USAGE_METRICS} + round_trips = 0 + per_round_prompt_tokens: list[int | None] = [] + compaction_events = 0 + truncation_events = 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 _require_arm_remaining() -> float: + rem = deadline - time.monotonic() + if rem <= 0.0: + raise DoubaoActorTransportError( + "Ark arm monotonic deadline exhausted", + error_code="ark_budget_exhausted", + ) + return rem + + def tracked_transport( + *, + endpoint: str, + headers: Mapping[str, str], + body: bytes, + timeout_seconds: float, + ) -> Mapping[str, Any]: + nonlocal round_trips, truncation_events + remaining = _require_arm_remaining() + round_trips += 1 + response = self._transport( + endpoint=endpoint, + headers=headers, + body=body, + timeout_seconds=min(float(timeout_seconds), remaining, 120.0), + ) + usage = response.get("usage") + round_prompt: int | None = None + if isinstance(usage, Mapping): + raw_prompt = usage.get("prompt_tokens") + if isinstance(raw_prompt, int) and not isinstance(raw_prompt, bool) and raw_prompt >= 0: + round_prompt = raw_prompt + 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): + _record_usage_metric("cached_tokens", pt_details.get("cached_tokens")) + ct_details = usage.get("completion_tokens_details") + if isinstance(ct_details, Mapping): + _record_usage_metric("reasoning_tokens", ct_details.get("reasoning_tokens")) + per_round_prompt_tokens.append(round_prompt) + choices = response.get("choices") + finish_reason = ( + choices[0].get("finish_reason") + if isinstance(choices, list) and len(choices) == 1 and isinstance(choices[0], Mapping) + else None + ) + if response.get("truncated") is True or finish_reason == "context_length_exceeded": + truncation_events += 1 + 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. 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}" + ) + 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): + _require_arm_remaining() + 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 + rem_for_tool = _require_arm_remaining() + label, tool_output = _execute_scoped_command( + step.tool_call.command, + trial_root=trial_root, + project_root=project_root, + source_root=self._source_root, + timeout_seconds=rem_for_tool, + ) + observed_commands.append(label) + append_exec_tool_exchange(messages, step.tool_call, tool_output) + + if final_content is None: + _require_arm_remaining() + final_content = client.next_final_content( + [ + *messages, + { + "role": "user", + "content": "Return the final microbench_model_verdict_v0 JSON now without more tool calls.", + }, + ] + ) + _require_arm_remaining() + except DoubaoActorTransportError as exc: + status = "quota_exhausted" if exc.error_code == "provider_authentication_failed" else "error" + return self._build_ark_outcome( + status=status, + error_code=exc.error_code, + verdict=None, + wire_bytes=wire_bytes, + usage_totals=usage_totals, + usage_reported_steps=usage_reported_steps, + round_trips=round_trips, + per_round_prompt_tokens=per_round_prompt_tokens, + compaction_events=compaction_events, + truncation_events=truncation_events, + observed_commands=observed_commands, + started=started, + ) + + parsed_verdict = _extract_verdict(final_content) + verdict, status, error_code = _validate_adapter_verdict( + parsed_verdict, + expected_scenario_id=scenario_id, + ) + return self._build_ark_outcome( + status=status, + error_code=error_code, + verdict=verdict, + wire_bytes=wire_bytes, + usage_totals=usage_totals, + usage_reported_steps=usage_reported_steps, + round_trips=round_trips, + per_round_prompt_tokens=per_round_prompt_tokens, + compaction_events=compaction_events, + truncation_events=truncation_events, + observed_commands=observed_commands, + started=started, + ) + + +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 _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] = [] + 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 + 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(): + 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 + + +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: + timeout_seconds = require_positive_finite_float(timeout_seconds, label="timeout_seconds") + started = time.monotonic() + deadline = resolve_deadline(started + timeout_seconds) or (started + timeout_seconds) + wire_bytes = len(prompt_text.encode("utf-8")) + + def _budget_exhausted_outcome() -> ModelRunOutcome: + return ModelRunOutcome( + model_id=self.model_id, + provider=self.provider, + status="error", + error_code="codex_budget_exhausted", + verdict=None, + efficiency=EfficiencyMetrics( + wire_bytes=wire_bytes, + wall_seconds=round(time.monotonic() - started, 3), + ), + telemetry_source="codex_session_usage", + ) + + 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", + ) + + if deadline - time.monotonic() <= 0.0: + return _budget_exhausted_outcome() + + 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", + "-", + ] + remaining_before_exec = deadline - time.monotonic() + if remaining_before_exec <= 0.0: + return _budget_exhausted_outcome() + + 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=remaining_before_exec, + ) + 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 stdout_text.splitlines(): + if line.strip() and not failure_obs.observe_stdout(line): + complete_stream = False + 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(stdout_text) + wall = round(time.monotonic() - started, 3) + + parsed_verdict: dict[str, Any] | None = None + 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 returncode != 0 and not timed_out + else None + ) + status = "ok" + error_code: str | None = None + verdict: dict[str, Any] | None = None + 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: + verdict, status, error_code = _validate_adapter_verdict( + parsed_verdict, + expected_scenario_id=scenario_id, + ) + + verified_round_trips = _opt_int(rollout_metrics, "round_trips") + raw_per_turn = rollout_metrics.get("per_turn_context_tokens") + per_turn_tuple = ( + tuple(int(v) for v in raw_per_turn if isinstance(v, int) and not isinstance(v, bool)) + if isinstance(raw_per_turn, (list, tuple)) and raw_per_turn + else None + ) + raw_ratio = rollout_metrics.get("peak_window_ratio") + peak_ratio = ( + float(raw_ratio) + if isinstance(raw_ratio, (int, float)) and not isinstance(raw_ratio, bool) + else None + ) + raw_win_src = rollout_metrics.get("occupancy_window_source") + raw_coverage = rollout_metrics.get("telemetry_coverage") + codex_coverage: dict[str, Any] | None = ( + dict(raw_coverage) if isinstance(raw_coverage, Mapping) else None + ) + 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=( + verified_round_trips + if verified_round_trips is not None and verified_round_trips > 0 + else None + ), + wall_seconds=wall, + initial_turn_context_tokens=_opt_int(rollout_metrics, "initial_turn_context_tokens"), + per_turn_context_tokens=per_turn_tuple, + peak_context_tokens=_opt_int(rollout_metrics, "peak_context_tokens"), + effective_context_window=_opt_int(rollout_metrics, "effective_context_window"), + min_headroom_tokens=_opt_int(rollout_metrics, "min_headroom_tokens"), + peak_window_ratio=peak_ratio, + compaction_events=_opt_int(rollout_metrics, "compaction_events"), + truncation_events=_opt_int(rollout_metrics, "truncation_events"), + occupancy_measurement_kind=str(rollout_metrics.get("occupancy_measurement_kind") or "unknown"), + occupancy_window_source=str(raw_win_src) if raw_win_src is not None else None, + ) + 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"), + telemetry_coverage=codex_coverage, + ) diff --git a/benchmark/microbench/run.py b/benchmark/microbench/run.py new file mode 100644 index 0000000000..cd6a5810ea --- /dev/null +++ b/benchmark/microbench/run.py @@ -0,0 +1,231 @@ +"""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, + require_positive_finite_float, +) +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 | 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']}` | `{scope_lbl}` | `{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 | Scope | Base Pass | Head Pass | Base Peak Ctx | Head Peak Ctx | Peak Ctx Delta | Window / Ratio / Kind | 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") + base_eff = row["base"].get("efficiency", {}) + head_eff = row["head"].get("efficiency", {}) + base_peak = base_eff.get("peak_context_tokens") + head_peak = head_eff.get("peak_context_tokens") + win = head_eff.get("effective_context_window") or base_eff.get("effective_context_window") + ratio = head_eff.get("peak_window_ratio") + kind = str(head_eff.get("occupancy_measurement_kind") or base_eff.get("occupancy_measurement_kind") or "unknown") + win_str = f"{win or 'n/a'} / {ratio if ratio is not None else 'n/a'} / {kind}" + lines.append( + 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"`{base_peak}` | `{head_peak}` | `{d.get('peak_context_tokens')}` | `{win_str}` | " + 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 _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)." + ) + 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( + "--context-delivery", + choices=("auto", "off", "on"), + default="auto", + help="M1 context-delivery mode: auto = Base off vs Head on; off/on = pin both arms to same setting.", + ) + 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) + parser.add_argument( + "--output-json", + type=Path, + default=None, + help="Optional path to write public-safe JSON receipt regardless of stdout --format.", + ) + 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, + "context_delivery_mode": args.context_delivery, + } + 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, + context_delivery=args.context_delivery, + ) + 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, + context_delivery=args.context_delivery, + ) + report["tier1"] = tier1 + report["passed"] = report["passed"] and bool(tier1["passed"]) + + assert_public_safe_payload(report, label="microbench_suite_report") + json_payload = json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False) + rendered = render_microbench_markdown(report) if args.format == "markdown" else json_payload + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(rendered + "\n", encoding="utf-8") + if args.output_json is not None: + assert_public_safe_payload(report, label="microbench_output_json") + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json_payload + "\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..aed1a91727 --- /dev/null +++ b/benchmark/microbench/scenarios.py @@ -0,0 +1,1470 @@ +"""Bounded M1/M2/M3 scenarios and deterministic constraint/efficiency oracles.""" + +from __future__ import annotations + +from collections.abc import Iterator, Mapping, Sequence +from contextlib import contextmanager +from dataclasses import dataclass +import hashlib +import importlib +import json +import os +from pathlib import Path +import shlex +import subprocess +import sys +import threading +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 import canary_harness as _canary_harness +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, + MicrobenchDeadlineExpired, + measure_text_tokens, + require_remaining_budget, + resolve_deadline, +) + +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, + deadline_monotonic: float | None = None, +) -> tuple[int, dict[str, Any]]: + deadline = resolve_deadline(deadline_monotonic) + timeout_s = 60.0 + if deadline is not None: + timeout_s = min(60.0, require_remaining_budget(deadline, stage="cli")) + if source_root is None and env_overrides is None and deadline 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 is None: + env["LOOPX_CONTEXT_DELIVERY"] = "off" + else: + 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, + ] + try: + 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=timeout_s, + ) + except subprocess.TimeoutExpired as exc: + if deadline is not None: + raise MicrobenchDeadlineExpired("cli_timeout") from exc + raise + 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 + + +_CANARY_CLI_PATCH_LOCK = threading.RLock() + + +@contextmanager +def _bounded_canary_cli(deadline_monotonic: float | None) -> Iterator[None]: + """Ensure CLI invocations inside ``canary_harness.import_fixture_authority`` obey deadlines.""" + deadline = resolve_deadline(deadline_monotonic) + if deadline is None: + yield + return + with _CANARY_CLI_PATCH_LOCK: + orig_run_json_cli = _canary_harness.run_json_cli + + def _bounded_run_json_cli( + *args: str, + registry_path: Path, + runtime_root: Path | None = None, + cwd: Path | None = None, + include_returncode: bool = True, + ) -> dict[str, Any]: + if runtime_root is None: + return orig_run_json_cli( + *args, + registry_path=registry_path, + runtime_root=runtime_root, + cwd=cwd, + include_returncode=include_returncode, + ) + rc, payload = _run_cli_with_source( + *args, + registry_path=registry_path, + runtime_root=runtime_root, + cwd=cwd, + deadline_monotonic=deadline, + ) + if rc != 0: + raise AssertionError(json.dumps(payload)) + if include_returncode: + payload["_returncode"] = rc + return payload + + _canary_harness.run_json_cli = _bounded_run_json_cli + try: + yield + finally: + _canary_harness.run_json_cli = orig_run_json_cli + + +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, + deadline_monotonic: float | None = None, +) -> PreparedMicrobenchFixture: + """Create isolated M1 fixture (#9498/#9504): blocked P0 + runnable P1 + historical acceptance.""" + deadline = resolve_deadline(deadline_monotonic) + if deadline is not None: + require_remaining_budget(deadline, stage="prepare_m1_fixture") + 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"], + ) + with _bounded_canary_cli(deadline): + 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, + context_delivery: str | None = None, + deadline_monotonic: float | None = None, +) -> dict[str, Any]: + """Run deterministic Base (`off`) or Head (`on`) arm for M1 (#9498/#9504).""" + if context_delivery not in (None, "auto", "off", "on"): + raise ValueError(f"unsupported context_delivery: {context_delivery!r}") + deadline = resolve_deadline(deadline_monotonic) + if deadline is not None: + require_remaining_budget(deadline, stage=f"m1_deterministic:{arm}") + delivery = ( + ("off" if arm == "base" else "on") + if context_delivery in (None, "auto") + else str(context_delivery) + ) + 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, + *, + deadline_monotonic: float | None = None, +) -> PreparedMicrobenchFixture: + """Create isolated M2 fixture (#9503 Stage-then-Swap & Semantic-Unit Fold).""" + deadline = resolve_deadline(deadline_monotonic) + if deadline is not None: + require_remaining_budget(deadline, stage="prepare_m2_fixture") + 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, + deadline_monotonic: float | None = None, +) -> dict[str, Any]: + """Run deterministic Base (`KeepRaw`) vs Head (`FoldToReceipt`/`EpochReset` + negative gate).""" + deadline = resolve_deadline(deadline_monotonic) + if deadline is not None: + require_remaining_budget(deadline, stage=f"m2_deterministic:{arm}") + 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(), + # 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, + } + + +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, + *, + deadline_monotonic: float | None = None, +) -> PreparedMicrobenchFixture: + """Create isolated M3 fixture: (a) blocked user_gate + (b) claim/settle lifecycle.""" + deadline = resolve_deadline(deadline_monotonic) + if deadline is not None: + require_remaining_budget(deadline, stage="prepare_m3_fixture") + 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], + ) + with _bounded_canary_cli(deadline): + 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], + ) + with _bounded_canary_cli(deadline): + 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, + deadline_monotonic: float | None = None, +) -> dict[str, Any]: + """Verify M3 basic claim, blocking gate, single settlement, and replay guards.""" + deadline = resolve_deadline(deadline_monotonic) + if deadline is not None: + require_remaining_budget(deadline, stage=f"m3_deterministic:{arm}") + 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..87ab1beb61 --- /dev/null +++ b/benchmark/microbench/tier0.py @@ -0,0 +1,482 @@ +"""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 +import inspect +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, + build_scenario_source_attribution, + compare_base_vs_head_efficiency, + require_remaining_budget, + resolve_deadline, + summarize_artifact_boundary, + summarize_claim_scope, +) +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 _call_with_deadline( + fn: Any, + *args: Any, + deadline_monotonic: float | None = None, + **kwargs: Any, +) -> Any: + effective_deadline = resolve_deadline(deadline_monotonic) + if effective_deadline is None: + return fn(*args, **kwargs) + try: + params = inspect.signature(fn).parameters + except (TypeError, ValueError): + return fn(*args, **kwargs) + if "deadline_monotonic" in params or any( + p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values() + ): + return fn(*args, deadline_monotonic=effective_deadline, **kwargs) + return fn(*args, **kwargs) + + +def _resolve_pinned_base_ref( + base_ref: str, + *, + main_ref: str = "origin/main", + deadline_monotonic: float | None = None, +) -> str: + effective_deadline = resolve_deadline(deadline_monotonic) + if effective_deadline is not None: + require_remaining_budget(effective_deadline, stage="resolve_base_ref") + helpers = _differential_smoke_helpers() + is_ancestor_fn = helpers["_is_ancestor"] + selected = select_cli_output_base_ref( + base_ref, + main_ref=main_ref, + is_ancestor=lambda ancestor, descendant: _call_with_deadline( + is_ancestor_fn, + ancestor, + descendant, + deadline_monotonic=effective_deadline, + ), + ) + if effective_deadline is not None: + require_remaining_budget(effective_deadline, stage="pin_base_ref") + return str( + _call_with_deadline( + helpers["_pin_probe_base_ref"], + selected, + main_ref=main_ref, + deadline_monotonic=effective_deadline, + ) + ) + + +def _head_commit(*, deadline_monotonic: float | None = None) -> str: + effective_deadline = resolve_deadline(deadline_monotonic) + timeout = 10.0 + if effective_deadline is not None: + rem = require_remaining_budget(effective_deadline, stage="head_commit") + timeout = min(10.0, rem) + completed = subprocess.run( + ["git", "rev-parse", "--verify", "HEAD"], + cwd=REPO_ROOT, + check=True, + capture_output=True, + text=True, + timeout=timeout, + ) + 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, + context_delivery: str = "auto", +) -> dict[str, Any]: + """Run deterministic Base vs Head Tier-0 M1/M2/M3 differential checks (<15s target).""" + if context_delivery not in {"auto", "off", "on"}: + raise ValueError(f"unsupported context_delivery: {context_delivery!r}") + 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) + if context_delivery == "auto": + return run_m1_deterministic_arm(fix, arm=arm_name, source_root=src_root) + return run_m1_deterministic_arm( + fix, + arm=arm_name, + source_root=src_root, + context_delivery=context_delivery, + ) + + 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_arms_ok = bool( + m2_base["behavior_constraint"].passed and m2_head["behavior_constraint"].passed + ) + m2_deltas = m2_cmp["deltas"] + tok_delta = m2_deltas.get("prompt_tokens") if isinstance(m2_deltas, Mapping) else None + head_ok = bool( + m2_arms_ok + and 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_arms_ok + and 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, + "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=prod_hot_path_ok, + note=( + "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": { + "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"], + ) + m3_cross = base_source_root is not None + m3_arms_ok = bool( + m3_base["behavior_constraint"].passed and m3_head["behavior_constraint"].passed + ) + return { + "scenario_id": "m3_claim_block_settle_invariants", + "passed": bool(m3_arms_ok and m3_cmp["behavior_preserved"]), + "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=m3_arms_ok, + ), + "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"], + ) + m1_base_ok = bool(m1_base["behavior_constraint"].passed) + m1_head_ok = bool(m1_head["behavior_constraint"].passed) + m1_arms_ok = m1_base_ok and m1_head_ok + m1_deltas = m1_cmp["deltas"] + wire_delta = m1_deltas.get("wire_bytes") if isinstance(m1_deltas, Mapping) else None + if context_delivery == "auto": + # Head slim delivery (`on`) must shrink delivered wire/tokens vs `off` while keeping invariants. + head_ok = bool( + m1_arms_ok + and m1_cmp["behavior_preserved"] + and isinstance(wire_delta, int) + and wire_delta < 0 + ) + else: + head_ok = bool(m1_arms_ok and m1_cmp["behavior_preserved"]) + m1_cross = base_source_root is not None + m1_comparison_kind = ( + ("cross_commit_differential" if m1_cross else "same_commit_arm_contrast") + if context_delivery == "auto" + else ("cross_commit_same_config" if m1_cross else "same_commit_aa") + ) + results.append( + { + "scenario_id": "m1_envelope_scoped_recovery", + "passed": head_ok, + "context_delivery_mode": context_delivery, + "source_attribution": build_scenario_source_attribution( + base_source="external_base_checkout" if m1_cross else "candidate_head", + head_source="candidate_head", + comparison_kind=m1_comparison_kind, + production_hot_path_covered=m1_arms_ok, + note=( + None + if m1_arms_ok + else "Excluded from production hot-path claims because one or both M1 arms failed behavior invariants." + ), + ), + "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, + }, + ) + m1_base_valid = bool(m1_base is not None and m1_base["behavior_constraint"].passed) + m1_head_valid = bool(m1_head is not None and m1_head["behavior_constraint"].passed) + probe_arms_valid = m1_base_valid and m1_head_valid + cli_diff_summary = { + "mode": "m1_probe_receipt_differential", + "ok": bool(cli_diff["ok"] and probe_arms_valid), + "baseline_valid": m1_base_valid, + "compared_row_count": cli_diff["compared_row_count"], + "failed_row_count": ( + int(cli_diff["failed_row_count"]) + if probe_arms_valid + else max(int(cli_diff["failed_row_count"]), 1) + ), + "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 (cli_diff_summary["ok"] if cli_diff_summary is not None else True) + 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", + "passed": overall_passed, + "wall_seconds": wall_seconds, + "head_commit": head_sha, + "base_ref": resolved_base_sha or "local_arm_contrast", + "context_delivery_mode": context_delivery, + "external_base_checkout_used": bool(claim_scope["cross_commit_scenarios"]), + "claim_scope": claim_scope, + "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..a3228cd3c3 --- /dev/null +++ b/benchmark/microbench/tier1.py @@ -0,0 +1,936 @@ +"""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 inspect +import json +from pathlib import Path +import re +import subprocess +import tempfile +import time +from typing import Any + +from .metrics import ( + MICROBENCH_RECEIPT_SCHEMA_VERSION, + BehaviorConstraintResult, + EfficiencyMetrics, + MicrobenchDeadlineExpired, + assert_public_safe_payload, + build_scenario_source_attribution, + compare_base_vs_head_efficiency, + microbench_deadline_scope, + require_remaining_budget, + summarize_artifact_boundary, + summarize_claim_scope, +) +from .models import ( + DEFAULT_ARK_FLASH_MODEL, + DEFAULT_CODEX_MODEL, + CodexGptMicrobenchRunner, + DeepSeekArkMicrobenchRunner, + MicrobenchModelRunner, + ModelRunOutcome, + require_positive_finite_float, + validate_microbench_verdict, +) +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 ( + _call_with_deadline, + _differential_smoke_helpers, + _head_commit, + _resolve_pinned_base_ref, +) + + +def _prompt_m1( + *, + arm: str, + context_delivery: 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 context_delivery == "on" 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}, context_delivery={context_delivery}).\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`, `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" + ) + + +_OBSERVED_SPEND_COMMANDS = frozenset( + {"loopx:quota spend-slot", "tool:quota_spend_slot", "tool:spend_slot"} +) + + +def _observed_command_spent_quota(observed_commands: Sequence[str]) -> bool: + for cmd in observed_commands: + norm = " ".join(str(cmd).strip().lower().split()) + if norm in _OBSERVED_SPEND_COMMANDS: + 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 + ) + 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, + "scenario_id_matches": scenario_ok, + "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 isinstance(obs, str) + and obs 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, + *, + 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, "deterministic_m1_recovery_passed": cli_gate_passed}, + violations=(f"model_{outcome.status}:{outcome.error_code or 'unknown'}",), + ) + 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"), + "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, + "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) + + +_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", + "already completed", + "already resolved", + "already fixed", + "already passed", + "no longer open", + "no longer needed", +) + + +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 (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] + 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) + if len(used_indices) != len(normalized_items): + return False, True + 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. 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'`, `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" + ) + + +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'}",), + ) + 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 = { + **_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, + "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, + } + 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` 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" + ) + + +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` 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" + ) + + +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'}",), + ) + 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", + "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 = { + **_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, + "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, + "telemetry_coverage": outcome.telemetry_coverage, + "observed_command_count": len(outcome.observed_commands), + "behavior_constraint": behavior.to_dict(), + "efficiency": outcome.efficiency.to_dict(), + } + + +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 _make_budget_exhausted_pair_row( + *, + runner: MicrobenchModelRunner, + scenario_id: str, + base_label: str, + head_label: str, + source_attribution: Mapping[str, object], + semantic_unit_settlement_hook_available: bool | None = None, +) -> 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 {} + ) + skipped = _budget_exhausted_outcome(runner) + fail_b = BehaviorConstraintResult( + passed=False, + checks={"within_budget": False}, + violations=("tier1_wall_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), + "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, + ), + } + + +def _invoke_m1_deterministic( + fixture: PreparedMicrobenchFixture, + *, + arm: str, + source_root: Path | None, + context_delivery: str, + deadline_monotonic: float, +) -> dict[str, Any]: + params = inspect.signature(run_m1_deterministic_arm).parameters + kwargs: dict[str, Any] = {"arm": arm, "source_root": source_root} + if context_delivery != "auto" or "context_delivery" in params: + kwargs["context_delivery"] = context_delivery + if "deadline_monotonic" in params: + kwargs["deadline_monotonic"] = deadline_monotonic + return run_m1_deterministic_arm(fixture, **kwargs) + + +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, + 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 {} + ) + rem_base = deadline - time.monotonic() + if rem_base <= 0: + return _make_budget_exhausted_pair_row( + runner=runner, + scenario_id=scenario_id, + base_label=base_label, + head_label=head_label, + source_attribution=source_attribution, + semantic_unit_settlement_hook_available=semantic_unit_settlement_hook_available, + ) + + 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, rem_base), + ) + base_behavior: BehaviorConstraintResult = base_grader(base_out) + 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, rem_head), + ) + 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, + 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( + 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), + "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, + context_delivery: str = "auto", +) -> 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", + ) + if context_delivery not in {"auto", "off", "on"}: + raise ValueError(f"unsupported context_delivery: {context_delivery!r}") + 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 = "deadline_exhausted" + resolved_base_sha: str | None = None + use_external_base = False + + 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), + ) + + def _default_source_attribution(sid: str, *, is_cross: bool) -> dict[str, object]: + if sid == "m1_envelope_scoped_recovery": + kind = ( + ("cross_commit_differential" if is_cross else "same_commit_arm_contrast") + if context_delivery == "auto" + else ("cross_commit_same_config" if is_cross else "same_commit_aa") + ) + return build_scenario_source_attribution( + base_source="external_base_checkout" if is_cross else "candidate_head", + head_source="candidate_head", + comparison_kind=kind, + production_hot_path_covered=False, + ) + if sid == "m2_epoch_prefetch_semantic_fold": + return build_scenario_source_attribution( + base_source="candidate_head", + head_source="candidate_head", + comparison_kind="same_commit_mechanism_verification", + production_hot_path_covered=False, + ) + return build_scenario_source_attribution( + base_source="candidate_head", + head_source="candidate_head", + comparison_kind="same_commit_gate_vs_claim_contrast", + production_hot_path_covered=False, + ) + + scenarios_plan: list[dict[str, Any]] = [] + rows: list[dict[str, Any]] = [] + prep_exhausted = False + with tempfile.TemporaryDirectory(prefix="loopx-microbench-t1-") as temp: + temp_root = Path(temp).resolve() + base_source_root: Path | None = None + try: + with microbench_deadline_scope(deadline): + head_sha = str( + _call_with_deadline(_head_commit, deadline_monotonic=deadline) + ) + if base_ref: + resolved_base_sha = str( + _call_with_deadline( + _resolve_pinned_base_ref, + base_ref, + main_ref=main_ref, + deadline_monotonic=deadline, + ) + ) + use_external_base = resolved_base_sha != head_sha + + if use_external_base and resolved_base_sha is not None: + require_remaining_budget(deadline, stage="materialize_base") + helpers = _differential_smoke_helpers() + base_source_root = temp_root / "base-src" + _call_with_deadline( + helpers["_materialize_base_source"], + resolved_base_sha, + base_source_root, + deadline_monotonic=deadline, + ) + + if "m1_envelope_scoped_recovery" in selected: + require_remaining_budget(deadline, stage="prepare:m1_envelope_scoped_recovery") + m1_base_fix = prepare_m1_fixture( + temp_root / "m1_base", + source_root=base_source_root, + deadline_monotonic=deadline, + ) + m1_head_fix = prepare_m1_fixture( + temp_root / "m1_head", + source_root=None, + deadline_monotonic=deadline, + ) + m1_base = _invoke_m1_deterministic( + m1_base_fix, + arm="base", + source_root=base_source_root, + context_delivery=context_delivery, + deadline_monotonic=deadline, + ) + m1_head = _invoke_m1_deterministic( + m1_head_fix, + arm="head", + source_root=None, + context_delivery=context_delivery, + deadline_monotonic=deadline, + ) + m1_base_delivery = str(m1_base.get("context_delivery") or ("off" if context_delivery == "auto" else context_delivery)) + m1_head_delivery = str(m1_head.get("context_delivery") or ("on" if context_delivery == "auto" else context_delivery)) + base_prompt = _prompt_m1( + arm="base", + context_delivery=m1_base_delivery, + fixture=m1_base_fix, + delivered_payload=m1_base["delivered_payload"], + decision_path=m1_base["decision_path"], + ) + head_prompt = _prompt_m1( + arm="head", + context_delivery=m1_head_delivery, + fixture=m1_head_fix, + delivered_payload=m1_head["delivered_payload"], + 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 + m1_kind = ( + ("cross_commit_differential" if m1_cross else "same_commit_arm_contrast") + if context_delivery == "auto" + else ("cross_commit_same_config" if m1_cross else "same_commit_aa") + ) + scenarios_plan.append( + { + "scenario_id": "m1_envelope_scoped_recovery", + "base_label": f"base_{m1_base_delivery}", + "head_label": f"head_{m1_head_delivery}", + "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": 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=m1_kind, + production_hot_path_covered=m1_cli_ok, + ), + } + ) + + if "m2_epoch_prefetch_semantic_fold" in selected: + require_remaining_budget(deadline, stage="prepare:m2_epoch_prefetch_semantic_fold") + m2_fix = prepare_m2_fixture(temp_root / "m2", deadline_monotonic=deadline) + m2_base = run_m2_deterministic_arm(m2_fix, arm="base", deadline_monotonic=deadline) + m2_head = run_m2_deterministic_arm(m2_fix, arm="head", deadline_monotonic=deadline) + 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_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, + 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, + "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_prod_ok, + note=( + "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." + ), + ), + } + ) + + if "m3_claim_block_settle_invariants" in selected: + require_remaining_budget(deadline, stage="prepare:m3_claim_block_settle_invariants") + m3_fix = prepare_m3_fixture(temp_root / "m3", deadline_monotonic=deadline) + m3_det = run_m3_deterministic_arm( + m3_fix, + arm="head", + source_root=None, + deadline_monotonic=deadline, + ) + 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), + "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, + ), + } + ) + except (MicrobenchDeadlineExpired, TimeoutError, subprocess.TimeoutExpired): + prep_exhausted = True + + if prep_exhausted: + m1_base_lbl = f"base_{'off' if context_delivery == 'auto' else context_delivery}" + m1_head_lbl = f"head_{'on' if context_delivery == 'auto' else context_delivery}" + label_map = { + "m1_envelope_scoped_recovery": (m1_base_lbl, m1_head_lbl), + "m2_epoch_prefetch_semantic_fold": ("base_keep_raw", "head_fold_receipt"), + "m3_claim_block_settle_invariants": ("m3a_blocked_gate", "m3b_claim_settle"), + } + for sid in selected: + b_lbl, h_lbl = label_map[sid] + attr = _default_source_attribution(sid, is_cross=use_external_base) + for runner in active_runners: + rows.append( + _make_budget_exhausted_pair_row( + runner=runner, + scenario_id=sid, + base_label=b_lbl, + head_label=h_lbl, + source_attribution=attr, + ) + ) + else: + 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"], + 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, + ) + 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]) + + finished_at = time.monotonic() + wall_seconds = round(finished_at - started, 3) + within_budget = (not prep_exhausted) and (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 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, + "head_commit": head_sha, + "base_ref": resolved_base_sha or "local_arm_contrast", + "context_delivery_mode": context_delivery, + "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 + ], + "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..98a8803bc5 --- /dev/null +++ b/benchmark/tests/test_dual_model_microbench.py @@ -0,0 +1,2581 @@ +"""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 +import types +from typing import Any + +import jsonschema +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, + MICROBENCH_VERDICT_SCHEMA, + CodexGptMicrobenchRunner, + DeepSeekArkMicrobenchRunner, + ModelRunOutcome, + validate_microbench_verdict, +) +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 import ( + metrics as microbench_metrics, + models as microbench_models, + scenarios as microbench_scenarios, + tier0 as microbench_tier0, + tier1 as microbench_tier1, +) +from benchmark.microbench.tier0 import run_tier0_differential +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: + 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, + "spend_classification": {{"observed": "none", "attempted": False, "confirmed": 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.efficiency.round_trips is None + assert out_ok.telemetry_coverage is not None + assert out_ok.telemetry_coverage["metrics"]["round_trips"]["status"] == "missing" + assert out_ok.telemetry_coverage["metrics"]["round_trips"]["reason"] == "missing_last_token_usage" + assert out_ok.telemetry_coverage["diagnostics"]["complete_record_count"] == 3 + 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, + "prompt_tokens_details": {"cached_tokens": 0}, + "completion_tokens_details": {"reasoning_tokens": 0}, + }, + "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, + "spend_classification": {"observed": "none", "attempted": False, "confirmed": False}, + "tool_actions_summary": ["cat fixture/m1-proof.json"], + } + return { + "usage": { + "prompt_tokens": 180, + "completion_tokens": 40, + "total_tokens": 220, + "prompt_tokens_details": {"cached_tokens": 0}, + "completion_tokens_details": {"reasoning_tokens": 0}, + }, + "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! + 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": ( + ("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": ( + ["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, + "spend_classification": {"observed": "none", "attempted": False, "confirmed": 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 + + +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_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", "attempted": False, "confirmed": False}, + "tool_actions_summary": [], + } + assert _grade_m2( + _outcome(valid_base), + expected_failures=expected_failures, + expected_obligations=expected_obligations, + gate_passed=True, + ).passed is True + + # 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",), + ), + ( + { + **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", "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",), + ), + ( + { + **valid_base, + "spend_attempted": True, + }, + ("no_premature_spend",), + ), + ] + for bad_verdict, expected_violations 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 + 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( + 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, + "spend_classification": {"observed": "none", "attempted": False, "confirmed": 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) + + 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_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 + 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 "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_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", + ], + "preserved_open_obligations": [ + "verify backoff ceiling test on sqlite provider", + "preserve terminal settlement receipt integrity", + ], + "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), + ) + + 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) + + +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, + "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. + 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) + + 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) + 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 & 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 + 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 + + # Read-only receipt narrative with typed read_only_receipt classification must pass (unverified prose ignored). + receipt_read_verdict = { + **base_m2_verdict, + "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_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 "spend_classification_consistent" in head_behavior["violations"] + assert "no_typed_spend_action" in head_behavior["violations"] + + 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. + 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, + "spend_classification": { + "observed": "none", + "attempted": False, + "confirmed": 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, + "spend_classification": { + "observed": "none", + "attempted": True, + "confirmed": False, + }, + "tool_actions_summary": ["checked user_gate"], + } + 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 "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", + "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, + "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( + 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: 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 +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"}}}})) +print(json.dumps({{"type": "item.completed", "item": {{"type": "function_call", "name": "quota_spend_slot"}}}})) +""", + 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", + "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: 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: + 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=1.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" + + +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) + + +def test_tier1_stops_deterministic_cli_and_runners_when_budget_expires_during_setup( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import time as std_time + + # Case 1: 0.10s total budget expires before any deterministic CLI process spawns. + now = {"t": 500.0} + + def _fake_monotonic() -> float: + now["t"] += 0.15 + return now["t"] + + cli_calls: list[tuple[Any, Any]] = [] + runner_calls: list[str] = [] + real_sub_run = subprocess.run + + def _spy_sub_run(*args: Any, **kwargs: Any) -> Any: + cmd = args[0] if args else kwargs.get("args", []) + if any("loopx.cli" in str(part) for part in (cmd or [])): + cli_calls.append((cmd, kwargs.get("timeout"))) + return real_sub_run(*args, **kwargs) + + class _NeverDispatchedRunner: + provider = "synthetic" + model_id = "synthetic-never-dispatched" + + def run_case(self, **kwargs: Any) -> ModelRunOutcome: + runner_calls.append(str(kwargs.get("scenario_id"))) + raise AssertionError("runner must not execute when setup exhausted deadline") + + monkeypatch.setattr(std_time, "monotonic", _fake_monotonic) + monkeypatch.setattr(microbench_scenarios.subprocess, "run", _spy_sub_run) + + report = run_tier1_dual_model_suite( + runners=[_NeverDispatchedRunner()], + max_total_seconds=0.10, + per_call_timeout_seconds=45.0, + ) + assert cli_calls == [] + assert runner_calls == [] + assert report["within_budget"] is False + assert report["passed"] is False + assert len(report["results"]) == 3 + for row in report["results"]: + assert row["passed"] is False + assert row["within_budget"] is False + assert row["base"]["status"] == "unavailable" + assert row["base"]["error_code"] == "tier1_wall_budget_exhausted" + assert row["head"]["error_code"] == "tier1_wall_budget_exhausted" + + # Case 2: real subprocess boundary passes shrinking remaining timeout (< 60s) and stops next CLI after expiry. + now2 = {"t": 800.0} + seen_cli_timeouts: list[tuple[str, float | None]] = [] + + def _step_monotonic() -> float: + return now2["t"] + + def _first_cli_expires(*args: Any, **kwargs: Any) -> Any: + cmd = args[0] if args else kwargs.get("args", []) + if not any("loopx.cli" in str(part) for part in (cmd or [])): + return real_sub_run(*args, **kwargs) + seen_cli_timeouts.append((" ".join(str(x) for x in cmd), kwargs.get("timeout"))) + result = real_sub_run(*args, **kwargs) + if "should-run" in seen_cli_timeouts[-1][0]: + now2["t"] = 815.0 # expire 10.0s suite budget as base `quota should-run` finishes + else: + now2["t"] += 1.0 # shrink remaining budget across pre-arm CLIs + return result + + monkeypatch.setattr(std_time, "monotonic", _step_monotonic) + monkeypatch.setattr(microbench_scenarios.subprocess, "run", _first_cli_expires) + + report2 = run_tier1_dual_model_suite( + runners=[_NeverDispatchedRunner()], + scenarios=("m1_envelope_scoped_recovery",), + max_total_seconds=10.0, + per_call_timeout_seconds=45.0, + ) + assert len(seen_cli_timeouts) >= 2, "expected deterministic CLIs before expiry" + assert seen_cli_timeouts[0][1] == pytest.approx(10.0) + assert seen_cli_timeouts[-1][1] is not None and seen_cli_timeouts[-1][1] < seen_cli_timeouts[0][1] + assert any("should-run" in cmd for cmd, _ in seen_cli_timeouts) + assert not any("context-read" in cmd for cmd, _ in seen_cli_timeouts) + assert runner_calls == [] + assert report2["within_budget"] is False + assert report2["passed"] is False + assert report2["results"][0]["base"]["error_code"] == "tier1_wall_budget_exhausted" + + +def test_ark_runner_clamps_every_http_round_and_tool_to_arm_deadline( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import time as std_time + + 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") + + 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"], + } + + # Subcase 1: 1.00s arm budget; round 1 takes 0.85s -> round 2 receives exact 0.15s and passes at 0.92s. + clock = {"t": 100.0} + monkeypatch.setattr(std_time, "monotonic", lambda: clock["t"]) + seen_timeouts_1: list[float] = [] + + def _transport_tight(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: float) -> dict[str, Any]: + del endpoint, headers, body + seen_timeouts_1.append(round(timeout_seconds, 4)) + if len(seen_timeouts_1) == 1: + clock["t"] = 100.85 + return { + "usage": {"prompt_tokens": 110, "completion_tokens": 10, "total_tokens": 120}, + "choices": [ + { + "message": { + "role": "assistant", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": { + "name": "exec_command", + "arguments": json.dumps({"cmd": "cat fixture/m1-proof.json"}), + }, + } + ], + } + } + ], + } + clock["t"] = 100.92 + return { + "usage": {"prompt_tokens": 140, "completion_tokens": 20, "total_tokens": 160}, + "choices": [{"message": {"role": "assistant", "content": json.dumps(verdict)}}], + } + + runner_tight = DeepSeekArkMicrobenchRunner(api_key="synthetic-key", transport=_transport_tight) + out_tight = runner_tight.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=1.0, + ) + assert out_tight.status == "ok", out_tight + assert seen_timeouts_1 == [pytest.approx(1.0), pytest.approx(0.15)] + assert out_tight.efficiency.initial_turn_context_tokens == 110 + assert out_tight.efficiency.per_turn_context_tokens == (110, 140) + assert out_tight.efficiency.peak_context_tokens == 140 + assert out_tight.efficiency.occupancy_measurement_kind == "per_request_input_proxy" + + # Subcase 2: 1.00s arm budget; round 1 advances clock to 1.10s -> 0 tool executions, 0 round-2 HTTP requests. + clock["t"] = 200.0 + seen_timeouts_2: list[float] = [] + tool_calls_2: list[str] = [] + monkeypatch.setattr( + microbench_models, + "_execute_scoped_command", + lambda cmd, **kwargs: (tool_calls_2.append(cmd), ("read:cat", "ok"))[1], + ) + + def _transport_expired(*, endpoint: str, headers: Any, body: bytes, timeout_seconds: float) -> dict[str, Any]: + del endpoint, headers, body + seen_timeouts_2.append(round(timeout_seconds, 4)) + clock["t"] = 201.10 + return { + "usage": {"prompt_tokens": 115, "completion_tokens": 12, "total_tokens": 127}, + "choices": [ + { + "message": { + "role": "assistant", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": { + "name": "exec_command", + "arguments": json.dumps({"cmd": "cat fixture/m1-proof.json"}), + }, + } + ], + } + } + ], + } + + runner_expired = DeepSeekArkMicrobenchRunner(api_key="synthetic-key", transport=_transport_expired) + out_expired = runner_expired.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=1.0, + ) + assert seen_timeouts_2 == [pytest.approx(1.0)] + assert tool_calls_2 == [] + assert out_expired.status == "error" + assert out_expired.error_code == "ark_budget_exhausted" + assert out_expired.verdict is None + assert out_expired.efficiency.round_trips == 1 + assert out_expired.efficiency.per_turn_context_tokens == (115,) + + +def test_codex_rollout_occupancy_extraction_validation_and_compaction(tmp_path: Path) -> None: + def _token_event( + *, + total_in: int, + total_cached: int, + total_out: int, + last_in: int | None, + last_cached: int = 0, + last_out: int = 0, + window: int | None = 475000, + ) -> dict[str, Any]: + info: dict[str, Any] = { + "total_token_usage": { + "input_tokens": total_in, + "cached_input_tokens": total_cached, + "output_tokens": total_out, + "reasoning_output_tokens": 0, + "total_tokens": total_in + total_out, + }, + } + if last_in is not None: + info["last_token_usage"] = { + "input_tokens": last_in, + "cached_input_tokens": last_cached, + "output_tokens": last_out, + "reasoning_output_tokens": 0, + "total_tokens": last_in + last_out, + } + if window is not None: + info["model_context_window"] = window + return { + "type": "event_msg", + "timestamp": "2026-11-27T00:00:05Z", + "payload": {"type": "token_count", "info": info}, + } + + # Valid multi-turn rollout with duplicate token_count snapshot, compaction, and truncation event. + valid_dir = tmp_path / "valid" + valid_dir.mkdir() + rollout = valid_dir / "rollout-valid.jsonl" + rows = [ + { + "type": "session_meta", + "timestamp": "2026-11-27T00:00:00Z", + "payload": {"id": "sess-occ-1"}, + }, + { + "type": "turn_context", + "timestamp": "2026-11-27T00:00:01Z", + "payload": {"model": "gpt-6.2-sol"}, + }, + _token_event(total_in=43607, total_cached=0, total_out=181, last_in=43607, last_cached=0, last_out=181), + _token_event(total_in=43607, total_cached=0, total_out=181, last_in=43607, last_cached=0, last_out=181), + {"type": "compacted", "timestamp": "2026-11-27T00:00:02Z", "payload": {"compaction_response_id": "c1"}}, + _token_event(total_in=92793, total_cached=43392, total_out=438, last_in=49186, last_cached=43392, last_out=257), + {"type": "event_msg", "timestamp": "2026-11-27T00:00:03Z", "payload": {"type": "context_truncated"}}, + _token_event(total_in=144795, total_cached=92288, total_out=610, last_in=52002, last_cached=48896, last_out=172), + ] + rollout.write_text("\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8") + + metrics = microbench_metrics.collect_codex_rollout_metrics(valid_dir) + assert metrics["prompt_tokens"] == 144795 + assert metrics["round_trips"] == 3 + assert metrics["complete_record_count"] == 8 + assert metrics["telemetry_coverage"]["metrics"]["round_trips"]["status"] == "complete" + assert metrics["telemetry_coverage"]["diagnostics"]["complete_record_count"] == 8 + assert metrics["initial_turn_context_tokens"] == 43607 + assert metrics["per_turn_context_tokens"] == (43607, 49186, 52002) + assert metrics["peak_context_tokens"] == 52002 + assert metrics["effective_context_window"] == 475000 + assert metrics["min_headroom_tokens"] == 475000 - 52002 + assert metrics["peak_window_ratio"] == pytest.approx(round(52002 / 475000, 6)) + assert metrics["compaction_events"] == 1 + assert metrics["truncation_events"] == 1 + assert metrics["occupancy_measurement_kind"] == "per_request_input_proxy" + assert metrics["occupancy_window_source"] == "codex_model_context_window" + + # Negative case: missing last_token_usage -> unknown occupancy (never fabricates per-request numbers). + no_last_dir = tmp_path / "no-last" + no_last_dir.mkdir() + (no_last_dir / "rollout.jsonl").write_text( + "\n".join( + json.dumps(r) + for r in [ + rows[0], + rows[1], + _token_event(total_in=1000, total_cached=0, total_out=20, last_in=None), + ] + ) + + "\n", + encoding="utf-8", + ) + m_nolast = microbench_metrics.collect_codex_rollout_metrics(no_last_dir) + assert m_nolast["prompt_tokens"] == 1000 + assert m_nolast["round_trips"] is None + assert m_nolast["telemetry_coverage"]["metrics"]["round_trips"]["status"] == "missing" + assert m_nolast["telemetry_coverage"]["metrics"]["round_trips"]["reason"] == "missing_last_token_usage" + assert m_nolast["occupancy_measurement_kind"] == "unknown" + assert m_nolast["peak_context_tokens"] is None + assert m_nolast["per_turn_context_tokens"] is None + + # Negative case: total delta != last_token_usage (counter gap) -> fails closed to unknown. + gap_dir = tmp_path / "gap" + gap_dir.mkdir() + (gap_dir / "rollout.jsonl").write_text( + "\n".join( + json.dumps(r) + for r in [ + rows[0], + rows[1], + _token_event(total_in=100, total_cached=0, total_out=10, last_in=100, last_out=10), + _token_event(total_in=300, total_cached=0, total_out=20, last_in=150, last_out=10), + ] + ) + + "\n", + encoding="utf-8", + ) + m_gap = microbench_metrics.collect_codex_rollout_metrics(gap_dir) + assert m_gap["round_trips"] is None + assert m_gap["telemetry_coverage"]["metrics"]["round_trips"]["status"] == "missing" + assert m_gap["telemetry_coverage"]["metrics"]["round_trips"]["reason"] == "counter_gap" + assert m_gap["occupancy_measurement_kind"] == "unknown" + assert m_gap["peak_context_tokens"] is None + assert m_gap["occupancy_error"] == "counter_gap" + + # Negative case: truncated/corrupt JSON line -> invalid_rollout_record fails closed to null round_trips. + corrupt_dir = tmp_path / "corrupt-tail" + corrupt_dir.mkdir() + (corrupt_dir / "rollout.jsonl").write_text( + "\n".join( + json.dumps(r) + for r in [ + rows[0], + rows[1], + _token_event(total_in=100, total_cached=0, total_out=10, last_in=100, last_out=10), + ] + ) + + "\n{truncated-json\n", + encoding="utf-8", + ) + m_corrupt = microbench_metrics.collect_codex_rollout_metrics(corrupt_dir) + assert m_corrupt["round_trips"] is None + assert m_corrupt["telemetry_coverage"]["metrics"]["round_trips"]["status"] == "missing" + assert m_corrupt["telemetry_coverage"]["metrics"]["round_trips"]["reason"] == "invalid_rollout_json" + assert m_corrupt["occupancy_measurement_kind"] == "unknown" + + # Negative case: multiple rollouts where one lacks last_token_usage -> partial status, null round_trips. + partial_dir = tmp_path / "partial-rollouts" + partial_dir.mkdir() + (partial_dir / "rollout-1.jsonl").write_text( + "\n".join( + json.dumps(r) + for r in [ + rows[0], + rows[1], + _token_event(total_in=100, total_cached=0, total_out=10, last_in=100, last_out=10), + ] + ) + + "\n", + encoding="utf-8", + ) + (partial_dir / "rollout-2.jsonl").write_text( + "\n".join( + json.dumps(r) + for r in [ + { + "type": "session_meta", + "timestamp": "2026-11-27T00:00:00Z", + "payload": {"id": "sess-occ-2"}, + }, + rows[1], + _token_event(total_in=200, total_cached=0, total_out=20, last_in=None), + ] + ) + + "\n", + encoding="utf-8", + ) + m_partial = microbench_metrics.collect_codex_rollout_metrics(partial_dir) + assert m_partial["round_trips"] is None + assert m_partial["telemetry_coverage"]["has_partial_coverage"] is True + assert m_partial["telemetry_coverage"]["partial_metrics"] == ["round_trips"] + assert m_partial["telemetry_coverage"]["metrics"]["round_trips"]["status"] == "partial" + + +def test_ark_partial_prompt_blocks_occupancy_and_cli_pin_with_output_json( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + trial_root = tmp_path / "trial" + project_root = trial_root / "project" + project_root.mkdir(parents=True) + call_idx = 0 + 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": [], + } + + def _partial_prompt_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": 120, "completion_tokens": 10, "total_tokens": 130}, + "choices": [ + { + "message": { + "role": "assistant", + "tool_calls": [ + { + "id": "call_ls", + "type": "function", + "function": {"name": "exec_command", "arguments": json.dumps({"cmd": "ls ."})}, + } + ], + } + } + ], + } + return { + "usage": {"completion_tokens": 15}, + "choices": [{"message": {"role": "assistant", "content": json.dumps(verdict)}}], + } + + r_partial = DeepSeekArkMicrobenchRunner(api_key="synthetic-key", transport=_partial_prompt_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.occupancy_measurement_kind == "unknown" + assert r_partial.efficiency.peak_context_tokens is None + assert r_partial.efficiency.per_turn_context_tokens is None + + cmp = compare_base_vs_head_efficiency( + EfficiencyMetrics( + wire_bytes=200, + prompt_tokens=100, + initial_turn_context_tokens=100, + peak_context_tokens=100, + occupancy_measurement_kind="per_request_input_proxy", + ), + 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"]["peak_context_tokens"] is None + assert cmp["deltas"]["initial_turn_context_tokens"] is None + + # CLI --context-delivery on + --output-json writes sanitized JSON while rendering Markdown stdout. + out_json = tmp_path / "nested" / "tier0-pinned.json" + rc = microbench_cli_main( + [ + "--tier", + "0", + "--scenario", + "m1_envelope_scoped_recovery", + "--context-delivery", + "on", + "--format", + "markdown", + "--output-json", + str(out_json), + ] + ) + assert rc == 0 + stdout_md = capsys.readouterr().out + assert "## Dual-Model Microbenchmark (M1/M2/M3)" in stdout_md + saved = json.loads(out_json.read_text(encoding="utf-8")) + assert saved["context_delivery_mode"] == "on" + assert saved["tier0"]["context_delivery_mode"] == "on" + m1_row = saved["tier0"]["scenarios"][0] + assert m1_row["passed"] is True + assert m1_row["source_attribution"]["comparison_kind"] == "same_commit_aa" + assert_public_safe_payload(saved) + + +def test_tier0_fails_and_blocks_hot_path_attribution_when_m1_baseline_fails( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_run_arm = microbench_scenarios.run_m1_deterministic_arm + + def _failing_base_arm( + fixture: Any, + *, + arm: str, + source_root: Path | None = None, + context_delivery: str | None = None, + deadline_monotonic: float | None = None, + ) -> dict[str, Any]: + result = real_run_arm( + fixture, + arm=arm, + source_root=source_root, + context_delivery=context_delivery, + deadline_monotonic=deadline_monotonic, + ) + if arm == "base": + checks = dict(result["behavior_constraint"].checks) + checks["blocked_p0_preserved"] = False + result["behavior_constraint"] = BehaviorConstraintResult( + passed=False, + checks=checks, + violations=("blocked_p0_preserved",), + ) + return result + + monkeypatch.setattr(microbench_tier0, "run_m1_deterministic_arm", _failing_base_arm) + report = run_tier0_differential(scenarios=("m1_envelope_scoped_recovery",)) + + assert report["passed"] is False + assert report["cli_output_differential"]["ok"] is False + assert report["cli_output_differential"]["baseline_valid"] is False + assert report["cli_output_differential"]["failed_row_count"] >= 1 + m1_row = report["scenarios"][0] + assert m1_row["passed"] is False + assert m1_row["base"]["behavior_constraint"]["passed"] is False + assert m1_row["head"]["behavior_constraint"]["passed"] is True + assert m1_row["comparison"]["baseline_valid"] is False + assert m1_row["comparison"]["behavior_preserved"] is False + assert m1_row["comparison"]["base_violations"] == ["blocked_p0_preserved"] + assert m1_row["comparison"]["deltas"]["wire_bytes"] < 0 + assert m1_row["source_attribution"]["production_hot_path_covered"] is False + assert m1_row["source_attribution"]["excluded_from_production_hot_path_claims"] is True + assert "m1_envelope_scoped_recovery" in report["claim_scope"]["excluded_from_production_hot_path_claims"] + assert "m1_envelope_scoped_recovery" not in report["claim_scope"]["production_hot_path_scenarios"] + + +def test_codex_runner_enforces_single_arm_deadline_across_setup_and_subprocess( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import time as std_time + + 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") + + # Marker-writing fake codex script based on _write_fake_codex. + codex_bin = tmp_path / "fake-codex-marker" + _write_fake_codex(codex_bin, mode="ok") + marker_file = tmp_path / "codex-invoked.marker" + codex_text = codex_bin.read_text(encoding="utf-8") + codex_bin.write_text( + codex_text.replace( + "_ = sys.stdin.read()", + f"pathlib.Path({str(marker_file)!r}).write_text('started', encoding='utf-8')\n" + f"if os.environ.get('FAKE_CODEX_SLEEP_SECONDS'):\n" + f" import time; time.sleep(float(os.environ['FAKE_CODEX_SLEEP_SECONDS']))\n" + "_ = sys.stdin.read()", + ), + encoding="utf-8", + ) + + # Subcase A: prepare_codex_home exhausts 0.05s budget -> 0 child processes launched. + clock_a = {"t": 100.0} + monkeypatch.setattr(std_time, "monotonic", lambda: clock_a["t"]) + real_prepare = microbench_models.prepare_codex_home + + def _slow_prepare_exhausted(*args: Any, **kwargs: Any) -> Any: + clock_a["t"] += 0.08 + return real_prepare(*args, **kwargs) + + monkeypatch.setattr(microbench_models, "prepare_codex_home", _slow_prepare_exhausted) + runner = CodexGptMicrobenchRunner( + codex_bin=str(codex_bin), + auth_json_path=auth_file, + sandbox="read-only", + ) + out_exhausted = 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=0.05, + ) + assert marker_file.exists() is False + assert out_exhausted.status == "error" + assert out_exhausted.error_code == "codex_budget_exhausted" + assert out_exhausted.verdict is None + + # Subcase B: prepare_codex_home consumes 0.35s of 1.00s budget -> subprocess receives ~0.65s remaining timeout. + clock_b = {"t": 200.0} + monkeypatch.setattr(std_time, "monotonic", lambda: clock_b["t"]) + seen_timeouts: list[float | None] = [] + real_sub_run = subprocess.run + + def _slow_prepare_partial(*args: Any, **kwargs: Any) -> Any: + clock_b["t"] += 0.35 + return real_prepare(*args, **kwargs) + + def _spy_codex_sub_run(*args: Any, **kwargs: Any) -> Any: + cmd = args[0] if args else kwargs.get("args", []) + if cmd and str(cmd[0]) == str(codex_bin): + seen_timeouts.append(kwargs.get("timeout")) + return real_sub_run(*args, **kwargs) + + monkeypatch.setattr(microbench_models, "prepare_codex_home", _slow_prepare_partial) + monkeypatch.setattr(microbench_models.subprocess, "run", _spy_codex_sub_run) + out_partial = 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=1.00, + ) + assert out_partial.status == "ok", out_partial + assert marker_file.exists() is True + assert seen_timeouts == [pytest.approx(0.65, abs=0.02)] + + # Subcase C: child process exceeding remaining timeout fails as codex_timeout. + monkeypatch.undo() + monkeypatch.setenv("FAKE_CODEX_SLEEP_SECONDS", "0.25") + out_timeout = 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=0.05, + ) + assert out_timeout.status == "error" + assert out_timeout.error_code == "codex_timeout" + + +def test_tier1_stops_git_base_resolution_and_export_stages_after_deadline( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import time as std_time + + class _NeverDispatchedRunner: + provider = "synthetic" + model_id = "synthetic-never-dispatched" + + def run_case(self, **kwargs: Any) -> ModelRunOutcome: + raise AssertionError(f"runner should not be called: {kwargs.get('scenario_id')}") + + real_sub_run = subprocess.run + + # Case A: git read-tree crosses 1.25s deadline by 0.30s (t += 1.55s) -> 0 ls-files, 0 checkout-index, 0 CLI/runner calls. + clock_a = {"t": 1000.0} + git_calls_a: list[tuple[list[str], float | None]] = [] + cli_calls_a: list[list[str]] = [] + + def _intercept_export_run(*args: Any, **kwargs: Any) -> Any: + cmd = [str(x) for x in (args[0] if args else kwargs.get("args", []))] + if any("loopx.cli" in part for part in cmd): + cli_calls_a.append(cmd) + if cmd and cmd[0] == "git": + git_calls_a.append((cmd, kwargs.get("timeout"))) + result = real_sub_run(*args, **kwargs) + if len(cmd) >= 2 and cmd[0] == "git" and cmd[1] == "read-tree": + clock_a["t"] += 1.55 + return result + + monkeypatch.setattr(std_time, "monotonic", lambda: clock_a["t"]) + monkeypatch.setattr(subprocess, "run", _intercept_export_run) + report_a = run_tier1_dual_model_suite( + runners=[_NeverDispatchedRunner()], + scenarios=("m1_envelope_scoped_recovery",), + base_ref="origin/main", + main_ref="origin/main", + max_total_seconds=1.25, + per_call_timeout_seconds=10.0, + ) + assert report_a["within_budget"] is False + assert report_a["passed"] is False + assert cli_calls_a == [] + assert any(len(cmd) >= 2 and cmd[1] == "read-tree" for cmd, _ in git_calls_a) + assert not any(len(cmd) >= 2 and cmd[1] == "ls-files" for cmd, _ in git_calls_a) + assert not any(len(cmd) >= 2 and cmd[1] == "checkout-index" for cmd, _ in git_calls_a) + for cmd, timeout in git_calls_a: + assert timeout is not None and timeout <= 1.25, (cmd, timeout) + assert report_a["results"][0]["base"]["error_code"] == "tier1_wall_budget_exhausted" + assert report_a["results"][0]["head"]["error_code"] == "tier1_wall_budget_exhausted" + + # Case B: git merge-base --is-ancestor crosses 0.50s deadline -> 0 pin / export / CLI / runner calls. + head_sha = microbench_tier0._head_commit() + clock_b = {"t": 2000.0} + git_calls_b: list[tuple[list[str], float | None]] = [] + + def _intercept_pin_run(*args: Any, **kwargs: Any) -> Any: + cmd = [str(x) for x in (args[0] if args else kwargs.get("args", []))] + if cmd and cmd[0] == "git": + git_calls_b.append((cmd, kwargs.get("timeout"))) + result = real_sub_run(*args, **kwargs) + if len(cmd) >= 3 and cmd[0] == "git" and cmd[1] == "merge-base" and "--is-ancestor" in cmd: + clock_b["t"] += 0.80 + return result + + monkeypatch.setattr(std_time, "monotonic", lambda: clock_b["t"]) + monkeypatch.setattr(subprocess, "run", _intercept_pin_run) + report_b = run_tier1_dual_model_suite( + runners=[_NeverDispatchedRunner()], + scenarios=("m1_envelope_scoped_recovery",), + base_ref=head_sha, + main_ref="origin/main", + max_total_seconds=0.50, + per_call_timeout_seconds=10.0, + ) + assert report_b["within_budget"] is False + assert report_b["passed"] is False + assert any("--is-ancestor" in cmd for cmd, _ in git_calls_b) + assert not any(len(cmd) >= 2 and cmd[1] == "read-tree" for cmd, _ in git_calls_b) + assert not any(len(cmd) >= 2 and cmd[1] == "ls-files" for cmd, _ in git_calls_b) + assert not any(len(cmd) >= 2 and cmd[1] == "checkout-index" for cmd, _ in git_calls_b) + assert report_b["results"][0]["base"]["error_code"] == "tier1_wall_budget_exhausted" + + +def test_tier1_codex_round_trips_counts_verified_requests_not_extra_log_lines( + tmp_path: Path, +) -> None: + trial_auth = tmp_path / "auth.json" + trial_auth.write_text('{"tokens":{}}', encoding="utf-8") + + def _write_paired_codex(bin_path: Path, *, unverified_head: bool) -> None: + script = f"""#!/usr/bin/env python3 +import json, os, pathlib, sys +args = sys.argv[1:] +prompt = sys.stdin.read() +schema_out = args[args.index("--output-last-message") + 1] +is_head = "arm=head" in prompt +home = pathlib.Path(os.environ["CODEX_HOME"]) +sessions = home / "sessions" / "2026" / "11" / "27" +sessions.mkdir(parents=True, exist_ok=True) +rollout = sessions / "rollout-paired.jsonl" + +def token_ev(total_in, total_out, last_in, last_out, include_last=True): + info = {{ + "total_token_usage": {{ + "input_tokens": total_in, + "cached_input_tokens": 0, + "output_tokens": total_out, + "reasoning_output_tokens": 0, + "total_tokens": total_in + total_out, + }}, + "model_context_window": 475000, + }} + if include_last: + info["last_token_usage"] = {{ + "input_tokens": last_in, + "cached_input_tokens": 0, + "output_tokens": last_out, + "reasoning_output_tokens": 0, + "total_tokens": last_in + last_out, + }} + return {{ + "type": "event_msg", + "timestamp": "2026-11-27T00:00:05Z", + "payload": {{"type": "token_count", "info": info}}, + }} + +rows = [ + {{"type": "session_meta", "timestamp": "2026-11-27T00:00:00Z", "payload": {{"model": "gpt-6.2-sol", "session_id": "sess-paired"}}}}, + {{"type": "turn_context", "timestamp": "2026-11-27T00:00:01Z", "payload": {{"model": "gpt-6.2-sol"}}}}, + token_ev(900, 10, 900, 10, include_last=not (is_head and {unverified_head!r})), +] +if is_head: + # Duplicate token_count + regular event + message record -> 7 lines total vs Base 4 lines, still 2 requests [900, 1000]. + rows.extend([ + token_ev(900, 10, 900, 10, include_last=not {unverified_head!r}), + {{"type": "event_msg", "timestamp": "2026-11-27T00:00:03Z", "payload": {{"type": "agent_reasoning"}}}}, + {{"type": "response_item", "timestamp": "2026-11-27T00:00:04Z", "payload": {{"type": "message", "role": "assistant"}}}}, + ]) +rows.append(token_ev(1900, 20, 1000, 10, include_last=not (is_head and {unverified_head!r}))) +rollout.write_text("\\n".join(json.dumps(r) for r in rows) + "\\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, + "spend_classification": {{"observed": "none", "attempted": False, "confirmed": False}}, + "tool_actions_summary": ["loopx quota context-read --select"], +}} +pathlib.Path(schema_out).write_text(json.dumps(verdict), encoding="utf-8") +print(json.dumps({{"type": "turn.completed", "usage": {{"input_tokens": 1900, "output_tokens": 20}}}})) +""" + bin_path.write_text(script, encoding="utf-8") + bin_path.chmod(bin_path.stat().st_mode | stat.S_IXUSR) + + # Case 1: Identical [900, 1000] request usage with Base=4 vs Head=7 JSONL lines -> round_trips=2 on both, delta=0. + codex_paired = tmp_path / "fake-codex-paired" + _write_paired_codex(codex_paired, unverified_head=False) + report = run_tier1_dual_model_suite( + runners=[ + CodexGptMicrobenchRunner( + codex_bin=str(codex_paired), + auth_json_path=trial_auth, + sandbox="read-only", + ) + ], + scenarios=("m1_envelope_scoped_recovery",), + base_ref=None, + max_total_seconds=60.0, + per_call_timeout_seconds=20.0, + ) + assert report["passed"] is True, report + row = report["results"][0] + assert row["base"]["efficiency"]["per_turn_context_tokens"] == [900, 1000] + assert row["head"]["efficiency"]["per_turn_context_tokens"] == [900, 1000] + assert row["base"]["efficiency"]["round_trips"] == 2 + assert row["head"]["efficiency"]["round_trips"] == 2 + assert row["comparison"]["deltas"]["round_trips"] == 0 + assert row["comparison"]["pct_changes"]["round_trips"] == 0.0 + assert row["base"]["telemetry_coverage"]["metrics"]["round_trips"]["status"] == "complete" + assert row["head"]["telemetry_coverage"]["metrics"]["round_trips"]["status"] == "complete" + assert row["base"]["telemetry_coverage"]["diagnostics"]["complete_record_count"] == 4 + assert row["head"]["telemetry_coverage"]["diagnostics"]["complete_record_count"] == 7 + + # Case 2: Head lacks last_token_usage -> round_trips stays null and delta is excluded via telemetry_coverage. + codex_unverified = tmp_path / "fake-codex-unverified" + _write_paired_codex(codex_unverified, unverified_head=True) + report_unverified = run_tier1_dual_model_suite( + runners=[ + CodexGptMicrobenchRunner( + codex_bin=str(codex_unverified), + auth_json_path=trial_auth, + sandbox="read-only", + ) + ], + scenarios=("m1_envelope_scoped_recovery",), + base_ref=None, + max_total_seconds=60.0, + per_call_timeout_seconds=20.0, + ) + assert report_unverified["passed"] is True, report_unverified + row_u = report_unverified["results"][0] + assert row_u["base"]["efficiency"]["round_trips"] == 2 + assert row_u["head"]["efficiency"]["round_trips"] is None + assert row_u["head"]["telemetry_coverage"]["metrics"]["round_trips"]["status"] == "missing" + assert "round_trips" in row_u["comparison"]["excluded_partial_metrics"] + assert row_u["comparison"]["deltas"]["round_trips"] is None + assert row_u["comparison"]["pct_changes"]["round_trips"] is None diff --git a/examples/benchmark-dual-model-microbench-smoke.py b/examples/benchmark-dual-model-microbench-smoke.py new file mode 100644 index 0000000000..38a99863ad --- /dev/null +++ b/examples/benchmark-dual-model-microbench-smoke.py @@ -0,0 +1,159 @@ +#!/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, + "spend_classification": { + "observed": "none", + "attempted": False, + "confirmed": 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, + "spend_classification": { + "observed": "none", + "attempted": False, + "confirmed": 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, + "spend_classification": { + "observed": "read_only_receipt", + "attempted": False, + "confirmed": 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()) diff --git a/examples/control_plane/cli-output-base-head-differential-smoke.py b/examples/control_plane/cli-output-base-head-differential-smoke.py index 49f94601d0..e2c965b4b3 100644 --- a/examples/control_plane/cli-output-base-head-differential-smoke.py +++ b/examples/control_plane/cli-output-base-head-differential-smoke.py @@ -10,6 +10,7 @@ import subprocess import sys import tempfile +import time from pathlib import Path @@ -33,10 +34,30 @@ ) +def _bounded_stage_timeout( + deadline_monotonic: float | None, + *, + stage: str, + default_timeout: float = 240.0, +) -> float: + if deadline_monotonic is None: + return default_timeout + remaining = float(deadline_monotonic) - time.monotonic() + if remaining <= 0.0: + raise TimeoutError(f"deadline exhausted before {stage}") + return min(default_timeout, remaining) + + def _run( command: list[str], *, cwd: Path, env: dict[str, str] | None = None, input_bytes: bytes | None = None, + deadline_monotonic: float | None = None, ) -> bytes: + timeout = _bounded_stage_timeout( + deadline_monotonic, + stage=" ".join(command[:3]) if command else "subprocess", + default_timeout=240.0, + ) completed = subprocess.run( command, cwd=cwd, @@ -45,7 +66,7 @@ def _run( check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - timeout=240, + timeout=timeout, ) if completed.returncode != 0: stdout = completed.stdout.decode("utf-8", errors="replace") @@ -58,15 +79,27 @@ def _run( return completed.stdout -def _materialize_base_source(base_ref: str, base_root: Path) -> None: +def _materialize_base_source( + base_ref: str, + base_root: Path, + *, + deadline_monotonic: float | None = None, +) -> None: """Export the pinned CLI source and its resources using a private Git index.""" env = {**os.environ, "GIT_INDEX_FILE": str(base_root.with_suffix(".index"))} - _run(["git", "read-tree", base_ref], cwd=REPO_ROOT, env=env) + _run( + ["git", "read-tree", base_ref], + cwd=REPO_ROOT, + env=env, + deadline_monotonic=deadline_monotonic, + ) # Root files include build manifests. The probe itself comes from the # candidate, so docs, test fixtures and other product trees are unnecessary. paths = _run( ["git", "ls-files", "-z", "--", ":(top,glob)*", "loopx/", "packages/", "scripts/", "skills/"], - cwd=REPO_ROOT, env=env, + cwd=REPO_ROOT, + env=env, + deadline_monotonic=deadline_monotonic, ) if b"loopx/__init__.py" not in paths.split(b"\0"): raise ValueError(f"CLI comparison base {base_ref} has no LoopX Python source") @@ -75,7 +108,10 @@ def _materialize_base_source(base_ref: str, base_root: Path) -> None: _run( ["git", f"--work-tree={base_root}", "checkout-index", f"--prefix={base_root.as_posix()}/", "--stdin", "-z"], - cwd=REPO_ROOT, env=env, input_bytes=paths, + cwd=REPO_ROOT, + env=env, + input_bytes=paths, + deadline_monotonic=deadline_monotonic, ) @@ -165,7 +201,21 @@ def _base_ceiling_observation(receipt: dict) -> dict: } -def _is_ancestor(ancestor: str, descendant: str) -> bool: +def _is_ancestor( + ancestor: str, + descendant: str, + *, + deadline_monotonic: float | None = None, +) -> bool: + timeout = ( + _bounded_stage_timeout( + deadline_monotonic, + stage="git merge-base --is-ancestor", + default_timeout=240.0, + ) + if deadline_monotonic is not None + else None + ) completed = subprocess.run( ["git", "merge-base", "--is-ancestor", ancestor, descendant], cwd=REPO_ROOT, @@ -175,6 +225,7 @@ def _is_ancestor(ancestor: str, descendant: str) -> bool: text=True, encoding="utf-8", errors="replace", + timeout=timeout, ) if completed.returncode == 0: return True @@ -186,9 +237,23 @@ def _is_ancestor(ancestor: str, descendant: str) -> bool: ) -def _pin_probe_base_ref(base_ref: str, *, main_ref: str) -> str: +def _pin_probe_base_ref( + base_ref: str, + *, + main_ref: str, + deadline_monotonic: float | None = None, +) -> str: # CI may fetch a newer main after its candidate merge commit was created. # Compare that candidate's ancestry, not unrelated later output changes. + timeout = ( + _bounded_stage_timeout( + deadline_monotonic, + stage="git pin base ref", + default_timeout=240.0, + ) + if deadline_monotonic is not None + else None + ) command = ( ["git", "merge-base", "--all", "--", base_ref, "HEAD"] if base_ref == main_ref else @@ -197,6 +262,7 @@ def _pin_probe_base_ref(base_ref: str, *, main_ref: str) -> str: completed = subprocess.run( command, cwd=REPO_ROOT, check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", + timeout=timeout, ) revisions = completed.stdout.splitlines() if completed.returncode != 0 or len(revisions) != 1: