Viewing files at commit f0c34b306c79Commit detailsView latest

scripts/oakbench/scorecard.py 370 lines · 16.4 KB · python
1
"""Target scorecard evaluation."""
2
3
from __future__ import annotations
4
5
from typing import Any
6
import math
7
8
from oakbench.baseline_book import BaselineCell, Target, iter_jsonl, metric_value
9
from oakbench.integrity import content_integrity_public_trust_passed
10
from oakbench.rows import number_or_none, row_returncode
11
from oakbench.populations import (population_conflicts, comparison_identity, comparison_conflicts,
12
                                 independent_run_count, missing_claim_identity)
13
from oakbench.stats import bootstrap_ci, named_statistic, required_n_for_relative_delta, validate_interval_settings
14
15
VERDICTS = ("GREEN", "RED", "AMBER", "UNDECIDABLE", "UNMEASURED", "INVALID")
16
17
# One JSONL loader for scorecard inputs; baseline_book owns the implementation.
18
load_jsonl = iter_jsonl
19
20
21
def evaluate_targets(
22
    rows: list[dict[str, Any]],
23
    targets: list[Target],
24
    baseline: dict[tuple[str, str | None, str, str, str, str, str], BaselineCell],
25
    *,
26
    bootstrap_samples: int = 2000,
27
    confidence: float = 0.95,
28
    seed: int = 20260609,
29
    mode: str = "diagnostic",
30
) -> list[dict[str, Any]]:
31
    validate_interval_settings(bootstrap_samples, confidence)
32
    if mode not in {"diagnostic", "claim"}:
33
        raise ValueError("mode must be diagnostic or claim")
34
    return [
35
        evaluate_target(
36
            rows,
37
            target,
38
            baseline.get(target.baseline_key),
39
            bootstrap_samples=bootstrap_samples,
40
            confidence=confidence,
41
            seed=seed,
42
            mode=mode,
43
        )
44
        for target in targets
45
    ]
46
47
48
def evaluate_target(
49
    rows: list[dict[str, Any]],
50
    target: Target,
51
    baseline: BaselineCell | None,
52
    *,
53
    bootstrap_samples: int,
54
    confidence: float,
55
    seed: int,
56
    mode: str = "diagnostic",
57
) -> dict[str, Any]:
58
    matched = [row for row in rows if _row_matches(row, target)]
59
    skipped = [row for row in matched if row_returncode(row) == 77]
60
    successful = [row for row in matched if row_returncode(row) == 0]
61
    failures = [row for row in matched if row_returncode(row) not in (0, 77)]
62
    values = [value for row in successful if (value := metric_value(row, target.metric)) is not None]
63
64
    base = {
65
        "target_id": target.target_id,
66
        "verdict": "UNMEASURED",
67
        "lane": target.lane,
68
        "profile": target.profile,
69
        "scenario": target.scenario,
70
        "operation": target.operation,
71
        "subject": target.subject,
72
        "comparator": target.comparator,
73
        "metric": target.metric,
74
        "goal_type": target.goal_type,
75
        "goal_value": target.goal_value,
76
        # "n" is the number of rows that actually contributed to the statistic
77
        # (metric measured, per ADR-0002 null-means-unmeasured); "n_successful"
78
        # is the pool it was drawn from. CI consumers should read "n".
79
        "n": len(values),
80
        "n_successful": len(successful),
81
        "skip_count": len(skipped),
82
        "failure_count": len(failures),
83
        "messages": [],
84
        "mode": mode,
85
        "claim_eligible": False,
86
        "independent_n": independent_run_count(successful),
87
        "confidence": confidence,
88
        "bootstrap_samples": bootstrap_samples,
89
    }
90
91
    if not matched:
92
        base["messages"].append("no matching rows")
93
        return base
94
    if skipped and not successful and not failures:
95
        base["messages"].append("; ".join(sorted({str(row.get("skip_reason") or "skipped") for row in skipped})))
96
        return base
97
    if baseline is None:
98
        base["messages"].append("missing baseline cell")
99
        return base
100
101
    guard_errors = guard_violations(matched, successful, failures, target.guards)
102
    # Outcome denominators are part of the experiment, not a separate identity
103
    # population. Failed/skipped trials cannot silently come from another host.
104
    conflicts = population_conflicts(matched)
105
    if conflicts:
106
        guard_errors.append(f"incompatible measurement population: {', '.join(conflicts)}")
