File size: 17,701 Bytes
0109502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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:<tier>") 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