Spaces:
Sleeping
Sleeping
PERDYPTO commited on
Update pipeline.py
Browse files- pipeline.py +271 -132
pipeline.py
CHANGED
|
@@ -12,11 +12,60 @@
|
|
| 12 |
#
|
| 13 |
# The FastAPI server starts automatically and exposes:
|
| 14 |
# /health -> current pipeline status + aggregated stats
|
| 15 |
-
# /status -> more detailed per
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
# ============================================================
|
| 17 |
|
| 18 |
import os
|
| 19 |
-
import
|
| 20 |
import json
|
| 21 |
import time
|
| 22 |
import gzip
|
|
@@ -26,7 +75,6 @@ import sqlite3
|
|
| 26 |
import subprocess
|
| 27 |
import traceback
|
| 28 |
import multiprocessing as mp
|
| 29 |
-
import requests
|
| 30 |
import threading
|
| 31 |
import signal
|
| 32 |
|
|
@@ -80,11 +128,21 @@ AST_ACCEPT_MODE = "ANY"
|
|
| 80 |
# Parallelism – reduced for HF Space (2 vCPU, 16 GB RAM)
|
| 81 |
MAX_WORKERS = 2
|
| 82 |
|
| 83 |
-
#
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
#
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
# Quality filters
|
| 90 |
MIN_CHARS = 100
|
|
@@ -102,12 +160,16 @@ REMOTE_STATE = f"{REMOTE_ROOT}/state"
|
|
| 102 |
REMOTE_FINAL = f"{REMOTE_ROOT}/final"
|
| 103 |
|
| 104 |
# Timeouts (in seconds)
|
| 105 |
-
AST_TIMEOUT = 30 # per
|
| 106 |
HTTP_TIMEOUT = (30, 120) # connect and read timeout for requests
|
| 107 |
UPLOAD_TIMEOUT = 300 # overall upload timeout
|
|
|
|
| 108 |
|
| 109 |
# ============================================================
|
| 110 |
# DATASET LIST – CATEGORY 1 (SOURCE CODE ONLY)
|
|
|
|
|
|
|
|
|
|
| 111 |
# ============================================================
|
| 112 |
DATASETS = [
|
| 113 |
{
|
|
@@ -225,7 +287,7 @@ pipeline_status = {
|
|
| 225 |
}
|
| 226 |
|
| 227 |
# ============================================================
|
| 228 |
-
# HELPER FUNCTIONS
|
| 229 |
# ============================================================
|
| 230 |
|
| 231 |
def retry(fn, label, retries=5, timeout=HTTP_TIMEOUT):
|
|
@@ -254,8 +316,10 @@ def upload_file(local_path, remote_path):
|
|
| 254 |
)
|
| 255 |
except Exception as e:
|
| 256 |
result[0] = e
|
| 257 |
-
|
| 258 |
-
|
|
|
|
|
|
|
| 259 |
thread.start()
|
| 260 |
thread.join(timeout=UPLOAD_TIMEOUT)
|
| 261 |
if thread.is_alive():
|
|
@@ -265,6 +329,71 @@ def upload_file(local_path, remote_path):
|
|
| 265 |
return result[1]
|
| 266 |
return retry(op, f"upload {remote_path}")
|
| 267 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
def exact_hash(text):
|
| 269 |
return hashlib.sha256(text.encode("utf-8", errors="strict")).hexdigest()
|
| 270 |
|
|
@@ -345,7 +474,7 @@ def extract_record(row, cfg):
|
|
| 345 |
}
|
| 346 |
|
| 347 |
# ============================================================
|
| 348 |
-
# AST VALIDATOR (subprocess workers
|
| 349 |
# ============================================================
|
| 350 |
|
| 351 |
AST_CHILD_CODE = r'''
|
|
@@ -362,13 +491,30 @@ for line in sys.stdin:
|
|
| 362 |
ast.parse(source)
|
| 363 |
print("OK", flush=True)
|
| 364 |
except Exception as e:
|
| 365 |
-
|
|
|
|
| 366 |
'''
|
| 367 |
|
| 368 |
class ASTWorker:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 369 |
def __init__(self, version, executable):
|
| 370 |
self.version = version
|
| 371 |
self.executable = executable
|
|
|
|
| 372 |
self._start_process()
|
| 373 |
|
| 374 |
def _start_process(self):
|
|
@@ -377,36 +523,57 @@ class ASTWorker:
|
|
| 377 |
stdin=subprocess.PIPE,
|
| 378 |
stdout=subprocess.PIPE,
|
| 379 |
stderr=subprocess.PIPE,
|
| 380 |
-
text=False, # use bytes to avoid encoding issues
|
| 381 |
bufsize=0, # unbuffered
|
| 382 |
)
|
| 383 |
|
| 384 |
def check(self, text, timeout=AST_TIMEOUT):
|
| 385 |
import base64
|
| 386 |
encoded = base64.b64encode(text.encode("utf-8", errors="strict")).decode("ascii")
|
| 387 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 388 |
try:
|
| 389 |
-
out, err = self.process.communicate(input=input_data, timeout=timeout)
|
| 390 |
-
result = out.decode("utf-8", errors="ignore").strip()
|
| 391 |
-
if result == "OK":
|
| 392 |
-
return True, "OK"
|
| 393 |
-
else:
|
| 394 |
-
return False, result
|
| 395 |
-
except subprocess.TimeoutExpired:
|
| 396 |
-
# Kill the process and restart
|
| 397 |
self.process.kill()
|
| 398 |
-
self.process.wait()
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
# Restart on any other error
|
| 403 |
-
try:
|
| 404 |
-
self.process.kill()
|
| 405 |
-
self.process.wait()
|
| 406 |
-
except Exception:
|
| 407 |
-
pass
|
| 408 |
-
self._start_process()
|
| 409 |
-
return False, str(e)
|
| 410 |
|
| 411 |
def close(self):
|
| 412 |
try:
|
|
@@ -440,16 +607,7 @@ class ASTValidator:
|
|
| 440 |
results[worker.version] = {"passed": bool(passed), "detail": detail}
|
| 441 |
if passed:
|
| 442 |
any_passed = True
|
| 443 |
-
# We still validate with other workers to collect full results,
|
| 444 |
-
# but we can break early if we only care about "any".
|
| 445 |
-
# To save time, we can break if we already have a pass.
|
| 446 |
-
# But we want to check all versions for completeness.
|
| 447 |
-
# We'll continue, but we can skip if we want speed.
|
| 448 |
-
# We'll continue to gather results but if we already have a pass,
|
| 449 |
-
# we still need to check others? Not necessary for "ANY" rule.
|
| 450 |
-
# We'll break early for speed.
|
| 451 |
break
|
| 452 |
-
# Return True if any worker passed
|
| 453 |
return any_passed, results
|
| 454 |
|
| 455 |
def close(self):
|
|
@@ -492,19 +650,18 @@ def load_task_state(dataset_name, task_id):
|
|
| 492 |
return json.load(f)
|
| 493 |
except Exception:
|
| 494 |
pass
|
| 495 |
-
# Try to download from bucket
|
|
|
|
| 496 |
remote_path = f"{REMOTE_STATE}/{dataset_name}/task_{task_id}.json"
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
if response.status_code == 200:
|
| 501 |
-
data = response.json()
|
| 502 |
path.parent.mkdir(parents=True, exist_ok=True)
|
| 503 |
with open(path, "w") as f:
|
| 504 |
json.dump(data, f, indent=2)
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
return default_state()
|
| 509 |
|
| 510 |
def save_task_state(dataset_name, task_id, state):
|
|
@@ -568,10 +725,19 @@ def process_partition(cfg, task_id, total_tasks, interpreters):
|
|
| 568 |
ds = ds.shard(num_shards=total_tasks, index=task_id)
|
| 569 |
print(f"[{dataset_name}] TASK {task_id}: assigned partition {task_id + 1}/{total_tasks}")
|
| 570 |
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 575 |
|
| 576 |
validator = ASTValidator(interpreters)
|
| 577 |
|
|
@@ -586,7 +752,7 @@ def process_partition(cfg, task_id, total_tasks, interpreters):
|
|
| 586 |
conn.execute("CREATE INDEX IF NOT EXISTS idx_normalized ON fingerprints(normalized_hash)")
|
| 587 |
conn.commit()
|
| 588 |
|
| 589 |
-
# In
|
| 590 |
exact_cache = set()
|
| 591 |
normalized_cache = set()
|
| 592 |
pending_hashes = [] # list of (exact_hash, normalized_hash) to be inserted in batch
|
|
@@ -595,7 +761,10 @@ def process_partition(cfg, task_id, total_tasks, interpreters):
|
|
| 595 |
shard_number = int(state.get("shards_uploaded", 0))
|
| 596 |
last_progress = time.time()
|
| 597 |
|
| 598 |
-
#
|
|
|
|
|
|
|
|
|
|
| 599 |
def flush_hash_cache():
|
| 600 |
nonlocal pending_hashes
|
| 601 |
if not pending_hashes:
|
|
@@ -609,24 +778,30 @@ def process_partition(cfg, task_id, total_tasks, interpreters):
|
|
| 609 |
exact_cache.clear()
|
| 610 |
normalized_cache.clear()
|
| 611 |
|
| 612 |
-
# Helper to flush records to shard and also flush hash cache
|
| 613 |
def flush_shard_and_cache():
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
records
|
| 622 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 623 |
flush_hash_cache()
|
| 624 |
-
|
|
|
|
| 625 |
save_task_state(dataset_name, task_id, state)
|
| 626 |
|
| 627 |
try:
|
| 628 |
for row in ds:
|
| 629 |
state["processed"] += 1
|
|
|
|
| 630 |
|
| 631 |
try:
|
| 632 |
extracted = extract_record(row, cfg)
|
|
@@ -672,12 +847,11 @@ def process_partition(cfg, task_id, total_tasks, interpreters):
|
|
| 672 |
state["other_reject"] += 1
|
| 673 |
continue
|
| 674 |
|
| 675 |
-
# Check duplicates: first in
|
| 676 |
if ehash in exact_cache or nhash in normalized_cache:
|
| 677 |
-
state["duplicate_exact"] += 1
|
| 678 |
continue
|
| 679 |
|
| 680 |
-
# Query SQLite
|
| 681 |
duplicate = conn.execute(
|
| 682 |
"SELECT exact_hash, normalized_hash FROM fingerprints WHERE exact_hash = ? OR normalized_hash = ? LIMIT 1",
|
| 683 |
(ehash, nhash)
|
|
@@ -716,7 +890,6 @@ def process_partition(cfg, task_id, total_tasks, interpreters):
|
|
| 716 |
"ast_acceptance_rule": "ANY",
|
| 717 |
}
|
| 718 |
|
| 719 |
-
# Add to in‑memory caches and pending batch
|
| 720 |
exact_cache.add(ehash)
|
| 721 |
normalized_cache.add(nhash)
|
| 722 |
pending_hashes.append((ehash, nhash))
|
|
@@ -725,17 +898,17 @@ def process_partition(cfg, task_id, total_tasks, interpreters):
|
|
| 725 |
state["bytes_accepted"] += len(text.encode("utf-8", errors="ignore"))
|
| 726 |
records.append(record)
|
| 727 |
|
| 728 |
-
# Flush shard when records reach SHARD_ROWS
|
| 729 |
if len(records) >= SHARD_ROWS:
|
| 730 |
flush_shard_and_cache()
|
| 731 |
print(f"[{dataset_name}] T{task_id} processed={state['processed']:,} | accepted={state['accepted']:,} | syntax={state['syntax_error']:,} | shards={state['shards_uploaded']:,}")
|
| 732 |
|
| 733 |
-
# Periodic checkpoint
|
|
|
|
|
|
|
|
|
|
| 734 |
if state["processed"] % CHECKPOINT_EVERY == 0:
|
| 735 |
-
|
| 736 |
-
if pending_hashes:
|
| 737 |
-
flush_hash_cache()
|
| 738 |
-
save_task_state(dataset_name, task_id, state)
|
| 739 |
|
| 740 |
# Live progress
|
| 741 |
now = time.time()
|
|
@@ -745,12 +918,8 @@ def process_partition(cfg, task_id, total_tasks, interpreters):
|
|
| 745 |
print(f"[{dataset_name}] T{task_id} processed={state['processed']:,} | accepted={state['accepted']:,} | syntax={state['syntax_error']:,} | rate={rate:.1f}/sec")
|
| 746 |
last_progress = now
|
| 747 |
|
| 748 |
-
# End of stream: flush
|
| 749 |
-
|
| 750 |
-
flush_shard_and_cache()
|
| 751 |
-
elif pending_hashes:
|
| 752 |
-
# In case there are pending hashes but no records (should not happen, but safe)
|
| 753 |
-
flush_hash_cache()
|
| 754 |
|
| 755 |
conn.commit()
|
| 756 |
state["complete"] = True
|
|
@@ -783,8 +952,12 @@ def process_partition(cfg, task_id, total_tasks, interpreters):
|
|
| 783 |
print("\n" + "!" * 80)
|
| 784 |
print(f"[{dataset_name}] TASK {task_id} FAILED")
|
| 785 |
print(traceback.format_exc())
|
| 786 |
-
# Try to flush any pending cache and save state
|
| 787 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 788 |
if pending_hashes:
|
| 789 |
flush_hash_cache()
|
| 790 |
conn.commit()
|
|
@@ -811,14 +984,12 @@ def process_partition(cfg, task_id, total_tasks, interpreters):
|
|
| 811 |
def get_interpreters():
|
| 812 |
interpreters = {}
|
| 813 |
for version in PYTHON_VERSIONS:
|
| 814 |
-
# Try uv find
|
| 815 |
result = subprocess.run(["uv", "python", "find", version], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 816 |
if result.returncode == 0:
|
| 817 |
path = result.stdout.strip().splitlines()[-1] if result.stdout else None
|
| 818 |
if path and Path(path).exists():
|
| 819 |
interpreters[version] = path
|
| 820 |
continue
|
| 821 |
-
# Fallback: search in PATH
|
| 822 |
major, minor = version.split(".")[0], version.split(".")[1]
|
| 823 |
check = subprocess.run(["which", f"python{major}.{minor}"], text=True, stdout=subprocess.PIPE)
|
| 824 |
if check.returncode == 0:
|
|
@@ -839,13 +1010,11 @@ def run_pipeline():
|
|
| 839 |
pipeline_status["finished_tasks"] = 0
|
| 840 |
|
| 841 |
try:
|
| 842 |
-
# Get interpreters
|
| 843 |
interpreters = get_interpreters()
|
| 844 |
print("Python interpreters found:")
|
| 845 |
for v, p in interpreters.items():
|
| 846 |
print(f" {v} -> {p}")
|
| 847 |
|
| 848 |
-
# Determine shard counts and build task queue
|
| 849 |
DATASET_TASKS = []
|
| 850 |
for cfg in DATASETS:
|
| 851 |
ds = load_stream(cfg)
|
|
@@ -863,12 +1032,10 @@ def run_pipeline():
|
|
| 863 |
|
| 864 |
print(f"Total scheduled task partitions: {len(DATASET_TASKS):,}")
|
| 865 |
|
| 866 |
-
# Run tasks concurrently (at most MAX_WORKERS at a time)
|
| 867 |
results = {}
|
| 868 |
task_cursor = 0
|
| 869 |
active = {}
|
| 870 |
with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
|
| 871 |
-
# initial fill
|
| 872 |
while len(active) < MAX_WORKERS and task_cursor < len(DATASET_TASKS):
|
| 873 |
task = DATASET_TASKS[task_cursor]
|
| 874 |
task_cursor += 1
|
|
@@ -876,7 +1043,6 @@ def run_pipeline():
|
|
| 876 |
active[future] = task
|
| 877 |
print(f"[SCHEDULER] STARTED {task['cfg']['name']} T{task['task_id']}")
|
| 878 |
|
| 879 |
-
# Continue until all tasks done
|
| 880 |
while active:
|
| 881 |
for completed_future in as_completed(active.keys()):
|
| 882 |
task = active.pop(completed_future)
|
|
@@ -889,14 +1055,13 @@ def run_pipeline():
|
|
| 889 |
pipeline_status["finished_tasks"] += 1
|
| 890 |
print(f"\n[SCHEDULER] FINISHED {task['cfg']['name']} T{task['task_id']} complete={result.get('complete', False)}")
|
| 891 |
|
| 892 |
-
# Fill the slot immediately
|
| 893 |
if task_cursor < len(DATASET_TASKS):
|
| 894 |
next_task = DATASET_TASKS[task_cursor]
|
| 895 |
task_cursor += 1
|
| 896 |
future = executor.submit(process_partition, next_task["cfg"], next_task["task_id"], next_task["total_tasks"], interpreters)
|
| 897 |
active[future] = next_task
|
| 898 |
print(f"[SCHEDULER] STARTED {next_task['cfg']['name']} T{next_task['task_id']}")
|
| 899 |
-
break
|
| 900 |
|
| 901 |
# ============================================================
|
| 902 |
# GLOBAL DEDUP (across all tasks/datasets)
|
|
@@ -918,8 +1083,7 @@ def run_pipeline():
|
|
| 918 |
global_records = []
|
| 919 |
global_shard_number = 0
|
| 920 |
|
| 921 |
-
|
| 922 |
-
pending_global_hashes = [] # list of (exact_hash, normalized_hash)
|
| 923 |
BATCH_SIZE = 1000
|
| 924 |
|
| 925 |
def flush_global_hashes():
|
|
@@ -951,7 +1115,6 @@ def run_pipeline():
|
|
| 951 |
global_records = []
|
| 952 |
global_shard_number += 1
|
| 953 |
|
| 954 |
-
# Collect all remote shard paths from completed tasks
|
| 955 |
REMOTE_SHARDS = []
|
| 956 |
for task in DATASET_TASKS:
|
| 957 |
key = (task["cfg"]["name"], task["task_id"])
|
|
@@ -964,22 +1127,16 @@ def run_pipeline():
|
|
| 964 |
|
| 965 |
print(f"Remote worker shards: {len(REMOTE_SHARDS):,}")
|
| 966 |
|
| 967 |
-
# Download each shard, dedup globally, and write final master shards
|
| 968 |
for idx, (dataset_name, task_id, shard_number, remote_path) in enumerate(REMOTE_SHARDS, 1):
|
| 969 |
print(f"\n[GLOBAL] {idx:,}/{len(REMOTE_SHARDS):,} {dataset_name} T{task_id} S{shard_number}")
|
| 970 |
local_path = TMP_ROOT / "global" / dataset_name / f"task_{task_id}" / Path(remote_path).name
|
| 971 |
-
|
| 972 |
-
|
| 973 |
-
|
| 974 |
-
|
| 975 |
-
|
| 976 |
-
|
| 977 |
-
|
| 978 |
-
with open(local_path, "wb") as f:
|
| 979 |
-
f.write(response.content)
|
| 980 |
-
except Exception as e:
|
| 981 |
-
print(f"Download error: {e}")
|
| 982 |
-
continue
|
| 983 |
|
| 984 |
with gzip.open(local_path, "rb") as f:
|
| 985 |
for line in f:
|
|
@@ -1003,24 +1160,19 @@ def run_pipeline():
|
|
| 1003 |
global_stats["duplicate_normalized"] += 1
|
| 1004 |
continue
|
| 1005 |
|
| 1006 |
-
# New record: add to pending hashes and global_records
|
| 1007 |
pending_global_hashes.append((ehash, nhash))
|
| 1008 |
global_records.append(record)
|
| 1009 |
global_stats["accepted_records"] += 1
|
| 1010 |
global_stats["bytes"] += int(record.get("char_count", 0))
|
| 1011 |
|
| 1012 |
-
# Flush hashes if batch size reached
|
| 1013 |
if len(pending_global_hashes) >= BATCH_SIZE:
|
| 1014 |
flush_global_hashes()
|
| 1015 |
|
| 1016 |
-
# Flush records if SHARD_ROWS reached
|
| 1017 |
if len(global_records) >= SHARD_ROWS:
|
| 1018 |
flush_global_records()
|
| 1019 |
|
| 1020 |
-
# After processing the shard, flush any remaining hashes
|
| 1021 |
if pending_global_hashes:
|
| 1022 |
flush_global_hashes()
|
| 1023 |
-
# Also flush records if any left (will be done at end, but safe)
|
| 1024 |
if len(global_records) >= SHARD_ROWS:
|
| 1025 |
flush_global_records()
|
| 1026 |
|
|
@@ -1033,22 +1185,20 @@ def run_pipeline():
|
|
| 1033 |
if idx % 10 == 0 or idx == len(REMOTE_SHARDS):
|
| 1034 |
print(f"[GLOBAL] input={global_stats['input_records']:,} | accepted={global_stats['accepted_records']:,} | exact_dup={global_stats['duplicate_exact']:,} | normalized_dup={global_stats['duplicate_normalized']:,}")
|
| 1035 |
|
| 1036 |
-
# Final flush
|
| 1037 |
if pending_global_hashes:
|
| 1038 |
flush_global_hashes()
|
| 1039 |
flush_global_records()
|
| 1040 |
gconn.commit()
|
| 1041 |
gconn.close()
|
| 1042 |
|
| 1043 |
-
# Upload global DB
|
| 1044 |
upload_file(GLOBAL_DB, f"{REMOTE_FINAL}/global_dedup.sqlite")
|
| 1045 |
|
| 1046 |
-
# Final metadata
|
| 1047 |
final_metadata = {
|
| 1048 |
"name": "Category 1 Python Master",
|
| 1049 |
"pipeline_version": "v4",
|
| 1050 |
"source_datasets": [cfg["dataset"] for cfg in DATASETS],
|
| 1051 |
"max_workers": MAX_WORKERS,
|
|
|
|
| 1052 |
"python_ast_versions": PYTHON_VERSIONS,
|
| 1053 |
"ast_acceptance_rule": "ANY",
|
| 1054 |
"dedup": {"exact_sha256": True, "normalized_sha256": True, "ast_structure_as_key": False},
|
|
@@ -1061,7 +1211,6 @@ def run_pipeline():
|
|
| 1061 |
json.dump(final_metadata, f, indent=2)
|
| 1062 |
upload_file(metadata_path, f"{REMOTE_FINAL}/dataset_metadata.json")
|
| 1063 |
|
| 1064 |
-
# Update global status with final stats
|
| 1065 |
pipeline_status["stats"] = global_stats
|
| 1066 |
pipeline_status["stats"]["final_shards"] = global_shard_number
|
| 1067 |
pipeline_status["completed"] = True
|
|
@@ -1091,12 +1240,9 @@ def run_pipeline():
|
|
| 1091 |
|
| 1092 |
@asynccontextmanager
|
| 1093 |
async def lifespan(app: FastAPI):
|
| 1094 |
-
# Startup: launch pipeline in a background thread (non‑daemon to allow graceful shutdown)
|
| 1095 |
thread = threading.Thread(target=run_pipeline, daemon=False)
|
| 1096 |
thread.start()
|
| 1097 |
yield
|
| 1098 |
-
# Shutdown: give the pipeline a chance to finish (or we can just let it continue)
|
| 1099 |
-
# We'll wait for a while, but if it's still running, we log and proceed.
|
| 1100 |
if thread.is_alive():
|
| 1101 |
print("[LIFESPAN] Pipeline is still running, waiting up to 60 seconds for graceful exit...")
|
| 1102 |
thread.join(timeout=60)
|
|
@@ -1107,9 +1253,6 @@ app = FastAPI(title="Category1 Pipeline API", lifespan=lifespan)
|
|
| 1107 |
|
| 1108 |
@app.get("/health")
|
| 1109 |
async def health():
|
| 1110 |
-
"""
|
| 1111 |
-
Returns current pipeline statistics and health status.
|
| 1112 |
-
"""
|
| 1113 |
return JSONResponse(content={
|
| 1114 |
"status": pipeline_status["current_stage"],
|
| 1115 |
"started": pipeline_status["started"],
|
|
@@ -1122,10 +1265,6 @@ async def health():
|
|
| 1122 |
|
| 1123 |
@app.get("/status")
|
| 1124 |
async def status():
|
| 1125 |
-
"""
|
| 1126 |
-
Returns detailed per‑dataset task status (reads state files).
|
| 1127 |
-
For a deeper view, you can scan STATE_ROOT/*/task_*_COMPLETE.json.
|
| 1128 |
-
"""
|
| 1129 |
detailed = {}
|
| 1130 |
for dataset_dir in STATE_ROOT.iterdir():
|
| 1131 |
if dataset_dir.is_dir():
|
|
|
|
| 12 |
#
|
| 13 |
# The FastAPI server starts automatically and exposes:
|
| 14 |
# /health -> current pipeline status + aggregated stats
|
| 15 |
+
# /status -> more detailed per-task progress
|
| 16 |
+
#
|
| 17 |
+
# ------------------------------------------------------------
|
| 18 |
+
# CHANGES IN THIS REVISION (vs. the version you pasted):
|
| 19 |
+
#
|
| 20 |
+
# 1. FIXED: bucket downloads no longer use a fabricated
|
| 21 |
+
# "https://huggingface.co/buckets/{id}/resolve/{path}" REST
|
| 22 |
+
# URL (that endpoint does not exist for buckets and was
|
| 23 |
+
# silently failing, caught by broad except blocks, which
|
| 24 |
+
# meant state-resume never worked and global dedup could
|
| 25 |
+
# complete "successfully" with zero records). Downloads now
|
| 26 |
+
# shell out to the documented `hf` CLI:
|
| 27 |
+
# hf buckets cp hf://buckets/<bucket_id>/<path> -
|
| 28 |
+
# which streams bytes to stdout. See download_bucket_file().
|
| 29 |
+
#
|
| 30 |
+
# 2. FIXED: ASTWorker no longer misuses Popen.communicate() in
|
| 31 |
+
# a loop (communicate() closes stdin and waits for exit — it
|
| 32 |
+
# cannot be called repeatedly against a persistent worker).
|
| 33 |
+
# Each worker now writes to stdin / reads a line from stdout
|
| 34 |
+
# directly, so the 4 interpreter subprocesses are genuinely
|
| 35 |
+
# long-lived and reused across every file, as originally
|
| 36 |
+
# intended. This is a large performance fix as well as a
|
| 37 |
+
# correctness fix.
|
| 38 |
+
#
|
| 39 |
+
# 3. FIXED: state["processed"] is now only advanced up to the
|
| 40 |
+
# last successfully flushed shard boundary, not per-row. This
|
| 41 |
+
# closes the crash/resume data-loss gap where accepted records
|
| 42 |
+
# sitting in an unflushed shard buffer would be silently
|
| 43 |
+
# skipped on resume (ds.skip(processed) skipped past rows
|
| 44 |
+
# that had never actually been uploaded).
|
| 45 |
+
#
|
| 46 |
+
# 4. FIXED: global-dedup shard download failures now hard-stop
|
| 47 |
+
# the pipeline (raise) instead of silently `continue`-ing
|
| 48 |
+
# past a missing shard, which previously could produce a
|
| 49 |
+
# "COMPLETE" pipeline run with silently missing data.
|
| 50 |
+
#
|
| 51 |
+
# 5. FIXED: upload_file's retry-with-thread-timeout wrapper now
|
| 52 |
+
# marks the helper thread as daemon=True, so repeated timeouts
|
| 53 |
+
# don't leak non-daemon threads that block process shutdown.
|
| 54 |
+
#
|
| 55 |
+
# 6. CHANGED (requested): SHARD_ROWS raised from 5,000 to
|
| 56 |
+
# 500,000 records per shard, so instead of many ~6-7MB files
|
| 57 |
+
# you get far fewer, larger (~500-700MB class) files. Same
|
| 58 |
+
# knob also governs CHECKPOINT_EVERY cadence (kept equal to
|
| 59 |
+
# SHARD_ROWS, consistent with the original design).
|
| 60 |
+
#
|
| 61 |
+
# 7. CHANGED (requested): all originally-listed datasets are kept
|
| 62 |
+
# in DATASETS for reference, but only the first
|
| 63 |
+
# ("the_stack_dedup_python") is active — every other entry is
|
| 64 |
+
# commented out, exactly as before, just re-confirmed intact.
|
| 65 |
# ============================================================
|
| 66 |
|
| 67 |
import os
|
| 68 |
+
import sys
|
| 69 |
import json
|
| 70 |
import time
|
| 71 |
import gzip
|
|
|
|
| 75 |
import subprocess
|
| 76 |
import traceback
|
| 77 |
import multiprocessing as mp
|
|
|
|
| 78 |
import threading
|
| 79 |
import signal
|
| 80 |
|
|
|
|
| 128 |
# Parallelism – reduced for HF Space (2 vCPU, 16 GB RAM)
|
| 129 |
MAX_WORKERS = 2
|
| 130 |
|
| 131 |
+
# ------------------------------------------------------------
|
| 132 |
+
# SHARD SIZE — CHANGED per request.
|
| 133 |
+
# Previously 5,000 rows/shard (~6-7MB gzip files, many of them).
|
| 134 |
+
# Now 500,000 rows/shard -> far fewer, larger files.
|
| 135 |
+
# NOTE: actual file size still depends on average row size; at
|
| 136 |
+
# ~1-1.4KB/row post-gzip this lands roughly in the 500MB-700MB
|
| 137 |
+
# range per file, as you asked for.
|
| 138 |
+
# ------------------------------------------------------------
|
| 139 |
+
SHARD_ROWS = 500_000
|
| 140 |
+
|
| 141 |
+
# Checkpoint frequency (in source records). Kept equal to
|
| 142 |
+
# SHARD_ROWS so a checkpoint always lines up with a shard flush
|
| 143 |
+
# boundary (see fix #3 above — this matters for correctness now,
|
| 144 |
+
# not just cadence).
|
| 145 |
+
CHECKPOINT_EVERY = SHARD_ROWS
|
| 146 |
|
| 147 |
# Quality filters
|
| 148 |
MIN_CHARS = 100
|
|
|
|
| 160 |
REMOTE_FINAL = f"{REMOTE_ROOT}/final"
|
| 161 |
|
| 162 |
# Timeouts (in seconds)
|
| 163 |
+
AST_TIMEOUT = 30 # per-file AST validation timeout
|
| 164 |
HTTP_TIMEOUT = (30, 120) # connect and read timeout for requests
|
| 165 |
UPLOAD_TIMEOUT = 300 # overall upload timeout
|
| 166 |
+
DOWNLOAD_TIMEOUT = 300 # overall download timeout (bucket CLI download)
|
| 167 |
|
| 168 |
# ============================================================
|
| 169 |
# DATASET LIST – CATEGORY 1 (SOURCE CODE ONLY)
|
| 170 |
+
# All originally-listed datasets are preserved below for
|
| 171 |
+
# reference. Only the first entry is active; every other entry
|
| 172 |
+
# stays commented out.
|
| 173 |
# ============================================================
|
| 174 |
DATASETS = [
|
| 175 |
{
|
|
|
|
| 287 |
}
|
| 288 |
|
| 289 |
# ============================================================
|
| 290 |
+
# HELPER FUNCTIONS
|
| 291 |
# ============================================================
|
| 292 |
|
| 293 |
def retry(fn, label, retries=5, timeout=HTTP_TIMEOUT):
|
|
|
|
| 316 |
)
|
| 317 |
except Exception as e:
|
| 318 |
result[0] = e
|
| 319 |
+
# FIX (#5): daemon=True so a hung upload thread doesn't
|
| 320 |
+
# block process shutdown / leak indefinitely on repeated
|
| 321 |
+
# retries.
|
| 322 |
+
thread = threading.Thread(target=target, daemon=True)
|
| 323 |
thread.start()
|
| 324 |
thread.join(timeout=UPLOAD_TIMEOUT)
|
| 325 |
if thread.is_alive():
|
|
|
|
| 329 |
return result[1]
|
| 330 |
return retry(op, f"upload {remote_path}")
|
| 331 |
|
| 332 |
+
def download_bucket_file(remote_path, local_path, timeout=DOWNLOAD_TIMEOUT):
|
| 333 |
+
"""
|
| 334 |
+
FIX (#1): Bucket downloads previously hit a fabricated REST URL
|
| 335 |
+
(huggingface.co/buckets/{id}/resolve/{path}) which is not a real
|
| 336 |
+
endpoint. The documented way to pull a file back out of a bucket
|
| 337 |
+
is the `hf` CLI's bucket-copy command, streaming to stdout:
|
| 338 |
+
|
| 339 |
+
hf buckets cp hf://buckets/<bucket_id>/<remote_path> -
|
| 340 |
+
|
| 341 |
+
We shell out to that here. Raises on any failure — callers must
|
| 342 |
+
NOT silently swallow this (see fix #4).
|
| 343 |
+
"""
|
| 344 |
+
local_path = Path(local_path)
|
| 345 |
+
local_path.parent.mkdir(parents=True, exist_ok=True)
|
| 346 |
+
remote_uri = f"hf://buckets/{BUCKET_ID}/{remote_path}"
|
| 347 |
+
|
| 348 |
+
def op():
|
| 349 |
+
env = os.environ.copy()
|
| 350 |
+
env["HF_TOKEN"] = HF_TOKEN
|
| 351 |
+
with open(local_path, "wb") as out_f:
|
| 352 |
+
proc = subprocess.run(
|
| 353 |
+
["hf", "buckets", "cp", remote_uri, "-"],
|
| 354 |
+
stdout=out_f,
|
| 355 |
+
stderr=subprocess.PIPE,
|
| 356 |
+
env=env,
|
| 357 |
+
timeout=timeout,
|
| 358 |
+
)
|
| 359 |
+
if proc.returncode != 0:
|
| 360 |
+
# Clean up partial file so we never mistake it for real data
|
| 361 |
+
try:
|
| 362 |
+
local_path.unlink()
|
| 363 |
+
except Exception:
|
| 364 |
+
pass
|
| 365 |
+
stderr_text = proc.stderr.decode("utf-8", errors="ignore") if proc.stderr else ""
|
| 366 |
+
raise RuntimeError(f"hf buckets cp failed ({proc.returncode}) for {remote_uri}: {stderr_text[:500]}")
|
| 367 |
+
if not local_path.exists() or local_path.stat().st_size == 0:
|
| 368 |
+
raise RuntimeError(f"Downloaded file missing or empty: {remote_uri}")
|
| 369 |
+
return local_path
|
| 370 |
+
|
| 371 |
+
return retry(op, f"download {remote_path}")
|
| 372 |
+
|
| 373 |
+
def download_bucket_json(remote_path, timeout=HTTP_TIMEOUT[1]):
|
| 374 |
+
"""Convenience wrapper: download a small JSON file from the bucket
|
| 375 |
+
and parse it. Returns None if the remote file genuinely does not
|
| 376 |
+
exist (as opposed to a transient failure, which retries and then
|
| 377 |
+
raises)."""
|
| 378 |
+
tmp_path = TMP_ROOT / "_json_fetch" / f"{hashlib.sha256(remote_path.encode()).hexdigest()}.json"
|
| 379 |
+
try:
|
| 380 |
+
download_bucket_file(remote_path, tmp_path, timeout=timeout)
|
| 381 |
+
except Exception as e:
|
| 382 |
+
# This can legitimately mean "doesn't exist yet" (first run,
|
| 383 |
+
# no state saved). We don't hard-fail here since callers use
|
| 384 |
+
# this specifically for optional resume state.
|
| 385 |
+
print(f"[STATE] Could not fetch remote state {remote_path}: {e}")
|
| 386 |
+
return None
|
| 387 |
+
try:
|
| 388 |
+
with open(tmp_path) as f:
|
| 389 |
+
data = json.load(f)
|
| 390 |
+
return data
|
| 391 |
+
finally:
|
| 392 |
+
try:
|
| 393 |
+
tmp_path.unlink()
|
| 394 |
+
except Exception:
|
| 395 |
+
pass
|
| 396 |
+
|
| 397 |
def exact_hash(text):
|
| 398 |
return hashlib.sha256(text.encode("utf-8", errors="strict")).hexdigest()
|
| 399 |
|
|
|
|
| 474 |
}
|
| 475 |
|
| 476 |
# ============================================================
|
| 477 |
+
# AST VALIDATOR (persistent subprocess workers, one per Python version)
|
| 478 |
# ============================================================
|
| 479 |
|
| 480 |
AST_CHILD_CODE = r'''
|
|
|
|
| 491 |
ast.parse(source)
|
| 492 |
print("OK", flush=True)
|
| 493 |
except Exception as e:
|
| 494 |
+
msg = (type(e).__name__ + "\t" + str(e)[:300]).replace("\n", " ").replace("\t", " ", 0)
|
| 495 |
+
print("ERR\t" + type(e).__name__ + "\t" + str(e)[:300].replace("\n", " "), flush=True)
|
| 496 |
'''
|
| 497 |
|
| 498 |
class ASTWorker:
|
| 499 |
+
"""
|
| 500 |
+
FIX (#2): The original implementation called
|
| 501 |
+
Popen.communicate() once per file against the SAME process
|
| 502 |
+
object. communicate() closes stdin and waits for the child to
|
| 503 |
+
exit — it is a one-shot call, not a request/response primitive
|
| 504 |
+
you can reuse. That meant every call after the first either hit
|
| 505 |
+
a dead pipe or forced a timeout-triggered restart, so in
|
| 506 |
+
practice each interpreter was likely being respawned per file
|
| 507 |
+
(or per call) instead of staying resident.
|
| 508 |
+
|
| 509 |
+
This version keeps the child's stdin/stdout pipes open across
|
| 510 |
+
calls and does the write + readline itself, so the persistent
|
| 511 |
+
"read one line, parse, print OK/ERR" loop in AST_CHILD_CODE is
|
| 512 |
+
actually used as designed.
|
| 513 |
+
"""
|
| 514 |
def __init__(self, version, executable):
|
| 515 |
self.version = version
|
| 516 |
self.executable = executable
|
| 517 |
+
self.process = None
|
| 518 |
self._start_process()
|
| 519 |
|
| 520 |
def _start_process(self):
|
|
|
|
| 523 |
stdin=subprocess.PIPE,
|
| 524 |
stdout=subprocess.PIPE,
|
| 525 |
stderr=subprocess.PIPE,
|
|
|
|
| 526 |
bufsize=0, # unbuffered
|
| 527 |
)
|
| 528 |
|
| 529 |
def check(self, text, timeout=AST_TIMEOUT):
|
| 530 |
import base64
|
| 531 |
encoded = base64.b64encode(text.encode("utf-8", errors="strict")).decode("ascii")
|
| 532 |
+
line = (encoded + "\n").encode("ascii")
|
| 533 |
+
|
| 534 |
+
result_holder = {}
|
| 535 |
+
|
| 536 |
+
def do_io():
|
| 537 |
+
try:
|
| 538 |
+
self.process.stdin.write(line)
|
| 539 |
+
self.process.stdin.flush()
|
| 540 |
+
out_line = self.process.stdout.readline()
|
| 541 |
+
result_holder["out"] = out_line
|
| 542 |
+
except Exception as e:
|
| 543 |
+
result_holder["exc"] = e
|
| 544 |
+
|
| 545 |
+
io_thread = threading.Thread(target=do_io, daemon=True)
|
| 546 |
+
io_thread.start()
|
| 547 |
+
io_thread.join(timeout=timeout)
|
| 548 |
+
|
| 549 |
+
if io_thread.is_alive():
|
| 550 |
+
# Genuinely stuck (e.g. pathological input causing a hang
|
| 551 |
+
# in ast.parse, or a dead pipe) — kill and restart.
|
| 552 |
+
self._restart()
|
| 553 |
+
return False, "TIMEOUT"
|
| 554 |
+
|
| 555 |
+
if "exc" in result_holder:
|
| 556 |
+
self._restart()
|
| 557 |
+
return False, repr(result_holder["exc"])
|
| 558 |
+
|
| 559 |
+
out_line = result_holder.get("out", b"")
|
| 560 |
+
if not out_line:
|
| 561 |
+
# Empty read means the child process exited/closed stdout.
|
| 562 |
+
self._restart()
|
| 563 |
+
return False, "EOF"
|
| 564 |
+
|
| 565 |
+
result = out_line.decode("utf-8", errors="ignore").strip()
|
| 566 |
+
if result == "OK":
|
| 567 |
+
return True, "OK"
|
| 568 |
+
return False, result
|
| 569 |
+
|
| 570 |
+
def _restart(self):
|
| 571 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 572 |
self.process.kill()
|
| 573 |
+
self.process.wait(timeout=5)
|
| 574 |
+
except Exception:
|
| 575 |
+
pass
|
| 576 |
+
self._start_process()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 577 |
|
| 578 |
def close(self):
|
| 579 |
try:
|
|
|
|
| 607 |
results[worker.version] = {"passed": bool(passed), "detail": detail}
|
| 608 |
if passed:
|
| 609 |
any_passed = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 610 |
break
|
|
|
|
| 611 |
return any_passed, results
|
| 612 |
|
| 613 |
def close(self):
|
|
|
|
| 650 |
return json.load(f)
|
| 651 |
except Exception:
|
| 652 |
pass
|
| 653 |
+
# Try to download from bucket (FIX #1: uses hf CLI now, not a
|
| 654 |
+
# fabricated REST URL).
|
| 655 |
remote_path = f"{REMOTE_STATE}/{dataset_name}/task_{task_id}.json"
|
| 656 |
+
data = download_bucket_json(remote_path)
|
| 657 |
+
if data is not None:
|
| 658 |
+
try:
|
|
|
|
|
|
|
| 659 |
path.parent.mkdir(parents=True, exist_ok=True)
|
| 660 |
with open(path, "w") as f:
|
| 661 |
json.dump(data, f, indent=2)
|
| 662 |
+
except Exception:
|
| 663 |
+
pass
|
| 664 |
+
return data
|
| 665 |
return default_state()
|
| 666 |
|
| 667 |
def save_task_state(dataset_name, task_id, state):
|
|
|
|
| 725 |
ds = ds.shard(num_shards=total_tasks, index=task_id)
|
| 726 |
print(f"[{dataset_name}] TASK {task_id}: assigned partition {task_id + 1}/{total_tasks}")
|
| 727 |
|
| 728 |
+
# FIX (#3): resume from the last row known to be SAFELY
|
| 729 |
+
# persisted (i.e. included in an uploaded shard + saved
|
| 730 |
+
# state), not from a per-row counter that could be ahead of
|
| 731 |
+
# what was actually flushed. We track that separately as
|
| 732 |
+
# "processed_committed" and keep "processed" as a live,
|
| 733 |
+
# in-progress counter that only gets promoted to
|
| 734 |
+
# "processed_committed" at flush time.
|
| 735 |
+
processed_committed = int(state.get("processed_committed", state.get("processed", 0)))
|
| 736 |
+
state["processed_committed"] = processed_committed
|
| 737 |
+
state["processed"] = processed_committed
|
| 738 |
+
if processed_committed > 0:
|
| 739 |
+
print(f"[{dataset_name}] TASK {task_id}: resuming after {processed_committed:,} committed records")
|
| 740 |
+
ds = ds.skip(processed_committed)
|
| 741 |
|
| 742 |
validator = ASTValidator(interpreters)
|
| 743 |
|
|
|
|
| 752 |
conn.execute("CREATE INDEX IF NOT EXISTS idx_normalized ON fingerprints(normalized_hash)")
|
| 753 |
conn.commit()
|
| 754 |
|
| 755 |
+
# In-memory caches for recently accepted hashes (to reduce SQLite queries/writes)
|
| 756 |
exact_cache = set()
|
| 757 |
normalized_cache = set()
|
| 758 |
pending_hashes = [] # list of (exact_hash, normalized_hash) to be inserted in batch
|
|
|
|
| 761 |
shard_number = int(state.get("shards_uploaded", 0))
|
| 762 |
last_progress = time.time()
|
| 763 |
|
| 764 |
+
# Rows seen since the last committed flush point (drives the
|
| 765 |
+
# "processed_committed" promotion in flush_shard_and_cache).
|
| 766 |
+
rows_since_commit = 0
|
| 767 |
+
|
| 768 |
def flush_hash_cache():
|
| 769 |
nonlocal pending_hashes
|
| 770 |
if not pending_hashes:
|
|
|
|
| 778 |
exact_cache.clear()
|
| 779 |
normalized_cache.clear()
|
| 780 |
|
|
|
|
| 781 |
def flush_shard_and_cache():
|
| 782 |
+
"""Upload whatever records are buffered, flush the hash
|
| 783 |
+
cache, and ONLY THEN advance processed_committed to the
|
| 784 |
+
current live 'processed' count. This is fix #3: state on
|
| 785 |
+
disk always reflects a point where every accepted record up
|
| 786 |
+
to it has actually been uploaded, so a crash between flushes
|
| 787 |
+
can only cause re-processing of rows already seen (safe,
|
| 788 |
+
just re-does some work) rather than silently losing accepted
|
| 789 |
+
records (unsafe, data loss)."""
|
| 790 |
+
nonlocal records, shard_number, rows_since_commit
|
| 791 |
+
if records:
|
| 792 |
+
upload_worker_shard(cfg, task_id, shard_number, records)
|
| 793 |
+
shard_number += 1
|
| 794 |
+
state["shards_uploaded"] = shard_number
|
| 795 |
+
records = []
|
| 796 |
flush_hash_cache()
|
| 797 |
+
state["processed_committed"] = state["processed"]
|
| 798 |
+
rows_since_commit = 0
|
| 799 |
save_task_state(dataset_name, task_id, state)
|
| 800 |
|
| 801 |
try:
|
| 802 |
for row in ds:
|
| 803 |
state["processed"] += 1
|
| 804 |
+
rows_since_commit += 1
|
| 805 |
|
| 806 |
try:
|
| 807 |
extracted = extract_record(row, cfg)
|
|
|
|
| 847 |
state["other_reject"] += 1
|
| 848 |
continue
|
| 849 |
|
| 850 |
+
# Check duplicates: first in-memory cache, then SQLite
|
| 851 |
if ehash in exact_cache or nhash in normalized_cache:
|
| 852 |
+
state["duplicate_exact"] += 1
|
| 853 |
continue
|
| 854 |
|
|
|
|
| 855 |
duplicate = conn.execute(
|
| 856 |
"SELECT exact_hash, normalized_hash FROM fingerprints WHERE exact_hash = ? OR normalized_hash = ? LIMIT 1",
|
| 857 |
(ehash, nhash)
|
|
|
|
| 890 |
"ast_acceptance_rule": "ANY",
|
| 891 |
}
|
| 892 |
|
|
|
|
| 893 |
exact_cache.add(ehash)
|
| 894 |
normalized_cache.add(nhash)
|
| 895 |
pending_hashes.append((ehash, nhash))
|
|
|
|
| 898 |
state["bytes_accepted"] += len(text.encode("utf-8", errors="ignore"))
|
| 899 |
records.append(record)
|
| 900 |
|
| 901 |
+
# Flush shard when records reach SHARD_ROWS (now 500,000)
|
| 902 |
if len(records) >= SHARD_ROWS:
|
| 903 |
flush_shard_and_cache()
|
| 904 |
print(f"[{dataset_name}] T{task_id} processed={state['processed']:,} | accepted={state['accepted']:,} | syntax={state['syntax_error']:,} | shards={state['shards_uploaded']:,}")
|
| 905 |
|
| 906 |
+
# Periodic checkpoint. With CHECKPOINT_EVERY == SHARD_ROWS
|
| 907 |
+
# this coincides with the shard-flush cadence above in the
|
| 908 |
+
# common case; kept as a belt-and-braces check in case
|
| 909 |
+
# quality/dup rejects mean many rows pass between accepts.
|
| 910 |
if state["processed"] % CHECKPOINT_EVERY == 0:
|
| 911 |
+
flush_shard_and_cache()
|
|
|
|
|
|
|
|
|
|
| 912 |
|
| 913 |
# Live progress
|
| 914 |
now = time.time()
|
|
|
|
| 918 |
print(f"[{dataset_name}] T{task_id} processed={state['processed']:,} | accepted={state['accepted']:,} | syntax={state['syntax_error']:,} | rate={rate:.1f}/sec")
|
| 919 |
last_progress = now
|
| 920 |
|
| 921 |
+
# End of stream: flush whatever remains (partial shard is fine)
|
| 922 |
+
flush_shard_and_cache()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 923 |
|
| 924 |
conn.commit()
|
| 925 |
state["complete"] = True
|
|
|
|
| 952 |
print("\n" + "!" * 80)
|
| 953 |
print(f"[{dataset_name}] TASK {task_id} FAILED")
|
| 954 |
print(traceback.format_exc())
|
|
|
|
| 955 |
try:
|
| 956 |
+
# Best-effort: flush whatever is safely flushable. Note we
|
| 957 |
+
# deliberately do NOT try to flush `records` here if the
|
| 958 |
+
# failure happened mid-shard-write, since we don't know
|
| 959 |
+
# its integrity — better to let a resume re-process those
|
| 960 |
+
# rows than risk uploading a corrupt/partial shard.
|
| 961 |
if pending_hashes:
|
| 962 |
flush_hash_cache()
|
| 963 |
conn.commit()
|
|
|
|
| 984 |
def get_interpreters():
|
| 985 |
interpreters = {}
|
| 986 |
for version in PYTHON_VERSIONS:
|
|
|
|
| 987 |
result = subprocess.run(["uv", "python", "find", version], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 988 |
if result.returncode == 0:
|
| 989 |
path = result.stdout.strip().splitlines()[-1] if result.stdout else None
|
| 990 |
if path and Path(path).exists():
|
| 991 |
interpreters[version] = path
|
| 992 |
continue
|
|
|
|
| 993 |
major, minor = version.split(".")[0], version.split(".")[1]
|
| 994 |
check = subprocess.run(["which", f"python{major}.{minor}"], text=True, stdout=subprocess.PIPE)
|
| 995 |
if check.returncode == 0:
|
|
|
|
| 1010 |
pipeline_status["finished_tasks"] = 0
|
| 1011 |
|
| 1012 |
try:
|
|
|
|
| 1013 |
interpreters = get_interpreters()
|
| 1014 |
print("Python interpreters found:")
|
| 1015 |
for v, p in interpreters.items():
|
| 1016 |
print(f" {v} -> {p}")
|
| 1017 |
|
|
|
|
| 1018 |
DATASET_TASKS = []
|
| 1019 |
for cfg in DATASETS:
|
| 1020 |
ds = load_stream(cfg)
|
|
|
|
| 1032 |
|
| 1033 |
print(f"Total scheduled task partitions: {len(DATASET_TASKS):,}")
|
| 1034 |
|
|
|
|
| 1035 |
results = {}
|
| 1036 |
task_cursor = 0
|
| 1037 |
active = {}
|
| 1038 |
with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
|
|
|
|
| 1039 |
while len(active) < MAX_WORKERS and task_cursor < len(DATASET_TASKS):
|
| 1040 |
task = DATASET_TASKS[task_cursor]
|
| 1041 |
task_cursor += 1
|
|
|
|
| 1043 |
active[future] = task
|
| 1044 |
print(f"[SCHEDULER] STARTED {task['cfg']['name']} T{task['task_id']}")
|
| 1045 |
|
|
|
|
| 1046 |
while active:
|
| 1047 |
for completed_future in as_completed(active.keys()):
|
| 1048 |
task = active.pop(completed_future)
|
|
|
|
| 1055 |
pipeline_status["finished_tasks"] += 1
|
| 1056 |
print(f"\n[SCHEDULER] FINISHED {task['cfg']['name']} T{task['task_id']} complete={result.get('complete', False)}")
|
| 1057 |
|
|
|
|
| 1058 |
if task_cursor < len(DATASET_TASKS):
|
| 1059 |
next_task = DATASET_TASKS[task_cursor]
|
| 1060 |
task_cursor += 1
|
| 1061 |
future = executor.submit(process_partition, next_task["cfg"], next_task["task_id"], next_task["total_tasks"], interpreters)
|
| 1062 |
active[future] = next_task
|
| 1063 |
print(f"[SCHEDULER] STARTED {next_task['cfg']['name']} T{next_task['task_id']}")
|
| 1064 |
+
break
|
| 1065 |
|
| 1066 |
# ============================================================
|
| 1067 |
# GLOBAL DEDUP (across all tasks/datasets)
|
|
|
|
| 1083 |
global_records = []
|
| 1084 |
global_shard_number = 0
|
| 1085 |
|
| 1086 |
+
pending_global_hashes = []
|
|
|
|
| 1087 |
BATCH_SIZE = 1000
|
| 1088 |
|
| 1089 |
def flush_global_hashes():
|
|
|
|
| 1115 |
global_records = []
|
| 1116 |
global_shard_number += 1
|
| 1117 |
|
|
|
|
| 1118 |
REMOTE_SHARDS = []
|
| 1119 |
for task in DATASET_TASKS:
|
| 1120 |
key = (task["cfg"]["name"], task["task_id"])
|
|
|
|
| 1127 |
|
| 1128 |
print(f"Remote worker shards: {len(REMOTE_SHARDS):,}")
|
| 1129 |
|
|
|
|
| 1130 |
for idx, (dataset_name, task_id, shard_number, remote_path) in enumerate(REMOTE_SHARDS, 1):
|
| 1131 |
print(f"\n[GLOBAL] {idx:,}/{len(REMOTE_SHARDS):,} {dataset_name} T{task_id} S{shard_number}")
|
| 1132 |
local_path = TMP_ROOT / "global" / dataset_name / f"task_{task_id}" / Path(remote_path).name
|
| 1133 |
+
|
| 1134 |
+
# FIX (#1 + #4): download via the real bucket-download path,
|
| 1135 |
+
# and if it fails, RAISE rather than silently `continue`.
|
| 1136 |
+
# A missing shard here means permanent, silent data loss in
|
| 1137 |
+
# the final master dataset if we just skip it — better to
|
| 1138 |
+
# stop the whole pipeline and surface the error clearly.
|
| 1139 |
+
download_bucket_file(remote_path, local_path, timeout=DOWNLOAD_TIMEOUT)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1140 |
|
| 1141 |
with gzip.open(local_path, "rb") as f:
|
| 1142 |
for line in f:
|
|
|
|
| 1160 |
global_stats["duplicate_normalized"] += 1
|
| 1161 |
continue
|
| 1162 |
|
|
|
|
| 1163 |
pending_global_hashes.append((ehash, nhash))
|
| 1164 |
global_records.append(record)
|
| 1165 |
global_stats["accepted_records"] += 1
|
| 1166 |
global_stats["bytes"] += int(record.get("char_count", 0))
|
| 1167 |
|
|
|
|
| 1168 |
if len(pending_global_hashes) >= BATCH_SIZE:
|
| 1169 |
flush_global_hashes()
|
| 1170 |
|
|
|
|
| 1171 |
if len(global_records) >= SHARD_ROWS:
|
| 1172 |
flush_global_records()
|
| 1173 |
|
|
|
|
| 1174 |
if pending_global_hashes:
|
| 1175 |
flush_global_hashes()
|
|
|
|
| 1176 |
if len(global_records) >= SHARD_ROWS:
|
| 1177 |
flush_global_records()
|
| 1178 |
|
|
|
|
| 1185 |
if idx % 10 == 0 or idx == len(REMOTE_SHARDS):
|
| 1186 |
print(f"[GLOBAL] input={global_stats['input_records']:,} | accepted={global_stats['accepted_records']:,} | exact_dup={global_stats['duplicate_exact']:,} | normalized_dup={global_stats['duplicate_normalized']:,}")
|
| 1187 |
|
|
|
|
| 1188 |
if pending_global_hashes:
|
| 1189 |
flush_global_hashes()
|
| 1190 |
flush_global_records()
|
| 1191 |
gconn.commit()
|
| 1192 |
gconn.close()
|
| 1193 |
|
|
|
|
| 1194 |
upload_file(GLOBAL_DB, f"{REMOTE_FINAL}/global_dedup.sqlite")
|
| 1195 |
|
|
|
|
| 1196 |
final_metadata = {
|
| 1197 |
"name": "Category 1 Python Master",
|
| 1198 |
"pipeline_version": "v4",
|
| 1199 |
"source_datasets": [cfg["dataset"] for cfg in DATASETS],
|
| 1200 |
"max_workers": MAX_WORKERS,
|
| 1201 |
+
"shard_rows": SHARD_ROWS,
|
| 1202 |
"python_ast_versions": PYTHON_VERSIONS,
|
| 1203 |
"ast_acceptance_rule": "ANY",
|
| 1204 |
"dedup": {"exact_sha256": True, "normalized_sha256": True, "ast_structure_as_key": False},
|
|
|
|
| 1211 |
json.dump(final_metadata, f, indent=2)
|
| 1212 |
upload_file(metadata_path, f"{REMOTE_FINAL}/dataset_metadata.json")
|
| 1213 |
|
|
|
|
| 1214 |
pipeline_status["stats"] = global_stats
|
| 1215 |
pipeline_status["stats"]["final_shards"] = global_shard_number
|
| 1216 |
pipeline_status["completed"] = True
|
|
|
|
| 1240 |
|
| 1241 |
@asynccontextmanager
|
| 1242 |
async def lifespan(app: FastAPI):
|
|
|
|
| 1243 |
thread = threading.Thread(target=run_pipeline, daemon=False)
|
| 1244 |
thread.start()
|
| 1245 |
yield
|
|
|
|
|
|
|
| 1246 |
if thread.is_alive():
|
| 1247 |
print("[LIFESPAN] Pipeline is still running, waiting up to 60 seconds for graceful exit...")
|
| 1248 |
thread.join(timeout=60)
|
|
|
|
| 1253 |
|
| 1254 |
@app.get("/health")
|
| 1255 |
async def health():
|
|
|
|
|
|
|
|
|
|
| 1256 |
return JSONResponse(content={
|
| 1257 |
"status": pipeline_status["current_stage"],
|
| 1258 |
"started": pipeline_status["started"],
|
|
|
|
| 1265 |
|
| 1266 |
@app.get("/status")
|
| 1267 |
async def status():
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1268 |
detailed = {}
|
| 1269 |
for dataset_dir in STATE_ROOT.iterdir():
|
| 1270 |
if dataset_dir.is_dir():
|