File size: 25,901 Bytes
031cf82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
#!/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 <GITHUB_PAT> \\
        [--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()