Retain Spark score backups if rollback fails

This commit is contained in:
Constantin committed 2026-11-03 13:53:27 -05:00
1 parent 50b60078ab
commit 95af71af3a
2 files changed
+67 -9

No files matched your search

+36 -9
View File
@@ -16,6 +16,7 @@ import argparse
import json import json
import math import math
import os import os
import shutil
from pathlib import Path from pathlib import Path
import struct import struct
import subprocess import subprocess
@@ -27,6 +28,20 @@ from spark25_validation import (fnv1a64, plugin_hashes, reference_provenance, sh
validate_reference, validate_report) validate_reference, validate_report)
class ScoreStaging:
"""Clean normally, but retain recoverable backups if rollback itself fails."""
def __init__(self, out):
self.path = Path(tempfile.mkdtemp(prefix=".spark25-score-", dir=out))
self.keep = False
def __enter__(self):
return self
def __exit__(self, exc_type, exc, traceback):
if not self.keep:
shutil.rmtree(self.path)
def parse_candidate(spec): def parse_candidate(spec):
name, sep, path = spec.partition("=") name, sep, path = spec.partition("=")
if not sep or not name or not path or Path(name).name != name or name in (".", ".."): if not sep or not name or not path or Path(name).name != name or name in (".", ".."):
@@ -174,12 +189,12 @@ def main():
"status_porcelain": git("status", "--porcelain")} "status_porcelain": git("status", "--porcelain")}
expected_rows = ref_meta.get("rows") expected_rows = ref_meta.get("rows")
with tempfile.TemporaryDirectory(prefix=".spark25-score-", dir=out) as staging: with ScoreStaging(out) as staging:
staged_outputs = [] staged_outputs = []
for name, model in candidates: for name, model in candidates:
report = out / f"{name}-kld.json" report = out / f"{name}-kld.json"
row_path = Path(str(report) + ".rows") row_path = Path(str(report) + ".rows")
staged_report = Path(staging) / report.name staged_report = staging.path / report.name
staged_rows = Path(str(staged_report) + ".rows") staged_rows = Path(str(staged_report) + ".rows")
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(staged_report)] "--kld-out", str(staged_report)]
@@ -211,25 +226,37 @@ def main():
verify_inputs() verify_inputs()
reference_provenance(ref_dir, reference_inputs, reuse=True) reference_provenance(ref_dir, reference_inputs, reuse=True)
receipt_temp = Path(staging) / "new-run.json" receipt_temp = staging.path / "new-run.json"
receipt_temp.write_text(json.dumps(run, indent=2) + "\n") receipt_temp.write_text(json.dumps(run, indent=2) + "\n")
backups = [] backups = []
promoted = [] promoted = []
try: try:
for index, (source, destination) in enumerate(staged_outputs): for index, (source, destination) in enumerate(staged_outputs):
backup = Path(staging) / f"backup-{index}" backup = staging.path / f"backup-{index}"
if destination.exists(): if destination.exists():
os.replace(destination, backup) os.replace(destination, backup)
backups.append((backup, destination)) backups.append((backup, destination))
os.replace(source, destination) os.replace(source, destination)
promoted.append(destination) promoted.append(destination)
os.replace(receipt_temp, out / "run.json") os.replace(receipt_temp, out / "run.json")
except BaseException: except BaseException as publication_error:
# Retain previous scores if any promotion or receipt publication fails. # Continue after individual rollback errors; retain all remaining backups on failure.
rollback_errors = []
for destination in reversed(promoted): for destination in reversed(promoted):
destination.unlink(missing_ok=True) try:
destination.unlink(missing_ok=True)
except OSError as exc:
rollback_errors.append(f"remove {destination}: {exc}")
for backup, destination in reversed(backups): for backup, destination in reversed(backups):
os.replace(backup, destination) try:
os.replace(backup, destination)
except OSError as exc:
rollback_errors.append(f"restore {backup} -> {destination}: {exc}")
if rollback_errors:
staging.keep = True
raise RuntimeError(f"score publication failed ({publication_error}); rollback "
f"incomplete; recover backups in {staging.path}: "
+ "; ".join(rollback_errors)) from publication_error
raise raise
print(f"Run receipt: {out / 'run.json'}") print(f"Run receipt: {out / 'run.json'}")
print("Per-position rows are available as <name>-kld.json.rows; replay severe positions with " print("Per-position rows are available as <name>-kld.json.rows; replay severe positions with "
@@ -240,6 +267,6 @@ def main():
if __name__ == "__main__": if __name__ == "__main__":
try: try:
sys.exit(main()) sys.exit(main())
except (KeyError, OSError, ValueError, subprocess.CalledProcessError) as exc: except (KeyError, OSError, ValueError, RuntimeError, subprocess.CalledProcessError) as exc:
print(f"spark25_quality: {exc}", file=sys.stderr) print(f"spark25_quality: {exc}", file=sys.stderr)
sys.exit(1) sys.exit(1)
+31
View File
@@ -403,6 +403,37 @@ class MeasurementTests(unittest.TestCase):
self.assertEqual([path.read_bytes() for path in paths], original) self.assertEqual([path.read_bytes() for path in paths], original)
self.assertFalse((self.out / 'run.json').exists()) self.assertFalse((self.out / 'run.json').exists())
def test_rollback_failure_retains_backup_and_restores_other_scores(self):
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
failures = []
def fail_publish_and_one_restore(src, dst):
src, dst = Path(src), Path(dst)
if dst == self.out / 'run.json':
failures.append('publish')
raise OSError('publication blocked')
if src.name == 'backup-1':
failures.append('restore')
raise OSError('restore blocked')
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_publish_and_one_restore), \
contextlib.redirect_stdout(io.StringIO()):
with self.assertRaisesRegex(RuntimeError, 'publication blocked.*recover backups') as error:
quality.main()
self.assertEqual(failures, ['publish', 'restore'])
self.assertIsInstance(error.exception.__cause__, OSError)
self.assertEqual(paths[0].read_bytes(), original[0])
self.assertFalse(paths[1].exists())
retained = list(self.out.glob('.spark25-score-*'))
self.assertEqual(len(retained), 1)
self.assertEqual((retained[0] / 'backup-1').read_bytes(), original[1])
self.assertIn(str(retained[0]), str(error.exception))
self.assertFalse((self.out / 'run.json').exists())
def test_tail_log_cannot_truncate_model_or_follow_symlink(self): def test_tail_log_cannot_truncate_model_or_follow_symlink(self):
self.record_quality() self.record_quality()
run, candidate, _, _, common = self.bind_tail() run, candidate, _, _, common = self.bind_tail()