"""The bundle descriptor, rebuilt from what is actually on disk.""" from __future__ import annotations import hashlib import json import os import tempfile from datetime import UTC, datetime from pathlib import Path from typing import Any import polars as pl from . import __version__ from .build import PIT_DELTA_NAME from .schema import BUILD_VERSION, CONFIG_SCHEMAS from .store import read_table RECIPE_ROOT = Path(__file__).resolve().parent.parent CONFIG_DESCRIPTIONS: dict[str, dict[str, str]] = { "dividends": { "path": "data/dividends/**/*.parquet", "grain": "one per-share dividend a filing stated for one period", }, "splits": { "path": "data/splits/**/*.parquet", "grain": "one split, with the window it must have happened in", }, "adjustment_factors": { "path": "data/adjustment_factors/**/*.parquet", "grain": "one span and the factor that puts an as-filed per-share figure on today's basis", }, "pit": { "path": "data/pit/**/*.parquet", "delta_path": f"data/pit/{PIT_DELTA_NAME}", "grain": "one point-in-time corporate action event", }, } def recipe_hash(project_root: Path | None = None) -> str: """Hash of the code that produced a build. The root defaults to the installed recipe rather than being derived from `data_dir`: a run writing elsewhere would otherwise hash an empty file set, which reads as a valid hash and proves nothing. """ root = (project_root or RECIPE_ROOT).resolve() digest = hashlib.sha256() files = sorted( { path for pattern in ("recipe/**/*.py", "jobs/**/*.py", "tests/**/*.py", "pyproject.toml") for path in root.glob(pattern) if path.is_file() } ) if not files: raise FileNotFoundError(f"no recipe sources under {root}") for path in files: digest.update(str(path.relative_to(root)).encode()) digest.update(b"\0") digest.update(path.read_bytes()) digest.update(b"\0") return f"sha256:{digest.hexdigest()}" def _coverage(data_dir: Path) -> dict[str, str | None]: bounds = read_table(data_dir, "pit").select( pl.col("event_date").min().alias("min_event"), pl.col("event_date").max().alias("max_event"), pl.col("knowledge_date").min().alias("min_knowledge"), pl.col("knowledge_date").max().alias("max_knowledge"), ).collect() if bounds.is_empty(): return {} row = bounds.row(0, named=True) return {k: (v.isoformat() if v is not None else None) for k, v in row.items()} def build_manifest(*, data_dir: Path, row_counts: dict[str, int], quality_ok: bool) -> dict[str, Any]: data_dir = Path(data_dir) project_root = data_dir.resolve().parent path = project_root / "manifest.json" manifest: dict[str, Any] = json.loads(path.read_text()) if path.exists() else {} manifest["generated_at"] = datetime.now(UTC).isoformat() manifest["rows"] = row_counts.get("pit", 0) manifest["config_rows"] = row_counts manifest["configs"] = CONFIG_DESCRIPTIONS manifest["coverage"] = _coverage(data_dir) manifest["quality_ok"] = quality_ok from .splits import KNOWN_RATIOS manifest["split_ratios_recognised"] = [label for _ratio, label in KNOWN_RATIOS] manifest["config_schemas"] = { name: {column: str(dtype) for column, dtype in schema.items()} for name, schema in CONFIG_SCHEMAS.items() } source = dict(manifest.get("source") or {}) source["recipe_hash"] = recipe_hash() source["build_version"] = BUILD_VERSION source["package_version"] = __version__ manifest["source"] = source descriptor, temporary = tempfile.mkstemp(prefix=".manifest-", suffix=".json", dir=project_root) try: with os.fdopen(descriptor, "w", encoding="utf-8") as handle: json.dump(manifest, handle, indent=2, sort_keys=True, ensure_ascii=False) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) finally: if os.path.exists(temporary): os.unlink(temporary) return manifest