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,484 @@
1
+ """Assemble the experiment report payload from persisted ``_ab_results`` rows.
2
+
3
+ One JSON-serializable payload per **experiment** — the shared contract the
4
+ offline HTML readout (WP3) and the explore cockpit (WP6/WP7) both consume
5
+ (data-contract-and-reporting.md §5.3; m3-implementation-plan.md D6). Kept in
6
+ documented lockstep with the renderer-side ``web/src/shared/payload.ts``
7
+ (WP3) — same keys, same units.
8
+
9
+ The payload derives from **stored** rows (including their persisted
10
+ ``method_params``/``alpha``/``srm_flag``), not from re-evaluating what the
11
+ current YAML would produce — the report shows *what actually ran* (the donor
12
+ doctrine). Header metadata comes from the experiment config (the truth);
13
+ ``_ab_experiments`` is informational only and never read here.
14
+
15
+ Units and null discipline (§5.3): timestamps are integer ms-epoch (UTC);
16
+ every nullable numeric passes through :func:`_num_or_none`, so NaN **and
17
+ ±inf** become JSON ``null`` (H5 zero-denominator NaNs; the verdict's
18
+ ``pair_mde`` ``math.inf`` = "configured but unavailable" — the rationale
19
+ strings carry the explanation). No NaN, numpy scalar, or datetime object ever
20
+ reaches the returned dict.
21
+
22
+ Cost discipline: per-point MDE reads the **stored** columns only — the
23
+ read-time D5(b) solve runs once per pair on the latest cutoff (the verdict),
24
+ never per historical point (a statsmodels root-solve × O(cutoffs) would cost
25
+ seconds-to-minutes at sub-day cadence; review finding).
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import math
31
+ from collections.abc import Mapping
32
+ from datetime import datetime
33
+ from itertools import combinations
34
+ from typing import Any
35
+
36
+ import numpy as np
37
+
38
+ from abkit.config.experiment_config import ComparisonConfig, ExperimentConfig
39
+ from abkit.config.metric_config import MetricConfig
40
+ from abkit.config.project_config import ProjectConfig
41
+ from abkit.core.period_planner import generate_grid
42
+ from abkit.database.internal_tables import InternalTablesManager
43
+ from abkit.pipeline.readout import ExperimentReadout, PairVerdict, evaluate, srm_summary
44
+ from abkit.reporting.calibration import build_calibration_block
45
+ from abkit.utils.datetime_utils import to_naive_utc
46
+ from abkit.utils.json_utils import json_loads
47
+
48
+ #: the payload schema version (§5.3) — bump on breaking key/unit changes
49
+ PAYLOAD_VERSION = 1
50
+
51
+ #: total point budget across metrics × pairs × cutoffs; exceeding it clips
52
+ #: every series to its trailing window and adds a top-level payload warning
53
+ #: (the donor capped at 1500 points for one series; an experiment payload
54
+ #: carries many series, so the budget is global)
55
+ REPORT_POINT_BUDGET = 20_000
56
+
57
+
58
+ def _ms(value: Any) -> int:
59
+ """Coerce a datetime / datetime64 to integer ms-epoch (UTC)."""
60
+ if isinstance(value, datetime):
61
+ value = to_naive_utc(value)
62
+ return int(np.datetime64(value, "ms").astype("int64"))
63
+
64
+
65
+ def _num_or_none(value: Any) -> float | None:
66
+ """Pass a stored Nullable number through; NaN/±inf/None become ``None``.
67
+
68
+ The inf clause extends the donor helper: ``pair_mde`` uses ``math.inf``
69
+ for "``calculate_mde: true`` but columns are NULL", and JSON ``Infinity``
70
+ is invalid in browsers — serialization only, no statistical number
71
+ changes.
72
+ """
73
+ if value is None:
74
+ return None
75
+ try:
76
+ f = float(value)
77
+ except (TypeError, ValueError):
78
+ return None
79
+ return f if math.isfinite(f) else None
80
+
81
+
82
+ def _flag01(value: Any) -> int:
83
+ """A stored Bool cell (bool / 0-1 int / numpy) as a terse 0/1 point flag."""
84
+ return 1 if value else 0
85
+
86
+
87
+ def _reject_flag(value: Any) -> int | None:
88
+ """``reject`` is Nullable(Bool): None = inference withheld (demoted)."""
89
+ if value is None:
90
+ return None
91
+ return 1 if value else 0
92
+
93
+
94
+ def _parse_json_cell(value: Any) -> Any:
95
+ """Parse a stored canonical-JSON cell (str | None); never raises."""
96
+ if value is None or value == "":
97
+ return None
98
+ if isinstance(value, (dict, list)):
99
+ return value
100
+ try:
101
+ return json_loads(value)
102
+ except (TypeError, ValueError):
103
+ return None
104
+
105
+
106
+ def _stored_pair_mde(row: dict) -> float | None:
107
+ """The per-point pair MDE from the **stored** columns only (D5(b) combine).
108
+
109
+ Deliberately no read-time ``pair_mde`` solve here: that runs a statsmodels
110
+ root-solve per t/z row, and cumulative windows give every cutoff a unique
111
+ ``(size, ratio)`` — so the whole series would cost O(cutoffs) solves
112
+ (seconds-to-minutes at sub-day cadence; review finding). The point series
113
+ honestly shows *what actually ran*: MDE where the row computed it
114
+ (``calculate_mde: true``), null otherwise. The read-time D5(b) fallback
115
+ stays where the FLAT decision needs it — the **verdict**, one solve per
116
+ pair on the latest cutoff (readout ``pair_mde``).
117
+
118
+ The **both-present guard** mirrors readout ``pair_mde``: enrich NULLs a
119
+ non-finite solve, so a half-present pair means one arm is undetectable —
120
+ taking the finite arm alone would fake adequate power (the exact trap the
121
+ verdict path guards; review finding). Half-present ⇒ null, never the
122
+ finite arm."""
123
+ mde_1, mde_2 = _num_or_none(row.get("mde_1")), _num_or_none(row.get("mde_2"))
124
+ if mde_1 is None or mde_2 is None:
125
+ return None
126
+ return max(abs(mde_1), abs(mde_2))
127
+
128
+
129
+ def _point(row: dict) -> dict:
130
+ """One ``_ab_results`` row → the terse §5.3 series point.
131
+
132
+ ``mde`` is the per-point pair MDE from the stored columns (:func:
133
+ `_stored_pair_mde`). Demoted rows pass their NULL test columns through as
134
+ nulls; sizes stay real. ``v1/v2/sd1/sd2/cv1/cv2`` are the per-arm stored
135
+ values/stds/CUPED covariate means — the WP3 additive extension (no v-bump)
136
+ feeding the §5.2 "variant means/lift" and §3 view-2 renderings; ``cv*`` is
137
+ null for non-CUPED rows.
138
+ """
139
+ return {
140
+ "t": _ms(row["end_ts"]),
141
+ "ed": _num_or_none(row.get("elapsed_days")),
142
+ "e": _num_or_none(row.get("effect")),
143
+ "lo": _num_or_none(row.get("left_bound")),
144
+ "hi": _num_or_none(row.get("right_bound")),
145
+ "p": _num_or_none(row.get("pvalue")),
146
+ "rj": _reject_flag(row.get("reject")),
147
+ "s1": int(row.get("size_1") or 0),
148
+ "s2": int(row.get("size_2") or 0),
149
+ "v1": _num_or_none(row.get("value_1")),
150
+ "v2": _num_or_none(row.get("value_2")),
151
+ "sd1": _num_or_none(row.get("std_1")),
152
+ "sd2": _num_or_none(row.get("std_2")),
153
+ "cv1": _num_or_none(row.get("cov_value_1")),
154
+ "cv2": _num_or_none(row.get("cov_value_2")),
155
+ "mde": _stored_pair_mde(row),
156
+ "hz": _flag01(row.get("is_horizon")),
157
+ "blk": _flag01(row.get("decision_blocked")),
158
+ "ins": _flag01(row.get("insufficient_data")),
159
+ }
160
+
161
+
162
+ def _verdict_to_payload(verdict: PairVerdict) -> dict:
163
+ """A WP1 :class:`PairVerdict` → the JSON-safe §5.3 verdict entry."""
164
+ return {
165
+ "metric": verdict.metric,
166
+ "pair": {"c": verdict.name_1, "t": verdict.name_2},
167
+ "verdict": verdict.verdict,
168
+ "rationale": list(verdict.rationale),
169
+ "caveats": list(verdict.caveats),
170
+ "significant": bool(verdict.significant),
171
+ "effect": _num_or_none(verdict.effect),
172
+ "pvalue": _num_or_none(verdict.pvalue),
173
+ "lo": _num_or_none(verdict.left_bound),
174
+ "hi": _num_or_none(verdict.right_bound),
175
+ "alpha": _num_or_none(verdict.alpha),
176
+ "mde": _num_or_none(verdict.mde),
177
+ "min_effect": _num_or_none(verdict.min_effect),
178
+ "end_ts": _ms(verdict.end_ts) if verdict.end_ts is not None else None,
179
+ "elapsed_days": _num_or_none(verdict.elapsed_days),
180
+ "is_horizon": bool(verdict.is_horizon),
181
+ # §6.5 representativeness chip: the weekly-cycle coverage fraction on an
182
+ # early decisive verdict (null otherwise); the report promotes it to a
183
+ # rendered chip rather than leaving it a caveat bullet.
184
+ "weekly_cycle_pct": _num_or_none(verdict.weekly_cycle_pct),
185
+ "guardrails": [
186
+ {
187
+ "metric": g.metric,
188
+ "pair": {"c": g.name_1, "t": g.name_2},
189
+ "regressed": bool(g.regressed),
190
+ "effect": _num_or_none(g.effect),
191
+ "desired_direction": g.desired_direction,
192
+ }
193
+ for g in verdict.guardrails
194
+ ],
195
+ }
196
+
197
+
198
+ def _window_filter(rows: list[dict], start: datetime | None, end: datetime | None) -> list[dict]:
199
+ """Keep rows with ``start <= end_ts <= end`` (both bounds inclusive).
200
+
201
+ Pinning ``end`` before the latest cutoff replays the report as-of that
202
+ moment — the readout then verdicts on the historical state (the donor's
203
+ replay stance).
204
+ """
205
+ if start is None and end is None:
206
+ return rows
207
+ kept = []
208
+ for row in rows:
209
+ end_ts = row["end_ts"]
210
+ if start is not None and end_ts < start:
211
+ continue
212
+ if end is not None and end_ts > end:
213
+ continue
214
+ kept.append(row)
215
+ return kept
216
+
217
+
218
+ def _metric_entry(
219
+ comparison: ComparisonConfig,
220
+ rows: list[dict],
221
+ variants: list[str],
222
+ metric_configs: Mapping[str, MetricConfig] | None,
223
+ ) -> dict:
224
+ """One configured comparison → the §5.3 ``metrics[]`` entry.
225
+
226
+ ``description`` comes from the metric YAML config (D6 — ``_ab_experiments``
227
+ stores only the experiment description). ``method``/``query``/``alpha``
228
+ prefer the latest stored row (what actually ran); config values are the
229
+ fallback for a never-run comparison. Provenance is deduped to one
230
+ ``query`` entry per metric; the rendered SQL never enters the payload.
231
+ """
232
+ metric_config = (metric_configs or {}).get(comparison.metric)
233
+
234
+ by_pair: dict[tuple[str, str], list[dict]] = {}
235
+ for row in rows:
236
+ by_pair.setdefault((str(row["name_1"]), str(row["name_2"])), []).append(row)
237
+
238
+ latest: dict | None = None
239
+ for group in by_pair.values():
240
+ candidate = group[-1]
241
+ if latest is None or candidate["end_ts"] > latest["end_ts"]:
242
+ latest = candidate
243
+
244
+ method_params = None
245
+ if latest is not None:
246
+ method_params = _parse_json_cell(latest.get("method_params"))
247
+ if method_params is None:
248
+ method_params = _parse_json_cell(comparison.method.canonical_params_json) or {}
249
+
250
+ warnings: list[str] = []
251
+ seen_warnings: set[str] = set()
252
+ for row in rows:
253
+ for warning in _parse_json_cell(row.get("warnings")) or []:
254
+ text = str(warning)
255
+ if text not in seen_warnings:
256
+ seen_warnings.add(text)
257
+ warnings.append(text)
258
+
259
+ pairs = []
260
+ for name_1, name_2 in combinations(variants, 2):
261
+ group = by_pair.get((name_1, name_2), [])
262
+ pairs.append(
263
+ {
264
+ "c": name_1,
265
+ "t": name_2,
266
+ "series": [_point(row) for row in group],
267
+ "diag": _parse_json_cell(group[-1].get("diagnostics")) if group else None,
268
+ }
269
+ )
270
+
271
+ return {
272
+ "name": comparison.metric,
273
+ "description": metric_config.description if metric_config is not None else None,
274
+ "main": bool(comparison.is_main_metric),
275
+ "guardrail": bool(comparison.is_guardrail),
276
+ "method": {
277
+ "name": comparison.method.name,
278
+ "params": method_params,
279
+ "id": comparison.method.method_config_id,
280
+ "alpha": _num_or_none(latest.get("alpha")) if latest is not None else None,
281
+ },
282
+ "query": str(latest.get("metric_query")) if latest is not None else None,
283
+ "pairs": pairs,
284
+ "warnings": warnings,
285
+ }
286
+
287
+
288
+ def _clip_to_budget(metrics: list[dict], max_points: int) -> str | None:
289
+ """Enforce the global point budget by trailing-window truncation.
290
+
291
+ Runs AFTER the readout evaluated the full series — clipping affects only
292
+ what gets baked, never the verdict. Returns the payload warning when
293
+ anything was dropped (no silent caps)."""
294
+ series_list = [pair["series"] for metric in metrics for pair in metric["pairs"]]
295
+ non_empty = [s for s in series_list if s]
296
+ total = sum(len(s) for s in non_empty)
297
+ if total <= max_points or not non_empty:
298
+ return None
299
+ allowed = max(1, max_points // len(non_empty))
300
+ dropped = 0
301
+ for metric in metrics:
302
+ for pair in metric["pairs"]:
303
+ series = pair["series"]
304
+ if len(series) > allowed:
305
+ dropped += len(series) - allowed
306
+ pair["series"] = series[-allowed:]
307
+ return (
308
+ f"payload clipped to the trailing {allowed} cutoffs per series "
309
+ f"({total} points exceeded the {max_points}-point budget; "
310
+ f"{dropped} older points dropped — pin start/end to window explicitly)"
311
+ )
312
+
313
+
314
+ def build_report_payload(
315
+ experiment: ExperimentConfig,
316
+ tables: InternalTablesManager,
317
+ *,
318
+ project: ProjectConfig | None = None,
319
+ metric_configs: Mapping[str, MetricConfig] | None = None,
320
+ generated_at: str | None = None,
321
+ start: datetime | None = None,
322
+ end: datetime | None = None,
323
+ max_points: int = REPORT_POINT_BUDGET,
324
+ ) -> dict:
325
+ """Read ``_ab_results`` for one experiment and assemble the §5.3 payload.
326
+
327
+ ``start``/``end`` bound the report window on ``end_ts`` (both inclusive);
328
+ pinning ``end`` replays the readout as-of a historical cutoff.
329
+ ``generated_at`` is a caller-supplied preformatted string — the builder
330
+ never reads the wall clock (determinism; the CLI owns formatting).
331
+ ``project`` resolves the effective correction for the readout (BH is
332
+ read-time) and names the payload; ``metric_configs`` supplies the metric
333
+ descriptions (D6). On a never-run project (no ``_ab_results`` table) every
334
+ key is still present with empty series — reporting never creates schema.
335
+ """
336
+ if start is not None:
337
+ start = to_naive_utc(start)
338
+ if end is not None:
339
+ end = to_naive_utc(end)
340
+
341
+ grid = generate_grid(
342
+ experiment.start_date,
343
+ experiment.end_date,
344
+ experiment.cadence_segments(),
345
+ experiment.timezone,
346
+ )
347
+ variants = list(experiment.assignment.variants)
348
+
349
+ declared_pairs = set(combinations(variants, 2))
350
+ ready = tables.results_table_exists()
351
+ declared_by_comparison: dict[str, list[dict]] = {}
352
+ rows_by_comparison: dict[str, list[dict]] = {}
353
+ stale_by_metric: dict[str, int] = {}
354
+ for comparison in experiment.comparisons:
355
+ loaded = (
356
+ tables.load_results(
357
+ experiment.name, comparison.metric, comparison.method.method_config_id
358
+ )
359
+ if ready
360
+ else []
361
+ )
362
+ # pairs outside the declared variants (a mid-flight arm rename) are
363
+ # not chartable; drop them from EVERY payload surface — series, look,
364
+ # period, latest-row method block — loudly, never silently
365
+ declared = [
366
+ row for row in loaded if (str(row["name_1"]), str(row["name_2"])) in declared_pairs
367
+ ]
368
+ if len(declared) != len(loaded):
369
+ stale_by_metric[comparison.metric] = len(loaded) - len(declared)
370
+ declared_by_comparison[comparison.metric] = declared
371
+ # the chart + verdict are as-of the window; the SRM block is not
372
+ rows_by_comparison[comparison.metric] = _window_filter(declared, start, end)
373
+
374
+ charted_rows = [row for rows in rows_by_comparison.values() for row in rows]
375
+ declared_rows = [row for rows in declared_by_comparison.values() for row in rows]
376
+ readout: ExperimentReadout = evaluate(experiment, charted_rows, project=project)
377
+
378
+ # SRM block — CURRENT experiment health, window-independent (§6 "SRM loud"):
379
+ # flag/pvalue come from the latest persisted row overall (not the latest
380
+ # *charted* row), so a pinned/empty replay never silences a failing gate.
381
+ # `observed` is the whole-cohort current split; at daily+ (χ²) it is the
382
+ # gate's own input, while below 1d (the anytime e-process, WP5) the flag is
383
+ # the latest look's running verdict — so a since-rebalanced sub-day cohort
384
+ # can read "FAILED" with a now-even split (an imbalance WAS detected). The
385
+ # chip names the gate via `srm.kind` so this reads correctly, not as χ².
386
+ srm_flag, srm_pvalue = srm_summary(experiment, declared_rows)
387
+ observed_counts: dict[str, int] = {}
388
+ if ready and tables.exposures_table_exists():
389
+ observed_counts = tables.get_exposure_counts(experiment.name)
390
+ # zero-fill declared variants, mirroring the driver's SRM gate input
391
+ observed = {variant: int(observed_counts.get(variant, 0)) for variant in variants}
392
+
393
+ metrics = [
394
+ _metric_entry(comparison, rows_by_comparison[comparison.metric], variants, metric_configs)
395
+ for comparison in experiment.comparisons
396
+ ]
397
+
398
+ # calibration block (M4): the latest `abk validate` matrix for this experiment,
399
+ # read-only (never creates schema — the `aa_runs_table_exists` guard). Independent
400
+ # of `_ab_results` (a validate-only project still shows its matrix). `null` until
401
+ # the first validate run, so the chip reads the M3 "uncalibrated" empty state
402
+ # (data-contract §5.3; the M4 shape lands without a payload v-bump).
403
+ calibration = None
404
+ if tables.aa_runs_table_exists():
405
+ calibration = build_calibration_block(tables.get_aa_runs(experiment.name))
406
+
407
+ warnings = list(readout.warnings)
408
+ for metric_name, dropped in stale_by_metric.items():
409
+ warnings.append(
410
+ f"{experiment.name}/{metric_name}: {dropped} persisted rows are for "
411
+ "variant pairs outside the declared variants (renamed arms?) — not "
412
+ "charted"
413
+ )
414
+ if ready:
415
+ # the driver's orphan scan, surfaced on the read path too: an edited
416
+ # method leaves the old series in _ab_results and the report would
417
+ # otherwise show a silently truncated history
418
+ stored_ids = tables.list_method_config_ids(experiment.name)
419
+ for comparison in experiment.comparisons:
420
+ orphaned = {
421
+ mc_id for (metric_name, mc_id) in stored_ids if metric_name == comparison.metric
422
+ } - {comparison.method.method_config_id}
423
+ if orphaned:
424
+ warnings.append(
425
+ f"{experiment.name}/{comparison.metric}: {len(orphaned)} orphaned "
426
+ "method_config_id series in _ab_results (the BI chart will "
427
+ "show duplicate stabilization lines) — run `abk clean`"
428
+ )
429
+ clip_warning = _clip_to_budget(metrics, max_points)
430
+ if clip_warning is not None:
431
+ warnings.append(clip_warning)
432
+
433
+ # look counter (§4): n = charted cutoffs where inference actually happened
434
+ # (at least one non-demoted row); planned = the one-enumeration grid length
435
+ informative_cutoffs = {
436
+ row["end_ts"] for row in charted_rows if not row.get("insufficient_data")
437
+ }
438
+ latest_end_ts = max((row["end_ts"] for row in charted_rows), default=None)
439
+
440
+ return {
441
+ "v": PAYLOAD_VERSION,
442
+ "experiment": experiment.name,
443
+ "project": project.name if project is not None else None,
444
+ "generated_at": generated_at,
445
+ "description": experiment.description,
446
+ "period": {
447
+ "start": _ms(grid.start_ts),
448
+ # 0 = no persisted cutoffs (the donor's empty sentinel); start
449
+ # and horizon stay real — they are config facts, not data facts
450
+ "end": _ms(latest_end_ts) if latest_end_ts is not None else 0,
451
+ "horizon": _ms(grid.horizon_ts),
452
+ },
453
+ "cadence_seconds": experiment.cadence_seconds_min(),
454
+ "tz": experiment.timezone,
455
+ "arms": variants,
456
+ "srm": {
457
+ "flag": bool(srm_flag),
458
+ "pvalue": _num_or_none(srm_pvalue),
459
+ "observed": observed,
460
+ "expected": {
461
+ variant: float(split)
462
+ for variant, split in experiment.assignment.expected_split.items()
463
+ },
464
+ # which gate produced flag/pvalue, so the chip names the right test:
465
+ # χ² at daily+, the anytime-valid e-process below 1d (WP5). Not
466
+ # persisted, so derived from the current cadence (statistics-changes §4.2).
467
+ "kind": "sequential_multinomial" if experiment.is_sub_day() else "chi2",
468
+ },
469
+ # the latest A/A validate matrix (M4); null until first `abk validate`.
470
+ # The M4 shape (fpr, peeking_fpr, headline, matrix_rows, report_link) fills
471
+ # in without a payload v-bump (§5.3; every field renderer-side optional).
472
+ "calibration": calibration,
473
+ "verdicts": [_verdict_to_payload(v) for v in readout.verdicts],
474
+ "metrics": metrics,
475
+ "look": {"n": len(informative_cutoffs), "planned": len(grid)},
476
+ # injected by the explore server at serve time; null in a baked report
477
+ "endpoints": {
478
+ "save_url": None,
479
+ "recompute_url": None,
480
+ "reload_url": None,
481
+ "validate_url": None,
482
+ },
483
+ "warnings": warnings,
484
+ }
@@ -0,0 +1,182 @@
1
+ """Assemble the report/explore ``calibration`` payload block from ``_ab_aa_runs`` rows.
2
+
3
+ The A/A matrix's analyst-facing clarity IS the M4 feature (aa-false-positive-matrix.md
4
+ §4): the readout report and the explore chip both surface *"nominal α X%, real peeking
5
+ FPR Y%"* plus the per-method matrix with a Recommended row. This module maps the
6
+ persisted audit rows (the as-built ``_ab_aa_runs`` shape, tables.py:224–263) into the
7
+ ``CalibrationBlock`` contract the renderer consumes (web/src/shared/payload.ts) — kept
8
+ in documented lockstep with that TS interface, the ``builder.py`` doctrine.
9
+
10
+ Row selection: one ``abk validate`` invocation writes a whole matrix under a shared
11
+ ``run_stamp`` (the ``{run_stamp}:{cell_hash}`` id, D4). The matrix shown is the **latest
12
+ invocation's** — all rows whose ``run_id`` prefix matches the newest row's ``run_stamp``
13
+ — so the Recommended row and its peers are always internally coherent (never a mix of
14
+ runs). The D3 chip lookup (``find_calibration``) is independent and keeps its own
15
+ newest-per-cell semantics; this block is display-only.
16
+
17
+ Pure: no DB, no clock, no NaN/inf leaks (every number passes ``_num``).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import math
23
+ from typing import Any
24
+
25
+ from abkit.utils.json_utils import json_loads
26
+
27
+
28
+ def _num(value: Any) -> float | None:
29
+ """A stored Nullable number → float, or ``None`` for NULL / NaN / ±inf."""
30
+ if value is None:
31
+ return None
32
+ try:
33
+ f = float(value)
34
+ except (TypeError, ValueError):
35
+ return None
36
+ return f if math.isfinite(f) else None
37
+
38
+
39
+ def _details(row: dict) -> dict:
40
+ """Parse the ``details`` JSON cell (stored as a string) into a dict."""
41
+ raw = row.get("details")
42
+ if isinstance(raw, dict):
43
+ return raw
44
+ if not raw:
45
+ return {}
46
+ try:
47
+ parsed = json_loads(raw)
48
+ except (ValueError, TypeError):
49
+ return {}
50
+ return parsed if isinstance(parsed, dict) else {}
51
+
52
+
53
+ def _run_stamp(row: dict) -> str:
54
+ """The invocation stamp — the ``run_id`` prefix before the ``:`` (D4)."""
55
+ return str(row.get("run_id", "")).split(":", 1)[0]
56
+
57
+
58
+ def _pct(value: float | None) -> str:
59
+ return "—" if value is None else f"{value * 100:.1f}%"
60
+
61
+
62
+ def _curve(details: dict, key: str) -> list[list[float]] | None:
63
+ """A stored ``[[x, y], ...]`` curve → a clean float list, or ``None``."""
64
+ raw = details.get(key)
65
+ if not isinstance(raw, list) or not raw:
66
+ return None
67
+ return [[float(p[0]), float(p[1])] for p in raw if isinstance(p, (list, tuple)) and len(p) == 2]
68
+
69
+
70
+ def _matrix_row(row: dict) -> dict:
71
+ """One persisted ``_ab_aa_runs`` row → a renderer ``CalibrationRow``."""
72
+ details = _details(row)
73
+ fpr = _num(row.get("fpr"))
74
+ budget = _num(row.get("budget"))
75
+ if budget is None:
76
+ budget = _num(details.get("budget"))
77
+ over_budget = fpr is not None and budget is not None and fpr > budget
78
+ peeking_curve = _curve(details, "peeking_curve")
79
+ kept = details.get("kept_grid_points")
80
+ total = details.get("total_grid_points")
81
+ note = None
82
+ if isinstance(kept, int) and isinstance(total, int) and kept < total:
83
+ note = f"{kept}/{total} looks scored (denser-early subsample)"
84
+ return {
85
+ "metric": row.get("metric"),
86
+ "method": row.get("method_name"),
87
+ "method_config_id": row.get("method_config_id"),
88
+ "fpr": fpr,
89
+ "single_look_fpr": _num(details.get("single_look_fpr")),
90
+ "peeking_fpr": _num(row.get("peeking_fpr")),
91
+ "power": _num(row.get("power")),
92
+ "achieved_mde": _num(row.get("achieved_mde")),
93
+ "coverage": _num(row.get("coverage")),
94
+ "effect_exaggeration": _num(row.get("effect_exaggeration")),
95
+ "alpha": _num(row.get("alpha")),
96
+ "budget": budget,
97
+ "over_budget": over_budget,
98
+ "recommended": bool(details.get("recommended", False)),
99
+ "rationale": details.get("recommended_rationale"),
100
+ "verdict": row.get("verdict") or "",
101
+ "status": row.get("status") or "success",
102
+ "iterations": row.get("iterations"),
103
+ "injected_effect": _num(row.get("injected_effect")),
104
+ "peeking_curve": peeking_curve,
105
+ "note": note,
106
+ # M5 D8 — the always-valid column, side-by-side (m5-implementation-plan §WP2)
107
+ "fpr_sequential": _num(row.get("fpr_sequential")),
108
+ "peeking_fpr_sequential": _num(row.get("peeking_fpr_sequential")),
109
+ "power_sequential": _num(row.get("power_sequential")),
110
+ "coverage_sequential": _num(row.get("coverage_sequential")),
111
+ "effect_exaggeration_sequential": _num(row.get("effect_exaggeration_sequential")),
112
+ "ci_width": _num(row.get("ci_width")),
113
+ "ci_width_sequential": _num(row.get("ci_width_sequential")),
114
+ "peeking_curve_sequential": _curve(details, "peeking_curve_sequential"),
115
+ }
116
+
117
+
118
+ def _headline(rows: list[dict], lead: dict) -> str:
119
+ """The one-line "nominal α X%, real peeking FPR Y%" story (R10)."""
120
+ alpha = lead.get("alpha")
121
+ single = lead.get("single_look_fpr")
122
+ if single is None:
123
+ single = lead.get("fpr")
124
+ peeking = lead.get("peeking_fpr")
125
+ alpha_txt = "—" if alpha is None else f"{alpha * 100:.1f}%"
126
+ parts = [f"nominal α {alpha_txt}", f"single-look FPR {_pct(single)}"]
127
+ if peeking is not None:
128
+ seg = f"peeking FPR {_pct(peeking)}"
129
+ peeking_seq = lead.get("peeking_fpr_sequential")
130
+ if peeking_seq is not None:
131
+ seg += f" → always-valid {_pct(peeking_seq)}" # the D8 recovery story
132
+ parts.append(seg)
133
+ over = [r for r in rows if r["over_budget"]]
134
+ if over:
135
+ parts.append(f"{len(over)} method(s) over budget")
136
+ return " · ".join(parts)
137
+
138
+
139
+ def build_calibration_block(aa_rows: list[dict], *, report_link: str | None = None) -> dict | None:
140
+ """Map ``_ab_aa_runs`` rows → the ``calibration`` payload block, or ``None``.
141
+
142
+ ``aa_rows`` are persisted rows (``get_aa_runs`` order — newest ``created_at``
143
+ first); only the latest invocation's rows are surfaced. Returns ``None`` when
144
+ there are no rows at all (the M3 empty state — the chip reads "uncalibrated").
145
+ """
146
+ if not aa_rows:
147
+ return None
148
+
149
+ # newest invocation: the run_stamp of the newest-created row (get_aa_runs is
150
+ # already ordered created_at DESC, but don't rely on it — pick explicitly).
151
+ def _created(row: dict) -> tuple[bool, Any]:
152
+ c = row.get("created_at")
153
+ return (c is not None, c)
154
+
155
+ newest = max(aa_rows, key=_created)
156
+ stamp = _run_stamp(newest)
157
+ invocation = [row for row in aa_rows if _run_stamp(row) == stamp]
158
+
159
+ matrix_rows = [_matrix_row(row) for row in invocation]
160
+ # sort for a stable, readable matrix: by metric, recommended first, then FPR
161
+ matrix_rows.sort(
162
+ key=lambda r: (
163
+ str(r["metric"]),
164
+ not r["recommended"],
165
+ r["fpr"] if r["fpr"] is not None else 1.0,
166
+ )
167
+ )
168
+ # the lead row anchors the headline + chip: the recommended row if any,
169
+ # else the first successful row with a measured FPR, else the first row.
170
+ lead = next(
171
+ (r for r in matrix_rows if r["recommended"]),
172
+ next((r for r in matrix_rows if r["fpr"] is not None), matrix_rows[0]),
173
+ )
174
+ return {
175
+ "fpr": lead["fpr"],
176
+ "peeking_fpr": lead["peeking_fpr"],
177
+ "alpha": lead["alpha"],
178
+ "budget": lead["budget"],
179
+ "headline": _headline(matrix_rows, lead),
180
+ "matrix_rows": matrix_rows,
181
+ "report_link": report_link,
182
+ }