107
    candidate_identity = comparison_identity(successful[0]) if successful else None
108
    if baseline.comparison_identity is not None and candidate_identity is not None:
109
        mismatch = comparison_conflicts(baseline.comparison_identity, candidate_identity)
110
        if mismatch:
111
            guard_errors.append(f"baseline comparison identity mismatch: {', '.join(mismatch)}")
112
    if guard_errors:
113
        base.update({"verdict": "INVALID", "messages": guard_errors})
114
        return base
115
116
    if not values:
117
        base["messages"].append("metric unmeasured in matching successful rows")
118
        return base
119
    eligibility_errors = claim_eligibility_errors(successful, matched, target, baseline, confidence)
120
    base["claim_ineligibility_reasons"] = eligibility_errors
121
    if mode == "claim" and eligibility_errors:
122
        base.update(verdict="AMBER", messages=eligibility_errors)
123
        return base
124
    base["claim_eligible"] = mode == "claim"
125
    if mode == "diagnostic":
126
        base["messages"].append("diagnostic only; not eligible for public claims")
127
    unmeasured = len(successful) - len(values)
128
    if unmeasured:
129
        base["messages"].append(f"metric unmeasured on {unmeasured} of {len(successful)} successful rows")
130
    if baseline.value == 0:
131
        base.update({"verdict": "UNDECIDABLE", "messages": ["baseline value is zero; ratio target is undefined"]})
132
        return base
133
134
    observed = statistic_value(values, target.statistic)
135
    ci_low, ci_high = bootstrap_ci(
136
        values,
137
        statistic=target.statistic,
138
        samples=bootstrap_samples,
139
        confidence=confidence,
140
        seed=seed,
141
    )
142
    baseline_denominators = _baseline_denominators(baseline)
143
    if baseline_denominators is None:
144
        base.update(
145
            {
146
                "verdict": "UNDECIDABLE",
147
                "messages": ["baseline confidence interval crosses zero; ratio target is undefined"],
148
            }
149
        )
150
        return base
151
    baseline_low, baseline_high = baseline_denominators
152
    ratio = observed / baseline.value
153
    ratio_low = ci_low / baseline_high
154
    ratio_high = ci_high / baseline_low
155
    base.update(
156
        {
157
            "value": observed,
158
            "ci_low": ci_low,
159
            "ci_high": ci_high,
160
            "baseline_value": baseline.value,
161
            "baseline_ci_low": baseline.ci_low,
162
            "baseline_ci_high": baseline.ci_high,
163
            "ratio": ratio,
164
            "ratio_ci_low": ratio_low,
165
            "ratio_ci_high": ratio_high,
166
        }
167
    )
168
169
    # GREEN/RED must clear the goal by more than the baseline noise floor:
170
    # the bootstrap CI only sees within-sample variance, so a narrow CI that
171
    # lands inside the noise band is instrument luck, not a verdict (ADR-0008:
172
    # a target can never out-resolve the instrument). Decisive results — CI
173
    # bounds that survive noise inflation — stay GREEN/RED.
174
    noise = float(baseline.noise_floor_pct or 0.0) / 100.0
175
    decisively_green = ratio_high * (1.0 + noise) <= target.goal_value
176
    decisively_red = ratio_low * (1.0 - noise) > target.goal_value
177
    # Partial metric coverage caps decisive verdicts at AMBER (ADR-0008): the
178
    # statistic only saw the rows where the metric was measured, so a decisive
179
    # bound may be an artifact of which rows happened to record it. Dropping
180
    # information can never show green — and, symmetrically, missing data
181
    # cannot fail a target either, so RED is capped to AMBER as well.
182
    if (decisively_green or decisively_red) and unmeasured:
183
        required = required_n_for_relative_delta(float(baseline.noise_floor_pct or 0.0), _target_delta_pct(target), len(values))
184
        base.update({"verdict": "AMBER", "required_n": required})
185
    elif decisively_green:
186
        base["verdict"] = "GREEN"
187
    elif decisively_red:
188
        base["verdict"] = "RED"
189
    elif _noise_makes_undecidable(target, baseline):
190
        required = required_n_for_relative_delta(float(baseline.noise_floor_pct or 0.0), _target_delta_pct(target), len(values))
191
        base.update(
192
            {
193
                "verdict": "UNDECIDABLE",
194
                "required_n": required,
195
                "messages": ["target is tighter than the baseline noise floor"],
196
            }
197
        )
