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
@@ -0,0 +1,244 @@
1
+ """
2
+ Project configuration models.
3
+
4
+ Defines configuration structure for abkit_project.yml.
5
+ """
6
+
7
+ from pathlib import Path
8
+ from typing import Literal
9
+
10
+ from pydantic import BaseModel, Field, field_validator, model_validator
11
+
12
+
13
+ class ProjectPathsConfig(BaseModel):
14
+ """
15
+ Project directory paths configuration.
16
+
17
+ Attributes:
18
+ experiments: Directory containing experiment YAML files
19
+ metrics: Directory containing metric YAML files
20
+ sql: Directory containing SQL query files
21
+ """
22
+
23
+ experiments: str = Field(default="experiments", description="Experiments directory")
24
+ metrics: str = Field(default="metrics", description="Metrics directory")
25
+ sql: str = Field(default="sql", description="SQL files directory")
26
+
27
+
28
+ class ProjectTablesConfig(BaseModel):
29
+ """Internal table names (the six ``_ab_*`` tables).
30
+
31
+ Overrides are NOT supported yet: the internal-tables mixins are keyed by
32
+ the canonical constants, so a renamed table would split the read and
33
+ write paths. The block exists (and validates) so the config surface is
34
+ stable when renaming lands.
35
+ """
36
+
37
+ experiments: str = Field(default="_ab_experiments")
38
+ exposures: str = Field(default="_ab_exposures")
39
+ unit_state: str = Field(default="_ab_unit_state")
40
+ results: str = Field(default="_ab_results")
41
+ aa_runs: str = Field(default="_ab_aa_runs")
42
+ tasks: str = Field(default="_ab_tasks")
43
+
44
+ @model_validator(mode="after")
45
+ def reject_overrides(self) -> "ProjectTablesConfig":
46
+ for name, field in type(self).model_fields.items():
47
+ if getattr(self, name) != field.default:
48
+ raise ValueError(
49
+ f"tables.{name}: internal table name overrides are not "
50
+ "supported yet (the _ab_* names are canonical)"
51
+ )
52
+ return self
53
+
54
+
55
+ class ProjectTimeoutsConfig(BaseModel):
56
+ """
57
+ Default timeout values for operations (in seconds).
58
+
59
+ Attributes:
60
+ load: Timeout for exposure/metric loading operations
61
+ compute: Timeout for the statistical compute stage (also the run-lock
62
+ staleness threshold)
63
+ """
64
+
65
+ load: int = Field(default=3600, description="Load timeout (seconds)")
66
+ compute: int = Field(default=7200, description="Compute timeout (seconds)")
67
+
68
+ @field_validator("load", "compute")
69
+ @classmethod
70
+ def validate_timeout(cls, v: int) -> int:
71
+ """Validate timeout value."""
72
+ if v < 1:
73
+ raise ValueError("Timeout must be at least 1 second")
74
+ if v > 86400: # 24 hours
75
+ raise ValueError("Timeout cannot exceed 24 hours (86400 seconds)")
76
+ return v
77
+
78
+
79
+ class ProjectStatisticsConfig(BaseModel):
80
+ """Project-wide statistical defaults (experiment fields override).
81
+
82
+ ``alpha``/``correction`` feed the inspectable two-tier scheme
83
+ (declarative-config.md §6); ``aa_fpr_budget`` colours the A/A matrix
84
+ (M4); nothing here enters ``method_config_id``.
85
+ """
86
+
87
+ alpha: float = Field(default=0.05, description="Default significance level")
88
+ test_type: Literal["relative", "absolute"] = Field(default="relative")
89
+ correction: Literal["none", "bonferroni", "benjamini_hochberg"] = Field(
90
+ default="bonferroni", description="Default multiple-testing correction"
91
+ )
92
+ power: float = Field(default=0.8, description="Default target power for MDE")
93
+ aa_fpr_budget: float | None = Field(
94
+ default=None,
95
+ description="A/A false-positive budget the validate matrix colours against",
96
+ )
97
+
98
+ @field_validator("alpha", "power")
99
+ @classmethod
100
+ def validate_fraction(cls, v: float) -> float:
101
+ if not 0.0 < v < 1.0:
102
+ raise ValueError(f"must be a fraction in (0, 1), got {v}")
103
+ return v
104
+
105
+ @field_validator("aa_fpr_budget")
106
+ @classmethod
107
+ def validate_budget(cls, v: float | None) -> float | None:
108
+ if v is not None and not 0.0 < v <= 1.0:
109
+ raise ValueError(f"aa_fpr_budget must be a fraction in (0, 1], got {v}")
110
+ return v
111
+
112
+
113
+ class ProjectLimitsConfig(BaseModel):
114
+ """Look-count and small-sample gates (cumulative-intervals.md §6.1).
115
+
116
+ ``max_looks`` is the ONE hard cadence gate (there is deliberately no time
117
+ floor); ``warn_looks`` triggers the peeking warning without
118
+ ``sequential.enabled``; ``min_units_per_arm`` drives the
119
+ ``insufficient_data`` demotion (row written, inference withheld).
120
+ """
121
+
122
+ max_looks: int = Field(default=5000, description="Planned looks above this = config error")
123
+ warn_looks: int = Field(
124
+ default=100, description="Looks above this without sequential = peeking warning"
125
+ )
126
+ min_units_per_arm: int = Field(
127
+ default=100, description="Below this the row is demoted to insufficient_data"
128
+ )
129
+
130
+ @field_validator("max_looks", "warn_looks", "min_units_per_arm")
131
+ @classmethod
132
+ def validate_positive(cls, v: int) -> int:
133
+ if v < 1:
134
+ raise ValueError(f"must be at least 1, got {v}")
135
+ return v
136
+
137
+
138
+ class ProjectComputeConfig(BaseModel):
139
+ """Compute backend selection. v1 ships recompute only; ``incremental`` is
140
+ the v2 path gated behind ``abk verify-incremental`` (cumulative-intervals §4)."""
141
+
142
+ mode: Literal["recompute"] = Field(
143
+ default="recompute",
144
+ description="v1: full-window recompute (the golden reference). "
145
+ "'incremental' arrives in v2 behind verify-incremental.",
146
+ )
147
+
148
+
149
+ class ProjectConfig(BaseModel):
150
+ """
151
+ Project configuration loaded from abkit_project.yml.
152
+
153
+ Example YAML:
154
+ ```yaml
155
+ name: "my_ab_project"
156
+ version: "1.0"
157
+
158
+ paths:
159
+ experiments: "experiments"
160
+ metrics: "metrics"
161
+ sql: "sql"
162
+
163
+ statistics:
164
+ alpha: 0.05
165
+ test_type: relative
166
+ correction: bonferroni
167
+ power: 0.8
168
+
169
+ limits:
170
+ max_looks: 5000
171
+ warn_looks: 100
172
+ min_units_per_arm: 100
173
+
174
+ timeouts:
175
+ load: 3600
176
+ compute: 7200
177
+
178
+ default_profile: "clickhouse_prod"
179
+ ```
180
+ """
181
+
182
+ name: str = Field(..., description="Project name")
183
+ version: str = Field(default="1.0", description="Project version")
184
+ paths: ProjectPathsConfig = Field(
185
+ default_factory=ProjectPathsConfig, description="Directory paths"
186
+ )
187
+ tables: ProjectTablesConfig = Field(
188
+ default_factory=ProjectTablesConfig, description="Default table names"
189
+ )
190
+ timeouts: ProjectTimeoutsConfig = Field(
191
+ default_factory=ProjectTimeoutsConfig, description="Operation timeouts"
192
+ )
193
+ statistics: ProjectStatisticsConfig = Field(
194
+ default_factory=ProjectStatisticsConfig, description="Statistical defaults"
195
+ )
196
+ limits: ProjectLimitsConfig = Field(
197
+ default_factory=ProjectLimitsConfig, description="Look-count / small-n gates"
198
+ )
199
+ compute: ProjectComputeConfig = Field(
200
+ default_factory=ProjectComputeConfig, description="Compute backend"
201
+ )
202
+ default_profile: str = Field(..., description="Default database profile")
203
+
204
+ @field_validator("name")
205
+ @classmethod
206
+ def validate_name(cls, v: str) -> str:
207
+ """Validate project name."""
208
+ if not v:
209
+ raise ValueError("Project name cannot be empty")
210
+ # Allow alphanumeric, underscore, dash, space
211
+ if not all(c.isalnum() or c in ("_", "-", " ") for c in v):
212
+ raise ValueError(
213
+ "Project name can only contain alphanumeric characters, "
214
+ "underscores, dashes, and spaces"
215
+ )
216
+ return v
217
+
218
+ @classmethod
219
+ def from_yaml_file(cls, path: Path) -> "ProjectConfig":
220
+ """
221
+ Load project configuration from YAML file.
222
+
223
+ Args:
224
+ path: Path to abkit_project.yml
225
+
226
+ Returns:
227
+ ProjectConfig instance
228
+
229
+ Raises:
230
+ FileNotFoundError: If file doesn't exist
231
+ ValueError: If YAML is invalid
232
+ """
233
+ import yaml
234
+
235
+ if not path.exists():
236
+ raise FileNotFoundError(f"Project config file not found: {path}")
237
+
238
+ with open(path) as f:
239
+ data = yaml.safe_load(f)
240
+
241
+ if not data:
242
+ raise ValueError(f"Empty project config file: {path}")
243
+
244
+ return cls.model_validate(data)
@@ -0,0 +1,393 @@
1
+ """Config validation.
2
+
3
+ Level 1: discovery + name uniqueness — parameterized by (directory, config
4
+ class) so experiments and metrics share one engine.
5
+
6
+ Level 2 (:func:`validate_level2`): the full declarative-config.md §8 matrix —
7
+ reference integrity, method-params-by-instantiation, CUPED covariate rules,
8
+ the cadence/looks gates (through the SAME grid enumeration the planner uses —
9
+ plan R1), and the no-DB SQL render smoke incl. the macro-usage lint. Runs
10
+ under ``abk run --steps validate`` without touching any database.
11
+
12
+ Namespace rule (cli-and-dx.md §1): experiment and metric names share ONE
13
+ namespace, so every uniqueness error names both files and the namespace —
14
+ detectkit users will assume the one-level model.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+ from typing import Protocol, TypeVar
22
+
23
+ from abkit.config.experiment_config import DAY_SECONDS, ExperimentConfig
24
+ from abkit.config.metric_config import MetricConfig
25
+ from abkit.config.project_config import ProjectConfig
26
+ from abkit.core.interval import Interval
27
+ from abkit.core.period_planner import GridLimitExceeded, generate_grid
28
+
29
+
30
+ class _NamedConfig(Protocol):
31
+ name: str
32
+
33
+
34
+ C = TypeVar("C", bound=_NamedConfig)
35
+
36
+
37
+ def is_discoverable_config_file(path: Path, base_dir: Path) -> bool:
38
+ """True for a *live* config YAML — excludes hidden dirs (``.history/``).
39
+
40
+ ``abk explore`` (M3) archives the previous config under
41
+ ``<dir>/.history/<name>/`` before writing the tuned version in place.
42
+ Those snapshots keep the original ``name:``, so discovering them as live
43
+ configs would flag every tuned config as a duplicate-name conflict and run
44
+ stale configs. Python's ``pathlib`` glob traverses hidden directories
45
+ (unlike shell globbing), so they must be filtered explicitly. Any hidden
46
+ path component *under* ``base_dir`` is skipped — this covers ``.history``
47
+ and editor/VCS scratch dirs, while a project rooted under a dot-directory
48
+ (checked only below ``base_dir``) is unaffected.
49
+ """
50
+ if not path.is_file() or path.suffix not in (".yml", ".yaml"):
51
+ return False
52
+ try:
53
+ parts = path.relative_to(base_dir).parts
54
+ except ValueError:
55
+ parts = path.parts
56
+ return not any(part.startswith(".") for part in parts)
57
+
58
+
59
+ def discover_config_files(base_dir: Path) -> list[Path]:
60
+ """All live config YAMLs under *base_dir* (recursive), ``.history`` excluded.
61
+
62
+ The single discovery seam shared by project validation and CLI selection,
63
+ so the exclusion can't drift between them. Sorted for determinism.
64
+ """
65
+ files = [
66
+ p
67
+ for pattern in ("**/*.yml", "**/*.yaml")
68
+ for p in base_dir.glob(pattern)
69
+ if is_discoverable_config_file(p, base_dir)
70
+ ]
71
+ return sorted(set(files))
72
+
73
+
74
+ def validate_config_uniqueness(
75
+ config_paths: list[Path],
76
+ config_cls: type[C],
77
+ namespace: str,
78
+ ) -> list[tuple[Path, C]]:
79
+ """Load every config and enforce unique names within *namespace*.
80
+
81
+ Raises ValueError naming BOTH conflicting files and the namespace, with
82
+ the parse error chained when a file fails validation.
83
+ """
84
+ configs: list[tuple[Path, C]] = []
85
+ seen_names: dict[str, Path] = {}
86
+
87
+ for config_path in config_paths:
88
+ try:
89
+ config = config_cls.from_yaml_file(config_path) # type: ignore[attr-defined]
90
+ except Exception as e:
91
+ raise ValueError(f"Failed to parse {namespace} config at {config_path}:\n{e}") from e
92
+
93
+ if config.name in seen_names:
94
+ conflicting_path = seen_names[config.name]
95
+ raise ValueError(
96
+ f"Duplicate {namespace} name '{config.name}' found:\n"
97
+ f" - {conflicting_path}\n"
98
+ f" - {config_path}\n\n"
99
+ f"{namespace.capitalize()} names must be unique across the project."
100
+ )
101
+
102
+ seen_names[config.name] = config_path
103
+ configs.append((config_path, config))
104
+
105
+ return configs
106
+
107
+
108
+ def validate_project_configs(
109
+ project_root: Path,
110
+ project_config: ProjectConfig | None = None,
111
+ ) -> tuple[list[tuple[Path, ExperimentConfig]], list[tuple[Path, MetricConfig]]]:
112
+ """Discover + parse + uniqueness-check all experiments and metrics.
113
+
114
+ Level-1 validation:
115
+ 1. Discover live YAMLs under ``experiments/`` and ``metrics/``.
116
+ 2. Parse each (pydantic fail-fast — all intra-file rules run here).
117
+ 3. Names unique within each namespace.
118
+ 4. Cross-namespace collision rule: experiment and metric names share ONE
119
+ namespace (an experiment named like a metric breaks two-level
120
+ selection) — the error names both files.
121
+
122
+ Returns:
123
+ (experiments, metrics) as lists of (path, config) tuples.
124
+ """
125
+ paths = (project_config or ProjectConfig(name="x", default_profile="x")).paths
126
+ experiments_dir = project_root / paths.experiments
127
+ metrics_dir = project_root / paths.metrics
128
+
129
+ for directory, kind in ((experiments_dir, "experiments"), (metrics_dir, "metrics")):
130
+ if not directory.exists():
131
+ raise FileNotFoundError(
132
+ f"{kind.capitalize()} directory not found: {directory}\n"
133
+ f"Expected structure:\n"
134
+ f" {project_root}/\n"
135
+ f" {paths.experiments}/\n"
136
+ f" {paths.metrics}/\n"
137
+ )
138
+
139
+ experiment_paths = discover_config_files(experiments_dir)
140
+ if not experiment_paths:
141
+ raise ValueError(
142
+ f"No experiment files found in {experiments_dir}\n"
143
+ f"Expected at least one *.yml or *.yaml file."
144
+ )
145
+ metric_paths = discover_config_files(metrics_dir)
146
+ if not metric_paths:
147
+ raise ValueError(
148
+ f"No metric files found in {metrics_dir}\n"
149
+ f"Expected at least one *.yml or *.yaml file."
150
+ )
151
+
152
+ experiments = validate_config_uniqueness(experiment_paths, ExperimentConfig, "experiment")
153
+ metrics = validate_config_uniqueness(metric_paths, MetricConfig, "metric")
154
+
155
+ # Cross-namespace collision: one shared namespace (cli-and-dx §1).
156
+ metric_names = {config.name: path for path, config in metrics}
157
+ for exp_path, exp_config in experiments:
158
+ if exp_config.name in metric_names:
159
+ raise ValueError(
160
+ f"Name '{exp_config.name}' is used by BOTH an experiment and a metric:\n"
161
+ f" - experiment: {exp_path}\n"
162
+ f" - metric: {metric_names[exp_config.name]}\n\n"
163
+ "Experiment and metric names share one namespace "
164
+ "(two-level selection would be ambiguous) — rename one of them."
165
+ )
166
+
167
+ return experiments, metrics
168
+
169
+
170
+ # ── level 2: the declarative-config.md §8 matrix ─────────────────────────────
171
+
172
+
173
+ @dataclass
174
+ class ValidationReport:
175
+ """Collected level-2 findings; errors block, warnings are surfaced."""
176
+
177
+ errors: list[str] = field(default_factory=list)
178
+ warnings: list[str] = field(default_factory=list)
179
+
180
+ @property
181
+ def ok(self) -> bool:
182
+ return not self.errors
183
+
184
+ def extend(self, other: ValidationReport) -> None:
185
+ self.errors.extend(other.errors)
186
+ self.warnings.extend(other.warnings)
187
+
188
+
189
+ def validate_experiment_level2(
190
+ experiment: ExperimentConfig,
191
+ metrics_by_name: dict[str, MetricConfig],
192
+ project: ProjectConfig,
193
+ project_root: Path | None = None,
194
+ experiment_path: Path | None = None,
195
+ ) -> ValidationReport:
196
+ """The §8 battery for one experiment (no DB, no compute)."""
197
+ report = ValidationReport()
198
+ where = f"experiment '{experiment.name}'" + (f" ({experiment_path})" if experiment_path else "")
199
+
200
+ # ── reference integrity + per-comparison method/metric rules ────────────
201
+ for comparison in experiment.comparisons:
202
+ label = f"{where}, comparison '{comparison.metric}'"
203
+ metric = metrics_by_name.get(comparison.metric)
204
+ if metric is None:
205
+ report.errors.append(
206
+ f"{label}: no metric named '{comparison.metric}' in the metrics/ "
207
+ f"library (known: {sorted(metrics_by_name)})"
208
+ )
209
+ continue
210
+
211
+ # unit-key consistency (omitted metric unit_key inherits)
212
+ if metric.unit_key is not None and metric.unit_key != experiment.unit_key:
213
+ report.errors.append(
214
+ f"{label}: metric.unit_key '{metric.unit_key}' != experiment."
215
+ f"unit_key '{experiment.unit_key}' (must match or be omitted)"
216
+ )
217
+
218
+ # method params validated BY INSTANTIATION (one path; quarantine and
219
+ # bad params fail here, at validate time, not at run time)
220
+ try:
221
+ comparison.method.bind(alpha=project.statistics.alpha)
222
+ except Exception as exc:
223
+ report.errors.append(f"{label}: method '{comparison.method.name}': {exc}")
224
+ continue
225
+
226
+ # capability lint (plan R8): the same declarative attributes analyze.py
227
+ # dispatches on must gate at VALIDATE time, not at run time
228
+ from abkit.stats import get_method_class
229
+
230
+ method_cls = get_method_class(comparison.method.name)
231
+ if method_cls.is_paired:
232
+ report.errors.append(
233
+ f"{label}: '{comparison.method.name}' is a paired design — "
234
+ "the v1 pipeline serves independent-arm experiments "
235
+ "(use the notebook API for paired data)"
236
+ )
237
+ continue
238
+ if method_cls.input_kind != metric.type:
239
+ report.errors.append(
240
+ f"{label}: method '{comparison.method.name}' expects a "
241
+ f"'{method_cls.input_kind}' metric, got '{metric.type}'"
242
+ )
243
+ continue
244
+
245
+ # CUPED covariate rules (statistics-changes §5; cumulative-intervals §6.5)
246
+ lookback = comparison.method.covariate_lookback
247
+ is_cuped = "cuped" in comparison.method.name
248
+ if is_cuped:
249
+ if metric.type != "sample":
250
+ report.errors.append(
251
+ f"{label}: CUPED needs a 'sample' metric (the covariate is the "
252
+ f"same metric over the pre-period), got type '{metric.type}'"
253
+ )
254
+ if lookback is None and metric.columns.covariate is None:
255
+ report.errors.append(
256
+ f"{label}: CUPED needs a covariate — set method params."
257
+ "covariate_lookback (pre-period render) or a metric "
258
+ "columns.covariate"
259
+ )
260
+ # (a non-CUPED method with covariate_lookback already failed bind()
261
+ # above — only CUPED methods declare the param in their schema)
262
+ if lookback is not None:
263
+ try:
264
+ lookback_seconds = Interval(lookback).seconds
265
+ except (ValueError, TypeError) as exc:
266
+ report.errors.append(f"{label}: bad covariate_lookback: {exc}")
267
+ else:
268
+ if lookback_seconds < DAY_SECONDS:
269
+ report.errors.append(
270
+ f"{label}: covariate_lookback < 1d is an error (the fixed "
271
+ "lookback is whole days — statistics-changes §5)"
272
+ )
273
+ elif lookback_seconds % DAY_SECONDS != 0:
274
+ report.errors.append(
275
+ f"{label}: covariate_lookback must be WHOLE days "
276
+ "(statistics-changes §5), got a fractional-day duration"
277
+ )
278
+ elif lookback_seconds < 7 * DAY_SECONDS:
279
+ report.warnings.append(
280
+ f"{label}: covariate_lookback < 7d — the covariate won't "
281
+ "cover a weekly cycle (diurnal/weekday confounding)"
282
+ )
283
+
284
+ # ── cadence & looks gates (through the planner's own enumeration) ───────
285
+ try:
286
+ grid = generate_grid(
287
+ experiment.start_date,
288
+ experiment.end_date,
289
+ experiment.cadence_segments(),
290
+ tz=experiment.timezone,
291
+ limit=project.limits.max_looks,
292
+ )
293
+ except GridLimitExceeded as exc:
294
+ report.errors.append(f"{where}: {exc}")
295
+ grid = None
296
+ if grid is not None and len(grid) > project.limits.warn_looks:
297
+ if not experiment.sequential.enabled:
298
+ report.warnings.append(
299
+ f"{where}: {len(grid)} planned looks with fixed-horizon CIs — "
300
+ f"peeking risk (warn_looks={project.limits.warn_looks}). "
301
+ "sequential: {enabled: true, scheme: always_valid} lets you "
302
+ "decide earlier at any look; `abk validate` measures this "
303
+ "grid's real A/A FPR."
304
+ )
305
+ for every, _ in experiment.cadence_segments():
306
+ if every < DAY_SECONDS and DAY_SECONDS % every != 0:
307
+ report.warnings.append(
308
+ f"{where}: 24h is not a multiple of the {every}s cadence — the "
309
+ "grid drifts across midnight (diurnal composition oscillates "
310
+ "across looks; daily BI rollups misalign)"
311
+ )
312
+
313
+ # ── SQL render smoke (StrictUndefined, no DB) + macro-usage lint ────────
314
+ report.extend(_render_smoke(experiment, metrics_by_name, project_root))
315
+
316
+ return report
317
+
318
+
319
+ def _render_smoke(
320
+ experiment: ExperimentConfig,
321
+ metrics_by_name: dict[str, MetricConfig],
322
+ project_root: Path | None,
323
+ ) -> ValidationReport:
324
+ """Render every SQL under fixture built-ins; assert the macro join."""
325
+ from abkit.loaders.query_template import QueryTemplate, RenderWindow, build_builtins
326
+
327
+ report = ValidationReport()
328
+ template = QueryTemplate()
329
+ from datetime import datetime, timedelta
330
+
331
+ start = datetime.combine(experiment.start_date, datetime.min.time())
332
+ builtins = build_builtins(
333
+ experiment_id=experiment.name,
334
+ unit_key=experiment.unit_key,
335
+ variants=experiment.assignment.variants,
336
+ added_filters=experiment.assignment.added_filters,
337
+ window=RenderWindow(start_ts=start, end_ts=start + timedelta(days=1)),
338
+ data_database="__data__",
339
+ internal_database="__internal__",
340
+ exposures_table="_ab_exposures",
341
+ dialect="clickhouse",
342
+ )
343
+
344
+ try:
345
+ assignment_sql = experiment.assignment.get_query_text(project_root)
346
+ rendered = template.render(assignment_sql, builtins)
347
+ except Exception as exc:
348
+ report.errors.append(f"experiment '{experiment.name}': assignment SQL: {exc}")
349
+ else:
350
+ for token in (experiment.unit_key, "variant", "exposure_ts"):
351
+ if token not in rendered:
352
+ report.errors.append(
353
+ f"experiment '{experiment.name}': assignment SQL must SELECT "
354
+ f"'{token}' (unit_key, variant, exposure_ts are the exposure "
355
+ "contract)"
356
+ )
357
+
358
+ for comparison in experiment.comparisons:
359
+ metric = metrics_by_name.get(comparison.metric)
360
+ if metric is None:
361
+ continue # already reported
362
+ try:
363
+ metric_sql = metric.get_query_text(project_root)
364
+ rendered = template.render(metric_sql, builtins)
365
+ except Exception as exc:
366
+ report.errors.append(f"metric '{comparison.metric}': {exc}")
367
+ continue
368
+ if "_abk_exposures" not in rendered:
369
+ report.errors.append(
370
+ f"metric '{comparison.metric}': rendered SQL does not join the "
371
+ "persisted cohort — import the packaged macro "
372
+ "({% import 'abkit_assignment.jinja' as ab %} … "
373
+ "{{ ab.exposed_units() }}); hand-rolled cohort logic fails "
374
+ "config-lint"
375
+ )
376
+
377
+ return report
378
+
379
+
380
+ def validate_level2(
381
+ project_root: Path,
382
+ project: ProjectConfig,
383
+ experiments: list[tuple[Path, ExperimentConfig]],
384
+ metrics: list[tuple[Path, MetricConfig]],
385
+ ) -> ValidationReport:
386
+ """Run the §8 battery over every experiment (``abk run --steps validate``)."""
387
+ metrics_by_name = {config.name: config for _, config in metrics}
388
+ report = ValidationReport()
389
+ for path, experiment in experiments:
390
+ report.extend(
391
+ validate_experiment_level2(experiment, metrics_by_name, project, project_root, path)
392
+ )
393
+ return report
abkit/core/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """Core functionality for abkit (stdlib-only: intervals, table models, the grid)."""
2
+
3
+ from abkit.core.interval import Interval
4
+ from abkit.core.models import ColumnDefinition, TableModel
5
+ from abkit.core.period_planner import (
6
+ Cutoff,
7
+ Grid,
8
+ GridLimitExceeded,
9
+ backlog_seconds,
10
+ generate_grid,
11
+ pending_cutoffs,
12
+ tz_midnight_utc,
13
+ )
14
+
15
+ __all__ = [
16
+ "ColumnDefinition",
17
+ "Cutoff",
18
+ "Grid",
19
+ "GridLimitExceeded",
20
+ "Interval",
21
+ "TableModel",
22
+ "backlog_seconds",
23
+ "generate_grid",
24
+ "pending_cutoffs",
25
+ "tz_midnight_utc",
26
+ ]