Spaces:
Sleeping

PERDYPTO commited on
Commit
10693a5
·
verified ·
1 Parent(s): 31263a5

Update hf_space.py

Browse files
Files changed (1) hide show
  1. hf_space.py +92 -189
hf_space.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import os
2
  import sqlite3
3
  import threading
@@ -23,24 +24,11 @@ except ImportError:
23
  DB_PATH = Path("github_pipeline.db")
24
  BUCKET = "PERDYPTO/db_snapshot"
25
 
26
- # --- RAM queue bounds -------------------------------------------------------
27
- # pending_ids is now a *bounded prefetch cache*, not the source of truth.
28
- # The DB (repo_ids table, status='pending') is always the source of truth.
29
- # This caps worst-case RAM usage for the queue regardless of how many rows
30
- # DuckDB discovers (27M+), since we never hold more than MAX_RAM_PENDING
31
- # job dicts in the process at once.
32
- # At ~384 bytes/item (measured), 500k items is ~185MB worst case — negligible
33
- # next to the DuckDB budget below, so this can be generous.
34
  MAX_RAM_PENDING = int(os.environ.get("MAX_RAM_PENDING", "500000"))
35
- # Once RAM drops below this, get-jobs will top it back up from the DB.
36
  RAM_REFILL_THRESHOLD = int(os.environ.get("RAM_REFILL_THRESHOLD", "100000"))
37
 
38
- # --- DuckDB memory bounds ----------------------------------------------------
39
- # Without an explicit limit, DuckDB will happily grow to consume all available
40
- # RAM while joining large remote parquet files, which can OOM-kill the whole
41
- # process (FastAPI + in-RAM queue included). Cap it well below total host RAM,
42
- # leaving headroom for the RAM queue, SQLite, and FastAPI/uvicorn itself.
43
- # On a 16GB Space: 5GB to DuckDB leaves ~11GB for everything else.
44
  DUCKDB_MEMORY_LIMIT = os.environ.get("DUCKDB_MEMORY_LIMIT", "5GB")
45
  DUCKDB_THREADS = os.environ.get("DUCKDB_THREADS", "2")
46
 
@@ -61,25 +49,41 @@ CREATE TABLE IF NOT EXISTS metadata (
61
  repo_id INTEGER PRIMARY KEY,
62
  full_name TEXT,
63
  description TEXT,
 
64
  stars INTEGER,
65
  forks_count INTEGER,
66
- open_issues INTEGER,
67
- license TEXT,
68
- archived INTEGER,
69
- created_at TEXT,
70
- updated_at TEXT,
71
- pushed_at TEXT,
72
- languages_json TEXT,
73
- python_bytes INTEGER,
74
- total_lang_bytes INTEGER,
75
- python_pct REAL,
76
- fetched_at TEXT
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  );
78
 
79
  CREATE INDEX IF NOT EXISTS idx_repo_ids_status ON repo_ids(status);
