"""Writing and reading the published tables. Every table is rebuilt from the parsed releases on each run and written whole. That is possible here, and not in the sibling datasets, because the input is a few thousand documents that never change once published: a rebuild reads them from cache and reproduces the same tables byte for byte. There is no append-only store and no merge, so there is nothing to drift. """ from __future__ import annotations import os import shutil import tempfile from pathlib import Path import polars as pl from .schema import CONFIG_SCHEMAS, align PART_NAME = "part-{index:05d}.parquet" # The whole dataset is under a million rows. One file per table keeps the # published tree small enough to list at a glance; the cap only matters if a # future backfill reaches back to the 1990s. MAX_ROWS_PER_FILE = 2_000_000 SORT_KEYS: dict[str, list[str]] = { "events": ["meeting_id", "event_type", "knowledge_at"], "meetings": ["meeting_end_date"], "documents": ["meeting_id", "document_type"], "sep": ["meeting_id", "variable", "projection_year"], "dot_plot": ["meeting_id", "projection_year", "rate_level"], "votes": ["meeting_id", "member_name"], "calendar": ["meeting_end_date"], "pit": ["entity_id", "event_date", "knowledge_date"], } def atomic_write_parquet(frame: pl.DataFrame, target: Path) -> None: """Write through a temporary file in the same directory, then rename. A partly written parquet is indistinguishable from a valid one until it is read, and a build interrupted mid-write would leave the dataset in a state that only fails later, in a consumer's process. """ target.parent.mkdir(parents=True, exist_ok=True) descriptor, temporary = tempfile.mkstemp(prefix=".part-", suffix=".parquet", dir=target.parent) os.close(descriptor) try: frame.write_parquet(temporary, compression="zstd", statistics=True) os.replace(temporary, target) finally: if os.path.exists(temporary): os.unlink(temporary) def write_table(data_dir: Path, table: str, frame: pl.DataFrame) -> int: root = Path(data_dir) / table if root.exists(): shutil.rmtree(root) root.mkdir(parents=True, exist_ok=True) aligned = align(frame, CONFIG_SCHEMAS[table]) keys = [key for key in SORT_KEYS.get(table, []) if key in aligned.columns] if keys and not aligned.is_empty(): aligned = aligned.sort(keys, nulls_last=True) if aligned.is_empty(): atomic_write_parquet(aligned, root / PART_NAME.format(index=0)) return 0 for index, start in enumerate(range(0, aligned.height, MAX_ROWS_PER_FILE)): atomic_write_parquet( aligned.slice(start, MAX_ROWS_PER_FILE), root / PART_NAME.format(index=index) ) return aligned.height def read_table(data_dir: Path, table: str) -> pl.LazyFrame: root = Path(data_dir) / table if not root.is_dir(): return pl.LazyFrame(schema=dict(CONFIG_SCHEMAS[table])) # The Delta table lives inside the pit directory and holds the very same # rows. Globbing it alongside the parquet parts returns every event twice, # which reads as a broken projection rather than a directory-listing # mistake. files = sorted( path for path in root.rglob("*.parquet") if not any(part.endswith(".delta") or part == "_delta_log" for part in path.parts) ) if not files: return pl.LazyFrame(schema=dict(CONFIG_SCHEMAS[table])) return pl.scan_parquet(files) def table_rows(data_dir: Path, table: str) -> int: return int(read_table(data_dir, table).select(pl.len()).collect().item()) def config_row_counts(data_dir: Path) -> dict[str, int]: return {name: table_rows(data_dir, name) for name in CONFIG_SCHEMAS} __all__ = [ "MAX_ROWS_PER_FILE", "PART_NAME", "SORT_KEYS", "atomic_write_parquet", "config_row_counts", "read_table", "table_rows", "write_table", ]