From 380f2cefca5d0a1e78cbdd05ec7e573918179547 Mon Sep 17 00:00:00 2001 From: hlin99 Date: Mon, 6 Apr 2026 13:40:05 +0800 Subject: [PATCH] feat(M84): endpoint response time regression detection - latency_regression.py: Welch's t-test, Cohen's d, percentile comparison - CLI: xpyd-acc latency-regression --old/--new/--alpha/--json - Exit 0 if no regression, exit 1 if significant slowdown - Rich terminal output with latency table and verdict - 26 tests covering statistics, integration, formatting, CLI --- docs/iterations/current.md | 4 +- src/xpyd_acc/cli/__init__.py | 2 + src/xpyd_acc/cli/analysis.py | 26 +++ src/xpyd_acc/cli/parsers.py | 18 ++ src/xpyd_acc/latency_regression.py | 309 +++++++++++++++++++++++++++++ tests/test_latency_regression.py | 268 +++++++++++++++++++++++++ 6 files changed, 626 insertions(+), 1 deletion(-) create mode 100644 src/xpyd_acc/latency_regression.py create mode 100644 tests/test_latency_regression.py diff --git a/docs/iterations/current.md b/docs/iterations/current.md index 3a6aa05..9c9e286 100644 --- a/docs/iterations/current.md +++ b/docs/iterations/current.md @@ -47,4 +47,6 @@ shell for exploratory comparison of two endpoints. | M79 | 2026-04-06 | Parallel Multi-Dataset Batch Run | ✅ merged | Both approved | | M80 | 2026-04-06 | Multi-Dataset CLI Integration | ✅ merged | Both approved | | M81 | 2026-04-06 | Automatic Threshold Tuning | ✅ merged | Both approved | -| M82 | 2026-04-06 | Interactive REPL for Exploratory Comparison | ⏳ pending review | — | +| M82 | 2026-04-06 | Interactive REPL for Exploratory Comparison | ✅ merged | Both approved | +| M83 | 2026-04-06 | Divergence Heatmap by Token Position | ⏳ pending merge (2 approvals, rebased) | Both approved | +| M84 | 2026-04-06 | Endpoint Response Time Regression Detection | ⏳ pending review | — | diff --git a/src/xpyd_acc/cli/__init__.py b/src/xpyd_acc/cli/__init__.py index 856be01..f3aaa8e 100644 --- a/src/xpyd_acc/cli/__init__.py +++ b/src/xpyd_acc/cli/__init__.py @@ -14,6 +14,7 @@ from .analysis import ( _run_entropy, _run_fingerprint, + _run_latency_regression, _run_length_bias, _run_sensitivity, _run_watch, @@ -133,6 +134,7 @@ def main(argv: list[str] | None = None) -> None: "completion": lambda: _run_completion(args, parser), "auto-threshold": lambda: _run_auto_threshold(args), "repl": lambda: _run_repl(args), + "latency-regression": lambda: _run_latency_regression(args), } if args.command in _early: diff --git a/src/xpyd_acc/cli/analysis.py b/src/xpyd_acc/cli/analysis.py index 4d98219..636beb2 100644 --- a/src/xpyd_acc/cli/analysis.py +++ b/src/xpyd_acc/cli/analysis.py @@ -258,3 +258,29 @@ def handle_token_diff(args: argparse.Namespace) -> None: data = [d.to_dict() for d in diffs] Path(args.td_json).write_text(_json.dumps(data, indent=2)) print(f"Exported to {args.td_json}") + + +def _run_latency_regression(args: argparse.Namespace) -> None: + """Run latency regression detection between two benchmark runs.""" + import json + from pathlib import Path + + from xpyd_acc.latency_regression import ( + format_latency_regression, + run_latency_regression, + ) + + result = run_latency_regression( + old_path=Path(args.old), + new_path=Path(args.new), + alpha=args.alpha, + ) + + format_latency_regression(result) + + if args.json: + with open(args.json, "w") as f: + json.dump(result.to_dict(), f, indent=2) + + if result.verdict == "slower": + raise SystemExit(1) diff --git a/src/xpyd_acc/cli/parsers.py b/src/xpyd_acc/cli/parsers.py index f93c711..7ce8a7b 100644 --- a/src/xpyd_acc/cli/parsers.py +++ b/src/xpyd_acc/cli/parsers.py @@ -50,6 +50,7 @@ def register_all(sub: argparse._SubParsersAction) -> None: _register_grafana_dashboard(sub) _register_auto_threshold(sub) _register_repl(sub) + _register_latency_regression(sub) def _register_compare(sub): lp = sub.add_parser("compare-logprobs", help="Compare logprobs between two endpoints") lp.add_argument("--baseline", required=True, help="Baseline endpoint URL") @@ -606,3 +607,20 @@ def _register_repl(sub): rp.add_argument("--target", required=True, help="Target endpoint URL") rp.add_argument("--model", default="default", help="Model name") rp.add_argument("--api-key", default=None, help="API key") + + +def _register_latency_regression(sub): + lr = sub.add_parser( + "latency-regression", + help="Detect response time regressions between two benchmark runs", + ) + lr.add_argument("--old", required=True, help="Path to old (baseline) benchmark JSON") + lr.add_argument("--new", required=True, help="Path to new (current) benchmark JSON") + lr.add_argument( + "--alpha", type=float, default=0.05, + help="Significance level for t-test (default: 0.05)", + ) + lr.add_argument( + "--json", default=None, + help="Export regression results as JSON to this path", + ) diff --git a/src/xpyd_acc/latency_regression.py b/src/xpyd_acc/latency_regression.py new file mode 100644 index 0000000..5f7a74f --- /dev/null +++ b/src/xpyd_acc/latency_regression.py @@ -0,0 +1,309 @@ +"""Endpoint response time regression detection (M84).""" + +from __future__ import annotations + +import json +import math +from dataclasses import asdict, dataclass +from pathlib import Path + +from rich.console import Console +from rich.table import Table + +from xpyd_acc.log import get_logger + +logger = get_logger("latency_regression") + + +@dataclass +class LatencyRegressionResult: + """Result of comparing two benchmark runs.""" + + old_mean_ms: float + new_mean_ms: float + mean_diff_ms: float + p_value: float + cohens_d: float + old_p50_ms: float + new_p50_ms: float + old_p95_ms: float + new_p95_ms: float + old_p99_ms: float + new_p99_ms: float + verdict: str # "faster", "slower", "unchanged" + alpha: float + old_count: int + new_count: int + + def to_dict(self) -> dict: + return asdict(self) + + +def _welch_t_test( + mean1: float, + std1: float, + n1: int, + mean2: float, + std2: float, + n2: int, +) -> tuple[float, float]: + """Welch's t-test. Returns (t_statistic, p_value). + + Two-tailed test. Uses approximation for p-value from t-distribution. + """ + if n1 < 2 or n2 < 2: + return 0.0, 1.0 + + se1 = (std1**2) / n1 + se2 = (std2**2) / n2 + se_sum = se1 + se2 + + if se_sum == 0: + return 0.0, 1.0 + + t_stat = (mean1 - mean2) / math.sqrt(se_sum) + + # Welch-Satterthwaite degrees of freedom + if se1 == 0 and se2 == 0: + df = n1 + n2 - 2 + else: + num = se_sum**2 + denom = (se1**2 / (n1 - 1)) + (se2**2 / (n2 - 1)) + if denom == 0: + df = n1 + n2 - 2 + else: + df = num / denom + + # Approximate two-tailed p-value using regularized incomplete beta function + p_value = _t_distribution_p_value(abs(t_stat), df) + return t_stat, p_value + + +def _t_distribution_p_value(t: float, df: float) -> float: + """Approximate two-tailed p-value for t-distribution. + + Uses the relationship between t-distribution and regularized incomplete beta. + """ + if df <= 0: + return 1.0 + x = df / (df + t**2) + p = _regularized_incomplete_beta(df / 2.0, 0.5, x) + return p + + +def _regularized_incomplete_beta(a: float, b: float, x: float) -> float: + """Regularized incomplete beta function I_x(a, b) via continued fraction.""" + if x <= 0: + return 0.0 + if x >= 1: + return 1.0 + + # Use the continued fraction expansion + ln_beta = math.lgamma(a) + math.lgamma(b) - math.lgamma(a + b) + front = math.exp( + math.log(x) * a + math.log(1 - x) * b - ln_beta + ) / a + + # Lentz's algorithm for continued fraction + # I_x(a,b) = front * cf where cf is a continued fraction + # Using the standard DLMF 8.17.22 expansion + def _cf(a: float, b: float, x: float) -> float: + max_iter = 200 + tiny = 1e-30 + f = 1.0 + c = 1.0 + d = 1.0 - (a + b) * x / (a + 1) + if abs(d) < tiny: + d = tiny + d = 1.0 / d + f = d + + for m in range(1, max_iter + 1): + # Even step + num = m * (b - m) * x / ((a + 2 * m - 1) * (a + 2 * m)) + d = 1.0 + num * d + if abs(d) < tiny: + d = tiny + c = 1.0 + num / c + if abs(c) < tiny: + c = tiny + d = 1.0 / d + f *= d * c + + # Odd step + num = -(a + m) * (a + b + m) * x / ((a + 2 * m) * (a + 2 * m + 1)) + d = 1.0 + num * d + if abs(d) < tiny: + d = tiny + c = 1.0 + num / c + if abs(c) < tiny: + c = tiny + d = 1.0 / d + delta = d * c + f *= delta + + if abs(delta - 1.0) < 1e-10: + break + + return f + + # For numerical stability, use symmetry when x > (a+1)/(a+b+2) + if x > (a + 1) / (a + b + 2): + return 1.0 - _regularized_incomplete_beta(b, a, 1 - x) + + return front * _cf(a, b, x) + + +def _cohens_d( + mean1: float, std1: float, n1: int, + mean2: float, std2: float, n2: int, +) -> float: + """Cohen's d effect size (pooled standard deviation).""" + if n1 < 2 or n2 < 2: + return 0.0 + pooled_var = ((n1 - 1) * std1**2 + (n2 - 1) * std2**2) / (n1 + n2 - 2) + pooled_std = math.sqrt(pooled_var) + if pooled_std == 0: + return 0.0 + return (mean2 - mean1) / pooled_std + + +def _percentile(data: list[float], p: float) -> float: + """Compute percentile from sorted data.""" + if not data: + return 0.0 + sorted_data = sorted(data) + k = (len(sorted_data) - 1) * p / 100.0 + f = math.floor(k) + c = math.ceil(k) + if f == c: + return sorted_data[int(k)] + return sorted_data[f] * (c - k) + sorted_data[c] * (k - f) + + +def _load_benchmark(path: Path) -> dict: + """Load benchmark JSON file.""" + with open(path) as f: + return json.load(f) + + +def run_latency_regression( + old_path: Path, + new_path: Path, + alpha: float = 0.05, +) -> LatencyRegressionResult: + """Compare two benchmark runs for latency regression. + + Args: + old_path: Path to old (baseline) benchmark JSON. + new_path: Path to new (current) benchmark JSON. + alpha: Significance level for the t-test. + + Returns: + LatencyRegressionResult with test results and verdict. + """ + old_data = _load_benchmark(old_path) + new_data = _load_benchmark(new_path) + + old_latencies = old_data.get("latencies_ms", []) + new_latencies = new_data.get("latencies_ms", []) + + if not old_latencies or not new_latencies: + raise ValueError("Both benchmark files must contain non-empty latencies_ms") + + import statistics as stats + + old_mean = stats.mean(old_latencies) + new_mean = stats.mean(new_latencies) + old_std = stats.stdev(old_latencies) if len(old_latencies) > 1 else 0.0 + new_std = stats.stdev(new_latencies) if len(new_latencies) > 1 else 0.0 + n_old = len(old_latencies) + n_new = len(new_latencies) + + _, p_value = _welch_t_test(old_mean, old_std, n_old, new_mean, new_std, n_new) + d = _cohens_d(old_mean, old_std, n_old, new_mean, new_std, n_new) + + if p_value < alpha: + verdict = "slower" if new_mean > old_mean else "faster" + else: + verdict = "unchanged" + + return LatencyRegressionResult( + old_mean_ms=old_mean, + new_mean_ms=new_mean, + mean_diff_ms=new_mean - old_mean, + p_value=p_value, + cohens_d=d, + old_p50_ms=_percentile(old_latencies, 50), + new_p50_ms=_percentile(new_latencies, 50), + old_p95_ms=_percentile(old_latencies, 95), + new_p95_ms=_percentile(new_latencies, 95), + old_p99_ms=_percentile(old_latencies, 99), + new_p99_ms=_percentile(new_latencies, 99), + verdict=verdict, + alpha=alpha, + old_count=n_old, + new_count=n_new, + ) + + +def format_latency_regression(result: LatencyRegressionResult) -> None: + """Print formatted latency regression report.""" + console = Console() + + # Verdict banner + if result.verdict == "slower": + console.print("\n[bold red]⚠️ REGRESSION DETECTED[/bold red]") + elif result.verdict == "faster": + console.print("\n[bold green]✅ IMPROVEMENT DETECTED[/bold green]") + else: + console.print("\n[bold blue]➡️ NO SIGNIFICANT CHANGE[/bold blue]") + + # Summary table + table = Table(title="Latency Regression Analysis") + table.add_column("Metric", style="cyan") + table.add_column("Old", justify="right") + table.add_column("New", justify="right") + table.add_column("Diff", justify="right") + + table.add_row( + "Mean (ms)", + f"{result.old_mean_ms:.2f}", + f"{result.new_mean_ms:.2f}", + f"{result.mean_diff_ms:+.2f}", + ) + table.add_row( + "P50 (ms)", + f"{result.old_p50_ms:.2f}", + f"{result.new_p50_ms:.2f}", + f"{result.new_p50_ms - result.old_p50_ms:+.2f}", + ) + table.add_row( + "P95 (ms)", + f"{result.old_p95_ms:.2f}", + f"{result.new_p95_ms:.2f}", + f"{result.new_p95_ms - result.old_p95_ms:+.2f}", + ) + table.add_row( + "P99 (ms)", + f"{result.old_p99_ms:.2f}", + f"{result.new_p99_ms:.2f}", + f"{result.new_p99_ms - result.old_p99_ms:+.2f}", + ) + console.print(table) + + # Statistics + console.print(f"\n Samples: old={result.old_count}, new={result.new_count}") + console.print(f" p-value: {result.p_value:.6f} (alpha={result.alpha})") + console.print(f" Cohen's d: {result.cohens_d:.4f}") + + effect = "negligible" + d_abs = abs(result.cohens_d) + if d_abs >= 0.8: + effect = "large" + elif d_abs >= 0.5: + effect = "medium" + elif d_abs >= 0.2: + effect = "small" + console.print(f" Effect: {effect}") + console.print(f" Verdict: {result.verdict}\n") diff --git a/tests/test_latency_regression.py b/tests/test_latency_regression.py new file mode 100644 index 0000000..a82796f --- /dev/null +++ b/tests/test_latency_regression.py @@ -0,0 +1,268 @@ +"""Tests for latency regression detection (M84).""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from xpyd_acc.latency_regression import ( + LatencyRegressionResult, + _cohens_d, + _percentile, + _welch_t_test, + format_latency_regression, + run_latency_regression, +) + +# --- Unit tests for statistics helpers --- + + +class TestWelchTTest: + def test_identical_samples(self): + t, p = _welch_t_test(100.0, 10.0, 30, 100.0, 10.0, 30) + assert t == 0.0 + assert p >= 0.99 # not significant + + def test_clearly_different(self): + # Large difference, small variance + t, p = _welch_t_test(100.0, 5.0, 50, 200.0, 5.0, 50) + assert p < 0.001 + + def test_small_samples(self): + t, p = _welch_t_test(100.0, 10.0, 1, 200.0, 10.0, 1) + assert p == 1.0 # n < 2 + + def test_zero_variance(self): + t, p = _welch_t_test(100.0, 0.0, 10, 100.0, 0.0, 10) + assert p == 1.0 + + +class TestCohensD: + def test_identical(self): + d = _cohens_d(100.0, 10.0, 30, 100.0, 10.0, 30) + assert d == 0.0 + + def test_large_effect(self): + d = _cohens_d(100.0, 10.0, 30, 120.0, 10.0, 30) + assert d == pytest.approx(2.0, abs=0.01) + + def test_small_samples(self): + d = _cohens_d(100.0, 10.0, 1, 200.0, 10.0, 1) + assert d == 0.0 + + def test_zero_std(self): + d = _cohens_d(100.0, 0.0, 10, 100.0, 0.0, 10) + assert d == 0.0 + + +class TestPercentile: + def test_empty(self): + assert _percentile([], 50) == 0.0 + + def test_single(self): + assert _percentile([42.0], 50) == 42.0 + + def test_median(self): + assert _percentile([1.0, 2.0, 3.0, 4.0, 5.0], 50) == 3.0 + + def test_p95(self): + data = list(range(1, 101)) + p95 = _percentile([float(x) for x in data], 95) + assert p95 == pytest.approx(95.05, abs=0.1) + + +# --- Integration tests --- + + +class TestRunLatencyRegression: + def _write_benchmark(self, path: Path, latencies: list[float]) -> None: + data = { + "url": "http://test", + "model": "test", + "requests": len(latencies), + "concurrency": 1, + "latencies_ms": latencies, + } + path.write_text(json.dumps(data)) + + def test_no_regression(self, tmp_path): + old = tmp_path / "old.json" + new = tmp_path / "new.json" + # Similar latencies + self._write_benchmark(old, [100.0, 102.0, 98.0, 101.0, 99.0] * 10) + self._write_benchmark(new, [101.0, 103.0, 99.0, 100.0, 98.0] * 10) + + result = run_latency_regression(old, new) + assert result.verdict == "unchanged" + assert result.p_value > 0.05 + + def test_regression_detected(self, tmp_path): + old = tmp_path / "old.json" + new = tmp_path / "new.json" + # Clear regression: new is much slower + self._write_benchmark(old, [100.0, 102.0, 98.0, 101.0, 99.0] * 10) + self._write_benchmark(new, [200.0, 202.0, 198.0, 201.0, 199.0] * 10) + + result = run_latency_regression(old, new) + assert result.verdict == "slower" + assert result.p_value < 0.05 + assert result.mean_diff_ms > 90 + + def test_improvement_detected(self, tmp_path): + old = tmp_path / "old.json" + new = tmp_path / "new.json" + self._write_benchmark(old, [200.0, 202.0, 198.0, 201.0, 199.0] * 10) + self._write_benchmark(new, [100.0, 102.0, 98.0, 101.0, 99.0] * 10) + + result = run_latency_regression(old, new) + assert result.verdict == "faster" + assert result.mean_diff_ms < -90 + + def test_custom_alpha(self, tmp_path): + old = tmp_path / "old.json" + new = tmp_path / "new.json" + self._write_benchmark(old, [100.0, 102.0, 98.0, 101.0, 99.0] * 10) + self._write_benchmark(new, [200.0, 202.0, 198.0, 201.0, 199.0] * 10) + + result = run_latency_regression(old, new, alpha=0.001) + assert result.alpha == 0.001 + assert result.verdict == "slower" + + def test_percentiles_computed(self, tmp_path): + old = tmp_path / "old.json" + new = tmp_path / "new.json" + self._write_benchmark(old, [100.0, 110.0, 120.0, 130.0, 140.0] * 10) + self._write_benchmark(new, [200.0, 210.0, 220.0, 230.0, 240.0] * 10) + + result = run_latency_regression(old, new) + assert result.old_p50_ms > 0 + assert result.new_p50_ms > 0 + assert result.old_p95_ms > 0 + assert result.new_p95_ms > 0 + assert result.old_p99_ms > 0 + assert result.new_p99_ms > 0 + + def test_empty_latencies_raises(self, tmp_path): + old = tmp_path / "old.json" + new = tmp_path / "new.json" + old.write_text(json.dumps({"latencies_ms": []})) + new.write_text(json.dumps({"latencies_ms": [100.0]})) + + with pytest.raises(ValueError, match="non-empty"): + run_latency_regression(old, new) + + def test_to_dict(self, tmp_path): + old = tmp_path / "old.json" + new = tmp_path / "new.json" + self._write_benchmark(old, [100.0, 102.0, 98.0]) + self._write_benchmark(new, [200.0, 202.0, 198.0]) + + result = run_latency_regression(old, new) + d = result.to_dict() + assert "old_mean_ms" in d + assert "verdict" in d + assert "cohens_d" in d + + def test_json_export(self, tmp_path): + old = tmp_path / "old.json" + new = tmp_path / "new.json" + self._write_benchmark(old, [100.0, 102.0, 98.0] * 10) + self._write_benchmark(new, [200.0, 202.0, 198.0] * 10) + + result = run_latency_regression(old, new) + out = tmp_path / "result.json" + with open(out, "w") as f: + json.dump(result.to_dict(), f) + + loaded = json.loads(out.read_text()) + assert loaded["verdict"] == "slower" + + +class TestFormatLatencyRegression: + def test_format_slower(self, capsys): + result = LatencyRegressionResult( + old_mean_ms=100.0, new_mean_ms=200.0, mean_diff_ms=100.0, + p_value=0.001, cohens_d=1.5, + old_p50_ms=100.0, new_p50_ms=200.0, + old_p95_ms=110.0, new_p95_ms=210.0, + old_p99_ms=120.0, new_p99_ms=220.0, + verdict="slower", alpha=0.05, + old_count=50, new_count=50, + ) + format_latency_regression(result) + # Just verify it runs without error + + def test_format_faster(self, capsys): + result = LatencyRegressionResult( + old_mean_ms=200.0, new_mean_ms=100.0, mean_diff_ms=-100.0, + p_value=0.001, cohens_d=-1.5, + old_p50_ms=200.0, new_p50_ms=100.0, + old_p95_ms=210.0, new_p95_ms=110.0, + old_p99_ms=220.0, new_p99_ms=120.0, + verdict="faster", alpha=0.05, + old_count=50, new_count=50, + ) + format_latency_regression(result) + + def test_format_unchanged(self, capsys): + result = LatencyRegressionResult( + old_mean_ms=100.0, new_mean_ms=101.0, mean_diff_ms=1.0, + p_value=0.8, cohens_d=0.05, + old_p50_ms=100.0, new_p50_ms=101.0, + old_p95_ms=110.0, new_p95_ms=111.0, + old_p99_ms=120.0, new_p99_ms=121.0, + verdict="unchanged", alpha=0.05, + old_count=50, new_count=50, + ) + format_latency_regression(result) + + +class TestCLI: + def _write_benchmark(self, path: Path, latencies: list[float]) -> None: + data = { + "url": "http://test", + "model": "test", + "requests": len(latencies), + "concurrency": 1, + "latencies_ms": latencies, + } + path.write_text(json.dumps(data)) + + def test_cli_no_regression(self, tmp_path): + from xpyd_acc.cli import main + + old = tmp_path / "old.json" + new = tmp_path / "new.json" + # Use identical latencies so no significant difference + self._write_benchmark(old, [100.0, 110.0, 90.0, 105.0, 95.0] * 10) + self._write_benchmark(new, [101.0, 109.0, 91.0, 104.0, 96.0] * 10) + + main(["latency-regression", "--old", str(old), "--new", str(new)]) + + def test_cli_regression_exit_1(self, tmp_path): + from xpyd_acc.cli import main + + old = tmp_path / "old.json" + new = tmp_path / "new.json" + self._write_benchmark(old, [100.0, 102.0, 98.0] * 10) + self._write_benchmark(new, [300.0, 302.0, 298.0] * 10) + + with pytest.raises(SystemExit) as exc_info: + main(["latency-regression", "--old", str(old), "--new", str(new)]) + assert exc_info.value.code == 1 + + def test_cli_json_export(self, tmp_path): + from xpyd_acc.cli import main + + old = tmp_path / "old.json" + new = tmp_path / "new.json" + out = tmp_path / "result.json" + self._write_benchmark(old, [100.0, 102.0, 98.0] * 10) + self._write_benchmark(new, [100.0, 102.0, 98.0] * 10) + + main(["latency-regression", "--old", str(old), "--new", str(new), + "--json", str(out)]) + loaded = json.loads(out.read_text()) + assert "verdict" in loaded