Viewing files at commit 1c9b819ab86bCommit detailsView latest

scripts/oakbench/cellstats.py 254 lines · 10.9 KB · python
1
"""Per-cell latency verdicts: A/A floor, bootstrap CI, exact permutation p, BH-FDR.
2
3
A "cell" is one (scenario, operation) compared between two subjects in one
4
lane invocation. The old devloop gate applied ONE threshold (2x an A/A floor
5
measured on the micro profile) to every cell, so a high-variance cell could
6
publish an "improvement" of a binary over itself. Here every cell is judged on
7
its own evidence:
8
9
1. Per-cell A/A floor: an A/A control subject (the baseline binary under a
10
   second subject name, interleaved in the same randomized runs) gives each
11
   cell its own null. The floor is the largest |relative median delta| inside
12
   the A/A bootstrap interval, clamped below by ``MIN_FLOOR_PCT``.
13
2. Effect CI: percentile bootstrap of the relative median delta
14
   (target / baseline - 1). Runs share indices across subjects (interleaved),
15
   so resampling is paired by run when both arms have the same run set.
16
3. p-value: exact two-sided permutation test of the Mann-Whitney rank
17
   statistic (all C(n1+n2, n1) relabelings; seeded Monte Carlo above
18
   ``EXACT_LIMIT``).
19
4. Benjamini-Hochberg over every tested cell in the comparison family.
20
21
A cell is a CHANGE only when BH rejects AND the CI excludes zero AND the
22
whole CI lies beyond the cell's A/A floor AND the absolute delta clears the minimum
23
milliseconds. A cell whose CI and floor say "change" but which BH does not
24
confirm is UNCONFIRMED: never published as a win or a regression, reported
25
with the repetitions needed to confirm. Missing A/A evidence or fewer than
26
``MIN_SAMPLES`` per arm is UNMEASURED, never a pass.
27
"""
28
29
from __future__ import annotations
30
31
import itertools
32
import math
33
import random
34
import statistics
35
from typing import Any, Callable, Iterable
36
37
from oakbench.stats import benjamini_hochberg_detail, required_n_for_relative_delta
38
39
CELL_STATS_VERSION = "2026-09-27.1"
40
MIN_FLOOR_PCT = 3.0
41
MIN_SAMPLES = 3
42
EXACT_LIMIT = 20_000
43
DEFAULT_FDR = 0.05
44
DEFAULT_CONFIDENCE = 0.95
45
DEFAULT_BOOTSTRAP = 2000
46
47
CellKey = tuple[str, str]
48
49
50
def samples_by_cell(
51
    rows: Iterable[dict[str, Any]],
52
    subject: str,
53
    value_of: Callable[[dict[str, Any]], Any],
54
    *,
55
    include: Callable[[dict[str, Any]], bool] | None = None,
56
) -> dict[CellKey, dict[int, float]]:
57
    """{(scenario, operation): {run: value}} for successful measured rows."""
58
    cells: dict[CellKey, dict[int, float]] = {}
59
    for row in rows:
60
        if row.get("subject") != subject or row.get("skipped"):
61
            continue
62
        if row.get("returncode") not in (0, None) or (include is not None and not include(row)):
63
            continue
64
        value = value_of(row)
65
        if type(value) not in (int, float) or not math.isfinite(value):
66
            continue
67
        key = (str(row.get("scenario")), str(row.get("operation")))
68
        run = row.get("run")
69
        run_key = run if type(run) is int else len(cells.get(key, {}))
70
        cells.setdefault(key, {})[run_key] = float(value)
71
    return cells
72
73
74
def relative_delta_pct(baseline: list[float], target: list[float]) -> float | None:
75
    base = statistics.median(baseline)
76
    if base <= 0:
77
        return None
78
    return (statistics.median(target) / base - 1.0) * 100.0
79
80
81
def bootstrap_relative_ci(
82
    baseline: dict[int, float],
83
    target: dict[int, float],
84
    *,
85
    samples: int = DEFAULT_BOOTSTRAP,
86
    confidence: float = DEFAULT_CONFIDENCE,
87
    seed: int = 20260927,
88
) -> tuple[float, float] | None:
89
    rng = random.Random(seed)
90
    paired = sorted(baseline) == sorted(target)
91
    runs = sorted(baseline)
92
    base_values = list(baseline.values())
93
    target_values = list(target.values())
