1"""Bounded historical backfill from `period=full&ticker_range=<letter>` archives → base files per (symbol, year).23Streams one vendor file (one ticker, full history) at a time so memory stays flat. Dates that already have a live4delta file are excluded (they are compacted later) so the no-duplicate invariant holds. Resumable: progress5checkpoint `job:<id>/done_symbols`; a restarted job skips symbols already published.6"""7from __future__ import annotations89from typing import Any1011import pyarrow as pa12import pyarrow.compute as pc13from findata_core.db import connection, transaction14from findata_market_firstrate import FirstRateMarketConnector15from findata_schema import Interval16from findata_schema.connector import FetchRequest1718from findata_ingest import queue19from findata_ingest.lake import Lake20from findata_ingest.tasks.common import (21 DATASET_ASSET,22 live_delta_dates,23 record_anomalies,24 record_quality_report,25 record_raw_archive,26 upsert_coverage,27)282930def run(job: dict[str, Any], lake: Lake, log) -> dict[str, Any]:31 p = job.get("params") or {}32 asset = p.get("type", "stock")33 letter = p["ticker_range"]34 timeframe = p.get("timeframe", "1min")35 adjustment = p.get("adjustment", "UNADJUSTED")36 only = set(s.upper() for s in (p.get("symbols") or []))37 max_symbols = int(p.get("max_symbols") or 0)38 dataset_id = job.get("dataset_id") or DATASET_ASSET[asset]39 run_id = job.get("run_id")40 interval = Interval({"1min": "1m", "5min": "5m", "30min": "30m", "1hour": "1h", "1day": "1d"}[timeframe])41 conn_fr = FirstRateMarketConnector()4243 ck = queue.get_checkpoint(f"job:{job['id']}", "state") or {}44 done = set(ck.get("done_symbols") or [])45 raw_rel = ck.get("raw_path")46 if raw_rel and (lake.root / raw_rel).exists():47 from datetime import datetime4849 from findata_schema.connector import FetchResult50 res = FetchResult(request=FetchRequest(dataset_id, {"type": asset, "period": "full", "ticker_range": letter, "timeframe": timeframe, "adjustment": adjustment}),51 path=lake.root / raw_rel, sha256=ck["sha256"], bytes=ck["bytes"], fetched_at=datetime.fromisoformat(ck["fetched_at"]),52 vendor_last_update=None)53 log.info("backfill.resume", done=len(done), archive=raw_rel)54 else:55 req = FetchRequest(dataset_id=dataset_id, params={"endpoint": "data_file", "type": asset, "period": "full", "ticker_range": letter,56 "timeframe": timeframe, "adjustment": adjustment})57 queue.progress(job["id"], {"stage": "download", "ticker_range": letter})58 res = conn_fr.fetch_range(req, lake.raw_dir("firstrate", dataset_id))59 raw_rel = str(res.path.relative_to(lake.root))60 with transaction() as conn:61 record_raw_archive(conn, "firstrate", dataset_id, req.params, raw_rel, res.sha256, res.bytes, res.file_count, res.vendor_last_update, run_id)62 queue.set_checkpoint(f"job:{job['id']}", "state", {"raw_path": raw_rel, "sha256": res.sha256, "bytes": res.bytes,63 "fetched_at": res.fetched_at.isoformat(), "done_symbols": sorted(done)})64 log.info("backfill.downloaded", bytes=res.bytes, files=res.file_count)6566 with connection() as conn:67 delta_dates = live_delta_dates(conn, dataset_id)68 stats = {"symbols": 0, "rows": 0, "files": 0, "skipped_rows_in_delta": 0, "anomalies": 0}69 for batch in conn_fr.normalize(res, symbols=list(only) if only else None):70 if batch.symbol in done:71 continue72 if max_symbols and stats["symbols"] >= max_symbols:73 break74 rep = conn_fr.validate(batch)75 t = batch.table76 if delta_dates:77 mask = pc.invert(pc.is_in(t.column("session_date"), value_set=pa.array(sorted(delta_dates), pa.date32())))78 kept = t.filter(mask)79 stats["skipped_rows_in_delta"] += t.num_rows - kept.num_rows80 t = kept81 if t.num_rows == 0:82 done.add(batch.symbol)83 queue.set_checkpoint(f"job:{job['id']}", "state", {"raw_path": raw_rel, "sha256": res.sha256, "bytes": res.bytes,84 "fetched_at": res.fetched_at.isoformat(), "done_symbols": sorted(done)})85 continue86 years = pc.year(t.column("session_date"))87 written = []88 for y in sorted(set(years.to_pylist())):89 ty = t.filter(pc.equal(years, y))90 written.append(lake.write_table(dataset_id, ty, "base", {"symbol": batch.symbol, "year": str(y)}))91 # retire previous base files of this symbol/year (re-backfill replaces)92 with connection() as conn:93 old = conn.execute("SELECT path FROM lake_files WHERE dataset_id=%s AND layout='base' AND version_removed IS NULL AND symbol_min=%s AND symbol_max=%s",94 (dataset_id, batch.symbol, batch.symbol)).fetchall()95 lake.publish(dataset_id, written, [o["path"] for o in old], run_id, note=f"backfill {asset} {letter} {batch.symbol}")96 with transaction() as conn:97 upsert_coverage(conn, dataset_id, t, interval)98 record_anomalies(conn, dataset_id, rep.anomalies, run_id, limit=500)99 stats["symbols"] += 1100 stats["rows"] += t.num_rows101 stats["files"] += len(written)102 stats["anomalies"] += len(rep.anomalies)103 done.add(batch.symbol)104 queue.set_checkpoint(f"job:{job['id']}", "state", {"raw_path": raw_rel, "sha256": res.sha256, "bytes": res.bytes,105 "fetched_at": res.fetched_at.isoformat(), "done_symbols": sorted(done)})106 queue.progress(job["id"], {"stage": "publish", **stats, "last_symbol": batch.symbol})107 with transaction() as conn:108 conn.execute("UPDATE raw_archives SET status='published' WHERE sha256=%s", (res.sha256,))109 record_quality_report(conn, dataset_id, run_id, stats["rows"], [])110 if not p.get("keep_raw", False) and p.get("delete_raw_after_publish", True):111 # full archives are re-downloadable; sha256 stays in raw_archives112 res.path.unlink(missing_ok=True)113 with transaction() as conn:114 conn.execute("UPDATE raw_archives SET status='deleted_after_publish', path=NULL WHERE sha256=%s", (res.sha256,))115 if interval == Interval.m1 and stats["rows"]:116 queue.enqueue("derive", dataset_id.replace(".1m.", ".5m."), {"source_dataset": dataset_id, "target_interval": "5m",117 "symbols": sorted(done)}, priority=45, dedupe_key=f"derive:{dataset_id}:5m:backfill:{job['id']}")118 log.info("backfill.done", **stats)119 return stats120