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,82 @@
1
+ """Experiment catalog mixin: ``_ab_experiments`` operations.
2
+
3
+ INFORMATIONAL table (BI joins descriptions/metadata from here; the pipeline
4
+ never reads it back for decisions). Callers pass a fully-prepared flat record
5
+ — JSON-typed fields (cadence, variants, expected_split, comparisons, tags)
6
+ must already be canonical-JSON strings via ``json_dumps_sorted``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+
15
+ from abkit.database.internal_tables._base import _InternalTablesBase
16
+ from abkit.database.tables import TABLE_EXPERIMENTS
17
+ from abkit.utils.datetime_utils import now_utc_naive
18
+
19
+
20
+ class _ExperimentsMixin(_InternalTablesBase):
21
+ #: record keys the caller must supply (created_at/updated_at are stamped here)
22
+ _EXPERIMENT_FIELDS = (
23
+ "experiment",
24
+ "description",
25
+ "status",
26
+ "is_actual",
27
+ "start_date",
28
+ "end_date",
29
+ "unit_key",
30
+ "cadence",
31
+ "data_lag_seconds",
32
+ "timezone",
33
+ "variants",
34
+ "expected_split",
35
+ "alpha",
36
+ "correction",
37
+ "sequential_enabled",
38
+ "sequential_scheme",
39
+ "comparisons",
40
+ "path",
41
+ "tags",
42
+ )
43
+
44
+ def upsert_experiment(self, record: dict[str, Any]) -> None:
45
+ """Replace the catalog row for ``record["experiment"]``.
46
+
47
+ ``created_at`` is preserved from an existing row (first-seen time);
48
+ ``updated_at`` is stamped now.
49
+ """
50
+ missing = [f for f in self._EXPERIMENT_FIELDS if f not in record]
51
+ if missing:
52
+ raise ValueError(f"experiment record is missing fields: {missing}")
53
+
54
+ existing = self.get_experiment(record["experiment"])
55
+ now = now_utc_naive()
56
+ created_at = existing["created_at"] if existing else now
57
+
58
+ full_record = {f: record[f] for f in self._EXPERIMENT_FIELDS}
59
+ full_record["created_at"] = created_at
60
+ full_record["updated_at"] = now
61
+
62
+ full_table_name = self._manager.get_full_table_name(TABLE_EXPERIMENTS, use_internal=True)
63
+ data = {col: np.array([value], dtype=object) for col, value in full_record.items()}
64
+ # sync=True: an async ClickHouse delete would leave transient duplicate
65
+ # catalog rows that no reader dedups (once-per-run write; cost negligible)
66
+ self._manager.upsert_record(
67
+ full_table_name, {"experiment": record["experiment"]}, data, sync=True
68
+ )
69
+
70
+ def get_experiment(self, experiment: str) -> dict | None:
71
+ """Return the catalog row for *experiment*, or None."""
72
+ full_table_name = self._manager.get_full_table_name(TABLE_EXPERIMENTS, use_internal=True)
73
+ rows = self._manager.execute_query(
74
+ f"SELECT * FROM {full_table_name} WHERE experiment = %(e)s",
75
+ {"e": experiment},
76
+ )
77
+ return rows[0] if rows else None
78
+
79
+ def list_experiments(self) -> list[dict]:
80
+ """Return every catalog row (for ``abk clean --orphaned-experiments``)."""
81
+ full_table_name = self._manager.get_full_table_name(TABLE_EXPERIMENTS, use_internal=True)
82
+ return self._manager.execute_query(f"SELECT * FROM {full_table_name}")
@@ -0,0 +1,163 @@
1
+ """Exposures mixin: ``_ab_exposures`` operations.
2
+
3
+ The persisted assignment cohort — loaded ONCE per run by the exposure loader
4
+ (quorum must-fix "persist the cohort once"), JOINed by every metric query via
5
+ the packaged macro, and the SRM gate's count source. READ-ONLY for compute:
6
+ only ``replace_exposures`` (the loader) and ``purge_experiment`` write here.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import bisect
12
+ from datetime import datetime
13
+
14
+ import numpy as np
15
+
16
+ from abkit.database.internal_tables._base import _InternalTablesBase
17
+ from abkit.database.tables import TABLE_EXPOSURES
18
+ from abkit.utils.datetime_utils import to_naive_utc
19
+
20
+ #: insert chunk size — bounds driver memory on multi-million-unit cohorts
21
+ EXPOSURE_INSERT_CHUNK = 100_000
22
+
23
+
24
+ class _ExposuresMixin(_InternalTablesBase):
25
+ def replace_exposures(self, experiment: str, data: dict[str, np.ndarray]) -> int:
26
+ """Replace the full cohort for *experiment*: sync delete + chunked insert.
27
+
28
+ Idempotent per experiment (delete-then-insert keyed by experiment —
29
+ plan R9): a re-run reloads the cohort from the assignment SQL and the
30
+ SRM gate re-checks it. Returns the number of exposure rows written.
31
+
32
+ ``data`` must contain ``unit_id``, ``variant``, ``exposure_ts`` and
33
+ optionally ``stratum`` arrays (the exposure loader validates shapes);
34
+ ``experiment`` and the ``loaded_at`` version are stamped here.
35
+ """
36
+ required = ("unit_id", "variant", "exposure_ts")
37
+ missing = [c for c in required if c not in data]
38
+ if missing:
39
+ raise ValueError(f"exposure data is missing columns: {missing}")
40
+
41
+ num_rows = len(data["unit_id"])
42
+ full_table_name = self._manager.get_full_table_name(TABLE_EXPOSURES, use_internal=True)
43
+
44
+ self._manager.delete_rows(
45
+ full_table_name, "experiment = %(e)s", {"e": experiment}, sync=True
46
+ )
47
+ if num_rows == 0:
48
+ return 0
49
+
50
+ loaded_at = self.next_version_ts()
51
+ stratum = data.get("stratum")
52
+ if stratum is None:
53
+ stratum = np.array([None] * num_rows, dtype=object)
54
+
55
+ written = 0
56
+ for start in range(0, num_rows, EXPOSURE_INSERT_CHUNK):
57
+ end = min(start + EXPOSURE_INSERT_CHUNK, num_rows)
58
+ chunk = {
59
+ "experiment": np.full(end - start, experiment, dtype=object),
60
+ "unit_id": data["unit_id"][start:end],
61
+ "variant": data["variant"][start:end],
62
+ "exposure_ts": data["exposure_ts"][start:end],
63
+ "stratum": stratum[start:end],
64
+ "loaded_at": np.full(end - start, loaded_at, dtype=object),
65
+ }
66
+ written += self._manager.insert_batch(
67
+ full_table_name, chunk, conflict_strategy="ignore"
68
+ )
69
+ return written
70
+
71
+ def exposures_table_exists(self) -> bool:
72
+ """True when ``_ab_exposures`` exists — a never-run project has none.
73
+
74
+ Read-only surfaces guard with this instead of ``ensure_tables()``;
75
+ mirrors :meth:`results_table_exists` (m3-implementation-plan.md WP2).
76
+ """
77
+ return self._manager.table_exists(TABLE_EXPOSURES, schema=self._manager.internal_location)
78
+
79
+ def get_exposure_counts(self, experiment: str) -> dict[str, int]:
80
+ """Per-variant unit counts — the SRM gate's observed counts.
81
+
82
+ Deduped (FINAL on ClickHouse) so a mid-merge ReplacingMergeTree never
83
+ double-counts a unit (quorum "correctness under async merge"). Whole
84
+ cohort by design: M2 SRM is a single whole-cohort check, so the report
85
+ pairs these counts with that whole-run flag/pvalue (an as-of subset
86
+ would mismatch it — review finding); per-cutoff SRM lands with
87
+ sequential (M5).
88
+ """
89
+ full_table_name = self._manager.get_full_table_name(TABLE_EXPOSURES, use_internal=True)
90
+ query = f"""
91
+ SELECT variant, count(*) AS cnt
92
+ FROM {full_table_name}{self._manager.final_modifier}
93
+ WHERE experiment = %(e)s
94
+ GROUP BY variant
95
+ """
96
+ rows = self._manager.execute_query(query, {"e": experiment})
97
+ return {row["variant"]: int(row["cnt"]) for row in rows if row.get("variant")}
98
+
99
+ def get_exposure_count_stream(
100
+ self, experiment: str, boundaries: list[datetime], variants: list[str]
101
+ ) -> list[dict[str, int]]:
102
+ """Cumulative per-variant unit counts as-of each look boundary.
103
+
104
+ The sub-day anytime-valid SRM (Lindon & Malek, cumulative-intervals.md
105
+ §6.5) needs the running count history: for each half-open cumulative
106
+ window ``[start, end_ts)`` the count of units first exposed BEFORE
107
+ ``end_ts`` (exclusive, matching the metric-load windows). Reads the
108
+ deduped persisted cohort ONCE and buckets in-process (one round trip,
109
+ not one query per look — a sub-day grid has many looks); every variant
110
+ in ``variants`` is zero-filled so a missing arm reads as 0 (the worst
111
+ SRM). Returns one dict per boundary, aligned and ascending.
112
+
113
+ (v1 reconstructs the full stream each run from ``_ab_exposures``, in
114
+ keeping with the recompute-not-incremental read path; a bucketed-SQL or
115
+ running-max-carry optimisation is a future v2.)
116
+ """
117
+ if not boundaries:
118
+ return []
119
+ full_table_name = self._manager.get_full_table_name(TABLE_EXPOSURES, use_internal=True)
120
+ rows = self._manager.execute_query(
121
+ f"SELECT variant, exposure_ts FROM {full_table_name}{self._manager.final_modifier} "
122
+ "WHERE experiment = %(e)s",
123
+ {"e": experiment},
124
+ )
125
+ # sorted exposure timestamps per declared variant; bisect_left(b) then
126
+ # yields exactly the count with exposure_ts < b (the exclusive edge).
127
+ per_variant: dict[str, list[datetime]] = {v: [] for v in variants}
128
+ for row in rows:
129
+ variant = row.get("variant")
130
+ timestamps = per_variant.get(variant)
131
+ if timestamps is None:
132
+ continue # a variant not declared this run — never counted
133
+ ts = to_naive_utc(row.get("exposure_ts"))
134
+ if ts is not None:
135
+ timestamps.append(ts)
136
+ for timestamps in per_variant.values():
137
+ timestamps.sort()
138
+ return [
139
+ {v: bisect.bisect_left(per_variant[v], boundary) for v in variants}
140
+ for boundary in boundaries
141
+ ]
142
+
143
+ def get_first_exposure_ts(self, experiment: str) -> datetime | None:
144
+ """Earliest exposure timestamp (diagnostics/plan)."""
145
+ full_table_name = self._manager.get_full_table_name(TABLE_EXPOSURES, use_internal=True)
146
+ rows = self._manager.execute_query(
147
+ f"SELECT min(exposure_ts) AS first_ts FROM {full_table_name} "
148
+ "WHERE experiment = %(e)s",
149
+ {"e": experiment},
150
+ )
151
+ if not rows:
152
+ return None
153
+ return self._normalize_max_timestamp(rows[0].get("first_ts"))
154
+
155
+ def count_exposures(self, experiment: str) -> int:
156
+ """Total cohort size (deduped)."""
157
+ full_table_name = self._manager.get_full_table_name(TABLE_EXPOSURES, use_internal=True)
158
+ rows = self._manager.execute_query(
159
+ f"SELECT count(*) AS cnt FROM {full_table_name}{self._manager.final_modifier} "
160
+ "WHERE experiment = %(e)s",
161
+ {"e": experiment},
162
+ )
163
+ return int(rows[0]["cnt"]) if rows else 0
@@ -0,0 +1,72 @@
1
+ """Maintenance mixin: cross-table cleanup helpers for ``abk clean``.
2
+
3
+ These support pruning data left behind when an analyst edits experiment
4
+ configs — most importantly removing all rows for an experiment whose YAML no
5
+ longer exists in the project. They are used only by the ``abk clean`` CLI
6
+ command, never by the run pipeline.
7
+
8
+ Deliberate exclusions from the experiment purge:
9
+
10
+ - ``_ab_aa_runs`` — audit trail, kept forever.
11
+ - ``_ab_unit_state`` — keyed by (source_table, column_set_id), NOT by
12
+ experiment (cumulative-intervals.md §5.3): state rows are shared across
13
+ experiments reading the same fact source, so no experiment owns them.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from abkit.database.internal_tables._base import _InternalTablesBase
19
+ from abkit.database.tables import (
20
+ TABLE_EXPERIMENTS,
21
+ TABLE_EXPOSURES,
22
+ TABLE_RESULTS,
23
+ TABLE_TASKS,
24
+ )
25
+
26
+ #: tables keyed by ``experiment`` (a removed experiment orphans rows in each)
27
+ EXPERIMENT_KEYED_TABLES: tuple[str, ...] = (
28
+ TABLE_EXPERIMENTS,
29
+ TABLE_EXPOSURES,
30
+ TABLE_RESULTS,
31
+ TABLE_TASKS,
32
+ )
33
+
34
+
35
+ class _MaintenanceMixin(_InternalTablesBase):
36
+ def list_known_experiments(self) -> set[str]:
37
+ """Return every ``experiment`` that has rows in any internal table.
38
+
39
+ Unions ``SELECT DISTINCT experiment`` across all experiment-keyed
40
+ tables so an experiment is reported even if it only ever loaded
41
+ exposures (and thus never wrote a result).
42
+ """
43
+ names: set[str] = set()
44
+ for table in EXPERIMENT_KEYED_TABLES:
45
+ full_table_name = self._manager.get_full_table_name(table, use_internal=True)
46
+ query = f"SELECT DISTINCT experiment FROM {full_table_name}"
47
+ result = self._manager.execute_query(query)
48
+ names.update(row["experiment"] for row in result if row.get("experiment"))
49
+ return names
50
+
51
+ def count_experiment_rows(self, experiment: str) -> dict[str, int]:
52
+ """Return per-table row counts for *experiment* (for dry-run reports)."""
53
+ counts: dict[str, int] = {}
54
+ for table in EXPERIMENT_KEYED_TABLES:
55
+ full_table_name = self._manager.get_full_table_name(table, use_internal=True)
56
+ query = f"SELECT count(*) AS cnt FROM {full_table_name} WHERE experiment = %(e)s"
57
+ result = self._manager.execute_query(query, {"e": experiment})
58
+ counts[table] = int(result[0]["cnt"]) if result else 0
59
+ return counts
60
+
61
+ def purge_experiment(self, experiment: str) -> None:
62
+ """Delete every row for *experiment* across experiment-keyed tables.
63
+
64
+ Each delete is issued synchronously (``sync=True``) so the purge is
65
+ fully applied when this returns. ``_ab_aa_runs`` (audit) and
66
+ ``_ab_unit_state`` (not experiment-owned) are deliberately untouched.
67
+ """
68
+ for table in EXPERIMENT_KEYED_TABLES:
69
+ full_table_name = self._manager.get_full_table_name(table, use_internal=True)
70
+ self._manager.delete_rows(
71
+ full_table_name, "experiment = %(e)s", {"e": experiment}, sync=True
72
+ )
@@ -0,0 +1,231 @@
1
+ """Results mixin: ``_ab_results`` operations — the BI contract's write/read path.
2
+
3
+ Write path: the enrich stage flattens ``TestResult`` rows and calls
4
+ :meth:`save_results`; the strictly-monotonic ``created_at`` LWW version is
5
+ stamped HERE (one distinct tick per row) so no caller can accidentally write
6
+ tying versions.
7
+
8
+ Read paths: the planner anti-join (:meth:`list_computed_cutoffs` — a SET
9
+ reader, not a cursor: the cumulative grid is not resumed, late/backfilled
10
+ cutoffs make ``max()`` insufficient), the ``abk clean`` drift scan
11
+ (:meth:`list_method_config_ids`), and result loading for reports/e2e.
12
+ Every correctness-sensitive read is deduped (FINAL on ClickHouse).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from datetime import datetime
18
+ from typing import Any
19
+
20
+ import numpy as np
21
+
22
+ from abkit.database.internal_tables._base import _InternalTablesBase
23
+ from abkit.database.tables import TABLE_RESULTS, get_results_table_model
24
+ from abkit.utils.datetime_utils import to_naive_utc
25
+
26
+ #: contract columns the enrich stage must supply (everything except created_at)
27
+ RESULT_COLUMNS: tuple[str, ...] = tuple(
28
+ col.name for col in get_results_table_model().columns if col.name != "created_at"
29
+ )
30
+
31
+
32
+ class _ResultsMixin(_InternalTablesBase):
33
+ def results_table_exists(self) -> bool:
34
+ """True when ``_ab_results`` exists — a never-run project has none.
35
+
36
+ Read-only surfaces (``abk run --report`` on a fresh project, explore)
37
+ guard with this instead of ``ensure_tables()``: reporting must never
38
+ create schema (m3-implementation-plan.md WP2).
39
+ """
40
+ return self._manager.table_exists(TABLE_RESULTS, schema=self._manager.internal_location)
41
+
42
+ def save_results(self, data: dict[str, np.ndarray]) -> int:
43
+ """Persist a batch of enriched result rows (LWW upsert semantics).
44
+
45
+ ``data`` must contain exactly the contract columns (RESULT_COLUMNS);
46
+ ``created_at`` is stamped here with one strictly-increasing distinct
47
+ version per row (quorum must-fix).
48
+ """
49
+ missing = [c for c in RESULT_COLUMNS if c not in data]
50
+ if missing:
51
+ raise ValueError(f"result batch is missing contract columns: {missing}")
52
+ extra = [c for c in data if c not in RESULT_COLUMNS]
53
+ if extra:
54
+ raise ValueError(f"result batch has unknown columns: {extra}")
55
+
56
+ num_rows = len(data["experiment"])
57
+ if num_rows == 0:
58
+ return 0
59
+
60
+ insert_data = dict(data)
61
+ insert_data["created_at"] = np.array(
62
+ [self.next_version_ts() for _ in range(num_rows)], dtype=object
63
+ )
64
+
65
+ full_table_name = self._manager.get_full_table_name(TABLE_RESULTS, use_internal=True)
66
+ return self._manager.insert_batch(full_table_name, insert_data, conflict_strategy="ignore")
67
+
68
+ def list_computed_cutoffs(
69
+ self, experiment: str, metric: str, method_config_id: str
70
+ ) -> set[datetime]:
71
+ """The planner anti-join source: every ``end_ts`` already computed.
72
+
73
+ Returns naive-UTC datetimes. A SET, not a max-cursor: a late hole in
74
+ the middle of the grid must be re-planned (plan WP7).
75
+ """
76
+ full_table_name = self._manager.get_full_table_name(TABLE_RESULTS, use_internal=True)
77
+ query = f"""
78
+ SELECT DISTINCT end_ts
79
+ FROM {full_table_name}{self._manager.final_modifier}
80
+ WHERE experiment = %(e)s
81
+ AND metric = %(m)s
82
+ AND method_config_id = %(mc)s
83
+ """
84
+ rows = self._manager.execute_query(
85
+ query, {"e": experiment, "m": metric, "mc": method_config_id}
86
+ )
87
+ cutoffs: set[datetime] = set()
88
+ for row in rows:
89
+ ts = to_naive_utc(row.get("end_ts"))
90
+ if ts is not None:
91
+ cutoffs.add(ts)
92
+ return cutoffs
93
+
94
+ def series_pair_ci_kinds(
95
+ self, experiment: str, metric: str, method_config_id: str
96
+ ) -> dict[tuple[str, str], set[str]]:
97
+ """Per-pair DISTINCT ``ci_kind`` among the NON-DEMOTED rows of a series.
98
+
99
+ The planner's sequential-mode self-invalidation (M5 WP3, plan B4):
100
+ ``sequential.enabled``/``ci_kind`` are deliberately excluded from
101
+ ``method_config_id`` (D7 — toggling must not orphan the series), so the
102
+ anti-join alone would treat a mode flip as "already computed" and skip
103
+ it, leaving stale ``ci_kind='fixed'`` rows. The driver compares this
104
+ persisted map against the mode THIS run stamps and forces a re-plan on a
105
+ mismatch.
106
+
107
+ Keyed **per (name_1, name_2)** because the first-usable-look τ² anchor
108
+ (D-Seq-anchor) can legitimately leave a pair that first becomes usable
109
+ AFTER the anchor cutoff ``fixed`` while another pair is ``always_valid``
110
+ — a series-wide aggregate would false-positive on that. Demoted rows
111
+ (``insufficient_data`` — no CI, always stamped ``'fixed'``) are excluded
112
+ so a small-sample early cutoff never reads as a mode mismatch. Deduped
113
+ (FINAL on ClickHouse).
114
+ """
115
+ full_table_name = self._manager.get_full_table_name(TABLE_RESULTS, use_internal=True)
116
+ query = f"""
117
+ SELECT DISTINCT name_1, name_2, ci_kind, insufficient_data
118
+ FROM {full_table_name}{self._manager.final_modifier}
119
+ WHERE experiment = %(e)s
120
+ AND metric = %(m)s
121
+ AND method_config_id = %(mc)s
122
+ """
123
+ rows = self._manager.execute_query(
124
+ query, {"e": experiment, "m": metric, "mc": method_config_id}
125
+ )
126
+ pairs: dict[tuple[str, str], set[str]] = {}
127
+ for row in rows:
128
+ if row.get("insufficient_data"):
129
+ continue
130
+ pair = (row.get("name_1"), row.get("name_2"))
131
+ pairs.setdefault(pair, set()).add(row.get("ci_kind") or "fixed")
132
+ return pairs
133
+
134
+ def list_method_config_ids(
135
+ self, experiment: str, metric: str | None = None
136
+ ) -> dict[tuple[str, str], int]:
137
+ """``{(metric, method_config_id): row_count}`` stored for an experiment.
138
+
139
+ The ``abk clean`` drift scan diffs this against the ids the current
140
+ YAML produces (through the SAME MethodConfig.build path the pipeline
141
+ stamps rows with); ``run``/``explore`` warn when a metric has more
142
+ than one id (duplicate stabilization lines in BI).
143
+ """
144
+ full_table_name = self._manager.get_full_table_name(TABLE_RESULTS, use_internal=True)
145
+ where = "experiment = %(e)s"
146
+ params: dict[str, Any] = {"e": experiment}
147
+ if metric is not None:
148
+ where += " AND metric = %(m)s"
149
+ params["m"] = metric
150
+ query = f"""
151
+ SELECT metric, method_config_id, count(*) AS cnt
152
+ FROM {full_table_name}{self._manager.final_modifier}
153
+ WHERE {where}
154
+ GROUP BY metric, method_config_id
155
+ """
156
+ rows = self._manager.execute_query(query, params)
157
+ return {
158
+ (row["metric"], row["method_config_id"]): int(row["cnt"])
159
+ for row in rows
160
+ if row.get("metric") and row.get("method_config_id")
161
+ }
162
+
163
+ def delete_results(
164
+ self,
165
+ experiment: str,
166
+ metric: str | None = None,
167
+ method_config_id: str | None = None,
168
+ from_ts: datetime | None = None,
169
+ to_ts: datetime | None = None,
170
+ mutations_sync: bool = False,
171
+ ) -> int:
172
+ """Delete result rows for the supplied filter set.
173
+
174
+ Used by ``abk clean`` (drift pruning; passes ``mutations_sync=True``
175
+ so a follow-up dry-run reflects the deletion) and by
176
+ ``run --full-refresh --from/--to`` (re-opening frozen cutoffs;
177
+ ``[from_ts, to_ts)`` filters on ``end_ts``).
178
+ """
179
+ full_table_name = self._manager.get_full_table_name(TABLE_RESULTS, use_internal=True)
180
+ where_parts = ["experiment = %(experiment)s"]
181
+ params: dict[str, Any] = {"experiment": experiment}
182
+ if metric:
183
+ where_parts.append("metric = %(metric)s")
184
+ params["metric"] = metric
185
+ if method_config_id:
186
+ where_parts.append("method_config_id = %(method_config_id)s")
187
+ params["method_config_id"] = method_config_id
188
+ if from_ts:
189
+ where_parts.append("end_ts >= %(from_ts)s")
190
+ params["from_ts"] = from_ts
191
+ if to_ts:
192
+ where_parts.append("end_ts < %(to_ts)s")
193
+ params["to_ts"] = to_ts
194
+
195
+ return self._manager.delete_rows(
196
+ full_table_name, " AND ".join(where_parts), params, sync=mutations_sync
197
+ )
198
+
199
+ def load_results(
200
+ self,
201
+ experiment: str,
202
+ metric: str | None = None,
203
+ method_config_id: str | None = None,
204
+ ) -> list[dict]:
205
+ """Load result rows ascending by ``end_ts`` (deduped).
206
+
207
+ Timestamps are normalised to naive UTC. Serves reports and the e2e
208
+ byte-stability assertions; BI reads the table directly.
209
+ """
210
+ full_table_name = self._manager.get_full_table_name(TABLE_RESULTS, use_internal=True)
211
+ where_parts = ["experiment = %(experiment)s"]
212
+ params: dict[str, Any] = {"experiment": experiment}
213
+ if metric:
214
+ where_parts.append("metric = %(metric)s")
215
+ params["metric"] = metric
216
+ if method_config_id:
217
+ where_parts.append("method_config_id = %(method_config_id)s")
218
+ params["method_config_id"] = method_config_id
219
+
220
+ query = f"""
221
+ SELECT *
222
+ FROM {full_table_name}{self._manager.final_modifier}
223
+ WHERE {" AND ".join(where_parts)}
224
+ ORDER BY metric, name_1, name_2, method_config_id, end_ts
225
+ """
226
+ rows = self._manager.execute_query(query, params)
227
+ for row in rows:
228
+ for ts_col in ("start_ts", "end_ts", "watermark_ts", "created_at"):
229
+ if row.get(ts_col) is not None:
230
+ row[ts_col] = to_naive_utc(row[ts_col])
231
+ return rows
@@ -0,0 +1,23 @@
1
+ """Schema management mixin (creates internal tables on demand)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abkit.database.internal_tables._base import _InternalTablesBase
6
+ from abkit.database.tables import INTERNAL_TABLES
7
+
8
+
9
+ class _SchemaMixin(_InternalTablesBase):
10
+ def ensure_tables(self) -> None:
11
+ """Create every internal ``_ab_*`` table that doesn't exist yet.
12
+
13
+ Idempotent: safe to call on every CLI invocation.
14
+ """
15
+ for table_name, model_factory in INTERNAL_TABLES.items():
16
+ full_table_name = self._manager.get_full_table_name(table_name, use_internal=True)
17
+ table_model = model_factory()
18
+ # Always register the schema so the manager knows each table's primary
19
+ # key / version column on the insert path — even on a fresh manager
20
+ # whose tables already exist (so create_table below is skipped).
21
+ self._manager.register_table(full_table_name, table_model)
22
+ if not self._manager.table_exists(table_name, schema=self._manager.internal_location):
23
+ self._manager.create_table(full_table_name, table_model, if_not_exists=True)