Tests-first oracle written by SDET before series_eval.py (STRA-290) and component_class.py (STRA-313): gen_exact.py (stdlib, independent: Fractions, Decimal, integrated Student-t CDF cross-checked to published tables, Pocock levels checked by numerical integration), series_cases.json (35 cases), component_cases.json (27 component and AC5 cases), and the unittest scripts/e2e/evidence/test_series_eval_golden.py. With the evaluators absent every case fails with '<tool> not found'. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
271 lines
13 KiB
Python
271 lines
13 KiB
Python
"""Golden-vector tests for the series evaluator (STRA-290) and the component classifier (STRA-313). Leaf STRA-310, role SDET.
|
|
|
|
Run from the repository root: python -m unittest scripts.e2e.evidence.test_series_eval_golden -v
|
|
Stdlib only, Python >= 3.9. The expected values are in golden/series_cases.json and golden/component_cases.json and were computed by
|
|
golden/gen_exact.py, which shares no code with the code under test (E8). These tests are written BEFORE series_eval.py and component_class.py
|
|
exist: while a tool is missing every case fails with '<tool> not found' (a failure raised with self.fail, never an error of this file).
|
|
|
|
The tests run the tools through their command line (INTERFACE v1):
|
|
|
|
series_eval.py <series.json> [--look K] [--blind-sd] [--simulate-null --runs R --seed S] (STRA-290)
|
|
stdout JSON {"metrics": {metric: {row: {"n","mean_l","ci_lo","ci_hi","r1","n_eff","mde","verdict"}}}, "series_verdict": ..., "looks": [...]}
|
|
exit 0 result produced, 2 REFUSED (mixed build or cache state; the message names the field), 3 malformed input
|
|
component_class.py cell <cell.json> [--confirm <confirm_cell.json>] / component_class.py ac5 <alt.json> (STRA-313)
|
|
stdout JSON, exit 0 result produced, 3 malformed input
|
|
|
|
Points the STRA-290 / STRA-313 bodies left open and that these golden vectors FIX (the author of the evaluators follows them; see the module
|
|
docstring of golden/gen_exact.py for the formulas): the series pair object may carry ours_build_id and cache_state (mixed values are REFUSED);
|
|
lag-1 autocorrelation is the standard acf estimator; with r1 > 0 the CI is mean +- t(dof) sd / sqrt(n_eff) with dof = max(1, floor(n_eff - 1));
|
|
thresholds are compared with an absolute tolerance of 1e-12 (so an sd = 0 bound exactly on 0 or ln 0.99 counts as ON the threshold);
|
|
--look K evaluates the interim SLOWER test at level 0.0221 on the valid pairs present (12 pairs for K = 1, 24 for K = 2 with N = 30);
|
|
the `ac5` input is {"cell_id", "N", "pairs": [{"d": default value, "a": alternative value}]} with l = ln(d / a); an `ac5` SLOWER exit reports
|
|
n and mean_l of the pairs seen so far and `look` as the 1-based index of the Pocock look (6, 12, 18, 24, 30 pairs).
|
|
"""
|
|
import json
|
|
import math
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
REPO = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
|
|
GOLDEN = os.path.join(HERE, "golden")
|
|
SERIES_EVAL = os.path.join(HERE, "series_eval.py")
|
|
COMPONENT_CLASS = os.path.join(HERE, "component_class.py")
|
|
GEN_EXACT = os.path.join(GOLDEN, "gen_exact.py")
|
|
TIMEOUT = 120
|
|
TIMEOUT_SIMULATION = 1200
|
|
|
|
LOAD_ERRORS = []
|
|
|
|
|
|
def _load(name):
|
|
try:
|
|
with open(os.path.join(GOLDEN, name), "r", encoding="utf-8") as handle:
|
|
return json.load(handle)
|
|
except (OSError, ValueError) as exc:
|
|
LOAD_ERRORS.append("%s: %s" % (name, exc))
|
|
return {"tolerances": {}, "cases": []}
|
|
|
|
|
|
SERIES_DOC = _load("series_cases.json")
|
|
COMPONENT_DOC = _load("component_cases.json")
|
|
TOL = dict(SERIES_DOC.get("tolerances") or {})
|
|
TOL.update(COMPONENT_DOC.get("tolerances") or {})
|
|
|
|
|
|
def numeric_leaves(obj):
|
|
if isinstance(obj, bool):
|
|
return
|
|
if isinstance(obj, (int, float)):
|
|
yield float(obj)
|
|
elif isinstance(obj, dict):
|
|
for value in obj.values():
|
|
for leaf in numeric_leaves(value):
|
|
yield leaf
|
|
elif isinstance(obj, list):
|
|
for value in obj:
|
|
for leaf in numeric_leaves(value):
|
|
yield leaf
|
|
|
|
|
|
def all_keys(obj):
|
|
if isinstance(obj, dict):
|
|
for key, value in obj.items():
|
|
yield key
|
|
for sub in all_keys(value):
|
|
yield sub
|
|
elif isinstance(obj, list):
|
|
for value in obj:
|
|
for sub in all_keys(value):
|
|
yield sub
|
|
|
|
|
|
def find_values(obj, key):
|
|
if isinstance(obj, dict):
|
|
for k, value in obj.items():
|
|
if k == key:
|
|
yield value
|
|
for sub in find_values(value, key):
|
|
yield sub
|
|
elif isinstance(obj, list):
|
|
for value in obj:
|
|
for sub in find_values(value, key):
|
|
yield sub
|
|
|
|
|
|
class GoldenBase(unittest.TestCase):
|
|
tool = None
|
|
|
|
def run_tool(self, args, timeout=TIMEOUT):
|
|
if not os.path.isfile(self.tool):
|
|
self.fail("%s not found (expected at %s)" % (os.path.basename(self.tool), self.tool))
|
|
try:
|
|
proc = subprocess.run([sys.executable, self.tool] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
universal_newlines=True, cwd=REPO, timeout=timeout)
|
|
except subprocess.TimeoutExpired:
|
|
self.fail("%s timed out after %s s: %s" % (os.path.basename(self.tool), timeout, " ".join(args)))
|
|
return proc
|
|
|
|
def close(self, got, want, key, label):
|
|
tol = TOL.get(key, 1e-9)
|
|
if not isinstance(got, (int, float)) or isinstance(got, bool):
|
|
self.fail("%s: %s is %r, expected the number %r" % (label, key, got, want))
|
|
if abs(got - want) > tol:
|
|
self.fail("%s: %s = %r, expected %r (tolerance %g)" % (label, key, got, want, tol))
|
|
|
|
def compare_fields(self, got, want, label):
|
|
for key, value in want.items():
|
|
if key not in got:
|
|
self.fail("%s: output has no key %r" % (label, key))
|
|
if isinstance(value, bool) or isinstance(value, str):
|
|
self.assertEqual(got[key], value, "%s: %s" % (label, key))
|
|
else:
|
|
self.close(got[key], value, key, label)
|
|
|
|
def parse(self, proc, label):
|
|
try:
|
|
return json.loads(proc.stdout)
|
|
except ValueError:
|
|
self.fail("%s: stdout is not JSON (exit %s). stdout: %r stderr: %r" % (label, proc.returncode, proc.stdout[:300], proc.stderr[:300]))
|
|
|
|
|
|
class SeriesEvalGolden(GoldenBase):
|
|
"""One test per case of golden/series_cases.json (generated below)."""
|
|
tool = SERIES_EVAL
|
|
|
|
def check_case(self, case):
|
|
expected = case["expected"]
|
|
variants = [("series", case.get("series"))]
|
|
if "series_b" in case:
|
|
variants.append(("series_b (%s)" % case.get("series_b_label", ""), case["series_b"]))
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
for index, (vlabel, series) in enumerate(variants):
|
|
label = "%s / %s" % (case["name"], vlabel)
|
|
path = os.path.join(tmp, "series_%d.json" % index)
|
|
with open(path, "w", encoding="utf-8") as handle:
|
|
if "raw_text" in case:
|
|
handle.write(case["raw_text"])
|
|
else:
|
|
json.dump(series, handle)
|
|
timeout = TIMEOUT_SIMULATION if "--simulate-null" in case["argv"] else TIMEOUT
|
|
proc = self.run_tool([path] + case["argv"], timeout)
|
|
self.check_output(case, label, proc, expected)
|
|
|
|
def check_output(self, case, label, proc, expected):
|
|
want_exit = expected.get("exit", 0)
|
|
self.assertEqual(proc.returncode, want_exit, "%s: exit code (stdout %r, stderr %r)" % (label, proc.stdout[:300], proc.stderr[:300]))
|
|
if want_exit != 0:
|
|
if "mention" in expected:
|
|
self.assertIn(expected["mention"], proc.stdout + proc.stderr, "%s: the message must name the mixed field" % label)
|
|
return
|
|
out = self.parse(proc, label)
|
|
text = proc.stdout
|
|
if "series_verdict" in expected:
|
|
self.assertEqual(out.get("series_verdict"), expected["series_verdict"], "%s: series_verdict" % label)
|
|
if "rows" in expected:
|
|
for metric in ("wall_norm", "ttft_sum", "decode_tps"):
|
|
got_rows = sorted((out.get("metrics") or {}).get(metric, {}).keys())
|
|
self.assertEqual(got_rows, sorted(expected["rows"]), "%s: row blocks of %s" % (label, metric))
|
|
for metric, rows in (expected.get("metrics") or {}).items():
|
|
for row, want in rows.items():
|
|
try:
|
|
got = out["metrics"][metric][row]
|
|
except (KeyError, TypeError):
|
|
self.fail("%s: output has no metrics.%s.%s" % (label, metric, row))
|
|
self.compare_fields(got, want, "%s %s/%s" % (label, metric, row))
|
|
for token in expected.get("forbidden_tokens", []):
|
|
self.assertIsNone(re.search(r"\b%s\b" % re.escape(token), text), "%s: the token %s must not appear in the output" % (label, token))
|
|
if "blind_sd" in expected:
|
|
want = expected["blind_sd"]
|
|
leaves = list(numeric_leaves(out))
|
|
self.assertTrue(any(abs(x - want) <= 1e-9 + 1e-9 * abs(want) for x in leaves),
|
|
"%s: the sd of the first 6 valid pairs (%r) is not among the output numbers %r" % (label, want, leaves[:20]))
|
|
for prefix in expected.get("forbidden_key_prefixes", []):
|
|
bad = [k for k in all_keys(out) if str(k).startswith(prefix)]
|
|
self.assertEqual(bad, [], "%s: --blind-sd must print no key starting with %r" % (label, prefix))
|
|
if "max_false_slower_rate" in expected:
|
|
rates = [v for v in find_values(out, "false_slower_rate") if isinstance(v, (int, float))]
|
|
self.assertTrue(rates, "%s: the output has no numeric false_slower_rate" % label)
|
|
self.assertLessEqual(rates[0], expected["max_false_slower_rate"], "%s: false_slower_rate" % label)
|
|
|
|
|
|
class ComponentClassGolden(GoldenBase):
|
|
"""One test per case of golden/component_cases.json (generated below)."""
|
|
tool = COMPONENT_CLASS
|
|
|
|
def check_case(self, case):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
sub = case["argv"][0]
|
|
if sub == "cell":
|
|
path = os.path.join(tmp, "cell.json")
|
|
with open(path, "w", encoding="utf-8") as handle:
|
|
json.dump(case["cell"], handle)
|
|
args = ["cell", path]
|
|
if "confirm_cell" in case:
|
|
cpath = os.path.join(tmp, "confirm_cell.json")
|
|
with open(cpath, "w", encoding="utf-8") as handle:
|
|
json.dump(case["confirm_cell"], handle)
|
|
args += ["--confirm", cpath]
|
|
else:
|
|
path = os.path.join(tmp, "alt.json")
|
|
with open(path, "w", encoding="utf-8") as handle:
|
|
json.dump(case["alt"], handle)
|
|
args = ["ac5", path]
|
|
proc = self.run_tool(args)
|
|
label = case["name"]
|
|
expected = dict(case["expected"])
|
|
want_exit = expected.pop("exit", 0)
|
|
self.assertEqual(proc.returncode, want_exit, "%s: exit code (stdout %r, stderr %r)" % (label, proc.stdout[:300], proc.stderr[:300]))
|
|
out = self.parse(proc, label)
|
|
self.compare_fields(out, expected, label)
|
|
|
|
|
|
class GoldenFilesIntact(unittest.TestCase):
|
|
"""Checks of the golden files themselves; these pass before the evaluators exist."""
|
|
|
|
def test_golden_files_load(self):
|
|
self.assertEqual(LOAD_ERRORS, [])
|
|
|
|
def test_case_names_unique_and_enough(self):
|
|
names = [c["name"] for doc in (SERIES_DOC, COMPONENT_DOC) for c in doc["cases"]]
|
|
self.assertEqual(len(names), len(set(names)), "duplicate case names")
|
|
self.assertGreaterEqual(len(names), 24)
|
|
for required in ("all_zero_l", "ci_bound_exactly_zero", "ci_bound_exactly_ln099", "n29_screening", "n30_final_verdict", "mixed_build_ids",
|
|
"mixed_warm_cold", "permutation_invariance", "unit_scale_invariance", "clear_pass", "clear_slower", "tie", "inconclusive",
|
|
"autocorr_neff_correction", "interim_look1_slower_exit", "interim_look2_slower_exit", "null_simulation",
|
|
"cell_faster", "cell_equal", "aa_ours_invalid_rerun_once", "slower_confirmed", "ac5_slower_at_look2", "ac5_tie_30"):
|
|
self.assertIn(required, names)
|
|
|
|
def test_every_case_has_a_basis(self):
|
|
for doc in (SERIES_DOC, COMPONENT_DOC):
|
|
for case in doc["cases"]:
|
|
self.assertTrue(str(case.get("basis", "")).strip(), "case %s has no basis" % case["name"])
|
|
|
|
def test_gen_exact_check_reports_no_differences(self):
|
|
proc = subprocess.run([sys.executable, GEN_EXACT, "--check"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True,
|
|
cwd=REPO, timeout=TIMEOUT)
|
|
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
|
|
self.assertIn("t(0.975,29)=2.0452 OK", proc.stdout)
|
|
self.assertIn("differences: 0", proc.stdout)
|
|
|
|
|
|
def _add_tests(cls, doc):
|
|
for case in doc["cases"]:
|
|
def test(self, case=case):
|
|
self.check_case(case)
|
|
test.__name__ = "test_" + case["name"]
|
|
test.__doc__ = case["name"]
|
|
setattr(cls, test.__name__, test)
|
|
|
|
|
|
_add_tests(SeriesEvalGolden, SERIES_DOC)
|
|
_add_tests(ComponentClassGolden, COMPONENT_DOC)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|