198
    else:
199
        required = required_n_for_relative_delta(float(baseline.noise_floor_pct or 0.0), _target_delta_pct(target), len(values))
200
        base.update({"verdict": "AMBER", "required_n": required})
201
        base["messages"].append("confidence interval straddles target")
202
    return base
203
204
205
def claim_eligibility_errors(successful, matched, target, baseline, confidence) -> list[str]:
206
    errors = []
207
    if confidence < 0.95:
208
        errors.append("candidate confidence must be at least 0.95 for claims")
209
    if (baseline.confidence is None or not math.isfinite(baseline.confidence) or
210
            not 0.95 <= baseline.confidence < 1):
211
        errors.append("recorded baseline confidence must be at least 0.95 and below 1 for claims")
212
    measured = [row for row in successful if metric_value(row, target.metric) is not None]
213
    # n=30 is a conservative eligibility floor, not a precision guarantee.
214
    minimum = max(30, {"p95": 20, "p99": 100}.get(target.statistic, 0))
215
    n = independent_run_count(measured)
216
    if n is None or n < minimum:
217
        errors.append(f"candidate requires at least {minimum} distinct recorded trials; observed {n}")
218
    if n is not None and n != len(measured):
219
        errors.append("candidate contains duplicate trial IDs")
220
    if baseline.independent_n is None or baseline.independent_n < minimum:
221
        errors.append(f"baseline requires at least {minimum} distinct recorded trials")
222
    if baseline.independent_n != baseline.n:
223
        errors.append("baseline sample count differs from distinct trial count")
224
    if len(measured) != len(matched):
225
        errors.append("candidate contains failed, skipped or unmeasured trials")
226
    if (baseline.failure_n != 0 or baseline.skipped_n != 0 or
227
            baseline.attempted_n != baseline.n):
228
        errors.append("baseline outcomes missing or contain failed, skipped or unmeasured trials")
229
    noise = baseline.noise_floor_pct
230
    if noise is None or not math.isfinite(noise) or noise < 0:
231
        errors.append("measured finite nonnegative baseline noise floor required")
232
    if (baseline.ci_low is None or baseline.ci_high is None or
233
            not all(math.isfinite(x) for x in (baseline.ci_low, baseline.ci_high)) or
234
            not baseline.ci_low <= baseline.value <= baseline.ci_high):
235
        errors.append("valid measured baseline confidence interval required")
236
    identities = [("candidate", comparison_identity(successful[0]))] if successful else []
237
    if baseline.comparison_identity is None:
238
        errors.append("versioned baseline comparison identity required")
239
    else:
240
        identities.append(("baseline", baseline.comparison_identity))
241
    for label, identity in identities:
242
        missing = missing_claim_identity(identity, target.lane, target.metric, target.operation)
243
        if any(name in target.guards for name in ("information_recall_at_least", "information_precision_at_least")):
244
            if not identity.get("output_oracle_version"):
245
                missing.append("output_oracle_version")
246
        if target.guards.get("patch_apply_ok") and not identity.get("patch_oracle_version"):
247
            missing.append("patch_oracle_version")
248
        if missing:
249
            errors.append(f"{label} claim identity missing: {', '.join(missing)}")
250
    return errors
251
252
253
def statistic_value(values: list[float], statistic: str) -> float:
254
    return float(named_statistic(statistic)(values))
255
256
257
def guard_violations(
258
    matched: list[dict[str, Any]],
259
    successful: list[dict[str, Any]],
260
    failures: list[dict[str, Any]],
261
    guards: dict[str, Any],
262
) -> list[str]:
263
    errors: list[str] = []
264
    if failures:
265
        errors.append(f"{len(failures)} matching rows failed")
266
    if "success_rate_at_least" in guards:
267
        success_rate = len(successful) / len(matched) if matched else 0.0
268
        if success_rate < float(guards["success_rate_at_least"]):
269
            errors.append(f"success_rate {success_rate:.3f} below guard {float(guards['success_rate_at_least']):.3f}")
270
    if "information_recall_at_least" in guards:
271
        _minimum_guard(successful, "information_recall", float(guards["information_recall_at_least"]), errors)
272
    if "information_precision_at_least" in guards:
273
        _minimum_guard(successful, "information_precision", float(guards["information_precision_at_least"]), errors)
274
    if guards.get("pipe_compatible_unified") is True:
