Viewing files at commit 25881039a2bbCommit detailsView latest

scripts/oakbench/scorecard.py 284 lines · 11.4 KB · python
1
"""Target scorecard evaluation."""
2
3
from __future__ import annotations
4
5
from typing import Any
6
7
from oakbench.baseline_book import BaselineCell, Target, iter_jsonl, metric_value
8
from oakbench.integrity import content_integrity_public_trust_passed
9
from oakbench.rows import number_or_none, row_returncode
10
from oakbench.stats import bootstrap_ci, named_statistic, required_n_for_relative_delta
11
12
VERDICTS = ("GREEN", "RED", "AMBER", "UNDECIDABLE", "UNMEASURED", "INVALID")
13
14
# One JSONL loader for scorecard inputs; baseline_book owns the implementation.
15
load_jsonl = iter_jsonl
16
17
18
def evaluate_targets(
19
    rows: list[dict[str, Any]],
20
    targets: list[Target],
21
    baseline: dict[tuple[str, str | None, str, str, str, str, str], BaselineCell],
22
    *,
23
    bootstrap_samples: int = 2000,
24
    confidence: float = 0.95,
25
    seed: int = 20260609,
26
) -> list[dict[str, Any]]:
27
    return [
28
        evaluate_target(
29
            rows,
30
            target,
31
            baseline.get(target.baseline_key),
32
            bootstrap_samples=bootstrap_samples,
33
            confidence=confidence,
34
            seed=seed,
35
        )
36
        for target in targets
37
    ]
38
39
40
def evaluate_target(
41
    rows: list[dict[str, Any]],
42
    target: Target,
43
    baseline: BaselineCell | None,
44
    *,
45
    bootstrap_samples: int,
46
    confidence: float,
47
    seed: int,
48
) -> dict[str, Any]:
49
    matched = [row for row in rows if _row_matches(row, target)]
50
    skipped = [row for row in matched if row_returncode(row) == 77]
51
    successful = [row for row in matched if row_returncode(row) == 0]
52
    failures = [row for row in matched if row_returncode(row) not in (0, 77)]
53
    values = [value for row in successful if (value := metric_value(row, target.metric)) is not None]
54
55
    base = {
56
        "target_id": target.target_id,
57
        "verdict": "UNMEASURED",
58
        "lane": target.lane,
59
        "profile": target.profile,
60
        "scenario": target.scenario,
61
        "operation": target.operation,
62
        "subject": target.subject,
63
        "comparator": target.comparator,
64
        "metric": target.metric,
65
        "goal_type": target.goal_type,
66
        "goal_value": target.goal_value,
67
        # "n" is the number of rows that actually contributed to the statistic
68
        # (metric measured, per ADR-0002 null-means-unmeasured); "n_successful"
69
        # is the pool it was drawn from. CI consumers should read "n".
70
        "n": len(values),
71
        "n_successful": len(successful),
72
        "skip_count": len(skipped),
73
        "failure_count": len(failures),
74
        "messages": [],
75
    }
76
77
    if not matched:
78
        base["messages"].append("no matching rows")
79
        return base
80
    if skipped and not successful and not failures:
81
        base["messages"].append("; ".join(sorted({str(row.get("skip_reason") or "skipped") for row in skipped})))
82
        return base
83
    if baseline is None:
84
        base["messages"].append("missing baseline cell")
85
        return base
86
87
    guard_errors = guard_violations(matched, successful, failures, target.guards)
88
    if guard_errors:
89
        base.update({"verdict": "INVALID", "messages": guard_errors})
90
        return base
91
92
    if not values:
93
        base["messages"].append("metric unmeasured in matching successful rows")
94
        return base
95
    unmeasured = len(successful) - len(values)
96
    if unmeasured:
97
        base["messages"].append(f"metric unmeasured on {unmeasured} of {len(successful)} successful rows")
98
    if baseline.value == 0:
99
        base.update({"verdict": "UNDECIDABLE", "messages": ["baseline value is zero; ratio target is undefined"]})
100
        return base
101
102
    observed = statistic_value(values, target.statistic)
