Protect Spark probe artifacts through promotion failures

This commit is contained in:
Constantin committed 2026-11-03 13:53:27 -05:00
1 parent acd256ba25
commit 50b60078ab
3 files changed
+87 -8

No files matched your search

+2 -1
View File
@@ -88,7 +88,8 @@ def candidate_server(run, candidate, common, log_path):
url = f"http://127.0.0.1:{port}"
command = [run["radiance"], "--model", candidate["model"], *common,
"--host", "127.0.0.1", "--port", str(port), "--served-model-name", model]
with log_path.open("w") as log:
# Never truncate a prior artifact or follow a symlink to a model/input.
with log_path.open("x") as log:
env = os.environ.copy()
env.pop("HF_TOKEN", None)
proc = subprocess.Popen(command, env=env, stdout=log, stderr=subprocess.STDOUT)
+25 -5
View File
@@ -86,6 +86,9 @@ def main():
inputs = [radiance, reference, corpus, *(model for _, model in candidates)]
inputs += [path.resolve() for path in (args.provenance, args.calibration_manifest) if path]
# Plugin symlinks can point outside the home; protect the target bytes too.
inputs += [path.resolve() for sub in ("kernels", "architectures", "quantizers")
for path in (home / sub).rglob("*.so")]
destinations = [out / "run.json"]
for name, _ in candidates:
report = out / f"{name}-kld.json"
@@ -93,8 +96,8 @@ def main():
if out == home or home in out.parents:
p.error("output directory must not be inside the plugin home")
for dest in destinations:
if dest.is_symlink() or dest.resolve() in inputs:
p.error(f"output path collides with an input or symlink: {dest}")
if dest.is_symlink() or dest.resolve() in inputs or (dest.exists() and not dest.is_file()):
p.error(f"output path collides with an input, symlink or non-file: {dest}")
if ref_dir.is_symlink():
p.error("reference output directory must not be a symlink")
if any(path == ref_dir or ref_dir in path.parents for path in inputs):
@@ -208,9 +211,26 @@ def main():
verify_inputs()
reference_provenance(ref_dir, reference_inputs, reuse=True)
for source, destination in staged_outputs:
os.replace(source, destination)
(out / "run.json").write_text(json.dumps(run, indent=2) + "\n")
receipt_temp = Path(staging) / "new-run.json"
receipt_temp.write_text(json.dumps(run, indent=2) + "\n")
backups = []
promoted = []
try:
for index, (source, destination) in enumerate(staged_outputs):
backup = Path(staging) / f"backup-{index}"
if destination.exists():
os.replace(destination, backup)
backups.append((backup, destination))
os.replace(source, destination)
promoted.append(destination)
os.replace(receipt_temp, out / "run.json")
except BaseException:
# Retain previous scores if any promotion or receipt publication fails.
for destination in reversed(promoted):
destination.unlink(missing_ok=True)
for backup, destination in reversed(backups):
os.replace(backup, destination)
raise
print(f"Run receipt: {out / 'run.json'}")
print("Per-position rows are available as <name>-kld.json.rows; replay severe positions with "
"tests/spark25_kld_tail.py. These are top-128-plus-tail KL values, not full-vocabulary KL.")
+60 -2
View File
@@ -4,6 +4,7 @@ import contextlib
import copy
import io
import json
import os
from pathlib import Path
import struct
import sys
@@ -261,10 +262,10 @@ class MeasurementTests(unittest.TestCase):
with patch.object(tail.subprocess, "Popen", side_effect=start), patch.object(tail, "get", side_effect=get):
if foreign:
with self.assertRaisesRegex(ValueError, "private server identity"):
with tail.candidate_server(run, candidate, common, self.root / "server.log"):
with tail.candidate_server(run, candidate, common, self.root / f"server-{foreign}.log"):
self.fail("must not expose an unrelated server")
else:
with tail.candidate_server(run, candidate, common, self.root / "server.log") as server:
with tail.candidate_server(run, candidate, common, self.root / f"server-{foreign}.log") as server:
command = server["command"]
self.assertEqual(command[command.index("--model") + 1], str(self.candidate))
self.assertTrue(server["model"].startswith("spark-tail-"))
@@ -359,6 +360,63 @@ class MeasurementTests(unittest.TestCase):
self.assertEqual(colliding.read_bytes(), b'irreplaceable input')
execute.assert_not_called()
def test_quality_protects_external_plugin_symlink_targets(self):
for name in ('run.json', 'full-kld.json', 'full-kld.json.rows'):
with self.subTest(name=name):
self.out = self.root / ('plugin-' + name)
self.out.mkdir()
target = self.out / name
target.write_bytes(b'plugin target')
plugin = self.home / 'kernels/fixture.so'
plugin.unlink()
plugin.symlink_to(target)
with patch.object(sys, 'argv', self.quality_args()), \
patch.object(quality.subprocess, 'run') as execute, \
contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit):
quality.main()
self.assertEqual(target.read_bytes(), b'plugin target')
execute.assert_not_called()
def test_quality_rolls_back_scores_on_promotion_or_receipt_failure(self):
for failure_name in ('full-kld.json.rows', 'run.json'):
with self.subTest(failure_name=failure_name):
self.out = self.root / ('promotion-' + failure_name)
self.record_quality()
paths = (self.out / 'full-kld.json', self.out / 'full-kld.json.rows')
original = [path.read_bytes() for path in paths]
real_replace = os.replace
failed = False
def fail_once(src, dst):
nonlocal failed
if not failed and Path(dst) == self.out / failure_name:
failed = True
raise OSError('simulated promotion failure')
return real_replace(src, dst)
with patch.object(sys, 'argv', self.quality_args('--reuse-reference')), \
patch.object(quality.subprocess, 'run', side_effect=self.fake_runtime), \
patch.object(quality.os, 'replace', side_effect=fail_once), \
contextlib.redirect_stdout(io.StringIO()):
with self.assertRaisesRegex(OSError, 'simulated promotion failure'):
quality.main()
self.assertTrue(failed)
self.assertEqual([path.read_bytes() for path in paths], original)
self.assertFalse((self.out / 'run.json').exists())
def test_tail_log_cannot_truncate_model_or_follow_symlink(self):
self.record_quality()
run, candidate, _, _, common = self.bind_tail()
before = self.candidate.read_bytes()
log = self.root / 'tail.server.log'
log.symlink_to(self.candidate)
for target in (log, self.candidate):
with self.subTest(target=target), patch.object(tail.subprocess, 'Popen') as start:
with self.assertRaises(FileExistsError):
with tail.candidate_server(run, candidate, common, target):
self.fail('must not start')
start.assert_not_called()
self.assertEqual(self.candidate.read_bytes(), before)
def test_qos_log_symlink_cannot_truncate_model(self):
output = self.root / 'symlink-qos'
output.mkdir()