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.
Files changed (122) hide show
  1. ab_analysis_kit-0.0.1.dev0.dist-info/METADATA +126 -0
  2. ab_analysis_kit-0.0.1.dev0.dist-info/RECORD +122 -0
  3. ab_analysis_kit-0.0.1.dev0.dist-info/WHEEL +5 -0
  4. ab_analysis_kit-0.0.1.dev0.dist-info/entry_points.txt +2 -0
  5. ab_analysis_kit-0.0.1.dev0.dist-info/licenses/LICENSE +21 -0
  6. ab_analysis_kit-0.0.1.dev0.dist-info/top_level.txt +1 -0
  7. abkit/__init__.py +40 -0
  8. abkit/cli/__init__.py +1 -0
  9. abkit/cli/_output.py +111 -0
  10. abkit/cli/commands/__init__.py +1 -0
  11. abkit/cli/commands/_context.py +83 -0
  12. abkit/cli/commands/clean.py +133 -0
  13. abkit/cli/commands/explore.py +208 -0
  14. abkit/cli/commands/init.py +427 -0
  15. abkit/cli/commands/run.py +282 -0
  16. abkit/cli/commands/unlock.py +59 -0
  17. abkit/cli/commands/validate.py +264 -0
  18. abkit/cli/main.py +279 -0
  19. abkit/compute/__init__.py +5 -0
  20. abkit/compute/recompute_backend.py +140 -0
  21. abkit/config/__init__.py +51 -0
  22. abkit/config/discovery.py +168 -0
  23. abkit/config/experiment_config.py +511 -0
  24. abkit/config/method_config.py +80 -0
  25. abkit/config/metric_config.py +214 -0
  26. abkit/config/profile.py +301 -0
  27. abkit/config/project_config.py +244 -0
  28. abkit/config/validator.py +393 -0
  29. abkit/core/__init__.py +26 -0
  30. abkit/core/interval.py +148 -0
  31. abkit/core/models.py +121 -0
  32. abkit/core/period_planner.py +206 -0
  33. abkit/database/__init__.py +51 -0
  34. abkit/database/_sql_manager.py +432 -0
  35. abkit/database/clickhouse_manager.py +495 -0
  36. abkit/database/internal_tables/__init__.py +6 -0
  37. abkit/database/internal_tables/_aa_runs.py +53 -0
  38. abkit/database/internal_tables/_base.py +71 -0
  39. abkit/database/internal_tables/_experiments.py +82 -0
  40. abkit/database/internal_tables/_exposures.py +163 -0
  41. abkit/database/internal_tables/_maintenance.py +72 -0
  42. abkit/database/internal_tables/_results.py +231 -0
  43. abkit/database/internal_tables/_schema.py +23 -0
  44. abkit/database/internal_tables/_tasks.py +237 -0
  45. abkit/database/internal_tables/_unit_state.py +148 -0
  46. abkit/database/internal_tables/manager.py +30 -0
  47. abkit/database/manager.py +450 -0
  48. abkit/database/mysql_manager.py +175 -0
  49. abkit/database/postgres_manager.py +145 -0
  50. abkit/database/tables.py +326 -0
  51. abkit/loaders/__init__.py +28 -0
  52. abkit/loaders/exposure_loader.py +121 -0
  53. abkit/loaders/metric_loader.py +251 -0
  54. abkit/loaders/query_template.py +167 -0
  55. abkit/loaders/templates/abkit_assignment.jinja +62 -0
  56. abkit/pipeline/__init__.py +37 -0
  57. abkit/pipeline/_types.py +52 -0
  58. abkit/pipeline/analyze.py +223 -0
  59. abkit/pipeline/driver.py +477 -0
  60. abkit/pipeline/enrich.py +137 -0
  61. abkit/pipeline/readout.py +779 -0
  62. abkit/reporting/__init__.py +19 -0
  63. abkit/reporting/assets/report.js +138 -0
  64. abkit/reporting/builder.py +484 -0
  65. abkit/reporting/calibration.py +182 -0
  66. abkit/reporting/html_report.py +109 -0
  67. abkit/stats/__init__.py +94 -0
  68. abkit/stats/accumulate.py +82 -0
  69. abkit/stats/base.py +347 -0
  70. abkit/stats/bootstrap/__init__.py +69 -0
  71. abkit/stats/bootstrap/applier.py +81 -0
  72. abkit/stats/bootstrap/bootstrap.py +311 -0
  73. abkit/stats/bootstrap/ci.py +72 -0
  74. abkit/stats/bootstrap/engine.py +383 -0
  75. abkit/stats/bootstrap/paired_bootstrap.py +57 -0
  76. abkit/stats/bootstrap/paired_post_normed_bootstrap.py +81 -0
  77. abkit/stats/bootstrap/poisson_bootstrap.py +112 -0
  78. abkit/stats/bootstrap/post_normed_bootstrap.py +102 -0
  79. abkit/stats/correction.py +88 -0
  80. abkit/stats/effects.py +141 -0
  81. abkit/stats/exceptions.py +31 -0
  82. abkit/stats/factory.py +26 -0
  83. abkit/stats/parametric/__init__.py +10 -0
  84. abkit/stats/parametric/cuped_ttest.py +183 -0
  85. abkit/stats/parametric/paired_cuped_ttest.py +125 -0
  86. abkit/stats/parametric/paired_ttest.py +136 -0
  87. abkit/stats/parametric/ratio_delta.py +113 -0
  88. abkit/stats/parametric/ttest.py +105 -0
  89. abkit/stats/parametric/ztest.py +134 -0
  90. abkit/stats/power.py +278 -0
  91. abkit/stats/registry.py +111 -0
  92. abkit/stats/result.py +84 -0
  93. abkit/stats/rng.py +39 -0
  94. abkit/stats/samples.py +531 -0
  95. abkit/stats/sequential/__init__.py +18 -0
  96. abkit/stats/sequential/apply.py +37 -0
  97. abkit/stats/sequential/confidence_sequence.py +96 -0
  98. abkit/stats/sequential/mixture.py +70 -0
  99. abkit/stats/srm.py +221 -0
  100. abkit/tuning/__init__.py +59 -0
  101. abkit/tuning/assets/explore.js +173 -0
  102. abkit/tuning/config_writer.py +409 -0
  103. abkit/tuning/html.py +88 -0
  104. abkit/tuning/payload.py +122 -0
  105. abkit/tuning/recompute.py +1039 -0
  106. abkit/tuning/server.py +882 -0
  107. abkit/tuning/session.py +233 -0
  108. abkit/utils/__init__.py +27 -0
  109. abkit/utils/datetime_utils.py +97 -0
  110. abkit/utils/env_interpolation.py +50 -0
  111. abkit/utils/json_utils.py +38 -0
  112. abkit/validate/__init__.py +36 -0
  113. abkit/validate/_types.py +35 -0
  114. abkit/validate/inject.py +75 -0
  115. abkit/validate/load.py +160 -0
  116. abkit/validate/panel.py +59 -0
  117. abkit/validate/persistence.py +59 -0
  118. abkit/validate/resample.py +94 -0
  119. abkit/validate/result.py +60 -0
  120. abkit/validate/run_id.py +45 -0
  121. abkit/validate/runner.py +389 -0
  122. abkit/validate/scoring.py +544 -0
