PERDYPTO commited on
Update projects/dataset_verification/router.py
Browse files
projects/dataset_verification/router.py
CHANGED
|
@@ -83,6 +83,25 @@ class ResultObject(BaseModel):
|
|
| 83 |
category: Category
|
| 84 |
failure_reason: Optional[str] = None
|
| 85 |
network_activity_detected: Optional[bool] = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
class MemoryStore:
|
| 88 |
def __init__(self, settings: Settings, clock: Callable[[], float] = _now):
|
|
@@ -172,6 +191,73 @@ class MemoryStore:
|
|
| 172 |
|
| 173 |
return self._public_job(job)
|
| 174 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
def report_result(self, worker_id: int, url: str, result: ResultObject) -> None:
|
| 176 |
with self.lock:
|
| 177 |
job = self.jobs.get(result.job_id)
|
|
@@ -195,6 +281,42 @@ class MemoryStore:
|
|
| 195 |
if worker is not None and worker["url"] == url:
|
| 196 |
worker["last_seen_at"] = now
|
| 197 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
def report_done(self, worker_id: int, url: str) -> List[str]:
|
| 199 |
with self.lock:
|
| 200 |
worker = self.workers.get(worker_id)
|
|
@@ -364,6 +486,7 @@ class MemoryStore:
|
|
| 364 |
"category": "infra_failure",
|
| 365 |
"failure_reason": f"job abandoned more than {self.settings.max_retries} times ({reason})",
|
| 366 |
"network_activity_detected": None,
|
|
|
|
| 367 |
}
|
| 368 |
job["completed_at"] = now
|
| 369 |
job["claimed_by"] = None
|
|
@@ -454,6 +577,9 @@ def desktop_auth(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
|
| 454 |
or not secrets.compare_digest(credentials.credentials.encode(), expected.encode())):
|
| 455 |
raise HTTPException(status_code=401, detail="Unauthorized")
|
| 456 |
|
|
|
|
|
|
|
|
|
|
| 457 |
@router.post("/worker/register", dependencies=[Depends(worker_auth)])
|
| 458 |
def worker_register(body: WorkerRegisterRequest):
|
| 459 |
return store.register_worker(body.worker_id, body.url, body.environment.model_dump())
|
|
@@ -524,4 +650,38 @@ def desktop_list_jobs():
|
|
| 524 |
|
| 525 |
@router.get("/desktop/status", dependencies=[Depends(desktop_auth)])
|
| 526 |
def desktop_status():
|
| 527 |
-
return store.get_status()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
category: Category
|
| 84 |
failure_reason: Optional[str] = None
|
| 85 |
network_activity_detected: Optional[bool] = None
|
| 86 |
+
# V2: Optional filesystem state dictionary
|
| 87 |
+
filesystem_state: Optional[Dict[str, str]] = None
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# ==================== V2 BATCH MODELS ====================
|
| 91 |
+
|
| 92 |
+
class WorkerBatchPollRequest(BaseModel):
|
| 93 |
+
worker_id: int
|
| 94 |
+
url: str
|
| 95 |
+
batch_size: int = 50 # Configurable, default 50
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class WorkerBatchResultRequest(BaseModel):
|
| 99 |
+
worker_id: int
|
| 100 |
+
url: str
|
| 101 |
+
results: List[ResultObject]
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# ==================== MEMORY STORE ====================
|
| 105 |
|
| 106 |
class MemoryStore:
|
| 107 |
def __init__(self, settings: Settings, clock: Callable[[], float] = _now):
|
|
|
|
| 191 |
|
| 192 |
return self._public_job(job)
|
| 193 |
|
| 194 |
+
# ==================== V2: BATCH POLL ====================
|
| 195 |
+
|
| 196 |
+
def poll_jobs_batch(self, worker_id: int, url: str, batch_size: int) -> List[dict]:
|
| 197 |
+
"""
|
| 198 |
+
Poll up to batch_size eligible jobs for a worker in a single call.
|
| 199 |
+
Respects max_concurrent_jobs limit.
|
| 200 |
+
"""
|
| 201 |
+
with self.lock:
|
| 202 |
+
worker = self.workers.get(worker_id)
|
| 203 |
+
if worker is None:
|
| 204 |
+
raise KeyError("worker not registered")
|
| 205 |
+
|
| 206 |
+
now = self.clock()
|
| 207 |
+
|
| 208 |
+
# If URL doesn't match, this is an old instance → tell it to shut down
|
| 209 |
+
if worker["url"] != url:
|
| 210 |
+
return [{"shutdown": True}]
|
| 211 |
+
|
| 212 |
+
worker["last_seen_at"] = now
|
| 213 |
+
|
| 214 |
+
if worker.get("reported_done") or (now - worker["last_seen_at"]) > self.settings.liveness_window:
|
| 215 |
+
return []
|
| 216 |
+
|
| 217 |
+
# Count active claims by this worker instance (same URL)
|
| 218 |
+
active_claims = sum(
|
| 219 |
+
1 for j in self.jobs.values()
|
| 220 |
+
if j["status"] == "claimed"
|
| 221 |
+
and j.get("claimed_by") == worker_id
|
| 222 |
+
and j.get("claimed_worker_url") == worker["url"]
|
| 223 |
+
)
|
| 224 |
+
max_concurrent = worker["environment"].get("max_concurrent_jobs", 1)
|
| 225 |
+
|
| 226 |
+
# Calculate how many more jobs this worker can take
|
| 227 |
+
available_slots = max_concurrent - active_claims
|
| 228 |
+
if available_slots <= 0:
|
| 229 |
+
return []
|
| 230 |
+
|
| 231 |
+
# Cap batch_size by available slots
|
| 232 |
+
take_count = min(batch_size, available_slots)
|
| 233 |
+
|
| 234 |
+
eligible = []
|
| 235 |
+
for job in self.jobs.values():
|
| 236 |
+
if job["status"] != "queued":
|
| 237 |
+
continue
|
| 238 |
+
if job["platform"] != worker["environment"].get("platform"):
|
| 239 |
+
continue
|
| 240 |
+
if job["python_version"] in worker["environment"].get("python_versions", []):
|
| 241 |
+
eligible.append(job)
|
| 242 |
+
|
| 243 |
+
if not eligible:
|
| 244 |
+
return []
|
| 245 |
+
|
| 246 |
+
# Sort by submission time (oldest first)
|
| 247 |
+
eligible.sort(key=lambda j: j["submitted_at"])
|
| 248 |
+
|
| 249 |
+
# Take up to take_count jobs
|
| 250 |
+
claimed_jobs = []
|
| 251 |
+
for job in eligible[:take_count]:
|
| 252 |
+
job["status"] = "claimed"
|
| 253 |
+
job["claimed_by"] = worker_id
|
| 254 |
+
job["claimed_worker_url"] = worker["url"]
|
| 255 |
+
job["claimed_at"] = now
|
| 256 |
+
job["claim_deadline"] = now + job["timeout"] + self.settings.claim_timeout_buffer
|
| 257 |
+
claimed_jobs.append(self._public_job(job))
|
| 258 |
+
|
| 259 |
+
return claimed_jobs
|
| 260 |
+
|
| 261 |
def report_result(self, worker_id: int, url: str, result: ResultObject) -> None:
|
| 262 |
with self.lock:
|
| 263 |
job = self.jobs.get(result.job_id)
|
|
|
|
| 281 |
if worker is not None and worker["url"] == url:
|
| 282 |
worker["last_seen_at"] = now
|
| 283 |
|
| 284 |
+
# ==================== V2: BATCH RESULTS ====================
|
| 285 |
+
|
| 286 |
+
def report_results_batch(self, worker_id: int, url: str, results: List[ResultObject]) -> None:
|
| 287 |
+
"""
|
| 288 |
+
Report multiple results in a single call. Each result is validated
|
| 289 |
+
against the same worker_id and url. If any job fails permission check,
|
| 290 |
+
a PermissionError is raised and no results are committed.
|
| 291 |
+
"""
|
| 292 |
+
with self.lock:
|
| 293 |
+
# First, validate all jobs exist and are claimed by this worker
|
| 294 |
+
jobs_to_update = []
|
| 295 |
+
for result in results:
|
| 296 |
+
job = self.jobs.get(result.job_id)
|
| 297 |
+
if job is None:
|
| 298 |
+
raise KeyError(f"job not found: {result.job_id}")
|
| 299 |
+
if job.get("claimed_by") != worker_id or job.get("claimed_worker_url") != url:
|
| 300 |
+
raise PermissionError(f"job {result.job_id} is not claimed by this worker instance")
|
| 301 |
+
jobs_to_update.append((job, result))
|
| 302 |
+
|
| 303 |
+
# All validations passed — commit all updates
|
| 304 |
+
now = self.clock()
|
| 305 |
+
for job, result in jobs_to_update:
|
| 306 |
+
job["status"] = "complete"
|
| 307 |
+
job["result"] = result.model_dump()
|
| 308 |
+
job["completed_at"] = now
|
| 309 |
+
job["claimed_by"] = None
|
| 310 |
+
job["claimed_worker_url"] = None
|
| 311 |
+
job["claimed_at"] = None
|
| 312 |
+
job["claim_deadline"] = None
|
| 313 |
+
self.total_completed += 1
|
| 314 |
+
|
| 315 |
+
# Update worker last_seen
|
| 316 |
+
worker = self.workers.get(worker_id)
|
| 317 |
+
if worker is not None and worker["url"] == url:
|
| 318 |
+
worker["last_seen_at"] = now
|
| 319 |
+
|
| 320 |
def report_done(self, worker_id: int, url: str) -> List[str]:
|
| 321 |
with self.lock:
|
| 322 |
worker = self.workers.get(worker_id)
|
|
|
|
| 486 |
"category": "infra_failure",
|
| 487 |
"failure_reason": f"job abandoned more than {self.settings.max_retries} times ({reason})",
|
| 488 |
"network_activity_detected": None,
|
| 489 |
+
"filesystem_state": None,
|
| 490 |
}
|
| 491 |
job["completed_at"] = now
|
| 492 |
job["claimed_by"] = None
|
|
|
|
| 577 |
or not secrets.compare_digest(credentials.credentials.encode(), expected.encode())):
|
| 578 |
raise HTTPException(status_code=401, detail="Unauthorized")
|
| 579 |
|
| 580 |
+
|
| 581 |
+
# ==================== V1 ENDPOINTS (unchanged) ====================
|
| 582 |
+
|
| 583 |
@router.post("/worker/register", dependencies=[Depends(worker_auth)])
|
| 584 |
def worker_register(body: WorkerRegisterRequest):
|
| 585 |
return store.register_worker(body.worker_id, body.url, body.environment.model_dump())
|
|
|
|
| 650 |
|
| 651 |
@router.get("/desktop/status", dependencies=[Depends(desktop_auth)])
|
| 652 |
def desktop_status():
|
| 653 |
+
return store.get_status()
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
# ==================== V2 ENDPOINTS (NEW) ====================
|
| 657 |
+
|
| 658 |
+
@router.post("/worker/jobs/batch", dependencies=[Depends(worker_auth)])
|
| 659 |
+
def worker_poll_batch(body: WorkerBatchPollRequest):
|
| 660 |
+
"""
|
| 661 |
+
V2: Poll up to batch_size jobs in a single request.
|
| 662 |
+
Returns a list of job objects (or empty list if none available).
|
| 663 |
+
"""
|
| 664 |
+
try:
|
| 665 |
+
jobs = store.poll_jobs_batch(body.worker_id, body.url, body.batch_size)
|
| 666 |
+
# Check for shutdown signal (returned as a dict with {'shutdown': True})
|
| 667 |
+
if jobs and isinstance(jobs[0], dict) and jobs[0].get("shutdown"):
|
| 668 |
+
return jobs[0] # Return the shutdown signal
|
| 669 |
+
return {"jobs": jobs}
|
| 670 |
+
except KeyError:
|
| 671 |
+
raise HTTPException(status_code=404, detail="Worker not registered")
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
@router.post("/worker/results/batch", dependencies=[Depends(worker_auth)])
|
| 675 |
+
def worker_results_batch(body: WorkerBatchResultRequest):
|
| 676 |
+
"""
|
| 677 |
+
V2: Submit multiple results in a single request.
|
| 678 |
+
All results are validated and committed atomically.
|
| 679 |
+
"""
|
| 680 |
+
try:
|
| 681 |
+
store.report_results_batch(body.worker_id, body.url, body.results)
|
| 682 |
+
job_ids = [r.job_id for r in body.results]
|
| 683 |
+
return {"status": "complete", "job_ids": job_ids}
|
| 684 |
+
except KeyError as e:
|
| 685 |
+
raise HTTPException(status_code=404, detail=str(e))
|
| 686 |
+
except PermissionError as e:
|
| 687 |
+
raise HTTPException(status_code=409, detail=str(e))
|