Viewing files at commit bd39a563b7f5Commit detailsView latest

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