Viewing files at commit 290f11640be1Commit detailsView latest

scripts/oakbench/cellstats.py 322 lines · 14.0 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
effect exceeds the cell's A/A floor (itself the outer A/A CI bound) 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
38
39
CELL_STATS_VERSION = "2026-09-27.2"
40
MIN_FLOOR_PCT = 3.0
41
MIN_SAMPLES = 5
42
SCREEN_P = 0.2
43
EXACT_LIMIT = 20_000
44
DEFAULT_FDR = 0.05
45
DEFAULT_CONFIDENCE = 0.95
46
DEFAULT_BOOTSTRAP = 2000
47
48
CellKey = tuple[str, str]
49
50
51
def samples_by_cell(
52
    rows: Iterable[dict[str, Any]],
53
    subject: str,
54
    value_of: Callable[[dict[str, Any]], Any],
55
    *,
56
    include: Callable[[dict[str, Any]], bool] | None = None,
57
) -> dict[CellKey, dict[int, float]]:
58
    """{(scenario, operation): {run: value}} for successful measured rows."""
59
    cells: dict[CellKey, dict[int, float]] = {}
60
    for row in rows:
61
        if row.get("subject") != subject or row.get("skipped"):
62
            continue
63
        if row.get("returncode") not in (0, None) or (include is not None and not include(row)):
64
            continue
65
        value = value_of(row)
66
        if type(value) not in (int, float) or not math.isfinite(value):
67
            continue
68
        key = (str(row.get("scenario")), str(row.get("operation")))
69
        run = row.get("run")
70
        run_key = run if type(run) is int else len(cells.get(key, {}))
71
        cells.setdefault(key, {})[run_key] = float(value)
72
    return cells
73
74
75
def relative_delta_pct(baseline: list[float], target: list[float]) -> float | None:
76
    base = statistics.median(baseline)
77
    if base <= 0:
78
        return None
79
    return (statistics.median(target) / base - 1.0) * 100.0
80
81
82
def bootstrap_relative_ci(
83
    baseline: dict[int, float],
84
    target: dict[int, float],
85
    *,
86
    samples: int = DEFAULT_BOOTSTRAP,
87
    confidence: float = DEFAULT_CONFIDENCE,
88
    seed: int = 20260927,
89
) -> tuple[float, float] | None:
90
    rng = random.Random(seed)
91
    paired = sorted(baseline) == sorted(target)
92
    runs = sorted(baseline)
93
    base_values = list(baseline.values())
94
    target_values = list(target.values())
95
    estimates = []
96
    for _ in range(samples):
97
        if paired:
98
            chosen = [runs[rng.randrange(len(runs))] for _ in runs]
99
            b = [baseline[run] for run in chosen]
100
            t = [target[run] for run in chosen]
101
        else:
102
            b = [base_values[rng.randrange(len(base_values))] for _ in base_values]
103
            t = [target_values[rng.randrange(len(target_values))] for _ in target_values]
104
        value = relative_delta_pct(b, t)
105
        if value is not None:
106
            estimates.append(value)
107
    if not estimates:
108
        return None
109
    estimates.sort()
110
    alpha = 1.0 - confidence
111
    low = estimates[max(0, math.floor(alpha / 2 * len(estimates)))]
112
    high = estimates[min(len(estimates) - 1, math.ceil((1 - alpha / 2) * len(estimates)) - 1)]
113
    return low, high
114
115
116
def _mann_whitney_u(baseline: list[float], target: list[float]) -> float:
117
    """U statistic of target over baseline (ties count one half)."""
118
    return sum(1.0 if t > b else 0.5 if t == b else 0.0 for t in target for b in baseline)
119
120
121
def permutation_p_value(baseline: list[float], target: list[float], *, seed: int = 20260927,
122
                        exact_limit: int = EXACT_LIMIT) -> float:
123
    """Exact two-sided permutation p for the Mann-Whitney rank statistic.
124
125
    Rank-based, so one stalled sample cannot manufacture significance; exact
126
    over all C(n1+n2, n1) relabelings (min p = 2/252 at 5 vs 5), seeded Monte
127
    Carlo above ``exact_limit``.
128
    """
129
    pooled = list(baseline) + list(target)
130
    n1 = len(baseline)
131
    centre = n1 * len(target) / 2.0
132
    observed = abs(_mann_whitney_u(baseline, target) - centre)
133
    tolerance = 1e-9
134
    total = math.comb(len(pooled), n1)
135
    extreme = 0
136
    if total <= exact_limit:
137
        indices = range(len(pooled))
138
        for chosen in itertools.combinations(indices, n1):
139
            picked = set(chosen)
140
            a = [pooled[i] for i in chosen]
141
            b = [pooled[i] for i in indices if i not in picked]
142
            if abs(_mann_whitney_u(a, b) - centre) >= observed - tolerance:
143
                extreme += 1
144
        return extreme / total
145
    rng = random.Random(seed)
