"""Write and read the published tables. Storage is deliberately simpler here than in the sibling datasets. There, rows arrive one filing at a time from a feed and an append-only store with a primary key is the only way to tell a new row from one already held. Here the unit of arrival is a whole quarterly archive, and every accession appears in exactly one archive -- verified across four quarters, zero overlap. So a quarter is written as one partition that a rebuild reproduces byte for byte, no key column is needed, and re-ingesting a quarter is idempotent by construction rather than by comparison. """ from __future__ import annotations import os import shutil import tempfile from collections.abc import Mapping from pathlib import Path import polars as pl from .schema import CONFIG_SCHEMAS, align PARTITION = "kind" # Facts of one quarter run to about forty megabytes of parquet; splitting that # into several files would only multiply metadata. One file per quarter also # makes the partition trivially replaceable. PART_NAME = "part-00000.parquet" def partition_dir(data_dir: Path, table: str, quarter: str) -> Path: return Path(data_dir) / table / f"{PARTITION}={quarter}" 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_quarter( data_dir: Path, table: str, quarter: str, frame: pl.DataFrame ) -> tuple[Path, int]: """Replace one quarter's partition of one table.""" schema = CONFIG_SCHEMAS[table] directory = partition_dir(data_dir, table, quarter) if directory.exists(): shutil.rmtree(directory) target = directory / PART_NAME atomic_write_parquet(align(frame, schema), target) return target, frame.height def ingested_quarters(data_dir: Path, table: str = "facts") -> set[str]: """Quarters already on disk, read from the partition names themselves. A separate ledger file would be a second source of truth about what was built, and the two would disagree the first time a run was interrupted. """ root = Path(data_dir) / table if not root.is_dir(): return set() return { path.name.split("=", 1)[1] for path in root.iterdir() if path.is_dir() and path.name.startswith(f"{PARTITION}=") and any(path.iterdir()) } def read_table( data_dir: Path, table: str, *, quarters: set[str] | None = None ) -> pl.LazyFrame: """Lazy scan of a table, optionally restricted to some quarters.""" 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 is made of parquet # files holding the very same rows. Globbing them alongside the partitions # returns every point-in-time event twice, which reads as a broken # projection rather than as 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) and (quarters is None or path.parent.name.split("=", 1)[-1] in quarters) ) 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 write_singleton(data_dir: Path, table: str, frame: pl.DataFrame) -> Path: """A table small enough to live in one file, such as the archive ledger.""" target = Path(data_dir) / table / PART_NAME atomic_write_parquet(align(frame, CONFIG_SCHEMAS[table]), target) return target def config_row_counts(data_dir: Path, tables: Mapping[str, object] | None = None) -> dict[str, int]: names = list(tables or CONFIG_SCHEMAS) return {name: table_rows(data_dir, name) for name in names}