#!/usr/bin/env python3 """Release a sealed L3 final-test bundle only after five-seed fitting.""" from __future__ import annotations import argparse import hashlib import json import sys from datetime import datetime, timezone from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO_ROOT / "src")) from telen.experiment import load_l3_training_bundle # noqa: E402 from telen.final_evaluation import ( # noqa: E402 load_l3_final_evaluation_bundle, ) def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def load(path: Path, artifact_type: str) -> dict: value = json.loads(path.read_text(encoding="utf-8")) if value.get("artifact_type") != artifact_type: raise ValueError(f"{path} has the wrong artifact_type") return value def portable(path: Path, base: Path) -> str: try: return str(path.resolve().relative_to(base.resolve())) except ValueError: return str(path.resolve()) def resolve_spec(spec: dict, manifest_path: Path) -> Path: path = Path(str(spec["path"])) if not path.is_absolute(): path = manifest_path.parent / path path = path.resolve() if not path.is_file() or sha256_file(path) != spec["sha256"]: raise ValueError("confirmatory pilot receipt path/hash is invalid") return path def prepare(args: argparse.Namespace) -> dict: if args.output.exists(): raise ValueError("final-test manifest already exists; overwrite refused") confirmatory_manifest = args.confirmatory_manifest.resolve() bundle = load_l3_training_bundle(confirmatory_manifest) if bundle.config.stage != "confirmatory_fit": raise ValueError("final test requires a confirmatory-fit manifest") confirmatory = load( args.confirmatory_receipt.resolve(), "telen_l3_confirmatory_fit" ) if ( confirmatory.get("status") != "completed_fit_without_final_test" or confirmatory.get("final_test_accessed") is not False or confirmatory.get("manifest_sha256") != sha256_file(confirmatory_manifest) ): raise ValueError("five-seed confirmatory fit is incomplete or unlinked") pilot_path = resolve_spec( bundle.manifest["files"]["pilot_evaluation_receipt"], bundle.manifest_path, ) pilot = load(pilot_path, "telen_l3_development_evaluation") if pilot.get("pilot_go_gate", {}).get("authorized") is not True: raise ValueError("development pilot did not authorize final lineage") evaluation = pilot.get("evaluation_config") if not isinstance(evaluation, dict): raise ValueError("pilot receipt has no frozen evaluation config") files = { "confirmatory_manifest": confirmatory_manifest, "confirmatory_receipt": args.confirmatory_receipt.resolve(), "train_dev_split_audit": args.train_dev_split_audit.resolve(), "train_dev_assignments": args.train_dev_assignments.resolve(), "test_annotation_audit": args.test_annotation_audit.resolve(), "test_annotation_events": args.test_annotation_events.resolve(), "test_questions": args.test_questions.resolve(), "test_qrels": args.test_qrels.resolve(), "test_assignments": args.test_assignments.resolve(), "test_versions": args.test_versions.resolve(), "test_events": args.test_events.resolve(), "test_version_embeddings": args.test_version_embeddings.resolve(), "test_query_embeddings": args.test_query_embeddings.resolve(), "test_queries": args.test_queries.resolve(), "test_candidates": args.test_candidates.resolve(), } missing = [name for name, path in files.items() if not path.is_file()] if missing: raise ValueError(f"missing final-test inputs: {missing}") args.output.parent.mkdir(parents=True, exist_ok=True) manifest = { "schema_version": 1, "artifact_type": "telen_l3_final_evaluation_bundle", "created_at": datetime.now(timezone.utc).isoformat(), "release": { "opened_after_confirmatory_fit": True, "confirmatory_receipt_sha256": sha256_file( args.confirmatory_receipt ), "all_five_seeds_required": True, "seed_selection_forbidden": True, "single_output_receipt": True, }, "files": { name: { "path": portable(path, args.output.parent), "sha256": sha256_file(path), } for name, path in files.items() }, "evaluation": evaluation, } pending = args.output.with_name(args.output.name + ".pending") if pending.exists(): raise ValueError("stale pending final-test manifest exists") pending.write_text( json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) try: load_l3_final_evaluation_bundle(pending) except Exception: pending.unlink(missing_ok=True) raise pending.replace(args.output) return manifest def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--confirmatory-manifest", type=Path, required=True) parser.add_argument("--confirmatory-receipt", type=Path, required=True) parser.add_argument("--train-dev-split-audit", type=Path, required=True) parser.add_argument("--train-dev-assignments", type=Path, required=True) parser.add_argument("--test-annotation-audit", type=Path, required=True) parser.add_argument("--test-annotation-events", type=Path, required=True) parser.add_argument("--test-questions", type=Path, required=True) parser.add_argument("--test-qrels", type=Path, required=True) parser.add_argument("--test-assignments", type=Path, required=True) parser.add_argument("--test-versions", type=Path, required=True) parser.add_argument("--test-events", type=Path, required=True) parser.add_argument("--test-version-embeddings", type=Path, required=True) parser.add_argument("--test-query-embeddings", type=Path, required=True) parser.add_argument("--test-queries", type=Path, required=True) parser.add_argument("--test-candidates", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) return parser.parse_args() def main() -> None: print(json.dumps(prepare(parse_args()), ensure_ascii=False, indent=2)) if __name__ == "__main__": main()