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,495 @@
1
+ """
2
+ ClickHouse database manager implementation.
3
+
4
+ Implements BaseDatabaseManager for ClickHouse using universal methods.
5
+ """
6
+
7
+ import time
8
+ from datetime import datetime, timedelta, timezone
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+
13
+ from abkit.utils.datetime_utils import now_utc_naive, to_naive_utc
14
+
15
+ try:
16
+ from clickhouse_driver import Client
17
+
18
+ CLICKHOUSE_AVAILABLE = True
19
+ except ImportError:
20
+ CLICKHOUSE_AVAILABLE = False
21
+
22
+ from abkit.core.models import TableModel
23
+ from abkit.database.manager import BaseDatabaseManager
24
+
25
+ _EPOCH_NAIVE = datetime(1970, 1, 1, 0, 0, 0)
26
+
27
+
28
+ class ClickHouseDatabaseManager(BaseDatabaseManager):
29
+ """
30
+ ClickHouse implementation of BaseDatabaseManager.
31
+
32
+ Uses universal methods - does NOT hardcode internal table logic.
33
+
34
+ Args:
35
+ host: ClickHouse host
36
+ port: ClickHouse port (default: 9000 for native protocol)
37
+ user: Database user
38
+ password: Database password
39
+ internal_database: Database for internal tables (_ab_*)
40
+ data_database: Database for user data tables
41
+ settings: Optional ClickHouse settings
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ host: str = "localhost",
47
+ port: int = 9000,
48
+ user: str = "default",
49
+ password: str = "",
50
+ internal_database: str = "abkit_internal",
51
+ data_database: str = "default",
52
+ settings: dict[str, Any] | None = None,
53
+ ):
54
+ """Initialize ClickHouse manager."""
55
+ if not CLICKHOUSE_AVAILABLE:
56
+ raise ImportError(
57
+ "clickhouse-driver is not installed. "
58
+ "Install with: pip install ab-analysis-kit[clickhouse]"
59
+ )
60
+
61
+ self._internal_database = internal_database
62
+ self._data_database = data_database
63
+
64
+ # Create client
65
+ self._client = Client(
66
+ host=host,
67
+ port=port,
68
+ user=user,
69
+ password=password,
70
+ settings=settings or {},
71
+ )
72
+
73
+ # Ensure databases exist
74
+ self._ensure_databases()
75
+
76
+ def _ensure_databases(self) -> None:
77
+ """Create internal and data databases if they don't exist."""
78
+ for db in [self._internal_database, self._data_database]:
79
+ self._client.execute(f"CREATE DATABASE IF NOT EXISTS {db}")
80
+
81
+ def execute_query(
82
+ self, query: str, params: dict[str, Any] | None = None
83
+ ) -> list[dict[str, Any]]:
84
+ """
85
+ Execute SQL query and return results as list of dictionaries.
86
+
87
+ Args:
88
+ query: SQL query to execute
89
+ params: Optional query parameters
90
+
91
+ Returns:
92
+ List of dictionaries where each dict represents a row
93
+ """
94
+ # Execute query with or without parameters
95
+ if params:
96
+ result = self._client.execute(query, params, with_column_types=True)
97
+ else:
98
+ result = self._client.execute(query, with_column_types=True)
99
+
100
+ # result is tuple: (rows, columns_with_types)
101
+ # columns_with_types is list of tuples: (name, type)
102
+ rows, columns_with_types = result
103
+ column_names = [col[0] for col in columns_with_types]
104
+
105
+ # Convert to list of dicts
106
+ return [dict(zip(column_names, row, strict=True)) for row in rows]
107
+
108
+ def create_table(
109
+ self, table_name: str, table_model: TableModel, if_not_exists: bool = True
110
+ ) -> None:
111
+ """
112
+ Create ClickHouse table from TableModel.
113
+
114
+ Converts generic TableModel to ClickHouse-specific DDL.
115
+
116
+ Args:
117
+ table_name: Name of table to create
118
+ table_model: Table schema definition
119
+ if_not_exists: Add IF NOT EXISTS clause
120
+ """
121
+ # Build column definitions
122
+ col_defs = []
123
+ for col in table_model.columns:
124
+ col_def = f"{col.name} {col.type}"
125
+ if col.default is not None:
126
+ col_def += f" DEFAULT {self._format_default(col.default)}"
127
+ col_defs.append(col_def)
128
+
129
+ columns_sql = ",\n ".join(col_defs)
130
+
131
+ # Build CREATE TABLE statement
132
+ if_not_exists_clause = "IF NOT EXISTS " if if_not_exists else ""
133
+
134
+ # For ClickHouse, use engine and order_by from table_model
135
+ engine = table_model.engine or "MergeTree"
136
+ order_by = table_model.order_by or table_model.primary_key
137
+
138
+ order_by_clause = ", ".join(order_by)
139
+
140
+ # Add parentheses only if engine doesn't already have them
141
+ if "(" in engine:
142
+ engine_clause = engine
143
+ else:
144
+ engine_clause = f"{engine}()"
145
+
146
+ ddl = f"""
147
+ CREATE TABLE {if_not_exists_clause}{table_name} (
148
+ {columns_sql}
149
+ )
150
+ ENGINE = {engine_clause}
151
+ ORDER BY ({order_by_clause})
152
+ """.strip()
153
+
154
+ self._client.execute(ddl)
155
+
156
+ def _format_default(self, value: Any) -> str:
157
+ """Format default value for SQL."""
158
+ if isinstance(value, str):
159
+ return f"'{value}'"
160
+ elif isinstance(value, (int, float)):
161
+ return str(value)
162
+ elif value is None:
163
+ return "NULL"
164
+ else:
165
+ return str(value)
166
+
167
+ def table_exists(self, table_name: str, schema: str | None = None) -> bool:
168
+ """
169
+ Check if table exists in ClickHouse.
170
+
171
+ Args:
172
+ table_name: Name of table to check
173
+ schema: Database name (if None, check both internal and data databases)
174
+
175
+ Returns:
176
+ True if table exists
177
+ """
178
+ if schema:
179
+ databases = [schema]
180
+ else:
181
+ databases = [self._internal_database, self._data_database]
182
+
183
+ for db in databases:
184
+ query = """
185
+ SELECT 1
186
+ FROM system.tables
187
+ WHERE database = %(database)s
188
+ AND name = %(table)s
189
+ """
190
+ result = self.execute_query(query, {"database": db, "table": table_name})
191
+ if result:
192
+ return True
193
+
194
+ return False
195
+
196
+ def insert_batch(
197
+ self, table_name: str, data: dict[str, np.ndarray], conflict_strategy: str = "ignore"
198
+ ) -> int:
199
+ """
200
+ Insert batch of data into ClickHouse table.
201
+
202
+ Args:
203
+ table_name: Table to insert into
204
+ data: Dictionary mapping column names to numpy arrays
205
+ conflict_strategy: "ignore" or "replace" (ClickHouse doesn't support REPLACE)
206
+
207
+ Returns:
208
+ Number of rows inserted
209
+ """
210
+ if not data:
211
+ return 0
212
+
213
+ # Validate all arrays have same length
214
+ lengths = [len(arr) for arr in data.values()]
215
+ if len(set(lengths)) > 1:
216
+ raise ValueError(
217
+ f"All arrays must have same length, got: {dict(zip(data.keys(), lengths, strict=True))}"
218
+ )
219
+
220
+ num_rows = lengths[0]
221
+ if num_rows == 0:
222
+ return 0
223
+
224
+ # Convert numpy arrays to lists for ClickHouse driver
225
+ column_names = list(data.keys())
226
+ rows = []
227
+
228
+ for i in range(num_rows):
229
+ row = []
230
+ for col_name in column_names:
231
+ value = data[col_name][i]
232
+
233
+ # Convert numpy types to Python types
234
+ if isinstance(value, (np.datetime64, np.timedelta64)):
235
+ # Convert numpy datetime64 to Python datetime
236
+ value = self._convert_numpy_datetime(value)
237
+ elif isinstance(value, np.ndarray):
238
+ value = value.tolist()
239
+ elif isinstance(value, (np.integer, np.floating, np.bool_)):
240
+ value = value.item()
241
+ # NaN -> NULL must run AFTER the numpy unwrap (an np.float64 NaN
242
+ # previously slipped through and was stored as NaN, not NULL)
243
+ if isinstance(value, float) and np.isnan(value):
244
+ value = None
245
+
246
+ row.append(value)
247
+ rows.append(row)
248
+
249
+ # For ClickHouse, conflict_strategy="ignore" is handled by PRIMARY KEY
250
+ # Duplicates are silently ignored by MergeTree
251
+ # Note: For ReplacingMergeTree, use conflict_strategy="replace"
252
+
253
+ # Insert data
254
+ self._client.execute(f"INSERT INTO {table_name} ({', '.join(column_names)}) VALUES", rows)
255
+
256
+ return num_rows
257
+
258
+ def _convert_numpy_datetime(self, dt: np.datetime64) -> datetime:
259
+ """Convert numpy datetime64 to Python datetime with UTC timezone."""
260
+ # Convert to timestamp
261
+ timestamp = (dt - np.datetime64("1970-01-01T00:00:00")) / np.timedelta64(1, "s")
262
+ return datetime.fromtimestamp(timestamp, tz=timezone.utc)
263
+
264
+ def get_max_timestamp(
265
+ self,
266
+ table_name: str,
267
+ where_clause: str = "",
268
+ params: dict[str, Any] | None = None,
269
+ timestamp_column: str = "timestamp",
270
+ ) -> datetime | None:
271
+ """
272
+ Get ``max(timestamp_column)`` under the WHERE clause.
273
+
274
+ Args:
275
+ table_name: Table to query
276
+ where_clause: SQL predicate placed after ``WHERE``; empty = no filter
277
+ params: Optional query parameters
278
+ timestamp_column: Name of timestamp column
279
+
280
+ Returns:
281
+ Max timestamp or None if no data
282
+ """
283
+ query = f"SELECT max({timestamp_column}) AS last_ts FROM {table_name}"
284
+ if where_clause:
285
+ query += f" WHERE {where_clause}"
286
+
287
+ result = self.execute_query(query, params)
288
+
289
+ if result and result[0]["last_ts"]:
290
+ last_ts = result[0]["last_ts"]
291
+
292
+ # ClickHouse returns epoch (1970-01-01 00:00:00) for an empty
293
+ # aggregate. Detect this and treat as None.
294
+ epoch = _EPOCH_NAIVE
295
+
296
+ # Handle both timezone-aware and naive datetimes
297
+ if last_ts.tzinfo is not None:
298
+ epoch = epoch.replace(tzinfo=last_ts.tzinfo)
299
+
300
+ if last_ts == epoch:
301
+ return None
302
+
303
+ return last_ts
304
+
305
+ return None
306
+
307
+ def delete_rows(
308
+ self,
309
+ table_name: str,
310
+ where_clause: str,
311
+ params: dict[str, Any] | None = None,
312
+ sync: bool = False,
313
+ ) -> int:
314
+ """
315
+ Delete rows via a ClickHouse ``ALTER TABLE ... DELETE`` mutation.
316
+
317
+ Args:
318
+ table_name: Fully qualified table name
319
+ where_clause: SQL predicate placed after ``WHERE``
320
+ params: Optional query parameters
321
+ sync: If True, append ``SETTINGS mutations_sync = 1`` so the
322
+ mutation is fully applied before returning.
323
+
324
+ Returns:
325
+ 0 — ClickHouse mutations are asynchronous and do not report a count.
326
+ """
327
+ query = f"ALTER TABLE {table_name} DELETE WHERE {where_clause}"
328
+ if sync:
329
+ query += " SETTINGS mutations_sync = 1"
330
+ self._client.execute(query, params or {})
331
+ return 0
332
+
333
+ @property
334
+ def final_modifier(self) -> str:
335
+ """ClickHouse collapses ReplacingMergeTree versions on read with FINAL."""
336
+ return " FINAL"
337
+
338
+ def upsert_record(
339
+ self,
340
+ table_name: str,
341
+ key_columns: dict[str, Any],
342
+ data: dict[str, np.ndarray],
343
+ sync: bool = False,
344
+ ) -> int:
345
+ """
346
+ Upsert record in ClickHouse using DELETE + INSERT pattern.
347
+
348
+ ClickHouse doesn't have native UPSERT, so we explicitly delete
349
+ the old record (if exists) and then insert the new one.
350
+
351
+ Args:
352
+ table_name: Fully qualified table name
353
+ key_columns: Dict of column names to values for WHERE clause
354
+ data: Dict of column names to numpy arrays for INSERT
355
+ sync: If True, the delete mutation is applied synchronously
356
+ (``mutations_sync = 1``) so the old row is guaranteed gone
357
+ before the insert — required for rows that must be immediately
358
+ uniquely visible (lock/status rows).
359
+
360
+ Returns:
361
+ Number of rows inserted (typically 1)
362
+ """
363
+ # Step 1: DELETE existing record (if any)
364
+ where_parts = [f"{col} = %({col})s" for col in key_columns.keys()]
365
+ self.delete_rows(table_name, " AND ".join(where_parts), dict(key_columns), sync=sync)
366
+
367
+ # Step 2: INSERT new record
368
+ return self.insert_batch(table_name, data, conflict_strategy="ignore")
369
+
370
+ def try_acquire_lock(
371
+ self,
372
+ table_name: str,
373
+ key_columns: dict[str, Any],
374
+ row: dict[str, Any],
375
+ *,
376
+ status_column: str = "status",
377
+ running_value: str = "running",
378
+ heartbeat_column: str = "started_at",
379
+ timeout_seconds: int = 3600,
380
+ token_column: str | None = None,
381
+ settle_seconds: float = 0.25,
382
+ ) -> bool:
383
+ """
384
+ ADVISORY lock claim — ClickHouse has no atomic upsert primitive.
385
+
386
+ Protocol: staleness check → conditional synchronous DELETE
387
+ (``mutations_sync = 1``; only rows that are NOT a live running claim —
388
+ or our own — are removed, so a racer can never erase an
389
+ already-confirmed claim) → INSERT with the heartbeat re-stamped at
390
+ insert time (so heartbeat order tracks insert order, not row-assembly
391
+ order) → a short settle pause → read-back with a deterministic winner
392
+ rule — the row with the smallest ``(heartbeat, token)`` wins, ties
393
+ broken by the token string. A loser deletes its OWN row before
394
+ returning False so it never blocks later staleness checks.
395
+
396
+ Residual advisory limitations (documented, by design — the SQL
397
+ backends are the atomic ones): cross-host clock skew larger than the
398
+ settle window can invert heartbeat order between racers, and a racer
399
+ whose insert becomes visible only after the winner's read-back +
400
+ settle can still self-confirm. Keep NTP sane and prefer one scheduler
401
+ per project.
402
+
403
+ ``token_column`` is REQUIRED (the read-back cannot tell two claimers
404
+ apart without it).
405
+ """
406
+ if token_column is None:
407
+ raise ValueError(
408
+ "ClickHouse advisory lock requires token_column (read-back verification)"
409
+ )
410
+ for key, value in key_columns.items():
411
+ if key not in row:
412
+ raise ValueError(f"lock row must contain key column {key!r}")
413
+ if row[key] != value:
414
+ raise ValueError(
415
+ f"lock row value for {key!r} ({row[key]!r}) != key_columns value ({value!r})"
416
+ )
417
+ if token_column not in row:
418
+ raise ValueError(f"lock row must contain token column {token_column!r}")
419
+
420
+ where = " AND ".join(f"{col} = %({col})s" for col in key_columns)
421
+ stale_before = now_utc_naive() - timedelta(seconds=timeout_seconds)
422
+
423
+ # 1. Staleness check: an actively-held lock blocks the claim.
424
+ existing = self.execute_query(
425
+ f"SELECT {status_column} AS s, {heartbeat_column} AS hb "
426
+ f"FROM {table_name} WHERE {where}",
427
+ dict(key_columns),
428
+ )
429
+ for r in existing:
430
+ heartbeat = to_naive_utc(r["hb"])
431
+ if r["s"] == running_value and heartbeat is not None and heartbeat >= stale_before:
432
+ return False
433
+
434
+ # 2. Claim: clear only CLAIMABLE rows (stale, finished, or our own) —
435
+ # never a rival's live running claim (a racer that passed step 1 before
436
+ # the winner confirmed must not erase the winner's row).
437
+ claim_params: dict[str, Any] = dict(key_columns)
438
+ claim_params["_abk_running"] = running_value
439
+ claim_params["_abk_stale_before"] = stale_before
440
+ claim_params["_abk_token"] = row[token_column]
441
+ self.delete_rows(
442
+ table_name,
443
+ f"{where} AND ({status_column} <> %(_abk_running)s "
444
+ f"OR {heartbeat_column} < %(_abk_stale_before)s "
445
+ f"OR {token_column} = %(_abk_token)s)",
446
+ claim_params,
447
+ sync=True,
448
+ )
449
+ # Re-stamp the heartbeat AT INSERT TIME: the winner rule below relies
450
+ # on heartbeat order tracking insert order (row assembly happens before
451
+ # the slow sync delete, which would invert it).
452
+ insert_row = dict(row)
453
+ insert_row[heartbeat_column] = now_utc_naive()
454
+ insert_data = {col: np.array([value], dtype=object) for col, value in insert_row.items()}
455
+ self.insert_batch(table_name, insert_data, conflict_strategy="ignore")
456
+
457
+ # 3. Settle, then read back: deterministic winner among racers.
458
+ if settle_seconds > 0:
459
+ time.sleep(settle_seconds)
460
+ rows_back = self.execute_query(
461
+ f"SELECT {token_column} AS t, {heartbeat_column} AS hb "
462
+ f"FROM {table_name} WHERE {where}",
463
+ dict(key_columns),
464
+ )
465
+ if not rows_back:
466
+ return False
467
+ winner = min(
468
+ rows_back,
469
+ key=lambda r: (to_naive_utc(r["hb"]) or _EPOCH_NAIVE, str(r["t"])),
470
+ )
471
+ if str(winner["t"]) == str(insert_row[token_column]):
472
+ return True
473
+ # Loser: remove our own row so it never blocks later staleness checks.
474
+ self.delete_rows(
475
+ table_name,
476
+ f"{where} AND {token_column} = %(_abk_token)s",
477
+ {**key_columns, "_abk_token": insert_row[token_column]},
478
+ sync=True,
479
+ )
480
+ return False
481
+
482
+ @property
483
+ def internal_location(self) -> str:
484
+ """Get internal database name."""
485
+ return self._internal_database
486
+
487
+ @property
488
+ def data_location(self) -> str:
489
+ """Get data database name."""
490
+ return self._data_database
491
+
492
+ def close(self) -> None:
493
+ """Close ClickHouse connection."""
494
+ if hasattr(self, "_client"):
495
+ self._client.disconnect()
@@ -0,0 +1,6 @@
1
+ """Internal ``_ab_*`` tables management for abkit."""
2
+
3
+ from abkit.database.internal_tables._unit_state import compute_column_set_id
4
+ from abkit.database.internal_tables.manager import InternalTablesManager
5
+
6
+ __all__ = ["InternalTablesManager", "compute_column_set_id"]
@@ -0,0 +1,53 @@
1
+ """A/A runs mixin: ``_ab_aa_runs`` operations.
2
+
3
+ Thin in M2 — the writer is exercised by ``abk validate`` (M4). An audit
4
+ trail: informational, never read by the run pipeline, deliberately NOT pruned
5
+ by ``abk clean`` (aa-false-positive-matrix.md).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ import numpy as np
13
+
14
+ from abkit.database.internal_tables._base import _InternalTablesBase
15
+ from abkit.database.tables import TABLE_AA_RUNS, get_aa_runs_table_model
16
+
17
+ #: record keys the caller must supply (created_at is stamped here)
18
+ AA_RUN_COLUMNS: tuple[str, ...] = tuple(
19
+ col.name for col in get_aa_runs_table_model().columns if col.name != "created_at"
20
+ )
21
+
22
+
23
+ class _AaRunsMixin(_InternalTablesBase):
24
+ def aa_runs_table_exists(self) -> bool:
25
+ """True when ``_ab_aa_runs`` exists — a never-validated project has none.
26
+
27
+ Read-only surfaces (the explore calibration chip, m3 WP4) guard with
28
+ this instead of ``ensure_tables()``: reading must never create schema
29
+ (the ``results_table_exists`` precedent).
30
+ """
31
+ return self._manager.table_exists(TABLE_AA_RUNS, schema=self._manager.internal_location)
32
+
33
+ def save_aa_run(self, record: dict[str, Any]) -> None:
34
+ """Persist one A/A validation run row (``created_at`` stamped here)."""
35
+ missing = [c for c in AA_RUN_COLUMNS if c not in record]
36
+ if missing:
37
+ raise ValueError(f"aa run record is missing fields: {missing}")
38
+
39
+ full_record = {c: record[c] for c in AA_RUN_COLUMNS}
40
+ full_record["created_at"] = self.next_version_ts()
41
+
42
+ full_table_name = self._manager.get_full_table_name(TABLE_AA_RUNS, use_internal=True)
43
+ data = {col: np.array([value], dtype=object) for col, value in full_record.items()}
44
+ self._manager.insert_batch(full_table_name, data, conflict_strategy="ignore")
45
+
46
+ def get_aa_runs(self, experiment: str) -> list[dict]:
47
+ """All A/A runs for an experiment, newest first (deduped)."""
48
+ full_table_name = self._manager.get_full_table_name(TABLE_AA_RUNS, use_internal=True)
49
+ return self._manager.execute_query(
50
+ f"SELECT * FROM {full_table_name}{self._manager.final_modifier} "
51
+ "WHERE experiment = %(e)s ORDER BY created_at DESC",
52
+ {"e": experiment},
53
+ )
@@ -0,0 +1,71 @@
1
+ """Shared state for the internal-tables mixins.
2
+
3
+ The split of :class:`InternalTablesManager` into mixins relies on every
4
+ mixin reading ``self._manager`` and a couple of small helpers that handle
5
+ ClickHouse quirks (notably the "epoch-as-NULL" return for ``MAX(t)`` over
6
+ empty ranges) plus the strictly-monotonic version source every LWW write
7
+ must use (quorum must-fix "created_at strictly-increasing & distinct").
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import threading
13
+ from datetime import datetime, timedelta
14
+
15
+ from abkit.database.manager import BaseDatabaseManager
16
+ from abkit.utils.datetime_utils import now_utc_naive
17
+
18
+ _EPOCH_NAIVE = datetime(1970, 1, 1, 0, 0, 0)
19
+ _ONE_MS = timedelta(milliseconds=1)
20
+
21
+
22
+ class _InternalTablesBase:
23
+ """Holds the underlying database manager and shared helpers."""
24
+
25
+ def __init__(self, manager: BaseDatabaseManager):
26
+ self._manager = manager
27
+ self._version_lock = threading.Lock()
28
+ self._last_version_ts: datetime | None = None
29
+ # lock ownership: (experiment, scope, process_type) -> our claim token,
30
+ # recorded by acquire_lock and required by the ownership-checked release
31
+ self._owned_lock_tokens: dict[tuple[str, str, str], str] = {}
32
+
33
+ @staticmethod
34
+ def _normalize_max_timestamp(value: datetime | None) -> datetime | None:
35
+ """Treat the Unix epoch sentinel as a missing value.
36
+
37
+ ClickHouse's ``max(timestamp)`` over an empty selection returns
38
+ ``1970-01-01 00:00:00`` instead of NULL. Without normalisation,
39
+ idempotency checks would think we already processed everything up
40
+ to 1970 and refuse to do work.
41
+ """
42
+ if value is None:
43
+ return None
44
+ epoch = _EPOCH_NAIVE
45
+ if value.tzinfo is not None:
46
+ epoch = epoch.replace(tzinfo=value.tzinfo)
47
+ if value == epoch:
48
+ return None
49
+ return value
50
+
51
+ def next_version_ts(self) -> datetime:
52
+ """Return a strictly-increasing, distinct naive-UTC version timestamp.
53
+
54
+ Every LWW-versioned write (``created_at`` on ``_ab_results``,
55
+ ``version`` on ``_ab_unit_state``, ``loaded_at`` on ``_ab_exposures``)
56
+ stamps its version through this method. Wall-clock ms precision would
57
+ tie for two writes within the same millisecond, making
58
+ ReplacingMergeTree/LWW dedup ambiguous — so ties are broken by
59
+ advancing at least 1ms past the previous issued version (per manager
60
+ instance, thread-safe). Cross-process ties are excluded by the
61
+ ``_ab_tasks`` lock serializing writers at (experiment[, metric]) grain
62
+ — this coupling is deliberate (plan R5).
63
+ """
64
+ with self._version_lock:
65
+ now = now_utc_naive()
66
+ # floor to ms so the DateTime64(3) round-trip is exact
67
+ now = now.replace(microsecond=(now.microsecond // 1000) * 1000)
68
+ if self._last_version_ts is not None and now <= self._last_version_ts:
69
+ now = self._last_version_ts + _ONE_MS
70
+ self._last_version_ts = now
71
+ return now