ab-analysis-kit 0.0.1.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. ab_analysis_kit-0.0.1.dev0.dist-info/METADATA +126 -0
  2. ab_analysis_kit-0.0.1.dev0.dist-info/RECORD +122 -0
  3. ab_analysis_kit-0.0.1.dev0.dist-info/WHEEL +5 -0
  4. ab_analysis_kit-0.0.1.dev0.dist-info/entry_points.txt +2 -0
  5. ab_analysis_kit-0.0.1.dev0.dist-info/licenses/LICENSE +21 -0
  6. ab_analysis_kit-0.0.1.dev0.dist-info/top_level.txt +1 -0
  7. abkit/__init__.py +40 -0
  8. abkit/cli/__init__.py +1 -0
  9. abkit/cli/_output.py +111 -0
  10. abkit/cli/commands/__init__.py +1 -0
  11. abkit/cli/commands/_context.py +83 -0
  12. abkit/cli/commands/clean.py +133 -0
  13. abkit/cli/commands/explore.py +208 -0
  14. abkit/cli/commands/init.py +427 -0
  15. abkit/cli/commands/run.py +282 -0
  16. abkit/cli/commands/unlock.py +59 -0
  17. abkit/cli/commands/validate.py +264 -0
  18. abkit/cli/main.py +279 -0
  19. abkit/compute/__init__.py +5 -0
  20. abkit/compute/recompute_backend.py +140 -0
  21. abkit/config/__init__.py +51 -0
  22. abkit/config/discovery.py +168 -0
  23. abkit/config/experiment_config.py +511 -0
  24. abkit/config/method_config.py +80 -0
  25. abkit/config/metric_config.py +214 -0
  26. abkit/config/profile.py +301 -0
  27. abkit/config/project_config.py +244 -0
  28. abkit/config/validator.py +393 -0
  29. abkit/core/__init__.py +26 -0
  30. abkit/core/interval.py +148 -0
  31. abkit/core/models.py +121 -0
  32. abkit/core/period_planner.py +206 -0
  33. abkit/database/__init__.py +51 -0
  34. abkit/database/_sql_manager.py +432 -0
  35. abkit/database/clickhouse_manager.py +495 -0
  36. abkit/database/internal_tables/__init__.py +6 -0
  37. abkit/database/internal_tables/_aa_runs.py +53 -0
  38. abkit/database/internal_tables/_base.py +71 -0
  39. abkit/database/internal_tables/_experiments.py +82 -0
  40. abkit/database/internal_tables/_exposures.py +163 -0
  41. abkit/database/internal_tables/_maintenance.py +72 -0
  42. abkit/database/internal_tables/_results.py +231 -0
  43. abkit/database/internal_tables/_schema.py +23 -0
  44. abkit/database/internal_tables/_tasks.py +237 -0
  45. abkit/database/internal_tables/_unit_state.py +148 -0
  46. abkit/database/internal_tables/manager.py +30 -0
  47. abkit/database/manager.py +450 -0
  48. abkit/database/mysql_manager.py +175 -0
  49. abkit/database/postgres_manager.py +145 -0
  50. abkit/database/tables.py +326 -0
  51. abkit/loaders/__init__.py +28 -0
  52. abkit/loaders/exposure_loader.py +121 -0
  53. abkit/loaders/metric_loader.py +251 -0
  54. abkit/loaders/query_template.py +167 -0
  55. abkit/loaders/templates/abkit_assignment.jinja +62 -0
  56. abkit/pipeline/__init__.py +37 -0
  57. abkit/pipeline/_types.py +52 -0
  58. abkit/pipeline/analyze.py +223 -0
  59. abkit/pipeline/driver.py +477 -0
  60. abkit/pipeline/enrich.py +137 -0
  61. abkit/pipeline/readout.py +779 -0
  62. abkit/reporting/__init__.py +19 -0
  63. abkit/reporting/assets/report.js +138 -0
  64. abkit/reporting/builder.py +484 -0
  65. abkit/reporting/calibration.py +182 -0
  66. abkit/reporting/html_report.py +109 -0
  67. abkit/stats/__init__.py +94 -0
  68. abkit/stats/accumulate.py +82 -0
  69. abkit/stats/base.py +347 -0
  70. abkit/stats/bootstrap/__init__.py +69 -0
  71. abkit/stats/bootstrap/applier.py +81 -0
  72. abkit/stats/bootstrap/bootstrap.py +311 -0
  73. abkit/stats/bootstrap/ci.py +72 -0
  74. abkit/stats/bootstrap/engine.py +383 -0
  75. abkit/stats/bootstrap/paired_bootstrap.py +57 -0
  76. abkit/stats/bootstrap/paired_post_normed_bootstrap.py +81 -0
  77. abkit/stats/bootstrap/poisson_bootstrap.py +112 -0
  78. abkit/stats/bootstrap/post_normed_bootstrap.py +102 -0
  79. abkit/stats/correction.py +88 -0
  80. abkit/stats/effects.py +141 -0
  81. abkit/stats/exceptions.py +31 -0
  82. abkit/stats/factory.py +26 -0
  83. abkit/stats/parametric/__init__.py +10 -0
  84. abkit/stats/parametric/cuped_ttest.py +183 -0
  85. abkit/stats/parametric/paired_cuped_ttest.py +125 -0
  86. abkit/stats/parametric/paired_ttest.py +136 -0
  87. abkit/stats/parametric/ratio_delta.py +113 -0
  88. abkit/stats/parametric/ttest.py +105 -0
  89. abkit/stats/parametric/ztest.py +134 -0
  90. abkit/stats/power.py +278 -0
  91. abkit/stats/registry.py +111 -0
  92. abkit/stats/result.py +84 -0
  93. abkit/stats/rng.py +39 -0
  94. abkit/stats/samples.py +531 -0
  95. abkit/stats/sequential/__init__.py +18 -0
  96. abkit/stats/sequential/apply.py +37 -0
  97. abkit/stats/sequential/confidence_sequence.py +96 -0
  98. abkit/stats/sequential/mixture.py +70 -0
  99. abkit/stats/srm.py +221 -0
  100. abkit/tuning/__init__.py +59 -0
  101. abkit/tuning/assets/explore.js +173 -0
  102. abkit/tuning/config_writer.py +409 -0
  103. abkit/tuning/html.py +88 -0
  104. abkit/tuning/payload.py +122 -0
  105. abkit/tuning/recompute.py +1039 -0
  106. abkit/tuning/server.py +882 -0
  107. abkit/tuning/session.py +233 -0
  108. abkit/utils/__init__.py +27 -0
  109. abkit/utils/datetime_utils.py +97 -0
  110. abkit/utils/env_interpolation.py +50 -0
  111. abkit/utils/json_utils.py +38 -0
  112. abkit/validate/__init__.py +36 -0
  113. abkit/validate/_types.py +35 -0
  114. abkit/validate/inject.py +75 -0
  115. abkit/validate/load.py +160 -0
  116. abkit/validate/panel.py +59 -0
  117. abkit/validate/persistence.py +59 -0
  118. abkit/validate/resample.py +94 -0
  119. abkit/validate/result.py +60 -0
  120. abkit/validate/run_id.py +45 -0
  121. abkit/validate/runner.py +389 -0
  122. abkit/validate/scoring.py +544 -0
