Viewing files at commit b297e8a25d08Commit detailsView latest

scripts/oakbench/scorecard.py 368 lines · 16.3 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
    conflicts = population_conflicts(successful)
103
    if conflicts:
104
        guard_errors.append(f"incompatible measurement population: {', '.join(conflicts)}")
105
    candidate_identity = comparison_identity(successful[0]) if successful else None
106
    if baseline.comparison_identity is not None and candidate_identity is not None:
107
        mismatch = comparison_conflicts(baseline.comparison_identity, candidate_identity)
108
        if mismatch:
109
            guard_errors.append(f"baseline comparison identity mismatch: {', '.join(mismatch)}")
110
    if guard_errors:
111
        base.update({"verdict": "INVALID", "messages": guard_errors})
112
        return base
113
114
    if not values:
115
        base["messages"].append("metric unmeasured in matching successful rows")
116
        return base
117
    eligibility_errors = claim_eligibility_errors(successful, matched, target, baseline, confidence)
118
    base["claim_ineligibility_reasons"] = eligibility_errors
119
    if mode == "claim" and eligibility_errors:
120
        base.update(verdict="AMBER", messages=eligibility_errors)
121
        return base
122
    base["claim_eligible"] = mode == "claim"
123
    if mode == "diagnostic":
124
        base["messages"].append("diagnostic only; not eligible for public claims")
125
    unmeasured = len(successful) - len(values)
126
    if unmeasured:
127
        base["messages"].append(f"metric unmeasured on {unmeasured} of {len(successful)} successful rows")
128
    if baseline.value == 0:
129
        base.update({"verdict": "UNDECIDABLE", "messages": ["baseline value is zero; ratio target is undefined"]})
130
        return base
131
132
    observed = statistic_value(values, target.statistic)
133
    ci_low, ci_high = bootstrap_ci(
134
        values,
135
        statistic=target.statistic,
136
        samples=bootstrap_samples,
137
        confidence=confidence,
138
        seed=seed,
139
    )
140
    baseline_denominators = _baseline_denominators(baseline)
141
    if baseline_denominators is None:
142
        base.update(
143
            {
144
                "verdict": "UNDECIDABLE",
145
                "messages": ["baseline confidence interval crosses zero; ratio target is undefined"],
146
            }
147
        )
148
        return base
149
    baseline_low, baseline_high = baseline_denominators
150
    ratio = observed / baseline.value
151
    ratio_low = ci_low / baseline_high
152
    ratio_high = ci_high / baseline_low
153
    base.update(
154
        {
155
            "value": observed,
156
            "ci_low": ci_low,
157
            "ci_high": ci_high,
158
            "baseline_value": baseline.value,
159
            "baseline_ci_low": baseline.ci_low,
160
            "baseline_ci_high": baseline.ci_high,
161
            "ratio": ratio,
162
            "ratio_ci_low": ratio_low,
163
            "ratio_ci_high": ratio_high,
164
        }
165
    )
166
167
    # GREEN/RED must clear the goal by more than the baseline noise floor:
168
    # the bootstrap CI only sees within-sample variance, so a narrow CI that
169
    # lands inside the noise band is instrument luck, not a verdict (ADR-0008:
170
    # a target can never out-resolve the instrument). Decisive results — CI
171
    # bounds that survive noise inflation — stay GREEN/RED.
172
    noise = float(baseline.noise_floor_pct or 0.0) / 100.0
173
    decisively_green = ratio_high * (1.0 + noise) <= target.goal_value
174
    decisively_red = ratio_low * (1.0 - noise) > target.goal_value
175
    # Partial metric coverage caps decisive verdicts at AMBER (ADR-0008): the
176
    # statistic only saw the rows where the metric was measured, so a decisive
177
    # bound may be an artifact of which rows happened to record it. Dropping
178
    # information can never show green — and, symmetrically, missing data
179
    # cannot fail a target either, so RED is capped to AMBER as well.
180
    if (decisively_green or decisively_red) and unmeasured:
181
        required = required_n_for_relative_delta(float(baseline.noise_floor_pct or 0.0), _target_delta_pct(target), len(values))
182
        base.update({"verdict": "AMBER", "required_n": required})
183
    elif decisively_green:
184
        base["verdict"] = "GREEN"
185
    elif decisively_red:
186
        base["verdict"] = "RED"
187
    elif _noise_makes_undecidable(target, baseline):
188
        required = required_n_for_relative_delta(float(baseline.noise_floor_pct or 0.0), _target_delta_pct(target), len(values))
