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.
- ab_analysis_kit-0.0.1.dev0.dist-info/METADATA +126 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/RECORD +122 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/WHEEL +5 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/entry_points.txt +2 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/licenses/LICENSE +21 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/top_level.txt +1 -0
- abkit/__init__.py +40 -0
- abkit/cli/__init__.py +1 -0
- abkit/cli/_output.py +111 -0
- abkit/cli/commands/__init__.py +1 -0
- abkit/cli/commands/_context.py +83 -0
- abkit/cli/commands/clean.py +133 -0
- abkit/cli/commands/explore.py +208 -0
- abkit/cli/commands/init.py +427 -0
- abkit/cli/commands/run.py +282 -0
- abkit/cli/commands/unlock.py +59 -0
- abkit/cli/commands/validate.py +264 -0
- abkit/cli/main.py +279 -0
- abkit/compute/__init__.py +5 -0
- abkit/compute/recompute_backend.py +140 -0
- abkit/config/__init__.py +51 -0
- abkit/config/discovery.py +168 -0
- abkit/config/experiment_config.py +511 -0
- abkit/config/method_config.py +80 -0
- abkit/config/metric_config.py +214 -0
- abkit/config/profile.py +301 -0
- abkit/config/project_config.py +244 -0
- abkit/config/validator.py +393 -0
- abkit/core/__init__.py +26 -0
- abkit/core/interval.py +148 -0
- abkit/core/models.py +121 -0
- abkit/core/period_planner.py +206 -0
- abkit/database/__init__.py +51 -0
- abkit/database/_sql_manager.py +432 -0
- abkit/database/clickhouse_manager.py +495 -0
- abkit/database/internal_tables/__init__.py +6 -0
- abkit/database/internal_tables/_aa_runs.py +53 -0
- abkit/database/internal_tables/_base.py +71 -0
- abkit/database/internal_tables/_experiments.py +82 -0
- abkit/database/internal_tables/_exposures.py +163 -0
- abkit/database/internal_tables/_maintenance.py +72 -0
- abkit/database/internal_tables/_results.py +231 -0
- abkit/database/internal_tables/_schema.py +23 -0
- abkit/database/internal_tables/_tasks.py +237 -0
- abkit/database/internal_tables/_unit_state.py +148 -0
- abkit/database/internal_tables/manager.py +30 -0
- abkit/database/manager.py +450 -0
- abkit/database/mysql_manager.py +175 -0
- abkit/database/postgres_manager.py +145 -0
- abkit/database/tables.py +326 -0
- abkit/loaders/__init__.py +28 -0
- abkit/loaders/exposure_loader.py +121 -0
- abkit/loaders/metric_loader.py +251 -0
- abkit/loaders/query_template.py +167 -0
- abkit/loaders/templates/abkit_assignment.jinja +62 -0
- abkit/pipeline/__init__.py +37 -0
- abkit/pipeline/_types.py +52 -0
- abkit/pipeline/analyze.py +223 -0
- abkit/pipeline/driver.py +477 -0
- abkit/pipeline/enrich.py +137 -0
- abkit/pipeline/readout.py +779 -0
- abkit/reporting/__init__.py +19 -0
- abkit/reporting/assets/report.js +138 -0
- abkit/reporting/builder.py +484 -0
- abkit/reporting/calibration.py +182 -0
- abkit/reporting/html_report.py +109 -0
- abkit/stats/__init__.py +94 -0
- abkit/stats/accumulate.py +82 -0
- abkit/stats/base.py +347 -0
- abkit/stats/bootstrap/__init__.py +69 -0
- abkit/stats/bootstrap/applier.py +81 -0
- abkit/stats/bootstrap/bootstrap.py +311 -0
- abkit/stats/bootstrap/ci.py +72 -0
- abkit/stats/bootstrap/engine.py +383 -0
- abkit/stats/bootstrap/paired_bootstrap.py +57 -0
- abkit/stats/bootstrap/paired_post_normed_bootstrap.py +81 -0
- abkit/stats/bootstrap/poisson_bootstrap.py +112 -0
- abkit/stats/bootstrap/post_normed_bootstrap.py +102 -0
- abkit/stats/correction.py +88 -0
- abkit/stats/effects.py +141 -0
- abkit/stats/exceptions.py +31 -0
- abkit/stats/factory.py +26 -0
- abkit/stats/parametric/__init__.py +10 -0
- abkit/stats/parametric/cuped_ttest.py +183 -0
- abkit/stats/parametric/paired_cuped_ttest.py +125 -0
- abkit/stats/parametric/paired_ttest.py +136 -0
- abkit/stats/parametric/ratio_delta.py +113 -0
- abkit/stats/parametric/ttest.py +105 -0
- abkit/stats/parametric/ztest.py +134 -0
- abkit/stats/power.py +278 -0
- abkit/stats/registry.py +111 -0
- abkit/stats/result.py +84 -0
- abkit/stats/rng.py +39 -0
- abkit/stats/samples.py +531 -0
- abkit/stats/sequential/__init__.py +18 -0
- abkit/stats/sequential/apply.py +37 -0
- abkit/stats/sequential/confidence_sequence.py +96 -0
- abkit/stats/sequential/mixture.py +70 -0
- abkit/stats/srm.py +221 -0
- abkit/tuning/__init__.py +59 -0
- abkit/tuning/assets/explore.js +173 -0
- abkit/tuning/config_writer.py +409 -0
- abkit/tuning/html.py +88 -0
- abkit/tuning/payload.py +122 -0
- abkit/tuning/recompute.py +1039 -0
- abkit/tuning/server.py +882 -0
- abkit/tuning/session.py +233 -0
- abkit/utils/__init__.py +27 -0
- abkit/utils/datetime_utils.py +97 -0
- abkit/utils/env_interpolation.py +50 -0
- abkit/utils/json_utils.py +38 -0
- abkit/validate/__init__.py +36 -0
- abkit/validate/_types.py +35 -0
- abkit/validate/inject.py +75 -0
- abkit/validate/load.py +160 -0
- abkit/validate/panel.py +59 -0
- abkit/validate/persistence.py +59 -0
- abkit/validate/resample.py +94 -0
- abkit/validate/result.py +60 -0
- abkit/validate/run_id.py +45 -0
- abkit/validate/runner.py +389 -0
- abkit/validate/scoring.py +544 -0
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"""Write a tuned experiment config back to its YAML — safely (WP5, D4).
|
|
2
|
+
|
|
3
|
+
The ONLY mutation seam of ``abk explore``. Order is validate → archive →
|
|
4
|
+
re-emit (the donor's discipline): a broken config never lands, and the
|
|
5
|
+
previous file is always recoverable **byte-verbatim** from
|
|
6
|
+
``<dir>/.history/<experiment>/`` (discovery excludes hidden dirs, so archives
|
|
7
|
+
are never picked up as live configs).
|
|
8
|
+
|
|
9
|
+
Apply targets ONE file — the experiment YAML (method params live on
|
|
10
|
+
``ComparisonConfig``; metric YAMLs are never touched, which also keeps the
|
|
11
|
+
analysis-unit knob preview-only). Write-back **merges**: each
|
|
12
|
+
:class:`TunedComparison` rewrites only its own comparison (matched by
|
|
13
|
+
metric); every comparison the cockpit didn't touch is preserved, and
|
|
14
|
+
experiment-level ``alpha``/``correction`` edits ride the same Apply.
|
|
15
|
+
|
|
16
|
+
Orphaning (D4, NEW vs the donor): before writing, the old-vs-new
|
|
17
|
+
``method_config_id`` is computed per touched comparison through the single
|
|
18
|
+
hashing path (``MethodConfig`` → the bound probe), and when the id changes
|
|
19
|
+
over a series with persisted rows the result carries an ``orphaned`` block —
|
|
20
|
+
the warning text mirrors the driver's. Apply **never** auto-cleans or
|
|
21
|
+
auto-runs: ``clean`` deletes data and ``run`` takes locks — both deserve
|
|
22
|
+
explicit intent.
|
|
23
|
+
|
|
24
|
+
YAML comments die on safe_load → re-emit; the verbatim archive is the
|
|
25
|
+
recovery (owner-ratified, D4). Re-emission is isolated behind ONE strategy
|
|
26
|
+
function — :func:`_reemit_yaml` — so a comment-preserving ruamel backend can
|
|
27
|
+
swap in later without touching the Apply contract (the ROADMAP backlog note).
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import os
|
|
33
|
+
import tempfile
|
|
34
|
+
from collections.abc import Mapping
|
|
35
|
+
from dataclasses import dataclass
|
|
36
|
+
from datetime import datetime, timezone
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
from typing import Any
|
|
39
|
+
|
|
40
|
+
import yaml
|
|
41
|
+
|
|
42
|
+
from abkit.config.experiment_config import ExperimentConfig
|
|
43
|
+
from abkit.config.method_config import MethodConfig
|
|
44
|
+
from abkit.config.metric_config import MetricConfig
|
|
45
|
+
from abkit.database.internal_tables import InternalTablesManager
|
|
46
|
+
from abkit.stats import create_method, get_method_class
|
|
47
|
+
|
|
48
|
+
_RULE = "# " + "─" * 61
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class TunedComparison:
|
|
53
|
+
"""One comparison the cockpit is writing back, matched by ``metric``.
|
|
54
|
+
|
|
55
|
+
``params`` is the FULL method param set for the dirty comparison (the
|
|
56
|
+
cockpit sends everything it shows — the donor's dirty-slot discipline:
|
|
57
|
+
the opened comparison is always written, a merely-viewed one never is).
|
|
58
|
+
``method_name=None`` keeps the configured method name; ``params=None``
|
|
59
|
+
with role flips only is a Review-mode marking edit (D9).
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
metric: str
|
|
63
|
+
method_name: str | None = None
|
|
64
|
+
params: Mapping[str, Any] | None = None
|
|
65
|
+
is_main_metric: bool | None = None
|
|
66
|
+
is_guardrail: bool | None = None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True)
|
|
70
|
+
class OrphanedSeries:
|
|
71
|
+
"""A touched comparison whose identity edit strands persisted rows."""
|
|
72
|
+
|
|
73
|
+
metric: str
|
|
74
|
+
old_id: str
|
|
75
|
+
new_id: str
|
|
76
|
+
rows: int
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True)
|
|
80
|
+
class AppliedConfig:
|
|
81
|
+
"""Result of one Apply: paths, what changed, and the orphaning consequence."""
|
|
82
|
+
|
|
83
|
+
experiment: str
|
|
84
|
+
saved: Path
|
|
85
|
+
archived: Path
|
|
86
|
+
updated: tuple[str, ...] = ()
|
|
87
|
+
preserved: tuple[str, ...] = ()
|
|
88
|
+
experiment_fields: tuple[str, ...] = ()
|
|
89
|
+
orphaned: tuple[OrphanedSeries, ...] = ()
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def orphan_warning(self) -> str | None:
|
|
93
|
+
"""The driver-identical warning line for the confirm dialog / reply /
|
|
94
|
+
CLI epilogue (driver.py's orphan scan wording + the re-run hint)."""
|
|
95
|
+
if not self.orphaned:
|
|
96
|
+
return None
|
|
97
|
+
parts = ", ".join(
|
|
98
|
+
f"{o.metric} ({o.rows} rows under {o.old_id[:12]}…)" for o in self.orphaned
|
|
99
|
+
)
|
|
100
|
+
return (
|
|
101
|
+
f"{self.experiment}: orphaned method_config_id series in _ab_results — "
|
|
102
|
+
f"{parts} (the BI chart will show duplicate stabilization lines) — run "
|
|
103
|
+
f"`abk clean`, then `abk run --select {self.experiment}`"
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _stamp(now: datetime | None = None) -> str:
|
|
108
|
+
"""UTC filesystem-safe timestamp (``20260704T101530Z``)."""
|
|
109
|
+
now = now or datetime.now(timezone.utc)
|
|
110
|
+
return now.strftime("%Y%m%dT%H%M%SZ")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _reemit_yaml(document: dict[str, Any], original_bytes: bytes) -> bytes:
|
|
114
|
+
"""THE document re-emission strategy (D4's designed seam).
|
|
115
|
+
|
|
116
|
+
PyYAML ``safe_dump`` today — comments die, the archive is the recovery. A
|
|
117
|
+
comment-preserving ruamel backend can replace this one function (using
|
|
118
|
+
``original_bytes`` for round-trip state) without touching the Apply
|
|
119
|
+
contract, the validate→archive→re-emit order, or archive semantics.
|
|
120
|
+
Nothing else in this module may serialize YAML.
|
|
121
|
+
"""
|
|
122
|
+
del original_bytes # unused by the PyYAML strategy
|
|
123
|
+
return yaml.safe_dump(
|
|
124
|
+
document, sort_keys=False, default_flow_style=False, allow_unicode=True
|
|
125
|
+
).encode("utf-8")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _identity_excluded_carryover(
|
|
129
|
+
method_cls: type, old_params: Mapping[str, Any], params: dict[str, Any]
|
|
130
|
+
) -> None:
|
|
131
|
+
"""Carry identity-excluded params (``seed``, ``max_block_bytes``) from the
|
|
132
|
+
slot being retuned unless the cockpit supplied them — the donor's
|
|
133
|
+
execution-param carry-over, derived from the specs, never a hardcode."""
|
|
134
|
+
for spec in method_cls.param_specs:
|
|
135
|
+
if not spec.identity and spec.name in old_params and spec.name not in params:
|
|
136
|
+
params[spec.name] = old_params[spec.name]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _method_config_id_of(entry: Mapping[str, Any]) -> str | None:
|
|
140
|
+
"""The canonical id of a comparison entry's method block, or ``None`` when
|
|
141
|
+
the stored block no longer binds (a legacy/broken entry never blocks Apply)."""
|
|
142
|
+
method = entry.get("method")
|
|
143
|
+
if not isinstance(method, Mapping) or not method.get("name"):
|
|
144
|
+
return None
|
|
145
|
+
try:
|
|
146
|
+
return MethodConfig(
|
|
147
|
+
name=str(method["name"]), params=dict(method.get("params") or {})
|
|
148
|
+
).method_config_id
|
|
149
|
+
except Exception:
|
|
150
|
+
return None
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _header(
|
|
154
|
+
experiment: str,
|
|
155
|
+
archive_rel: str,
|
|
156
|
+
stamp: str,
|
|
157
|
+
updated: list[str],
|
|
158
|
+
preserved: list[str],
|
|
159
|
+
experiment_fields: list[str],
|
|
160
|
+
orphan_warning: str | None,
|
|
161
|
+
) -> str:
|
|
162
|
+
changed = f"# Updated comparison(s): {', '.join(updated) if updated else 'none'}"
|
|
163
|
+
if preserved:
|
|
164
|
+
changed += f"; preserved: {', '.join(preserved)}"
|
|
165
|
+
if experiment_fields:
|
|
166
|
+
changed += f". Experiment-level: {', '.join(experiment_fields)}."
|
|
167
|
+
lines = [
|
|
168
|
+
_RULE,
|
|
169
|
+
f"# Hand-tuned via `abk explore` ({stamp})",
|
|
170
|
+
f"# Previous config archived at: {archive_rel}",
|
|
171
|
+
changed,
|
|
172
|
+
]
|
|
173
|
+
if orphan_warning:
|
|
174
|
+
lines.append(f"# ⚠ {orphan_warning}")
|
|
175
|
+
lines += [f"# Reproduce: abk explore --select {experiment}", _RULE]
|
|
176
|
+
# every line must stay ONE comment line — a newline smuggled through a
|
|
177
|
+
# name would inject uncommented text into the emitted YAML
|
|
178
|
+
return "\n".join(line.replace("\n", " ").replace("\r", " ") for line in lines)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _merge_comparison(
|
|
182
|
+
entries: list[Any],
|
|
183
|
+
tuned: TunedComparison,
|
|
184
|
+
metrics_by_name: Mapping[str, MetricConfig] | None,
|
|
185
|
+
) -> tuple[int, dict[str, Any], str | None, str | None]:
|
|
186
|
+
"""Validate one tuned comparison and return its merged entry.
|
|
187
|
+
|
|
188
|
+
Returns ``(slot, new_entry, old_id, new_id)``. Raises ``ValueError``
|
|
189
|
+
(nothing written upstream) on an unknown metric, a non-tunable method
|
|
190
|
+
(paired / wrong input kind — tunability is registry-derived, never a
|
|
191
|
+
hardcoded name set), or invalid params.
|
|
192
|
+
"""
|
|
193
|
+
slot = next(
|
|
194
|
+
(
|
|
195
|
+
i
|
|
196
|
+
for i, entry in enumerate(entries)
|
|
197
|
+
if isinstance(entry, Mapping) and entry.get("metric") == tuned.metric
|
|
198
|
+
),
|
|
199
|
+
None,
|
|
200
|
+
)
|
|
201
|
+
if slot is None:
|
|
202
|
+
raise ValueError(
|
|
203
|
+
f"comparison for metric '{tuned.metric}' not found in the experiment "
|
|
204
|
+
"(Apply edits existing comparisons; it never invents new ones)"
|
|
205
|
+
)
|
|
206
|
+
entry = dict(entries[slot])
|
|
207
|
+
old_id = _method_config_id_of(entry)
|
|
208
|
+
|
|
209
|
+
if tuned.params is None and tuned.method_name is not None:
|
|
210
|
+
raise ValueError(
|
|
211
|
+
f"comparison '{tuned.metric}': a method switch must carry the full "
|
|
212
|
+
"param set (the cockpit always sends what it shows)"
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
new_id = old_id
|
|
216
|
+
if tuned.params is not None:
|
|
217
|
+
old_method = entry.get("method") if isinstance(entry.get("method"), Mapping) else {}
|
|
218
|
+
old_name = str(old_method.get("name", "")) if old_method else ""
|
|
219
|
+
old_params = dict(old_method.get("params") or {}) if old_method else {}
|
|
220
|
+
name = tuned.method_name or old_name
|
|
221
|
+
if not name:
|
|
222
|
+
raise ValueError(f"comparison '{tuned.metric}': no method name to apply")
|
|
223
|
+
|
|
224
|
+
method_cls = get_method_class(name) # Unknown/Quarantined surface verbatim
|
|
225
|
+
if method_cls.is_paired:
|
|
226
|
+
raise ValueError(
|
|
227
|
+
f"method '{name}' is a paired design — not tunable from explore "
|
|
228
|
+
"(the pipeline serves independent-arm experiments)"
|
|
229
|
+
)
|
|
230
|
+
if metrics_by_name is not None and tuned.metric in metrics_by_name:
|
|
231
|
+
metric_type = metrics_by_name[tuned.metric].type
|
|
232
|
+
if method_cls.input_kind != metric_type:
|
|
233
|
+
raise ValueError(
|
|
234
|
+
f"method '{name}' expects a '{method_cls.input_kind}' metric, "
|
|
235
|
+
f"got '{metric_type}' ({tuned.metric})"
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
params = {k: v for k, v in dict(tuned.params).items() if k != "name"}
|
|
239
|
+
_identity_excluded_carryover(method_cls, old_params, params)
|
|
240
|
+
# Validate by actually constructing the method (its ParamSpecs run);
|
|
241
|
+
# alpha is experiment-level and does not affect param validation.
|
|
242
|
+
create_method(name, alpha=0.05, params=dict(params))
|
|
243
|
+
|
|
244
|
+
entry["method"] = {"name": name, "params": params} if params else {"name": name}
|
|
245
|
+
new_id = MethodConfig(name=name, params=dict(params)).method_config_id
|
|
246
|
+
|
|
247
|
+
if tuned.is_main_metric is not None:
|
|
248
|
+
entry["is_main_metric"] = bool(tuned.is_main_metric)
|
|
249
|
+
if tuned.is_guardrail is not None:
|
|
250
|
+
entry["is_guardrail"] = bool(tuned.is_guardrail)
|
|
251
|
+
|
|
252
|
+
return slot, entry, old_id, new_id
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def apply_tuned_config(
|
|
256
|
+
*,
|
|
257
|
+
original_path: Path,
|
|
258
|
+
project_root: Path,
|
|
259
|
+
comparisons: list[TunedComparison] | None = None,
|
|
260
|
+
alpha: float | None = None,
|
|
261
|
+
correction: str | None = None,
|
|
262
|
+
tables: InternalTablesManager | None = None,
|
|
263
|
+
metrics_by_name: Mapping[str, MetricConfig] | None = None,
|
|
264
|
+
now: datetime | None = None,
|
|
265
|
+
) -> AppliedConfig:
|
|
266
|
+
"""Validate, archive, then re-emit the experiment YAML with the edits merged.
|
|
267
|
+
|
|
268
|
+
The single Apply seam (D4): per-comparison ``method`` blocks, Review-mode
|
|
269
|
+
role flips, and experiment-level ``alpha``/``correction`` — merged into
|
|
270
|
+
the parsed document, validated as a whole (``ExperimentConfig``), archived
|
|
271
|
+
byte-verbatim, then re-emitted through :func:`_reemit_yaml`. Raises
|
|
272
|
+
``ValueError`` / the stats-core config exceptions (writing NOTHING) on any
|
|
273
|
+
invalid input or an empty change-set.
|
|
274
|
+
|
|
275
|
+
``tables`` (optional) enables the orphan scan: an identity-changing edit
|
|
276
|
+
over a series with persisted rows yields the ``orphaned`` block + the
|
|
277
|
+
driver-identical warning. Apply never auto-cleans and never auto-runs.
|
|
278
|
+
"""
|
|
279
|
+
comparisons = comparisons or []
|
|
280
|
+
if not comparisons and alpha is None and correction is None:
|
|
281
|
+
raise ValueError("nothing to apply: no comparison edits and no experiment-level changes")
|
|
282
|
+
|
|
283
|
+
original_bytes = original_path.read_bytes()
|
|
284
|
+
raw = yaml.safe_load(original_bytes.decode("utf-8"))
|
|
285
|
+
if not isinstance(raw, dict):
|
|
286
|
+
raise ValueError(f"experiment config is empty or malformed: {original_path}")
|
|
287
|
+
|
|
288
|
+
# Support the nested `experiment: {...}` form (ExperimentConfig.from_yaml_file).
|
|
289
|
+
nested = isinstance(raw.get("experiment"), dict)
|
|
290
|
+
body: dict[str, Any] = raw["experiment"] if nested else raw
|
|
291
|
+
|
|
292
|
+
entries = body.get("comparisons")
|
|
293
|
+
merged: list[Any] = list(entries) if isinstance(entries, list) else []
|
|
294
|
+
|
|
295
|
+
updated_slots: set[int] = set()
|
|
296
|
+
updated_metrics: list[str] = []
|
|
297
|
+
id_changes: list[tuple[str, str | None, str | None]] = []
|
|
298
|
+
for tuned in comparisons:
|
|
299
|
+
slot, entry, old_id, new_id = _merge_comparison(merged, tuned, metrics_by_name)
|
|
300
|
+
if slot in updated_slots:
|
|
301
|
+
raise ValueError(f"comparison '{tuned.metric}' appears twice in one Apply")
|
|
302
|
+
merged[slot] = entry
|
|
303
|
+
updated_slots.add(slot)
|
|
304
|
+
updated_metrics.append(tuned.metric)
|
|
305
|
+
id_changes.append((tuned.metric, old_id, new_id))
|
|
306
|
+
|
|
307
|
+
body["comparisons"] = merged
|
|
308
|
+
preserved_metrics = [
|
|
309
|
+
str(entry.get("metric"))
|
|
310
|
+
for i, entry in enumerate(merged)
|
|
311
|
+
if i not in updated_slots and isinstance(entry, Mapping)
|
|
312
|
+
]
|
|
313
|
+
|
|
314
|
+
experiment_fields: list[str] = []
|
|
315
|
+
if alpha is not None:
|
|
316
|
+
body["alpha"] = alpha
|
|
317
|
+
experiment_fields.append(f"alpha={alpha:g}")
|
|
318
|
+
if correction is not None:
|
|
319
|
+
body["correction"] = correction
|
|
320
|
+
experiment_fields.append(f"correction={correction}")
|
|
321
|
+
|
|
322
|
+
# Validate the WHOLE merged document before touching the filesystem.
|
|
323
|
+
validated = ExperimentConfig.model_validate(body)
|
|
324
|
+
experiment_name = validated.name
|
|
325
|
+
|
|
326
|
+
# Orphan detection (D4): identity changed AND persisted rows under the old id.
|
|
327
|
+
orphaned: list[OrphanedSeries] = []
|
|
328
|
+
if tables is not None:
|
|
329
|
+
for metric, old_id, new_id in id_changes:
|
|
330
|
+
if new_id is None or old_id == new_id:
|
|
331
|
+
continue
|
|
332
|
+
stored = tables.list_method_config_ids(experiment_name, metric)
|
|
333
|
+
if old_id is None:
|
|
334
|
+
# The stored method block no longer binds (legacy/quarantined
|
|
335
|
+
# entry) — the id it ran under is unknowable from the config.
|
|
336
|
+
# A broken entry never BLOCKS Apply, but the warn-before-write
|
|
337
|
+
# DoD must still hold: every persisted series that is not the
|
|
338
|
+
# new id is about to be stranded.
|
|
339
|
+
for (m, stored_id), rows in stored.items():
|
|
340
|
+
if m == metric and stored_id != new_id and rows:
|
|
341
|
+
orphaned.append(
|
|
342
|
+
OrphanedSeries(
|
|
343
|
+
metric=metric, old_id=stored_id, new_id=new_id, rows=rows
|
|
344
|
+
)
|
|
345
|
+
)
|
|
346
|
+
continue
|
|
347
|
+
rows = stored.get((metric, old_id), 0)
|
|
348
|
+
if rows:
|
|
349
|
+
orphaned.append(
|
|
350
|
+
OrphanedSeries(metric=metric, old_id=old_id, new_id=new_id, rows=rows)
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
# Archive the previous file byte-verbatim; only then overwrite.
|
|
354
|
+
stamp = _stamp(now)
|
|
355
|
+
archive_dir = original_path.parent / ".history" / experiment_name
|
|
356
|
+
archive_dir.mkdir(parents=True, exist_ok=True)
|
|
357
|
+
archive_path = archive_dir / f"{experiment_name}-{stamp}.yml"
|
|
358
|
+
suffix = 1
|
|
359
|
+
while archive_path.exists(): # rapid same-second Applies must not clobber
|
|
360
|
+
suffix += 1
|
|
361
|
+
archive_path = archive_dir / f"{experiment_name}-{stamp}-{suffix}.yml"
|
|
362
|
+
archive_path.write_bytes(original_bytes)
|
|
363
|
+
|
|
364
|
+
try:
|
|
365
|
+
archive_rel = str(archive_path.relative_to(project_root))
|
|
366
|
+
except ValueError:
|
|
367
|
+
archive_rel = str(archive_path)
|
|
368
|
+
|
|
369
|
+
result = AppliedConfig(
|
|
370
|
+
experiment=experiment_name,
|
|
371
|
+
saved=original_path,
|
|
372
|
+
archived=archive_path,
|
|
373
|
+
updated=tuple(updated_metrics),
|
|
374
|
+
preserved=tuple(preserved_metrics),
|
|
375
|
+
experiment_fields=tuple(experiment_fields),
|
|
376
|
+
orphaned=tuple(orphaned),
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
header = _header(
|
|
380
|
+
experiment_name,
|
|
381
|
+
archive_rel,
|
|
382
|
+
stamp,
|
|
383
|
+
updated_metrics,
|
|
384
|
+
preserved_metrics,
|
|
385
|
+
experiment_fields,
|
|
386
|
+
result.orphan_warning,
|
|
387
|
+
)
|
|
388
|
+
_atomic_write_bytes(
|
|
389
|
+
original_path, header.encode("utf-8") + b"\n" + _reemit_yaml(raw, original_bytes)
|
|
390
|
+
)
|
|
391
|
+
return result
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _atomic_write_bytes(path: Path, data: bytes) -> None:
|
|
395
|
+
"""temp + ``os.replace`` in the target's own directory (same filesystem)
|
|
396
|
+
so a mid-write failure (ENOSPC, SIGKILL, power loss) can never truncate
|
|
397
|
+
the user's live config — "a broken config never lands" applies to the
|
|
398
|
+
filesystem, not just the validator."""
|
|
399
|
+
fd, tmp_name = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
|
|
400
|
+
try:
|
|
401
|
+
with os.fdopen(fd, "wb") as handle:
|
|
402
|
+
handle.write(data)
|
|
403
|
+
handle.flush()
|
|
404
|
+
os.fsync(handle.fileno())
|
|
405
|
+
os.replace(tmp_name, path)
|
|
406
|
+
except BaseException:
|
|
407
|
+
if os.path.exists(tmp_name):
|
|
408
|
+
os.unlink(tmp_name)
|
|
409
|
+
raise
|
abkit/tuning/html.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Render the explore payload into one self-contained HTML page (WP6).
|
|
2
|
+
|
|
3
|
+
The same delivery model — and the same WP3-hardened template mechanics — as
|
|
4
|
+
``reporting/html_report.py``: one document, the committed ``assets/explore.js``
|
|
5
|
+
bundle inlined, the data baked as a JS literal. One-pass regex substitution
|
|
6
|
+
(never ``.format``, never sequential ``str.replace``), every ``<`` in the baked
|
|
7
|
+
JSON escaped as ``\\u003c``, no webfonts, no network (CLAUDE.md invariant 6).
|
|
8
|
+
|
|
9
|
+
The bundle assigns ``window.__ABK_EXPLORE__``; the page mounts it on
|
|
10
|
+
``#abk-explore``. The committed bundle is built from ``web/src/explore/`` by
|
|
11
|
+
``web/build.mjs`` (WP7 — until it lands, a minimal placeholder bundle renders
|
|
12
|
+
an honest pending note).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
from html import escape
|
|
19
|
+
from importlib.resources import files
|
|
20
|
+
|
|
21
|
+
from abkit.utils.json_utils import json_dumps_sorted
|
|
22
|
+
|
|
23
|
+
# The A/B split tile with the explore accent (data-URI, no network) — the one
|
|
24
|
+
# placeholder-brand token layer, swapped per branding-and-site.md.
|
|
25
|
+
_FAVICON = (
|
|
26
|
+
"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'"
|
|
27
|
+
"%3E%3Crect width='32' height='32' rx='7' fill='%232e7d5b'/%3E%3Crect x='17' y='6'"
|
|
28
|
+
" width='9' height='20' rx='2' fill='%23fcfcfb' opacity='0.55'/%3E%3Crect x='6' "
|
|
29
|
+
"y='12' width='9' height='14' rx='2' fill='%23fcfcfb'/%3E%3C/svg%3E"
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
_TEMPLATE = """<!doctype html>
|
|
33
|
+
<html lang="en">
|
|
34
|
+
<head>
|
|
35
|
+
<meta charset="utf-8" />
|
|
36
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
37
|
+
<title>abkit explore — __EXPERIMENT__</title>
|
|
38
|
+
<link rel="icon" href="__FAVICON__" />
|
|
39
|
+
<style>
|
|
40
|
+
/* Page shell only — the renderer injects its own scoped styles under the
|
|
41
|
+
abk-explore root. System fonts: zero network requests. */
|
|
42
|
+
html,body{margin:0;background:#f9f9f7;color:#0b0b0b;
|
|
43
|
+
font-family:system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;}
|
|
44
|
+
*{box-sizing:border-box;}
|
|
45
|
+
</style>
|
|
46
|
+
</head>
|
|
47
|
+
<body>
|
|
48
|
+
<div id="abk-explore"></div>
|
|
49
|
+
<script>window.__ABK_EXPLORE_PAYLOAD__ = __PAYLOAD__;</script>
|
|
50
|
+
<script>__EXPLORE_JS__</script>
|
|
51
|
+
<script>
|
|
52
|
+
(function(){
|
|
53
|
+
var mount = document.getElementById('abk-explore');
|
|
54
|
+
try { window.__ABK_EXPLORE__.render(window.__ABK_EXPLORE_PAYLOAD__, mount); }
|
|
55
|
+
catch (e) { mount.textContent = 'Failed to render explore: ' + e; }
|
|
56
|
+
})();
|
|
57
|
+
</script>
|
|
58
|
+
</body>
|
|
59
|
+
</html>
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _explore_js() -> str:
|
|
64
|
+
"""Read the committed explore renderer bundle shipped in the wheel."""
|
|
65
|
+
return (files("abkit.tuning") / "assets" / "explore.js").read_text(encoding="utf-8")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _bake_payload_json(payload: dict) -> str:
|
|
69
|
+
"""Canonical JSON with every ``<`` escaped (the WP3-hardened bake)."""
|
|
70
|
+
return json_dumps_sorted(payload).replace("<", "\\u003c")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
_PLACEHOLDER_RE = re.compile(r"__(EXPERIMENT|FAVICON|PAYLOAD|EXPLORE_JS)__")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def render_explore_html(payload: dict) -> str:
|
|
77
|
+
"""Build the self-contained explore HTML document for one payload.
|
|
78
|
+
|
|
79
|
+
Pure: no DB, no filesystem writes, no clock. The server bakes it once
|
|
80
|
+
post-bind; ``--no-serve`` writes it to ``reports/`` (WP8).
|
|
81
|
+
"""
|
|
82
|
+
values = {
|
|
83
|
+
"EXPERIMENT": escape(str(payload.get("experiment", "experiment"))),
|
|
84
|
+
"FAVICON": _FAVICON,
|
|
85
|
+
"PAYLOAD": _bake_payload_json(payload),
|
|
86
|
+
"EXPLORE_JS": _explore_js(),
|
|
87
|
+
}
|
|
88
|
+
return _PLACEHOLDER_RE.sub(lambda m: values[m.group(1)], _TEMPLATE)
|
abkit/tuning/payload.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""The explore payload: the WP2 experiment payload + explore extras (WP6, D6).
|
|
2
|
+
|
|
3
|
+
Thin by design (the donor's series/window logic is superseded by the WP2
|
|
4
|
+
builder + the WP4 engine): the report payload rides verbatim — the report
|
|
5
|
+
renderer ignores unknown keys, the explore client reads the ``explore`` block
|
|
6
|
+
— extended with the knob surfaces auto-derived from ``param_specs`` (D12),
|
|
7
|
+
the per-metric initial calibration state (D3), the session-cache facts, and
|
|
8
|
+
the endpoint slots a server injects post-bind (``None`` in the static
|
|
9
|
+
``--no-serve`` page — the client's preview-badge substrate, D3 gating).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
from typing import Any, get_args
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
from abkit.config.experiment_config import CorrectionKind
|
|
20
|
+
from abkit.tuning.recompute import RecomputeEngine, find_calibration, resolve_fpr_budget
|
|
21
|
+
from abkit.tuning.session import ExploreSession
|
|
22
|
+
from abkit.utils.datetime_utils import to_naive_utc
|
|
23
|
+
|
|
24
|
+
#: endpoint slots the server fills post-bind; null = static preview (D3)
|
|
25
|
+
ENDPOINT_SLOTS = ("save_url", "recompute_url", "reload_url", "validate_url")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _ms(value: datetime) -> int:
|
|
29
|
+
"""ms-epoch UTC — the §5.3 point-time unit (builder parity)."""
|
|
30
|
+
return int(np.datetime64(to_naive_utc(value), "ms").astype("int64"))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _jsonable_surface(surface: dict[str, Any]) -> dict[str, Any]:
|
|
34
|
+
"""The knob surface with its datetimes as ms-epoch ints (JSON-safe)."""
|
|
35
|
+
out = dict(surface)
|
|
36
|
+
cache = dict(out.get("cache") or {})
|
|
37
|
+
for key in ("cutoffs", "covariate_cutoffs"):
|
|
38
|
+
cache[key] = [_ms(ts) for ts in cache.get(key, [])]
|
|
39
|
+
out["cache"] = cache
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def build_explore_payload(
|
|
44
|
+
session: ExploreSession,
|
|
45
|
+
engine: RecomputeEngine,
|
|
46
|
+
report_payload: dict[str, Any],
|
|
47
|
+
) -> dict[str, Any]:
|
|
48
|
+
"""Wrap one experiment's report payload with the explore block.
|
|
49
|
+
|
|
50
|
+
Pure over the session (no DB): knob surfaces, the initial calibration chip
|
|
51
|
+
per metric — keyed by the CONFIGURED ``(method_config_id, alpha)``, D3;
|
|
52
|
+
every ``/recompute`` reply re-keys it live — and the cache facts. All keys
|
|
53
|
+
are present even for an empty-results experiment (the WP2 empty-state
|
|
54
|
+
contract extends here: the client renders an empty state, never crashes).
|
|
55
|
+
"""
|
|
56
|
+
metrics: dict[str, Any] = {}
|
|
57
|
+
for name, series in session.series_by_metric.items():
|
|
58
|
+
surface = _jsonable_surface(engine.knob_surface(name))
|
|
59
|
+
alpha = series.configured_alpha
|
|
60
|
+
calibration = find_calibration(
|
|
61
|
+
session.aa_rows,
|
|
62
|
+
name,
|
|
63
|
+
series.comparison.method.method_config_id,
|
|
64
|
+
alpha,
|
|
65
|
+
budget=resolve_fpr_budget(session.project, alpha, series.metric),
|
|
66
|
+
)
|
|
67
|
+
surface["calibration"] = {
|
|
68
|
+
"state": calibration.state,
|
|
69
|
+
"fpr": calibration.fpr,
|
|
70
|
+
"peeking_fpr": calibration.peeking_fpr,
|
|
71
|
+
"peeking_fpr_sequential": calibration.peeking_fpr_sequential,
|
|
72
|
+
"calibrated_alpha": calibration.calibrated_alpha,
|
|
73
|
+
"alpha": calibration.alpha,
|
|
74
|
+
"budget": calibration.budget,
|
|
75
|
+
"over_budget": calibration.over_budget,
|
|
76
|
+
"runs": calibration.runs,
|
|
77
|
+
"headline": calibration.headline,
|
|
78
|
+
}
|
|
79
|
+
metrics[name] = surface
|
|
80
|
+
|
|
81
|
+
default_metric = next(
|
|
82
|
+
(
|
|
83
|
+
name
|
|
84
|
+
for name, series in session.series_by_metric.items()
|
|
85
|
+
if series.comparison.is_main_metric
|
|
86
|
+
),
|
|
87
|
+
next(iter(session.series_by_metric), None),
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
# The experiment-level knob substrate (WP7): the client renders the raw
|
|
91
|
+
# alpha/correction knobs and mirrors analyze.effective_alphas to resolve
|
|
92
|
+
# them into the EFFECTIVE per-comparison alpha every /recompute sends
|
|
93
|
+
# (KnobState.alpha) — that mirror needs the resolved raw values and the
|
|
94
|
+
# two-tier counts, which the report payload does not carry.
|
|
95
|
+
experiment = session.experiment
|
|
96
|
+
project = session.project
|
|
97
|
+
payload = dict(report_payload)
|
|
98
|
+
payload["explore"] = {
|
|
99
|
+
"metrics": metrics,
|
|
100
|
+
"default_metric": default_metric,
|
|
101
|
+
"experiment": {
|
|
102
|
+
"alpha": (
|
|
103
|
+
experiment.alpha if experiment.alpha is not None else project.statistics.alpha
|
|
104
|
+
),
|
|
105
|
+
"correction": (
|
|
106
|
+
experiment.correction
|
|
107
|
+
if experiment.correction is not None
|
|
108
|
+
else project.statistics.correction
|
|
109
|
+
),
|
|
110
|
+
"correction_choices": list(get_args(CorrectionKind)),
|
|
111
|
+
"groups_count": len(experiment.assignment.variants),
|
|
112
|
+
"non_main_count": sum(1 for c in experiment.comparisons if not c.is_main_metric),
|
|
113
|
+
},
|
|
114
|
+
"cache": {
|
|
115
|
+
"values": session.cache_values,
|
|
116
|
+
"disabled_reason": session.cache_disabled_reason,
|
|
117
|
+
},
|
|
118
|
+
"warnings": list(session.warnings),
|
|
119
|
+
}
|
|
120
|
+
for slot in ENDPOINT_SLOTS:
|
|
121
|
+
payload.setdefault(slot, None)
|
|
122
|
+
return payload
|