passgate 0.1.1__tar.gz
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.
- passgate-0.1.1/LICENSE +21 -0
- passgate-0.1.1/PKG-INFO +112 -0
- passgate-0.1.1/README.md +87 -0
- passgate-0.1.1/pyproject.toml +46 -0
- passgate-0.1.1/setup.cfg +4 -0
- passgate-0.1.1/src/passgate/__init__.py +17 -0
- passgate-0.1.1/src/passgate/__main__.py +6 -0
- passgate-0.1.1/src/passgate/cli.py +149 -0
- passgate-0.1.1/src/passgate/gate.py +174 -0
- passgate-0.1.1/src/passgate/py.typed +0 -0
- passgate-0.1.1/src/passgate/stats.py +79 -0
- passgate-0.1.1/src/passgate.egg-info/PKG-INFO +112 -0
- passgate-0.1.1/src/passgate.egg-info/SOURCES.txt +17 -0
- passgate-0.1.1/src/passgate.egg-info/dependency_links.txt +1 -0
- passgate-0.1.1/src/passgate.egg-info/entry_points.txt +2 -0
- passgate-0.1.1/src/passgate.egg-info/top_level.txt +1 -0
- passgate-0.1.1/tests/test_cli_edge.py +134 -0
- passgate-0.1.1/tests/test_gate.py +97 -0
- passgate-0.1.1/tests/test_stats.py +85 -0
passgate-0.1.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 calasdan-sketch
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
passgate-0.1.1/PKG-INFO
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: passgate
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Statistical pass^N gate: require an eval candidate to clear a Wilson-bound bar on every round, not just on average
|
|
5
|
+
Author: calasdan-sketch
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: evals,llm,reliability,wilson,statistics,gate,regression,ci
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
19
|
+
Classifier: Topic :: Software Development :: Testing
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# passgate
|
|
27
|
+
|
|
28
|
+
**Pass once is luck. Pass^N is a gate.** A statistical reliability gate for LLM evals: a candidate must clear a Wilson-bound pass bar on **every** evaluation round, not just on average — then optionally prove it beats your baseline.
|
|
29
|
+
|
|
30
|
+
Eval flakiness is the quiet killer: a prompt scores 91% once, ships, and regresses. Averaging hides the weak round. `passgate` requires each round's *conservative* pass-rate estimate (the lower bound of the Wilson score interval) to clear your bar, so a candidate that needs 3 good rounds to ship must produce 3 good rounds.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install passgate
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Also runnable as `python -m passgate ...`. Python 3.9+, no dependencies.
|
|
39
|
+
|
|
40
|
+
## The gate
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
passgate gate rounds.json --threshold 0.9 --min-rounds 3
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`rounds.json` (or `.csv`) holds one entry per round:
|
|
47
|
+
|
|
48
|
+
```json
|
|
49
|
+
[
|
|
50
|
+
{ "label": "baseline-eval-set", "trials": 100, "passes": 93 },
|
|
51
|
+
{ "label": "adversarial-set", "trials": 100, "passes": 95 },
|
|
52
|
+
{ "label": "regression-set", "trials": 120, "passes": 116 }
|
|
53
|
+
]
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Output is a per-round scoreboard and a verdict; exit code `1` fails CI:
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
passgate: 2/3 round(s) clear Wilson-lower >= 0.900 (95% confidence, min 3 rounds)
|
|
60
|
+
PASS round 1: 93/100 = 0.930 (lower 0.863)
|
|
61
|
+
FAIL round 2: 70/100 = 0.700 (lower 0.604)
|
|
62
|
+
verdict: FAIL
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Note what the gate does: **93/100 does not certify ≥ 0.9** at 95% confidence with 100 trials — you need more data or a lower bar. That is the point: the bar scales with evidence, not vibes. Add `--json` for machines.
|
|
66
|
+
|
|
67
|
+
## Candidate vs baseline
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
passgate compare --candidate 93/100 --candidate 95/100 \
|
|
71
|
+
--baseline 85/100 --baseline 88/100
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Pooled two-proportion z-test with a one-sided p-value, plus Fisher's exact p (exact hypergeometric enumeration — right for small rounds where the normal approximation lies). Exit `0` only when the improvement is statistically significant at `--alpha` (default 0.05).
|
|
75
|
+
|
|
76
|
+
## Python API
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from passgate import Round, evaluate_rounds, compare
|
|
80
|
+
|
|
81
|
+
result = evaluate_rounds(
|
|
82
|
+
[Round(trials=100, passes=93), Round(trials=100, passes=95)],
|
|
83
|
+
threshold=0.9, confidence=0.95, min_rounds=2,
|
|
84
|
+
)
|
|
85
|
+
assert result.passed, str(result)
|
|
86
|
+
|
|
87
|
+
cmp = compare([Round(100, 93)], [Round(100, 85)])
|
|
88
|
+
print(cmp.verdict) # candidate-better | baseline-better | inconclusive
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## CI
|
|
92
|
+
|
|
93
|
+
```yaml
|
|
94
|
+
- run: pip install passgate
|
|
95
|
+
- run: python run_evals.py --out rounds.json # your eval runner
|
|
96
|
+
- run: passgate gate rounds.json --threshold 0.9 --min-rounds 3
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Notes
|
|
100
|
+
|
|
101
|
+
- Wilson interval (not Wald): behaves correctly near 0% and 100%, where the naive interval explodes.
|
|
102
|
+
- `gate` fails when rounds < `--min-rounds`, so "we only ran it once" cannot pass a 3-round gate.
|
|
103
|
+
- Pure stdlib — no scipy, no pandas.
|
|
104
|
+
- Exit codes: `0` pass, `1` gate failed / improvement not significant, `2` bad input (missing file, bad JSON/CSV, invalid number). Keeps CI from treating a typo as a model regression.
|
|
105
|
+
- Input files may be UTF-8 with or without a BOM, LF or CRLF.
|
|
106
|
+
- The Wilson interval is two-sided, so a 95% interval gives a one-sided 97.5% lower bound per round. Requiring every round to clear the bar is conservative, but passgate does not apply a formal multiple-testing correction.
|
|
107
|
+
- Rounds are treated as independent samples of one pass rate. If rounds reuse the same test items, the real uncertainty is larger than the bound shows.
|
|
108
|
+
- `compare` pools all rounds; it does not model round-to-round variance.
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
MIT. See `LICENSE`.
|
passgate-0.1.1/README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# passgate
|
|
2
|
+
|
|
3
|
+
**Pass once is luck. Pass^N is a gate.** A statistical reliability gate for LLM evals: a candidate must clear a Wilson-bound pass bar on **every** evaluation round, not just on average — then optionally prove it beats your baseline.
|
|
4
|
+
|
|
5
|
+
Eval flakiness is the quiet killer: a prompt scores 91% once, ships, and regresses. Averaging hides the weak round. `passgate` requires each round's *conservative* pass-rate estimate (the lower bound of the Wilson score interval) to clear your bar, so a candidate that needs 3 good rounds to ship must produce 3 good rounds.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install passgate
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Also runnable as `python -m passgate ...`. Python 3.9+, no dependencies.
|
|
14
|
+
|
|
15
|
+
## The gate
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
passgate gate rounds.json --threshold 0.9 --min-rounds 3
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
`rounds.json` (or `.csv`) holds one entry per round:
|
|
22
|
+
|
|
23
|
+
```json
|
|
24
|
+
[
|
|
25
|
+
{ "label": "baseline-eval-set", "trials": 100, "passes": 93 },
|
|
26
|
+
{ "label": "adversarial-set", "trials": 100, "passes": 95 },
|
|
27
|
+
{ "label": "regression-set", "trials": 120, "passes": 116 }
|
|
28
|
+
]
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Output is a per-round scoreboard and a verdict; exit code `1` fails CI:
|
|
32
|
+
|
|
33
|
+
```
|
|
34
|
+
passgate: 2/3 round(s) clear Wilson-lower >= 0.900 (95% confidence, min 3 rounds)
|
|
35
|
+
PASS round 1: 93/100 = 0.930 (lower 0.863)
|
|
36
|
+
FAIL round 2: 70/100 = 0.700 (lower 0.604)
|
|
37
|
+
verdict: FAIL
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Note what the gate does: **93/100 does not certify ≥ 0.9** at 95% confidence with 100 trials — you need more data or a lower bar. That is the point: the bar scales with evidence, not vibes. Add `--json` for machines.
|
|
41
|
+
|
|
42
|
+
## Candidate vs baseline
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
passgate compare --candidate 93/100 --candidate 95/100 \
|
|
46
|
+
--baseline 85/100 --baseline 88/100
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Pooled two-proportion z-test with a one-sided p-value, plus Fisher's exact p (exact hypergeometric enumeration — right for small rounds where the normal approximation lies). Exit `0` only when the improvement is statistically significant at `--alpha` (default 0.05).
|
|
50
|
+
|
|
51
|
+
## Python API
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from passgate import Round, evaluate_rounds, compare
|
|
55
|
+
|
|
56
|
+
result = evaluate_rounds(
|
|
57
|
+
[Round(trials=100, passes=93), Round(trials=100, passes=95)],
|
|
58
|
+
threshold=0.9, confidence=0.95, min_rounds=2,
|
|
59
|
+
)
|
|
60
|
+
assert result.passed, str(result)
|
|
61
|
+
|
|
62
|
+
cmp = compare([Round(100, 93)], [Round(100, 85)])
|
|
63
|
+
print(cmp.verdict) # candidate-better | baseline-better | inconclusive
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## CI
|
|
67
|
+
|
|
68
|
+
```yaml
|
|
69
|
+
- run: pip install passgate
|
|
70
|
+
- run: python run_evals.py --out rounds.json # your eval runner
|
|
71
|
+
- run: passgate gate rounds.json --threshold 0.9 --min-rounds 3
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Notes
|
|
75
|
+
|
|
76
|
+
- Wilson interval (not Wald): behaves correctly near 0% and 100%, where the naive interval explodes.
|
|
77
|
+
- `gate` fails when rounds < `--min-rounds`, so "we only ran it once" cannot pass a 3-round gate.
|
|
78
|
+
- Pure stdlib — no scipy, no pandas.
|
|
79
|
+
- Exit codes: `0` pass, `1` gate failed / improvement not significant, `2` bad input (missing file, bad JSON/CSV, invalid number). Keeps CI from treating a typo as a model regression.
|
|
80
|
+
- Input files may be UTF-8 with or without a BOM, LF or CRLF.
|
|
81
|
+
- The Wilson interval is two-sided, so a 95% interval gives a one-sided 97.5% lower bound per round. Requiring every round to clear the bar is conservative, but passgate does not apply a formal multiple-testing correction.
|
|
82
|
+
- Rounds are treated as independent samples of one pass rate. If rounds reuse the same test items, the real uncertainty is larger than the bound shows.
|
|
83
|
+
- `compare` pools all rounds; it does not model round-to-round variance.
|
|
84
|
+
|
|
85
|
+
## License
|
|
86
|
+
|
|
87
|
+
MIT. See `LICENSE`.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "passgate"
|
|
7
|
+
version = "0.1.1"
|
|
8
|
+
description = "Statistical pass^N gate: require an eval candidate to clear a Wilson-bound bar on every round, not just on average"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "calasdan-sketch" }]
|
|
14
|
+
keywords = ["evals", "llm", "reliability", "wilson", "statistics", "gate", "regression", "ci"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Environment :: Console",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.9",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
"Topic :: Scientific/Engineering :: Information Analysis",
|
|
27
|
+
"Topic :: Software Development :: Testing",
|
|
28
|
+
"Typing :: Typed",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.scripts]
|
|
32
|
+
passgate = "passgate.cli:main"
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.packages.find]
|
|
35
|
+
where = ["src"]
|
|
36
|
+
|
|
37
|
+
[tool.setuptools.package-data]
|
|
38
|
+
passgate = ["py.typed"]
|
|
39
|
+
|
|
40
|
+
[tool.ruff]
|
|
41
|
+
extend-exclude = [".venv-sop", "build", "dist"]
|
|
42
|
+
target-version = "py39"
|
|
43
|
+
|
|
44
|
+
[tool.ruff.lint]
|
|
45
|
+
select = ["E", "F", "I", "B"]
|
|
46
|
+
ignore = ["E501"]
|
passgate-0.1.1/setup.cfg
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""passgate - statistical pass^N reliability gate for evals."""
|
|
2
|
+
|
|
3
|
+
from .gate import GateResult, Round, compare, evaluate_rounds
|
|
4
|
+
from .stats import fisher_exact_2x2, two_proportion_z, wilson_interval, wilson_lower
|
|
5
|
+
|
|
6
|
+
__version__ = "0.1.1"
|
|
7
|
+
__all__ = [
|
|
8
|
+
"Round",
|
|
9
|
+
"GateResult",
|
|
10
|
+
"evaluate_rounds",
|
|
11
|
+
"compare",
|
|
12
|
+
"wilson_lower",
|
|
13
|
+
"wilson_interval",
|
|
14
|
+
"two_proportion_z",
|
|
15
|
+
"fisher_exact_2x2",
|
|
16
|
+
"__version__",
|
|
17
|
+
]
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""passgate CLI: gate eval rounds, or compare a candidate against a baseline.
|
|
2
|
+
|
|
3
|
+
Exit codes: 0 = pass, 1 = gate/comparison did not pass, 2 = bad input or usage.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import csv
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
from typing import Any, List, Optional
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .gate import Round, compare, evaluate_rounds
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class InputError(ValueError):
|
|
18
|
+
"""Bad user input (file, format, or number). Reported with exit code 2."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def parse_ratio(text: str) -> Round:
|
|
22
|
+
"""'93/100' -> Round(trials=100, passes=93)."""
|
|
23
|
+
try:
|
|
24
|
+
passes_s, trials_s = text.split("/", 1)
|
|
25
|
+
return Round(trials=int(trials_s), passes=int(passes_s))
|
|
26
|
+
except (ValueError, AttributeError):
|
|
27
|
+
raise InputError(f"bad round {text!r}, expected PASSES/TRIALS e.g. 93/100") from None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _to_int(value: Any, what: str, where: str) -> int:
|
|
31
|
+
if value is None or isinstance(value, bool):
|
|
32
|
+
raise InputError(f"{where}: missing or invalid {what}")
|
|
33
|
+
try:
|
|
34
|
+
if isinstance(value, float):
|
|
35
|
+
if not value.is_integer():
|
|
36
|
+
raise ValueError
|
|
37
|
+
return int(value)
|
|
38
|
+
return int(str(value).strip())
|
|
39
|
+
except ValueError:
|
|
40
|
+
raise InputError(f"{where}: {what} must be a whole number, got {value!r}") from None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _make_round(trials: Any, passes: Any, label: str, where: str) -> Round:
|
|
44
|
+
t = _to_int(trials, "trials", where)
|
|
45
|
+
p = _to_int(passes, "passes", where)
|
|
46
|
+
try:
|
|
47
|
+
return Round(trials=t, passes=p, label=label)
|
|
48
|
+
except ValueError as e:
|
|
49
|
+
raise InputError(f"{where}: {e}") from None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def load_rounds(path: str) -> List[Round]:
|
|
53
|
+
"""JSON list of {trials, passes} (or [passes, trials] pairs) or CSV (trials,passes[,label]).
|
|
54
|
+
|
|
55
|
+
Files may carry a UTF-8 BOM (common from Windows tools) and CRLF line endings.
|
|
56
|
+
"""
|
|
57
|
+
rounds: List[Round] = []
|
|
58
|
+
try:
|
|
59
|
+
if path.lower().endswith(".csv"):
|
|
60
|
+
with open(path, newline="", encoding="utf-8-sig") as fh:
|
|
61
|
+
for i, row in enumerate(csv.DictReader(fh), start=1):
|
|
62
|
+
row = {(k or "").strip().lower(): v for k, v in row.items()}
|
|
63
|
+
trials = row.get("trials") if row.get("trials") not in (None, "") else row.get("n")
|
|
64
|
+
passes = row.get("passes") if row.get("passes") not in (None, "") else row.get("k")
|
|
65
|
+
rounds.append(
|
|
66
|
+
_make_round(trials, passes, (row.get("label") or "").strip(), f"{path} row {i}")
|
|
67
|
+
)
|
|
68
|
+
return rounds
|
|
69
|
+
with open(path, encoding="utf-8-sig") as fh:
|
|
70
|
+
data = json.load(fh)
|
|
71
|
+
except FileNotFoundError:
|
|
72
|
+
raise InputError(f"rounds file not found: {path}") from None
|
|
73
|
+
except OSError as e:
|
|
74
|
+
raise InputError(f"cannot read {path}: {e.strerror or e}") from None
|
|
75
|
+
except UnicodeDecodeError:
|
|
76
|
+
raise InputError(f"{path} is not valid UTF-8 text") from None
|
|
77
|
+
except json.JSONDecodeError as e:
|
|
78
|
+
raise InputError(f"{path} is not valid JSON: {e}") from None
|
|
79
|
+
if not isinstance(data, list):
|
|
80
|
+
raise InputError(f"{path}: expected a JSON list of rounds")
|
|
81
|
+
for i, item in enumerate(data, start=1):
|
|
82
|
+
where = f"{path} round {i}"
|
|
83
|
+
if isinstance(item, dict):
|
|
84
|
+
rounds.append(
|
|
85
|
+
_make_round(item.get("trials"), item.get("passes"), str(item.get("label", "")), where)
|
|
86
|
+
)
|
|
87
|
+
elif isinstance(item, (list, tuple)) and len(item) == 2:
|
|
88
|
+
rounds.append(_make_round(item[1], item[0], f"round {i}", where))
|
|
89
|
+
else:
|
|
90
|
+
raise InputError(f"{where}: expected {{trials, passes}} or [passes, trials]")
|
|
91
|
+
return rounds
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
95
|
+
ap = argparse.ArgumentParser(
|
|
96
|
+
prog="passgate",
|
|
97
|
+
description="Require an eval candidate to clear a Wilson-bound pass bar on EVERY round.",
|
|
98
|
+
epilog="Exit codes: 0 pass, 1 fail / not significant, 2 bad input.",
|
|
99
|
+
)
|
|
100
|
+
ap.add_argument("--version", action="version", version=f"passgate {__version__}")
|
|
101
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
102
|
+
|
|
103
|
+
g = sub.add_parser("gate", help="pass^N gate over eval rounds; exit 1 if any round is weak")
|
|
104
|
+
g.add_argument("rounds", help="JSON or CSV rounds file")
|
|
105
|
+
g.add_argument("--threshold", type=float, default=0.9, help="required Wilson lower bound (default 0.9)")
|
|
106
|
+
g.add_argument("--confidence", type=float, default=0.95, help="interval confidence (default 0.95)")
|
|
107
|
+
g.add_argument("--min-rounds", type=int, default=1, help="fail if fewer rounds than this")
|
|
108
|
+
g.add_argument("--json", action="store_true", help="machine-readable output")
|
|
109
|
+
|
|
110
|
+
c = sub.add_parser("compare", help="candidate vs baseline: is the candidate actually better?")
|
|
111
|
+
c.add_argument("--candidate", required=True, action="append", help="PASSES/TRIALS (repeatable, one per round)")
|
|
112
|
+
c.add_argument("--baseline", required=True, action="append", help="PASSES/TRIALS (repeatable)")
|
|
113
|
+
c.add_argument("--alpha", type=float, default=0.05)
|
|
114
|
+
c.add_argument("--json", action="store_true", help="machine-readable output")
|
|
115
|
+
return ap
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _emit(text: str) -> None:
|
|
119
|
+
"""Print without ever crashing on a legacy Windows console encoding."""
|
|
120
|
+
try:
|
|
121
|
+
print(text)
|
|
122
|
+
except UnicodeEncodeError:
|
|
123
|
+
enc = getattr(sys.stdout, "encoding", None) or "ascii"
|
|
124
|
+
print(text.encode(enc, errors="replace").decode(enc))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
128
|
+
args = _build_parser().parse_args(argv)
|
|
129
|
+
try:
|
|
130
|
+
if args.cmd == "gate":
|
|
131
|
+
rounds = load_rounds(args.rounds)
|
|
132
|
+
result = evaluate_rounds(
|
|
133
|
+
rounds, threshold=args.threshold, confidence=args.confidence, min_rounds=args.min_rounds
|
|
134
|
+
)
|
|
135
|
+
_emit(json.dumps(result.as_dict(), indent=2) if args.json else str(result))
|
|
136
|
+
return 0 if result.passed else 1
|
|
137
|
+
|
|
138
|
+
cand = [parse_ratio(x) for x in args.candidate]
|
|
139
|
+
base = [parse_ratio(x) for x in args.baseline]
|
|
140
|
+
cmp_ = compare(cand, base, alpha=args.alpha)
|
|
141
|
+
_emit(json.dumps(cmp_.as_dict(), indent=2) if args.json else str(cmp_))
|
|
142
|
+
return 0 if cmp_.verdict == "candidate-better" else 1
|
|
143
|
+
except ValueError as e: # includes InputError and validation errors from the library
|
|
144
|
+
print(f"passgate: {e}", file=sys.stderr)
|
|
145
|
+
return 2
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
if __name__ == "__main__": # pragma: no cover
|
|
149
|
+
sys.exit(main())
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""The pass^N gate and the candidate-vs-baseline comparison."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import math
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any, Dict, List, Sequence
|
|
7
|
+
|
|
8
|
+
from .stats import fisher_exact_2x2, two_proportion_z, wilson_lower, z_for_confidence
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class Round:
|
|
13
|
+
"""One evaluation round: how many trials, how many passed."""
|
|
14
|
+
|
|
15
|
+
trials: int
|
|
16
|
+
passes: int
|
|
17
|
+
label: str = ""
|
|
18
|
+
|
|
19
|
+
def __post_init__(self) -> None:
|
|
20
|
+
if self.trials <= 0:
|
|
21
|
+
raise ValueError("trials must be positive")
|
|
22
|
+
if not 0 <= self.passes <= self.trials:
|
|
23
|
+
raise ValueError(f"passes {self.passes} outside [0, {self.trials}]")
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def rate(self) -> float:
|
|
27
|
+
return self.passes / self.trials
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class RoundEval:
|
|
32
|
+
round: Round
|
|
33
|
+
wilson_lower: float
|
|
34
|
+
meets: bool
|
|
35
|
+
|
|
36
|
+
def as_dict(self) -> Dict[str, Any]:
|
|
37
|
+
return {
|
|
38
|
+
"label": self.round.label,
|
|
39
|
+
"trials": self.round.trials,
|
|
40
|
+
"passes": self.round.passes,
|
|
41
|
+
"rate": round(self.round.rate, 6),
|
|
42
|
+
"wilson_lower": round(self.wilson_lower, 6),
|
|
43
|
+
"meets": self.meets,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class GateResult:
|
|
49
|
+
threshold: float
|
|
50
|
+
confidence: float
|
|
51
|
+
min_rounds: int
|
|
52
|
+
rounds: List[RoundEval] = field(default_factory=list)
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def passed(self) -> bool:
|
|
56
|
+
return (
|
|
57
|
+
len(self.rounds) >= self.min_rounds
|
|
58
|
+
and all(r.meets for r in self.rounds)
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
def __bool__(self) -> bool:
|
|
62
|
+
return self.passed
|
|
63
|
+
|
|
64
|
+
def as_dict(self) -> Dict[str, Any]:
|
|
65
|
+
return {
|
|
66
|
+
"passed": self.passed,
|
|
67
|
+
"threshold": self.threshold,
|
|
68
|
+
"confidence": self.confidence,
|
|
69
|
+
"min_rounds": self.min_rounds,
|
|
70
|
+
"rounds": [r.as_dict() for r in self.rounds],
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
def __str__(self) -> str:
|
|
74
|
+
head = (
|
|
75
|
+
f"passgate: {sum(r.meets for r in self.rounds)}/{len(self.rounds)} round(s) "
|
|
76
|
+
f"clear Wilson-lower >= {self.threshold:.3f} "
|
|
77
|
+
f"({self.confidence:.0%} confidence, min {self.min_rounds} rounds)"
|
|
78
|
+
)
|
|
79
|
+
lines = [
|
|
80
|
+
f" {'PASS' if r.meets else 'FAIL'} "
|
|
81
|
+
f"{(r.round.label or 'round ' + str(i + 1)):>12}: "
|
|
82
|
+
f"{r.round.passes}/{r.round.trials} = {r.round.rate:.3f} "
|
|
83
|
+
f"(lower {r.wilson_lower:.3f})"
|
|
84
|
+
for i, r in enumerate(self.rounds)
|
|
85
|
+
]
|
|
86
|
+
verdict = "PASS" if self.passed else "FAIL"
|
|
87
|
+
return "\n".join([head] + lines + [f"verdict: {verdict}"])
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def evaluate_rounds(
|
|
91
|
+
rounds: Sequence[Round],
|
|
92
|
+
threshold: float = 0.9,
|
|
93
|
+
confidence: float = 0.95,
|
|
94
|
+
min_rounds: int = 1,
|
|
95
|
+
) -> GateResult:
|
|
96
|
+
"""Gate: EVERY round's Wilson lower bound must clear ``threshold``.
|
|
97
|
+
|
|
98
|
+
A flaky candidate that spikes on average but has one weak round fails —
|
|
99
|
+
the "pass^N" property.
|
|
100
|
+
"""
|
|
101
|
+
if not 0.0 < threshold < 1.0:
|
|
102
|
+
raise ValueError("threshold must be between 0 and 1")
|
|
103
|
+
z_for_confidence(confidence) # validates 0.5 < confidence < 1
|
|
104
|
+
if min_rounds < 1:
|
|
105
|
+
raise ValueError("min_rounds must be >= 1")
|
|
106
|
+
result = GateResult(threshold=threshold, confidence=confidence, min_rounds=min_rounds)
|
|
107
|
+
for r in rounds:
|
|
108
|
+
lower = wilson_lower(r.passes, r.trials, confidence)
|
|
109
|
+
result.rounds.append(RoundEval(round=r, wilson_lower=lower, meets=lower >= threshold))
|
|
110
|
+
return result
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass
|
|
114
|
+
class Comparison:
|
|
115
|
+
candidate_rate: float
|
|
116
|
+
baseline_rate: float
|
|
117
|
+
z: float
|
|
118
|
+
p_one_sided: float
|
|
119
|
+
fisher_p: float
|
|
120
|
+
alpha: float
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def better(self) -> bool:
|
|
124
|
+
return self.candidate_rate > self.baseline_rate and self.p_one_sided < self.alpha
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def verdict(self) -> str:
|
|
128
|
+
if self.p_one_sided < self.alpha:
|
|
129
|
+
return "candidate-better" if self.candidate_rate > self.baseline_rate else "baseline-better"
|
|
130
|
+
return "inconclusive"
|
|
131
|
+
|
|
132
|
+
def as_dict(self) -> Dict[str, Any]:
|
|
133
|
+
return {
|
|
134
|
+
"candidate_rate": round(self.candidate_rate, 6),
|
|
135
|
+
"baseline_rate": round(self.baseline_rate, 6),
|
|
136
|
+
"z": round(self.z, 6) if math.isfinite(self.z) else None,
|
|
137
|
+
"p_one_sided": round(self.p_one_sided, 6),
|
|
138
|
+
"fisher_p": round(self.fisher_p, 6),
|
|
139
|
+
"alpha": self.alpha,
|
|
140
|
+
"verdict": self.verdict,
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
def __str__(self) -> str:
|
|
144
|
+
return (
|
|
145
|
+
f"candidate {self.candidate_rate:.3f} vs baseline {self.baseline_rate:.3f} - "
|
|
146
|
+
f"z={self.z:.3f}, one-sided p={self.p_one_sided:.4g}, "
|
|
147
|
+
f"fisher p={self.fisher_p:.4g}, verdict: {self.verdict}"
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def compare(
|
|
152
|
+
candidate: Sequence[Round],
|
|
153
|
+
baseline: Sequence[Round],
|
|
154
|
+
alpha: float = 0.05,
|
|
155
|
+
) -> Comparison:
|
|
156
|
+
"""Compare candidate vs baseline on pooled totals, with Fisher as a check."""
|
|
157
|
+
if not candidate or not baseline:
|
|
158
|
+
raise ValueError("compare needs at least one candidate round and one baseline round")
|
|
159
|
+
if not 0.0 < alpha < 1.0:
|
|
160
|
+
raise ValueError("alpha must be between 0 and 1")
|
|
161
|
+
c1 = sum(r.passes for r in candidate)
|
|
162
|
+
n1 = sum(r.trials for r in candidate)
|
|
163
|
+
c2 = sum(r.passes for r in baseline)
|
|
164
|
+
n2 = sum(r.trials for r in baseline)
|
|
165
|
+
z, p = two_proportion_z(c1, n1, c2, n2)
|
|
166
|
+
fisher = fisher_exact_2x2(c1, n1 - c1, c2, n2 - c2)
|
|
167
|
+
return Comparison(
|
|
168
|
+
candidate_rate=c1 / n1,
|
|
169
|
+
baseline_rate=c2 / n2,
|
|
170
|
+
z=z,
|
|
171
|
+
p_one_sided=p,
|
|
172
|
+
fisher_p=fisher,
|
|
173
|
+
alpha=alpha,
|
|
174
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Small, dependency-free statistics used by the gate.
|
|
2
|
+
|
|
3
|
+
All bounds are exact closed forms; ``z`` comes from the standard normal
|
|
4
|
+
quantile (``statistics.NormalDist``), so results match any reference
|
|
5
|
+
implementation to floating-point precision.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
from statistics import NormalDist
|
|
11
|
+
from typing import Tuple
|
|
12
|
+
|
|
13
|
+
_NORMAL = NormalDist()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def z_for_confidence(confidence: float) -> float:
|
|
17
|
+
if not 0.5 < confidence < 1.0:
|
|
18
|
+
raise ValueError("confidence must be between 0.5 and 1.0")
|
|
19
|
+
return _NORMAL.inv_cdf(0.5 + confidence / 2.0)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def wilson_interval(passes: int, trials: int, confidence: float = 0.95) -> Tuple[float, float]:
|
|
23
|
+
"""Two-sided Wilson score interval for a binomial proportion."""
|
|
24
|
+
if trials <= 0:
|
|
25
|
+
raise ValueError("trials must be positive")
|
|
26
|
+
if not 0 <= passes <= trials:
|
|
27
|
+
raise ValueError("passes must be within [0, trials]")
|
|
28
|
+
z = z_for_confidence(confidence)
|
|
29
|
+
phat = passes / trials
|
|
30
|
+
denom = 1.0 + z * z / trials
|
|
31
|
+
center = (phat + z * z / (2 * trials)) / denom
|
|
32
|
+
half = (z * math.sqrt((phat * (1 - phat) + z * z / (4 * trials)) / trials)) / denom
|
|
33
|
+
return max(0.0, center - half), min(1.0, center + half)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def wilson_lower(passes: int, trials: int, confidence: float = 0.95) -> float:
|
|
37
|
+
"""Lower bound of the Wilson interval — the conservative pass-rate estimate."""
|
|
38
|
+
return wilson_interval(passes, trials, confidence)[0]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def two_proportion_z(c1: int, n1: int, c2: int, n2: int) -> Tuple[float, float]:
|
|
42
|
+
"""Pooled two-proportion z-test: candidate (c1/n1) vs baseline (c2/n2).
|
|
43
|
+
|
|
44
|
+
Returns (z, one_sided_p). Positive z means the candidate is better.
|
|
45
|
+
"""
|
|
46
|
+
if n1 <= 0 or n2 <= 0:
|
|
47
|
+
raise ValueError("sample sizes must be positive")
|
|
48
|
+
if not (0 <= c1 <= n1 and 0 <= c2 <= n2):
|
|
49
|
+
raise ValueError("passes must be within [0, trials]")
|
|
50
|
+
p1, p2 = c1 / n1, c2 / n2
|
|
51
|
+
pooled = (c1 + c2) / (n1 + n2)
|
|
52
|
+
se = math.sqrt(pooled * (1 - pooled) * (1 / n1 + 1 / n2))
|
|
53
|
+
if se == 0.0:
|
|
54
|
+
return (0.0, 1.0) if p1 == p2 else (math.inf if p1 > p2 else -math.inf, 0.0)
|
|
55
|
+
z = (p1 - p2) / se
|
|
56
|
+
return z, _NORMAL.cdf(-z)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def fisher_exact_2x2(a: int, b: int, c: int, d: int) -> float:
|
|
60
|
+
"""Two-sided Fisher's exact p-value for [[a, b], [c, d]].
|
|
61
|
+
|
|
62
|
+
Exact hypergeometric enumeration — right for small eval rounds where the
|
|
63
|
+
normal approximation lies.
|
|
64
|
+
"""
|
|
65
|
+
for v in (a, b, c, d):
|
|
66
|
+
if v < 0:
|
|
67
|
+
raise ValueError("counts must be non-negative")
|
|
68
|
+
n = a + b + c + d
|
|
69
|
+
if n == 0:
|
|
70
|
+
raise ValueError("table is empty")
|
|
71
|
+
row1, col1 = a + b, a + c
|
|
72
|
+
|
|
73
|
+
def prob(x: int) -> float:
|
|
74
|
+
return math.comb(col1, x) * math.comb(n - col1, row1 - x) / math.comb(n, row1)
|
|
75
|
+
|
|
76
|
+
lo = max(0, row1 + col1 - n)
|
|
77
|
+
hi = min(row1, col1)
|
|
78
|
+
observed = prob(a)
|
|
79
|
+
return min(1.0, sum(prob(x) for x in range(lo, hi + 1) if prob(x) <= observed + 1e-12))
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: passgate
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Statistical pass^N gate: require an eval candidate to clear a Wilson-bound bar on every round, not just on average
|
|
5
|
+
Author: calasdan-sketch
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: evals,llm,reliability,wilson,statistics,gate,regression,ci
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
19
|
+
Classifier: Topic :: Software Development :: Testing
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# passgate
|
|
27
|
+
|
|
28
|
+
**Pass once is luck. Pass^N is a gate.** A statistical reliability gate for LLM evals: a candidate must clear a Wilson-bound pass bar on **every** evaluation round, not just on average — then optionally prove it beats your baseline.
|
|
29
|
+
|
|
30
|
+
Eval flakiness is the quiet killer: a prompt scores 91% once, ships, and regresses. Averaging hides the weak round. `passgate` requires each round's *conservative* pass-rate estimate (the lower bound of the Wilson score interval) to clear your bar, so a candidate that needs 3 good rounds to ship must produce 3 good rounds.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install passgate
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Also runnable as `python -m passgate ...`. Python 3.9+, no dependencies.
|
|
39
|
+
|
|
40
|
+
## The gate
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
passgate gate rounds.json --threshold 0.9 --min-rounds 3
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`rounds.json` (or `.csv`) holds one entry per round:
|
|
47
|
+
|
|
48
|
+
```json
|
|
49
|
+
[
|
|
50
|
+
{ "label": "baseline-eval-set", "trials": 100, "passes": 93 },
|
|
51
|
+
{ "label": "adversarial-set", "trials": 100, "passes": 95 },
|
|
52
|
+
{ "label": "regression-set", "trials": 120, "passes": 116 }
|
|
53
|
+
]
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Output is a per-round scoreboard and a verdict; exit code `1` fails CI:
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
passgate: 2/3 round(s) clear Wilson-lower >= 0.900 (95% confidence, min 3 rounds)
|
|
60
|
+
PASS round 1: 93/100 = 0.930 (lower 0.863)
|
|
61
|
+
FAIL round 2: 70/100 = 0.700 (lower 0.604)
|
|
62
|
+
verdict: FAIL
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Note what the gate does: **93/100 does not certify ≥ 0.9** at 95% confidence with 100 trials — you need more data or a lower bar. That is the point: the bar scales with evidence, not vibes. Add `--json` for machines.
|
|
66
|
+
|
|
67
|
+
## Candidate vs baseline
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
passgate compare --candidate 93/100 --candidate 95/100 \
|
|
71
|
+
--baseline 85/100 --baseline 88/100
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Pooled two-proportion z-test with a one-sided p-value, plus Fisher's exact p (exact hypergeometric enumeration — right for small rounds where the normal approximation lies). Exit `0` only when the improvement is statistically significant at `--alpha` (default 0.05).
|
|
75
|
+
|
|
76
|
+
## Python API
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from passgate import Round, evaluate_rounds, compare
|
|
80
|
+
|
|
81
|
+
result = evaluate_rounds(
|
|
82
|
+
[Round(trials=100, passes=93), Round(trials=100, passes=95)],
|
|
83
|
+
threshold=0.9, confidence=0.95, min_rounds=2,
|
|
84
|
+
)
|
|
85
|
+
assert result.passed, str(result)
|
|
86
|
+
|
|
87
|
+
cmp = compare([Round(100, 93)], [Round(100, 85)])
|
|
88
|
+
print(cmp.verdict) # candidate-better | baseline-better | inconclusive
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## CI
|
|
92
|
+
|
|
93
|
+
```yaml
|
|
94
|
+
- run: pip install passgate
|
|
95
|
+
- run: python run_evals.py --out rounds.json # your eval runner
|
|
96
|
+
- run: passgate gate rounds.json --threshold 0.9 --min-rounds 3
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Notes
|
|
100
|
+
|
|
101
|
+
- Wilson interval (not Wald): behaves correctly near 0% and 100%, where the naive interval explodes.
|
|
102
|
+
- `gate` fails when rounds < `--min-rounds`, so "we only ran it once" cannot pass a 3-round gate.
|
|
103
|
+
- Pure stdlib — no scipy, no pandas.
|
|
104
|
+
- Exit codes: `0` pass, `1` gate failed / improvement not significant, `2` bad input (missing file, bad JSON/CSV, invalid number). Keeps CI from treating a typo as a model regression.
|
|
105
|
+
- Input files may be UTF-8 with or without a BOM, LF or CRLF.
|
|
106
|
+
- The Wilson interval is two-sided, so a 95% interval gives a one-sided 97.5% lower bound per round. Requiring every round to clear the bar is conservative, but passgate does not apply a formal multiple-testing correction.
|
|
107
|
+
- Rounds are treated as independent samples of one pass rate. If rounds reuse the same test items, the real uncertainty is larger than the bound shows.
|
|
108
|
+
- `compare` pools all rounds; it does not model round-to-round variance.
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
MIT. See `LICENSE`.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/passgate/__init__.py
|
|
5
|
+
src/passgate/__main__.py
|
|
6
|
+
src/passgate/cli.py
|
|
7
|
+
src/passgate/gate.py
|
|
8
|
+
src/passgate/py.typed
|
|
9
|
+
src/passgate/stats.py
|
|
10
|
+
src/passgate.egg-info/PKG-INFO
|
|
11
|
+
src/passgate.egg-info/SOURCES.txt
|
|
12
|
+
src/passgate.egg-info/dependency_links.txt
|
|
13
|
+
src/passgate.egg-info/entry_points.txt
|
|
14
|
+
src/passgate.egg-info/top_level.txt
|
|
15
|
+
tests/test_cli_edge.py
|
|
16
|
+
tests/test_gate.py
|
|
17
|
+
tests/test_stats.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
passgate
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Edge cases found in the SOP review: exit codes, BOM/CRLF, bad input, API validation."""
|
|
2
|
+
import json
|
|
3
|
+
import subprocess
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from passgate import Round, compare, evaluate_rounds
|
|
9
|
+
from passgate.cli import load_rounds, main
|
|
10
|
+
from passgate.stats import fisher_exact_2x2, two_proportion_z
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_bad_ratio_exits_2_not_1(capsys):
|
|
14
|
+
# exit 1 means "gate failed" in CI; bad input must be distinguishable
|
|
15
|
+
assert main(["compare", "--candidate", "oops", "--baseline", "5/10"]) == 2
|
|
16
|
+
assert "bad round" in capsys.readouterr().err
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_missing_file_exits_2(capsys):
|
|
20
|
+
assert main(["gate", "no-such-file.json"]) == 2
|
|
21
|
+
assert "not found" in capsys.readouterr().err
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_invalid_json_exits_2(tmp_path, capsys):
|
|
25
|
+
f = tmp_path / "r.json"
|
|
26
|
+
f.write_text("{not json", encoding="utf-8")
|
|
27
|
+
assert main(["gate", str(f)]) == 2
|
|
28
|
+
assert "not valid JSON" in capsys.readouterr().err
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_json_not_a_list(tmp_path):
|
|
32
|
+
f = tmp_path / "r.json"
|
|
33
|
+
f.write_text('{"trials": 10, "passes": 9}', encoding="utf-8")
|
|
34
|
+
assert main(["gate", str(f)]) == 2
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_missing_keys_exit_2(tmp_path, capsys):
|
|
38
|
+
f = tmp_path / "r.json"
|
|
39
|
+
f.write_text('[{"trials": 10}]', encoding="utf-8")
|
|
40
|
+
assert main(["gate", str(f)]) == 2
|
|
41
|
+
assert "passes" in capsys.readouterr().err
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_passes_over_trials_exit_2(tmp_path):
|
|
45
|
+
f = tmp_path / "r.json"
|
|
46
|
+
f.write_text("[[11, 10]]", encoding="utf-8")
|
|
47
|
+
assert main(["gate", str(f)]) == 2
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_bom_and_crlf_csv(tmp_path):
|
|
51
|
+
f = tmp_path / "r.csv"
|
|
52
|
+
f.write_bytes(b"\xef\xbb\xbftrials,passes,label\r\n100,99,a\r\n100,98,b\r\n")
|
|
53
|
+
rounds = load_rounds(str(f))
|
|
54
|
+
assert [r.label for r in rounds] == ["a", "b"] and rounds[0].passes == 99
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_bom_json(tmp_path):
|
|
58
|
+
f = tmp_path / "r.json"
|
|
59
|
+
f.write_bytes(b"\xef\xbb\xbf" + json.dumps([[9, 10]]).encode())
|
|
60
|
+
assert load_rounds(str(f))[0].trials == 10
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_csv_alt_columns_n_k(tmp_path):
|
|
64
|
+
f = tmp_path / "r.csv"
|
|
65
|
+
f.write_text("n,k\n50,49\n", encoding="utf-8")
|
|
66
|
+
r = load_rounds(str(f))[0]
|
|
67
|
+
assert (r.trials, r.passes) == (50, 49)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_csv_missing_column_exit_2(tmp_path):
|
|
71
|
+
f = tmp_path / "r.csv"
|
|
72
|
+
f.write_text("trials\n50\n", encoding="utf-8")
|
|
73
|
+
assert main(["gate", str(f)]) == 2
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_bad_threshold_exit_2(tmp_path, capsys):
|
|
77
|
+
f = tmp_path / "r.json"
|
|
78
|
+
f.write_text("[[9, 10]]", encoding="utf-8")
|
|
79
|
+
assert main(["gate", str(f), "--threshold", "1.5"]) == 2
|
|
80
|
+
assert main(["gate", str(f), "--confidence", "2"]) == 2
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_bad_alpha_exit_2():
|
|
84
|
+
assert main(["compare", "--candidate", "9/10", "--baseline", "5/10", "--alpha", "0"]) == 2
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_empty_rounds_file_fails_gate(tmp_path):
|
|
88
|
+
f = tmp_path / "r.json"
|
|
89
|
+
f.write_text("[]", encoding="utf-8")
|
|
90
|
+
assert main(["gate", str(f)]) == 1 # zero rounds can never satisfy min_rounds
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_compare_json_is_valid_json_when_infinite(capsys):
|
|
94
|
+
# zero-variance case used to emit the non-standard token Infinity
|
|
95
|
+
assert main(["compare", "--candidate", "10/10", "--baseline", "0/10", "--json"]) == 0
|
|
96
|
+
out = capsys.readouterr().out
|
|
97
|
+
json.loads(out, parse_constant=lambda c: pytest.fail(f"non-standard JSON constant {c}"))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_compare_empty_inputs_raise():
|
|
101
|
+
with pytest.raises(ValueError):
|
|
102
|
+
compare([], [Round(5, 10)])
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_evaluate_rounds_validates_confidence():
|
|
106
|
+
with pytest.raises(ValueError):
|
|
107
|
+
evaluate_rounds([], confidence=1.5)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def test_p_value_precise_for_large_z():
|
|
111
|
+
_, p = two_proportion_z(1000, 1000, 500, 1000)
|
|
112
|
+
assert 0.0 <= p < 1e-100 # 1 - cdf(z) would have rounded to exactly 0.0 or lost precision
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_fisher_empty_table():
|
|
116
|
+
with pytest.raises(ValueError):
|
|
117
|
+
fisher_exact_2x2(0, 0, 0, 0)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_output_is_ascii_safe():
|
|
121
|
+
r = evaluate_rounds([Round(100, 93)], threshold=0.5)
|
|
122
|
+
assert str(r).isascii()
|
|
123
|
+
c = compare([Round(100, 93)], [Round(100, 85)])
|
|
124
|
+
assert str(c).isascii()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def test_python_dash_m_entry():
|
|
128
|
+
proc = subprocess.run(
|
|
129
|
+
[sys.executable, "-m", "passgate", "compare", "--candidate", "93/100", "--baseline", "85/100"],
|
|
130
|
+
capture_output=True,
|
|
131
|
+
text=True,
|
|
132
|
+
check=False,
|
|
133
|
+
)
|
|
134
|
+
assert proc.returncode == 0 and "candidate-better" in proc.stdout
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Gate logic and CLI tests."""
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from passgate import Round, compare, evaluate_rounds
|
|
7
|
+
from passgate.cli import main
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def rounds(*ratios, label=""):
|
|
11
|
+
return [Round(passes=k, trials=n, label=f"{label}{i+1}") for i, (k, n) in enumerate(ratios)]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_strong_candidate_passes():
|
|
15
|
+
# wilson_lower(93, 100, 0.95) ~= 0.863 -> clears 0.85 on every round
|
|
16
|
+
result = evaluate_rounds(rounds((93, 100), (95, 100), (92, 100)), threshold=0.85)
|
|
17
|
+
assert result.passed, str(result)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_flaky_candidate_fails_even_with_high_average():
|
|
21
|
+
# average pass rate 89%, but one weak round kills the run — the pass^N property
|
|
22
|
+
result = evaluate_rounds(rounds((99, 100), (99, 100), (70, 100)), threshold=0.85)
|
|
23
|
+
assert not result.passed
|
|
24
|
+
assert not result.rounds[2].meets
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_threshold_too_high_for_sample_size():
|
|
28
|
+
# 93/100 is genuinely good but 100 trials cannot certify >= 0.9 at 95%
|
|
29
|
+
assert not evaluate_rounds(rounds((93, 100)), threshold=0.9).passed
|
|
30
|
+
# ... while 1000 trials with the same rate can
|
|
31
|
+
assert evaluate_rounds(rounds((930, 1000)), threshold=0.9).passed
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_min_rounds_enforced():
|
|
35
|
+
result = evaluate_rounds(rounds((95, 100)), threshold=0.85, min_rounds=3)
|
|
36
|
+
assert not result.passed
|
|
37
|
+
assert "min 3" in str(result)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_round_validation():
|
|
41
|
+
with pytest.raises(ValueError):
|
|
42
|
+
Round(trials=0, passes=0)
|
|
43
|
+
with pytest.raises(ValueError):
|
|
44
|
+
Round(trials=10, passes=11)
|
|
45
|
+
with pytest.raises(ValueError):
|
|
46
|
+
evaluate_rounds([], threshold=1.5)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_report_str_and_dict():
|
|
50
|
+
result = evaluate_rounds(rounds((99, 100), (70, 100), label="r"), threshold=0.85)
|
|
51
|
+
text = str(result)
|
|
52
|
+
assert "verdict: FAIL" in text and "r2" in text
|
|
53
|
+
data = result.as_dict()
|
|
54
|
+
assert data["passed"] is False and len(data["rounds"]) == 2
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_compare_candidate_better():
|
|
58
|
+
cmp_ = compare(rounds((93, 100)), rounds((85, 100)), alpha=0.05)
|
|
59
|
+
assert cmp_.verdict == "candidate-better"
|
|
60
|
+
assert cmp_.better and cmp_.p_one_sided < 0.05
|
|
61
|
+
assert 0.0 < cmp_.fisher_p < 0.2 # exact test is stricter than the z-test
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_compare_inconclusive_on_tiny_samples():
|
|
65
|
+
cmp_ = compare(rounds((3, 3)), rounds((2, 3)), alpha=0.05)
|
|
66
|
+
assert cmp_.verdict == "inconclusive"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_cli_gate_json_pass(tmp_path, capsys):
|
|
70
|
+
f = tmp_path / "rounds.json"
|
|
71
|
+
f.write_text(json.dumps([{"trials": 100, "passes": 93}] * 3), encoding="utf-8")
|
|
72
|
+
code = main(["gate", str(f), "--threshold", "0.85", "--json"])
|
|
73
|
+
out = json.loads(capsys.readouterr().out)
|
|
74
|
+
assert code == 0 and out["passed"] is True
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_cli_gate_csv_fail(tmp_path, capsys):
|
|
78
|
+
f = tmp_path / "rounds.csv"
|
|
79
|
+
f.write_text("trials,passes\n100,70\n100,99\n", encoding="utf-8")
|
|
80
|
+
assert main(["gate", str(f), "--threshold", "0.85"]) == 1
|
|
81
|
+
assert "verdict: FAIL" in capsys.readouterr().out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_cli_pairs_format(tmp_path, capsys):
|
|
85
|
+
f = tmp_path / "rounds.json"
|
|
86
|
+
f.write_text(json.dumps([[99, 100], [98, 100]]), encoding="utf-8")
|
|
87
|
+
assert main(["gate", str(f), "--threshold", "0.9", "--min-rounds", "2"]) == 0
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def test_cli_compare(capsys):
|
|
91
|
+
code = main(["compare", "--candidate", "93/100", "--baseline", "85/100"])
|
|
92
|
+
assert code == 0
|
|
93
|
+
assert "candidate-better" in capsys.readouterr().out
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def test_cli_missing_file(capsys):
|
|
97
|
+
assert main(['gate', 'no-such-file.json']) == 2
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Statistics tests — references are derived, not remembered."""
|
|
2
|
+
import math
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from passgate.stats import (
|
|
7
|
+
fisher_exact_2x2,
|
|
8
|
+
two_proportion_z,
|
|
9
|
+
wilson_interval,
|
|
10
|
+
wilson_lower,
|
|
11
|
+
z_for_confidence,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_wilson_perfect_score_exact_form():
|
|
16
|
+
# for p_hat == 1 the Wilson lower bound collapses to 1 / (1 + z^2/n)
|
|
17
|
+
z = z_for_confidence(0.95)
|
|
18
|
+
assert wilson_lower(100, 100, 0.95) == pytest.approx(1.0 / (1.0 + z * z / 100), abs=1e-12)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_wilson_zero_score_symmetric():
|
|
22
|
+
z = z_for_confidence(0.95)
|
|
23
|
+
lo, hi = wilson_interval(0, 100, 0.95)
|
|
24
|
+
assert lo == pytest.approx(0.0, abs=1e-12)
|
|
25
|
+
assert hi == pytest.approx(1.0 - 1.0 / (1.0 + z * z / 100), abs=1e-12)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_wilson_bounds_bracket_the_rate():
|
|
29
|
+
lo, hi = wilson_interval(93, 100, 0.95)
|
|
30
|
+
assert 0.0 <= lo <= 0.93 <= hi <= 1.0
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_wilson_monotone_in_passes():
|
|
34
|
+
lowers = [wilson_lower(p, 100, 0.95) for p in range(0, 101)]
|
|
35
|
+
assert lowers == sorted(lowers)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_wilson_tighter_with_more_data():
|
|
39
|
+
# same observed rate, larger sample -> higher lower bound
|
|
40
|
+
assert wilson_lower(90, 100, 0.95) < wilson_lower(900, 1000, 0.95)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_wilson_input_validation():
|
|
44
|
+
with pytest.raises(ValueError):
|
|
45
|
+
wilson_lower(5, 0)
|
|
46
|
+
with pytest.raises(ValueError):
|
|
47
|
+
wilson_lower(11, 10)
|
|
48
|
+
with pytest.raises(ValueError):
|
|
49
|
+
z_for_confidence(0.4)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_two_proportion_z_direction_and_magnitude():
|
|
53
|
+
# derived: pooled p = 178/200 = 0.89, se = sqrt(0.89*0.11*0.02),
|
|
54
|
+
# z = (0.93 - 0.85) / se
|
|
55
|
+
se = math.sqrt(0.89 * 0.11 * (1 / 100 + 1 / 100))
|
|
56
|
+
z, p = two_proportion_z(93, 100, 85, 100)
|
|
57
|
+
assert z == pytest.approx(0.08 / se, rel=1e-9)
|
|
58
|
+
assert 0.03 < p < 0.04
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_two_proportion_z_degenerate():
|
|
62
|
+
z, p = two_proportion_z(50, 100, 50, 100)
|
|
63
|
+
assert z == 0.0 and p == 0.5 # one-sided p at z=0 is 0.5
|
|
64
|
+
z, p = two_proportion_z(60, 100, 40, 100)
|
|
65
|
+
assert z > 0 and p < 0.01
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_fisher_perfect_separation():
|
|
69
|
+
# [[10,0],[0,10]]: only x=0 and x=10 are as extreme, each 1/C(20,10)
|
|
70
|
+
expected = 2 / math.comb(20, 10)
|
|
71
|
+
assert fisher_exact_2x2(10, 0, 0, 10) == pytest.approx(expected, rel=1e-9)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_fisher_identical_groups_not_significant():
|
|
75
|
+
p = fisher_exact_2x2(8, 2, 8, 2)
|
|
76
|
+
assert p > 0.5
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_fisher_symmetry():
|
|
80
|
+
assert fisher_exact_2x2(1, 9, 11, 1) == pytest.approx(fisher_exact_2x2(11, 1, 1, 9), rel=1e-12)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_fisher_validation():
|
|
84
|
+
with pytest.raises(ValueError):
|
|
85
|
+
fisher_exact_2x2(-1, 2, 3, 4)
|