File size: 1,859 Bytes
de2ca63 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | """
Shared append-only ingest harness for a ziplime PIT dataset.
Reads `recipe.fetch(since)`, stamps `ingested_at`, drops byte-identical duplicates of
existing (entity_id, event_date, knowledge_date) rows, and **appends** to the Delta table.
It never issues UPDATE/DELETE/MERGE — append-only is the PIT invariant the linter enforces.
"""
from __future__ import annotations
import argparse, hashlib
from datetime import datetime, timezone
from pathlib import Path
import polars as pl
from deltalake import DeltaTable, write_deltalake
import recipe
TABLE_URI = str(Path(__file__).parent / "data" / "data_bundle" /
"yahoo_finance_daily_data" / "1784755946" / "data.delta")
def _row_hash(df: pl.DataFrame) -> pl.Series:
cols = [c for c in df.columns if c != "ingested_at"]
return df.select(cols).hash_rows().cast(pl.Utf8)
async def main(since: datetime) -> None:
fresh = await recipe.fetch(since)
if fresh.is_empty():
print("recipe returned no rows; nothing to append")
return
fresh = fresh.with_columns(
pl.lit(datetime.now(timezone.utc)).alias("ingested_at"),
)
try:
existing = pl.from_arrow(DeltaTable(TABLE_URI).to_pyarrow_table())
seen = set(_row_hash(existing).to_list())
fresh = fresh.filter(~_row_hash(fresh).is_in(seen))
except Exception:
pass # first ingest / fresh table
if fresh.is_empty():
print("no new or revised rows after dedup")
return
write_deltalake(TABLE_URI, fresh.to_arrow(), mode="append")
print(f"appended {len(fresh)} rows to {TABLE_URI}")
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--since", default="2025-01-01")
args = ap.parse_args()
import asyncio
asyncio.run(main(datetime.fromisoformat(args.since).replace(tzinfo=timezone.utc)))
|