94
    estimates = []
95
    for _ in range(samples):
96
        if paired:
97
            chosen = [runs[rng.randrange(len(runs))] for _ in runs]
98
            b = [baseline[run] for run in chosen]
99
            t = [target[run] for run in chosen]
100
        else:
101
            b = [base_values[rng.randrange(len(base_values))] for _ in base_values]
102
            t = [target_values[rng.randrange(len(target_values))] for _ in target_values]
103
        value = relative_delta_pct(b, t)
104
        if value is not None:
105
            estimates.append(value)
106
    if not estimates:
107
        return None
108
    estimates.sort()
109
    alpha = 1.0 - confidence
110
    low = estimates[max(0, math.floor(alpha / 2 * len(estimates)))]
111
    high = estimates[min(len(estimates) - 1, math.ceil((1 - alpha / 2) * len(estimates)) - 1)]
112
    return low, high
113
114
115
def _mann_whitney_u(baseline: list[float], target: list[float]) -> float:
116
    """U statistic of target over baseline (ties count one half)."""
117
    return sum(1.0 if t > b else 0.5 if t == b else 0.0 for t in target for b in baseline)
118
119
120
def permutation_p_value(baseline: list[float], target: list[float], *, seed: int = 20260927,
121
                        exact_limit: int = EXACT_LIMIT) -> float:
122
    """Exact two-sided permutation p for the Mann-Whitney rank statistic.
123
124
    Rank-based, so one stalled sample cannot manufacture significance; exact
125
    over all C(n1+n2, n1) relabelings (min p = 2/252 at 5 vs 5), seeded Monte
126
    Carlo above ``exact_limit``.
127
    """
128
    pooled = list(baseline) + list(target)
129
    n1 = len(baseline)
130
    centre = n1 * len(target) / 2.0
131
    observed = abs(_mann_whitney_u(baseline, target) - centre)
132
    tolerance = 1e-9
133
    total = math.comb(len(pooled), n1)
134
    extreme = 0
135
    if total <= exact_limit:
136
        indices = range(len(pooled))
137
        for chosen in itertools.combinations(indices, n1):
138
            picked = set(chosen)
139
            a = [pooled[i] for i in chosen]
140
            b = [pooled[i] for i in indices if i not in picked]
141
            if abs(_mann_whitney_u(a, b) - centre) >= observed - tolerance:
142
                extreme += 1
143
        return extreme / total
144
    rng = random.Random(seed)
145
    draws = exact_limit
146
    for _ in range(draws):
147
        shuffled = pooled[:]
148
        rng.shuffle(shuffled)
149
        if abs(_mann_whitney_u(shuffled[:n1], shuffled[n1:]) - centre) >= observed - tolerance:
150
            extreme += 1
151
    return (extreme + 1) / (draws + 1)
152
153
154
def aa_floor_pct(baseline: dict[int, float], control: dict[int, float], **kwargs: Any) -> float | None:
155
    """Per-cell A/A floor: largest |delta| the identical binary shows here."""
156
    if len(baseline) < MIN_SAMPLES or len(control) < MIN_SAMPLES:
157
        return None
158
    point = relative_delta_pct(list(baseline.values()), list(control.values()))
159
    interval = bootstrap_relative_ci(baseline, control, **kwargs)
160
    if point is None or interval is None:
161
        return None
162
    return max(MIN_FLOOR_PCT, abs(point), abs(interval[0]), abs(interval[1]))
163
164
165
def cell_floors(rows: list[dict[str, Any]], baseline: str, control: str,
166
                value_of: Callable[[dict[str, Any]], Any], **kwargs: Any) -> dict[CellKey, float]:
167
    base = samples_by_cell(rows, baseline, value_of)
168
    other = samples_by_cell(rows, control, value_of)
169
    floors = {}
170
    for key in sorted(set(base) & set(other)):
171
        floor = aa_floor_pct(base[key], other[key], **kwargs)
172
        if floor is not None:
173
            floors[key] = floor
174
    return floors