80
  """
81
 
82
- # Bounded prefetch cache: {"repo_id": int, "repo_path": str}
83
  pending_ids: List[Dict[str, Any]] = []
84
  processing_ids: set = set()
85
  ram_lock = asyncio.Lock()
@@ -87,31 +91,29 @@ db_lock = threading.Lock()
87
  db_conn = None
88
  last_db_changes = 0
89
 
90
-
91
  def now() -> str:
92
  return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
93
 
94
-
95
  def download_db_from_bucket():
96
  global DB_PATH
97
  if not os.environ.get("HF_TOKEN"):
98
  print("No HF_TOKEN, starting fresh DB")
99
  return True
100
-
101
  login(token=os.environ.get("HF_TOKEN"), add_to_git_credential=False)
102
-
103
  for attempt in range(5):
104
  try:
105
  remote_name = "github_pipeline.db"
106
  existing = {item.path for item in list_bucket_tree(BUCKET) if item.type == "file"}
107
-
108
  if remote_name in existing:
109
  print(f"Attempt {attempt+1}: Downloading DB from bucket {BUCKET}...")
110
  if DB_PATH.exists():
111
  DB_PATH.unlink()
112
-
113
  download_bucket_files(BUCKET, files=[(remote_name, str(DB_PATH))])
114
-
115
  if DB_PATH.exists() and DB_PATH.stat().st_size > 0:
116
  print("✅ Download complete and verified.")
117
  return True
@@ -120,21 +122,19 @@ def download_db_from_bucket():
120
  else:
121
  print("DB not found in bucket. Starting fresh.")
122
  return True
123
-
124
  except Exception as e:
125
  print(f"❌ Download failed: {e}. Retrying in 10 seconds...")
126
  time.sleep(10)
127
-
128
  raise RuntimeError("CRITICAL: Failed to download DB after 5 attempts. Halting to prevent data overwrite.")
129
 
130
-
131
  def init_db():
132
  conn = sqlite3.connect(str(DB_PATH), check_same_thread=False, timeout=60)
133
  conn.row_factory = sqlite3.Row
134
  conn.executescript(SCHEMA)
135
  return conn
136
 
137
-
138
  def upload_db_to_bucket():
139
  print("[Checkpoint] Uploading DB to HF Bucket...")
140
  try:
@@ -155,7 +155,6 @@ def upload_db_to_bucket():
155
  except Exception as e:
156
  print(f"[Checkpoint] Upload FAILED: {e}")
157
 
158
-
159
  async def background_uploader():
160
  global last_db_changes
161
  while True:
@@ -169,24 +168,15 @@ async def background_uploader():
169
  else:
170
  print("[Checkpoint] No changes detected. Skipping.")
171
 
172
-
173
  async def stuck_job_recoverer():
174
- """Background task to put jobs back in pending if they've been processing > 15 minutes.
175
-
176
- This only ever touches the DB. The RAM cache will naturally pick these up
177
- next time it refills from the DB, so there's no need (and no attempt) to
178
- push them directly into pending_ids here.
179
- """
180
  while True:
181
- await asyncio.sleep(300) # Check every 5 minutes
182
  threshold = (datetime.utcnow() - timedelta(minutes=15)).strftime("%Y-%m-%dT%H:%M:%SZ")
183
-
184
  with db_lock:
185
  stuck_rows = db_conn.execute(
186
  "SELECT repo_id FROM repo_ids WHERE status='in_progress' AND updated_at < ?",
187
  (threshold,)
188
  ).fetchall()
189
-
190
  if stuck_rows:
191
  ts_now = now()
192
  stuck_ids = [r["repo_id"] for r in stuck_rows]
@@ -197,75 +187,49 @@ async def stuck_job_recoverer():
197
  db_conn.commit()
198
  else:
199
  stuck_ids = []
200
-
201
  if stuck_ids:
202
  async with ram_lock:
203
  processing_ids.difference_update(stuck_ids)
204
  print(f"[Recovery] Recovered {len(stuck_ids)} stuck jobs back to pending in DB.")
205
 
206
-
207
  def run_duckdb_ingest_sync():
208
- """Runs the DuckDB remote join starting from the Python content folder.
209
-
210
- IMPORTANT: this function only writes to the SQLite DB. It never touches
211
- the in-RAM pending_ids cache directly. That decoupling is what keeps this
212
- safe to run against a 27M+ row remote join without risking the RAM queue
213
- growing unbounded or the process getting OOM-killed mid-ingest.
214
- """
215
  if duckdb is None or HfFileSystem is None:
216
  print("[Ingest] DuckDB or HfFileSystem not installed. Ingestion disabled.")
217
  return
218
 
219
- print(f"[Ingest] Starting DuckDB remote join (memory_limit={DUCKDB_MEMORY_LIMIT}, "
220
- f"threads={DUCKDB_THREADS})...")
221
  try:
222
  fs = HfFileSystem()
223
  con = duckdb.connect()
224
  con.register_filesystem(fs)
225
-
226
- # Cap DuckDB's own resource usage so this join can never consume all
227
- # available host RAM out from under the FastAPI process.
228
  con.execute(f"SET memory_limit='{DUCKDB_MEMORY_LIMIT}'")
229
  con.execute(f"SET threads={DUCKDB_THREADS}")
230
- # Spill to disk instead of erroring/ballooning RAM if the join needs
231
- # more working memory than the limit allows.
232
  con.execute("SET temp_directory='duckdb_spill'")
233
-
234
  query = """
235
  WITH python_repo_ids AS (
236
  SELECT DISTINCT UNNEST(repo_ids) AS repo_id
237
  FROM 'hf://buckets/HuggingFaceCode/stack-v3-full/contents/language=Python/*.parquet'
238
  )
239
- SELECT
240
- m.repo_id,
241
- m.repo_path,
242
- m.num_files
243
  FROM python_repo_ids AS p
244
  INNER JOIN 'hf://buckets/HuggingFaceCode/stack-v3-full/metadata/*.parquet' AS m
245
  ON p.repo_id = m.repo_id
