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
abkit/core/interval.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Interval (duration) parsing and handling.
|
|
2
|
+
|
|
3
|
+
Used for the experiment ``cadence`` scalar and horizon arithmetic
|
|
4
|
+
(docs/specs/cumulative-intervals.md §6.1: grammar ``N{s,m,h,d,w}``, whole
|
|
5
|
+
seconds >= 1s). Long unit names ("10min", "2hours") are also accepted.
|
|
6
|
+
|
|
7
|
+
Schedule-typed cadence (the ``[{every, until}]`` coarsening list) is NOT this
|
|
8
|
+
class's job — segments are validated in config and expanded by
|
|
9
|
+
``core/period_planner`` (each segment's ``every``/``until`` is one Interval).
|
|
10
|
+
|
|
11
|
+
Supports:
|
|
12
|
+
- Integer seconds: 600
|
|
13
|
+
- String format: "30s", "10min", "1h", "1d", "2w"
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
from datetime import timedelta
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Interval:
|
|
21
|
+
"""
|
|
22
|
+
Represents a time interval in whole seconds.
|
|
23
|
+
|
|
24
|
+
Supports parsing from:
|
|
25
|
+
- Integer (seconds): 600
|
|
26
|
+
- String: "10min", "1h", "1d", "30s", "1w"
|
|
27
|
+
|
|
28
|
+
Examples:
|
|
29
|
+
>>> interval = Interval("10min")
|
|
30
|
+
>>> interval.seconds
|
|
31
|
+
600
|
|
32
|
+
>>> interval = Interval(3600)
|
|
33
|
+
>>> interval.seconds
|
|
34
|
+
3600
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
UNITS = {
|
|
38
|
+
"s": 1,
|
|
39
|
+
"sec": 1,
|
|
40
|
+
"second": 1,
|
|
41
|
+
"seconds": 1,
|
|
42
|
+
"m": 60,
|
|
43
|
+
"min": 60,
|
|
44
|
+
"minute": 60,
|
|
45
|
+
"minutes": 60,
|
|
46
|
+
"h": 3600,
|
|
47
|
+
"hour": 3600,
|
|
48
|
+
"hours": 3600,
|
|
49
|
+
"d": 86400,
|
|
50
|
+
"day": 86400,
|
|
51
|
+
"days": 86400,
|
|
52
|
+
"w": 604800,
|
|
53
|
+
"week": 604800,
|
|
54
|
+
"weeks": 604800,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
def __init__(self, value: int | str):
|
|
58
|
+
"""
|
|
59
|
+
Initialize interval from integer or string.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
value: Interval as integer (seconds) or string ("10min")
|
|
63
|
+
|
|
64
|
+
Raises:
|
|
65
|
+
ValueError: If string format is invalid
|
|
66
|
+
"""
|
|
67
|
+
if isinstance(value, bool):
|
|
68
|
+
raise TypeError(f"Interval must be int or str, got {type(value)}")
|
|
69
|
+
if isinstance(value, int):
|
|
70
|
+
if value <= 0:
|
|
71
|
+
raise ValueError(f"Interval must be positive, got {value}")
|
|
72
|
+
self._seconds = value
|
|
73
|
+
elif isinstance(value, str):
|
|
74
|
+
self._seconds = self._parse_string(value)
|
|
75
|
+
else:
|
|
76
|
+
raise TypeError(f"Interval must be int or str, got {type(value)}")
|
|
77
|
+
|
|
78
|
+
def _parse_string(self, s: str) -> int:
|
|
79
|
+
"""
|
|
80
|
+
Parse interval string.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
s: String like "10min", "1h", "30s"
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
Interval in seconds
|
|
87
|
+
|
|
88
|
+
Raises:
|
|
89
|
+
ValueError: If format is invalid
|
|
90
|
+
"""
|
|
91
|
+
s = s.strip().lower()
|
|
92
|
+
|
|
93
|
+
# Match pattern: digits followed by unit
|
|
94
|
+
match = re.match(r"^(\d+)([a-z]+)$", s)
|
|
95
|
+
if not match:
|
|
96
|
+
raise ValueError(
|
|
97
|
+
f"Invalid interval format: '{s}'. "
|
|
98
|
+
f"Expected format: <number><unit> (e.g., '10min', '1h')"
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
value_str, unit = match.groups()
|
|
102
|
+
value = int(value_str)
|
|
103
|
+
|
|
104
|
+
if value <= 0:
|
|
105
|
+
raise ValueError(f"Interval value must be positive, got {value}")
|
|
106
|
+
|
|
107
|
+
if unit not in self.UNITS:
|
|
108
|
+
raise ValueError(
|
|
109
|
+
f"Unknown time unit: '{unit}'. "
|
|
110
|
+
f"Supported units: {', '.join(sorted(set(self.UNITS.keys())))}"
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
return value * self.UNITS[unit]
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def seconds(self) -> int:
|
|
117
|
+
"""Get interval in seconds."""
|
|
118
|
+
return self._seconds
|
|
119
|
+
|
|
120
|
+
def to_timedelta(self) -> timedelta:
|
|
121
|
+
"""Get interval as a :class:`datetime.timedelta` (planner arithmetic)."""
|
|
122
|
+
return timedelta(seconds=self._seconds)
|
|
123
|
+
|
|
124
|
+
def __eq__(self, other) -> bool:
|
|
125
|
+
"""Check equality based on seconds."""
|
|
126
|
+
if isinstance(other, Interval):
|
|
127
|
+
return self._seconds == other._seconds
|
|
128
|
+
return False
|
|
129
|
+
|
|
130
|
+
def __hash__(self) -> int:
|
|
131
|
+
"""Hash based on seconds."""
|
|
132
|
+
return hash(self._seconds)
|
|
133
|
+
|
|
134
|
+
def __repr__(self) -> str:
|
|
135
|
+
"""String representation."""
|
|
136
|
+
return f"Interval({self._seconds})"
|
|
137
|
+
|
|
138
|
+
def __str__(self) -> str:
|
|
139
|
+
"""User-friendly string representation."""
|
|
140
|
+
# Try to represent in human-readable format
|
|
141
|
+
if self._seconds % 86400 == 0:
|
|
142
|
+
return f"{self._seconds // 86400}d"
|
|
143
|
+
elif self._seconds % 3600 == 0:
|
|
144
|
+
return f"{self._seconds // 3600}h"
|
|
145
|
+
elif self._seconds % 60 == 0:
|
|
146
|
+
return f"{self._seconds // 60}min"
|
|
147
|
+
else:
|
|
148
|
+
return f"{self._seconds}s"
|
abkit/core/models.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Core data models for abkit.
|
|
3
|
+
|
|
4
|
+
Defines table schemas and column definitions for database abstraction.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class ColumnDefinition:
|
|
13
|
+
"""
|
|
14
|
+
Definition of a table column.
|
|
15
|
+
|
|
16
|
+
Attributes:
|
|
17
|
+
name: Column name
|
|
18
|
+
type: SQL type (database-specific)
|
|
19
|
+
nullable: Whether column can be NULL
|
|
20
|
+
default: Default value for column
|
|
21
|
+
max_length: Optional length bound for String columns. Dialects that
|
|
22
|
+
must size strings use it (MySQL renders ``VARCHAR(max_length)``);
|
|
23
|
+
others ignore it. Primary-key strings on MySQL count toward
|
|
24
|
+
InnoDB's 3072-byte composite-index cap (4 bytes/char under
|
|
25
|
+
utf8mb4), so wide composite keys MUST set this.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
name: str
|
|
29
|
+
type: str
|
|
30
|
+
nullable: bool = False
|
|
31
|
+
default: Any | None = None
|
|
32
|
+
max_length: int | None = None
|
|
33
|
+
|
|
34
|
+
def __post_init__(self):
|
|
35
|
+
"""Validate column definition."""
|
|
36
|
+
if not self.name:
|
|
37
|
+
raise ValueError("Column name cannot be empty")
|
|
38
|
+
if not self.type:
|
|
39
|
+
raise ValueError("Column type cannot be empty")
|
|
40
|
+
if self.max_length is not None and self.max_length <= 0:
|
|
41
|
+
raise ValueError(f"max_length must be positive, got {self.max_length}")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class TableModel:
|
|
46
|
+
"""
|
|
47
|
+
Model for table schema definition.
|
|
48
|
+
|
|
49
|
+
This is used by BaseDatabaseManager.create_table() to create tables
|
|
50
|
+
in a database-agnostic way.
|
|
51
|
+
|
|
52
|
+
Attributes:
|
|
53
|
+
columns: List of column definitions
|
|
54
|
+
primary_key: List of column names forming primary key
|
|
55
|
+
engine: Database engine (ClickHouse-specific, e.g., "MergeTree")
|
|
56
|
+
order_by: Columns for ORDER BY clause (ClickHouse-specific)
|
|
57
|
+
indexes: Additional indexes to create
|
|
58
|
+
version_column: Column that drives last-writer-wins deduplication.
|
|
59
|
+
On ClickHouse this is the version encoded in the engine string
|
|
60
|
+
(e.g. ``ReplacingMergeTree(created_at)``); on SQL backends with an
|
|
61
|
+
enforced primary key it drives a version-aware upsert so a re-insert
|
|
62
|
+
with a newer ``version_column`` replaces the existing row. ``None``
|
|
63
|
+
for tables that do not deduplicate by version (e.g. ``_ab_tasks``).
|
|
64
|
+
|
|
65
|
+
Example:
|
|
66
|
+
>>> model = TableModel(
|
|
67
|
+
... columns=[
|
|
68
|
+
... ColumnDefinition("id", "Int32"),
|
|
69
|
+
... ColumnDefinition("name", "String"),
|
|
70
|
+
... ],
|
|
71
|
+
... primary_key=["id"],
|
|
72
|
+
... engine="MergeTree",
|
|
73
|
+
... order_by=["id"]
|
|
74
|
+
... )
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
columns: list[ColumnDefinition]
|
|
78
|
+
primary_key: list[str]
|
|
79
|
+
engine: str | None = None
|
|
80
|
+
order_by: list[str] | None = None
|
|
81
|
+
indexes: list[str] = field(default_factory=list)
|
|
82
|
+
version_column: str | None = None
|
|
83
|
+
|
|
84
|
+
def __post_init__(self):
|
|
85
|
+
"""Validate table model."""
|
|
86
|
+
if not self.columns:
|
|
87
|
+
raise ValueError("Table must have at least one column")
|
|
88
|
+
|
|
89
|
+
if not self.primary_key:
|
|
90
|
+
raise ValueError("Table must have a primary key")
|
|
91
|
+
|
|
92
|
+
# Validate primary key columns exist
|
|
93
|
+
column_names = {col.name for col in self.columns}
|
|
94
|
+
for pk_col in self.primary_key:
|
|
95
|
+
if pk_col not in column_names:
|
|
96
|
+
raise ValueError(f"Primary key column '{pk_col}' not found in table columns")
|
|
97
|
+
|
|
98
|
+
# Validate order_by columns exist (if specified)
|
|
99
|
+
if self.order_by:
|
|
100
|
+
for order_col in self.order_by:
|
|
101
|
+
if order_col not in column_names:
|
|
102
|
+
raise ValueError(f"ORDER BY column '{order_col}' not found in table columns")
|
|
103
|
+
|
|
104
|
+
# Validate version column exists (if specified)
|
|
105
|
+
if self.version_column and self.version_column not in column_names:
|
|
106
|
+
raise ValueError(f"Version column '{self.version_column}' not found in table columns")
|
|
107
|
+
|
|
108
|
+
def get_column(self, name: str) -> ColumnDefinition | None:
|
|
109
|
+
"""
|
|
110
|
+
Get column definition by name.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
name: Column name
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
ColumnDefinition or None if not found
|
|
117
|
+
"""
|
|
118
|
+
for col in self.columns:
|
|
119
|
+
if col.name == name:
|
|
120
|
+
return col
|
|
121
|
+
return None
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""The expanding cumulative grid — abkit's compute heart.
|
|
2
|
+
|
|
3
|
+
Pure functions only (no config/DB imports): ONE grid generator consumed by
|
|
4
|
+
BOTH the config validator's look-count gates and the pipeline planner, so the
|
|
5
|
+
counts can never drift (plan R1; cumulative-intervals.md §6.1/§6.3).
|
|
6
|
+
|
|
7
|
+
Semantics (all timestamps naive UTC; ``end_ts`` EXCLUSIVE half-open windows):
|
|
8
|
+
|
|
9
|
+
- ``start_ts`` = experiment-timezone midnight of ``start_date``.
|
|
10
|
+
- ``horizon_ts`` = tz midnight AFTER ``end_date`` (the horizon cutoff covers
|
|
11
|
+
``end_date`` in full). Always emitted, flagged ``is_horizon`` — even when
|
|
12
|
+
the cadence does not divide the duration.
|
|
13
|
+
- Sub-day segments anchor at ``start_ts`` (``start_ts + k·every``).
|
|
14
|
+
- Day-or-coarser segments snap to experiment-timezone midnights (DST-safe:
|
|
15
|
+
midnights are computed in local time then converted), day-counted from
|
|
16
|
+
``start_date`` — so a schedule's daily tail is point-for-point comparable
|
|
17
|
+
with a pure-daily series.
|
|
18
|
+
- A segment covers offsets ``(prev_until, until]`` from ``start_ts``; the
|
|
19
|
+
last segment runs to the horizon.
|
|
20
|
+
- ``cadence: 1d`` with ``data_lag: 0`` + half-open windows reproduces the
|
|
21
|
+
legacy ``*_wo_curr_day`` convention exactly (§6.2).
|
|
22
|
+
- No ``look_index`` anywhere — ordinality is ORDER BY end_ts (§6.3).
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
from datetime import date, datetime, time, timedelta, timezone
|
|
29
|
+
from zoneinfo import ZoneInfo
|
|
30
|
+
|
|
31
|
+
DAY_SECONDS = 86400
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class GridLimitExceeded(Exception):
|
|
35
|
+
"""Raised when a grid would exceed the caller's look limit (``max_looks``)."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, limit: int):
|
|
38
|
+
self.limit = limit
|
|
39
|
+
super().__init__(
|
|
40
|
+
f"the cadence grid exceeds {limit} looks (the max_looks gate — "
|
|
41
|
+
"coarsen the cadence or raise limits.max_looks)"
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True, order=True)
|
|
46
|
+
class Cutoff:
|
|
47
|
+
"""One cumulative look: the window is ``[grid.start_ts, end_ts)``."""
|
|
48
|
+
|
|
49
|
+
end_ts: datetime # naive UTC, EXCLUSIVE
|
|
50
|
+
is_horizon: bool = field(default=False, compare=False)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class Grid:
|
|
55
|
+
"""The full planned look grid for one experiment."""
|
|
56
|
+
|
|
57
|
+
start_ts: datetime # naive UTC — the pinned left edge of every window
|
|
58
|
+
horizon_ts: datetime # naive UTC — the planned final cutoff
|
|
59
|
+
cutoffs: tuple[Cutoff, ...] # ascending by end_ts; horizon always last
|
|
60
|
+
|
|
61
|
+
def __len__(self) -> int:
|
|
62
|
+
return len(self.cutoffs)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def tz_midnight_utc(day: date, zone: ZoneInfo) -> datetime:
|
|
66
|
+
"""Local midnight of *day* in *zone*, as naive UTC."""
|
|
67
|
+
local = datetime.combine(day, time.min).replace(tzinfo=zone)
|
|
68
|
+
return local.astimezone(timezone.utc).replace(tzinfo=None)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def generate_grid(
|
|
72
|
+
start_date: date,
|
|
73
|
+
end_date: date,
|
|
74
|
+
cadence_segments: list[tuple[int, int | None]],
|
|
75
|
+
tz: str = "UTC",
|
|
76
|
+
limit: int | None = None,
|
|
77
|
+
) -> Grid:
|
|
78
|
+
"""Enumerate the cumulative cutoff grid.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
start_date: pinned experiment start (interpreted in ``tz``)
|
|
82
|
+
end_date: planner horizon date (the horizon cutoff covers it in full)
|
|
83
|
+
cadence_segments: normalised ``[(every_seconds, until_seconds|None)]``
|
|
84
|
+
(``ExperimentConfig.cadence_segments()``); segments are validated
|
|
85
|
+
by the config layer (strictly coarsening, increasing until)
|
|
86
|
+
tz: experiment timezone (date interpretation + midnight snapping)
|
|
87
|
+
limit: raise :class:`GridLimitExceeded` when the grid would exceed
|
|
88
|
+
this many looks — the validator's ``max_looks`` gate runs through
|
|
89
|
+
the SAME enumeration the planner uses
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
:class:`Grid` with cutoffs ascending; the horizon point is always
|
|
93
|
+
present and flagged, deduplicating an aligned grid point.
|
|
94
|
+
"""
|
|
95
|
+
if end_date < start_date:
|
|
96
|
+
raise ValueError(f"end_date ({end_date}) is before start_date ({start_date})")
|
|
97
|
+
zone = ZoneInfo(tz)
|
|
98
|
+
start_ts = tz_midnight_utc(start_date, zone)
|
|
99
|
+
horizon_ts = tz_midnight_utc(end_date + timedelta(days=1), zone)
|
|
100
|
+
|
|
101
|
+
points: set[datetime] = set()
|
|
102
|
+
|
|
103
|
+
def add(point: datetime) -> None:
|
|
104
|
+
points.add(point)
|
|
105
|
+
if limit is not None and len(points) > limit:
|
|
106
|
+
raise GridLimitExceeded(limit)
|
|
107
|
+
|
|
108
|
+
prev_until = 0
|
|
109
|
+
for index, (every, until) in enumerate(cadence_segments):
|
|
110
|
+
is_last = index == len(cadence_segments) - 1
|
|
111
|
+
seg_start_ts = start_ts + timedelta(seconds=prev_until)
|
|
112
|
+
if until is None:
|
|
113
|
+
seg_end_ts = horizon_ts
|
|
114
|
+
else:
|
|
115
|
+
seg_end_ts = min(start_ts + timedelta(seconds=until), horizon_ts)
|
|
116
|
+
|
|
117
|
+
if every % DAY_SECONDS == 0:
|
|
118
|
+
# Day-or-coarser: snap to tz midnights, day-counted from start_date
|
|
119
|
+
# so schedule tails stay point-for-point comparable with pure-daily.
|
|
120
|
+
# Whole-day segment bounds compare in DAY SPACE, not absolute
|
|
121
|
+
# seconds: across a DST fall-back a local midnight lands more than
|
|
122
|
+
# `until` seconds after start_ts and the boundary look would be
|
|
123
|
+
# silently dropped by a timestamp comparison.
|
|
124
|
+
every_days = every // DAY_SECONDS
|
|
125
|
+
start_days = prev_until // DAY_SECONDS if prev_until % DAY_SECONDS == 0 else None
|
|
126
|
+
until_days = (
|
|
127
|
+
until // DAY_SECONDS if until is not None and until % DAY_SECONDS == 0 else None
|
|
128
|
+
)
|
|
129
|
+
day_offset = every_days
|
|
130
|
+
while True:
|
|
131
|
+
point = tz_midnight_utc(start_date + timedelta(days=day_offset), zone)
|
|
132
|
+
if point > horizon_ts:
|
|
133
|
+
break
|
|
134
|
+
if until_days is not None:
|
|
135
|
+
if day_offset > until_days:
|
|
136
|
+
break
|
|
137
|
+
elif point > seg_end_ts:
|
|
138
|
+
break
|
|
139
|
+
past_start = (
|
|
140
|
+
day_offset > start_days if start_days is not None else point > seg_start_ts
|
|
141
|
+
)
|
|
142
|
+
if past_start:
|
|
143
|
+
add(point)
|
|
144
|
+
day_offset += every_days
|
|
145
|
+
else:
|
|
146
|
+
# Sub-day: anchor at start_ts in absolute-duration arithmetic.
|
|
147
|
+
step = timedelta(seconds=every)
|
|
148
|
+
k = prev_until // every # skip straight to the segment
|
|
149
|
+
while True:
|
|
150
|
+
k += 1
|
|
151
|
+
point = start_ts + step * k
|
|
152
|
+
if point > seg_end_ts:
|
|
153
|
+
break
|
|
154
|
+
if point > seg_start_ts:
|
|
155
|
+
add(point)
|
|
156
|
+
|
|
157
|
+
if until is not None:
|
|
158
|
+
prev_until = until
|
|
159
|
+
if is_last or seg_end_ts >= horizon_ts:
|
|
160
|
+
break
|
|
161
|
+
|
|
162
|
+
add(horizon_ts) # always planned, even when cadence doesn't divide the duration
|
|
163
|
+
|
|
164
|
+
cutoffs = tuple(Cutoff(end_ts=ts, is_horizon=(ts == horizon_ts)) for ts in sorted(points))
|
|
165
|
+
return Grid(start_ts=start_ts, horizon_ts=horizon_ts, cutoffs=cutoffs)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def pending_cutoffs(
|
|
169
|
+
grid: Grid,
|
|
170
|
+
computed_end_ts: set[datetime],
|
|
171
|
+
watermark_ts: datetime,
|
|
172
|
+
full_refresh_window: tuple[datetime, datetime] | None = None,
|
|
173
|
+
) -> list[Cutoff]:
|
|
174
|
+
"""The planner anti-join: which looks to compute this run.
|
|
175
|
+
|
|
176
|
+
A cutoff is pending iff it is COMPLETE (``end_ts <= watermark_ts``, where
|
|
177
|
+
``watermark_ts = now_utc − data_lag`` computed once per run in Python —
|
|
178
|
+
never ``now()`` in SQL, §6.2) and not already computed. The computed set
|
|
179
|
+
comes from ``list_computed_cutoffs`` — a SET, so a late hole in the middle
|
|
180
|
+
of the series is re-planned, not skipped past by a max-cursor.
|
|
181
|
+
|
|
182
|
+
``full_refresh_window=[from_ts, to_ts)`` re-includes already-computed
|
|
183
|
+
cutoffs inside the window (``run --full-refresh --from/--to`` re-opens
|
|
184
|
+
frozen points; the caller deletes the stale rows).
|
|
185
|
+
"""
|
|
186
|
+
pending = []
|
|
187
|
+
for cutoff in grid.cutoffs:
|
|
188
|
+
if cutoff.end_ts > watermark_ts:
|
|
189
|
+
continue
|
|
190
|
+
refreshed = full_refresh_window is not None and (
|
|
191
|
+
full_refresh_window[0] <= cutoff.end_ts < full_refresh_window[1]
|
|
192
|
+
)
|
|
193
|
+
if cutoff.end_ts in computed_end_ts and not refreshed:
|
|
194
|
+
continue
|
|
195
|
+
pending.append(cutoff)
|
|
196
|
+
return pending
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def backlog_seconds(computed_end_ts: set[datetime], watermark_ts: datetime) -> float | None:
|
|
200
|
+
"""How far the computed series trails the watermark (§6.4 backlog warning).
|
|
201
|
+
|
|
202
|
+
None when nothing is computed yet (a fresh experiment isn't "backlogged").
|
|
203
|
+
"""
|
|
204
|
+
if not computed_end_ts:
|
|
205
|
+
return None
|
|
206
|
+
return (watermark_ts - max(computed_end_ts)).total_seconds()
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Database managers for abkit.
|
|
2
|
+
|
|
3
|
+
The generic, ``table_name``-keyed manager layer plus the internal ``_ab_*``
|
|
4
|
+
tables (CLAUDE.md invariant: ``_ab_*`` semantics live in ``internal_tables/``,
|
|
5
|
+
never in the base managers).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from abkit.database._sql_manager import SQLDatabaseManager
|
|
9
|
+
from abkit.database.clickhouse_manager import ClickHouseDatabaseManager
|
|
10
|
+
from abkit.database.internal_tables import InternalTablesManager, compute_column_set_id
|
|
11
|
+
from abkit.database.manager import BaseDatabaseManager
|
|
12
|
+
from abkit.database.mysql_manager import MySQLDatabaseManager
|
|
13
|
+
from abkit.database.postgres_manager import PostgresDatabaseManager
|
|
14
|
+
from abkit.database.tables import (
|
|
15
|
+
INTERNAL_TABLES,
|
|
16
|
+
TABLE_AA_RUNS,
|
|
17
|
+
TABLE_EXPERIMENTS,
|
|
18
|
+
TABLE_EXPOSURES,
|
|
19
|
+
TABLE_RESULTS,
|
|
20
|
+
TABLE_TASKS,
|
|
21
|
+
TABLE_UNIT_STATE,
|
|
22
|
+
get_aa_runs_table_model,
|
|
23
|
+
get_experiments_table_model,
|
|
24
|
+
get_exposures_table_model,
|
|
25
|
+
get_results_table_model,
|
|
26
|
+
get_tasks_table_model,
|
|
27
|
+
get_unit_state_table_model,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"INTERNAL_TABLES",
|
|
32
|
+
"BaseDatabaseManager",
|
|
33
|
+
"ClickHouseDatabaseManager",
|
|
34
|
+
"InternalTablesManager",
|
|
35
|
+
"MySQLDatabaseManager",
|
|
36
|
+
"PostgresDatabaseManager",
|
|
37
|
+
"SQLDatabaseManager",
|
|
38
|
+
"TABLE_AA_RUNS",
|
|
39
|
+
"TABLE_EXPERIMENTS",
|
|
40
|
+
"TABLE_EXPOSURES",
|
|
41
|
+
"TABLE_RESULTS",
|
|
42
|
+
"TABLE_TASKS",
|
|
43
|
+
"TABLE_UNIT_STATE",
|
|
44
|
+
"compute_column_set_id",
|
|
45
|
+
"get_aa_runs_table_model",
|
|
46
|
+
"get_experiments_table_model",
|
|
47
|
+
"get_exposures_table_model",
|
|
48
|
+
"get_results_table_model",
|
|
49
|
+
"get_tasks_table_model",
|
|
50
|
+
"get_unit_state_table_model",
|
|
51
|
+
]
|