175
176
177
def classify_cells(
178
    rows: list[dict[str, Any]],
179
    target: str,
180
    baseline: str,
181
    floors: dict[CellKey, float],
182
    *,
183
    value_of: Callable[[dict[str, Any]], Any] = lambda row: row.get("elapsed_ms"),
184
    cells: Iterable[CellKey] | None = None,
185
    min_delta_ms: float = 0.0,
186
    fdr: float = DEFAULT_FDR,
187
    confidence: float = DEFAULT_CONFIDENCE,
188
    bootstrap_samples: int = DEFAULT_BOOTSTRAP,
189
    seed: int = 20260927,
190
) -> dict[CellKey, dict[str, Any]]:
191
    """Per-cell verdict dicts for one comparison family (see module doc)."""
192
    base_cells = samples_by_cell(rows, baseline, value_of)
193
    target_cells = samples_by_cell(rows, target, value_of)
194
    keys = sorted(set(cells) if cells is not None else (set(base_cells) | set(target_cells)))
195
    results: dict[CellKey, dict[str, Any]] = {}
196
    tested: list[CellKey] = []
197
    p_values: list[float] = []
198
    for key in keys:
199
        base = base_cells.get(key, {})
200
        cand = target_cells.get(key, {})
201
        item: dict[str, Any] = {
202
            "cell_stats_version": CELL_STATS_VERSION, "scenario": key[0], "operation": key[1],
203
            "baseline_n": len(base), "target_n": len(cand), "floor_pct": floors.get(key),
204
            "baseline_median": statistics.median(base.values()) if base else None,
205
            "target_median": statistics.median(cand.values()) if cand else None,
206
            "delta_pct": None, "ci_low_pct": None, "ci_high_pct": None, "p_value": None,
207
            "fdr_rejected": None, "verdict": "unmeasured", "reason": None,
208
        }
209
        results[key] = item
210
        if len(base) < MIN_SAMPLES or len(cand) < MIN_SAMPLES:
211
            item["reason"] = f"fewer than {MIN_SAMPLES} measured runs per arm"
212
            continue
213
        delta = relative_delta_pct(list(base.values()), list(cand.values()))
214
        interval = bootstrap_relative_ci(base, cand, samples=bootstrap_samples, confidence=confidence, seed=seed)
215
        if delta is None or interval is None:
216
            item["reason"] = "baseline median is zero"
217
            continue
218
        item.update(delta_pct=delta, ci_low_pct=interval[0], ci_high_pct=interval[1],
219
                    p_value=permutation_p_value(list(base.values()), list(cand.values()), seed=seed))
220
        tested.append(key)
221
        p_values.append(item["p_value"])
222
    bh = benjamini_hochberg_detail(p_values, fdr=fdr)
223
    for key, rejected in zip(tested, bh["rejected"]):
224
        item = results[key]
225
        item["fdr_rejected"] = rejected
226
        floor = item["floor_pct"]
227
        excludes_zero = item["ci_low_pct"] > 0 or item["ci_high_pct"] < 0
228
        abs_ms = abs(item["target_median"] - item["baseline_median"])
229
        if floor is None:
230
            item.update(verdict="unmeasured", reason="no per-cell A/A floor for this cell")
231
            continue
232
        # The whole interval must clear the floor, not just the point estimate.
233
        near_bound = min(abs(item["ci_low_pct"]), abs(item["ci_high_pct"]))
234
        if excludes_zero and near_bound > floor and abs_ms >= min_delta_ms:
235
            direction = "regression" if item["delta_pct"] > 0 else "improvement"
236
            if rejected:
237
                item["verdict"] = direction
238
            else:
239
                item["verdict"] = "unconfirmed_" + direction
240
                item["reason"] = "not significant after Benjamini-Hochberg across the comparison family"
241
                n = min(item["baseline_n"], item["target_n"])
242
                item["required_n"] = required_n_for_relative_delta(floor, abs(item["delta_pct"]), n)
243
        else:
244
            item["verdict"] = "no_change"
245
    return results
246
247
248
def describe(item: dict[str, Any], label: str) -> str:
249
    def pct(value: float | None) -> str:
250
        return "?" if value is None else f"{value:+.1f}%"
251
    return (f"`{item['scenario']}/{item['operation']}` vs {label}: {pct(item['delta_pct'])} "
252
            f"({item['baseline_median']:.1f} -> {item['target_median']:.1f} ms; "
253
            f"95% CI [{pct(item['ci_low_pct'])}, {pct(item['ci_high_pct'])}], "
254
            f"A/A floor {item['floor_pct']:.1f}%, p={item['p_value']:.4f}, n={item['baseline_n']}/{item['target_n']})")