246
  """
247
-
248
  cur = con.execute(query)
249
  first_print = False
250
  batch_size = 10000
251
  total_inserted = 0
252
-
253
  while True:
254
  rows = cur.fetchmany(batch_size)
255
  if not rows:
256
  break
257
-
258
  if not first_print:
259
  print(f"✅ FIRST CORRELATION FOUND: repo_id={rows[0][0]}, repo_path={rows[0][1]}, num_files={rows[0][2]}")
260
  first_print = True
261
-
262
- # INSERT OR IGNORE already no-ops on any repo_id that exists in
263
- # any status (it's the primary key), so there's no need for a
264
- # separate SELECT ... WHERE repo_id IN (...) pre-check here. That
265
- # pre-check used to build one placeholder per row, which is the
266
- # same fragile pattern that broke refill_pending_from_db at scale
267
- # — removing it avoids relying on SQLite's bound-variable limit
268
- # entirely rather than just staying under it.
269
  with db_lock:
270
  changes_before = db_conn.total_changes
271
  db_conn.executemany(
@@ -273,49 +237,20 @@ def run_duckdb_ingest_sync():
273
  [(r[0], r[1], r[2], now()) for r in rows]
274
  )
275
  db_conn.commit()
276
- # total_changes delta = rows actually inserted (INSERT OR
277
- # IGNORE doesn't count no-op'd duplicates as a change).
278
  total_inserted += db_conn.total_changes - changes_before
279
-
280
- # rows go out of scope and get GC'd each loop iteration;
281
- # nothing here accumulates across batches.
282
  if total_inserted and total_inserted % 100000 < batch_size:
283
  print(f"[Ingest] {total_inserted} new pending rows inserted so far...")
284
-
285
  print(f"[Ingest] DuckDB remote join completed successfully. Total new rows: {total_inserted}")
286
-
287
  except Exception as e:
288
  print(f"[Ingest] DuckDB query failed: {e}")
289
 
290
-
291
  async def refill_pending_from_db(target_size: int = MAX_RAM_PENDING):
292
- """Top up the in-RAM pending cache from the DB, up to target_size.
293
-
294
- Caller must already hold ram_lock. This is the ONLY place that grows
295
- pending_ids, and it always caps growth at target_size - len(pending_ids),
296
- so the list can never exceed MAX_RAM_PENDING regardless of how many rows
297
- exist in the DB.
298
-
299
- IMPORTANT: this claims rows via a single UPDATE ... WHERE repo_id IN
300
- (SELECT ...) statement rather than building one '?' placeholder per row.
301
- SQLite has a hard cap on bound parameters per statement (SQLITE_MAX_
302
- VARIABLE_NUMBER — 999 on older builds, up to ~32766 on newer ones), so
303
- binding one placeholder per row breaks as soon as `need` exceeds that
304
- cap. A subquery-based UPDATE has a fixed, small number of placeholders
305
- no matter how many rows it touches, so this is safe at any MAX_RAM_
306
- PENDING size.
307
- """
308
  global pending_ids
309
  need = target_size - len(pending_ids)
310
  if need <= 0:
311
  return 0
312
-
313
  ts = now()
314
  with db_lock:
315
- # Claim up to `need` pending rows in one statement: select their
316
- # rowids via a subquery, flip them to in_progress, and return the
317
- # claimed repo_id/repo_path via RETURNING — no per-row placeholders
318
- # anywhere, so this scales to any batch size SQLite's LIMIT allows.
319
  rows = db_conn.execute(
320
  """
321
  UPDATE repo_ids
@@ -328,170 +263,139 @@ async def refill_pending_from_db(target_size: int = MAX_RAM_PENDING):
328
  (ts, need)
329
  ).fetchall()
330
  db_conn.commit()
331
-
332
  if not rows:
333
  return 0
334
-
335
  new_jobs = [{"repo_id": r["repo_id"], "repo_path": r["repo_path"]} for r in rows]
336
  pending_ids.extend(new_jobs)
337
  processing_ids.update(j["repo_id"] for j in new_jobs)
338
  return len(new_jobs)
339
 
340
-
341
  @asynccontextmanager
342
  async def lifespan(app: FastAPI):
343
  global db_conn, pending_ids, processing_ids, last_db_changes
344
-
345
- # 1. Download DB FIRST (Retries internally)
346
  download_db_from_bucket()
347
-
348
- # 2. Initialize DB connection SECOND
349
  db_conn = init_db()
350
-
351
  with db_lock:
352
  print("Resetting in_progress -> pending...")
353
  db_conn.execute("UPDATE repo_ids SET status='pending' WHERE status='in_progress'")
354
  db_conn.commit()
355
  last_db_changes = db_conn.total_changes
356
-
357
  print(f"Priming RAM cache with up to {MAX_RAM_PENDING} pending IDs (DB remains source of truth)...")
358
  async with ram_lock:
359
  pending_ids = []
360
  processing_ids = set()
361
  loaded = await refill_pending_from_db(MAX_RAM_PENDING)
