diff --git a/src/evaltrust/api.py b/src/evaltrust/api.py index 39661f7..4d860bb 100644 --- a/src/evaltrust/api.py +++ b/src/evaltrust/api.py @@ -47,6 +47,10 @@ def audit( run_aware: bool = False, run_aware_future_runs: int | None = None, correction: str = "bonferroni", + # --- efficiency (advisory; absent when not supplied) --- + token_count_data: "EvalData | None" = None, + latency_data: "EvalData | None" = None, + latency_unit: str = "ms", # --- config passthrough (takes precedence over loose kwargs) --- config: "AuditConfig | None" = None, ) -> AuditReport: @@ -83,6 +87,19 @@ def audit( correction: Multiple-comparison correction for suite audits: ``"bonferroni"``, ``"holm"``, or ``"none"`` (default ``"bonferroni"``). + token_count_data: + Optional :class:`EvalData` whose ``scores`` carry per-example token + counts for the same two models. When supplied, an advisory + ``Efficiency`` finding is added that shows the token-count ratio + alongside the quality delta. Does not change the verdict level. + latency_data: + Optional :class:`EvalData` whose ``scores`` carry per-example latency + values for the same two models. When supplied, an advisory + ``Efficiency`` finding is added. Does not change the verdict level. + latency_unit: + Unit label for latency values (default ``"ms"``). Pass ``"s"`` if + the caller stores seconds, ``"us"`` for microseconds, etc. Used + verbatim in the finding text so the output always matches the data. config: A fully built :class:`AuditConfig`. When supplied, all loose statistical kwargs above are ignored and the config is used directly. @@ -103,7 +120,9 @@ def audit( correction=correction, ) - kw = dict(config=config, threshold=threshold, slice_by=slice_by) + kw = dict(config=config, threshold=threshold, slice_by=slice_by, + token_count_data=token_count_data, latency_data=latency_data, + latency_unit=latency_unit) if isinstance(source, EvalData): return run_audit(source, model_a=model_a, model_b=model_b, **kw) diff --git a/src/evaltrust/audit/efficiency.py b/src/evaltrust/audit/efficiency.py new file mode 100644 index 0000000..9152cbd --- /dev/null +++ b/src/evaltrust/audit/efficiency.py @@ -0,0 +1,365 @@ +"""Efficiency audit -- cost and latency alongside quality. + +Advisory-only: the findings never change the verdict level (status is always +PASS or SKIP). The pillar is silently absent when no cost or latency data is +present, so default output for quality-only files is unchanged. + +The findings make the quality/cost tradeoff explicit: + + Efficiency + ok model_b uses 3.2x the tokens of model_a for a +4.1 pt quality gain + +rather than leaving it as vague advice text ("decide on cost or speed"). + +Data flow +--------- +The caller passes separate ``EvalData`` objects for token counts and for +latency, each keyed by model -- the same shape as the quality ``EvalData``. +This keeps the quality audit's ``EvalData`` clean and requires no schema +changes to ``Example``. + +The adapter layer (e.g. the MLflow adapter) already reads ``token_count`` +and ``latency`` as named metric columns; the CLI or the Python API can pass +those datasets in alongside the quality dataset. +""" + +from __future__ import annotations + +import math + +import numpy as np + +from ..core.schema import EvalData, Finding, Status + +PILLAR = "Efficiency" + + +def audit_efficiency( + quality_data: EvalData, + model_a: str, + model_b: str, + *, + token_count_data: EvalData | None = None, + latency_data: EvalData | None = None, + latency_unit: str = "ms", +) -> list[Finding]: + """Return advisory efficiency findings when cost or latency data is present. + + Parameters + ---------- + quality_data: + The quality ``EvalData`` already used by the other audit checks. Used + only to read the mean quality scores for each model so the quality delta + can be shown alongside the cost/latency delta. + model_a, model_b: + The two models being compared (same labels as the quality audit). + token_count_data: + Optional ``EvalData`` whose ``scores`` carry per-example token counts + for the same two models. When ``None`` the token-count finding is + skipped. + latency_data: + Optional ``EvalData`` whose ``scores`` carry per-example latency + values for the same two models. When ``None`` the latency finding is + skipped. + latency_unit: + The unit label for latency values (default ``"ms"``). Pass ``"s"`` + if the caller stores seconds, ``"us"`` for microseconds, etc. The + value is used verbatim in the ``how_detected`` text so the finding + always reflects the actual unit of the data. + + Returns + ------- + list[Finding] + Zero findings when neither dataset is supplied. One finding per + dataset that is supplied. All findings have ``status = Status.PASS`` + (informational) so they never lower the confidence verdict. + """ + findings: list[Finding] = [] + + # Mean quality scores (for the tradeoff narrative). + mean_q_a = _mean(quality_data, model_a) + mean_q_b = _mean(quality_data, model_b) + quality_delta = mean_q_b - mean_q_a # positive means B is better + + # Guard: if quality_delta is NaN (e.g. preference-only data where _mean + # finds no scores for a model), we cannot produce a meaningful tradeoff + # narrative and must not emit NaN into details (not JSON-serialisable by + # strict parsers). Treat as "quality data unavailable" and skip both + # findings -- the quality audit itself will flag the missing scores. + if math.isnan(quality_delta): + return findings + + if token_count_data is not None: + f = _token_finding(token_count_data, model_a, model_b, + quality_delta) + if f is not None: + findings.append(f) + + if latency_data is not None: + f = _latency_finding(latency_data, model_a, model_b, + quality_delta, latency_unit) + if f is not None: + findings.append(f) + + return findings + + +# --------------------------------------------------------------------------- # +# Internal helpers +# --------------------------------------------------------------------------- # + +def _mean(data: EvalData, model: str) -> float: + vals = [ex.scores[model] for ex in data.examples if model in ex.scores] + return float(np.mean(vals)) if vals else float("nan") + + +def _ratio_str(numerator: float, denominator: float) -> str: + """Return 'Nx' where N = numerator / denominator, formatted compactly.""" + if denominator == 0: + return "infinitely" + return f"{numerator / denominator:.2g}x" + + +def _quality_delta_str(delta: float) -> str: + """'+4.1 pt quality gain' or '-2.0 pt quality drop' or 'no quality change'. + + Uses the signed delta directly so drops are negative and gains are positive. + """ + if abs(delta) < 1e-9: + return "no quality change" + direction = "gain" if delta > 0 else "drop" + sign = "+" if delta > 0 else "-" + return f"{sign}{abs(delta) * 100:.1f} pt quality {direction}" + + +def _token_finding( + token_data: EvalData, + model_a: str, + model_b: str, + quality_delta: float, +) -> Finding | None: + mean_tok_a = _mean(token_data, model_a) + mean_tok_b = _mean(token_data, model_b) + + if np.isnan(mean_tok_a) or np.isnan(mean_tok_b): + return None # data present but no overlap with these models; skip silently + + q_str = _quality_delta_str(quality_delta) + + # ratio_b_over_a: how many times more tokens does B use vs A? + # > 1 means B is more expensive; < 1 means B is cheaper. + ratio_b_over_a = _ratio_str(mean_tok_b, mean_tok_a) # mean_tok_b / mean_tok_a + ratio_a_over_b = _ratio_str(mean_tok_a, mean_tok_b) # mean_tok_a / mean_tok_b (>1 when B cheaper) + + tok_equal = math.isclose(mean_tok_a, mean_tok_b, rel_tol=1e-9) + + if tok_equal: + comparison = f"{model_b} uses the same number of tokens as {model_a}" + elif mean_tok_b > mean_tok_a: + # B costs more tokens + comparison = f"{model_b} uses {ratio_b_over_a} the tokens of {model_a}" + else: + # B is cheaper -- show how much cheaper B is relative to A (ratio > 1) + comparison = f"{model_b} uses {ratio_a_over_b} fewer tokens than {model_a}" + + title = f"Token cost: {comparison}" + how = ( + f"{model_a} averaged {mean_tok_a:.1f} tokens/example; " + f"{model_b} averaged {mean_tok_b:.1f} tokens/example. " + f"Quality delta: {q_str}." + ) + + if tok_equal: + # Cost is equal -- recommendation driven purely by quality delta. + if abs(quality_delta) < 1e-9: + fix = ( + f"The models are equal on both quality and token cost. " + f"Either model is a valid choice." + ) + elif quality_delta > 0: + fix = ( + f"The models cost the same number of tokens. {model_b} is " + f"better on quality ({q_str}) -- prefer {model_b}." + ) + else: + fix = ( + f"The models cost the same number of tokens. {model_b} is " + f"worse on quality ({q_str}) -- prefer {model_a}." + ) + elif abs(quality_delta) < 1e-9: + if mean_tok_b > mean_tok_a: + fix = ( + f"The models are equivalent on quality. {model_b} costs " + f"{ratio_b_over_a} the tokens -- prefer {model_a}." + ) + else: + fix = ( + f"The models are equivalent on quality. {model_b} uses " + f"{ratio_a_over_b} fewer tokens -- prefer {model_b}." + ) + elif quality_delta > 0: + # B is better on quality + if mean_tok_b > mean_tok_a: + fix = ( + f"{model_b} is better on quality ({q_str}) but costs " + f"{ratio_b_over_a} the tokens. Decide whether the quality " + f"gain justifies the extra cost." + ) + else: + fix = ( + f"{model_b} is both better on quality ({q_str}) and uses " + f"{ratio_a_over_b} fewer tokens. Prefer {model_b}." + ) + else: + # B is worse on quality + if mean_tok_b > mean_tok_a: + fix = ( + f"{model_b} is worse on quality ({q_str}) and costs " + f"{ratio_b_over_a} the tokens. Prefer {model_a}." + ) + else: + fix = ( + f"{model_b} is worse on quality ({q_str}) but uses " + f"{ratio_a_over_b} fewer tokens. Decide whether the cost " + f"saving justifies the quality drop." + ) + + tok_ratio = mean_tok_b / mean_tok_a if mean_tok_a != 0 else None + return Finding( + pillar=PILLAR, + title=title, + status=Status.PASS, # advisory -- never lowers the verdict + why=( + "A model that is marginally better on quality but uses significantly " + "more tokens may not be worth the extra cost in production. Showing " + "the ratio makes the tradeoff concrete." + ), + how_detected=how, + how_to_fix=fix, + details={ + "check": "efficiency_tokens", + "model_a": model_a, + "model_b": model_b, + "mean_tokens_a": mean_tok_a, + "mean_tokens_b": mean_tok_b, + "token_ratio_b_over_a": tok_ratio, + "quality_delta": quality_delta, + }, + ) + + +def _latency_finding( + latency_data: EvalData, + model_a: str, + model_b: str, + quality_delta: float, + latency_unit: str = "ms", +) -> Finding | None: + mean_lat_a = _mean(latency_data, model_a) + mean_lat_b = _mean(latency_data, model_b) + + if np.isnan(mean_lat_a) or np.isnan(mean_lat_b): + return None + + q_str = _quality_delta_str(quality_delta) + + # ratio_b_over_a: how many times slower is B vs A? + # > 1 means B is slower; < 1 means B is faster. + ratio_b_over_a = _ratio_str(mean_lat_b, mean_lat_a) # mean_lat_b / mean_lat_a + ratio_a_over_b = _ratio_str(mean_lat_a, mean_lat_b) # mean_lat_a / mean_lat_b (>1 when B faster) + + lat_equal = math.isclose(mean_lat_a, mean_lat_b, rel_tol=1e-9) + + if lat_equal: + comparison = f"{model_b} has the same latency as {model_a}" + elif mean_lat_b > mean_lat_a: + # B is slower + comparison = f"{model_b} is {ratio_b_over_a} slower than {model_a}" + else: + # B is faster -- show how much faster B is relative to A (ratio > 1) + comparison = f"{model_b} is {ratio_a_over_b} faster than {model_a}" + + title = f"Latency: {comparison}" + # Use caller-supplied unit so the label matches the data (ms, s, us, etc.) + how = ( + f"{model_a} averaged {mean_lat_a:.1f} {latency_unit}/example; " + f"{model_b} averaged {mean_lat_b:.1f} {latency_unit}/example. " + f"Quality delta: {q_str}." + ) + + if lat_equal: + # Latency is equal -- recommendation driven purely by quality delta. + if abs(quality_delta) < 1e-9: + fix = ( + f"The models are equal on both quality and latency. " + f"Either model is a valid choice." + ) + elif quality_delta > 0: + fix = ( + f"The models have the same latency. {model_b} is better on " + f"quality ({q_str}) -- prefer {model_b}." + ) + else: + fix = ( + f"The models have the same latency. {model_b} is worse on " + f"quality ({q_str}) -- prefer {model_a}." + ) + elif abs(quality_delta) < 1e-9: + if mean_lat_b > mean_lat_a: + fix = ( + f"The models are equivalent on quality. {model_b} is " + f"{ratio_b_over_a} slower -- prefer {model_a}." + ) + else: + fix = ( + f"The models are equivalent on quality. {model_b} is " + f"{ratio_a_over_b} faster -- prefer {model_b}." + ) + elif quality_delta > 0: + # B is better on quality + if mean_lat_b > mean_lat_a: + fix = ( + f"{model_b} is better on quality ({q_str}) but {ratio_b_over_a} " + f"slower. Decide whether the latency increase is acceptable " + f"for the quality gain." + ) + else: + fix = ( + f"{model_b} is both better on quality ({q_str}) and " + f"{ratio_a_over_b} faster. Prefer {model_b}." + ) + else: + # B is worse on quality + if mean_lat_b > mean_lat_a: + fix = ( + f"{model_b} is worse on quality ({q_str}) and {ratio_b_over_a} " + f"slower. Prefer {model_a}." + ) + else: + fix = ( + f"{model_b} is worse on quality ({q_str}) but {ratio_a_over_b} " + f"faster. Decide whether the speed gain justifies the quality drop." + ) + + lat_ratio = mean_lat_b / mean_lat_a if mean_lat_a != 0 else None + return Finding( + pillar=PILLAR, + title=title, + status=Status.PASS, # advisory -- never lowers the verdict + why=( + "A model that is marginally better on quality but noticeably slower " + "may hurt user experience in latency-sensitive deployments. Showing " + "the ratio makes the tradeoff concrete." + ), + how_detected=how, + how_to_fix=fix, + details={ + "check": "efficiency_latency", + "model_a": model_a, + "model_b": model_b, + "mean_latency_a": mean_lat_a, + "mean_latency_b": mean_lat_b, + "latency_ratio_b_over_a": lat_ratio, + "quality_delta": quality_delta, + }, + ) diff --git a/src/evaltrust/audit/runner.py b/src/evaltrust/audit/runner.py index fc7f839..6d5ecb5 100644 --- a/src/evaltrust/audit/runner.py +++ b/src/evaltrust/audit/runner.py @@ -10,6 +10,7 @@ from ..core.schema import EvalData, Finding, Status from ..versions import METHODOLOGY_VERSION, SCHEMA_VERSION from .allpairs import audit_all_pairs +from .efficiency import audit_efficiency from .bayesian import audit_bayesian_win_probability from .predictive_rerun import audit_predictive_rerun from .win_rate import audit_win_rate @@ -144,9 +145,12 @@ def run_audit( threshold: float | None = None, config: "AuditConfig | None" = None, slice_by: str | None = None, + token_count_data: "EvalData | None" = None, + latency_data: "EvalData | None" = None, + latency_unit: str = "ms", + observed_ranges: "dict[str, dict[str, float | int]] | None" = None, *, significant: bool | None = None, - observed_ranges: dict[str, dict[str, float | int]] | None = None, ) -> AuditReport: # When no config is given, build one from the loose kwargs. cfg = config or AuditConfig(alpha=alpha, equivalence_margin=equivalence_margin, @@ -157,7 +161,11 @@ def run_audit( # threshold or a lone model -> single. if model_a is not None and model_b is not None: return _comparison(data, model_a, model_b, cfg, significant=significant, - slice_by=slice_by, observed_ranges=observed_ranges) + slice_by=slice_by, + token_count_data=token_count_data, + latency_data=latency_data, + latency_unit=latency_unit, + observed_ranges=observed_ranges) if threshold is not None: if data.has_preferences and not any(ex.scores for ex in data.examples): raise ValueError( @@ -172,7 +180,11 @@ def run_audit( return _single(data, model_a or data.models[0], None, cfg) model_a, model_b = _pick_models(data) return _comparison(data, model_a, model_b, cfg, significant=significant, - slice_by=slice_by, observed_ranges=observed_ranges) + slice_by=slice_by, + token_count_data=token_count_data, + latency_data=latency_data, + latency_unit=latency_unit, +) def _strongest(data: EvalData) -> str: @@ -182,7 +194,9 @@ def _strongest(data: EvalData) -> str: def _comparison(data, model_a, model_b, cfg, significant=None, - slice_by=None, observed_ranges=None) -> AuditReport: + slice_by=None, token_count_data=None, + latency_data=None, latency_unit="ms", + observed_ranges=None) -> AuditReport: differences = data.differences(model_a, model_b) has_pair_scores = any( model_a in ex.scores or model_b in ex.scores for ex in data.examples) @@ -310,6 +324,14 @@ def _comparison(data, model_a, model_b, cfg, significant=None, "preference_only" if preference_only else "no_paired_scores", )) + if token_count_data is not None or latency_data is not None: + findings += audit_efficiency( + data, model_a, model_b, + token_count_data=token_count_data, + latency_data=latency_data, + latency_unit=latency_unit, + ) + return AuditReport( model_a=model_a, model_b=model_b, n_examples=data.n_examples, source_format=data.source_format, findings=findings, diff --git a/src/evaltrust/cli.py b/src/evaltrust/cli.py index acaa799..c4741d8 100644 --- a/src/evaltrust/cli.py +++ b/src/evaltrust/cli.py @@ -12,6 +12,7 @@ from __future__ import annotations import json +from collections import OrderedDict from dataclasses import replace from importlib.metadata import PackageNotFoundError, version as package_version from pathlib import Path @@ -327,18 +328,87 @@ def audit( suite_report = None report = None try: + _EFFICIENCY_KEYS = {"token_count", "latency"} + if len(results) == 2: data = load_comparison(results, label_a=model_a, label_b=model_b) # Two input files already define one pair. Keep all-pairs scoped to # a single file that declares the model family. + # Also try to extract token_count and latency from each file's suite + # so they can be passed as efficiency side-channels. + token_count_data = None + latency_data = None + try: + suite_a = load_suite(results[0]) + suite_b = load_suite(results[1]) + # Merge token_count from both files if present in both. + if "token_count" in suite_a and "token_count" in suite_b: + from .core.pairing import primary_model + la = primary_model(suite_a["token_count"]) + lb = primary_model(suite_b["token_count"]) + lbl_a = (model_a or data.models[0]) + lbl_b = (model_b or data.models[1]) + from .core.pairing import merge_two as _merge + token_count_data = _merge( + suite_a["token_count"], suite_b["token_count"], + lbl_a, lbl_b) + if "latency" in suite_a and "latency" in suite_b: + lbl_a = (model_a or data.models[0]) + lbl_b = (model_b or data.models[1]) + from .core.pairing import merge_two as _merge + latency_data = _merge( + suite_a["latency"], suite_b["latency"], + lbl_a, lbl_b) + except Exception: + # Efficiency extraction is best-effort: if anything goes wrong + # (format doesn't support suites, pairing fails, etc.), just + # proceed without efficiency findings. + token_count_data = None + latency_data = None + report = run_audit( data, config=replace(cfg, all_pairs=False), - slice_by=slice_by) + slice_by=slice_by, + token_count_data=token_count_data, + latency_data=latency_data) else: suite = load_suite(results[0]) if len(suite) > 1: - suite_report = audit_suite( - suite, model_a=model_a, model_b=model_b, config=cfg) + # Extract operational columns (token_count, latency) before + # deciding whether this is a multi-metric suite or a single + # quality metric with cost/latency side-channels. + # The MLflow adapter (and any future adapter that follows the + # same convention) puts these in the suite keyed by their bare + # names. We pull them out here so run_audit receives them as + # first-class efficiency datasets rather than treating them as + # quality metrics. + token_count_data = suite.get("token_count") + latency_data = suite.get("latency") + # Quality suite: everything except the operational columns. + quality_suite = OrderedDict( + (k, v) for k, v in suite.items() if k not in _EFFICIENCY_KEYS + ) + if len(quality_suite) > 1: + # Genuine multi-metric suite: audit as a suite. + # Efficiency data is advisory; the suite path doesn't yet + # thread it through, so we skip it silently here and let + # the suite report stand on its own. + suite_report = audit_suite( + quality_suite, model_a=model_a, model_b=model_b, config=cfg) + elif len(quality_suite) == 1: + # Single quality metric + optional cost/latency side-channels. + data = next(iter(quality_suite.values())) + report = run_audit(data, model_a=model_a, model_b=model_b, + threshold=threshold, config=cfg, + slice_by=slice_by, + token_count_data=token_count_data, + latency_data=latency_data) + else: + # Suite was only operational columns (no quality metric). + # Fall back to the original suite path so the user gets a + # useful error rather than a silent empty report. + suite_report = audit_suite( + suite, model_a=model_a, model_b=model_b, config=cfg) else: data = next(iter(suite.values())) report = run_audit(data, model_a=model_a, model_b=model_b, diff --git a/tests/test_cli.py b/tests/test_cli.py index 0da0201..43a8933 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -740,3 +740,174 @@ def test_utf8_encoding_cli_audit(tmp_path): assert result.exception is None # Verify the file was correctly loaded and processed assert "A vs B" in result.stdout + + +# --------------------------------------------------------------------------- +# Efficiency pillar: CLI end-to-end wiring (issue #165) +# --------------------------------------------------------------------------- +# The efficiency pillar is wired automatically when the loaded data contains +# token_count or latency alongside a quality metric. Two real-world shapes +# are tested: +# +# 1. Two MLflow-style single-model files passed together +# (evaltrust audit runA.json runB.json) +# Each file has correctness/score + token_count + latency. +# +# 2. A single MLflow eval_results_table file with one quality metric column +# and bare token_count / latency columns. +# (evaltrust audit mlflow_run.json) +# This goes through load_suite → quality_suite path. + + +def _mlflow_single_model(tmp_path, name, quality_scores, token_counts, latency_ms): + """Build a minimal MLflow eval_results_table (single model per file).""" + columns = ["correctness/score", "token_count", "latency"] + data = list(zip(quality_scores, token_counts, latency_ms)) + raw = {"columns": columns, "data": [list(row) for row in data]} + p = tmp_path / name + p.write_text(json.dumps(raw)) + return str(p) + + +def test_cli_two_mlflow_files_shows_efficiency(tmp_path): + """Two MLflow single-model files: evaltrust audit runA.json runB.json + must show the Efficiency pillar automatically.""" + n = 60 + file_a = _mlflow_single_model( + tmp_path, "run_a.json", + quality_scores=[0.5] * n, + token_counts=[100] * n, + latency_ms=[200.0] * n, + ) + file_b = _mlflow_single_model( + tmp_path, "run_b.json", + quality_scores=[0.8] * n, + token_counts=[300] * n, + latency_ms=[600.0] * n, + ) + result = runner.invoke(app, ["audit", file_a, file_b, "--plain"]) + assert result.exit_code == 0, result.output + assert "Efficiency" in result.stdout + + +def test_cli_two_mlflow_files_token_finding(tmp_path): + """Token cost finding must appear in two-file MLflow comparison.""" + n = 60 + file_a = _mlflow_single_model( + tmp_path, "a.json", [0.5] * n, [100] * n, [200.0] * n) + file_b = _mlflow_single_model( + tmp_path, "b.json", [0.8] * n, [300] * n, [600.0] * n) + result = runner.invoke(app, ["audit", file_a, file_b, "--plain"]) + assert result.exit_code == 0, result.output + assert "Token cost" in result.stdout + + +def test_cli_two_mlflow_files_latency_finding(tmp_path): + """Latency finding must appear in two-file MLflow comparison.""" + n = 60 + file_a = _mlflow_single_model( + tmp_path, "a.json", [0.5] * n, [100] * n, [200.0] * n) + file_b = _mlflow_single_model( + tmp_path, "b.json", [0.8] * n, [300] * n, [600.0] * n) + result = runner.invoke(app, ["audit", file_a, file_b, "--plain"]) + assert result.exit_code == 0, result.output + assert "Latency" in result.stdout + + +def test_cli_two_mlflow_files_efficiency_does_not_change_verdict(tmp_path): + """Efficiency findings are advisory (PASS): they must not lower the verdict + or cause a non-zero exit with --strict.""" + n = 80 + file_a = _mlflow_single_model( + tmp_path, "a.json", [0.5] * n, [100] * n, [200.0] * n) + file_b = _mlflow_single_model( + tmp_path, "b.json", [0.85] * n, [500] * n, [800.0] * n) + result = runner.invoke(app, ["audit", file_a, file_b, "--strict", "--plain"]) + assert "Efficiency" in result.stdout + # High-confidence quality win + advisory efficiency = exit 0 + assert result.exit_code == 0 + + +def test_cli_two_mlflow_files_json_includes_efficiency(tmp_path): + """--json output must include Efficiency findings for two-file MLflow runs.""" + n = 60 + file_a = _mlflow_single_model( + tmp_path, "a.json", [0.5] * n, [100] * n, [200.0] * n) + file_b = _mlflow_single_model( + tmp_path, "b.json", [0.8] * n, [300] * n, [600.0] * n) + result = runner.invoke(app, ["audit", file_a, file_b, "--json"]) + assert result.exit_code == 0, result.output + data = json.loads(result.stdout) + efficiency = [f for f in data["findings"] if f.get("pillar") == "Efficiency"] + assert len(efficiency) >= 1 + + +def test_cli_quality_only_two_files_no_efficiency(tmp_path): + """Two files with no token_count or latency columns must not show Efficiency.""" + columns = ["correctness/score"] + raw_a = {"columns": columns, "data": [[0.5]] * 60} + raw_b = {"columns": columns, "data": [[0.8]] * 60} + fa = tmp_path / "a.json"; fa.write_text(json.dumps(raw_a)) + fb = tmp_path / "b.json"; fb.write_text(json.dumps(raw_b)) + result = runner.invoke(app, ["audit", str(fa), str(fb), "--plain"]) + assert result.exit_code == 0, result.output + assert "Efficiency" not in result.stdout + + +def test_cli_single_mlflow_file_with_efficiency(tmp_path): + """Single MLflow file (two quality cols + token_count + latency, two models). + Goes through the load_suite → quality_suite extraction path.""" + # Use the generic format so the adapter produces a suite with multiple + # metrics keyed by name. The generic adapter emits a 'metric' per score + # column when examples carry per-metric scores. + # Simplest correct shape: standard two-model file where the suite has one + # quality metric plus token_count and latency stored as separate examples. + # We use the MLflow split-table shape for a single model and check the + # single-file suite path works with the extracted side-channels. + n = 60 + # Single-model MLflow file with quality + efficiency columns. + columns = ["correctness/score", "token_count", "latency"] + data = [[0.7, 120, 250.0]] * n + raw = {"columns": columns, "data": data} + p = tmp_path / "mlflow.json" + p.write_text(json.dumps(raw)) + # Single-model file: goes through the suite path; only one model so the + # audit will produce a single-model threshold report (no comparison). + # We just check it doesn't crash and exits cleanly. + result = runner.invoke(app, ["audit", str(p), "--plain"]) + assert result.exit_code == 0, result.output + + +def test_cli_efficiency_quality_findings_unchanged(tmp_path): + """Adding token_count to a two-file comparison must not alter any quality + finding's status compared to files without token_count.""" + n = 60 + # Without efficiency columns + cols_q = ["correctness/score"] + raw_qa = {"columns": cols_q, "data": [[0.5]] * n} + raw_qb = {"columns": cols_q, "data": [[0.8]] * n} + qa = tmp_path / "qa.json"; qa.write_text(json.dumps(raw_qa)) + qb = tmp_path / "qb.json"; qb.write_text(json.dumps(raw_qb)) + + # With efficiency columns + file_a = _mlflow_single_model( + tmp_path, "ea.json", [0.5] * n, [100] * n, [200.0] * n) + file_b = _mlflow_single_model( + tmp_path, "eb.json", [0.8] * n, [300] * n, [600.0] * n) + + r1 = runner.invoke(app, ["audit", str(qa), str(qb), "--json"]) + r2 = runner.invoke(app, ["audit", file_a, file_b, "--json"]) + assert r1.exit_code == 0, r1.output + assert r2.exit_code == 0, r2.output + + d1 = json.loads(r1.stdout) + d2 = json.loads(r2.stdout) + # Compare statuses by pillar — titles include model names so they'll differ + # between runs, but statuses must be identical. + statuses_1 = sorted(f["status"] for f in d1["findings"] + if f.get("pillar") != "Efficiency") + statuses_2 = sorted(f["status"] for f in d2["findings"] + if f.get("pillar") != "Efficiency") + assert statuses_1 == statuses_2, ( + "Adding efficiency columns must not change quality finding statuses" + ) diff --git a/tests/test_efficiency.py b/tests/test_efficiency.py new file mode 100644 index 0000000..2c0de81 --- /dev/null +++ b/tests/test_efficiency.py @@ -0,0 +1,592 @@ +"""Tests for the Efficiency audit (issue #165). + +The efficiency findings are advisory-only: they appear when token_count or +latency data is present, but they never lower the confidence verdict. Default +output for quality-only files must be unchanged (no new findings, no verdict +change). +""" + +import pytest + +from evaltrust.audit.efficiency import audit_efficiency, PILLAR +from evaltrust.audit.runner import run_audit +from evaltrust.core.schema import EvalData, Example, Status + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def make_data(a_scores, b_scores, models=("A", "B")): + """Build a two-model EvalData from parallel score lists.""" + examples = [ + Example(id=str(i), scores={models[0]: float(a), models[1]: float(b)}) + for i, (a, b) in enumerate(zip(a_scores, b_scores)) + ] + return EvalData(models=list(models), examples=examples, + source_format="test", metadata={}) + + +def single_model_data(model, scores): + """Build a single-model EvalData (for cost/latency parallel datasets).""" + examples = [ + Example(id=str(i), scores={model: float(s)}) + for i, s in enumerate(scores) + ] + return EvalData(models=[model], examples=examples, + source_format="test", metadata={}) + + +def two_model_cost_data(a_costs, b_costs, models=("A", "B")): + """Build a cost/latency EvalData with per-example values for two models.""" + examples = [ + Example(id=str(i), scores={models[0]: float(a), models[1]: float(b)}) + for i, (a, b) in enumerate(zip(a_costs, b_costs)) + ] + return EvalData(models=list(models), examples=examples, + source_format="test", metadata={}) + + +def by_check(findings, check): + hits = [f for f in findings if f.details.get("check") == check] + return hits + + +# --------------------------------------------------------------------------- +# No data → no findings +# --------------------------------------------------------------------------- + +def test_no_efficiency_data_returns_empty(): + quality = make_data([0] * 50, [1] * 50) + findings = audit_efficiency(quality, "A", "B", + token_count_data=None, latency_data=None) + assert findings == [] + + +def test_no_efficiency_data_does_not_appear_in_run_audit(): + quality = make_data([0] * 50, [1] * 50) + report = run_audit(quality, model_a="A", model_b="B") + efficiency_findings = [f for f in report.findings if f.pillar == PILLAR] + assert efficiency_findings == [] + + +# --------------------------------------------------------------------------- +# Token count findings +# --------------------------------------------------------------------------- + +def test_token_count_finding_is_advisory_pass(): + quality = make_data([0.8] * 20, [0.9] * 20) + tokens = two_model_cost_data([100] * 20, [320] * 20) + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + tf = by_check(findings, "efficiency_tokens") + assert len(tf) == 1 + assert tf[0].status is Status.PASS + assert tf[0].pillar == PILLAR + + +def test_token_finding_details_contain_ratio(): + quality = make_data([0.8] * 10, [0.9] * 10) + tokens = two_model_cost_data([100] * 10, [300] * 10) + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + (tf,) = by_check(findings, "efficiency_tokens") + details = tf.details + assert details["mean_tokens_a"] == pytest.approx(100.0) + assert details["mean_tokens_b"] == pytest.approx(300.0) + assert details["token_ratio_b_over_a"] == pytest.approx(3.0) + + +def test_token_finding_shows_quality_delta(): + quality = make_data([0.7] * 10, [0.8] * 10) + tokens = two_model_cost_data([100] * 10, [300] * 10) + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + (tf,) = by_check(findings, "efficiency_tokens") + assert tf.details["quality_delta"] == pytest.approx(0.1) + # The "3x more tokens for a quality gain" tradeoff should be explicit. + assert "3" in tf.how_detected + assert "quality" in tf.how_detected.lower() + + +def test_token_finding_cheaper_and_better_recommends_b(): + quality = make_data([0.7] * 10, [0.9] * 10) + tokens = two_model_cost_data([300] * 10, [100] * 10) # B is cheaper + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + (tf,) = by_check(findings, "efficiency_tokens") + # B is better on quality AND cheaper → prefer B + assert "cheaper" in tf.how_to_fix.lower() or "prefer" in tf.how_to_fix.lower() + + +def test_token_finding_worse_and_more_expensive_recommends_a(): + quality = make_data([0.9] * 10, [0.7] * 10) + tokens = two_model_cost_data([100] * 10, [300] * 10) # B is expensive and worse + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + (tf,) = by_check(findings, "efficiency_tokens") + # B is worse AND pricier → prefer A + assert "A" in tf.how_to_fix + + +def test_token_finding_equivalent_quality_recommends_cheaper(): + quality = make_data([0.8] * 10, [0.8] * 10) # same quality + tokens = two_model_cost_data([100] * 10, [400] * 10) + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + (tf,) = by_check(findings, "efficiency_tokens") + assert "cheaper" in tf.how_to_fix.lower() or "prefer" in tf.how_to_fix.lower() + + +# --------------------------------------------------------------------------- +# Latency findings +# --------------------------------------------------------------------------- + +def test_latency_finding_is_advisory_pass(): + quality = make_data([0.8] * 20, [0.9] * 20) + latency = two_model_cost_data([200] * 20, [800] * 20) + findings = audit_efficiency(quality, "A", "B", latency_data=latency) + lf = by_check(findings, "efficiency_latency") + assert len(lf) == 1 + assert lf[0].status is Status.PASS + assert lf[0].pillar == PILLAR + + +def test_latency_finding_details(): + quality = make_data([0.8] * 10, [0.9] * 10) + latency = two_model_cost_data([200] * 10, [600] * 10) + findings = audit_efficiency(quality, "A", "B", latency_data=latency) + (lf,) = by_check(findings, "efficiency_latency") + assert lf.details["mean_latency_a"] == pytest.approx(200.0) + assert lf.details["mean_latency_b"] == pytest.approx(600.0) + assert lf.details["latency_ratio_b_over_a"] == pytest.approx(3.0) + + +def test_latency_finding_faster_and_better_recommends_b(): + quality = make_data([0.7] * 10, [0.9] * 10) + latency = two_model_cost_data([600] * 10, [200] * 10) # B is faster + findings = audit_efficiency(quality, "A", "B", latency_data=latency) + (lf,) = by_check(findings, "efficiency_latency") + assert "prefer" in lf.how_to_fix.lower() or "faster" in lf.how_to_fix.lower() + + +# --------------------------------------------------------------------------- +# Both token and latency together +# --------------------------------------------------------------------------- + +def test_both_token_and_latency_findings(): + quality = make_data([0.8] * 20, [0.9] * 20) + tokens = two_model_cost_data([100] * 20, [300] * 20) + latency = two_model_cost_data([200] * 20, [600] * 20) + findings = audit_efficiency(quality, "A", "B", + token_count_data=tokens, latency_data=latency) + assert len(by_check(findings, "efficiency_tokens")) == 1 + assert len(by_check(findings, "efficiency_latency")) == 1 + assert len(findings) == 2 + + +# --------------------------------------------------------------------------- +# Verdict is unchanged by efficiency findings +# --------------------------------------------------------------------------- + +def test_efficiency_findings_do_not_lower_verdict(): + """Efficiency findings are PASS and must never be the cause of a lower verdict. + + We verify that every Efficiency finding is Status.PASS (advisory), and that + removing efficiency findings from the verdict computation does not change the + reported verdict level — i.e. no Efficiency finding is a driver. + """ + import numpy as np + rng = np.random.default_rng(42) + # Realistic continuous scores: A ~ 0.5, B ~ 0.7, enough n to be conclusive. + a = list(rng.uniform(0.3, 0.7, 200)) + b = list(rng.uniform(0.5, 0.9, 200)) + quality = make_data(a, b) + tokens = two_model_cost_data([100] * 200, [300] * 200) + report = run_audit(quality, model_a="A", model_b="B", + token_count_data=tokens) + + # All efficiency findings must be advisory (PASS). + for f in report.findings: + if f.pillar == PILLAR: + assert f.status is Status.PASS + + # No Efficiency finding should be a verdict driver. + for f in report.verdict.drivers: + assert f.pillar != PILLAR + + +def test_efficiency_findings_do_not_alter_quality_only_report(): + """Adding efficiency data must not change any existing finding.""" + quality = make_data([0] * 50, [1] * 50) + report_no_eff = run_audit(quality, model_a="A", model_b="B") + tokens = two_model_cost_data([100] * 50, [300] * 50) + report_with_eff = run_audit(quality, model_a="A", model_b="B", + token_count_data=tokens) + + # All pre-existing findings (non-Efficiency pillar) must be unchanged. + old_checks = {(f.pillar, f.details.get("check")): f.status + for f in report_no_eff.findings} + for f in report_with_eff.findings: + if f.pillar == PILLAR: + continue + key = (f.pillar, f.details.get("check")) + assert key in old_checks, f"Unexpected new non-Efficiency finding: {key}" + assert f.status is old_checks[key] + + +# --------------------------------------------------------------------------- +# Missing model data → silent skip, no crash +# --------------------------------------------------------------------------- + +def test_token_data_missing_one_model_returns_no_finding(): + """If cost data only has one of the two models, skip silently.""" + quality = make_data([0.8] * 10, [0.9] * 10) + # Only model A in the token dataset + tokens = single_model_data("A", [100] * 10) + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + # NaN for B → should return no token finding + assert by_check(findings, "efficiency_tokens") == [] + + +def test_latency_data_missing_one_model_returns_no_finding(): + quality = make_data([0.8] * 10, [0.9] * 10) + latency = single_model_data("B", [500] * 10) + findings = audit_efficiency(quality, "A", "B", latency_data=latency) + assert by_check(findings, "efficiency_latency") == [] + + +# --------------------------------------------------------------------------- +# to_dict serialisability +# --------------------------------------------------------------------------- + +def test_token_finding_is_json_serialisable(): + import json + quality = make_data([0.8] * 10, [0.9] * 10) + tokens = two_model_cost_data([100] * 10, [300] * 10) + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + assert findings + d = findings[0].to_dict() + json.dumps(d) # must not raise + + +def test_latency_finding_is_json_serialisable(): + import json + quality = make_data([0.8] * 10, [0.9] * 10) + latency = two_model_cost_data([200] * 10, [600] * 10) + findings = audit_efficiency(quality, "A", "B", latency_data=latency) + assert findings + d = findings[0].to_dict() + json.dumps(d) # must not raise + + +# --------------------------------------------------------------------------- +# API-level smoke test (evaltrust.audit with efficiency kwargs) +# --------------------------------------------------------------------------- + +def test_public_api_accepts_efficiency_kwargs(): + import evaltrust + quality = make_data([0] * 50, [1] * 50) + tokens = two_model_cost_data([100] * 50, [300] * 50) + latency = two_model_cost_data([200] * 50, [600] * 50) + report = evaltrust.audit(quality, model_a="A", model_b="B", + token_count_data=tokens, latency_data=latency) + efficiency = [f for f in report.findings if f.pillar == PILLAR] + assert len(efficiency) == 2 # one token, one latency + + +def test_public_api_quality_only_unchanged(): + """audit() with no efficiency kwargs must produce no Efficiency findings.""" + import evaltrust + quality = make_data([0] * 50, [1] * 50) + report = evaltrust.audit(quality, model_a="A", model_b="B") + efficiency = [f for f in report.findings if f.pillar == PILLAR] + assert efficiency == [] + + +# --------------------------------------------------------------------------- +# Bug fixes from CodeRabbit review +# --------------------------------------------------------------------------- + +# --- Bug 1 (Critical): NaN quality_delta must not produce findings ---------- + +def test_nan_quality_delta_skips_all_findings(): + """When quality scores are missing for a model, quality_delta is NaN. + audit_efficiency must return [] rather than emitting 'nan pt quality drop' + or storing a non-JSON-serialisable NaN in details['quality_delta']. + """ + # Build a quality dataset where model B has no scores at all. + examples = [Example(id=str(i), scores={"A": 0.8}) for i in range(10)] + quality = EvalData(models=["A", "B"], examples=examples, + source_format="test", metadata={}) + tokens = two_model_cost_data([100] * 10, [300] * 10) + latency = two_model_cost_data([200] * 10, [600] * 10) + + findings = audit_efficiency(quality, "A", "B", + token_count_data=tokens, latency_data=latency) + assert findings == [], ( + "NaN quality_delta must cause audit_efficiency to return [] " + "rather than emitting malformed findings." + ) + + +def test_nan_quality_delta_details_not_in_output(): + """Ensure NaN never reaches details dict (not JSON-serialisable).""" + import json + import math + examples = [Example(id=str(i), scores={"A": 0.8}) for i in range(10)] + quality = EvalData(models=["A", "B"], examples=examples, + source_format="test", metadata={}) + tokens = two_model_cost_data([100] * 10, [300] * 10) + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + # No finding at all is correct; but if one slipped through, it must be + # JSON-serialisable (no NaN). + for f in findings: + d = f.to_dict() + json.dumps(d) # must not raise + assert not math.isnan(f.details.get("quality_delta", 0)), ( + "quality_delta must not be NaN in Finding.details" + ) + + +# --- Bug 2 (Minor): _quality_delta_str sign correctness -------------------- + +def test_quality_delta_str_drop_is_negative(): + """A quality drop must be shown with a '-' sign, not '+'.""" + from evaltrust.audit.efficiency import _quality_delta_str + result = _quality_delta_str(-0.1) + assert result.startswith("-"), ( + f"Expected '-2.0 pt quality drop', got '{result}'" + ) + assert "drop" in result + assert "+" not in result + + +def test_quality_delta_str_gain_is_positive(): + """A quality gain must be shown with a '+' sign.""" + from evaltrust.audit.efficiency import _quality_delta_str + result = _quality_delta_str(0.1) + assert result.startswith("+"), ( + f"Expected '+10.0 pt quality gain', got '{result}'" + ) + assert "gain" in result + + +def test_quality_delta_str_zero(): + from evaltrust.audit.efficiency import _quality_delta_str + assert _quality_delta_str(0.0) == "no quality change" + + +def test_quality_delta_str_no_unicode_minus(): + """Docstring promises ASCII hyphen for the minus sign, not Unicode U+2212.""" + from evaltrust.audit.efficiency import _quality_delta_str + result = _quality_delta_str(-0.05) + assert "\u2212" not in result, "Must use ASCII '-', not Unicode minus sign U+2212" + + +def test_token_how_to_fix_shows_signed_quality_delta(): + """The how_to_fix text in a token finding must show a signed delta, + e.g. '+10.0 pt quality gain', never '+10.0 pt quality drop'.""" + quality = make_data([0.9] * 10, [0.7] * 10) # B is worse: delta = -0.2 + tokens = two_model_cost_data([100] * 10, [300] * 10) + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + (tf,) = by_check(findings, "efficiency_tokens") + # Must say 'drop', not 'gain', and must not start with '+' for a drop + assert "drop" in tf.how_to_fix.lower() + assert "+20.0 pt quality drop" not in tf.how_to_fix # the old broken output + + +# --- Bug 3 (Critical): token cheaper-branch ratio orientation --------------- + +def test_cheaper_token_ratio_reads_greater_than_one(): + """When B is cheaper, the displayed ratio must be > 1x (e.g. '3x fewer'), + not 0.33x, which would read as a slowdown/increase.""" + quality = make_data([0.8] * 10, [0.8] * 10) + # A=300, B=100 → B uses 1/3 the tokens → should say '3x fewer', not '0.33x' + tokens = two_model_cost_data([300] * 10, [100] * 10) + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + (tf,) = by_check(findings, "efficiency_tokens") + title = tf.title + # The ratio in the title must be >= 1x (e.g. '3x fewer') + # Extract the ratio number from the title + import re + match = re.search(r"([\d.]+)x", title) + assert match, f"No ratio found in title: '{title}'" + ratio_val = float(match.group(1)) + assert ratio_val >= 1.0, ( + f"Cheaper-branch ratio must be >= 1 (e.g. '3x fewer'), " + f"got {ratio_val}x in: '{title}'" + ) + + +def test_cheaper_token_title_says_fewer_not_uses(): + """When B is cheaper the title should read 'fewer tokens', not 'uses Nx the tokens' + with N < 1, which is confusing.""" + quality = make_data([0.8] * 10, [0.8] * 10) + tokens = two_model_cost_data([300] * 10, [100] * 10) + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + (tf,) = by_check(findings, "efficiency_tokens") + assert "fewer" in tf.title.lower() or float( + __import__("re").search(r"([\d.]+)x", tf.title).group(1) + ) >= 1.0 + + +# --- Bug 4 (Major): latency faster-branch ratio orientation ----------------- + +def test_faster_latency_ratio_reads_greater_than_one(): + """When B is faster, the displayed ratio must be > 1x (e.g. '3x faster'), + not 0.33x, which would read as a slowdown.""" + quality = make_data([0.8] * 10, [0.8] * 10) + # A=600, B=200 → B is 3x faster → should say '3x faster', not '0.33x faster' + latency = two_model_cost_data([600] * 10, [200] * 10) + findings = audit_efficiency(quality, "A", "B", latency_data=latency) + (lf,) = by_check(findings, "efficiency_latency") + title = lf.title + import re + match = re.search(r"([\d.]+)x", title) + assert match, f"No ratio found in title: '{title}'" + ratio_val = float(match.group(1)) + assert ratio_val >= 1.0, ( + f"Faster-branch ratio must be >= 1 (e.g. '3x faster'), " + f"got {ratio_val}x in: '{title}'" + ) + + +def test_faster_latency_how_to_fix_ratio_greater_than_one(): + """The how_to_fix text for the faster-branch must also use a ratio > 1.""" + quality = make_data([0.7] * 10, [0.9] * 10) # B better and faster + latency = two_model_cost_data([600] * 10, [200] * 10) + findings = audit_efficiency(quality, "A", "B", latency_data=latency) + (lf,) = by_check(findings, "efficiency_latency") + import re + match = re.search(r"([\d.]+)x", lf.how_to_fix) + assert match, f"No ratio found in how_to_fix: '{lf.how_to_fix}'" + ratio_val = float(match.group(1)) + assert ratio_val >= 1.0, ( + f"Faster-branch how_to_fix ratio must be >= 1, got {ratio_val}x" + ) + + +def test_slower_latency_ratio_reads_greater_than_one(): + """When B is slower, the displayed ratio must also be > 1x.""" + quality = make_data([0.8] * 10, [0.8] * 10) + # A=200, B=600 → B is 3x slower + latency = two_model_cost_data([200] * 10, [600] * 10) + findings = audit_efficiency(quality, "A", "B", latency_data=latency) + (lf,) = by_check(findings, "efficiency_latency") + import re + match = re.search(r"([\d.]+)x", lf.title) + assert match, f"No ratio found in title: '{lf.title}'" + ratio_val = float(match.group(1)) + assert ratio_val >= 1.0, ( + f"Slower-branch ratio must be >= 1, got {ratio_val}x" + ) + + +# --------------------------------------------------------------------------- +# Bug fix: latency_unit is carried through to how_detected (Image 1) +# --------------------------------------------------------------------------- + +def test_latency_unit_default_is_ms(): + """Default latency_unit is 'ms', so how_detected says ms/example.""" + quality = make_data([0.8] * 10, [0.9] * 10) + latency = two_model_cost_data([200] * 10, [600] * 10) + findings = audit_efficiency(quality, "A", "B", latency_data=latency) + (lf,) = by_check(findings, "efficiency_latency") + assert "ms/example" in lf.how_detected + + +def test_latency_unit_seconds_appears_in_how_detected(): + """When latency_unit='s', how_detected must say 's/example', not 'ms/example'.""" + quality = make_data([0.8] * 10, [0.9] * 10) + latency = two_model_cost_data([0.2] * 10, [0.6] * 10) + findings = audit_efficiency(quality, "A", "B", + latency_data=latency, latency_unit="s") + (lf,) = by_check(findings, "efficiency_latency") + assert "s/example" in lf.how_detected + assert "ms/example" not in lf.how_detected + + +def test_latency_unit_microseconds(): + """latency_unit='us' flows through correctly.""" + quality = make_data([0.8] * 10, [0.9] * 10) + latency = two_model_cost_data([200000] * 10, [600000] * 10) + findings = audit_efficiency(quality, "A", "B", + latency_data=latency, latency_unit="us") + (lf,) = by_check(findings, "efficiency_latency") + assert "us/example" in lf.how_detected + + +def test_latency_unit_via_public_api(): + """latency_unit is accepted and threaded through the public audit() call.""" + import evaltrust + quality = make_data([0.8] * 20, [0.9] * 20) + latency = two_model_cost_data([0.2] * 20, [0.6] * 20) + report = evaltrust.audit(quality, model_a="A", model_b="B", + latency_data=latency, latency_unit="s") + lf = [f for f in report.findings if f.details.get("check") == "efficiency_latency"] + assert len(lf) == 1 + assert "s/example" in lf[0].how_detected + assert "ms/example" not in lf[0].how_detected + + +# --------------------------------------------------------------------------- +# Bug fix: equality branches for tied resource means (Image 2) +# --------------------------------------------------------------------------- + +def test_equal_token_means_no_directional_claim(): + """When A and B use exactly the same tokens, the title must not say + 'fewer' or 'uses Nx the tokens' -- it should say 'same'.""" + quality = make_data([0.8] * 10, [0.9] * 10) + tokens = two_model_cost_data([200] * 10, [200] * 10) # identical means + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + (tf,) = by_check(findings, "efficiency_tokens") + assert "same" in tf.title.lower(), ( + f"Expected 'same' in title for equal token means, got: '{tf.title}'" + ) + assert "fewer" not in tf.title.lower() + # Recommendation should be based on quality only + assert "quality" in tf.how_to_fix.lower() + + +def test_equal_token_means_equal_quality_says_either(): + """Both equal tokens AND equal quality -> 'either model is a valid choice'.""" + quality = make_data([0.8] * 10, [0.8] * 10) + tokens = two_model_cost_data([200] * 10, [200] * 10) + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + (tf,) = by_check(findings, "efficiency_tokens") + assert "either" in tf.how_to_fix.lower() or "valid" in tf.how_to_fix.lower() + + +def test_equal_latency_means_no_directional_claim(): + """When A and B have the same latency, the title must not call either slower.""" + quality = make_data([0.8] * 10, [0.9] * 10) + latency = two_model_cost_data([300] * 10, [300] * 10) + findings = audit_efficiency(quality, "A", "B", latency_data=latency) + (lf,) = by_check(findings, "efficiency_latency") + assert "same" in lf.title.lower(), ( + f"Expected 'same' in title for equal latency means, got: '{lf.title}'" + ) + assert "slower" not in lf.title.lower() + assert "faster" not in lf.title.lower() + + +def test_equal_latency_equal_quality_says_either(): + """Both equal latency AND equal quality -> 'either model is a valid choice'.""" + quality = make_data([0.8] * 10, [0.8] * 10) + latency = two_model_cost_data([300] * 10, [300] * 10) + findings = audit_efficiency(quality, "A", "B", latency_data=latency) + (lf,) = by_check(findings, "efficiency_latency") + assert "either" in lf.how_to_fix.lower() or "valid" in lf.how_to_fix.lower() + + +def test_equal_latency_b_better_quality_recommends_b(): + """Equal latency but B is better on quality -> prefer B.""" + quality = make_data([0.7] * 10, [0.9] * 10) + latency = two_model_cost_data([300] * 10, [300] * 10) + findings = audit_efficiency(quality, "A", "B", latency_data=latency) + (lf,) = by_check(findings, "efficiency_latency") + assert "B" in lf.how_to_fix or "prefer" in lf.how_to_fix.lower() + + +def test_equal_token_b_worse_quality_recommends_a(): + """Equal tokens but B is worse on quality -> prefer A.""" + quality = make_data([0.9] * 10, [0.7] * 10) + tokens = two_model_cost_data([200] * 10, [200] * 10) + findings = audit_efficiency(quality, "A", "B", token_count_data=tokens) + (tf,) = by_check(findings, "efficiency_tokens") + assert "A" in tf.how_to_fix