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
abkit/validate/load.py ADDED
@@ -0,0 +1,160 @@
1
+ """The A/A load stage: build a :class:`PlaceboPanel` from the experiment's own cohort
2
+ over the actual cadence grid (docs/specs/m4-implementation-plan.md D1, WP2).
3
+
4
+ The placebo data source is the experiment's *own* pooled per-unit metric values,
5
+ loaded per cutoff through the pipeline's real loaders (``RecomputeBackend.load_cutoff``
6
+ → ``metric_loader``, so the packaged assignment macro, the cumulative window semantics,
7
+ the CUPED pre-period render, and the D11 canonical unit order all come for free). The
8
+ scorer then permutes the pooled units into arms (resample.py) — an exact null by
9
+ construction. Nothing here writes to the warehouse: the split is in-memory only.
10
+
11
+ Dense grids are subsampled to ``cap`` points, denser early (where the peeking FPR
12
+ accrues fastest), with the horizon always retained and the ``(kept, total)`` count
13
+ disclosed on the panel (aa-fpr §3 "the matrix must state when it did").
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import numpy as np
19
+
20
+ from abkit.compute.recompute_backend import RecomputeBackend
21
+ from abkit.config.experiment_config import ComparisonConfig
22
+ from abkit.config.metric_config import MetricConfig
23
+ from abkit.core.period_planner import Cutoff, Grid
24
+ from abkit.loaders.metric_loader import MetricLoadResult
25
+ from abkit.validate._types import ValidateError
26
+ from abkit.validate.panel import PanelCutoff, PlaceboPanel
27
+
28
+ #: Peeking-grid cap (aa-fpr §3 "~100 points, denser early").
29
+ DEFAULT_GRID_CAP = 100
30
+
31
+ _DAY_SECONDS = 86400.0
32
+
33
+ #: Metric-kind → (primary role, secondary role) in ``MetricLoadResult.roles_by_variant``.
34
+ _ROLES: dict[str, tuple[str, str | None]] = {
35
+ "sample": ("value", None),
36
+ "fraction": ("count", "nobs"),
37
+ "ratio": ("numerator", "denominator"),
38
+ }
39
+
40
+
41
+ def subsample_grid(cutoffs: tuple[Cutoff, ...], cap: int) -> tuple[list[Cutoff], int, int]:
42
+ """Downsample an ascending cutoff grid to ``cap`` points, denser early.
43
+
44
+ The horizon (last) and first looks are always kept; the interior is sampled with
45
+ quadratic spacing so points cluster early where the peeking FPR accrues fastest,
46
+ then backfilled with the earliest unused looks toward ``cap``. Returns
47
+ ``(kept_cutoffs, kept_count, total_count)`` for the disclosure note.
48
+ """
49
+ total = len(cutoffs)
50
+ if cap < 2:
51
+ raise ValidateError(f"grid cap must be >= 2, got {cap}")
52
+ if total <= cap:
53
+ return list(cutoffs), total, total
54
+
55
+ picks: set[int] = {0, total - 1}
56
+ for k in range(cap):
57
+ frac = (k / (cap - 1)) ** 2 # quadratic → denser near 0
58
+ picks.add(int(round(frac * (total - 1))))
59
+ i = 0
60
+ while len(picks) < cap and i < total: # backfill earliest-first (denser early)
61
+ picks.add(i)
62
+ i += 1
63
+ kept = sorted(picks)
64
+ return [cutoffs[i] for i in kept], len(kept), total
65
+
66
+
67
+ def _pool(
68
+ loaded: MetricLoadResult, input_kind: str
69
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray | None, np.ndarray | None]:
70
+ """Pool a per-variant load into one per-unit (units, values, secondary, covariate)."""
71
+ if input_kind not in _ROLES:
72
+ raise ValidateError(f"unsupported metric input_kind {input_kind!r}")
73
+ primary_role, secondary_role = _ROLES[input_kind]
74
+ variants = loaded.variants()
75
+ if not variants:
76
+ empty = np.array([], dtype=np.float64)
77
+ return np.array([], dtype=object), empty, None, None
78
+
79
+ def _stack(role: str) -> np.ndarray:
80
+ return np.concatenate([loaded.roles_by_variant[v][role] for v in variants])
81
+
82
+ units = np.concatenate([loaded.units_by_variant[v] for v in variants])
83
+ values = _stack(primary_role)
84
+ secondary = _stack(secondary_role) if secondary_role is not None else None
85
+ covariate = None
86
+ if all("covariate" in loaded.roles_by_variant[v] for v in variants):
87
+ covariate = _stack("covariate")
88
+ return units, values, secondary, covariate
89
+
90
+
91
+ def load_placebo_panel(
92
+ backend: RecomputeBackend,
93
+ comparison: ComparisonConfig,
94
+ metric: MetricConfig,
95
+ metric_sql: str,
96
+ grid: Grid,
97
+ *,
98
+ input_kind: str,
99
+ cap: int = DEFAULT_GRID_CAP,
100
+ ) -> PlaceboPanel:
101
+ """Load the pooled per-unit panel for one (metric, comparison) over the grid.
102
+
103
+ ``input_kind`` mirrors the method family (``sample`` | ``fraction`` | ``ratio``).
104
+ The covariate is loaded when the comparison's method declares ``covariate_lookback``
105
+ (a fixed pre-period constant per unit — the same value across cutoffs).
106
+ """
107
+ kept_cutoffs, kept, total = subsample_grid(grid.cutoffs, cap)
108
+ if not kept_cutoffs:
109
+ raise ValidateError("empty cadence grid")
110
+
111
+ loads = [
112
+ (cut, backend.load_cutoff(comparison, metric, metric_sql, grid, cut))
113
+ for cut in kept_cutoffs
114
+ ]
115
+
116
+ # The horizon (last, by construction the superset of every earlier cumulative
117
+ # cutoff) defines the global unit universe and the fixed covariate.
118
+ horizon_load = loads[-1][1]
119
+ h_units, _h_values, _h_secondary, h_cov = _pool(horizon_load, input_kind)
120
+ if h_units.size == 0:
121
+ raise ValidateError(
122
+ f"metric '{metric.name}': no units at the horizon cutoff — nothing to validate"
123
+ )
124
+
125
+ order = np.argsort(h_units, kind="stable")
126
+ global_units = h_units[order]
127
+ global_index = {unit: idx for idx, unit in enumerate(global_units)}
128
+ n_units = int(global_units.size)
129
+ covariate = None if h_cov is None else np.asarray(h_cov[order], dtype=np.float64)
130
+
131
+ panel_cutoffs: list[PanelCutoff] = []
132
+ for cut, loaded in loads:
133
+ units, values, secondary, _cov = _pool(loaded, input_kind)
134
+ # map present units → global indices (units absent from the horizon cannot
135
+ # occur under cumulative growth; guard drops any stray rather than crashing)
136
+ keep = np.array([unit in global_index for unit in units], dtype=bool)
137
+ if not keep.all():
138
+ units, values = units[keep], values[keep]
139
+ if secondary is not None:
140
+ secondary = secondary[keep]
141
+ unit_idx = np.array([global_index[unit] for unit in units], dtype=np.int64)
142
+ elapsed = (cut.end_ts - grid.start_ts).total_seconds() / _DAY_SECONDS
143
+ panel_cutoffs.append(
144
+ PanelCutoff(
145
+ elapsed_days=elapsed,
146
+ is_horizon=cut.is_horizon,
147
+ unit_idx=unit_idx,
148
+ values=np.asarray(values, dtype=np.float64),
149
+ secondary=None if secondary is None else np.asarray(secondary, dtype=np.float64),
150
+ )
151
+ )
152
+
153
+ return PlaceboPanel(
154
+ n_units=n_units,
155
+ cutoffs=tuple(panel_cutoffs),
156
+ covariate=covariate,
157
+ input_kind=input_kind,
158
+ kept_grid_points=kept,
159
+ total_grid_points=total,
160
+ )
@@ -0,0 +1,59 @@
1
+ """The placebo panel — per-cutoff pooled per-unit values the scorer resamples.
2
+
3
+ The load stage (WP2) fills this from the experiment's own cohort over the actual
4
+ cadence grid (docs/specs/m4-implementation-plan.md D1); WP1 defines the contract
5
+ and scores against it. All arrays are numpy, in canonical sorted-unit order (the
6
+ D11 byte-stability guarantee, metric_loader.py:186–205).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+
13
+ import numpy.typing as npt
14
+
15
+ FloatArray = npt.NDArray # float64 per-unit values
16
+ IntArray = npt.NDArray # int64 global unit indices
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class PanelCutoff:
21
+ """Pooled per-unit data at one cadence cutoff.
22
+
23
+ A unit's arm is fixed at enrollment and constant across the grid (D1), so the
24
+ cutoffs carry *global* unit indices (``unit_idx`` into ``[0, n_units)``) rather
25
+ than re-indexing per cutoff. The unit set grows monotonically over cumulative
26
+ windows (a unit present at cutoff ``k`` is present at every later cutoff).
27
+ """
28
+
29
+ elapsed_days: float
30
+ is_horizon: bool
31
+ #: Global unit indices present by this cutoff (into ``[0, PlaceboPanel.n_units)``).
32
+ unit_idx: IntArray
33
+ #: Primary per-unit value aligned to ``unit_idx`` — the metric value for a
34
+ #: sample/CUPED metric, the per-unit numerator for a ratio metric, or the
35
+ #: per-unit success count for a fraction metric.
36
+ values: FloatArray
37
+ #: Per-unit secondary array aligned to ``unit_idx`` — the denominator for a
38
+ #: ratio metric, the trials (``nobs``) for a fraction metric, else None.
39
+ secondary: FloatArray | None = None
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class PlaceboPanel:
44
+ """The full panel for one (experiment, metric) over the subsampled grid.
45
+
46
+ ``input_kind`` mirrors ``BaseMethod.input_kind`` (sample | ratio | fraction) and
47
+ drives how each arm's sufficient statistics are built (resample.py).
48
+ ``kept_grid_points``/``total_grid_points`` disclose any peeking-grid subsampling
49
+ (aa-fpr §3 "the matrix must state when it did").
50
+ """
51
+
52
+ n_units: int
53
+ cutoffs: tuple[PanelCutoff, ...]
54
+ #: Per-unit covariate aligned to global indices ``[0, n_units)`` — a fixed
55
+ #: pre-period constant (CUPED), present-independent; None when no covariate.
56
+ covariate: FloatArray | None
57
+ input_kind: str
58
+ kept_grid_points: int
59
+ total_grid_points: int
@@ -0,0 +1,59 @@
1
+ """Serialize an :class:`AaValidateResult` into ``_ab_aa_runs`` records (m4 WP3).
2
+
3
+ Each :class:`CellResult` becomes one ``save_aa_run`` record with a per-cell-unique
4
+ ``run_id`` (D4) — every ``AA_RUN_COLUMNS`` key present (``save_aa_run`` stamps
5
+ ``created_at`` itself). The command (WP4) calls ``save_aa_run`` for each record under
6
+ the validate lock.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ from abkit.utils.json_utils import json_dumps_sorted
14
+ from abkit.validate.result import AaValidateResult
15
+ from abkit.validate.run_id import cell_hash, make_run_id
16
+
17
+
18
+ def aa_run_records(result: AaValidateResult) -> list[dict[str, Any]]:
19
+ """Every scored cell as a ``save_aa_run``-ready record (``created_at`` excluded)."""
20
+ records: list[dict[str, Any]] = []
21
+ for cell in result.cells:
22
+ run_id = make_run_id(
23
+ result.run_stamp,
24
+ cell_hash(cell.metric, cell.method_config_id, cell.mode, cell.alpha),
25
+ )
26
+ details = {**cell.details, "recommended": cell.recommended, "budget": cell.budget}
27
+ records.append(
28
+ {
29
+ "experiment": result.experiment,
30
+ "run_id": run_id,
31
+ "metric": cell.metric,
32
+ "method_name": cell.method_name,
33
+ "method_params": cell.method_params,
34
+ "method_config_id": cell.method_config_id,
35
+ "mode": cell.mode,
36
+ "iterations": cell.iterations,
37
+ "alpha": cell.alpha,
38
+ "injected_effect": cell.injected_effect,
39
+ "fpr": cell.fpr,
40
+ "peeking_fpr": cell.peeking_fpr,
41
+ "power": cell.power,
42
+ "achieved_mde": cell.achieved_mde,
43
+ "coverage": cell.coverage,
44
+ "effect_exaggeration": cell.effect_exaggeration,
45
+ "tau2": cell.tau2,
46
+ "fpr_sequential": cell.fpr_sequential,
47
+ "peeking_fpr_sequential": cell.peeking_fpr_sequential,
48
+ "power_sequential": cell.power_sequential,
49
+ "coverage_sequential": cell.coverage_sequential,
50
+ "effect_exaggeration_sequential": cell.effect_exaggeration_sequential,
51
+ "ci_width": cell.ci_width,
52
+ "ci_width_sequential": cell.ci_width_sequential,
53
+ "verdict": cell.verdict,
54
+ "details": json_dumps_sorted(details),
55
+ "status": cell.status,
56
+ "error_message": cell.error_message,
57
+ }
58
+ )
59
+ return records
@@ -0,0 +1,94 @@
1
+ """Placebo A/A splits (docs/specs/m4-implementation-plan.md D1).
2
+
3
+ One iteration draws a single unit-level permutation, **held constant across the
4
+ whole cadence grid** (a unit's arm is fixed at enrollment — the real assignment
5
+ semantics). Permuting the pooled population destroys any true treatment effect,
6
+ so both arms are exchangeable draws from one distribution → an exact null by
7
+ construction (the standard permutation-A/A). Seeds are always derived
8
+ (``derive_seed``, rng.py:24–34) — never RNG-global, never wall-clock (D13).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import numpy as np
14
+
15
+ from abkit.stats.rng import make_rng
16
+ from abkit.stats.samples import Fraction, RatioSample, RatioSufficientStats, Sample, SufficientStats
17
+
18
+ #: Minimum units per arm to build sufficient statistics (variance / covariance
19
+ #: need ≥2; below this the cutoff is a gap, never a zero — mirrors the readout's
20
+ #: demotion discipline).
21
+ MIN_ARM_UNITS = 2
22
+
23
+ ArmStats = SufficientStats | RatioSufficientStats | Fraction
24
+
25
+
26
+ def placebo_mask(n_units: int, share_a: float, seed: int) -> np.ndarray:
27
+ """Boolean arm-A membership over global units ``[0, n_units)``.
28
+
29
+ ``share_a`` is arm A's expected split share (e.g. 0.5). The count is rounded
30
+ to the nearest unit; the permutation is drawn from a fresh local generator.
31
+ """
32
+ if n_units <= 0:
33
+ raise ValueError(f"n_units must be positive, got {n_units}")
34
+ if not 0.0 < share_a < 1.0:
35
+ raise ValueError(f"share_a must be in (0, 1), got {share_a}")
36
+ rng = make_rng(seed)
37
+ perm = rng.permutation(n_units)
38
+ n_a = int(round(n_units * share_a))
39
+ n_a = min(max(n_a, 1), n_units - 1) # keep both arms non-empty
40
+ mask = np.zeros(n_units, dtype=bool)
41
+ mask[perm[:n_a]] = True
42
+ return mask
43
+
44
+
45
+ def present_positions(mask: np.ndarray, unit_idx: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
46
+ """Split a cutoff's present units into (arm-A, arm-B) positions.
47
+
48
+ ``unit_idx`` are the global indices present at the cutoff; the returned arrays
49
+ index *into the cutoff's own value arrays* (``PanelCutoff.values``), so
50
+ ``values[pos_a]`` are arm A's values at that cutoff.
51
+ """
52
+ arm_of_present = mask[unit_idx]
53
+ pos_a = np.flatnonzero(arm_of_present)
54
+ pos_b = np.flatnonzero(~arm_of_present)
55
+ return pos_a, pos_b
56
+
57
+
58
+ def build_arm(
59
+ input_kind: str,
60
+ values: np.ndarray,
61
+ secondary: np.ndarray | None,
62
+ covariate: np.ndarray | None,
63
+ unit_idx: np.ndarray,
64
+ pos: np.ndarray,
65
+ *,
66
+ name: str | None = None,
67
+ ) -> ArmStats | None:
68
+ """Build one arm's sufficient statistics from its present-unit positions.
69
+
70
+ Returns ``None`` when the arm is too small to score (``< MIN_ARM_UNITS``) — a
71
+ gap, not a zero. ``covariate`` is indexed by *global* unit id
72
+ (``unit_idx[pos]``) since it is a fixed per-unit constant; the value arrays are
73
+ indexed by cutoff position (``pos``). ``secondary`` is the per-unit trials
74
+ (fraction) or denominator (ratio).
75
+ """
76
+ if pos.size < MIN_ARM_UNITS:
77
+ return None
78
+ arm_values = values[pos]
79
+ if input_kind == "fraction":
80
+ if secondary is None:
81
+ raise ValueError("fraction input_kind requires an nobs (trials) array")
82
+ nobs = float(secondary[pos].sum())
83
+ if nobs <= 0:
84
+ return None # a zero-trial arm is degenerate — a gap, not a crash (Fraction rejects nobs≤0)
85
+ # per-unit (successes, trials) summed into the arm's proportion suffstats
86
+ return Fraction(count=float(arm_values.sum()), nobs=nobs, name=name)
87
+ if input_kind == "ratio":
88
+ if secondary is None:
89
+ raise ValueError("ratio input_kind requires a denominator array")
90
+ return RatioSufficientStats.from_ratio_sample(
91
+ RatioSample(arm_values, secondary[pos], name=name)
92
+ )
93
+ cov = None if covariate is None else covariate[unit_idx[pos]]
94
+ return SufficientStats.from_sample(Sample(arm_values, cov_array=cov, name=name))
@@ -0,0 +1,60 @@
1
+ """The validate result model — per-cell rows + the recommendation (m4 WP3).
2
+
3
+ Flattens the donor ``AutoTuneResult`` to the as-built ``_ab_aa_runs`` shape
4
+ (docs/specs/aa-false-positive-matrix.md §7 as amended, tables.py:224–263): one
5
+ :class:`CellResult` per scored (metric × method × alpha) cell, plus the recommended
6
+ method per metric.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+ from typing import Any
13
+
14
+ from abkit.validate._types import DecisionEntry
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class CellResult:
19
+ """One scored matrix cell — maps 1:1 onto an ``_ab_aa_runs`` row."""
20
+
21
+ metric: str
22
+ method_name: str
23
+ method_params: str # canonical JSON
24
+ method_config_id: str
25
+ mode: str # fpr | power | mde (the selection objective)
26
+ alpha: float # effective post-correction per-comparison alpha
27
+ iterations: int
28
+ injected_effect: float | None
29
+ fpr: float | None
30
+ peeking_fpr: float | None
31
+ power: float | None
32
+ achieved_mde: float | None
33
+ coverage: float | None
34
+ effect_exaggeration: float | None
35
+ verdict: str # plain-language per-method verdict
36
+ budget: float | None # the aa_fpr_budget the verdict judged against
37
+ recommended: bool
38
+ details: dict[str, Any] # peeking curve, subsample note, selection rationale, warnings
39
+ status: str = "success" # success | failed
40
+ error_message: str = ""
41
+ # M5 D8 always-valid sequential column (None when the method is sequential-ineligible
42
+ # or τ² could not be anchored). ``tau2`` is the frozen mixture variance (provenance).
43
+ tau2: float | None = None
44
+ fpr_sequential: float | None = None
45
+ peeking_fpr_sequential: float | None = None
46
+ power_sequential: float | None = None
47
+ coverage_sequential: float | None = None
48
+ effect_exaggeration_sequential: float | None = None
49
+ ci_width: float | None = None
50
+ ci_width_sequential: float | None = None
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class AaValidateResult:
55
+ """The whole validate run for one experiment."""
56
+
57
+ experiment: str
58
+ run_stamp: str
59
+ cells: tuple[CellResult, ...]
60
+ decision_log: tuple[DecisionEntry, ...] = field(default_factory=tuple)
@@ -0,0 +1,45 @@
1
+ """Deterministic, wall-clock-free run ids for ``_ab_aa_runs`` (m4 D4).
2
+
3
+ The table's PK is ``(experiment, run_id)`` under ``ReplacingMergeTree(created_at)``, so
4
+ a matrix written under one shared ``run_id`` would collapse to a single row after a
5
+ merge. Each row therefore gets a per-cell-unique id ``f"{run_stamp}:{cell_hash}"``:
6
+
7
+ - ``cell_hash`` identifies the scored cell (metric, method_config_id, mode, alpha) —
8
+ stable across invocations;
9
+ - ``run_stamp`` identifies the invocation (the frozen run timestamp + selection
10
+ inputs) — so re-running validate appends a fresh audit row rather than silently
11
+ replacing the prior one, while ``find_calibration`` still picks the newest
12
+ ``created_at`` among matching cells.
13
+
14
+ Both are ``sha256`` over ``json_dumps_sorted`` — no wall clock inside the hash (the
15
+ timestamp is an explicit input, the donor ``config_emitter.compute_run_id`` discipline).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ from typing import Any
22
+
23
+ from abkit.utils.json_utils import json_dumps_sorted
24
+
25
+
26
+ def _digest(payload: dict[str, Any], length: int) -> str:
27
+ return hashlib.sha256(json_dumps_sorted(payload).encode("utf-8")).hexdigest()[:length]
28
+
29
+
30
+ def cell_hash(metric: str, method_config_id: str, mode: str, alpha: float) -> str:
31
+ """A stable 12-hex id for one scored matrix cell."""
32
+ return _digest(
33
+ {"metric": metric, "method_config_id": method_config_id, "mode": mode, "alpha": alpha},
34
+ 12,
35
+ )
36
+
37
+
38
+ def run_stamp(experiment: str, now_iso: str, selection: dict[str, Any]) -> str:
39
+ """An 8-hex id for one validate invocation (the frozen run time is an input)."""
40
+ return _digest({"experiment": experiment, "now": now_iso, "selection": selection}, 8)
41
+
42
+
43
+ def make_run_id(stamp: str, cell: str) -> str:
44
+ """Combine the invocation stamp and the cell hash into the row's ``run_id``."""
45
+ return f"{stamp}:{cell}"