362
  print(f"Loaded {loaded} pending IDs into RAM cache.")
363
-
364
- # Run DuckDB ingestion in a separate thread so it doesn't block FastAPI.
365
- # It writes only to the DB (see run_duckdb_ingest_sync docstring), so it
366
- # cannot inflate the RAM queue no matter how many rows it discovers.
367
  asyncio.create_task(asyncio.to_thread(run_duckdb_ingest_sync))
368
-
369
- # Start background uploader
370
  asyncio.create_task(background_uploader())
371
- # Start stuck job recoverer
372
  asyncio.create_task(stuck_job_recoverer())
373
  yield
374
 
375
-
376
  app = FastAPI(lifespan=lifespan)
377
 
378
-
379
  @app.get("/stats")
380
  async def get_stats():
381
- """Real-time stats endpoint."""
382
  async with ram_lock:
383
  ram_pending = len(pending_ids)
384
  ram_processing = len(processing_ids)
385
-
386
  with db_lock:
387
  statuses = db_conn.execute("SELECT status, COUNT(*) as count FROM repo_ids GROUP BY status").fetchall()
388
  metadata_count = db_conn.execute("SELECT COUNT(*) as c FROM metadata").fetchone()["c"]
389
-
390
- status_dict = {row["status"]: row["count"] for row in statuses}
391
-
392
  return {
393
- "ram_queue": {
394
- "pending_ids": ram_pending,
395
- "processing_ids": ram_processing,
396
- "max_ram_pending": MAX_RAM_PENDING
397
- },
398
- "database": {
399
- "repo_ids": status_dict,
400
- "metadata_rows": metadata_count
401
- }
402
  }
403
 
404
-
405
  @app.get("/get-jobs")
406
  async def get_jobs():
407
  async with ram_lock:
408
- # Top up from DB first if we're running low, so a single big ask
409
- # doesn't drain the cache to zero and leave the next caller waiting
410
- # on a synchronous DB read under lock.
411
- #
412
- # RAM_REFILL_THRESHOLD should be set >= your typical per-call batch
413
- # size (10000 here), otherwise the cache can bleed down over several
414
- # calls without ever crossing the threshold and triggering a refill
415
- # (e.g. 50000 -> 40000 -> 30000 all stay above a 10000 threshold).
416
- # Default threshold is set well above 10000 for exactly this reason.
417
  if len(pending_ids) < RAM_REFILL_THRESHOLD:
418
  await refill_pending_from_db(MAX_RAM_PENDING)
419
-
420
  if not pending_ids:
421
  return {"jobs": []}
422
-
423
  batch_size = min(10000, len(pending_ids))
424
  batch = pending_ids[-batch_size:]
425
  del pending_ids[-batch_size:]
426
-
427
- # Jobs served from the RAM cache were already marked in_progress in
428
- # the DB at refill time, so no DB write is needed here — this keeps
429
- # get-jobs fast even under heavy concurrent polling.
430
  return {"jobs": batch}
431
 
432
-
433
  class WorkPayload(BaseModel):
434
  metadata: List[Dict[str, Any]] = []
435
  errors: List[Dict[str, Any]] = []
436
 
437
-
438
  @app.get("/reset-errors")
439
  async def reset_errors():
440
- """Moves all error jobs back to pending in the DB.
441
-
442
- Does NOT bulk-load them into RAM (that would reintroduce the unbounded
443
- growth this refactor removes) — the next /get-jobs refill will pick them
444
- up naturally, capped at MAX_RAM_PENDING as always.
445
- """
446
  with db_lock:
447
  error_count = db_conn.execute("SELECT COUNT(*) as c FROM repo_ids WHERE status='error'").fetchone()["c"]
448
  db_conn.execute("UPDATE repo_ids SET status='pending', last_error=NULL, updated_at=? WHERE status='error'", (now(),))
449
  db_conn.commit()
450
  total_pending_in_db = db_conn.execute("SELECT COUNT(*) as c FROM repo_ids WHERE status='pending'").fetchone()["c"]
 
451
 
452
- return {
453
- "status": "success",
454
- "reset_count": error_count,
455
- "total_pending_in_db": total_pending_in_db
456
- }
457
-
 
 
 
 
 
 
 
 
 
 
 
 
 
458
 
459
  @app.post("/post-work")
460
  async def post_work(payload: WorkPayload):
461
  processed_rids = set()
462
  ts = now()
463
-
464
  with db_lock:
465
- # Save Metadata
466
  for m in payload.metadata:
467
  rid = m["repo_id"]
468
  processed_rids.add(rid)
