Reversible clean-root candidate rebuilt from oak/benchmarks main@009dead264ca; original repository retained.

scripts/devloop.py in oak/benchmarks

scripts/devloop.py 1222 lines · 61.5 KB · python
1
#!/usr/bin/env python3
2
"""One command, one verdict: is this Oak changeset better, same, or worse?
3
4
The inner loop for agents developing Oak against this suite:
5
6
1. Resolve (or `cargo build --release`) the local Oak binary from the Oak
7
   source checkout.
8
2. Run the comparison lanes (core, workflow, contention) with git, the
9
   installed Oak baseline, an A/A control (the SAME baseline binary under the
10
   subject name ``oak_installed_aa``) and the local changeset, all interleaved
11
   in randomized order within every run.
12
3. Judge every (scenario, operation) cell on its own evidence
13
   (oakbench.cellstats): the cell's A/A floor, a bootstrap CI of the relative
14
   median delta, an exact permutation p-value and Benjamini-Hochberg across
15
   the comparison family. A latency change is claimed only when BH rejects,
16
   the CI excludes zero and lies wholly beyond the cell's A/A floor. There is
17
   no global threshold imported from another profile.
18
4. Run the roundtrip conformance matrix (lane ``conformance``) against the
19
   local changeset: a behaviour that newly fails vs
20
   config/conformance_expected_failures.json is REGRESSED; harness errors or
21
   missing behaviours are UNMEASURED; a listed failure that now passes is
22
   reported as FIXED (update the list).
23
5. Print a one-screen verdict and exit 0 (PASS), 1 (REGRESSED), or 2 (UNMEASURED).
24
25
Examples:
26
27
    python3 scripts/devloop.py                       # build ../oak, full quick loop
28
    python3 scripts/devloop.py --oak-local-bin ../oak/target/release/oak --skip-build
29
    python3 scripts/devloop.py --lanes core          # fastest signal only
30
31
Thresholds follow the suite's regression policy: efficiency gates (exact
32
metrics: tool calls, output bytes) apply to the Oak-baseline comparison only
33
(ADR-0004); the Git comparison is a latency guardrail.
34
"""
35
36
from __future__ import annotations
37
38
import argparse
39
import dataclasses
40
import json
41
import shutil
42
import statistics
43
import subprocess
44
import sys
45
import time
46
from datetime import datetime, timezone
47
from pathlib import Path
48
from typing import Any, Optional
49
50
from oakbench import cellstats
51
from oakbench import remotes as oakbench_remotes
52
from oakbench.reporting import percentile_nearest, slower_pct, symmetric_ratio_spread_pct
53
from oakbench.rows import output_bytes as row_output_bytes
54
from oakbench.rows import row_returncode
55
from oakbench.rows import token_total as row_token_total
56
from oakbench.rows import tool_calls as row_tool_calls
57
from oakbench.subjects import DEFAULT_OAK_REPO
58
59
ROOT = Path(__file__).resolve().parents[1]
60
SCRIPTS = ROOT / "scripts"
61
LANES = ("core", "workflow", "contention", "conformance")
62
DEFAULT_CONTENTION_WORKERS = "2,8"
63
DEFAULT_CONTENTION_COMMITS_PER_WORKER = 3
64
DEFAULT_CONTENTION_MODES = "shared_checkout,workspace_per_task,clone_push_storm"
65
SKIP_RETURNCODE = 77
66
AA_SUBJECT = "oak_installed_aa"
67
68
# Operations excluded from the noise floor: process spawn and sub-steps have
69
# the largest relative jitter and are not the deltas the verdict gates on.
70
NOISE_FLOOR_EXCLUDED = ("proc.spawn",)
71
NOISE_FLOOR_MIN_PCT = 3.0
72
73
74
def parse_args() -> argparse.Namespace:
75
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
76
    parser.add_argument("--oak-repo", type=Path, default=DEFAULT_OAK_REPO)
77
    parser.add_argument("--oak-local-bin", type=Path, help="Use this binary instead of building --oak-repo.")
78
    parser.add_argument(
79
        "--oak-baseline-bin",
80
        type=Path,
81
        help="Oak baseline binary (default: `oak` on PATH = released install).",
82
    )
83
    parser.add_argument("--skip-build", action="store_true", help="Never run cargo; require --oak-local-bin.")
84
    parser.add_argument(
85
        "--allow-drift",
86
        action="store_true",
87
        help="Report harness/Oak drift (stale flags, mappings, reader schema) as INFO instead of making the "
88
        "verdict UNMEASURED.",
89
    )
90
    parser.add_argument("--lanes", default="core,workflow,contention,conformance", help=f"Comma list from: {', '.join(LANES)}")
91
    parser.add_argument(
92
        "--contention-workers",
93
        default=DEFAULT_CONTENTION_WORKERS,
94
        help="Comma-separated worker tiers for the contention lane; launch gates use 16,32,64,128.",
95
    )
96
    parser.add_argument(
97
        "--contention-commits-per-worker",
98
        type=int,
99
        default=DEFAULT_CONTENTION_COMMITS_PER_WORKER,
100
    )
101
    parser.add_argument(
102
        "--contention-modes",
103
        default=DEFAULT_CONTENTION_MODES,
104
        help="Comma-separated parallel_contention modes to run in devloop.",
105
    )
106
    parser.add_argument("--runs", type=int, default=5,
107
                        help="Repetitions per comparison lane (default 5; per-cell statistics need >= 3).")
108
    parser.add_argument("--noise-floor-runs", type=int, default=5,
109
                        help="Repetitions for the optional legacy global micro A/A (--global-noise-floor).")
110
    parser.add_argument("--skip-noise-floor", action="store_true",
111
                        help="Omit the in-lane A/A control subject; every latency cell is then UNMEASURED.")
112
    parser.add_argument("--global-noise-floor", action="store_true",
113
                        help="Also run the legacy micro-profile A/A (informational; never gates a cell).")
114
    parser.add_argument("--core-profiles", default="smoke",
115
                        help="Comma list of bench.py profiles for the core lane (e.g. micro,smoke).")
116
    parser.add_argument("--fdr", type=float, default=cellstats.DEFAULT_FDR,
117
                        help="Benjamini-Hochberg false discovery rate across each comparison family.")
118
    parser.add_argument("--results", type=Path, default=ROOT / "results" / "devloop")
119
    parser.add_argument("--oak-threshold-pct", type=float, default=10.0)
120
    parser.add_argument("--git-threshold-pct", type=float, default=25.0)
121
    parser.add_argument("--min-delta-ms", type=float, default=0.0,
122
                        help="Optional absolute floor in ms (default 0: each cell's A/A floor and CI decide).")
123
    parser.add_argument("--confirm-runs", type=int, default=20,
124
                        help="Runs per arm for the independent confirmation stage on screened cells (core lane).")
125
    parser.add_argument("--confirm-budget-s", type=float, default=900.0,
126
                        help="Wall-time budget for the confirmation stage; fewer runs are used if needed.")
127
    parser.add_argument("--target-mde-pct", type=float, default=20.0,
128
                        help="Cells whose minimum detectable effect exceeds this are re-measured in confirmation.")
129
    parser.add_argument("--no-confirm", action="store_true",
130
                        help="Skip the confirmation stage (unconfirmed candidates then make the verdict UNMEASURED).")
131
    parser.add_argument("--output-bytes-threshold-pct", type=float, default=25.0)
132
    parser.add_argument(
133
        "--scorecard",
134
        action="store_true",
135
        help="Append a target scorecard vs the CURRENT Git Baseline Book (informational; never changes the verdict exit code).",
136
    )
137
    return parser.parse_args()
138
139
140
def scorecard_lines(rows: list[dict[str, Any]], root: Path = ROOT, noise_floor_pct: float | None = None,
141
                    cell_floors: dict[tuple[str, str], float] | None = None) -> list[str]:
142
    """Target-TDD lines for the devloop report; regression-TDD owns the exit code."""
143
    targets_path = root / "config" / "targets.json"
144
    if not targets_path.exists():
145
        return ["- no targets config (config/targets.json missing)"]
146
    current = root / "baselines" / "git" / "CURRENT"
147
    if not current.exists():
148
        return ["- no baseline book (baselines/git/CURRENT missing); run scripts/baseline_campaign.py run"]