abkit/cli/main.py ADDED
@@ -0,0 +1,279 @@
1
+ """``abk`` — the ab-analysis-kit command-line interface.
2
+
3
+ dbt-like commands over declarative experiment/metric YAML (cli-and-dx.md §1).
4
+ Command bodies import lazily so ``abk --version`` stays instant and no DB
5
+ driver is required until a command actually needs one. Failures exit NON-ZERO
6
+ — the CLI is the Prefect unit of automation (a deliberate, recorded deviation
7
+ from the detectkit donor's swallow-and-return-0 behaviour).
8
+
9
+ Surface: ``init``, ``run``, ``unlock``, ``clean`` (M2) + ``explore`` (M3).
10
+ The remaining commands (``validate``, ``plan``, ``init-claude``,
11
+ ``test-report``) land per ROADMAP.md M4–M6.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import click
17
+
18
+ from abkit import __version__
19
+
20
+
21
+ @click.group()
22
+ @click.version_option(__version__, prog_name="abk")
23
+ def cli() -> None:
24
+ """ab-analysis-kit — declarative A/B experiment analysis.
25
+
26
+ Examples:
27
+ abk init my_ab_project
28
+ abk run --select signup_test
29
+ abk run --steps validate
30
+ abk run --select tag:actual
31
+
32
+ Docs: https://abkit.pipelab.dev
33
+ """
34
+
35
+
36
+ @cli.command()
37
+ @click.argument("project_name")
38
+ @click.option(
39
+ "--target-dir",
40
+ "-d",
41
+ default=".",
42
+ help="Directory to create the project in (default: current directory)",
43
+ )
44
+ @click.option(
45
+ "--db-type",
46
+ type=click.Choice(["clickhouse", "postgres", "mysql"]),
47
+ default="clickhouse",
48
+ show_default=True,
49
+ help="Database backend to scaffold the profiles and example SQL for.",
50
+ )
51
+ def init(project_name: str, target_dir: str, db_type: str) -> None:
52
+ """Initialize a new abkit project (with a runnable example experiment).
53
+
54
+ Creates abkit_project.yml, profiles.yml, experiments/, metrics/, sql/
55
+ and a seed-dataset example so `abk run --select example_signup_test`
56
+ produces real results on a fresh machine.
57
+ """
58
+ from abkit.cli.commands.init import run_init
59
+
60
+ run_init(project_name, target_dir, db_type=db_type)
61
+
62
+
63
+ @cli.command()
64
+ @click.option(
65
+ "--select",
66
+ "-s",
67
+ multiple=True,
68
+ help="Experiment selector: name, path glob, tag:<tag>, or * (repeatable; default all)",
69
+ )
70
+ @click.option("--exclude", multiple=True, help="Selectors to exclude (same forms)")
71
+ @click.option(
72
+ "--steps",
73
+ default="validate,plan,load,compute",
74
+ show_default=True,
75
+ help="Comma-separated pipeline steps. 'validate' alone = config-lint, no DB.",
76
+ )
77
+ @click.option("--profile", help="Profile name (default: profiles.yml default_profile)")
78
+ @click.option("--from", "from_ts", help="Full-refresh window start (with --full-refresh)")
79
+ @click.option("--to", "to_ts", help="Full-refresh window end, exclusive (with --full-refresh)")
80
+ @click.option(
81
+ "--full-refresh",
82
+ is_flag=True,
83
+ help="Re-open already-computed cutoffs in [--from, --to) and recompute them",
84
+ )
85
+ @click.option("--force", is_flag=True, help="Take over a held lock (use with care)")
86
+ @click.option(
87
+ "--workers",
88
+ default=1,
89
+ show_default=True,
90
+ help="Worker threads across experiments (each gets its own DB connection)",
91
+ )
92
+ @click.option(
93
+ "--report",
94
+ "report_path",
95
+ is_flag=False,
96
+ flag_value="",
97
+ default=None,
98
+ help=(
99
+ "After the run, emit a self-contained HTML readout per experiment "
100
+ "(best-effort — never fails the run). Optional value: an output file "
101
+ "or directory; defaults to reports/<experiment>.html."
102
+ ),
103
+ )
104
+ def run(
105
+ select: tuple[str, ...],
106
+ exclude: tuple[str, ...],
107
+ steps: str,
108
+ profile: str | None,
109
+ from_ts: str | None,
110
+ to_ts: str | None,
111
+ full_refresh: bool,
112
+ force: bool,
113
+ workers: int,
114
+ report_path: str | None,
115
+ ) -> None:
116
+ """Run the pipeline: validate → plan → load → SRM → compute → persist."""
117
+ from abkit.cli.commands.run import run_run
118
+
119
+ run_run(
120
+ select,
121
+ exclude,
122
+ steps,
123
+ profile,
124
+ from_ts,
125
+ to_ts,
126
+ full_refresh,
127
+ force,
128
+ workers,
129
+ report_path,
130
+ )
131
+
132
+
133
+ @cli.command()
134
+ @click.option(
135
+ "--select",
136
+ "-s",
137
+ multiple=True,
138
+ help="Experiment selector — must match exactly ONE experiment",
139
+ )
140
+ @click.option("--metric", help="Open the cockpit on this comparison (default: the main metric)")
141
+ @click.option("--profile", help="Profile name (default: profiles.yml default_profile)")
142
+ @click.option(
143
+ "--no-serve",
144
+ is_flag=True,
145
+ help="Write a static snapshot to reports/<experiment>__explore.html instead of serving",
146
+ )
147
+ @click.option("--no-open", is_flag=True, help="Do not launch a browser (the URL still prints)")
148
+ def explore(
149
+ select: tuple[str, ...],
150
+ metric: str | None,
151
+ profile: str | None,
152
+ no_serve: bool,
153
+ no_open: bool,
154
+ ) -> None:
155
+ """Serve the interactive explore cockpit for one experiment.
156
+
157
+ Reads the persisted results (run `abk run` first), lets you tune method
158
+ knobs live against a localhost page, and — only on an explicit Apply —
159
+ writes the tuned config back to the experiment YAML (the previous file is
160
+ archived under experiments/.history/).
161
+ """
162
+ from abkit.cli.commands.explore import run_explore
163
+
164
+ run_explore(select, metric, profile, no_serve, no_open)
165
+
166
+
167
+ @cli.command()
168
+ @click.option(
169
+ "--select",
170
+ "-s",
171
+ multiple=True,
172
+ help="Experiment selector — name, path glob, tag:<tag>, or * (repeatable; default all)",
173
+ )
174
+ @click.option(
175
+ "--method",
176
+ "-m",
177
+ multiple=True,
178
+ help="Extra registered method(s) to score beyond the declared comparison (repeatable)",
179
+ )
180
+ @click.option("--metric", help="Validate only this metric (default: every declared comparison)")
181
+ @click.option(
182
+ "--iterations", "-n", default=2000, show_default=True, help="Placebo A/A splits per cell"
183
+ )
184
+ @click.option(
185
+ "--inject-effect",
186
+ type=float,
187
+ default=None,
188
+ help="Inject this relative effect (e.g. 0.05) to measure power / achieved MDE / coverage",
189
+ )
190
+ @click.option(
191
+ "--scoring",
192
+ type=click.Choice(["fpr", "power", "mde"]),
193
+ default="fpr",
194
+ show_default=True,
195
+ help="Selection objective for the 'Recommended' row (all columns are always computed)",
196
+ )
197
+ @click.option(
198
+ "--report",
199
+ "report_path",
200
+ is_flag=False,
201
+ flag_value="",
202
+ default=None,
203
+ help=(
204
+ "Emit a self-contained HTML matrix report (best-effort). Optional value: an "
205
+ "output file or directory; defaults to reports/<experiment>__validate.html."
206
+ ),
207
+ )
208
+ @click.option("--force", is_flag=True, help="Take over a held validate lock (use with care)")
209
+ @click.option("--profile", help="Profile name (default: profiles.yml default_profile)")
210
+ def validate(
211
+ select: tuple[str, ...],
212
+ method: tuple[str, ...],
213
+ metric: str | None,
214
+ iterations: int,
215
+ inject_effect: float | None,
216
+ scoring: str,
217
+ report_path: str | None,
218
+ force: bool,
219
+ profile: str | None,
220
+ ) -> None:
221
+ """Score each method's empirical false-positive rate on placebo A/A splits.
222
+
223
+ Out-of-band from `abk run`: measures whether each method is actually calibrated
224
+ on this data (FPR ≈ α?), the honest cumulative-peeking FPR, power, achieved MDE,
225
+ and CI coverage — persisted to `_ab_aa_runs` so the explore calibration chip
226
+ lights. `--report` writes the matrix as a self-contained HTML page.
227
+ """
228
+ from abkit.cli.commands.validate import run_validate
229
+
230
+ run_validate(
231
+ select, method, metric, iterations, inject_effect, scoring, report_path, force, profile
232
+ )
233
+
234
+
235
+ @cli.command()
236
+ @click.option(
237
+ "--select",
238
+ "-s",
239
+ multiple=True,
240
+ help="Experiment selector (name, glob, tag:<tag>, *; default all)",
241
+ )
242
+ @click.option("--profile", help="Profile name (default: profiles.yml default_profile)")
243
+ def unlock(select: tuple[str, ...], profile: str | None) -> None:
244
+ """Clear stale pipeline locks left by a run that died."""
245
+ from abkit.cli.commands.unlock import run_unlock
246
+
247
+ run_unlock(select, profile)
248
+
249
+
250
+ @cli.command()
251
+ @click.option(
252
+ "--select",
253
+ "-s",
254
+ multiple=True,
255
+ help="Experiment selector (name, glob, tag:<tag>, *; default all)",
256
+ )
257
+ @click.option(
258
+ "--orphaned-experiments",
259
+ is_flag=True,
260
+ help="Purge experiments that have DB rows but no YAML in the project",
261
+ )
262
+ @click.option("--execute", is_flag=True, help="Apply the changes (default: dry run)")
263
+ @click.option("--yes", is_flag=True, help="Skip the per-experiment purge confirmation")
264
+ @click.option("--profile", help="Profile name (default: profiles.yml default_profile)")
265
+ def clean(
266
+ select: tuple[str, ...],
267
+ orphaned_experiments: bool,
268
+ execute: bool,
269
+ yes: bool,
270
+ profile: str | None,
271
+ ) -> None:
272
+ """Prune orphaned result series (method_config_id drift) and removed experiments."""
273
+ from abkit.cli.commands.clean import run_clean
274
+
275
+ run_clean(select, orphaned_experiments, execute, yes, profile)
276
+
277
+
278
+ if __name__ == "__main__":
279
+ cli()
@@ -0,0 +1,5 @@
1
+ """Compute backends: v1 recompute (golden reference); v2 incremental deferred."""
2
+
3
+ from abkit.compute.recompute_backend import RecomputeBackend, dialect_of
4
+
5
+ __all__ = ["RecomputeBackend", "dialect_of"]
@@ -0,0 +1,140 @@
1
+ """The v1 compute strategy: full-window recompute (the golden reference).
2
+
3
+ Each cutoff re-renders the metric SQL over the FULL cumulative window
4
+ ``[start_ts, end_ts)`` and re-executes it — cumulative-intervals.md §4:
5
+ correctness-first, made cheap-to-skip by the planner anti-join, with the
6
+ warehouse cohort persisted once (the macro joins ``_ab_exposures``). The v2
7
+ incremental backend (reading ``_ab_unit_state`` moments) is deferred behind
8
+ ``abk verify-incremental``.
9
+
10
+ The CUPED covariate is loaded ONCE per (comparison, run) — the fixed
11
+ whole-day lookback window ``[start_ts − lookback, start_ts)`` never moves
12
+ with the cutoff (statistics-changes.md §5) — and attached to every cutoff's
13
+ load.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from datetime import timedelta
19
+ from typing import Any
20
+ from zoneinfo import ZoneInfo
21
+
22
+ from abkit.config.experiment_config import ComparisonConfig, ExperimentConfig
23
+ from abkit.config.metric_config import MetricConfig
24
+ from abkit.core.interval import Interval
25
+ from abkit.core.period_planner import Cutoff, Grid, tz_midnight_utc
26
+ from abkit.database.manager import BaseDatabaseManager
27
+ from abkit.loaders.metric_loader import (
28
+ MetricLoadResult,
29
+ load_covariate_from_preperiod,
30
+ load_metric,
31
+ )
32
+ from abkit.loaders.query_template import QueryTemplate, RenderWindow, build_builtins
33
+
34
+
35
+ def dialect_of(manager: BaseDatabaseManager) -> str:
36
+ """The ``ab_dialect`` built-in from the concrete manager class."""
37
+ name = type(manager).__name__.lower()
38
+ if "clickhouse" in name:
39
+ return "clickhouse"
40
+ if "postgres" in name:
41
+ return "postgres"
42
+ if "mysql" in name:
43
+ return "mysql"
44
+ return "clickhouse" # fixture/unknown backends get the richest dialect
45
+
46
+
47
+ class RecomputeBackend:
48
+ """Loads one comparison's data per cutoff by full-window recomputation."""
49
+
50
+ def __init__(
51
+ self,
52
+ manager: BaseDatabaseManager,
53
+ experiment: ExperimentConfig,
54
+ exposures_table: str = "_ab_exposures",
55
+ ) -> None:
56
+ self._manager = manager
57
+ self._experiment = experiment
58
+ self._exposures_table = exposures_table
59
+ self._template = QueryTemplate()
60
+ self._covariate_cache: dict[str, dict[str, float]] = {}
61
+
62
+ def _builtins(
63
+ self,
64
+ window: RenderWindow,
65
+ apply_exposure_filter: bool = True,
66
+ cov_window: RenderWindow | None = None,
67
+ ) -> dict[str, Any]:
68
+ experiment = self._experiment
69
+ return build_builtins(
70
+ experiment_id=experiment.name,
71
+ unit_key=experiment.unit_key,
72
+ variants=experiment.assignment.variants,
73
+ added_filters=experiment.assignment.added_filters,
74
+ window=window,
75
+ data_database=self._manager.data_location,
76
+ internal_database=self._manager.internal_location,
77
+ exposures_table=self._exposures_table,
78
+ dialect=dialect_of(self._manager),
79
+ apply_exposure_filter=apply_exposure_filter,
80
+ cov_window=cov_window,
81
+ )
82
+
83
+ def _preperiod_window(self, lookback: str | int, grid: Grid) -> RenderWindow:
84
+ """The fixed pre-period, WHOLE-DAY aligned in the experiment timezone.
85
+
86
+ ``[tz-midnight(start_date − lookback_days), start_ts)`` — day
87
+ arithmetic in the experiment tz (a UTC-seconds subtraction would
88
+ misalign local days across a DST transition inside the lookback;
89
+ statistics-changes.md §5 defines the lookback in whole days).
90
+ """
91
+ lookback_days = Interval(lookback).seconds // 86400
92
+ zone = ZoneInfo(self._experiment.timezone)
93
+ pre_start = tz_midnight_utc(
94
+ self._experiment.start_date - timedelta(days=lookback_days), zone
95
+ )
96
+ return RenderWindow(start_ts=pre_start, end_ts=grid.start_ts)
97
+
98
+ def render(self, metric_sql: str, window: RenderWindow) -> str:
99
+ """The provenance copy of the executed SQL."""
100
+ return self._template.render(metric_sql, self._builtins(window))
101
+
102
+ def load_cutoff(
103
+ self,
104
+ comparison: ComparisonConfig,
105
+ metric: MetricConfig,
106
+ metric_sql: str,
107
+ grid: Grid,
108
+ cutoff: Cutoff,
109
+ ) -> MetricLoadResult:
110
+ """Load one (comparison, cutoff): full window + cached covariate."""
111
+ window = RenderWindow(start_ts=grid.start_ts, end_ts=cutoff.end_ts)
112
+ lookback = comparison.method.covariate_lookback
113
+ pre_window = (
114
+ self._preperiod_window(lookback, grid)
115
+ if lookback is not None and metric.columns.covariate is None
116
+ else None
117
+ )
118
+ loaded = load_metric(
119
+ self._manager,
120
+ metric,
121
+ metric_sql,
122
+ self._builtins(window, cov_window=pre_window),
123
+ declared_variants=self._experiment.assignment.variants,
124
+ template=self._template,
125
+ )
126
+
127
+ if pre_window is not None:
128
+ covariate = self._covariate_cache.get(metric.name)
129
+ if covariate is None:
130
+ covariate = load_covariate_from_preperiod(
131
+ self._manager,
132
+ metric,
133
+ metric_sql,
134
+ self._builtins(pre_window, apply_exposure_filter=False, cov_window=pre_window),
135
+ declared_variants=self._experiment.assignment.variants,
136
+ template=self._template,
137
+ )
138
+ self._covariate_cache[metric.name] = covariate
139
+ loaded.attach_covariate(covariate)
140
+ return loaded
@@ -0,0 +1,51 @@
1
+ """Declarative configuration for abkit (YAML models + validation)."""
2
+
3
+ from abkit.config.discovery import (
4
+ find_project_root,
5
+ select_configs,
6
+ select_experiments,
7
+ )
8
+ from abkit.config.experiment_config import (
9
+ AssignmentConfig,
10
+ CadenceSegment,
11
+ ComparisonConfig,
12
+ ExperimentConfig,
13
+ SequentialConfig,
14
+ )
15
+ from abkit.config.method_config import MethodConfig
16
+ from abkit.config.metric_config import MetricColumnsConfig, MetricConfig
17
+ from abkit.config.profile import ProfileConfig, ProfilesConfig
18
+ from abkit.config.project_config import ProjectConfig
19
+ from abkit.config.validator import (
20
+ ValidationReport,
21
+ discover_config_files,
22
+ is_discoverable_config_file,
23
+ validate_config_uniqueness,
24
+ validate_experiment_level2,
25
+ validate_level2,
26
+ validate_project_configs,
27
+ )
28
+
29
+ __all__ = [
30
+ "AssignmentConfig",
31
+ "CadenceSegment",
32
+ "ComparisonConfig",
33
+ "ExperimentConfig",
34
+ "MethodConfig",
35
+ "MetricColumnsConfig",
36
+ "MetricConfig",
37
+ "ProfileConfig",
38
+ "ProfilesConfig",
39
+ "ProjectConfig",
40
+ "SequentialConfig",
41
+ "ValidationReport",
42
+ "discover_config_files",
43
+ "find_project_root",
44
+ "is_discoverable_config_file",
45
+ "select_configs",
46
+ "select_experiments",
47
+ "validate_config_uniqueness",
48
+ "validate_experiment_level2",
49
+ "validate_level2",
50
+ "validate_project_configs",
51
+ ]
@@ -0,0 +1,168 @@
1
+ """Project-root discovery + the two-level selector.
2
+
3
+ Hoisted out of the CLI (the donor kept it inside ``run.py``) so ``abk run``,
4
+ ``abk explore``, ``abk clean`` and the validator share ONE selection seam.
5
+
6
+ Two-level semantics (cli-and-dx.md §1 — detectkit users will assume the
7
+ one-level model): ``--select`` resolves EXPERIMENTS only; metrics are chosen
8
+ with the distinct ``--metric`` flag. Selector forms: an experiment name, a
9
+ path glob (``experiments/growth/*.yml``), ``tag:<tag>``, or ``*``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from pathlib import Path
15
+ from typing import TypeVar
16
+
17
+ import yaml
18
+
19
+ from abkit.config.experiment_config import ExperimentConfig
20
+ from abkit.config.metric_config import MetricConfig
21
+ from abkit.config.validator import (
22
+ discover_config_files,
23
+ is_discoverable_config_file,
24
+ validate_config_uniqueness,
25
+ )
26
+
27
+ PROJECT_FILE = "abkit_project.yml"
28
+
29
+ C = TypeVar("C", ExperimentConfig, MetricConfig)
30
+
31
+
32
+ def find_project_root(start: Path | None = None) -> Path | None:
33
+ """Find the abkit project root by walking up from *start* (default cwd).
34
+
35
+ Searches up to 10 levels for ``abkit_project.yml``.
36
+ """
37
+ current = (start or Path.cwd()).resolve()
38
+ for _ in range(10):
39
+ if (current / PROJECT_FILE).exists():
40
+ return current
41
+ if current.parent == current:
42
+ break
43
+ current = current.parent
44
+ return None
45
+
46
+
47
+ def _find_by_name(base_dir: Path, name: str) -> Path | None:
48
+ """Recursive search by the ``name:`` field (cheap YAML peek)."""
49
+ for path in discover_config_files(base_dir):
50
+ try:
51
+ with open(path) as f:
52
+ data = yaml.safe_load(f)
53
+ except Exception:
54
+ continue
55
+ if isinstance(data, dict) and data.get("name") == name:
56
+ return path
57
+ return None
58
+
59
+
60
+ def find_by_tag(base_dir: Path, tag: str) -> tuple[list[Path], list[str]]:
61
+ """All live configs carrying *tag*; returns (paths, skip-warnings)."""
62
+ matching: list[Path] = []
63
+ skipped: list[str] = []
64
+ for path in discover_config_files(base_dir):
65
+ try:
66
+ with open(path) as f:
67
+ data = yaml.safe_load(f)
68
+ except Exception as e:
69
+ skipped.append(f"Skipping {path}: {e}")
70
+ continue
71
+ if isinstance(data, dict) and tag in (data.get("tags") or []):
72
+ matching.append(path)
73
+ return matching, skipped
74
+
75
+
76
+ def select_configs(
77
+ selector: str,
78
+ project_root: Path,
79
+ base_dir_name: str,
80
+ config_cls: type[C],
81
+ namespace: str,
82
+ ) -> tuple[list[tuple[Path, C]], list[str]]:
83
+ """Resolve one selector against a config directory.
84
+
85
+ Selector types (donor semantics, ``.history`` always excluded):
86
+ - name: ``signup_test`` (file name first, then recursive ``name:`` search)
87
+ - path pattern: ``experiments/growth/*.yml`` (or relative to the dir)
88
+ - tag: ``tag:actual``
89
+ - ``*``: everything
90
+
91
+ Returns (selected configs uniqueness-checked, warnings).
92
+ """
93
+ base_dir = project_root / base_dir_name
94
+ if not base_dir.exists():
95
+ return [], []
96
+
97
+ warnings: list[str] = []
98
+ paths: list[Path] = []
99
+
100
+ if selector.startswith("tag:"):
101
+ paths, warnings = find_by_tag(base_dir, selector[4:])
102
+ elif "*" in selector or "/" in selector:
103
+ if selector == "*":
104
+ paths = discover_config_files(base_dir)
105
+ else:
106
+ pattern = (
107
+ selector
108
+ if selector.startswith(f"{base_dir_name}/")
109
+ else f"{base_dir_name}/{selector}"
110
+ )
111
+ paths = [
112
+ p for p in project_root.glob(pattern) if is_discoverable_config_file(p, base_dir)
113
+ ]
114
+ else:
115
+ for suffix in (".yml", ".yaml"):
116
+ candidate = base_dir / f"{selector}{suffix}"
117
+ if candidate.exists():
118
+ paths = [candidate]
119
+ break
120
+ else:
121
+ found = _find_by_name(base_dir, selector)
122
+ if found:
123
+ paths = [found]
124
+
125
+ if not paths:
126
+ return [], warnings
127
+ return validate_config_uniqueness(sorted(set(paths)), config_cls, namespace), warnings
128
+
129
+
130
+ def select_experiments(
131
+ project_root: Path,
132
+ select: tuple[str, ...],
133
+ exclude: tuple[str, ...] = (),
134
+ experiments_dir: str = "experiments",
135
+ ) -> tuple[list[tuple[Path, ExperimentConfig]], list[str]]:
136
+ """Resolve ``--select``/``--exclude`` to a unique experiment list.
137
+
138
+ No selectors means ``*``. Every selection error names the namespace: an
139
+ unmatched selector reminds that ``--select`` resolves experiments and
140
+ metrics need ``--metric``.
141
+ """
142
+ selectors = select or ("*",)
143
+ chosen: dict[str, tuple[Path, ExperimentConfig]] = {}
144
+ warnings: list[str] = []
145
+
146
+ for selector in selectors:
147
+ found, warns = select_configs(
148
+ selector, project_root, experiments_dir, ExperimentConfig, "experiment"
149
+ )
150
+ warnings.extend(warns)
151
+ if not found:
152
+ warnings.append(
153
+ f"selector '{selector}' matched no experiments "
154
+ f"(--select resolves the experiment namespace; use --metric for metrics)"
155
+ )
156
+ for path, config in found:
157
+ chosen[config.name] = (path, config)
158
+
159
+ for selector in exclude:
160
+ found, warns = select_configs(
161
+ selector, project_root, experiments_dir, ExperimentConfig, "experiment"
162
+ )
163
+ warnings.extend(warns)
164
+ for _, config in found:
165
+ chosen.pop(config.name, None)
166
+
167
+ ordered = sorted(chosen.values(), key=lambda pair: pair[1].name)
168
+ return ordered, warnings