469
  db_conn.execute(
470
  """
471
  INSERT INTO metadata (
472
- repo_id, full_name, description, stars, forks_count, open_issues,
473
- license, archived, created_at, updated_at, pushed_at, languages_json,
474
- python_bytes, total_lang_bytes, python_pct, fetched_at
475
- ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
 
 
476
  ON CONFLICT(repo_id) DO UPDATE SET
477
- full_name=excluded.full_name, description=excluded.description, stars=excluded.stars,
478
- forks_count=excluded.forks_count, open_issues=excluded.open_issues, license=excluded.license,
479
- archived=excluded.archived, created_at=excluded.created_at, updated_at=excluded.updated_at,
480
- pushed_at=excluded.pushed_at, languages_json=excluded.languages_json,
 
 
 
 
481
  python_bytes=excluded.python_bytes, total_lang_bytes=excluded.total_lang_bytes,
482
  python_pct=excluded.python_pct, fetched_at=excluded.fetched_at
483
  """,
484
  (
485
- rid, m.get("full_name"), m.get("description"), m.get("stars"),
486
- m.get("forks_count"), m.get("open_issues"), m.get("license"),
487
- m.get("archived", 0), m.get("created_at"), m.get("updated_at"),
488
- m.get("pushed_at"), m.get("languages_json"), m.get("python_bytes"),
489
- m.get("total_lang_bytes"), m.get("python_pct"), ts
 
 
490
  )
491
  )
492
  db_conn.execute("UPDATE repo_ids SET status='done', last_error=NULL, updated_at=? WHERE repo_id=?", (ts, rid))
493
 
494
- # Save Errors
495
  for e in payload.errors:
496
  rid = e["repo_id"]
497
  processed_rids.add(rid)
@@ -499,7 +403,6 @@ async def post_work(payload: WorkPayload):
499
 
500
  db_conn.commit()
501
 
502
- # Remove from RAM processing set
503
  async with ram_lock:
504
  processing_ids.difference_update(processed_rids)
505
 
 
1
+ # hf_space.py
2
  import os
3
  import sqlite3
4
  import threading
 
24
  DB_PATH = Path("github_pipeline.db")
25
  BUCKET = "PERDYPTO/db_snapshot"
26
 
27
+ # --- RAM queue bounds ---
 
 
 
 
 
 
 
28
  MAX_RAM_PENDING = int(os.environ.get("MAX_RAM_PENDING", "500000"))
 
29
  RAM_REFILL_THRESHOLD = int(os.environ.get("RAM_REFILL_THRESHOLD", "100000"))
30
 
31
+ # --- DuckDB memory bounds ---
 
 
 
 
 
32
  DUCKDB_MEMORY_LIMIT = os.environ.get("DUCKDB_MEMORY_LIMIT", "5GB")
33
  DUCKDB_THREADS = os.environ.get("DUCKDB_THREADS", "2")
34
 
 
49
  repo_id INTEGER PRIMARY KEY,
50
  full_name TEXT,
51
  description TEXT,
52
+ homepage_url TEXT,
53
  stars INTEGER,
54
  forks_count INTEGER,
55
+ watchers_count INTEGER,
56
+ open_issues INTEGER,
57
+ license TEXT,
58
+ license_name TEXT,
59
+ archived INTEGER,
60
+ disabled INTEGER,
61
+ is_fork INTEGER,
62
+ is_private INTEGER,
63
+ is_template INTEGER,
64
+ disk_usage_kb INTEGER,
65
+ primary_language TEXT,
66
+ default_branch TEXT,
67
+ topics_json TEXT,
68
+ created_at TEXT,
69
+ updated_at TEXT,
70
+ pushed_at TEXT,
71
+ languages_json TEXT,
72
+ python_bytes INTEGER,
73
+ total_lang_bytes INTEGER,
74
+ python_pct REAL,
75
+ fetched_at TEXT
76
+ );
77
+
78
+ CREATE TABLE IF NOT EXISTS parquet_progress (
79
+ part INTEGER PRIMARY KEY,
80
+ status TEXT NOT NULL DEFAULT 'pending',
81
+ ingested_at TEXT
82
  );
83
 
84
  CREATE INDEX IF NOT EXISTS idx_repo_ids_status ON repo_ids(status);
