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,109 @@
1
+ """Render an experiment report payload into one self-contained HTML file.
2
+
3
+ The self-contained inline-bundle delivery model (the detectkit donor pattern,
4
+ shared with the M3 explore page): one HTML document with the renderer JS
5
+ inlined (the pre-built, committed ``assets/report.js`` bundle — built from
6
+ ``web/src/report/`` by ``web/build.mjs``) and the data baked in as a JS
7
+ literal. No CDN, no webfonts, no network — nothing leaves the browser, and the
8
+ document embeds in a future app unchanged (CLAUDE.md invariant 6).
9
+
10
+ Template mechanics (m3-implementation-plan.md WP3 hotspots, hardened past the
11
+ donor per the WP3 adversarial review):
12
+
13
+ - Placeholders are substituted in ONE regex pass (never ``.format`` — literal
14
+ ``{}`` in the JS/CSS survive; never sequential ``str.replace`` — a payload
15
+ string containing a placeholder token like ``__REPORT_JS__`` must not be
16
+ re-scanned and clobbered).
17
+ - The baked payload JSON escapes EVERY ``<`` as ``\\u003c`` (valid JSON, same
18
+ parsed string). Escaping only ``</`` — the donor's hardening — is not
19
+ enough: per the HTML tokenizer a ``<!--`` + ``<script`` pair inside script
20
+ data enters the double-escaped state and swallows the real ``</script>``
21
+ terminator, so no ``<`` may survive at all (data-contract §5.3 bake-time
22
+ escaping).
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import re
28
+ from html import escape
29
+ from importlib.resources import files
30
+
31
+ from abkit.utils.json_utils import json_dumps_sorted
32
+
33
+ # A small placeholder-brand tile (data-URI, no network): an A/B split square
34
+ # using the placeholder accent from the one brand-token layer — swapped with
35
+ # the finalized logo/palette per branding-and-site.md.
36
+ _FAVICON = (
37
+ "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'"
38
+ "%3E%3Crect width='32' height='32' rx='7' fill='%233987e5'/%3E%3Crect x='17' y='6'"
39
+ " width='9' height='20' rx='2' fill='%23fcfcfb' opacity='0.55'/%3E%3Crect x='6' "
40
+ "y='12' width='9' height='14' rx='2' fill='%23fcfcfb'/%3E%3C/svg%3E"
41
+ )
42
+
43
+ _TEMPLATE = """<!doctype html>
44
+ <html lang="en">
45
+ <head>
46
+ <meta charset="utf-8" />
47
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
48
+ <title>abkit report — __EXPERIMENT__</title>
49
+ <link rel="icon" href="__FAVICON__" />
50
+ <style>
51
+ /* Page shell only — the renderer injects its own scoped styles and the one
52
+ brand-token layer (web/src/report/report.ts injectStyle). System fonts:
53
+ the report must open file:// with zero network requests. */
54
+ html,body{margin:0;background:#f9f9f7;color:#0b0b0b;
55
+ font-family:system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;}
56
+ *{box-sizing:border-box;}
57
+ </style>
58
+ </head>
59
+ <body>
60
+ <div id="abk-report"></div>
61
+ <script>window.__ABK_PAYLOAD__ = __PAYLOAD__;</script>
62
+ <script>__REPORT_JS__</script>
63
+ <script>
64
+ (function(){
65
+ var mount = document.getElementById('abk-report');
66
+ try { window.__ABK_REPORT__.render(window.__ABK_PAYLOAD__, mount); }
67
+ catch (e) { mount.textContent = 'Failed to render report: ' + e; }
68
+ })();
69
+ </script>
70
+ </body>
71
+ </html>
72
+ """
73
+
74
+
75
+ def _report_js() -> str:
76
+ """Read the committed report renderer bundle shipped in the wheel."""
77
+ return (files("abkit.reporting") / "assets" / "report.js").read_text(encoding="utf-8")
78
+
79
+
80
+ def _bake_payload_json(payload: dict) -> str:
81
+ """Canonical JSON with every ``<`` escaped as ``\\u003c`` (script-safe).
82
+
83
+ ``\\u003c`` is a plain JSON escape — the parsed value is byte-identical —
84
+ but no ``<`` survives in the document, so payload strings can neither
85
+ terminate the inline script block (``</script>``) nor poison the HTML
86
+ tokenizer's script-data-escaped states (``<!--`` + ``<script``, which
87
+ would swallow the real terminator even with ``</`` escaped).
88
+ """
89
+ return json_dumps_sorted(payload).replace("<", "\\u003c")
90
+
91
+
92
+ _PLACEHOLDER_RE = re.compile(r"__(EXPERIMENT|FAVICON|PAYLOAD|REPORT_JS)__")
93
+
94
+
95
+ def render_report_html(payload: dict) -> str:
96
+ """Build the self-contained HTML document for one experiment ``payload``.
97
+
98
+ Pure: no DB, no filesystem writes, no clock. The caller writes the
99
+ returned string (``abk run --report`` — cli/commands/run.py).
100
+ """
101
+ values = {
102
+ "EXPERIMENT": escape(str(payload.get("experiment", "experiment"))),
103
+ "FAVICON": _FAVICON,
104
+ "PAYLOAD": _bake_payload_json(payload),
105
+ "REPORT_JS": _report_js(),
106
+ }
107
+ # One pass: substituted content (payload strings, the bundle body) is
108
+ # never re-scanned for other placeholder tokens.
109
+ return _PLACEHOLDER_RE.sub(lambda m: values[m.group(1)], _TEMPLATE)
@@ -0,0 +1,94 @@
1
+ """``abkit.stats`` — the pure, importable, numpy-first statistical core.
2
+
3
+ Invariant (CLAUDE.md): this package depends only on numpy/scipy/statsmodels (plus
4
+ the stdlib) — never on config/DB/Jinja/click. It serves the pipeline, the explore
5
+ cockpit, the A/A harness and notebook users from one math implementation.
6
+
7
+ >>> from abkit.stats import Sample, create_method
8
+ >>> method = create_method("t-test", alpha=0.05, params={"test_type": "relative"})
9
+ >>> result = method.compare_pair(Sample([...], name="control"), Sample([...], name="treatment"))
10
+ """
11
+
12
+ from abkit.stats import bootstrap, parametric # noqa: F401 (register all methods)
13
+ from abkit.stats.accumulate import merge_joint_moments, merge_ratio_suffstats, merge_suffstats
14
+ from abkit.stats.base import (
15
+ BaseMethod,
16
+ ParamSpec,
17
+ compute_method_config_id,
18
+ method_config_payload,
19
+ )
20
+ from abkit.stats.correction import (
21
+ TwoTierAlphas,
22
+ adjust_alpha,
23
+ benjamini_hochberg,
24
+ n_comparisons,
25
+ two_tier_alphas,
26
+ )
27
+ from abkit.stats.exceptions import (
28
+ AbkitStatsWarning,
29
+ MethodParamError,
30
+ QuarantinedMethodError,
31
+ SampleValidationError,
32
+ StatsError,
33
+ UnknownMethodError,
34
+ )
35
+ from abkit.stats.factory import create_method
36
+ from abkit.stats.registry import available_methods, get_method_class, register
37
+ from abkit.stats.result import TestResult
38
+ from abkit.stats.rng import derive_seed, make_rng
39
+ from abkit.stats.samples import (
40
+ Fraction,
41
+ JointMoments,
42
+ PairedSufficientStats,
43
+ RatioSample,
44
+ RatioSufficientStats,
45
+ Sample,
46
+ SufficientStats,
47
+ align_paired,
48
+ )
49
+ from abkit.stats.srm import (
50
+ DEFAULT_SRM_ALPHA,
51
+ SrmResult,
52
+ sequential_multinomial_srm,
53
+ srm_check,
54
+ )
55
+
56
+ __all__ = [
57
+ "AbkitStatsWarning",
58
+ "BaseMethod",
59
+ "DEFAULT_SRM_ALPHA",
60
+ "Fraction",
61
+ "JointMoments",
62
+ "MethodParamError",
63
+ "PairedSufficientStats",
64
+ "ParamSpec",
65
+ "QuarantinedMethodError",
66
+ "RatioSample",
67
+ "RatioSufficientStats",
68
+ "Sample",
69
+ "SampleValidationError",
70
+ "SrmResult",
71
+ "StatsError",
72
+ "SufficientStats",
73
+ "TestResult",
74
+ "TwoTierAlphas",
75
+ "UnknownMethodError",
76
+ "adjust_alpha",
77
+ "align_paired",
78
+ "available_methods",
79
+ "benjamini_hochberg",
80
+ "compute_method_config_id",
81
+ "create_method",
82
+ "derive_seed",
83
+ "get_method_class",
84
+ "make_rng",
85
+ "merge_joint_moments",
86
+ "merge_ratio_suffstats",
87
+ "merge_suffstats",
88
+ "method_config_payload",
89
+ "n_comparisons",
90
+ "register",
91
+ "sequential_multinomial_srm",
92
+ "srm_check",
93
+ "two_tier_alphas",
94
+ ]
@@ -0,0 +1,82 @@
1
+ """Mergeable sufficient statistics — the v2 incremental primitive.
2
+
3
+ Chan's parallel (Welford-family) update on centered moments: numerically stable,
4
+ never the catastrophic ``Σx²/n − x̄²`` form (docs/specs/statistics-changes.md §1.1).
5
+ In v1 this powers cross-day/stratum merges in memory; in v2 the warehouse
6
+ ``_ab_unit_state`` seam reads reduce to exactly these merges.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import numpy as np
12
+
13
+ from abkit.stats.exceptions import SampleValidationError
14
+ from abkit.stats.samples import JointMoments, RatioSufficientStats, SufficientStats
15
+
16
+
17
+ def _merged_name(name_a: str | None, name_b: str | None) -> str | None:
18
+ return name_a if name_a == name_b else None
19
+
20
+
21
+ def _chan_terms(
22
+ n_a: int, mean_a: float, n_b: int, mean_b: float
23
+ ) -> tuple[int, float, float, float]:
24
+ """Common Chan-update pieces: merged n & mean, the mean delta, and n_a·n_b/n."""
25
+ n = n_a + n_b
26
+ delta = mean_b - mean_a
27
+ weight = n_a * n_b / n
28
+ mean = mean_a + delta * n_b / n
29
+ return n, mean, delta, weight
30
+
31
+
32
+ def merge_suffstats(a: SufficientStats, b: SufficientStats) -> SufficientStats:
33
+ """Merge two disjoint per-unit populations of the same variant."""
34
+ if a.has_covariate != b.has_covariate:
35
+ raise SampleValidationError("cannot merge suffstats with and without covariate moments")
36
+ n, mean, delta_y, weight = _chan_terms(a.n, a.mean, b.n, b.mean)
37
+ m2 = a.m2 + b.m2 + delta_y**2 * weight
38
+ if not a.has_covariate:
39
+ return SufficientStats(n=n, mean=mean, m2=m2, name=_merged_name(a.name, b.name))
40
+
41
+ assert a.cov_mean is not None and a.cov_m2 is not None and a.cross_c is not None
42
+ assert b.cov_mean is not None and b.cov_m2 is not None and b.cross_c is not None
43
+ _, cov_mean, delta_x, _ = _chan_terms(a.n, a.cov_mean, b.n, b.cov_mean)
44
+ cov_m2 = a.cov_m2 + b.cov_m2 + delta_x**2 * weight
45
+ cross_c = a.cross_c + b.cross_c + delta_y * delta_x * weight
46
+ return SufficientStats(
47
+ n=n,
48
+ mean=mean,
49
+ m2=m2,
50
+ cov_mean=cov_mean,
51
+ cov_m2=cov_m2,
52
+ cross_c=cross_c,
53
+ name=_merged_name(a.name, b.name),
54
+ )
55
+
56
+
57
+ def merge_ratio_suffstats(a: RatioSufficientStats, b: RatioSufficientStats) -> RatioSufficientStats:
58
+ n, mean_num, delta_num, weight = _chan_terms(a.n, a.mean_num, b.n, b.mean_num)
59
+ _, mean_den, delta_den, _ = _chan_terms(a.n, a.mean_den, b.n, b.mean_den)
60
+ return RatioSufficientStats(
61
+ n=n,
62
+ mean_num=mean_num,
63
+ m2_num=a.m2_num + b.m2_num + delta_num**2 * weight,
64
+ mean_den=mean_den,
65
+ m2_den=a.m2_den + b.m2_den + delta_den**2 * weight,
66
+ c_nd=a.c_nd + b.c_nd + delta_num * delta_den * weight,
67
+ name=_merged_name(a.name, b.name),
68
+ )
69
+
70
+
71
+ def merge_joint_moments(a: JointMoments, b: JointMoments) -> JointMoments:
72
+ """Chan's update generalised to the full co-moment matrix."""
73
+ if a.labels != b.labels:
74
+ raise SampleValidationError(
75
+ f"cannot merge JointMoments with labels {a.labels} != {b.labels}"
76
+ )
77
+ n = a.n + b.n
78
+ delta = b.mean - a.mean
79
+ weight = a.n * b.n / n
80
+ mean = a.mean + delta * b.n / n
81
+ comoment = a.comoment + b.comoment + np.outer(delta, delta) * weight
82
+ return JointMoments(n=n, mean=mean, comoment=comoment, labels=a.labels)
abkit/stats/base.py ADDED
@@ -0,0 +1,347 @@
1
+ """``BaseMethod`` — the plugin contract every statistical method implements.
2
+
3
+ Methods are plugins (CLAUDE.md invariant): a new estimator is one subclass plus a
4
+ registry entry; the pipeline/DB/CLI never special-case a method name. Each method
5
+ declares its parameter schema (:class:`ParamSpec`), and its identity is the
6
+ canonical ``method_config_id`` hash (docs/specs/declarative-config.md §7):
7
+
8
+ method_config_id = sha256( method_name # registry name
9
+ + json_dumps_sorted(params) # non-default identity params
10
+ + ALGORITHM_VERSION ) # appended only when > 1
11
+
12
+ ``seed`` (and ``alpha``, which is experiment-level in the declarative model) are
13
+ identity-EXCLUDED so re-keying never orphans a published cumulative series; re-run
14
+ byte-stability comes from the deterministic per-row seed (``rng.derive_seed``).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import itertools
21
+ import math
22
+ from abc import ABC, abstractmethod
23
+ from collections.abc import Sequence
24
+ from dataclasses import dataclass
25
+ from typing import Any, ClassVar
26
+
27
+ import numpy as np
28
+
29
+ from abkit.stats.exceptions import MethodParamError, SampleValidationError
30
+ from abkit.stats.result import TestResult
31
+ from abkit.stats.samples import RatioSample, Sample
32
+ from abkit.utils.json_utils import json_dumps_sorted
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class ParamSpec:
37
+ """Schema entry for one method parameter.
38
+
39
+ ``identity=False`` marks the parameter as excluded from ``method_config_id``
40
+ (it never changes the statistical series identity — e.g. ``seed``).
41
+ Numeric params are validated for finiteness always (a NaN/inf param value can
42
+ never be a valid identity — ``json_dumps_sorted`` forbids it) and against the
43
+ optional ``minimum``/``maximum`` bounds — validation fails at construction
44
+ with :class:`MethodParamError`, never downstream in scipy/statsmodels.
45
+ """
46
+
47
+ name: str
48
+ types: tuple[type, ...]
49
+ default: Any
50
+ identity: bool = True
51
+ choices: tuple[Any, ...] | None = None
52
+ minimum: float | None = None
53
+ maximum: float | None = None
54
+ exclusive_bounds: bool = False
55
+ description: str = ""
56
+
57
+ def validate(self, value: Any, method_name: str) -> Any:
58
+ # Normalise numpy scalars (e.g. an np.int64 seed from the pipeline) to
59
+ # plain Python types before type-checking.
60
+ if isinstance(value, np.bool_):
61
+ value = bool(value)
62
+ elif isinstance(value, np.integer):
63
+ value = int(value)
64
+ elif isinstance(value, np.floating):
65
+ value = float(value)
66
+ if bool not in self.types and isinstance(value, bool):
67
+ raise MethodParamError(
68
+ f"{method_name}: param {self.name!r} must be {self._type_names()}, got bool"
69
+ )
70
+ if not isinstance(value, self.types):
71
+ if float in self.types and isinstance(value, int) and not isinstance(value, bool):
72
+ value = float(value)
73
+ else:
74
+ raise MethodParamError(
75
+ f"{method_name}: param {self.name!r} must be {self._type_names()}, "
76
+ f"got {type(value).__name__}"
77
+ )
78
+ if self.choices is not None and value not in self.choices:
79
+ raise MethodParamError(
80
+ f"{method_name}: param {self.name!r} must be one of {list(self.choices)}, got {value!r}"
81
+ )
82
+ if isinstance(value, float) and not math.isfinite(value):
83
+ raise MethodParamError(
84
+ f"{method_name}: param {self.name!r} must be finite, got {value!r}"
85
+ )
86
+ if isinstance(value, (int, float)):
87
+ below = self.minimum is not None and (
88
+ value < self.minimum or (self.exclusive_bounds and value == self.minimum)
89
+ )
90
+ above = self.maximum is not None and (
91
+ value > self.maximum or (self.exclusive_bounds and value == self.maximum)
92
+ )
93
+ if below or above:
94
+ left, right = ("(", ")") if self.exclusive_bounds else ("[", "]")
95
+ low = "-inf" if self.minimum is None else self.minimum
96
+ high = "+inf" if self.maximum is None else self.maximum
97
+ raise MethodParamError(
98
+ f"{method_name}: param {self.name!r} must be within "
99
+ f"{left}{low}, {high}{right}, got {value!r}"
100
+ )
101
+ return value
102
+
103
+ def _type_names(self) -> str:
104
+ return " | ".join(t.__name__ for t in self.types)
105
+
106
+
107
+ # --- shared parameter specs (single source; methods compose their schemas) ------
108
+
109
+ TEST_TYPE_PARAM = ParamSpec(
110
+ name="test_type",
111
+ types=(str,),
112
+ default="relative",
113
+ choices=("relative", "absolute"),
114
+ description="Effect estimand: relative lift over control (default) or absolute difference.",
115
+ )
116
+ CALCULATE_MDE_PARAM = ParamSpec(
117
+ name="calculate_mde",
118
+ types=(bool,),
119
+ default=False,
120
+ description="Compute per-arm MDE at the configured power (statsmodels solve).",
121
+ )
122
+ POWER_PARAM = ParamSpec(
123
+ name="power",
124
+ types=(float,),
125
+ default=0.8,
126
+ minimum=0.0,
127
+ maximum=1.0,
128
+ exclusive_bounds=True,
129
+ description="Target power for the MDE solve.",
130
+ )
131
+ COVARIATE_LOOKBACK_PARAM = ParamSpec(
132
+ name="covariate_lookback",
133
+ types=(str, int),
134
+ default=None,
135
+ description=(
136
+ "Pre-period covariate window (fixed whole-day lookback, e.g. '14d' — "
137
+ "statistics-changes.md §5). IDENTITY-BEARING: a different lookback is a "
138
+ "different covariate, hence a different series. The math here never "
139
+ "reads it — the pipeline's loader materialises the covariate values; "
140
+ "the duration grammar is validated by the config layer (the pure core "
141
+ "does not parse durations)."
142
+ ),
143
+ )
144
+ N_SAMPLES_PARAM = ParamSpec(
145
+ name="n_samples",
146
+ types=(int,),
147
+ default=1000,
148
+ minimum=1,
149
+ description="Number of bootstrap resamples.",
150
+ )
151
+ STRATIFY_PARAM = ParamSpec(
152
+ name="stratify",
153
+ types=(bool,),
154
+ default=False,
155
+ description="Resample within strata (requires categories_array on the samples).",
156
+ )
157
+ WEIGHT_METHOD_PARAM = ParamSpec(
158
+ name="weight_method",
159
+ types=(str,),
160
+ default="min",
161
+ choices=("min", "mean"),
162
+ description="How per-stratum weights are pooled across variants (baseline §4.2).",
163
+ )
164
+ STAT_PARAM = ParamSpec(
165
+ name="stat",
166
+ types=(str,),
167
+ default="mean",
168
+ description=(
169
+ "Named statistic bootstrapped per resample — a key of "
170
+ "abkit.stats.bootstrap.applier.STAT_FUNCS ('mean'/'median' built in; extend via "
171
+ "register_stat — names, not callables, so identity stays hashable). "
172
+ "The Poisson engine is mean-only (H7)."
173
+ ),
174
+ )
175
+ SEED_PARAM = ParamSpec(
176
+ name="seed",
177
+ types=(int,),
178
+ default=None,
179
+ identity=False,
180
+ description=(
181
+ "Bootstrap RNG seed. Identity-excluded for ALL bootstrap methods "
182
+ "(declarative-config.md §7); the pipeline derives it per row via rng.derive_seed."
183
+ ),
184
+ )
185
+ MAX_BLOCK_BYTES_PARAM = ParamSpec(
186
+ name="max_block_bytes",
187
+ types=(int,),
188
+ default=None,
189
+ identity=False,
190
+ minimum=1,
191
+ description=(
192
+ "Memory cap for the resample matrix; replicates stream in blocks under it "
193
+ "(H10). Never changes results — block boundaries are stream-invariant."
194
+ ),
195
+ )
196
+
197
+
198
+ def require_pair_type(method_name: str, group_1: Any, group_2: Any, expected: type) -> None:
199
+ """Raise unless both groups are instances of ``expected`` (clear input errors)."""
200
+ for label, group in (("first", group_1), ("second", group_2)):
201
+ if not isinstance(group, expected):
202
+ raise SampleValidationError(
203
+ f"{method_name}: {label} group must be {expected.__name__}, got {type(group).__name__}"
204
+ )
205
+
206
+
207
+ def method_config_payload(
208
+ method_name: str,
209
+ identity_params: dict[str, Any],
210
+ algorithm_version: int,
211
+ ) -> bytes:
212
+ """The exact bytes hashed into ``method_config_id`` — pinned by a byte test."""
213
+ payload = method_name + json_dumps_sorted(identity_params)
214
+ if algorithm_version > 1: # appended only when > 1 (match detectkit)
215
+ payload += str(algorithm_version)
216
+ return payload.encode("utf-8")
217
+
218
+
219
+ def compute_method_config_id(
220
+ method_name: str,
221
+ identity_params: dict[str, Any],
222
+ algorithm_version: int,
223
+ ) -> str:
224
+ return hashlib.sha256(
225
+ method_config_payload(method_name, identity_params, algorithm_version)
226
+ ).hexdigest()
227
+
228
+
229
+ class BaseMethod(ABC):
230
+ """Abstract statistical method: pairwise comparisons with dual entry.
231
+
232
+ Dual entry (architecture pillar 3): ``from_suffstats`` powers the closed-form
233
+ pipeline/explore path, ``from_samples`` the bootstrap & golden-reproduction
234
+ path; for closed-form methods the two are one math path (``from_samples``
235
+ reduces raw arrays to sufficient statistics and delegates).
236
+ """
237
+
238
+ #: Registry name (kebab-case, e.g. ``"cuped-t-test"``) — part of the identity hash.
239
+ name: ClassVar[str]
240
+ #: Bumped on any deliberate deviation from the captured baseline — never silently.
241
+ ALGORITHM_VERSION: ClassVar[int] = 1
242
+ #: The method's parameter schema.
243
+ param_specs: ClassVar[tuple[ParamSpec, ...]] = ()
244
+ #: Declarative capability attributes (plan R8) — the pipeline dispatches on
245
+ #: these instead of isinstance checks against concrete classes. Purely
246
+ #: descriptive: no numeric behaviour depends on them (no version bump).
247
+ #: Which container family ``from_samples`` expects: sample | fraction | ratio.
248
+ input_kind: ClassVar[str] = "sample"
249
+ #: Paired designs need unit-aligned arms (not served by the v1 pipeline).
250
+ is_paired: ClassVar[bool] = False
251
+ #: Needs a per-unit ``cov_array`` on both samples (CUPED / post-normed) —
252
+ #: the explore Tier-S gate reads this instead of guessing from param names.
253
+ requires_covariate: ClassVar[bool] = False
254
+ #: Eligible for the M5 always-valid sequential transform. True requires a
255
+ #: symmetric normal fixed CI, whose SE is recoverable by CI-inversion
256
+ #: (``sequential.se_from_ci_length``); the pipeline dispatches on this flag
257
+ #: instead of name-checking. Bootstrap percentile CIs are asymmetric → the
258
+ #: bootstrap base sets this False (docs/specs/m5-implementation-plan.md D1).
259
+ supports_sequential: ClassVar[bool] = True
260
+
261
+ def __init__(self, alpha: float = 0.05, **params: Any) -> None:
262
+ if not 0.0 < alpha < 1.0:
263
+ raise MethodParamError(f"{self.name}: alpha must be in (0, 1), got {alpha}")
264
+ self.alpha = float(alpha)
265
+
266
+ specs = {spec.name: spec for spec in self.param_specs}
267
+ unknown = set(params) - set(specs)
268
+ if unknown:
269
+ hints = []
270
+ if "seed" in unknown and "seed" not in specs:
271
+ hints.append(
272
+ "seed is only accepted by bootstrap methods (closed-form methods are "
273
+ "deterministic; declarative-config.md §7)"
274
+ )
275
+ if "alpha" in unknown:
276
+ hints.append("alpha is a direct argument, not a method param")
277
+ raise MethodParamError(
278
+ f"{self.name}: unknown param(s) {sorted(unknown)}; "
279
+ f"valid params: {sorted(specs)}" + (". " + " ".join(hints) if hints else "")
280
+ )
281
+
282
+ self.params: dict[str, Any] = {}
283
+ for name, spec in specs.items():
284
+ if name in params and params[name] is not None:
285
+ self.params[name] = spec.validate(params[name], self.name)
286
+ else:
287
+ self.params[name] = spec.default
288
+ self._validate_params()
289
+
290
+ def _validate_params(self) -> None: # noqa: B027 — optional hook, deliberately non-abstract
291
+ """Hook for cross-parameter validation (override as needed)."""
292
+
293
+ # --- identity -----------------------------------------------------------
294
+ @property
295
+ def test_type(self) -> str:
296
+ return str(self.params["test_type"])
297
+
298
+ @property
299
+ def identity_params(self) -> dict[str, Any]:
300
+ """Non-default, identity-bearing params — the dict that is hashed & stored."""
301
+ specs = {spec.name: spec for spec in self.param_specs}
302
+ return {
303
+ name: value
304
+ for name, value in self.params.items()
305
+ if specs[name].identity and value != specs[name].default
306
+ }
307
+
308
+ @property
309
+ def method_params(self) -> dict[str, Any]:
310
+ """Alias for :attr:`identity_params` — what lands in ``TestResult``/``_ab_results``."""
311
+ return self.identity_params
312
+
313
+ @property
314
+ def method_config_id(self) -> str:
315
+ return compute_method_config_id(self.name, self.identity_params, self.ALGORITHM_VERSION)
316
+
317
+ # --- comparison ---------------------------------------------------------
318
+ def compare(self, groups: Sequence[Any]) -> list[TestResult]:
319
+ """Run all pairwise variant comparisons (baseline §5: ``combinations(groups, 2)``)."""
320
+ if len(groups) < 2:
321
+ raise SampleValidationError(f"{self.name}: compare requires at least two groups")
322
+ return [
323
+ self.compare_pair(group_1, group_2)
324
+ for group_1, group_2 in itertools.combinations(groups, 2)
325
+ ]
326
+
327
+ def compare_pair(self, group_1: Any, group_2: Any) -> TestResult:
328
+ """Compare one (control, treatment) pair, dispatching on the input kind."""
329
+ raw = isinstance(group_1, (Sample, RatioSample)), isinstance(group_2, (Sample, RatioSample))
330
+ if raw[0] != raw[1]:
331
+ raise SampleValidationError(
332
+ f"{self.name}: cannot mix raw samples and sufficient statistics in one pair"
333
+ )
334
+ if raw[0]:
335
+ return self.from_samples(group_1, group_2)
336
+ return self.from_suffstats(group_1, group_2)
337
+
338
+ @abstractmethod
339
+ def from_samples(self, sample_1: Any, sample_2: Any) -> TestResult:
340
+ """Compare from per-unit arrays (bootstrap & golden-reproduction entry)."""
341
+
342
+ @abstractmethod
343
+ def from_suffstats(self, stats_1: Any, stats_2: Any) -> TestResult:
344
+ """Compare from sufficient statistics (closed-form pipeline/explore entry)."""
345
+
346
+ def __repr__(self) -> str:
347
+ return f"{type(self).__name__}(alpha={self.alpha}, params={self.params})"