149
    book_id = current.read_text().strip()
150
    book_path = root / "baselines" / "git" / book_id / "book.json"
151
    if not book_path.exists():
152
        return [f"- baseline book {book_id!r} is named by CURRENT but has no book.json"]
153
    from oakbench.baseline_book import load_baseline_book, load_targets
154
    from oakbench.scorecard import evaluate_targets
155
156
    baseline = load_baseline_book(book_path)
157
    if noise_floor_pct is not None:
158
        baseline = {
159
            key: dataclasses.replace(
160
                cell,
161
                noise_floor_pct=max(float(cell.noise_floor_pct or 0.0), float(noise_floor_pct)),
162
            )
163
            for key, cell in baseline.items()
164
        }
165
    if cell_floors:
166
        # Each scorecard cell's noise floor is at least that cell's own A/A floor.
167
        baseline = {
168
            key: dataclasses.replace(
169
                cell,
170
                noise_floor_pct=max(float(cell.noise_floor_pct or 0.0),
171
                                    cell_floors.get((str(getattr(cell, "scenario", "")), str(getattr(cell, "operation", ""))), 0.0)),
172
            )
173
            for key, cell in baseline.items()
174
        }
175
    results = evaluate_targets(rows, load_targets(targets_path), baseline)
176
    lines = []
177
    for item in results:
178
        ratio = item.get("ratio")
179
        ratio_text = "" if ratio is None else f" ratio {ratio:.3f} vs goal {item['goal_value']:.3f}"
180
        notes = "; ".join(str(note) for note in item.get("messages") or [])
181
        lines.append(f"- {item['verdict']} `{item['target_id']}`{ratio_text}" + (f" — {notes}" if notes else ""))
182
    return lines or ["- no targets defined"]
183
184
185
def conformance_checks(rows: list[dict[str, Any]], expected_path: Path | None = None) -> tuple[list[str], list[str]]:
186
    """(regressions, measurement notes) from conformance rows vs the expected-failures list."""
187
    from oakbench import conformance_gate
188
    from oakbench.conformance import SCENARIOS
189
    from oakbench.conformance_matrix import BEHAVIOURS
190
    expected = conformance_gate.load_expected(expected_path or conformance_gate.EXPECTED_FAILURES)
191
    required = list(SCENARIOS) + [behaviour.id for behaviour in BEHAVIOURS]
192
    result = conformance_gate.evaluate(rows, expected, required)
193
    regressions = [f"[conformance] CONFORMANCE {item}" for item in result["regressions"]]
194
    notes = [f"UNMEASURED conformance: {item}" for item in result["unmeasured"]]
195
    notes += [f"INFO conformance FIXED {item}" for item in result["fixed"]]
196
    notes.append(f"INFO {conformance_gate.summary_lines(result)[0]}")
197
    return regressions, notes
198
199
200
def run_lane(command: list[str], label: str) -> float:
201
    print(f"[devloop] {label}: {' '.join(str(part) for part in command)}", flush=True)
202
    started = time.perf_counter()
203
    proc = subprocess.run(command, cwd=ROOT, check=False)
204
    # Lane exit codes signal benchmark-operation failures; the verdict reads
205
    # those from the rows, so a nonzero lane exit is not fatal here.
206
    if proc.returncode not in (0, 1):
207
        raise SystemExit(f"{label} failed to run (exit {proc.returncode})")
208
    return time.perf_counter() - started
209
210
211
def breach_cell(line: str) -> tuple[str, str] | None:
212
    """(scenario, operation) named in a compare_subjects line's first `a/b` span."""
213
    start = line.find("`")
214
    end = line.find("`", start + 1)
215
    if start < 0 or end < 0 or "/" not in line[start + 1:end]:
216
        return None
217
    scenario, operation = line[start + 1:end].split("/", 1)
218
    return scenario, operation
219
220
221
def measured_by_oak(rows: list[dict[str, Any]], key: tuple[str, str]) -> bool:
222
    """True when either Oak arm has a measured (non-skip) row for the cell."""
223
    return any(row.get("subject") in ("oak_local", "oak_installed") and not row.get("skipped")
224
               and (str(row.get("scenario")), str(row.get("operation"))) == key for row in rows)
225
226
227
def confirmation_plan(candidates: list[tuple[str, str]], stage1_seconds: float, stage1_runs: int,
228
                      scenario_count: int, confirm_runs: int, budget_s: float) -> tuple[list[str], int]:
229
    """(scenarios to re-run, runs per arm) within the wall-time budget."""
230
    scenarios = sorted({scenario for scenario, _ in candidates})
231
    if not scenarios:
232
        return [], 0
233
    per_scenario_run = stage1_seconds / max(1, stage1_runs * max(1, scenario_count))