85
  """
86
 
 
87
  pending_ids: List[Dict[str, Any]] = []
88
  processing_ids: set = set()
89
  ram_lock = asyncio.Lock()
 
91
  db_conn = None
92
  last_db_changes = 0
93
 
 
94
  def now() -> str:
95
  return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
96
 
 
97
  def download_db_from_bucket():
98
  global DB_PATH
99
  if not os.environ.get("HF_TOKEN"):
100
  print("No HF_TOKEN, starting fresh DB")
101
  return True
102
+
103
  login(token=os.environ.get("HF_TOKEN"), add_to_git_credential=False)
104
+
105
  for attempt in range(5):
106
  try:
107
  remote_name = "github_pipeline.db"
108
  existing = {item.path for item in list_bucket_tree(BUCKET) if item.type == "file"}
109
+
110
  if remote_name in existing:
111
  print(f"Attempt {attempt+1}: Downloading DB from bucket {BUCKET}...")
112
  if DB_PATH.exists():
113
  DB_PATH.unlink()
114
+
115
  download_bucket_files(BUCKET, files=[(remote_name, str(DB_PATH))])
116
+
117
  if DB_PATH.exists() and DB_PATH.stat().st_size > 0:
118
  print("✅ Download complete and verified.")
119
  return True
 
122
  else:
123
  print("DB not found in bucket. Starting fresh.")
124
  return True
125
+
126
  except Exception as e:
127
  print(f"❌ Download failed: {e}. Retrying in 10 seconds...")
128
  time.sleep(10)
129
+
130
  raise RuntimeError("CRITICAL: Failed to download DB after 5 attempts. Halting to prevent data overwrite.")
131
 
 
132
  def init_db():
133
  conn = sqlite3.connect(str(DB_PATH), check_same_thread=False, timeout=60)
134
  conn.row_factory = sqlite3.Row
135
  conn.executescript(SCHEMA)
136
  return conn
137
 
 
138
  def upload_db_to_bucket():
139
  print("[Checkpoint] Uploading DB to HF Bucket...")
140
  try:
 
155
  except Exception as e:
156
  print(f"[Checkpoint] Upload FAILED: {e}")
157
 
 
158
  async def background_uploader():
159
  global last_db_changes
160
  while True:
 
168
  else:
169
  print("[Checkpoint] No changes detected. Skipping.")
170
 
 
171
  async def stuck_job_recoverer():
 
 
 
 
 
 
172
  while True:
173
+ await asyncio.sleep(300)
174
  threshold = (datetime.utcnow() - timedelta(minutes=15)).strftime("%Y-%m-%dT%H:%M:%SZ")
 
175
  with db_lock:
176
  stuck_rows = db_conn.execute(
177
  "SELECT repo_id FROM repo_ids WHERE status='in_progress' AND updated_at < ?",
178
  (threshold,)
179
  ).fetchall()
 
180
  if stuck_rows:
181
  ts_now = now()
182
  stuck_ids = [r["repo_id"] for r in stuck_rows]
 
187
  db_conn.commit()
188
  else:
189
  stuck_ids = []
 
190
  if stuck_ids:
191
  async with ram_lock:
192
  processing_ids.difference_update(stuck_ids)
193
  print(f"[Recovery] Recovered {len(stuck_ids)} stuck jobs back to pending in DB.")
194
 
 
195
  def run_duckdb_ingest_sync():
 
 
 
 
 
 
 
196
  if duckdb is None or HfFileSystem is None:
197
  print("[Ingest] DuckDB or HfFileSystem not installed. Ingestion disabled.")
198
  return
199
 
200
+ print(f"[Ingest] Starting DuckDB remote join (memory_limit={DUCKDB_MEMORY_LIMIT}, threads={DUCKDB_THREADS})...")
 
201
  try:
202
  fs = HfFileSystem()
203
  con = duckdb.connect()
204
  con.register_filesystem(fs)
 
 
 
205
  con.execute(f"SET memory_limit='{DUCKDB_MEMORY_LIMIT}'")
206
  con.execute(f"SET threads={DUCKDB_THREADS}")
207
+ con.execute("SET preserve_insertion_order=false;")
 
208
  con.execute("SET temp_directory='duckdb_spill'")
209
+
210
  query = """
211
  WITH python_repo_ids AS (
212
  SELECT DISTINCT UNNEST(repo_ids) AS repo_id
213
  FROM 'hf://buckets/HuggingFaceCode/stack-v3-full/contents/language=Python/*.parquet'
214
  )
215
+ SELECT m.repo_id, m.repo_path, m.num_files
 
 
 
216
  FROM python_repo_ids AS p
217
  INNER JOIN 'hf://buckets/HuggingFaceCode/stack-v3-full/metadata/*.parquet' AS m
218
  ON p.repo_id = m.repo_id