275
        missing = [row for row in successful if row.get("pipe_compatible_unified") is None]
276
        bad = [row for row in successful if row.get("pipe_compatible_unified") is False]
277
        if missing:
278
            errors.append(f"{len(missing)} rows have unmeasured pipe_compatible_unified guard")
279
        if bad:
280
            errors.append(f"{len(bad)} rows failed pipe_compatible_unified guard")
281
    if guards.get("patch_apply_ok") is True:
282
        if any(row.get("patch_apply_ok") is not True for row in successful):
283
            errors.append("patch_apply_ok guard is failed or unmeasured")
284
    if guards.get("content_integrity_public_trust") is True:
285
        missing = [row for row in successful if row.get("content_integrity_check_passed") is None]
286
        failed = [row for row in successful if row.get("content_integrity_check_passed") is False]
287
        weak = [
288
            row
289
            for row in successful
290
            if row.get("content_integrity_check_passed") is True
291
            and not content_integrity_public_trust_passed(row)
292
        ]
293
        if missing:
294
            errors.append(f"{len(missing)} rows have unmeasured content_integrity_public_trust guard")
295
        if failed:
296
            errors.append(f"{len(failed)} rows failed content_integrity_public_trust guard")
297
        if weak:
298
            errors.append(f"{len(weak)} rows have weak content_integrity_source for public trust")
299
    return errors
300
301
302
def _minimum_guard(rows: list[dict[str, Any]], key: str, minimum: float, errors: list[str]) -> None:
303
    if not rows:
304
        errors.append(f"{key} guard has no successful observations")
305
        return
306
    values = [value for row in rows if (value := _number_or_none(row.get(key))) is not None]
307
    if len(values) != len(rows):
308
        errors.append(f"{key} guard is unmeasured on {len(rows) - len(values)} rows")
309
    elif min(values) < minimum:
310
        errors.append(f"{key} minimum {min(values):.3f} below guard {minimum:.3f}")
311
312
313
def _row_matches(row: dict[str, Any], target: Target) -> bool:
314
    lane = _row_lane(row)
315
    return (
316
        lane == target.lane
317
        and str(row.get("subject")) == target.subject
318
        and str(row.get("scenario")) == target.scenario
319
        and str(row.get("operation")) == target.operation
320
        and (
321
            (target.profile is None and row.get("profile") is None)
322
            or (target.profile is not None and str(row.get("profile")) == target.profile)
323
        )
324
    )
325
326
327
def _row_lane(row: dict[str, Any]) -> str | None:
328
    for key in ("lane", "benchmark_lane", "measurement_lane"):
329
        if row.get(key) is not None:
330
            return str(row[key])
331
    if "workflow" in row or "phase" in row:
332
        return "workflow"
333
    if all(key in row for key in ("token_metrics", "turn_metrics", "tool_call_metrics")):
334
        return "agent"
335
    if "contention_mode" in row or "workers" in row:
336
        return "contention"
337
    if str(row.get("scenario") or "") == "task_loop":
338
        return "task-loop"
339
    if row.get("subject_kind") is None and row.get("subject") is not None:
340
        return "mount"
341
    if all(key in row for key in ("profile", "scenario", "operation", "subject", "subject_kind", "command")):
342
        return "core"
343
    return None
344
345
346
def _noise_makes_undecidable(target: Target, baseline: BaselineCell) -> bool:
347
    if baseline.noise_floor_pct is None:
348
        return False
349
    return baseline.noise_floor_pct > _target_delta_pct(target)
350
351
352
def _baseline_denominators(baseline: BaselineCell) -> tuple[float, float] | None:
353
    low = baseline.ci_low if baseline.ci_low is not None else baseline.value
354
    high = baseline.ci_high if baseline.ci_high is not None else baseline.value
355
    if low <= 0 or high <= 0:
356
        return None
357
    return low, high
358
359
360
def _target_delta_pct(target: Target) -> float:
361
    # The margin the instrument must resolve is the distance from parity in
362
    # either direction: a goal of 1.5x demands the same 50% resolution a goal
363
    # of 0.5x does. A parity goal (1.0) has zero margin and is undecidable
364
    # whenever any noise floor exists.
365
    if target.goal_type == "ratio_at_most":
366
        return abs(1.0 - target.goal_value) * 100.0
367
    return 0.0
368
369
370
_number_or_none = number_or_none