Author SHA1 Message Date
Pavlo Ratushnyi 4736b193da 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
2026-10-08 00:46:44 +02:00
11 changed files with 1121 additions and 1172 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
+3 -96
View File
@@ -9,7 +9,6 @@ import re
import shutil
import stat
import subprocess
import sys
import tempfile
import uuid
@@ -18,9 +17,6 @@ NAME = 'strata-next-linux-x86_64-musl'
FILES = {NAME, 'PROVENANCE.json', 'SHA256SUMS'}
# Official Ubuntu 26.04 linux/amd64 manifest, observed 2026-10-04; glibc is probed.
BASE = 'ubuntu@sha256:88a381d5b5eeb2b35d3ad70925a362c37ce569daf43ede89ff818ec20e4d3794'
PROBE_INFRA_TIMEOUT = 120
PROBE_APP_TIMEOUT = 30
PROBE_OUTPUT_LIMIT = 64 * 1024
def digest(path):
@@ -128,107 +124,18 @@ def docker(*args, timeout=30, check=True):
check=check, timeout=timeout)
def _bounded_output(value, stream):
if not isinstance(value, str) or len(value.encode('utf-8')) > PROBE_OUTPUT_LIMIT:
raise ValueError(f'isolated CLI {stream} exceeds {PROBE_OUTPUT_LIMIT}-byte limit')
return value
def _report_best_effort(message):
try:
print(message, file=sys.stderr, flush=True)
except BaseException:
pass
def _safe_report(message):
try:
_report_best_effort(message)
except BaseException:
pass
def _diagnose_owned_container(name):
for label, args in (
('inspect', ('inspect', '--format', '{{json .State}}', name)),
('logs', ('logs', '--tail', '40', name)),
):
try:
result = docker(*args, timeout=8, check=False)
output = (result.stdout or '') + (result.stderr or '')
if len(output.encode('utf-8')) > PROBE_OUTPUT_LIMIT:
output = '[earlier output truncated]\n' + output[-PROBE_OUTPUT_LIMIT:]
_safe_report(
f'Owned runtime-image probe {label} (exit {result.returncode}):\n{output}')
except BaseException as error:
_safe_report(
f'Owned runtime-image probe {label} unavailable: {type(error).__name__}')
def isolated_run(image, arguments, *, entrypoint=None):
name = 'strata-image-probe-' + uuid.uuid4().hex
args = ['create', '--name', name, '--platform', 'linux/amd64', '--network', 'none',
args = ['run', '--name', name, '--rm', '--platform', 'linux/amd64', '--network', 'none',
'--read-only', '--user', '65532:65532', '--cap-drop', 'ALL',
'--security-opt', 'no-new-privileges', '-e', 'CUDA_VISIBLE_DEVICES=',
'-e', 'NVIDIA_VISIBLE_DEVICES=void']
if entrypoint:
args += ['--entrypoint', entrypoint]
primary_error = None
try:
created = docker(*args, image, *arguments, timeout=PROBE_INFRA_TIMEOUT)
_bounded_output(created.stdout, 'create output')
docker('start', name, timeout=PROBE_INFRA_TIMEOUT)
waited = docker('wait', name, timeout=PROBE_APP_TIMEOUT, check=False)
_bounded_output(waited.stdout, 'wait status')
_bounded_output(waited.stderr, 'wait stderr')
if waited.returncode:
raise subprocess.CalledProcessError(
waited.returncode, ['docker', 'wait', name],
output=waited.stdout, stderr=waited.stderr)
if not re.fullmatch(r'(?:0|[1-9][0-9]{0,2})\n?', waited.stdout):
raise ValueError('docker wait returned a malformed CLI exit status')
exit_status = int(waited.stdout.rstrip('\n'))
if exit_status > 255:
raise ValueError('docker wait returned a CLI exit status outside 0..255')
logs = docker('logs', name, timeout=30, check=False)
stdout = _bounded_output(logs.stdout, 'stdout')
stderr = _bounded_output(logs.stderr, 'stderr')
if logs.returncode:
raise subprocess.CalledProcessError(
logs.returncode, ['docker', 'logs', name], output=stdout, stderr=stderr)
if exit_status:
raise subprocess.CalledProcessError(
exit_status, ['docker', 'container', 'probe', name],
output=stdout, stderr=stderr)
if stderr:
_report_best_effort(f'Runtime-image probe stderr:\n{stderr}')
return stdout
except BaseException as error:
primary_error = error
try:
_diagnose_owned_container(name)
except BaseException as diagnostic_error:
_safe_report(
f'Owned runtime-image probe diagnostics failed: {type(diagnostic_error).__name__}')
raise
return docker(*args, image, *arguments).stdout
finally:
cleanup_error = None
try:
result = docker('rm', '-f', name, timeout=10, check=False)
if result.returncode:
cleanup_error = subprocess.CalledProcessError(
result.returncode, ['docker', 'rm', '-f', name],
output=result.stdout, stderr=result.stderr)
except BaseException as error:
cleanup_error = error
if cleanup_error is not None:
if primary_error is None:
raise cleanup_error
_safe_report(
f'Owned runtime-image probe cleanup failed after '
f'{type(primary_error).__name__}: {type(cleanup_error).__name__}')
docker('rm', '-f', name, check=False)
def assemble(args):
+2 -1
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"
@@ -14,7 +16,6 @@ python3 "${repo_root}/scripts/test-static-cuda-profile.py"
python3 "${repo_root}/scripts/test-static-cuda-elf.py"
python3 "${repo_root}/scripts/test-linux-package.py"
python3 "${repo_root}/scripts/test-runtime-image.py"
python3 "${repo_root}/scripts/test-ple-config-parity.py"
python3 "${repo_root}/scripts/test-gitea-release.py"
python3 "${repo_root}/scripts/test-keyless-routing.py"
-439
View File
@@ -1,439 +0,0 @@
#!/usr/bin/env python3
"""Offline, secret-safe preflight for the Qwen GPU-PLE profile migration.
This can prove selected settings and the explicitly supplied KAR file digest.
It cannot certify deployed parity: credential, model-pack, MTP and incomplete
environment identity remain unverified unless separately established. The
legacy input must be an operator-supplied redacted projection, not the complete
original config; this proves no credential equivalence. Credential-bearing JSON
is rejected with a static category after parsing and must not be supplied.
"""
import argparse
import hashlib
import json
import os
import re
import stat
import sys
from pathlib import Path
PINNED_ARCHIVE_SHA256 = '536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5'
PINNED_NATIVE_SHARD = 'Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf'
PINNED_NATIVE_MANIFEST = 'qwen3.8-flash-next-iq3-s.json'
MAX_JSON_BYTES = 1024 * 1024
MAX_ARCHIVE_BYTES = 100 * 1024**3
MAX_ASSET_BUNDLES = 16
U64_MAX = (1 << 64) - 1
LEGACY_KEYS = {'exe', 'args', 'cwd', 'log'}
FILE_CONFIG_KEYS = {
'queue_timeout_s', 'mtp_pack', 'response_history_dir', 'assets',
'native_model', 'gpu_requirement', 'cuda_memory', 'engine_probe',
'shutdown_grace_s', 'max_in_flight_requests', 'api_key_file', 'bind',
'model', 'engine',
}
ENGINE_KEYS = {
'executable', 'args', 'startup_timeout_s', 'generation_timeout_s',
'max_restarts', 'tokenizer_dir',
}
ASSET_KEYS = {'manifest', 'directory'}
NATIVE_MODEL_KEYS = {'manifest', 'source_dir', 'output', 'runtime_profile'}
CUDA_MEMORY_KEYS = {'required_mib', 'reserve_mib'}
NONSECRET_ENV = {
'STRATA_BIND', 'STRATA_MODEL_ID', 'STRATA_ENGINE_EXE',
'STRATA_ENGINE_ARGS_JSON', 'STRATA_STARTUP_TIMEOUT_S',
'STRATA_GENERATION_TIMEOUT_S', 'STRATA_MAX_WORKER_RESTARTS',
'STRATA_TOKENIZER_DIR', 'STRATA_MAX_IN_FLIGHT_REQUESTS',
'STRATA_QUEUE_TIMEOUT_S', 'STRATA_SHUTDOWN_GRACE_S',
'STRATA_RESPONSE_HISTORY_DIR', 'CUDA_VISIBLE_DEVICES',
}
REQUIRED_SETTINGS = {
'--max-context': '262144', '--kv': 'int8', '--kv-resident': '32768',
'--spec': '4', '--spec-min-p': '0.5', '--expert-cache': 'auto',
'--prefill': 'auto', '--vram-reserve-mib': '700',
}
PLE_FLAGS = ('--ple-kar', '--ple-kar-level', '--ple-kar-gpu-cache-mib')
UNVERIFIED = {
'authentication_equivalence', 'legacy_pack_content_equivalence',
'mtp_content_equivalence', 'native_runtime_defaults', 'http_capacity_policy',
'worker_slot_count', 'request_model_identity', 'source_config_projection',
}
class InvalidInput(ValueError):
pass
def _pairs(pairs):
result = {}
for key, value in pairs:
if key in result:
raise InvalidInput('duplicate_json_key')
result[key] = value
return result
def _constant(_value):
raise InvalidInput('nonstandard_json_constant')
def read_json(path):
try:
with open_regular(path, 'invalid_json') as stream:
if os.fstat(stream.fileno()).st_size > MAX_JSON_BYTES:
raise InvalidInput('json_size_limit')
data = stream.read(MAX_JSON_BYTES + 1)
if len(data) > MAX_JSON_BYTES:
raise InvalidInput('json_size_limit')
return json.loads(data.decode('utf-8'), object_pairs_hook=_pairs,
parse_constant=_constant)
except InvalidInput:
raise
except (OSError, UnicodeError, json.JSONDecodeError, RecursionError, OverflowError):
raise InvalidInput('invalid_json') from None
def open_regular(path, category):
# O_NOFOLLOW and O_NONBLOCK are required together: never fall back to
# following a symlink or waiting for a FIFO on unsupported platforms.
if not hasattr(os, 'O_NOFOLLOW') or not hasattr(os, 'O_NONBLOCK'):
raise InvalidInput('safe_file_open_unavailable')
flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK
if hasattr(os, 'O_CLOEXEC'):
flags |= os.O_CLOEXEC
try:
fd = os.open(os.fspath(path), flags)
except (OSError, TypeError, ValueError):
raise InvalidInput(category) from None
try:
if not stat.S_ISREG(os.fstat(fd).st_mode):
raise InvalidInput(category)
return os.fdopen(fd, 'rb')
except BaseException as error:
try:
os.close(fd)
except OSError:
pass
if isinstance(error, InvalidInput):
raise
if isinstance(error, OSError):
raise InvalidInput(category) from None
raise
def _keys(value, allowed, category):
if not isinstance(value, dict) or not set(value).issubset(allowed):
raise InvalidInput(category)
def _string(value):
return isinstance(value, str) and bool(value)
def _strings(value):
return isinstance(value, list) and all(isinstance(item, str) for item in value)
def validate_legacy(value):
if isinstance(value, dict) and 'api_key' in value:
raise InvalidInput('legacy_credential_present')
_keys(value, LEGACY_KEYS, 'legacy_schema')
if set(value) != LEGACY_KEYS or not all(_string(value[key]) for key in ('exe', 'cwd', 'log')):
raise InvalidInput('legacy_schema')
if not _strings(value['args']):
raise InvalidInput('legacy_schema')
def validate_candidate(value):
_keys(value, FILE_CONFIG_KEYS, 'candidate_schema')
if 'engine' not in value or not isinstance(value['engine'], dict):
raise InvalidInput('candidate_schema')
_keys(value['engine'], ENGINE_KEYS, 'candidate_schema')
engine = value['engine']
if not _string(engine.get('executable')) or not _strings(engine.get('args', [])):
raise InvalidInput('candidate_schema')
for key, low, high in (('startup_timeout_s', 1, 3600),
('generation_timeout_s', 1, 86400),
('max_restarts', 0, 3)):
if key in engine and (type(engine[key]) is not int or not low <= engine[key] <= high):
raise InvalidInput('candidate_schema')
if 'tokenizer_dir' in engine and not _string(engine['tokenizer_dir']):
raise InvalidInput('candidate_schema')
if 'native_model' not in value or not isinstance(value['native_model'], dict):
raise InvalidInput('candidate_schema')
_keys(value['native_model'], NATIVE_MODEL_KEYS, 'candidate_schema')
if set(value['native_model']) != NATIVE_MODEL_KEYS or value['native_model'].get('runtime_profile') != 'qwen4exp-flash-next':
raise InvalidInput('candidate_schema')
for key in ('manifest', 'source_dir', 'output'):
if not _string(value['native_model'].get(key)):
raise InvalidInput('candidate_schema')
assets = value.get('assets', [])
if (not isinstance(assets, list) or len(assets) > MAX_ASSET_BUNDLES or
not all(isinstance(asset, dict) for asset in assets)):
raise InvalidInput('candidate_schema')
for asset in assets:
_keys(asset, ASSET_KEYS, 'candidate_schema')
if set(asset) != ASSET_KEYS or not all(_string(asset[key]) for key in ASSET_KEYS):
raise InvalidInput('candidate_schema')
if 'cuda_memory' in value:
_keys(value['cuda_memory'], CUDA_MEMORY_KEYS, 'candidate_schema')
if set(value['cuda_memory']) != CUDA_MEMORY_KEYS:
raise InvalidInput('candidate_schema')
required, reserve = (value['cuda_memory'][key] for key in ('required_mib', 'reserve_mib'))
if (type(required) is not int or type(reserve) is not int or required <= 0 or reserve < 0 or
required > U64_MAX or reserve > U64_MAX or required + reserve > U64_MAX):
raise InvalidInput('candidate_schema')
if 'gpu_requirement' in value and value['gpu_requirement'] != 'cuda-13.0-linux':
raise InvalidInput('candidate_schema')
for key in ('mtp_pack', 'response_history_dir', 'api_key_file', 'bind', 'model'):
if key in value and not _string(value[key]):
raise InvalidInput('candidate_schema')
if 'queue_timeout_s' in value and (type(value['queue_timeout_s']) is not int or
not 1 <= value['queue_timeout_s'] <= 86400):
raise InvalidInput('candidate_schema')
if 'shutdown_grace_s' in value and (type(value['shutdown_grace_s']) is not int or
not 0 <= value['shutdown_grace_s'] <= 20):
raise InvalidInput('candidate_schema')
if 'max_in_flight_requests' in value and (type(value['max_in_flight_requests']) is not int or
not 1 <= value['max_in_flight_requests'] <= 256):
raise InvalidInput('candidate_schema')
if 'engine_probe' in value and type(value['engine_probe']) is not bool:
raise InvalidInput('candidate_schema')
if 'mtp_pack' not in value or not _string(value['mtp_pack']):
raise InvalidInput('candidate_schema')
if 'tokenizer_dir' in engine:
raise InvalidInput('candidate_schema')
def validate_context(value):
_keys(value, {'legacy', 'candidate', 'environment_complete'}, 'service_context_schema')
if set(value) != {'legacy', 'candidate', 'environment_complete'} or not isinstance(value['environment_complete'], bool):
raise InvalidInput('service_context_schema')
for side in ('legacy', 'candidate'):
item = value[side]
allowed = {'bind', 'cwd', 'log', 'effective_slots', 'environment'}
required = allowed - {'effective_slots'}
_keys(item, allowed, 'service_context_schema')
if not required.issubset(item) or not all(_string(item[k]) for k in ('bind', 'cwd', 'log')):
raise InvalidInput('service_context_schema')
if ('effective_slots' in item and
(type(item['effective_slots']) is not int or item['effective_slots'] < 0)):
raise InvalidInput('service_context_schema')
env = item['environment']
if not isinstance(env, dict) or not set(env).issubset(NONSECRET_ENV):
raise InvalidInput('service_context_schema')
if not all(isinstance(v, str) for v in env.values()):
raise InvalidInput('service_context_schema')
def option_values(arguments, name):
found = []
index = 0
while index < len(arguments):
token = arguments[index]
if token == name:
if index + 1 >= len(arguments) or arguments[index + 1].startswith('--'):
raise InvalidInput('engine_arguments')
found.append(arguments[index + 1])
index += 2
elif token.startswith(name + '='):
found.append(token[len(name) + 1:])
index += 1
else:
index += 1
if len(found) > 1:
raise InvalidInput('duplicate_engine_option')
return found
def strip_legacy_migrations(arguments):
result = []
migrated = {'--pack', '--native', '--mtp'}
seen = set()
index = 0
while index < len(arguments):
token = arguments[index]
name = token.split('=', 1)[0]
if name in migrated:
if name in seen or token != name or index + 1 >= len(arguments) or arguments[index + 1].startswith('--'):
raise InvalidInput('legacy_model_arguments')
seen.add(name)
index += 2
else:
result.append(token)
index += 1
if seen != migrated:
raise InvalidInput('legacy_model_arguments')
return result
def ple_selection(arguments, archive_path):
"""Return argv without its PLE tuple and whether the exact tuple was present."""
seen = [token for token in arguments
if any(token == flag or token.startswith(flag + '=') for flag in PLE_FLAGS)]
if not seen:
return list(arguments), False
expected = [PLE_FLAGS[0], str(archive_path), PLE_FLAGS[1], '2', PLE_FLAGS[2], '64']
if arguments[-len(expected):] != expected:
raise InvalidInput('ple_arguments')
if len(seen) != len(PLE_FLAGS):
raise InvalidInput('ple_arguments')
return list(arguments[:-len(expected)]), True
def check_archive(path, expected):
if not re.fullmatch(r'[0-9a-f]{64}', expected) or expected != PINNED_ARCHIVE_SHA256:
raise InvalidInput('archive_pin')
try:
stream = open_regular(path, 'archive_file')
with stream:
if os.fstat(stream.fileno()).st_size > MAX_ARCHIVE_BYTES:
raise InvalidInput('archive_size_limit')
_verify_archive_stream(stream, expected)
except InvalidInput:
raise
except OSError:
raise InvalidInput('archive_file') from None
def _verify_archive_stream(stream, expected):
digest = hashlib.sha256()
size = 0
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
size += len(chunk)
if size > MAX_ARCHIVE_BYTES:
raise InvalidInput('archive_size_limit')
digest.update(chunk)
if digest.hexdigest() != expected:
raise InvalidInput('archive_digest')
def compare(legacy, candidate, context, archive_path, archive_sha, expected_executable,
expected_bind, expected_log):
validate_legacy(legacy)
validate_candidate(candidate)
validate_context(context)
check_archive(archive_path, archive_sha)
mismatches = []
unverified = sorted(UNVERIFIED)
engine = candidate['engine']
legacy_args = legacy['args']
candidate_args = engine.get('args', [])
legacy_env = context['legacy']['environment']
candidate_env = context['candidate']['environment']
effective_executable = candidate_env.get('STRATA_ENGINE_EXE', engine['executable'])
effective_bind = candidate_env.get('STRATA_BIND', candidate.get('bind', '127.0.0.1:8081'))
if effective_executable != expected_executable or not _string(expected_executable):
mismatches.append('executable_selection')
slots = [context[side].get('effective_slots') for side in ('legacy', 'candidate')]
if any(value is None for value in slots):
unverified.append('worker_slot_count')
elif slots != [1, 1]:
mismatches.append('slot_count')
if context['legacy']['cwd'] != context['candidate']['cwd']:
mismatches.append('working_directory')
if context['candidate']['bind'] != expected_bind or effective_bind != context['candidate']['bind']:
mismatches.append('bind_selection')
if context['candidate']['log'] != expected_log:
mismatches.append('log_selection')
for name in set(legacy_env) | set(candidate_env):
if legacy_env.get(name) == candidate_env.get(name):
continue
if name == 'STRATA_BIND':
# The bind delta is explicit and independently checked above.
continue
if name == 'STRATA_ENGINE_EXE' and candidate_env.get(name) == expected_executable:
# The executable delta is explicit and independently checked above.
continue
mismatches.append('environment_delta')
break
effective_args = candidate_args
if 'STRATA_ENGINE_ARGS_JSON' in candidate_env:
try:
override = json.loads(candidate_env['STRATA_ENGINE_ARGS_JSON'], object_pairs_hook=_pairs,
parse_constant=_constant)
except (InvalidInput, json.JSONDecodeError):
mismatches.append('engine_arguments')
else:
if not _strings(override):
mismatches.append('engine_arguments')
else:
effective_args = override
if effective_args != candidate_args:
mismatches.append('engine_arguments')
if 'STRATA_ENGINE_ARGS_JSON' in legacy_env:
mismatches.append('environment_delta')
if not context['environment_complete']:
unverified.append('effective_environment')
try:
legacy_base, _had_legacy_ple = ple_selection(legacy_args, archive_path)
legacy_base = strip_legacy_migrations(legacy_base)
candidate_base, had_candidate_ple = ple_selection(effective_args, archive_path)
expected_base = legacy_base + [
PLE_FLAGS[0], str(archive_path), PLE_FLAGS[1], '2', PLE_FLAGS[2], '64']
if not had_candidate_ple or candidate_base != legacy_base or effective_args != expected_base:
mismatches.append('engine_arguments')
for flag, wanted in REQUIRED_SETTINGS.items():
if option_values(legacy_args, flag) != [wanted] or option_values(effective_args, flag) != [wanted]:
mismatches.append('profile_settings')
for flag in ('--pack', '--native', '--gguf', '--mtp'):
if option_values(effective_args, flag):
mismatches.append('native_asset_mapping')
legacy_mtp = option_values(legacy_args, '--mtp')
legacy_native = option_values(legacy_args, '--native')
if legacy_mtp != [candidate.get('mtp_pack')]:
mismatches.append('mtp_asset_mapping')
if (len(legacy_native) != 1 or Path(legacy_native[0]).name != PINNED_NATIVE_SHARD or
Path(candidate['native_model']['source_dir']) != Path(legacy_native[0]).parent or
Path(candidate['native_model']['manifest']).name != PINNED_NATIVE_MANIFEST):
mismatches.append('model_selection')
except InvalidInput as error:
mismatches.append(error.args[0] if error.args and error.args[0] in {
'legacy_model_arguments', 'duplicate_engine_option', 'engine_arguments', 'ple_arguments'
} else 'engine_arguments')
if candidate.get('mtp_pack') not in [asset['directory'] for asset in candidate.get('assets', [])]:
mismatches.append('mtp_asset_mapping')
if context['legacy']['bind'] == '' or context['legacy']['log'] == '':
mismatches.append('service_context')
if candidate.get('api_key_file') is None:
mismatches.append('authentication_configuration')
# The candidate's strict schema is checked, but source pack/MTP contents and
# credentials are intentionally not opened by this preflight.
return {
'status': 'mismatch' if mismatches else 'incomplete' if unverified else 'verified',
'mismatches': sorted(set(mismatches)),
'unverified': sorted(set(unverified)),
}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--legacy-config', required=True,
help='operator-supplied redacted projection (exe/args/cwd/log only; never the original file or api_key)')
parser.add_argument('--candidate-config', required=True)
parser.add_argument('--service-context', required=True)
parser.add_argument('--archive', required=True)
parser.add_argument('--archive-sha256', required=True)
parser.add_argument('--expected-executable', required=True)
parser.add_argument('--expected-bind', required=True)
parser.add_argument('--expected-log', required=True)
args = parser.parse_args(argv)
try:
result = compare(read_json(args.legacy_config), read_json(args.candidate_config),
read_json(args.service_context), args.archive, args.archive_sha256,
args.expected_executable, args.expected_bind, args.expected_log)
except InvalidInput as error:
result = {'status': 'mismatch', 'mismatches': [error.args[0]], 'unverified': sorted(UNVERIFIED)}
except Exception:
result = {'status': 'mismatch', 'mismatches': ['internal_validation_error'],
'unverified': sorted(UNVERIFIED)}
print(json.dumps(result, sort_keys=True))
return {'verified': 0, 'mismatch': 1, 'incomplete': 2}[result['status']]
if __name__ == '__main__':
sys.exit(main())
+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()
-357
View File
@@ -1,357 +0,0 @@
#!/usr/bin/env python3
"""Synthetic, offline tests for the secret-safe PLE parity preflight."""
import importlib.util
import hashlib
import io
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from contextlib import redirect_stdout
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('parity', Path(__file__).with_name('check-ple-config-parity.py'))
parity = importlib.util.module_from_spec(spec)
spec.loader.exec_module(parity)
class ParityTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.archive = self.root / 'synthetic.kar'
self.archive.write_bytes(b'synthetic archive bytes')
self.archive_sha = hashlib.sha256(self.archive.read_bytes()).hexdigest()
self.legacy_args = [
'--pack', '/models/current-pack', '--native',
'/models/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf',
'--max-context', '262144', '--kv', 'int8', '--kv-resident', '32768',
'--spec', '4', '--spec-min-p', '0.5', '--expert-cache', 'auto',
'--prefill', 'auto', '--vram-reserve-mib', '700', '--mtp', '/models/mtp-v1',
]
self.candidate_executable = '/runtime/strata-next'
self.ple = ['--ple-kar', str(self.archive), '--ple-kar-level', '2',
'--ple-kar-gpu-cache-mib', '64']
self.legacy = {'exe': '/legacy/strata', 'args': list(self.legacy_args),
'cwd': '/srv/qwen', 'log': '/var/log/old-engine.log'}
self.candidate = {
'bind': '127.0.0.1:18081',
'api_key_file': str(self.root / 'unread-api-key'),
'max_in_flight_requests': 1,
'engine': {'executable': self.candidate_executable,
'args': self.legacy_args_after_migration() + self.ple,
'startup_timeout_s': 600, 'max_restarts': 0},
'native_model': {'manifest': '/fixtures/qwen3.8-flash-next-iq3-s.json',
'source_dir': '/models', 'output': '/models/new-pack',
'runtime_profile': 'qwen4exp-flash-next'},
'assets': [{'manifest': '/fixtures/mtp-manifest.json',
'directory': '/models/mtp-v1'}],
'mtp_pack': '/models/mtp-v1',
}
self.context = {
'legacy': {'bind': '192.168.1.196:18081', 'cwd': '/srv/qwen',
'log': '/var/log/old-engine.log', 'effective_slots': 1,
'environment': {}},
'candidate': {'bind': '127.0.0.1:18081', 'cwd': '/srv/qwen',
'log': 'systemd-journal', 'effective_slots': 1,
'environment': {}},
'environment_complete': True,
}
self.expected_sha = parity.PINNED_ARCHIVE_SHA256
def legacy_args_after_migration(self):
result = []
skip = False
for token in self.legacy_args:
if skip:
skip = False
elif token in {'--pack', '--native', '--mtp'}:
skip = True
else:
result.append(token)
return result
def run_compare(self, *, legacy=None, candidate=None, context=None):
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha):
return parity.compare(legacy or self.legacy, candidate or self.candidate,
context or self.context, self.archive, self.archive_sha,
self.candidate_executable, '127.0.0.1:18081', 'systemd-journal')
def test_baseline_to_gpu_ple_is_incomplete_not_full_pass(self):
result = self.run_compare()
self.assertEqual(result['status'], 'incomplete')
self.assertEqual(result['mismatches'], [])
self.assertEqual(set(result['unverified']), parity.UNVERIFIED)
self.assertIn('request_model_identity', result['unverified'])
def test_already_ple_selected_in_original_is_preserved_exactly(self):
legacy = json.loads(json.dumps(self.legacy))
legacy['args'] += self.ple
candidate = json.loads(json.dumps(self.candidate))
candidate['engine']['args'] = self.legacy_args_after_migration() + self.ple
self.assertEqual(self.run_compare(legacy=legacy, candidate=candidate)['mismatches'], [])
def test_partial_duplicate_changed_or_reordered_ple_fails(self):
cases = [
self.ple[:-2],
self.ple + self.ple,
['--ple-kar', str(self.archive), '--ple-kar-level', '3', '--ple-kar-gpu-cache-mib', '64'],
['--ple-kar-level', '2', '--ple-kar', str(self.archive), '--ple-kar-gpu-cache-mib', '64'],
]
for flags in cases:
with self.subTest(flags=flags):
legacy = json.loads(json.dumps(self.legacy))
legacy['args'] += flags
result = self.run_compare(legacy=legacy)
self.assertIn('ple_arguments', result['mismatches'])
def test_malformed_candidate_ple_tuple_is_rejected(self):
cases = [
self.ple[:-2],
self.ple + self.ple,
['--ple-kar', str(self.archive), '--ple-kar-level', '1',
'--ple-kar-gpu-cache-mib', '64'],
['--ple-kar-level', '2', '--ple-kar', str(self.archive),
'--ple-kar-gpu-cache-mib', '64'],
]
for flags in cases:
with self.subTest(flags=flags):
candidate = json.loads(json.dumps(self.candidate))
candidate['engine']['args'] = self.legacy_args_after_migration() + flags
result = self.run_compare(candidate=candidate)
self.assertIn('ple_arguments', result['mismatches'])
def test_changes_to_non_ple_model_mtp_and_profile_settings_fail(self):
cases = []
altered = json.loads(json.dumps(self.candidate))
altered['engine']['args'][1] = '262143'
cases.append((altered, 'profile_settings'))
altered = json.loads(json.dumps(self.legacy))
altered['args'][3] = '/models/Other-IQ3_S.gguf'
cases.append((altered, 'model_selection'))
altered = json.loads(json.dumps(self.candidate))
altered['mtp_pack'] = '/models/mtp-other'
altered['assets'][0]['directory'] = '/models/mtp-other'
cases.append((altered, 'mtp_asset_mapping'))
altered = json.loads(json.dumps(self.candidate))
altered['engine']['args'].insert(0, '--force')
altered['engine']['args'].insert(1, 'other')
cases.append((altered, 'engine_arguments'))
for value, expected in cases:
with self.subTest(expected=expected):
if expected in ('model_selection',):
result = self.run_compare(legacy=value)
else:
result = self.run_compare(candidate=value)
self.assertIn(expected, result['mismatches'])
def test_every_retained_profile_setting_must_match_on_both_sides(self):
for flag, wanted in parity.REQUIRED_SETTINGS.items():
with self.subTest(flag=flag, side='legacy'):
legacy = json.loads(json.dumps(self.legacy))
index = legacy['args'].index(flag)
legacy['args'][index + 1] = f'{wanted}-changed'
self.assertIn('profile_settings',
self.run_compare(legacy=legacy)['mismatches'])
with self.subTest(flag=flag, side='candidate'):
candidate = json.loads(json.dumps(self.candidate))
index = candidate['engine']['args'].index(flag)
candidate['engine']['args'][index + 1] = f'{wanted}-changed'
self.assertIn('profile_settings',
self.run_compare(candidate=candidate)['mismatches'])
def test_service_context_requires_bind_workdir_log_and_one_slot(self):
for key, value in [('cwd', '/srv/other'), ('bind', '0.0.0.0:18081'),
('log', '/tmp/other.log'), ('effective_slots', 2)]:
context = json.loads(json.dumps(self.context))
context['candidate'][key] = value
result = self.run_compare(context=context)
expected = {'cwd': 'working_directory', 'bind': 'bind_selection',
'log': 'log_selection', 'effective_slots': 'slot_count'}[key]
self.assertIn(expected, result['mismatches'])
context = json.loads(json.dumps(self.context))
context['environment_complete'] = False
self.assertIn('effective_environment', self.run_compare(context=context)['unverified'])
for side in ('legacy', 'candidate'):
context = json.loads(json.dumps(self.context))
context[side].pop('effective_slots')
result = self.run_compare(context=context)
self.assertNotIn('slot_count', result['mismatches'])
self.assertIn('worker_slot_count', result['unverified'])
def test_only_declared_bind_and_executable_environment_deltas_are_allowed(self):
context = json.loads(json.dumps(self.context))
context['candidate']['environment'] = {
'STRATA_BIND': '127.0.0.1:18081',
'STRATA_ENGINE_EXE': self.candidate_executable,
}
self.assertEqual(self.run_compare(context=context)['mismatches'], [])
context['candidate']['environment']['CUDA_VISIBLE_DEVICES'] = '1'
self.assertIn('environment_delta', self.run_compare(context=context)['mismatches'])
def test_http_request_capacity_is_not_confused_with_worker_slot_count(self):
candidate = json.loads(json.dumps(self.candidate))
candidate.pop('max_in_flight_requests')
result = self.run_compare(candidate=candidate)
self.assertNotIn('slot_count', result['mismatches'])
self.assertIn('http_capacity_policy', result['unverified'])
def test_archive_bytes_are_stream_checked_against_pin(self):
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha):
parity.check_archive(self.archive, self.archive_sha)
self.archive.write_bytes(b'corrupted fixture')
with self.assertRaisesRegex(parity.InvalidInput, 'archive_digest'):
parity.check_archive(self.archive, self.archive_sha)
with self.assertRaisesRegex(parity.InvalidInput, 'archive_pin'):
parity.check_archive(self.archive, '0' * 64)
def test_strict_json_rejects_duplicates_constants_invalid_utf8_and_nonobject(self):
path = self.root / 'config.json'
for raw in (b'{"x":1,"x":2}', b'{"x":NaN}', b'\xff', b'[]'):
with self.subTest(raw=raw):
path.write_bytes(raw)
with self.assertRaises(parity.InvalidInput):
value = parity.read_json(path)
parity.validate_legacy(value)
def test_json_parser_recursion_and_overflow_errors_are_bounded(self):
path = self.root / 'nested.json'
path.write_text('{}')
for error in (RecursionError, OverflowError):
with self.subTest(error=error.__name__):
with patch.object(parity.json, 'loads', side_effect=error):
with self.assertRaisesRegex(parity.InvalidInput, 'invalid_json'):
parity.read_json(path)
def test_safe_file_open_accepts_regular_files_and_rejects_symlinks(self):
config = self.root / 'regular.json'
config.write_text('{}')
self.assertEqual(parity.read_json(config), {})
config_link = self.root / 'config-link.json'
config_link.symlink_to(config)
with self.assertRaisesRegex(parity.InvalidInput, 'invalid_json'):
parity.read_json(config_link)
archive_link = self.root / 'archive-link.kar'
archive_link.symlink_to(self.archive)
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha):
with self.assertRaisesRegex(parity.InvalidInput, 'archive_file'):
parity.check_archive(archive_link, self.archive_sha)
@unittest.skipUnless(hasattr(os, 'mkfifo'), 'named FIFO unavailable')
def test_named_fifo_is_rejected_quickly_for_json_and_archive(self):
fifo = self.root / 'input.fifo'
os.mkfifo(fifo)
module_path = Path(__file__).with_name('check-ple-config-parity.py')
code = (
"import importlib.util,sys; "
"s=importlib.util.spec_from_file_location('p',sys.argv[1]); "
"m=importlib.util.module_from_spec(s); s.loader.exec_module(m); "
"\ntry:\n"
" if sys.argv[3]=='json': m.read_json(sys.argv[2])\n"
" else: m.check_archive(sys.argv[2],m.PINNED_ARCHIVE_SHA256)\n"
"except m.InvalidInput: pass\nelse: raise SystemExit(9)"
)
for kind in ('json', 'archive'):
with self.subTest(kind=kind):
result = subprocess.run(
[sys.executable, '-c', code, str(module_path), str(fifo), kind],
capture_output=True, text=True, timeout=2)
self.assertEqual(result.returncode, 0, result.stderr)
def test_nonregular_open_failure_closes_the_descriptor(self):
opened = []
real_open = os.open
def capture(path, flags):
fd = real_open(path, flags)
opened.append(fd)
return fd
with patch.object(parity.os, 'open', capture):
with self.assertRaisesRegex(parity.InvalidInput, 'invalid_json'):
parity.open_regular(self.root, 'invalid_json')
self.assertEqual(len(opened), 1)
with self.assertRaises(OSError):
os.fstat(opened[0])
def test_candidate_resource_limits_match_runtime_bounds(self):
cases = []
candidate = json.loads(json.dumps(self.candidate))
candidate['max_in_flight_requests'] = 257
cases.append(candidate)
candidate = json.loads(json.dumps(self.candidate))
candidate['assets'] = [{'manifest': f'/m/{i}', 'directory': f'/a/{i}'}
for i in range(parity.MAX_ASSET_BUNDLES + 1)]
cases.append(candidate)
for memory in ({'required_mib': parity.U64_MAX + 1, 'reserve_mib': 0},
{'required_mib': parity.U64_MAX, 'reserve_mib': 1},
{'required_mib': 1, 'reserve_mib': -1}):
candidate = json.loads(json.dumps(self.candidate))
candidate['cuda_memory'] = memory
cases.append(candidate)
for candidate in cases:
with self.subTest(candidate=candidate):
with self.assertRaisesRegex(parity.InvalidInput, 'candidate_schema'):
parity.validate_candidate(candidate)
def test_unknown_legacy_and_native_keys_are_rejected(self):
legacy = dict(self.legacy, future_secret_setting='opaque')
with self.assertRaisesRegex(parity.InvalidInput, 'legacy_schema'):
parity.validate_legacy(legacy)
with self.assertRaisesRegex(parity.InvalidInput, 'legacy_credential_present'):
parity.validate_legacy(dict(self.legacy, api_key='must-not-be-read'))
candidate = json.loads(json.dumps(self.candidate))
candidate['future_runtime_setting'] = True
with self.assertRaisesRegex(parity.InvalidInput, 'candidate_schema'):
parity.validate_candidate(candidate)
candidate = json.loads(json.dumps(self.candidate))
candidate['engine']['future_runtime_setting'] = True
with self.assertRaisesRegex(parity.InvalidInput, 'candidate_schema'):
parity.validate_candidate(candidate)
def test_candidate_secret_file_is_not_opened_and_output_never_contains_secret(self):
secret_path = Path(self.candidate['api_key_file'])
secret_path.write_text('synthetic-secret-do-not-print')
original_open = Path.open
def guarded_open(path, *args, **kwargs):
if path == secret_path:
raise AssertionError('secret file must not be opened')
return original_open(path, *args, **kwargs)
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha), \
patch.object(Path, 'open', guarded_open):
output = parity.compare(self.legacy, self.candidate, self.context, self.archive,
self.archive_sha, self.candidate_executable,
'127.0.0.1:18081', 'systemd-journal')
encoded = json.dumps(output)
self.assertNotIn('synthetic-secret', encoded)
self.assertEqual(output['status'], 'incomplete')
def test_cli_prints_safe_json_and_returns_two_for_positive_incomplete_fixture(self):
legacy_path = self.root / 'legacy.json'
candidate_path = self.root / 'candidate.json'
context_path = self.root / 'context.json'
for path, value in ((legacy_path, self.legacy), (candidate_path, self.candidate),
(context_path, self.context)):
path.write_text(json.dumps(value))
stdout = io.StringIO()
argv = ['--legacy-config', str(legacy_path), '--candidate-config', str(candidate_path),
'--service-context', str(context_path), '--archive', str(self.archive),
'--archive-sha256', self.archive_sha, '--expected-executable', self.candidate_executable,
'--expected-bind', '127.0.0.1:18081', '--expected-log', 'systemd-journal']
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha), redirect_stdout(stdout):
result = parity.main(argv)
self.assertEqual(result, 2)
self.assertNotIn('synthetic-secret', stdout.getvalue())
self.assertNotIn(str(self.root), stdout.getvalue())
self.assertEqual(json.loads(stdout.getvalue())['status'], 'incomplete')
if __name__ == '__main__':
unittest.main()
-139
View File
@@ -3,7 +3,6 @@
import importlib.util
import hashlib
import json
import subprocess
from pathlib import Path
import shutil
import tempfile
@@ -157,143 +156,5 @@ class PackageTests(unittest.TestCase):
b.frozen_file(self.pkg/b.NAME, Path(stage)/'out', 1)
class IsolatedProbeTests(unittest.TestCase):
def setUp(self):
reporter = patch.object(b, '_report_best_effort')
reporter.start()
self.addCleanup(reporter.stop)
def fake_docker(self, calls, *, wait_stdout='0\n', wait_stderr='', wait_rc=0,
logs_stdout='probe output\n', logs_stderr='', logs_rc=0,
start_error=None, wait_error=None, cleanup_error=None, logs_size=None):
container = None
def invoke(*args, timeout=30, check=True):
nonlocal container
calls.append((args, timeout, check))
if args[0] == 'create':
container = args[args.index('--name') + 1]
return SimpleNamespace(stdout='a' * 64 + '\n', stderr='', returncode=0)
if args[0] == 'start':
self.assertEqual(args[1], container)
if start_error is not None:
raise start_error
return SimpleNamespace(stdout=container + '\n', stderr='', returncode=0)
if args[0] == 'wait':
self.assertEqual(args[1], container)
if wait_error is not None:
raise wait_error
return SimpleNamespace(stdout=wait_stdout, stderr=wait_stderr, returncode=wait_rc)
if args[0] == 'logs':
self.assertEqual(args[-1], container)
stdout = logs_stdout if logs_size is None else 'x' * logs_size
return SimpleNamespace(stdout=stdout, stderr=logs_stderr, returncode=logs_rc)
if args[:2] == ('inspect', '--format'):
self.assertEqual(args[-1], container)
raise OSError('synthetic inspect unavailable')
if args[0] == 'inspect':
self.assertEqual(args[-1], container)
raise OSError('synthetic inspect unavailable')
if args[:2] == ('rm', '-f'):
self.assertEqual(args[-1], container)
if cleanup_error is not None:
raise cleanup_error
return SimpleNamespace(stdout='', stderr='', returncode=0)
raise AssertionError(f'unexpected Docker call: {args!r}')
return invoke
def test_probe_uses_long_infrastructure_deadline_and_original_cli_deadline(self):
calls = []
with patch.object(b, 'docker', side_effect=self.fake_docker(calls)):
output = b.isolated_run('sha256:' + 'a' * 64, ['engine-info'], entrypoint='strata-next')
self.assertEqual(output, 'probe output\n')
operations = [call[0][0] for call in calls]
self.assertEqual(operations, ['create', 'start', 'wait', 'logs', 'rm'])
create, start, wait, logs, remove = calls
self.assertEqual(create[1], 120)
self.assertEqual(start[1], 120)
self.assertEqual(wait[1], 30)
self.assertEqual(logs[1], 30)
self.assertEqual(remove[1], 10)
self.assertNotIn('--rm', create[0])
self.assertEqual(create[0][create[0].index('--network') + 1], 'none')
self.assertIn('--read-only', create[0])
self.assertIn('--cap-drop', create[0])
self.assertIn('65532:65532', create[0])
self.assertIn('strata-next', create[0])
self.assertEqual(start[0][1], create[0][create[0].index('--name') + 1])
self.assertEqual(wait[0][1], start[0][1])
self.assertEqual(logs[0][-1], start[0][1])
self.assertEqual(remove[0][-1], start[0][1])
def test_probe_rejects_malformed_wait_status_and_bounds_both_streams(self):
for status in ('', '0\n1\n', '-1\n', '256\n'):
with self.subTest(status=status):
calls = []
with patch.object(b, 'docker', side_effect=self.fake_docker(calls, wait_stdout=status)):
with self.assertRaisesRegex(ValueError, 'malformed CLI exit status|outside 0..255'):
b.isolated_run('image', ['engine-help'])
self.assertEqual([x[0][0] for x in calls[:3]], ['create', 'start', 'wait'])
self.assertEqual(calls[-1][0][0:2], ('rm', '-f'))
for stream in ('stdout', 'stderr'):
with self.subTest(stream=stream):
calls = []
kwargs = {'logs_size': b.PROBE_OUTPUT_LIMIT + 1} if stream == 'stdout' else {
'logs_stderr': 'x' * (b.PROBE_OUTPUT_LIMIT + 1)}
with patch.object(b, 'docker', side_effect=self.fake_docker(calls, **kwargs)):
with self.assertRaisesRegex(ValueError, f'CLI {stream} exceeds'):
b.isolated_run('image', ['engine-help'])
self.assertEqual(calls[-1][0][0:2], ('rm', '-f'))
def test_nonzero_cli_exit_preserves_both_streams(self):
calls = []
with patch.object(b, 'docker', side_effect=self.fake_docker(
calls, wait_stdout='17\n', logs_stdout='help stdout', logs_stderr='help stderr')):
with self.assertRaises(subprocess.CalledProcessError) as raised:
b.isolated_run('image', ['engine-help'])
self.assertEqual(raised.exception.returncode, 17)
self.assertEqual(raised.exception.output, 'help stdout')
self.assertEqual(raised.exception.stderr, 'help stderr')
self.assertEqual([x[0][0] for x in calls[:4]], ['create', 'start', 'wait', 'logs'])
self.assertEqual(calls[-1][0][0:2], ('rm', '-f'))
def test_infrastructure_timeout_keeps_original_across_broken_reporting_and_cleanup(self):
calls = []
timeout = subprocess.TimeoutExpired(['docker', 'start'], 120)
with patch.object(b, 'docker', side_effect=self.fake_docker(
calls, start_error=timeout,
cleanup_error=subprocess.TimeoutExpired(['docker', 'rm'], 10))), \
patch.object(b, '_report_best_effort', side_effect=BrokenPipeError('closed stderr')):
with self.assertRaises(subprocess.TimeoutExpired) as raised:
b.isolated_run('image', ['engine-info'])
self.assertIs(raised.exception, timeout)
operations = [x[0][0] for x in calls]
self.assertEqual(operations, ['create', 'start', 'inspect', 'logs', 'rm'])
container = calls[0][0][calls[0][0].index('--name') + 1]
self.assertTrue(all(call[0][-1] == container for call in calls[2:]))
self.assertTrue(all(call[1] <= 10 for call in calls[2:]))
def test_application_timeout_is_not_extended_by_infrastructure_deadlines(self):
calls = []
timeout = subprocess.TimeoutExpired(['docker', 'wait'], 30)
with patch.object(b, 'docker', side_effect=self.fake_docker(calls, wait_error=timeout)):
with self.assertRaises(subprocess.TimeoutExpired) as raised:
b.isolated_run('image', ['engine-help'])
self.assertIs(raised.exception, timeout)
self.assertEqual([x[1] for x in calls[:3]], [120, 120, 30])
self.assertEqual(calls[-1][0][:2], ('rm', '-f'))
def test_cleanup_failure_after_success_is_not_silently_ignored(self):
calls = []
with patch.object(b, 'docker', side_effect=self.fake_docker(
calls, cleanup_error=OSError('synthetic cleanup failure'))):
with self.assertRaisesRegex(OSError, 'synthetic cleanup failure'):
b.isolated_run('image', ['engine-info'])
self.assertEqual(calls[-1][0][0:2], ('rm', '-f'))
self.assertEqual(calls[-1][1], 10)
if __name__ == '__main__':
unittest.main()