234
    affordable = int(budget_s // max(1e-6, per_scenario_run * len(scenarios)))
235
    return scenarios, min(confirm_runs, affordable)
236
237
238
def _csv(value: str) -> list[str]:
239
    return [item.strip() for item in value.split(",") if item.strip()]
240
241
242
def remote_preflight_requirements(
243
    lanes: list[str],
244
    *,
245
    contention_modes: list[str] | None = None,
246
    contention_workers: list[str] | None = None,
247
) -> list[oakbench_remotes.RemoteRequirement]:
248
    requirements: list[oakbench_remotes.RemoteRequirement] = []
249
    if "core" in lanes:
250
        requirements.append(
251
            oakbench_remotes.RemoteRequirement(
252
                purpose="default",
253
                lane="devloop/core",
254
                operations=(
255
                    "remote.net.push.first",
256
                    "remote.net.clone.cold",
257
                    "remote.net.fetch.uptodate",
258
                ),
259
            )
260
        )
261
    if "workflow" in lanes:
262
        requirements.append(
263
            oakbench_remotes.RemoteRequirement(
264
                purpose="sync",
265
                lane="devloop/workflow",
266
                operations=(
267
                    "sync_push_divergence/workflow.skipped",
268
                    "sync_pull_upstream/workflow.skipped",
269
                    "sync_pull_dirty/workflow.skipped",
270
                    "sync_non_ff_after_amend/workflow.skipped",
271
                ),
272
            )
273
        )
274
    if "contention" in lanes:
275
        modes = contention_modes or _csv(DEFAULT_CONTENTION_MODES)
276
        workers = contention_workers or _csv(DEFAULT_CONTENTION_WORKERS)
277
        operations: list[str] = []
278
        if "workspace_per_task" in modes:
279
            operations.extend(
280
                f"contention_workspace_per_task_w{workers_level}/parallel.total"
281
                for workers_level in workers
282
            )
283
        if "clone_push_storm" in modes:
284
            operations.extend(
285
                f"contention_clone_push_storm_w{workers_level}/parallel.total"
286
                for workers_level in workers
287
            )
288
        if operations:
289
            requirements.append(
290
                oakbench_remotes.RemoteRequirement(
291
                    purpose="fleet",
292
                    lane="devloop/contention",
293
                    operations=tuple(operations),
294
                )
295
            )
296
    return requirements
297
298
299
def build_oak_local(oak_repo: Path) -> Path:
300
    cargo_toml = oak_repo / "Cargo.toml"
301
    if not cargo_toml.exists():
302
        raise SystemExit(
303
            f"No Cargo.toml at {oak_repo}; pass --oak-local-bin or --oak-repo. "
304
            "devloop never mutates the Oak source checkout, it only builds it."
305
        )
306
    if shutil.which("cargo") is None:
307
        raise SystemExit("cargo is not installed; pass --oak-local-bin instead of building.")
308
    print(f"[devloop] building oak from {oak_repo} (cargo build --release)", flush=True)
309
    start = time.perf_counter()
310
    proc = subprocess.run(
311
        ["cargo", "build", "--release"],
312
        cwd=oak_repo,
313
        text=True,
314
        stdout=subprocess.PIPE,
315
        stderr=subprocess.STDOUT,
316
        check=False,
317
    )
318
    elapsed = time.perf_counter() - start
319
    if proc.returncode != 0:
320
        tail = "\n".join(proc.stdout.splitlines()[-25:])
321
        raise SystemExit(f"cargo build failed (exit {proc.returncode}) after {elapsed:.0f}s:\n{tail}")
322
    binary = oak_repo / "target" / "release" / "oak"
323
    if not binary.exists():
324
        raise SystemExit(f"build succeeded but {binary} does not exist")
325
    print(f"[devloop] built {binary} in {elapsed:.0f}s", flush=True)
326
    return binary
327
328
329
def load_jsonl(path: Path) -> list[dict[str, Any]]:
330
    try:
331
        text = path.read_text()
332
    except FileNotFoundError:
333
        raise SystemExit(f"[devloop] result JSONL missing: {path}") from None
334
    except OSError as exc:
335
        raise SystemExit(f"[devloop] result JSONL unreadable: {path}: {exc}") from None
336
337
    rows: list[dict[str, Any]] = []
338
    for line_number, line in enumerate(text.splitlines(), start=1):
339
        stripped = line.strip()
340
        if not stripped:
341
            continue
342
        try:
343
            row = json.loads(stripped)
344
        except json.JSONDecodeError as exc:
345
            raise SystemExit(
346
                f"[devloop] malformed result JSONL: {path}:{line_number}: {exc.msg}"
347
            ) from None
348
        if not isinstance(row, dict):
349
            raise SystemExit(f"[devloop] result JSONL row is not an object: {path}:{line_number}") from None
350
        rows.append(row)
351
352
    if not rows:
353
        raise SystemExit(f"[devloop] result JSONL contains no rows: {path}")
354
    return rows
355
356
357
def median_by_key(
358
    rows: list[dict[str, Any]], value_of, *, successful_only: bool = True
359
) -> dict[tuple[str, str, str], float]:
360
    grouped: dict[tuple[str, str, str], list[float]] = {}
361
    for row in rows:
362
        operation = str(row.get("operation") or "")
363
        if operation.endswith((".add", ".commit")):
364
            continue
365
        if successful_only and row_returncode(row) != 0:
366
            continue
367
        value = value_of(row)
368
        if value is None:
369
            continue
370
        key = (str(row.get("subject")), str(row.get("scenario")), operation)
371
        grouped.setdefault(key, []).append(float(value))
372
    return {key: float(statistics.median(values)) for key, values in grouped.items()}
373
374
375
def outcome_counts_by_key(rows: list[dict[str, Any]]) -> dict[tuple[str, str, str], dict[str, int]]:
376
    counts: dict[tuple[str, str, str], dict[str, int]] = {}
377
    for row in rows:
378
        operation = str(row.get("operation") or "")
379
        if operation.endswith((".add", ".commit")):
380
            continue
381
        key = (str(row.get("subject")), str(row.get("scenario")), operation)
382
        item = counts.setdefault(key, {"success": 0, "failure": 0, "skip": 0})
383
        returncode = row_returncode(row)
384
        if returncode == 0 and not row.get("skipped"):
385
            item["success"] += 1
386
        elif returncode == SKIP_RETURNCODE or row.get("skipped"):
387
            item["skip"] += 1
388
        else:
389
            item["failure"] += 1
390
    return counts
391
392
393
def diagnostic_operation(operation: str) -> bool:
394
    return operation.endswith((".determinism", ".inforecall"))
395
396
397
def measure_noise_floor(aa_dir: Path, baseline_bin: Path, runs: int) -> tuple[float, int]:
398
    """A/A null test: same binary as both subjects. Returns (p95 symmetric ratio spread, ops)."""
399
    run_lane(
400
        [
401
            sys.executable,
402
            str(SCRIPTS / "bench.py"),
403
            "--profile",
404
            "micro",
405
            "--runs",
406
            str(runs),
407
            "--subjects",
408
            "oak_installed,oak_local",
409
            "--oak-installed-bin",
410
            str(baseline_bin),
411
            "--oak-local-bin",
412
            str(baseline_bin),
413
            "--skip-determinism-probe",
414
            "--skip-remote",
415
            "--randomize-subject-order",
416
            "--results",
417
            str(aa_dir),
418
        ],
419
        "noise floor (A/A)",
420
    )
421
    rows = load_jsonl(aa_dir / "latest.jsonl")
422
    medians = median_by_key(rows, lambda row: row.get("elapsed_ms"))
423
    spreads: list[float] = []
424
    for (subject, scenario, operation), value in medians.items():
425
        if subject != "oak_installed" or operation in NOISE_FLOOR_EXCLUDED or operation.startswith("mode.setup"):
426
            continue
427
        other = medians.get(("oak_local", scenario, operation))
428
        pct = symmetric_ratio_spread_pct(value, other)
429
        if pct is not None:
430
            spreads.append(pct)
431
    if not spreads:
432
        return NOISE_FLOOR_MIN_PCT, 0
433
    p95 = percentile_nearest(spreads, 95.0) or NOISE_FLOOR_MIN_PCT
434
    return max(p95, NOISE_FLOOR_MIN_PCT), len(spreads)
435
436
437
def vcs_operations(rows: list[dict[str, Any]]) -> set[tuple[str, str]]:
438
    """(scenario, operation) pairs that actually invoke the subject's VCS.
439
440
    Latency gates apply only to these: search/read/edit/test steps run
441
    identical commands for every subject, so a delta there is host noise, not
442
    the changeset.
443
    """
444
    ops: set[tuple[str, str]] = set()
445
    for row in rows:
446
        if int(row.get("vcs_tool_call_count", 0) or 0) >= 1:
447
            ops.add((str(row.get("scenario")), str(row.get("operation"))))
448
    return ops
449
450
451
def embedded_null_p95(rows: list[dict[str, Any]], target: str, baseline: str) -> tuple[float, int]:
452
    """Noise estimate from identical-command steps: the spread between subjects
453
    on operations with zero VCS calls is what zero looks like in this lane."""
454
    latency = median_by_key(rows, lambda row: row.get("elapsed_ms"))
455
    vcs_ops = vcs_operations(rows)
456
    outcomes = outcome_counts_by_key(rows)
457
    spreads: list[float] = []
458
    for (subject, scenario, operation), value in latency.items():
459
        if subject != baseline or (scenario, operation) in vcs_ops or diagnostic_operation(operation):
460
            continue
461
        baseline_outcome = outcomes.get((baseline, scenario, operation), {})
462
        target_outcome = outcomes.get((target, scenario, operation), {})
463
        if baseline_outcome.get("failure", 0) or baseline_outcome.get("skip", 0):
464
            continue
465
        if target_outcome.get("failure", 0) or target_outcome.get("skip", 0):
466
            continue
467
        pct = symmetric_ratio_spread_pct(value, latency.get((target, scenario, operation)))
468
        if pct is not None:
469
            spreads.append(pct)
470
    if not spreads:
471
        return 0.0, 0
472
    return percentile_nearest(spreads, 95.0) or 0.0, len(spreads)
473
474
475
def same_patch_failure(left: dict[str, Any], right: dict[str, Any]) -> bool:
476
    if left.get("patch_failure_source") == "subject_tree_manifest_comparison":
477
        fields = ("patch_failure_source", "patch_failure_reason", "patch_oracle_version",
478
                  "patch_input_sha256", "patch_expected_tree_sha256", "patch_subject_tree_after_sha256")
479
        return (left.get("patch_apply_ok") is False and right.get("patch_apply_ok") is False
480
                and left.get("patch_failure_reason") == "diff_mutated_subject_tree"
481
                and all(isinstance(left.get(field), str) and len(left[field]) == 64 for field in fields[3:])
482
                and all(left.get(field) == right.get(field) for field in fields))
483
    fields = ("patch_input_sha256", "patch_expected_tree_sha256", "patch_apply_returncode",
484
              "patch_failure_reason", "patch_oracle_version", "patch_instrument_sha256",
485
              "patch_instrument_version")
486
    fingerprints = all(isinstance(left.get(field), str) and len(left[field]) == 64
487
                       for field in fields[:2])
488
    return (fingerprints and left.get("patch_apply_ok") is False and right.get("patch_apply_ok") is False
489
            and type(left.get("patch_apply_returncode")) is int
490
            and bool(left.get("patch_failure_reason")) and bool(left.get("patch_oracle_version"))
491
            and isinstance(left.get("patch_instrument_sha256"), str) and len(left["patch_instrument_sha256"]) == 64
492
            and bool(left.get("patch_instrument_version"))
493
            and all(left.get(field) == right.get(field) for field in fields))
494
495
496
def preexisting_patch_breach(breach: str, rows: list[dict[str, Any]]) -> bool:
497
    target_rows = [row for row in rows if row.get("subject") == "oak_local"
498
                   and breach.startswith(f"{breach.split(' ', 1)[0]} `{row.get('scenario')}/{row.get('operation')}`:")]
499
    if not target_rows:
500
        return False
501
    for target_row in target_rows:
502
        baseline_rows = [row for row in rows if row.get("subject") == "oak_installed"
503
                         and (row.get("scenario"), row.get("operation")) ==
504
                         (target_row.get("scenario"), target_row.get("operation"))]
505
        baseline_rows = [base for base in baseline_rows if base.get("run") == target_row.get("run")]
506
        if not baseline_rows or not all(same_patch_failure(target_row, base) for base in baseline_rows):
507
            return False
508
    return True
509
510
511
def compare_subjects(
512
    rows: list[dict[str, Any]],
513
    target: str,
514
    baseline: str,
515
    label: str,
516
    latency_threshold_pct: float,
517
    min_delta_ms: float,
518
    *,
519
    efficiency_gates: bool,
520
    output_bytes_threshold_pct: float,
521
    diagnostics: list[str] | None = None,
522
    cell_verdicts: dict[tuple[str, str], dict[str, Any]] | None = None,
523
    unconfirmed_prefix: str = "UNCONFIRMED",
524
) -> tuple[list[str], list[str]]:
525
    """Returns (regressions, improvements) lines for one baseline comparison.
526
527
    With ``cell_verdicts`` (oakbench.cellstats), latency is judged per cell;
528
    the legacy single threshold is used only when none are supplied.
529
    """
530
    diagnostics = diagnostics if diagnostics is not None else []
531
    gate_ops = vcs_operations(rows)
532
    latency = median_by_key(rows, lambda row: row.get("elapsed_ms"))
533
    tools = median_by_key(rows, row_tool_calls)
534
    bytes_out = median_by_key(rows, row_output_bytes)
535
    tokens = median_by_key(rows, row_token_total)
536
    outcomes = outcome_counts_by_key(rows)
537
538
    regressions: list[str] = []
539
    improvements: list[str] = []
540
    scenario_ops = sorted(
541
        {
542
            (scenario, op)
543
            for subject, scenario, op in set(latency) | set(outcomes)
544
            if subject in {target, baseline}
545
        }
546
    )
547
    target_kinds = {row.get("subject_kind") for row in rows if row.get("subject") == target} - {None}
548
    baseline_kinds = {row.get("subject_kind") for row in rows if row.get("subject") == baseline} - {None}
549
    incompatible_remote = (target_kinds == {"oak"} and baseline_kinds == {"git"}) or (target_kinds == {"git"} and baseline_kinds == {"oak"})
550
    for scenario, operation in scenario_ops:
551
        if incompatible_remote and operation.startswith("remote."):
552
            diagnostics.append(f"INFO TRANSPORT `{scenario}/{operation}`: local Git and network Oak operations are not comparable")
553
            continue
554
        if (scenario, operation) not in gate_ops or diagnostic_operation(operation):
555
            continue
556
        target_key = (target, scenario, operation)
557
        baseline_key = (baseline, scenario, operation)
558
559
        target_outcome = outcomes.get(target_key, {"success": 0, "failure": 0, "skip": 0})
560
        baseline_outcome = outcomes.get(baseline_key, {"success": 0, "failure": 0, "skip": 0})
561
        target_successes = target_outcome["success"]
562
        target_failures = target_outcome["failure"]
563
        target_skips = target_outcome["skip"]
564
        baseline_successes = baseline_outcome["success"]
565
        baseline_failures = baseline_outcome["failure"]
566
        if baseline_successes and target_successes == 0 and target_failures == 0 and target_skips > 0:
567
            diagnostics.append(f"UNMEASURED `{scenario}/{operation}` vs {label}: "
568
                               f"target has no measured attempts ({target_skips} skipped)")
569
        elif baseline_successes and target_successes == 0:
570
            regressions.append(
571
                f"NO SUCCESS `{scenario}/{operation}` vs {label}: target had 0 successful run(s) "
572
                f"({target_failures} failed, {target_skips} skipped), baseline had {baseline_successes}"
573
            )
574
        else:
575
            target_attempts = target_successes + target_failures
576
            baseline_attempts = baseline_successes + baseline_failures
577
            if target_attempts and baseline_attempts:
578
                target_failure_rate = target_failures / target_attempts
579
                baseline_failure_rate = baseline_failures / baseline_attempts
580
                target_less_reliable = target_failures > baseline_failures or target_successes < baseline_successes
581
                if target_failure_rate > baseline_failure_rate and target_less_reliable:
582
                    if baseline_failures == 0:
583
                        regressions.append(
584
                            f"FAIL `{scenario}/{operation}` vs {label}: {target_failures} failed run(s), "
585
                            "baseline clean"
586
                        )
587
                    else:
588
                        regressions.append(
589
                            f"FAIL-RATE `{scenario}/{operation}` vs {label}: "
590
                            f"{baseline_failures}/{baseline_attempts} -> {target_failures}/{target_attempts} "
591
                            f"failed run(s); successes {baseline_successes} -> {target_successes}"
592
                        )
593
594
        if baseline_key not in latency:
595
            continue
596
597
        pct = slower_pct(latency[baseline_key], latency.get(target_key))
598
        delta = (latency.get(target_key) or 0) - latency[baseline_key]
599
        if cell_verdicts is not None:
600
            item = cell_verdicts.get((scenario, operation))
601
            verdict = item.get("verdict") if item else "unmeasured"
602
            if verdict == "regression":
603
                regressions.append("SLOWER " + cellstats.describe(item, label))
604
            elif verdict == "improvement":
605
                improvements.append("faster " + cellstats.describe(item, label))
606
            elif verdict == "unconfirmed_regression":
607
                diagnostics.append(unconfirmed_prefix + " slower " + cellstats.describe(item, label) +
608
                                   f"; not claimed; ~{item.get('required_n')} runs/arm to confirm")
609
            elif verdict == "unconfirmed_improvement":
610
                diagnostics.append("INFO UNCONFIRMED faster " + cellstats.describe(item, label) + "; not claimed")
611
            pct = None
612
        if pct is not None:
613
            if pct >= latency_threshold_pct and delta >= min_delta_ms:
614
                regressions.append(
615
                    f"SLOWER `{scenario}/{operation}` vs {label}: {pct:+.1f}% "
616
                    f"({latency[baseline_key]:.1f} -> {latency[target_key]:.1f} ms)"
617
                )
618
            elif pct <= -latency_threshold_pct and -delta >= min_delta_ms:
619
                improvements.append(
620
                    f"faster `{scenario}/{operation}` vs {label}: {pct:+.1f}% "
621
                    f"({latency[baseline_key]:.1f} -> {latency[target_key]:.1f} ms)"
622
                )
623
624
        if efficiency_gates:
625
            tool_pct = slower_pct(tools.get(baseline_key), tools.get(target_key))
626
            if tool_pct is not None and tool_pct > 0:
627
                regressions.append(
628
                    f"TOOLS `{scenario}/{operation}` vs {label}: {tool_pct:+.1f}% "
629
                    f"({tools[baseline_key]:.0f} -> {tools[target_key]:.0f} calls)"
630
                )
631
            bytes_pct = slower_pct(bytes_out.get(baseline_key), bytes_out.get(target_key))
632
            if bytes_pct is not None and bytes_pct > output_bytes_threshold_pct:
633
                regressions.append(
634
                    f"OUTPUT `{scenario}/{operation}` vs {label}: {bytes_pct:+.1f}% "
635
                    f"({bytes_out[baseline_key]:.0f} -> {bytes_out[target_key]:.0f} bytes)"
636
                )
637
            elif bytes_pct is not None and bytes_pct < -output_bytes_threshold_pct:
638
                improvements.append(
639
                    f"leaner `{scenario}/{operation}` vs {label}: {bytes_pct:+.1f}% output bytes"
640
                )
641
            token_pct = slower_pct(tokens.get(baseline_key), tokens.get(target_key))
642
            if token_pct is not None and token_pct < -output_bytes_threshold_pct:
643
                improvements.append(f"fewer tokens `{scenario}/{operation}` vs {label}: {token_pct:+.1f}%")
644
645
    # Output-sufficiency gates: exact semantic metrics from the inforecall
646
    # probe rows, always on. A changeset can win every token/latency gate by
647
    # dropping changed-file names from output or breaking piped-diff
648
    # structure; that is a regression, not an optimization.
649
    oracle_versions: dict[tuple[str, str, str], set[Any]] = {}
650
    for row in rows:
651
        if "information_recall" in row or "information_precision" in row:
652
            key = (str(row.get("subject")), str(row.get("scenario")), str(row.get("operation")))
653
            oracle_versions.setdefault(key, set()).add(row.get("output_oracle_version"))
654
    incompatible_output = set()
655
    for (subject, scenario, operation), versions in oracle_versions.items():
656
        if subject != target:
657
            continue
658
        baseline_versions = oracle_versions.get((baseline, scenario, operation))
659
        if baseline_versions is not None and (len(versions) != 1 or versions != baseline_versions):
660
            incompatible_output.add((scenario, operation))
661
            regressions.append(f"OUTPUT-ORACLE `{scenario}/{operation}`: incompatible output oracle versions")
662
    output_rows = [row for row in rows if (str(row.get("scenario")), str(row.get("operation"))) not in incompatible_output]
663
    recall = median_by_key(output_rows, lambda row: row.get("information_recall"))
664
    precision = median_by_key(output_rows, lambda row: row.get("information_precision"))
665
    pipe_compat = median_by_key(
666
        rows,
667
        lambda row: (
668
            1.0
669
            if row.get("pipe_compatible_unified") is True
670
            else (0.0 if row.get("pipe_compatible_unified") is False else None)
671
        ),
672
    )
673
    for (subject, scenario, operation), value in sorted(recall.items()):
674
        if subject != target:
675
            continue
676
        base_value = recall.get((baseline, scenario, operation))
677
        if base_value is not None and value < base_value - 1e-6:
678
            regressions.append(
679
                f"RECALL `{scenario}/{operation}` vs {label}: changed-file recall "
680
                f"{base_value:.3f} -> {value:.3f} (output got cheaper by losing information)"
681
            )
682
    for (subject, scenario, operation), value in sorted(pipe_compat.items()):
683
        if subject != target:
684
            continue
685
        base_value = pipe_compat.get((baseline, scenario, operation))
686
        if base_value is not None and value < base_value - 1e-6:
687
            regressions.append(
688
                f"PIPE-COMPAT `{scenario}/{operation}` vs {label}: unified-diff structure lost "
689
                f"(rate {base_value:.2f} -> {value:.2f}); this legacy metric checks structure only"
690
            )
691
692
    for (subject, scenario, operation), value in sorted(precision.items()):
693
        if subject == target:
694
            base_value = precision.get((baseline, scenario, operation))
695
            if base_value is not None and value < base_value - 1e-6:
696
                regressions.append(f"PRECISION `{scenario}/{operation}` vs {label}: {base_value:.3f} -> {value:.3f}")
697
    patch_cells = {}
698
    for item in rows:
699
        if item.get("patch_application_required") is True or "patch_apply_ok" in item:
700
            key = (str(item.get("subject")), str(item.get("scenario")), str(item.get("operation")))
701
            patch_cells.setdefault(key, []).append(item)
702
    for scenario, operation in sorted({(key[1], key[2]) for key in patch_cells if key[0] in {target, baseline}}):
703
        base_rows = patch_cells.get((baseline, scenario, operation), [])
704
        target_rows = patch_cells.get((target, scenario, operation), [])
705
        proven_baseline = any(item.get("patch_apply_ok") is True and item.get("patch_application_required") is True
706
                              for item in base_rows)
707
        prefix = f"PATCH-APPLY `{scenario}/{operation}`"
708
        if not target_rows:
709
            if proven_baseline:
710
                regressions.append(prefix + ": target omitted previously measured patch evidence")
711
            elif any(base.get("patch_apply_ok") is True for base in base_rows):
712
                diagnostics.append("INFO " + prefix + ": target omitted previously measured optional patch evidence")
713
            continue
714
        for item in target_rows:
715
            if item.get("patch_apply_ok") is None:
716
                severity = "UNMEASURED " if item.get("patch_application_required") is True else "INFO "
717
                diagnostics.append(severity + prefix + ": " + str(item.get("patch_skip_reason") or "patch evidence unavailable"))
718
                continue
719
            instrument_rows = [probe for probe in [item, *[base for base in base_rows if base.get("run") == item.get("run")]]
720
                               if probe.get("patch_apply_ok") is not None
721
                               and probe.get("patch_failure_source") != "subject_tree_manifest_comparison"]
722
            if any(not isinstance(probe.get("patch_instrument_sha256"), str)
723
                   or len(probe["patch_instrument_sha256"]) != 64
724
                   or not probe.get("patch_instrument_version") for probe in instrument_rows):
725
                severity = "UNMEASURED " if item.get("patch_application_required") is True else "INFO "
726
                diagnostics.append(severity + prefix + ": patch instrument identity unavailable")
727
                continue
728
            versions = {base.get("patch_oracle_version") for base in base_rows if base.get("patch_apply_ok") is not None}
729
            if versions and versions != {item.get("patch_oracle_version")}:
730
                message = f"PATCH-ORACLE `{scenario}/{operation}`: incompatible or missing patch oracle version"
731
                if item.get("patch_application_required") is True:
732
                    regressions.append(message)
733
                else:
734
                    diagnostics.append("INFO " + message)
735
            elif item.get("patch_apply_ok") is False and (item.get("patch_application_required") is True
736
                                                        or item.get("patch_failure_source") == "subject_tree_manifest_comparison"):
737
                matched_rows = [base for base in base_rows if base.get("run") == item.get("run")]
738
                identical_failure = bool(matched_rows) and all(same_patch_failure(item, base) for base in matched_rows)
739
                if identical_failure:
740
                    diagnostics.append("PREEXISTING " + prefix + ": same measured defect in baseline and target")
741
                else:
742
                    regressions.append(prefix + ": exact patch application failed")
743
            elif item.get("patch_apply_ok") is False:
744
                diagnostics.append("INFO " + prefix + ": optional exact patch application failed")
745
746
    return regressions, improvements
747
748
749
def contention_checks(rows: list[dict[str, Any]], target: str, baseline: str) -> tuple[list[str], list[str]]:
750
    regressions: list[str] = []
751
    improvements: list[str] = []
752
    totals: dict[tuple[str, str], dict[str, Any]] = {}
753
    for row in rows:
754
        if row.get("operation") != "parallel.total" or row.get("skipped"):
755
            continue
756
        totals[(str(row.get("subject")), str(row.get("scenario")))] = row
757
758
    for (subject, scenario), row in sorted(totals.items()):
759
        if subject != target:
760
            continue
761
        metrics = row.get("parallel_metrics", {})
762
        if metrics.get("integrity_check_passed") is False:
763
            regressions.append(f"INTEGRITY `{scenario}`: post-contention check failed for {target}")
764
        if (metrics.get("lost_updates_detected") or 0) > 0:
765
            regressions.append(
766
                f"LOST UPDATES `{scenario}`: {metrics['lost_updates_detected']} payload(s) lost for {target}"
767
            )
768
        base = totals.get((baseline, scenario))
769
        if base:
770
            target_tp = metrics.get("commit_throughput_per_s")
771
            base_tp = base.get("parallel_metrics", {}).get("commit_throughput_per_s")
772
            if target_tp and base_tp:
773
                pct = ((target_tp - base_tp) / base_tp) * 100.0
774
                if pct < -15.0:
775
                    regressions.append(
776
                        f"THROUGHPUT `{scenario}` vs Oak baseline: {pct:+.1f}% "
777
                        f"({base_tp:.1f} -> {target_tp:.1f} snapshots/s)"
778
                    )
779
                elif pct > 15.0:
780
                    improvements.append(f"throughput `{scenario}` vs Oak baseline: {pct:+.1f}%")
781
    return regressions, improvements
782
783
784
def drift_preflight(local_bin: Path, baseline_bin: Path, oak_repo: Path, allow: bool) -> list[str]:
785
    """Check the harness still describes the Oak under test (oakbench.drift).
786
787
    Drift in the target build (a flag the suite runs no longer exists, the
788
    duplicated command mappings disagree, the independent reader does not
789
    know Oak's newest schema) means cells would measure the wrong thing, so
790
    it makes the verdict UNMEASURED unless --allow-drift. Baseline-binary CLI
791
    gaps are INFO: those baseline cells record failures, which is accurate for
792
    that binary but not a like-for-like latency comparison.
793
    """
794
    from oakbench import drift as oakbench_drift
795
796
    notes: list[str] = []
797
    prefix = "INFO drift" if allow else "UNMEASURED [drift]"
798
    target = oakbench_drift.all_drift(str(local_bin), oak_repo if (oak_repo / "Cargo.toml").exists() else None)
799
    for check, problems in target.items():
800
        notes.extend(f"{prefix} {check}: {problem}" for problem in problems)
801
    if not oakbench_drift.is_oak_cli(str(local_bin)):
802
        notes.append(f"INFO drift cli: {local_bin} does not identify as an Oak CLI; CLI drift unchecked")
803
    if oakbench_drift.is_oak_cli(str(baseline_bin)):
804
        for problem in oakbench_drift.cli_flag_drift(str(baseline_bin)):
805
            notes.append(f"INFO drift baseline cli: {problem} (baseline cells for it measure the failure)")
806
    for note in notes:
807
        print(f"[devloop] {note}", flush=True)
808
    if not notes:
809
        print("[devloop] drift preflight: harness matches the Oak under test", flush=True)
810
    return notes
811
812
813
def main() -> int:
814
    args = parse_args()
815
    lanes = [lane.strip() for lane in args.lanes.split(",") if lane.strip()]
816
    unknown = [lane for lane in lanes if lane not in LANES]
817
    if unknown:
818
        raise SystemExit(f"unknown lanes: {', '.join(unknown)}; valid: {', '.join(LANES)}")
819
    contention_modes = _csv(args.contention_modes)
820
    contention_workers = _csv(args.contention_workers)
821
    oakbench_remotes.print_remote_preflight_warnings(
822
        oakbench_remotes.oak_remote_preflight_warnings(
823
            remote_preflight_requirements(
824
                lanes,
825
                contention_modes=contention_modes,
826
                contention_workers=contention_workers,
827
            )
828
        )
829
    )
830
831
    baseline_bin = args.oak_baseline_bin or (Path(shutil.which("oak")) if shutil.which("oak") else None)
832
    if baseline_bin is None:
833
        raise SystemExit("No Oak baseline: install oak or pass --oak-baseline-bin")
834
    if args.oak_local_bin:
835
        local_bin = args.oak_local_bin.resolve()
836
        if not local_bin.exists():
837
            raise SystemExit(f"--oak-local-bin does not exist: {local_bin}")
838
    elif args.skip_build:
839
        raise SystemExit("--skip-build requires --oak-local-bin")
840
    else:
841
        local_bin = build_oak_local(args.oak_repo)
842
843
    drift_notes = drift_preflight(local_bin, baseline_bin, args.oak_repo, args.allow_drift)
844
845
    bench_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
846
    out = args.results / bench_id
847
    out.mkdir(parents=True, exist_ok=True)
848
    started = time.perf_counter()
849
850
    noise_pct = NOISE_FLOOR_MIN_PCT
851
    noise_ops = 0
852
    if args.global_noise_floor:
853
        noise_pct, noise_ops = measure_noise_floor(out / "aa", baseline_bin, args.noise_floor_runs)
854
    effective_oak_threshold = max(args.oak_threshold_pct, 2.0 * noise_pct)
855
    effective_git_threshold = max(args.git_threshold_pct, 2.0 * noise_pct)
856
    if args.runs < cellstats.MIN_SAMPLES:
857
        print(f"[devloop] WARNING --runs {args.runs} < {cellstats.MIN_SAMPLES}: every latency cell will be UNMEASURED",
858
              flush=True)
859
860
    aa_names = [] if args.skip_noise_floor else [AA_SUBJECT]
861
    subject_flags = [
862
        "--subjects",
863
        ",".join(["git", "oak_installed", *aa_names, "oak_local"]),
864
        "--oak-installed-bin",
865
        str(baseline_bin),
866
        *([] if args.skip_noise_floor else ["--oak-aa-bin", str(baseline_bin)]),
867
        "--oak-local-bin",
868
        str(local_bin),
869
    ]
870
    core_profiles = _csv(args.core_profiles)
871
    lane_dirs: list[tuple[str, Path]] = []
872
    core_meta: dict[str, dict[str, Any]] = {}
873
874
    if "core" in lanes:
875
        for profile in core_profiles:
876
            directory = out / ("core" if core_profiles == ["smoke"] else f"core-{profile}")
877
            seconds = run_lane(
878
                [
879
                    sys.executable,
880
                    str(SCRIPTS / "bench.py"),
881
                    "--profile",
882
                    profile,
883
                    "--runs",
884
                    str(args.runs),
885
                    "--randomize-subject-order",
886
                    *subject_flags,
887
                    "--results",
888
                    str(directory),
889
                ],
890
                f"core lane ({profile})",
891
            )
892
            lane_name = "core" if core_profiles == ["smoke"] else f"core:{profile}"
893
            lane_dirs.append((lane_name, directory))
894
            core_meta[lane_name] = {"profile": profile, "seconds": seconds, "directory": directory}
895
    if "workflow" in lanes:
896
        run_lane(
897
            [
898
                sys.executable,
899
                str(SCRIPTS / "workflow_ab.py"),
900
                "--workflows",
901
                "all",
902
                "--runs",
903
                str(args.runs),
904
                "--randomize-subject-order",
905
                *subject_flags,
906
                "--results",
907
                str(out / "workflow"),
908
            ],
909
            "workflow lane",
910
        )
911
        lane_dirs.append(("workflow", out / "workflow"))
912
    if "contention" in lanes:
913
        run_lane(
914
            [
915
                sys.executable,
916
                str(SCRIPTS / "parallel_contention.py"),
917
                "--workers",
918
                args.contention_workers,
919
                "--commits-per-worker",
920
                str(args.contention_commits_per_worker),
921
                "--modes",
922
                args.contention_modes,
923
                *subject_flags,
924
                "--results",
925
                str(out / "contention"),
926
            ],
927
            "contention lane",
928
        )
929
930
    if "conformance" in lanes:
931
        run_lane(
932
            [
933
                sys.executable,
934
                str(SCRIPTS / "vcs_conformance.py"),
935
                "--workdir",
936
                str(out / "conformance-work"),
937
                "--subjects",
938
                "git,oak",
939
                "--oak-bin",
940
                str(local_bin),
941
                "--output",
942
                str(out / "conformance" / "latest.jsonl"),
943
                "--quiet",
944
            ],
945
            "conformance lane",
946
        )
947
948
    regressions: list[str] = []
949
    improvements: list[str] = []
950
    guardrails: list[str] = []
951
    known_gaps: list[str] = []
952
    null_notes: list[str] = []
953
    measurement_notes: list[str] = list(drift_notes)
954
    scorecard_rows: list[dict[str, Any]] = []
955
    cell_notes: list[str] = []
956
    cell_floor_map: dict[tuple[str, str], float] = {}
957
    cell_records: list[dict[str, Any]] = []
958
    detection_lines: list[str] = []
959
    for lane, directory in lane_dirs:
960
        rows = load_jsonl(directory / "latest.jsonl")
961
        scorecard_rows += rows
962
        latency_of = lambda row: row.get("elapsed_ms")
963
        gated = {key for key in vcs_operations(rows) if not diagnostic_operation(key[1])
964
                 and not key[1].endswith((".add", ".commit"))}
965
        floors = cellstats.cell_floors(rows, "oak_installed", AA_SUBJECT, latency_of) if aa_names else {}
966
        for key, value in floors.items():
967
            cell_floor_map[key] = max(value, cell_floor_map.get(key, 0.0))
968
969
        def verdicts(target: str, baseline: str, min_delta: float) -> dict[tuple[str, str], dict[str, Any]]:
970
            return cellstats.classify_cells(rows, target, baseline, floors, value_of=latency_of,
971
                                            cells=gated, min_delta_ms=min_delta, fdr=args.fdr)
972
973
        oak_cells = verdicts("oak_local", "oak_installed", args.min_delta_ms)
974
        for item in oak_cells.values():
975
            item["stage"] = "screen"
976
        # Adaptive confirmation (core lane): re-measure only screened cells'
977
        # scenarios with more runs, then decide those cells on the FRESH data
978
        # alone (independent replication; BH over the candidate family only).
979
        candidates = cellstats.screen_candidates(oak_cells, target_mde_pct=args.target_mde_pct) if aa_names else []
980
        meta = core_meta.get(lane)
981
        if candidates and meta and not args.no_confirm and args.confirm_runs >= cellstats.MIN_SAMPLES:
982
            scenario_count = len({key[0] for key in oak_cells})
983
            scenarios, confirm_runs = confirmation_plan(candidates, meta["seconds"], args.runs, scenario_count,
984
                                                        args.confirm_runs, args.confirm_budget_s)
985
            if confirm_runs >= cellstats.MIN_SAMPLES:
986
                confirm_dir = meta["directory"].with_name(meta["directory"].name + "-confirm")
987
                operations = {op for _, op in candidates}
988
                run_lane(
989
                    [sys.executable, str(SCRIPTS / "bench.py"), "--profile", meta["profile"],
990
                     "--scenarios", ",".join(scenarios), "--runs", str(confirm_runs), "--randomize-subject-order",
991
                     "--skip-determinism-probe",
992
                     *([] if any(op.startswith("remote.") for op in operations) else ["--skip-remote"]),
993
                     *([] if "diff.dirty" in operations else ["--skip-diff"]),
994
                     *subject_flags, "--results", str(confirm_dir)],
995
                    f"confirmation ({lane}: {len(candidates)} cell(s), {len(scenarios)} scenario(s), runs={confirm_runs})",
996
                )
997
                confirm_rows = load_jsonl(confirm_dir / "latest.jsonl")
998
                confirm_floors = cellstats.cell_floors(confirm_rows, "oak_installed", AA_SUBJECT, latency_of)
999
                confirmed = cellstats.classify_cells(confirm_rows, "oak_local", "oak_installed", confirm_floors,
1000
                                                     value_of=latency_of, cells=candidates,
1001
                                                     min_delta_ms=args.min_delta_ms, fdr=args.fdr)
1002
                # QA R2-2: the A/A self-check covers the confirmation rows too.
1003
                confirm_aa = cellstats.classify_cells(confirm_rows, AA_SUBJECT, "oak_installed", confirm_floors,
1004
                                                      value_of=latency_of, cells=candidates,
1005
                                                      min_delta_ms=args.min_delta_ms, fdr=args.fdr)
1006
                confirm_aa_changes = [item for item in confirm_aa.values() if item["verdict"] in ("regression", "improvement")]
1007
                if confirm_aa_changes:
1008
                    measurement_notes.append(f"UNMEASURED [{lane}] A/A control shows {len(confirm_aa_changes)} change(s) "
1009
                                             "between identical binaries in the confirmation stage; host too noisy")
1010
                cell_records.extend({"lane": lane, "comparison": AA_SUBJECT + "_vs_oak_installed", "stage": "confirmation", **item}
1011
                                    for item in confirm_aa.values())
1012
                for key, item in confirmed.items():
1013
                    item.update(stage="confirmation", screen_verdict=oak_cells[key]["verdict"],
1014
                                screen_delta_pct=oak_cells[key]["delta_pct"], screen_p_value=oak_cells[key]["p_value"])
1015
                    oak_cells[key] = item
1016
                    if key in confirm_floors:
1017
                        cell_floor_map[key] = max(confirm_floors[key], cell_floor_map.get(key, 0.0))
1018
                cell_notes.append(f"[{lane}] confirmation: {len(candidates)} screened cell(s) re-measured at "
1019
                                  f"runs={confirm_runs} in {', '.join(scenarios)}; decided on fresh data only")
1020
            else:
1021
                cell_notes.append(f"[{lane}] confirmation skipped: budget {args.confirm_budget_s:.0f}s affords "
1022
                                  f"{confirm_runs} run(s) < {cellstats.MIN_SAMPLES}")
1023
        # Fail closed (QA P1-1): a gated Oak-vs-Oak cell that either Oak arm
1024
        # measured but that has no verdict makes the whole run UNMEASURED.
1025
        for key, item in sorted(oak_cells.items()):
1026
            if item["verdict"] == "unmeasured" and measured_by_oak(rows, key):
1027
                measurement_notes.append(f"UNMEASURED [{lane}] `{key[0]}/{key[1]}` vs Oak baseline: "
1028
                                         f"{item.get('reason') or 'no verdict'}")
1029
        for item in oak_cells.values():
1030
            # Without the confirmation stage a lone screen-stage change cannot
1031
            # pass BH when the family is too large for n: no power statement.
1032
            if (item["verdict"] == "no_change" and item.get("stage") == "screen"
1033
                    and (args.no_confirm or not candidates or meta is None)
1034
                    and cellstats.runs_for_bh(item.get("family_size") or 1, args.fdr,
1035
                                              min(item["baseline_n"], item["target_n"])) > min(item["baseline_n"], item["target_n"])):
1036
                item["mde_pct"] = None
1037
                item["reason"] = "single-cell change not confirmable at this n without the confirmation stage"
1038
        no_change = [item for item in oak_cells.values() if item["verdict"] == "no_change"]
1039
        if no_change:
1040
            mdes = sorted(item["mde_pct"] for item in no_change if item.get("mde_pct") is not None)
1041
            if mdes:
1042
                cell_notes.append(f"[{lane}] detection limits: {len(no_change)} cell(s) no change; minimum detectable "
1043
                                  f"effect at {cellstats.MDE_POWER:.0%} power median {statistics.median(mdes):.1f}%, "
1044
                                  f"max {mdes[-1]:.1f}%" + (f" ({len(no_change) - len(mdes)} cell(s) without a power "
1045
                                  "statement)" if len(mdes) < len(no_change) else ""))
1046
            detection_lines.extend(f"[{lane}] " + cellstats.describe(item, "Oak baseline") for item in no_change)
1047
        git_min_delta = max(args.min_delta_ms, 10.0)
1048
        local_git_cells = verdicts("oak_local", "git", git_min_delta)
1049
        baseline_git_cells = verdicts("oak_installed", "git", git_min_delta)
1050
        aa_cells = verdicts(AA_SUBJECT, "oak_installed", args.min_delta_ms) if aa_names else {}
1051
        tested = [item for item in oak_cells.values() if item["p_value"] is not None]
1052
        unmeasured = [item for item in oak_cells.values() if item["verdict"] == "unmeasured"]
1053
        if floors:
1054
            ordered = sorted(floors.values())
1055
            cell_notes.append(
1056
                f"[{lane}] per-cell A/A floors ({len(floors)} cells): median {statistics.median(ordered):.1f}%, "
1057
                f"max {ordered[-1]:.1f}%; {len(tested)} cells tested, BH q={args.fdr}; "
1058
                f"{len(unmeasured)} cell(s) unmeasured")
1059
        else:
1060
            cell_notes.append(f"[{lane}] no A/A control rows: every latency cell is UNMEASURED")
1061
        cell_records.extend({"lane": lane, "comparison": name, **item}
1062
                            for name, family in (("oak_local_vs_oak_installed", oak_cells),
1063
                                                 ("oak_local_vs_git", local_git_cells),
1064
                                                 ("oak_installed_vs_git", baseline_git_cells),
1065
                                                 (AA_SUBJECT + "_vs_oak_installed", aa_cells))
1066
                            for item in family.values())
1067
        aa_changes = [item for item in aa_cells.values() if item["verdict"] in ("regression", "improvement")]
1068
        if aa_changes:
1069
            measurement_notes.append(f"UNMEASURED [{lane}] A/A control shows {len(aa_changes)} change(s) "
1070
                                     "between identical binaries; host too noisy for latency verdicts")
1071
        # Per-lane embedded null control: identical-command steps (search,
1072
        # read, edit, test) cannot differ between subjects, so their spread is
1073
        # this lane's live noise measurement; thresholds rise to clear it.
1074
        null_pct, null_ops = embedded_null_p95(rows, "oak_local", "oak_installed")
1075
        lane_oak_threshold = max(effective_oak_threshold, 2.0 * null_pct)
1076
        lane_git_threshold = max(effective_git_threshold, 2.0 * null_pct)
1077
        if null_ops:
1078
            null_notes.append(
1079
                f"[{lane}] embedded null ({null_ops} identical-command ops): p95 spread {null_pct:.1f}%; "
1080
                f"lane threshold {lane_oak_threshold:.1f}%"
1081
            )
1082
        lane_regressions, lane_improvements = compare_subjects(
1083
            rows,
1084
            "oak_local",
1085
            "oak_installed",
1086
            "Oak baseline",
1087
            lane_oak_threshold,
1088
            args.min_delta_ms,
1089
            efficiency_gates=True,
1090
            output_bytes_threshold_pct=args.output_bytes_threshold_pct,
1091
            diagnostics=measurement_notes,
1092
            cell_verdicts=oak_cells,
1093
        )
1094
        regressions += [f"[{lane}] {item}" for item in lane_regressions]
1095
        improvements += [f"[{lane}] {item}" for item in lane_improvements]
1096
1097
        # Git guardrail: only breaches the CHANGESET introduced fail the
1098
        # verdict. Pre-existing Oak-vs-Git gaps (also breached by the installed
1099
        # baseline) are listed as known gaps — a verdict that fails every run
1100
        # on inherited gaps teaches agents to ignore it (ADR-0004's lesson).
1101
        local_breaches, git_improvements = compare_subjects(
1102
            rows,
1103
            "oak_local",
1104
            "git",
1105
            "Git guardrail",
1106
            lane_git_threshold,
1107
            max(args.min_delta_ms, 10.0),
1108
            efficiency_gates=False,
1109
            output_bytes_threshold_pct=args.output_bytes_threshold_pct,
1110
            diagnostics=measurement_notes,
1111
            cell_verdicts=local_git_cells,
1112
            # Git-guardrail candidates inform; only Oak-baseline candidates make the verdict inconclusive.
1113
            unconfirmed_prefix="INFO UNCONFIRMED",
1114
        )
1115
        baseline_breaches, _ = compare_subjects(
1116
            rows,
1117
            "oak_installed",
1118
            "git",
1119
            "Git guardrail",
1120
            lane_git_threshold,
1121
            max(args.min_delta_ms, 10.0),
1122
            efficiency_gates=False,
1123
            output_bytes_threshold_pct=args.output_bytes_threshold_pct,
1124
            cell_verdicts=baseline_git_cells,
1125
        )
1126
        preexisting = {breach.split(":")[0] for breach in baseline_breaches}
1127
        oak_regressed = {key for key, item in oak_cells.items() if item["verdict"] == "regression"}
1128
        for breach in local_breaches:
1129
            is_patch = breach.startswith(("PATCH-APPLY ", "PATCH-ORACLE "))
1130
            if breach.startswith("SLOWER "):
1131
                # QA P1-2: a latency breach is introduced by the changeset only
1132
                # when the SAME cell's Oak-vs-Oak comparison is a confirmed
1133
                # regression; otherwise it is a pre-existing Oak-vs-Git gap.
1134
                cell = breach_cell(breach)
1135
                if cell in oak_regressed:
1136
                    guardrails.append(f"[{lane}] {breach}")
1137
                else:
1138
                    known_gaps.append(f"[{lane}] {breach}")
1139
            elif breach.split(":")[0] in preexisting and (not is_patch or preexisting_patch_breach(breach, rows)):
1140
                known_gaps.append(f"[{lane}] {breach}")
1141
            else:
1142
                guardrails.append(f"[{lane}] {breach}")
1143
        improvements += [f"[{lane}] {item}" for item in git_improvements]
1144
    if "contention" in lanes:
1145
        rows = load_jsonl(out / "contention" / "latest.jsonl")
1146
        scorecard_rows += rows
1147
        lane_regressions, lane_improvements = contention_checks(rows, "oak_local", "oak_installed")
1148
        regressions += [f"[contention] {item}" for item in lane_regressions]
1149
        improvements += [f"[contention] {item}" for item in lane_improvements]
1150
1151
    if "conformance" in lanes:
1152
        conformance_regressions, conformance_notes = conformance_checks(
1153
            load_jsonl(out / "conformance" / "latest.jsonl"))
1154
        regressions += conformance_regressions
1155
        measurement_notes += conformance_notes
1156
1157
    elapsed_s = time.perf_counter() - started
1158
    verdict = ("REGRESSED" if regressions or guardrails else
1159
               "UNMEASURED" if any(note.startswith(("UNMEASURED", "UNCONFIRMED")) for note in measurement_notes)
1160
               else "PASS")
1161
    lines = [
1162
        "# Devloop Verdict",
1163
        "",
1164
        f"**{verdict}** — oak_local ({local_bin}) vs Oak baseline ({baseline_bin}) and Git, "
1165
        f"lanes: {', '.join(lanes)}, runs={args.runs}, total {elapsed_s:.0f}s.",
1166
        "",
1167
        f"- Latency verdicts are per cell (cellstats {cellstats.CELL_STATS_VERSION}): change only when "
1168
        f"BH-FDR q={args.fdr} rejects AND the 95% bootstrap CI excludes 0 AND the effect exceeds that "
1169
        f"cell's A/A floor ({AA_SUBJECT} = baseline binary, interleaved). Screened cells are re-measured "
1170
        f"(up to --confirm-runs {args.confirm_runs}) and decided on fresh data. UNCONFIRMED candidates are never claimed.",
1171
        *[f"- {note}" for note in cell_notes],
1172
        *([f"- Legacy global micro A/A (informational only, {noise_ops} ops): p95 spread {noise_pct:.1f}%."]
1173
          if args.global_noise_floor else []),
1174
        f"- Efficiency gates (exact metrics) vs Oak baseline only (ADR-0004): any tool-call increase, "
1175
        f">{args.output_bytes_threshold_pct:.0f}% output bytes.",
1176
        *[f"- {note}" for note in null_notes],
1177
        "",
1178
        f"## Regressions vs Oak baseline ({len(regressions)})",
1179
        "",
1180
        *([f"- {item}" for item in regressions] or ["- none"]),
1181
        "",
1182
        f"## New Git-guardrail breaches introduced by this changeset ({len(guardrails)})",
1183
        "",
1184
        *([f"- {item}" for item in guardrails] or ["- none"]),
1185
        "",
1186
        f"## Known Git gaps, pre-existing in the baseline ({len(known_gaps)}) — tracked, not failing",
1187
        "",
1188
        *([f"- {item}" for item in known_gaps] or ["- none"]),
1189
        "",
1190
        "## Correctness measurement notes",
1191
        "",
1192
        *([f"- {item}" for item in dict.fromkeys(measurement_notes)] or ["- none"]),
1193
        "",
1194
        f"## Improvements ({len(improvements)})",
1195
        "",
1196
        *([f"- {item}" for item in improvements[:20]] or ["- none"]),
1197
        "",
1198
        f"## Detection limits: no change >= X% at {cellstats.MDE_POWER:.0%} power ({len(detection_lines)} cells)",
1199
        "",
1200
        *([f"- {item}" for item in detection_lines] or ["- none"]),
1201
        "",
1202
        f"Raw rows: {out}/ (per-cell decisions: cells.json)",
1203
    ]
1204
    if args.scorecard:
1205
        lines += [
1206
            "",
1207
            "## Scorecard vs Git Baseline Book (informational)",
1208
            "",
1209
            *scorecard_lines(scorecard_rows, noise_floor_pct=noise_pct if args.global_noise_floor else None,
1210
                             cell_floors=cell_floor_map),
1211
        ]
1212
    report = "\n".join(lines) + "\n"
1213
    (out / "verdict.md").write_text(report)
1214
    # Every per-cell decision (floor, CI, p, BH) for audit; derived, never committed.
1215
    (out / "cells.json").write_text(json.dumps(cell_records, indent=1, sort_keys=True) + "\n")
1216
    print()
1217
    print(report)
1218
    return 0 if verdict == "PASS" else (2 if verdict == "UNMEASURED" else 1)
1219
1220
1221
if __name__ == "__main__":
1222
    raise SystemExit(main())