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,511 @@
|
|
|
1
|
+
"""Experiment configuration — THE primary entity (declarative-config.md §2).
|
|
2
|
+
|
|
3
|
+
An experiment declares its READ-ONLY assignment source, variants and expected
|
|
4
|
+
split (the SRM gate input), the pinned cumulative window edges, the cadence
|
|
5
|
+
(scalar duration or a dense-early coarsening schedule —
|
|
6
|
+
cumulative-intervals.md §6), and the list of comparisons binding library
|
|
7
|
+
metrics to statistical methods.
|
|
8
|
+
|
|
9
|
+
Validation split: everything checkable from THIS file alone lives here
|
|
10
|
+
(fail-fast at parse); cross-file reference integrity, look-count gates that
|
|
11
|
+
need the project config + the planner grid, and SQL render checks live in
|
|
12
|
+
``config/validator`` level 2 (WP6).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import zoneinfo
|
|
18
|
+
from datetime import date
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, Literal
|
|
21
|
+
|
|
22
|
+
from pydantic import BaseModel, Field, field_validator, model_validator
|
|
23
|
+
|
|
24
|
+
from abkit.config.method_config import MethodConfig
|
|
25
|
+
from abkit.core.interval import Interval
|
|
26
|
+
from abkit.database.tables import MAX_EXPERIMENT_NAME_LENGTH, MAX_VARIANT_NAME_LENGTH
|
|
27
|
+
from abkit.utils.json_utils import json_dumps_sorted
|
|
28
|
+
|
|
29
|
+
DAY_SECONDS = 86400
|
|
30
|
+
|
|
31
|
+
ExperimentStatus = Literal["design", "running", "concluded", "archived"]
|
|
32
|
+
CorrectionKind = Literal["none", "bonferroni", "benjamini_hochberg"]
|
|
33
|
+
SequentialScheme = Literal["always_valid", "alpha_spending"]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class CadenceSegment(BaseModel):
|
|
37
|
+
"""One segment of a coarsening cadence schedule: ``{every: 1h, until: 48h}``.
|
|
38
|
+
|
|
39
|
+
``until`` is measured from ``start_ts``; the LAST segment may omit it
|
|
40
|
+
(runs to the horizon).
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
every: int | str = Field(..., description="Cutoff step within this segment")
|
|
44
|
+
until: int | str | None = Field(
|
|
45
|
+
default=None, description="Segment end, measured from start_ts (last segment: omit)"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
@field_validator("every", "until")
|
|
49
|
+
@classmethod
|
|
50
|
+
def _parses_as_interval(cls, v: int | str | None) -> int | str | None:
|
|
51
|
+
if v is not None:
|
|
52
|
+
Interval(v) # raises ValueError on bad grammar / non-positive
|
|
53
|
+
return v
|
|
54
|
+
|
|
55
|
+
def every_seconds(self) -> int:
|
|
56
|
+
return Interval(self.every).seconds
|
|
57
|
+
|
|
58
|
+
def until_seconds(self) -> int | None:
|
|
59
|
+
return None if self.until is None else Interval(self.until).seconds
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class AssignmentConfig(BaseModel):
|
|
63
|
+
"""The READ-ONLY exposure source — abkit does not randomize."""
|
|
64
|
+
|
|
65
|
+
query: str | None = Field(default=None, description="Inline assignment SQL")
|
|
66
|
+
query_file: Path | None = Field(default=None, description="Path to assignment SQL file")
|
|
67
|
+
added_filters: str = Field(
|
|
68
|
+
default="", description="Optional extra SQL fragment (must start with AND)"
|
|
69
|
+
)
|
|
70
|
+
variants: list[str] = Field(..., description="Variant names; FIRST is control (name_1)")
|
|
71
|
+
expected_split: dict[str, float] = Field(
|
|
72
|
+
..., description="Expected assignment shares; drives the SRM chi-square gate"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
@field_validator("variants")
|
|
76
|
+
@classmethod
|
|
77
|
+
def validate_variants(cls, v: list[str]) -> list[str]:
|
|
78
|
+
if len(v) < 2:
|
|
79
|
+
raise ValueError("assignment.variants needs at least two variants")
|
|
80
|
+
if len(v) != len(set(v)):
|
|
81
|
+
raise ValueError("assignment.variants must be unique")
|
|
82
|
+
for name in v:
|
|
83
|
+
if not name:
|
|
84
|
+
raise ValueError("variant names cannot be empty")
|
|
85
|
+
if len(name) > MAX_VARIANT_NAME_LENGTH:
|
|
86
|
+
raise ValueError(
|
|
87
|
+
f"variant name '{name}' is longer than {MAX_VARIANT_NAME_LENGTH} "
|
|
88
|
+
"characters (the storage key budget)"
|
|
89
|
+
)
|
|
90
|
+
return v
|
|
91
|
+
|
|
92
|
+
@field_validator("added_filters")
|
|
93
|
+
@classmethod
|
|
94
|
+
def validate_added_filters(cls, v: str) -> str:
|
|
95
|
+
v = v.strip()
|
|
96
|
+
if v and not v.upper().startswith("AND"):
|
|
97
|
+
raise ValueError(
|
|
98
|
+
"assignment.added_filters must start with 'AND' (it is appended "
|
|
99
|
+
"to the packaged cohort WHERE clause)"
|
|
100
|
+
)
|
|
101
|
+
return v
|
|
102
|
+
|
|
103
|
+
@model_validator(mode="after")
|
|
104
|
+
def validate_query_source(self) -> AssignmentConfig:
|
|
105
|
+
if self.query is None and self.query_file is None:
|
|
106
|
+
raise ValueError("assignment needs either 'query' or 'query_file'")
|
|
107
|
+
if self.query is not None and self.query_file is not None:
|
|
108
|
+
raise ValueError("assignment: only one of 'query' or 'query_file', not both")
|
|
109
|
+
return self
|
|
110
|
+
|
|
111
|
+
@model_validator(mode="after")
|
|
112
|
+
def validate_expected_split(self) -> AssignmentConfig:
|
|
113
|
+
unknown = set(self.expected_split) - set(self.variants)
|
|
114
|
+
if unknown:
|
|
115
|
+
raise ValueError(
|
|
116
|
+
f"expected_split names unknown variants {sorted(unknown)} "
|
|
117
|
+
f"(assignment.variants: {self.variants})"
|
|
118
|
+
)
|
|
119
|
+
missing = set(self.variants) - set(self.expected_split)
|
|
120
|
+
if missing:
|
|
121
|
+
raise ValueError(f"expected_split is missing variants {sorted(missing)}")
|
|
122
|
+
for name, share in self.expected_split.items():
|
|
123
|
+
if not 0.0 < share < 1.0:
|
|
124
|
+
raise ValueError(
|
|
125
|
+
f"expected_split['{name}'] must be a fraction in (0, 1), got {share}"
|
|
126
|
+
)
|
|
127
|
+
total = sum(self.expected_split.values())
|
|
128
|
+
if abs(total - 1.0) > 1e-6:
|
|
129
|
+
raise ValueError(f"expected_split must sum to 1.0, got {total}")
|
|
130
|
+
return self
|
|
131
|
+
|
|
132
|
+
def get_query_text(self, project_root: Path | None = None) -> str:
|
|
133
|
+
"""Get the assignment SQL text (inline or from file)."""
|
|
134
|
+
if self.query is not None:
|
|
135
|
+
return self.query
|
|
136
|
+
query_path = project_root / self.query_file if project_root is not None else self.query_file
|
|
137
|
+
if not query_path.exists():
|
|
138
|
+
raise FileNotFoundError(f"Assignment query file not found: {query_path}")
|
|
139
|
+
with open(query_path) as f:
|
|
140
|
+
return f.read()
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class SequentialConfig(BaseModel):
|
|
144
|
+
"""Opt-in peeking-correct CIs (default off = legacy behaviour, decision Q2)."""
|
|
145
|
+
|
|
146
|
+
enabled: bool = Field(default=False)
|
|
147
|
+
scheme: SequentialScheme = Field(default="always_valid")
|
|
148
|
+
|
|
149
|
+
@model_validator(mode="after")
|
|
150
|
+
def validate_scheme(self) -> SequentialConfig:
|
|
151
|
+
# M5 ships always_valid (mSPRT/asymptotic-CS) only; group-sequential is deferred
|
|
152
|
+
# (m5-implementation-plan.md D6). The Literal keeps forward-compat; the message
|
|
153
|
+
# is friendlier than a bare enum error.
|
|
154
|
+
if self.scheme == "alpha_spending":
|
|
155
|
+
raise ValueError(
|
|
156
|
+
"scheme: alpha_spending (group-sequential) is planned for M6 — "
|
|
157
|
+
"use scheme: always_valid (the mSPRT/asymptotic always-valid mode)"
|
|
158
|
+
)
|
|
159
|
+
return self
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class ComparisonConfig(BaseModel):
|
|
163
|
+
"""One (metric × method) binding within an experiment.
|
|
164
|
+
|
|
165
|
+
``min_effect``/``desired_direction`` are READ-TIME verdict inputs
|
|
166
|
+
(m3-implementation-plan.md D5; data-contract-and-reporting.md §1) — they
|
|
167
|
+
are not method params and never enter ``method_config_id``.
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
metric: str = Field(..., description="References metrics/<name>.yml by name")
|
|
171
|
+
is_main_metric: bool = Field(default=False, description="Primary winner criterion")
|
|
172
|
+
is_guardrail: bool = Field(default=False, description="Checked for regression only")
|
|
173
|
+
method: MethodConfig = Field(..., description="The statistical method to run")
|
|
174
|
+
min_effect: float | None = Field(
|
|
175
|
+
default=None,
|
|
176
|
+
gt=0,
|
|
177
|
+
description=(
|
|
178
|
+
"The business-meaningful effect in the units of this comparison's "
|
|
179
|
+
"persisted effect (test_type-dependent). Enables the FLAT verdict: "
|
|
180
|
+
"without it, flat cannot be distinguished from underpowered (D5(b))"
|
|
181
|
+
),
|
|
182
|
+
)
|
|
183
|
+
desired_direction: Literal["increase", "decrease"] = Field(
|
|
184
|
+
default="increase",
|
|
185
|
+
description=(
|
|
186
|
+
"Which effect sign is good for this metric — orients WIN vs LOSE "
|
|
187
|
+
"for main metrics and the regression check for guardrails (D5(c))"
|
|
188
|
+
),
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
@model_validator(mode="after")
|
|
192
|
+
def validate_roles(self) -> ComparisonConfig:
|
|
193
|
+
if self.is_main_metric and self.is_guardrail:
|
|
194
|
+
raise ValueError(
|
|
195
|
+
f"comparison '{self.metric}': is_main_metric and is_guardrail "
|
|
196
|
+
"cannot both be true"
|
|
197
|
+
)
|
|
198
|
+
return self
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class ReadoutConfig(BaseModel):
|
|
202
|
+
"""Read-time verdict knobs (m3-implementation-plan.md D5 — never identity)."""
|
|
203
|
+
|
|
204
|
+
stabilization_days: float = Field(
|
|
205
|
+
default=7.0,
|
|
206
|
+
gt=0,
|
|
207
|
+
description=(
|
|
208
|
+
"The trailing elapsed-days window over which significance must be "
|
|
209
|
+
"persistent (judged over elapsed time, never look count — "
|
|
210
|
+
"data-contract-and-reporting.md §4); default 7 covers one weekly cycle"
|
|
211
|
+
),
|
|
212
|
+
)
|
|
213
|
+
guardrail_policy: Literal["block", "warn"] = Field(
|
|
214
|
+
default="block",
|
|
215
|
+
description=(
|
|
216
|
+
"What a regressed guardrail does to a WIN: 'block' caps it at "
|
|
217
|
+
"INCONCLUSIVE (default); 'warn' keeps WIN with a mandatory loud "
|
|
218
|
+
"caveat (owner-ratified D5(c))"
|
|
219
|
+
),
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class ExperimentConfig(BaseModel):
|
|
224
|
+
"""The experiment — see the module docstring and declarative-config.md §2."""
|
|
225
|
+
|
|
226
|
+
name: str = Field(..., description="Globally unique experiment name (DB key)")
|
|
227
|
+
description: str | None = Field(default=None)
|
|
228
|
+
status: ExperimentStatus = Field(default="running")
|
|
229
|
+
is_actual: bool = Field(default=True, description="Scheduled runs pick it up")
|
|
230
|
+
tags: list[str] | None = Field(default=None)
|
|
231
|
+
|
|
232
|
+
start_date: date = Field(..., description="PINNED left edge of every cumulative window")
|
|
233
|
+
end_date: date = Field(..., description="Planner horizon (drives the power plan)")
|
|
234
|
+
unit_key: str = Field(..., description="Randomization + default analysis unit")
|
|
235
|
+
|
|
236
|
+
cadence: int | str | list[CadenceSegment] = Field(
|
|
237
|
+
default="1d",
|
|
238
|
+
description="Cumulative cutoff step: duration scalar or coarsening schedule",
|
|
239
|
+
)
|
|
240
|
+
data_lag: int | str | None = Field(
|
|
241
|
+
default=None,
|
|
242
|
+
description=(
|
|
243
|
+
"Completeness watermark: data assumed complete through now() - "
|
|
244
|
+
"data_lag. REQUIRED when cadence < 1d; default 0 reproduces "
|
|
245
|
+
"*_wo_curr_day at daily cadence"
|
|
246
|
+
),
|
|
247
|
+
)
|
|
248
|
+
timezone: str = Field(
|
|
249
|
+
default="UTC",
|
|
250
|
+
description="Interprets date-typed fields & daily midnight snapping; storage is UTC",
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
assignment: AssignmentConfig = Field(...)
|
|
254
|
+
alpha: float | None = Field(
|
|
255
|
+
default=None, description="Experiment-level significance (None -> project default)"
|
|
256
|
+
)
|
|
257
|
+
correction: CorrectionKind | None = Field(default=None, description="None -> project default")
|
|
258
|
+
sequential: SequentialConfig = Field(default_factory=SequentialConfig)
|
|
259
|
+
readout: ReadoutConfig = Field(default_factory=ReadoutConfig)
|
|
260
|
+
comparisons: list[ComparisonConfig] = Field(...)
|
|
261
|
+
|
|
262
|
+
# ── field validators ─────────────────────────────────────────────────────
|
|
263
|
+
|
|
264
|
+
@field_validator("name")
|
|
265
|
+
@classmethod
|
|
266
|
+
def validate_name(cls, v: str) -> str:
|
|
267
|
+
if not v:
|
|
268
|
+
raise ValueError("Experiment name cannot be empty")
|
|
269
|
+
if not all(c.isalnum() or c in ("_", "-") for c in v):
|
|
270
|
+
raise ValueError(
|
|
271
|
+
"Experiment name can only contain alphanumeric characters, "
|
|
272
|
+
"underscores, and dashes"
|
|
273
|
+
)
|
|
274
|
+
if len(v) > MAX_EXPERIMENT_NAME_LENGTH:
|
|
275
|
+
raise ValueError(
|
|
276
|
+
f"Experiment name is longer than {MAX_EXPERIMENT_NAME_LENGTH} "
|
|
277
|
+
"characters (the storage key budget)"
|
|
278
|
+
)
|
|
279
|
+
return v
|
|
280
|
+
|
|
281
|
+
@field_validator("alpha")
|
|
282
|
+
@classmethod
|
|
283
|
+
def validate_alpha(cls, v: float | None) -> float | None:
|
|
284
|
+
if v is not None and not 0.0 < v < 1.0:
|
|
285
|
+
raise ValueError(f"alpha must be in (0, 1), got {v}")
|
|
286
|
+
return v
|
|
287
|
+
|
|
288
|
+
@field_validator("timezone")
|
|
289
|
+
@classmethod
|
|
290
|
+
def validate_timezone(cls, v: str) -> str:
|
|
291
|
+
try:
|
|
292
|
+
zoneinfo.ZoneInfo(v)
|
|
293
|
+
except (zoneinfo.ZoneInfoNotFoundError, ValueError) as exc:
|
|
294
|
+
raise ValueError(f"unknown timezone: {v!r}") from exc
|
|
295
|
+
return v
|
|
296
|
+
|
|
297
|
+
@field_validator("data_lag")
|
|
298
|
+
@classmethod
|
|
299
|
+
def validate_data_lag(cls, v: int | str | None) -> int | str | None:
|
|
300
|
+
if v is None or v == 0:
|
|
301
|
+
return v
|
|
302
|
+
Interval(v) # raises on bad grammar / negative
|
|
303
|
+
return v
|
|
304
|
+
|
|
305
|
+
@field_validator("cadence")
|
|
306
|
+
@classmethod
|
|
307
|
+
def validate_cadence_scalar(cls, v):
|
|
308
|
+
if not isinstance(v, list):
|
|
309
|
+
Interval(v) # whole seconds >= 1s (the §6.1 grammar)
|
|
310
|
+
return v
|
|
311
|
+
|
|
312
|
+
# ── model validators ─────────────────────────────────────────────────────
|
|
313
|
+
|
|
314
|
+
@model_validator(mode="after")
|
|
315
|
+
def validate_dates(self) -> ExperimentConfig:
|
|
316
|
+
if self.end_date < self.start_date:
|
|
317
|
+
raise ValueError(f"end_date ({self.end_date}) is before start_date ({self.start_date})")
|
|
318
|
+
return self
|
|
319
|
+
|
|
320
|
+
@model_validator(mode="after")
|
|
321
|
+
def validate_cadence_schedule(self) -> ExperimentConfig:
|
|
322
|
+
"""Schedule segments: non-overlapping, strictly coarsening, increasing until."""
|
|
323
|
+
if not isinstance(self.cadence, list):
|
|
324
|
+
if self.cadence_seconds_min() > self.horizon_seconds():
|
|
325
|
+
raise ValueError(
|
|
326
|
+
f"cadence ({self.cadence}) is longer than the experiment horizon "
|
|
327
|
+
f"({self.horizon_seconds()}s) — no cutoff would ever be produced"
|
|
328
|
+
)
|
|
329
|
+
return self
|
|
330
|
+
|
|
331
|
+
segments = self.cadence
|
|
332
|
+
if not segments:
|
|
333
|
+
raise ValueError("cadence schedule cannot be empty")
|
|
334
|
+
previous_every = 0
|
|
335
|
+
previous_until = 0
|
|
336
|
+
for i, seg in enumerate(segments):
|
|
337
|
+
is_last = i == len(segments) - 1
|
|
338
|
+
every = seg.every_seconds()
|
|
339
|
+
until = seg.until_seconds()
|
|
340
|
+
if every <= previous_every:
|
|
341
|
+
raise ValueError(
|
|
342
|
+
"cadence schedule must be strictly coarsening: segment "
|
|
343
|
+
f"{i} 'every' ({seg.every}) must be longer than the previous"
|
|
344
|
+
)
|
|
345
|
+
if until is None and not is_last:
|
|
346
|
+
raise ValueError(
|
|
347
|
+
f"cadence schedule segment {i} needs 'until' (only the last "
|
|
348
|
+
"segment may run to the horizon)"
|
|
349
|
+
)
|
|
350
|
+
if until is not None:
|
|
351
|
+
if until <= previous_until:
|
|
352
|
+
raise ValueError(
|
|
353
|
+
"cadence schedule 'until' bounds must be strictly increasing: "
|
|
354
|
+
f"segment {i} ({seg.until})"
|
|
355
|
+
)
|
|
356
|
+
if until <= every:
|
|
357
|
+
raise ValueError(
|
|
358
|
+
f"cadence schedule segment {i}: 'until' ({seg.until}) must "
|
|
359
|
+
f"exceed 'every' ({seg.every})"
|
|
360
|
+
)
|
|
361
|
+
previous_until = until
|
|
362
|
+
previous_every = every
|
|
363
|
+
if self.cadence_seconds_min() > self.horizon_seconds():
|
|
364
|
+
raise ValueError("cadence schedule's densest segment is longer than the horizon")
|
|
365
|
+
return self
|
|
366
|
+
|
|
367
|
+
@model_validator(mode="after")
|
|
368
|
+
def validate_sub_day_gates(self) -> ExperimentConfig:
|
|
369
|
+
"""cumulative-intervals §6: sub-day cadence gates that need no project config."""
|
|
370
|
+
if not self.is_sub_day():
|
|
371
|
+
return self
|
|
372
|
+
if self.data_lag is None:
|
|
373
|
+
raise ValueError(
|
|
374
|
+
"cadence < 1d requires 'data_lag' (declare your ingestion SLA — "
|
|
375
|
+
"cumulative-intervals.md §6.2). Use data_lag: 0 only if data is "
|
|
376
|
+
"truly complete in real time."
|
|
377
|
+
)
|
|
378
|
+
# (scheme: alpha_spending is rejected globally in SequentialConfig — M6 deferral.)
|
|
379
|
+
return self
|
|
380
|
+
|
|
381
|
+
@model_validator(mode="after")
|
|
382
|
+
def validate_comparisons(self) -> ExperimentConfig:
|
|
383
|
+
if not self.comparisons:
|
|
384
|
+
raise ValueError("an experiment needs at least one comparison")
|
|
385
|
+
metrics = [c.metric for c in self.comparisons]
|
|
386
|
+
duplicates = sorted({m for m in metrics if metrics.count(m) > 1})
|
|
387
|
+
if duplicates:
|
|
388
|
+
raise ValueError(
|
|
389
|
+
f"duplicate metric references in comparisons: {duplicates} "
|
|
390
|
+
"(bind each metric at most once per experiment)"
|
|
391
|
+
)
|
|
392
|
+
if not any(c.is_main_metric for c in self.comparisons):
|
|
393
|
+
raise ValueError(
|
|
394
|
+
"at least one comparison must set is_main_metric: true "
|
|
395
|
+
"(it drives the verdict and the two-tier Bonferroni)"
|
|
396
|
+
)
|
|
397
|
+
return self
|
|
398
|
+
|
|
399
|
+
# ── derived accessors ────────────────────────────────────────────────────
|
|
400
|
+
|
|
401
|
+
def cadence_segments(self) -> list[tuple[int, int | None]]:
|
|
402
|
+
"""Normalised ``[(every_seconds, until_seconds|None), ...]``.
|
|
403
|
+
|
|
404
|
+
A scalar cadence is one segment running to the horizon — a property
|
|
405
|
+
the planner tests pin: grids for ``1d`` and ``[{every: 1d}]`` must be
|
|
406
|
+
identical (plan R1).
|
|
407
|
+
"""
|
|
408
|
+
if isinstance(self.cadence, list):
|
|
409
|
+
return [(seg.every_seconds(), seg.until_seconds()) for seg in self.cadence]
|
|
410
|
+
return [(Interval(self.cadence).seconds, None)]
|
|
411
|
+
|
|
412
|
+
def cadence_seconds_min(self) -> int:
|
|
413
|
+
"""The densest step (drives the sub-day gates)."""
|
|
414
|
+
return min(every for every, _ in self.cadence_segments())
|
|
415
|
+
|
|
416
|
+
def is_sub_day(self) -> bool:
|
|
417
|
+
return self.cadence_seconds_min() < DAY_SECONDS
|
|
418
|
+
|
|
419
|
+
def data_lag_seconds(self) -> int:
|
|
420
|
+
"""The declared ingestion SLA in seconds (0 when unset — daily default)."""
|
|
421
|
+
if self.data_lag is None or self.data_lag == 0:
|
|
422
|
+
return 0
|
|
423
|
+
return Interval(self.data_lag).seconds
|
|
424
|
+
|
|
425
|
+
def horizon_seconds(self) -> int:
|
|
426
|
+
"""Length of the full experiment window: [start_date .. end_date] inclusive."""
|
|
427
|
+
return ((self.end_date - self.start_date).days + 1) * DAY_SECONDS
|
|
428
|
+
|
|
429
|
+
def cadence_canonical_json(self) -> str:
|
|
430
|
+
"""Canonical JSON for the ``_ab_experiments`` catalog (always a segment list)."""
|
|
431
|
+
return json_dumps_sorted(
|
|
432
|
+
[{"every": every, "until": until} for every, until in self.cadence_segments()]
|
|
433
|
+
)
|
|
434
|
+
|
|
435
|
+
def main_metrics(self) -> list[str]:
|
|
436
|
+
return [c.metric for c in self.comparisons if c.is_main_metric]
|
|
437
|
+
|
|
438
|
+
def get_comparison(self, metric: str) -> ComparisonConfig:
|
|
439
|
+
for comparison in self.comparisons:
|
|
440
|
+
if comparison.metric == metric:
|
|
441
|
+
return comparison
|
|
442
|
+
raise KeyError(f"no comparison for metric {metric!r} in experiment {self.name!r}")
|
|
443
|
+
|
|
444
|
+
def catalog_record(
|
|
445
|
+
self,
|
|
446
|
+
path: str = "",
|
|
447
|
+
effective_alpha: float | None = None,
|
|
448
|
+
effective_correction: str | None = None,
|
|
449
|
+
) -> dict[str, Any]:
|
|
450
|
+
"""The flat ``_ab_experiments`` row (JSON fields canonical).
|
|
451
|
+
|
|
452
|
+
``effective_alpha``/``effective_correction`` are the project-resolved
|
|
453
|
+
values the pipeline actually runs with (an unset experiment field
|
|
454
|
+
falls back to the project default — the caller resolves).
|
|
455
|
+
"""
|
|
456
|
+
return {
|
|
457
|
+
"experiment": self.name,
|
|
458
|
+
"description": self.description,
|
|
459
|
+
"status": self.status,
|
|
460
|
+
"is_actual": self.is_actual,
|
|
461
|
+
"start_date": self.start_date,
|
|
462
|
+
"end_date": self.end_date,
|
|
463
|
+
"unit_key": self.unit_key,
|
|
464
|
+
"cadence": self.cadence_canonical_json(),
|
|
465
|
+
"data_lag_seconds": self.data_lag_seconds(),
|
|
466
|
+
"timezone": self.timezone,
|
|
467
|
+
"variants": json_dumps_sorted(self.assignment.variants),
|
|
468
|
+
"expected_split": json_dumps_sorted(self.assignment.expected_split),
|
|
469
|
+
"alpha": effective_alpha if effective_alpha is not None else self.alpha,
|
|
470
|
+
"correction": (
|
|
471
|
+
effective_correction if effective_correction is not None else self.correction
|
|
472
|
+
),
|
|
473
|
+
"sequential_enabled": self.sequential.enabled,
|
|
474
|
+
"sequential_scheme": self.sequential.scheme,
|
|
475
|
+
"comparisons": json_dumps_sorted(
|
|
476
|
+
[
|
|
477
|
+
{
|
|
478
|
+
"metric": c.metric,
|
|
479
|
+
"is_main_metric": c.is_main_metric,
|
|
480
|
+
"is_guardrail": c.is_guardrail,
|
|
481
|
+
"method": c.method.name,
|
|
482
|
+
"method_config_id": c.method.method_config_id,
|
|
483
|
+
}
|
|
484
|
+
for c in self.comparisons
|
|
485
|
+
]
|
|
486
|
+
),
|
|
487
|
+
"path": path,
|
|
488
|
+
"tags": json_dumps_sorted(self.tags or []),
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
@classmethod
|
|
492
|
+
def from_yaml_file(cls, path: Path) -> ExperimentConfig:
|
|
493
|
+
"""Load experiment configuration from a YAML file.
|
|
494
|
+
|
|
495
|
+
Supports both flat and nested (``experiment: {...}``) structures.
|
|
496
|
+
"""
|
|
497
|
+
import yaml
|
|
498
|
+
|
|
499
|
+
if not path.exists():
|
|
500
|
+
raise FileNotFoundError(f"Experiment config file not found: {path}")
|
|
501
|
+
|
|
502
|
+
with open(path) as f:
|
|
503
|
+
data = yaml.safe_load(f)
|
|
504
|
+
|
|
505
|
+
if not data:
|
|
506
|
+
raise ValueError(f"Empty experiment config file: {path}")
|
|
507
|
+
|
|
508
|
+
if "experiment" in data and isinstance(data["experiment"], dict):
|
|
509
|
+
data = data["experiment"]
|
|
510
|
+
|
|
511
|
+
return cls.model_validate(data)
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Method configuration — the tunable, hashed statistical object.
|
|
2
|
+
|
|
3
|
+
Plan R4 (m2-implementation-plan.md): this model deliberately does NOT
|
|
4
|
+
re-implement hashing or a parallel param schema. It stores only
|
|
5
|
+
``{name, params}``; validation, the quarantine policy, and the canonical
|
|
6
|
+
``method_config_id`` all come from ONE instantiation through the
|
|
7
|
+
``abkit.stats`` factory (declarative-config.md §7: one canonical spec).
|
|
8
|
+
Instantiation IS validation — a quarantined branch or a bad param fails at
|
|
9
|
+
config-validate/plan time, never at run time.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
|
|
17
|
+
|
|
18
|
+
from abkit.stats import BaseMethod, create_method
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class MethodConfig(BaseModel):
|
|
22
|
+
"""One comparison's statistical method: registry name + params.
|
|
23
|
+
|
|
24
|
+
``alpha`` is deliberately NOT here — it is an experiment-level setting
|
|
25
|
+
(post-correction effective alpha is injected at bind time) and never
|
|
26
|
+
enters ``method_config_id``.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
model_config = ConfigDict(frozen=True)
|
|
30
|
+
|
|
31
|
+
name: str = Field(..., description="Registry name (e.g. 'z-test', 'cuped-t-test')")
|
|
32
|
+
params: dict[str, Any] = Field(default_factory=dict, description="Method params")
|
|
33
|
+
|
|
34
|
+
_bound_probe: BaseMethod | None = PrivateAttr(default=None)
|
|
35
|
+
|
|
36
|
+
def bind(self, alpha: float = 0.05) -> BaseMethod:
|
|
37
|
+
"""Instantiate the method via the stats factory (validates params).
|
|
38
|
+
|
|
39
|
+
Raises the stats-core exceptions unchanged (``UnknownMethodError``,
|
|
40
|
+
``MethodParamError``, ``QuarantinedMethodError``) — the validator
|
|
41
|
+
surfaces them as config errors.
|
|
42
|
+
|
|
43
|
+
Closed-form instances are reusable across cutoffs; bootstrap methods
|
|
44
|
+
are re-bound per row by the analyze stage with the deterministic
|
|
45
|
+
derived seed injected into a params copy (``seed`` is
|
|
46
|
+
identity-excluded, so the id below is unaffected).
|
|
47
|
+
"""
|
|
48
|
+
return create_method(self.name, alpha=alpha, params=dict(self.params))
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def method_config_id(self) -> str:
|
|
52
|
+
"""The canonical identity hash, read off a probe instance (cached).
|
|
53
|
+
|
|
54
|
+
Byte-identical to ``BaseMethod.method_config_id`` by construction —
|
|
55
|
+
there is no second hashing path.
|
|
56
|
+
"""
|
|
57
|
+
if self._bound_probe is None:
|
|
58
|
+
# alpha does not enter the id; any value produces the same hash
|
|
59
|
+
self._bound_probe = self.bind(alpha=0.05)
|
|
60
|
+
return self._bound_probe.method_config_id
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def covariate_lookback(self) -> str | int | None:
|
|
64
|
+
"""The CUPED pre-period lookback param (pipeline-consumed; see the
|
|
65
|
+
stats-core ``COVARIATE_LOOKBACK_PARAM`` — identity-bearing there)."""
|
|
66
|
+
return self.params.get("covariate_lookback")
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def canonical_params_json(self) -> str:
|
|
70
|
+
"""The canonical ``method_params`` JSON string persisted to ``_ab_results``.
|
|
71
|
+
|
|
72
|
+
Read off the probe instance so config-time and enrich-time
|
|
73
|
+
serialisations can never disagree (quorum: "canonical method_params
|
|
74
|
+
JSON everywhere").
|
|
75
|
+
"""
|
|
76
|
+
if self._bound_probe is None:
|
|
77
|
+
self._bound_probe = self.bind(alpha=0.05)
|
|
78
|
+
from abkit.utils.json_utils import json_dumps_sorted
|
|
79
|
+
|
|
80
|
+
return json_dumps_sorted(self._bound_probe.method_params)
|