Harden Spark measurement identity and fresh output checks

This commit is contained in:
Constantin committed 2026-11-03 13:53:27 -05:00
1 parent 4a60c64ec5
commit a4403a1a90
4 files changed
+100 -11

No files matched your search

+5 -1
View File
@@ -156,7 +156,11 @@ These are end-to-end request measurements (prefill plus decode and service overh
throughput or task scores. Every response must report positive integer prompt usage and exactly throughput or task scores. Every response must report positive integer prompt usage and exactly
`--max-tokens` generated tokens with a `length` finish (EOS is ignored for this fixed-work smoke). `--max-tokens` generated tokens with a `length` finish (EOS is ignored for this fixed-work smoke).
Missing, zero or short counts fail the run rather than producing a successful throughput receipt. Missing, zero or short counts fail the run rather than producing a successful throughput receipt.
Runtime/model/plugin hashes are checked again before writing the receipt; use a fresh `--out`: The prompt file is parsed and hashed from the same byte snapshot and rechecked before receipt; the
private server uses a unique served model ID and is checked for identity and liveness. Requests per
repeat must be at least the largest requested concurrency. This is a client concurrency level, not
proof that requests actually overlapped in a server batch. Runtime/model/plugin hashes are also
checked again before writing the receipt; use a fresh `--out`:
```sh ```sh
python3 tests/spark25_qos.py \\ python3 tests/spark25_qos.py \\
+24 -7
View File
@@ -7,6 +7,7 @@ strings at the requested concurrency levels. It records artifact hashes, p50/p95
latency, and aggregate generated-token throughput; it does not claim task quality. latency, and aggregate generated-token throughput; it does not claim task quality.
""" """
import argparse import argparse
import hashlib
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
import json import json
import math import math
@@ -18,6 +19,7 @@ import sys
import time import time
import urllib.error import urllib.error
import urllib.request import urllib.request
import uuid
from spark25_validation import plugin_hashes, sha256 from spark25_validation import plugin_hashes, sha256
@@ -32,9 +34,9 @@ def quantile(values, q):
return values[lo] if lo + 1 == len(values) else values[lo] + (at - lo) * (values[lo + 1] - values[lo]) return values[lo] if lo + 1 == len(values) else values[lo] + (at - lo) * (values[lo + 1] - values[lo])
def prompts_from(path): def prompts_from(path, raw):
prompts = [] prompts = []
for line_no, line in enumerate(Path(path).read_text().splitlines(), 1): for line_no, line in enumerate(raw.decode('utf-8').splitlines(), 1):
if not line: if not line:
continue continue
row = json.loads(line) row = json.loads(line)
@@ -72,6 +74,15 @@ def request(url, model, prompt, max_tokens, timeout):
"completion_tokens": completed, "finish_reason": "length"} "completion_tokens": completed, "finish_reason": "length"}
def verify_server(url, served, proc):
if proc.poll() is not None:
raise RuntimeError("candidate server exited during measurement")
with urllib.request.urlopen(url + "/v1/models", timeout=5) as response:
models = json.load(response)
if served not in {item.get("id") for item in models.get("data", [])} or proc.poll() is not None:
raise RuntimeError("private server identity does not match the launched candidate")
def main(): def main():
p = argparse.ArgumentParser(description=__doc__) p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--radiance", required=True, type=Path) p.add_argument("--radiance", required=True, type=Path)
@@ -94,7 +105,9 @@ def main():
radiance, home, model = args.radiance.resolve(), args.home.resolve(), args.model.resolve() radiance, home, model = args.radiance.resolve(), args.home.resolve(), args.model.resolve()
prompt_path, out = args.prompts.resolve(), args.out.resolve() prompt_path, out = args.prompts.resolve(), args.out.resolve()
prompts = prompts_from(prompt_path) prompt_bytes = prompt_path.read_bytes()
prompt_hash = hashlib.sha256(prompt_bytes).hexdigest()
prompts = prompts_from(prompt_path, prompt_bytes)
concurrencies = [int(x) for x in args.concurrency.split(",")] concurrencies = [int(x) for x in args.concurrency.split(",")]
if not concurrencies or any(x < 1 for x in concurrencies): if not concurrencies or any(x < 1 for x in concurrencies):
p.error("--concurrency must be comma-separated positive integers") p.error("--concurrency must be comma-separated positive integers")
@@ -102,6 +115,8 @@ def main():
args.max_model_len < 1 or args.max_num_batched_tokens < 1 or args.gpu_headroom_mib < 0 or args.max_model_len < 1 or args.max_num_batched_tokens < 1 or args.gpu_headroom_mib < 0 or
not math.isfinite(args.timeout) or args.timeout <= 0): not math.isfinite(args.timeout) or args.timeout <= 0):
p.error("counts/limits/timeout must be positive and finite; headroom must be nonnegative") p.error("counts/limits/timeout must be positive and finite; headroom must be nonnegative")
if args.requests < max(concurrencies):
p.error("requests per repeat must be at least the largest requested concurrency")
for path in (radiance, model): for path in (radiance, model):
if not path.is_file(): if not path.is_file():
p.error(f"not a file: {path}") p.error(f"not a file: {path}")
@@ -112,7 +127,7 @@ def main():
with socket.socket() as sock: with socket.socket() as sock:
sock.bind(("127.0.0.1", 0)) sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1] port = sock.getsockname()[1]
served = "spark-qos" served = "spark-qos-" + uuid.uuid4().hex
command = [str(radiance), "--model", str(model), "--radiance-home", str(home), command = [str(radiance), "--model", str(model), "--radiance-home", str(home),
"--kernels", args.kernels, "--host", "127.0.0.1", "--port", str(port), "--kernels", args.kernels, "--host", "127.0.0.1", "--port", str(port),
"--served-model-name", served, "--tp", str(args.tp), "--kv-cache-dtype", "bf16", "--served-model-name", served, "--tp", str(args.tp), "--kv-cache-dtype", "bf16",
@@ -123,7 +138,7 @@ def main():
receipt = {"model": str(model), "model_sha256": sha256(model), receipt = {"model": str(model), "model_sha256": sha256(model),
"radiance": str(radiance), "radiance_sha256": sha256(radiance), "radiance": str(radiance), "radiance_sha256": sha256(radiance),
"radiance_home": str(home), "prompt_file": str(prompt_path), "radiance_home": str(home), "prompt_file": str(prompt_path),
"prompt_file_sha256": sha256(prompt_path), "kernels": args.kernels, "prompt_file_sha256": prompt_hash, "kernels": args.kernels,
"tp": args.tp, "kv_cache_dtype": "bf16", "prefix_cache": False, "tp": args.tp, "kv_cache_dtype": "bf16", "prefix_cache": False,
"speculation": 0, "max_num_seqs": max(concurrencies), "speculation": 0, "max_num_seqs": max(concurrencies),
"max_model_len": args.max_model_len, "max_model_len": args.max_model_len,
@@ -158,6 +173,7 @@ def main():
else: else:
raise TimeoutError(f"Radiance did not become ready; see {out / 'server.log'}") raise TimeoutError(f"Radiance did not become ready; see {out / 'server.log'}")
verify_server(url, served, proc)
for concurrency in concurrencies: for concurrency in concurrencies:
samples = [] samples = []
started = time.perf_counter() started = time.perf_counter()
@@ -184,6 +200,7 @@ def main():
"generated_tokens": generated, "generated_tokens": generated,
"aggregate_completion_tokens_per_second": generated / wall if wall else 0.0, "aggregate_completion_tokens_per_second": generated / wall if wall else 0.0,
"samples": samples} "samples": samples}
verify_server(url, served, proc)
receipt["results"][str(concurrency)] = summary receipt["results"][str(concurrency)] = summary
print(f"concurrency={concurrency} requests={len(samples)} p50={summary['latency_seconds']['p50']:.3f}s " print(f"concurrency={concurrency} requests={len(samples)} p50={summary['latency_seconds']['p50']:.3f}s "
f"p95={summary['latency_seconds']['p95']:.3f}s max={summary['latency_seconds']['max']:.3f}s " f"p95={summary['latency_seconds']['p95']:.3f}s max={summary['latency_seconds']['max']:.3f}s "
@@ -197,8 +214,8 @@ def main():
proc.wait() proc.wait()
server_log.close() server_log.close()
if (plugin_hashes(home) != plugins or sha256(radiance) != receipt["radiance_sha256"] or if (plugin_hashes(home) != plugins or sha256(radiance) != receipt["radiance_sha256"] or
sha256(model) != receipt["model_sha256"]): sha256(model) != receipt["model_sha256"] or sha256(prompt_path) != prompt_hash):
raise ValueError("runtime, model or plugin inventory changed during the measurement") raise ValueError("runtime, model, prompt file or plugin inventory changed during the measurement")
report = out / "qos.json" report = out / "qos.json"
report.write_text(json.dumps(receipt, indent=2) + "\n") report.write_text(json.dumps(receipt, indent=2) + "\n")
print(f"QoS receipt: {report}") print(f"QoS receipt: {report}")
+4 -1
View File
@@ -160,13 +160,16 @@ def main():
command = [str(radiance), "--model", str(model), *common, "--kld-ref", str(ref_dir), command = [str(radiance), "--model", str(model), *common, "--kld-ref", str(ref_dir),
"--kld-out", str(report)] "--kld-out", str(report)]
candidate_sha256 = sha256(model) candidate_sha256 = sha256(model)
row_path = Path(str(report) + ".rows")
# A success without fresh output must never reuse an earlier score on retry.
report.unlink(missing_ok=True)
row_path.unlink(missing_ok=True)
subprocess.run(command, env=os.environ.copy(), check=True) subprocess.run(command, env=os.environ.copy(), check=True)
scored = json.loads(report.read_text()) scored = json.loads(report.read_text())
validate_report(scored, ref_dir, reference, corpus, model, expected_rows) validate_report(scored, ref_dir, reference, corpus, model, expected_rows)
if sha256(model) != candidate_sha256: if sha256(model) != candidate_sha256:
p.error(f"{name}: candidate changed during scoring") p.error(f"{name}: candidate changed during scoring")
values = scored["all"]["kld"] values = scored["all"]["kld"]
row_path = Path(str(report) + ".rows")
raw = row_path.read_bytes() raw = row_path.read_bytes()
if len(raw) != expected_rows * 16: if len(raw) != expected_rows * 16:
p.error(f"{name}: unexpected per-position rows size {len(raw)}") p.error(f"{name}: unexpected per-position rows size {len(raw)}")
+67 -2
View File
@@ -311,13 +311,77 @@ class MeasurementTests(unittest.TestCase):
"choices": [{"finish_reason": "length"}]} "choices": [{"finish_reason": "length"}]}
with patch.object(sys, "argv", args), patch.object(qos.subprocess, "Popen", return_value=proc), \ with patch.object(sys, "argv", args), patch.object(qos.subprocess, "Popen", return_value=proc), \
patch.object(qos.urllib.request, "urlopen", side_effect=lambda *a, **k: self.response(response)), \ patch.object(qos.urllib.request, "urlopen", side_effect=lambda *a, **k: self.response(response)), \
contextlib.redirect_stdout(io.StringIO()): patch.object(qos, "verify_server"), contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(qos.main(), 0) self.assertEqual(qos.main(), 0)
receipt = json.loads((output / "qos.json").read_text()) receipt = json.loads((output / "qos.json").read_text())
self.assertIn("architectures/fixture.so", receipt["architecture_shared_objects"]) self.assertIn("architectures/fixture.so", receipt["architecture_shared_objects"])
self.assertEqual(receipt["results"]["1"]["generated_tokens"], 2) self.assertEqual(receipt["results"]["1"]["generated_tokens"], 2)
proc.terminate.assert_called_once() proc.terminate.assert_called_once()
def test_reuse_rejects_stale_or_partial_scorer_output(self):
self.record_quality()
for output in ('none', 'report', 'rows'):
with self.subTest(output=output):
# Restore an old valid report, then simulate a successful incomplete scorer.
if not (self.out / 'run.json').exists():
self.record_quality('--reuse-reference')
def incomplete(command, **kwargs):
report = self.out / 'full-kld.json'
rows = Path(str(report) + '.rows')
old_report, old_rows = self.saved_outputs
if output == 'report':
report.write_bytes(old_report)
if output == 'rows':
rows.write_bytes(old_rows)
self.saved_outputs = ((self.out / 'full-kld.json').read_bytes(),
(self.out / 'full-kld.json.rows').read_bytes())
with patch.object(sys, 'argv', self.quality_args('--reuse-reference')), \
patch.object(quality.subprocess, 'run', side_effect=incomplete):
with self.assertRaises(FileNotFoundError):
quality.main()
self.assertFalse((self.out / 'run.json').exists())
def test_qos_rejects_fewer_requests_than_concurrency(self):
args = ['spark25_qos.py', '--radiance', str(self.runtime), '--home', str(self.home),
'--model', str(self.candidate), '--prompts', str(self.corpus), '--out', str(self.root / 'qos'),
'--requests', '1', '--concurrency', '4']
with patch.object(sys, 'argv', args), contextlib.redirect_stderr(io.StringIO()), \
patch.object(qos.subprocess, 'Popen') as start:
with self.assertRaises(SystemExit):
qos.main()
start.assert_not_called()
def test_qos_rejects_foreign_server_and_dead_child(self):
proc = Mock()
proc.poll.return_value = None
with patch.object(qos.urllib.request, 'urlopen', return_value=self.response({'data': [{'id': 'foreign'}]})):
with self.assertRaisesRegex(RuntimeError, 'identity'):
qos.verify_server('http://localhost', 'unique-id', proc)
proc.poll.return_value = 1
with self.assertRaisesRegex(RuntimeError, 'exited'):
qos.verify_server('http://localhost', 'unique-id', proc)
proc.poll.return_value = None
with patch.object(qos.urllib.request, 'urlopen', return_value=self.response({'data': [{'id': 'unique-id'}]})):
qos.verify_server('http://localhost', 'unique-id', proc)
def test_qos_rejects_prompt_file_replacement_after_snapshot(self):
output = self.root / 'changed-qos'
args = ['spark25_qos.py', '--radiance', str(self.runtime), '--home', str(self.home),
'--model', str(self.candidate), '--prompts', str(self.corpus), '--out', str(output),
'--requests', '1', '--repeats', '1', '--concurrency', '1', '--max-tokens', '2']
proc = Mock()
proc.poll.return_value = None
response = {'usage': {'prompt_tokens': 3, 'completion_tokens': 2},
'choices': [{'finish_reason': 'length'}]}
def change(*args):
self.corpus.write_text('{"prompt":"different"}\n')
with patch.object(sys, 'argv', args), patch.object(qos.subprocess, 'Popen', return_value=proc), \
patch.object(qos.urllib.request, 'urlopen', side_effect=lambda *a, **k: self.response(response)), \
patch.object(qos, 'verify_server', side_effect=change), contextlib.redirect_stdout(io.StringIO()):
with self.assertRaisesRegex(ValueError, 'prompt file'):
qos.main()
self.assertFalse((output / 'qos.json').exists())
def test_failed_qos_does_not_emit_success_receipt(self): def test_failed_qos_does_not_emit_success_receipt(self):
output = self.root / "qos" output = self.root / "qos"
args = ["spark25_qos.py", "--radiance", str(self.runtime), "--home", str(self.home), args = ["spark25_qos.py", "--radiance", str(self.runtime), "--home", str(self.home),
@@ -326,7 +390,8 @@ class MeasurementTests(unittest.TestCase):
proc = Mock() proc = Mock()
proc.poll.return_value = None proc.poll.return_value = None
with patch.object(sys, "argv", args), patch.object(qos.subprocess, "Popen", return_value=proc), \ with patch.object(sys, "argv", args), patch.object(qos.subprocess, "Popen", return_value=proc), \
patch.object(qos.urllib.request, "urlopen", side_effect=lambda *a, **k: self.response({})): patch.object(qos.urllib.request, "urlopen", side_effect=lambda *a, **k: self.response({})), \
patch.object(qos, "verify_server"):
with self.assertRaisesRegex(ValueError, "missing usage"): with self.assertRaisesRegex(ValueError, "missing usage"):
qos.main() qos.main()
proc.terminate.assert_called_once() proc.terminate.assert_called_once()