|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Build a fresh D3 representative daily preview and external build evidence.""" |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import argparse |
| 6 | +import hashlib |
| 7 | +import json |
| 8 | +import re |
| 9 | +import shutil |
| 10 | +import sys |
| 11 | +import tempfile |
| 12 | +from pathlib import Path |
| 13 | +from unittest.mock import patch |
| 14 | + |
| 15 | +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) |
| 16 | + |
| 17 | +from quant_advisor_research import advisory_report |
| 18 | +from quant_advisor_research.preview_bundle import PreviewBundleError, build_preview_bundle, read_preview_bundle |
| 19 | + |
| 20 | + |
| 21 | +BASE_SHA_RE = re.compile(r"[0-9a-f]{40}") |
| 22 | +BUNDLE_CONTRACT = "qar.preview_bundle.v1" |
| 23 | +SCHEMA_VERSION = "5" |
| 24 | +REPORT_CONTRACT = "model_recommendations.v5" |
| 25 | +FIXED_FILES = ["manifest.json", "report.html", "report.json"] |
| 26 | + |
| 27 | + |
| 28 | +def fail(code: str) -> PreviewBundleError: |
| 29 | + return PreviewBundleError(code) |
| 30 | + |
| 31 | + |
| 32 | +def sha256(path: Path) -> str: |
| 33 | + return hashlib.sha256(path.read_bytes()).hexdigest() |
| 34 | + |
| 35 | + |
| 36 | +def require_contract(report: dict[str, object], manifest: dict[str, object]) -> dict[str, object]: |
| 37 | + source = manifest.get("source") |
| 38 | + expected = { |
| 39 | + "schema_version": SCHEMA_VERSION, |
| 40 | + "contract_version": REPORT_CONTRACT, |
| 41 | + "cadence": "daily", |
| 42 | + "as_of": report.get("as_of"), |
| 43 | + "generated_at": report.get("generated_at"), |
| 44 | + } |
| 45 | + if ( |
| 46 | + report.get("schema_version") != SCHEMA_VERSION |
| 47 | + or report.get("cadence") != "daily" |
| 48 | + or manifest.get("bundle_contract") != BUNDLE_CONTRACT |
| 49 | + or not isinstance(source, dict) |
| 50 | + or source != expected |
| 51 | + ): |
| 52 | + raise fail("contract_drift") |
| 53 | + return source |
| 54 | + |
| 55 | + |
| 56 | +def build(args: argparse.Namespace) -> None: |
| 57 | + if BASE_SHA_RE.fullmatch(args.base_sha) is None: |
| 58 | + raise fail("base_sha_invalid") |
| 59 | + if not args.frozen_generated_at: |
| 60 | + raise fail("frozen_generated_at_required") |
| 61 | + events = Path(args.political_events) |
| 62 | + watchlist = Path(args.political_watchlist) |
| 63 | + output = Path(args.artifact_dir) |
| 64 | + if not events.is_file() or not watchlist.is_file(): |
| 65 | + raise fail("fixture_missing") |
| 66 | + |
| 67 | + repeat_parent = Path(tempfile.mkdtemp(prefix=f".{output.name}.repeat-", dir=output.parent)) |
| 68 | + try: |
| 69 | + repeat_output = repeat_parent / "preview" |
| 70 | + with patch.object(advisory_report, "utc_now_iso", return_value=args.frozen_generated_at): |
| 71 | + first = advisory_report.build_advisory_report( |
| 72 | + as_of=args.as_of, |
| 73 | + cadence="daily", |
| 74 | + political_events_path=events, |
| 75 | + political_watchlist_path=watchlist, |
| 76 | + ) |
| 77 | + build_preview_bundle(first, output) |
| 78 | + first_readback = read_preview_bundle(output) |
| 79 | + second = advisory_report.build_advisory_report( |
| 80 | + as_of=args.as_of, |
| 81 | + cadence="daily", |
| 82 | + political_events_path=events, |
| 83 | + political_watchlist_path=watchlist, |
| 84 | + ) |
| 85 | + build_preview_bundle(second, repeat_output) |
| 86 | + first_report = dict(first_readback.report) |
| 87 | + first_manifest = dict(first_readback.manifest) |
| 88 | + manifest_source = require_contract(first_report, first_manifest) |
| 89 | + repeat_equal = all((output / name).read_bytes() == (repeat_output / name).read_bytes() for name in FIXED_FILES) |
| 90 | + finally: |
| 91 | + shutil.rmtree(repeat_parent, ignore_errors=True) |
| 92 | + if not repeat_equal: |
| 93 | + raise fail("repeat_build_non_deterministic") |
| 94 | + payload = { |
| 95 | + "source_kind": "repository_representative_fixture", |
| 96 | + "base_sha": args.base_sha, |
| 97 | + "bundle_contract": BUNDLE_CONTRACT, |
| 98 | + "source": {key: first_report[key] for key in ("cadence", "as_of", "generated_at", "schema_version")}, |
| 99 | + "manifest_source": manifest_source, |
| 100 | + "deterministic_clock": {"mode": "frozen_harness", "generated_at": args.frozen_generated_at}, |
| 101 | + "files": sorted(path.name for path in output.iterdir()), |
| 102 | + "sha256": {name: sha256(output / name) for name in FIXED_FILES}, |
| 103 | + "repeat_build_bytes": repeat_equal, |
| 104 | + } |
| 105 | + if payload["files"] != FIXED_FILES: |
| 106 | + raise fail("file_set_invalid") |
| 107 | + evidence_path = Path(args.evidence_path) |
| 108 | + if evidence_path.exists(): |
| 109 | + raise fail("evidence_exists") |
| 110 | + evidence_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") |
| 111 | + print(json.dumps(payload, ensure_ascii=False, sort_keys=True)) |
| 112 | + |
| 113 | + |
| 114 | +def main() -> None: |
| 115 | + parser = argparse.ArgumentParser() |
| 116 | + parser.add_argument("--as-of", required=True) |
| 117 | + parser.add_argument("--political-events", required=True) |
| 118 | + parser.add_argument("--political-watchlist", required=True) |
| 119 | + parser.add_argument("--artifact-dir", required=True) |
| 120 | + parser.add_argument("--evidence-path", required=True) |
| 121 | + parser.add_argument("--base-sha", required=True) |
| 122 | + parser.add_argument("--frozen-generated-at", required=True) |
| 123 | + try: |
| 124 | + build(parser.parse_args()) |
| 125 | + except PreviewBundleError as exc: |
| 126 | + print(f"d3_reslice_build_failed:{exc.code}", file=sys.stderr) |
| 127 | + raise SystemExit(1) from None |
| 128 | + except (OSError, TypeError, ValueError, UnicodeError): |
| 129 | + print("d3_reslice_build_failed", file=sys.stderr) |
| 130 | + raise SystemExit(1) from None |
| 131 | + |
| 132 | + |
| 133 | +if __name__ == "__main__": |
| 134 | + main() |
0 commit comments