from __future__ import annotations import json import os import signal import time from pathlib import Path from .source_loader import stream_hf_dataset, normalize_source_row from .source_checks import check_source_record from .code_extractor import extract_code from .static_checks import inspect_code from .executor import run_code from .dedupe import Deduper from .secret_scan import scan_code, ensure_secret_scanner_ready from .nim_reviewer import NIMReviewer from .nim_schema import validate_nim_response from .coverage import CoverageTracker from .decision import decide from .dataset_writer import DatasetWriter from .utils import load_json from . import tiers as tiers_mod def build_paths(project_root: Path) -> dict: return { "topics": project_root / "config/topics_basic_python.json", "tier2_libraries": project_root / "config/tier2_libraries.json", "thresholds": project_root / "config/thresholds.json", "sources": project_root / "config/sources.json", "output": project_root / "data", "dedupe": project_root / "data/metadata/exact_hashes.txt", "coverage": project_root / "data/metadata/topic_coverage.json", "checkpoint": project_root / "data/metadata/checkpoint.json", } def load_checkpoint(path: Path) -> dict: """Load the checkpoint file if present. Returns {} if missing or unreadable (e.g. truncated by a power loss mid-write) so a run always falls back to starting from row 0 rather than crashing.""" if not path.exists(): return {} try: return json.loads(path.read_text(encoding="utf-8")) except Exception: return {} def save_checkpoint(path: Path, payload: dict) -> None: """Atomic checkpoint write: write to a sibling temp file, flush+fsync it, then os.replace() over the real file. This way a crash or power cut can only ever leave the OLD checkpoint intact or the NEW one fully written — never a half-written, corrupt checkpoint.json.""" path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") with tmp.open("w", encoding="utf-8") as f: json.dump(payload, f, indent=2) f.flush() os.fsync(f.fileno()) os.replace(tmp, path) def _install_stop_handler(): """Catch Ctrl+C (SIGINT) and a polite kill (SIGTERM) so the pipeline finishes writing the record it's currently on, saves a checkpoint, and exits cleanly instead of getting cut off mid-record. A second Ctrl+C still forces an immediate exit if the person really wants out now.""" state = {"stop": False, "count": 0} def handler(signum, frame): state["count"] += 1 state["stop"] = True if state["count"] >= 2: raise KeyboardInterrupt("Second stop signal: forcing immediate exit.") print("\n[stopping after current record — checkpoint will be saved; " "press Ctrl+C again to force quit immediately]") signal.signal(signal.SIGINT, handler) try: signal.signal(signal.SIGTERM, handler) except (ValueError, AttributeError): pass # SIGTERM not available on some platforms (e.g. Windows consoles) return state def _merge_stats(cumulative: dict, run_stats: dict) -> dict: out = dict(cumulative) for k, v in run_stats.items(): if isinstance(v, (int, float)) and not isinstance(v, bool): out[k] = out.get(k, 0) + v return out def run(project_root: Path, limit: int = 500, dry_run: bool = False, source_name_override: str | None = None, active_tiers: tuple[str, ...] = (tiers_mod.TIER1_BASIC,), resume: bool = True) -> dict: """Run the pipeline for up to `limit` NEW rows this invocation. Resumability: progress (how many source rows have been consumed so far) is stored in data/metadata/checkpoint.json. Each call to `run()`: - loads that checkpoint (unless resume=False), - skips over rows already consumed on a prior run/day, - processes up to `limit` more rows, - and saves the new cursor + cumulative stats back to the checkpoint — after EVERY row, not just at the end, so a crash or closed terminal never loses more than the one row that was in flight. This is what makes "run it for a while today, close it, run it again tomorrow, repeat for weeks" work: each run just continues from where the last one left off, on the same source, until the whole dataset is consumed or you stop asking it to run. active_tiers controls which of the three dataset tiers are actually processed end-to-end this run: - basic_python_syntax : fully automated today (default; run this now). - per_library : classified and NIM-reviewed, but never auto-included, since there's no per-library execution environment yet. - real_world_repository : classified only; not executed or scored. Records whose tier isn't in active_tiers are still classified and written (decision="skip", reason="tier_not_active:") so nothing is lost — they're just not spending NIM requests or execution time this run. """ # Fail closed, once, before doing any other work: don't burn NIM/API # requests or partially process a batch if secret scanning isn't in place. ensure_secret_scanner_ready() paths = build_paths(project_root) topics = load_json(paths["topics"]) tier2_libraries = load_json(paths["tier2_libraries"]) thresholds = load_json(paths["thresholds"]) source_cfg = load_json(paths["sources"])["primary"] source_name = source_name_override or source_cfg["name"] checkpoint = load_checkpoint(paths["checkpoint"]) if resume else {} same_source = checkpoint.get("source") == source_name rows_completed = int(checkpoint.get("rows_completed", 0)) if same_source else 0 cumulative_stats = dict(checkpoint.get("cumulative_stats", {})) if same_source else {} source_exhausted = bool(checkpoint.get("source_exhausted")) if same_source else False if source_exhausted: print(f"'{source_name}' is already fully processed ({rows_completed} rows). " "Nothing new to do. Point --source at a different dataset, or delete " "data/metadata/checkpoint.json to reprocess from the start.") return {"processed": 0, "rows_completed": rows_completed, "source_exhausted": True} if rows_completed: print(f"Resuming '{source_name}' at row {rows_completed} " f"(already processed in earlier runs).") deduper = Deduper(paths["dedupe"], thresholds.get("near_duplicate_similarity", 0.94)) coverage = CoverageTracker( paths["coverage"], topics, thresholds["default_topic_target"] ) writer = DatasetWriter(paths["output"]) reviewer = None if dry_run else NIMReviewer(topics) stats = {"processed": 0, "include": 0, "manual_review": 0, "reject": 0, "skip": 0, "retry": 0, "nim_schema_failures": 0} dataset = stream_hf_dataset(source_name, source_cfg.get("split", "train")) if rows_completed: dataset = dataset.skip(rows_completed) stop_state = _install_stop_handler() row_index = rows_completed - 1 # kept correct even if the loop body never runs exhausted_this_run = True # flipped to False the moment we break instead of exhausting the source def checkpoint_now(exhausted: bool) -> None: save_checkpoint(paths["checkpoint"], { "source": source_name, "rows_completed": row_index + 1, "cumulative_stats": _merge_stats(cumulative_stats, stats), "last_run_stats": stats, "source_exhausted": exhausted, "last_updated": time.strftime("%Y-%m-%dT%H:%M:%S"), }) try: for offset, row in enumerate(dataset): if offset >= limit: exhausted_this_run = False break if stop_state["stop"]: exhausted_this_run = False print(f"Stopping early by request, after {stats['processed']} " "records this run.") break row_index = rows_completed + offset record = normalize_source_row( row, source_name, row_index, source_cfg.get("instruction_field", "instruction"), source_cfg.get("input_field", "input"), source_cfg.get("output_field", "output"), ) stats["processed"] += 1 source_ok, source_reason = check_source_record(record) code = extract_code(record["output"]) if not source_ok: final = { **record, "code": code, "tier": "unclassified", "checks": {"source_passed": False}, "decision": "reject", "decision_reason": source_reason, } writer.write("reject", final, tier="unclassified") stats["reject"] += 1 checkpoint_now(exhausted=False) continue if not code: final = { **record, "code": None, "tier": "unclassified", "checks": {"source_passed": True, "code_extracted": False}, "decision": "reject", "decision_reason": "no_usable_python_code", } writer.write("reject", final, tier="unclassified") stats["reject"] += 1 checkpoint_now(exhausted=False) continue static = inspect_code(code) # Duplicate check happens BEFORE sandbox execution and BEFORE any # NIM API call, on purpose: there's no point spending execution # time (or worse, a paid API request) testing/reviewing code # that's already been seen before. Cheapest check first. dup = deduper.check_and_add(code, record["record_id"]) duplicate, code_hash = dup["duplicate"], dup["exact_hash"] secret = scan_code(code) tier, tier_library = tiers_mod.classify_tier(static.imports, tier2_libraries) # Only tier 1 (import-free) has an execution environment today. # Tiers 2/3 don't have a per-library or per-project sandbox yet, so # we classify and (optionally) NIM-review them without executing. # Skip execution entirely for duplicates — we're going to `skip` # this record regardless of what execution would show. execution = None if (not duplicate and tier == tiers_mod.TIER1_BASIC and static.ast_valid and static.compile_valid and not static.secret_found and secret["passed"]): execution = run_code(code) checks = { "source_passed": True, "code_extracted": True, "ast_valid": static.ast_valid, "compile_valid": static.compile_valid, "secret_found": static.secret_found, "secret_passed": secret["passed"], "secret_scan": secret, "duplicate_kind": dup["kind"], "duplicate_match_id": dup["match_id"], "duplicate_similarity": dup["similarity"], "ast_fingerprint": dup["ast_fingerprint"], "code_too_short": static.code_too_short, "imports": static.imports, "static_error": static.error, "duplicate": duplicate, "code_hash": code_hash, "tier": tier, "tier_library": tier_library, "basic_tier_allowed": tier == tiers_mod.TIER1_BASIC, "execution_attempted": bool(execution and execution.attempted), "execution_status": execution.status if execution else "not_attempted", "execution_isolation": execution.isolation if execution else None, "execution_warning": execution.warning if execution else None, "execution_passed": bool(execution and execution.passed), "execution_timed_out": bool(execution and execution.timed_out), "execution_returncode": execution.returncode if execution else None, "execution_stdout": execution.stdout if execution else "", "execution_stderr": execution.stderr if execution else "", } # Hard/static failures are written without spending a NIM request. hard_reason = None hard_decision = None if not static.ast_valid: hard_decision, hard_reason = "reject", "syntax_invalid" elif not static.compile_valid: hard_decision, hard_reason = "reject", "compile_failed" elif static.secret_found: hard_decision, hard_reason = "reject", "secret_detected" elif checks.get("secret_scan", {}).get("passed") is False: hard_decision, hard_reason = "reject", "gitleaks_secret_detected" elif duplicate: hard_decision, hard_reason = "skip", "duplicate" elif tier not in active_tiers: hard_decision, hard_reason = "skip", f"tier_not_active:{tier}" elif execution is not None and not execution.passed: hard_decision, hard_reason = "reject", "sandbox_execution_failed" if hard_decision is not None: final = { **record, "code": code, "tier": tier, "tier_library": tier_library, "checks": checks, "nim": None, "nim_status": "not_called_hard_check", "decision": hard_decision, "decision_reason": hard_reason, } writer.write(hard_decision, final, tier=tier, tier_library=tier_library) stats[hard_decision] += 1 checkpoint_now(exhausted=False) continue if dry_run: final = { **record, "code": code, "tier": tier, "tier_library": tier_library, "checks": checks, "nim": None, "decision": "manual_review", "decision_reason": "dry_run_nim_not_called", } writer.write("manual_review", final, tier=tier, tier_library=tier_library) stats["manual_review"] += 1 checkpoint_now(exhausted=False) continue try: nim, raw, attempts = reviewer.review(record["instruction"], record["input"], code) writer.write_raw_nim(record["record_id"], raw) nim["review_attempts"] = attempts schema_ok, schema_error = validate_nim_response(nim, set(topics)) except Exception as exc: final = { **record, "code": code, "tier": tier, "tier_library": tier_library, "checks": checks, "nim": None, "decision": "retry", "decision_reason": f"nim_request_failed: {type(exc).__name__}: {exc}", } writer.write("retry", final, tier=tier, tier_library=tier_library) stats["retry"] = stats.get("retry", 0) + 1 checkpoint_now(exhausted=False) continue if not schema_ok: stats["nim_schema_failures"] += 1 final = { **record, "code": code, "tier": tier, "tier_library": tier_library, "checks": checks, "nim": nim, "decision": "manual_review", "decision_reason": f"nim_schema_invalid: {schema_error}", } writer.write("manual_review", final, tier=tier, tier_library=tier_library) stats["manual_review"] += 1 checkpoint_now(exhausted=False) continue decision, reason = decide(checks, nim, coverage) if tier != tiers_mod.TIER1_BASIC and decision == "include": # Never auto-include a record whose code was never executed. decision, reason = "manual_review", f"{reason}_unverified_no_execution_env" if decision == "include": coverage.add(nim["dominant_topic"]) final = { **record, "code": code, "tier": tier, "tier_library": tier_library, "checks": checks, "nim": nim, "decision": decision, "decision_reason": reason, } writer.write(decision, final, tier=tier, tier_library=tier_library) stats[decision] += 1 # Checkpoint after every single row: this is what lets a power # failure or a killed terminal lose at most the one in-flight row, # not the whole run. checkpoint_now(exhausted=False) else: # The for-loop finished naturally (the dataset ran out of rows) # rather than via `break` — that means the entire source has been # consumed. exhausted_this_run stays True in that case. pass finally: checkpoint_now(exhausted=exhausted_this_run) stats["rows_completed"] = row_index + 1 stats["source_exhausted"] = exhausted_this_run stats["cumulative_stats"] = _merge_stats(cumulative_stats, stats) return stats