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,1039 @@
|
|
|
1
|
+
"""The explore recompute engine — Tiers E/α/S/R over one session (D1).
|
|
2
|
+
|
|
3
|
+
One knob-change request is answered entirely from in-memory state
|
|
4
|
+
(m3-implementation-plan.md WP4; cli-and-dx §2 as amended by D1 — "no DB
|
|
5
|
+
round-trip" means no *warehouse* round-trip per knob change):
|
|
6
|
+
|
|
7
|
+
- **Tier E (exact, whole grid):** suffstats reconstructed from persisted
|
|
8
|
+
rows. t-test — ``SufficientStats(n=size_i, mean=value_i, m2=std_i²·size_i)``;
|
|
9
|
+
z-test — ``nobs`` inverted from the persisted SE (``nobs = p(1−p)/std_i²``),
|
|
10
|
+
NEVER taken from ``size_i`` (the one-row-per-unit count — the critique
|
|
11
|
+
blocker); ratio-delta — the exact surrogate ``RatioSufficientStats(n,
|
|
12
|
+
value_i, std_i²·n, mean_den=1, m2_den=0, c_nd=0)`` (``_arm_linearisation``
|
|
13
|
+
then reproduces ``R = value_i`` and ``var0_L = std_i²`` exactly).
|
|
14
|
+
- **Tier α (approx, whole grid):** alpha-inversion for closed-form rows —
|
|
15
|
+
every parametric CI here is ``effect ± z·se`` (``effects.normal_test``, the
|
|
16
|
+
z-test's explicit quantiles), so ``se = (right − left) / (2·z_{1−α/2})``
|
|
17
|
+
recovers the SE and the α-independent p-value passes through. Percentile
|
|
18
|
+
bootstrap CIs are NOT normal-invertible — resampling methods (declaratively:
|
|
19
|
+
a ``seed`` param spec) never take this path.
|
|
20
|
+
- **Tier S (exact, cached cutoffs):** ``from_samples`` over the session
|
|
21
|
+
cache — bootstrap knobs, the stratify toggle, CUPED with per-unit
|
|
22
|
+
covariates. Bootstrap seeds are re-derived per the persisted-row convention
|
|
23
|
+
(``derive_seed(exp, metric, name_1, name_2, end_ts, n_samples)``,
|
|
24
|
+
analyze-parity) so unchanged knobs reproduce stored rows byte-exactly under
|
|
25
|
+
the D11 canonical unit order.
|
|
26
|
+
- **Tier R (classified only):** CUPED off→on without a cached covariate and
|
|
27
|
+
``covariate_lookback`` changes need a new pre-period render — the knob
|
|
28
|
+
surface marks them ``R``; the serialized ``/reload`` action (WP6) executes
|
|
29
|
+
them, never a silent per-knob warehouse hit.
|
|
30
|
+
|
|
31
|
+
Identity is hashed ONLY through the bound probe (``MethodConfig`` →
|
|
32
|
+
``BaseMethod.method_config_id`` — one canonical path); the knob panel
|
|
33
|
+
metadata is auto-derived from ``param_specs`` (invariant 3 — nothing here
|
|
34
|
+
special-cases a method name); ``QuarantinedMethodError`` surfaces verbatim.
|
|
35
|
+
|
|
36
|
+
The calibration lookup (D3) lives here as :func:`find_calibration` — keyed by
|
|
37
|
+
``(metric, method_config_id, alpha)`` against the as-built ``_ab_aa_runs``
|
|
38
|
+
schema — one function ``abk validate`` (M4) reuses.
|
|
39
|
+
|
|
40
|
+
Thread discipline: everything in this module reads the immutable session —
|
|
41
|
+
no DB handles, safe under the WP6 request lock.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
from __future__ import annotations
|
|
45
|
+
|
|
46
|
+
import math
|
|
47
|
+
import warnings as _warnings
|
|
48
|
+
from collections.abc import Mapping
|
|
49
|
+
from dataclasses import dataclass, field, replace
|
|
50
|
+
from datetime import datetime
|
|
51
|
+
from typing import Any, Literal
|
|
52
|
+
|
|
53
|
+
import scipy.stats as sps
|
|
54
|
+
|
|
55
|
+
from abkit.config.method_config import MethodConfig
|
|
56
|
+
from abkit.config.metric_config import MetricConfig
|
|
57
|
+
from abkit.config.project_config import ProjectConfig
|
|
58
|
+
from abkit.core.interval import Interval
|
|
59
|
+
from abkit.loaders.metric_loader import MetricLoadResult
|
|
60
|
+
from abkit.pipeline.analyze import build_container
|
|
61
|
+
from abkit.stats import (
|
|
62
|
+
AbkitStatsWarning,
|
|
63
|
+
Fraction,
|
|
64
|
+
MethodParamError,
|
|
65
|
+
RatioSufficientStats,
|
|
66
|
+
SufficientStats,
|
|
67
|
+
TestResult,
|
|
68
|
+
available_methods,
|
|
69
|
+
create_method,
|
|
70
|
+
derive_seed,
|
|
71
|
+
get_method_class,
|
|
72
|
+
)
|
|
73
|
+
from abkit.stats.base import BaseMethod, ParamSpec
|
|
74
|
+
from abkit.stats.power import get_cuped_ttest_power, get_fraction_power, get_ttest_power
|
|
75
|
+
from abkit.stats.sequential import mixture_tau2, se_from_ci_length, to_always_valid
|
|
76
|
+
from abkit.tuning.session import ComparisonSeries, ExploreSession
|
|
77
|
+
from abkit.utils.json_utils import json_loads
|
|
78
|
+
|
|
79
|
+
Tier = Literal["exact", "approx", "baseline"]
|
|
80
|
+
|
|
81
|
+
#: knob → tier letters used by the side rail (WP7): E exact whole-grid,
|
|
82
|
+
#: S session-cache (cached cutoffs), R explicit reload.
|
|
83
|
+
KnobTier = Literal["E", "S", "R"]
|
|
84
|
+
|
|
85
|
+
_KIND_ROLES: dict[str, tuple[str, ...]] = {
|
|
86
|
+
"sample": ("value",),
|
|
87
|
+
"fraction": ("count", "nobs"),
|
|
88
|
+
"ratio": ("numerator", "denominator"),
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# ── declarative family probes (never method names — invariant 3) ────────────
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _needs_seed(method_cls: type[BaseMethod]) -> bool:
|
|
96
|
+
"""Resampling family: per-row derived seeds; percentile (non-normal) CIs."""
|
|
97
|
+
return any(spec.name == "seed" for spec in method_cls.param_specs)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _needs_covariate(method_cls: type[BaseMethod]) -> bool:
|
|
101
|
+
"""CUPED family: per-unit covariate dependence — cross-moments are not
|
|
102
|
+
persisted, so exact reconstruction from rows is impossible."""
|
|
103
|
+
return any(spec.name == "covariate_lookback" for spec in method_cls.param_specs)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def classify_knob(method_cls: type[BaseMethod], knob: str) -> KnobTier:
|
|
107
|
+
"""The D1 tier a change of ``knob`` recomputes through, per family."""
|
|
108
|
+
if knob == "covariate_lookback":
|
|
109
|
+
return "R" # a different lookback is a new pre-period render
|
|
110
|
+
if _needs_seed(method_cls) or _needs_covariate(method_cls):
|
|
111
|
+
return "S"
|
|
112
|
+
return "E"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def alpha_knob_tier(method_cls: type[BaseMethod]) -> str:
|
|
116
|
+
"""Tier for the experiment-level alpha knob under this family."""
|
|
117
|
+
if _needs_seed(method_cls):
|
|
118
|
+
return "S" # percentile CI: re-resample from the cache
|
|
119
|
+
if _needs_covariate(method_cls):
|
|
120
|
+
return "alpha" # α-inversion, whole grid (approx segments)
|
|
121
|
+
return "E"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _spec_payload(spec: ParamSpec) -> dict[str, Any]:
|
|
125
|
+
"""One ``ParamSpec`` as a JSON-safe knob descriptor (D12: the rail is
|
|
126
|
+
auto-derived from these — a knob that has no spec cannot appear)."""
|
|
127
|
+
return {
|
|
128
|
+
"name": spec.name,
|
|
129
|
+
"type": "|".join(t.__name__ for t in spec.types),
|
|
130
|
+
"default": spec.default,
|
|
131
|
+
"identity": spec.identity,
|
|
132
|
+
"choices": list(spec.choices) if spec.choices is not None else None,
|
|
133
|
+
"minimum": spec.minimum,
|
|
134
|
+
"maximum": spec.maximum,
|
|
135
|
+
"exclusive_bounds": spec.exclusive_bounds,
|
|
136
|
+
"description": spec.description,
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _lookback_seconds(value: str | int | None) -> int | None:
|
|
141
|
+
if value is None:
|
|
142
|
+
return None
|
|
143
|
+
try:
|
|
144
|
+
return Interval(value).seconds
|
|
145
|
+
except Exception:
|
|
146
|
+
return None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
# ── request / reply shapes ───────────────────────────────────────────────────
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@dataclass(frozen=True)
|
|
153
|
+
class KnobState:
|
|
154
|
+
"""One live knob combination: method + params + effective alpha.
|
|
155
|
+
|
|
156
|
+
``alpha`` is the effective per-comparison alpha (experiment-level knobs —
|
|
157
|
+
raw alpha and correction — resolve to it upstream, WP6); it never enters
|
|
158
|
+
``method_config_id``. A ``seed`` in ``params`` is ignored with a warning —
|
|
159
|
+
the engine always injects the deterministic per-row seed (analyze-parity;
|
|
160
|
+
identity-excluded).
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
method_name: str
|
|
164
|
+
params: Mapping[str, Any] = field(default_factory=dict)
|
|
165
|
+
alpha: float = 0.05
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@dataclass
|
|
169
|
+
class ExplorePoint:
|
|
170
|
+
"""One recomputed cutoff of one pair (§5.3 point semantics, full names —
|
|
171
|
+
WP6 maps to the terse payload keys)."""
|
|
172
|
+
|
|
173
|
+
end_ts: datetime
|
|
174
|
+
elapsed_days: float | None
|
|
175
|
+
tier: Tier
|
|
176
|
+
effect: float | None
|
|
177
|
+
left_bound: float | None
|
|
178
|
+
right_bound: float | None
|
|
179
|
+
pvalue: float | None
|
|
180
|
+
reject: bool | None
|
|
181
|
+
mde_1: float | None
|
|
182
|
+
mde_2: float | None
|
|
183
|
+
value_1: float | None
|
|
184
|
+
value_2: float | None
|
|
185
|
+
std_1: float | None
|
|
186
|
+
std_2: float | None
|
|
187
|
+
size_1: int | None
|
|
188
|
+
size_2: int | None
|
|
189
|
+
insufficient: bool = False
|
|
190
|
+
warnings: list[str] = field(default_factory=list)
|
|
191
|
+
result: TestResult | None = field(default=None, repr=False, compare=False)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@dataclass
|
|
195
|
+
class PairRecompute:
|
|
196
|
+
"""One (control, treatment) pair's recomputed series + windshield chips."""
|
|
197
|
+
|
|
198
|
+
name_1: str
|
|
199
|
+
name_2: str
|
|
200
|
+
points: list[ExplorePoint]
|
|
201
|
+
chips: dict[str, Any]
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@dataclass
|
|
205
|
+
class CalibrationStatus:
|
|
206
|
+
"""The D3 chip state for one (metric, method_config_id, alpha) key."""
|
|
207
|
+
|
|
208
|
+
state: Literal["uncalibrated", "calibrated", "alpha_mismatch"]
|
|
209
|
+
alpha: float
|
|
210
|
+
fpr: float | None = None
|
|
211
|
+
peeking_fpr: float | None = None
|
|
212
|
+
#: M5 D8 — the always-valid peeking FPR beside the fixed one (the recovery to ~α).
|
|
213
|
+
peeking_fpr_sequential: float | None = None
|
|
214
|
+
calibrated_alpha: float | None = None
|
|
215
|
+
budget: float | None = None
|
|
216
|
+
over_budget: bool | None = None
|
|
217
|
+
runs: int = 0
|
|
218
|
+
headline: str = ""
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@dataclass
|
|
222
|
+
class RecomputeResult:
|
|
223
|
+
"""One knob state answered: per-pair series, live identity, calibration."""
|
|
224
|
+
|
|
225
|
+
metric: str
|
|
226
|
+
method_name: str
|
|
227
|
+
method_config_id: str
|
|
228
|
+
alpha: float
|
|
229
|
+
identity_changed: bool
|
|
230
|
+
pairs: list[PairRecompute]
|
|
231
|
+
calibration: CalibrationStatus
|
|
232
|
+
warnings: list[str] = field(default_factory=list)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# ── calibration (D3) ─────────────────────────────────────────────────────────
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def resolve_fpr_budget(
|
|
239
|
+
project: ProjectConfig, alpha: float, metric: MetricConfig | None = None
|
|
240
|
+
) -> float:
|
|
241
|
+
"""metric ``aa_fpr_budget`` → project ``aa_fpr_budget`` → ``α × 1.5``
|
|
242
|
+
(aa-false-positive-matrix.md §4.1; D12). One resolver, never a hardcode."""
|
|
243
|
+
if metric is not None and metric.aa_fpr_budget is not None:
|
|
244
|
+
return float(metric.aa_fpr_budget)
|
|
245
|
+
budget = project.statistics.aa_fpr_budget
|
|
246
|
+
return float(budget) if budget is not None else alpha * 1.5
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def find_calibration(
|
|
250
|
+
aa_rows: list[dict],
|
|
251
|
+
metric: str,
|
|
252
|
+
method_config_id: str,
|
|
253
|
+
alpha: float,
|
|
254
|
+
budget: float | None = None,
|
|
255
|
+
) -> CalibrationStatus:
|
|
256
|
+
"""The chip lookup, keyed by ``(metric, method_config_id, alpha)`` (D3).
|
|
257
|
+
|
|
258
|
+
Alpha is in the key: it is identity-excluded from ``method_config_id``,
|
|
259
|
+
but empirical FPR is measured at a specific nominal α — an alpha edit
|
|
260
|
+
downgrades the chip to ``alpha_mismatch`` and gates like uncalibrated.
|
|
261
|
+
``status='failed'`` rows and rows without an ``fpr`` never count. Any
|
|
262
|
+
identity or alpha edit flips the chip automatically — that IS the
|
|
263
|
+
staleness semantics (no separate "stale" state).
|
|
264
|
+
"""
|
|
265
|
+
matches = [
|
|
266
|
+
row
|
|
267
|
+
for row in aa_rows
|
|
268
|
+
if row.get("metric") == metric
|
|
269
|
+
and row.get("method_config_id") == method_config_id
|
|
270
|
+
and row.get("status") == "success"
|
|
271
|
+
and row.get("fpr") is not None
|
|
272
|
+
]
|
|
273
|
+
matches.sort(
|
|
274
|
+
key=lambda row: (row.get("created_at") is not None, row.get("created_at")), reverse=True
|
|
275
|
+
)
|
|
276
|
+
if not matches:
|
|
277
|
+
return CalibrationStatus(
|
|
278
|
+
state="uncalibrated",
|
|
279
|
+
alpha=alpha,
|
|
280
|
+
budget=budget,
|
|
281
|
+
headline="uncalibrated — run `abk validate` (M4)",
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
same_alpha = [
|
|
285
|
+
row
|
|
286
|
+
for row in matches
|
|
287
|
+
if math.isclose(float(row["alpha"]), alpha, rel_tol=1e-9, abs_tol=1e-12)
|
|
288
|
+
]
|
|
289
|
+
if not same_alpha:
|
|
290
|
+
calibrated_alpha = float(matches[0]["alpha"])
|
|
291
|
+
return CalibrationStatus(
|
|
292
|
+
state="alpha_mismatch",
|
|
293
|
+
alpha=alpha,
|
|
294
|
+
calibrated_alpha=calibrated_alpha,
|
|
295
|
+
budget=budget,
|
|
296
|
+
runs=len(matches),
|
|
297
|
+
headline=(
|
|
298
|
+
f"calibrated at α={calibrated_alpha:g}, current α={alpha:g} — "
|
|
299
|
+
"re-run `abk validate` for this alpha"
|
|
300
|
+
),
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
newest = same_alpha[0]
|
|
304
|
+
fpr = float(newest["fpr"])
|
|
305
|
+
peeking = newest.get("peeking_fpr")
|
|
306
|
+
peeking_seq = newest.get("peeking_fpr_sequential")
|
|
307
|
+
over = None if budget is None else fpr > budget
|
|
308
|
+
headline = f"calibrated — FPR {fpr:.1%} vs nominal α={alpha:g}"
|
|
309
|
+
if over:
|
|
310
|
+
headline += f" (over the {budget:.1%} budget)"
|
|
311
|
+
# M5 D8: surface the always-valid recovery when peeking inflates past budget.
|
|
312
|
+
if peeking is not None and peeking_seq is not None:
|
|
313
|
+
headline += f"; peeking {float(peeking):.1%}→{float(peeking_seq):.1%} (always-valid)"
|
|
314
|
+
return CalibrationStatus(
|
|
315
|
+
state="calibrated",
|
|
316
|
+
alpha=alpha,
|
|
317
|
+
fpr=fpr,
|
|
318
|
+
peeking_fpr=None if peeking is None else float(peeking),
|
|
319
|
+
peeking_fpr_sequential=None if peeking_seq is None else float(peeking_seq),
|
|
320
|
+
budget=budget,
|
|
321
|
+
over_budget=over,
|
|
322
|
+
runs=len(same_alpha),
|
|
323
|
+
headline=headline,
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
# ── row-level reconstruction helpers ─────────────────────────────────────────
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _row_float(row: dict, key: str) -> float | None:
|
|
331
|
+
value = row.get(key)
|
|
332
|
+
if value is None:
|
|
333
|
+
return None
|
|
334
|
+
value = float(value)
|
|
335
|
+
return value if math.isfinite(value) else None
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _row_int(row: dict, key: str) -> int | None:
|
|
339
|
+
value = row.get(key)
|
|
340
|
+
return None if value is None else int(value)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _invert_fraction(prop: float, std: float, name: str | None) -> Fraction | None:
|
|
344
|
+
"""The z-test inversion: ``nobs = p(1−p)/std²`` from the persisted SE.
|
|
345
|
+
|
|
346
|
+
Degenerate rows (``p ∈ {0, 1}`` ⇒ ``std = 0``) are not invertible —
|
|
347
|
+
they route to Tier S / pass-through.
|
|
348
|
+
"""
|
|
349
|
+
if not (0.0 < prop < 1.0) or not (math.isfinite(std) and std > 0.0):
|
|
350
|
+
return None
|
|
351
|
+
nobs = prop * (1.0 - prop) / (std * std)
|
|
352
|
+
if not math.isfinite(nobs) or nobs <= 0.0:
|
|
353
|
+
return None
|
|
354
|
+
return Fraction(count=prop * nobs, nobs=nobs, name=name)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _parse_params(value: Any) -> dict[str, Any]:
|
|
358
|
+
"""The row's canonical ``method_params`` JSON cell as a dict; never raises."""
|
|
359
|
+
if isinstance(value, dict):
|
|
360
|
+
return value
|
|
361
|
+
if not value:
|
|
362
|
+
return {}
|
|
363
|
+
try:
|
|
364
|
+
parsed = json_loads(value)
|
|
365
|
+
except (TypeError, ValueError):
|
|
366
|
+
return {}
|
|
367
|
+
return parsed if isinstance(parsed, dict) else {}
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _row_serves_suffstats(row: dict) -> bool:
|
|
371
|
+
"""Whether this row's per-arm columns carry MEAN/std semantics.
|
|
372
|
+
|
|
373
|
+
Rows written by a resampling method with a non-mean ``stat`` persist the
|
|
374
|
+
bootstrapped statistic (e.g. the median) in ``value_i`` — reconstructing
|
|
375
|
+
mean-based suffstats from them would be silently wrong, never "exact".
|
|
376
|
+
Unknown/quarantined legacy row methods are never reconstructed.
|
|
377
|
+
"""
|
|
378
|
+
method_name = row.get("method_name")
|
|
379
|
+
if not method_name:
|
|
380
|
+
return False
|
|
381
|
+
try:
|
|
382
|
+
row_cls = get_method_class(method_name)
|
|
383
|
+
except Exception:
|
|
384
|
+
return False
|
|
385
|
+
if any(spec.name == "stat" for spec in row_cls.param_specs):
|
|
386
|
+
if _parse_params(row.get("method_params")).get("stat", "mean") != "mean":
|
|
387
|
+
return False
|
|
388
|
+
return True
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _exact_suffstats(method_cls: type[BaseMethod], row: dict) -> tuple[Any, Any] | None:
|
|
392
|
+
"""Tier E: both arms' suffstats containers from one persisted row, or
|
|
393
|
+
``None`` when this family/row is not exactly reconstructable."""
|
|
394
|
+
if _needs_seed(method_cls) or method_cls.requires_covariate or _needs_covariate(method_cls):
|
|
395
|
+
return None
|
|
396
|
+
if not _row_serves_suffstats(row):
|
|
397
|
+
return None
|
|
398
|
+
value_1, value_2 = _row_float(row, "value_1"), _row_float(row, "value_2")
|
|
399
|
+
std_1, std_2 = _row_float(row, "std_1"), _row_float(row, "std_2")
|
|
400
|
+
size_1, size_2 = _row_int(row, "size_1"), _row_int(row, "size_2")
|
|
401
|
+
if None in (value_1, value_2, std_1, std_2, size_1, size_2):
|
|
402
|
+
return None
|
|
403
|
+
if size_1 <= 0 or size_2 <= 0:
|
|
404
|
+
return None
|
|
405
|
+
name_1, name_2 = row.get("name_1"), row.get("name_2")
|
|
406
|
+
|
|
407
|
+
kind = method_cls.input_kind
|
|
408
|
+
if kind == "sample":
|
|
409
|
+
# std_i is the persisted np.std (ddof=0) ⇒ m2 = std² · n exactly.
|
|
410
|
+
return (
|
|
411
|
+
SufficientStats(n=size_1, mean=value_1, m2=std_1 * std_1 * size_1, name=name_1),
|
|
412
|
+
SufficientStats(n=size_2, mean=value_2, m2=std_2 * std_2 * size_2, name=name_2),
|
|
413
|
+
)
|
|
414
|
+
if kind == "fraction":
|
|
415
|
+
fraction_1 = _invert_fraction(value_1, std_1, name_1)
|
|
416
|
+
fraction_2 = _invert_fraction(value_2, std_2, name_2)
|
|
417
|
+
if fraction_1 is None or fraction_2 is None:
|
|
418
|
+
return None
|
|
419
|
+
return (fraction_1, fraction_2)
|
|
420
|
+
if kind == "ratio":
|
|
421
|
+
# std_i is the per-unit linearised std ⇒ the den≡1 surrogate is exact:
|
|
422
|
+
# _arm_linearisation gives R = value_i and var0_L = std_i² back.
|
|
423
|
+
return (
|
|
424
|
+
RatioSufficientStats(
|
|
425
|
+
n=size_1,
|
|
426
|
+
mean_num=value_1,
|
|
427
|
+
m2_num=std_1 * std_1 * size_1,
|
|
428
|
+
mean_den=1.0,
|
|
429
|
+
m2_den=0.0,
|
|
430
|
+
c_nd=0.0,
|
|
431
|
+
name=name_1,
|
|
432
|
+
),
|
|
433
|
+
RatioSufficientStats(
|
|
434
|
+
n=size_2,
|
|
435
|
+
mean_num=value_2,
|
|
436
|
+
m2_num=std_2 * std_2 * size_2,
|
|
437
|
+
mean_den=1.0,
|
|
438
|
+
m2_den=0.0,
|
|
439
|
+
c_nd=0.0,
|
|
440
|
+
name=name_2,
|
|
441
|
+
),
|
|
442
|
+
)
|
|
443
|
+
return None
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _alpha_inverted_bounds(row: dict, new_alpha: float) -> tuple[float, float, float, bool] | None:
|
|
447
|
+
"""Tier α: ``(left, right, pvalue, reject)`` at ``new_alpha`` from a
|
|
448
|
+
closed-form row's symmetric normal CI; ``None`` when not invertible."""
|
|
449
|
+
effect = _row_float(row, "effect")
|
|
450
|
+
left = _row_float(row, "left_bound")
|
|
451
|
+
right = _row_float(row, "right_bound")
|
|
452
|
+
pvalue = _row_float(row, "pvalue")
|
|
453
|
+
row_alpha = _row_float(row, "alpha")
|
|
454
|
+
if None in (effect, left, right, pvalue, row_alpha):
|
|
455
|
+
return None
|
|
456
|
+
if not 0.0 < row_alpha < 1.0 or right < left:
|
|
457
|
+
return None
|
|
458
|
+
z_old = float(sps.norm.ppf(1.0 - row_alpha / 2.0))
|
|
459
|
+
if not math.isfinite(z_old) or z_old <= 0.0:
|
|
460
|
+
return None
|
|
461
|
+
se = (right - left) / (2.0 * z_old)
|
|
462
|
+
z_new = float(sps.norm.ppf(1.0 - new_alpha / 2.0))
|
|
463
|
+
return (
|
|
464
|
+
effect - z_new * se,
|
|
465
|
+
effect + z_new * se,
|
|
466
|
+
pvalue,
|
|
467
|
+
bool(pvalue < new_alpha),
|
|
468
|
+
)
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _clean(value: float | None) -> float | None:
|
|
472
|
+
if value is None:
|
|
473
|
+
return None
|
|
474
|
+
value = float(value)
|
|
475
|
+
return value if math.isfinite(value) else None
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
# ── the engine ───────────────────────────────────────────────────────────────
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
class RecomputeEngine:
|
|
482
|
+
"""Answers knob states from one immutable :class:`ExploreSession`."""
|
|
483
|
+
|
|
484
|
+
def __init__(self, session: ExploreSession) -> None:
|
|
485
|
+
self._session = session
|
|
486
|
+
|
|
487
|
+
# -- knob metadata --------------------------------------------------------
|
|
488
|
+
|
|
489
|
+
def default_knobs(self, metric: str) -> KnobState:
|
|
490
|
+
"""The configured baseline knob state for ``metric``."""
|
|
491
|
+
series = self._session.series(metric)
|
|
492
|
+
return KnobState(
|
|
493
|
+
method_name=series.comparison.method.name,
|
|
494
|
+
params=dict(series.comparison.method.params),
|
|
495
|
+
alpha=series.configured_alpha,
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
def knob_surface(self, metric: str) -> dict[str, Any]:
|
|
499
|
+
"""The side-rail metadata block (D12): methods valid for this metric
|
|
500
|
+
type, their ``param_specs`` verbatim, and the per-knob tier map."""
|
|
501
|
+
series = self._session.series(metric)
|
|
502
|
+
methods: list[dict[str, Any]] = []
|
|
503
|
+
for name in available_methods():
|
|
504
|
+
method_cls = get_method_class(name)
|
|
505
|
+
if method_cls.input_kind != series.metric.type or method_cls.is_paired:
|
|
506
|
+
continue
|
|
507
|
+
methods.append(
|
|
508
|
+
{
|
|
509
|
+
"name": name,
|
|
510
|
+
"seeded": _needs_seed(method_cls),
|
|
511
|
+
# the ↻ badge substrate: WP7 marks the method Tier R when
|
|
512
|
+
# this is true and the cache holds no covariate cutoffs
|
|
513
|
+
"needs_covariate": method_cls.requires_covariate,
|
|
514
|
+
"alpha_tier": alpha_knob_tier(method_cls),
|
|
515
|
+
# correction resolves to the effective per-comparison alpha
|
|
516
|
+
# upstream (analyze.effective_alphas), so it recomputes
|
|
517
|
+
# through the same tier the alpha knob does (WP4 DoD)
|
|
518
|
+
"correction_tier": alpha_knob_tier(method_cls),
|
|
519
|
+
"params": [_spec_payload(spec) for spec in method_cls.param_specs],
|
|
520
|
+
"tiers": {
|
|
521
|
+
spec.name: classify_knob(method_cls, spec.name)
|
|
522
|
+
for spec in method_cls.param_specs
|
|
523
|
+
},
|
|
524
|
+
}
|
|
525
|
+
)
|
|
526
|
+
cached = self._session.cached_cutoffs(metric)
|
|
527
|
+
covariate_cutoffs = []
|
|
528
|
+
for ts in cached:
|
|
529
|
+
loaded = self._session.loaded(metric, ts)
|
|
530
|
+
if loaded is not None and loaded.roles_by_variant:
|
|
531
|
+
if all("covariate" in roles for roles in loaded.roles_by_variant.values()):
|
|
532
|
+
covariate_cutoffs.append(ts)
|
|
533
|
+
return {
|
|
534
|
+
"metric": metric,
|
|
535
|
+
"metric_type": series.metric.type,
|
|
536
|
+
"configured": {
|
|
537
|
+
"method": series.comparison.method.name,
|
|
538
|
+
"params": dict(series.comparison.method.params),
|
|
539
|
+
"method_config_id": series.comparison.method.method_config_id,
|
|
540
|
+
"alpha": series.configured_alpha,
|
|
541
|
+
},
|
|
542
|
+
"methods": methods,
|
|
543
|
+
"cache": {
|
|
544
|
+
"cutoffs": cached,
|
|
545
|
+
"covariate_cutoffs": covariate_cutoffs,
|
|
546
|
+
"disabled_reason": self._session.cache_disabled_reason,
|
|
547
|
+
},
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
# -- recompute ------------------------------------------------------------
|
|
551
|
+
|
|
552
|
+
def recompute(self, metric: str, knobs: KnobState) -> RecomputeResult:
|
|
553
|
+
"""One knob state → per-pair series + chips + identity + calibration.
|
|
554
|
+
|
|
555
|
+
Raises the stats-core exceptions verbatim (``UnknownMethodError``,
|
|
556
|
+
``QuarantinedMethodError``, ``MethodParamError``) — WP6 maps them to
|
|
557
|
+
HTTP 400s; they are never swallowed or substituted.
|
|
558
|
+
"""
|
|
559
|
+
session = self._session
|
|
560
|
+
series = session.series(metric)
|
|
561
|
+
engine_warnings: list[str] = []
|
|
562
|
+
|
|
563
|
+
if not 0.0 < knobs.alpha < 1.0:
|
|
564
|
+
raise MethodParamError(f"alpha must be in (0, 1), got {knobs.alpha}")
|
|
565
|
+
|
|
566
|
+
params = dict(knobs.params)
|
|
567
|
+
if "seed" in params:
|
|
568
|
+
params.pop("seed")
|
|
569
|
+
engine_warnings.append(
|
|
570
|
+
"seed is derived per row (identity-excluded) — the supplied value is ignored"
|
|
571
|
+
)
|
|
572
|
+
|
|
573
|
+
# ONE canonical identity/validation path: config model → bound probe.
|
|
574
|
+
method_config = MethodConfig(name=knobs.method_name, params=params)
|
|
575
|
+
probe = method_config.bind(alpha=knobs.alpha)
|
|
576
|
+
method_cls = type(probe)
|
|
577
|
+
|
|
578
|
+
# The analyze_cutoff-parity gate (analyze.py): without it a cross-kind
|
|
579
|
+
# knob state would reconstruct nonsense suffstats (a fraction row's
|
|
580
|
+
# std_i is the SE, not a sample std) and label it tier="exact".
|
|
581
|
+
if method_cls.is_paired:
|
|
582
|
+
raise MethodParamError(
|
|
583
|
+
f"method '{knobs.method_name}' is a paired design — explore serves "
|
|
584
|
+
"independent-arm experiments (use the notebook API for paired data)"
|
|
585
|
+
)
|
|
586
|
+
if method_cls.input_kind != series.metric.type:
|
|
587
|
+
raise MethodParamError(
|
|
588
|
+
f"method '{knobs.method_name}' expects a '{method_cls.input_kind}' "
|
|
589
|
+
f"metric, got '{series.metric.type}' — pick a method from the knob "
|
|
590
|
+
"surface's method list"
|
|
591
|
+
)
|
|
592
|
+
|
|
593
|
+
live_id = probe.method_config_id
|
|
594
|
+
identity_changed = live_id != series.comparison.method.method_config_id
|
|
595
|
+
|
|
596
|
+
reusable = None if _needs_seed(method_cls) else probe
|
|
597
|
+
|
|
598
|
+
pair_rows: dict[tuple[str, str], list[dict]] = {}
|
|
599
|
+
for row in series.rows:
|
|
600
|
+
pair_rows.setdefault((row["name_1"], row["name_2"]), []).append(row)
|
|
601
|
+
|
|
602
|
+
# M5 WP3c: the cockpit is a READ-VIEW over persisted rows (D2), so it must
|
|
603
|
+
# never mix CI vocabularies within a pair's series. A pair is widened into
|
|
604
|
+
# the always-valid CI live iff its BAKED rows are already always_valid —
|
|
605
|
+
# NOT off config.sequential (which only governs the next `abk run`). This
|
|
606
|
+
# reproduces the baked per-pair vocabulary exactly: the multi-pair case
|
|
607
|
+
# where the driver's first-usable-look anchor left a late-usable pair fixed,
|
|
608
|
+
# and a config toggle not yet applied by a re-run (either direction). Gated
|
|
609
|
+
# on the LIVE method's declarative supports_sequential — a knob switch to a
|
|
610
|
+
# percentile-CI method (bootstrap) can never be widened.
|
|
611
|
+
av_pairs: set[tuple[str, str]] = set()
|
|
612
|
+
if method_cls.supports_sequential:
|
|
613
|
+
for pair, rows in pair_rows.items():
|
|
614
|
+
if any(
|
|
615
|
+
r.get("ci_kind") == "always_valid" and not r.get("insufficient_data")
|
|
616
|
+
for r in rows
|
|
617
|
+
):
|
|
618
|
+
av_pairs.add(pair)
|
|
619
|
+
|
|
620
|
+
seq_reload_needed = False
|
|
621
|
+
pairs: list[PairRecompute] = []
|
|
622
|
+
for (name_1, name_2), rows in pair_rows.items():
|
|
623
|
+
points: list[ExplorePoint] = []
|
|
624
|
+
for row in rows:
|
|
625
|
+
point = self._compute_point(
|
|
626
|
+
series, row, method_cls, probe.params, knobs, reusable, identity_changed
|
|
627
|
+
)
|
|
628
|
+
if point is not None:
|
|
629
|
+
points.append(point)
|
|
630
|
+
if (name_1, name_2) in av_pairs:
|
|
631
|
+
points, dropped = self._sequentialize_points(points, knobs.alpha)
|
|
632
|
+
seq_reload_needed = seq_reload_needed or dropped
|
|
633
|
+
chips = self._chips(series, points, method_cls, probe.params, knobs, name_1)
|
|
634
|
+
pairs.append(PairRecompute(name_1=name_1, name_2=name_2, points=points, chips=chips))
|
|
635
|
+
|
|
636
|
+
if seq_reload_needed:
|
|
637
|
+
engine_warnings.append(
|
|
638
|
+
"alpha recompute is unavailable for some cutoffs under the sequential "
|
|
639
|
+
"mode (their always-valid CI cannot be re-derived by α-inversion) — "
|
|
640
|
+
"use Reload to recompute them"
|
|
641
|
+
)
|
|
642
|
+
|
|
643
|
+
calibration = find_calibration(
|
|
644
|
+
session.aa_rows,
|
|
645
|
+
metric,
|
|
646
|
+
live_id,
|
|
647
|
+
knobs.alpha,
|
|
648
|
+
budget=resolve_fpr_budget(session.project, knobs.alpha, series.metric),
|
|
649
|
+
)
|
|
650
|
+
if session.cache_disabled_reason is not None:
|
|
651
|
+
engine_warnings.append(session.cache_disabled_reason)
|
|
652
|
+
|
|
653
|
+
return RecomputeResult(
|
|
654
|
+
metric=metric,
|
|
655
|
+
method_name=method_cls.name,
|
|
656
|
+
method_config_id=live_id,
|
|
657
|
+
alpha=knobs.alpha,
|
|
658
|
+
identity_changed=identity_changed,
|
|
659
|
+
pairs=pairs,
|
|
660
|
+
calibration=calibration,
|
|
661
|
+
warnings=engine_warnings,
|
|
662
|
+
)
|
|
663
|
+
|
|
664
|
+
# -- internals -------------------------------------------------------------
|
|
665
|
+
|
|
666
|
+
def _compute_point(
|
|
667
|
+
self,
|
|
668
|
+
series: ComparisonSeries,
|
|
669
|
+
row: dict,
|
|
670
|
+
method_cls: type[BaseMethod],
|
|
671
|
+
resolved_params: dict[str, Any],
|
|
672
|
+
knobs: KnobState,
|
|
673
|
+
reusable: BaseMethod | None,
|
|
674
|
+
identity_changed: bool,
|
|
675
|
+
) -> ExplorePoint | None:
|
|
676
|
+
"""One row → the best-tier point, or ``None`` (a baseline-only gap)."""
|
|
677
|
+
if row.get("insufficient_data"):
|
|
678
|
+
# Demoted rows pass through UNTOUCHED (WP4: NULL test columns,
|
|
679
|
+
# real sizes) — the client greys them; they are method-independent
|
|
680
|
+
# facts, so they ride along under every knob state.
|
|
681
|
+
return self._baseline_point(row)
|
|
682
|
+
|
|
683
|
+
# Tier E — exact reconstruction, whole grid.
|
|
684
|
+
containers = _exact_suffstats(method_cls, row)
|
|
685
|
+
if containers is not None and reusable is not None:
|
|
686
|
+
result, caught = _compare(reusable, *containers)
|
|
687
|
+
return self._point_from_result(row, result, caught, tier="exact")
|
|
688
|
+
|
|
689
|
+
# Tier S — the session cache (from_samples), cached cutoffs only.
|
|
690
|
+
loaded = self._session.loaded(series.metric.name, row["end_ts"])
|
|
691
|
+
entry_lookback = self._session.cache_lookback.get((series.metric.name, row["end_ts"]))
|
|
692
|
+
if loaded is not None and self._cache_serves(
|
|
693
|
+
series,
|
|
694
|
+
method_cls,
|
|
695
|
+
resolved_params,
|
|
696
|
+
loaded,
|
|
697
|
+
row["name_1"],
|
|
698
|
+
row["name_2"],
|
|
699
|
+
entry_lookback,
|
|
700
|
+
):
|
|
701
|
+
group_1 = build_container(method_cls.input_kind, row["name_1"], loaded)
|
|
702
|
+
group_2 = build_container(method_cls.input_kind, row["name_2"], loaded)
|
|
703
|
+
if reusable is not None:
|
|
704
|
+
method = reusable
|
|
705
|
+
else:
|
|
706
|
+
seeded_params = dict(knobs.params)
|
|
707
|
+
seeded_params.pop("seed", None)
|
|
708
|
+
seeded_params["seed"] = derive_seed(
|
|
709
|
+
self._session.experiment.name,
|
|
710
|
+
series.metric.name,
|
|
711
|
+
row["name_1"],
|
|
712
|
+
row["name_2"],
|
|
713
|
+
row["end_ts"],
|
|
714
|
+
seeded_params.get("n_samples", 1000),
|
|
715
|
+
)
|
|
716
|
+
method = create_method(knobs.method_name, alpha=knobs.alpha, params=seeded_params)
|
|
717
|
+
result, caught = _compare(method, group_1, group_2)
|
|
718
|
+
return self._point_from_result(row, result, caught, tier="exact")
|
|
719
|
+
|
|
720
|
+
if identity_changed:
|
|
721
|
+
return None # a different series with no way to compute it here
|
|
722
|
+
|
|
723
|
+
# Same identity: pass persisted numbers through, or α-invert them.
|
|
724
|
+
if math.isclose(knobs.alpha, _row_float(row, "alpha") or -1.0, rel_tol=1e-12):
|
|
725
|
+
return self._baseline_point(row)
|
|
726
|
+
if not _needs_seed(method_cls):
|
|
727
|
+
inverted = _alpha_inverted_bounds(row, knobs.alpha)
|
|
728
|
+
if inverted is not None:
|
|
729
|
+
left, right, pvalue, reject = inverted
|
|
730
|
+
return ExplorePoint(
|
|
731
|
+
end_ts=row["end_ts"],
|
|
732
|
+
elapsed_days=_row_float(row, "elapsed_days"),
|
|
733
|
+
tier="approx",
|
|
734
|
+
effect=_row_float(row, "effect"),
|
|
735
|
+
left_bound=_clean(left),
|
|
736
|
+
right_bound=_clean(right),
|
|
737
|
+
pvalue=_clean(pvalue),
|
|
738
|
+
reject=reject,
|
|
739
|
+
mde_1=None, # the stored MDE was solved at the old alpha
|
|
740
|
+
mde_2=None,
|
|
741
|
+
value_1=_row_float(row, "value_1"),
|
|
742
|
+
value_2=_row_float(row, "value_2"),
|
|
743
|
+
std_1=_row_float(row, "std_1"),
|
|
744
|
+
std_2=_row_float(row, "std_2"),
|
|
745
|
+
size_1=_row_int(row, "size_1"),
|
|
746
|
+
size_2=_row_int(row, "size_2"),
|
|
747
|
+
)
|
|
748
|
+
if _row_float(row, "effect") is None:
|
|
749
|
+
# NULLed rows (H5 NaN outputs) pass through untouched under any
|
|
750
|
+
# same-identity knob state — there is no number to mislabel.
|
|
751
|
+
return self._baseline_point(row)
|
|
752
|
+
return None
|
|
753
|
+
|
|
754
|
+
def _sequentialize_points(
|
|
755
|
+
self, points: list[ExplorePoint], alpha: float
|
|
756
|
+
) -> tuple[list[ExplorePoint], bool]:
|
|
757
|
+
"""Widen ONE always-valid pair's reconstructed points into the CS (M5 WP3c).
|
|
758
|
+
|
|
759
|
+
Called only for pairs the baked series persisted as ``always_valid`` (the
|
|
760
|
+
caller's ``av_pairs`` gate). Freeze τ² from the first look with a usable fixed
|
|
761
|
+
CI — mirroring ``driver._sequential_tau2``'s D-Seq-anchor via the SAME
|
|
762
|
+
``se_from_ci_length``/``mixture_tau2`` helpers — then widen every reconstructed
|
|
763
|
+
(Tier E/S) point with ``to_always_valid``. For fully Tier-E-reconstructable
|
|
764
|
+
families (t/z/ratio) the recovered fixed CI equals the pipeline's pre-widening
|
|
765
|
+
CI, so the configured knob state reproduces the baked always-valid bounds. (A
|
|
766
|
+
partially-cached CUPED default may anchor τ² a look later than the pipeline —
|
|
767
|
+
its uncached first look has no ``result`` to invert — still a valid confidence
|
|
768
|
+
sequence, never a vocabulary mix.)
|
|
769
|
+
|
|
770
|
+
- **Tier E/S** points carry the raw fixed ``result`` → widened.
|
|
771
|
+
- **Baseline** points are persisted pass-throughs already carrying the mode's
|
|
772
|
+
bounds (this pair is always_valid) → left untouched.
|
|
773
|
+
- **α-inverted** (``tier='approx'``) points recovered their SE from an
|
|
774
|
+
already-widened persisted CI, so they cannot be honestly widened → dropped
|
|
775
|
+
(returns ``dropped=True`` so the caller surfaces a Reload hint), never shown
|
|
776
|
+
as a silent fixed CI on a sequential chart.
|
|
777
|
+
|
|
778
|
+
Returns ``(points, dropped_any_approx)``. When no look has a usable fixed CI
|
|
779
|
+
(τ² undefined — e.g. an all-baseline CUPED pair) the points are passed through:
|
|
780
|
+
baseline points already carry the persisted always-valid bounds.
|
|
781
|
+
"""
|
|
782
|
+
tau2: float | None = None
|
|
783
|
+
for point in points:
|
|
784
|
+
if point.result is None:
|
|
785
|
+
continue
|
|
786
|
+
se = se_from_ci_length(point.result.ci_length, alpha)
|
|
787
|
+
if math.isfinite(se) and se > 0.0:
|
|
788
|
+
tau2 = mixture_tau2(se * se, alpha)
|
|
789
|
+
break
|
|
790
|
+
|
|
791
|
+
out: list[ExplorePoint] = []
|
|
792
|
+
dropped = False
|
|
793
|
+
for point in points:
|
|
794
|
+
if point.result is not None:
|
|
795
|
+
if tau2 is None:
|
|
796
|
+
out.append(point) # degenerate everywhere; nothing to widen
|
|
797
|
+
continue
|
|
798
|
+
av = to_always_valid(point.result, tau2, alpha)
|
|
799
|
+
out.append(
|
|
800
|
+
replace(
|
|
801
|
+
point,
|
|
802
|
+
left_bound=_clean(av.left_bound),
|
|
803
|
+
right_bound=_clean(av.right_bound),
|
|
804
|
+
pvalue=_clean(av.pvalue),
|
|
805
|
+
reject=bool(av.reject),
|
|
806
|
+
result=av,
|
|
807
|
+
)
|
|
808
|
+
)
|
|
809
|
+
elif point.tier == "approx":
|
|
810
|
+
dropped = True # α-inversion is not valid vocabulary under sequential
|
|
811
|
+
else:
|
|
812
|
+
out.append(point) # baseline pass-through — already always-valid
|
|
813
|
+
return out, dropped
|
|
814
|
+
|
|
815
|
+
def _baseline_point(self, row: dict) -> ExplorePoint:
|
|
816
|
+
reject = row.get("reject")
|
|
817
|
+
return ExplorePoint(
|
|
818
|
+
end_ts=row["end_ts"],
|
|
819
|
+
elapsed_days=_row_float(row, "elapsed_days"),
|
|
820
|
+
tier="baseline",
|
|
821
|
+
effect=_row_float(row, "effect"),
|
|
822
|
+
left_bound=_row_float(row, "left_bound"),
|
|
823
|
+
right_bound=_row_float(row, "right_bound"),
|
|
824
|
+
pvalue=_row_float(row, "pvalue"),
|
|
825
|
+
reject=None if reject is None else bool(reject),
|
|
826
|
+
mde_1=_row_float(row, "mde_1"),
|
|
827
|
+
mde_2=_row_float(row, "mde_2"),
|
|
828
|
+
value_1=_row_float(row, "value_1"),
|
|
829
|
+
value_2=_row_float(row, "value_2"),
|
|
830
|
+
std_1=_row_float(row, "std_1"),
|
|
831
|
+
std_2=_row_float(row, "std_2"),
|
|
832
|
+
size_1=_row_int(row, "size_1"),
|
|
833
|
+
size_2=_row_int(row, "size_2"),
|
|
834
|
+
insufficient=bool(row.get("insufficient_data")),
|
|
835
|
+
)
|
|
836
|
+
|
|
837
|
+
def _point_from_result(
|
|
838
|
+
self, row: dict, result: TestResult, caught: list[str], tier: Tier
|
|
839
|
+
) -> ExplorePoint:
|
|
840
|
+
# Point sizes keep the ROW's persisted unit-count semantics across
|
|
841
|
+
# every tier (a fraction result's size_i is round(nobs) — exposing it
|
|
842
|
+
# here would make sizes jump between tiers of one series); the raw
|
|
843
|
+
# ``result`` rides along for consumers that need method sizes.
|
|
844
|
+
return ExplorePoint(
|
|
845
|
+
end_ts=row["end_ts"],
|
|
846
|
+
elapsed_days=_row_float(row, "elapsed_days"),
|
|
847
|
+
tier=tier,
|
|
848
|
+
effect=_clean(result.effect),
|
|
849
|
+
left_bound=_clean(result.left_bound),
|
|
850
|
+
right_bound=_clean(result.right_bound),
|
|
851
|
+
pvalue=_clean(result.pvalue),
|
|
852
|
+
reject=bool(result.reject),
|
|
853
|
+
mde_1=_clean(result.mde_1),
|
|
854
|
+
mde_2=_clean(result.mde_2),
|
|
855
|
+
value_1=_clean(result.value_1),
|
|
856
|
+
value_2=_clean(result.value_2),
|
|
857
|
+
std_1=_clean(result.std_1),
|
|
858
|
+
std_2=_clean(result.std_2),
|
|
859
|
+
size_1=_row_int(row, "size_1"),
|
|
860
|
+
size_2=_row_int(row, "size_2"),
|
|
861
|
+
warnings=[*caught, *result.warnings],
|
|
862
|
+
result=result,
|
|
863
|
+
)
|
|
864
|
+
|
|
865
|
+
def _cache_serves(
|
|
866
|
+
self,
|
|
867
|
+
series: ComparisonSeries,
|
|
868
|
+
method_cls: type[BaseMethod],
|
|
869
|
+
resolved_params: dict[str, Any],
|
|
870
|
+
loaded: MetricLoadResult,
|
|
871
|
+
name_1: str,
|
|
872
|
+
name_2: str,
|
|
873
|
+
entry_lookback: str | int | None = None,
|
|
874
|
+
) -> bool:
|
|
875
|
+
"""Whether this cached cutoff can feed ``method_cls`` for this pair.
|
|
876
|
+
|
|
877
|
+
``entry_lookback`` is the ``covariate_lookback`` the cache entry was
|
|
878
|
+
RENDERED with (a Tier-R reload may differ from the configured method).
|
|
879
|
+
"""
|
|
880
|
+
needed_roles = _KIND_ROLES.get(method_cls.input_kind)
|
|
881
|
+
if needed_roles is None:
|
|
882
|
+
return False
|
|
883
|
+
for variant in (name_1, name_2):
|
|
884
|
+
if loaded.size(variant) == 0:
|
|
885
|
+
return False
|
|
886
|
+
roles = loaded.roles_by_variant.get(variant, {})
|
|
887
|
+
if any(role not in roles for role in needed_roles):
|
|
888
|
+
return False
|
|
889
|
+
# declared capability, not param-name guessing: post-normed
|
|
890
|
+
# bootstrap needs cov_array yet has no covariate_lookback param
|
|
891
|
+
if method_cls.requires_covariate and "covariate" not in roles:
|
|
892
|
+
return False
|
|
893
|
+
if resolved_params.get("stratify") and loaded.strata_by_variant.get(variant) is None:
|
|
894
|
+
return False
|
|
895
|
+
if _needs_covariate(method_cls) and series.metric.columns.covariate is None:
|
|
896
|
+
# The cached covariate was rendered over the ENTRY's lookback; a
|
|
897
|
+
# different lookback is a new pre-period render — Tier R.
|
|
898
|
+
requested = _lookback_seconds(resolved_params.get("covariate_lookback"))
|
|
899
|
+
if requested != _lookback_seconds(entry_lookback):
|
|
900
|
+
return False
|
|
901
|
+
return True
|
|
902
|
+
|
|
903
|
+
def _chips(
|
|
904
|
+
self,
|
|
905
|
+
series: ComparisonSeries,
|
|
906
|
+
points: list[ExplorePoint],
|
|
907
|
+
method_cls: type[BaseMethod],
|
|
908
|
+
resolved_params: dict[str, Any],
|
|
909
|
+
knobs: KnobState,
|
|
910
|
+
name_1: str,
|
|
911
|
+
) -> dict[str, Any]:
|
|
912
|
+
"""The windshield chips off the latest point WITH inference (§5.1) —
|
|
913
|
+
a demoted/NULLed latest cutoff must not blank the chips when an older
|
|
914
|
+
cutoff still carries numbers (it is flagged, not hidden)."""
|
|
915
|
+
latest = next((point for point in reversed(points) if point.effect is not None), None)
|
|
916
|
+
if latest is None:
|
|
917
|
+
return {
|
|
918
|
+
"lift": None,
|
|
919
|
+
"ci_half": None,
|
|
920
|
+
"pvalue": None,
|
|
921
|
+
"power": None,
|
|
922
|
+
"power_note": "no recomputable cutoffs for this knob state",
|
|
923
|
+
"latest_end_ts": None,
|
|
924
|
+
"tier": None,
|
|
925
|
+
}
|
|
926
|
+
ci_half = None
|
|
927
|
+
if latest.left_bound is not None and latest.right_bound is not None:
|
|
928
|
+
ci_half = (latest.right_bound - latest.left_bound) / 2.0
|
|
929
|
+
power, power_note = self._pair_power(
|
|
930
|
+
series, latest, method_cls, resolved_params, knobs, name_1
|
|
931
|
+
)
|
|
932
|
+
return {
|
|
933
|
+
"lift": latest.effect,
|
|
934
|
+
"ci_half": ci_half,
|
|
935
|
+
"pvalue": latest.pvalue,
|
|
936
|
+
"power": power,
|
|
937
|
+
"power_note": power_note,
|
|
938
|
+
"latest_end_ts": latest.end_ts,
|
|
939
|
+
"tier": latest.tier,
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
def _pair_power(
|
|
943
|
+
self,
|
|
944
|
+
series: ComparisonSeries,
|
|
945
|
+
latest: ExplorePoint,
|
|
946
|
+
method_cls: type[BaseMethod],
|
|
947
|
+
resolved_params: dict[str, Any],
|
|
948
|
+
knobs: KnobState,
|
|
949
|
+
name_1: str,
|
|
950
|
+
) -> tuple[float | None, str | None]:
|
|
951
|
+
"""Achieved power to detect ``min_effect`` at the current knob state.
|
|
952
|
+
|
|
953
|
+
Family capability is declarative: resampling and MDE-less families
|
|
954
|
+
report an honest reason instead of a faked number (D5(b) spirit).
|
|
955
|
+
"""
|
|
956
|
+
min_effect = series.comparison.min_effect
|
|
957
|
+
if min_effect is None:
|
|
958
|
+
return None, "no min_effect configured — the power chip needs one (D5(b))"
|
|
959
|
+
if _needs_seed(method_cls):
|
|
960
|
+
return None, f"no power solve for resampling methods ({method_cls.name})"
|
|
961
|
+
if "calculate_mde" not in {spec.name for spec in method_cls.param_specs}:
|
|
962
|
+
return None, f"method '{method_cls.name}' has no power/MDE capability"
|
|
963
|
+
if None in (latest.value_1, latest.std_1, latest.size_1, latest.size_2):
|
|
964
|
+
return None, "per-arm stats unavailable at the latest cutoff"
|
|
965
|
+
|
|
966
|
+
test_type = str(resolved_params.get("test_type", "relative"))
|
|
967
|
+
ratio = latest.size_2 / latest.size_1
|
|
968
|
+
try:
|
|
969
|
+
if method_cls.input_kind == "fraction":
|
|
970
|
+
# the proportion solve runs on TRIAL counts (nobs), which the
|
|
971
|
+
# point's persisted unit-count sizes deliberately are not
|
|
972
|
+
if latest.result is not None:
|
|
973
|
+
nobs_1, nobs_2 = latest.result.size_1, latest.result.size_2
|
|
974
|
+
else:
|
|
975
|
+
inv_1 = _invert_fraction(latest.value_1, latest.std_1, None)
|
|
976
|
+
inv_2 = _invert_fraction(latest.value_2, latest.std_2, None)
|
|
977
|
+
if inv_1 is None or inv_2 is None:
|
|
978
|
+
return None, "trial counts unavailable at the latest cutoff"
|
|
979
|
+
nobs_1, nobs_2 = inv_1.sample_size, inv_2.sample_size
|
|
980
|
+
power = get_fraction_power(
|
|
981
|
+
latest.value_1,
|
|
982
|
+
nobs_1,
|
|
983
|
+
min_effect,
|
|
984
|
+
test_type=test_type,
|
|
985
|
+
alpha=knobs.alpha,
|
|
986
|
+
ratio=nobs_2 / nobs_1,
|
|
987
|
+
)
|
|
988
|
+
elif _needs_covariate(method_cls):
|
|
989
|
+
corr = self._control_corr(series, latest.end_ts, name_1)
|
|
990
|
+
if corr is None:
|
|
991
|
+
return None, (
|
|
992
|
+
"CUPED power needs the covariate correlation — "
|
|
993
|
+
"cutoff not in the session cache"
|
|
994
|
+
)
|
|
995
|
+
power = get_cuped_ttest_power(
|
|
996
|
+
latest.value_1,
|
|
997
|
+
latest.std_1,
|
|
998
|
+
corr,
|
|
999
|
+
latest.size_1,
|
|
1000
|
+
min_effect,
|
|
1001
|
+
test_type=test_type,
|
|
1002
|
+
alpha=knobs.alpha,
|
|
1003
|
+
ratio=ratio,
|
|
1004
|
+
)
|
|
1005
|
+
else:
|
|
1006
|
+
power = get_ttest_power(
|
|
1007
|
+
latest.value_1,
|
|
1008
|
+
latest.std_1,
|
|
1009
|
+
latest.size_1,
|
|
1010
|
+
min_effect,
|
|
1011
|
+
test_type=test_type,
|
|
1012
|
+
alpha=knobs.alpha,
|
|
1013
|
+
ratio=ratio,
|
|
1014
|
+
)
|
|
1015
|
+
except Exception as exc: # statsmodels solve failures are data-dependent
|
|
1016
|
+
return None, f"power solve failed: {exc}"
|
|
1017
|
+
return (power if math.isfinite(power) else None), None
|
|
1018
|
+
|
|
1019
|
+
def _control_corr(
|
|
1020
|
+
self, series: ComparisonSeries, end_ts: datetime, name_1: str
|
|
1021
|
+
) -> float | None:
|
|
1022
|
+
loaded = self._session.loaded(series.metric.name, end_ts)
|
|
1023
|
+
if loaded is None:
|
|
1024
|
+
return None
|
|
1025
|
+
roles = loaded.roles_by_variant.get(name_1, {})
|
|
1026
|
+
if "value" not in roles or "covariate" not in roles:
|
|
1027
|
+
return None
|
|
1028
|
+
sample = build_container("sample", name_1, loaded)
|
|
1029
|
+
corr = sample.corr_coef
|
|
1030
|
+
return None if corr is None or not math.isfinite(corr) else float(corr)
|
|
1031
|
+
|
|
1032
|
+
|
|
1033
|
+
def _compare(method: BaseMethod, group_1: Any, group_2: Any) -> tuple[TestResult, list[str]]:
|
|
1034
|
+
"""``compare_pair`` with the analyze-stage warning capture (plan R7)."""
|
|
1035
|
+
with _warnings.catch_warnings(record=True) as caught:
|
|
1036
|
+
_warnings.simplefilter("always", AbkitStatsWarning)
|
|
1037
|
+
result = method.compare_pair(group_1, group_2)
|
|
1038
|
+
messages = [str(w.message) for w in caught if issubclass(w.category, AbkitStatsWarning)]
|
|
1039
|
+
return result, messages
|