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,450 @@
1
+ """
2
+ Base database manager interface.
3
+
4
+ Provides universal methods for database operations WITHOUT hardcoding
5
+ specific table logic (e.g., _ab_exposures, _ab_results).
6
+
7
+ The manager is database-agnostic and provides generic operations:
8
+ - execute_query(): Run SQL and return results
9
+ - create_table(): Create table from TableModel
10
+ - table_exists(): Check if table exists
11
+ - insert_batch(): Insert batch of data
12
+ - get_max_timestamp(): Max of a timestamp column under a WHERE clause
13
+ - try_acquire_lock(): Atomically claim a lock row (task locking)
14
+
15
+ Invariant (CLAUDE.md): the manager stays generic and ``table_name``-keyed;
16
+ ``_ab_*`` semantics (row shapes, staleness policy, lock grain) live in
17
+ ``database/internal_tables/``, never here.
18
+ """
19
+
20
+ from abc import ABC, abstractmethod
21
+ from datetime import datetime
22
+ from typing import Any
23
+
24
+ import numpy as np
25
+
26
+ from abkit.core.models import TableModel
27
+
28
+
29
+ class BaseDatabaseManager(ABC):
30
+ """
31
+ Universal database manager interface.
32
+
33
+ This class provides GENERIC methods for database operations.
34
+ It does NOT hardcode logic for internal tables (_ab_results, etc.).
35
+
36
+ Internal table management is handled by higher-level classes that
37
+ use these generic methods.
38
+
39
+ Key Design Principles:
40
+ 1. Universal methods (not table-specific)
41
+ 2. Works with any table via table_name parameter
42
+ 3. Type conversion handled internally
43
+ 4. Connection pooling and error handling
44
+ """
45
+
46
+ @abstractmethod
47
+ def execute_query(
48
+ self, query: str, params: dict[str, Any] | None = None
49
+ ) -> list[dict[str, Any]]:
50
+ """
51
+ Execute SQL query and return results as list of dictionaries.
52
+
53
+ Args:
54
+ query: SQL query to execute
55
+ params: Optional query parameters for parameterized queries
56
+
57
+ Returns:
58
+ List of dictionaries where each dict represents a row
59
+
60
+ Raises:
61
+ DatabaseError: If query execution fails
62
+
63
+ Example:
64
+ >>> results = manager.execute_query(
65
+ ... "SELECT * FROM _ab_results WHERE experiment = %(exp)s",
66
+ ... {"exp": "signup_test"}
67
+ ... )
68
+ >>> for row in results:
69
+ ... print(row['end_ts'], row['effect'])
70
+ """
71
+ pass
72
+
73
+ @abstractmethod
74
+ def create_table(
75
+ self, table_name: str, table_model: TableModel, if_not_exists: bool = True
76
+ ) -> None:
77
+ """
78
+ Create table from TableModel definition.
79
+
80
+ Converts database-agnostic TableModel into database-specific DDL.
81
+
82
+ Args:
83
+ table_name: Name of table to create
84
+ table_model: Table schema definition
85
+ if_not_exists: Add IF NOT EXISTS clause
86
+
87
+ Raises:
88
+ DatabaseError: If table creation fails
89
+
90
+ Example:
91
+ >>> model = TableModel(
92
+ ... columns=[
93
+ ... ColumnDefinition("id", "Int32"),
94
+ ... ColumnDefinition("value", "Float64", nullable=True),
95
+ ... ],
96
+ ... primary_key=["id"],
97
+ ... engine="MergeTree",
98
+ ... order_by=["id"]
99
+ ... )
100
+ >>> manager.create_table("my_table", model)
101
+ """
102
+ pass
103
+
104
+ @abstractmethod
105
+ def table_exists(self, table_name: str, schema: str | None = None) -> bool:
106
+ """
107
+ Check if table exists in database.
108
+
109
+ Args:
110
+ table_name: Name of table to check
111
+ schema: Optional schema/database name (if None, use default)
112
+
113
+ Returns:
114
+ True if table exists, False otherwise
115
+
116
+ Example:
117
+ >>> if not manager.table_exists("_ab_results"):
118
+ ... manager.create_table("_ab_results", results_model)
119
+ """
120
+ pass
121
+
122
+ @abstractmethod
123
+ def insert_batch(
124
+ self, table_name: str, data: dict[str, np.ndarray], conflict_strategy: str = "ignore"
125
+ ) -> int:
126
+ """
127
+ Insert batch of data into table.
128
+
129
+ Universal method that works with any table - NOT specific to
130
+ internal tables.
131
+
132
+ Args:
133
+ table_name: Name of table to insert into
134
+ data: Dictionary mapping column names to numpy arrays
135
+ All arrays must have same length
136
+ conflict_strategy: How to handle conflicts:
137
+ - "ignore": Skip rows with duplicate primary keys
138
+ - "replace": Replace existing rows
139
+ - "fail": Raise error on conflict
140
+
141
+ Returns:
142
+ Number of rows inserted (may be less than input if conflicts ignored)
143
+
144
+ Raises:
145
+ ValueError: If arrays have different lengths
146
+ DatabaseError: If insertion fails
147
+
148
+ Example:
149
+ >>> data = {
150
+ ... "experiment": np.array(["signup_test", "signup_test"]),
151
+ ... "unit_id": np.array(["u1", "u2"]),
152
+ ... "variant": np.array(["control", "treatment"]),
153
+ ... }
154
+ >>> rows_inserted = manager.insert_batch(
155
+ ... "_ab_exposures", data, conflict_strategy="ignore"
156
+ ... )
157
+ """
158
+ pass
159
+
160
+ @abstractmethod
161
+ def get_max_timestamp(
162
+ self,
163
+ table_name: str,
164
+ where_clause: str = "",
165
+ params: dict[str, Any] | None = None,
166
+ timestamp_column: str = "timestamp",
167
+ ) -> datetime | None:
168
+ """
169
+ Get ``max(timestamp_column)`` for rows matching a WHERE clause.
170
+
171
+ Universal method that works with any table containing a timestamp
172
+ column. Backends must normalise their NULL representation: ClickHouse
173
+ returns the epoch (1970-01-01) for an empty aggregate, which is
174
+ translated to ``None``.
175
+
176
+ Args:
177
+ table_name: Table to query
178
+ where_clause: SQL predicate placed after ``WHERE`` (may use
179
+ ``%(name)s`` placeholders resolved from ``params``); empty
180
+ string means no filter
181
+ params: Optional query parameters for the WHERE clause
182
+ timestamp_column: Name of timestamp column (default: "timestamp")
183
+
184
+ Returns:
185
+ Max timestamp or None if no data found
186
+
187
+ Example:
188
+ >>> last = manager.get_max_timestamp(
189
+ ... "_ab_results", "experiment = %(e)s", {"e": "signup_test"},
190
+ ... timestamp_column="end_ts",
191
+ ... )
192
+ """
193
+ pass
194
+
195
+ @abstractmethod
196
+ def try_acquire_lock(
197
+ self,
198
+ table_name: str,
199
+ key_columns: dict[str, Any],
200
+ row: dict[str, Any],
201
+ *,
202
+ status_column: str = "status",
203
+ running_value: str = "running",
204
+ heartbeat_column: str = "started_at",
205
+ timeout_seconds: int = 3600,
206
+ token_column: str | None = None,
207
+ ) -> bool:
208
+ """
209
+ Atomically claim a lock row; return True iff this caller now owns it.
210
+
211
+ The claim succeeds when the row does not exist, is not in the running
212
+ state, or its heartbeat is older than ``timeout_seconds`` (a stale lock
213
+ left by a dead process may be stolen). On success the full ``row`` is
214
+ written; on failure the existing row is left untouched.
215
+
216
+ The manager stays generic: the lock-table semantics (which column is
217
+ the status, what "running" means, the row shape) are injected by the
218
+ caller — ``internal_tables/_tasks`` owns the ``_ab_tasks`` policy.
219
+
220
+ Atomicity by backend (quorum must-fix "atomic lock"):
221
+ - PostgreSQL: single-statement ``INSERT ... ON CONFLICT (pk) DO UPDATE
222
+ ... WHERE <not running or stale>``; claim detected via rowcount.
223
+ - MySQL: single-statement row-alias ``INSERT ... AS new ON DUPLICATE
224
+ KEY UPDATE`` with the claim condition latched into a session
225
+ variable (MySQL 8.0.19+); claim detected via affected-rows.
226
+ - ClickHouse: ADVISORY only (no atomic upsert primitive exists):
227
+ staleness check -> synchronous DELETE -> INSERT -> read-back with a
228
+ deterministic winner tie-break on ``(heartbeat, token)``. Requires
229
+ ``token_column`` for the read-back verification.
230
+
231
+ Args:
232
+ table_name: Fully qualified lock table name
233
+ key_columns: PK columns identifying the lock row
234
+ row: The full row to write on a successful claim (must contain all
235
+ key columns with identical values, the status column set to
236
+ ``running_value``, and a fresh heartbeat)
237
+ status_column: Column holding the task status
238
+ running_value: Status value that means "actively held"
239
+ heartbeat_column: Timestamp column used for staleness
240
+ timeout_seconds: Age after which a running lock counts as stale
241
+ token_column: Column holding a caller-unique token; required for
242
+ the ClickHouse read-back, ignored by SQL backends
243
+
244
+ Returns:
245
+ True if the lock was acquired, False if it is held by another
246
+ live owner
247
+ """
248
+ pass
249
+
250
+ @abstractmethod
251
+ def upsert_record(
252
+ self,
253
+ table_name: str,
254
+ key_columns: dict[str, Any],
255
+ data: dict[str, np.ndarray],
256
+ sync: bool = False,
257
+ ) -> int:
258
+ """
259
+ Delete record by key columns, then insert new record.
260
+
261
+ This is a universal database-agnostic upsert pattern that guarantees
262
+ uniqueness by explicitly deleting old record before inserting new one.
263
+
264
+ Use this when ReplacingMergeTree or native UPSERT is not suitable
265
+ (e.g., for informational tables where guaranteed uniqueness is required).
266
+
267
+ Implementation varies by database:
268
+ - ClickHouse: ALTER TABLE ... DELETE + INSERT
269
+ - PostgreSQL: DELETE + INSERT (in transaction)
270
+ - MySQL: DELETE + INSERT (in transaction)
271
+
272
+ Args:
273
+ table_name: Fully qualified table name
274
+ key_columns: Dict of column names to values for WHERE clause
275
+ (e.g., {"experiment": "signup_test"})
276
+ data: Dict of column names to numpy arrays for INSERT
277
+ (must include all key columns)
278
+ sync: If True, the delete is fully applied before the insert
279
+ (ClickHouse: ``mutations_sync = 1``). Use for rows that must be
280
+ immediately uniquely visible (e.g. lock/status rows). SQL
281
+ backends are always synchronous so this is a no-op there.
282
+
283
+ Returns:
284
+ Number of rows inserted (typically 1)
285
+
286
+ Raises:
287
+ DatabaseError: If operation fails
288
+
289
+ Example:
290
+ >>> manager.upsert_record(
291
+ ... table_name="abkit_internal._ab_experiments",
292
+ ... key_columns={"experiment": "signup_test"},
293
+ ... data={
294
+ ... "experiment": np.array(["signup_test"]),
295
+ ... "status": np.array(["running"]),
296
+ ... ...
297
+ ... }
298
+ ... )
299
+ """
300
+ pass
301
+
302
+ @abstractmethod
303
+ def delete_rows(
304
+ self,
305
+ table_name: str,
306
+ where_clause: str,
307
+ params: dict[str, Any] | None = None,
308
+ sync: bool = False,
309
+ ) -> int:
310
+ """
311
+ Delete rows matching a WHERE clause from a table.
312
+
313
+ This is the single generic delete primitive. It exists so that
314
+ higher-level code (InternalTablesManager) never has to write
315
+ backend-specific delete syntax: ClickHouse renders an
316
+ ``ALTER TABLE ... DELETE`` mutation, while SQL backends render a plain
317
+ ``DELETE FROM ... WHERE ...``.
318
+
319
+ Args:
320
+ table_name: Fully qualified table name to delete from
321
+ where_clause: SQL predicate placed after ``WHERE`` (may use
322
+ ``%(name)s`` placeholders resolved from ``params``)
323
+ params: Optional query parameters for the WHERE clause
324
+ sync: If True, wait for the delete to be fully applied before
325
+ returning. On ClickHouse this appends ``SETTINGS
326
+ mutations_sync = 1`` (async mutations are synchronous-on-request);
327
+ SQL backends are always synchronous so this is a no-op there.
328
+
329
+ Returns:
330
+ Number of rows deleted when the backend can report it (SQL
331
+ backends), else 0 (ClickHouse mutations do not return a count).
332
+
333
+ Example:
334
+ >>> manager.delete_rows(
335
+ ... "abkit_internal._ab_exposures",
336
+ ... "experiment = %(e)s",
337
+ ... {"e": "signup_test"},
338
+ ... )
339
+ """
340
+ pass
341
+
342
+ @property
343
+ def final_modifier(self) -> str:
344
+ """
345
+ SQL fragment appended after a table name to collapse duplicate versions
346
+ on read.
347
+
348
+ ClickHouse's ReplacingMergeTree may hold transient duplicate primary
349
+ keys until a background merge runs, so dedup reads append ``FINAL``
350
+ (quorum must-fix "correctness under async merge" — every
351
+ correctness-sensitive read of a versioned table must use this or an
352
+ argMax/LIMIT 1 BY equivalent). Backends with an enforced unique primary
353
+ key (PostgreSQL, MySQL) never have duplicates, so this is the empty
354
+ string for them.
355
+
356
+ Returns:
357
+ ``" FINAL"`` on ClickHouse, ``""`` (no modifier) by default.
358
+ """
359
+ return ""
360
+
361
+ @property
362
+ @abstractmethod
363
+ def internal_location(self) -> str:
364
+ """
365
+ Get full location path for internal tables.
366
+
367
+ Format depends on database:
368
+ - ClickHouse: "database_name"
369
+ - PostgreSQL: "schema_name"
370
+
371
+ Returns:
372
+ Full path to internal schema/database
373
+
374
+ Example:
375
+ >>> manager.internal_location
376
+ 'abkit_internal'
377
+ """
378
+ pass
379
+
380
+ @property
381
+ @abstractmethod
382
+ def data_location(self) -> str:
383
+ """
384
+ Get full location path for user data tables.
385
+
386
+ Format depends on database:
387
+ - ClickHouse: "database_name"
388
+ - PostgreSQL: "schema_name"
389
+
390
+ Returns:
391
+ Full path to data schema/database
392
+
393
+ Example:
394
+ >>> manager.data_location
395
+ 'analytics'
396
+ """
397
+ pass
398
+
399
+ def register_table(self, table_name: str, table_model: TableModel) -> None:
400
+ """
401
+ Register a table's schema (primary key, version column) with the manager.
402
+
403
+ Backends that need per-table schema knowledge on the insert path — to
404
+ build conflict handling / version-aware upserts — record it here. This is
405
+ called for every internal table on every run (even when the table already
406
+ exists, so the DDL step is skipped), so a fresh manager instance always
407
+ knows the schema. The default is a no-op (ClickHouse derives nothing from
408
+ it; dedup is handled by the table engine).
409
+
410
+ Args:
411
+ table_name: Fully qualified table name
412
+ table_model: Table schema definition
413
+ """
414
+ return None
415
+
416
+ def get_full_table_name(self, table_name: str, use_internal: bool = True) -> str:
417
+ """
418
+ Get fully qualified table name.
419
+
420
+ Args:
421
+ table_name: Table name
422
+ use_internal: If True, use internal_location, else data_location
423
+
424
+ Returns:
425
+ Fully qualified table name
426
+
427
+ Example:
428
+ >>> manager.get_full_table_name("_ab_results", use_internal=True)
429
+ 'abkit_internal._ab_results'
430
+ """
431
+ location = self.internal_location if use_internal else self.data_location
432
+ return f"{location}.{table_name}"
433
+
434
+ @abstractmethod
435
+ def close(self) -> None:
436
+ """
437
+ Close database connection and cleanup resources.
438
+
439
+ Example:
440
+ >>> manager.close()
441
+ """
442
+ pass
443
+
444
+ def __enter__(self):
445
+ """Context manager entry."""
446
+ return self
447
+
448
+ def __exit__(self, exc_type, exc_val, exc_tb):
449
+ """Context manager exit - close connection."""
450
+ self.close()
@@ -0,0 +1,175 @@
1
+ """MySQL database manager implementation.
2
+
3
+ Implements :class:`BaseDatabaseManager` for MySQL on top of the shared
4
+ :class:`SQLDatabaseManager`. MySQL has no schema-vs-database distinction, so the
5
+ internal/data *locations* are real **databases** (``CREATE DATABASE IF NOT
6
+ EXISTS``). Dedup for the ``ReplacingMergeTree`` tables is reproduced with an
7
+ enforced primary key plus a version-aware ``INSERT ... ON DUPLICATE KEY UPDATE``
8
+ (row-alias form, MySQL 8.0.19+ — the documented floor).
9
+
10
+ MySQL cannot index ``TEXT`` columns in a primary key without a prefix length, so
11
+ ``String`` columns that are part of the primary key are rendered as
12
+ ``VARCHAR(255)`` while the rest stay ``TEXT``. Composite ``_ab_*`` keys must fit
13
+ InnoDB's 3072-byte index cap — size key columns deliberately.
14
+
15
+ The lock claim is a SINGLE row-alias ``INSERT ... ON DUPLICATE KEY UPDATE``
16
+ whose claim condition is latched into a session variable by the FIRST assignment
17
+ (SET clauses evaluate left to right), so every column sees the SAME verdict —
18
+ computed against the pre-update row — and the claim is atomic. Affected-rows
19
+ semantics: 1 = inserted (claimed), 2 = updated (claimed), 0 = left untouched
20
+ (held by a live owner).
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from typing import Any
26
+
27
+ from abkit.database._sql_manager import SQLDatabaseManager
28
+
29
+ try:
30
+ import pymysql # type: ignore[import-untyped]
31
+
32
+ PYMYSQL_AVAILABLE = True
33
+ except ImportError:
34
+ PYMYSQL_AVAILABLE = False
35
+
36
+
37
+ class MySQLDatabaseManager(SQLDatabaseManager):
38
+ """MySQL implementation of :class:`BaseDatabaseManager`.
39
+
40
+ Args:
41
+ host: MySQL host.
42
+ port: MySQL port (default 3306).
43
+ user: Database user.
44
+ password: Database password.
45
+ internal_database: Database for internal ``_ab_*`` tables.
46
+ data_database: Database for user data tables.
47
+ database: Optional default database for the connection.
48
+ settings: Extra ``pymysql.connect`` keyword arguments.
49
+ """
50
+
51
+ _TYPE_MAP = {
52
+ "datetime": "DATETIME(3)",
53
+ "date": "DATE",
54
+ "float": "DOUBLE",
55
+ "int": "INT",
56
+ "bool": "TINYINT(1)",
57
+ "string": "TEXT",
58
+ }
59
+
60
+ # MySQL quotes identifiers with backticks (``interval`` etc. are reserved).
61
+ _IDENT_QUOTE = "`"
62
+
63
+ def __init__(
64
+ self,
65
+ host: str = "localhost",
66
+ port: int = 3306,
67
+ user: str = "root",
68
+ password: str = "",
69
+ internal_database: str = "abkit",
70
+ data_database: str = "analytics",
71
+ database: str | None = None,
72
+ settings: dict[str, Any] | None = None,
73
+ ) -> None:
74
+ if not PYMYSQL_AVAILABLE:
75
+ raise ImportError(
76
+ "pymysql is not installed. Install with: pip install ab-analysis-kit[mysql]"
77
+ )
78
+ super().__init__(
79
+ host=host,
80
+ port=port,
81
+ user=user,
82
+ password=password,
83
+ internal_location=internal_database,
84
+ data_location=data_database,
85
+ database=database,
86
+ settings=settings,
87
+ )
88
+
89
+ def _connect(self) -> Any:
90
+ return pymysql.connect(
91
+ host=self._host,
92
+ port=self._port,
93
+ user=self._user,
94
+ password=self._password,
95
+ database=self._database,
96
+ charset="utf8mb4",
97
+ **self._settings,
98
+ )
99
+
100
+ def _ensure_locations(self) -> None:
101
+ for db in (self._internal_location, self._data_location):
102
+ self.execute_query(f"CREATE DATABASE IF NOT EXISTS {db}")
103
+
104
+ def _string_type(self, in_primary_key: bool, max_length: int | None = None) -> str:
105
+ # TEXT cannot be part of a PRIMARY KEY without a prefix length; sized
106
+ # columns honor max_length so wide composite keys fit InnoDB's
107
+ # 3072-byte index cap (4 bytes/char under utf8mb4).
108
+ if max_length is not None:
109
+ return f"VARCHAR({max_length})"
110
+ return "VARCHAR(255)" if in_primary_key else "TEXT"
111
+
112
+ def _build_insert_sql(
113
+ self,
114
+ table_name: str,
115
+ columns: list[str],
116
+ primary_key: list[str],
117
+ version_column: str | None,
118
+ conflict_strategy: str,
119
+ ) -> str:
120
+ placeholders = ", ".join(["%s"] * len(columns))
121
+ cols = ", ".join(self._q(c) for c in columns)
122
+ plain = f"INSERT INTO {table_name} ({cols}) VALUES ({placeholders})"
123
+
124
+ if conflict_strategy == "fail" or not primary_key:
125
+ return plain
126
+
127
+ non_pk = [c for c in columns if c not in primary_key]
128
+ if conflict_strategy == "ignore" and (version_column is None or not non_pk):
129
+ return f"INSERT IGNORE INTO {table_name} ({cols}) VALUES ({placeholders})"
130
+
131
+ # Row-alias form (MySQL 8.0.19+) avoids the deprecated VALUES() function.
132
+ # Existing-row references are qualified with the table name: with the
133
+ # `AS new` alias in scope, an unqualified column in the UPDATE expression
134
+ # is ambiguous ("Column '…' in field list is ambiguous").
135
+ aliased = f"{plain} AS new"
136
+ tbl = self._q(table_name.split(".")[-1])
137
+ if conflict_strategy == "replace":
138
+ sets = ", ".join(f"{self._q(c)} = new.{self._q(c)}" for c in non_pk)
139
+ else: # versioned "ignore" -> last-writer-wins by version column
140
+ ver = self._q(version_column) if version_column else None
141
+ sets = ", ".join(
142
+ f"{self._q(c)} = IF(new.{ver} >= {tbl}.{ver}, new.{self._q(c)}, {tbl}.{self._q(c)})"
143
+ for c in non_pk
144
+ )
145
+ return f"{aliased} ON DUPLICATE KEY UPDATE {sets}"
146
+
147
+ def _build_claim_sql(
148
+ self,
149
+ table_name: str,
150
+ columns: list[str],
151
+ primary_key: list[str],
152
+ status_column: str,
153
+ heartbeat_column: str,
154
+ ) -> str:
155
+ cols = ", ".join(self._q(c) for c in columns)
156
+ placeholders = ", ".join(f"%({c})s" for c in columns)
157
+ non_pk = [c for c in columns if c not in primary_key]
158
+ tbl = self._q(table_name.split(".")[-1])
159
+ # Latch the claim verdict into a session variable in the FIRST SET
160
+ # clause: MySQL evaluates SET clauses left to right, so without the
161
+ # latch a later IF would see columns already overwritten by an earlier
162
+ # clause (e.g. a fresh heartbeat) and the row could be torn.
163
+ condition = (
164
+ f"@abk_claim := ({tbl}.{self._q(status_column)} <> %(_abk_running)s "
165
+ f"OR {tbl}.{self._q(heartbeat_column)} < %(_abk_stale_before)s)"
166
+ )
167
+ first, *rest = non_pk
168
+ sets = [f"{self._q(first)} = IF({condition}, new.{self._q(first)}, {tbl}.{self._q(first)})"]
169
+ sets += [
170
+ f"{self._q(c)} = IF(@abk_claim, new.{self._q(c)}, {tbl}.{self._q(c)})" for c in rest
171
+ ]
172
+ return (
173
+ f"INSERT INTO {table_name} ({cols}) VALUES ({placeholders}) AS new "
174
+ f"ON DUPLICATE KEY UPDATE {', '.join(sets)}"
175
+ )