103
    ci_low, ci_high = bootstrap_ci(
104
        values,
105
        statistic=target.statistic,
106
        samples=bootstrap_samples,
107
        confidence=confidence,
108
        seed=seed,
109
    )
110
    baseline_denominators = _baseline_denominators(baseline)
111
    if baseline_denominators is None:
112
        base.update(
113
            {
114
                "verdict": "UNDECIDABLE",
115
                "messages": ["baseline confidence interval crosses zero; ratio target is undefined"],
116
            }
117
        )
118
        return base
119
    baseline_low, baseline_high = baseline_denominators
120
    ratio = observed / baseline.value
121
    ratio_low = ci_low / baseline_high
122
    ratio_high = ci_high / baseline_low
123
    base.update(
124
        {
125
            "value": observed,
126
            "ci_low": ci_low,
127
            "ci_high": ci_high,
128
            "baseline_value": baseline.value,
129
            "baseline_ci_low": baseline.ci_low,
130
            "baseline_ci_high": baseline.ci_high,
131
            "ratio": ratio,
132
            "ratio_ci_low": ratio_low,
133
            "ratio_ci_high": ratio_high,
134
        }
135
    )
136
137
    # GREEN/RED must clear the goal by more than the baseline noise floor:
138
    # the bootstrap CI only sees within-sample variance, so a narrow CI that
139
    # lands inside the noise band is instrument luck, not a verdict (ADR-0008:
140
    # a target can never out-resolve the instrument). Decisive results — CI
141
    # bounds that survive noise inflation — stay GREEN/RED.
142
    noise = float(baseline.noise_floor_pct or 0.0) / 100.0
143
    decisively_green = ratio_high * (1.0 + noise) <= target.goal_value
144
    decisively_red = ratio_low * (1.0 - noise) > target.goal_value
145
    # Partial metric coverage caps decisive verdicts at AMBER (ADR-0008): the
146
    # statistic only saw the rows where the metric was measured, so a decisive
147
    # bound may be an artifact of which rows happened to record it. Dropping
148
    # information can never show green — and, symmetrically, missing data
149
    # cannot fail a target either, so RED is capped to AMBER as well.
150
    if (decisively_green or decisively_red) and unmeasured:
151
        required = required_n_for_relative_delta(float(baseline.noise_floor_pct or 0.0), _target_delta_pct(target), len(values))
152
        base.update({"verdict": "AMBER", "required_n": required})
153
    elif decisively_green:
154
        base["verdict"] = "GREEN"
155
    elif decisively_red:
156
        base["verdict"] = "RED"
157
    elif _noise_makes_undecidable(target, baseline):
158
        required = required_n_for_relative_delta(float(baseline.noise_floor_pct or 0.0), _target_delta_pct(target), len(values))
159
        base.update(
160
            {
161
                "verdict": "UNDECIDABLE",
162
                "required_n": required,
163
                "messages": ["target is tighter than the baseline noise floor"],
164
            }
165
        )
166
    else:
167
        required = required_n_for_relative_delta(float(baseline.noise_floor_pct or 0.0), _target_delta_pct(target), len(values))
168
        base.update({"verdict": "AMBER", "required_n": required})
169
        base["messages"].append("confidence interval straddles target")
170
    return base
171
172
173
def statistic_value(values: list[float], statistic: str) -> float:
174
    return float(named_statistic(statistic)(values))
175
176
177
def guard_violations(
178
    matched: list[dict[str, Any]],
179
    successful: list[dict[str, Any]],
180
    failures: list[dict[str, Any]],
181
    guards: dict[str, Any],
182
) -> list[str]:
183
    errors: list[str] = []
184
    if failures:
185
        errors.append(f"{len(failures)} matching rows failed")
186
    if "success_rate_at_least" in guards:
187
        success_rate = len(successful) / len(matched) if matched else 0.0
188
        if success_rate < float(guards["success_rate_at_least"]):
189
            errors.append(f"success_rate {success_rate:.3f} below guard {float(guards['success_rate_at_least']):.3f}")
190
    if "information_recall_at_least" in guards:
191
        _minimum_guard(successful, "information_recall", float(guards["information_recall_at_least"]), errors)
192
    if "information_precision_at_least" in guards:
