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,477 @@
1
+ """The per-experiment pipeline driver + the cross-experiment worker pool.
2
+
3
+ Stage order per experiment (architecture.md §5), all under ONE ``_ab_tasks``
4
+ lock at ``(experiment, "pipeline", "run")`` grain:
5
+
6
+ lock → catalog upsert → LOAD exposures → SRM gate → per comparison:
7
+ plan (grid − computed, ≤ watermark) → per cutoff: load → analyze →
8
+ enrich → persist → release
9
+
10
+ Reliability contract (kept from the reviewed donor):
11
+ - the catalog upsert happens INSIDE the locked section (two concurrent runs
12
+ must not race it);
13
+ - failures are recorded on the lock row BEFORE propagating; ``BaseException``
14
+ (Ctrl+C, SystemExit) is recorded as failed then RE-RAISED;
15
+ - a lock this run did not acquire is never released;
16
+ - the watermark is computed ONCE per run in Python (never now() in SQL).
17
+
18
+ The STATE stage (``_ab_unit_state`` materialization) is deliberately NOT
19
+ wired in v1: the read path is recompute (architecture §5.2 "thin
20
+ materialization"), so writing day-state would double the warehouse scan for
21
+ data nothing reads. The schema, mixins and the §5.2 idempotency invariant are
22
+ locked and tested (WP3); the stage activates when v2 flips the read path.
23
+
24
+ Concurrency (§5.7): experiments are independent series — ``run_experiments``
25
+ fans them out on a thread pool, ONE manager per worker (DB-API connections
26
+ are not thread-safe), locks keeping cross-process runs safe. The M1
27
+ Generator-based RNG made the stats core process/thread-safe.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import math
33
+ from collections.abc import Callable, Sequence
34
+ from concurrent.futures import ThreadPoolExecutor
35
+ from datetime import datetime, timedelta
36
+ from pathlib import Path
37
+
38
+ from abkit.compute.recompute_backend import RecomputeBackend, dialect_of
39
+ from abkit.config.experiment_config import ExperimentConfig
40
+ from abkit.config.metric_config import MetricConfig
41
+ from abkit.config.project_config import ProjectConfig
42
+ from abkit.core.period_planner import backlog_seconds, generate_grid, pending_cutoffs
43
+ from abkit.database.internal_tables import InternalTablesManager
44
+ from abkit.database.manager import BaseDatabaseManager
45
+ from abkit.database.tables import TABLE_EXPOSURES
46
+ from abkit.loaders.exposure_loader import load_exposures
47
+ from abkit.loaders.query_template import RenderWindow, build_builtins
48
+ from abkit.pipeline._types import STATUS_COMPLETED, STATUS_FAILED, PipelineStep, RunOutcome
49
+ from abkit.pipeline.analyze import analyze_cutoff, comparison_alpha, effective_alphas
50
+ from abkit.pipeline.enrich import rows_for_cutoff
51
+ from abkit.stats import (
52
+ DEFAULT_SRM_ALPHA,
53
+ SrmResult,
54
+ get_method_class,
55
+ sequential_multinomial_srm,
56
+ srm_check,
57
+ )
58
+ from abkit.stats.sequential import mixture_tau2, se_from_ci_length
59
+ from abkit.utils.datetime_utils import now_utc_naive
60
+
61
+ LOCK_SCOPE = "pipeline"
62
+ LOCK_PROCESS = "run"
63
+
64
+ Logger = Callable[[str], None]
65
+
66
+
67
+ def _noop_log(_: str) -> None: # pragma: no cover - trivial
68
+ return None
69
+
70
+
71
+ def _sequential_tau2(
72
+ backend,
73
+ experiment,
74
+ comparison,
75
+ metric,
76
+ metric_sql,
77
+ grid,
78
+ alphas,
79
+ project,
80
+ effective_alpha: float,
81
+ ) -> dict[tuple[str, str], float]:
82
+ """Per-pair mixture variance τ² from the FIRST usable grid cutoff (M5 WP3, D-Seq-anchor).
83
+
84
+ τ² is anchored to the earliest look with a usable fixed CI: scan the grid from the
85
+ start, running the fixed analysis (``sequential_tau2=None``), and return
86
+ ``{(name_1, name_2): tau2}`` from the first cutoff that yields usable pairs — stable
87
+ across runs (the first look is idempotent) and computable live (no horizon data
88
+ needed). Empty when the method is sequential-ineligible or no look is usable, so the
89
+ series stays fixed. One extra cutoff load per comparison per run (normally the first).
90
+ """
91
+ method_cls = get_method_class(comparison.method.name)
92
+ if not method_cls.supports_sequential:
93
+ return {}
94
+ for cutoff in grid.cutoffs:
95
+ loaded = backend.load_cutoff(comparison, metric, metric_sql, grid, cutoff)
96
+ outcomes = analyze_cutoff(
97
+ experiment, comparison, metric, loaded, cutoff.end_ts, alphas, project
98
+ )
99
+ tau2: dict[tuple[str, str], float] = {}
100
+ for outcome in outcomes:
101
+ if outcome.result is None:
102
+ continue
103
+ se = se_from_ci_length(outcome.result.ci_length, effective_alpha)
104
+ if math.isfinite(se) and se > 0.0:
105
+ tau2[(outcome.name_1, outcome.name_2)] = mixture_tau2(se * se, effective_alpha)
106
+ if tau2:
107
+ return tau2
108
+ return {}
109
+
110
+
111
+ def _sequential_mode_changed(
112
+ per_pair_kinds: dict[tuple[str, str], set[str]],
113
+ seq_eligible: bool,
114
+ sequential_tau2: dict[tuple[str, str], float] | None,
115
+ ) -> bool:
116
+ """Does the persisted series' ``ci_kind`` disagree with the mode this run stamps?
117
+
118
+ The toggle self-invalidation predicate (M5 WP3, plan B4). Per pair, the mode
119
+ this run would stamp is ``always_valid`` iff the experiment's sequential mode
120
+ is on, the method supports it (``seq_eligible``), AND this pair has a frozen
121
+ τ² — i.e. it is exactly the condition under which ``analyze_cutoff`` widens
122
+ the pair (a pair usable only after the first-usable-look anchor is legitimately
123
+ left ``fixed``). Any persisted non-demoted row of a different kind means the
124
+ ``sequential.enabled`` toggle flipped since the series was written, so the
125
+ driver force-re-plans it. Idempotent: after the re-plan the persisted kinds
126
+ match what this same predicate expects, so the next run plans zero.
127
+ """
128
+ tau2 = sequential_tau2 or {}
129
+ for pair, kinds in per_pair_kinds.items():
130
+ if not kinds:
131
+ continue
132
+ expected = "always_valid" if (seq_eligible and pair in tau2) else "fixed"
133
+ if kinds != {expected}:
134
+ return True
135
+ return False
136
+
137
+
138
+ def run_experiment(
139
+ experiment: ExperimentConfig,
140
+ metrics_by_name: dict[str, MetricConfig],
141
+ project: ProjectConfig,
142
+ manager: BaseDatabaseManager,
143
+ tables: InternalTablesManager,
144
+ steps: Sequence[PipelineStep] = tuple(PipelineStep),
145
+ project_root: Path | None = None,
146
+ experiment_path: Path | None = None,
147
+ now_utc: datetime | None = None,
148
+ force: bool = False,
149
+ full_refresh_window: tuple[datetime, datetime] | None = None,
150
+ log: Logger = _noop_log,
151
+ ) -> RunOutcome:
152
+ """Run the recompute pipeline for one experiment. Returns the outcome."""
153
+ outcome = RunOutcome(experiment=experiment.name)
154
+ steps = list(steps)
155
+ now = now_utc or now_utc_naive()
156
+
157
+ if PipelineStep.LOAD not in steps and PipelineStep.COMPUTE not in steps:
158
+ outcome.status = "skipped"
159
+ return outcome
160
+
161
+ tables.ensure_tables()
162
+ timeout = project.timeouts.compute
163
+ if not tables.acquire_lock(
164
+ experiment.name, LOCK_SCOPE, LOCK_PROCESS, timeout_seconds=timeout, force=force
165
+ ):
166
+ outcome.status = "locked"
167
+ outcome.error = (
168
+ f"experiment '{experiment.name}' is locked by a running pipeline "
169
+ "(abk unlock clears a stale lock)"
170
+ )
171
+ return outcome
172
+
173
+ try:
174
+ # Catalog upsert inside the lock (concurrent runs must not race it).
175
+ alphas = effective_alphas(experiment, project)
176
+ correction = experiment.correction or project.statistics.correction
177
+ tables.upsert_experiment(
178
+ experiment.catalog_record(
179
+ path=str(experiment_path or ""),
180
+ effective_alpha=alphas.alpha,
181
+ effective_correction=correction,
182
+ )
183
+ )
184
+
185
+ # The grid is the single source of the experiment's window bounds —
186
+ # the exposure load below must use the SAME tz-snapped edges the
187
+ # analysis windows use, never naive calendar midnights.
188
+ grid = generate_grid(
189
+ experiment.start_date,
190
+ experiment.end_date,
191
+ experiment.cadence_segments(),
192
+ tz=experiment.timezone,
193
+ limit=project.limits.max_looks,
194
+ )
195
+
196
+ # ── LOAD: the cohort, once per run (§5.5) ────────────────────────────
197
+ log(f"LOAD {experiment.name}: loading exposures")
198
+ assignment_sql = experiment.assignment.get_query_text(project_root)
199
+ assignment_builtins = build_builtins(
200
+ experiment_id=experiment.name,
201
+ unit_key=experiment.unit_key,
202
+ variants=experiment.assignment.variants,
203
+ added_filters=experiment.assignment.added_filters,
204
+ window=RenderWindow(start_ts=grid.start_ts, end_ts=grid.horizon_ts),
205
+ data_database=manager.data_location,
206
+ internal_database=manager.internal_location,
207
+ exposures_table=TABLE_EXPOSURES,
208
+ dialect=dialect_of(manager),
209
+ )
210
+ observed_counts = load_exposures(
211
+ manager, tables, experiment, assignment_sql, assignment_builtins
212
+ )
213
+ outcome.exposures_loaded = sum(observed_counts.values())
214
+
215
+ # ── SRM gate: blocking-but-non-dropping (§5.4) ───────────────────────
216
+ # The watermark is needed here too: the sub-day gate evaluates every
217
+ # COMPLETE look (end_ts ≤ watermark). Computed once per run (never now()
218
+ # in SQL — §6.2).
219
+ watermark_ts = now - timedelta(seconds=experiment.data_lag_seconds())
220
+ srm_by_cutoff: dict[datetime, SrmResult] | None = None
221
+ if experiment.is_sub_day():
222
+ # Sub-day: a dense cadence peeks the χ² hard gate dozens of times a
223
+ # day → false alarms. Swap to the anytime-valid Dirichlet-multinomial
224
+ # e-process (Lindon & Malek 2022; statistics-changes.md §4.2), valid
225
+ # at EVERY look by construction. ONE verdict per look, stamped on
226
+ # that look's rows (the truthful as-of SRM, cumulative-intervals.md
227
+ # §6.5); the run headline is the latest complete look's running
228
+ # verdict. The gate is NOT gated by demotion — counts/SRM stay
229
+ # visible even where inference is withheld (§6.1(4)).
230
+ looks = [c.end_ts for c in grid.cutoffs if c.end_ts <= watermark_ts]
231
+ stream = tables.get_exposure_count_stream(
232
+ experiment.name, looks, list(experiment.assignment.variants)
233
+ )
234
+ look_results = sequential_multinomial_srm(stream, experiment.assignment.expected_split)
235
+ srm_by_cutoff = dict(zip(looks, look_results, strict=True))
236
+ srm = (
237
+ look_results[-1]
238
+ if look_results
239
+ # no complete look yet ⇒ nothing to gate or write; a benign ok.
240
+ else SrmResult(
241
+ pvalue=1.0,
242
+ srm_flag=False,
243
+ alpha=DEFAULT_SRM_ALPHA,
244
+ kind="sequential_multinomial",
245
+ e_value=1.0,
246
+ )
247
+ )
248
+ else:
249
+ # Daily & coarser keep the χ² gate (a bounded daily look count on the
250
+ # strict 0.001 hard gate ⇒ negligible peeking inflation). Zero-fill
251
+ # declared variants absent from the cohort: a missing arm is the
252
+ # worst SRM there is — it must FLAG, not crash the chi-square.
253
+ observed_counts = {
254
+ variant: observed_counts.get(variant, 0)
255
+ for variant in experiment.assignment.variants
256
+ }
257
+ srm = srm_check(observed_counts, experiment.assignment.expected_split)
258
+ outcome.srm_flagged = srm.srm_flag
259
+ if srm.srm_flag:
260
+ log(f"SRM {experiment.name}: {srm.describe()}")
261
+ outcome.warnings.append(srm.describe())
262
+
263
+ if PipelineStep.COMPUTE not in steps:
264
+ tables.release_lock(experiment.name, LOCK_SCOPE, LOCK_PROCESS, STATUS_COMPLETED)
265
+ return outcome
266
+
267
+ # ── PLAN + COMPUTE per comparison ────────────────────────────────────
268
+ backend = RecomputeBackend(manager, experiment, exposures_table=TABLE_EXPOSURES)
269
+
270
+ for comparison in experiment.comparisons:
271
+ metric = metrics_by_name[comparison.metric]
272
+ method_config_id = comparison.method.method_config_id
273
+ metric_sql = metric.get_query_text(project_root)
274
+ effective_alpha = comparison_alpha(comparison, alphas)
275
+
276
+ method_cls = get_method_class(comparison.method.name)
277
+ seq_eligible = experiment.sequential.enabled and method_cls.supports_sequential
278
+
279
+ computed = tables.list_computed_cutoffs(experiment.name, metric.name, method_config_id)
280
+ if full_refresh_window is not None:
281
+ tables.delete_results(
282
+ experiment.name,
283
+ metric=metric.name,
284
+ method_config_id=method_config_id,
285
+ from_ts=full_refresh_window[0],
286
+ to_ts=full_refresh_window[1],
287
+ mutations_sync=True,
288
+ )
289
+ pending = pending_cutoffs(grid, computed, watermark_ts, full_refresh_window)
290
+
291
+ # M5 WP3: freeze τ² once per comparison, anchored to the first usable
292
+ # look (D-Seq-anchor), so every cutoff's always-valid CI shares one
293
+ # mixing prior. It is computed here (not lazily) because it also
294
+ # classifies which pairs SHOULD be always_valid when checking the
295
+ # persisted series for a sequential-mode toggle. Cost: one first-look
296
+ # load per sequential comparison per run (the accepted anytime price).
297
+ sequential_tau2: dict[tuple[str, str], float] | None = None
298
+ if seq_eligible and (pending or computed):
299
+ sequential_tau2 = _sequential_tau2(
300
+ backend,
301
+ experiment,
302
+ comparison,
303
+ metric,
304
+ metric_sql,
305
+ grid,
306
+ alphas,
307
+ project,
308
+ effective_alpha,
309
+ )
310
+
311
+ # M5 WP3 (B4): the toggle self-invalidates. ``sequential.enabled`` is
312
+ # (correctly) not in ``method_config_id``, so the anti-join would skip
313
+ # a flipped-but-fully-computed series and leave stale rows. When the
314
+ # persisted ci_kind disagrees with the mode this run stamps, force a
315
+ # re-plan of the whole series: dropping ``computed`` re-plans every
316
+ # complete cutoff, and the re-saved rows supersede the stale ones by LWW
317
+ # (same PK — ci_kind is not identity-bearing — newer ``created_at``;
318
+ # FINAL/argMax reads collapse to the new rows on every backend). We do
319
+ # NOT delete first: a delete-all would strand any cutoff that a widened
320
+ # ``data_lag`` pushed past the watermark this run (it would be removed
321
+ # but not re-planned), whereas LWW leaves such a cutoff untouched.
322
+ if computed and _sequential_mode_changed(
323
+ tables.series_pair_ci_kinds(experiment.name, metric.name, method_config_id),
324
+ seq_eligible,
325
+ sequential_tau2,
326
+ ):
327
+ computed = set()
328
+ pending = pending_cutoffs(grid, computed, watermark_ts, full_refresh_window)
329
+ log(
330
+ f"MODE {experiment.name}/{metric.name}: sequential mode changed "
331
+ f"(now {'always_valid' if seq_eligible else 'fixed'}) — re-planning "
332
+ "the full series"
333
+ )
334
+
335
+ outcome.cutoffs_planned += len(pending)
336
+ log(
337
+ f"PLAN {experiment.name}/{metric.name}: {len(pending)} pending "
338
+ f"of {len(grid)} looks (alpha={effective_alpha:.6g})"
339
+ )
340
+ # threshold on the TAIL segment's cadence: a dense-early schedule
341
+ # that coarsened to daily must not warn forever on its 1h segment
342
+ lag = backlog_seconds(computed, watermark_ts)
343
+ tail_cadence = experiment.cadence_segments()[-1][0]
344
+ if lag is not None and lag > 3 * tail_cadence:
345
+ outcome.warnings.append(
346
+ f"{experiment.name}/{metric.name}: computed series trails the "
347
+ f"watermark by {lag / 3600.0:.1f}h (> 3 cadence steps) — backlog"
348
+ )
349
+
350
+ # Orphan detection: >1 stored id per metric = duplicate BI lines.
351
+ stored_ids = {
352
+ mc_id
353
+ for (m, mc_id) in tables.list_method_config_ids(experiment.name, metric.name)
354
+ if m == metric.name
355
+ }
356
+ orphaned = stored_ids - {method_config_id}
357
+ if orphaned:
358
+ outcome.warnings.append(
359
+ f"{experiment.name}/{metric.name}: {len(orphaned)} orphaned "
360
+ "method_config_id series in _ab_results (the BI chart will "
361
+ "show duplicate stabilization lines) — run `abk clean`"
362
+ )
363
+
364
+ for cutoff in pending:
365
+ loaded = backend.load_cutoff(comparison, metric, metric_sql, grid, cutoff)
366
+ outcomes = analyze_cutoff(
367
+ experiment,
368
+ comparison,
369
+ metric,
370
+ loaded,
371
+ cutoff.end_ts,
372
+ alphas,
373
+ project,
374
+ sequential_tau2=sequential_tau2,
375
+ )
376
+ # sub-day stamps each look its OWN anytime-valid verdict; daily &
377
+ # coarser broadcast the one whole-cohort χ² gate to every row.
378
+ cutoff_srm = (
379
+ srm_by_cutoff.get(cutoff.end_ts, srm) if srm_by_cutoff is not None else srm
380
+ )
381
+ rows = rows_for_cutoff(
382
+ experiment,
383
+ comparison,
384
+ metric,
385
+ outcomes,
386
+ cutoff,
387
+ grid,
388
+ effective_alpha,
389
+ cutoff_srm,
390
+ watermark_ts,
391
+ metric_query=metric_sql,
392
+ metric_rendered_query=backend.render(
393
+ metric_sql, RenderWindow(grid.start_ts, cutoff.end_ts)
394
+ ),
395
+ )
396
+ outcome.results_written += tables.save_results(rows)
397
+ log(f"RESULT {experiment.name}/{metric.name}: " f"{outcome.results_written} rows total")
398
+
399
+ except BaseException as exc:
400
+ # Record the failure on the lock row BEFORE propagating; Ctrl+C /
401
+ # SystemExit are recorded then re-raised (the reviewed donor contract).
402
+ tables.release_lock(
403
+ experiment.name, LOCK_SCOPE, LOCK_PROCESS, STATUS_FAILED, error_message=str(exc)
404
+ )
405
+ if not isinstance(exc, Exception):
406
+ raise
407
+ outcome.status = STATUS_FAILED
408
+ outcome.error = f"{type(exc).__name__}: {exc}"
409
+ return outcome
410
+
411
+ if not tables.release_lock(experiment.name, LOCK_SCOPE, LOCK_PROCESS, STATUS_COMPLETED):
412
+ outcome.warnings.append(
413
+ f"{experiment.name}: the run outlived its lock timeout and the lock "
414
+ "was taken over — this run's tail may have interleaved with the new "
415
+ "owner (raise timeouts.compute)"
416
+ )
417
+ return outcome
418
+
419
+
420
+ def run_experiments(
421
+ experiments: Sequence[tuple[Path, ExperimentConfig]],
422
+ metrics_by_name: dict[str, MetricConfig],
423
+ project: ProjectConfig,
424
+ manager_factory: Callable[[], BaseDatabaseManager],
425
+ steps: Sequence[PipelineStep] = tuple(PipelineStep),
426
+ project_root: Path | None = None,
427
+ max_workers: int = 1,
428
+ now_utc: datetime | None = None,
429
+ force: bool = False,
430
+ full_refresh_window: tuple[datetime, datetime] | None = None,
431
+ log: Logger = _noop_log,
432
+ ) -> list[RunOutcome]:
433
+ """Run many experiments, optionally on a worker pool (§5.7).
434
+
435
+ ``manager_factory`` builds ONE manager per worker (DB-API connections are
436
+ not thread-safe); the shared ``now_utc`` keeps every experiment's
437
+ watermark consistent within one invocation.
438
+ """
439
+ now = now_utc or now_utc_naive()
440
+
441
+ if max_workers > 1 and len(experiments) > 1:
442
+ # Serialize the first-run DDL: concurrent CREATE SCHEMA/TABLE IF NOT
443
+ # EXISTS intermittently races on PostgreSQL (unique-violation on the
444
+ # catalog); one up-front ensure_tables makes the pool's calls no-ops.
445
+ bootstrap = manager_factory()
446
+ try:
447
+ InternalTablesManager(bootstrap).ensure_tables()
448
+ finally:
449
+ bootstrap.close()
450
+
451
+ def _run_one(item: tuple[Path, ExperimentConfig]) -> RunOutcome:
452
+ path, experiment = item
453
+ manager = manager_factory()
454
+ try:
455
+ tables = InternalTablesManager(manager)
456
+ return run_experiment(
457
+ experiment,
458
+ metrics_by_name,
459
+ project,
460
+ manager,
461
+ tables,
462
+ steps=steps,
463
+ project_root=project_root,
464
+ experiment_path=path,
465
+ now_utc=now,
466
+ force=force,
467
+ full_refresh_window=full_refresh_window,
468
+ log=log,
469
+ )
470
+ finally:
471
+ manager.close()
472
+
473
+ if max_workers <= 1 or len(experiments) <= 1:
474
+ return [_run_one(item) for item in experiments]
475
+
476
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
477
+ return list(pool.map(_run_one, experiments))
@@ -0,0 +1,137 @@
1
+ """The enrich stage: PairOutcomes → the full ``_ab_results`` contract rows.
2
+
3
+ Everything ``TestResult`` lacks is bridged here (the stats-surface §4 map):
4
+ identity (``method_config_id`` off the bound instance; ``method_params`` via
5
+ the ONE canonical serialisation), the window columns, integrity flags
6
+ (SRM broadcast, ``decision_blocked``, ``insufficient_data``), sequence
7
+ columns, the R7 ``warnings``/``diagnostics`` JSON payloads, and provenance.
8
+ ``created_at`` is stamped by ``save_results`` (the strictly-monotonic source).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ from datetime import datetime, timedelta
15
+ from typing import Any
16
+ from zoneinfo import ZoneInfo
17
+
18
+ import numpy as np
19
+
20
+ from abkit.config.experiment_config import ComparisonConfig, ExperimentConfig
21
+ from abkit.config.metric_config import MetricConfig
22
+ from abkit.core.period_planner import Cutoff, Grid
23
+ from abkit.database.internal_tables._results import RESULT_COLUMNS
24
+ from abkit.pipeline.analyze import PairOutcome
25
+ from abkit.stats import SrmResult
26
+ from abkit.utils.json_utils import json_dumps_sorted
27
+
28
+ DAY_SECONDS = 86400.0
29
+ _ONE_US = timedelta(microseconds=1)
30
+
31
+
32
+ def _clean(value: float | None) -> float | None:
33
+ """NaN/inf → None (nullable contract columns)."""
34
+ if value is None:
35
+ return None
36
+ if isinstance(value, float) and not math.isfinite(value):
37
+ return None
38
+ return value
39
+
40
+
41
+ def rows_for_cutoff(
42
+ experiment: ExperimentConfig,
43
+ comparison: ComparisonConfig,
44
+ metric: MetricConfig,
45
+ outcomes: list[PairOutcome],
46
+ cutoff: Cutoff,
47
+ grid: Grid,
48
+ effective_alpha: float,
49
+ srm: SrmResult,
50
+ watermark_ts: datetime,
51
+ metric_query: str,
52
+ metric_rendered_query: str,
53
+ ) -> dict[str, np.ndarray]:
54
+ """Flatten one (comparison, cutoff)'s outcomes into contract-column arrays."""
55
+ rows: list[dict[str, Any]] = []
56
+ window_seconds = int((cutoff.end_ts - grid.start_ts).total_seconds())
57
+ method_config_id = comparison.method.method_config_id
58
+ method_params_json = comparison.method.canonical_params_json
59
+ # Derived dates are EXPERIMENT-timezone dates (§6.3 'legacy-identical at
60
+ # daily cadence' — a Moscow daily experiment's end_date must be the Moscow
61
+ # date, not the UTC date of the naive timestamp).
62
+ zone = ZoneInfo(experiment.timezone)
63
+ utc = ZoneInfo("UTC")
64
+ start_date_local = grid.start_ts.replace(tzinfo=utc).astimezone(zone).date()
65
+ end_date_local = (cutoff.end_ts - _ONE_US).replace(tzinfo=utc).astimezone(zone).date()
66
+
67
+ for outcome in outcomes:
68
+ result = outcome.result
69
+ demoted = result is None
70
+ row: dict[str, Any] = {
71
+ # identity
72
+ "experiment": experiment.name,
73
+ "metric": metric.name,
74
+ "is_main_metric": comparison.is_main_metric,
75
+ "is_guardrail": comparison.is_guardrail,
76
+ "method_name": comparison.method.name,
77
+ "method_params": method_params_json,
78
+ "method_config_id": method_config_id,
79
+ "name_1": outcome.name_1,
80
+ "name_2": outcome.name_2,
81
+ # window (§6.3: end_ts exclusive; dates derived; fractional x-axis)
82
+ "start_ts": grid.start_ts,
83
+ "end_ts": cutoff.end_ts,
84
+ "start_date": start_date_local,
85
+ "end_date": end_date_local,
86
+ "window_seconds": window_seconds,
87
+ "elapsed_days": window_seconds / DAY_SECONDS,
88
+ # per-arm
89
+ "value_1": _clean(result.value_1) if result else None,
90
+ "value_2": _clean(result.value_2) if result else None,
91
+ "std_1": _clean(result.std_1) if result else None,
92
+ "std_2": _clean(result.std_2) if result else None,
93
+ "cov_value_1": _clean(result.cov_value_1) if result else None,
94
+ "cov_value_2": _clean(result.cov_value_2) if result else None,
95
+ "size_1": outcome.size_1,
96
+ "size_2": outcome.size_2,
97
+ # test (withheld under demotion)
98
+ "alpha": effective_alpha,
99
+ "pvalue": _clean(result.pvalue) if result else None,
100
+ "effect": _clean(result.effect) if result else None,
101
+ "left_bound": _clean(result.left_bound) if result else None,
102
+ "right_bound": _clean(result.right_bound) if result else None,
103
+ "ci_length": _clean(result.ci_length) if result else None,
104
+ "reject": bool(result.reject) if result else None,
105
+ "mde_1": _clean(result.mde_1) if result else None,
106
+ "mde_2": _clean(result.mde_2) if result else None,
107
+ # integrity: SRM broadcast; a failed gate blocks the decision but
108
+ # NEVER drops the row (architecture §5.4 — loud, not silent)
109
+ "srm_flag": srm.srm_flag,
110
+ "srm_pvalue": _clean(srm.pvalue),
111
+ "decision_blocked": srm.srm_flag,
112
+ "insufficient_data": demoted,
113
+ # sequence: the method stamps ci_kind ("fixed" by default, "always_valid"
114
+ # under the M5 sequential mode); a demoted row has no CI, so "fixed".
115
+ "ci_kind": result.ci_kind if result else "fixed",
116
+ "is_horizon": cutoff.is_horizon,
117
+ # diagnostics (plan R7 — the human-readable failure signal)
118
+ "warnings": (
119
+ json_dumps_sorted(list(outcome.warnings) + (result.warnings if result else []))
120
+ if (outcome.warnings or (result and result.warnings))
121
+ else None
122
+ ),
123
+ "diagnostics": (
124
+ json_dumps_sorted({k: _clean(v) for k, v in result.diagnostics.items()})
125
+ if result and result.diagnostics
126
+ else None
127
+ ),
128
+ # provenance
129
+ "metric_query": metric_query,
130
+ "metric_rendered_query": metric_rendered_query,
131
+ "watermark_ts": watermark_ts,
132
+ }
133
+ rows.append(row)
134
+
135
+ return {
136
+ column: np.array([row[column] for row in rows], dtype=object) for column in RESULT_COLUMNS
137
+ }