189
        base.update(
190
            {
191
                "verdict": "UNDECIDABLE",
192
                "required_n": required,
193
                "messages": ["target is tighter than the baseline noise floor"],
194
            }
195
        )
196
    else:
197
        required = required_n_for_relative_delta(float(baseline.noise_floor_pct or 0.0), _target_delta_pct(target), len(values))
198
        base.update({"verdict": "AMBER", "required_n": required})
199
        base["messages"].append("confidence interval straddles target")
200
    return base
201
202
203
def claim_eligibility_errors(successful, matched, target, baseline, confidence) -> list[str]:
204
    errors = []
205
    if confidence < 0.95:
206
        errors.append("candidate confidence must be at least 0.95 for claims")
207
    if (baseline.confidence is None or not math.isfinite(baseline.confidence) or
208
            not 0.95 <= baseline.confidence < 1):
209
        errors.append("recorded baseline confidence must be at least 0.95 and below 1 for claims")
210
    measured = [row for row in successful if metric_value(row, target.metric) is not None]
211
    # n=30 is a conservative eligibility floor, not a precision guarantee.
212
    minimum = max(30, {"p95": 20, "p99": 100}.get(target.statistic, 0))
213
    n = independent_run_count(measured)
214
    if n is None or n < minimum:
215
        errors.append(f"candidate requires at least {minimum} distinct recorded trials; observed {n}")
216
    if n is not None and n != len(measured):
217
        errors.append("candidate contains duplicate trial IDs")
218
    if baseline.independent_n is None or baseline.independent_n < minimum:
219
        errors.append(f"baseline requires at least {minimum} distinct recorded trials")
220
    if baseline.independent_n != baseline.n:
221
        errors.append("baseline sample count differs from distinct trial count")
222
    if len(measured) != len(matched):
223
        errors.append("candidate contains failed, skipped or unmeasured trials")
224
    if (baseline.failure_n != 0 or baseline.skipped_n != 0 or
225
            baseline.attempted_n != baseline.n):
226
        errors.append("baseline outcomes missing or contain failed, skipped or unmeasured trials")
227
    noise = baseline.noise_floor_pct
228
    if noise is None or not math.isfinite(noise) or noise < 0:
229
        errors.append("measured finite nonnegative baseline noise floor required")
230
    if (baseline.ci_low is None or baseline.ci_high is None or
231
            not all(math.isfinite(x) for x in (baseline.ci_low, baseline.ci_high)) or
232
            not baseline.ci_low <= baseline.value <= baseline.ci_high):
233
        errors.append("valid measured baseline confidence interval required")
234
    identities = [("candidate", comparison_identity(successful[0]))] if successful else []
235
    if baseline.comparison_identity is None:
236
        errors.append("versioned baseline comparison identity required")
237
    else:
238
        identities.append(("baseline", baseline.comparison_identity))
239
    for label, identity in identities:
240
        missing = missing_claim_identity(identity, target.lane, target.metric, target.operation)
241
        if any(name in target.guards for name in ("information_recall_at_least", "information_precision_at_least")):
242
            if not identity.get("output_oracle_version"):
243
                missing.append("output_oracle_version")
244
        if target.guards.get("patch_apply_ok") and not identity.get("patch_oracle_version"):
245
            missing.append("patch_oracle_version")
246
        if missing:
247
            errors.append(f"{label} claim identity missing: {', '.join(missing)}")
248
    return errors
249
250
251
def statistic_value(values: list[float], statistic: str) -> float:
252
    return float(named_statistic(statistic)(values))
253
254
255
def guard_violations(
256
    matched: list[dict[str, Any]],
257
    successful: list[dict[str, Any]],
258
    failures: list[dict[str, Any]],
259
    guards: dict[str, Any],
260
) -> list[str]:
261
    errors: list[str] = []
262
    if failures:
263
        errors.append(f"{len(failures)} matching rows failed")
264
    if "success_rate_at_least" in guards:
265
        success_rate = len(successful) / len(matched) if matched else 0.0
266
        if success_rate < float(guards["success_rate_at_least"]):
267
            errors.append(f"success_rate {success_rate:.3f} below guard {float(guards['success_rate_at_least']):.3f}")
268
    if "information_recall_at_least" in guards:
269
        _minimum_guard(successful, "information_recall", float(guards["information_recall_at_least"]), errors)
270
    if "information_precision_at_least" in guards:
