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,251 @@
|
|
|
1
|
+
"""Metric loader: metric SQL → per-unit, per-variant role arrays.
|
|
2
|
+
|
|
3
|
+
Render → execute → validate → group. The loader returns typed per-unit
|
|
4
|
+
arrays keyed by variant and column role; the analyze stage (WP8) converts
|
|
5
|
+
them into stats-core containers (``Sample``/``Fraction``/``RatioSample`` or
|
|
6
|
+
sufficient statistics) per the method family — the loader knows nothing
|
|
7
|
+
about methods.
|
|
8
|
+
|
|
9
|
+
CUPED covariate mechanics (statistics-changes.md §5, fixed whole-day
|
|
10
|
+
lookback): when a comparison's method declares ``covariate_lookback``, the
|
|
11
|
+
SAME metric SQL is rendered a SECOND time over the pre-period window
|
|
12
|
+
``[start_ts − lookback, start_ts)`` with the exposure filter dropped
|
|
13
|
+
(``ab_apply_exposure_filter=false`` — pre-period precedes exposure by
|
|
14
|
+
construction), and the pre-period VALUE becomes the covariate, keyed by
|
|
15
|
+
unit (absent units → 0.0, the standard new-user convention). This is the
|
|
16
|
+
legacy CUPED semantics — the covariate is the same metric over the
|
|
17
|
+
pre-period — expressed as two renders of one query instead of a conditional
|
|
18
|
+
aggregate, so plain additive ``sum()``/``count()`` metric SQL stays correct.
|
|
19
|
+
An explicit ``columns.covariate`` role (a covariate column computed by the
|
|
20
|
+
author's own SQL) takes precedence and skips the second render.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import math
|
|
26
|
+
import warnings
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
|
|
31
|
+
from abkit.config.metric_config import MetricConfig
|
|
32
|
+
from abkit.database.manager import BaseDatabaseManager
|
|
33
|
+
from abkit.loaders.query_template import QueryTemplate
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class MetricLoadError(Exception):
|
|
37
|
+
"""Raised when a metric result set violates the one-row-per-unit contract."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
#: roles carried through per metric type (unit + these become arrays)
|
|
41
|
+
_NUMERIC_ROLES = ("value", "covariate", "count", "nobs", "numerator", "denominator")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _to_float_array(values: list[Any], role: str, metric: str) -> np.ndarray:
|
|
45
|
+
out = np.empty(len(values), dtype=np.float64)
|
|
46
|
+
for i, v in enumerate(values):
|
|
47
|
+
if v is None:
|
|
48
|
+
out[i] = np.nan
|
|
49
|
+
else:
|
|
50
|
+
try:
|
|
51
|
+
out[i] = float(v)
|
|
52
|
+
except (TypeError, ValueError) as exc:
|
|
53
|
+
raise MetricLoadError(
|
|
54
|
+
f"metric '{metric}': column role '{role}' has a non-numeric "
|
|
55
|
+
f"value {v!r} at row {i}"
|
|
56
|
+
) from exc
|
|
57
|
+
if np.isnan(out).any():
|
|
58
|
+
n_nan = int(np.isnan(out).sum())
|
|
59
|
+
warnings.warn(
|
|
60
|
+
f"metric '{metric}': {n_nan} NULL values in role '{role}' treated as NaN",
|
|
61
|
+
stacklevel=3,
|
|
62
|
+
)
|
|
63
|
+
return out
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class MetricLoadResult:
|
|
67
|
+
"""Per-variant, per-role per-unit arrays for one (metric, window) load."""
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
metric: str,
|
|
72
|
+
units_by_variant: dict[str, np.ndarray],
|
|
73
|
+
roles_by_variant: dict[str, dict[str, np.ndarray]],
|
|
74
|
+
strata_by_variant: dict[str, np.ndarray | None],
|
|
75
|
+
):
|
|
76
|
+
self.metric = metric
|
|
77
|
+
self.units_by_variant = units_by_variant
|
|
78
|
+
self.roles_by_variant = roles_by_variant
|
|
79
|
+
self.strata_by_variant = strata_by_variant
|
|
80
|
+
|
|
81
|
+
def variants(self) -> list[str]:
|
|
82
|
+
return sorted(self.units_by_variant)
|
|
83
|
+
|
|
84
|
+
def size(self, variant: str) -> int:
|
|
85
|
+
return len(self.units_by_variant.get(variant, ()))
|
|
86
|
+
|
|
87
|
+
def attach_covariate(self, covariate_by_unit: dict[str, float]) -> None:
|
|
88
|
+
"""Join a pre-period covariate onto every variant's units (absent → 0.0)."""
|
|
89
|
+
for variant, units in self.units_by_variant.items():
|
|
90
|
+
self.roles_by_variant[variant]["covariate"] = np.array(
|
|
91
|
+
[covariate_by_unit.get(u, 0.0) for u in units], dtype=np.float64
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def load_metric(
|
|
96
|
+
manager: BaseDatabaseManager,
|
|
97
|
+
metric: MetricConfig,
|
|
98
|
+
metric_sql: str,
|
|
99
|
+
builtins: dict[str, Any],
|
|
100
|
+
declared_variants: list[str],
|
|
101
|
+
template: QueryTemplate | None = None,
|
|
102
|
+
) -> MetricLoadResult:
|
|
103
|
+
"""Render + execute + validate one metric query for one window.
|
|
104
|
+
|
|
105
|
+
Contract (declarative-config.md §3): ONE ROW PER UNIT with additive
|
|
106
|
+
aggregate columns over the window. Guards:
|
|
107
|
+
|
|
108
|
+
- rendered SQL must join the persisted cohort (``_abk_exposures``) — the
|
|
109
|
+
macro-usage lint's runtime half;
|
|
110
|
+
- required role columns present in the result set;
|
|
111
|
+
- rows > distinct units → loud one-row-per-unit warning naming the fix
|
|
112
|
+
("did you forget GROUP BY <unit_key>?"); duplicate unit rows are
|
|
113
|
+
REJECTED, not silently aggregated;
|
|
114
|
+
- observed variants ⊆ declared variants.
|
|
115
|
+
"""
|
|
116
|
+
template = template or QueryTemplate()
|
|
117
|
+
rendered = template.render(metric_sql, builtins)
|
|
118
|
+
if "_abk_exposures" not in rendered:
|
|
119
|
+
raise MetricLoadError(
|
|
120
|
+
f"metric '{metric.name}': rendered SQL does not join the persisted "
|
|
121
|
+
"cohort — use the packaged macro ({% import 'abkit_assignment.jinja' "
|
|
122
|
+
"as ab %} ... {{ ab.exposed_units() }})"
|
|
123
|
+
)
|
|
124
|
+
rows = manager.execute_query(rendered)
|
|
125
|
+
|
|
126
|
+
role_map = metric.columns.role_map()
|
|
127
|
+
variant_col = role_map["variant"]
|
|
128
|
+
unit_col = builtins["ab_unit_key"]
|
|
129
|
+
stratum_col = role_map.get("stratum")
|
|
130
|
+
|
|
131
|
+
result_units: dict[str, list[str]] = {}
|
|
132
|
+
result_roles: dict[str, dict[str, list[Any]]] = {}
|
|
133
|
+
result_strata: dict[str, list[Any]] = {}
|
|
134
|
+
|
|
135
|
+
if rows:
|
|
136
|
+
present = rows[0].keys()
|
|
137
|
+
# every declared role — INCLUDING stratum — must be present in the
|
|
138
|
+
# result set (a missing stratum column was a raw KeyError before)
|
|
139
|
+
needed = {unit_col: "unit"} | {col: role for role, col in role_map.items()}
|
|
140
|
+
missing = [col for col in needed if col not in present]
|
|
141
|
+
if missing:
|
|
142
|
+
raise MetricLoadError(
|
|
143
|
+
f"metric '{metric.name}': result set is missing columns {missing} "
|
|
144
|
+
f"(have: {sorted(present)}). The query must return the unit key "
|
|
145
|
+
"and every declared column role."
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
seen_units: dict[str, set[str]] = {}
|
|
149
|
+
duplicates = 0
|
|
150
|
+
for row in rows:
|
|
151
|
+
variant = row[variant_col]
|
|
152
|
+
if variant not in declared_variants:
|
|
153
|
+
raise MetricLoadError(
|
|
154
|
+
f"metric '{metric.name}': variant '{variant}' is not declared "
|
|
155
|
+
f"in the experiment ({declared_variants})"
|
|
156
|
+
)
|
|
157
|
+
unit = str(row[unit_col])
|
|
158
|
+
bucket = seen_units.setdefault(variant, set())
|
|
159
|
+
if unit in bucket:
|
|
160
|
+
duplicates += 1
|
|
161
|
+
continue
|
|
162
|
+
bucket.add(unit)
|
|
163
|
+
|
|
164
|
+
result_units.setdefault(variant, []).append(unit)
|
|
165
|
+
roles = result_roles.setdefault(variant, {})
|
|
166
|
+
for role, col in role_map.items():
|
|
167
|
+
if role in ("variant", "stratum"):
|
|
168
|
+
continue
|
|
169
|
+
roles.setdefault(role, []).append(row[col])
|
|
170
|
+
if stratum_col is not None:
|
|
171
|
+
result_strata.setdefault(variant, []).append(row[stratum_col])
|
|
172
|
+
|
|
173
|
+
if duplicates:
|
|
174
|
+
raise MetricLoadError(
|
|
175
|
+
f"metric '{metric.name}': {duplicates} duplicate unit rows — the "
|
|
176
|
+
f"contract is ONE ROW PER UNIT. Did you forget "
|
|
177
|
+
f"GROUP BY {unit_col} in the metric SQL?"
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
# Canonical per-unit order (m3-implementation-plan.md D11): sort every
|
|
181
|
+
# variant's arrays by unit key. Bootstrap replicates index these arrays,
|
|
182
|
+
# so the physical warehouse read order — which ClickHouse does not
|
|
183
|
+
# guarantee — would otherwise leak into persisted numbers. Sorting is an
|
|
184
|
+
# input-assembly fix, not a method change (identical Samples still give
|
|
185
|
+
# identical results); recorded in statistics-changes.md §8.
|
|
186
|
+
order_by_variant = {
|
|
187
|
+
v: sorted(range(len(units)), key=units.__getitem__) for v, units in result_units.items()
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
def _reorder(variant: str, values: list[Any]) -> list[Any]:
|
|
191
|
+
return [values[i] for i in order_by_variant[variant]]
|
|
192
|
+
|
|
193
|
+
units_by_variant = {
|
|
194
|
+
v: np.array(_reorder(v, units), dtype=object) for v, units in result_units.items()
|
|
195
|
+
}
|
|
196
|
+
roles_by_variant = {
|
|
197
|
+
v: {
|
|
198
|
+
role: _to_float_array(_reorder(v, values), role, metric.name)
|
|
199
|
+
for role, values in roles.items()
|
|
200
|
+
}
|
|
201
|
+
for v, roles in result_roles.items()
|
|
202
|
+
}
|
|
203
|
+
strata_by_variant: dict[str, np.ndarray | None] = {
|
|
204
|
+
v: (np.array(_reorder(v, result_strata[v]), dtype=object) if v in result_strata else None)
|
|
205
|
+
for v in units_by_variant
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
return MetricLoadResult(
|
|
209
|
+
metric=metric.name,
|
|
210
|
+
units_by_variant=units_by_variant,
|
|
211
|
+
roles_by_variant=roles_by_variant,
|
|
212
|
+
strata_by_variant=strata_by_variant,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def load_covariate_from_preperiod(
|
|
217
|
+
manager: BaseDatabaseManager,
|
|
218
|
+
metric: MetricConfig,
|
|
219
|
+
metric_sql: str,
|
|
220
|
+
preperiod_builtins: dict[str, Any],
|
|
221
|
+
declared_variants: list[str],
|
|
222
|
+
template: QueryTemplate | None = None,
|
|
223
|
+
) -> dict[str, float]:
|
|
224
|
+
"""The covariate render: the same metric SQL over the pre-period window.
|
|
225
|
+
|
|
226
|
+
``preperiod_builtins`` must carry the ``[start_ts − lookback, start_ts)``
|
|
227
|
+
window and ``ab_apply_exposure_filter=False``. Returns ``{unit: value}``;
|
|
228
|
+
NaNs are dropped (a NULL pre-period value means "no pre-period signal" —
|
|
229
|
+
the join defaults those units to 0.0).
|
|
230
|
+
"""
|
|
231
|
+
if preperiod_builtins.get("ab_apply_exposure_filter", True):
|
|
232
|
+
raise ValueError(
|
|
233
|
+
"covariate render requires ab_apply_exposure_filter=False "
|
|
234
|
+
"(the pre-period precedes exposure by construction)"
|
|
235
|
+
)
|
|
236
|
+
result = load_metric(
|
|
237
|
+
manager, metric, metric_sql, preperiod_builtins, declared_variants, template
|
|
238
|
+
)
|
|
239
|
+
covariate: dict[str, float] = {}
|
|
240
|
+
for variant in result.variants():
|
|
241
|
+
units = result.units_by_variant[variant]
|
|
242
|
+
values = result.roles_by_variant[variant].get("value")
|
|
243
|
+
if values is None:
|
|
244
|
+
raise MetricLoadError(
|
|
245
|
+
f"metric '{metric.name}': the pre-period covariate render needs "
|
|
246
|
+
"a 'value' role (CUPED covariate = the same metric pre-period)"
|
|
247
|
+
)
|
|
248
|
+
for unit, value in zip(units, values, strict=True):
|
|
249
|
+
if not math.isnan(value):
|
|
250
|
+
covariate[unit] = float(value)
|
|
251
|
+
return covariate
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""SQL query templating with Jinja2 — the ``ab_*`` render surface.
|
|
2
|
+
|
|
3
|
+
Renders metric/assignment SQL with the authoritative built-ins table
|
|
4
|
+
(declarative-config.md §5) under ``StrictUndefined`` (an undeclared variable
|
|
5
|
+
hard-fails), and loads the PACKAGED assignment macro
|
|
6
|
+
(``{% import 'abkit_assignment.jinja' as ab %}``) from ``abkit.loaders.templates``
|
|
7
|
+
via ``PackageLoader`` so correctness-critical cohort/window/dedup SQL is never
|
|
8
|
+
hand-repeated.
|
|
9
|
+
|
|
10
|
+
Deliberate deviation from the detectkit donor (recorded in CHANGELOG):
|
|
11
|
+
built-ins WIN over caller context — a context key shadowing ``ab_end_ts``
|
|
12
|
+
would silently change the analysis window, so a collision raises
|
|
13
|
+
:class:`TemplateRenderError` instead.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from datetime import date, datetime, timedelta
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from jinja2 import (
|
|
23
|
+
Environment,
|
|
24
|
+
PackageLoader,
|
|
25
|
+
StrictUndefined,
|
|
26
|
+
TemplateSyntaxError,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TemplateRenderError(Exception):
|
|
31
|
+
"""Raised for template syntax errors, undefined variables, or built-in shadowing."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
#: SQL-safe formats shared by ClickHouse / PostgreSQL / MySQL
|
|
35
|
+
_TS_FORMAT = "%Y-%m-%d %H:%M:%S"
|
|
36
|
+
_DATE_FORMAT = "%Y-%m-%d"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class RenderWindow:
|
|
41
|
+
"""One cumulative window's render-time bounds (naive UTC; end EXCLUSIVE)."""
|
|
42
|
+
|
|
43
|
+
start_ts: datetime
|
|
44
|
+
end_ts: datetime
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def start_date(self) -> date:
|
|
48
|
+
return self.start_ts.date()
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def end_date(self) -> date:
|
|
52
|
+
"""The last date the half-open window covers (partition-pruning bound)."""
|
|
53
|
+
return (self.end_ts - timedelta(microseconds=1)).date()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def build_builtins(
|
|
57
|
+
*,
|
|
58
|
+
experiment_id: str,
|
|
59
|
+
unit_key: str,
|
|
60
|
+
variants: list[str],
|
|
61
|
+
added_filters: str,
|
|
62
|
+
window: RenderWindow,
|
|
63
|
+
data_database: str,
|
|
64
|
+
internal_database: str,
|
|
65
|
+
exposures_table: str,
|
|
66
|
+
dialect: str,
|
|
67
|
+
apply_exposure_filter: bool = True,
|
|
68
|
+
cov_window: RenderWindow | None = None,
|
|
69
|
+
) -> dict[str, Any]:
|
|
70
|
+
"""The authoritative ``ab_*`` built-ins dict (declarative-config.md §5).
|
|
71
|
+
|
|
72
|
+
``apply_exposure_filter=False`` is set by the loader's COVARIATE render:
|
|
73
|
+
the pre-period window precedes exposure by construction, so the
|
|
74
|
+
``event_time >= exposure_ts`` predicate must be dropped there
|
|
75
|
+
(statistics-changes.md §5 fixed-lookback mechanics).
|
|
76
|
+
"""
|
|
77
|
+
builtins: dict[str, Any] = {
|
|
78
|
+
"ab_experiment_id": experiment_id,
|
|
79
|
+
"ab_unit_key": unit_key,
|
|
80
|
+
"ab_variants": list(variants),
|
|
81
|
+
"ab_added_filters": added_filters,
|
|
82
|
+
"ab_start_date": window.start_date.strftime(_DATE_FORMAT),
|
|
83
|
+
"ab_end_date": window.end_date.strftime(_DATE_FORMAT),
|
|
84
|
+
"ab_start_ts": window.start_ts.strftime(_TS_FORMAT),
|
|
85
|
+
"ab_end_ts": window.end_ts.strftime(_TS_FORMAT),
|
|
86
|
+
"data_database": data_database,
|
|
87
|
+
"internal_database": internal_database,
|
|
88
|
+
"ab_exposures_table": f"{internal_database}.{exposures_table}",
|
|
89
|
+
"ab_dialect": dialect,
|
|
90
|
+
"ab_apply_exposure_filter": apply_exposure_filter,
|
|
91
|
+
}
|
|
92
|
+
# Only present when a covariate window exists — otherwise a template
|
|
93
|
+
# referencing ab_cov_* hard-fails under StrictUndefined instead of
|
|
94
|
+
# silently rendering the string 'None' into SQL.
|
|
95
|
+
if cov_window is not None:
|
|
96
|
+
builtins["ab_cov_start"] = cov_window.start_date.strftime(_DATE_FORMAT)
|
|
97
|
+
builtins["ab_cov_end"] = cov_window.end_date.strftime(_DATE_FORMAT)
|
|
98
|
+
return builtins
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class QueryTemplate:
|
|
102
|
+
"""SQL query template renderer using Jinja2 (StrictUndefined always).
|
|
103
|
+
|
|
104
|
+
Example:
|
|
105
|
+
>>> template = QueryTemplate()
|
|
106
|
+
>>> sql = template.render(
|
|
107
|
+
... "SELECT 1 FROM t WHERE ts < '{{ ab_end_ts }}'",
|
|
108
|
+
... builtins,
|
|
109
|
+
... )
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
def __init__(self) -> None:
|
|
113
|
+
# The loader is shared across renders; the Environment is rebuilt per
|
|
114
|
+
# render so the ab_* built-ins can live in env.globals — plain
|
|
115
|
+
# {% import 'abkit_assignment.jinja' as ab %} (no `with context`)
|
|
116
|
+
# resolves names against globals, never the caller's render context.
|
|
117
|
+
self._loader = PackageLoader("abkit.loaders", "templates")
|
|
118
|
+
|
|
119
|
+
def _make_env(self, template_globals: dict[str, Any]) -> Environment:
|
|
120
|
+
env = Environment(
|
|
121
|
+
autoescape=False, # SQL, not HTML
|
|
122
|
+
trim_blocks=True,
|
|
123
|
+
lstrip_blocks=True,
|
|
124
|
+
undefined=StrictUndefined,
|
|
125
|
+
loader=self._loader,
|
|
126
|
+
)
|
|
127
|
+
env.globals.update(template_globals)
|
|
128
|
+
return env
|
|
129
|
+
|
|
130
|
+
def render(
|
|
131
|
+
self,
|
|
132
|
+
query: str,
|
|
133
|
+
builtins: dict[str, Any],
|
|
134
|
+
context: dict[str, Any] | None = None,
|
|
135
|
+
) -> str:
|
|
136
|
+
"""Render a SQL template.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
query: the SQL template text
|
|
140
|
+
builtins: the ``ab_*`` built-ins (:func:`build_builtins`)
|
|
141
|
+
context: optional extra variables; a key colliding with a
|
|
142
|
+
built-in raises (shadowing ``ab_end_ts`` must never be silent)
|
|
143
|
+
|
|
144
|
+
Raises:
|
|
145
|
+
TemplateRenderError: on syntax errors, undefined variables, or
|
|
146
|
+
built-in shadowing
|
|
147
|
+
"""
|
|
148
|
+
template_context = dict(builtins)
|
|
149
|
+
if context:
|
|
150
|
+
collisions = sorted(set(context) & set(builtins))
|
|
151
|
+
if collisions:
|
|
152
|
+
raise TemplateRenderError(
|
|
153
|
+
f"context must not shadow built-ins: {collisions} "
|
|
154
|
+
"(the ab_* window bounds are authoritative)"
|
|
155
|
+
)
|
|
156
|
+
template_context.update(context)
|
|
157
|
+
|
|
158
|
+
try:
|
|
159
|
+
env = self._make_env(template_context)
|
|
160
|
+
template = env.from_string(query)
|
|
161
|
+
return template.render()
|
|
162
|
+
except TemplateSyntaxError as e:
|
|
163
|
+
raise TemplateRenderError(f"Invalid template syntax: {e.message}") from e
|
|
164
|
+
except TemplateRenderError:
|
|
165
|
+
raise
|
|
166
|
+
except Exception as e:
|
|
167
|
+
raise TemplateRenderError(f"Template rendering failed: {e}") from e
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{#-
|
|
2
|
+
The PACKAGED assignment macro (declarative-config.md §4 — the quorum
|
|
3
|
+
"no leaked boilerplate" must-fix). A metric SQL imports it as:
|
|
4
|
+
|
|
5
|
+
{% import 'abkit_assignment.jinja' as ab %}
|
|
6
|
+
|
|
7
|
+
and describes ONLY the metric aggregation; the correctness-critical
|
|
8
|
+
cohort join, window filter and dedup live here, once:
|
|
9
|
+
|
|
10
|
+
- ab.exposed_units() — JOINs the persisted _ab_exposures cohort (loaded
|
|
11
|
+
once per run), deduped per dialect (FINAL on ClickHouse — a mid-merge
|
|
12
|
+
ReplacingMergeTree must never yield a unit twice; PG/MySQL enforce the
|
|
13
|
+
PK), and applies BOTH the coarse event_date predicate (Date partition
|
|
14
|
+
pruning) and the precise half-open event_time window
|
|
15
|
+
(cumulative-intervals.md §6.4). The exposure_ts filter is dropped when
|
|
16
|
+
the loader renders the pre-period covariate window
|
|
17
|
+
(ab_apply_exposure_filter=false — pre-period precedes exposure by
|
|
18
|
+
construction).
|
|
19
|
+
- ab.variant_col() / ab.stratum_col() — arm/stratum labels from the cohort.
|
|
20
|
+
|
|
21
|
+
Collision-proofing: the cohort subquery projects its columns under _abk_-
|
|
22
|
+
prefixed aliases, so a fact table with columns named unit_id/variant/
|
|
23
|
+
exposure_ts/stratum can never be captured by the join. The fact-side unit
|
|
24
|
+
key is cast to a string per dialect (the persisted cohort stores unit ids
|
|
25
|
+
as strings).
|
|
26
|
+
|
|
27
|
+
assignment.added_filters is deliberately NOT injected here: it filters the
|
|
28
|
+
ASSIGNMENT (cohort) query only — silently narrowing every metric's fact
|
|
29
|
+
scan would change numbers invisibly.
|
|
30
|
+
|
|
31
|
+
Validation asserts the rendered SQL joins _ab_exposures; a metric authored
|
|
32
|
+
without this macro fails config-lint.
|
|
33
|
+
-#}
|
|
34
|
+
|
|
35
|
+
{%- macro _unit_key_str() -%}
|
|
36
|
+
{%- if ab_dialect == 'clickhouse' -%}toString({{ ab_unit_key }})
|
|
37
|
+
{%- elif ab_dialect == 'postgres' -%}CAST({{ ab_unit_key }} AS TEXT)
|
|
38
|
+
{%- else -%}CAST({{ ab_unit_key }} AS CHAR){%- endif -%}
|
|
39
|
+
{%- endmacro -%}
|
|
40
|
+
|
|
41
|
+
{%- macro exposed_units(event_date_col='event_date', event_time_col='event_time') -%}
|
|
42
|
+
INNER JOIN (
|
|
43
|
+
SELECT
|
|
44
|
+
unit_id AS _abk_unit_id,
|
|
45
|
+
variant AS _abk_variant,
|
|
46
|
+
exposure_ts AS _abk_exposure_ts,
|
|
47
|
+
stratum AS _abk_stratum
|
|
48
|
+
FROM {{ ab_exposures_table }}{% if ab_dialect == 'clickhouse' %} FINAL{% endif %}
|
|
49
|
+
WHERE experiment = '{{ ab_experiment_id }}'
|
|
50
|
+
) AS _abk_exposures ON _abk_exposures._abk_unit_id = {{ _unit_key_str() }}
|
|
51
|
+
WHERE {{ event_date_col }} >= '{{ ab_start_date }}'
|
|
52
|
+
AND {{ event_date_col }} <= '{{ ab_end_date }}'
|
|
53
|
+
AND {{ event_time_col }} >= '{{ ab_start_ts }}'
|
|
54
|
+
AND {{ event_time_col }} < '{{ ab_end_ts }}'
|
|
55
|
+
{%- if ab_apply_exposure_filter %}
|
|
56
|
+
AND {{ event_time_col }} >= _abk_exposures._abk_exposure_ts
|
|
57
|
+
{%- endif %}
|
|
58
|
+
{%- endmacro -%}
|
|
59
|
+
|
|
60
|
+
{%- macro variant_col() -%}_abk_exposures._abk_variant{%- endmacro -%}
|
|
61
|
+
|
|
62
|
+
{%- macro stratum_col() -%}_abk_exposures._abk_stratum{%- endmacro -%}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""The recompute pipeline: plan → load → SRM → analyze → enrich → persist → readout."""
|
|
2
|
+
|
|
3
|
+
from abkit.pipeline._types import PipelineStep, RunOutcome
|
|
4
|
+
from abkit.pipeline.analyze import (
|
|
5
|
+
AnalyzeError,
|
|
6
|
+
PairOutcome,
|
|
7
|
+
analyze_cutoff,
|
|
8
|
+
comparison_alpha,
|
|
9
|
+
effective_alphas,
|
|
10
|
+
)
|
|
11
|
+
from abkit.pipeline.driver import run_experiment, run_experiments
|
|
12
|
+
from abkit.pipeline.enrich import rows_for_cutoff
|
|
13
|
+
from abkit.pipeline.readout import (
|
|
14
|
+
ExperimentReadout,
|
|
15
|
+
GuardrailStatus,
|
|
16
|
+
PairVerdict,
|
|
17
|
+
)
|
|
18
|
+
from abkit.pipeline.readout import (
|
|
19
|
+
evaluate as evaluate_readout,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"AnalyzeError",
|
|
24
|
+
"ExperimentReadout",
|
|
25
|
+
"GuardrailStatus",
|
|
26
|
+
"PairOutcome",
|
|
27
|
+
"PairVerdict",
|
|
28
|
+
"PipelineStep",
|
|
29
|
+
"RunOutcome",
|
|
30
|
+
"analyze_cutoff",
|
|
31
|
+
"comparison_alpha",
|
|
32
|
+
"effective_alphas",
|
|
33
|
+
"evaluate_readout",
|
|
34
|
+
"rows_for_cutoff",
|
|
35
|
+
"run_experiment",
|
|
36
|
+
"run_experiments",
|
|
37
|
+
]
|
abkit/pipeline/_types.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Shared pipeline types: steps, statuses, outcomes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from enum import Enum
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class PipelineStep(str, Enum):
|
|
10
|
+
"""The selectable ``--steps`` stages (architecture.md §5)."""
|
|
11
|
+
|
|
12
|
+
VALIDATE = "validate"
|
|
13
|
+
PLAN = "plan"
|
|
14
|
+
LOAD = "load"
|
|
15
|
+
COMPUTE = "compute"
|
|
16
|
+
|
|
17
|
+
@classmethod
|
|
18
|
+
def parse(cls, steps: str) -> list[PipelineStep]:
|
|
19
|
+
"""Parse a ``--steps`` string; unknown names raise with the valid list."""
|
|
20
|
+
parsed = []
|
|
21
|
+
for raw in steps.split(","):
|
|
22
|
+
raw = raw.strip().lower()
|
|
23
|
+
if not raw:
|
|
24
|
+
continue
|
|
25
|
+
try:
|
|
26
|
+
parsed.append(cls(raw))
|
|
27
|
+
except ValueError:
|
|
28
|
+
valid = ", ".join(step.value for step in cls)
|
|
29
|
+
raise ValueError(f"unknown step '{raw}' (valid: {valid})") from None
|
|
30
|
+
if not parsed:
|
|
31
|
+
raise ValueError("no steps selected")
|
|
32
|
+
return parsed
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
#: task-status values in ``_ab_tasks``
|
|
36
|
+
STATUS_RUNNING = "running"
|
|
37
|
+
STATUS_COMPLETED = "completed"
|
|
38
|
+
STATUS_FAILED = "failed"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class RunOutcome:
|
|
43
|
+
"""One experiment's run summary (the driver's return value)."""
|
|
44
|
+
|
|
45
|
+
experiment: str
|
|
46
|
+
status: str = "completed" # completed | failed | locked | skipped
|
|
47
|
+
error: str | None = None
|
|
48
|
+
exposures_loaded: int = 0
|
|
49
|
+
srm_flagged: bool = False
|
|
50
|
+
cutoffs_planned: int = 0
|
|
51
|
+
results_written: int = 0
|
|
52
|
+
warnings: list[str] = field(default_factory=list)
|