219
  """
220
+
221
  cur = con.execute(query)
222
  first_print = False
223
  batch_size = 10000
224
  total_inserted = 0
225
+
226
  while True:
227
  rows = cur.fetchmany(batch_size)
228
  if not rows:
229
  break
 
230
  if not first_print:
231
  print(f"✅ FIRST CORRELATION FOUND: repo_id={rows[0][0]}, repo_path={rows[0][1]}, num_files={rows[0][2]}")
232
  first_print = True
 
 
 
 
 
 
 
 
233
  with db_lock:
234
  changes_before = db_conn.total_changes
235
  db_conn.executemany(
 
237
  [(r[0], r[1], r[2], now()) for r in rows]
238
  )
239
  db_conn.commit()
 
 
240
  total_inserted += db_conn.total_changes - changes_before
 
 
 
241
  if total_inserted and total_inserted % 100000 < batch_size:
242
  print(f"[Ingest] {total_inserted} new pending rows inserted so far...")
 
243
  print(f"[Ingest] DuckDB remote join completed successfully. Total new rows: {total_inserted}")
 
244
  except Exception as e:
245
  print(f"[Ingest] DuckDB query failed: {e}")
246
 
 
247
  async def refill_pending_from_db(target_size: int = MAX_RAM_PENDING):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  global pending_ids
249
  need = target_size - len(pending_ids)
250
  if need <= 0:
251
  return 0
 
252
  ts = now()
253
  with db_lock:
 
 
 
 
254
  rows = db_conn.execute(
255
  """
256
  UPDATE repo_ids
 
263
  (ts, need)
264
  ).fetchall()
265
  db_conn.commit()
 
266
  if not rows:
267
  return 0
 
268
  new_jobs = [{"repo_id": r["repo_id"], "repo_path": r["repo_path"]} for r in rows]
269
  pending_ids.extend(new_jobs)
270
  processing_ids.update(j["repo_id"] for j in new_jobs)
271
  return len(new_jobs)
272
 
 
273
  @asynccontextmanager
274
  async def lifespan(app: FastAPI):
275
  global db_conn, pending_ids, processing_ids, last_db_changes
276
+
 
277
  download_db_from_bucket()
 
 
278
  db_conn = init_db()
279
+
280
  with db_lock:
281
  print("Resetting in_progress -> pending...")
282
  db_conn.execute("UPDATE repo_ids SET status='pending' WHERE status='in_progress'")
283
  db_conn.commit()
284
  last_db_changes = db_conn.total_changes
285
+
286
  print(f"Priming RAM cache with up to {MAX_RAM_PENDING} pending IDs (DB remains source of truth)...")
287
  async with ram_lock:
288
  pending_ids = []
289
  processing_ids = set()
290
  loaded = await refill_pending_from_db(MAX_RAM_PENDING)
291
  print(f"Loaded {loaded} pending IDs into RAM cache.")
292
+
 
 
 
293
  asyncio.create_task(asyncio.to_thread(run_duckdb_ingest_sync))
 
 
294
  asyncio.create_task(background_uploader())
 
295
  asyncio.create_task(stuck_job_recoverer())
296
  yield
297
 
 
298
  app = FastAPI(lifespan=lifespan)
299
 
 
300
  @app.get("/stats")
301
  async def get_stats():
 
302
  async with ram_lock:
303
  ram_pending = len(pending_ids)
304
  ram_processing = len(processing_ids)
 
305
  with db_lock:
306
  statuses = db_conn.execute("SELECT status, COUNT(*) as count FROM repo_ids GROUP BY status").fetchall()
307
  metadata_count = db_conn.execute("SELECT COUNT(*) as c FROM metadata").fetchone()["c"]
 
 
 
308
  return {
309
+ "ram_queue": {"pending_ids": ram_pending, "processing_ids": ram_processing, "max_ram_pending": MAX_RAM_PENDING},
310
+ "database": {"repo_ids": {r["status"]: r["count"] for r in statuses}, "metadata_rows": metadata_count}
 
 
 
 
 
 
 
311
  }
312
 
 
313
  @app.get("/get-jobs")
314
  async def get_jobs():
315
  async with ram_lock:
 
 
 
 
 
 
 
 
 
316
  if len(pending_ids) < RAM_REFILL_THRESHOLD:
317
  await refill_pending_from_db(MAX_RAM_PENDING)
 
318
  if not pending_ids:
319
  return {"jobs": []}
 
320
  batch_size = min(10000, len(pending_ids))
321
  batch = pending_ids[-batch_size:]
322
  del pending_ids[-batch_size:]
 
 
 
 
323
  return {"jobs": batch}
324
 
 
325
  class WorkPayload(BaseModel):
326
  metadata: List[Dict[str, Any]] = []
327
  errors: List[Dict[str, Any]] = []
328
 
 
329
  @app.get("/reset-errors")
330
  async def reset_errors():
 
 
 
 
 
 
331
  with db_lock:
332
  error_count = db_conn.execute("SELECT COUNT(*) as c FROM repo_ids WHERE status='error'").fetchone()["c"]
