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,282 @@
1
+ """Implementation of ``abk run`` — the pipeline driver command.
2
+
3
+ VALIDATE (config-lint, no DB) always runs first; the effective per-comparison
4
+ alphas are echoed (the inspectable two-tier scheme, declarative-config.md §6);
5
+ SRM failures print the loud red gate line (data-contract §6). Any failed
6
+ experiment or validation error exits NON-ZERO (the CLI is the Prefect unit of
7
+ automation).
8
+
9
+ ``--report`` (tri-state: absent / bare / path — the donor's flag shape) emits
10
+ one self-contained HTML readout per experiment after its pipeline, inside
11
+ try/except: a report failure yellow-skips and NEVER fails the run — the one
12
+ recorded exception to the exit-non-zero contract (m3-implementation-plan.md
13
+ WP3/D8). Emission happens even when zero cutoffs were pending — re-running an
14
+ up-to-date experiment is the "just give me the report" path (D8).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ from datetime import datetime
21
+ from pathlib import Path
22
+
23
+ import click
24
+
25
+ from abkit.cli._output import (
26
+ StageLogRenderer,
27
+ echo_done,
28
+ echo_error,
29
+ echo_noop,
30
+ echo_srm,
31
+ echo_tree,
32
+ )
33
+ from abkit.cli.commands._context import load_project_context
34
+ from abkit.config import select_experiments, validate_level2
35
+ from abkit.config.experiment_config import ExperimentConfig
36
+ from abkit.pipeline import PipelineStep, effective_alphas, run_experiments
37
+ from abkit.stats import n_comparisons
38
+
39
+
40
+ def _parse_date(value: str | None, option: str) -> datetime | None:
41
+ if value is None:
42
+ return None
43
+ for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
44
+ try:
45
+ return datetime.strptime(value, fmt)
46
+ except ValueError:
47
+ continue
48
+ raise click.BadParameter(
49
+ f"invalid {option} value {value!r} (use YYYY-MM-DD or 'YYYY-MM-DD HH:MM:SS')"
50
+ )
51
+
52
+
53
+ def _resolve_report_path(report_path: str, project_root: Path, experiment: str) -> Path:
54
+ """The donor's path convention: "" → reports/<experiment>.html under the
55
+ project root; a ``.html`` value → that exact file; anything else → a
56
+ directory getting ``/<experiment>.html`` appended."""
57
+ if report_path == "":
58
+ return project_root / "reports" / f"{experiment}.html"
59
+ candidate = Path(report_path)
60
+ if candidate.suffix.lower() == ".html":
61
+ return candidate
62
+ return candidate / f"{experiment}.html"
63
+
64
+
65
+ def _emit_experiment_report(
66
+ experiment: ExperimentConfig,
67
+ tables,
68
+ context,
69
+ report_path: str,
70
+ generated_at: str,
71
+ ) -> None:
72
+ """Build + write one experiment readout; prints the house report line.
73
+
74
+ Raises on failure — the caller owns the yellow-skip (never fail the run
75
+ on a report)."""
76
+ from abkit.reporting import build_report_payload, render_report_html
77
+
78
+ payload = build_report_payload(
79
+ experiment,
80
+ tables,
81
+ project=context.project,
82
+ metric_configs=context.metrics_by_name,
83
+ generated_at=generated_at,
84
+ )
85
+ if payload["period"]["end"] == 0:
86
+ click.echo(" │ Report: no persisted results, skipped")
87
+ return
88
+
89
+ out = _resolve_report_path(report_path, context.root, experiment.name)
90
+ out.parent.mkdir(parents=True, exist_ok=True)
91
+ # atomic replace: a mid-write failure (disk full, kill) must never leave
92
+ # a truncated file where a previous good report lived (review finding)
93
+ tmp = out.with_suffix(out.suffix + ".tmp")
94
+ tmp.write_text(render_report_html(payload), encoding="utf-8")
95
+ os.replace(tmp, out)
96
+
97
+ try:
98
+ shown: Path | str = out.relative_to(context.root)
99
+ except ValueError:
100
+ shown = out
101
+ verdicts = [str(v["verdict"]) for v in payload["verdicts"]]
102
+ note = " · ".join(verdicts) if verdicts else "no verdicts yet"
103
+ if payload["srm"]["flag"]:
104
+ note += " · SRM FAILED"
105
+ click.echo(click.style(f" │ Report → {shown} ({note})", fg="cyan"))
106
+
107
+
108
+ def run_run(
109
+ select: tuple[str, ...],
110
+ exclude: tuple[str, ...],
111
+ steps: str,
112
+ profile: str | None,
113
+ from_ts: str | None,
114
+ to_ts: str | None,
115
+ full_refresh: bool,
116
+ force: bool,
117
+ workers: int,
118
+ report_path: str | None = None,
119
+ ) -> None:
120
+ try:
121
+ parsed_steps = PipelineStep.parse(steps)
122
+ except ValueError as exc:
123
+ raise click.BadParameter(str(exc), param_hint="--steps") from exc
124
+
125
+ validate_only = parsed_steps == [PipelineStep.VALIDATE]
126
+ if validate_only and report_path is not None:
127
+ raise click.BadParameter(
128
+ "--report needs pipeline steps (validate-only runs never touch the DB)",
129
+ param_hint="--report",
130
+ )
131
+ context = load_project_context(require_profiles=not validate_only)
132
+ click.echo(f"Project root: {context.root}")
133
+
134
+ # ── VALIDATE: level-2 config lint, no DB (declarative-config §8) ─────────
135
+ report = validate_level2(context.root, context.project, context.experiments, context.metrics)
136
+ for warning in report.warnings:
137
+ click.echo(click.style(f" ⚠ {warning}", fg="yellow"))
138
+ if not report.ok:
139
+ for error in report.errors:
140
+ echo_error("validate", error)
141
+ raise click.ClickException(f"config validation failed ({len(report.errors)} errors)")
142
+ click.echo(
143
+ click.style(
144
+ f" ✓ config valid: {len(context.experiments)} experiment(s), "
145
+ f"{len(context.metrics)} metric(s)",
146
+ fg="green",
147
+ )
148
+ )
149
+ if validate_only:
150
+ echo_done("Validation passed.")
151
+ return
152
+
153
+ # ── selection + the inspectable alphas ───────────────────────────────────
154
+ selected, selection_warnings = select_experiments(context.root, select, exclude)
155
+ for warning in selection_warnings:
156
+ click.echo(click.style(f" ⚠ {warning}", fg="yellow"))
157
+ if not selected:
158
+ echo_done("Nothing selected.")
159
+ return
160
+ if (
161
+ report_path is not None
162
+ and report_path != ""
163
+ and Path(report_path).suffix.lower() == ".html"
164
+ and len(selected) > 1
165
+ ):
166
+ raise click.BadParameter(
167
+ f"--report {report_path} names one file but {len(selected)} experiments "
168
+ "are selected — pass a directory instead",
169
+ param_hint="--report",
170
+ )
171
+
172
+ for _, experiment in selected:
173
+ alphas = effective_alphas(experiment, context.project)
174
+ pairs = n_comparisons(alphas.groups_count, 1)
175
+ children = [
176
+ f"alpha={alphas.alpha} over {alphas.groups_count} variants "
177
+ f"(C({alphas.groups_count},2)={pairs} pairs)",
178
+ f"main-metric alpha: {alphas.main:.6g}",
179
+ ]
180
+ if alphas.secondary is not None and alphas.metrics_count:
181
+ children.append(
182
+ f"secondary alpha: {alphas.secondary:.6g} "
183
+ f"(÷{pairs}×{alphas.metrics_count} non-main metrics)"
184
+ )
185
+ echo_tree(f"{experiment.name}: effective alphas", children)
186
+
187
+ full_refresh_window = None
188
+ if full_refresh:
189
+ window_from = _parse_date(from_ts, "--from")
190
+ window_to = _parse_date(to_ts, "--to")
191
+ if window_from is None or window_to is None:
192
+ raise click.BadParameter("--full-refresh needs both --from and --to")
193
+ full_refresh_window = (window_from, window_to)
194
+ elif from_ts or to_ts:
195
+ raise click.BadParameter("--from/--to only apply with --full-refresh")
196
+
197
+ renderer = StageLogRenderer()
198
+
199
+ def log(line: str) -> None:
200
+ stage, _, rest = line.partition(" ")
201
+ renderer(stage.strip().lower(), rest.strip())
202
+
203
+ outcomes = run_experiments(
204
+ selected,
205
+ context.metrics_by_name,
206
+ context.project,
207
+ manager_factory=context.manager_factory(profile),
208
+ steps=parsed_steps,
209
+ project_root=context.root,
210
+ max_workers=max(1, workers),
211
+ force=force,
212
+ full_refresh_window=full_refresh_window,
213
+ log=log,
214
+ )
215
+
216
+ click.echo()
217
+ failed = 0
218
+ experiments_by_name = {experiment.name: experiment for _, experiment in selected}
219
+ report_manager = None
220
+ report_tables = None
221
+ generated_at = None
222
+ try:
223
+ for outcome in outcomes:
224
+ if outcome.status == "completed":
225
+ children = [
226
+ f"exposures: {outcome.exposures_loaded}",
227
+ f"cutoffs planned: {outcome.cutoffs_planned}",
228
+ f"results written: {outcome.results_written}",
229
+ ]
230
+ srm_warnings = [w for w in outcome.warnings if "SRM" in w]
231
+ other_warnings = [w for w in outcome.warnings if "SRM" not in w]
232
+ echo_tree(outcome.experiment, children, warnings=other_warnings)
233
+ for warning in srm_warnings:
234
+ echo_srm(warning)
235
+ elif outcome.status == "locked":
236
+ echo_noop(outcome.experiment, outcome.error or "locked")
237
+ elif outcome.status == "skipped":
238
+ echo_noop(outcome.experiment, "nothing to do for the selected steps")
239
+ else:
240
+ failed += 1
241
+ echo_error(outcome.experiment, outcome.error or "failed")
242
+
243
+ # ── the readout (D8): per experiment, after its pipeline, inside
244
+ # try/except — never fail the run on a report ─────────────────────
245
+ if report_path is None:
246
+ continue
247
+ if outcome.status not in ("completed", "skipped"):
248
+ # a locked/failed pipeline withholds the report but must say
249
+ # so — automation polling for the artifact should not have to
250
+ # guess (review finding); the lock/error line already printed
251
+ click.echo(
252
+ click.style(f" │ Report skipped: experiment {outcome.status}", fg="yellow")
253
+ )
254
+ continue
255
+ try:
256
+ if report_tables is None:
257
+ from abkit.database.internal_tables import InternalTablesManager
258
+ from abkit.utils.datetime_utils import now_utc_naive
259
+
260
+ report_manager = context.manager_factory(profile)()
261
+ report_tables = InternalTablesManager(report_manager)
262
+ generated_at = now_utc_naive().strftime("%Y-%m-%d %H:%M UTC")
263
+ _emit_experiment_report(
264
+ experiments_by_name[outcome.experiment],
265
+ report_tables,
266
+ context,
267
+ report_path,
268
+ generated_at or "",
269
+ )
270
+ except Exception as report_error: # never fail the run on a report
271
+ click.echo(click.style(f" │ Report skipped: {report_error}", fg="yellow"))
272
+ finally:
273
+ if report_manager is not None:
274
+ report_manager.close()
275
+
276
+ total_rows = sum(o.results_written for o in outcomes)
277
+ echo_done(
278
+ f"{len(outcomes)} experiment(s), {total_rows} result row(s)"
279
+ + (f", {failed} FAILED" if failed else "")
280
+ )
281
+ if failed:
282
+ raise SystemExit(1)
@@ -0,0 +1,59 @@
1
+ """Implementation of ``abk unlock``.
2
+
3
+ Force-releases stale pipeline locks left behind by a run that died without
4
+ releasing them (e.g. the database restarted mid-run). Normally the lock
5
+ auto-expires after its timeout; this command clears it immediately.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import click
11
+
12
+ from abkit.cli._output import echo_done, echo_error, echo_noop, echo_tree
13
+ from abkit.cli.commands._context import load_project_context
14
+ from abkit.config import select_experiments
15
+ from abkit.database.internal_tables import InternalTablesManager
16
+
17
+
18
+ def run_unlock(select: tuple[str, ...], profile: str | None) -> None:
19
+ context = load_project_context()
20
+ click.echo(f"Project root: {context.root}")
21
+
22
+ selected, warnings = select_experiments(context.root, select)
23
+ for warning in warnings:
24
+ click.echo(click.style(f" ⚠ {warning}", fg="yellow"))
25
+ if not selected:
26
+ echo_done("Nothing selected.")
27
+ return
28
+
29
+ manager = context.manager_factory(profile)()
30
+ try:
31
+ tables = InternalTablesManager(manager)
32
+ tables.ensure_tables()
33
+
34
+ cleared = 0
35
+ errors = 0
36
+ # the pipeline lock (run) and the out-of-band validate lock (m4 D5) share the
37
+ # (experiment, scope, process_type) key shape — clear both process types.
38
+ lock_kinds = (("pipeline", "run"), ("pipeline", "validate"))
39
+ for _, experiment in selected:
40
+ released = []
41
+ try:
42
+ for scope, process_type in lock_kinds:
43
+ if tables.clear_lock(experiment.name, scope, process_type):
44
+ released.append(process_type)
45
+ except Exception as exc:
46
+ errors += 1
47
+ echo_error(experiment.name, f"error clearing lock: {exc}")
48
+ continue
49
+ if released:
50
+ cleared += 1
51
+ echo_tree(experiment.name, [f"{kind} lock cleared" for kind in released])
52
+ else:
53
+ echo_noop(experiment.name, "no active lock")
54
+ finally:
55
+ manager.close()
56
+
57
+ echo_done(f"Cleared {cleared} lock(s) of {len(selected)} experiment(s).")
58
+ if errors:
59
+ raise SystemExit(1)
@@ -0,0 +1,264 @@
1
+ """Implementation of ``abk validate`` — the A/A false-positive matrix (m4 WP4).
2
+
3
+ Out-of-band from ``abk run``: for each selected experiment it draws N placebo A/A
4
+ splits over the experiment's own cohort, scores each method's empirical FPR /
5
+ cumulative-peeking FPR / power / achieved-MDE / CI-coverage, and persists one
6
+ ``_ab_aa_runs`` row per cell (docs/specs/aa-false-positive-matrix.md). Rows carry the
7
+ effective per-comparison alpha, so the explore calibration chip lights (D3).
8
+
9
+ Lock discipline (D5): a distinct ``(experiment, "pipeline", "validate")`` claim —
10
+ validate writes only ``_ab_aa_runs`` (never read by the run pipeline), so it need not
11
+ serialize behind nightly runs. Failures are recorded on the lock row before
12
+ propagating; ``abk unlock`` clears both the run and validate locks. Any failed
13
+ experiment exits NON-ZERO. ``--report`` is best-effort (the one exception).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ from pathlib import Path
20
+
21
+ import click
22
+
23
+ from abkit.cli._output import (
24
+ StageLogRenderer,
25
+ echo_done,
26
+ echo_error,
27
+ echo_noop,
28
+ echo_tree,
29
+ )
30
+ from abkit.cli.commands._context import load_project_context
31
+ from abkit.config import select_experiments, validate_level2
32
+ from abkit.config.method_config import MethodConfig
33
+ from abkit.core.period_planner import generate_grid
34
+ from abkit.pipeline import effective_alphas
35
+ from abkit.stats import n_comparisons
36
+
37
+ _VALIDATE_STAGE_TITLES = {
38
+ "load": "LOAD",
39
+ "resample": "RESAMPLE",
40
+ "score": "SCORE",
41
+ "persist": "PERSIST",
42
+ }
43
+
44
+
45
+ def _resolve_report_path(report_path: str, project_root: Path, experiment: str) -> Path:
46
+ """Same tri-state convention as ``abk run``, defaulting to the ``__validate`` suffix
47
+ so a validate report never clobbers the run readout (the ``__explore`` precedent)."""
48
+ if report_path == "":
49
+ return project_root / "reports" / f"{experiment}__validate.html"
50
+ candidate = Path(report_path)
51
+ if candidate.suffix.lower() == ".html":
52
+ return candidate
53
+ return candidate / f"{experiment}__validate.html"
54
+
55
+
56
+ def run_validate(
57
+ select: tuple[str, ...],
58
+ method: tuple[str, ...],
59
+ metric: str | None,
60
+ iterations: int,
61
+ inject_effect: float | None,
62
+ scoring: str,
63
+ report_path: str | None,
64
+ force: bool,
65
+ profile: str | None,
66
+ ) -> None:
67
+ context = load_project_context(require_profiles=True)
68
+ click.echo(f"Project root: {context.root}")
69
+
70
+ # ── config lint (no DB) ──────────────────────────────────────────────────
71
+ report = validate_level2(context.root, context.project, context.experiments, context.metrics)
72
+ for warning in report.warnings:
73
+ click.echo(click.style(f" ⚠ {warning}", fg="yellow"))
74
+ if not report.ok:
75
+ for error in report.errors:
76
+ echo_error("validate", error)
77
+ raise click.ClickException(f"config validation failed ({len(report.errors)} errors)")
78
+
79
+ selected, selection_warnings = select_experiments(context.root, select)
80
+ for warning in selection_warnings:
81
+ click.echo(click.style(f" ⚠ {warning}", fg="yellow"))
82
+ if not selected:
83
+ echo_done("Nothing selected.")
84
+ return
85
+ if (
86
+ report_path is not None
87
+ and report_path != ""
88
+ and Path(report_path).suffix.lower() == ".html"
89
+ and len(selected) > 1
90
+ ):
91
+ raise click.BadParameter(
92
+ f"--report {report_path} names one file but {len(selected)} experiments "
93
+ "are selected — pass a directory instead",
94
+ param_hint="--report",
95
+ )
96
+
97
+ failed = 0
98
+ for _, experiment in selected:
99
+ status = _validate_one(
100
+ experiment,
101
+ context,
102
+ profile,
103
+ method,
104
+ metric,
105
+ iterations,
106
+ inject_effect,
107
+ scoring,
108
+ report_path,
109
+ force,
110
+ )
111
+ if status == "failed":
112
+ failed += 1
113
+
114
+ echo_done(f"{len(selected)} experiment(s) validated" + (f", {failed} FAILED" if failed else ""))
115
+ if failed:
116
+ raise SystemExit(1)
117
+
118
+
119
+ def _validate_one(
120
+ experiment,
121
+ context,
122
+ profile,
123
+ method_names,
124
+ metric_filter,
125
+ iterations,
126
+ inject_effect,
127
+ scoring,
128
+ report_path,
129
+ force,
130
+ ) -> str:
131
+ from abkit.compute.recompute_backend import RecomputeBackend
132
+ from abkit.database.internal_tables import InternalTablesManager
133
+ from abkit.utils.datetime_utils import now_utc_naive
134
+ from abkit.validate import ValidateSettings, aa_run_records, run_validation
135
+
136
+ # the inspectable effective alphas (R28), echoed like `abk run`
137
+ alphas = effective_alphas(experiment, context.project)
138
+ pairs = n_comparisons(alphas.groups_count, 1)
139
+ echo_tree(
140
+ f"{experiment.name}: effective alphas",
141
+ [
142
+ f"alpha={alphas.alpha} over {alphas.groups_count} variants (C({alphas.groups_count},2)={pairs} pairs)",
143
+ f"main-metric alpha: {alphas.main:.6g}",
144
+ ],
145
+ )
146
+
147
+ # the manager's whole lifetime is under an OUTER try/finally so a raise anywhere —
148
+ # incl. acquire_lock itself before the inner try — never leaks the warehouse
149
+ # connection into the (potentially long-lived) caller (m4 exit-gate review).
150
+ manager = context.manager_factory(profile)()
151
+ try:
152
+ tables = InternalTablesManager(manager)
153
+ if not tables.acquire_lock(
154
+ experiment.name,
155
+ "pipeline",
156
+ "validate",
157
+ timeout_seconds=context.project.timeouts.compute,
158
+ force=force,
159
+ ):
160
+ echo_noop(experiment.name, "validate lock held (use --force or `abk unlock`)")
161
+ return "locked"
162
+
163
+ renderer = StageLogRenderer(titles=_VALIDATE_STAGE_TITLES)
164
+ try:
165
+ tables.ensure_tables()
166
+ backend = RecomputeBackend(manager, experiment)
167
+ grid = generate_grid(
168
+ experiment.start_date,
169
+ experiment.end_date,
170
+ experiment.cadence_segments(),
171
+ tz=experiment.timezone,
172
+ )
173
+ renderer("load", f"cohort over {len(grid.cutoffs)} cutoffs")
174
+ extra_methods = [MethodConfig(name=name) for name in method_names]
175
+ metric_sqls = {cfg.name: cfg.get_query_text(context.root) for _, cfg in context.metrics}
176
+ settings = ValidateSettings(
177
+ iterations=iterations, inject_effect=inject_effect, mode=scoring
178
+ )
179
+ renderer("resample", f"{iterations} placebo splits/cell")
180
+
181
+ result = run_validation(
182
+ backend,
183
+ experiment,
184
+ context.project,
185
+ context.metrics_by_name,
186
+ metric_sqls,
187
+ grid,
188
+ settings,
189
+ now_iso=now_utc_naive().isoformat(),
190
+ extra_methods=extra_methods,
191
+ metric_filter=metric_filter,
192
+ )
193
+ renderer("score", f"{len(result.cells)} cell(s)")
194
+
195
+ records = aa_run_records(result)
196
+ for record in records:
197
+ tables.save_aa_run(record)
198
+ renderer("persist", f"{len(records)} _ab_aa_runs row(s)")
199
+
200
+ _emit_matrix(experiment.name, result)
201
+ tables.release_lock(experiment.name, "pipeline", "validate", status="completed")
202
+ except BaseException as exc: # incl. KeyboardInterrupt/SystemExit — never strand the lock
203
+ tables.release_lock(
204
+ experiment.name, "pipeline", "validate", status="failed", error_message=str(exc)
205
+ )
206
+ echo_error(experiment.name, f"validate failed: {exc}")
207
+ if not isinstance(exc, Exception):
208
+ # a signal / interpreter exit still propagates — but with the lock RELEASED,
209
+ # never stranded for the 2h compute timeout (driver.py:229–236 precedent).
210
+ raise
211
+ return "failed"
212
+
213
+ if report_path is not None:
214
+ try:
215
+ _emit_report(experiment, context, tables, report_path)
216
+ except Exception as report_error: # never fail validate on a report
217
+ click.echo(click.style(f" │ Report skipped: {report_error}", fg="yellow"))
218
+ return "completed"
219
+ finally:
220
+ manager.close()
221
+
222
+
223
+ def _emit_matrix(experiment: str, result) -> None:
224
+ by_metric: dict[str, list] = {}
225
+ for cell in result.cells:
226
+ by_metric.setdefault(cell.metric, []).append(cell)
227
+ for metric, cells in sorted(by_metric.items()):
228
+ children = []
229
+ for cell in cells:
230
+ mark = "★ " if cell.recommended else ""
231
+ children.append(f"{mark}{cell.verdict}")
232
+ echo_tree(f"{experiment} · {metric}", children)
233
+
234
+
235
+ def _emit_report(experiment, context, tables, report_path: str) -> None:
236
+ """Bake the self-contained readout, now carrying the A/A calibration matrix (WP5).
237
+
238
+ Reuses the report bundle (D10): ``build_report_payload`` fills the ``calibration``
239
+ block from the ``_ab_aa_runs`` rows validate just wrote, and ``render_report_html``
240
+ bakes the committed ``report.js`` — one renderer, no third bundle. Best-effort: the
241
+ caller yellow-skips a bake failure so it never masks a successful validation."""
242
+ from abkit.reporting import build_report_payload, render_report_html
243
+ from abkit.utils.datetime_utils import now_utc_naive
244
+
245
+ payload = build_report_payload(
246
+ experiment,
247
+ tables,
248
+ project=context.project,
249
+ metric_configs=context.metrics_by_name,
250
+ generated_at=now_utc_naive().strftime("%Y-%m-%d %H:%M UTC"),
251
+ )
252
+ out = _resolve_report_path(report_path, context.root, experiment.name)
253
+ out.parent.mkdir(parents=True, exist_ok=True)
254
+ # atomic replace: a mid-write kill must never leave a truncated file (run.py precedent)
255
+ tmp = out.with_suffix(out.suffix + ".tmp")
256
+ tmp.write_text(render_report_html(payload), encoding="utf-8")
257
+ os.replace(tmp, out)
258
+ try:
259
+ shown: Path | str = out.relative_to(context.root)
260
+ except ValueError:
261
+ shown = out
262
+ cal = payload.get("calibration")
263
+ note = cal["headline"] if cal and cal.get("headline") else "no calibration rows"
264
+ click.echo(click.style(f" │ Report → {shown} ({note})", fg="cyan"))