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.
- ab_analysis_kit-0.0.1.dev0.dist-info/METADATA +126 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/RECORD +122 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/WHEEL +5 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/entry_points.txt +2 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/licenses/LICENSE +21 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/top_level.txt +1 -0
- abkit/__init__.py +40 -0
- abkit/cli/__init__.py +1 -0
- abkit/cli/_output.py +111 -0
- abkit/cli/commands/__init__.py +1 -0
- abkit/cli/commands/_context.py +83 -0
- abkit/cli/commands/clean.py +133 -0
- abkit/cli/commands/explore.py +208 -0
- abkit/cli/commands/init.py +427 -0
- abkit/cli/commands/run.py +282 -0
- abkit/cli/commands/unlock.py +59 -0
- abkit/cli/commands/validate.py +264 -0
- abkit/cli/main.py +279 -0
- abkit/compute/__init__.py +5 -0
- abkit/compute/recompute_backend.py +140 -0
- abkit/config/__init__.py +51 -0
- abkit/config/discovery.py +168 -0
- abkit/config/experiment_config.py +511 -0
- abkit/config/method_config.py +80 -0
- abkit/config/metric_config.py +214 -0
- abkit/config/profile.py +301 -0
- abkit/config/project_config.py +244 -0
- abkit/config/validator.py +393 -0
- abkit/core/__init__.py +26 -0
- abkit/core/interval.py +148 -0
- abkit/core/models.py +121 -0
- abkit/core/period_planner.py +206 -0
- abkit/database/__init__.py +51 -0
- abkit/database/_sql_manager.py +432 -0
- abkit/database/clickhouse_manager.py +495 -0
- abkit/database/internal_tables/__init__.py +6 -0
- abkit/database/internal_tables/_aa_runs.py +53 -0
- abkit/database/internal_tables/_base.py +71 -0
- abkit/database/internal_tables/_experiments.py +82 -0
- abkit/database/internal_tables/_exposures.py +163 -0
- abkit/database/internal_tables/_maintenance.py +72 -0
- abkit/database/internal_tables/_results.py +231 -0
- abkit/database/internal_tables/_schema.py +23 -0
- abkit/database/internal_tables/_tasks.py +237 -0
- abkit/database/internal_tables/_unit_state.py +148 -0
- abkit/database/internal_tables/manager.py +30 -0
- abkit/database/manager.py +450 -0
- abkit/database/mysql_manager.py +175 -0
- abkit/database/postgres_manager.py +145 -0
- abkit/database/tables.py +326 -0
- abkit/loaders/__init__.py +28 -0
- abkit/loaders/exposure_loader.py +121 -0
- abkit/loaders/metric_loader.py +251 -0
- abkit/loaders/query_template.py +167 -0
- abkit/loaders/templates/abkit_assignment.jinja +62 -0
- abkit/pipeline/__init__.py +37 -0
- abkit/pipeline/_types.py +52 -0
- abkit/pipeline/analyze.py +223 -0
- abkit/pipeline/driver.py +477 -0
- abkit/pipeline/enrich.py +137 -0
- abkit/pipeline/readout.py +779 -0
- abkit/reporting/__init__.py +19 -0
- abkit/reporting/assets/report.js +138 -0
- abkit/reporting/builder.py +484 -0
- abkit/reporting/calibration.py +182 -0
- abkit/reporting/html_report.py +109 -0
- abkit/stats/__init__.py +94 -0
- abkit/stats/accumulate.py +82 -0
- abkit/stats/base.py +347 -0
- abkit/stats/bootstrap/__init__.py +69 -0
- abkit/stats/bootstrap/applier.py +81 -0
- abkit/stats/bootstrap/bootstrap.py +311 -0
- abkit/stats/bootstrap/ci.py +72 -0
- abkit/stats/bootstrap/engine.py +383 -0
- abkit/stats/bootstrap/paired_bootstrap.py +57 -0
- abkit/stats/bootstrap/paired_post_normed_bootstrap.py +81 -0
- abkit/stats/bootstrap/poisson_bootstrap.py +112 -0
- abkit/stats/bootstrap/post_normed_bootstrap.py +102 -0
- abkit/stats/correction.py +88 -0
- abkit/stats/effects.py +141 -0
- abkit/stats/exceptions.py +31 -0
- abkit/stats/factory.py +26 -0
- abkit/stats/parametric/__init__.py +10 -0
- abkit/stats/parametric/cuped_ttest.py +183 -0
- abkit/stats/parametric/paired_cuped_ttest.py +125 -0
- abkit/stats/parametric/paired_ttest.py +136 -0
- abkit/stats/parametric/ratio_delta.py +113 -0
- abkit/stats/parametric/ttest.py +105 -0
- abkit/stats/parametric/ztest.py +134 -0
- abkit/stats/power.py +278 -0
- abkit/stats/registry.py +111 -0
- abkit/stats/result.py +84 -0
- abkit/stats/rng.py +39 -0
- abkit/stats/samples.py +531 -0
- abkit/stats/sequential/__init__.py +18 -0
- abkit/stats/sequential/apply.py +37 -0
- abkit/stats/sequential/confidence_sequence.py +96 -0
- abkit/stats/sequential/mixture.py +70 -0
- abkit/stats/srm.py +221 -0
- abkit/tuning/__init__.py +59 -0
- abkit/tuning/assets/explore.js +173 -0
- abkit/tuning/config_writer.py +409 -0
- abkit/tuning/html.py +88 -0
- abkit/tuning/payload.py +122 -0
- abkit/tuning/recompute.py +1039 -0
- abkit/tuning/server.py +882 -0
- abkit/tuning/session.py +233 -0
- abkit/utils/__init__.py +27 -0
- abkit/utils/datetime_utils.py +97 -0
- abkit/utils/env_interpolation.py +50 -0
- abkit/utils/json_utils.py +38 -0
- abkit/validate/__init__.py +36 -0
- abkit/validate/_types.py +35 -0
- abkit/validate/inject.py +75 -0
- abkit/validate/load.py +160 -0
- abkit/validate/panel.py +59 -0
- abkit/validate/persistence.py +59 -0
- abkit/validate/resample.py +94 -0
- abkit/validate/result.py +60 -0
- abkit/validate/run_id.py +45 -0
- abkit/validate/runner.py +389 -0
- abkit/validate/scoring.py +544 -0
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""Task locking mixin: ``_ab_tasks`` operations.
|
|
2
|
+
|
|
3
|
+
Owns the ``_ab_tasks`` POLICY (row shape, staleness semantics, owner token);
|
|
4
|
+
the atomicity PRIMITIVE lives in the generic manager
|
|
5
|
+
(``BaseDatabaseManager.try_acquire_lock``) — PG/MySQL claim in a single
|
|
6
|
+
statement, ClickHouse is advisory with a read-back tie-break (see the manager
|
|
7
|
+
docstrings for the per-backend contract).
|
|
8
|
+
|
|
9
|
+
Lock grain: ``(experiment, scope, process_type)``. The default whole-pipeline
|
|
10
|
+
lock is ``scope="pipeline"``; the key shape reserves per-metric scopes for
|
|
11
|
+
later parallelism (cumulative-intervals.md §5.7).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import socket
|
|
18
|
+
import uuid
|
|
19
|
+
from datetime import datetime
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
from abkit.database.internal_tables._base import _InternalTablesBase
|
|
25
|
+
from abkit.database.tables import TABLE_TASKS
|
|
26
|
+
from abkit.utils.datetime_utils import now_utc_naive, to_naive_utc
|
|
27
|
+
|
|
28
|
+
DEFAULT_SCOPE = "pipeline"
|
|
29
|
+
DEFAULT_PROCESS_TYPE = "run"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _make_owner_token() -> str:
|
|
33
|
+
"""Owner token: unique per claim attempt (host:pid:nonce).
|
|
34
|
+
|
|
35
|
+
Required by the ClickHouse advisory claim's read-back verification; also
|
|
36
|
+
makes ``check_lock`` output human-attributable.
|
|
37
|
+
"""
|
|
38
|
+
return f"{socket.gethostname()}:{os.getpid()}:{uuid.uuid4().hex[:8]}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _TasksMixin(_InternalTablesBase):
|
|
42
|
+
def acquire_lock(
|
|
43
|
+
self,
|
|
44
|
+
experiment: str,
|
|
45
|
+
scope: str = DEFAULT_SCOPE,
|
|
46
|
+
process_type: str = DEFAULT_PROCESS_TYPE,
|
|
47
|
+
timeout_seconds: int = 3600,
|
|
48
|
+
force: bool = False,
|
|
49
|
+
) -> bool:
|
|
50
|
+
"""Try to acquire the task lock; return False if it's actively held.
|
|
51
|
+
|
|
52
|
+
A ``running`` row whose age exceeds ``timeout_seconds`` is treated as
|
|
53
|
+
stale and overridden — the owning process likely died without
|
|
54
|
+
releasing the lock (e.g. the database restarted mid-run), and a hung
|
|
55
|
+
row must never block future runs.
|
|
56
|
+
|
|
57
|
+
With ``force=True`` the running-status check is skipped entirely and
|
|
58
|
+
the lock is taken unconditionally (synchronous replace); the row is
|
|
59
|
+
still (re)written as ``running`` so the forced run owns the lock and
|
|
60
|
+
releases it on exit.
|
|
61
|
+
"""
|
|
62
|
+
row = self._task_row(
|
|
63
|
+
experiment, scope, process_type, status="running", timeout_seconds=timeout_seconds
|
|
64
|
+
)
|
|
65
|
+
full_table_name = self._manager.get_full_table_name(TABLE_TASKS, use_internal=True)
|
|
66
|
+
key_columns = {"experiment": experiment, "scope": scope, "process_type": process_type}
|
|
67
|
+
|
|
68
|
+
if force:
|
|
69
|
+
self._manager.upsert_record(
|
|
70
|
+
full_table_name, key_columns, self._row_arrays(row), sync=True
|
|
71
|
+
)
|
|
72
|
+
self._owned_lock_tokens[(experiment, scope, process_type)] = row["locked_by"]
|
|
73
|
+
return True
|
|
74
|
+
|
|
75
|
+
claimed = self._manager.try_acquire_lock(
|
|
76
|
+
full_table_name,
|
|
77
|
+
key_columns,
|
|
78
|
+
row,
|
|
79
|
+
status_column="status",
|
|
80
|
+
running_value="running",
|
|
81
|
+
heartbeat_column="started_at",
|
|
82
|
+
timeout_seconds=timeout_seconds,
|
|
83
|
+
token_column="locked_by",
|
|
84
|
+
)
|
|
85
|
+
if claimed:
|
|
86
|
+
self._owned_lock_tokens[(experiment, scope, process_type)] = row["locked_by"]
|
|
87
|
+
return claimed
|
|
88
|
+
|
|
89
|
+
def clear_lock(
|
|
90
|
+
self,
|
|
91
|
+
experiment: str,
|
|
92
|
+
scope: str = DEFAULT_SCOPE,
|
|
93
|
+
process_type: str = DEFAULT_PROCESS_TYPE,
|
|
94
|
+
) -> bool:
|
|
95
|
+
"""Force-release a (possibly stale) lock; return True if one was held.
|
|
96
|
+
|
|
97
|
+
Used by ``abk unlock`` to recover from a hung run that left a
|
|
98
|
+
``running`` row behind. The age check is ignored so even a not-yet-
|
|
99
|
+
stale lock is cleared. Marks the task ``completed`` so future runs
|
|
100
|
+
proceed without ``--force``.
|
|
101
|
+
"""
|
|
102
|
+
existing = self.check_lock(experiment, scope, process_type, ignore_timeout=True)
|
|
103
|
+
if existing is None:
|
|
104
|
+
return False
|
|
105
|
+
|
|
106
|
+
self.release_lock(experiment, scope, process_type, status="completed", force=True)
|
|
107
|
+
return True
|
|
108
|
+
|
|
109
|
+
def release_lock(
|
|
110
|
+
self,
|
|
111
|
+
experiment: str,
|
|
112
|
+
scope: str,
|
|
113
|
+
process_type: str,
|
|
114
|
+
status: str,
|
|
115
|
+
error_message: str | None = None,
|
|
116
|
+
force: bool = False,
|
|
117
|
+
) -> bool:
|
|
118
|
+
"""Mark the task as ``completed`` or ``failed``. Returns True if released.
|
|
119
|
+
|
|
120
|
+
OWNERSHIP-CHECKED by default: a run whose lock aged past its timeout
|
|
121
|
+
and was legitimately stolen by a newer run must NOT wipe the new
|
|
122
|
+
owner's live ``running`` row on exit — the release is skipped and
|
|
123
|
+
False is returned (the caller logs it). The check reads the current
|
|
124
|
+
row's ``locked_by`` against the token this instance recorded at
|
|
125
|
+
acquire time; ``force=True`` (``abk unlock``) skips it.
|
|
126
|
+
|
|
127
|
+
A successful release is a synchronous full replace (delete by key +
|
|
128
|
+
insert), so on ClickHouse it also sweeps any loser rows a racing
|
|
129
|
+
advisory claim left behind.
|
|
130
|
+
"""
|
|
131
|
+
key = (experiment, scope, process_type)
|
|
132
|
+
full_table_name = self._manager.get_full_table_name(TABLE_TASKS, use_internal=True)
|
|
133
|
+
|
|
134
|
+
if not force:
|
|
135
|
+
token = self._owned_lock_tokens.get(key)
|
|
136
|
+
if token is None:
|
|
137
|
+
return False # never acquired by this instance — nothing to release
|
|
138
|
+
current = self._manager.execute_query(
|
|
139
|
+
f"SELECT locked_by FROM {full_table_name} "
|
|
140
|
+
"WHERE experiment = %(experiment)s AND scope = %(scope)s "
|
|
141
|
+
"AND process_type = %(process_type)s",
|
|
142
|
+
{"experiment": experiment, "scope": scope, "process_type": process_type},
|
|
143
|
+
)
|
|
144
|
+
owners = {str(r.get("locked_by")) for r in current}
|
|
145
|
+
if current and token not in owners:
|
|
146
|
+
# The lock was stolen (our row aged out); leave the new owner alone.
|
|
147
|
+
self._owned_lock_tokens.pop(key, None)
|
|
148
|
+
return False
|
|
149
|
+
|
|
150
|
+
row = self._task_row(
|
|
151
|
+
experiment, scope, process_type, status=status, error_message=error_message
|
|
152
|
+
)
|
|
153
|
+
self._manager.upsert_record(
|
|
154
|
+
full_table_name,
|
|
155
|
+
{"experiment": experiment, "scope": scope, "process_type": process_type},
|
|
156
|
+
self._row_arrays(row),
|
|
157
|
+
sync=True,
|
|
158
|
+
)
|
|
159
|
+
self._owned_lock_tokens.pop(key, None)
|
|
160
|
+
return True
|
|
161
|
+
|
|
162
|
+
def check_lock(
|
|
163
|
+
self,
|
|
164
|
+
experiment: str,
|
|
165
|
+
scope: str = DEFAULT_SCOPE,
|
|
166
|
+
process_type: str = DEFAULT_PROCESS_TYPE,
|
|
167
|
+
ignore_timeout: bool = False,
|
|
168
|
+
) -> dict | None:
|
|
169
|
+
"""Return an active running-task row, or ``None`` if no lock is active.
|
|
170
|
+
|
|
171
|
+
A ``running`` row whose age (``now - started_at``) exceeds its stored
|
|
172
|
+
``timeout_seconds`` is considered stale and reported as released
|
|
173
|
+
(returns ``None``), so a hung process never blocks future runs. Pass
|
|
174
|
+
``ignore_timeout=True`` to get the raw running row regardless of age
|
|
175
|
+
(used by ``abk unlock`` to detect and report even stale locks).
|
|
176
|
+
|
|
177
|
+
Scans ALL rows for the key (a ClickHouse advisory race can leave more
|
|
178
|
+
than one): any live running row means locked.
|
|
179
|
+
"""
|
|
180
|
+
full_table_name = self._manager.get_full_table_name(TABLE_TASKS, use_internal=True)
|
|
181
|
+
query = f"""
|
|
182
|
+
SELECT *
|
|
183
|
+
FROM {full_table_name}
|
|
184
|
+
WHERE experiment = %(experiment)s
|
|
185
|
+
AND scope = %(scope)s
|
|
186
|
+
AND process_type = %(process_type)s
|
|
187
|
+
AND status = 'running'
|
|
188
|
+
"""
|
|
189
|
+
results = self._manager.execute_query(
|
|
190
|
+
query,
|
|
191
|
+
{"experiment": experiment, "scope": scope, "process_type": process_type},
|
|
192
|
+
)
|
|
193
|
+
if not results:
|
|
194
|
+
return None
|
|
195
|
+
|
|
196
|
+
if ignore_timeout:
|
|
197
|
+
return results[0]
|
|
198
|
+
|
|
199
|
+
now = now_utc_naive()
|
|
200
|
+
for row in results:
|
|
201
|
+
started_at = to_naive_utc(row.get("started_at"))
|
|
202
|
+
timeout_seconds = row.get("timeout_seconds")
|
|
203
|
+
if started_at is None or timeout_seconds is None:
|
|
204
|
+
return row
|
|
205
|
+
if (now - started_at).total_seconds() <= timeout_seconds:
|
|
206
|
+
return row
|
|
207
|
+
# Every running row is stale: the owners never released. Treat as free.
|
|
208
|
+
return None
|
|
209
|
+
|
|
210
|
+
# ── row assembly ─────────────────────────────────────────────────────────
|
|
211
|
+
|
|
212
|
+
@staticmethod
|
|
213
|
+
def _task_row(
|
|
214
|
+
experiment: str,
|
|
215
|
+
scope: str,
|
|
216
|
+
process_type: str,
|
|
217
|
+
status: str,
|
|
218
|
+
timeout_seconds: int = 3600,
|
|
219
|
+
error_message: str | None = None,
|
|
220
|
+
started_at: datetime | None = None,
|
|
221
|
+
) -> dict[str, Any]:
|
|
222
|
+
now = now_utc_naive()
|
|
223
|
+
return {
|
|
224
|
+
"experiment": experiment,
|
|
225
|
+
"scope": scope,
|
|
226
|
+
"process_type": process_type,
|
|
227
|
+
"status": status,
|
|
228
|
+
"started_at": started_at or now,
|
|
229
|
+
"updated_at": now,
|
|
230
|
+
"locked_by": _make_owner_token(),
|
|
231
|
+
"error_message": error_message,
|
|
232
|
+
"timeout_seconds": timeout_seconds,
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
@staticmethod
|
|
236
|
+
def _row_arrays(row: dict[str, Any]) -> dict[str, np.ndarray]:
|
|
237
|
+
return {col: np.array([value], dtype=object) for col, value in row.items()}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Unit-state mixin: ``_ab_unit_state`` operations (the scalability seam).
|
|
2
|
+
|
|
3
|
+
v1 is a THIN materialization — the compute read path stays recompute — but the
|
|
4
|
+
two invariants that would be silent corruption by the time v2 flips the read
|
|
5
|
+
path are enforced NOW (cumulative-intervals.md §5.2/§5.3):
|
|
6
|
+
|
|
7
|
+
1. **Idempotent per (source, column-set, day)**: replace-not-sum. Writing a
|
|
8
|
+
day twice leaves aggregates unchanged (the twice-run invariant test).
|
|
9
|
+
2. **Cardinality key** ``(source_table, column_set_id, unit_id, day)`` — NOT
|
|
10
|
+
per (experiment, metric) — so co-located metrics sharing a fact source
|
|
11
|
+
share one set of per-unit moments. State rows are deliberately
|
|
12
|
+
experiment-independent: the exposure join happens at read time.
|
|
13
|
+
|
|
14
|
+
The state stage advances only at day close (§6.4); sub-day cutoffs read
|
|
15
|
+
closed-day state plus a current-day fact tail.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import hashlib
|
|
21
|
+
from datetime import date
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
|
|
26
|
+
from abkit.database.internal_tables._base import _InternalTablesBase
|
|
27
|
+
from abkit.database.tables import TABLE_UNIT_STATE
|
|
28
|
+
from abkit.utils.json_utils import json_dumps_sorted
|
|
29
|
+
|
|
30
|
+
#: moment columns in table order; absent moments must be written as 0.0
|
|
31
|
+
MOMENT_COLUMNS = (
|
|
32
|
+
"n",
|
|
33
|
+
"sum_value",
|
|
34
|
+
"sum_value_sq",
|
|
35
|
+
"sum_cov",
|
|
36
|
+
"sum_cov_sq",
|
|
37
|
+
"sum_value_cov",
|
|
38
|
+
"sum_denominator",
|
|
39
|
+
"sum_denominator_sq",
|
|
40
|
+
"sum_value_denominator",
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def compute_column_set_id(source_table: str, column_roles: dict[str, str]) -> str:
|
|
45
|
+
"""Identity of a (source table, column-role set) pair — 16 hex chars.
|
|
46
|
+
|
|
47
|
+
Two metrics reading the same columns of the same fact table share one
|
|
48
|
+
state series (§5.3). Hashed over the canonical JSON of the source table
|
|
49
|
+
plus the role->column mapping so identity survives dict ordering.
|
|
50
|
+
"""
|
|
51
|
+
payload = json_dumps_sorted({"source_table": source_table, "columns": column_roles})
|
|
52
|
+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class _UnitStateMixin(_InternalTablesBase):
|
|
56
|
+
def replace_day_state(
|
|
57
|
+
self,
|
|
58
|
+
source_table: str,
|
|
59
|
+
column_set_id: str,
|
|
60
|
+
day: date,
|
|
61
|
+
data: dict[str, np.ndarray],
|
|
62
|
+
) -> int:
|
|
63
|
+
"""Replace one closed day's per-unit moments (replace-not-sum, §5.2).
|
|
64
|
+
|
|
65
|
+
Synchronously deletes every row for ``(source_table, column_set_id,
|
|
66
|
+
day)`` then inserts the new batch, so a re-run/backfill/lost-lock
|
|
67
|
+
retry can never double-count. ``data`` must contain ``unit_id`` plus
|
|
68
|
+
any subset of :data:`MOMENT_COLUMNS` (missing moments are written as
|
|
69
|
+
zeros); the ``version`` is stamped here.
|
|
70
|
+
"""
|
|
71
|
+
if "unit_id" not in data:
|
|
72
|
+
raise ValueError("unit state data must contain a unit_id column")
|
|
73
|
+
unknown = [c for c in data if c != "unit_id" and c not in MOMENT_COLUMNS]
|
|
74
|
+
if unknown:
|
|
75
|
+
raise ValueError(f"unknown unit-state moment columns: {unknown}")
|
|
76
|
+
|
|
77
|
+
full_table_name = self._manager.get_full_table_name(TABLE_UNIT_STATE, use_internal=True)
|
|
78
|
+
self._manager.delete_rows(
|
|
79
|
+
full_table_name,
|
|
80
|
+
"source_table = %(s)s AND column_set_id = %(c)s AND day = %(d)s",
|
|
81
|
+
{"s": source_table, "c": column_set_id, "d": day},
|
|
82
|
+
sync=True,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
num_rows = len(data["unit_id"])
|
|
86
|
+
if num_rows == 0:
|
|
87
|
+
return 0
|
|
88
|
+
|
|
89
|
+
version = self.next_version_ts()
|
|
90
|
+
insert_data: dict[str, np.ndarray] = {
|
|
91
|
+
"source_table": np.full(num_rows, source_table, dtype=object),
|
|
92
|
+
"column_set_id": np.full(num_rows, column_set_id, dtype=object),
|
|
93
|
+
"unit_id": data["unit_id"],
|
|
94
|
+
"day": np.full(num_rows, day, dtype=object),
|
|
95
|
+
}
|
|
96
|
+
for moment in MOMENT_COLUMNS:
|
|
97
|
+
if moment in data:
|
|
98
|
+
insert_data[moment] = data[moment]
|
|
99
|
+
elif moment == "n":
|
|
100
|
+
insert_data[moment] = np.zeros(num_rows, dtype=np.int64)
|
|
101
|
+
else:
|
|
102
|
+
insert_data[moment] = np.zeros(num_rows, dtype=np.float64)
|
|
103
|
+
insert_data["version"] = np.full(num_rows, version, dtype=object)
|
|
104
|
+
|
|
105
|
+
return self._manager.insert_batch(full_table_name, insert_data, conflict_strategy="ignore")
|
|
106
|
+
|
|
107
|
+
def sum_moments(
|
|
108
|
+
self,
|
|
109
|
+
source_table: str,
|
|
110
|
+
column_set_id: str,
|
|
111
|
+
from_day: date,
|
|
112
|
+
to_day: date,
|
|
113
|
+
) -> dict[str, float]:
|
|
114
|
+
"""Aggregate moments over ``[from_day, to_day]`` (both inclusive).
|
|
115
|
+
|
|
116
|
+
Deduped (FINAL on ClickHouse) so replace-not-sum versions never
|
|
117
|
+
double-count mid-merge — the read side of the §5.2 invariant, and the
|
|
118
|
+
assertion surface for the twice-run test. v1 uses this only in tests;
|
|
119
|
+
the v2 incremental backend will read per-unit rows.
|
|
120
|
+
"""
|
|
121
|
+
full_table_name = self._manager.get_full_table_name(TABLE_UNIT_STATE, use_internal=True)
|
|
122
|
+
select = ", ".join(f"sum({m}) AS {m}" for m in MOMENT_COLUMNS)
|
|
123
|
+
rows = self._manager.execute_query(
|
|
124
|
+
f"SELECT {select} FROM {full_table_name}{self._manager.final_modifier} "
|
|
125
|
+
"WHERE source_table = %(s)s AND column_set_id = %(c)s "
|
|
126
|
+
"AND day >= %(from)s AND day <= %(to)s",
|
|
127
|
+
{"s": source_table, "c": column_set_id, "from": from_day, "to": to_day},
|
|
128
|
+
)
|
|
129
|
+
if not rows:
|
|
130
|
+
return dict.fromkeys(MOMENT_COLUMNS, 0.0)
|
|
131
|
+
row: dict[str, Any] = rows[0]
|
|
132
|
+
return {m: float(row[m]) if row.get(m) is not None else 0.0 for m in MOMENT_COLUMNS}
|
|
133
|
+
|
|
134
|
+
def get_last_state_day(self, source_table: str, column_set_id: str) -> date | None:
|
|
135
|
+
"""Latest closed day materialized for this state series."""
|
|
136
|
+
full_table_name = self._manager.get_full_table_name(TABLE_UNIT_STATE, use_internal=True)
|
|
137
|
+
rows = self._manager.execute_query(
|
|
138
|
+
f"SELECT max(day) AS last_day FROM {full_table_name} "
|
|
139
|
+
"WHERE source_table = %(s)s AND column_set_id = %(c)s",
|
|
140
|
+
{"s": source_table, "c": column_set_id},
|
|
141
|
+
)
|
|
142
|
+
if not rows or rows[0].get("last_day") is None:
|
|
143
|
+
return None
|
|
144
|
+
last_day = rows[0]["last_day"]
|
|
145
|
+
# ClickHouse returns the epoch date for an empty max(); normalise.
|
|
146
|
+
if last_day == date(1970, 1, 1):
|
|
147
|
+
return None
|
|
148
|
+
return last_day
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Composite :class:`InternalTablesManager` assembled from per-table mixins."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abkit.database.internal_tables._aa_runs import _AaRunsMixin
|
|
6
|
+
from abkit.database.internal_tables._experiments import _ExperimentsMixin
|
|
7
|
+
from abkit.database.internal_tables._exposures import _ExposuresMixin
|
|
8
|
+
from abkit.database.internal_tables._maintenance import _MaintenanceMixin
|
|
9
|
+
from abkit.database.internal_tables._results import _ResultsMixin
|
|
10
|
+
from abkit.database.internal_tables._schema import _SchemaMixin
|
|
11
|
+
from abkit.database.internal_tables._tasks import _TasksMixin
|
|
12
|
+
from abkit.database.internal_tables._unit_state import _UnitStateMixin
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class InternalTablesManager(
|
|
16
|
+
_SchemaMixin,
|
|
17
|
+
_ExperimentsMixin,
|
|
18
|
+
_ExposuresMixin,
|
|
19
|
+
_UnitStateMixin,
|
|
20
|
+
_ResultsMixin,
|
|
21
|
+
_AaRunsMixin,
|
|
22
|
+
_TasksMixin,
|
|
23
|
+
_MaintenanceMixin,
|
|
24
|
+
):
|
|
25
|
+
"""High-level façade over a :class:`BaseDatabaseManager` for ``_ab_*`` tables.
|
|
26
|
+
|
|
27
|
+
The class itself adds no behaviour; each mixin owns the methods for
|
|
28
|
+
one logical table. Splitting them keeps every file small and makes it
|
|
29
|
+
obvious where to look when tracking down a bug.
|
|
30
|
+
"""
|