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,145 @@
1
+ """PostgreSQL database manager implementation.
2
+
3
+ Implements :class:`BaseDatabaseManager` for PostgreSQL on top of the shared
4
+ :class:`SQLDatabaseManager`. The internal/data *locations* are PostgreSQL
5
+ **schemas** inside a single connected database; abkit creates the schemas
6
+ (``CREATE SCHEMA IF NOT EXISTS``) but the database itself must already exist.
7
+ Dedup for the ``ReplacingMergeTree`` tables is reproduced with an enforced
8
+ primary key plus a version-aware ``INSERT ... ON CONFLICT DO UPDATE``.
9
+
10
+ The lock claim is a SINGLE statement (``INSERT ... ON CONFLICT (pk) DO UPDATE
11
+ ... WHERE <not running or stale>``), so two concurrent claimers serialize on
12
+ the row and exactly one observes an affected row — the quorum "atomic lock"
13
+ must-fix, with no TOCTOU window.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Any
19
+
20
+ from abkit.database._sql_manager import SQLDatabaseManager
21
+
22
+ try:
23
+ import psycopg2 # type: ignore[import-untyped]
24
+
25
+ PSYCOPG2_AVAILABLE = True
26
+ except ImportError:
27
+ PSYCOPG2_AVAILABLE = False
28
+
29
+
30
+ class PostgresDatabaseManager(SQLDatabaseManager):
31
+ """PostgreSQL implementation of :class:`BaseDatabaseManager`.
32
+
33
+ Args:
34
+ host: PostgreSQL host.
35
+ port: PostgreSQL port (default 5432).
36
+ user: Database user.
37
+ password: Database password.
38
+ database: Database to connect to (must already exist).
39
+ internal_schema: Schema for internal ``_ab_*`` tables.
40
+ data_schema: Schema for user data tables.
41
+ settings: Extra ``psycopg2.connect`` keyword arguments.
42
+ """
43
+
44
+ _TYPE_MAP = {
45
+ "datetime": "TIMESTAMP(3)",
46
+ "date": "DATE",
47
+ "float": "DOUBLE PRECISION",
48
+ "int": "INTEGER",
49
+ "bool": "BOOLEAN",
50
+ "string": "TEXT",
51
+ }
52
+
53
+ def __init__(
54
+ self,
55
+ host: str = "localhost",
56
+ port: int = 5432,
57
+ user: str = "postgres",
58
+ password: str = "",
59
+ database: str = "postgres",
60
+ internal_schema: str = "abkit",
61
+ data_schema: str = "public",
62
+ settings: dict[str, Any] | None = None,
63
+ ) -> None:
64
+ if not PSYCOPG2_AVAILABLE:
65
+ raise ImportError(
66
+ "psycopg2 is not installed. Install with: pip install ab-analysis-kit[postgres]"
67
+ )
68
+ super().__init__(
69
+ host=host,
70
+ port=port,
71
+ user=user,
72
+ password=password,
73
+ internal_location=internal_schema,
74
+ data_location=data_schema,
75
+ database=database,
76
+ settings=settings,
77
+ )
78
+
79
+ def _connect(self) -> Any:
80
+ return psycopg2.connect(
81
+ host=self._host,
82
+ port=self._port,
83
+ user=self._user,
84
+ password=self._password,
85
+ dbname=self._database,
86
+ **self._settings,
87
+ )
88
+
89
+ def _ensure_locations(self) -> None:
90
+ for schema in (self._internal_location, self._data_location):
91
+ self.execute_query(f"CREATE SCHEMA IF NOT EXISTS {schema}")
92
+
93
+ def _build_insert_sql(
94
+ self,
95
+ table_name: str,
96
+ columns: list[str],
97
+ primary_key: list[str],
98
+ version_column: str | None,
99
+ conflict_strategy: str,
100
+ ) -> str:
101
+ placeholders = ", ".join(["%s"] * len(columns))
102
+ col_list = ", ".join(self._q(c) for c in columns)
103
+ base = f"INSERT INTO {table_name} ({col_list}) VALUES ({placeholders})"
104
+
105
+ if conflict_strategy == "fail" or not primary_key:
106
+ return base
107
+
108
+ pk_target = f"ON CONFLICT ({', '.join(self._q(c) for c in primary_key)})"
109
+ if conflict_strategy == "ignore" and version_column is None:
110
+ return f"{base} {pk_target} DO NOTHING"
111
+
112
+ non_pk = [c for c in columns if c not in primary_key]
113
+ if not non_pk:
114
+ return f"{base} {pk_target} DO NOTHING"
115
+
116
+ set_clause = ", ".join(f"{self._q(c)} = EXCLUDED.{self._q(c)}" for c in non_pk)
117
+ stmt = f"{base} {pk_target} DO UPDATE SET {set_clause}"
118
+ # Versioned "ignore" == last-writer-wins: only overwrite when the
119
+ # incoming row's version is newer-or-equal (mirrors ReplacingMergeTree).
120
+ if version_column is not None and conflict_strategy == "ignore":
121
+ bare = table_name.split(".")[-1]
122
+ ver = self._q(version_column)
123
+ stmt += f" WHERE {bare}.{ver} <= EXCLUDED.{ver}"
124
+ return stmt
125
+
126
+ def _build_claim_sql(
127
+ self,
128
+ table_name: str,
129
+ columns: list[str],
130
+ primary_key: list[str],
131
+ status_column: str,
132
+ heartbeat_column: str,
133
+ ) -> str:
134
+ col_list = ", ".join(self._q(c) for c in columns)
135
+ placeholders = ", ".join(f"%({c})s" for c in columns)
136
+ non_pk = [c for c in columns if c not in primary_key]
137
+ set_clause = ", ".join(f"{self._q(c)} = EXCLUDED.{self._q(c)}" for c in non_pk)
138
+ bare = table_name.split(".")[-1]
139
+ return (
140
+ f"INSERT INTO {table_name} ({col_list}) VALUES ({placeholders}) "
141
+ f"ON CONFLICT ({', '.join(self._q(c) for c in primary_key)}) "
142
+ f"DO UPDATE SET {set_clause} "
143
+ f"WHERE {bare}.{self._q(status_column)} <> %(_abk_running)s "
144
+ f"OR {bare}.{self._q(heartbeat_column)} < %(_abk_stale_before)s"
145
+ )
@@ -0,0 +1,326 @@
1
+ """
2
+ Internal table models for abkit — the greenfield ``_ab_*`` schema.
3
+
4
+ Founding decision (CLAUDE.md / architecture.md §6): storage is GREENFIELD.
5
+ The legacy ``marts.*`` layout is reference only; these schemas are designed
6
+ from the decision logic and the specs:
7
+
8
+ - ``_ab_experiments`` — experiment catalog (informational)
9
+ - ``_ab_exposures`` — per-unit assignment cohort, loaded once, read-only
10
+ - ``_ab_unit_state`` — cumulative per-unit day-bucketed moments (the
11
+ scalability seam; cumulative-intervals.md §5.2/§5.3/§6.4)
12
+ - ``_ab_results`` — the BI contract (data-contract-and-reporting.md §2)
13
+ - ``_ab_aa_runs`` — A/A validation audit trail (written by ``abk validate``, M4)
14
+ - ``_ab_tasks`` — run locks + idempotency
15
+
16
+ Sizing note: string primary-key columns carry ``max_length`` so composite keys
17
+ fit MySQL InnoDB's 3072-byte index cap (utf8mb4 = 4 bytes/char). The config
18
+ validator enforces the same bounds on names (experiment/metric <= 128 chars,
19
+ variant names <= 64).
20
+ """
21
+
22
+ from abkit.core.models import ColumnDefinition, TableModel
23
+
24
+ #: Length bounds mirrored by the config validator.
25
+ MAX_EXPERIMENT_NAME_LENGTH = 128
26
+ MAX_METRIC_NAME_LENGTH = 128
27
+ MAX_VARIANT_NAME_LENGTH = 64
28
+
29
+
30
+ def get_experiments_table_model() -> TableModel:
31
+ """``_ab_experiments`` — the experiment catalog.
32
+
33
+ INFORMATIONAL ONLY (BI joins metric/experiment metadata from here — the
34
+ one source of truth for descriptions; data-contract §2 note). Replaced on
35
+ every run via the DELETE + INSERT upsert pattern.
36
+
37
+ Primary Key: (experiment); Engine: MergeTree (upsert_record keeps it unique).
38
+ """
39
+ return TableModel(
40
+ columns=[
41
+ ColumnDefinition("experiment", "String", max_length=MAX_EXPERIMENT_NAME_LENGTH),
42
+ ColumnDefinition("description", "Nullable(String)", nullable=True),
43
+ ColumnDefinition("status", "String"), # design|running|concluded|archived
44
+ ColumnDefinition("is_actual", "Bool"),
45
+ ColumnDefinition("start_date", "Date"),
46
+ ColumnDefinition("end_date", "Date"),
47
+ ColumnDefinition("unit_key", "String"),
48
+ ColumnDefinition("cadence", "String"), # canonical JSON: scalar or schedule
49
+ ColumnDefinition("data_lag_seconds", "Int64"),
50
+ ColumnDefinition("timezone", "String"),
51
+ ColumnDefinition("variants", "String"), # canonical JSON array, order = config
52
+ ColumnDefinition("expected_split", "String"), # canonical JSON object
53
+ ColumnDefinition("alpha", "Nullable(Float64)", nullable=True),
54
+ ColumnDefinition("correction", "Nullable(String)", nullable=True),
55
+ ColumnDefinition("sequential_enabled", "Bool"),
56
+ ColumnDefinition("sequential_scheme", "String"),
57
+ ColumnDefinition("comparisons", "String"), # canonical JSON summary
58
+ ColumnDefinition("path", "String"), # experiments/<name>.yml
59
+ ColumnDefinition("tags", "String"), # canonical JSON array
60
+ ColumnDefinition("created_at", "DateTime64(3, 'UTC')"),
61
+ ColumnDefinition("updated_at", "DateTime64(3, 'UTC')"),
62
+ ],
63
+ primary_key=["experiment"],
64
+ engine="MergeTree",
65
+ order_by=["experiment"],
66
+ )
67
+
68
+
69
+ def get_exposures_table_model() -> TableModel:
70
+ """``_ab_exposures`` — the persisted per-unit assignment cohort.
71
+
72
+ Loaded ONCE per run from the assignment SQL (quorum must-fix "persist the
73
+ cohort once"); metric SQL JOINs this table via the packaged macro instead
74
+ of re-deriving the cohort every interval. READ-ONLY for compute: abkit
75
+ never writes back into it from the pipeline and never randomizes.
76
+
77
+ Primary Key: (experiment, unit_id); Engine: ReplacingMergeTree(loaded_at)
78
+ so a re-load self-heals duplicates on ClickHouse; SQL backends get the
79
+ version-aware LWW upsert.
80
+ """
81
+ return TableModel(
82
+ columns=[
83
+ ColumnDefinition("experiment", "String", max_length=MAX_EXPERIMENT_NAME_LENGTH),
84
+ ColumnDefinition("unit_id", "String", max_length=255),
85
+ ColumnDefinition("variant", "String", max_length=MAX_VARIANT_NAME_LENGTH),
86
+ ColumnDefinition("exposure_ts", "DateTime64(3, 'UTC')"),
87
+ ColumnDefinition("stratum", "Nullable(String)", nullable=True),
88
+ ColumnDefinition("loaded_at", "DateTime64(3, 'UTC')"),
89
+ ],
90
+ primary_key=["experiment", "unit_id"],
91
+ engine="ReplacingMergeTree(loaded_at)",
92
+ order_by=["experiment", "unit_id"],
93
+ version_column="loaded_at",
94
+ )
95
+
96
+
97
+ def get_unit_state_table_model() -> TableModel:
98
+ """``_ab_unit_state`` — cumulative per-unit moments, day-bucketed.
99
+
100
+ The scalability seam (cumulative-intervals.md §4/§6.4). v1 is a thin
101
+ materialization: the read path stays recompute; the schema, cardinality
102
+ key, and idempotency invariant are locked NOW because the corruption is
103
+ silent until v2 flips the read path (§5.2).
104
+
105
+ - Keyed per (source_table, column_set_id, unit_id, day) — NOT per
106
+ (experiment, metric) — so co-located metrics sharing a fact source share
107
+ one set of per-unit moments (§5.3). ``column_set_id`` identifies the
108
+ column-role set (see ``internal_tables/_unit_state.compute_column_set_id``).
109
+ - ``day``-bucketed: sub-day cutoffs read closed-day state + a current-day
110
+ tail fact-scan; the state stage advances only at day close (§6.4).
111
+ - Replace-not-sum (§5.2): ``ReplacingMergeTree(version)`` on ClickHouse,
112
+ version-aware LWW upsert on SQL backends. Running the state stage twice
113
+ for one day leaves aggregates unchanged (the twice-run invariant test).
114
+ - Plain Float64 moments, deliberately NOT AggregateFunction states: they
115
+ must round-trip through PG/MySQL, and v2's Python accumulator reads
116
+ moments, not CH agg states (plan R2).
117
+
118
+ Moment columns cover the closed-form method families (§3): mean/t-test
119
+ {n, Σx, Σx²}, CUPED co-moments {Σc, Σc², Σxc}, ratio {Σd, Σd², Σxd}.
120
+ Unused moments stay 0 for a given column set.
121
+ """
122
+ return TableModel(
123
+ columns=[
124
+ ColumnDefinition("source_table", "String", max_length=128),
125
+ ColumnDefinition("column_set_id", "String", max_length=64),
126
+ ColumnDefinition("unit_id", "String", max_length=255),
127
+ ColumnDefinition("day", "Date"),
128
+ ColumnDefinition("n", "UInt64"),
129
+ ColumnDefinition("sum_value", "Float64", default="0"),
130
+ ColumnDefinition("sum_value_sq", "Float64", default="0"),
131
+ ColumnDefinition("sum_cov", "Float64", default="0"),
132
+ ColumnDefinition("sum_cov_sq", "Float64", default="0"),
133
+ ColumnDefinition("sum_value_cov", "Float64", default="0"),
134
+ ColumnDefinition("sum_denominator", "Float64", default="0"),
135
+ ColumnDefinition("sum_denominator_sq", "Float64", default="0"),
136
+ ColumnDefinition("sum_value_denominator", "Float64", default="0"),
137
+ ColumnDefinition("version", "DateTime64(3, 'UTC')"),
138
+ ],
139
+ primary_key=["source_table", "column_set_id", "unit_id", "day"],
140
+ engine="ReplacingMergeTree(version)",
141
+ order_by=["source_table", "column_set_id", "unit_id", "day"],
142
+ version_column="version",
143
+ )
144
+
145
+
146
+ def get_results_table_model() -> TableModel:
147
+ """``_ab_results`` — the clean BI contract (data-contract §2).
148
+
149
+ One row per (experiment, metric, variant-pair, method_config_id, end_ts).
150
+ ``end_ts`` is the canonical cutoff key (UTC, EXCLUSIVE half-open window);
151
+ ``end_date``/``start_date`` are derived Dates, legacy-identical at daily
152
+ cadence. Idempotency is last-writer-wins on the PK via the
153
+ strictly-monotonic ``created_at`` version (quorum must-fix); BI dedup
154
+ reads use argMax/LIMIT 1 BY, internal reads use FINAL.
155
+
156
+ Test columns are Nullable: ``insufficient_data`` rows are written with
157
+ inference withheld (counts and SRM stay visible — cumulative-intervals
158
+ §6.1.4). ``warnings``/``diagnostics`` are canonical-JSON payloads carrying
159
+ the human-readable failure signal (θ, boot_mean, H5 zero-denominator
160
+ explanations) — data-contract §2 as amended in this WP (plan R7).
161
+ """
162
+ return TableModel(
163
+ columns=[
164
+ # identity
165
+ ColumnDefinition("experiment", "String", max_length=MAX_EXPERIMENT_NAME_LENGTH),
166
+ ColumnDefinition("metric", "String", max_length=MAX_METRIC_NAME_LENGTH),
167
+ ColumnDefinition("is_main_metric", "Bool"),
168
+ ColumnDefinition("is_guardrail", "Bool"),
169
+ ColumnDefinition("method_name", "String"),
170
+ ColumnDefinition("method_params", "String"), # THE canonical JSON string
171
+ ColumnDefinition("method_config_id", "String", max_length=64),
172
+ ColumnDefinition("name_1", "String", max_length=MAX_VARIANT_NAME_LENGTH),
173
+ ColumnDefinition("name_2", "String", max_length=MAX_VARIANT_NAME_LENGTH),
174
+ # window (cumulative-intervals §6.3)
175
+ ColumnDefinition("start_ts", "DateTime64(3, 'UTC')"),
176
+ ColumnDefinition("end_ts", "DateTime64(3, 'UTC')"), # EXCLUSIVE
177
+ ColumnDefinition("start_date", "Date"),
178
+ ColumnDefinition("end_date", "Date"),
179
+ ColumnDefinition("window_seconds", "Int64"),
180
+ ColumnDefinition("elapsed_days", "Float64"), # fractional; chart x-axis
181
+ # per-arm
182
+ ColumnDefinition("value_1", "Nullable(Float64)", nullable=True),
183
+ ColumnDefinition("value_2", "Nullable(Float64)", nullable=True),
184
+ ColumnDefinition("std_1", "Nullable(Float64)", nullable=True),
185
+ ColumnDefinition("std_2", "Nullable(Float64)", nullable=True),
186
+ ColumnDefinition("cov_value_1", "Nullable(Float64)", nullable=True),
187
+ ColumnDefinition("cov_value_2", "Nullable(Float64)", nullable=True),
188
+ ColumnDefinition("size_1", "UInt64"),
189
+ ColumnDefinition("size_2", "UInt64"),
190
+ # test (Nullable: withheld under insufficient_data demotion)
191
+ ColumnDefinition("alpha", "Float64"), # effective, post-correction
192
+ ColumnDefinition("pvalue", "Nullable(Float64)", nullable=True),
193
+ ColumnDefinition("effect", "Nullable(Float64)", nullable=True),
194
+ ColumnDefinition("left_bound", "Nullable(Float64)", nullable=True),
195
+ ColumnDefinition("right_bound", "Nullable(Float64)", nullable=True),
196
+ ColumnDefinition("ci_length", "Nullable(Float64)", nullable=True),
197
+ ColumnDefinition("reject", "Nullable(Bool)", nullable=True),
198
+ ColumnDefinition("mde_1", "Nullable(Float64)", nullable=True),
199
+ ColumnDefinition("mde_2", "Nullable(Float64)", nullable=True),
200
+ # integrity
201
+ ColumnDefinition("srm_flag", "Bool"),
202
+ ColumnDefinition("srm_pvalue", "Nullable(Float64)", nullable=True),
203
+ ColumnDefinition("decision_blocked", "Bool"),
204
+ ColumnDefinition("insufficient_data", "Bool"),
205
+ # sequence
206
+ ColumnDefinition("ci_kind", "String"), # fixed | always_valid
207
+ ColumnDefinition("is_horizon", "Bool"),
208
+ # diagnostics (plan R7 — spec amended in this WP)
209
+ ColumnDefinition("warnings", "Nullable(String)", nullable=True), # JSON array
210
+ ColumnDefinition("diagnostics", "Nullable(String)", nullable=True), # JSON object
211
+ # provenance
212
+ ColumnDefinition("metric_query", "String"),
213
+ ColumnDefinition("metric_rendered_query", "String"),
214
+ ColumnDefinition("watermark_ts", "DateTime64(3, 'UTC')"),
215
+ ColumnDefinition("created_at", "DateTime64(3, 'UTC')"), # strictly-monotonic LWW
216
+ ],
217
+ primary_key=["experiment", "metric", "name_1", "name_2", "method_config_id", "end_ts"],
218
+ engine="ReplacingMergeTree(created_at)",
219
+ order_by=["experiment", "metric", "name_1", "name_2", "method_config_id", "end_ts"],
220
+ version_column="created_at",
221
+ )
222
+
223
+
224
+ def get_aa_runs_table_model() -> TableModel:
225
+ """``_ab_aa_runs`` — the A/A validation audit trail.
226
+
227
+ Written by ``abk validate`` (M4): one row per scored (experiment, metric,
228
+ method) cell — empirical FPR vs nominal alpha, honest cumulative-peeking
229
+ FPR over the actual cadence grid, power / achieved-MDE under injected
230
+ effects, CI coverage, effect-exaggeration-at-stop, and the plain-language
231
+ verdict. An audit trail: informational, never read by the run pipeline,
232
+ deliberately NOT pruned by ``abk clean`` (aa-false-positive-matrix.md).
233
+ The M4 work package may extend the payload before the first release.
234
+ """
235
+ return TableModel(
236
+ columns=[
237
+ ColumnDefinition("experiment", "String", max_length=MAX_EXPERIMENT_NAME_LENGTH),
238
+ ColumnDefinition("run_id", "String", max_length=64),
239
+ ColumnDefinition("metric", "String"),
240
+ ColumnDefinition("method_name", "String"),
241
+ ColumnDefinition("method_params", "String"), # canonical JSON
242
+ ColumnDefinition("method_config_id", "String"),
243
+ ColumnDefinition("mode", "String"), # fpr | power | mde
244
+ ColumnDefinition("iterations", "Int32"),
245
+ ColumnDefinition("alpha", "Float64"),
246
+ ColumnDefinition("injected_effect", "Nullable(Float64)", nullable=True),
247
+ ColumnDefinition("fpr", "Nullable(Float64)", nullable=True),
248
+ ColumnDefinition("peeking_fpr", "Nullable(Float64)", nullable=True),
249
+ ColumnDefinition("power", "Nullable(Float64)", nullable=True),
250
+ ColumnDefinition("achieved_mde", "Nullable(Float64)", nullable=True),
251
+ ColumnDefinition("coverage", "Nullable(Float64)", nullable=True),
252
+ ColumnDefinition("effect_exaggeration", "Nullable(Float64)", nullable=True),
253
+ # M5 D8: the always-valid sequential column, side-by-side with the fixed
254
+ # measurements above (aa-false-positive-matrix.md; m5-implementation-plan §WP2).
255
+ ColumnDefinition("tau2", "Nullable(Float64)", nullable=True), # frozen mixture variance
256
+ ColumnDefinition("fpr_sequential", "Nullable(Float64)", nullable=True),
257
+ ColumnDefinition("peeking_fpr_sequential", "Nullable(Float64)", nullable=True),
258
+ ColumnDefinition("power_sequential", "Nullable(Float64)", nullable=True),
259
+ ColumnDefinition("coverage_sequential", "Nullable(Float64)", nullable=True),
260
+ ColumnDefinition("effect_exaggeration_sequential", "Nullable(Float64)", nullable=True),
261
+ ColumnDefinition("ci_width", "Nullable(Float64)", nullable=True), # fixed horizon width
262
+ ColumnDefinition("ci_width_sequential", "Nullable(Float64)", nullable=True),
263
+ ColumnDefinition("verdict", "String"),
264
+ ColumnDefinition("details", "String"), # canonical JSON
265
+ ColumnDefinition("status", "String"), # success | failed
266
+ ColumnDefinition("error_message", "Nullable(String)", nullable=True),
267
+ ColumnDefinition("created_at", "DateTime64(3, 'UTC')"),
268
+ ],
269
+ primary_key=["experiment", "run_id"],
270
+ engine="ReplacingMergeTree(created_at)",
271
+ order_by=["experiment", "run_id"],
272
+ version_column="created_at",
273
+ )
274
+
275
+
276
+ def get_tasks_table_model() -> TableModel:
277
+ """``_ab_tasks`` — run locks + idempotency.
278
+
279
+ Primary Key: (experiment, scope, process_type). ``scope`` is the lock
280
+ grain: ``"pipeline"`` for the whole-experiment lock; the key shape
281
+ reserves per-metric locks (scope = metric name) for later parallelism
282
+ (cumulative-intervals §5.7). ``locked_by`` is the owner token
283
+ (host:pid:nonce) — required by the ClickHouse advisory claim read-back.
284
+
285
+ Deliberately drops detectkit's resume-cursor (``last_processed_timestamp``)
286
+ and alerting columns: an experiment is a finite re-runnable recomputation,
287
+ not a resumed cursor (§7) — the planner anti-join replaces the cursor.
288
+
289
+ Engine: plain MergeTree; uniqueness is maintained by the lock protocol
290
+ (atomic claim / sync upsert_record), not by a version merge.
291
+ """
292
+ return TableModel(
293
+ columns=[
294
+ ColumnDefinition("experiment", "String", max_length=MAX_EXPERIMENT_NAME_LENGTH),
295
+ ColumnDefinition("scope", "String", max_length=MAX_METRIC_NAME_LENGTH),
296
+ ColumnDefinition("process_type", "String", max_length=32),
297
+ ColumnDefinition("status", "String"), # running | completed | failed
298
+ ColumnDefinition("started_at", "DateTime64(3, 'UTC')"),
299
+ ColumnDefinition("updated_at", "DateTime64(3, 'UTC')"),
300
+ ColumnDefinition("locked_by", "String"),
301
+ ColumnDefinition("error_message", "Nullable(String)", nullable=True),
302
+ ColumnDefinition("timeout_seconds", "Int32"),
303
+ ],
304
+ primary_key=["experiment", "scope", "process_type"],
305
+ engine="MergeTree",
306
+ order_by=["experiment", "scope", "process_type"],
307
+ )
308
+
309
+
310
+ # Table names as constants
311
+ TABLE_EXPERIMENTS = "_ab_experiments"
312
+ TABLE_EXPOSURES = "_ab_exposures"
313
+ TABLE_UNIT_STATE = "_ab_unit_state"
314
+ TABLE_RESULTS = "_ab_results"
315
+ TABLE_AA_RUNS = "_ab_aa_runs"
316
+ TABLE_TASKS = "_ab_tasks"
317
+
318
+ # Map of table names to model factories
319
+ INTERNAL_TABLES = {
320
+ TABLE_EXPERIMENTS: get_experiments_table_model,
321
+ TABLE_EXPOSURES: get_exposures_table_model,
322
+ TABLE_UNIT_STATE: get_unit_state_table_model,
323
+ TABLE_RESULTS: get_results_table_model,
324
+ TABLE_AA_RUNS: get_aa_runs_table_model,
325
+ TABLE_TASKS: get_tasks_table_model,
326
+ }
@@ -0,0 +1,28 @@
1
+ """Loaders: Jinja templating + the packaged macro + exposure/metric loading."""
2
+
3
+ from abkit.loaders.exposure_loader import ExposureLoadError, load_exposures
4
+ from abkit.loaders.metric_loader import (
5
+ MetricLoadError,
6
+ MetricLoadResult,
7
+ load_covariate_from_preperiod,
8
+ load_metric,
9
+ )
10
+ from abkit.loaders.query_template import (
11
+ QueryTemplate,
12
+ RenderWindow,
13
+ TemplateRenderError,
14
+ build_builtins,
15
+ )
16
+
17
+ __all__ = [
18
+ "ExposureLoadError",
19
+ "MetricLoadError",
20
+ "MetricLoadResult",
21
+ "QueryTemplate",
22
+ "RenderWindow",
23
+ "TemplateRenderError",
24
+ "build_builtins",
25
+ "load_covariate_from_preperiod",
26
+ "load_exposures",
27
+ "load_metric",
28
+ ]
@@ -0,0 +1,121 @@
1
+ """Exposure loader: assignment SQL → the persisted ``_ab_exposures`` cohort.
2
+
3
+ Runs ONCE per experiment per run (quorum must-fix "persist the cohort once" —
4
+ metric SQL joins the persisted cohort instead of re-deriving it every
5
+ interval). The assignment source is READ-ONLY: abkit never randomizes and
6
+ never writes back into it; ``replace_exposures`` is idempotent per experiment
7
+ (delete-then-insert), so a re-run self-heals and the SRM gate re-checks the
8
+ fresh counts (plan R9).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import warnings
14
+ from typing import Any
15
+
16
+ import numpy as np
17
+
18
+ from abkit.config.experiment_config import ExperimentConfig
19
+ from abkit.database.internal_tables import InternalTablesManager
20
+ from abkit.database.manager import BaseDatabaseManager
21
+ from abkit.loaders.query_template import QueryTemplate
22
+ from abkit.utils.datetime_utils import to_naive_utc
23
+
24
+
25
+ class ExposureLoadError(Exception):
26
+ """Raised when the assignment result violates the exposure contract."""
27
+
28
+
29
+ def load_exposures(
30
+ manager: BaseDatabaseManager,
31
+ tables: InternalTablesManager,
32
+ experiment: ExperimentConfig,
33
+ assignment_sql: str,
34
+ builtins: dict[str, Any],
35
+ template: QueryTemplate | None = None,
36
+ ) -> dict[str, int]:
37
+ """Render + execute the assignment SQL, validate, persist the cohort.
38
+
39
+ Contract on the assignment result set (declarative-config.md §2):
40
+ one row per unit with columns ``<unit_key>``, ``variant``, ``exposure_ts``
41
+ and optional ``stratum``. Violations:
42
+
43
+ - missing required columns → error
44
+ - a unit appearing in MORE THAN ONE variant → hard error (a corrupted
45
+ assignment invalidates every downstream number)
46
+ - duplicate rows within one variant → deduped to the EARLIEST exposure
47
+ (legacy first-exposure semantics), with a loud warning
48
+ - observed variants not declared in the config → error (the SRM
49
+ expected_split could not cover them)
50
+ - an empty cohort → error (a misconfigured source, not a valid state)
51
+
52
+ Returns the per-variant unit counts (the SRM gate's observed counts).
53
+ """
54
+ template = template or QueryTemplate()
55
+ rendered = template.render(assignment_sql, builtins)
56
+ rows = manager.execute_query(rendered)
57
+
58
+ if not rows:
59
+ raise ExposureLoadError(
60
+ f"assignment query for experiment '{experiment.name}' returned no rows "
61
+ "— check the assignment SQL and its filters"
62
+ )
63
+
64
+ unit_key = experiment.unit_key
65
+ required = (unit_key, "variant", "exposure_ts")
66
+ missing = [c for c in required if c not in rows[0]]
67
+ if missing:
68
+ raise ExposureLoadError(
69
+ f"assignment query must SELECT {list(required)} (missing: {missing}). "
70
+ "Columns present: " + ", ".join(sorted(rows[0]))
71
+ )
72
+ has_stratum = "stratum" in rows[0]
73
+
74
+ declared = set(experiment.assignment.variants)
75
+ seen: dict[Any, tuple[str, Any, Any]] = {} # unit -> (variant, exposure_ts, stratum)
76
+ duplicate_rows = 0
77
+ for row in rows:
78
+ unit = row[unit_key]
79
+ variant = row["variant"]
80
+ if variant not in declared:
81
+ raise ExposureLoadError(
82
+ f"assignment returned variant '{variant}' not declared in "
83
+ f"assignment.variants {sorted(declared)}"
84
+ )
85
+ exposure_ts = to_naive_utc(row["exposure_ts"])
86
+ stratum = row.get("stratum") if has_stratum else None
87
+ if unit in seen:
88
+ prev_variant, prev_ts, prev_stratum = seen[unit]
89
+ if prev_variant != variant:
90
+ raise ExposureLoadError(
91
+ f"unit '{unit}' is assigned to BOTH '{prev_variant}' and "
92
+ f"'{variant}' — the assignment source is corrupted; "
93
+ "every downstream effect would be untrustworthy"
94
+ )
95
+ duplicate_rows += 1
96
+ if exposure_ts is not None and (prev_ts is None or exposure_ts < prev_ts):
97
+ seen[unit] = (variant, exposure_ts, stratum)
98
+ else:
99
+ seen[unit] = (variant, exposure_ts, stratum)
100
+
101
+ if duplicate_rows:
102
+ warnings.warn(
103
+ f"assignment for '{experiment.name}' returned {duplicate_rows} duplicate "
104
+ f"unit rows — deduped to the earliest exposure_ts. Is the assignment "
105
+ "query one-row-per-unit?",
106
+ stacklevel=2,
107
+ )
108
+
109
+ units = list(seen)
110
+ data = {
111
+ "unit_id": np.array([str(u) for u in units], dtype=object),
112
+ "variant": np.array([seen[u][0] for u in units], dtype=object),
113
+ "exposure_ts": np.array([seen[u][1] for u in units], dtype=object),
114
+ "stratum": np.array([seen[u][2] for u in units], dtype=object),
115
+ }
116
+ tables.replace_exposures(experiment.name, data)
117
+
118
+ counts: dict[str, int] = {}
119
+ for variant, _, _ in seen.values():
120
+ counts[variant] = counts.get(variant, 0) + 1
121
+ return counts