#!/usr/bin/env python3 """ collect_pipeline_artifacts.py ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Discovers and parses data-engineering pipeline artifact files for DEPosit repositories listed in Data/all_DE_repositories.csv (or a --repos subset). Usage ----- python collect_pipeline_artifacts.py \\ --token \\ [--db Data/DE_pipeline_artifacts.db] \\ [--repos-csv Data/all_DE_repositories.csv] \\ [--repos owner/repo ...] # optional subset [--fresh] # reprocess all repos from scratch [--workers 1] Set GITHUB_TOKEN_SE4DE (or use --token / .env); see github_tokens.py and .env.example. Pipeline -------- For each repository: 1. Fetch the full git tree (one API call via /git/trees?recursive=1). 2. Filter blob paths against the artifact-type patterns in pipeline_parsers. 3. Confirm ambiguous path matches with content-level signals. 4. Fetch file content (base64-decoded from the Blobs API). 5. Route to the appropriate parser and insert features into SQLite. 6. Mirror each finished repository to CSV files under Data/pipeline_artifacts/. Rate-limit budget ----------------- - /git/trees: 1 call per repo. - /git/blobs: 1 call per matched file. - GitHub authenticated REST API: 5,000 req/hr. The script sleeps when the remaining budget falls below a configurable threshold and retries after the reset window. """ import argparse import base64 import csv import logging import os import re import sqlite3 import sys import threading import time from datetime import datetime, timezone from pathlib import Path import requests SCRIPT_DIR = Path(__file__).resolve().parent ROOT_DIR = SCRIPT_DIR.parent DEFAULT_DB = ROOT_DIR / "Data" / "DE_pipeline_artifacts.db" DEFAULT_REPOS_CSV = ROOT_DIR / "Data" / "filtered_DE_repositories.csv" DEFAULT_CSV_DIR = ROOT_DIR / "Data" / "pipeline_artifacts" # SQLite table -> CSV filename (one file per feature table) CSV_EXPORT_TABLES: dict[str, str] = { "pipeline_files": "DE_pipeline_files.csv", "airflow_dag_features": "DE_pipeline_airflow_dag_features.csv", "dbt_model_features": "DE_pipeline_dbt_model_features.csv", "dbt_project_summary": "DE_pipeline_dbt_project_summary.csv", "prefect_flow_features": "DE_pipeline_prefect_flow_features.csv", "dagster_features": "DE_pipeline_dagster_features.csv", "luigi_task_features": "DE_pipeline_luigi_task_features.csv", "kedro_pipeline_features": "DE_pipeline_kedro_pipeline_features.csv", "beam_pipeline_features": "DE_pipeline_beam_pipeline_features.csv", "dlt_features": "DE_pipeline_dlt_features.csv", } # ── Local parsers ───────────────────────────────────────────────────────────── sys.path.insert(0, str(SCRIPT_DIR)) from pipeline_parsers import ARTIFACT_PATTERNS, CONTENT_SIGNALS from pipeline_parsers.airflow_parser import extract as extract_airflow from pipeline_parsers.dbt_parser import (extract_model as extract_dbt_model, extract_project as extract_dbt_project, extract_schema as extract_dbt_schema) from pipeline_parsers.prefect_parser import extract as extract_prefect from pipeline_parsers.dagster_parser import extract as extract_dagster from pipeline_parsers.other_parsers import (extract_luigi, extract_kedro, extract_kedro_catalog, extract_beam, extract_dlt) logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%H:%M:%S", ) log = logging.getLogger(__name__) # ── Constants ───────────────────────────────────────────────────────────────── _MAX_FILE_BYTES = 500_000 # skip files larger than this (likely generated) _MAX_FILES_PER_REPO = 2_000 # guard against repos with enormous dags/ dirs # Pre-compile all path patterns _COMPILED_PATTERNS: dict[str, list[re.Pattern]] = { atype: [re.compile(p) for p in pats] for atype, pats in ARTIFACT_PATTERNS.items() } # ── GitHub API helpers ──────────────────────────────────────────────────────── from github_api import GITHUB_API, GitHubSession # noqa: E402 from github_tokens import add_github_token_args, resolve_token # noqa: E402 def _fetch_tree(session: GitHubSession, owner: str, repo: str ) -> tuple[list[dict] | None, str]: """Return (blob entries, tree_status) from the default branch recursive tree.""" url = f"{GITHUB_API}/repos/{owner}/{repo}/git/trees/HEAD?recursive=1" resp = session.get(url) if resp.status_code == 404: log.warning("%s/%s: 404 on tree fetch", owner, repo) return None, "404" if resp.status_code == 409: log.warning("%s/%s: empty repo", owner, repo) return None, "empty" if resp.status_code != 200: return None, f"http_{resp.status_code}" data = resp.json() status = "truncated" if data.get("truncated") else "ok" if status == "truncated": log.warning("%s/%s: tree truncated (very large repo)", owner, repo) blobs = [e for e in data.get("tree", []) if e.get("type") == "blob"] return blobs, status def _fetch_blob(session: GitHubSession, owner: str, repo: str, sha: str) -> str | None: """Return decoded text content of a git blob, or None on failure.""" url = f"{GITHUB_API}/repos/{owner}/{repo}/git/blobs/{sha}" resp = session.get(url) if resp.status_code != 200: return None data = resp.json() if data.get("encoding") != "base64": return None try: return base64.b64decode(data["content"]).decode("utf-8", errors="replace") except Exception: return None # ── Artifact type detection ─────────────────────────────────────────────────── def _classify_path(file_path: str) -> str | None: """Return the artifact type for a file path, or None if no match.""" for atype, patterns in _COMPILED_PATTERNS.items(): for pat in patterns: if pat.search(file_path): return atype return None def _confirm_with_content(artifact_type: str, raw_bytes: bytes) -> bool: """ For path-ambiguous types, verify that the file content contains at least one expected signal. Types with an empty signal list always pass. """ signals = CONTENT_SIGNALS.get(artifact_type, []) if not signals: return True return any(sig in raw_bytes for sig in signals) # ── SQLite helpers ──────────────────────────────────────────────────────────── def load_repos_from_csv( csv_path: Path, subset: list[str] | None = None, *, include_archived: bool = False, ) -> list[str]: """ Load owner/repo names from all_DE_repositories.csv. Expects columns: full_name (required), archived, disabled (optional booleans). By default skips archived/disabled rows; deduplicates by full_name. """ if not csv_path.is_file(): raise FileNotFoundError(f"Repository list not found: {csv_path}") def _is_true(value: str | None) -> bool: return (value or "").strip().lower() in ("true", "1", "yes") seen: set[str] = set() repos: list[str] = [] with open(csv_path, encoding="utf-8", newline="") as f: reader = csv.DictReader(f) if not reader.fieldnames or "full_name" not in reader.fieldnames: raise ValueError(f"{csv_path} must contain a full_name column") for row in reader: name = (row.get("full_name") or "").strip() if not name or name in seen: continue if "/" not in name or name.count("/") != 1: log.warning("Skipping invalid full_name: %r", name) continue if not include_archived and ( _is_true(row.get("archived")) or _is_true(row.get("disabled")) ): continue seen.add(name) repos.append(name) repos.sort() if subset: allowed = { r.strip() for r in subset if r.strip() and "/" in r and r.count("/") == 1 } repos = [r for r in repos if r in allowed] extra = sorted(allowed - set(repos)) if extra: log.info("Adding %d repo(s) from --repos not in CSV: %s", len(extra), ", ".join(extra[:5])) repos = sorted(set(repos) | set(extra)) return repos def _migrate_db(conn: sqlite3.Connection) -> None: """Apply additive schema changes to existing DE_pipeline_artifacts.db files.""" cols = { row[1] for row in conn.execute("PRAGMA table_info(dbt_model_features)").fetchall() } if cols and "has_tests" not in cols: conn.execute("ALTER TABLE dbt_model_features ADD COLUMN has_tests INTEGER") log.info("Migrated dbt_model_features: added has_tests column") conn.execute( """ CREATE TABLE IF NOT EXISTS repo_scan_status ( repo_full_name TEXT PRIMARY KEY, artifact_file_count INTEGER NOT NULL, tree_status TEXT, scanned_at TEXT NOT NULL ) """ ) def _mark_repo_scanned( conn: sqlite3.Connection, repo: str, artifact_count: int, tree_status: str, ) -> None: conn.execute( """ INSERT OR REPLACE INTO repo_scan_status (repo_full_name, artifact_file_count, tree_status, scanned_at) VALUES (?, ?, ?, ?) """, (repo, artifact_count, tree_status, datetime.now(timezone.utc).isoformat()), ) def _init_db(db_path: Path) -> sqlite3.Connection: db_path.parent.mkdir(parents=True, exist_ok=True) schema = SCRIPT_DIR / "pipeline_schema.sql" conn = sqlite3.connect(str(db_path)) conn.row_factory = sqlite3.Row conn.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA synchronous=NORMAL") if schema.exists(): conn.executescript(schema.read_text()) _migrate_db(conn) conn.commit() return conn class PipelineCsvExporter: """Keep per-table CSV files in sync with SQLite (one repo at a time).""" def __init__(self, csv_dir: Path) -> None: self.csv_dir = Path(csv_dir) self.csv_dir.mkdir(parents=True, exist_ok=True) self._lock = threading.Lock() self._columns_cache: dict[str, list[str]] = {} def reset_all(self) -> None: with self._lock: for filename in CSV_EXPORT_TABLES.values(): path = self.csv_dir / filename if path.exists(): path.unlink() def _columns(self, conn: sqlite3.Connection, table: str) -> list[str]: if table not in self._columns_cache: rows = conn.execute(f"PRAGMA table_info({table})").fetchall() self._columns_cache[table] = [ r[1] for r in rows if r[1] != "id" ] return self._columns_cache[table] def _read_rows(self, path: Path) -> list[dict[str, str]]: if not path.exists(): return [] with open(path, encoding="utf-8", newline="") as f: return list(csv.DictReader(f)) def sync_repo(self, conn: sqlite3.Connection, repo: str) -> None: """Replace all CSV rows for repo with current SQLite contents.""" with self._lock: for table, filename in CSV_EXPORT_TABLES.items(): cols = self._columns(conn, table) if not cols: continue col_list = ", ".join(cols) new_rows = conn.execute( f"SELECT {col_list} FROM {table} WHERE repo_full_name = ?", (repo,), ).fetchall() new_dicts = [dict(row) for row in new_rows] out_path = self.csv_dir / filename kept = [ row for row in self._read_rows(out_path) if row.get("repo_full_name") != repo ] if not kept and not new_dicts and not out_path.exists(): continue fieldnames = list(kept[0].keys()) if kept else cols with open(out_path, "w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=fieldnames, extrasaction="ignore") writer.writeheader() for row in kept: writer.writerow(row) for row in new_dicts: writer.writerow({k: row.get(k) for k in fieldnames}) def _already_processed(conn: sqlite3.Connection, repo: str) -> bool: row = conn.execute( "SELECT 1 FROM repo_scan_status WHERE repo_full_name = ? LIMIT 1", (repo,), ).fetchone() if row is not None: return True # Legacy runs before repo_scan_status: treat repos with pipeline_files as done return conn.execute( "SELECT 1 FROM pipeline_files WHERE repo_full_name = ? LIMIT 1", (repo,), ).fetchone() is not None def _insert_file_record(conn: sqlite3.Connection, repo: str, path: str, atype: str, sha: str, size: int) -> None: conn.execute( """INSERT OR IGNORE INTO pipeline_files (repo_full_name, file_path, artifact_type, file_sha, file_size_bytes, collected_at) VALUES (?, ?, ?, ?, ?, ?)""", (repo, path, atype, sha, size, datetime.now(timezone.utc).isoformat()), ) def _set_parse_error(conn: sqlite3.Connection, repo: str, path: str, error: str | None) -> None: """parse_error lives on pipeline_files, not on per-artifact feature tables.""" if not error: return conn.execute( "UPDATE pipeline_files SET parse_error = ? " "WHERE repo_full_name = ? AND file_path = ?", (error, repo, path), ) def _insert_features(conn: sqlite3.Connection, table: str, repo: str, path: str, features: dict) -> None: parse_error = features.pop("parse_error", None) features = {k: v for k, v in features.items() if v is not None} if not features: _set_parse_error(conn, repo, path, parse_error) return features["repo_full_name"] = repo features["file_path"] = path cols = ", ".join(features.keys()) placeholders = ", ".join("?" * len(features)) conn.execute( f"INSERT OR REPLACE INTO {table} ({cols}) VALUES ({placeholders})", list(features.values()), ) _set_parse_error(conn, repo, path, parse_error) # ── Per-artifact dispatch ───────────────────────────────────────────────────── def _process_file(conn: sqlite3.Connection, session: GitHubSession, owner: str, repo: str, repo_full: str, entry: dict, artifact_type: str) -> None: path = entry["path"] sha = entry["sha"] size = entry.get("size", 0) if size > _MAX_FILE_BYTES: log.debug("%s: %s too large (%d bytes), skipping", repo_full, path, size) return content = _fetch_blob(session, owner, repo, sha) if content is None: return raw = content.encode("utf-8", errors="replace") if not _confirm_with_content(artifact_type, raw): return # path matched but content signals absent _insert_file_record(conn, repo_full, path, artifact_type, sha, size) try: if artifact_type == "airflow_dag": for dag_features in extract_airflow(content, path): _insert_features(conn, "airflow_dag_features", repo_full, path, dag_features) elif artifact_type == "dbt_model": f = extract_dbt_model(content, path) _insert_features(conn, "dbt_model_features", repo_full, path, f) elif artifact_type == "dbt_schema": fname = Path(path).name.lower() if fname in ("dbt_project.yml", "dbt_project.yaml"): f = extract_dbt_project(content, path) parse_error = f.pop("parse_error", None) f = {k: v for k, v in f.items() if v is not None} if f: f["repo_full_name"] = repo_full cols = ", ".join(f.keys()) placeholders = ", ".join("?" * len(f)) conn.execute( f"INSERT OR REPLACE INTO dbt_project_summary " f"({cols}) VALUES ({placeholders})", list(f.values()), ) _set_parse_error(conn, repo_full, path, parse_error) else: # schema.yml: per-model test coverage merged into model rows coverage = extract_dbt_schema(content, path) for model_name, has_tests in coverage.items(): updated = conn.execute( """UPDATE dbt_model_features SET has_tests = ? WHERE repo_full_name = ? AND model_name = ?""", (has_tests, repo_full, model_name), ).rowcount if updated == 0: log.debug( "%s schema.yml: no dbt_model_features row for model %s", repo_full, model_name, ) elif artifact_type == "prefect_flow": f = extract_prefect(content, path) _insert_features(conn, "prefect_flow_features", repo_full, path, f) elif artifact_type == "dagster": f = extract_dagster(content, path) _insert_features(conn, "dagster_features", repo_full, path, f) elif artifact_type == "luigi": f = extract_luigi(content, path) _insert_features(conn, "luigi_task_features", repo_full, path, f) elif artifact_type == "kedro": fname = Path(path).name.lower() if "catalog" in fname and fname.endswith((".yml", ".yaml")): f = extract_kedro_catalog(content, path) else: f = extract_kedro(content, path) _insert_features(conn, "kedro_pipeline_features", repo_full, path, f) elif artifact_type == "beam": f = extract_beam(content, path) _insert_features(conn, "beam_pipeline_features", repo_full, path, f) elif artifact_type == "dlt": f = extract_dlt(content, path) _insert_features(conn, "dlt_features", repo_full, path, f) except Exception as exc: # noqa: BLE001 log.error("%s %s: feature extraction failed: %s", repo_full, path, exc) _set_parse_error(conn, repo_full, path, str(exc)) # ── Main collection loop ────────────────────────────────────────────────────── def collect_repo(conn: sqlite3.Connection, session: GitHubSession, repo_full: str, csv_exporter: PipelineCsvExporter | None = None, *, progress_idx: int | None = None, progress_total: int | None = None) -> None: owner, repo = repo_full.split("/", 1) if progress_idx is not None and progress_total is not None: log.info("[%d/%d] Processing %s", progress_idx, progress_total, repo_full) else: log.info("Processing %s", repo_full) blobs, tree_status = _fetch_tree(session, owner, repo) if blobs is None: _mark_repo_scanned(conn, repo_full, 0, tree_status) conn.commit() if csv_exporter is not None: csv_exporter.sync_repo(conn, repo_full) return matched: list[tuple[dict, str]] = [] for entry in blobs: atype = _classify_path(entry["path"]) if atype: matched.append((entry, atype)) if len(matched) > _MAX_FILES_PER_REPO: log.warning("%s: %d matched files, capping at %d", repo_full, len(matched), _MAX_FILES_PER_REPO) matched = matched[:_MAX_FILES_PER_REPO] if progress_idx is not None and progress_total is not None: log.info(" [%d/%d] %d pipeline artifact files found", progress_idx, progress_total, len(matched)) else: log.info(" %d pipeline artifact files found", len(matched)) for entry, atype in matched: _process_file(conn, session, owner, repo, repo_full, entry, atype) _mark_repo_scanned(conn, repo_full, len(matched), tree_status) conn.commit() if csv_exporter is not None: csv_exporter.sync_repo(conn, repo_full) def main() -> None: ap = argparse.ArgumentParser( description="Collect pipeline artifact features for DEPosit repositories." ) ap.add_argument( "--db", default=str(DEFAULT_DB), help=f"SQLite output database (default: {DEFAULT_DB.relative_to(ROOT_DIR)})", ) add_github_token_args(ap) ap.add_argument( "--repos-csv", default=str(DEFAULT_REPOS_CSV), help=f"Repository cohort CSV with full_name column (default: {DEFAULT_REPOS_CSV.name})", ) ap.add_argument( "--repos", nargs="*", help="Optional subset of owner/repo names (must appear in --repos-csv unless given alone)", ) ap.add_argument( "--include-archived", action="store_true", help="Also process repositories marked archived or disabled in the CSV", ) ap.add_argument( "--fresh", action="store_true", help="Reprocess every repo from scratch (default: skip repos already in the DB).", ) ap.add_argument("--workers", type=int, default=1, help="Parallel worker threads (default 1; each uses its own API session).") ap.add_argument( "--csv-dir", default=str(DEFAULT_CSV_DIR), help=f"Directory for pipeline CSV exports (default: {DEFAULT_CSV_DIR.relative_to(ROOT_DIR)})", ) ap.add_argument( "--no-csv", action="store_true", help="Skip CSV export (SQLite only).", ) args = ap.parse_args() token = resolve_token(args.token, args.tokens) if not token: ap.error( "GitHub token required: pass --token, set GITHUB_TOKEN_SE4DE, " "or copy .env.example to .env" ) db_path = Path(args.db) csv_path = Path(args.repos_csv) conn = _init_db(db_path) repos = load_repos_from_csv( csv_path, subset=args.repos or None, include_archived=args.include_archived, ) if not repos: ap.error(f"No repositories to process from {csv_path}") csv_exporter = None if not args.no_csv: csv_exporter = PipelineCsvExporter(Path(args.csv_dir)) if args.fresh: csv_exporter.reset_all() log.info("CSV export: %s (cleared for --fresh)", args.csv_dir) else: log.info("CSV export: %s (synced per repo)", args.csv_dir) log.info("Repository list: %s (%d repos)", csv_path, len(repos)) log.info("Output database: %s", db_path) total = len(repos) log.info("Total repos in queue: %d", total) if args.workers > 1: from concurrent.futures import ThreadPoolExecutor def _worker(item: tuple[int, str]) -> None: idx, repo = item c = sqlite3.connect(str(db_path)) c.row_factory = sqlite3.Row c.execute("PRAGMA journal_mode=WAL") if not args.fresh and _already_processed(c, repo): log.info("[%d/%d] Skipping %s (already processed)", idx, total, repo) c.close() return session = GitHubSession(token) try: collect_repo( c, session, repo, csv_exporter, progress_idx=idx, progress_total=total, ) except requests.RequestException as exc: log.error("[%d/%d] %s: network/API error (retry on next run): %s", idx, total, repo, exc) finally: c.close() work_items = list(enumerate(repos, 1)) with ThreadPoolExecutor(max_workers=args.workers) as pool: pool.map(_worker, work_items) else: session = GitHubSession(token) for idx, repo in enumerate(repos, 1): if not args.fresh and _already_processed(conn, repo): log.info("[%d/%d] Skipping %s (already processed)", idx, total, repo) continue try: collect_repo( conn, session, repo, csv_exporter, progress_idx=idx, progress_total=total, ) except requests.RequestException as exc: log.error("[%d/%d] %s: network/API error (retry on next run): %s", idx, total, repo, exc) conn.rollback() conn.close() log.info("Done.") if __name__ == "__main__": main()