feat(bench): validate paired comparisons and report uncertainty privately
Linux / keyless-cuda-gate (pull_request) Skipped
Linux / verify (pull_request) Successful in 4m32s
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 1m38s
Linux / linux-static-cli (pull_request) Successful in 11m8s
Linux / release-cli (pull_request) Skipped

This commit is contained in:
Pavlo Ratushnyi
2026-10-08 00:46:44 +02:00
parent d7d24c7401
commit 4736b193da
7 changed files with 1118 additions and 140 deletions
+66
View File
@@ -9,6 +9,72 @@ Store future benchmark definitions and sanitized fixtures in Git; place generate
`fixtures/chat/paired-smoke.json` contains public synthetic arithmetic, retrieval, and function-call prompts. Run `scripts/bench-chat-paired.py` from the repository root. It sends one untimed warmup per case and endpoint, then alternates baseline/candidate order over repeated, sequential requests with the same model, prompt, greedy sampling settings, and token cap. It checks each response's terminal `finish_reason` and case-specific text or tool arguments. The report includes per-case pass counts, raw response timings, and paired wall-time ratios. The full response report is written only to a new private path outside Git with mode 0600; API keys are read from private server config files and omitted from the report.
For the current upstream server, pass its full bound URL as `--baseline-url`, its `/health` URL as `--baseline-ready-url`, the configured model name as `--model`, and its private JSON config as `--baseline-auth-config`. The readiness poll waits for a nonzero `max_context` because upstream can report `loaded: true` during loading. Once a compressed inference endpoint exists, pass its URL as `--candidate-url` and optionally `--candidate-ready-url`. A baseline-only run is a functional check and cannot establish a speedup. Even a paired run of this small synthetic suite is only a smoke test: the charter's long-context, real-agent, cache-state, and model-quality gates still require separate runs. Record engine/config digests, GPU, driver, CUDA, power settings, and artifact digests in a private `--metadata` JSON for any reported performance result. Never commit the report or private config.
## Offline comparison of sequential Chat reports
When two model arms cannot fit together, compare two **single-arm** schema-1
reports from the same suite/model/configuration. A standalone harness run may
label its rows `baseline` in both files; the filenames select the comparison
arms. Each file must contain one arm, exactly one warmup per case and the full
declared repeat range. Missing or duplicate pairs, category drift, malformed
rows, nonfinite numbers and inconsistent successful HTTP/terminal/quality
claims fail before any comparison is published. Genuine observed quality or
HTTP failures remain explicit data, with failed categories reported separately.
```sh
python3 -B scripts/compare-chat-reports.py \
/private/evaluation/baseline.json /private/evaluation/candidate.json \
--output /private/evaluation/comparison.json
python3 -B scripts/render-paired-report.py /private/evaluation/comparison.json \
--output /private/evaluation/comparison.md
```
JSON and Markdown outputs must be new files outside Git and use mode 0600;
neither overwrites an existing file. The comparator prints fixed aggregate
counts only, without case labels, response text, tool arguments or metadata.
Markdown omits raw responses, tool arguments and metadata values. Private
metadata remains in the private JSON for reproducibility.
Existing schema-1 median fields remain available. Overall, category and case
groups additionally contain mean, median, linearly interpolated p10/p90 and
sample counts for both arms' wall times and positive paired prefill/decode
rates. Ratios are calculated **within each pair**, then summarized; they are
not ratios of arm medians. Zero token rates (for example fully cached prefill)
and missing timings never become divisions by zero: `timing_coverage` and
`unavailable_pairs` disclose their exclusion, while a wholly unavailable
throughput summary stays `null`. Counts must be nonnegative integers; timing
values must be finite/nonnegative and measured wall times strictly positive.
Ratio uncertainty uses a deterministic distribution-free, two-sided 95%
confidence interval for the population **median paired ratio**, selected from
order statistics with exact binomial coverage. This bounds work without a
bootstrap dependency or random seed. Fewer than six pairs cannot yield a finite
95% interval and receive `null` bounds; fewer than 30 pairs receive an explicit
small-sample flag. The interval assumes independent pairs sharing a population
median; sequential cache/load drift and correlated repeats can invalidate that
assumption. Category/overall mixtures also depend on case composition. The
interval does not measure those systematic errors or uncertainty in the mean.
The report names missing charter provenance fields without echoing their
values: `engine_commit`, `control_plane_commit`, `model_sha256`, `quantization`,
`gpu`, `driver`, `cuda_toolkit`, `power_limit_watts`, `context_tokens`,
`kv_configuration`, `slots`, `batch_size`, `speculation`, `cache_state`,
`workload_sha256`, `quality_gate_result`, `draft_acceptance_rate`,
`expert_cache_hit_rate`, `kv_streaming_hit_rate`; measured TTFT and prompt/output
token-count coverage are checked separately. Unavailable/not-applicable metrics
should be explained in private provenance; a declaration is not a measurement.
Conflicting declared hardware, model source, context/KV/slot/batch/speculation,
cache or workload identity refuses pairing. Engine/control-plane/codec version
changes can be the intended comparison, but must be recorded for each arm.
Inputs are bounded to 32 MiB each, 64 cases, 4,096 measured pairs, 100 repeats
per case, JSON depth 32 and one million JSON nodes. Timing/count magnitudes are
bounded to 10^12. Split larger suites deliberately instead of silently dropping
rows. JSON statistics and the Markdown rendering remain **descriptive**:
sequential runs, synthetic CPU fixtures, complete metadata or passing smoke
checks never automatically qualify GPU inference, model quality or an
end-to-end agent performance improvement. Those charter gates remain separate.
# Live Responses episode replay
`scripts/replay-live-responses.py` is an offline evaluator for an **explicitly
+2
View File
@@ -5,6 +5,8 @@ repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/test-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py"
python3 "${repo_root}/scripts/test-benchmark-harness.py"
python3 "${repo_root}/scripts/test-paired-report.py"
python3 "${repo_root}/scripts/test-paired-markdown.py"
python3 "${repo_root}/scripts/test-native-service.py"
python3 "${repo_root}/scripts/test-native-api.py"
python3 "${repo_root}/scripts/test-native-menu.py"
+453 -139
View File
@@ -1,69 +1,379 @@
#!/usr/bin/env python3
"""Compare two private, sequential runs of bench-chat-paired.py.
"""Descriptively compare two private, sequential bench-chat-paired.py runs.
Useful on one GPU when both model arms cannot fit in VRAM together. The output
is a descriptive paired report; load order and disk/cache drift still matter.
No performance/model-quality qualification follows from this offline report.
"""
import argparse
import datetime as dt
import json
import math
import os
from pathlib import Path
import statistics
import sys
MAX_INPUT_BYTES = 32 * 1024 * 1024
MAX_CASES = 64
MAX_PAIRS = 4096
MAX_REPEATS = 100
MAX_NUMBER = 1e12
COUNT_FIELDS = {"prompt_n", "predicted_n", "cache_n", "draft_n", "draft_accepted_n"}
USAGE_COUNTS = {"prompt_tokens", "completion_tokens", "total_tokens", "input_tokens",
"output_tokens", "cached_tokens", "reasoning_tokens",
"accepted_prediction_tokens", "rejected_prediction_tokens"}
# Canonical private metadata keys. Presence is an operator assertion, not proof.
PROVENANCE_FIELDS = (
"engine_commit", "control_plane_commit", "model_sha256", "quantization",
"gpu", "driver", "cuda_toolkit", "power_limit_watts", "context_tokens",
"kv_configuration", "slots", "batch_size", "speculation", "cache_state",
"workload_sha256", "quality_gate_result", "draft_acceptance_rate",
"expert_cache_hit_rate", "kv_streaming_hit_rate",
)
LIMITATION = (
"Descriptive only: sequential model loads and requests may drift with I/O, "
"cache state and load order; repeats may be correlated. Synthetic/CPU "
"results and supplied metadata do not qualify GPU inference, end-to-end "
"agent performance or model quality. Pooled cases/categories depend on "
"their case composition; uncertainty assumes independent pairs sharing "
"a common population median."
)
def reject(message):
# Fixed field names only; never include values from a private report.
raise ValueError(message)
def integer(value, minimum=0, maximum=int(MAX_NUMBER)):
return type(value) is int and minimum <= value <= maximum
def number(value, positive=False):
return (type(value) in (int, float) and math.isfinite(value)
and (value > 0 if positive else value >= 0) and value <= MAX_NUMBER)
def label(value):
return isinstance(value, str) and bool(value.strip()) and len(value) <= 128
def unique_object(items):
result = {}
for key, value in items:
if key in result:
reject("duplicate JSON field")
result[key] = value
return result
def finite_float(text):
value = float(text)
if not math.isfinite(value):
reject("nonfinite JSON number")
return value
def bounded_tree(report):
# Keep only one iterator per depth, not a second copy of a wide JSON array.
stack = [(iter((report,)), 0)]
nodes = 0
while stack:
iterator, depth = stack[-1]
try:
value = next(iterator)
except StopIteration:
stack.pop()
continue
nodes += 1
if depth > 32 or nodes > 1_000_000:
reject("report exceeds structure limit")
if isinstance(value, dict):
stack.append((iter(value.values()), depth + 1))
elif isinstance(value, list):
stack.append((iter(value), depth + 1))
elif type(value) is float and not math.isfinite(value):
reject("nonfinite JSON number")
def load_report(path):
with path.open("rb") as source:
raw = source.read(MAX_INPUT_BYTES + 1)
if len(raw) > MAX_INPUT_BYTES:
reject("report exceeds input byte limit")
try:
report = json.loads(raw, object_pairs_hook=unique_object, parse_float=finite_float,
parse_constant=lambda _: reject("nonfinite JSON number"))
except (UnicodeError, json.JSONDecodeError, RecursionError):
reject("invalid report JSON")
bounded_tree(report)
validate_report(report)
return report
def normalized(row):
try:
message = row["response"]["choices"][0]["message"]
return {
"content": message.get("content"),
"tool_calls": [
{"name": call["function"]["name"],
"arguments": json.loads(call["function"]["arguments"])}
for call in message.get("tool_calls") or []
],
}
except (KeyError, IndexError, TypeError, ValueError):
choices = row["response"]["choices"]
if not isinstance(choices, list) or len(choices) != 1:
return None
choice = choices[0]
message = choice["message"]
if message.get("role") != "assistant" or choice.get("finish_reason") not in ("stop", "tool_calls"):
return None
content = message.get("content")
if content is not None and not isinstance(content, str):
return None
calls = message.get("tool_calls")
if calls is None:
calls = []
if not isinstance(calls, list) or len(calls) > 128:
return None
if bool(calls) != (choice["finish_reason"] == "tool_calls"):
return None
tools, call_ids = [], set()
for call in calls:
call_id = call.get("id")
if not label(call_id) or call_id in call_ids:
return None
call_ids.add(call_id)
function = call["function"]
if call.get("type") != "function" or not label(function["name"]):
return None
if not isinstance(function["arguments"], str):
return None
arguments = json.loads(function["arguments"], object_pairs_hook=unique_object, parse_float=finite_float,
parse_constant=lambda _: reject("nonfinite tool JSON"))
if not isinstance(arguments, dict):
return None
bounded_tree(arguments)
tools.append({"name": function["name"], "arguments": arguments})
if content is None and not tools:
return None
return {"content": content, "tool_calls": tools}
except (KeyError, IndexError, TypeError, ValueError, AttributeError, RecursionError):
return None
def selected(report):
rows = {}
for row in report["rows"]:
def validate_usage(usage):
if usage is None:
return
if not isinstance(usage, dict):
reject("usage must be an object")
for key, value in usage.items():
if key in USAGE_COUNTS and not integer(value):
reject("usage token count must be a bounded nonnegative integer")
if key in ("prompt_tokens_details", "completion_tokens_details",
"input_tokens_details", "output_tokens_details"):
if not isinstance(value, dict):
reject("usage token details must be an object")
validate_usage(value)
if all(key in usage for key in ("prompt_tokens", "completion_tokens", "total_tokens")):
if usage["prompt_tokens"] + usage["completion_tokens"] != usage["total_tokens"]:
reject("usage total_tokens is inconsistent")
for prefix in ("prompt", "input"):
total = usage.get(prefix + "_tokens")
cached = usage.get(prefix + "_tokens_details", {}).get("cached_tokens")
if total is not None and cached is not None and cached > total:
reject("usage cached_tokens exceeds input tokens")
def validate_report(report):
if not isinstance(report, dict) or type(report.get("schema")) is not int or report["schema"] != 1:
reject("unsupported report schema")
digest = report.get("suite_sha256")
if (not isinstance(digest, str) or len(digest) != 64
or any(char not in "0123456789abcdefABCDEF" for char in digest)):
reject("suite_sha256 must be a SHA-256 digest")
if not label(report.get("model")):
reject("model must be a bounded nonempty string")
config = report.get("configuration")
if not isinstance(config, dict) or not integer(config.get("repeats"), 1, MAX_REPEATS):
reject("configuration.repeats is invalid")
for field in ("max_tokens", "seed"):
if field in config and not integer(config[field], 1 if field == "max_tokens" else 0):
reject("configuration integer is invalid")
if "temperature" in config and not number(config["temperature"]):
reject("configuration.temperature is invalid")
if "stream" in config and config["stream"] is not False:
reject("configuration.stream must be false")
for field in ("reasoning_effort", "cache_state"):
if field in config and (not isinstance(config[field], str) or not config[field].strip() or len(config[field]) > 1024):
reject("configuration text field is invalid")
if not isinstance(report.get("metadata", {}), dict):
reject("metadata must be an object")
rows = report.get("rows")
if not isinstance(rows, list) or not rows or len(rows) > MAX_PAIRS + MAX_CASES:
reject("rows exceed report limits or are empty")
cases, measured, warmups, arms = {}, set(), set(), set()
for row in rows:
if not isinstance(row, dict) or not label(row.get("case_id")) or not label(row.get("category")):
reject("row case_id/category is invalid")
if row.get("arm") not in ("baseline", "candidate"):
reject("row arm is invalid")
arms.add(row["arm"])
case = row["case_id"]
if case in cases and cases[case] != row["category"]:
reject("case category changes between rows")
cases[case] = row["category"]
if type(row.get("warmup")) is not bool:
reject("row warmup must be boolean")
if row["warmup"]:
continue
key = (row["case_id"], row["repeat"])
if key in rows:
raise ValueError(f"duplicate run {key}")
rows[key] = row
return rows
if row.get("repeat") is not None or case in warmups:
reject("invalid or duplicate warmup")
warmups.add(case)
else:
repeat = row.get("repeat")
if not integer(repeat, 0, config["repeats"] - 1) or (case, repeat) in measured:
reject("invalid or duplicate measured repeat")
measured.add((case, repeat))
if not number(row.get("wall_seconds"), positive=True):
reject("wall_seconds must be finite and positive")
if not integer(row.get("http_status"), 100, 599):
reject("http_status is invalid")
quality = row.get("quality")
if not isinstance(quality, dict) or type(quality.get("passed")) is not bool:
reject("quality.passed must be boolean")
response = row.get("response")
if not isinstance(response, dict):
reject("response must be an object")
if quality["passed"] and (row["http_status"] != 200 or normalized(row) is None):
reject("quality.passed contradicts HTTP/terminal response")
validate_usage(response.get("usage"))
timing = response.get("timings")
if timing is not None:
if not isinstance(timing, dict):
reject("timings must be an object")
for key, value in timing.items():
if key in COUNT_FIELDS or key.endswith("_n"):
if not integer(value):
reject("timing token count must be a bounded nonnegative integer")
elif not number(value):
reject("optional timing must be finite and nonnegative")
if (len(arms) != 1 or len(cases) > MAX_CASES or len(measured) > MAX_PAIRS
or warmups != cases.keys()
or len(measured) != len(cases) * config["repeats"]):
reject("report must contain one arm and complete warmup/repeat coverage")
def selected(report):
return {(row["case_id"], row["repeat"]): row for row in report["rows"] if not row["warmup"]}
def percentile(values, fraction):
position = (len(values) - 1) * fraction
lower = int(position)
remainder = position - lower
return values[lower] * (1 - remainder) + values[min(lower + 1, len(values) - 1)] * remainder
def median_interval(values):
"""Exact distribution-free paired median order-statistic interval.
Pick the narrowest symmetric interval with >=95% binomial coverage.
Below six pairs no finite two-sided 95% interval exists; disclose null bounds.
"""
n = len(values)
total = 1 << n
weight, tail, chosen, chosen_tail = 1, 0, 0, 0
for k in range(1, n // 2 + 1):
tail += weight
if 40 * tail > total:
break
chosen, chosen_tail = k, tail
weight = weight * (n - k + 1) // k
return {
"method": "exact paired median order-statistic interval",
"confidence_level": 0.95,
"coverage_lower_bound": 1 - 2 * chosen_tail / total if chosen else None,
"lower": values[chosen - 1] if chosen else None,
"upper": values[n - chosen] if chosen else None,
"finite_interval_available": bool(chosen),
"assumption": "independent pairs with a common population median; ties are conservative",
}
def distribution(values, uncertainty=False):
values = sorted(values)
result = {"sample_count": len(values), "mean": statistics.fmean(values),
"median": statistics.median(values), "p10": percentile(values, 0.1),
"p90": percentile(values, 0.9), "small_sample": len(values) < 30}
if uncertainty:
result["median_confidence_interval"] = median_interval(values)
return result
def ratio(candidate, baseline):
result = candidate / baseline
if not math.isfinite(result) or result <= 0:
reject("paired ratio is not finite and positive")
return result
def throughput(pairs, field):
measured = [(pair["baseline_timings"].get(field), pair["candidate_timings"].get(field))
for pair in pairs]
valid = [(a, b) for a, b in measured if a is not None and b is not None and a > 0 and b > 0]
if not valid:
return None
ratios = [ratio(b, a) for a, b in valid]
return {
"pairs": len(valid), "unavailable_pairs": len(pairs) - len(valid),
"baseline_median_tokens_per_second": statistics.median(a for a, _ in valid),
"candidate_median_tokens_per_second": statistics.median(b for _, b in valid),
"candidate_over_baseline_median_ratio": statistics.median(ratios),
"baseline_distribution": distribution([a for a, _ in valid]),
"candidate_distribution": distribution([b for _, b in valid]),
"candidate_over_baseline_ratio_distribution": distribution(ratios, uncertainty=True),
}
def group_summary(pairs):
baseline_failed = sum(not pair["baseline_quality_passed"] for pair in pairs)
candidate_failed = sum(not pair["candidate_quality_passed"] for pair in pairs)
mismatched = sum(not pair["same_normalized_output"] for pair in pairs)
return {
"pairs": len(pairs),
"same_normalized_output": len(pairs) - mismatched,
"both_quality_passed": sum(pair["baseline_quality_passed"] and
pair["candidate_quality_passed"] for pair in pairs),
"candidate_over_baseline_wall_median_ratio": statistics.median(
pair["candidate_over_baseline_wall_ratio"] for pair in pairs),
"wall_seconds": {
"baseline": distribution([pair["baseline_wall_seconds"] for pair in pairs]),
"candidate": distribution([pair["candidate_wall_seconds"] for pair in pairs]),
},
"candidate_over_baseline_wall_ratio_distribution": distribution(
[pair["candidate_over_baseline_wall_ratio"] for pair in pairs], uncertainty=True),
"quality": {"baseline_failed": baseline_failed, "candidate_failed": candidate_failed,
"normalized_output_mismatches": mismatched,
"baseline_http_or_protocol_failed": sum(pair["baseline_protocol_failed"] for pair in pairs),
"candidate_http_or_protocol_failed": sum(pair["candidate_protocol_failed"] for pair in pairs),
"observed_checks_passed": not (baseline_failed or candidate_failed or mismatched)},
"timing_coverage": {
field: {"available_pairs": sum(pair["baseline_timings"].get(field, 0) > 0 and
pair["candidate_timings"].get(field, 0) > 0 for pair in pairs),
"total_pairs": len(pairs)}
for field in ("prompt_per_second", "predicted_per_second")
},
"prefill": throughput(pairs, "prompt_per_second"),
"decode": throughput(pairs, "predicted_per_second"),
}
def initial_requests(base, candidate):
def rows(report):
selected_rows = {}
for row in report["rows"]:
if row["warmup"]:
case = row["case_id"]
if case in selected_rows:
raise ValueError(f"duplicate initial request for {case}")
selected_rows[case] = row
return selected_rows
b_rows, c_rows = rows(base), rows(candidate)
b_rows = {row["case_id"]: row for row in base["rows"] if row["warmup"]}
c_rows = {row["case_id"]: row for row in candidate["rows"] if row["warmup"]}
if b_rows.keys() != c_rows.keys():
raise ValueError("initial requests differ between arms")
reject("initial requests differ between arms")
result = {}
for case in sorted(b_rows):
b, c = b_rows[case], c_rows[case]
b_timing = b["response"].get("timings") or {}
c_timing = c["response"].get("timings") or {}
if b["category"] != c["category"]:
reject("initial case category differs")
b_timing, c_timing = b["response"].get("timings") or {}, c["response"].get("timings") or {}
result[case] = {
"baseline_wall_seconds": b["wall_seconds"],
"candidate_wall_seconds": c["wall_seconds"],
"baseline_quality_passed": b["quality"]["passed"],
"candidate_quality_passed": c["quality"]["passed"],
"baseline_wall_seconds": b["wall_seconds"], "candidate_wall_seconds": c["wall_seconds"],
"baseline_quality_passed": b["quality"]["passed"], "candidate_quality_passed": c["quality"]["passed"],
"baseline_prompt_tokens_processed": b_timing.get("prompt_n"),
"candidate_prompt_tokens_processed": c_timing.get("prompt_n"),
"baseline_cached_prompt_tokens": b_timing.get("cache_n"),
@@ -74,35 +384,71 @@ def initial_requests(base, candidate):
return result
def throughput(pairs, field):
measured = []
def provenance(report):
metadata = report.get("metadata", {})
missing = [field for field in PROVENANCE_FIELDS if metadata.get(field) in (None, "", [], {})]
measured = [row for row in report["rows"] if not row["warmup"]]
if not all(any((row["response"].get("timings") or {}).get(key, 0) > 0
for key in ("ttft_ms", "ttft_seconds")) for row in measured):
missing.append("ttft")
if not all(all(key in (row["response"].get("usage") or {})
for key in ("prompt_tokens", "completion_tokens")) for row in measured):
missing.append("prompt_output_token_counts")
return {"missing_fields": missing, "metadata_presence_is_not_verified_evidence": True}
def compare(base, candidate):
for field in ("schema", "suite_sha256", "model", "configuration"):
if base[field] != candidate[field]:
reject("reports differ in " + field)
# An intended code/codec change may differ between arms, but a declared
# different workload/hardware/cache setup cannot be pooled as matched pairs.
for field in ("gpu", "driver", "power_limit_watts", "model_sha256", "context_tokens",
"kv_configuration", "slots", "batch_size", "speculation", "cache_state", "workload_sha256"):
b_value, c_value = base.get("metadata", {}).get(field), candidate.get("metadata", {}).get(field)
if b_value not in (None, "", [], {}) and c_value not in (None, "", [], {}) and b_value != c_value:
reject("incompatible paired provenance field")
b_rows, c_rows = selected(base), selected(candidate)
if not b_rows or b_rows.keys() != c_rows.keys():
reject("reports do not contain the same measured cases")
pairs = []
for key in sorted(b_rows):
b, c = b_rows[key], c_rows[key]
if b["category"] != c["category"]:
reject("case category differs")
b_normal, c_normal = normalized(b), normalized(c)
pairs.append({
"case_id": key[0], "repeat": key[1], "category": b["category"],
"baseline_wall_seconds": b["wall_seconds"], "candidate_wall_seconds": c["wall_seconds"],
"candidate_over_baseline_wall_ratio": ratio(c["wall_seconds"], b["wall_seconds"]),
"baseline_quality_passed": b["quality"]["passed"], "candidate_quality_passed": c["quality"]["passed"],
"baseline_protocol_failed": b["http_status"] != 200 or b_normal is None,
"candidate_protocol_failed": c["http_status"] != 200 or c_normal is None,
"same_normalized_output": b["http_status"] == c["http_status"] == 200 and b_normal is not None and b_normal == c_normal,
"baseline_usage": b["response"].get("usage"), "candidate_usage": c["response"].get("usage"),
"baseline_timings": b["response"].get("timings") or {}, "candidate_timings": c["response"].get("timings") or {},
})
grouped_cases, grouped_categories = {}, {}
for pair in pairs:
baseline = pair["baseline_timings"].get(field)
candidate = pair["candidate_timings"].get(field)
if (isinstance(baseline, (int, float)) and isinstance(candidate, (int, float))
and baseline > 0 and candidate > 0):
measured.append((baseline, candidate))
if not measured:
return None
return {
"pairs": len(measured),
"baseline_median_tokens_per_second": statistics.median(a for a, _ in measured),
"candidate_median_tokens_per_second": statistics.median(b for _, b in measured),
"candidate_over_baseline_median_ratio": statistics.median(b / a for a, b in measured),
}
def group_summary(pairs):
return {
"pairs": len(pairs),
"same_normalized_output": sum(pair["same_normalized_output"] for pair in pairs),
"both_quality_passed": sum(pair["baseline_quality_passed"] and
pair["candidate_quality_passed"] for pair in pairs),
"candidate_over_baseline_wall_median_ratio": statistics.median(
pair["candidate_over_baseline_wall_ratio"] for pair in pairs),
"prefill": throughput(pairs, "prompt_per_second"),
"decode": throughput(pairs, "predicted_per_second"),
}
grouped_cases.setdefault(pair["case_id"], []).append(pair)
grouped_categories.setdefault(pair["category"], []).append(pair)
categories = {category: group_summary(members) for category, members in sorted(grouped_categories.items())}
summary = group_summary(pairs)
summary.update({
"baseline_quality_passed": sum(p["baseline_quality_passed"] for p in pairs),
"candidate_quality_passed": sum(p["candidate_quality_passed"] for p in pairs),
"categories": categories,
"cases": {case: group_summary(members) for case, members in sorted(grouped_cases.items())},
"failed_quality_categories": [name for name, result in categories.items()
if not result["quality"]["observed_checks_passed"]],
})
warmups = initial_requests(base, candidate)
summary["initial_request_quality_failed"] = sum(
not (row["baseline_quality_passed"] and row["candidate_quality_passed"]) for row in warmups.values())
return {"summary": summary, "pairs": pairs, "initial_requests": warmups,
"provenance": {"baseline": provenance(base), "candidate": provenance(candidate)},
"qualification": {"performance_qualified": False, "model_quality_qualified": False,
"reason": "descriptive offline comparison; separate charter gates required"}}
def main():
@@ -111,78 +457,46 @@ def main():
parser.add_argument("candidate", type=Path)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
repository = Path(__file__).resolve().parent.parent
output = args.output.resolve()
if output == repository or repository in output.parents:
parser.error("output must be outside the repository")
base, candidate = (json.loads(path.read_text()) for path in
(args.baseline, args.candidate))
for field in ("schema", "suite_sha256", "model", "configuration"):
if base[field] != candidate[field]:
raise ValueError(f"reports differ in {field}")
b_rows, c_rows = selected(base), selected(candidate)
if not b_rows or b_rows.keys() != c_rows.keys():
raise ValueError("reports do not contain the same measured cases")
pairs = []
for key in sorted(b_rows):
b, c = b_rows[key], c_rows[key]
if b["category"] != c["category"]:
raise ValueError("case category differs")
pairs.append({
"case_id": key[0], "repeat": key[1], "category": b["category"],
"baseline_wall_seconds": b["wall_seconds"],
"candidate_wall_seconds": c["wall_seconds"],
"candidate_over_baseline_wall_ratio": c["wall_seconds"] / b["wall_seconds"],
"baseline_quality_passed": b["quality"]["passed"],
"candidate_quality_passed": c["quality"]["passed"],
"same_normalized_output": (b["http_status"] == c["http_status"] == 200
and normalized(b) is not None
and normalized(b) == normalized(c)),
"baseline_usage": b["response"].get("usage") if isinstance(b["response"], dict) else None,
"candidate_usage": c["response"].get("usage") if isinstance(c["response"], dict) else None,
"baseline_timings": (b["response"].get("timings") or {})
if isinstance(b["response"], dict) else {},
"candidate_timings": (c["response"].get("timings") or {})
if isinstance(c["response"], dict) else {},
})
categories = {}
for category in sorted({pair["category"] for pair in pairs}):
members = [pair for pair in pairs if pair["category"] == category]
categories[category] = group_summary(members)
cases = {case: group_summary([pair for pair in pairs if pair["case_id"] == case])
for case in sorted({pair["case_id"] for pair in pairs})}
report = {
"schema": 1, "created_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
"baseline_report": str(args.baseline.resolve()),
"candidate_report": str(args.candidate.resolve()),
"baseline_metadata": base.get("metadata", {}),
"candidate_metadata": candidate.get("metadata", {}),
"comparison_limit": "Sequential model loads on one GPU; wall times include API and may drift with I/O and cache state.",
"summary": {
"pairs": len(pairs),
"baseline_quality_passed": sum(p["baseline_quality_passed"] for p in pairs),
"candidate_quality_passed": sum(p["candidate_quality_passed"] for p in pairs),
"same_normalized_output": sum(p["same_normalized_output"] for p in pairs),
"candidate_over_baseline_wall_median_ratio": statistics.median(
p["candidate_over_baseline_wall_ratio"] for p in pairs),
"prefill": throughput(pairs, "prompt_per_second"),
"decode": throughput(pairs, "predicted_per_second"),
"categories": categories,
"cases": cases,
},
"initial_requests": initial_requests(base, candidate),
"pairs": pairs,
}
output.parent.mkdir(parents=True, exist_ok=True)
old_mask = os.umask(0o077)
try:
with output.open("x", encoding="utf-8") as file:
json.dump(report, file, indent=2, ensure_ascii=False)
file.write("\n")
finally:
os.umask(old_mask)
print(json.dumps(report["summary"], indent=2))
repository = Path(__file__).resolve().parent.parent
if args.output.is_symlink():
reject("output must not be a symbolic link")
output = args.output.resolve()
if output == repository or repository in output.parents or any((parent / ".git").exists() for parent in output.parents):
reject("output must be outside Git repositories")
base, candidate = load_report(args.baseline), load_report(args.candidate)
report = {"schema": 1, "created_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
"baseline_report": str(args.baseline.resolve()), "candidate_report": str(args.candidate.resolve()),
"baseline_metadata": base.get("metadata", {}), "candidate_metadata": candidate.get("metadata", {}),
"comparison_limit": LIMITATION, **compare(base, candidate)}
payload = (json.dumps(report, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
old_mask = os.umask(0o077)
try:
output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
finally:
os.umask(old_mask)
try:
with os.fdopen(fd, "wb") as destination:
destination.write(payload)
except BaseException:
output.unlink(missing_ok=True)
raise
summary = report["summary"]
print(json.dumps({"pairs": summary["pairs"],
"baseline_quality_passed": summary["baseline_quality_passed"],
"candidate_quality_passed": summary["candidate_quality_passed"],
"same_normalized_output": summary["same_normalized_output"],
"failed_quality_category_count": len(summary["failed_quality_categories"]),
"performance_qualified": False, "model_quality_qualified": False}))
except (ValueError, TypeError, OverflowError, RecursionError):
print("paired report rejected: invalid or incompatible report data", file=sys.stderr)
return 1
except OSError:
print("paired report rejected: private input/output unavailable or output already exists", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
main()
raise SystemExit(main())
+181
View File
@@ -0,0 +1,181 @@
#!/usr/bin/env python3
"""Render a private descriptive paired JSON report as private Markdown."""
import argparse
import html
import json
import math
import os
from pathlib import Path
MAX_BYTES = 16 * 1024 * 1024
MAX_GROUPS = 1000
def count(value, ceiling=None):
if type(value) is not int or value < 0 or (ceiling is not None and value > ceiling):
raise ValueError("invalid count")
return value
def number(value):
if type(value) not in (int, float) or not math.isfinite(value) or value <= 0:
raise ValueError("invalid measurement")
return f"{value:.6g}"
def label(value):
if not isinstance(value, str) or not value or len(value) > 256:
raise ValueError("invalid group label")
return html.escape(value).replace("|", "&#124;").replace("`", "&#96;").replace("\n", " ").replace("\r", " ").replace("[", "&#91;").replace("]", "&#93;")
def distribution_row(name, distribution, expected):
n = count(distribution["sample_count"], expected)
if n != expected or not n:
raise ValueError("distribution count does not match")
values = [number(distribution[key]) for key in ("mean", "median", "p10", "p90")]
if not distribution["p10"] <= distribution["median"] <= distribution["p90"]:
raise ValueError("invalid percentiles")
small = distribution["small_sample"]
if type(small) is not bool or small != (n < 30):
raise ValueError("invalid sample warning")
interval = distribution.get("median_confidence_interval")
bounds = "not reported"
if interval is not None:
available = interval["finite_interval_available"]
if type(available) is not bool:
raise ValueError("invalid interval availability")
level = interval["confidence_level"]
number(level)
if level > 1:
raise ValueError("invalid confidence level")
if available:
lower, upper = interval["lower"], interval["upper"]
low_text, high_text = number(lower), number(upper)
if not lower <= distribution["median"] <= upper:
raise ValueError("invalid confidence interval")
bounds = f"{level * 100:.6g}%: [{low_text}, {high_text}]"
else:
if interval["lower"] is not None or interval["upper"] is not None:
raise ValueError("unavailable interval has bounds")
bounds = "insufficient pairs for finite interval"
warning = "small sample (<30 pairs)" if small else "30+ pairs; still descriptive"
return f"| {name} | {n} | {' | '.join(values)} | {bounds} | {warning} |"
def render(report):
if not isinstance(report, dict) or type(report.get("schema")) is not int or report["schema"] != 1:
raise ValueError("unsupported report")
summary = report["summary"]
pairs = count(summary["pairs"])
if not pairs:
raise ValueError("empty report")
baseline = count(summary["baseline_quality_passed"], pairs)
candidate = count(summary["candidate_quality_passed"], pairs)
same = count(summary["same_normalized_output"], pairs)
ratio = number(summary["candidate_over_baseline_wall_median_ratio"])
lines = ["# Descriptive paired comparison", "",
"Sequential loads and synthetic fixtures may confound this comparison. "
"These numbers do not qualify GPU inference, model quality, or a performance improvement.", "",
"## Aggregate", "", "| Metric | Value |", "| --- | ---: |",
f"| Measured pairs | {pairs} |",
f"| Baseline quality checks passed | {baseline}/{pairs} |",
f"| Candidate quality checks passed | {candidate}/{pairs} |",
f"| Same normalized output | {same}/{pairs} |",
f"| Candidate/baseline median wall ratio (lower is faster) | {ratio} |"]
if "initial_request_quality_failed" in summary:
initial_failed = count(summary["initial_request_quality_failed"], pairs)
lines.append(f"| Initial requests failing quality checks | {initial_failed} |")
lines += ["",
"## Categories", "", "Any failing category remains a failed gate; aggregate results cannot hide it.", "",
"| Category | Pairs | Both quality checks passed | Same output | Wall ratio | Observed checks |",
"| --- | ---: | ---: | ---: | ---: | --- |"]
groups = summary["categories"]
if not isinstance(groups, dict) or not groups or len(groups) > MAX_GROUPS:
raise ValueError("invalid categories")
total = total_same = total_both_quality = 0
for name, group in sorted(groups.items()):
n = count(group["pairs"], pairs)
if not n:
raise ValueError("empty category")
total += n
quality = count(group["both_quality_passed"], n)
same_group = count(group["same_normalized_output"], n)
total_same += same_group
total_both_quality += quality
wall = number(group["candidate_over_baseline_wall_median_ratio"])
verdict = "PASS (observed only)" if quality == same_group == n else "FAIL"
lines.append(f"| {label(name)} | {n} | {quality}/{n} | {same_group}/{n} | {wall} | {verdict} |")
if total != pairs or total_same != same or total_both_quality > min(baseline, candidate):
raise ValueError("category counts do not match")
lines += ["", "## Throughput", "",
"Optional timings cover only pairs with measurements in both arms.", "",
"| Timing | Pairs | Baseline median tok/s | Candidate median tok/s | Candidate/baseline ratio |",
"| --- | ---: | ---: | ---: | ---: |"]
for name in ("prefill", "decode"):
timing = summary.get(name)
if timing is None:
lines.append(f"| {name} | 0 | unavailable | unavailable | unavailable |")
continue
n = count(timing["pairs"], pairs)
if not n:
raise ValueError("empty timing")
b = number(timing["baseline_median_tokens_per_second"])
c = number(timing["candidate_median_tokens_per_second"])
r = number(timing["candidate_over_baseline_median_ratio"])
lines.append(f"| {name} | {n} | {b} | {c} | {r} |")
distributions = []
for name, group in [("Aggregate", summary), *[(label(k), v) for k, v in sorted(groups.items())]]:
for arm in ("baseline", "candidate"):
value = group.get("wall_seconds", {}).get(arm)
if value is not None:
distributions.append(distribution_row(f"{name}: {arm} wall seconds", value, group["pairs"]))
value = group.get("candidate_over_baseline_wall_ratio_distribution")
if value is not None:
distributions.append(distribution_row(f"{name}: wall ratio", value, group["pairs"]))
for name in ("prefill", "decode"):
timing = summary.get(name)
if timing is not None:
for key in ("baseline_distribution", "candidate_distribution", "candidate_over_baseline_ratio_distribution"):
if key in timing:
distributions.append(distribution_row(f"{name}: {key.replace('_', ' ')}", timing[key], timing["pairs"]))
if distributions:
lines += ["", "## Distributions and uncertainty", "",
"Intervals describe paired medians under independent-pair assumptions. "
"Repeated cases, sequential loads and cache drift limit their interpretation.", "",
"| Measurement | Pairs | Mean | Median | P10 | P90 | Median interval | Sample limit |",
"| --- | ---: | ---: | ---: | ---: | ---: | --- | --- |", *distributions]
lines += ["", "Raw responses, tool arguments, and private metadata values are omitted.", ""]
return "\n".join(lines)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("report", type=Path)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
try:
output = args.output.resolve()
if any((parent / ".git").exists() for parent in (output, *output.parents)):
raise ValueError("output must be outside Git")
with args.report.open("rb") as source:
data = source.read(MAX_BYTES + 1)
if len(data) > MAX_BYTES:
raise ValueError("report too large")
document = render(json.loads(data))
output.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
try:
with os.fdopen(fd, "w", encoding="utf-8") as target:
target.write(document)
except BaseException:
output.unlink()
raise
except (ValueError, KeyError, TypeError, OSError, RecursionError):
parser.exit(1, "paired Markdown report refused: invalid input or unavailable private output\n")
print("Private descriptive Markdown report written.")
if __name__ == "__main__":
main()
+11 -1
View File
@@ -28,7 +28,8 @@ class Handler(http.server.BaseHTTPRequestHandler):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
if "tools" in body:
message = {"role": "assistant", "content": None,
"tool_calls": [{"function": {"name": "get_weather",
"tool_calls": [{"id": "call_fixture_weather", "type": "function",
"function": {"name": "get_weather",
"arguments": '{"city":"Paris"}'}}]}
finish = "tool_calls"
else:
@@ -117,6 +118,15 @@ def main():
assert sequential["candidate_quality_passed"] == 3
assert sequential["decode"]["pairs"] == 3
assert sequential["prefill"]["candidate_over_baseline_median_ratio"] == 1.0
markdown = private / "sequential-comparison.md"
rendered = subprocess.run([
"python3", str(root / "scripts/render-paired-report.py"),
str(compared), "--output", str(markdown),
], check=True, capture_output=True, text=True)
assert stat.S_IMODE(markdown.stat().st_mode) == 0o600
assert TOKEN not in markdown.read_text() + rendered.stdout + rendered.stderr
assert "Distributions and uncertainty" in markdown.read_text()
assert "insufficient pairs for finite interval" in markdown.read_text()
finally:
server.shutdown()
server.server_close()
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Owned synthetic CLI tests for private paired Markdown publication."""
import copy
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
SCRIPT = Path(__file__).with_name("render-paired-report.py")
class MarkdownTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix="leleka-paired-md-")
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.source = self.root / "input.json"
self.output = self.root / "report.md"
self.report = {"schema": 1, "metadata": {"private": "PRIVATE_VALUE"},
"pairs": [{"response": "PRIVATE_RESPONSE"}], "summary": {
"pairs": 2, "baseline_quality_passed": 2, "candidate_quality_passed": 1,
"same_normalized_output": 1, "candidate_over_baseline_wall_median_ratio": 0.8,
"categories": {"tool|<script>[link](url)": {
"pairs": 2, "both_quality_passed": 1, "same_normalized_output": 1,
"candidate_over_baseline_wall_median_ratio": 0.8}},
"prefill": None, "decode": {"pairs": 2,
"baseline_median_tokens_per_second": 100,
"candidate_median_tokens_per_second": 125,
"candidate_over_baseline_median_ratio": 1.25}}}
def run_report(self, report=None, output=None):
self.source.write_text(json.dumps(self.report if report is None else report))
return subprocess.run([sys.executable, "-B", str(SCRIPT), str(self.source),
"--output", str(output or self.output)], text=True,
capture_output=True, timeout=10)
def test_summary_quality_limits_and_privacy(self):
result = self.run_report()
self.assertEqual(result.returncode, 0, result.stderr)
document = self.output.read_text()
self.assertIn("1/2", document)
self.assertIn("0.8", document)
self.assertIn("1.25", document)
self.assertIn("do not qualify GPU inference", document)
self.assertIn("&#124;", document)
self.assertNotIn("<script>", document)
for secret in ("PRIVATE_VALUE", "PRIVATE_RESPONSE"):
self.assertNotIn(secret, document + result.stdout + result.stderr)
self.assertNotIn("tool|", result.stdout + result.stderr)
self.assertEqual(self.output.stat().st_mode & 0o777, 0o600)
def test_no_overwrite(self):
self.output.write_text("keep")
self.assertNotEqual(self.run_report().returncode, 0)
self.assertEqual(self.output.read_text(), "keep")
def test_invalid_measurements_publish_nothing(self):
for value in (0, -1, True, float("nan"), float("inf"), "0.8"):
with self.subTest(value=value):
report = copy.deepcopy(self.report)
report["summary"]["candidate_over_baseline_wall_median_ratio"] = value
self.assertNotEqual(self.run_report(report).returncode, 0)
self.assertFalse(self.output.exists())
def test_counts_must_match(self):
report = copy.deepcopy(self.report)
report["summary"]["categories"][next(iter(report["summary"]["categories"]))]["pairs"] = 1
self.assertNotEqual(self.run_report(report).returncode, 0)
self.assertFalse(self.output.exists())
def test_distribution_and_small_sample_interval(self):
self.report["summary"]["candidate_over_baseline_wall_ratio_distribution"] = {
"sample_count": 2, "mean": 0.8, "median": 0.8, "p10": 0.7, "p90": 0.9,
"small_sample": True, "median_confidence_interval": {
"confidence_level": 0.95, "finite_interval_available": False,
"lower": None, "upper": None}}
self.assertEqual(self.run_report().returncode, 0)
document = self.output.read_text()
self.assertIn("small sample (<30 pairs)", document)
self.assertIn("insufficient pairs for finite interval", document)
def test_interval_not_allowed_to_hide_invalid_bounds(self):
self.report["summary"]["candidate_over_baseline_wall_ratio_distribution"] = {
"sample_count": 2, "mean": 0.8, "median": 0.8, "p10": 0.7, "p90": 0.9,
"small_sample": True, "median_confidence_interval": {
"confidence_level": 0.95, "finite_interval_available": True,
"lower": 0.9, "upper": 1.0}}
self.assertNotEqual(self.run_report().returncode, 0)
self.assertFalse(self.output.exists())
def test_git_output_refused(self):
git = self.root / "checkout"
git.mkdir()
(git / ".git").write_text("gitdir: ignored")
output = git / "private.md"
self.assertNotEqual(self.run_report(output=output).returncode, 0)
self.assertFalse(output.exists())
if __name__ == "__main__":
unittest.main()
+301
View File
@@ -0,0 +1,301 @@
#!/usr/bin/env python3
"""Independent, offline synthetic regression checks for private paired reports."""
import copy
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parent.parent
SCRIPT = ROOT / "scripts/compare-chat-reports.py"
PRIVATE = "PRIVATE_SYNTHETIC_SENTINEL_7863"
def response():
return {"choices": [{"message": {"role": "assistant", "content": "OK"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 20, "completion_tokens": 2, "total_tokens": 22},
"timings": {"prompt_n": 20, "predicted_n": 2, "prompt_per_second": 200.0,
"predicted_per_second": 50.0}}
def report(walls=(1., 2., 3., 4., 5., 6.), case="case", category="arithmetic"):
rows = []
for repeat, wall in [(None, 10000.), *enumerate(walls)]:
rows.append({"arm": "baseline", "case_id": case, "category": category,
"repeat": repeat, "warmup": repeat is None, "wall_seconds": wall,
"http_status": 200, "quality": {"passed": True}, "response": response()})
return {"schema": 1, "suite_sha256": "a" * 64, "model": "synthetic-only",
"configuration": {"repeats": len(walls), "temperature": 0, "seed": 42},
"metadata": {}, "rows": rows}
class PairedReports(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="paired-report-private-")
self.addCleanup(self.temp.cleanup)
self.directory = Path(self.temp.name)
self.b, self.c, self.out = (self.directory / name for name in ("baseline.json", "candidate.json", "comparison.json"))
def invoke(self, baseline, candidate, output=None):
self.b.write_text(json.dumps(baseline))
self.c.write_text(json.dumps(candidate))
result = subprocess.run([sys.executable, "-B", str(SCRIPT), str(self.b), str(self.c),
"--output", str(output or self.out)], text=True, capture_output=True, timeout=15)
self.assertNotIn(PRIVATE, result.stdout + result.stderr)
return result
def compare(self, baseline, candidate):
result = self.invoke(baseline, candidate)
self.assertEqual(result.returncode, 0, result.stderr)
return json.loads(self.out.read_text())
def refuse(self, baseline, candidate):
self.out.unlink(missing_ok=True)
result = self.invoke(baseline, candidate)
self.assertNotEqual(result.returncode, 0)
self.assertFalse(self.out.exists(), "invalid input must not publish a report")
self.assertNotIn("Traceback", result.stderr)
def test_known_outlier_distribution_and_exact_interval(self):
result = self.compare(report((1.,) * 6), report((1., 2., 3., 4., 5., 100.)))
group = result["summary"]["cases"]["case"]
stats = group["candidate_over_baseline_wall_ratio_distribution"]
self.assertEqual(stats["sample_count"], 6)
self.assertAlmostEqual(stats["mean"], 115 / 6)
self.assertEqual(stats["median"], 3.5)
self.assertEqual(stats["p10"], 1.5)
self.assertEqual(stats["p90"], 52.5)
ci = stats["median_confidence_interval"]
# For six independent pairs, extrema cover the median except both
# all-below/all-above events: 1 - 2*(1/2)^6 = 31/32.
self.assertEqual((ci["lower"], ci["upper"]), (1., 100.))
self.assertEqual(ci["coverage_lower_bound"], 31 / 32)
self.assertTrue(stats["small_sample"])
self.assertEqual(result["summary"]["categories"]["arithmetic"], group)
self.assertEqual(group["wall_seconds"]["baseline"]["mean"], 1)
def test_pair_ratios_are_not_ratio_of_arm_medians(self):
baseline, candidate = report((1., 2., 100.) * 2), report((2., 100., 101.) * 2)
for row in baseline["rows"]:
row["response"]["timings"]["predicted_per_second"] = row["wall_seconds"]
for row in candidate["rows"]:
row["response"]["timings"]["predicted_per_second"] = row["wall_seconds"]
summary = self.compare(baseline, candidate)["summary"]
self.assertEqual(summary["candidate_over_baseline_wall_median_ratio"], 2)
self.assertEqual(summary["decode"]["candidate_over_baseline_median_ratio"], 2)
self.assertEqual(summary["decode"]["candidate_median_tokens_per_second"] /
summary["decode"]["baseline_median_tokens_per_second"], 50)
def test_small_n_has_no_fabricated_finite_confidence(self):
stats = self.compare(report((2.,)), report((1.,)))["summary"]["candidate_over_baseline_wall_ratio_distribution"]
ci = stats["median_confidence_interval"]
self.assertEqual(stats["median"], .5)
self.assertFalse(ci["finite_interval_available"])
self.assertIsNone(ci["lower"])
self.assertIsNone(ci["upper"])
self.assertTrue(stats["small_sample"])
def test_independent_binomial_order_statistic_references(self):
# Published binomial tail values/reference ranks, independent of the
# comparator's recurrence. Values 1..n make each rank unambiguous.
for n, bounds, coverage in ((5, (None, None), None),
(9, (2, 8), .9609375),
(30, (10, 21), .9572260547429323)):
with self.subTest(n=n):
self.out.unlink(missing_ok=True)
data = self.compare(report((1.,) * n), report(tuple(range(1, n + 1))))
stats = data["summary"]["candidate_over_baseline_wall_ratio_distribution"]
ci = stats["median_confidence_interval"]
self.assertEqual((ci["lower"], ci["upper"]), bounds)
if coverage is None:
self.assertIsNone(ci["coverage_lower_bound"])
else:
self.assertAlmostEqual(ci["coverage_lower_bound"], coverage)
self.assertEqual(stats["small_sample"], n < 30)
def test_deterministic_and_order_independent(self):
baseline, candidate = report(), report((2., 1., 4., 3., 9., 7.))
first = self.compare(baseline, candidate)
self.out.unlink()
baseline["rows"].reverse()
candidate["rows"].reverse()
second = self.compare(baseline, candidate)
self.assertEqual(first["summary"], second["summary"])
self.assertEqual(first["pairs"], second["pairs"])
def test_failed_category_cannot_be_averaged_into_pass(self):
baseline, candidate = report(), report()
baseline["rows"] += report(case=PRIVATE, category="tool-integrity")["rows"]
candidate["rows"] += report(case=PRIVATE, category="tool-integrity")["rows"]
candidate["rows"][-1].update(http_status=500, response={"error": PRIVATE}, quality={"passed": False})
result = self.compare(baseline, candidate)
summary = result["summary"]
self.assertTrue(summary["categories"]["arithmetic"]["quality"]["observed_checks_passed"])
failed = summary["categories"]["tool-integrity"]["quality"]
self.assertEqual(failed["candidate_failed"], 1)
self.assertEqual(failed["candidate_http_or_protocol_failed"], 1)
self.assertFalse(failed["observed_checks_passed"])
self.assertFalse(summary["quality"]["observed_checks_passed"])
self.assertEqual(summary["failed_quality_categories"], ["tool-integrity"])
self.assertFalse(result["qualification"]["performance_qualified"])
self.assertFalse(result["qualification"]["model_quality_qualified"])
def test_optional_cached_zero_rates_are_disclosed_not_divided(self):
baseline, candidate = report(), report()
for row in baseline["rows"] + candidate["rows"]:
row["response"]["timings"]["prompt_per_second"] = 0
row["response"]["timings"]["prompt_n"] = 0
row["response"]["timings"]["cache_n"] = 20
candidate["rows"][-1]["response"].pop("timings")
summary = self.compare(baseline, candidate)["summary"]
self.assertIsNone(summary["prefill"])
self.assertEqual(summary["timing_coverage"]["prompt_per_second"]["available_pairs"], 0)
self.assertEqual(summary["decode"]["pairs"], 5)
self.assertEqual(summary["decode"]["unavailable_pairs"], 1)
def test_invalid_numeric_and_structural_rows_refused(self):
mutations = [
lambda r: r.update(wall_seconds=0), lambda r: r.update(wall_seconds=-1),
lambda r: r.update(wall_seconds=float("nan")), lambda r: r.update(wall_seconds=float("inf")),
lambda r: r.update(wall_seconds=True), lambda r: r.update(wall_seconds="2"),
lambda r: r.update(http_status=True), lambda r: r.update(http_status=99),
lambda r: r.update(http_status=500), lambda r: r.update(quality={"passed": 1}),
lambda r: r.update(quality={"passed": "false"}), lambda r: r.update(response=[]),
lambda r: r.update(warmup="false"), lambda r: r.update(repeat=True),
lambda r: r["response"].update(timings=[]),
lambda r: r["response"]["timings"].update(predicted_per_second=float("nan")),
lambda r: r["response"]["timings"].update(predicted_per_second=-1),
lambda r: r["response"]["timings"].update(predicted_per_second=True),
lambda r: r["response"]["timings"].update(prompt_n=2.5),
lambda r: r["response"].update(usage="bad"),
lambda r: r["response"]["usage"].update(total_tokens=1),
lambda r: r["response"]["usage"].update(completion_tokens=True),
lambda r: r["response"]["usage"].update(prompt_tokens_details={"cached_tokens": 21}),
]
for index, mutate in enumerate(mutations):
with self.subTest(index=index):
candidate = report()
mutate(candidate["rows"][1])
self.refuse(report(), candidate)
def test_pairing_warmups_categories_and_bounds_refused(self):
mutations = [lambda r: r["rows"].append(copy.deepcopy(r["rows"][1])),
lambda r: r["rows"].append(copy.deepcopy(r["rows"][0])),
lambda r: r["rows"].pop(), lambda r: r["rows"].pop(0),
lambda r: r["rows"][1].update(category="other"),
lambda r: r["rows"][1].update(case_id=PRIVATE),
lambda r: r["rows"][1].update(arm="candidate"),
lambda r: r["configuration"].update(repeats=101),
lambda r: r["configuration"].update(repeats=True),
lambda r: r["configuration"].update(max_tokens=True),
lambda r: r["configuration"].update(stream=True),
lambda r: r.update(schema=True), lambda r: r.update(suite_sha256="bad"),
lambda r: r.update(metadata=[])]
for index, mutate in enumerate(mutations):
with self.subTest(index=index):
candidate = report()
mutate(candidate)
self.refuse(report(), candidate)
baseline, candidate = report(), report()
baseline["metadata"]["gpu"] = "fixture-a"
candidate["metadata"]["gpu"] = "fixture-b"
self.refuse(baseline, candidate)
def test_malformed_tools_and_incomplete_terminals_refused(self):
call = {"id": "call_fixture", "type": "function", "function": {"name": "synthetic", "arguments": '{"x":1}'}}
for invalid in ("missing-id", "empty-id", "whitespace-id", "whitespace-name", "duplicate-id", "overflow", "duplicate-field", "list-arguments", "incomplete"):
with self.subTest(invalid=invalid):
candidate = report()
choice = candidate["rows"][1]["response"]["choices"][0]
choice.update(finish_reason="tool_calls", message={"role": "assistant", "content": None, "tool_calls": [copy.deepcopy(call)]})
calls = choice["message"]["tool_calls"]
if invalid == "missing-id": calls[0].pop("id")
if invalid == "empty-id": calls[0]["id"] = ""
if invalid == "whitespace-id": calls[0]["id"] = " \t"
if invalid == "whitespace-name": calls[0]["function"]["name"] = " \t"
if invalid == "duplicate-id": calls.append(copy.deepcopy(calls[0]))
if invalid == "overflow": calls[0]["function"]["arguments"] = '{"x":1e309}'
if invalid == "duplicate-field": calls[0]["function"]["arguments"] = '{"x":1,"x":2}'
if invalid == "list-arguments": calls[0]["function"]["arguments"] = '[1]'
if invalid == "incomplete": choice["finish_reason"] = "length"
self.refuse(report(), candidate)
def test_failure_terminals_never_count_as_protocol_equivalence(self):
baseline, candidate = report(), report()
for row in baseline["rows"] + candidate["rows"]:
row["quality"]["passed"] = False
row["response"]["choices"][0]["finish_reason"] = "length"
summary = self.compare(baseline, candidate)["summary"]
self.assertEqual(summary["same_normalized_output"], 0)
self.assertEqual(summary["quality"]["candidate_http_or_protocol_failed"], 6)
self.assertFalse(summary["quality"]["observed_checks_passed"])
def test_case_pair_and_nested_json_work_limits(self):
baseline = report((1.,))
for index in range(1, 65):
baseline["rows"] += report((1.,), case=f"case-{index}")["rows"]
self.refuse(baseline, copy.deepcopy(baseline))
baseline = report((1.,) * 100)
for index in range(1, 41):
baseline["rows"] += report((1.,) * 100, case=f"case-{index}")["rows"]
self.refuse(baseline, copy.deepcopy(baseline))
baseline = report()
nested = {}
for _ in range(33):
nested = {"nested": nested}
baseline["metadata"] = nested
self.refuse(baseline, report())
def test_provenance_names_only_and_never_automatic_qualification(self):
baseline, candidate = report(), report()
baseline["metadata"] = candidate["metadata"] = {"operator_note": PRIVATE, "quality_gate_result": "claimed-pass"}
result = self.compare(baseline, candidate)
missing = result["provenance"]["candidate"]["missing_fields"]
self.assertIn("gpu", missing)
self.assertIn("ttft", missing)
self.assertNotIn("quality_gate_result", missing)
self.assertNotIn(PRIVATE, json.dumps(result["provenance"]))
self.assertIn("Synthetic/CPU", result["comparison_limit"])
self.assertFalse(result["qualification"]["model_quality_qualified"])
def test_private_mode_no_overwrite_and_no_git_output(self):
old_mask = os.umask(0)
try:
self.compare(report(), report())
finally:
os.umask(old_mask)
self.assertEqual(self.out.stat().st_mode & 0o777, 0o600)
original = self.out.read_bytes()
self.assertNotEqual(self.invoke(report(), report()).returncode, 0)
self.assertEqual(self.out.read_bytes(), original)
git_directory = self.directory / "fake-git"
git_directory.mkdir()
(git_directory / ".git").write_text("gitdir: fixture")
output = git_directory / "report.json"
self.assertNotEqual(self.invoke(report(), report(), output).returncode, 0)
self.assertFalse(output.exists())
symlink = self.directory / "link.json"
destination = self.directory / "nonexistent.json"
symlink.symlink_to(destination)
self.assertNotEqual(self.invoke(report(), report(), symlink).returncode, 0)
self.assertFalse(destination.exists())
def test_duplicate_json_and_oversize_refused_without_private_diagnostic(self):
self.c.write_text(json.dumps(report()))
self.b.write_text('{"schema":1,"schema":1,"private":"' + PRIVATE + '"}')
result = subprocess.run([sys.executable, "-B", str(SCRIPT), str(self.b), str(self.c), "--output", str(self.out)], capture_output=True, text=True, timeout=15)
self.assertNotEqual(result.returncode, 0)
self.assertNotIn(PRIVATE, result.stdout + result.stderr)
self.assertFalse(self.out.exists())
with self.b.open("wb") as source:
source.truncate(32 * 1024 * 1024 + 1)
result = subprocess.run([sys.executable, "-B", str(SCRIPT), str(self.b), str(self.c), "--output", str(self.out)], capture_output=True, text=True, timeout=15)
self.assertNotEqual(result.returncode, 0)
self.assertFalse(self.out.exists())
if __name__ == "__main__":
unittest.main()