"""Final stage of the daily refresh: export Postgres → SQLite → gzip → push to the HF Space, and write a small status file the dashboard can surface. This runs inside `scripts/daily_refresh.sh` (which has already loaded the shell PATH and exported HF_TOKEN + DATABASE_URL). """ from __future__ import annotations import gzip import io import json import os import shutil import sqlite3 import subprocess import sys from datetime import UTC, datetime from pathlib import Path from huggingface_hub import CommitOperationAdd, HfApi REPO = Path(__file__).resolve().parent.parent SQLITE_PATH = REPO / "tracker_local.sqlite" SEED_PATH = REPO / "tracker_seed.dat" STATUS_PATH = REPO / "data" / "last_refresh.json" HF_REPO = "fti-opportunity-tracker/app" # Every push stores a new ~50 MB LFS blob for the seed. Superseded blobs keep # counting against the Space's 1 GB repo cap until the history is squashed and # HF garbage-collects them, so without this the push eventually 403s with # "Repository storage limit reached" and the deployed data silently goes stale. # Squash well below the cap: GC is not immediate (~100 min observed), so the # remaining headroom has to cover several days of pushes in the meantime. SQUASH_THRESHOLD_BYTES = 700_000_000 def export_postgres_to_sqlite() -> None: subprocess.run( ["uv", "run", "python", "scripts/export_to_sqlite.py"], cwd=REPO, check=True, ) def gzip_to_seed() -> None: if SEED_PATH.exists(): SEED_PATH.unlink() # gzip in chunks to a temp path, then move. tmp = SEED_PATH.with_suffix(".dat.tmp") with SQLITE_PATH.open("rb") as src, gzip.open(tmp, "wb", compresslevel=9) as dst: shutil.copyfileobj(src, dst, length=1 << 20) tmp.replace(SEED_PATH) def _hf_gitignore_without_seed() -> bytes: """Local .gitignore content with tracker_seed.dat removed. The local git repo ignores tracker_seed.dat (large binary, regenerated daily). But the HF Space git repo must track it for the Docker build. When create_commit finds a .gitignore in the operations it uses that content for the ignore check — so we include it here to allow the seed upload to go through. """ lines = (REPO / ".gitignore").read_text().splitlines() filtered = [l for l in lines if l.strip() != "tracker_seed.dat"] return "\n".join(filtered).encode() def push_to_hf(token: str) -> str: """Push the seed to HF Space. Retries up to 5 times on transient errors (DNS hiccups, closed-client, brief HF 5xx — all observed in the wild). Commits .gitignore alongside tracker_seed.dat so create_commit uses the included gitignore (which omits tracker_seed.dat) rather than the server-side .gitignore that blocks the upload. """ import time last_exc: Exception | None = None hf_gitignore = _hf_gitignore_without_seed() for attempt in range(5): try: # Construct a fresh HfApi each attempt so a previous closed-client # doesn't poison the next try. api = HfApi(token=token) commit = api.create_commit( repo_id=HF_REPO, repo_type="space", operations=[ CommitOperationAdd( path_in_repo=".gitignore", path_or_fileobj=io.BytesIO(hf_gitignore), ), CommitOperationAdd( path_in_repo="tracker_seed.dat", path_or_fileobj=str(SEED_PATH), ), ], commit_message=( f"Daily refresh {datetime.now(UTC).strftime('%Y-%m-%d %H:%M UTC')}" ), ) return str(commit).rsplit("/", 1)[-1] except Exception as exc: last_exc = exc wait_s = 5 + attempt * 10 # 5, 15, 25, 35, 45 print( f"HF push attempt {attempt + 1}/5 failed: " f"{type(exc).__name__}: {exc}; retrying in {wait_s}s", flush=True, ) time.sleep(wait_s) raise RuntimeError(f"HF push failed after 5 retries: {last_exc}") from last_exc def reclaim_storage_if_needed(token: str) -> dict | None: """Squash the Space's git history when stored bytes approach the repo cap. Squashing makes every superseded seed blob unreferenced; HF's GC then reclaims them. Never fatal — if the check or the squash fails we still attempt the push, which is what actually matters. """ try: api = HfApi(token=token) info = api.repo_info(HF_REPO, repo_type="space", expand=["usedStorage"]) used = getattr(info, "used_storage", None) if used is None: print("storage: usedStorage unavailable — skipping squash", flush=True) return None if used < SQUASH_THRESHOLD_BYTES: print(f"storage: {used / 1e6:.0f} MB used — below squash threshold", flush=True) return {"used_bytes": used, "squashed": False} print(f"storage: {used / 1e6:.0f} MB used — squashing history", flush=True) api.super_squash_history(repo_id=HF_REPO, repo_type="space", branch="main") return {"used_bytes": used, "squashed": True} except Exception as exc: # noqa: BLE001 print(f"storage: squash check failed ({exc}) — continuing to push", flush=True) return {"error": f"{type(exc).__name__}: {exc}"} def db_counts() -> dict[str, int]: out: dict[str, int] = {} with sqlite3.connect(SQLITE_PATH) as conn: cur = conn.cursor() out["opps"] = cur.execute("SELECT COUNT(*) FROM opportunities").fetchone()[0] out["enriched"] = cur.execute( "SELECT COUNT(*) FROM opportunities WHERE ai_enrichment_at IS NOT NULL" ).fetchone()[0] out["consulting"] = cur.execute( "SELECT COUNT(*) FROM opportunities WHERE is_consulting=1" ).fetchone()[0] out["non_consulting"] = cur.execute( "SELECT COUNT(*) FROM opportunities WHERE is_consulting=0" ).fetchone()[0] out["open_opps"] = cur.execute( "SELECT COUNT(*) FROM opportunities " "WHERE closing_date IS NULL OR closing_date >= date('now')" ).fetchone()[0] return out def write_status(payload: dict) -> None: STATUS_PATH.parent.mkdir(parents=True, exist_ok=True) STATUS_PATH.write_text(json.dumps(payload, indent=2, default=str)) def main() -> int: payload: dict = { "started_at": datetime.now(UTC).isoformat(), "status": "running", } try: export_postgres_to_sqlite() payload.update(db_counts()) gzip_to_seed() payload["seed_bytes"] = SEED_PATH.stat().st_size token = os.environ.get("HF_TOKEN") if not token: raise RuntimeError("HF_TOKEN missing — refusing to skip the push silently") payload["storage"] = reclaim_storage_if_needed(token) payload["push_commit_sha"] = push_to_hf(token) payload["status"] = "ok" except Exception as exc: payload["status"] = "failed" payload["error"] = f"{type(exc).__name__}: {exc}" payload["finished_at"] = datetime.now(UTC).isoformat() write_status(payload) print(json.dumps(payload, indent=2, default=str)) return 1 payload["finished_at"] = datetime.now(UTC).isoformat() write_status(payload) print(json.dumps(payload, indent=2, default=str)) return 0 if __name__ == "__main__": sys.exit(main())