PERDYPTO commited on
Update projects/dataset_verification/router.py
Browse files
projects/dataset_verification/router.py
CHANGED
|
@@ -12,9 +12,6 @@ from fastapi import APIRouter, Body, Depends, HTTPException, Query
|
|
| 12 |
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
| 13 |
from pydantic import BaseModel, Field
|
| 14 |
|
| 15 |
-
# ---------------------------------------------------------------------------
|
| 16 |
-
# Utilities
|
| 17 |
-
# ---------------------------------------------------------------------------
|
| 18 |
|
| 19 |
def _now() -> float:
|
| 20 |
return time.time()
|
|
@@ -29,9 +26,6 @@ def iso_from_ts(ts: float) -> str:
|
|
| 29 |
def generate_job_id() -> str:
|
| 30 |
return "job_" + secrets.token_hex(6)
|
| 31 |
|
| 32 |
-
# ---------------------------------------------------------------------------
|
| 33 |
-
# Settings
|
| 34 |
-
# ---------------------------------------------------------------------------
|
| 35 |
|
| 36 |
@dataclass
|
| 37 |
class Settings:
|
|
@@ -42,29 +36,31 @@ class Settings:
|
|
| 42 |
max_retries: int = int(os.getenv("MAX_RETRIES", "3"))
|
| 43 |
retention_seconds: float = float(os.getenv("RESULT_RETENTION_SECONDS", "3600"))
|
| 44 |
|
| 45 |
-
# ---------------------------------------------------------------------------
|
| 46 |
-
# Pydantic Models
|
| 47 |
-
# ---------------------------------------------------------------------------
|
| 48 |
|
| 49 |
class Environment(BaseModel):
|
| 50 |
platform: str
|
| 51 |
os_version: str
|
| 52 |
python_versions: List[str]
|
| 53 |
-
max_concurrent_jobs: int = 20
|
| 54 |
notes: Optional[str] = None
|
| 55 |
|
|
|
|
| 56 |
class WorkerRegisterRequest(BaseModel):
|
| 57 |
worker_id: int
|
| 58 |
url: str
|
| 59 |
environment: Environment
|
| 60 |
|
|
|
|
| 61 |
class PollRequest(BaseModel):
|
| 62 |
worker_id: int
|
|
|
|
|
|
|
| 63 |
|
| 64 |
class DoneRequest(BaseModel):
|
| 65 |
worker_id: int
|
| 66 |
url: str
|
| 67 |
|
|
|
|
| 68 |
class JobSubmission(BaseModel):
|
| 69 |
job_id: Optional[str] = None
|
| 70 |
python_version: str
|
|
@@ -76,15 +72,13 @@ class JobSubmission(BaseModel):
|
|
| 76 |
stdin: Optional[str] = None
|
| 77 |
timeout: float
|
| 78 |
|
|
|
|
| 79 |
Category = Literal[
|
| 80 |
-
"success",
|
| 81 |
-
"
|
| 82 |
-
"dependency_install_failed",
|
| 83 |
-
"infra_failure",
|
| 84 |
-
"checker_error",
|
| 85 |
-
"not_applicable",
|
| 86 |
]
|
| 87 |
|
|
|
|
| 88 |
class ResultObject(BaseModel):
|
| 89 |
job_id: str
|
| 90 |
stdout: str
|
|
@@ -95,9 +89,6 @@ class ResultObject(BaseModel):
|
|
| 95 |
failure_reason: Optional[str] = None
|
| 96 |
network_activity_detected: Optional[bool] = None
|
| 97 |
|
| 98 |
-
# ---------------------------------------------------------------------------
|
| 99 |
-
# Memory Store
|
| 100 |
-
# ---------------------------------------------------------------------------
|
| 101 |
|
| 102 |
class MemoryStore:
|
| 103 |
def __init__(self, settings: Settings, clock: Callable[[], float] = _now):
|
|
@@ -110,11 +101,11 @@ class MemoryStore:
|
|
| 110 |
self.total_submitted = 0
|
| 111 |
self.total_completed = 0
|
| 112 |
|
| 113 |
-
# --- Registration ------------------------------------------------------
|
| 114 |
def register_worker(self, worker_id: int, url: str, environment: dict) -> dict:
|
| 115 |
with self.lock:
|
| 116 |
now = self.clock()
|
| 117 |
worker = self.workers.get(worker_id)
|
|
|
|
| 118 |
if worker is None:
|
| 119 |
worker = {
|
| 120 |
"worker_id": worker_id,
|
|
@@ -126,21 +117,32 @@ class MemoryStore:
|
|
| 126 |
}
|
| 127 |
self.workers[worker_id] = worker
|
| 128 |
else:
|
|
|
|
|
|
|
| 129 |
worker["url"] = url
|
| 130 |
worker["environment"] = environment
|
| 131 |
worker["last_seen_at"] = now
|
| 132 |
worker["registered_at"] = now
|
| 133 |
worker["reported_done"] = False
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
return self._worker_public_locked(worker_id, now)
|
| 135 |
|
| 136 |
-
|
| 137 |
-
def poll_job(self, worker_id: int):
|
| 138 |
with self.lock:
|
| 139 |
worker = self.workers.get(worker_id)
|
| 140 |
if worker is None:
|
| 141 |
raise KeyError("worker not registered")
|
| 142 |
|
| 143 |
now = self.clock()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
worker["last_seen_at"] = now
|
| 145 |
|
| 146 |
if worker.get("reported_done") or (now - worker["last_seen_at"]) > self.settings.liveness_window:
|
|
@@ -176,13 +178,10 @@ class MemoryStore:
|
|
| 176 |
job["claimed_by"] = worker_id
|
| 177 |
job["claimed_worker_url"] = worker["url"]
|
| 178 |
job["claimed_at"] = now
|
| 179 |
-
job["claim_deadline"] =
|
| 180 |
-
now + job["timeout"] + self.settings.claim_timeout_buffer
|
| 181 |
-
)
|
| 182 |
|
| 183 |
return self._public_job(job)
|
| 184 |
|
| 185 |
-
# --- Result reporting ---------------------------------------------------
|
| 186 |
def report_result(self, worker_id: int, url: str, result: ResultObject) -> None:
|
| 187 |
with self.lock:
|
| 188 |
job = self.jobs.get(result.job_id)
|
|
@@ -203,10 +202,9 @@ class MemoryStore:
|
|
| 203 |
self.total_completed += 1
|
| 204 |
|
| 205 |
worker = self.workers.get(worker_id)
|
| 206 |
-
if worker is not None:
|
| 207 |
worker["last_seen_at"] = now
|
| 208 |
|
| 209 |
-
# --- Graceful shutdown --------------------------------------------------
|
| 210 |
def report_done(self, worker_id: int, url: str) -> List[str]:
|
| 211 |
with self.lock:
|
| 212 |
worker = self.workers.get(worker_id)
|
|
@@ -226,13 +224,11 @@ class MemoryStore:
|
|
| 226 |
released.append(job["job_id"])
|
| 227 |
return released
|
| 228 |
|
| 229 |
-
# --- Job submission -----------------------------------------------------
|
| 230 |
def submit_job(self, job_data: JobSubmission) -> str:
|
| 231 |
with self.lock:
|
| 232 |
job_id = job_data.job_id or generate_job_id()
|
| 233 |
if job_id in self.jobs:
|
| 234 |
raise ValueError("job_id already exists")
|
| 235 |
-
|
| 236 |
now = self.clock()
|
| 237 |
self.jobs[job_id] = {
|
| 238 |
"job_id": job_id,
|
|
@@ -258,7 +254,6 @@ class MemoryStore:
|
|
| 258 |
self.total_submitted += 1
|
| 259 |
return job_id
|
| 260 |
|
| 261 |
-
# --- Query methods ------------------------------------------------------
|
| 262 |
def get_job(self, job_id: str):
|
| 263 |
with self.lock:
|
| 264 |
job = self.jobs.get(job_id)
|
|
@@ -307,14 +302,12 @@ class MemoryStore:
|
|
| 307 |
queued = sum(1 for j in self.jobs.values() if j["status"] == "queued")
|
| 308 |
claimed = sum(1 for j in self.jobs.values() if j["status"] == "claimed")
|
| 309 |
complete = sum(1 for j in self.jobs.values() if j["status"] == "complete")
|
| 310 |
-
|
| 311 |
claimed_by_worker = {}
|
| 312 |
for j in self.jobs.values():
|
| 313 |
if j["status"] == "claimed":
|
| 314 |
wid = j.get("claimed_by")
|
| 315 |
if wid is not None:
|
| 316 |
claimed_by_worker[wid] = claimed_by_worker.get(wid, 0) + 1
|
| 317 |
-
|
| 318 |
workers = []
|
| 319 |
for wid, w in self.workers.items():
|
| 320 |
workers.append({
|
|
@@ -327,26 +320,20 @@ class MemoryStore:
|
|
| 327 |
"last_seen_at": iso_from_ts(w["last_seen_at"]),
|
| 328 |
"registered_at": iso_from_ts(w["registered_at"]),
|
| 329 |
})
|
| 330 |
-
|
| 331 |
return {
|
| 332 |
"uptime_seconds": now - self.start_time,
|
| 333 |
"total_submitted": self.total_submitted,
|
| 334 |
"total_completed": self.total_completed,
|
| 335 |
-
"jobs_by_status": {
|
| 336 |
-
"queued": queued,
|
| 337 |
-
"claimed": claimed,
|
| 338 |
-
"complete": complete,
|
| 339 |
-
},
|
| 340 |
"workers": workers,
|
| 341 |
"claimed_by_worker": claimed_by_worker,
|
| 342 |
}
|
| 343 |
|
| 344 |
-
# --- Background tasks ---------------------------------------------------
|
| 345 |
def process_expired_claims(self) -> None:
|
| 346 |
with self.lock:
|
| 347 |
now = self.clock()
|
| 348 |
for job in list(self.jobs.values()):
|
| 349 |
-
if
|
| 350 |
self._abandon_claim_locked(job, "claim timeout", now)
|
| 351 |
|
| 352 |
def cleanup_completed(self) -> None:
|
|
@@ -354,10 +341,9 @@ class MemoryStore:
|
|
| 354 |
now = self.clock()
|
| 355 |
for job_id in list(self.jobs):
|
| 356 |
job = self.jobs[job_id]
|
| 357 |
-
if
|
| 358 |
del self.jobs[job_id]
|
| 359 |
|
| 360 |
-
# --- Internal helpers ----------------------------------------------------
|
| 361 |
def _abandon_claim_locked(self, job: dict, reason: str, now: float) -> None:
|
| 362 |
if job.get("retry_count", 0) >= self.settings.max_retries:
|
| 363 |
job["status"] = "complete"
|
|
@@ -431,10 +417,8 @@ class MemoryStore:
|
|
| 431 |
"timeout": job["timeout"],
|
| 432 |
}
|
| 433 |
|
| 434 |
-
# ---------------------------------------------------------------------------
|
| 435 |
-
# Global store and background loop
|
| 436 |
-
# ---------------------------------------------------------------------------
|
| 437 |
|
|
|
|
| 438 |
settings = Settings()
|
| 439 |
store = MemoryStore(settings)
|
| 440 |
|
|
@@ -446,10 +430,7 @@ def _background_loop():
|
|
| 446 |
|
| 447 |
threading.Thread(target=_background_loop, daemon=True).start()
|
| 448 |
|
| 449 |
-
# ---------------------------------------------------------------------------
|
| 450 |
# APIRouter
|
| 451 |
-
# ---------------------------------------------------------------------------
|
| 452 |
-
|
| 453 |
router = APIRouter()
|
| 454 |
security = HTTPBearer(auto_error=False)
|
| 455 |
|
|
@@ -465,7 +446,6 @@ def desktop_auth(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
|
| 465 |
or not secrets.compare_digest(credentials.credentials.encode(), expected.encode())):
|
| 466 |
raise HTTPException(status_code=401, detail="Unauthorized")
|
| 467 |
|
| 468 |
-
# Worker endpoints
|
| 469 |
@router.post("/worker/register", dependencies=[Depends(worker_auth)])
|
| 470 |
def worker_register(body: WorkerRegisterRequest):
|
| 471 |
return store.register_worker(body.worker_id, body.url, body.environment.model_dump())
|
|
@@ -473,8 +453,8 @@ def worker_register(body: WorkerRegisterRequest):
|
|
| 473 |
@router.post("/worker/poll", dependencies=[Depends(worker_auth)])
|
| 474 |
def worker_poll(body: PollRequest):
|
| 475 |
try:
|
| 476 |
-
|
| 477 |
-
return {"job":
|
| 478 |
except KeyError:
|
| 479 |
raise HTTPException(status_code=404, detail="Worker not registered")
|
| 480 |
|
|
@@ -497,7 +477,6 @@ def worker_done(body: DoneRequest):
|
|
| 497 |
released = store.report_done(body.worker_id, body.url)
|
| 498 |
return {"released_job_ids": released}
|
| 499 |
|
| 500 |
-
# Desktop endpoints
|
| 501 |
@router.post("/desktop/job", dependencies=[Depends(desktop_auth)])
|
| 502 |
def desktop_submit_job(body: JobSubmission):
|
| 503 |
try:
|
|
|
|
| 12 |
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
| 13 |
from pydantic import BaseModel, Field
|
| 14 |
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
def _now() -> float:
|
| 17 |
return time.time()
|
|
|
|
| 26 |
def generate_job_id() -> str:
|
| 27 |
return "job_" + secrets.token_hex(6)
|
| 28 |
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
@dataclass
|
| 31 |
class Settings:
|
|
|
|
| 36 |
max_retries: int = int(os.getenv("MAX_RETRIES", "3"))
|
| 37 |
retention_seconds: float = float(os.getenv("RESULT_RETENTION_SECONDS", "3600"))
|
| 38 |
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
class Environment(BaseModel):
|
| 41 |
platform: str
|
| 42 |
os_version: str
|
| 43 |
python_versions: List[str]
|
| 44 |
+
max_concurrent_jobs: int = 20
|
| 45 |
notes: Optional[str] = None
|
| 46 |
|
| 47 |
+
|
| 48 |
class WorkerRegisterRequest(BaseModel):
|
| 49 |
worker_id: int
|
| 50 |
url: str
|
| 51 |
environment: Environment
|
| 52 |
|
| 53 |
+
|
| 54 |
class PollRequest(BaseModel):
|
| 55 |
worker_id: int
|
| 56 |
+
url: str
|
| 57 |
+
|
| 58 |
|
| 59 |
class DoneRequest(BaseModel):
|
| 60 |
worker_id: int
|
| 61 |
url: str
|
| 62 |
|
| 63 |
+
|
| 64 |
class JobSubmission(BaseModel):
|
| 65 |
job_id: Optional[str] = None
|
| 66 |
python_version: str
|
|
|
|
| 72 |
stdin: Optional[str] = None
|
| 73 |
timeout: float
|
| 74 |
|
| 75 |
+
|
| 76 |
Category = Literal[
|
| 77 |
+
"success", "timeout", "dependency_install_failed",
|
| 78 |
+
"infra_failure", "checker_error", "not_applicable",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
]
|
| 80 |
|
| 81 |
+
|
| 82 |
class ResultObject(BaseModel):
|
| 83 |
job_id: str
|
| 84 |
stdout: str
|
|
|
|
| 89 |
failure_reason: Optional[str] = None
|
| 90 |
network_activity_detected: Optional[bool] = None
|
| 91 |
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
class MemoryStore:
|
| 94 |
def __init__(self, settings: Settings, clock: Callable[[], float] = _now):
|
|
|
|
| 101 |
self.total_submitted = 0
|
| 102 |
self.total_completed = 0
|
| 103 |
|
|
|
|
| 104 |
def register_worker(self, worker_id: int, url: str, environment: dict) -> dict:
|
| 105 |
with self.lock:
|
| 106 |
now = self.clock()
|
| 107 |
worker = self.workers.get(worker_id)
|
| 108 |
+
|
| 109 |
if worker is None:
|
| 110 |
worker = {
|
| 111 |
"worker_id": worker_id,
|
|
|
|
| 117 |
}
|
| 118 |
self.workers[worker_id] = worker
|
| 119 |
else:
|
| 120 |
+
# Replace existing worker: keep old record info? We just overwrite.
|
| 121 |
+
old_url = worker["url"]
|
| 122 |
worker["url"] = url
|
| 123 |
worker["environment"] = environment
|
| 124 |
worker["last_seen_at"] = now
|
| 125 |
worker["registered_at"] = now
|
| 126 |
worker["reported_done"] = False
|
| 127 |
+
# The old worker will get a shutdown signal on its next poll
|
| 128 |
+
# because its URL no longer matches the current record.
|
| 129 |
+
logger.info(f"Worker {worker_id} replaced. Old URL: {old_url}, new URL: {url}")
|
| 130 |
+
|
| 131 |
return self._worker_public_locked(worker_id, now)
|
| 132 |
|
| 133 |
+
def poll_job(self, worker_id: int, url: str):
|
|
|
|
| 134 |
with self.lock:
|
| 135 |
worker = self.workers.get(worker_id)
|
| 136 |
if worker is None:
|
| 137 |
raise KeyError("worker not registered")
|
| 138 |
|
| 139 |
now = self.clock()
|
| 140 |
+
|
| 141 |
+
# If the worker's URL does not match the current registered URL,
|
| 142 |
+
# this is an old instance that has been superseded.
|
| 143 |
+
if worker["url"] != url:
|
| 144 |
+
return {"shutdown": True}
|
| 145 |
+
|
| 146 |
worker["last_seen_at"] = now
|
| 147 |
|
| 148 |
if worker.get("reported_done") or (now - worker["last_seen_at"]) > self.settings.liveness_window:
|
|
|
|
| 178 |
job["claimed_by"] = worker_id
|
| 179 |
job["claimed_worker_url"] = worker["url"]
|
| 180 |
job["claimed_at"] = now
|
| 181 |
+
job["claim_deadline"] = now + job["timeout"] + self.settings.claim_timeout_buffer
|
|
|
|
|
|
|
| 182 |
|
| 183 |
return self._public_job(job)
|
| 184 |
|
|
|
|
| 185 |
def report_result(self, worker_id: int, url: str, result: ResultObject) -> None:
|
| 186 |
with self.lock:
|
| 187 |
job = self.jobs.get(result.job_id)
|
|
|
|
| 202 |
self.total_completed += 1
|
| 203 |
|
| 204 |
worker = self.workers.get(worker_id)
|
| 205 |
+
if worker is not None and worker["url"] == url:
|
| 206 |
worker["last_seen_at"] = now
|
| 207 |
|
|
|
|
| 208 |
def report_done(self, worker_id: int, url: str) -> List[str]:
|
| 209 |
with self.lock:
|
| 210 |
worker = self.workers.get(worker_id)
|
|
|
|
| 224 |
released.append(job["job_id"])
|
| 225 |
return released
|
| 226 |
|
|
|
|
| 227 |
def submit_job(self, job_data: JobSubmission) -> str:
|
| 228 |
with self.lock:
|
| 229 |
job_id = job_data.job_id or generate_job_id()
|
| 230 |
if job_id in self.jobs:
|
| 231 |
raise ValueError("job_id already exists")
|
|
|
|
| 232 |
now = self.clock()
|
| 233 |
self.jobs[job_id] = {
|
| 234 |
"job_id": job_id,
|
|
|
|
| 254 |
self.total_submitted += 1
|
| 255 |
return job_id
|
| 256 |
|
|
|
|
| 257 |
def get_job(self, job_id: str):
|
| 258 |
with self.lock:
|
| 259 |
job = self.jobs.get(job_id)
|
|
|
|
| 302 |
queued = sum(1 for j in self.jobs.values() if j["status"] == "queued")
|
| 303 |
claimed = sum(1 for j in self.jobs.values() if j["status"] == "claimed")
|
| 304 |
complete = sum(1 for j in self.jobs.values() if j["status"] == "complete")
|
|
|
|
| 305 |
claimed_by_worker = {}
|
| 306 |
for j in self.jobs.values():
|
| 307 |
if j["status"] == "claimed":
|
| 308 |
wid = j.get("claimed_by")
|
| 309 |
if wid is not None:
|
| 310 |
claimed_by_worker[wid] = claimed_by_worker.get(wid, 0) + 1
|
|
|
|
| 311 |
workers = []
|
| 312 |
for wid, w in self.workers.items():
|
| 313 |
workers.append({
|
|
|
|
| 320 |
"last_seen_at": iso_from_ts(w["last_seen_at"]),
|
| 321 |
"registered_at": iso_from_ts(w["registered_at"]),
|
| 322 |
})
|
|
|
|
| 323 |
return {
|
| 324 |
"uptime_seconds": now - self.start_time,
|
| 325 |
"total_submitted": self.total_submitted,
|
| 326 |
"total_completed": self.total_completed,
|
| 327 |
+
"jobs_by_status": {"queued": queued, "claimed": claimed, "complete": complete},
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
"workers": workers,
|
| 329 |
"claimed_by_worker": claimed_by_worker,
|
| 330 |
}
|
| 331 |
|
|
|
|
| 332 |
def process_expired_claims(self) -> None:
|
| 333 |
with self.lock:
|
| 334 |
now = self.clock()
|
| 335 |
for job in list(self.jobs.values()):
|
| 336 |
+
if job["status"] == "claimed" and job.get("claim_deadline") and now >= job["claim_deadline"]:
|
| 337 |
self._abandon_claim_locked(job, "claim timeout", now)
|
| 338 |
|
| 339 |
def cleanup_completed(self) -> None:
|
|
|
|
| 341 |
now = self.clock()
|
| 342 |
for job_id in list(self.jobs):
|
| 343 |
job = self.jobs[job_id]
|
| 344 |
+
if job["status"] == "complete" and job.get("completed_at") and (now - job["completed_at"]) > self.settings.retention_seconds:
|
| 345 |
del self.jobs[job_id]
|
| 346 |
|
|
|
|
| 347 |
def _abandon_claim_locked(self, job: dict, reason: str, now: float) -> None:
|
| 348 |
if job.get("retry_count", 0) >= self.settings.max_retries:
|
| 349 |
job["status"] = "complete"
|
|
|
|
| 417 |
"timeout": job["timeout"],
|
| 418 |
}
|
| 419 |
|
|
|
|
|
|
|
|
|
|
| 420 |
|
| 421 |
+
# Global store and background loop
|
| 422 |
settings = Settings()
|
| 423 |
store = MemoryStore(settings)
|
| 424 |
|
|
|
|
| 430 |
|
| 431 |
threading.Thread(target=_background_loop, daemon=True).start()
|
| 432 |
|
|
|
|
| 433 |
# APIRouter
|
|
|
|
|
|
|
| 434 |
router = APIRouter()
|
| 435 |
security = HTTPBearer(auto_error=False)
|
| 436 |
|
|
|
|
| 446 |
or not secrets.compare_digest(credentials.credentials.encode(), expected.encode())):
|
| 447 |
raise HTTPException(status_code=401, detail="Unauthorized")
|
| 448 |
|
|
|
|
| 449 |
@router.post("/worker/register", dependencies=[Depends(worker_auth)])
|
| 450 |
def worker_register(body: WorkerRegisterRequest):
|
| 451 |
return store.register_worker(body.worker_id, body.url, body.environment.model_dump())
|
|
|
|
| 453 |
@router.post("/worker/poll", dependencies=[Depends(worker_auth)])
|
| 454 |
def worker_poll(body: PollRequest):
|
| 455 |
try:
|
| 456 |
+
response = store.poll_job(body.worker_id, body.url)
|
| 457 |
+
return response if response is not None else {"job": None}
|
| 458 |
except KeyError:
|
| 459 |
raise HTTPException(status_code=404, detail="Worker not registered")
|
| 460 |
|
|
|
|
| 477 |
released = store.report_done(body.worker_id, body.url)
|
| 478 |
return {"released_job_ids": released}
|
| 479 |
|
|
|
|
| 480 |
@router.post("/desktop/job", dependencies=[Depends(desktop_auth)])
|
| 481 |
def desktop_submit_job(body: JobSubmission):
|
| 482 |
try:
|