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
abkit/tuning/server.py ADDED
@@ -0,0 +1,882 @@
1
+ """The explore localhost server (WP6) — the donor's interaction contract.
2
+
3
+ A pure-stdlib server bound to ``127.0.0.1`` with a one-shot token: GET serves
4
+ ONE pre-rendered page (unauthenticated, any path — the token gates only the
5
+ POSTs); ``POST /recompute`` answers knob changes from the in-memory session
6
+ (repeatable, advisory, lock-serialized, **stale-dropping** — a ``threading``
7
+ lock alone cannot cancel an in-flight bootstrap, so the handler drops
8
+ outdated ``request_id``s BEFORE and AFTER acquiring the compute lock);
9
+ ``POST /reload`` executes the confirmed Tier-R actions (its OWN manager
10
+ inside the serialized handler — DB-API connections are not thread-safe) and
11
+ streams a run-log through ``server.echo`` (``/recompute`` stays silent — per-
12
+ knob terminal streaming is spam); ``POST /validate`` is Auto mode (M4 WP6) —
13
+ a reduced-N server-side ``abk validate`` (its OWN manager + the out-of-band
14
+ ``'validate'`` ``_ab_tasks`` lock, ``request_lock``-serialized, request_id
15
+ stale-dropping) that refreshes ``session.aa_rows`` in place so the live D3
16
+ chip greens without an explore restart, and returns the recommended knob state
17
+ per metric for the client to re-seed from; ``POST /apply`` is the only terminal
18
+ action — it enforces the
19
+ calibration gate server-side (``confirm_uncalibrated`` required while the
20
+ knob state's D3 lookup is not green), writes through the WP5 seam, echoes the
21
+ ``orphaned`` block for the CLI epilogue, and shuts the server down from a
22
+ spawned daemon thread. An invalid config returns 400 and KEEPS serving.
23
+
24
+ No pipeline lock is taken: explore writes only YAML, and every read is the
25
+ FINAL-deduped ``load_results`` path (seam map §6).
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import contextlib
31
+ import json
32
+ import os
33
+ import secrets
34
+ import threading
35
+ import webbrowser
36
+ from collections.abc import Callable, Iterator
37
+ from dataclasses import asdict
38
+ from datetime import datetime
39
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
40
+ from pathlib import Path
41
+ from typing import TYPE_CHECKING, Any, cast
42
+
43
+ from abkit.config.method_config import MethodConfig
44
+ from abkit.core.period_planner import Cutoff
45
+ from abkit.tuning.config_writer import AppliedConfig, TunedComparison, apply_tuned_config
46
+ from abkit.tuning.html import render_explore_html
47
+ from abkit.tuning.payload import ENDPOINT_SLOTS, _ms
48
+ from abkit.tuning.recompute import (
49
+ KnobState,
50
+ RecomputeEngine,
51
+ RecomputeResult,
52
+ find_calibration,
53
+ resolve_fpr_budget,
54
+ )
55
+ from abkit.tuning.session import ExploreSession
56
+
57
+ if TYPE_CHECKING:
58
+ from abkit.config.metric_config import MetricConfig
59
+ from abkit.database.internal_tables import InternalTablesManager
60
+ from abkit.database.manager import BaseDatabaseManager
61
+
62
+ _MAX_BODY = 5_000_000 # generous cap on the posted knob/config payload
63
+ _MAX_DRAIN = 32_000_000 # how much of an oversized body to drain before the 413
64
+
65
+
66
+ @contextlib.contextmanager
67
+ def _quiet_stderr() -> Iterator[None]:
68
+ """Silence OS-level stderr for the duration of the block.
69
+
70
+ ``webbrowser.open`` shells out to ``xdg-open``, which prints a wall of
71
+ "browser not found" lines on a headless / WSL box. The launch is
72
+ best-effort (the URL is already printed), so swallow that noise.
73
+ """
74
+ try:
75
+ devnull = os.open(os.devnull, os.O_WRONLY)
76
+ except OSError:
77
+ yield
78
+ return
79
+ saved = os.dup(2)
80
+ try:
81
+ os.dup2(devnull, 2)
82
+ yield
83
+ finally:
84
+ os.dup2(saved, 2)
85
+ os.close(saved)
86
+ os.close(devnull)
87
+
88
+
89
+ class _ExploreServer(ThreadingHTTPServer):
90
+ """Localhost server holding the per-serve state the handler reads."""
91
+
92
+ # Don't block interpreter exit on in-flight request threads (we stop after
93
+ # a single successful apply anyway).
94
+ daemon_threads = True
95
+
96
+ def __init__(self, address: tuple[str, int], handler: type[BaseHTTPRequestHandler]) -> None:
97
+ super().__init__(address, handler)
98
+ self.token: str = ""
99
+ self.html: str = ""
100
+ self.original_path: Path = Path(".")
101
+ self.project_root: Path = Path(".")
102
+ self.applied: AppliedConfig | None = None
103
+ # /reload's run-log sink; serve_explore swaps in the command's echo.
104
+ self.echo: Callable[[str], None] = print
105
+ # The in-memory state every answer comes from (None = a bare server).
106
+ self.session: ExploreSession | None = None
107
+ self.engine: RecomputeEngine | None = None
108
+ # The Apply seam's orphan scan + validation context.
109
+ self.tables: InternalTablesManager | None = None
110
+ self.metrics_by_name: dict[str, MetricConfig] | None = None
111
+ # Tier-R support: a manager per /reload call (DB-API connections are
112
+ # not thread-safe; the session-load manager belongs to the CLI thread).
113
+ self.manager_factory: Callable[[], BaseDatabaseManager] | None = None
114
+ self.metric_sql_by_name: dict[str, str] | None = None
115
+ # One compute at a time (two tabs / queued knob drags stay safe)…
116
+ self.request_lock = threading.Lock()
117
+ # …and the server-side stale-drop: outdated request ids never compute.
118
+ self._id_lock = threading.Lock()
119
+ self.latest_request_id: int = 0
120
+
121
+ def check_stale(self, request_id: int | None) -> bool:
122
+ """Record ``request_id`` and report whether it is already outdated."""
123
+ if request_id is None:
124
+ return False # id-less requests carry no ordering semantics
125
+ with self._id_lock:
126
+ if request_id < self.latest_request_id:
127
+ return True
128
+ self.latest_request_id = request_id
129
+ return False
130
+
131
+ def is_stale(self, request_id: int | None) -> bool:
132
+ """Re-check after acquiring the compute lock (a newer id may have
133
+ arrived while this request waited on it)."""
134
+ if request_id is None:
135
+ return False
136
+ with self._id_lock:
137
+ return request_id < self.latest_request_id
138
+
139
+
140
+ class _Handler(BaseHTTPRequestHandler):
141
+ def log_message(self, *args: Any) -> None: # silence default stderr logging
142
+ return
143
+
144
+ def _srv(self) -> _ExploreServer:
145
+ return cast(_ExploreServer, self.server)
146
+
147
+ def do_GET(self) -> None:
148
+ body = self._srv().html.encode("utf-8")
149
+ self.send_response(200)
150
+ self.send_header("Content-Type", "text/html; charset=utf-8")
151
+ self.send_header("Content-Length", str(len(body)))
152
+ self.end_headers()
153
+ self.wfile.write(body)
154
+
155
+ def do_POST(self) -> None:
156
+ from urllib.parse import parse_qs, urlparse
157
+
158
+ srv = self._srv()
159
+ parsed = urlparse(self.path)
160
+ if parse_qs(parsed.query).get("token", [""])[0] != srv.token:
161
+ self._reply_error(403, "bad token")
162
+ return
163
+ try:
164
+ length = int(self.headers.get("Content-Length", "0") or "0")
165
+ except ValueError:
166
+ # a malformed header must be a clean 400, never a dead thread
167
+ self._reply_error(400, "bad Content-Length header")
168
+ return
169
+ if length <= 0 or length > _MAX_BODY:
170
+ # Drain a bounded amount before replying so the client can read
171
+ # the 413 instead of hitting a broken pipe mid-upload.
172
+ if 0 < length <= _MAX_DRAIN:
173
+ with contextlib.suppress(OSError):
174
+ self.rfile.read(length)
175
+ self._reply_error(413, "empty or too large")
176
+ return
177
+ body = self.rfile.read(length)
178
+ if parsed.path == "/recompute":
179
+ self._handle_recompute(srv, body)
180
+ elif parsed.path == "/reload":
181
+ self._handle_reload(srv, body)
182
+ elif parsed.path == "/validate":
183
+ self._handle_validate(srv, body)
184
+ elif parsed.path == "/apply":
185
+ self._handle_apply(srv, body)
186
+ else:
187
+ self._reply_error(404, f"unknown endpoint: {parsed.path}")
188
+
189
+ # -- transport helpers (donor-verbatim) -----------------------------------
190
+
191
+ def _reply_json(self, payload: dict[str, Any], code: int = 200) -> None:
192
+ resp = json.dumps(payload, default=_json_default).encode("utf-8")
193
+ self.send_response(code)
194
+ self.send_header("Content-Type", "application/json")
195
+ self.send_header("Content-Length", str(len(resp)))
196
+ self.end_headers()
197
+ self.wfile.write(resp)
198
+
199
+ def _reply_error(self, code: int, detail: str) -> None:
200
+ """Error detail in the UTF-8 body, never the latin-1 status line.
201
+
202
+ ``send_error`` writes the message into the HTTP status line, which is
203
+ latin-1 only — a pydantic/stats exception carrying a unicode dash or
204
+ ``α`` would crash the response with ``UnicodeEncodeError`` instead of
205
+ returning a clean error. The page reads the body via ``r.text()``.
206
+ """
207
+ body = detail.encode("utf-8")
208
+ self.send_response(code)
209
+ self.send_header("Content-Type", "text/plain; charset=utf-8")
210
+ self.send_header("Content-Length", str(len(body)))
211
+ self.end_headers()
212
+ self.wfile.write(body)
213
+
214
+ # -- endpoints -------------------------------------------------------------
215
+
216
+ def _handle_recompute(self, srv: _ExploreServer, body: bytes) -> None:
217
+ """Answer one knob state — silent (structured JSON only), repeatable."""
218
+ if srv.engine is None:
219
+ self._reply_error(400, "recompute is unavailable for this session")
220
+ return
221
+ try:
222
+ request = json.loads(body.decode("utf-8"))
223
+ metric, knobs, request_id = _parse_knob_request(request)
224
+ except Exception as exc:
225
+ self._reply_error(400, f"invalid recompute request: {exc}")
226
+ return
227
+ if srv.check_stale(request_id):
228
+ self._reply_json({"stale": True, "request_id": request_id}, code=409)
229
+ return
230
+ with srv.request_lock:
231
+ if srv.is_stale(request_id):
232
+ self._reply_json({"stale": True, "request_id": request_id}, code=409)
233
+ return
234
+ try:
235
+ result = srv.engine.recompute(metric, knobs)
236
+ except Exception as exc:
237
+ self._reply_error(400, f"recompute failed: {exc}")
238
+ return
239
+ self._reply_json(_result_json(result, request_id))
240
+
241
+ def _handle_reload(self, srv: _ExploreServer, body: bytes) -> None:
242
+ """The confirmed Tier-R action: re-render the cached cutoffs under the
243
+ requested method (its own manager), then answer like /recompute —
244
+ streaming the run-log through ``srv.echo`` (never per-knob spam)."""
245
+ if (
246
+ srv.session is None
247
+ or srv.engine is None
248
+ or srv.manager_factory is None
249
+ or not srv.metric_sql_by_name
250
+ ):
251
+ self._reply_error(400, "reload is unavailable for this session")
252
+ return
253
+ try:
254
+ request = json.loads(body.decode("utf-8"))
255
+ metric, knobs, request_id = _parse_knob_request(request)
256
+ except Exception as exc:
257
+ self._reply_error(400, f"invalid reload request: {exc}")
258
+ return
259
+ if srv.check_stale(request_id):
260
+ self._reply_json({"stale": True, "request_id": request_id}, code=409)
261
+ return
262
+ with srv.request_lock:
263
+ if srv.is_stale(request_id):
264
+ self._reply_json({"stale": True, "request_id": request_id}, code=409)
265
+ return
266
+ try:
267
+ result = _run_reload(srv, metric, knobs)
268
+ except Exception as exc:
269
+ srv.echo(f"RELOAD {metric}: failed — {exc}")
270
+ self._reply_error(400, f"reload failed: {exc}")
271
+ return
272
+ self._reply_json(_result_json(result, request_id))
273
+
274
+ def _handle_validate(self, srv: _ExploreServer, body: bytes) -> None:
275
+ """Auto mode (WP6, D11): a reduced-N server-side ``abk validate`` that
276
+ refreshes the live session's calibration in place, then answers with the
277
+ recommended knob state per metric so the client re-seeds + re-renders the
278
+ chip. Serialized under the request lock (its own manager, its own
279
+ ``'validate'`` lock), stale-dropping like ``/recompute`` and ``/reload``.
280
+ The Apply gate is unchanged — Auto only populates rows."""
281
+ if (
282
+ srv.session is None
283
+ or srv.manager_factory is None
284
+ or not srv.metric_sql_by_name
285
+ or not srv.metrics_by_name
286
+ ):
287
+ self._reply_error(400, "Auto mode is unavailable for this session")
288
+ return
289
+ try:
290
+ request = json.loads(body.decode("utf-8"))
291
+ raw_id = (request or {}).get("request_id")
292
+ request_id = (
293
+ int(raw_id) if isinstance(raw_id, int) and not isinstance(raw_id, bool) else None
294
+ )
295
+ except Exception as exc:
296
+ self._reply_error(400, f"invalid validate request: {exc}")
297
+ return
298
+ if srv.check_stale(request_id):
299
+ self._reply_json({"stale": True, "request_id": request_id}, code=409)
300
+ return
301
+ with srv.request_lock:
302
+ if srv.is_stale(request_id):
303
+ self._reply_json({"stale": True, "request_id": request_id}, code=409)
304
+ return
305
+ try:
306
+ reply = _run_validate(srv)
307
+ except Exception as exc:
308
+ srv.echo(f"VALIDATE: failed — {exc}")
309
+ self._reply_error(400, f"validate failed: {exc}")
310
+ return
311
+ reply["request_id"] = request_id
312
+ self._reply_json(reply)
313
+
314
+ def _handle_apply(self, srv: _ExploreServer, body: bytes) -> None:
315
+ """The only terminal action: gate → WP5 seam → reply → self-shutdown.
316
+
317
+ Serialized under the request lock: two tabs' Applies must not race the
318
+ archive/rewrite seam or the shared CLI-thread DB manager, and a second
319
+ Apply after a successful one is refused (the server is already going
320
+ down). Every request-shaped failure is a clean 400/409 — a handler
321
+ thread must never die replyless on malformed input.
322
+ """
323
+ try:
324
+ request = json.loads(body.decode("utf-8"))
325
+ comparisons = _parse_tuned_comparisons(request)
326
+ alpha = request.get("alpha")
327
+ alpha = None if alpha is None else float(alpha)
328
+ correction = request.get("correction")
329
+ correction = None if correction is None else str(correction)
330
+ except Exception as exc:
331
+ self._reply_error(400, f"invalid apply request: {exc}")
332
+ return
333
+
334
+ with srv.request_lock:
335
+ if srv.applied is not None:
336
+ self._reply_error(409, "already applied — the server is shutting down")
337
+ return
338
+
339
+ # The calibration gate (D3, server-side half): while the applied
340
+ # knob state has no green D3 lookup, Apply needs the explicit
341
+ # confirm_uncalibrated — a visible cost, never a hard block.
342
+ try:
343
+ uncalibrated = _uncalibrated_keys(srv, comparisons, alpha, correction)
344
+ except Exception as exc:
345
+ self._reply_error(400, f"invalid apply request: {exc}")
346
+ return
347
+ if uncalibrated and not bool(request.get("confirm_uncalibrated")):
348
+ self._reply_error(
349
+ 409,
350
+ "these params have never passed `abk validate` — the real FPR is "
351
+ "unknown and the nominal α may understate it. Re-send with "
352
+ f"confirm_uncalibrated: true to apply anyway. ({'; '.join(uncalibrated)})",
353
+ )
354
+ return
355
+
356
+ try:
357
+ applied = apply_tuned_config(
358
+ original_path=srv.original_path,
359
+ project_root=srv.project_root,
360
+ comparisons=comparisons,
361
+ alpha=alpha,
362
+ correction=correction,
363
+ tables=srv.tables,
364
+ metrics_by_name=srv.metrics_by_name,
365
+ )
366
+ except Exception as exc:
367
+ # Keep serving so the user can fix the knobs and retry.
368
+ self._reply_error(400, f"invalid config: {exc}")
369
+ return
370
+ srv.applied = applied
371
+
372
+ try:
373
+ self._reply_json(
374
+ {
375
+ "saved": str(applied.saved),
376
+ "archived": str(applied.archived),
377
+ "updated": list(applied.updated),
378
+ "preserved": list(applied.preserved),
379
+ "experiment_fields": list(applied.experiment_fields),
380
+ "orphaned": [asdict(o) for o in applied.orphaned],
381
+ "orphan_warning": applied.orphan_warning,
382
+ }
383
+ )
384
+ finally:
385
+ # The YAML is written: shut down EVEN IF the reply write failed
386
+ # (a vanished client must not leave the server alive — Ctrl-C
387
+ # would then report "unchanged" after a successful write).
388
+ threading.Thread(target=srv.shutdown, daemon=True).start()
389
+
390
+
391
+ def _parse_knob_request(request: dict[str, Any]) -> tuple[str, KnobState, int | None]:
392
+ metric = str(request["metric"])
393
+ method = request.get("method") or {}
394
+ knobs = KnobState(
395
+ method_name=str(method.get("name", "")),
396
+ params=dict(method.get("params") or {}),
397
+ alpha=float(request.get("alpha", 0.05)),
398
+ )
399
+ raw_id = request.get("request_id")
400
+ request_id = int(raw_id) if isinstance(raw_id, int) and not isinstance(raw_id, bool) else None
401
+ return metric, knobs, request_id
402
+
403
+
404
+ def _parse_tuned_comparisons(request: dict[str, Any]) -> list[TunedComparison]:
405
+ """``comparisons: [{metric, method: {name, params}, is_main_metric, …}]`` —
406
+ one entry per DIRTY comparison (the donor's dirty-slot discipline)."""
407
+ out: list[TunedComparison] = []
408
+ for entry in request.get("comparisons") or []:
409
+ if not isinstance(entry, dict):
410
+ continue
411
+ method = entry.get("method")
412
+ # an ABSENT params key stays None — the writer's "a method switch must
413
+ # carry the full param set" guard must see the absence, not a fake {}
414
+ params = None
415
+ if isinstance(method, dict) and "params" in method:
416
+ params = dict(method.get("params") or {})
417
+ out.append(
418
+ TunedComparison(
419
+ metric=str(entry.get("metric", "")),
420
+ method_name=(
421
+ str(method["name"]) if isinstance(method, dict) and method.get("name") else None
422
+ ),
423
+ params=params,
424
+ is_main_metric=entry.get("is_main_metric"),
425
+ is_guardrail=entry.get("is_guardrail"),
426
+ )
427
+ )
428
+ return out
429
+
430
+
431
+ def _uncalibrated_keys(
432
+ srv: _ExploreServer,
433
+ comparisons: list[TunedComparison],
434
+ alpha: float | None,
435
+ correction: str | None,
436
+ ) -> list[str]:
437
+ """The (metric, id, alpha) keys this Apply would run at that are NOT green.
438
+
439
+ D3 keys calibration by the EFFECTIVE post-correction per-comparison alpha
440
+ — an alpha or correction edit re-keys every comparison, and role flips
441
+ move comparisons between the two Bonferroni tiers, so ALL of those gate
442
+ conservatively (with ``_ab_aa_runs`` empty until M4, every Apply takes
443
+ the confirm path — the mechanically testable M3 DoD). Without a session
444
+ (a bare server) everything is uncalibrated.
445
+ """
446
+ session = srv.session
447
+ if session is None:
448
+ return ["no session — calibration unknown"]
449
+
450
+ from abkit.pipeline.analyze import comparison_alpha, effective_alphas
451
+
452
+ # The PROSPECTIVE experiment folds in alpha/correction edits AND the
453
+ # posted role flips before resolving effective alphas: a role flip moves
454
+ # comparisons across the two Bonferroni tiers and shifts the non-main
455
+ # count, so gating at the OLD roles' alphas would under-gate exactly the
456
+ # edit class D3 calls out (milestone-review finding — latent while
457
+ # ``_ab_aa_runs`` is empty, load-bearing from M4 on).
458
+ role_updates = {
459
+ tuned.metric: tuned
460
+ for tuned in comparisons
461
+ if tuned.is_main_metric is not None or tuned.is_guardrail is not None
462
+ }
463
+ prospective_comparisons = []
464
+ flipped_by_metric: dict[str, Any] = {}
465
+ for comp in session.experiment.comparisons:
466
+ tuned = role_updates.get(comp.metric)
467
+ if tuned is not None:
468
+ role_fields: dict[str, Any] = {}
469
+ if tuned.is_main_metric is not None:
470
+ role_fields["is_main_metric"] = bool(tuned.is_main_metric)
471
+ if tuned.is_guardrail is not None:
472
+ role_fields["is_guardrail"] = bool(tuned.is_guardrail)
473
+ comp = comp.model_copy(update=role_fields)
474
+ prospective_comparisons.append(comp)
475
+ flipped_by_metric.setdefault(comp.metric, comp) # explore serves the first
476
+ updates: dict[str, Any] = {}
477
+ if alpha is not None:
478
+ updates["alpha"] = alpha
479
+ if correction is not None:
480
+ updates["correction"] = correction
481
+ if role_updates:
482
+ updates["comparisons"] = prospective_comparisons
483
+ prospective = session.experiment.model_copy(update=updates) if updates else session.experiment
484
+ try:
485
+ alphas = effective_alphas(prospective, session.project)
486
+ except Exception:
487
+ alphas = None # apply_tuned_config will produce the real error
488
+
489
+ def _effective(metric: str, series: Any) -> float:
490
+ if alphas is None:
491
+ return series.configured_alpha
492
+ return comparison_alpha(flipped_by_metric.get(metric, series.comparison), alphas)
493
+
494
+ findings: list[str] = []
495
+
496
+ def _check(metric: str, method_config_id: str, effective_alpha: float) -> None:
497
+ budget = resolve_fpr_budget(session.project, effective_alpha)
498
+ status = find_calibration(
499
+ session.aa_rows, metric, method_config_id, effective_alpha, budget=budget
500
+ )
501
+ if status.state != "calibrated":
502
+ findings.append(f"{metric}: {status.headline}")
503
+
504
+ checked: set[str] = set()
505
+ for tuned in comparisons:
506
+ if tuned.params is None or tuned.metric not in session.series_by_metric:
507
+ continue
508
+ series = session.series_by_metric[tuned.metric]
509
+ name = tuned.method_name or series.comparison.method.name
510
+ # the writer strips a riding "name" key — the gate must key identically
511
+ params = {k: v for k, v in dict(tuned.params).items() if k != "name"}
512
+ try:
513
+ new_id = MethodConfig(name=name, params=params).method_config_id
514
+ except Exception:
515
+ # unbindable params gate conservatively; the writer then rejects
516
+ # them with the real error message
517
+ findings.append(f"{tuned.metric}: method params not bindable — treated as uncalibrated")
518
+ checked.add(tuned.metric)
519
+ continue
520
+ _check(tuned.metric, new_id, _effective(tuned.metric, series))
521
+ checked.add(tuned.metric)
522
+
523
+ rekeys_everything = (
524
+ alpha is not None
525
+ or correction is not None
526
+ or any(
527
+ tuned.is_main_metric is not None or tuned.is_guardrail is not None
528
+ for tuned in comparisons
529
+ )
530
+ )
531
+ if rekeys_everything:
532
+ # experiment-level alpha/correction edits re-key EVERY comparison at
533
+ # its prospective effective alpha; role flips move comparisons across
534
+ # the two Bonferroni tiers — both gate conservatively (D3)
535
+ for metric, series in session.series_by_metric.items():
536
+ if metric not in checked:
537
+ _check(
538
+ metric, series.comparison.method.method_config_id, _effective(metric, series)
539
+ )
540
+ return findings
541
+
542
+
543
+ def _run_reload(srv: _ExploreServer, metric: str, knobs: KnobState) -> RecomputeResult:
544
+ """Re-render the metric's cached cutoffs under the requested method.
545
+
546
+ Runs inside the request lock with its OWN manager (created and closed
547
+ here). Cache entries — and the lookback they were rendered with — are
548
+ replaced in place; the engine then answers from the refreshed session.
549
+ """
550
+ from abkit.compute.recompute_backend import RecomputeBackend
551
+
552
+ session = cast(ExploreSession, srv.session)
553
+ engine = cast(RecomputeEngine, srv.engine)
554
+ factory = cast(Callable[[], Any], srv.manager_factory)
555
+ sql_by_name = cast("dict[str, str]", srv.metric_sql_by_name)
556
+
557
+ series = session.series(metric)
558
+ if metric not in sql_by_name:
559
+ raise ValueError(f"no metric SQL for '{metric}'")
560
+ method_config = MethodConfig(name=knobs.method_name, params=dict(knobs.params))
561
+ method_config.bind(alpha=knobs.alpha) # validate BEFORE any warehouse work
562
+ comparison = series.comparison.model_copy(update={"method": method_config})
563
+
564
+ if session.cache_disabled_reason is not None:
565
+ # a budget-degraded session must not grow a shadow cache the replies
566
+ # would keep contradicting with the "suffstats-only" warning
567
+ raise ValueError(f"reload disabled: {session.cache_disabled_reason}")
568
+
569
+ cutoffs = session.cached_cutoffs(metric) or series.cutoffs[-1:]
570
+ if not cutoffs:
571
+ raise ValueError(f"metric '{metric}' has no computed cutoffs to reload")
572
+
573
+ from abkit.tuning.session import loaded_value_count
574
+
575
+ experiment = session.experiment.name
576
+ srv.echo(
577
+ f"RELOAD {experiment}/{metric}: {len(cutoffs)} cutoff(s) under "
578
+ f"method '{knobs.method_name}' "
579
+ f"(covariate_lookback={method_config.covariate_lookback!r})"
580
+ )
581
+ manager = factory()
582
+ try:
583
+ backend = RecomputeBackend(manager, session.experiment)
584
+ for end_ts in cutoffs:
585
+ loaded = backend.load_cutoff(
586
+ comparison, series.metric, sql_by_name[metric], session.grid, Cutoff(end_ts=end_ts)
587
+ )
588
+ previous = session.cache.get((metric, end_ts))
589
+ if previous is not None:
590
+ session.cache_values -= loaded_value_count(previous)
591
+ session.cache[(metric, end_ts)] = loaded
592
+ session.cache_lookback[(metric, end_ts)] = method_config.covariate_lookback
593
+ session.cache_values += loaded_value_count(loaded)
594
+ srv.echo(f"LOAD {experiment}/{metric}: cutoff {end_ts} reloaded")
595
+ finally:
596
+ manager.close()
597
+ srv.echo(f"RELOAD {experiment}/{metric}: done — recomputing")
598
+ return engine.recompute(metric, knobs)
599
+
600
+
601
+ #: Auto mode runs synchronously inside the HTTP handler, so it uses a reduced
602
+ #: iteration count and a smaller peeking-grid cap than the ``abk validate`` CLI
603
+ #: defaults (2000 / 100). Its FPR is a fast estimate that may legitimately
604
+ #: differ from the full-population CLI run (aa-fpr §5 vs §6 — disclosed in the
605
+ #: UX); the CLI is the source of truth for a final calibration decision.
606
+ AUTO_ITERATIONS = 400
607
+ AUTO_GRID_CAP = 24
608
+
609
+
610
+ def _run_validate(srv: _ExploreServer) -> dict[str, Any]:
611
+ """The Auto-mode reduced validate: score the declared comparisons over a few
612
+ hundred placebo splits, persist the ``_ab_aa_runs`` rows, refresh the live
613
+ ``session.aa_rows`` snapshot in place (D11 — the chip greens without a
614
+ restart), and return the recommended knob state + refreshed calibration per
615
+ metric. Runs inside the request lock with its OWN manager and its OWN
616
+ out-of-band ``'validate'`` lock (never the run pipeline's lock, D5)."""
617
+ from abkit.compute.recompute_backend import RecomputeBackend
618
+ from abkit.database.internal_tables import InternalTablesManager
619
+ from abkit.utils.datetime_utils import now_utc_naive
620
+ from abkit.utils.json_utils import json_loads
621
+ from abkit.validate import ValidateSettings, aa_run_records, run_validation
622
+
623
+ session = cast(ExploreSession, srv.session)
624
+ factory = cast(Callable[[], Any], srv.manager_factory)
625
+ metric_sqls = cast("dict[str, str]", srv.metric_sql_by_name)
626
+ metrics_by_name = cast("dict[str, MetricConfig]", srv.metrics_by_name)
627
+ experiment = session.experiment
628
+
629
+ settings = ValidateSettings(iterations=AUTO_ITERATIONS, mode="fpr", grid_cap=AUTO_GRID_CAP)
630
+ srv.echo(
631
+ f"VALIDATE {experiment.name}: {settings.iterations} placebo splits/cell "
632
+ f"(Auto — a reduced estimate; run `abk validate` for the full population)"
633
+ )
634
+
635
+ # The manager's WHOLE lifetime is under the outer try/finally so it is closed
636
+ # even if acquire_lock itself raises (a transient DB error, or `_ab_tasks`
637
+ # absent before ensure_tables) — the /reload precedent (a raise before the
638
+ # inner try must not leak a connection in the long-lived server).
639
+ manager = factory()
640
+ try:
641
+ tables = InternalTablesManager(manager)
642
+ if not tables.acquire_lock(
643
+ experiment.name,
644
+ "pipeline",
645
+ "validate",
646
+ timeout_seconds=session.project.timeouts.compute,
647
+ force=False,
648
+ ):
649
+ raise ValueError(
650
+ "an `abk validate` run is already in progress for this experiment — retry shortly"
651
+ )
652
+ try:
653
+ tables.ensure_tables()
654
+ backend = RecomputeBackend(manager, experiment)
655
+ result = run_validation(
656
+ backend,
657
+ experiment,
658
+ session.project,
659
+ metrics_by_name,
660
+ metric_sqls,
661
+ session.grid,
662
+ settings,
663
+ now_iso=now_utc_naive().isoformat(),
664
+ )
665
+ records = aa_run_records(result)
666
+ for record in records:
667
+ tables.save_aa_run(record)
668
+ # D11: refresh the one-time snapshot in place so subsequent /recompute
669
+ # D3 lookups (find_calibration reads session.aa_rows) go green without a
670
+ # restart. Re-read so the LWW-stamped created_at drives the newest-wins
671
+ # ordering find_calibration relies on.
672
+ session.aa_rows = tables.get_aa_runs(experiment.name)
673
+ tables.release_lock(experiment.name, "pipeline", "validate", status="completed")
674
+ except Exception as exc:
675
+ # only reached AFTER a successful acquire — release the lock we hold
676
+ tables.release_lock(
677
+ experiment.name, "pipeline", "validate", status="failed", error_message=str(exc)
678
+ )
679
+ raise
680
+ finally:
681
+ manager.close()
682
+
683
+ # The recommended knob state per metric + the REFRESHED calibration (read off
684
+ # the just-mutated snapshot) so the client re-seeds the rail and re-renders
685
+ # the chip verbatim without a round-trip.
686
+ recommended: dict[str, Any] = {}
687
+ for cell in result.cells:
688
+ if not cell.recommended:
689
+ continue
690
+ metric_cfg = metrics_by_name.get(cell.metric)
691
+ budget = resolve_fpr_budget(session.project, cell.alpha, metric_cfg)
692
+ calibration = find_calibration(
693
+ session.aa_rows, cell.metric, cell.method_config_id, cell.alpha, budget=budget
694
+ )
695
+ try:
696
+ params = json_loads(cell.method_params)
697
+ except (TypeError, ValueError):
698
+ params = {}
699
+ recommended[cell.metric] = {
700
+ "method": {
701
+ "name": cell.method_name,
702
+ "params": params if isinstance(params, dict) else {},
703
+ },
704
+ "alpha": cell.alpha,
705
+ "verdict": cell.verdict,
706
+ "calibration": asdict(calibration),
707
+ }
708
+ srv.echo(
709
+ f"VALIDATE {experiment.name}: done — {len(records)} cell(s), "
710
+ f"{len(recommended)} metric(s) recommended"
711
+ )
712
+ return {
713
+ "recommended": recommended,
714
+ "log": [f"{entry.stage}: {entry.message}" for entry in result.decision_log],
715
+ }
716
+
717
+
718
+ def _json_default(o: Any) -> Any:
719
+ """JSON fallback so a reply carrying numpy scalars/arrays serializes.
720
+
721
+ Invoked by ``json.dumps`` only for otherwise-unserializable values, so the
722
+ hot plain-dict replies never import numpy.
723
+ """
724
+ import numpy as np
725
+
726
+ if isinstance(o, np.generic):
727
+ return o.item()
728
+ if isinstance(o, np.ndarray):
729
+ return o.tolist()
730
+ if isinstance(o, datetime):
731
+ return _ms(o)
732
+ raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")
733
+
734
+
735
+ def _result_json(result: RecomputeResult, request_id: int | None) -> dict[str, Any]:
736
+ """One RecomputeResult as the wire reply (datetimes → ms-epoch ints)."""
737
+ return {
738
+ "request_id": request_id,
739
+ "metric": result.metric,
740
+ "method": result.method_name,
741
+ "method_config_id": result.method_config_id,
742
+ "alpha": result.alpha,
743
+ "identity_changed": result.identity_changed,
744
+ "warnings": list(result.warnings),
745
+ "calibration": asdict(result.calibration),
746
+ "pairs": [
747
+ {
748
+ "name_1": pair.name_1,
749
+ "name_2": pair.name_2,
750
+ "chips": {
751
+ **pair.chips,
752
+ "latest_end_ts": (
753
+ None
754
+ if pair.chips.get("latest_end_ts") is None
755
+ else _ms(pair.chips["latest_end_ts"])
756
+ ),
757
+ },
758
+ "points": [
759
+ {
760
+ "end_ts": _ms(point.end_ts),
761
+ "elapsed_days": point.elapsed_days,
762
+ "tier": point.tier,
763
+ "effect": point.effect,
764
+ "left_bound": point.left_bound,
765
+ "right_bound": point.right_bound,
766
+ "pvalue": point.pvalue,
767
+ "reject": point.reject,
768
+ "mde_1": point.mde_1,
769
+ "mde_2": point.mde_2,
770
+ "value_1": point.value_1,
771
+ "value_2": point.value_2,
772
+ "std_1": point.std_1,
773
+ "std_2": point.std_2,
774
+ "size_1": point.size_1,
775
+ "size_2": point.size_2,
776
+ "insufficient": point.insufficient,
777
+ "warnings": list(point.warnings),
778
+ }
779
+ for point in pair.points
780
+ ],
781
+ }
782
+ for pair in result.pairs
783
+ ],
784
+ }
785
+
786
+
787
+ def build_explore_server(
788
+ *,
789
+ payload: dict[str, Any],
790
+ original_path: Path,
791
+ project_root: Path,
792
+ session: ExploreSession | None = None,
793
+ engine: RecomputeEngine | None = None,
794
+ tables: InternalTablesManager | None = None,
795
+ metrics_by_name: dict[str, MetricConfig] | None = None,
796
+ manager_factory: Callable[[], BaseDatabaseManager] | None = None,
797
+ metric_sql_by_name: dict[str, str] | None = None,
798
+ ) -> tuple[_ExploreServer, str]:
799
+ """Construct (without running) the explore server; return ``(server, url)``.
800
+
801
+ The bound port is known only after construction, so the tokened endpoint
802
+ URLs are injected into the payload here and the HTML is rendered ONCE,
803
+ post-bind. Omitting ``manager_factory``/``metric_sql_by_name`` disables
804
+ ``/reload`` (400); omitting ``engine`` disables ``/recompute`` too — the
805
+ static-preview degradations, never crashes.
806
+ """
807
+ server = _ExploreServer(("127.0.0.1", 0), _Handler)
808
+ token = secrets.token_urlsafe(16)
809
+ port = int(server.server_address[1])
810
+ server.token = token
811
+ server.original_path = original_path
812
+ server.project_root = project_root
813
+ server.session = session
814
+ server.engine = engine
815
+ server.tables = tables
816
+ server.metrics_by_name = metrics_by_name
817
+ server.manager_factory = manager_factory
818
+ server.metric_sql_by_name = metric_sql_by_name
819
+ endpoint_urls = {
820
+ "save_url": f"http://127.0.0.1:{port}/apply?token={token}",
821
+ "recompute_url": f"http://127.0.0.1:{port}/recompute?token={token}",
822
+ "reload_url": f"http://127.0.0.1:{port}/reload?token={token}",
823
+ "validate_url": f"http://127.0.0.1:{port}/validate?token={token}",
824
+ }
825
+ assert set(endpoint_urls) == set(ENDPOINT_SLOTS)
826
+ server.html = render_explore_html({**payload, **endpoint_urls})
827
+ return server, f"http://127.0.0.1:{port}/?token={token}"
828
+
829
+
830
+ def serve_explore(
831
+ *,
832
+ payload: dict[str, Any],
833
+ original_path: Path,
834
+ project_root: Path,
835
+ session: ExploreSession | None = None,
836
+ engine: RecomputeEngine | None = None,
837
+ tables: InternalTablesManager | None = None,
838
+ metrics_by_name: dict[str, MetricConfig] | None = None,
839
+ manager_factory: Callable[[], BaseDatabaseManager] | None = None,
840
+ metric_sql_by_name: dict[str, str] | None = None,
841
+ open_browser: bool = True,
842
+ echo: Callable[[str], None] = print,
843
+ on_ready: Callable[[str], None] | None = None,
844
+ ) -> AppliedConfig | None:
845
+ """Serve explore until the user applies (returns the result) or cancels (None)."""
846
+ server, url = build_explore_server(
847
+ payload=payload,
848
+ original_path=original_path,
849
+ project_root=project_root,
850
+ session=session,
851
+ engine=engine,
852
+ tables=tables,
853
+ metrics_by_name=metrics_by_name,
854
+ manager_factory=manager_factory,
855
+ metric_sql_by_name=metric_sql_by_name,
856
+ )
857
+ server.echo = echo
858
+ if on_ready is not None:
859
+ on_ready(url)
860
+ echo(f" Explore: {url}")
861
+ echo(
862
+ " Open the URL above if no browser opens. Turn the knobs, then click "
863
+ "Apply (Ctrl-C to cancel)."
864
+ )
865
+ if open_browser:
866
+ try:
867
+ with _quiet_stderr():
868
+ webbrowser.open(url)
869
+ except Exception:
870
+ pass
871
+ try:
872
+ server.serve_forever(poll_interval=0.3)
873
+ except KeyboardInterrupt:
874
+ # Fall through to the applied-aware return: a Ctrl-C racing the
875
+ # post-Apply self-shutdown window (~poll_interval) must not discard a
876
+ # SUCCESSFUL Apply — the YAML is already rewritten and a series
877
+ # possibly orphaned; reporting it as "cancelled — unchanged" would
878
+ # suppress the orphan/re-run epilogue (milestone-review finding).
879
+ pass
880
+ finally:
881
+ server.server_close()
882
+ return server.applied