146
    draws = exact_limit
147
    for _ in range(draws):
148
        shuffled = pooled[:]
149
        rng.shuffle(shuffled)
150
        if abs(_mann_whitney_u(shuffled[:n1], shuffled[n1:]) - centre) >= observed - tolerance:
151
            extreme += 1
152
    return (extreme + 1) / (draws + 1)
153
154
155
def min_exact_p(n1: int, n2: int) -> float:
156
    """Smallest two-sided exact permutation p-value reachable at n1 vs n2."""
157
    return min(1.0, 2.0 / math.comb(n1 + n2, n1))
158
159
160
def runs_for_bh(family_size: int, fdr: float, start: int = MIN_SAMPLES) -> int:
161
    """Runs per arm at which ONE cell can be confirmed by BH in a family of m.
162
163
    A lone change is BH-significant only if its p <= fdr / m, and the exact
164
    permutation p can never be below 2 / C(2n, n).
165
    """
166
    n = max(2, start)
167
    while min_exact_p(n, n) > fdr / max(1, family_size) and n < 200:
168
        n += 1
169
    return n
170
171
172
def required_runs(item: dict[str, Any], family_size: int, fdr: float) -> int | None:
173
    """Runs per arm to confirm this cell's observed effect: the larger of the
174
    BH feasibility bound and the n that shrinks the CI half-width inside the
175
    effect's margin over the floor (half-width scales as 1/sqrt(n))."""
176
    delta, floor = item.get("delta_pct"), item.get("floor_pct")
177
    low, high = item.get("ci_low_pct"), item.get("ci_high_pct")
178
    n = min(item.get("baseline_n") or 0, item.get("target_n") or 0)
179
    if None in (delta, floor, low, high) or n < 2:
180
        return None
181
    if abs(delta) <= floor:
182
        return None  # the observed effect is inside the noise floor; no n confirms it
183
    half = (high - low) / 2.0
184
    n_ci = math.ceil(n * (half / abs(delta)) ** 2) if half > 0 else n
185
    return max(n + 1, n_ci, runs_for_bh(family_size, fdr, n))
186
187
188
def minimum_detectable_effect_pct(item: dict[str, Any]) -> float | None:
189
    """Smallest true |effect| this cell could have confirmed at its n: the
190
    point effect must exceed the floor AND the CI (half-width h) must exclude
191
    zero, so MDE ~= max(floor, h)."""
192
    floor, low, high = item.get("floor_pct"), item.get("ci_low_pct"), item.get("ci_high_pct")
193
    if None in (floor, low, high):
194
        return None
195
    return max(floor, (high - low) / 2.0)
196
197
198
def screen_candidates(cells: dict[CellKey, dict[str, Any]], *, target_mde_pct: float,
199
                      screen_p: float = SCREEN_P) -> list[CellKey]:
200
    """Cells worth an independent confirmation run: anything suggestive
201
    (p <= screen_p, CI excluding zero, a stage-1 change or unconfirmed
202
    candidate) or too imprecise to rule out ``target_mde_pct``."""
203
    chosen = []
204
    for key, item in cells.items():
205
        if item.get("p_value") is None:
206
            continue
207
        excludes_zero = item["ci_low_pct"] > 0 or item["ci_high_pct"] < 0
208
        mde = item.get("mde_pct")
209
        if (item["verdict"] != "no_change" or item["p_value"] <= screen_p or excludes_zero
210
                or (mde is not None and mde > target_mde_pct)):
211
            chosen.append(key)
212
    return chosen
213
214
215
def aa_floor_pct(baseline: dict[int, float], control: dict[int, float], **kwargs: Any) -> float | None:
216
    """Per-cell A/A floor: largest |delta| the identical binary shows here."""
217
    if len(baseline) < MIN_SAMPLES or len(control) < MIN_SAMPLES:
218
        return None
219
    point = relative_delta_pct(list(baseline.values()), list(control.values()))
220
    interval = bootstrap_relative_ci(baseline, control, **kwargs)
221
    if point is None or interval is None:
222
        return None
223
    return max(MIN_FLOOR_PCT, abs(point), abs(interval[0]), abs(interval[1]))
224
225
226
def cell_floors(rows: list[dict[str, Any]], baseline: str, control: str,
227
                value_of: Callable[[dict[str, Any]], Any], **kwargs: Any) -> dict[CellKey, float]:
228
    base = samples_by_cell(rows, baseline, value_of)
229
    other = samples_by_cell(rows, control, value_of)
230
    floors = {}
231
    for key in sorted(set(base) & set(other)):
232
        floor = aa_floor_pct(base[key], other[key], **kwargs)
233
        if floor is not None:
234
            floors[key] = floor
235
    return floors