271
        _minimum_guard(successful, "information_precision", float(guards["information_precision_at_least"]), errors)
272
    if guards.get("pipe_compatible_unified") is True:
273
        missing = [row for row in successful if row.get("pipe_compatible_unified") is None]
274
        bad = [row for row in successful if row.get("pipe_compatible_unified") is False]
275
        if missing:
276
            errors.append(f"{len(missing)} rows have unmeasured pipe_compatible_unified guard")
277
        if bad:
278
            errors.append(f"{len(bad)} rows failed pipe_compatible_unified guard")
279
    if guards.get("patch_apply_ok") is True:
280
        if any(row.get("patch_apply_ok") is not True for row in successful):
281
            errors.append("patch_apply_ok guard is failed or unmeasured")
282
    if guards.get("content_integrity_public_trust") is True:
283
        missing = [row for row in successful if row.get("content_integrity_check_passed") is None]
284
        failed = [row for row in successful if row.get("content_integrity_check_passed") is False]
285
        weak = [
286
            row
287
            for row in successful
288
            if row.get("content_integrity_check_passed") is True
289
            and not content_integrity_public_trust_passed(row)
290
        ]
291
        if missing:
292
            errors.append(f"{len(missing)} rows have unmeasured content_integrity_public_trust guard")
293
        if failed:
294
            errors.append(f"{len(failed)} rows failed content_integrity_public_trust guard")
295
        if weak:
296
            errors.append(f"{len(weak)} rows have weak content_integrity_source for public trust")
297
    return errors
298
299
300
def _minimum_guard(rows: list[dict[str, Any]], key: str, minimum: float, errors: list[str]) -> None:
301
    if not rows:
302
        errors.append(f"{key} guard has no successful observations")
303
        return
304
    values = [value for row in rows if (value := _number_or_none(row.get(key))) is not None]
305
    if len(values) != len(rows):
306
        errors.append(f"{key} guard is unmeasured on {len(rows) - len(values)} rows")
307
    elif min(values) < minimum:
308
        errors.append(f"{key} minimum {min(values):.3f} below guard {minimum:.3f}")
309
310
311
def _row_matches(row: dict[str, Any], target: Target) -> bool:
312
    lane = _row_lane(row)
313
    return (
314
        lane == target.lane
315
        and str(row.get("subject")) == target.subject
316
        and str(row.get("scenario")) == target.scenario
317
        and str(row.get("operation")) == target.operation
318
        and (
319
            (target.profile is None and row.get("profile") is None)
320
            or (target.profile is not None and str(row.get("profile")) == target.profile)
321
        )
322
    )
323
324
325
def _row_lane(row: dict[str, Any]) -> str | None:
326
    for key in ("lane", "benchmark_lane", "measurement_lane"):
327
        if row.get(key) is not None:
328
            return str(row[key])
329
    if "workflow" in row or "phase" in row:
330
        return "workflow"
331
    if all(key in row for key in ("token_metrics", "turn_metrics", "tool_call_metrics")):
332
        return "agent"
333
    if "contention_mode" in row or "workers" in row:
334
        return "contention"
335
    if str(row.get("scenario") or "") == "task_loop":
336
        return "task-loop"
337
    if row.get("subject_kind") is None and row.get("subject") is not None:
338
        return "mount"
339
    if all(key in row for key in ("profile", "scenario", "operation", "subject", "subject_kind", "command")):
340
        return "core"
341
    return None
342
343
344
def _noise_makes_undecidable(target: Target, baseline: BaselineCell) -> bool:
345
    if baseline.noise_floor_pct is None:
346
        return False
347
    return baseline.noise_floor_pct > _target_delta_pct(target)
348
349
350
def _baseline_denominators(baseline: BaselineCell) -> tuple[float, float] | None:
351
    low = baseline.ci_low if baseline.ci_low is not None else baseline.value
352
    high = baseline.ci_high if baseline.ci_high is not None else baseline.value
353
    if low <= 0 or high <= 0:
354
        return None
355
    return low, high
356
357
358
def _target_delta_pct(target: Target) -> float:
359
    # The margin the instrument must resolve is the distance from parity in
360
    # either direction: a goal of 1.5x demands the same 50% resolution a goal
361
    # of 0.5x does. A parity goal (1.0) has zero margin and is undecidable
362
    # whenever any noise floor exists.
363
    if target.goal_type == "ratio_at_most":
364
        return abs(1.0 - target.goal_value) * 100.0
365
    return 0.0
366
367
368
_number_or_none = number_or_none