333
  db_conn.execute("UPDATE repo_ids SET status='pending', last_error=NULL, updated_at=? WHERE status='error'", (now(),))
334
  db_conn.commit()
335
  total_pending_in_db = db_conn.execute("SELECT COUNT(*) as c FROM repo_ids WHERE status='pending'").fetchone()["c"]
336
+ return {"status": "success", "reset_count": error_count, "total_pending_in_db": total_pending_in_db}
337
 
338
+ @app.get("/reset-metadata")
339
+ async def reset_metadata():
340
+ """Drops the metadata table (removing old schema) and recreates it with new columns.
341
+ Resets ALL repo_ids back to pending so workers can re-scrape them with the new fields.
342
+ Does NOT trigger DuckDB to re-run.
343
+ """
344
+ with db_lock:
345
+ print("[RESET] Dropping metadata table and resetting all jobs to pending...")
346
+ db_conn.execute("DROP TABLE IF EXISTS metadata;")
347
+ db_conn.execute(SCHEMA) # Recreates metadata with new columns
348
+ db_conn.execute("UPDATE repo_ids SET status='pending', last_error=NULL, updated_at=?", (now(),))
349
+ db_conn.commit()
350
+
351
+ async with ram_lock:
352
+ pending_ids.clear()
353
+ processing_ids.clear()
354
+ loaded = await refill_pending_from_db(MAX_RAM_PENDING)
355
+
356
+ return {"status": "success", "message": "Metadata wiped and recreated. All jobs reset to pending.", "ram_loaded": loaded}
357
 
358
  @app.post("/post-work")
359
  async def post_work(payload: WorkPayload):
360
  processed_rids = set()
361
  ts = now()
 
362
  with db_lock:
 
363
  for m in payload.metadata:
364
  rid = m["repo_id"]
365
  processed_rids.add(rid)
366
  db_conn.execute(
367
  """
368
  INSERT INTO metadata (
369
+ repo_id, full_name, description, homepage_url, stars, forks_count,
370
+ watchers_count, open_issues, license, license_name, archived, disabled,
371
+ is_fork, is_private, is_template, disk_usage_kb, primary_language,
372
+ default_branch, topics_json, created_at, updated_at, pushed_at,
373
+ languages_json, python_bytes, total_lang_bytes, python_pct, fetched_at
374
+ ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
375
  ON CONFLICT(repo_id) DO UPDATE SET
376
+ full_name=excluded.full_name, description=excluded.description, homepage_url=excluded.homepage_url,
377
+ stars=excluded.stars, forks_count=excluded.forks_count, watchers_count=excluded.watchers_count,
378
+ open_issues=excluded.open_issues, license=excluded.license, license_name=excluded.license_name,
379
+ archived=excluded.archived, disabled=excluded.disabled, is_fork=excluded.is_fork,
380
+ is_private=excluded.is_private, is_template=excluded.is_template, disk_usage_kb=excluded.disk_usage_kb,
381
+ primary_language=excluded.primary_language, default_branch=excluded.default_branch,
382
+ topics_json=excluded.topics_json, created_at=excluded.created_at, updated_at=excluded.updated_at,
383
+ pushed_at=excluded.pushed_at, languages_json=excluded.languages_json,
384
  python_bytes=excluded.python_bytes, total_lang_bytes=excluded.total_lang_bytes,
385
  python_pct=excluded.python_pct, fetched_at=excluded.fetched_at
386
  """,
387
  (
388
+ rid, m.get("full_name"), m.get("description"), m.get("homepage_url"), m.get("stars"),
389
+ m.get("forks_count"), m.get("watchers_count"), m.get("open_issues", 0), m.get("license"),
390
+ m.get("license_name"), m.get("archived", 0), m.get("disabled", 0), m.get("is_fork", 0),
391
+ m.get("is_private", 0), m.get("is_template", 0), m.get("disk_usage_kb"), m.get("primary_language"),
392
+ m.get("default_branch"), m.get("topics_json"), m.get("created_at"), m.get("updated_at"),
393
+ m.get("pushed_at"), m.get("languages_json"), m.get("python_bytes"), m.get("total_lang_bytes"),
394
+ m.get("python_pct"), ts
395
  )
396
  )
397
  db_conn.execute("UPDATE repo_ids SET status='done', last_error=NULL, updated_at=? WHERE repo_id=?", (ts, rid))
398
 
 
399
  for e in payload.errors:
400
  rid = e["repo_id"]
401
  processed_rids.add(rid)
 
403
 
404
  db_conn.commit()
405
 
 
406
  async with ram_lock:
407
  processing_ids.difference_update(processed_rids)
408