236
237
238
def classify_cells(
239
    rows: list[dict[str, Any]],
240
    target: str,
241
    baseline: str,
242
    floors: dict[CellKey, float],
243
    *,
244
    value_of: Callable[[dict[str, Any]], Any] = lambda row: row.get("elapsed_ms"),
245
    cells: Iterable[CellKey] | None = None,
246
    min_delta_ms: float = 0.0,
247
    fdr: float = DEFAULT_FDR,
248
    confidence: float = DEFAULT_CONFIDENCE,
249
    bootstrap_samples: int = DEFAULT_BOOTSTRAP,
250
    seed: int = 20260927,
251
) -> dict[CellKey, dict[str, Any]]:
252
    """Per-cell verdict dicts for one comparison family (see module doc)."""
253
    base_cells = samples_by_cell(rows, baseline, value_of)
254
    target_cells = samples_by_cell(rows, target, value_of)
255
    keys = sorted(set(cells) if cells is not None else (set(base_cells) | set(target_cells)))
256
    results: dict[CellKey, dict[str, Any]] = {}
257
    tested: list[CellKey] = []
258
    p_values: list[float] = []
259
    for key in keys:
260
        base = base_cells.get(key, {})
261
        cand = target_cells.get(key, {})
262
        item: dict[str, Any] = {
263
            "cell_stats_version": CELL_STATS_VERSION, "scenario": key[0], "operation": key[1],
264
            "baseline_n": len(base), "target_n": len(cand), "floor_pct": floors.get(key),
265
            "baseline_median": statistics.median(base.values()) if base else None,
266
            "target_median": statistics.median(cand.values()) if cand else None,
267
            "delta_pct": None, "ci_low_pct": None, "ci_high_pct": None, "p_value": None,
268
            "fdr_rejected": None, "verdict": "unmeasured", "reason": None,
269
        }
270
        results[key] = item
271
        if len(base) < MIN_SAMPLES or len(cand) < MIN_SAMPLES:
272
            item["reason"] = f"fewer than {MIN_SAMPLES} measured runs per arm"
273
            continue
274
        delta = relative_delta_pct(list(base.values()), list(cand.values()))
275
        interval = bootstrap_relative_ci(base, cand, samples=bootstrap_samples, confidence=confidence, seed=seed)
276
        if delta is None or interval is None:
277
            item["reason"] = "baseline median is zero"
278
            continue
279
        item.update(delta_pct=delta, ci_low_pct=interval[0], ci_high_pct=interval[1],
280
                    p_value=permutation_p_value(list(base.values()), list(cand.values()), seed=seed))
281
        tested.append(key)
282
        p_values.append(item["p_value"])
283
    bh = benjamini_hochberg_detail(p_values, fdr=fdr)
284
    for key, rejected in zip(tested, bh["rejected"]):
285
        item = results[key]
286
        item["fdr_rejected"] = rejected
287
        floor = item["floor_pct"]
288
        excludes_zero = item["ci_low_pct"] > 0 or item["ci_high_pct"] < 0
289
        abs_ms = abs(item["target_median"] - item["baseline_median"])
290
        if floor is None:
291
            item.update(verdict="unmeasured", reason="no per-cell A/A floor for this cell")
292
            continue
293
        # The floor already takes the A/A interval's outer bound; requiring the
294
        # target interval to clear it as well would count the noise twice.
295
        if excludes_zero and abs(item["delta_pct"]) > floor and abs_ms >= min_delta_ms:
296
            direction = "regression" if item["delta_pct"] > 0 else "improvement"
297
            if rejected:
298
                item["verdict"] = direction
299
            else:
300
                item["verdict"] = "unconfirmed_" + direction
301
                item["reason"] = "not significant after Benjamini-Hochberg across the comparison family"
302
        else:
303
            item["verdict"] = "no_change"
304
    for key in tested:
305
        item = results[key]
306
        item["family_size"] = len(tested)
307
        item["mde_pct"] = minimum_detectable_effect_pct(item)
308
        if item["verdict"].startswith("unconfirmed_"):
309
            item["required_n"] = required_runs(item, len(tested), fdr)
310
    return results
311
312
313
def describe(item: dict[str, Any], label: str) -> str:
314
    def pct(value: float | None) -> str:
315
        return "?" if value is None else f"{value:+.1f}%"
316
    if item.get("verdict") == "no_change" and item.get("mde_pct") is not None:
317
        return (f"`{item['scenario']}/{item['operation']}` vs {label}: no change detected >= "
318
                f"{item['mde_pct']:.1f}% (observed {pct(item['delta_pct'])}, n={item['baseline_n']}/{item['target_n']})")
319
    return (f"`{item['scenario']}/{item['operation']}` vs {label}: {pct(item['delta_pct'])} "
320
            f"({item['baseline_median']:.1f} -> {item['target_median']:.1f} ms; "
321
            f"95% CI [{pct(item['ci_low_pct'])}, {pct(item['ci_high_pct'])}], "
322
            f"A/A floor {item['floor_pct']:.1f}%, p={item['p_value']:.4f}, n={item['baseline_n']}/{item['target_n']})")