193
        _minimum_guard(successful, "information_precision", float(guards["information_precision_at_least"]), errors)
194
    if guards.get("pipe_compatible_unified") is True:
195
        missing = [row for row in successful if row.get("pipe_compatible_unified") is None]
196
        bad = [row for row in successful if row.get("pipe_compatible_unified") is False]
197
        if missing:
198
            errors.append(f"{len(missing)} rows have unmeasured pipe_compatible_unified guard")
199
        if bad:
200
            errors.append(f"{len(bad)} rows failed pipe_compatible_unified guard")
201
    if guards.get("content_integrity_public_trust") is True:
202
        missing = [row for row in successful if row.get("content_integrity_check_passed") is None]
203
        failed = [row for row in successful if row.get("content_integrity_check_passed") is False]
204
        weak = [
205
            row
206
            for row in successful
207
            if row.get("content_integrity_check_passed") is True
208
            and not content_integrity_public_trust_passed(row)
209
        ]
210
        if missing:
211
            errors.append(f"{len(missing)} rows have unmeasured content_integrity_public_trust guard")
212
        if failed:
213
            errors.append(f"{len(failed)} rows failed content_integrity_public_trust guard")
214
        if weak:
215
            errors.append(f"{len(weak)} rows have weak content_integrity_source for public trust")
216
    return errors
217
218
219
def _minimum_guard(rows: list[dict[str, Any]], key: str, minimum: float, errors: list[str]) -> None:
220
    values = [value for row in rows if (value := _number_or_none(row.get(key))) is not None]
221
    if len(values) != len(rows):
222
        errors.append(f"{key} guard is unmeasured on {len(rows) - len(values)} rows")
223
    elif min(values) < minimum:
224
        errors.append(f"{key} minimum {min(values):.3f} below guard {minimum:.3f}")
225
226
227
def _row_matches(row: dict[str, Any], target: Target) -> bool:
228
    lane = _row_lane(row)
229
    return (
230
        lane == target.lane
231
        and str(row.get("subject")) == target.subject
232
        and str(row.get("scenario")) == target.scenario
233
        and str(row.get("operation")) == target.operation
234
        and (
235
            (target.profile is None and row.get("profile") is None)
236
            or (target.profile is not None and str(row.get("profile")) == target.profile)
237
        )
238
    )
239
240
241
def _row_lane(row: dict[str, Any]) -> str | None:
242
    for key in ("lane", "benchmark_lane", "measurement_lane"):
243
        if row.get(key) is not None:
244
            return str(row[key])
245
    if "workflow" in row or "phase" in row:
246
        return "workflow"
247
    if all(key in row for key in ("token_metrics", "turn_metrics", "tool_call_metrics")):
248
        return "agent"
249
    if "contention_mode" in row or "workers" in row:
250
        return "contention"
251
    if str(row.get("scenario") or "") == "task_loop":
252
        return "task-loop"
253
    if row.get("subject_kind") is None and row.get("subject") is not None:
254
        return "mount"
255
    if all(key in row for key in ("profile", "scenario", "operation", "subject", "subject_kind", "command")):
256
        return "core"
257
    return None
258
259
260
def _noise_makes_undecidable(target: Target, baseline: BaselineCell) -> bool:
261
    if baseline.noise_floor_pct is None:
262
        return False
263
    return baseline.noise_floor_pct > _target_delta_pct(target)
264
265
266
def _baseline_denominators(baseline: BaselineCell) -> tuple[float, float] | None:
267
    low = baseline.ci_low if baseline.ci_low is not None else baseline.value
268
    high = baseline.ci_high if baseline.ci_high is not None else baseline.value
269
    if low <= 0 or high <= 0:
270
        return None
271
    return low, high
272
273
274
def _target_delta_pct(target: Target) -> float:
275
    # The margin the instrument must resolve is the distance from parity in
276
    # either direction: a goal of 1.5x demands the same 50% resolution a goal
277
    # of 0.5x does. A parity goal (1.0) has zero margin and is undecidable
278
    # whenever any noise floor exists.
279
    if target.goal_type == "ratio_at_most":
280
        return abs(1.0 - target.goal_value) * 100.0
281
    return 0.0
282
283
284
_number_or_none = number_or_none