From eed0067e47e44d7d397325dbe7b2a653c82332c3 Mon Sep 17 00:00:00 2001 From: hlin99 Date: Mon, 6 Apr 2026 10:16:51 +0800 Subject: [PATCH] feat(M81): automatic threshold tuning from historical reports - auto_threshold.py: analyze_thresholds(), ThresholdRecommendation, format_recommendations() - Percentile-based fail_threshold and numeric_tolerance recommendations - Confidence scoring based on sample size and report count - CLI: xpyd-acc auto-threshold --reports ... --percentile ... --json ... - 18 tests covering computation, serialization, formatting, CLI integration Closes #175 --- docs/iterations/current.md | 174 +++++-------------------- src/xpyd_acc/auto_threshold.py | 183 ++++++++++++++++++++++++++ src/xpyd_acc/cli/__init__.py | 2 + src/xpyd_acc/cli/parsers.py | 20 +++ src/xpyd_acc/cli/report.py | 23 ++++ tests/test_auto_threshold.py | 232 +++++++++++++++++++++++++++++++++ 6 files changed, 494 insertions(+), 140 deletions(-) create mode 100644 src/xpyd_acc/auto_threshold.py create mode 100644 tests/test_auto_threshold.py diff --git a/docs/iterations/current.md b/docs/iterations/current.md index f5b26d0..cc80c7c 100644 --- a/docs/iterations/current.md +++ b/docs/iterations/current.md @@ -1,97 +1,47 @@ -# Current Iteration — M73 +# Current Iteration — M81 ## Milestone -**M73** — Multi-Model Comparison in Single Batch Run +**M81** — Automatic Threshold Tuning ## What Was Done -Added `multi_model.py` module enabling `batch-compare` to accept multiple `--model` flags -and run the same dataset against each model, producing a `MultiModelBatchReport` with: +Added `xpyd-acc auto-threshold --reports r1.json r2.json ...` command that analyzes +historical batch reports and recommends optimal `--fail-threshold` and `--numeric-tolerance` +values based on percentile-based statistical analysis. -- Per-model `BatchReport` (reuses existing `run_batch()`) -- Cross-model analysis: systematic divergences (all models), model-specific, all-match -- JSON and Markdown export with per-model breakdowns -- Terminal formatting with per-model pass/fail indicators - -### Files Changed - -- **`src/xpyd_acc/multi_model.py`** (new): `MultiModelBatchReport`, `CrossModelSummary`, - `compute_cross_model_summary()`, `format_multi_model_report()`, `run_multi_model()` -- **`src/xpyd_acc/cli.py`**: `--model` changed to `action="append"` for repeatable flag; - multi-model branch added in `_run_batch_compare()` with JSON/Markdown export and exit code -- **`tests/test_multi_model.py`** (new): 15 tests covering dataclasses, cross-model summary, - report serialization, formatting, and async `run_multi_model()` with mocked `run_batch` - -### Tests - -15 tests all passing: -- `CrossModelSummary` serialization -- `compute_cross_model_summary` for all-match, systematic, model-specific, empty, single-model -- `MultiModelBatchReport` JSON round-trip, Markdown generation -- `format_multi_model_report` terminal output -- `run_multi_model` with callback, backward compat, parameter forwarding, mixed results - -## Iteration History - -| # | Date | Task | Result | Reviewer Comments | -|---|------|------|--------|-------------------| -| 1 | 2026-04-06 | M73: Multi-Model Comparison | ⏳ pending review | — | -| 2 | 2026-04-06 | M73: CLI Modularization — split cli.py into cli/ package | ⏳ pending review | — | - ---- - -## Iteration 3: M74 — Divergence Root Cause Heuristics - -**Date:** 2026-04-06 -**Issue:** #161 -**Branch:** `feat/m74-root-cause-heuristics` - -### What was done - -Added `xpyd-acc root-cause --report ` CLI subcommand that analyzes batch report divergence patterns and suggests probable root cause (prefill, KV transfer, decode, truncation, mixed, or inconclusive). - -### Files changed - -- **`src/xpyd_acc/root_cause.py`** (new): `analyze_root_cause()`, `RootCauseAnalysis`, `Evidence` dataclasses, `_classify_sample()` heuristic rules, `format_root_cause()` terminal display, `analyze_from_file()` convenience function -- **`src/xpyd_acc/cli/analysis.py`**: Added `handle_root_cause()` CLI handler -- **`src/xpyd_acc/cli/parsers.py`**: Registered `root-cause` subcommand with `--report` and `--json` flags -- **`src/xpyd_acc/cli/__init__.py`**: Wired `root-cause` to handler -- **`tests/test_root_cause.py`** (new): 21 tests covering heuristic classification, analysis, serialization, formatting, file I/O, CLI integration -- **`ROADMAP.md`**: Marked M73 ✅, added M74-M76 - -### Tests - -21 tests all passing. Full suite: 1085 passed. - ---- - -## Iteration: M75 — Side-by-Side Token Diff Viewer +### Implementation -**Date:** 2026-04-06 -**Issue:** #163 -**Branch:** feat/m75-token-diff +- `auto_threshold.py` module: + - `ThresholdRecommendation` dataclass with `to_dict()` serialization + - `analyze_thresholds()` — percentile-based recommendation engine + - `load_reports()` — fault-tolerant multi-report loader + - `format_recommendations()` — terminal display + - `_percentile()` — interpolating percentile computation +- Fail threshold: p95 of observed divergence rates × 1.1 + headroom +- Numeric tolerance: p95 of logprob gaps at divergence points +- Confidence scoring: high (≥500 samples, ≥3 reports), medium, low +- `--percentile ` flag to control recommendation aggressiveness +- `--json ` export -### What was done +### Files Changed -- Created `src/xpyd_acc/token_diff.py` module with: - - `TokenDiffLine` and `TokenDiff` dataclasses with JSON serialization - - `build_token_diff()` — builds aligned diff with context window - - `format_token_diff()` — rich terminal output with ANSI colors or plain text - - `build_from_report()`, `build_all_divergent()`, `diff_from_file()` helpers - - Color-coded output: green (match), red (mismatch), yellow (logprob warning), cyan (one-sided) - - Logprob annotations at divergence point -- Added CLI subcommand `xpyd-acc token-diff`: - - `--report`, `--sample`, `--all-divergent`, `--context`, `--format`, `--json` -- Created `tests/test_token_diff.py` with 25 tests covering: - - Dataclass serialization, diff building, empty/asymmetric outputs - - Context window, logprob annotations, logprob warning status - - Report lookup, divergent filtering, file I/O - - CLI help, sample mode, JSON export, error handling +- `src/xpyd_acc/auto_threshold.py` (new) +- `src/xpyd_acc/cli/report.py` — added `_run_auto_threshold()` handler +- `src/xpyd_acc/cli/parsers.py` — registered `auto-threshold` subcommand +- `src/xpyd_acc/cli/__init__.py` — wired handler to early dispatch +- `tests/test_auto_threshold.py` (new, 18 tests) +- `docs/iterations/current.md` — updated ### Tests -25 tests all passing. +18 tests covering: +- Percentile computation (basic, p95, empty, single) +- Threshold analysis (empty reports, single report, multiple/high-confidence, no logprob gaps, custom percentile) +- ThresholdRecommendation serialization and JSON round-trip +- Format output with data and without data +- Report loading (valid, missing, mixed) +- CLI integration (basic and custom percentile) ## Iteration History @@ -102,62 +52,6 @@ Added `xpyd-acc root-cause --report ` CLI subcommand that analyzes batch r | M76 | 2026-04-06 | Report Dashboard Server | ✅ merged | Both approved | | M77 | 2026-04-06 | Prometheus Metrics Export | ✅ merged | Both approved | | M78 | 2026-04-06 | Grafana Dashboard Template Export | ✅ merged | Both approved | - -## Iteration M79: Parallel Multi-Dataset Batch Run - -### What -Added `multi_dataset.py` module for running multiple evaluation datasets concurrently. - -### Implementation -- `MultiDatasetReport` dataclass with per-dataset `BatchReport` and aggregate stats -- `run_multi_dataset()` async function runs datasets in parallel via `asyncio.gather()` -- `format_multi_dataset_report()` for terminal display with per-dataset pass/fail indicators -- JSON and Markdown export with per-dataset breakdowns -- Callback support via `on_dataset_complete` parameter - -### Files Changed -- `src/xpyd_acc/multi_dataset.py` (new) -- `tests/test_multi_dataset.py` (new, 18 tests) - -### Tests -18 tests covering: -- Dataclass construction, aggregation, edge cases (empty, all match, all diverge) -- JSON serialization and round-trip -- Markdown export with truncation -- Async execution with mocked run_batch -- Callback invocation -- Kwargs forwarding -- Empty dataset map handling - ---- - -## M80: Multi-Dataset CLI Integration - -**Date:** 2026-04-06 -**Issue:** #173 -**Status:** In progress - -### Problem -M79 added `multi_dataset.py` with `run_multi_dataset()` but no CLI integration — users cannot invoke multi-dataset runs from the command line. - -### Solution -- Made `--dataset` flag repeatable (argparse `action="append"`) -- When >1 dataset given, `_run_batch_compare` delegates to `_run_multi_dataset()` -- Added `_run_multi_dataset()` in `batch.py`: loads datasets, runs concurrent comparison, prints results -- Per-dataset `--fail-threshold` checking -- JSON/Markdown export support - -### Files Changed -- `src/xpyd_acc/cli/parsers.py` (--dataset becomes repeatable) -- `src/xpyd_acc/cli/batch.py` (multi-dataset routing + handler) -- `tests/test_multi_dataset_cli.py` (new, 10 tests) -- `ROADMAP.md` (M79 ✅, M80 added) - -### Tests -10 tests covering: -- Dataclass aggregation -- JSON/Markdown export -- Terminal formatting -- CLI flag repeatability -- Multi-dataset delegation -- Single-dataset backward compatibility +| 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 | ⏳ pending review | — | diff --git a/src/xpyd_acc/auto_threshold.py b/src/xpyd_acc/auto_threshold.py new file mode 100644 index 0000000..03bcb9f --- /dev/null +++ b/src/xpyd_acc/auto_threshold.py @@ -0,0 +1,183 @@ +"""Automatic threshold tuning from historical batch reports.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +from xpyd_acc.batch_compare import BatchReport, load_report +from xpyd_acc.log import get_logger + +logger = get_logger("auto_threshold") + + +@dataclass +class ThresholdRecommendation: + """Recommended threshold values based on historical report analysis.""" + + fail_threshold: float | None + numeric_tolerance: float | None + confidence: str # "high", "medium", "low" + sample_size: int + reasoning: list[str] + divergence_rates: list[float] = field(default_factory=list) + logprob_gaps: list[float] = field(default_factory=list) + percentile_used: float = 0.95 + + def to_dict(self) -> dict[str, Any]: + return { + "fail_threshold": self.fail_threshold, + "numeric_tolerance": self.numeric_tolerance, + "confidence": self.confidence, + "sample_size": self.sample_size, + "reasoning": self.reasoning, + "divergence_rates": self.divergence_rates, + "logprob_gaps": self.logprob_gaps, + "percentile_used": self.percentile_used, + } + + +def _percentile(data: list[float], p: float) -> float: + """Compute the p-th percentile of a sorted list (0 < p < 1).""" + if not data: + return 0.0 + sorted_data = sorted(data) + k = (len(sorted_data) - 1) * p + floor_k = int(k) + ceil_k = min(floor_k + 1, len(sorted_data) - 1) + frac = k - floor_k + return sorted_data[floor_k] + frac * (sorted_data[ceil_k] - sorted_data[floor_k]) + + +def analyze_thresholds( + reports: list[BatchReport], + percentile_level: float = 0.95, +) -> ThresholdRecommendation: + """Analyze batch reports and recommend threshold values. + + Args: + reports: List of BatchReport objects to analyze. + percentile_level: Percentile to use for recommendations (0-1). + + Returns: + ThresholdRecommendation with suggested values. + """ + if not reports: + return ThresholdRecommendation( + fail_threshold=None, + numeric_tolerance=None, + confidence="low", + sample_size=0, + reasoning=["No reports provided — cannot compute thresholds."], + percentile_used=percentile_level, + ) + + divergence_rates: list[float] = [] + logprob_gaps: list[float] = [] + total_samples = 0 + + for report in reports: + divergence_rates.append(report.divergence_rate) + total_samples += report.total_samples + for result in report.results: + if result.logprob_gap is not None and not result.exact_match: + logprob_gaps.append(result.logprob_gap) + + reasoning: list[str] = [] + + # Fail threshold recommendation + fail_threshold: float | None = None + if divergence_rates: + p_val = _percentile(divergence_rates, percentile_level) + # Round up slightly to give headroom + fail_threshold = round(min(p_val * 1.1 + 0.005, 1.0), 3) + reasoning.append( + f"Observed divergence rates: min={min(divergence_rates):.3f}, " + f"max={max(divergence_rates):.3f}, " + f"p{int(percentile_level * 100)}={p_val:.3f} " + f"→ recommended fail_threshold={fail_threshold:.3f}" + ) + + # Numeric tolerance recommendation + numeric_tolerance: float | None = None + if logprob_gaps: + p_val = _percentile(logprob_gaps, percentile_level) + numeric_tolerance = round(p_val, 4) + reasoning.append( + f"Observed logprob gaps at divergence: min={min(logprob_gaps):.4f}, " + f"max={max(logprob_gaps):.4f}, " + f"p{int(percentile_level * 100)}={p_val:.4f} " + f"→ recommended numeric_tolerance={numeric_tolerance:.4f}" + ) + else: + reasoning.append("No logprob gap data available — cannot recommend numeric_tolerance.") + + # Confidence assessment + if total_samples >= 500 and len(reports) >= 3: + confidence = "high" + elif total_samples >= 100 or len(reports) >= 2: + confidence = "medium" + else: + confidence = "low" + + reasoning.append( + f"Analyzed {len(reports)} report(s) with {total_samples} total samples " + f"→ confidence: {confidence}" + ) + + return ThresholdRecommendation( + fail_threshold=fail_threshold, + numeric_tolerance=numeric_tolerance, + confidence=confidence, + sample_size=total_samples, + reasoning=reasoning, + divergence_rates=divergence_rates, + logprob_gaps=logprob_gaps, + percentile_used=percentile_level, + ) + + +def load_reports(paths: list[str]) -> list[BatchReport]: + """Load multiple batch reports from file paths.""" + reports: list[BatchReport] = [] + for p in paths: + try: + reports.append(load_report(p)) + except Exception as exc: + logger.warning("Failed to load report %s: %s", p, exc) + return reports + + +def format_recommendations(rec: ThresholdRecommendation) -> str: + """Format recommendations as a human-readable string.""" + lines: list[str] = [] + lines.append("═══ Threshold Recommendations ═══") + lines.append("") + + if rec.fail_threshold is not None: + lines.append(f" fail_threshold: {rec.fail_threshold:.3f}") + else: + lines.append(" fail_threshold: (no data)") + + if rec.numeric_tolerance is not None: + lines.append(f" numeric_tolerance: {rec.numeric_tolerance:.4f}") + else: + lines.append(" numeric_tolerance: (no data)") + + lines.append(f" confidence: {rec.confidence}") + lines.append(f" sample_size: {rec.sample_size}") + lines.append(f" percentile: p{int(rec.percentile_used * 100)}") + lines.append("") + + if rec.divergence_rates: + lines.append(f" Divergence rates: {', '.join(f'{r:.3f}' for r in rec.divergence_rates)}") + if rec.logprob_gaps: + n = len(rec.logprob_gaps) + lines.append(f" Logprob gap samples: {n}") + + lines.append("") + lines.append("Reasoning:") + for r in rec.reasoning: + lines.append(f" • {r}") + + return "\n".join(lines) diff --git a/src/xpyd_acc/cli/__init__.py b/src/xpyd_acc/cli/__init__.py index 82e2c9e..f4f8bee 100644 --- a/src/xpyd_acc/cli/__init__.py +++ b/src/xpyd_acc/cli/__init__.py @@ -35,6 +35,7 @@ _run_ab_test, _run_aggregate, _run_annotate, + _run_auto_threshold, _run_cluster, _run_diff, _run_explain, @@ -129,6 +130,7 @@ def main(argv: list[str] | None = None) -> None: "config": lambda: _run_config(args), "profiles": lambda: _run_profiles(config), "completion": lambda: _run_completion(args, parser), + "auto-threshold": lambda: _run_auto_threshold(args), } if args.command in _early: diff --git a/src/xpyd_acc/cli/parsers.py b/src/xpyd_acc/cli/parsers.py index 3d4bff4..eb8dde3 100644 --- a/src/xpyd_acc/cli/parsers.py +++ b/src/xpyd_acc/cli/parsers.py @@ -48,6 +48,7 @@ def register_all(sub: argparse._SubParsersAction) -> None: _register_serve(sub) _register_prometheus(sub) _register_grafana_dashboard(sub) + _register_auto_threshold(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") @@ -574,3 +575,22 @@ def _register_grafana_dashboard(sub): "--title", default="xPyD-acc Divergence Dashboard", help="Dashboard title", ) + + +def _register_auto_threshold(sub): + at = sub.add_parser( + "auto-threshold", + help="Recommend fail-threshold and numeric-tolerance from historical reports", + ) + at.add_argument( + "--reports", nargs="+", required=True, + help="Paths to batch report JSON files", + ) + at.add_argument( + "--percentile", type=float, default=0.95, + help="Percentile for threshold recommendation (default: 0.95)", + ) + at.add_argument( + "--json", default=None, + help="Export recommendations as JSON to this path", + ) diff --git a/src/xpyd_acc/cli/report.py b/src/xpyd_acc/cli/report.py index cb12044..3464999 100644 --- a/src/xpyd_acc/cli/report.py +++ b/src/xpyd_acc/cli/report.py @@ -378,3 +378,26 @@ def _run_grafana_dashboard(args: argparse.Namespace) -> None: Path(args.output).write_text(dashboard.to_json(), encoding="utf-8") print(f"Grafana dashboard written to {args.output}") + + +def _run_auto_threshold(args: argparse.Namespace) -> None: + """Analyze historical reports and recommend thresholds.""" + import json + from pathlib import Path + + from xpyd_acc.auto_threshold import ( + analyze_thresholds, + format_recommendations, + load_reports, + ) + + reports = load_reports(args.reports) + rec = analyze_thresholds(reports, percentile_level=args.percentile) + + print(format_recommendations(rec)) + + if args.json: + Path(args.json).write_text( + json.dumps(rec.to_dict(), indent=2), encoding="utf-8" + ) + print(f"\nRecommendations exported to {args.json}") diff --git a/tests/test_auto_threshold.py b/tests/test_auto_threshold.py new file mode 100644 index 0000000..6492747 --- /dev/null +++ b/tests/test_auto_threshold.py @@ -0,0 +1,232 @@ +"""Tests for auto_threshold module.""" + +from __future__ import annotations + +import json +from pathlib import Path + +from xpyd_acc.auto_threshold import ( + ThresholdRecommendation, + _percentile, + analyze_thresholds, + format_recommendations, + load_reports, +) +from xpyd_acc.batch_compare import BatchReport, SampleResult + + +def _make_result( + match: bool = True, + logprob_gap: float | None = None, + sample_id: str = "s1", +) -> SampleResult: + return SampleResult( + sample_id=sample_id, + prompt="test", + baseline_output="a", + target_output="a" if match else "b", + exact_match=match, + first_divergence_index=None if match else 5, + baseline_logprob_at_divergence=None, + target_logprob_at_divergence=None, + logprob_gap=logprob_gap, + classification="match" if match else "likely_bug", + context_length=10, + ) + + +def _make_report( + divergence_rate: float, + total: int = 100, + logprob_gaps: list[float] | None = None, +) -> BatchReport: + divergent = int(total * divergence_rate) + match = total - divergent + results: list[SampleResult] = [] + gaps = logprob_gaps or [] + for i in range(divergent): + gap = gaps[i] if i < len(gaps) else 0.05 + results.append(_make_result(match=False, logprob_gap=gap, sample_id=f"d{i}")) + for i in range(match): + results.append(_make_result(match=True, sample_id=f"m{i}")) + return BatchReport( + total_samples=total, + divergent_samples=divergent, + match_samples=match, + divergence_rate=divergence_rate, + results=results, + ) + + +class TestPercentile: + def test_basic(self): + assert _percentile([1, 2, 3, 4, 5], 0.5) == 3.0 + + def test_p95(self): + data = list(range(1, 101)) + p = _percentile(data, 0.95) + assert 95 <= p <= 96 + + def test_empty(self): + assert _percentile([], 0.5) == 0.0 + + def test_single(self): + assert _percentile([42], 0.5) == 42.0 + + +class TestAnalyzeThresholds: + def test_empty_reports(self): + rec = analyze_thresholds([]) + assert rec.fail_threshold is None + assert rec.confidence == "low" + assert rec.sample_size == 0 + + def test_single_report(self): + report = _make_report(0.1, total=50, logprob_gaps=[0.02, 0.04, 0.06, 0.08, 0.1]) + rec = analyze_thresholds([report]) + assert rec.fail_threshold is not None + assert rec.fail_threshold > 0.1 + assert rec.numeric_tolerance is not None + assert rec.confidence == "low" # only 50 samples, 1 report + assert rec.sample_size == 50 + + def test_multiple_reports_high_confidence(self): + reports = [ + _make_report(0.05, total=200, logprob_gaps=[0.01] * 10), + _make_report(0.08, total=200, logprob_gaps=[0.02] * 16), + _make_report(0.03, total=200, logprob_gaps=[0.005] * 6), + ] + rec = analyze_thresholds(reports) + assert rec.confidence == "high" + assert rec.sample_size == 600 + assert rec.fail_threshold is not None + assert len(rec.divergence_rates) == 3 + + def test_no_logprob_gaps(self): + report = _make_report(0.0, total=100) + rec = analyze_thresholds([report]) + assert rec.numeric_tolerance is None + assert "cannot recommend numeric_tolerance" in rec.reasoning[-2].lower() or \ + any("cannot recommend" in r.lower() for r in rec.reasoning) + + def test_custom_percentile(self): + reports = [_make_report(0.1, total=100, logprob_gaps=[0.05] * 10)] + rec_90 = analyze_thresholds(reports, percentile_level=0.90) + rec_99 = analyze_thresholds(reports, percentile_level=0.99) + assert rec_90.percentile_used == 0.90 + assert rec_99.percentile_used == 0.99 + + +class TestThresholdRecommendation: + def test_to_dict(self): + rec = ThresholdRecommendation( + fail_threshold=0.1, + numeric_tolerance=0.05, + confidence="high", + sample_size=500, + reasoning=["test"], + divergence_rates=[0.05, 0.1], + logprob_gaps=[0.01, 0.02], + percentile_used=0.95, + ) + d = rec.to_dict() + assert d["fail_threshold"] == 0.1 + assert d["numeric_tolerance"] == 0.05 + assert d["confidence"] == "high" + assert d["sample_size"] == 500 + assert len(d["divergence_rates"]) == 2 + + def test_json_serializable(self): + rec = ThresholdRecommendation( + fail_threshold=0.1, + numeric_tolerance=None, + confidence="low", + sample_size=10, + reasoning=["r1"], + ) + s = json.dumps(rec.to_dict()) + loaded = json.loads(s) + assert loaded["fail_threshold"] == 0.1 + + +class TestFormatRecommendations: + def test_format_with_data(self): + rec = ThresholdRecommendation( + fail_threshold=0.1, + numeric_tolerance=0.05, + confidence="medium", + sample_size=200, + reasoning=["reason 1", "reason 2"], + divergence_rates=[0.05, 0.08], + logprob_gaps=[0.01] * 5, + ) + out = format_recommendations(rec) + assert "0.100" in out + assert "0.0500" in out + assert "medium" in out + assert "reason 1" in out + + def test_format_no_data(self): + rec = ThresholdRecommendation( + fail_threshold=None, + numeric_tolerance=None, + confidence="low", + sample_size=0, + reasoning=["No reports"], + ) + out = format_recommendations(rec) + assert "(no data)" in out + + +class TestLoadReports: + def test_load_valid(self, tmp_path: Path): + report = _make_report(0.1, total=10) + p = tmp_path / "r.json" + p.write_text(report.to_json(), encoding="utf-8") + loaded = load_reports([str(p)]) + assert len(loaded) == 1 + assert loaded[0].total_samples == 10 + + def test_load_missing_file(self): + loaded = load_reports(["/nonexistent/report.json"]) + assert len(loaded) == 0 + + def test_load_mixed(self, tmp_path: Path): + report = _make_report(0.05, total=20) + p = tmp_path / "good.json" + p.write_text(report.to_json(), encoding="utf-8") + loaded = load_reports([str(p), "/bad/path.json"]) + assert len(loaded) == 1 + + +class TestCLIIntegration: + def test_auto_threshold_cli(self, tmp_path: Path): + from xpyd_acc.cli import main + + report = _make_report(0.1, total=50, logprob_gaps=[0.03, 0.05, 0.07, 0.04, 0.06]) + rp = tmp_path / "report.json" + rp.write_text(report.to_json(), encoding="utf-8") + jp = tmp_path / "out.json" + + main(["auto-threshold", "--reports", str(rp), "--json", str(jp)]) + + assert jp.exists() + data = json.loads(jp.read_text(encoding="utf-8")) + assert "fail_threshold" in data + assert "numeric_tolerance" in data + + def test_auto_threshold_custom_percentile(self, tmp_path: Path): + from xpyd_acc.cli import main + + report = _make_report(0.2, total=30, logprob_gaps=[0.1] * 6) + rp = tmp_path / "report.json" + rp.write_text(report.to_json(), encoding="utf-8") + jp = tmp_path / "out.json" + + main([ + "auto-threshold", "--reports", str(rp), + "--percentile", "0.90", "--json", str(jp), + ]) + + data = json.loads(jp.read_text(encoding="utf-8")) + assert data["percentile_used"] == 0.90