Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(ab): report when the accept hold is what keeps a verdict at continue (#1524) (#1585)

Yunare Maia9e0874e72951
diff --git a/benchmarks/gate-1265-ab-nig.md b/benchmarks/gate-1265-ab-nig.md
index 470900a1..9bc496d9 100644
--- a/benchmarks/gate-1265-ab-nig.md
+++ b/benchmarks/gate-1265-ab-nig.md
@@ -128,6 +128,19 @@ scale. k = 5 keeps almost all of k = 8's power for 3 fewer rows.
- **Row order matters for the held-out rows.** The first k rows of each arm, in file order,
set the scale. If an arm's first rows are all identical, more rows are held out until one
differs; this depends only on the held-out rows, so the guarantee is unchanged.
+- **These sweeps predate the accept hold.** `ACCEPT_HOLD_SPREAD_RATIO` (#1419) was added after
+ this record was written, so every number above is from a run with the hold OFF. On Gaussian
+ rows the two spreads agree, so the hold changes almost no verdict — 2 of the 600 seeded runs in
+ `tests/test_issue1265_ab_nig.py`, one only in the number of rows it took and one rejecting
+ instead of accepting, which is the safe direction — and the conclusions here carry over. The
+ timing figures in particular were not measured with it on.
+- **A hold that fires on a saturated warm-up is never released by more rows.** The held-out
+ rows are fixed, so a run can sit at `continue` for the whole dataset while the confidence
+ sequence for the difference is already inside `+-effect_size`. `soup ab` now reports that
+ state (`accept_held` plus the two spreads) in the panel and on the `MsprtVerdict` that
+ `run_msprt` / `msprt_step` return, instead of only advising more samples (#1524). It has
+ no JSON output, and a held run sends no webhook. #1418 replaced the accept rule and kept
+ this hold, so the hold still applies.
## Environment
diff --git a/changelog.d/0.75.1/1585.changed.md b/changelog.d/0.75.1/1585.changed.md
new file mode 100644
index 00000000..4f886e2e
--- /dev/null
+++ b/changelog.d/0.75.1/1585.changed.md
@@ -0,0 +1 @@
+- `soup ab` now says when the accept hold is what is keeping a run at `continue`. #1419 holds `accept_h0` back while the tested rows spread more than `ACCEPT_HOLD_SPREAD_RATIO` (3) times the held-out ones, and the held-out rows are fixed — so once that hold fires on a saturated warm-up (a warm cache, or a judge that gives the same score for the first rows), no amount of extra data of the same kind releases it. The run sat at `continue` for the whole dataset with the accept rule already satisfied, while the panel printed "Insufficient evidence. Collect more samples and re-run.", advice that cannot help. A `continue` now carries `accept_held` plus the two spreads that decided it (`held_out_spread`, `tested_spread`, and `held_out_rows`), and the panel prints one line naming the ratio and what to do about it. The four keys are not added to the webhook payload: a held run is a `continue` and the webhook fires only on a terminal decision, so they could only ever be `false` / `null` there — the panel and the `MsprtVerdict` are where the facts live. These are new keys only: nothing is renamed or removed, and a run that is not held carries no note at all. The accept rule itself is unchanged (#1524 by @yunaremaia in #1585).
\ No newline at end of file
diff --git a/docs/evaluation.md b/docs/evaluation.md
index 713b3d22..cdd3c87d 100644
--- a/docs/evaluation.md
+++ b/docs/evaluation.md
@@ -269,6 +269,20 @@ The statistic is a Bayes factor that averages over both the size of the differen
`--effect-size` is in the metric's units, but the statistic needs it in standard deviations. So the first 5 rows of each arm set that scale (their pooled standard deviation) and are not otherwise tested; the verdict table shows this as `prior_scale`, and the reported means and row counts still cover every row. If an arm's first rows are all identical, more rows are held out until one differs. If they barely vary (a warm cache, or a judge that gives 1.0 early), `accept_h0` waits as `continue` while the tested rows' standard deviation is more than 3 times theirs: that start makes the prior far too wide. A `reject_h0` is never held back.
+That wait is worth reading, because the held-out rows are fixed: once the hold fires, **more rows of the same kind never release it**. A run in that state is stuck at `continue` with the accept rule already satisfied — the confidence sequence for the difference lies inside `(-effect_size, +effect_size)` — so the verdict reports the hold rather than leaving you to guess, and the panel prints one line naming the ratio and what to do about it:
+
+```text
+Held back: the tested rows spread 25.7 times the held-out ones (held_out_spread
+0.002218, tested_spread 0.05706, limit 3x), so accept_h0 is withheld even though
+the confidence sequence for the difference is already inside +-0.1. The first 5
+rows of each arm set the scale of --effect-size and barely vary (a warm cache, or
+a judge that gives the same score early). Those rows are fixed, so more samples of
+the same kind will not release the hold: drop them, or reorder the input so the
+first rows vary, and re-run.
+```
+
+The same three facts are on the verdict returned by `run_msprt` / `msprt_step`: `accept_held` (bool), `held_out_spread` and `tested_spread` (the two pooled standard deviations, both `null` when nothing is held — a `continue` with no hold carries no explanation). The held-out rows' spread is measured over however many rows were actually held out, which is more than 5 when an arm's first rows are all identical. A webhook is never sent for a held run: `accept_held=True` is only legal on a `continue`, and the webhook fires only on a terminal decision.
+
A simulation of the re-run-after-every-pair procedure (`--effect-size` from 0.1 to 5 standard deviations, 100,000 runs each, up to 1000 rows per arm) gives a worst false-positive rate of 0.033 at `--alpha 0.05` and 0.0066 at `--alpha 0.01`. The burn-in design this replaced (#1227) sat at 0.051 and 0.011. Against a true difference of exactly `--effect-size`, the test finds it with probability above 0.99 at `--alpha 0.05` or below when `--effect-size` is at least 0.3 standard deviations (1000 rows per arm; 0.984 at `--alpha 0.1`). There are two costs. When `--effect-size` is below about 0.2 standard deviations, 1000 rows are too few for either design to be reliable, and this one detects less often (0.31 against 0.45 at 0.1 standard deviations, `--alpha 0.05`). And when there is no difference, reaching `accept_h0` takes longer than under the burn-in design at small effect sizes. Mean pairs at stop when the two arms are the same, `--alpha 0.05`, runs of up to 1000 rows per arm, by `--effect-size` in standard deviations:
| `--effect-size` / sd | 0.2 | 0.3 | 0.4 | 0.5 | 0.7 | 1 | 1.5 | 2 | 5 |
diff --git a/src/soup_cli/commands/ab.py b/src/soup_cli/commands/ab.py
index c1b0099f..d437848e 100644
--- a/src/soup_cli/commands/ab.py
+++ b/src/soup_cli/commands/ab.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import math
from typing import Optional
import typer
@@ -13,6 +14,7 @@ from rich.table import Table
from soup_cli.commands._webhook_cli import emit_webhooks, validate_webhook_flags
from soup_cli.config.deprecation import deadline_clause
from soup_cli.utils.ab_test import (
+ ACCEPT_HOLD_SPREAD_RATIO,
HIGHER_IS_BETTER,
PRIOR_SCALE_ROWS,
MsprtConfig,
@@ -124,9 +126,45 @@ def ab(
table.add_row("n_treatment", str(verdict.n_treatment))
table.add_row("mean_control", f"{verdict.mean_control:.4f}")
table.add_row("mean_treatment", f"{verdict.mean_treatment:.4f}")
+ # #1524 - the two spreads behind the hold, when it is what kept the verdict
+ # at `continue`. Shown next to the statistic so the reader can see that the
+ # accept rule was already satisfied.
+ if verdict.accept_held:
+ table.add_row("accept_held", "[bold]true[/]")
+ table.add_row("held_out_rows", str(verdict.held_out_rows))
+ table.add_row("held_out_spread", f"{verdict.held_out_spread:.4g}")
+ table.add_row("tested_spread", f"{verdict.tested_spread:.4g}")
console.print(table)
- if verdict.decision == "reject_h0" and worse:
+ if verdict.accept_held:
+ # #1524 - the accept rule is already satisfied (the confidence sequence
+ # lies inside the effect-size band); the only thing keeping this at
+ # `continue` is the 3x spread rule. The held-out rows are fixed,
+ # so "collect more samples" cannot help here — name the ratio and point
+ # at the rows that actually set it.
+ ratio = (
+ verdict.tested_spread / verdict.held_out_spread
+ if verdict.held_out_spread
+ else math.inf
+ )
+ console.print(
+ Panel(
+ "[cyan]Held back: the tested rows spread "
+ f"{ratio:.3g} times the held-out ones "
+ f"(held_out_spread {verdict.held_out_spread:.4g}, "
+ f"tested_spread {verdict.tested_spread:.4g}, "
+ f"limit {ACCEPT_HOLD_SPREAD_RATIO:g}x), so accept_h0 is "
+ "withheld even though the confidence sequence for the "
+ f"difference is already inside +-{cfg.effect_size:g}. "
+ f"The first {verdict.held_out_rows} rows of each arm set the scale of "
+ "--effect-size and barely vary (a warm cache, or a judge that gives "
+ "the same score early). Those rows are fixed, so more samples of the "
+ "same kind will not release the hold: drop them, or reorder the input "
+ "so the first rows vary, and re-run.[/]",
+ border_style="cyan",
+ )
+ )
+ elif verdict.decision == "reject_h0" and worse:
console.print(
Panel(
"[red]Significant difference detected: the treatment is worse than "
@@ -173,6 +211,10 @@ def ab(
# Webhook only fires on a terminal decision (reject_h0 / accept_h0) —
# a `continue` verdict carries no actionable signal (issue #207).
+ # #1524 - a held run is a `continue` by construction (`accept_held` is only
+ # legal on one), so it never reaches this payload: the hold is reported on
+ # the panel and on the `MsprtVerdict` returned by `run_msprt` / `msprt_step`,
+ # and nothing about it belongs here as a key that is always false.
if verdict.decision != "continue":
emit_webhooks(
slack_url,
diff --git a/src/soup_cli/utils/ab_test.py b/src/soup_cli/utils/ab_test.py
index e3e0454a..3bd2dc1d 100644
--- a/src/soup_cli/utils/ab_test.py
+++ b/src/soup_cli/utils/ab_test.py
@@ -37,6 +37,17 @@ effect_size or more ends in `accept_h0` in at most an alpha share of runs,
however often the operator looks, so alpha bounds both wrong verdicts and beta
is retired. Record: benchmarks/gate-1418-ab-cs-accept.md.
+#1419 added a hold on `accept_h0` (see ACCEPT_HOLD_SPREAD_RATIO) which fixes the
+wrong accepts after a saturated start but, because the held-out rows are fixed,
+can leave a run at `continue` for the whole dataset with the confidence sequence
+for the difference already inside (-effect_size, +effect_size). That state is
+reported, not fixed, here (#1524): the verdict carries `accept_held` and the two
+spreads, so the panel can advise dropping or reordering the saturated rows rather
+than collecting more samples that provably cannot help. The accept rule itself is
+unchanged. #1418's confidence sequence covers at its level for any prior scale
+fixed before the tested rows, so it does not need the hold for its guarantee;
+whether the hold stays is #1524's question, and until then it is unchanged.
+
Two known limitations:
1. Single metric per pass — multi-metric correction (Bonferroni / Holm)
is operator-controlled. The CLI accepts one metric at a time.
@@ -200,6 +211,14 @@ class MsprtVerdict:
``direction`` is ``"better"`` or ``"worse"`` (the treatment relative to
control, by the metric's polarity) on a ``reject_h0``, and ``None`` on
``accept_h0`` / ``continue``.
+
+ ``accept_held`` is ``True`` only when ``ACCEPT_HOLD_SPREAD_RATIO`` is what
+ keeps the verdict at ``continue`` (#1524), and then ``held_out_spread`` and
+ ``tested_spread`` carry the two pooled standard deviations the 3x rule
+ compared. Both are ``None`` on every other verdict: there is no hold, so
+ there is nothing to report, and a consumer must not print the note for a
+ run it does not describe. All three are additive, so a verdict from before
+ this change still reads as "not held".
"""
decision: str
@@ -209,6 +228,10 @@ class MsprtVerdict:
mean_control: float
mean_treatment: float
direction: str | None = None
+ accept_held: bool = False
+ held_out_spread: float | None = None
+ tested_spread: float | None = None
+ held_out_rows: int = 0
def __post_init__(self) -> None:
if self.decision not in _VALID_DECISIONS:
@@ -228,6 +251,53 @@ class MsprtVerdict:
f"only a reject_h0 verdict has a direction; got {self.direction!r} "
f"with decision {self.decision!r}"
)
+ if isinstance(self.accept_held, bool) is False:
+ raise TypeError(f"accept_held must be a bool, got {self.accept_held!r}")
+ # #1524 - the hold only ever fires on the accept branch, so a terminal
+ # decision claiming to be held is a caller bug, not a verdict.
+ if self.accept_held and self.decision != "continue":
+ raise ValueError(
+ f"only a continue verdict can be held by the spread rule; got "
+ f"accept_held=True with decision {self.decision!r}"
+ )
+ for name in ("held_out_spread", "tested_spread"):
+ value = getattr(self, name)
+ if value is None:
+ continue
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise TypeError(f"{name} must be a number or None, got {value!r}")
+ if not math.isfinite(value) or value < 0.0:
+ raise ValueError(
+ f"{name} must be a finite spread >= 0, got {value!r}"
+ )
+ if self.accept_held and (self.held_out_spread is None or self.tested_spread is None):
+ missing = [
+ name
+ for name in ("held_out_spread", "tested_spread")
+ if getattr(self, name) is None
+ ]
+ raise ValueError(
+ f"a held verdict must carry both spreads; missing {', '.join(missing)}"
+ )
+ # No hold, no explanation: the spreads only exist to explain one.
+ if not self.accept_held and (
+ self.held_out_spread is not None or self.tested_spread is not None
+ ):
+ raise ValueError(
+ "held_out_spread / tested_spread are only meaningful with "
+ f"accept_held=True; got them with accept_held={self.accept_held!r}"
+ )
+ if isinstance(self.held_out_rows, bool) or not isinstance(self.held_out_rows, int):
+ raise TypeError(f"held_out_rows must be an int, got {self.held_out_rows!r}")
+ if self.held_out_rows < 0:
+ raise ValueError(
+ f"held_out_rows must be >= 0, got {self.held_out_rows}"
+ )
+ if self.accept_held and self.held_out_rows < 1:
+ raise ValueError(
+ "a held verdict must say how many rows were held out; got "
+ f"held_out_rows={self.held_out_rows}"
+ )
def _validate_sample_list(samples: object, *, arm: str) -> list[float]:
@@ -483,6 +553,15 @@ def msprt_step(
``mean_control`` / ``mean_treatment`` and the row counts cover every row;
the statistic and the direction use the rows after the held-out ones.
+
+ A ``continue`` may carry ``accept_held`` (#1524): when the 3x spread rule is
+ what is keeping the accept back, the verdict reports it and names both
+ spreads. That case is reported rather than fixed here — the held-out rows
+ are fixed, so a saturated warm-up is never released by more rows — and the
+ accept rule itself is unchanged. #1418's confidence sequence covers at its
+ level for any prior scale fixed before the tested rows, so it does not need
+ the hold for its guarantee; whether the hold stays is #1524's question, and
+ until then it is unchanged.
"""
ctrl = _validate_sample_list(control, arm="control")
treat = _validate_sample_list(treatment, arm="treatment")
@@ -491,7 +570,16 @@ def msprt_step(
if n_c and n_t:
_require_finite_means(config.metric, ctrl, treat, sum(ctrl) / n_c, sum(treat) / n_t)
- def verdict(llr: float = 0.0, decision: str = "continue", direction: str | None = None):
+ def verdict(
+ llr: float = 0.0,
+ decision: str = "continue",
+ direction: str | None = None,
+ *,
+ accept_held: bool = False,
+ held_out_spread: float | None = None,
+ tested_spread: float | None = None,
+ held_out_rows: int = 0,
+ ):
return MsprtVerdict(
decision=decision,
log_likelihood_ratio=llr,
@@ -500,6 +588,10 @@ def msprt_step(
mean_control=sum(ctrl) / n_c if n_c else 0.0,
mean_treatment=sum(treat) / n_t if n_t else 0.0,
direction=direction,
+ accept_held=accept_held,
+ held_out_spread=held_out_spread,
+ tested_spread=tested_spread,
+ held_out_rows=held_out_rows,
)
held = _held_out_rows(ctrl, treat)
@@ -563,8 +655,22 @@ def msprt_step(
# it stays, is at ACCEPT_HOLD_SPREAD_RATIO. A reject is never held
# back, so the Type-I bound is unchanged.
held_out_sd = config.effect_size / standardised_effect
- if math.sqrt(pooled_variance) > ACCEPT_HOLD_SPREAD_RATIO * held_out_sd:
- return verdict(llr)
+ tested_sd = math.sqrt(pooled_variance)
+ if tested_sd > ACCEPT_HOLD_SPREAD_RATIO * held_out_sd:
+ # #1524 - the held-out rows are fixed, so once the hold fires no
+ # amount of extra data of the same kind releases it: the run stays
+ # at `continue` however many rows arrive, with the confidence
+ # sequence for the difference already inside +-effect_size. Say so
+ # on the verdict, with the two spreads that decided it, so the panel
+ # can advise something the operator can act on instead of "collect
+ # more samples".
+ return verdict(
+ llr,
+ accept_held=True,
+ held_out_spread=held_out_sd,
+ tested_spread=tested_sd,
+ held_out_rows=held,
+ )
return verdict(llr, "accept_h0")
return verdict(llr)
diff --git a/tests/test_issue1524_ab_accept_hold_note.py b/tests/test_issue1524_ab_accept_hold_note.py
new file mode 100644
index 00000000..c1cca0f3
--- /dev/null
+++ b/tests/test_issue1524_ab_accept_hold_note.py
@@ -0,0 +1,517 @@
+"""#1524 — a `continue` held by the 3x rule says so, with the two spreads.
+
+#1419 holds `accept_h0` back at `continue` while the tested rows' pooled
+standard deviation is more than `ACCEPT_HOLD_SPREAD_RATIO` (3) times the
+held-out rows'. That fixed the wrong accepts after a saturated start, and left
+the other side open: the held-out rows are FIXED, so once the hold fires, more
+rows of the same kind never release it. A run that sits there prints "Insufficient
+evidence. Collect more samples and re-run." with the confidence sequence for the
+difference already inside `+-effect_size`, and that advice cannot help — the
+held-out spread does not move.
+
+So the verdict now carries `accept_held` plus the two spreads, and the panel
+prints one line that names the ratio and what to do about it. There is no JSON
+to gain keys in — `soup ab` has none, and a held run sends no webhook (the
+webhook fires only on a terminal decision, and a hold is only legal on a
+`continue`) — so the facts live on the panel and on the `MsprtVerdict`.
+
+The two tests that matter are the pair below. `test_a_held_accept_says_why`
+fails if the hold is removed (it asserts the field AND that the hold is what
+caused it, by monkeypatching the ratio away), and
+`test_an_unheld_continue_carries_no_note` pins the other direction: a `continue`
+that is merely short of evidence must not borrow this explanation.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import json
+import math
+import random
+import re
+
+import pytest
+from typer.testing import CliRunner
+
+runner = CliRunner()
+
+_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
+_BOX_RE = re.compile(f"[{chr(0x2500)}-{chr(0x257F)}|]")
+
+
+def _plain(text: str) -> str:
+ return " ".join(_BOX_RE.sub(" ", _ANSI_RE.sub("", text)).split())
+
+
+def _step(control, treatment, metric="judge_score", **kwargs):
+ from soup_cli.utils.ab_test import MsprtConfig, msprt_step
+
+ return msprt_step(MsprtConfig(metric=metric, **kwargs), control=control, treatment=treatment)
+
+
+def _saturated_warm_up(rows: int = 60, *, seed: int = 0, effect_size: float = 0.1):
+ """The issue's repro shape: the first 5 rows of each arm nearly constant at
+ 1.0 (a saturated judge / warm cache), then ordinary rows drawn from the SAME
+ distribution for both arms, so there is no real difference to find.
+
+ The warm-up spread is tiny but non-zero. Exactly-equal rows would not work:
+ `_held_out_rows` keeps holding out rows while both arms are still constant,
+ so the held-out window would swallow the ordinary rows too and the two
+ spreads would agree. A saturated *judge* returns near-1.0, not bit-equal 1.0.
+ """
+ rng = random.Random(seed)
+ warm = [1.0 + rng.gauss(0.0, 0.002) for _ in range(5)]
+ ordinary = [
+ round(min(1.0, max(0.0, rng.gauss(0.82, 0.05))), 3) for _ in range(rows)
+ ]
+ return warm + ordinary, warm + ordinary
+
+
+# ---------------------------------------------------------------------------
+# The hold names itself
+# ---------------------------------------------------------------------------
+
+
+class TestAcceptHoldNote:
+ """A `continue` held by the 3x rule reports the hold and its two spreads."""
+
+ def test_a_held_accept_says_why(self):
+ """Saturated warm-up: `continue`, `accept_held` true, both spreads real.
+
+ The premise is that the accept boundary is already crossed, so the hold
+ is the only thing keeping this at `continue` — otherwise the new field
+ would be reporting a reason that is not the reason.
+ """
+ from soup_cli.utils.ab_test import PRIOR_SCALE_ROWS
+
+ control, treatment = _saturated_warm_up(40, seed=2)
+
+ verdict = _step(control, treatment)
+
+ assert verdict.decision == "continue", verdict.decision
+ assert verdict.accept_held is True
+ # Both spreads are present, finite, and the tested rows really are the
+ # wider ones — that is the whole content of the note.
+ assert verdict.held_out_spread is not None
+ assert verdict.tested_spread is not None
+ assert math.isfinite(verdict.held_out_spread)
+ assert math.isfinite(verdict.tested_spread)
+ assert verdict.held_out_spread > 0.0
+ assert verdict.tested_spread > 3.0 * verdict.held_out_spread
+ # It names how many rows set the scale, so the panel's advice points at
+ # real rows rather than at the default.
+ assert verdict.held_out_rows == PRIOR_SCALE_ROWS
+
+ def test_a_saturated_start_that_is_bit_equal_reports_the_wider_window(self):
+ """The held-out window grows while both arms are still exactly constant.
+
+ The panel has to name the rows that actually set the scale, which is not
+ always `PRIOR_SCALE_ROWS`: `_held_out_rows` keeps holding rows out while
+ both arms are still bit-equal, so the count is only knowable per run.
+ """
+ rng = random.Random(7)
+ from soup_cli.utils.ab_test import PRIOR_SCALE_ROWS
+
+ control = [1.0] * 7 + [0.999] + [
+ round(rng.gauss(0.82, 0.05), 3) for _ in range(60)
+ ]
+ treatment = [1.0] * 7 + [0.9991] + [
+ round(rng.gauss(0.82, 0.05), 3) for _ in range(60)
+ ]
+
+ verdict = _step(control, treatment)
+
+ assert verdict.decision == "continue", verdict.decision
+ assert verdict.accept_held is True
+ # Wider than PRIOR_SCALE_ROWS: the report must not hardcode the default.
+ assert verdict.held_out_rows == 8
+ assert verdict.held_out_rows != PRIOR_SCALE_ROWS
+ assert verdict.tested_spread > 3.0 * verdict.held_out_spread
+
+ def test_the_note_is_caused_by_the_hold_not_by_the_data(self, monkeypatch):
+ """Remove the hold and the same rows accept: the field tracks the hold.
+
+ Without this the first test would pass on any `continue` that happened to
+ carry the two spreads, which is what a hardcoded note would do.
+ """
+ from soup_cli.utils import ab_test
+
+ control, treatment = _saturated_warm_up(40, seed=2)
+
+ monkeypatch.setattr(ab_test, "ACCEPT_HOLD_SPREAD_RATIO", math.inf)
+ verdict = _step(control, treatment)
+
+ assert verdict.decision == "accept_h0", verdict.decision
+ assert verdict.accept_held is False
+
+ def test_more_rows_of_the_same_kind_do_not_release_it(self):
+ """The reason the note matters: the run stays held as rows arrive.
+
+ The held-out rows are fixed, so the tested spread converges and the ratio
+ only ever grows. A note that advised "collect more samples" would be
+ advising the one thing that provably does not help.
+
+ The invariant is that the hold never *releases* once it has fired, not
+ that it fires on literally every peek: a peek can also sit at `continue`
+ for want of tested rows before the accept branch is reached at all.
+ """
+ control, treatment = _saturated_warm_up(200, seed=2)
+
+ rows = [
+ _step(control[:n], treatment[:n])
+ for n in range(7, len(control) + 1)
+ ]
+ assert all(v.decision == "continue" for v in rows)
+ assert any(v.accept_held for v in rows), "the hold never fired"
+ # From the first held peek on, every later peek is still held.
+ first_held = next(i for i, v in enumerate(rows) if v.accept_held)
+ assert all(v.accept_held for v in rows[first_held:]), [
+ (rows[i].n_control, v.decision, v.accept_held)
+ for i, v in enumerate(rows)
+ if i >= first_held and not v.accept_held
+ ]
+ # Still held with the whole dataset in hand — the issue's "no decision in
+ # 300 rows", here at 200.
+ last = rows[-1]
+ assert last.accept_held is True
+ assert last.tested_spread > 3.0 * last.held_out_spread
+
+ def test_an_unheld_continue_carries_no_note(self):
+ """A `continue` that is merely short of evidence borrows no explanation.
+
+ The control for the false explanation: ordinary Gaussian rows where the
+ held-out and tested spreads agree must not report a hold, and must carry
+ no spreads either, so a consumer reading the field cannot print the note
+ for a run it does not describe.
+ """
+ rng = random.Random(1_524)
+ control = [rng.gauss(0.0, 1.0) for _ in range(30)]
+ treatment = [rng.gauss(0.0, 1.0) for _ in range(30)]
+
+ verdict = _step(control, treatment, effect_size=2.0)
+
+ assert verdict.decision == "accept_h0", verdict.decision
+ assert verdict.accept_held is False
+ assert verdict.held_out_spread is None
+ assert verdict.tested_spread is None
+
+ def test_a_reject_is_never_held(self):
+ """A `reject_h0` clears the boundary above the hold, so it cannot carry one."""
+ rng = random.Random(1_524)
+ control = [rng.gauss(0.0, 1.0) for _ in range(40)]
+ treatment = [rng.gauss(3.0, 1.0) for _ in range(40)]
+
+ verdict = _step(control, treatment, effect_size=0.1)
+
+ assert verdict.decision == "reject_h0", verdict.decision
+ assert verdict.accept_held is False
+ assert verdict.held_out_spread is None
+ assert verdict.held_out_rows == 0
+
+ def test_too_few_tested_rows_is_continue_without_a_note(self):
+ """Still inside the warm-up the verdict has no tested rows to compare."""
+ verdict = _step([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [1.0] * 7)
+
+ assert verdict.decision == "continue"
+ assert verdict.accept_held is False
+
+ def test_the_note_is_the_holds_own_ratio(self, monkeypatch):
+ """A different ratio changes which runs are held, not the note's rule."""
+ from soup_cli.utils import ab_test
+
+ control, treatment = _saturated_warm_up(40, seed=2)
+
+ monkeypatch.setattr(ab_test, "ACCEPT_HOLD_SPREAD_RATIO", 1e9)
+ verdict = _step(control, treatment)
+
+ # Same verdict object shape, hold off: accepts, and says nothing.
+ assert verdict.decision == "accept_h0"
+ assert verdict.accept_held is False
+
+
+# ---------------------------------------------------------------------------
+# The verdict field is validated like the rest
+# ---------------------------------------------------------------------------
+
+
+class TestAcceptHeldValidation:
+ """`accept_held` cannot be set on a decision the hold does not produce."""
+
+ def test_only_continue_can_be_held(self):
+ from soup_cli.utils.ab_test import MsprtVerdict
+
+ for decision in ("accept_h0", "reject_h0"):
+ kwargs = {"direction": "better"} if decision == "reject_h0" else {}
+ with pytest.raises(ValueError, match="continue"):
+ MsprtVerdict(
+ decision=decision,
+ log_likelihood_ratio=0.0,
+ n_control=10,
+ n_treatment=10,
+ mean_control=1.0,
+ mean_treatment=1.0,
+ accept_held=True,
+ **kwargs,
+ )
+
+ def test_a_held_verdict_must_carry_both_spreads(self):
+ """`accept_held` without the numbers behind it would be an unfalsifiable note."""
+ from soup_cli.utils.ab_test import MsprtVerdict
+
+ for missing in ("held_out_spread", "tested_spread"):
+ fields = {"held_out_spread": 0.01, "tested_spread": 0.5}
+ fields[missing] = None
+ with pytest.raises(ValueError, match=missing):
+ MsprtVerdict(
+ decision="continue",
+ log_likelihood_ratio=-2.0,
+ n_control=20,
+ n_treatment=20,
+ mean_control=1.0,
+ mean_treatment=1.0,
+ accept_held=True,
+ **fields,
+ )
+
+ def test_spreads_are_non_negative_and_finite(self):
+ from soup_cli.utils.ab_test import MsprtVerdict
+
+ for bad in (-0.1, math.inf, math.nan):
+ with pytest.raises(ValueError, match="spread"):
+ MsprtVerdict(
+ decision="continue",
+ log_likelihood_ratio=-2.0,
+ n_control=20,
+ n_treatment=20,
+ mean_control=1.0,
+ mean_treatment=1.0,
+ accept_held=True,
+ held_out_spread=0.01,
+ tested_spread=bad,
+ )
+
+ def test_spreads_without_a_hold_are_refused(self):
+ """No hold, no explanation: the two must not float free of each other."""
+ from soup_cli.utils.ab_test import MsprtVerdict
+
+ with pytest.raises(ValueError, match="accept_held"):
+ MsprtVerdict(
+ decision="continue",
+ log_likelihood_ratio=-2.0,
+ n_control=20,
+ n_treatment=20,
+ mean_control=1.0,
+ mean_treatment=1.0,
+ held_out_spread=0.01,
+ tested_spread=0.5,
+ )
+
+ def test_the_verdict_is_still_frozen(self):
+ """The new fields do not cost the verdict its immutability."""
+ from soup_cli.utils.ab_test import MsprtVerdict
+
+ verdict = MsprtVerdict(
+ decision="continue",
+ log_likelihood_ratio=-2.0,
+ n_control=20,
+ n_treatment=20,
+ mean_control=1.0,
+ mean_treatment=1.0,
+ )
+ with pytest.raises(dataclasses.FrozenInstanceError):
+ verdict.accept_held = True # type: ignore[misc]
+
+
+# ---------------------------------------------------------------------------
+# The panel
+# ---------------------------------------------------------------------------
+
+
+def _write_jsonl(path, control, treatment, metric="judge_score"):
+ rows = []
+ for c, t in zip(control, treatment):
+ rows.append(json.dumps({"arm": "control", metric: c}))
+ rows.append(json.dumps({"arm": "treatment", metric: t}))
+ path.write_text("\n".join(rows), encoding="utf-8")
+
+
+def test_the_panel_names_the_hold_and_its_ratio(tmp_path, monkeypatch):
+ """One actionable line: the ratio, and what to do about it."""
+ from soup_cli.cli import app
+ from soup_cli.utils.ab_test import MsprtConfig, run_msprt
+
+ monkeypatch.chdir(tmp_path)
+ control, treatment = _saturated_warm_up(40, seed=2)
+ inp = tmp_path / "ab.jsonl"
+ _write_jsonl(inp, control, treatment)
+ verdict = run_msprt(str(inp), config=MsprtConfig(metric="judge_score"))
+ assert verdict.accept_held is True, verdict # the premise
+
+ result = runner.invoke(app, ["ab", "--input", str(inp), "--metric", "judge_score"])
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+
+ out = _plain(result.output).lower()
+ ratio = verdict.tested_spread / verdict.held_out_spread
+ assert f"held back: the tested rows spread {ratio:.3g} times" in out, out
+ assert (
+ f"(held_out_spread {verdict.held_out_spread:.4g}, "
+ f"tested_spread {verdict.tested_spread:.4g}, limit 3x)"
+ ) in out, out
+ # The three details the note's advice rests on, pinned.
+ assert "already inside +-0.1." in out, out
+ assert "accept_held true" in out, out
+ # Each spread appears exactly twice: once as a table row, once in the panel
+ # prose. A count of 1 means one of the two was dropped.
+ assert out.count(f"held_out_spread {verdict.held_out_spread:.4g}") == 2, out
+ assert out.count(f"tested_spread {verdict.tested_spread:.4g}") == 2, out
+ # It must not ALSO print the advice it replaces.
+ assert "insufficient evidence" not in out, out
+
+
+def test_the_panel_of_an_unheld_continue_is_unchanged(tmp_path, monkeypatch):
+ """The control: an unheld continue past the warm-up still prints the old line."""
+ from soup_cli.cli import app
+ from soup_cli.utils.ab_test import MsprtConfig, run_msprt
+
+ monkeypatch.chdir(tmp_path)
+ rng = random.Random(0)
+ control = [round(rng.gauss(0.80, 0.05), 3) for _ in range(10)]
+ treatment = [round(rng.gauss(0.80, 0.05), 3) for _ in range(10)]
+ inp = tmp_path / "ab.jsonl"
+ _write_jsonl(inp, control, treatment)
+ verdict = run_msprt(str(inp), config=MsprtConfig(metric="judge_score"))
+ # The premise: past the warm-up, undecided, and not held.
+ assert (verdict.decision, verdict.accept_held) == ("continue", False), verdict
+
+ result = runner.invoke(app, ["ab", "--input", str(inp), "--metric", "judge_score"])
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+
+ out = _plain(result.output).lower()
+ assert "insufficient evidence. collect more samples and re-run." in out, out
+ assert "held back" not in out, out
+ assert "accept_held" not in out, out
+
+
+def test_the_panel_names_the_rows_that_actually_set_the_scale(tmp_path, monkeypatch):
+ """A bit-equal warm-up holds out more than ``PRIOR_SCALE_ROWS`` rows.
+
+ ``PRIOR_SCALE_ROWS`` is 5, so a panel that printed the constant would be
+ right on every input but this one. ``_held_out_rows`` keeps holding rows out
+ while both arms are still bit-equal, so the count is only knowable per run
+ and the panel has to name the real one.
+ """
+ from soup_cli.cli import app
+ from soup_cli.utils.ab_test import MsprtConfig, run_msprt
+
+ monkeypatch.chdir(tmp_path)
+ rng = random.Random(7)
+ control = [1.0] * 7 + [0.999] + [round(rng.gauss(0.82, 0.05), 3) for _ in range(60)]
+ treatment = [1.0] * 7 + [0.9991] + [round(rng.gauss(0.82, 0.05), 3) for _ in range(60)]
+ inp = tmp_path / "ab.jsonl"
+ _write_jsonl(inp, control, treatment)
+ verdict = run_msprt(str(inp), config=MsprtConfig(metric="judge_score"))
+ assert verdict.accept_held is True, verdict # the premise
+ assert verdict.held_out_rows != 5, verdict.held_out_rows # the premise
+
+ result = runner.invoke(app, ["ab", "--input", str(inp), "--metric", "judge_score"])
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+
+ out = _plain(result.output).lower()
+ assert f"held_out_rows {verdict.held_out_rows}" in out, out
+ assert f"the first {verdict.held_out_rows} rows of each arm set the scale" in out, out
+
+
+# ---------------------------------------------------------------------------
+# JSON output stays backward compatible
+# ---------------------------------------------------------------------------
+
+
+def test_the_verdict_fields_are_added_not_renamed():
+ """Every field #1265 shipped is still there, and the new ones are additive."""
+ import dataclasses
+
+ from soup_cli.utils.ab_test import MsprtVerdict
+
+ names = {f.name for f in dataclasses.fields(MsprtVerdict)}
+ assert {
+ "decision",
+ "log_likelihood_ratio",
+ "n_control",
+ "n_treatment",
+ "mean_control",
+ "mean_treatment",
+ "direction",
+ } <= names
+ assert {"accept_held", "held_out_spread", "tested_spread", "held_out_rows"} <= names
+
+
+def test_the_webhook_payload_gains_the_keys_without_losing_any(tmp_path, monkeypatch):
+ """The POSTed verdict gains keys; every key #1265 shipped is still there.
+
+ Run through the real command so the test fails if `ab.py` drops or renames a
+ key, rather than only checking a dict the test wrote itself.
+ """
+ from soup_cli.cli import app
+ from soup_cli.commands import ab as ab_cmd
+
+ sent: list[dict] = []
+ monkeypatch.setattr(
+ ab_cmd, "emit_webhooks",
+ lambda slack, discord, *, payload, console: sent.append(payload),
+ )
+
+ monkeypatch.chdir(tmp_path)
+ rng = random.Random(1_524)
+ control = [rng.gauss(0.0, 1.0) for _ in range(40)]
+ treatment = [rng.gauss(3.0, 1.0) for _ in range(40)]
+ inp = tmp_path / "ab.jsonl"
+ _write_jsonl(inp, control, treatment)
+
+ result = runner.invoke(
+ app,
+ [
+ "ab", "--input", str(inp), "--metric", "judge_score",
+ "--slack-url", "https://hooks.slack.com/services/T/B/X",
+ ],
+ )
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ assert len(sent) == 1, sent
+
+ payload = sent[0]
+ # Every key that was there before, unchanged. The four #1524 keys are NOT
+ # here on purpose: a held run is a `continue` and the webhook only fires on
+ # a terminal decision, so they could only ever be false / null.
+ assert set(payload) >= {
+ "command",
+ "metric",
+ "decision",
+ "direction",
+ "log_likelihood_ratio",
+ "n_control",
+ "n_treatment",
+ "mean_control",
+ "mean_treatment",
+ }
+ # Nothing renamed: the old names must not have become aliases.
+ assert not {"spread_ratio", "held", "held_back"} & set(payload)
+ # No hold keys: there is nothing to hold back on a terminal decision.
+ assert not {"accept_held", "held_out_spread", "tested_spread", "held_out_rows"} & set(payload)
+ assert payload["decision"] == "reject_h0"
+ # Still JSON-serialisable end to end.
+ json.dumps(payload)
+
+
+def test_run_msprt_reports_the_hold_from_a_file(tmp_path, monkeypatch):
+ """The JSONL path carries the note too, not just `msprt_step`."""
+ from soup_cli.utils.ab_test import MsprtConfig, run_msprt
+
+ monkeypatch.chdir(tmp_path)
+ control, treatment = _saturated_warm_up(40, seed=2)
+ inp = tmp_path / "ab.jsonl"
+ _write_jsonl(inp, control, treatment)
+
+ verdict = run_msprt(str(inp), config=MsprtConfig(metric="judge_score"))
+
+ assert verdict.decision == "continue"
+ assert verdict.accept_held is True
+ assert verdict.tested_spread > 3.0 * verdict.held_out_spread