@@ -0,0 +1,779 @@
1
+ """The readout stage: persisted ``_ab_results`` rows → the experiment verdict.
2
+
3
+ WIN / LOSE / FLAT / INCONCLUSIVE per (main-metric comparison ×
4
+ control-vs-treatment pair), evaluated at the series' latest computed cutoff
5
+ (data-contract-and-reporting.md §1; the numeric rules are
6
+ m3-implementation-plan.md D5). Pure decision logic over the row dicts
7
+ ``load_results()`` returns — no DB, no rendering. Verdicts are read-time
8
+ only: recomputed at render, never persisted (D5(f)).
9
+
10
+ Decision order per pair (each gate may short-circuit to INCONCLUSIVE):
11
+
12
+ 1. **SRM hard gate** (§1) — a flagged cohort makes every effect untrustworthy.
13
+ 2. **Pre-horizon withholding** (D5(d); quorum "peeking is the product") —
14
+ with fixed-horizon CIs (every M3 row), WIN/LOSE **and FLAT** are withheld
15
+ until ``is_horizon``; FLAT is equally a stop decision.
16
+ 3. **Latest-cutoff usability** — ``insufficient_data`` demotion or degenerate
17
+ (NULL-bound) inference at the latest cutoff.
18
+ 4. **Elapsed-time stabilization** (§4: never look count) — the trailing
19
+ ``readout.stabilization_days`` window, widened to the last
20
+ ``MIN_STABLE_CUTOFFS`` informative cutoffs when the cadence is coarser
21
+ than the window.
22
+ 5. **Significance + sign consistency** → WIN/LOSE against the comparison's
23
+ ``desired_direction``; all-quiet + adequately powered (``min_effect`` vs
24
+ the pair MDE, D5(b)) → FLAT.
25
+ 6. **Guardrail regression** (D5(c), owner-ratified policy) —
26
+ ``guardrail_policy: block`` caps WIN at INCONCLUSIVE; ``warn`` keeps WIN
27
+ with a mandatory loud caveat. LOSE is never upgraded or blocked.
28
+
29
+ Benjamini-Hochberg (``correction: benjamini_hochberg``) is applied HERE at
30
+ read time, per cutoff across the experiment's comparisons — compute-time rows
31
+ deliberately carry the raw alpha (``analyze.effective_alphas``); an M3 readout
32
+ ignoring it would verdict at the wrong alpha.
33
+
34
+ MDE fallback (D5(b)): rows persisted with ``calculate_mde: false`` carry NULL
35
+ ``mde_1/2``. For t-test and z-test rows the pair MDE is recomputed read-time
36
+ from the on-row per-arm stats via ``stats/power.py`` — byte-equivalent to the
37
+ method's own solve (the z-test ``nobs`` is inverted from the persisted SE,
38
+ never taken from ``size_i``, which counts unit rows). Methods without an MDE
39
+ capability (ratio-delta, the bootstrap family) leave FLAT honestly
40
+ unreachable, with the rationale saying so.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import json
46
+ import math
47
+ from collections.abc import Sequence
48
+ from dataclasses import asdict, dataclass
49
+ from datetime import datetime
50
+ from typing import Any, Literal
51
+
52
+ from abkit.config.experiment_config import ComparisonConfig, ExperimentConfig
53
+ from abkit.config.project_config import ProjectConfig
54
+ from abkit.stats.correction import benjamini_hochberg
55
+ from abkit.stats.exceptions import UnknownMethodError
56
+ from abkit.stats.power import get_fraction_mde, get_ttest_mde
57
+ from abkit.stats.registry import get_method_class
58
+
59
+ VerdictKind = Literal["WIN", "LOSE", "FLAT", "INCONCLUSIVE"]
60
+
61
+ #: The representativeness horizon (§4): verdicts covering less than one weekly
62
+ #: cycle carry the "covers X% of a weekly cycle" caveat.
63
+ WEEKLY_CYCLE_DAYS = 7.0
64
+ #: The stabilization-window floor (D5(a)): fewer informative cutoffs than this
65
+ #: cannot demonstrate persistence.
66
+ MIN_STABLE_CUTOFFS = 3
67
+
68
+ _DAY_SECONDS = 86400.0
69
+
70
+
71
+ # ── row coercion (DB backends return numpy scalars / 0-1 ints for booleans) ──
72
+
73
+
74
+ def _num(value: Any) -> float | None:
75
+ """None-safe finite float (NaN/inf → None, matching the nullable contract)."""
76
+ if value is None:
77
+ return None
78
+ v = float(value)
79
+ return v if math.isfinite(v) else None
80
+
81
+
82
+ def _flag(value: Any) -> bool:
83
+ if value is None:
84
+ return False
85
+ if isinstance(value, bool):
86
+ return value
87
+ return bool(int(value))
88
+
89
+
90
+ # ── results ──────────────────────────────────────────────────────────────────
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class GuardrailStatus:
95
+ """One guardrail comparison's regression check for one variant pair."""
96
+
97
+ metric: str
98
+ name_1: str
99
+ name_2: str
100
+ regressed: bool
101
+ effect: float | None
102
+ desired_direction: str
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class PairVerdict:
107
+ """The verdict for one (main-metric comparison × control-vs-treatment pair)."""
108
+
109
+ metric: str
110
+ name_1: str
111
+ name_2: str
112
+ verdict: VerdictKind
113
+ rationale: tuple[str, ...]
114
+ caveats: tuple[str, ...]
115
+ end_ts: datetime | None
116
+ elapsed_days: float | None
117
+ is_horizon: bool
118
+ effect: float | None
119
+ pvalue: float | None
120
+ left_bound: float | None
121
+ right_bound: float | None
122
+ alpha: float | None
123
+ significant: bool
124
+ mde: float | None
125
+ min_effect: float | None
126
+ #: Weekly-cycle coverage fraction (elapsed / 7d) when a decisive verdict is
127
+ #: called before one full weekly cycle, else ``None`` — the report promotes
128
+ #: it to a representativeness chip (§6.5). ``None`` on INCONCLUSIVE or ≥7d.
129
+ weekly_cycle_pct: float | None
130
+ guardrails: tuple[GuardrailStatus, ...]
131
+
132
+ def to_dict(self) -> dict[str, Any]:
133
+ payload = asdict(self)
134
+ payload["rationale"] = list(self.rationale)
135
+ payload["caveats"] = list(self.caveats)
136
+ payload["guardrails"] = [asdict(g) for g in self.guardrails]
137
+ return payload
138
+
139
+
140
+ @dataclass(frozen=True)
141
+ class ExperimentReadout:
142
+ """The experiment-level readout: per-pair verdicts + the SRM summary."""
143
+
144
+ experiment: str
145
+ srm_flag: bool
146
+ srm_pvalue: float | None
147
+ verdicts: tuple[PairVerdict, ...]
148
+ warnings: tuple[str, ...]
149
+
150
+ def to_dict(self) -> dict[str, Any]:
151
+ return {
152
+ "experiment": self.experiment,
153
+ "srm_flag": self.srm_flag,
154
+ "srm_pvalue": self.srm_pvalue,
155
+ "verdicts": [v.to_dict() for v in self.verdicts],
156
+ "warnings": list(self.warnings),
157
+ }
158
+
159
+
160
+ # ── significance (BH-aware) ──────────────────────────────────────────────────
161
+
162
+
163
+ @dataclass(frozen=True)
164
+ class _Sig:
165
+ significant: bool
166
+ sign: int # +1 effect up, -1 effect down, 0 undecidable
167
+
168
+
169
+ _RowKey = tuple[str, str, str, Any] # (metric, name_1, name_2, end_ts)
170
+
171
+
172
+ def _row_key(row: dict) -> _RowKey:
173
+ return (str(row["metric"]), str(row["name_1"]), str(row["name_2"]), row["end_ts"])
174
+
175
+
176
+ def _informative(row: dict) -> bool:
177
+ """A row the stabilization scan may judge: inference present, not demoted.
178
+
179
+ Demoted (``insufficient_data``) and degenerate (NULL-bound) rows are gaps —
180
+ skipped, never treated as zeros.
181
+ """
182
+ if _flag(row.get("insufficient_data")):
183
+ return False
184
+ return _num(row.get("left_bound")) is not None and _num(row.get("right_bound")) is not None
185
+
186
+
187
+ def _build_sig_map(rows: Sequence[dict], correction: str) -> dict[_RowKey, _Sig]:
188
+ """Per-row significance under the experiment's correction scheme.
189
+
190
+ Bonferroni/none: the CI already reflects the stored effective alpha —
191
+ significance is "the CI excludes zero" (≡ the stored ``reject``).
192
+ Benjamini-Hochberg: adjusted per cutoff across every informative row at
193
+ that ``end_ts`` (metrics × pairs — mirroring the compute-time
194
+ ``n_comparisons`` convention), compared against the stored raw alpha.
195
+ """
196
+ sig: dict[_RowKey, _Sig] = {}
197
+ informative = [row for row in rows if _informative(row)]
198
+
199
+ if correction != "benjamini_hochberg":
200
+ for row in informative:
201
+ left = _num(row.get("left_bound"))
202
+ right = _num(row.get("right_bound"))
203
+ if left is not None and left > 0:
204
+ sig[_row_key(row)] = _Sig(True, 1)
205
+ elif right is not None and right < 0:
206
+ sig[_row_key(row)] = _Sig(True, -1)
207
+ else:
208
+ sig[_row_key(row)] = _Sig(False, 0)
209
+ return sig
210
+
211
+ by_cutoff: dict[Any, list[dict]] = {}
212
+ for row in informative:
213
+ if _num(row.get("pvalue")) is None:
214
+ sig[_row_key(row)] = _Sig(False, 0)
215
+ continue
216
+ by_cutoff.setdefault(row["end_ts"], []).append(row)
217
+ for cutoff_rows in by_cutoff.values():
218
+ adjusted = benjamini_hochberg([_num(row["pvalue"]) for row in cutoff_rows])
219
+ for row, adj in zip(cutoff_rows, adjusted, strict=False):
220
+ alpha = _num(row.get("alpha"))
221
+ effect = _num(row.get("effect"))
222
+ significant = alpha is not None and float(adj) < alpha
223
+ sign = 0
224
+ if significant and effect is not None and effect != 0:
225
+ sign = 1 if effect > 0 else -1
226
+ if significant and sign == 0:
227
+ significant = False
228
+ sig[_row_key(row)] = _Sig(significant, sign)
229
+ return sig
230
+
231
+
232
+ # ── MDE (D5(b)) ──────────────────────────────────────────────────────────────
233
+
234
+
235
+ def _combine_mde(mde_1: float | None, mde_2: float | None) -> float | None:
236
+ """The pair MDE: the larger per-arm magnitude (compared against min_effect)."""
237
+ magnitudes = [abs(m) for m in (mde_1, mde_2) if m is not None]
238
+ return max(magnitudes) if magnitudes else None
239
+
240
+
241
+ def pair_mde(row: dict) -> tuple[float | None, str | None]:
242
+ """``(pair_mde, unavailable_reason)`` for one row — stored or read-time.
243
+
244
+ The stored pair is trusted only when BOTH ``mde_1/2`` are present: enrich
245
+ NULLs a non-finite solve (an arm with zero variance or ``n<=1`` has
246
+ infinite MDE), so a half-present pair means one arm is undetectable —
247
+ taking the finite arm alone would fake adequate power (review finding).
248
+ Otherwise the fallback recomputes the method's own solve from on-row
249
+ stats — exact for t-test (mean/std/units persist directly) and z-test
250
+ (``nobs`` inverted from the persisted SE ``sqrt(p(1−p)/nobs)``; ``size_i``
251
+ is the unit-row count and must never be used as ``nobs``). Where the
252
+ fallback cannot recompute but ``calculate_mde: true`` is on the row's
253
+ params, a NULL column provably WAS a non-finite solve — the pair MDE is
254
+ ``inf`` (reads as underpowered), never None.
255
+ """
256
+ stored_1, stored_2 = _num(row.get("mde_1")), _num(row.get("mde_2"))
257
+ if stored_1 is not None and stored_2 is not None:
258
+ return _combine_mde(stored_1, stored_2), None
259
+
260
+ method_name = str(row.get("method_name"))
261
+ try:
262
+ method_cls = get_method_class(method_name)
263
+ except UnknownMethodError:
264
+ return None, f"unknown method {method_name!r}"
265
+ params: dict[str, Any] = json.loads(row["method_params"]) if row.get("method_params") else {}
266
+ defaults = {spec.name: spec.default for spec in method_cls.param_specs}
267
+ test_type = str(params.get("test_type", defaults.get("test_type", "relative")))
268
+ power = float(params.get("power", defaults.get("power", 0.8)))
269
+ calculate_mde = bool(params.get("calculate_mde", defaults.get("calculate_mde", False)))
270
+ alpha = _num(row.get("alpha"))
271
+ value_1, value_2 = _num(row.get("value_1")), _num(row.get("value_2"))
272
+ std_1, std_2 = _num(row.get("std_1")), _num(row.get("std_2"))
273
+
274
+ def unavailable(reason: str) -> tuple[float | None, str | None]:
275
+ # calculate_mde: true wrote the mde columns; a NULL one provably was a
276
+ # non-finite solve (enrich NULLs inf) — underpowered, not unknown.
277
+ if calculate_mde:
278
+ return math.inf, None
279
+ return None, reason
280
+
281
+ if method_cls.name == "t-test":
282
+ size_1 = row.get("size_1")
283
+ size_2 = row.get("size_2")
284
+ if None in (value_1, value_2, std_1, std_2, alpha, size_1, size_2):
285
+ return unavailable("per-arm stats unavailable on the row")
286
+ n1, n2 = int(size_1), int(size_2)
287
+ if n1 <= 0 or n2 <= 0:
288
+ return unavailable("per-arm sizes unavailable on the row")
289
+ mde_1 = get_ttest_mde(
290
+ value_1, std_1, n1, test_type=test_type, alpha=alpha, power=power, ratio=n2 / n1
291
+ )
292
+ mde_2 = get_ttest_mde(
293
+ value_2, std_2, n2, test_type=test_type, alpha=alpha, power=power, ratio=n1 / n2
294
+ )
295
+ return _combine_mde(mde_1, mde_2), None
296
+
297
+ if method_cls.name == "z-test":
298
+ if None in (value_1, value_2, std_1, std_2, alpha):
299
+ return unavailable("per-arm stats unavailable on the row")
300
+ if not (0.0 < value_1 < 1.0 and 0.0 < value_2 < 1.0 and std_1 > 0 and std_2 > 0):
301
+ return unavailable("degenerate proportion (p in {0, 1}) — nobs is not invertible")
302
+ # std_i is the SE of the proportion: sqrt(p(1-p)/nobs) -> invert nobs.
303
+ nobs_1 = value_1 * (1.0 - value_1) / (std_1**2)
304
+ nobs_2 = value_2 * (1.0 - value_2) / (std_2**2)
305
+ mde_1 = get_fraction_mde(
306
+ value_1,
307
+ int(round(nobs_1)),
308
+ test_type=test_type,
309
+ alpha=alpha,
310
+ power=power,
311
+ ratio=nobs_2 / nobs_1,
312
+ )
313
+ mde_2 = get_fraction_mde(
314
+ value_2,
315
+ int(round(nobs_2)),
316
+ test_type=test_type,
317
+ alpha=alpha,
318
+ power=power,
319
+ ratio=nobs_1 / nobs_2,
320
+ )
321
+ return _combine_mde(mde_1, mde_2), None
322
+
323
+ if any(spec.name == "calculate_mde" for spec in method_cls.param_specs):
324
+ return unavailable(
325
+ f"MDE not computed — set calculate_mde: true on {method_cls.name!r} "
326
+ "(its solve needs moments that are not persisted per row)"
327
+ )
328
+ return None, f"method {method_cls.name!r} has no MDE capability"
329
+
330
+
331
+ # ── evaluate ─────────────────────────────────────────────────────────────────
332
+
333
+
334
+ def _group_series(rows: Sequence[dict]) -> dict[tuple[str, str, str], list[dict]]:
335
+ """Group rows into ``(metric, name_1, name_2)`` series, each end_ts-ascending."""
336
+ series: dict[tuple[str, str, str], list[dict]] = {}
337
+ for row in rows:
338
+ key = (str(row["metric"]), str(row["name_1"]), str(row["name_2"]))
339
+ series.setdefault(key, []).append(row)
340
+ for group in series.values():
341
+ group.sort(key=lambda row: row["end_ts"])
342
+ return series
343
+
344
+
345
+ def _srm_from_series(
346
+ experiment: ExperimentConfig, series: dict[tuple[str, str, str], list[dict]]
347
+ ) -> tuple[bool, float | None]:
348
+ """The experiment-level SRM ``(flag, pvalue)`` over pre-grouped series.
349
+
350
+ When any latest row is flagged, the reported p-value must come from a
351
+ FLAGGED row (a lagging non-flagged series would otherwise pair
352
+ ``srm_flag=True`` with a healthy p — review finding); ``min()`` picks the
353
+ loudest evidence. ALL comparisons' series are scanned, not just main —
354
+ SRM is a whole-experiment fact stamped on every row, and a main-only scan
355
+ goes silent exactly when the main series is empty under its CURRENT
356
+ ``method_config_id`` (e.g. right after an explore Apply edited the main
357
+ method) while flagged rows still exist on other series (§6 must stay
358
+ loud — milestone-review finding).
359
+ """
360
+ control = experiment.assignment.variants[0]
361
+ treatments = experiment.assignment.variants[1:]
362
+ srm_flag = False
363
+ flagged_pvalues: list[float] = []
364
+ healthy_pvalues: list[float] = []
365
+ for comparison in experiment.comparisons:
366
+ for treatment in treatments:
367
+ group = series.get((comparison.metric, control, treatment))
368
+ if not group:
369
+ continue
370
+ latest = group[-1]
371
+ flagged = _flag(latest.get("srm_flag"))
372
+ srm_flag = srm_flag or flagged
373
+ pvalue = _num(latest.get("srm_pvalue"))
374
+ if pvalue is not None:
375
+ (flagged_pvalues if flagged else healthy_pvalues).append(pvalue)
376
+ if flagged_pvalues:
377
+ return srm_flag, min(flagged_pvalues)
378
+ if healthy_pvalues:
379
+ return srm_flag, healthy_pvalues[0]
380
+ return srm_flag, None
381
+
382
+
383
+ def srm_summary(experiment: ExperimentConfig, rows: Sequence[dict]) -> tuple[bool, float | None]:
384
+ """The experiment-level SRM ``(flag, pvalue)`` over raw (ungrouped) rows.
385
+
386
+ The report's loud §6 SRM chip calls this over the FULL persisted rows
387
+ (current experiment health, window-independent) so the chip never goes
388
+ silent under a pinned/empty replay — while ``evaluate`` uses the same core
389
+ over the windowed series for the as-of verdict. SRM is a whole-experiment
390
+ gate ("is assignment broken?"), not a per-cutoff series in M2 (per-cutoff
391
+ lands with M5 sequential)."""
392
+ filtered, _warnings = _filter_rows(experiment, rows)
393
+ return _srm_from_series(experiment, _group_series(filtered))
394
+
395
+
396
+ def evaluate(
397
+ experiment: ExperimentConfig,
398
+ rows: Sequence[dict],
399
+ *,
400
+ project: ProjectConfig | None = None,
401
+ ) -> ExperimentReadout:
402
+ """The pure verdict over ``load_results()`` rows for one experiment.
403
+
404
+ ``project`` resolves the effective correction when the experiment leaves
405
+ it unset — the same resolution the pipeline runs with
406
+ (``analyze.effective_alphas`` requires the project; here it is optional
407
+ for notebook convenience). When BOTH are absent the readout falls back to
408
+ stored-alpha CI significance — correct for ``none``/``bonferroni`` (the
409
+ persisted bounds already carry the effective alpha) but WRONG for a
410
+ project-level ``benjamini_hochberg`` default, so the degradation is
411
+ surfaced as a loud ``ExperimentReadout.warnings`` entry, never silent
412
+ (review finding; D5(g): read-time BH is required, not optional).
413
+ """
414
+ correction = experiment.correction
415
+ unresolved_correction = correction is None and project is None
416
+ if correction is None:
417
+ correction = project.statistics.correction if project is not None else "none"
418
+
419
+ filtered, warnings = _filter_rows(experiment, rows)
420
+ if unresolved_correction:
421
+ warnings.append(
422
+ "correction is unset on the experiment and no project config was "
423
+ "passed — significance falls back to the stored-alpha CI; a "
424
+ "project-level 'benjamini_hochberg' default would be mis-scored "
425
+ "(pass project= to resolve the effective correction)"
426
+ )
427
+ sig_map = _build_sig_map(filtered, correction)
428
+
429
+ series = _group_series(filtered)
430
+
431
+ control = experiment.assignment.variants[0]
432
+ treatments = experiment.assignment.variants[1:]
433
+ main_comparisons = [c for c in experiment.comparisons if c.is_main_metric]
434
+ guardrail_comparisons = [c for c in experiment.comparisons if c.is_guardrail]
435
+
436
+ verdicts: list[PairVerdict] = []
437
+ for comparison in main_comparisons:
438
+ for treatment in treatments:
439
+ verdicts.append(
440
+ _pair_verdict(
441
+ experiment,
442
+ comparison,
443
+ control,
444
+ treatment,
445
+ series,
446
+ sig_map,
447
+ guardrail_comparisons,
448
+ )
449
+ )
450
+
451
+ srm_flag, srm_pvalue = _srm_from_series(experiment, series)
452
+
453
+ return ExperimentReadout(
454
+ experiment=experiment.name,
455
+ srm_flag=srm_flag,
456
+ srm_pvalue=srm_pvalue,
457
+ verdicts=tuple(verdicts),
458
+ warnings=tuple(warnings),
459
+ )
460
+
461
+
462
+ def _filter_rows(
463
+ experiment: ExperimentConfig, rows: Sequence[dict]
464
+ ) -> tuple[list[dict], list[str]]:
465
+ """Keep only rows under each comparison's CURRENT ``method_config_id``.
466
+
467
+ Orphaned series (an edited identity param leaves old rows behind) and
468
+ rows for metrics the config no longer binds are ignored with a warning —
469
+ the driver prints the same story at run time (duplicate stabilization
470
+ lines; ``abk clean``).
471
+ """
472
+ configured = {c.metric: c.method.method_config_id for c in experiment.comparisons}
473
+ filtered: list[dict] = []
474
+ orphaned: dict[str, set[str]] = {}
475
+ unconfigured: set[str] = set()
476
+ for row in rows:
477
+ metric = str(row["metric"])
478
+ expected = configured.get(metric)
479
+ if expected is None:
480
+ unconfigured.add(metric)
481
+ continue
482
+ if str(row["method_config_id"]) != expected:
483
+ orphaned.setdefault(metric, set()).add(str(row["method_config_id"]))
484
+ continue
485
+ filtered.append(row)
486
+
487
+ warnings: list[str] = []
488
+ for metric in sorted(orphaned):
489
+ ids = orphaned[metric]
490
+ warnings.append(
491
+ f"metric {metric!r}: ignored {len(ids)} orphaned method_config_id "
492
+ "series (edited method params leave old rows behind — run `abk clean`)"
493
+ )
494
+ for metric in sorted(unconfigured):
495
+ warnings.append(f"ignored rows for metric {metric!r} — not bound by this experiment")
496
+ return filtered, warnings
497
+
498
+
499
+ def _pair_verdict(
500
+ experiment: ExperimentConfig,
501
+ comparison: ComparisonConfig,
502
+ control: str,
503
+ treatment: str,
504
+ series: dict[tuple[str, str, str], list[dict]],
505
+ sig_map: dict[_RowKey, _Sig],
506
+ guardrail_comparisons: list[ComparisonConfig],
507
+ ) -> PairVerdict:
508
+ metric = comparison.metric
509
+ group = series.get((metric, control, treatment), [])
510
+ rationale: list[str] = []
511
+ caveats: list[str] = []
512
+
513
+ def build(verdict: VerdictKind, latest: dict | None) -> PairVerdict:
514
+ guardrails = _guardrail_statuses(control, treatment, series, guardrail_comparisons)
515
+ verdict, extra_rationale, extra_caveats = _apply_guardrail_policy(
516
+ experiment, verdict, guardrails
517
+ )
518
+ rationale.extend(extra_rationale)
519
+ caveats.extend(extra_caveats)
520
+ elapsed = _num(latest.get("elapsed_days")) if latest else None
521
+ decisive = verdict != "INCONCLUSIVE"
522
+ weekly_cycle_pct: float | None = None
523
+ if decisive and elapsed is not None and elapsed < WEEKLY_CYCLE_DAYS:
524
+ weekly_cycle_pct = elapsed / WEEKLY_CYCLE_DAYS
525
+ caveats.append(
526
+ f"covers {weekly_cycle_pct:.0%} of a weekly cycle — "
527
+ "day-of-week effects may not be represented"
528
+ )
529
+ # WP4 (§6.5): a decisive verdict reached *before* the planned horizon is
530
+ # only legitimate under an always-valid CI (fixed CIs are withheld above);
531
+ # name the reason so a reader isn't surprised by an early WIN/LOSE/FLAT.
532
+ latest_ci_kind = str(latest.get("ci_kind") or "fixed") if latest else "fixed"
533
+ latest_is_horizon = _flag(latest.get("is_horizon")) if latest else False
534
+ if decisive and not latest_is_horizon and latest_ci_kind == "always_valid":
535
+ rationale.append(
536
+ "called before the planned horizon under an always-valid "
537
+ "confidence sequence — peeking-safe by construction (its "
538
+ "cumulative-peeking FPR is measured by `abk validate`)"
539
+ )
540
+ key = _row_key(latest) if latest else None
541
+ latest_sig = sig_map.get(key, _Sig(False, 0)) if key else _Sig(False, 0)
542
+ mde_value, _ = pair_mde(latest) if latest else (None, None)
543
+ return PairVerdict(
544
+ metric=metric,
545
+ name_1=control,
546
+ name_2=treatment,
547
+ verdict=verdict,
548
+ rationale=tuple(rationale),
549
+ caveats=tuple(caveats),
550
+ end_ts=latest["end_ts"] if latest else None,
551
+ elapsed_days=elapsed,
552
+ is_horizon=_flag(latest.get("is_horizon")) if latest else False,
553
+ effect=_num(latest.get("effect")) if latest else None,
554
+ pvalue=_num(latest.get("pvalue")) if latest else None,
555
+ left_bound=_num(latest.get("left_bound")) if latest else None,
556
+ right_bound=_num(latest.get("right_bound")) if latest else None,
557
+ alpha=_num(latest.get("alpha")) if latest else None,
558
+ significant=latest_sig.significant,
559
+ mde=mde_value,
560
+ min_effect=comparison.min_effect,
561
+ weekly_cycle_pct=weekly_cycle_pct,
562
+ guardrails=guardrails,
563
+ )
564
+
565
+ if not group:
566
+ rationale.append(
567
+ f"no computed results for this pair — run `abk run --select {experiment.name}`"
568
+ )
569
+ return build("INCONCLUSIVE", None)
570
+
571
+ latest = group[-1]
572
+
573
+ # 1. SRM hard gate (§1: effects untrustworthy under a broken cohort).
574
+ if _flag(latest.get("srm_flag")) or _flag(latest.get("decision_blocked")):
575
+ srm_p = _num(latest.get("srm_pvalue"))
576
+ # Name the gate that actually ran: χ² at daily+, the anytime-valid
577
+ # sequential multinomial e-process below 1d (WP5). ``kind`` is not
578
+ # persisted, so it is derived from the current cadence (the gate that
579
+ # wrote these rows) — statistics-changes.md §4.2.
580
+ gate = "anytime-valid" if experiment.is_sub_day() else "chi-square"
581
+ rationale.append(
582
+ "SRM failed"
583
+ + (f" ({gate} p={srm_p:.3g})" if srm_p is not None else "")
584
+ + " — observed group sizes are inconsistent with expected_split; "
585
+ "effects untrustworthy (hard gate)"
586
+ )
587
+ return build("INCONCLUSIVE", latest)
588
+
589
+ # 2. Pre-horizon withholding (D5(d)): fixed CIs are not peeking-valid.
590
+ ci_kind = str(latest.get("ci_kind") or "fixed")
591
+ if not _flag(latest.get("is_horizon")) and ci_kind == "fixed":
592
+ elapsed = _num(latest.get("elapsed_days")) or 0.0
593
+ horizon_days = experiment.horizon_seconds() / _DAY_SECONDS
594
+ rationale.append(
595
+ f"pre-horizon: latest cutoff covers {elapsed:.1f} of {horizon_days:.1f} "
596
+ "planned days and fixed-horizon CIs are not peeking-valid — "
597
+ "WIN/LOSE/FLAT withheld until the horizon (enable `sequential: "
598
+ "{enabled: true}` on a sequential-eligible method for peeking-valid "
599
+ "early readouts)"
600
+ )
601
+ if experiment.sequential.enabled:
602
+ caveats.append(
603
+ "sequential.enabled is set, but these rows carry fixed CIs — the "
604
+ "method is not sequential-eligible (e.g. bootstrap) or this pair had "
605
+ "no usable look at the τ² anchor; the pre-horizon refusal still applies"
606
+ )
607
+ return build("INCONCLUSIVE", latest)
608
+
609
+ # 3. Latest-cutoff usability.
610
+ if _flag(latest.get("insufficient_data")):
611
+ rationale.append(
612
+ f"insufficient data at the latest cutoff ({latest.get('size_1')}/"
613
+ f"{latest.get('size_2')} units) — inference withheld"
614
+ )
615
+ return build("INCONCLUSIVE", latest)
616
+ if not _informative(latest):
617
+ rationale.append(
618
+ "no confidence interval at the latest cutoff (degenerate variance) — "
619
+ "cannot judge significance"
620
+ )
621
+ return build("INCONCLUSIVE", latest)
622
+
623
+ # 4. The elapsed-time stabilization window (D5(a)).
624
+ stabilization_days = experiment.readout.stabilization_days
625
+ informative = [row for row in group if _informative(row)]
626
+ latest_elapsed = _num(latest.get("elapsed_days")) or 0.0
627
+ window = [
628
+ row
629
+ for row in informative
630
+ if (_num(row.get("elapsed_days")) or 0.0) >= latest_elapsed - stabilization_days
631
+ ]
632
+ if len(window) < MIN_STABLE_CUTOFFS:
633
+ # Coarse cadence: widen to the last MIN_STABLE_CUTOFFS informative cutoffs.
634
+ window = informative[-MIN_STABLE_CUTOFFS:]
635
+ if len(window) < MIN_STABLE_CUTOFFS:
636
+ rationale.append(
637
+ f"only {len(window)} informative cutoff(s) available — at least "
638
+ f"{MIN_STABLE_CUTOFFS} are needed to judge stabilization over the "
639
+ f"trailing {stabilization_days:g} days"
640
+ )
641
+ return build("INCONCLUSIVE", latest)
642
+
643
+ # 5. Significance + sign consistency over the window.
644
+ sigs = [sig_map.get(_row_key(row), _Sig(False, 0)) for row in window]
645
+ desired_sign = 1 if comparison.desired_direction == "increase" else -1
646
+
647
+ if all(s.significant for s in sigs):
648
+ signs = {s.sign for s in sigs}
649
+ if len(signs) == 1:
650
+ sign = signs.pop()
651
+ direction = "desired" if sign == desired_sign else "adverse"
652
+ rationale.append(
653
+ f"CI excludes zero in the {direction} direction "
654
+ f"({'up' if sign > 0 else 'down'}) at every informative cutoff in the "
655
+ f"trailing {stabilization_days:g}-day window ({len(window)} cutoffs)"
656
+ )
657
+ return build("WIN" if sign == desired_sign else "LOSE", latest)
658
+ rationale.append(
659
+ "not stabilized: the effect sign flipped within the trailing "
660
+ f"{stabilization_days:g}-day window"
661
+ )
662
+ return build("INCONCLUSIVE", latest)
663
+
664
+ if any(s.significant for s in sigs):
665
+ rationale.append(
666
+ "not stabilized: the CI crossed zero within the trailing "
667
+ f"{stabilization_days:g}-day window (significant at some cutoffs, "
668
+ "not at others)"
669
+ )
670
+ return build("INCONCLUSIVE", latest)
671
+
672
+ # All quiet: FLAT needs the power story (D5(b)).
673
+ min_effect = comparison.min_effect
674
+ if min_effect is None:
675
+ rationale.append(
676
+ "CI includes zero across the window but no min_effect is configured — "
677
+ "cannot distinguish flat from underpowered (set comparisons[].min_effect)"
678
+ )
679
+ return build("INCONCLUSIVE", latest)
680
+ mde_value, mde_reason = pair_mde(latest)
681
+ if mde_value is None:
682
+ rationale.append(
683
+ "CI includes zero across the window but the MDE is unavailable: "
684
+ f"{mde_reason} — FLAT is not callable"
685
+ )
686
+ return build("INCONCLUSIVE", latest)
687
+ if mde_value <= min_effect:
688
+ rationale.append(
689
+ f"CI includes zero across the trailing {stabilization_days:g}-day window "
690
+ f"and the test is adequately powered (MDE {mde_value:.4g} <= "
691
+ f"min_effect {min_effect:g})"
692
+ )
693
+ return build("FLAT", latest)
694
+ rationale.append(
695
+ f"underpowered: MDE {mde_value:.4g} > min_effect {min_effect:g} — "
696
+ "keep running (INCONCLUSIVE, not FLAT)"
697
+ )
698
+ return build("INCONCLUSIVE", latest)
699
+
700
+
701
+ def _guardrail_statuses(
702
+ control: str,
703
+ treatment: str,
704
+ series: dict[tuple[str, str, str], list[dict]],
705
+ guardrail_comparisons: list[ComparisonConfig],
706
+ ) -> tuple[GuardrailStatus, ...]:
707
+ statuses: list[GuardrailStatus] = []
708
+ for guardrail in guardrail_comparisons:
709
+ group = series.get((guardrail.metric, control, treatment), [])
710
+ informative = [row for row in group if _informative(row)]
711
+ desired_sign = 1 if guardrail.desired_direction == "increase" else -1
712
+ if not informative:
713
+ statuses.append(
714
+ GuardrailStatus(
715
+ metric=guardrail.metric,
716
+ name_1=control,
717
+ name_2=treatment,
718
+ regressed=False,
719
+ effect=None,
720
+ desired_direction=guardrail.desired_direction,
721
+ )
722
+ )
723
+ continue
724
+ latest = informative[-1]
725
+ # D5(c): regression = the STORED CI excludes zero against the desired
726
+ # direction at the stored per-row alpha — conservative ("any
727
+ # significant harm flags"), no stabilization requirement, and
728
+ # deliberately CORRECTION-INDEPENDENT: BH adjustment (which can only
729
+ # inflate p-values) must never un-flag a stored-significant harm
730
+ # (milestone-review finding).
731
+ left = _num(latest.get("left_bound"))
732
+ right = _num(latest.get("right_bound"))
733
+ sign = (
734
+ 1 if (left is not None and left > 0) else -1 if (right is not None and right < 0) else 0
735
+ )
736
+ regressed = sign != 0 and sign == -desired_sign
737
+ statuses.append(
738
+ GuardrailStatus(
739
+ metric=guardrail.metric,
740
+ name_1=control,
741
+ name_2=treatment,
742
+ regressed=regressed,
743
+ effect=_num(latest.get("effect")),
744
+ desired_direction=guardrail.desired_direction,
745
+ )
746
+ )
747
+ return tuple(statuses)
748
+
749
+
750
+ def _apply_guardrail_policy(
751
+ experiment: ExperimentConfig,
752
+ verdict: VerdictKind,
753
+ guardrails: tuple[GuardrailStatus, ...],
754
+ ) -> tuple[VerdictKind, list[str], list[str]]:
755
+ """D5(c), owner-ratified: block caps WIN; warn keeps WIN with a loud caveat.
756
+
757
+ The regression is always spelled out; LOSE is never upgraded or blocked.
758
+ """
759
+ rationale: list[str] = []
760
+ caveats: list[str] = []
761
+ regressed = [g for g in guardrails if g.regressed]
762
+ if not regressed:
763
+ return verdict, rationale, caveats
764
+ policy = experiment.readout.guardrail_policy
765
+ for g in regressed:
766
+ effect_str = f"effect {g.effect:+.4g}" if g.effect is not None else "effect unavailable"
767
+ message = (
768
+ f"guardrail {g.metric!r} regressed ({effect_str} against desired "
769
+ f"direction {g.desired_direction!r})"
770
+ )
771
+ if verdict == "WIN" and policy == "block":
772
+ rationale.append(f"{message} — WIN withheld (guardrail_policy: block)")
773
+ elif verdict == "WIN":
774
+ caveats.append(f"{message} — verdict kept under guardrail_policy: warn")
775
+ else:
776
+ caveats.append(message)
777
+ if verdict == "WIN" and policy == "block":
778
+ return "INCONCLUSIVE", rationale, caveats
779
+ return verdict, rationale, caveats