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,208 @@
|
|
|
1
|
+
"""``abk explore`` — the interactive cockpit shell (WP8; cli-and-dx.md §1).
|
|
2
|
+
|
|
3
|
+
Orchestration only: resolve exactly ONE experiment, guard on a never-run
|
|
4
|
+
project (friendly noop, D2), print the startup orphan warning (the same
|
|
5
|
+
``list_method_config_ids`` scan the driver and ``abk clean`` use), build the
|
|
6
|
+
WP2 report payload + the WP4 session (progress streamed through the house
|
|
7
|
+
``StageLogRenderer``), then either write the static snapshot (``--no-serve``)
|
|
8
|
+
or serve the WP6 localhost cockpit until the user Applies or cancels. All
|
|
9
|
+
failures raise ``click.ClickException`` → non-zero exit (the house rule).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import tempfile
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import click
|
|
19
|
+
|
|
20
|
+
from abkit.cli._output import StageLogRenderer, echo_done, echo_noop
|
|
21
|
+
from abkit.cli.commands._context import load_project_context
|
|
22
|
+
from abkit.config import select_experiments
|
|
23
|
+
from abkit.utils.datetime_utils import now_utc_naive
|
|
24
|
+
|
|
25
|
+
#: session-load stage titles for the run-log tree
|
|
26
|
+
_EXPLORE_STAGE_TITLES = {"SERIES": "SESSION", "CACHE": "CACHE"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _atomic_write_text(path: Path, text: str) -> None:
|
|
30
|
+
"""temp + ``os.replace`` so a mid-write failure never truncates a
|
|
31
|
+
previous good snapshot (the WP3 report-emission precedent)."""
|
|
32
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
33
|
+
fd, tmp_name = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
|
|
34
|
+
try:
|
|
35
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
36
|
+
handle.write(text)
|
|
37
|
+
os.replace(tmp_name, path)
|
|
38
|
+
except BaseException:
|
|
39
|
+
if os.path.exists(tmp_name):
|
|
40
|
+
os.unlink(tmp_name)
|
|
41
|
+
raise
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def run_explore(
|
|
45
|
+
select: tuple[str, ...],
|
|
46
|
+
metric: str | None,
|
|
47
|
+
profile: str | None,
|
|
48
|
+
no_serve: bool,
|
|
49
|
+
no_open: bool,
|
|
50
|
+
) -> None:
|
|
51
|
+
from abkit.compute.recompute_backend import RecomputeBackend
|
|
52
|
+
from abkit.database.internal_tables import InternalTablesManager
|
|
53
|
+
from abkit.reporting import build_report_payload
|
|
54
|
+
from abkit.tuning import (
|
|
55
|
+
RecomputeEngine,
|
|
56
|
+
backend_cutoff_loader,
|
|
57
|
+
build_explore_payload,
|
|
58
|
+
load_session,
|
|
59
|
+
render_explore_html,
|
|
60
|
+
serve_explore,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
context = load_project_context(require_profiles=True)
|
|
64
|
+
selected, selection_warnings = select_experiments(context.root, select)
|
|
65
|
+
for warning in selection_warnings:
|
|
66
|
+
click.echo(click.style(f" ⚠ {warning}", fg="yellow"))
|
|
67
|
+
if not selected:
|
|
68
|
+
raise click.ClickException(
|
|
69
|
+
"no experiment matched — `--select` resolves the experiment "
|
|
70
|
+
"namespace (a name, path glob, tag:<tag>, or *)"
|
|
71
|
+
)
|
|
72
|
+
if len(selected) > 1:
|
|
73
|
+
names = ", ".join(experiment.name for _, experiment in selected)
|
|
74
|
+
raise click.ClickException(
|
|
75
|
+
f"explore serves ONE experiment; the selection matched {len(selected)}: "
|
|
76
|
+
f"{names} — narrow --select"
|
|
77
|
+
)
|
|
78
|
+
experiment_path, experiment = selected[0]
|
|
79
|
+
metrics_by_name = context.metrics_by_name
|
|
80
|
+
|
|
81
|
+
configured_metrics = [comparison.metric for comparison in experiment.comparisons]
|
|
82
|
+
if metric is not None and metric not in configured_metrics:
|
|
83
|
+
raise click.ClickException(
|
|
84
|
+
f"--metric '{metric}' is not a configured comparison of "
|
|
85
|
+
f"'{experiment.name}' (have: {', '.join(configured_metrics)})"
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
click.echo(click.style(f"Explore: {experiment.name}", fg="cyan", bold=True))
|
|
89
|
+
|
|
90
|
+
manager = context.profiles.create_manager(profile)
|
|
91
|
+
try:
|
|
92
|
+
tables = InternalTablesManager(manager)
|
|
93
|
+
|
|
94
|
+
# D2 guard: explore reads persisted rows — a never-run project noops.
|
|
95
|
+
stored_ids = (
|
|
96
|
+
tables.list_method_config_ids(experiment.name)
|
|
97
|
+
if (tables.results_table_exists())
|
|
98
|
+
else {}
|
|
99
|
+
)
|
|
100
|
+
if not stored_ids:
|
|
101
|
+
echo_noop(
|
|
102
|
+
experiment.name,
|
|
103
|
+
f"no computed results yet — run `abk run --select {experiment.name}` first",
|
|
104
|
+
)
|
|
105
|
+
return
|
|
106
|
+
|
|
107
|
+
# Startup orphan warning: the driver-identical scan (cli-and-dx §2).
|
|
108
|
+
configured_ids = {
|
|
109
|
+
comparison.metric: comparison.method.method_config_id
|
|
110
|
+
for comparison in experiment.comparisons
|
|
111
|
+
}
|
|
112
|
+
for metric_name in configured_metrics:
|
|
113
|
+
ids = {mc_id for (m, mc_id) in stored_ids if m == metric_name}
|
|
114
|
+
orphaned = ids - {configured_ids[metric_name]}
|
|
115
|
+
if orphaned:
|
|
116
|
+
click.echo(
|
|
117
|
+
click.style(
|
|
118
|
+
f" ⚠ {experiment.name}/{metric_name}: {len(orphaned)} orphaned "
|
|
119
|
+
"method_config_id series in _ab_results (the BI chart will "
|
|
120
|
+
"show duplicate stabilization lines) — run `abk clean`",
|
|
121
|
+
fg="yellow",
|
|
122
|
+
bold=True,
|
|
123
|
+
)
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
# The one session load pass (D2), streamed in the house tree style.
|
|
127
|
+
renderer = StageLogRenderer(titles=_EXPLORE_STAGE_TITLES)
|
|
128
|
+
|
|
129
|
+
def log(message: str) -> None:
|
|
130
|
+
stage, _, rest = message.partition(" ")
|
|
131
|
+
renderer(stage, rest.strip())
|
|
132
|
+
|
|
133
|
+
metric_sql_by_name = {
|
|
134
|
+
name: metrics_by_name[name].get_query_text(context.root) for name in configured_metrics
|
|
135
|
+
}
|
|
136
|
+
backend = RecomputeBackend(manager, experiment)
|
|
137
|
+
session = load_session(
|
|
138
|
+
experiment,
|
|
139
|
+
metrics_by_name,
|
|
140
|
+
context.project,
|
|
141
|
+
tables,
|
|
142
|
+
loader=backend_cutoff_loader(backend, metric_sql_by_name),
|
|
143
|
+
log=log,
|
|
144
|
+
)
|
|
145
|
+
engine = RecomputeEngine(session)
|
|
146
|
+
|
|
147
|
+
report_payload = build_report_payload(
|
|
148
|
+
experiment,
|
|
149
|
+
tables,
|
|
150
|
+
project=context.project,
|
|
151
|
+
metric_configs=metrics_by_name,
|
|
152
|
+
generated_at=now_utc_naive().strftime("%Y-%m-%d %H:%M UTC"),
|
|
153
|
+
)
|
|
154
|
+
payload = build_explore_payload(session, engine, report_payload)
|
|
155
|
+
if metric is not None:
|
|
156
|
+
payload["explore"]["default_metric"] = metric
|
|
157
|
+
|
|
158
|
+
if no_serve:
|
|
159
|
+
out = context.root / "reports" / f"{experiment.name}__explore.html"
|
|
160
|
+
_atomic_write_text(out, render_explore_html(payload))
|
|
161
|
+
try:
|
|
162
|
+
shown = out.relative_to(Path.cwd())
|
|
163
|
+
except ValueError:
|
|
164
|
+
shown = out
|
|
165
|
+
click.echo(click.style(f" │ Explore snapshot → {shown}", fg="cyan"))
|
|
166
|
+
echo_done("Static explore page written (Apply disabled — serve to tune).")
|
|
167
|
+
return
|
|
168
|
+
|
|
169
|
+
applied = serve_explore(
|
|
170
|
+
payload=payload,
|
|
171
|
+
original_path=experiment_path,
|
|
172
|
+
project_root=context.root,
|
|
173
|
+
session=session,
|
|
174
|
+
engine=engine,
|
|
175
|
+
tables=tables,
|
|
176
|
+
metrics_by_name=metrics_by_name,
|
|
177
|
+
manager_factory=context.manager_factory(profile),
|
|
178
|
+
metric_sql_by_name=metric_sql_by_name,
|
|
179
|
+
open_browser=not no_open,
|
|
180
|
+
echo=click.echo,
|
|
181
|
+
)
|
|
182
|
+
finally:
|
|
183
|
+
manager.close()
|
|
184
|
+
|
|
185
|
+
if applied is None:
|
|
186
|
+
echo_done(f"explore cancelled — {experiment.name} unchanged.")
|
|
187
|
+
return
|
|
188
|
+
|
|
189
|
+
# The Apply epilogue (donor tune.py reshaped): archive, roles, the orphan
|
|
190
|
+
# consequence, and the re-run hint — Apply never auto-runs (D4).
|
|
191
|
+
try:
|
|
192
|
+
archive_shown = applied.archived.relative_to(context.root)
|
|
193
|
+
except ValueError:
|
|
194
|
+
archive_shown = applied.archived
|
|
195
|
+
lines = [f"Archived previous config: {archive_shown}"]
|
|
196
|
+
if applied.updated:
|
|
197
|
+
lines.append(f"Updated comparison(s): {', '.join(applied.updated)}")
|
|
198
|
+
if applied.preserved:
|
|
199
|
+
lines.append(f"Preserved: {', '.join(applied.preserved)}")
|
|
200
|
+
if applied.experiment_fields:
|
|
201
|
+
lines.append(f"Experiment-level: {', '.join(applied.experiment_fields)}")
|
|
202
|
+
for line in lines:
|
|
203
|
+
click.echo(f" │ {line}")
|
|
204
|
+
warning = applied.orphan_warning
|
|
205
|
+
if warning:
|
|
206
|
+
click.echo(click.style(f" ⚠ {warning}", fg="yellow", bold=True))
|
|
207
|
+
click.echo(f" └ Re-run `abk run --select {experiment.name}` to compute the new series.")
|
|
208
|
+
echo_done(f"Applied to {applied.saved}.")
|
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
"""Implementation of ``abk init`` — project scaffolding with a RUNNABLE example.
|
|
2
|
+
|
|
3
|
+
The A/B empty path is longer than detectkit's, so init ships a fully working
|
|
4
|
+
example (cli-and-dx.md §6): ``example_signup_test.yml`` + a real assignment
|
|
5
|
+
SQL + two example metrics (a z-test fraction and a CUPED sample) against a
|
|
6
|
+
documented synthetic seed dataset — so ``abk init && <seed> && abk run
|
|
7
|
+
--select example_signup_test`` produces real results on a fresh machine, not
|
|
8
|
+
a placeholder-table error.
|
|
9
|
+
|
|
10
|
+
Donor discipline kept: every scaffolded artifact ROUND-TRIPS through the real
|
|
11
|
+
pydantic config classes + the level-2 validator before init reports success —
|
|
12
|
+
docs and examples cannot drift from the code (declarative-config.md §5).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import click
|
|
20
|
+
|
|
21
|
+
from abkit.cli._output import echo_done, echo_tree
|
|
22
|
+
|
|
23
|
+
# ── scaffold payloads ─────────────────────────────────────────────────────────
|
|
24
|
+
|
|
25
|
+
PROJECT_YML = """\
|
|
26
|
+
# abkit project configuration (see docs: https://abkit.pipelab.dev)
|
|
27
|
+
name: "{project_name}"
|
|
28
|
+
version: "1.0"
|
|
29
|
+
|
|
30
|
+
default_profile: dev
|
|
31
|
+
|
|
32
|
+
# statistics: # project-wide defaults (experiments override)
|
|
33
|
+
# alpha: 0.05
|
|
34
|
+
# correction: bonferroni
|
|
35
|
+
# power: 0.8
|
|
36
|
+
# limits:
|
|
37
|
+
# max_looks: 5000 # the one hard cadence gate
|
|
38
|
+
# warn_looks: 100 # peeking warning threshold without sequential
|
|
39
|
+
# min_units_per_arm: 100
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
PROFILES_CLICKHOUSE = """\
|
|
43
|
+
default_profile: dev
|
|
44
|
+
|
|
45
|
+
profiles:
|
|
46
|
+
dev:
|
|
47
|
+
type: clickhouse
|
|
48
|
+
host: localhost
|
|
49
|
+
port: 9000
|
|
50
|
+
user: default
|
|
51
|
+
password: ""
|
|
52
|
+
internal_database: abkit_internal # the _ab_* tables live here
|
|
53
|
+
data_database: analytics # your fact tables (and the seed dataset)
|
|
54
|
+
|
|
55
|
+
prod:
|
|
56
|
+
type: clickhouse
|
|
57
|
+
host: "{{{{ env_var('ABKIT_CH_HOST') }}}}"
|
|
58
|
+
port: 9000
|
|
59
|
+
user: "{{{{ env_var('ABKIT_CH_USER') }}}}"
|
|
60
|
+
password: "{{{{ env_var('ABKIT_CH_PASSWORD') }}}}"
|
|
61
|
+
internal_database: abkit_internal
|
|
62
|
+
data_database: analytics
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
PROFILES_POSTGRES = """\
|
|
66
|
+
default_profile: dev
|
|
67
|
+
|
|
68
|
+
profiles:
|
|
69
|
+
dev:
|
|
70
|
+
type: postgres
|
|
71
|
+
host: localhost
|
|
72
|
+
port: 5432
|
|
73
|
+
user: postgres
|
|
74
|
+
password: ""
|
|
75
|
+
database: postgres
|
|
76
|
+
internal_schema: abkit
|
|
77
|
+
data_schema: public
|
|
78
|
+
|
|
79
|
+
prod:
|
|
80
|
+
type: postgres
|
|
81
|
+
host: "{{{{ env_var('ABKIT_PG_HOST') }}}}"
|
|
82
|
+
port: 5432
|
|
83
|
+
user: "{{{{ env_var('ABKIT_PG_USER') }}}}"
|
|
84
|
+
password: "{{{{ env_var('ABKIT_PG_PASSWORD') }}}}"
|
|
85
|
+
database: analytics
|
|
86
|
+
internal_schema: abkit
|
|
87
|
+
data_schema: public
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
PROFILES_MYSQL = """\
|
|
91
|
+
default_profile: dev
|
|
92
|
+
|
|
93
|
+
profiles:
|
|
94
|
+
dev:
|
|
95
|
+
type: mysql
|
|
96
|
+
host: localhost
|
|
97
|
+
port: 3306
|
|
98
|
+
user: root
|
|
99
|
+
password: ""
|
|
100
|
+
internal_database: abkit
|
|
101
|
+
data_database: analytics
|
|
102
|
+
|
|
103
|
+
prod:
|
|
104
|
+
type: mysql
|
|
105
|
+
host: "{{{{ env_var('ABKIT_MYSQL_HOST') }}}}"
|
|
106
|
+
port: 3306
|
|
107
|
+
user: "{{{{ env_var('ABKIT_MYSQL_USER') }}}}"
|
|
108
|
+
password: "{{{{ env_var('ABKIT_MYSQL_PASSWORD') }}}}"
|
|
109
|
+
internal_database: abkit
|
|
110
|
+
data_database: analytics
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
EXPERIMENT_YML = """\
|
|
114
|
+
# The runnable example experiment — works against seed/seed_dataset.*.sql.
|
|
115
|
+
# Fixed past dates keep every daily cutoff complete, so a first run computes
|
|
116
|
+
# the full 14-point stabilization series immediately.
|
|
117
|
+
name: example_signup_test
|
|
118
|
+
description: "Example: onboarding experiment against the synthetic seed dataset"
|
|
119
|
+
status: running
|
|
120
|
+
is_actual: true
|
|
121
|
+
tags: [example]
|
|
122
|
+
|
|
123
|
+
start_date: 2024-07-01 # PINNED left edge of every cumulative window
|
|
124
|
+
end_date: 2024-07-14 # planner horizon (the last cutoff covers this day)
|
|
125
|
+
unit_key: user_id
|
|
126
|
+
cadence: 1d # or dense-early: [{every: 1h, until: 48h}, {every: 1d}]
|
|
127
|
+
timezone: UTC
|
|
128
|
+
|
|
129
|
+
assignment: # READ-ONLY exposure source — abkit never randomizes
|
|
130
|
+
query_file: sql/example_assignment.sql
|
|
131
|
+
variants: [control, treatment] # FIRST is control (name_1)
|
|
132
|
+
expected_split: {control: 0.5, treatment: 0.5} # drives the SRM gate
|
|
133
|
+
|
|
134
|
+
alpha: 0.05
|
|
135
|
+
correction: bonferroni # two-tier: main metric vs the rest (inspectable at run)
|
|
136
|
+
|
|
137
|
+
comparisons:
|
|
138
|
+
- metric: example_signup_cr
|
|
139
|
+
is_main_metric: true # drives the verdict + the two-tier Bonferroni
|
|
140
|
+
method: {name: z-test, params: {test_type: relative, calculate_mde: true}}
|
|
141
|
+
- metric: example_arpu
|
|
142
|
+
method:
|
|
143
|
+
name: cuped-t-test
|
|
144
|
+
params: {test_type: relative, covariate_lookback: 14d}
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
SIGNUP_CR_YML = """\
|
|
148
|
+
name: example_signup_cr
|
|
149
|
+
description: "Example: signup conversion (fraction metric, z-test)"
|
|
150
|
+
type: fraction
|
|
151
|
+
unit_key: user_id
|
|
152
|
+
tags: [example]
|
|
153
|
+
columns: # column roles in the query's result set
|
|
154
|
+
variant: variant
|
|
155
|
+
count: signed_up
|
|
156
|
+
nobs: visits
|
|
157
|
+
sql: |
|
|
158
|
+
{% import 'abkit_assignment.jinja' as ab %}
|
|
159
|
+
-- ONE ROW PER UNIT with additive aggregates over the cumulative window.
|
|
160
|
+
-- The window is PINNED-START / MOVING-END: ab_start_date never moves,
|
|
161
|
+
-- ab_end_ts advances per cutoff — so every run aggregates from experiment
|
|
162
|
+
-- start through the cutoff (the stabilization chart's points).
|
|
163
|
+
-- ab.exposed_units() joins the persisted cohort (_ab_exposures), applies
|
|
164
|
+
-- the window + exposure filters and dedup — never re-implement those.
|
|
165
|
+
SELECT
|
|
166
|
+
{{ ab.variant_col() }} AS variant,
|
|
167
|
+
user_id,
|
|
168
|
+
max(signed_up) AS signed_up, -- converted within the window?
|
|
169
|
+
1 AS visits -- one trial per exposed unit
|
|
170
|
+
FROM {{ data_database }}.example_signup_events
|
|
171
|
+
{{ ab.exposed_units() }}
|
|
172
|
+
GROUP BY variant, user_id
|
|
173
|
+
"""
|
|
174
|
+
|
|
175
|
+
ARPU_YML = """\
|
|
176
|
+
name: example_arpu
|
|
177
|
+
description: "Example: revenue per user (sample metric, CUPED)"
|
|
178
|
+
type: sample
|
|
179
|
+
unit_key: user_id
|
|
180
|
+
tags: [example]
|
|
181
|
+
columns:
|
|
182
|
+
variant: variant
|
|
183
|
+
value: gross_usd
|
|
184
|
+
sql: |
|
|
185
|
+
{% import 'abkit_assignment.jinja' as ab %}
|
|
186
|
+
-- CUPED needs no extra SQL: with covariate_lookback set on the method,
|
|
187
|
+
-- abkit renders THIS SAME query a second time over the pre-period window
|
|
188
|
+
-- (exposure filter dropped) and uses the pre-period value as the covariate.
|
|
189
|
+
SELECT
|
|
190
|
+
{{ ab.variant_col() }} AS variant,
|
|
191
|
+
user_id,
|
|
192
|
+
sum(gross_usd) AS gross_usd -- ADDITIVE: one row per unit
|
|
193
|
+
FROM {{ data_database }}.example_signup_events
|
|
194
|
+
{{ ab.exposed_units() }}
|
|
195
|
+
GROUP BY variant, user_id
|
|
196
|
+
"""
|
|
197
|
+
|
|
198
|
+
ASSIGNMENT_SQL = """\
|
|
199
|
+
-- The assignment (exposure) source: one row per unit with its variant and
|
|
200
|
+
-- first-exposure timestamp. abkit persists this ONCE per run into
|
|
201
|
+
-- _ab_exposures; every metric query joins that cohort via the packaged macro.
|
|
202
|
+
SELECT
|
|
203
|
+
user_id,
|
|
204
|
+
variant,
|
|
205
|
+
exposure_ts
|
|
206
|
+
FROM {{ data_database }}.example_ab_assignments
|
|
207
|
+
WHERE 1 = 1
|
|
208
|
+
{{ ab_added_filters }}
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
SEED_CLICKHOUSE = """\
|
|
212
|
+
-- Synthetic seed dataset for the example experiment (ClickHouse).
|
|
213
|
+
-- Load: clickhouse-client --multiquery < seed/seed_dataset.clickhouse.sql
|
|
214
|
+
-- 600 users, 50/50 split, 14 experiment days + a 14-day pre-period
|
|
215
|
+
-- (the CUPED covariate window). Deterministic: reloading reproduces
|
|
216
|
+
-- identical numbers.
|
|
217
|
+
|
|
218
|
+
CREATE DATABASE IF NOT EXISTS analytics;
|
|
219
|
+
|
|
220
|
+
DROP TABLE IF EXISTS analytics.example_ab_assignments;
|
|
221
|
+
CREATE TABLE analytics.example_ab_assignments
|
|
222
|
+
(
|
|
223
|
+
user_id String,
|
|
224
|
+
variant String,
|
|
225
|
+
exposure_ts DateTime('UTC')
|
|
226
|
+
)
|
|
227
|
+
ENGINE = MergeTree ORDER BY user_id;
|
|
228
|
+
|
|
229
|
+
INSERT INTO analytics.example_ab_assignments
|
|
230
|
+
SELECT
|
|
231
|
+
concat('user_', toString(number)) AS user_id,
|
|
232
|
+
if(number % 2 = 0, 'control', 'treatment') AS variant,
|
|
233
|
+
toDateTime('2024-07-01 08:00:00', 'UTC') AS exposure_ts
|
|
234
|
+
FROM numbers(600);
|
|
235
|
+
|
|
236
|
+
DROP TABLE IF EXISTS analytics.example_signup_events;
|
|
237
|
+
CREATE TABLE analytics.example_signup_events
|
|
238
|
+
(
|
|
239
|
+
user_id String,
|
|
240
|
+
event_date Date,
|
|
241
|
+
event_time DateTime('UTC'),
|
|
242
|
+
signed_up UInt8,
|
|
243
|
+
gross_usd Float64
|
|
244
|
+
)
|
|
245
|
+
ENGINE = MergeTree ORDER BY (event_date, user_id);
|
|
246
|
+
|
|
247
|
+
-- Experiment period (2024-07-01 .. 2024-07-14), one row per user per day.
|
|
248
|
+
-- Conversion is per USER (20% of control vs 25% of treatment convert, each on
|
|
249
|
+
-- their k % 14-th day); treatment also spends ~15% more.
|
|
250
|
+
INSERT INTO analytics.example_signup_events
|
|
251
|
+
SELECT
|
|
252
|
+
concat('user_', toString(number % 600)) AS user_id,
|
|
253
|
+
toDate('2024-07-01') + toIntervalDay(intDiv(number, 600)) AS event_date,
|
|
254
|
+
toDateTime(toDate('2024-07-01') + toIntervalDay(intDiv(number, 600)), 'UTC')
|
|
255
|
+
+ toIntervalHour(12) AS event_time,
|
|
256
|
+
multiIf(
|
|
257
|
+
(number % 600) % 2 = 0
|
|
258
|
+
AND intDiv(number % 600, 2) % 5 = 0
|
|
259
|
+
AND intDiv(number, 600) = intDiv(number % 600, 2) % 14, 1,
|
|
260
|
+
(number % 600) % 2 = 1
|
|
261
|
+
AND intDiv(number % 600, 2) % 4 = 0
|
|
262
|
+
AND intDiv(number, 600) = intDiv(number % 600, 2) % 14, 1,
|
|
263
|
+
0
|
|
264
|
+
) AS signed_up,
|
|
265
|
+
((number % 600) % 7) * 1.5
|
|
266
|
+
* if((number % 600) % 2 = 0, 1.0, 1.15) AS gross_usd
|
|
267
|
+
FROM numbers(600 * 14);
|
|
268
|
+
|
|
269
|
+
-- Pre-period (2024-06-17 .. 2024-06-30): the CUPED covariate source.
|
|
270
|
+
-- No treatment effect before the experiment, by construction.
|
|
271
|
+
INSERT INTO analytics.example_signup_events
|
|
272
|
+
SELECT
|
|
273
|
+
concat('user_', toString(number % 600)) AS user_id,
|
|
274
|
+
toDate('2024-06-17') + toIntervalDay(intDiv(number, 600)) AS event_date,
|
|
275
|
+
toDateTime(toDate('2024-06-17') + toIntervalDay(intDiv(number, 600)), 'UTC')
|
|
276
|
+
+ toIntervalHour(12) AS event_time,
|
|
277
|
+
0 AS signed_up,
|
|
278
|
+
((number % 600) % 7) * 1.4 AS gross_usd
|
|
279
|
+
FROM numbers(600 * 14);
|
|
280
|
+
"""
|
|
281
|
+
|
|
282
|
+
GITIGNORE = """\
|
|
283
|
+
.env
|
|
284
|
+
*.pyc
|
|
285
|
+
__pycache__/
|
|
286
|
+
"""
|
|
287
|
+
|
|
288
|
+
README = """\
|
|
289
|
+
# {project_name}
|
|
290
|
+
|
|
291
|
+
An [ab-analysis-kit](https://abkit.pipelab.dev) project: declarative A/B
|
|
292
|
+
experiment analysis (YAML + SQL) over your warehouse.
|
|
293
|
+
|
|
294
|
+
## Quickstart (the runnable example)
|
|
295
|
+
|
|
296
|
+
1. Load the synthetic seed dataset (ClickHouse):
|
|
297
|
+
|
|
298
|
+
clickhouse-client --multiquery < seed/seed_dataset.clickhouse.sql
|
|
299
|
+
|
|
300
|
+
2. Lint the configs (no database needed):
|
|
301
|
+
|
|
302
|
+
abk run --steps validate
|
|
303
|
+
|
|
304
|
+
3. Run the example experiment:
|
|
305
|
+
|
|
306
|
+
abk run --select example_signup_test
|
|
307
|
+
|
|
308
|
+
This computes the full 14-point cumulative series for both metrics and
|
|
309
|
+
writes it to `abkit_internal._ab_results` — the BI-friendly contract
|
|
310
|
+
table. Re-running is idempotent (already-computed cutoffs are skipped).
|
|
311
|
+
|
|
312
|
+
4. Look at the numbers:
|
|
313
|
+
|
|
314
|
+
SELECT metric, end_date, effect, pvalue, left_bound, right_bound
|
|
315
|
+
FROM abkit_internal._ab_results
|
|
316
|
+
WHERE experiment = 'example_signup_test'
|
|
317
|
+
ORDER BY metric, end_ts
|
|
318
|
+
|
|
319
|
+
## Layout
|
|
320
|
+
|
|
321
|
+
- `abkit_project.yml` — project config (statistical defaults, limits)
|
|
322
|
+
- `profiles.yml` — database connections (secrets via `${{ENV_VAR}}`)
|
|
323
|
+
- `experiments/` — experiment definitions (the PRIMARY entity)
|
|
324
|
+
- `metrics/` — the reusable metric library (YAML + SQL)
|
|
325
|
+
- `sql/` — shared SQL files (assignment sources, metric queries)
|
|
326
|
+
- `seed/` — the synthetic example dataset
|
|
327
|
+
- `runners/` — orchestration examples (Prefect)
|
|
328
|
+
|
|
329
|
+
## Domain rules worth knowing
|
|
330
|
+
|
|
331
|
+
- Every metric query must be ONE ROW PER UNIT and join the cohort via the
|
|
332
|
+
packaged macro (`{{{{ ab.exposed_units() }}}}`) — config-lint enforces it.
|
|
333
|
+
- Check SRM before trusting any effect: a red `SRM FAILED` line means the
|
|
334
|
+
assignment is broken and effects are untrustworthy.
|
|
335
|
+
- The daily cumulative series is peeking-prone: watch it, but decide at the
|
|
336
|
+
horizon (sequential methods arrive as an opt-in).
|
|
337
|
+
- Editing method params orphans the old result series (`abk clean` prunes).
|
|
338
|
+
"""
|
|
339
|
+
|
|
340
|
+
PREFECT_FLOW = '''\
|
|
341
|
+
"""Prefect orchestration example: recompute all actual experiments daily.
|
|
342
|
+
|
|
343
|
+
The CLI is the unit of automation — a Prefect task simply shells out to
|
|
344
|
+
``abk run``; locks are self-healing for unattended runs and failures exit
|
|
345
|
+
non-zero. Requires ``pip install prefect`` (abkit itself never imports it).
|
|
346
|
+
|
|
347
|
+
prefect deploy runners/prefect_flow.py:abkit_daily --cron "0 6 * * *"
|
|
348
|
+
"""
|
|
349
|
+
|
|
350
|
+
import subprocess
|
|
351
|
+
|
|
352
|
+
from prefect import flow, task
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
@task(retries=1)
|
|
356
|
+
def abk_run() -> None:
|
|
357
|
+
subprocess.run(["abk", "run", "--select", "tag:actual"], check=True)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
@flow(name="abkit-daily")
|
|
361
|
+
def abkit_daily() -> None:
|
|
362
|
+
abk_run()
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
if __name__ == "__main__":
|
|
366
|
+
abkit_daily()
|
|
367
|
+
'''
|
|
368
|
+
|
|
369
|
+
PROFILES_BY_DB = {
|
|
370
|
+
"clickhouse": PROFILES_CLICKHOUSE,
|
|
371
|
+
"postgres": PROFILES_POSTGRES,
|
|
372
|
+
"mysql": PROFILES_MYSQL,
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def run_init(project_name: str, target_dir: str, db_type: str = "clickhouse") -> None:
|
|
377
|
+
root = Path(target_dir) / project_name
|
|
378
|
+
if root.exists():
|
|
379
|
+
raise click.ClickException(f"directory already exists: {root} (init refuses to overwrite)")
|
|
380
|
+
|
|
381
|
+
files: dict[str, str] = {
|
|
382
|
+
"abkit_project.yml": PROJECT_YML.format(project_name=project_name),
|
|
383
|
+
"profiles.yml": PROFILES_BY_DB[db_type],
|
|
384
|
+
".gitignore": GITIGNORE,
|
|
385
|
+
"README.md": README.format(project_name=project_name),
|
|
386
|
+
"experiments/example_signup_test.yml": EXPERIMENT_YML,
|
|
387
|
+
"metrics/example_signup_cr.yml": SIGNUP_CR_YML,
|
|
388
|
+
"metrics/example_arpu.yml": ARPU_YML,
|
|
389
|
+
"sql/example_assignment.sql": ASSIGNMENT_SQL,
|
|
390
|
+
"seed/seed_dataset.clickhouse.sql": SEED_CLICKHOUSE,
|
|
391
|
+
"runners/prefect_flow.py": PREFECT_FLOW,
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
for rel_path, content in files.items():
|
|
395
|
+
path = root / rel_path
|
|
396
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
397
|
+
path.write_text(content)
|
|
398
|
+
|
|
399
|
+
# Round-trip: every scaffolded artifact through the REAL config classes +
|
|
400
|
+
# the level-2 validator (macro lint, method instantiation, looks gates) —
|
|
401
|
+
# the scaffold cannot drift from the code.
|
|
402
|
+
from abkit.config import (
|
|
403
|
+
ProfilesConfig,
|
|
404
|
+
ProjectConfig,
|
|
405
|
+
validate_level2,
|
|
406
|
+
validate_project_configs,
|
|
407
|
+
)
|
|
408
|
+
|
|
409
|
+
try:
|
|
410
|
+
project = ProjectConfig.from_yaml_file(root / "abkit_project.yml")
|
|
411
|
+
ProfilesConfig.from_yaml(root / "profiles.yml")
|
|
412
|
+
experiments, metrics = validate_project_configs(root, project)
|
|
413
|
+
report = validate_level2(root, project, experiments, metrics)
|
|
414
|
+
if not report.ok:
|
|
415
|
+
raise ValueError("; ".join(report.errors))
|
|
416
|
+
except Exception as exc: # pragma: no cover - a scaffold bug, not user error
|
|
417
|
+
raise click.ClickException(
|
|
418
|
+
f"scaffold failed its own validation (this is an abkit bug): {exc}"
|
|
419
|
+
) from exc
|
|
420
|
+
|
|
421
|
+
echo_tree(f"{project_name}/", list(files))
|
|
422
|
+
echo_done(
|
|
423
|
+
f"Project '{project_name}' created ({db_type}). Next:\n"
|
|
424
|
+
f" 1. cd {project_name}\n"
|
|
425
|
+
" 2. load the seed dataset (see README.md)\n"
|
|
426
|
+
" 3. abk run --select example_signup_test"
|
|
427
|
+
)
|