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,233 @@
1
+ """The explore session: persisted series + the bounded Tier-S cache.
2
+
3
+ Data source & freshness are D2 (m3-implementation-plan.md): explore reads the
4
+ **persisted** ``_ab_results`` series for the baseline (what actually ran) and
5
+ performs exactly ONE warehouse load pass at session start to fill the per-unit
6
+ cache — read-only, lock-free. Freshness is whatever the last ``abk run``
7
+ produced; no rows ⇒ the caller shows the friendly "run ``abk run`` first"
8
+ noop (WP8).
9
+
10
+ Thread discipline (WP4): the load pass runs on the main thread with one
11
+ manager **before** serving; after :func:`load_session` returns, the session is
12
+ immutable in-memory state — per-knob recompute (``recompute.py``) touches no
13
+ DB. Tier-R reloads create their own manager inside the serialized handler
14
+ (WP6), never through this module.
15
+
16
+ Cache budget: the latest persisted cutoff of every comparison is loaded
17
+ first; older cutoffs fill newest-first while the total stays under
18
+ ``EXPLORE_CACHE_BUDGET`` numeric values. If even the latest cutoffs do not
19
+ fit, the cache is dropped entirely and the session degrades to
20
+ suffstats-only mode (``cache_disabled_reason`` set; Tier-S knobs disabled
21
+ with that reason — never a silent partial cache the UI would misread as
22
+ "bootstrap is live").
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from collections.abc import Callable
28
+ from dataclasses import dataclass, field
29
+ from datetime import datetime
30
+
31
+ from abkit.compute.recompute_backend import RecomputeBackend
32
+ from abkit.config.experiment_config import ComparisonConfig, ExperimentConfig
33
+ from abkit.config.metric_config import MetricConfig
34
+ from abkit.config.project_config import ProjectConfig
35
+ from abkit.core.period_planner import Cutoff, Grid, generate_grid
36
+ from abkit.database.internal_tables import InternalTablesManager
37
+ from abkit.loaders.metric_loader import MetricLoadResult
38
+ from abkit.pipeline.analyze import comparison_alpha, effective_alphas
39
+
40
+ #: Tier-S cache budget in stored numeric values (role-array floats across
41
+ #: variants and cutoffs; ≈160 MB of float64) — m3-implementation-plan.md WP4.
42
+ EXPLORE_CACHE_BUDGET = 20_000_000
43
+
44
+ #: One (comparison, cutoff) load — ``RecomputeBackend.load_cutoff`` bound to
45
+ #: its metric SQL (see :func:`backend_cutoff_loader`); tests may stub it.
46
+ CutoffLoader = Callable[[ComparisonConfig, MetricConfig, Grid, Cutoff], MetricLoadResult]
47
+
48
+
49
+ def backend_cutoff_loader(
50
+ backend: RecomputeBackend, metric_sql_by_name: dict[str, str]
51
+ ) -> CutoffLoader:
52
+ """Adapt a ``RecomputeBackend`` to the session's loader callable."""
53
+
54
+ def _load(
55
+ comparison: ComparisonConfig, metric: MetricConfig, grid: Grid, cutoff: Cutoff
56
+ ) -> MetricLoadResult:
57
+ return backend.load_cutoff(
58
+ comparison, metric, metric_sql_by_name[metric.name], grid, cutoff
59
+ )
60
+
61
+ return _load
62
+
63
+
64
+ def loaded_value_count(loaded: MetricLoadResult) -> int:
65
+ """Numeric values one cached cutoff holds — the cache-budget unit."""
66
+ return sum(arr.size for roles in loaded.roles_by_variant.values() for arr in roles.values())
67
+
68
+
69
+ @dataclass
70
+ class ComparisonSeries:
71
+ """One configured comparison's persisted series (FINAL-deduped, ascending).
72
+
73
+ ``rows`` carry only the CONFIGURED ``method_config_id`` — orphaned series
74
+ are the startup warning's job (WP8), never silently merged into explore.
75
+ """
76
+
77
+ comparison: ComparisonConfig
78
+ metric: MetricConfig
79
+ configured_alpha: float
80
+ rows: list[dict]
81
+ cutoffs: list[datetime] # distinct end_ts, ascending
82
+
83
+
84
+ @dataclass
85
+ class ExploreSession:
86
+ """Immutable in-memory state one explore serve runs against."""
87
+
88
+ experiment: ExperimentConfig
89
+ project: ProjectConfig
90
+ grid: Grid
91
+ series_by_metric: dict[str, ComparisonSeries]
92
+ aa_rows: list[dict] = field(default_factory=list)
93
+ cache: dict[tuple[str, datetime], MetricLoadResult] = field(default_factory=dict)
94
+ #: the covariate_lookback each cached entry was RENDERED with — a Tier-R
95
+ #: /reload may re-render a cutoff under a different lookback, and the
96
+ #: cache gate must compare against what is actually in the entry, not the
97
+ #: configured method (recompute._cache_serves)
98
+ cache_lookback: dict[tuple[str, datetime], str | int | None] = field(default_factory=dict)
99
+ cache_values: int = 0
100
+ cache_disabled_reason: str | None = None
101
+ warnings: list[str] = field(default_factory=list)
102
+
103
+ def series(self, metric: str) -> ComparisonSeries:
104
+ try:
105
+ return self.series_by_metric[metric]
106
+ except KeyError:
107
+ raise KeyError(
108
+ f"metric '{metric}' is not a configured comparison of experiment "
109
+ f"'{self.experiment.name}' (have: {sorted(self.series_by_metric)})"
110
+ ) from None
111
+
112
+ def loaded(self, metric: str, end_ts: datetime) -> MetricLoadResult | None:
113
+ return self.cache.get((metric, end_ts))
114
+
115
+ def cached_cutoffs(self, metric: str) -> list[datetime]:
116
+ return sorted(ts for (m, ts) in self.cache if m == metric)
117
+
118
+
119
+ def load_session(
120
+ experiment: ExperimentConfig,
121
+ metrics_by_name: dict[str, MetricConfig],
122
+ project: ProjectConfig,
123
+ tables: InternalTablesManager,
124
+ loader: CutoffLoader | None = None,
125
+ budget: int = EXPLORE_CACHE_BUDGET,
126
+ log: Callable[[str], None] = lambda _: None,
127
+ ) -> ExploreSession:
128
+ """The one warehouse load pass (D2): series + the bounded Tier-S cache.
129
+
130
+ ``loader=None`` builds a suffstats-only session (no Tier S) — the
131
+ ``--no-serve`` static path and unit tests use it.
132
+ """
133
+ alphas = effective_alphas(experiment, project)
134
+ grid = generate_grid(
135
+ experiment.start_date,
136
+ experiment.end_date,
137
+ experiment.cadence_segments(),
138
+ tz=experiment.timezone,
139
+ limit=project.limits.max_looks,
140
+ )
141
+
142
+ session = ExploreSession(
143
+ experiment=experiment,
144
+ project=project,
145
+ grid=grid,
146
+ series_by_metric={},
147
+ )
148
+
149
+ for comparison in experiment.comparisons:
150
+ if comparison.metric in session.series_by_metric:
151
+ session.warnings.append(
152
+ f"metric '{comparison.metric}' appears in more than one comparison — "
153
+ "explore serves the first"
154
+ )
155
+ continue
156
+ metric = metrics_by_name[comparison.metric]
157
+ rows = tables.load_results(
158
+ experiment.name,
159
+ metric=metric.name,
160
+ method_config_id=comparison.method.method_config_id,
161
+ )
162
+ cutoffs = sorted({row["end_ts"] for row in rows if row.get("end_ts") is not None})
163
+ session.series_by_metric[metric.name] = ComparisonSeries(
164
+ comparison=comparison,
165
+ metric=metric,
166
+ configured_alpha=comparison_alpha(comparison, alphas),
167
+ rows=rows,
168
+ cutoffs=cutoffs,
169
+ )
170
+ log(f"SERIES {experiment.name}/{metric.name}: {len(rows)} rows, {len(cutoffs)} cutoffs")
171
+
172
+ # The calibration chip's source (D3) — tolerate a never-validated project.
173
+ if tables.aa_runs_table_exists():
174
+ session.aa_rows = tables.get_aa_runs(experiment.name)
175
+
176
+ if loader is None:
177
+ session.cache_disabled_reason = (
178
+ "no warehouse loader — suffstats-only session (Tier-S knobs disabled)"
179
+ )
180
+ return session
181
+
182
+ # ── Tier-S load: latest cutoffs first, then older newest-first ──────────
183
+ latest_loads: list[tuple[str, datetime]] = []
184
+ older_loads: list[tuple[str, datetime]] = []
185
+ for name, series in session.series_by_metric.items():
186
+ if not series.cutoffs:
187
+ continue
188
+ latest_loads.append((name, series.cutoffs[-1]))
189
+ older_loads.extend((name, ts) for ts in series.cutoffs[:-1])
190
+ older_loads.sort(key=lambda item: item[1], reverse=True)
191
+
192
+ def _load_one(metric_name: str, end_ts: datetime) -> int:
193
+ series = session.series_by_metric[metric_name]
194
+ loaded = loader(series.comparison, series.metric, grid, Cutoff(end_ts=end_ts))
195
+ session.cache[(metric_name, end_ts)] = loaded
196
+ session.cache_lookback[(metric_name, end_ts)] = series.comparison.method.covariate_lookback
197
+ return loaded_value_count(loaded)
198
+
199
+ for metric_name, end_ts in latest_loads:
200
+ session.cache_values += _load_one(metric_name, end_ts)
201
+ log(f"CACHE {experiment.name}/{metric_name}: latest cutoff {end_ts}")
202
+ if session.cache_values > budget:
203
+ break # degrading anyway — bound the transient peak too
204
+
205
+ if session.cache_values > budget:
206
+ # Even the latest cutoffs bust the budget: degrade honestly to
207
+ # suffstats-only — a partial cache would misreport bootstrap as live.
208
+ session.cache.clear()
209
+ session.cache_lookback.clear()
210
+ session.cache_disabled_reason = (
211
+ f"session cache over budget: the latest cutoffs alone hold "
212
+ f"{session.cache_values} values (> {budget}) — suffstats-only "
213
+ "session (Tier-S knobs disabled; raise the budget or reduce arms)"
214
+ )
215
+ session.cache_values = 0
216
+ session.warnings.append(session.cache_disabled_reason)
217
+ return session
218
+
219
+ for metric_name, end_ts in older_loads:
220
+ series = session.series_by_metric[metric_name]
221
+ loaded = loader(series.comparison, series.metric, grid, Cutoff(end_ts=end_ts))
222
+ count = loaded_value_count(loaded)
223
+ if session.cache_values + count > budget:
224
+ session.warnings.append(
225
+ f"session cache budget reached at {session.cache_values} values — "
226
+ f"older cutoffs before {end_ts} stay suffstats-only"
227
+ )
228
+ break
229
+ session.cache[(metric_name, end_ts)] = loaded
230
+ session.cache_lookback[(metric_name, end_ts)] = series.comparison.method.covariate_lookback
231
+ session.cache_values += count
232
+
233
+ return session
@@ -0,0 +1,27 @@
1
+ """Domain-neutral helpers shared across abkit (stdlib-only at import time).
2
+
3
+ This package is imported by ``abkit.stats`` (the pure core), so nothing here
4
+ may import numpy/pydantic/yaml/click/jinja2/orjson — enforced by
5
+ ``tests/stats/test_purity.py``.
6
+ """
7
+
8
+ from abkit.utils.datetime_utils import (
9
+ format_duration,
10
+ now_utc,
11
+ now_utc_naive,
12
+ to_aware_utc,
13
+ to_naive_utc,
14
+ )
15
+ from abkit.utils.env_interpolation import interpolate_env_vars
16
+ from abkit.utils.json_utils import json_dumps_sorted, json_loads
17
+
18
+ __all__ = [
19
+ "format_duration",
20
+ "interpolate_env_vars",
21
+ "json_dumps_sorted",
22
+ "json_loads",
23
+ "now_utc",
24
+ "now_utc_naive",
25
+ "to_aware_utc",
26
+ "to_naive_utc",
27
+ ]
@@ -0,0 +1,97 @@
1
+ """UTC datetime utilities.
2
+
3
+ Contract: all internal timestamps are naive UTC (tzinfo=None).
4
+ - ClickHouse DateTime64(3, 'UTC') stores and returns naive UTC
5
+ - numpy datetime64 has no timezone representation
6
+ - Comparisons between timestamps must use the same convention
7
+
8
+ Experiment-local timezones (the ``timezone:`` config field) are interpreted at
9
+ the planner boundary only (docs/specs/cumulative-intervals.md §6.3); storage
10
+ and comparison are always UTC.
11
+
12
+ Functions:
13
+ now_utc() -> aware UTC datetime (for calculations requiring timezone)
14
+ now_utc_naive() -> naive UTC datetime (for numpy / ClickHouse inserts)
15
+ to_naive_utc() -> normalize any datetime to naive UTC
16
+ to_aware_utc() -> normalize any datetime to aware UTC
17
+ """
18
+
19
+ from datetime import datetime, timezone
20
+
21
+
22
+ def now_utc() -> datetime:
23
+ """Return current time as timezone-aware UTC datetime."""
24
+ return datetime.now(timezone.utc)
25
+
26
+
27
+ def now_utc_naive() -> datetime:
28
+ """Return current time as naive UTC datetime (for numpy / ClickHouse)."""
29
+ return datetime.now(timezone.utc).replace(tzinfo=None)
30
+
31
+
32
+ def to_naive_utc(dt: datetime | None) -> datetime | None:
33
+ """Strip tzinfo from a UTC datetime, returning naive UTC.
34
+
35
+ Args:
36
+ dt: datetime object (aware or naive) or None
37
+
38
+ Returns:
39
+ Naive UTC datetime, or None if input is None
40
+ """
41
+ if dt is None:
42
+ return None
43
+ if dt.tzinfo is not None:
44
+ # CONVERT to UTC first: an aware non-UTC value (e.g. a tz-aware
45
+ # exposure_ts column) must not be re-labelled by stripping tzinfo.
46
+ return dt.astimezone(timezone.utc).replace(tzinfo=None)
47
+ return dt
48
+
49
+
50
+ def to_aware_utc(dt: datetime | None) -> datetime | None:
51
+ """Attach UTC timezone to a naive datetime.
52
+
53
+ Args:
54
+ dt: datetime object (aware or naive) or None
55
+
56
+ Returns:
57
+ Timezone-aware UTC datetime, or None if input is None
58
+ """
59
+ if dt is None:
60
+ return None
61
+ return dt if dt.tzinfo is not None else dt.replace(tzinfo=timezone.utc)
62
+
63
+
64
+ def format_duration(seconds: int | float) -> str:
65
+ """Format a span of seconds as a compact human string (max two units).
66
+
67
+ Used by CLI/report output to express windows and elapsed spans in plain
68
+ language:
69
+
70
+ >>> format_duration(600) # 10 minutes
71
+ '10m'
72
+ >>> format_duration(9000) # 2h 30m
73
+ '2h 30m'
74
+ >>> format_duration(90000) # 1d 1h
75
+ '1d 1h'
76
+ >>> format_duration(30)
77
+ '30s'
78
+
79
+ Keeps at most the two most-significant non-zero units so the result
80
+ stays glanceable. Sub-minute spans render in seconds; zero/negative
81
+ inputs degrade to ``"0m"`` rather than raising.
82
+ """
83
+ total = int(round(seconds))
84
+ if total <= 0:
85
+ return "0m"
86
+ if total < 60:
87
+ return f"{total}s"
88
+
89
+ parts: list[str] = []
90
+ remaining = total
91
+ for label, size in (("d", 86400), ("h", 3600), ("m", 60)):
92
+ if remaining >= size:
93
+ qty, remaining = divmod(remaining, size)
94
+ parts.append(f"{qty}{label}")
95
+ if len(parts) == 2:
96
+ break
97
+ return " ".join(parts)
@@ -0,0 +1,50 @@
1
+ """Environment variable interpolation for configuration values.
2
+
3
+ Supports two syntaxes inside string values:
4
+
5
+ - ``${VAR_NAME}`` — shell-style.
6
+ - ``{{ env_var('VAR_NAME') }}`` — dbt-style.
7
+
8
+ Unresolved placeholders (variable not set) are kept as-is so that callers
9
+ get a chance to validate or report missing environment variables instead
10
+ of silently falling back to an empty string.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import re
17
+ from typing import Any
18
+
19
+ _SHELL_PATTERN = re.compile(r"\$\{([^}]+)\}")
20
+ _DBT_PATTERN = re.compile(r"\{\{\s*env_var\(['\"]([^'\"]+)['\"]\)\s*\}\}")
21
+
22
+
23
+ def interpolate_env_vars(value: Any) -> Any:
24
+ """Recursively interpolate environment variables in *value*.
25
+
26
+ Strings are scanned for both supported placeholder syntaxes; mappings
27
+ and sequences are walked depth-first. Other types pass through
28
+ unchanged.
29
+ """
30
+ if isinstance(value, str):
31
+ return _interpolate_string(value)
32
+ if isinstance(value, dict):
33
+ return {k: interpolate_env_vars(v) for k, v in value.items()}
34
+ if isinstance(value, list):
35
+ return [interpolate_env_vars(item) for item in value]
36
+ if isinstance(value, tuple):
37
+ return tuple(interpolate_env_vars(item) for item in value)
38
+ return value
39
+
40
+
41
+ def _interpolate_string(value: str) -> str:
42
+ value = _SHELL_PATTERN.sub(
43
+ lambda m: os.environ.get(m.group(1), m.group(0)),
44
+ value,
45
+ )
46
+ value = _DBT_PATTERN.sub(
47
+ lambda m: os.environ.get(m.group(1), m.group(0)),
48
+ value,
49
+ )
50
+ return value
@@ -0,0 +1,38 @@
1
+ """Canonical JSON serialisation.
2
+
3
+ This is the ONE serialisation path used both for ``method_config_id`` hashing and
4
+ for persisting ``method_params`` (docs/specs/declarative-config.md §7,
5
+ docs/specs/quorum-review.md "canonical method_params JSON everywhere"). Exact-string
6
+ BI filters and identity hashes must never disagree, so nothing else may serialise
7
+ method params.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from typing import Any
14
+
15
+
16
+ def json_dumps_sorted(obj: Any) -> str:
17
+ """Serialise ``obj`` to canonical JSON: sorted keys, no whitespace, UTF-8 text.
18
+
19
+ ``allow_nan=False`` — NaN/Infinity are not valid JSON and must never appear in
20
+ method params (they would silently break BI series identity).
21
+ """
22
+ return json.dumps(
23
+ obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
24
+ )
25
+
26
+
27
+ def json_loads(value: str | bytes) -> Any:
28
+ """Parse a JSON document (stdlib only — this module must stay import-light).
29
+
30
+ Accepts ``bytes``/``bytearray``/``memoryview`` and str subclasses such as
31
+ ``numpy.str_`` (coerced to exact ``str`` first, matching the dumps path's
32
+ text-in/text-out convention).
33
+ """
34
+ if isinstance(value, (bytes, bytearray, memoryview)):
35
+ value = bytes(value).decode("utf-8")
36
+ elif type(value) is not str:
37
+ value = str(value)
38
+ return json.loads(value)
@@ -0,0 +1,36 @@
1
+ """The A/A false-positive-matrix engine (``abk validate`` — M4).
2
+
3
+ This package scores a method configuration by empirical false-positive rate and
4
+ power against synthetic ground truth (placebo A/A splits + injected effects),
5
+ answering *"is this method actually calibrated on this data, or does it lie about
6
+ its α?"* (docs/specs/aa-false-positive-matrix.md; docs/specs/m4-implementation-plan.md).
7
+
8
+ The engine is pure: it imports ``abkit.stats`` freely but never touches the DB,
9
+ the filesystem, Jinja, or click — the donor's "engine never touches I/O; the
10
+ caller loads and persists" contract. WP1 ships the numeric heart (placebo split,
11
+ effect injection, scoring); the loaders, runner, CLI, and report land in WP2–WP7.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from abkit.validate._types import DecisionEntry, ValidateError
17
+ from abkit.validate.panel import PanelCutoff, PlaceboPanel
18
+ from abkit.validate.persistence import aa_run_records
19
+ from abkit.validate.result import AaValidateResult, CellResult
20
+ from abkit.validate.runner import ValidateSettings, enumerate_cells, run_validation
21
+ from abkit.validate.scoring import CellScore, score_cell
22
+
23
+ __all__ = [
24
+ "DecisionEntry",
25
+ "ValidateError",
26
+ "PanelCutoff",
27
+ "PlaceboPanel",
28
+ "CellScore",
29
+ "score_cell",
30
+ "AaValidateResult",
31
+ "CellResult",
32
+ "ValidateSettings",
33
+ "enumerate_cells",
34
+ "run_validation",
35
+ "aa_run_records",
36
+ ]
@@ -0,0 +1,35 @@
1
+ """Small shared types for the validate engine (ported from the donor autotune).
2
+
3
+ Dependency-free (no imports from other validate modules) so every stage can
4
+ import these without cycles — the donor ``detectkit/autotune/_types.py`` +
5
+ ``_base.py::AutoTuneError`` convention, reshaped experiment-primary.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+
14
+ class ValidateError(RuntimeError):
15
+ """Raised when a cell cannot be scored (no data, degenerate population, …).
16
+
17
+ The A/A analog of the donor's ``AutoTuneError`` — the command records it on
18
+ the lock row and writes a ``status='failed'`` audit row (WP3/WP4).
19
+ """
20
+
21
+
22
+ @dataclass
23
+ class DecisionEntry:
24
+ """One ordered, human-readable rationale entry for the decision log.
25
+
26
+ Ported verbatim from ``detectkit/autotune/_types.py`` — the runner walks
27
+ these into the ``details`` JSON and the ``#``-comment report header (WP3/WP5).
28
+ """
29
+
30
+ stage: str
31
+ message: str
32
+ fields: dict[str, Any] = field(default_factory=dict)
33
+
34
+ def to_dict(self) -> dict[str, Any]:
35
+ return {"stage": self.stage, "message": self.message, "fields": self.fields}
@@ -0,0 +1,75 @@
1
+ """Effect injection at the sufficient-statistics level (docs/specs/m4-implementation-plan.md D2).
2
+
3
+ A known effect is injected into one placebo arm to measure power / achieved-MDE /
4
+ CI-coverage. The algebra is exact and numpy-only (purity-safe — this lives in
5
+ ``abkit.validate``, never ``abkit.stats``): scaling ``y → y·(1+δ)`` maps the raw
6
+ centered moments a ``SufficientStats`` stores (``m2 = Σ(y−ȳ)²``,
7
+ ``cross_c = Σ(y−ȳ)(x−x̄)``, samples.py:290–307) by ``(1+δ)²`` and ``(1+δ)``
8
+ respectively, leaving the covariate moments untouched — so ``corr_coef`` is
9
+ invariant and CUPED needs no special case.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from abkit.stats.samples import Fraction, RatioSufficientStats, SufficientStats
15
+ from abkit.validate._types import ValidateError
16
+
17
+ #: Returned suffstats type for a multiplicative injection.
18
+ InjectableStats = SufficientStats | RatioSufficientStats | Fraction
19
+
20
+
21
+ def inject_multiplicative(stats: InjectableStats, delta: float) -> InjectableStats:
22
+ """Return a copy of ``stats`` with the metric scaled by ``(1+δ)``.
23
+
24
+ ``SufficientStats`` (t-test / z-test-on-means / CUPED): ``mean·(1+δ)``,
25
+ ``m2·(1+δ)²``, ``cross_c·(1+δ)``; covariate moments unchanged. The tiny
26
+ negative ``m2`` that float cancellation can produce is clamped to ``0.0``
27
+ (samples.py:273–274 rejects ``m2<0``; the ratio_delta.py:52 precedent).
28
+
29
+ ``RatioSufficientStats``: scale ``mean_num``, ``m2_num·(1+δ)²``, ``c_nd·(1+δ)``;
30
+ denominator moments unchanged (the numerator is the metric).
31
+
32
+ ``Fraction``: ``count·(1+δ)`` **clamped to ``≤nobs``** — a high base-rate
33
+ proportion cannot be lifted past 100 %; the caller treats a clamped injection
34
+ as an unreachable MDE (WP5), never a crash.
35
+ """
36
+ factor = 1.0 + float(delta)
37
+
38
+ if isinstance(stats, SufficientStats):
39
+ return SufficientStats(
40
+ n=stats.n,
41
+ mean=stats.mean * factor,
42
+ m2=max(0.0, stats.m2 * factor * factor),
43
+ cov_mean=stats.cov_mean,
44
+ cov_m2=stats.cov_m2,
45
+ cross_c=None if stats.cross_c is None else stats.cross_c * factor,
46
+ name=stats.name,
47
+ )
48
+ if isinstance(stats, RatioSufficientStats):
49
+ return RatioSufficientStats(
50
+ n=stats.n,
51
+ mean_num=stats.mean_num * factor,
52
+ m2_num=max(0.0, stats.m2_num * factor * factor),
53
+ mean_den=stats.mean_den,
54
+ m2_den=stats.m2_den,
55
+ c_nd=stats.c_nd * factor,
56
+ name=stats.name,
57
+ )
58
+ if isinstance(stats, Fraction):
59
+ return Fraction(
60
+ count=min(stats.nobs, stats.count * factor),
61
+ nobs=stats.nobs,
62
+ name=stats.name,
63
+ )
64
+ raise ValidateError(f"cannot inject an effect into {type(stats).__name__}")
65
+
66
+
67
+ def injection_clamped(stats: InjectableStats, delta: float) -> bool:
68
+ """True when a multiplicative injection would saturate (Fraction count > nobs).
69
+
70
+ The scorer flags such a cell as "MDE unreachable" instead of reporting a
71
+ truncated effect as if it were the requested δ.
72
+ """
73
+ if isinstance(stats, Fraction):
74
+ return stats.count * (1.0 + float(delta)) > stats.nobs
75
+ return False