PERDYPTO commited on
Update projects/dataset_verification/router.py
Browse files- projects/dataset_verification/router.py +1160 -180
projects/dataset_verification/router.py
CHANGED
|
@@ -3,6 +3,9 @@ import os
|
|
| 3 |
import secrets
|
| 4 |
import threading
|
| 5 |
import time
|
|
|
|
|
|
|
|
|
|
| 6 |
from dataclasses import dataclass
|
| 7 |
from datetime import datetime, timezone
|
| 8 |
from typing import Callable, Dict, List, Literal, Optional
|
|
@@ -13,9 +16,11 @@ from pydantic import BaseModel, Field
|
|
| 13 |
|
| 14 |
logger = logging.getLogger("dataset_verification")
|
| 15 |
|
|
|
|
| 16 |
def _now() -> float:
|
| 17 |
return time.time()
|
| 18 |
|
|
|
|
| 19 |
def iso_from_ts(ts: float) -> str:
|
| 20 |
return (
|
| 21 |
datetime.fromtimestamp(ts, tz=timezone.utc)
|
|
@@ -23,9 +28,15 @@ def iso_from_ts(ts: float) -> str:
|
|
| 23 |
.replace("+00:00", "Z")
|
| 24 |
)
|
| 25 |
|
|
|
|
| 26 |
def generate_job_id() -> str:
|
| 27 |
return "job_" + secrets.token_hex(6)
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
@dataclass
|
| 30 |
class Settings:
|
| 31 |
github_shared_secret: str = os.getenv("GITHUB_SHARED_SECRET", "")
|
|
@@ -35,6 +46,18 @@ class Settings:
|
|
| 35 |
max_retries: int = int(os.getenv("MAX_RETRIES", "3"))
|
| 36 |
retention_seconds: float = float(os.getenv("RESULT_RETENTION_SECONDS", "3600"))
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
class Environment(BaseModel):
|
| 39 |
platform: str
|
| 40 |
os_version: str
|
|
@@ -42,19 +65,23 @@ class Environment(BaseModel):
|
|
| 42 |
max_concurrent_jobs: int = 20
|
| 43 |
notes: Optional[str] = None
|
| 44 |
|
|
|
|
| 45 |
class WorkerRegisterRequest(BaseModel):
|
| 46 |
worker_id: int
|
| 47 |
url: str
|
| 48 |
environment: Environment
|
| 49 |
|
|
|
|
| 50 |
class PollRequest(BaseModel):
|
| 51 |
worker_id: int
|
| 52 |
url: str
|
| 53 |
|
|
|
|
| 54 |
class DoneRequest(BaseModel):
|
| 55 |
worker_id: int
|
| 56 |
url: str
|
| 57 |
|
|
|
|
| 58 |
class JobSubmission(BaseModel):
|
| 59 |
job_id: Optional[str] = None
|
| 60 |
python_version: str
|
|
@@ -66,14 +93,21 @@ class JobSubmission(BaseModel):
|
|
| 66 |
stdin: Optional[str] = None
|
| 67 |
timeout: float
|
| 68 |
|
|
|
|
| 69 |
class JobBatchSubmission(BaseModel):
|
| 70 |
jobs: List[JobSubmission]
|
| 71 |
|
|
|
|
| 72 |
Category = Literal[
|
| 73 |
-
"success",
|
| 74 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
]
|
| 76 |
|
|
|
|
| 77 |
class ResultObject(BaseModel):
|
| 78 |
job_id: str
|
| 79 |
stdout: str
|
|
@@ -92,7 +126,7 @@ class ResultObject(BaseModel):
|
|
| 92 |
class WorkerBatchPollRequest(BaseModel):
|
| 93 |
worker_id: int
|
| 94 |
url: str
|
| 95 |
-
batch_size: int = 50
|
| 96 |
|
| 97 |
|
| 98 |
class WorkerBatchResultRequest(BaseModel):
|
|
@@ -101,6 +135,30 @@ class WorkerBatchResultRequest(BaseModel):
|
|
| 101 |
results: List[ResultObject]
|
| 102 |
|
| 103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
# ==================== MEMORY STORE ====================
|
| 105 |
|
| 106 |
class MemoryStore:
|
|
@@ -108,11 +166,24 @@ class MemoryStore:
|
|
| 108 |
self.settings = settings
|
| 109 |
self.clock = clock
|
| 110 |
self.lock = threading.RLock()
|
|
|
|
| 111 |
self.workers: Dict[int, dict] = {}
|
| 112 |
self.jobs: Dict[str, dict] = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
self.start_time = self.clock()
|
| 114 |
self.total_submitted = 0
|
| 115 |
self.total_completed = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
def register_worker(self, worker_id: int, url: str, environment: dict) -> dict:
|
| 118 |
with self.lock:
|
|
@@ -136,10 +207,17 @@ class MemoryStore:
|
|
| 136 |
worker["last_seen_at"] = now
|
| 137 |
worker["registered_at"] = now
|
| 138 |
worker["reported_done"] = False
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
return self._worker_public_locked(worker_id, now)
|
| 142 |
|
|
|
|
|
|
|
|
|
|
| 143 |
def poll_job(self, worker_id: int, url: str):
|
| 144 |
with self.lock:
|
| 145 |
worker = self.workers.get(worker_id)
|
|
@@ -148,23 +226,29 @@ class MemoryStore:
|
|
| 148 |
|
| 149 |
now = self.clock()
|
| 150 |
|
| 151 |
-
#
|
| 152 |
if worker["url"] != url:
|
| 153 |
return {"shutdown": True}
|
| 154 |
|
|
|
|
|
|
|
| 155 |
worker["last_seen_at"] = now
|
| 156 |
|
| 157 |
-
if worker.get("reported_done")
|
| 158 |
return None
|
| 159 |
|
| 160 |
-
# Count active claims by this worker instance (same URL)
|
| 161 |
active_claims = sum(
|
| 162 |
-
1
|
|
|
|
| 163 |
if j["status"] == "claimed"
|
| 164 |
and j.get("claimed_by") == worker_id
|
| 165 |
and j.get("claimed_worker_url") == worker["url"]
|
| 166 |
)
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
if active_claims >= max_concurrent:
|
| 169 |
return None
|
| 170 |
|
|
@@ -174,7 +258,10 @@ class MemoryStore:
|
|
| 174 |
continue
|
| 175 |
if job["platform"] != worker["environment"].get("platform"):
|
| 176 |
continue
|
| 177 |
-
if
|
|
|
|
|
|
|
|
|
|
| 178 |
eligible.append(job)
|
| 179 |
|
| 180 |
if not eligible:
|
|
@@ -187,17 +274,15 @@ class MemoryStore:
|
|
| 187 |
job["claimed_by"] = worker_id
|
| 188 |
job["claimed_worker_url"] = worker["url"]
|
| 189 |
job["claimed_at"] = now
|
| 190 |
-
job["claim_deadline"] =
|
|
|
|
|
|
|
| 191 |
|
| 192 |
return self._public_job(job)
|
| 193 |
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 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:
|
|
@@ -205,123 +290,163 @@ class MemoryStore:
|
|
| 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")
|
| 215 |
return []
|
| 216 |
|
| 217 |
-
# Count active claims by this worker instance (same URL)
|
| 218 |
active_claims = sum(
|
| 219 |
-
1
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
| 227 |
available_slots = max_concurrent - active_claims
|
|
|
|
| 228 |
if available_slots <= 0:
|
| 229 |
return []
|
| 230 |
|
| 231 |
-
|
| 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
|
|
|
|
|
|
|
|
|
|
| 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"] =
|
|
|
|
|
|
|
| 257 |
claimed_jobs.append(self._public_job(job))
|
| 258 |
|
| 259 |
return claimed_jobs
|
| 260 |
|
| 261 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
with self.lock:
|
| 263 |
job = self.jobs.get(result.job_id)
|
| 264 |
if job is None:
|
| 265 |
raise KeyError("job not found")
|
| 266 |
-
|
| 267 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
|
| 269 |
now = self.clock()
|
| 270 |
-
job["status"] = "complete"
|
| 271 |
-
job["result"] = result.model_dump()
|
| 272 |
-
job["completed_at"] = now
|
| 273 |
-
job["claimed_by"] = None
|
| 274 |
-
job["claimed_worker_url"] = None
|
| 275 |
-
job["claimed_at"] = None
|
| 276 |
-
job["claim_deadline"] = None
|
| 277 |
|
| 278 |
-
self.
|
|
|
|
|
|
|
| 279 |
|
| 280 |
worker = self.workers.get(worker_id)
|
| 281 |
if worker is not None and worker["url"] == url:
|
| 282 |
worker["last_seen_at"] = now
|
| 283 |
|
| 284 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 307 |
-
|
| 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)
|
| 323 |
if worker is None:
|
| 324 |
return []
|
|
|
|
| 325 |
if worker["url"] != url:
|
| 326 |
return []
|
| 327 |
|
|
@@ -330,38 +455,91 @@ class MemoryStore:
|
|
| 330 |
worker["last_seen_at"] = now
|
| 331 |
|
| 332 |
released = []
|
|
|
|
| 333 |
for job in list(self.jobs.values()):
|
| 334 |
-
if
|
| 335 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
released.append(job["job_id"])
|
| 337 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 338 |
|
| 339 |
def submit_job(self, job_data: JobSubmission) -> str:
|
| 340 |
with self.lock:
|
| 341 |
job_id = job_data.job_id or generate_job_id()
|
|
|
|
| 342 |
if job_id in self.jobs:
|
| 343 |
raise ValueError("job_id already exists")
|
| 344 |
|
| 345 |
now = self.clock()
|
| 346 |
-
self.jobs[job_id] = self._build_job_dict(
|
|
|
|
|
|
|
| 347 |
self.total_submitted += 1
|
|
|
|
| 348 |
return job_id
|
| 349 |
|
| 350 |
-
def submit_jobs_batch(
|
| 351 |
-
|
|
|
|
| 352 |
with self.lock:
|
| 353 |
now = self.clock()
|
| 354 |
job_ids = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
for job_data in jobs_data:
|
| 356 |
job_id = job_data.job_id or generate_job_id()
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 360 |
self.total_submitted += 1
|
| 361 |
job_ids.append(job_id)
|
|
|
|
| 362 |
return job_ids
|
| 363 |
|
| 364 |
-
def _build_job_dict(
|
|
|
|
|
|
|
| 365 |
return {
|
| 366 |
"job_id": job_id,
|
| 367 |
"python_version": job_data.python_version,
|
|
@@ -387,95 +565,537 @@ class MemoryStore:
|
|
| 387 |
def get_job(self, job_id: str):
|
| 388 |
with self.lock:
|
| 389 |
job = self.jobs.get(job_id)
|
|
|
|
| 390 |
if job is None:
|
| 391 |
return None, None
|
|
|
|
| 392 |
if job["status"] == "complete":
|
| 393 |
return "complete", job["result"]
|
|
|
|
| 394 |
matching = self._matching_worker_ids_locked(job)
|
|
|
|
| 395 |
return "pending", {
|
| 396 |
"retry_count": job["retry_count"],
|
| 397 |
"matching_worker_ids": matching,
|
| 398 |
-
"last_abandon_reason": job.get(
|
|
|
|
|
|
|
| 399 |
"submitted_at": iso_from_ts(job["submitted_at"]),
|
| 400 |
}
|
| 401 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 402 |
def list_workers(self) -> List[dict]:
|
| 403 |
with self.lock:
|
| 404 |
now = self.clock()
|
| 405 |
-
return [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
|
| 407 |
def list_jobs(self) -> List[dict]:
|
| 408 |
with self.lock:
|
| 409 |
result = []
|
|
|
|
| 410 |
for job in self.jobs.values():
|
| 411 |
item = {
|
| 412 |
"job_id": job["job_id"],
|
| 413 |
"status": job["status"],
|
| 414 |
-
"submitted_at": iso_from_ts(
|
|
|
|
|
|
|
| 415 |
"python_version": job["python_version"],
|
| 416 |
"platform": job["platform"],
|
| 417 |
"retry_count": job["retry_count"],
|
| 418 |
"claimed_by": job.get("claimed_by"),
|
| 419 |
-
"
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 423 |
}
|
| 424 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
item["result"] = job["result"]
|
|
|
|
| 426 |
result.append(item)
|
|
|
|
| 427 |
return result
|
| 428 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
def get_status(self) -> dict:
|
| 430 |
with self.lock:
|
| 431 |
now = self.clock()
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 435 |
claimed_by_worker = {}
|
|
|
|
| 436 |
for j in self.jobs.values():
|
| 437 |
if j["status"] == "claimed":
|
| 438 |
wid = j.get("claimed_by")
|
| 439 |
if wid is not None:
|
| 440 |
-
claimed_by_worker[wid] =
|
|
|
|
|
|
|
|
|
|
| 441 |
workers = []
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
return {
|
| 454 |
"uptime_seconds": now - self.start_time,
|
| 455 |
"total_submitted": self.total_submitted,
|
| 456 |
"total_completed": self.total_completed,
|
| 457 |
-
"jobs_by_status": {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 458 |
"workers": workers,
|
| 459 |
"claimed_by_worker": claimed_by_worker,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
}
|
| 461 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 462 |
def process_expired_claims(self) -> None:
|
|
|
|
|
|
|
| 463 |
with self.lock:
|
| 464 |
now = self.clock()
|
|
|
|
| 465 |
for job in list(self.jobs.values()):
|
| 466 |
-
if
|
| 467 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
|
| 469 |
def cleanup_completed(self) -> None:
|
| 470 |
with self.lock:
|
| 471 |
now = self.clock()
|
|
|
|
| 472 |
for job_id in list(self.jobs):
|
| 473 |
job = self.jobs[job_id]
|
| 474 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 475 |
del self.jobs[job_id]
|
| 476 |
|
| 477 |
-
|
| 478 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 479 |
job["status"] = "complete"
|
| 480 |
job["result"] = {
|
| 481 |
"job_id": job["job_id"],
|
|
@@ -484,7 +1104,11 @@ class MemoryStore:
|
|
| 484 |
"exit_code": 1,
|
| 485 |
"timed_out": False,
|
| 486 |
"category": "infra_failure",
|
| 487 |
-
"failure_reason":
|
|
|
|
|
|
|
|
|
|
|
|
|
| 488 |
"network_activity_detected": None,
|
| 489 |
"filesystem_state": None,
|
| 490 |
}
|
|
@@ -493,9 +1117,13 @@ class MemoryStore:
|
|
| 493 |
job["claimed_worker_url"] = None
|
| 494 |
job["claimed_at"] = None
|
| 495 |
job["claim_deadline"] = None
|
|
|
|
| 496 |
self.total_completed += 1
|
|
|
|
| 497 |
else:
|
| 498 |
-
job["retry_count"] =
|
|
|
|
|
|
|
| 499 |
job["status"] = "queued"
|
| 500 |
job["claimed_by"] = None
|
| 501 |
job["claimed_worker_url"] = None
|
|
@@ -503,35 +1131,81 @@ class MemoryStore:
|
|
| 503 |
job["claim_deadline"] = None
|
| 504 |
job["last_abandon_reason"] = reason
|
| 505 |
|
| 506 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
matching = []
|
|
|
|
| 508 |
for worker_id, worker in self.workers.items():
|
| 509 |
-
if
|
|
|
|
|
|
|
|
|
|
| 510 |
continue
|
| 511 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
matching.append(worker_id)
|
|
|
|
| 513 |
return matching
|
| 514 |
|
| 515 |
-
def _status_locked(
|
|
|
|
|
|
|
| 516 |
worker = self.workers.get(worker_id)
|
|
|
|
| 517 |
if worker is None:
|
| 518 |
return "unresponsive"
|
| 519 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 520 |
return "unresponsive"
|
|
|
|
| 521 |
for job in self.jobs.values():
|
| 522 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 523 |
return "busy"
|
|
|
|
| 524 |
return "idle"
|
| 525 |
|
| 526 |
-
def _worker_public_locked(
|
|
|
|
|
|
|
| 527 |
worker = self.workers[worker_id]
|
|
|
|
| 528 |
return {
|
| 529 |
"worker_id": worker["worker_id"],
|
| 530 |
"url": worker["url"],
|
| 531 |
"environment": worker["environment"],
|
| 532 |
-
"registered_at": iso_from_ts(
|
| 533 |
-
|
| 534 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 535 |
}
|
| 536 |
|
| 537 |
@staticmethod
|
|
@@ -549,139 +1223,445 @@ class MemoryStore:
|
|
| 549 |
}
|
| 550 |
|
| 551 |
|
| 552 |
-
#
|
|
|
|
| 553 |
settings = Settings()
|
| 554 |
store = MemoryStore(settings)
|
| 555 |
|
|
|
|
| 556 |
def _background_loop():
|
| 557 |
while True:
|
| 558 |
time.sleep(1)
|
| 559 |
-
|
| 560 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 561 |
|
| 562 |
-
threading.Thread(target=_background_loop, daemon=True).start()
|
| 563 |
|
| 564 |
-
#
|
|
|
|
| 565 |
router = APIRouter()
|
| 566 |
security = HTTPBearer(auto_error=False)
|
| 567 |
|
| 568 |
-
|
|
|
|
|
|
|
|
|
|
| 569 |
expected = settings.github_shared_secret
|
| 570 |
-
if (not expected or not credentials or credentials.scheme.lower() != "bearer"
|
| 571 |
-
or not secrets.compare_digest(credentials.credentials.encode(), expected.encode())):
|
| 572 |
-
raise HTTPException(status_code=401, detail="Unauthorized")
|
| 573 |
|
| 574 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 575 |
expected = settings.desktop_api_key
|
| 576 |
-
if (not expected or not credentials or credentials.scheme.lower() != "bearer"
|
| 577 |
-
or not secrets.compare_digest(credentials.credentials.encode(), expected.encode())):
|
| 578 |
-
raise HTTPException(status_code=401, detail="Unauthorized")
|
| 579 |
-
|
| 580 |
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 584 |
def worker_register(body: WorkerRegisterRequest):
|
| 585 |
-
return store.register_worker(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 586 |
|
| 587 |
-
@router.post(
|
|
|
|
|
|
|
|
|
|
| 588 |
def worker_poll(body: PollRequest):
|
| 589 |
try:
|
| 590 |
-
response = store.poll_job(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 591 |
if response is None:
|
| 592 |
return {"job": None}
|
|
|
|
| 593 |
if response.get("shutdown"):
|
| 594 |
return response
|
|
|
|
| 595 |
return {"job": response}
|
|
|
|
| 596 |
except KeyError:
|
| 597 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 598 |
|
| 599 |
-
@router.post(
|
|
|
|
|
|
|
|
|
|
| 600 |
def worker_result(
|
| 601 |
worker_id: int = Query(...),
|
| 602 |
url: str = Query(...),
|
| 603 |
result: ResultObject = Body(...),
|
| 604 |
):
|
| 605 |
try:
|
| 606 |
-
store.report_result(
|
| 607 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 608 |
except KeyError:
|
| 609 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 610 |
except PermissionError:
|
| 611 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 612 |
|
| 613 |
-
@router.post(
|
|
|
|
|
|
|
|
|
|
| 614 |
def worker_done(body: DoneRequest):
|
| 615 |
-
released = store.report_done(
|
| 616 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 617 |
|
| 618 |
-
@router.post(
|
|
|
|
|
|
|
|
|
|
| 619 |
def desktop_submit_job(body: JobSubmission):
|
| 620 |
try:
|
| 621 |
job_id = store.submit_job(body)
|
| 622 |
-
return {"job_id": job_id, "status": "queued"}
|
| 623 |
-
except ValueError:
|
| 624 |
-
raise HTTPException(status_code=409, detail="job_id already exists")
|
| 625 |
|
| 626 |
-
|
| 627 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 628 |
try:
|
| 629 |
-
job_ids = store.submit_jobs_batch(
|
| 630 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 631 |
except ValueError as e:
|
| 632 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 633 |
|
| 634 |
-
@router.get(
|
|
|
|
|
|
|
|
|
|
| 635 |
def desktop_get_result(job_id: str):
|
| 636 |
status, data = store.get_job(job_id)
|
|
|
|
| 637 |
if status is None:
|
| 638 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 639 |
if status == "complete":
|
| 640 |
-
return {
|
| 641 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 642 |
|
| 643 |
-
@router.get(
|
|
|
|
|
|
|
|
|
|
| 644 |
def desktop_list_workers():
|
| 645 |
return store.list_workers()
|
| 646 |
|
| 647 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 648 |
def desktop_list_jobs():
|
| 649 |
return store.list_jobs()
|
| 650 |
|
| 651 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 652 |
def desktop_status():
|
| 653 |
return store.get_status()
|
| 654 |
|
| 655 |
|
| 656 |
-
# ==================== V2 ENDPOINTS (
|
| 657 |
|
| 658 |
-
@router.post(
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
|
|
|
| 664 |
try:
|
| 665 |
-
jobs = store.poll_jobs_batch(
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 669 |
return {"jobs": jobs}
|
|
|
|
| 670 |
except KeyError:
|
| 671 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 672 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 673 |
|
| 674 |
-
|
| 675 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 676 |
"""
|
| 677 |
-
|
| 678 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 679 |
"""
|
| 680 |
try:
|
| 681 |
-
store.
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import secrets
|
| 4 |
import threading
|
| 5 |
import time
|
| 6 |
+
import json
|
| 7 |
+
import urllib.request
|
| 8 |
+
import urllib.error
|
| 9 |
from dataclasses import dataclass
|
| 10 |
from datetime import datetime, timezone
|
| 11 |
from typing import Callable, Dict, List, Literal, Optional
|
|
|
|
| 16 |
|
| 17 |
logger = logging.getLogger("dataset_verification")
|
| 18 |
|
| 19 |
+
|
| 20 |
def _now() -> float:
|
| 21 |
return time.time()
|
| 22 |
|
| 23 |
+
|
| 24 |
def iso_from_ts(ts: float) -> str:
|
| 25 |
return (
|
| 26 |
datetime.fromtimestamp(ts, tz=timezone.utc)
|
|
|
|
| 28 |
.replace("+00:00", "Z")
|
| 29 |
)
|
| 30 |
|
| 31 |
+
|
| 32 |
def generate_job_id() -> str:
|
| 33 |
return "job_" + secrets.token_hex(6)
|
| 34 |
|
| 35 |
+
|
| 36 |
+
def generate_request_id() -> str:
|
| 37 |
+
return "verify_" + secrets.token_hex(8)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
@dataclass
|
| 41 |
class Settings:
|
| 42 |
github_shared_secret: str = os.getenv("GITHUB_SHARED_SECRET", "")
|
|
|
|
| 46 |
max_retries: int = int(os.getenv("MAX_RETRIES", "3"))
|
| 47 |
retention_seconds: float = float(os.getenv("RESULT_RETENTION_SECONDS", "3600"))
|
| 48 |
|
| 49 |
+
# New logical verification request settings.
|
| 50 |
+
verification_retention_seconds: float = float(
|
| 51 |
+
os.getenv("VERIFICATION_RETENTION_SECONDS", "3600")
|
| 52 |
+
)
|
| 53 |
+
callback_timeout_seconds: float = float(
|
| 54 |
+
os.getenv("VERIFICATION_CALLBACK_TIMEOUT_SECONDS", "15")
|
| 55 |
+
)
|
| 56 |
+
callback_max_retries: int = int(
|
| 57 |
+
os.getenv("VERIFICATION_CALLBACK_MAX_RETRIES", "3")
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
class Environment(BaseModel):
|
| 62 |
platform: str
|
| 63 |
os_version: str
|
|
|
|
| 65 |
max_concurrent_jobs: int = 20
|
| 66 |
notes: Optional[str] = None
|
| 67 |
|
| 68 |
+
|
| 69 |
class WorkerRegisterRequest(BaseModel):
|
| 70 |
worker_id: int
|
| 71 |
url: str
|
| 72 |
environment: Environment
|
| 73 |
|
| 74 |
+
|
| 75 |
class PollRequest(BaseModel):
|
| 76 |
worker_id: int
|
| 77 |
url: str
|
| 78 |
|
| 79 |
+
|
| 80 |
class DoneRequest(BaseModel):
|
| 81 |
worker_id: int
|
| 82 |
url: str
|
| 83 |
|
| 84 |
+
|
| 85 |
class JobSubmission(BaseModel):
|
| 86 |
job_id: Optional[str] = None
|
| 87 |
python_version: str
|
|
|
|
| 93 |
stdin: Optional[str] = None
|
| 94 |
timeout: float
|
| 95 |
|
| 96 |
+
|
| 97 |
class JobBatchSubmission(BaseModel):
|
| 98 |
jobs: List[JobSubmission]
|
| 99 |
|
| 100 |
+
|
| 101 |
Category = Literal[
|
| 102 |
+
"success",
|
| 103 |
+
"timeout",
|
| 104 |
+
"dependency_install_failed",
|
| 105 |
+
"infra_failure",
|
| 106 |
+
"checker_error",
|
| 107 |
+
"not_applicable",
|
| 108 |
]
|
| 109 |
|
| 110 |
+
|
| 111 |
class ResultObject(BaseModel):
|
| 112 |
job_id: str
|
| 113 |
stdout: str
|
|
|
|
| 126 |
class WorkerBatchPollRequest(BaseModel):
|
| 127 |
worker_id: int
|
| 128 |
url: str
|
| 129 |
+
batch_size: int = 50
|
| 130 |
|
| 131 |
|
| 132 |
class WorkerBatchResultRequest(BaseModel):
|
|
|
|
| 135 |
results: List[ResultObject]
|
| 136 |
|
| 137 |
|
| 138 |
+
# ==================== NEW LOGICAL VERIFICATION MODELS ====================
|
| 139 |
+
|
| 140 |
+
class VerificationSubmission(BaseModel):
|
| 141 |
+
"""
|
| 142 |
+
One logical verification request.
|
| 143 |
+
|
| 144 |
+
The jobs are ordinary JobSubmission objects, so the existing worker
|
| 145 |
+
protocol remains unchanged. The coordinator tracks them as one logical
|
| 146 |
+
request and can return one consolidated result or call a callback.
|
| 147 |
+
"""
|
| 148 |
+
request_id: Optional[str] = None
|
| 149 |
+
jobs: List[JobSubmission]
|
| 150 |
+
callback_url: Optional[str] = None
|
| 151 |
+
|
| 152 |
+
# Optional shared secret sent in the callback header:
|
| 153 |
+
# X-Verification-Callback-Secret
|
| 154 |
+
callback_secret: Optional[str] = None
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class VerificationCallbackConfig(BaseModel):
|
| 158 |
+
callback_url: str
|
| 159 |
+
callback_secret: Optional[str] = None
|
| 160 |
+
|
| 161 |
+
|
| 162 |
# ==================== MEMORY STORE ====================
|
| 163 |
|
| 164 |
class MemoryStore:
|
|
|
|
| 166 |
self.settings = settings
|
| 167 |
self.clock = clock
|
| 168 |
self.lock = threading.RLock()
|
| 169 |
+
|
| 170 |
self.workers: Dict[int, dict] = {}
|
| 171 |
self.jobs: Dict[str, dict] = {}
|
| 172 |
+
|
| 173 |
+
# Logical verification requests:
|
| 174 |
+
# request_id -> request state
|
| 175 |
+
self.verifications: Dict[str, dict] = {}
|
| 176 |
+
|
| 177 |
self.start_time = self.clock()
|
| 178 |
self.total_submitted = 0
|
| 179 |
self.total_completed = 0
|
| 180 |
+
self.total_verification_requests = 0
|
| 181 |
+
self.total_callbacks_sent = 0
|
| 182 |
+
self.total_callback_failures = 0
|
| 183 |
+
|
| 184 |
+
# ------------------------------------------------------------------
|
| 185 |
+
# Worker management
|
| 186 |
+
# ------------------------------------------------------------------
|
| 187 |
|
| 188 |
def register_worker(self, worker_id: int, url: str, environment: dict) -> dict:
|
| 189 |
with self.lock:
|
|
|
|
| 207 |
worker["last_seen_at"] = now
|
| 208 |
worker["registered_at"] = now
|
| 209 |
worker["reported_done"] = False
|
| 210 |
+
|
| 211 |
+
logger.info(
|
| 212 |
+
f"Worker {worker_id} replaced. "
|
| 213 |
+
f"Old URL: {old_url}, new URL: {url}"
|
| 214 |
+
)
|
| 215 |
|
| 216 |
return self._worker_public_locked(worker_id, now)
|
| 217 |
|
| 218 |
+
def _worker_is_stale_locked(self, worker: dict, now: float) -> bool:
|
| 219 |
+
return (now - worker["last_seen_at"]) > self.settings.liveness_window
|
| 220 |
+
|
| 221 |
def poll_job(self, worker_id: int, url: str):
|
| 222 |
with self.lock:
|
| 223 |
worker = self.workers.get(worker_id)
|
|
|
|
| 226 |
|
| 227 |
now = self.clock()
|
| 228 |
|
| 229 |
+
# URL mismatch means an old worker instance must shut down.
|
| 230 |
if worker["url"] != url:
|
| 231 |
return {"shutdown": True}
|
| 232 |
|
| 233 |
+
# The poll itself is a liveness signal. Record it first, then
|
| 234 |
+
# use last_seen_at for status reporting elsewhere.
|
| 235 |
worker["last_seen_at"] = now
|
| 236 |
|
| 237 |
+
if worker.get("reported_done"):
|
| 238 |
return None
|
| 239 |
|
|
|
|
| 240 |
active_claims = sum(
|
| 241 |
+
1
|
| 242 |
+
for j in self.jobs.values()
|
| 243 |
if j["status"] == "claimed"
|
| 244 |
and j.get("claimed_by") == worker_id
|
| 245 |
and j.get("claimed_worker_url") == worker["url"]
|
| 246 |
)
|
| 247 |
+
|
| 248 |
+
max_concurrent = worker["environment"].get(
|
| 249 |
+
"max_concurrent_jobs", 1
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
if active_claims >= max_concurrent:
|
| 253 |
return None
|
| 254 |
|
|
|
|
| 258 |
continue
|
| 259 |
if job["platform"] != worker["environment"].get("platform"):
|
| 260 |
continue
|
| 261 |
+
if (
|
| 262 |
+
job["python_version"]
|
| 263 |
+
in worker["environment"].get("python_versions", [])
|
| 264 |
+
):
|
| 265 |
eligible.append(job)
|
| 266 |
|
| 267 |
if not eligible:
|
|
|
|
| 274 |
job["claimed_by"] = worker_id
|
| 275 |
job["claimed_worker_url"] = worker["url"]
|
| 276 |
job["claimed_at"] = now
|
| 277 |
+
job["claim_deadline"] = (
|
| 278 |
+
now + job["timeout"] + self.settings.claim_timeout_buffer
|
| 279 |
+
)
|
| 280 |
|
| 281 |
return self._public_job(job)
|
| 282 |
|
| 283 |
+
def poll_jobs_batch(
|
| 284 |
+
self, worker_id: int, url: str, batch_size: int
|
| 285 |
+
) -> List[dict]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
with self.lock:
|
| 287 |
worker = self.workers.get(worker_id)
|
| 288 |
if worker is None:
|
|
|
|
| 290 |
|
| 291 |
now = self.clock()
|
| 292 |
|
|
|
|
| 293 |
if worker["url"] != url:
|
| 294 |
return [{"shutdown": True}]
|
| 295 |
|
| 296 |
+
# The batch poll itself proves the worker is alive.
|
| 297 |
worker["last_seen_at"] = now
|
| 298 |
|
| 299 |
+
if worker.get("reported_done"):
|
| 300 |
return []
|
| 301 |
|
|
|
|
| 302 |
active_claims = sum(
|
| 303 |
+
1
|
| 304 |
+
for j in self.jobs.values()
|
| 305 |
if j["status"] == "claimed"
|
| 306 |
and j.get("claimed_by") == worker_id
|
| 307 |
and j.get("claimed_worker_url") == worker["url"]
|
| 308 |
)
|
|
|
|
| 309 |
|
| 310 |
+
max_concurrent = worker["environment"].get(
|
| 311 |
+
"max_concurrent_jobs", 1
|
| 312 |
+
)
|
| 313 |
available_slots = max_concurrent - active_claims
|
| 314 |
+
|
| 315 |
if available_slots <= 0:
|
| 316 |
return []
|
| 317 |
|
| 318 |
+
batch_size = max(0, int(batch_size))
|
| 319 |
take_count = min(batch_size, available_slots)
|
| 320 |
|
| 321 |
+
if take_count <= 0:
|
| 322 |
+
return []
|
| 323 |
+
|
| 324 |
eligible = []
|
| 325 |
for job in self.jobs.values():
|
| 326 |
if job["status"] != "queued":
|
| 327 |
continue
|
| 328 |
if job["platform"] != worker["environment"].get("platform"):
|
| 329 |
continue
|
| 330 |
+
if (
|
| 331 |
+
job["python_version"]
|
| 332 |
+
in worker["environment"].get("python_versions", [])
|
| 333 |
+
):
|
| 334 |
eligible.append(job)
|
| 335 |
|
| 336 |
if not eligible:
|
| 337 |
return []
|
| 338 |
|
|
|
|
| 339 |
eligible.sort(key=lambda j: j["submitted_at"])
|
| 340 |
|
|
|
|
| 341 |
claimed_jobs = []
|
| 342 |
for job in eligible[:take_count]:
|
| 343 |
job["status"] = "claimed"
|
| 344 |
job["claimed_by"] = worker_id
|
| 345 |
job["claimed_worker_url"] = worker["url"]
|
| 346 |
job["claimed_at"] = now
|
| 347 |
+
job["claim_deadline"] = (
|
| 348 |
+
now + job["timeout"] + self.settings.claim_timeout_buffer
|
| 349 |
+
)
|
| 350 |
claimed_jobs.append(self._public_job(job))
|
| 351 |
|
| 352 |
return claimed_jobs
|
| 353 |
|
| 354 |
+
# ------------------------------------------------------------------
|
| 355 |
+
# Result reporting
|
| 356 |
+
# ------------------------------------------------------------------
|
| 357 |
+
|
| 358 |
+
def report_result(
|
| 359 |
+
self, worker_id: int, url: str, result: ResultObject
|
| 360 |
+
) -> None:
|
| 361 |
+
callback_payload = None
|
| 362 |
+
|
| 363 |
with self.lock:
|
| 364 |
job = self.jobs.get(result.job_id)
|
| 365 |
if job is None:
|
| 366 |
raise KeyError("job not found")
|
| 367 |
+
|
| 368 |
+
if (
|
| 369 |
+
job.get("claimed_by") != worker_id
|
| 370 |
+
or job.get("claimed_worker_url") != url
|
| 371 |
+
):
|
| 372 |
+
raise PermissionError(
|
| 373 |
+
"job is not claimed by this worker instance"
|
| 374 |
+
)
|
| 375 |
|
| 376 |
now = self.clock()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 377 |
|
| 378 |
+
self._complete_job_locked(job, result, now)
|
| 379 |
+
|
| 380 |
+
callback_payload = self._collect_ready_callbacks_locked()
|
| 381 |
|
| 382 |
worker = self.workers.get(worker_id)
|
| 383 |
if worker is not None and worker["url"] == url:
|
| 384 |
worker["last_seen_at"] = now
|
| 385 |
|
| 386 |
+
self._dispatch_callbacks(callback_payload)
|
| 387 |
+
|
| 388 |
+
def report_results_batch(
|
| 389 |
+
self, worker_id: int, url: str, results: List[ResultObject]
|
| 390 |
+
) -> None:
|
| 391 |
+
callback_payload = None
|
| 392 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
with self.lock:
|
|
|
|
| 394 |
jobs_to_update = []
|
| 395 |
+
|
| 396 |
+
# Validate every item first; atomic semantics preserved.
|
| 397 |
for result in results:
|
| 398 |
job = self.jobs.get(result.job_id)
|
| 399 |
if job is None:
|
| 400 |
raise KeyError(f"job not found: {result.job_id}")
|
| 401 |
+
|
| 402 |
+
if (
|
| 403 |
+
job.get("claimed_by") != worker_id
|
| 404 |
+
or job.get("claimed_worker_url") != url
|
| 405 |
+
):
|
| 406 |
+
raise PermissionError(
|
| 407 |
+
f"job {result.job_id} is not claimed by this worker instance"
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
jobs_to_update.append((job, result))
|
| 411 |
|
|
|
|
| 412 |
now = self.clock()
|
| 413 |
+
|
| 414 |
for job, result in jobs_to_update:
|
| 415 |
+
self._complete_job_locked(job, result, now)
|
| 416 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 417 |
worker = self.workers.get(worker_id)
|
| 418 |
if worker is not None and worker["url"] == url:
|
| 419 |
worker["last_seen_at"] = now
|
| 420 |
|
| 421 |
+
callback_payload = self._collect_ready_callbacks_locked()
|
| 422 |
+
|
| 423 |
+
self._dispatch_callbacks(callback_payload)
|
| 424 |
+
|
| 425 |
+
def _complete_job_locked(
|
| 426 |
+
self, job: dict, result: ResultObject, now: float
|
| 427 |
+
) -> None:
|
| 428 |
+
job["status"] = "complete"
|
| 429 |
+
job["result"] = result.model_dump()
|
| 430 |
+
job["completed_at"] = now
|
| 431 |
+
job["claimed_by"] = None
|
| 432 |
+
job["claimed_worker_url"] = None
|
| 433 |
+
job["claimed_at"] = None
|
| 434 |
+
job["claim_deadline"] = None
|
| 435 |
+
|
| 436 |
+
self.total_completed += 1
|
| 437 |
+
|
| 438 |
+
# ------------------------------------------------------------------
|
| 439 |
+
# Worker lifecycle
|
| 440 |
+
# ------------------------------------------------------------------
|
| 441 |
+
|
| 442 |
def report_done(self, worker_id: int, url: str) -> List[str]:
|
| 443 |
+
callback_payload = None
|
| 444 |
+
|
| 445 |
with self.lock:
|
| 446 |
worker = self.workers.get(worker_id)
|
| 447 |
if worker is None:
|
| 448 |
return []
|
| 449 |
+
|
| 450 |
if worker["url"] != url:
|
| 451 |
return []
|
| 452 |
|
|
|
|
| 455 |
worker["last_seen_at"] = now
|
| 456 |
|
| 457 |
released = []
|
| 458 |
+
|
| 459 |
for job in list(self.jobs.values()):
|
| 460 |
+
if (
|
| 461 |
+
job["status"] == "claimed"
|
| 462 |
+
and job["claimed_by"] == worker_id
|
| 463 |
+
and job.get("claimed_worker_url") == url
|
| 464 |
+
):
|
| 465 |
+
self._abandon_claim_locked(
|
| 466 |
+
job, "worker reported done", now
|
| 467 |
+
)
|
| 468 |
released.append(job["job_id"])
|
| 469 |
+
|
| 470 |
+
callback_payload = self._collect_ready_callbacks_locked()
|
| 471 |
+
|
| 472 |
+
self._dispatch_callbacks(callback_payload)
|
| 473 |
+
return released
|
| 474 |
+
|
| 475 |
+
# ------------------------------------------------------------------
|
| 476 |
+
# Ordinary jobs
|
| 477 |
+
# ------------------------------------------------------------------
|
| 478 |
|
| 479 |
def submit_job(self, job_data: JobSubmission) -> str:
|
| 480 |
with self.lock:
|
| 481 |
job_id = job_data.job_id or generate_job_id()
|
| 482 |
+
|
| 483 |
if job_id in self.jobs:
|
| 484 |
raise ValueError("job_id already exists")
|
| 485 |
|
| 486 |
now = self.clock()
|
| 487 |
+
self.jobs[job_id] = self._build_job_dict(
|
| 488 |
+
job_id, job_data, now
|
| 489 |
+
)
|
| 490 |
self.total_submitted += 1
|
| 491 |
+
|
| 492 |
return job_id
|
| 493 |
|
| 494 |
+
def submit_jobs_batch(
|
| 495 |
+
self, jobs_data: List[JobSubmission]
|
| 496 |
+
) -> List[str]:
|
| 497 |
with self.lock:
|
| 498 |
now = self.clock()
|
| 499 |
job_ids = []
|
| 500 |
+
|
| 501 |
+
# First validate all explicit IDs so the operation doesn't
|
| 502 |
+
# partially submit due to a later duplicate.
|
| 503 |
+
requested_ids = set()
|
| 504 |
+
|
| 505 |
for job_data in jobs_data:
|
| 506 |
job_id = job_data.job_id or generate_job_id()
|
| 507 |
+
|
| 508 |
+
if job_data.job_id:
|
| 509 |
+
if job_id in self.jobs:
|
| 510 |
+
raise ValueError(
|
| 511 |
+
f"job_id already exists: {job_id}"
|
| 512 |
+
)
|
| 513 |
+
if job_id in requested_ids:
|
| 514 |
+
raise ValueError(
|
| 515 |
+
f"duplicate job_id in batch: {job_id}"
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
requested_ids.add(job_id)
|
| 519 |
+
|
| 520 |
+
# Build and commit all jobs.
|
| 521 |
+
for job_data in jobs_data:
|
| 522 |
+
job_id = job_data.job_id or generate_job_id()
|
| 523 |
+
|
| 524 |
+
# Extremely unlikely random collision; regenerate safely.
|
| 525 |
+
while job_id in self.jobs:
|
| 526 |
+
if job_data.job_id:
|
| 527 |
+
raise ValueError(
|
| 528 |
+
f"job_id already exists: {job_id}"
|
| 529 |
+
)
|
| 530 |
+
job_id = generate_job_id()
|
| 531 |
+
|
| 532 |
+
self.jobs[job_id] = self._build_job_dict(
|
| 533 |
+
job_id, job_data, now
|
| 534 |
+
)
|
| 535 |
self.total_submitted += 1
|
| 536 |
job_ids.append(job_id)
|
| 537 |
+
|
| 538 |
return job_ids
|
| 539 |
|
| 540 |
+
def _build_job_dict(
|
| 541 |
+
self, job_id: str, job_data: JobSubmission, now: float
|
| 542 |
+
) -> dict:
|
| 543 |
return {
|
| 544 |
"job_id": job_id,
|
| 545 |
"python_version": job_data.python_version,
|
|
|
|
| 565 |
def get_job(self, job_id: str):
|
| 566 |
with self.lock:
|
| 567 |
job = self.jobs.get(job_id)
|
| 568 |
+
|
| 569 |
if job is None:
|
| 570 |
return None, None
|
| 571 |
+
|
| 572 |
if job["status"] == "complete":
|
| 573 |
return "complete", job["result"]
|
| 574 |
+
|
| 575 |
matching = self._matching_worker_ids_locked(job)
|
| 576 |
+
|
| 577 |
return "pending", {
|
| 578 |
"retry_count": job["retry_count"],
|
| 579 |
"matching_worker_ids": matching,
|
| 580 |
+
"last_abandon_reason": job.get(
|
| 581 |
+
"last_abandon_reason"
|
| 582 |
+
),
|
| 583 |
"submitted_at": iso_from_ts(job["submitted_at"]),
|
| 584 |
}
|
| 585 |
|
| 586 |
+
# ------------------------------------------------------------------
|
| 587 |
+
# Logical verification request API
|
| 588 |
+
# ------------------------------------------------------------------
|
| 589 |
+
|
| 590 |
+
def submit_verification(
|
| 591 |
+
self, submission: VerificationSubmission
|
| 592 |
+
) -> dict:
|
| 593 |
+
with self.lock:
|
| 594 |
+
request_id = (
|
| 595 |
+
submission.request_id or generate_request_id()
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
if request_id in self.verifications:
|
| 599 |
+
raise ValueError("request_id already exists")
|
| 600 |
+
|
| 601 |
+
if not submission.jobs:
|
| 602 |
+
raise ValueError("verification request must contain at least one job")
|
| 603 |
+
|
| 604 |
+
# Create all ordinary coordinator jobs in the same lock.
|
| 605 |
+
now = self.clock()
|
| 606 |
+
job_ids = []
|
| 607 |
+
|
| 608 |
+
for job_data in submission.jobs:
|
| 609 |
+
job_id = job_data.job_id or generate_job_id()
|
| 610 |
+
|
| 611 |
+
if job_id in self.jobs:
|
| 612 |
+
raise ValueError(
|
| 613 |
+
f"job_id already exists: {job_id}"
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
job_record = self._build_job_dict(
|
| 617 |
+
job_id, job_data, now
|
| 618 |
+
)
|
| 619 |
+
self.jobs[job_id] = job_record
|
| 620 |
+
self.total_submitted += 1
|
| 621 |
+
job_ids.append(job_id)
|
| 622 |
+
|
| 623 |
+
self.verifications[request_id] = {
|
| 624 |
+
"request_id": request_id,
|
| 625 |
+
"job_ids": job_ids,
|
| 626 |
+
"submitted_at": now,
|
| 627 |
+
"completed_at": None,
|
| 628 |
+
"status": "pending",
|
| 629 |
+
"callback_url": submission.callback_url,
|
| 630 |
+
"callback_secret": submission.callback_secret,
|
| 631 |
+
"callback_status": "not_configured"
|
| 632 |
+
if not submission.callback_url
|
| 633 |
+
else "pending",
|
| 634 |
+
"callback_attempts": 0,
|
| 635 |
+
"callback_last_error": None,
|
| 636 |
+
}
|
| 637 |
+
|
| 638 |
+
self.total_verification_requests += 1
|
| 639 |
+
|
| 640 |
+
return self._verification_public_locked(
|
| 641 |
+
self.verifications[request_id]
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
def get_verification(self, request_id: str) -> Optional[dict]:
|
| 645 |
+
with self.lock:
|
| 646 |
+
verification = self.verifications.get(request_id)
|
| 647 |
+
|
| 648 |
+
if verification is None:
|
| 649 |
+
return None
|
| 650 |
+
|
| 651 |
+
return self._verification_public_locked(verification)
|
| 652 |
+
|
| 653 |
+
def _verification_result_locked(self, verification: dict) -> dict:
|
| 654 |
+
results = []
|
| 655 |
+
|
| 656 |
+
for job_id in verification["job_ids"]:
|
| 657 |
+
job = self.jobs.get(job_id)
|
| 658 |
+
|
| 659 |
+
if job is None:
|
| 660 |
+
results.append(
|
| 661 |
+
{
|
| 662 |
+
"job_id": job_id,
|
| 663 |
+
"status": "missing",
|
| 664 |
+
}
|
| 665 |
+
)
|
| 666 |
+
continue
|
| 667 |
+
|
| 668 |
+
item = {
|
| 669 |
+
"job_id": job_id,
|
| 670 |
+
"status": job["status"],
|
| 671 |
+
"python_version": job["python_version"],
|
| 672 |
+
"platform": job["platform"],
|
| 673 |
+
}
|
| 674 |
+
|
| 675 |
+
if job["status"] == "complete":
|
| 676 |
+
item["result"] = job.get("result")
|
| 677 |
+
|
| 678 |
+
results.append(item)
|
| 679 |
+
|
| 680 |
+
return {
|
| 681 |
+
"request_id": verification["request_id"],
|
| 682 |
+
"status": verification["status"],
|
| 683 |
+
"submitted_at": iso_from_ts(
|
| 684 |
+
verification["submitted_at"]
|
| 685 |
+
),
|
| 686 |
+
"completed_at": (
|
| 687 |
+
iso_from_ts(verification["completed_at"])
|
| 688 |
+
if verification.get("completed_at")
|
| 689 |
+
else None
|
| 690 |
+
),
|
| 691 |
+
"job_count": len(verification["job_ids"]),
|
| 692 |
+
"completed_job_count": sum(
|
| 693 |
+
1 for x in results if x["status"] == "complete"
|
| 694 |
+
),
|
| 695 |
+
"results": results,
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
def _verification_is_complete_locked(
|
| 699 |
+
self, verification: dict
|
| 700 |
+
) -> bool:
|
| 701 |
+
for job_id in verification["job_ids"]:
|
| 702 |
+
job = self.jobs.get(job_id)
|
| 703 |
+
|
| 704 |
+
# Missing is not considered complete.
|
| 705 |
+
if job is None or job["status"] != "complete":
|
| 706 |
+
return False
|
| 707 |
+
|
| 708 |
+
return True
|
| 709 |
+
|
| 710 |
+
def _finalize_ready_verifications_locked(self) -> None:
|
| 711 |
+
now = self.clock()
|
| 712 |
+
|
| 713 |
+
for verification in self.verifications.values():
|
| 714 |
+
if verification["status"] != "pending":
|
| 715 |
+
continue
|
| 716 |
+
|
| 717 |
+
if not self._verification_is_complete_locked(verification):
|
| 718 |
+
continue
|
| 719 |
+
|
| 720 |
+
verification["status"] = "complete"
|
| 721 |
+
verification["completed_at"] = now
|
| 722 |
+
|
| 723 |
+
def _collect_ready_callbacks_locked(self) -> List[dict]:
|
| 724 |
+
self._finalize_ready_verifications_locked()
|
| 725 |
+
|
| 726 |
+
callbacks = []
|
| 727 |
+
|
| 728 |
+
for verification in self.verifications.values():
|
| 729 |
+
if verification["status"] != "complete":
|
| 730 |
+
continue
|
| 731 |
+
|
| 732 |
+
callback_url = verification.get("callback_url")
|
| 733 |
+
if not callback_url:
|
| 734 |
+
continue
|
| 735 |
+
|
| 736 |
+
callback_status = verification.get(
|
| 737 |
+
"callback_status"
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
# Do not repeatedly dispatch successful callbacks.
|
| 741 |
+
if callback_status == "sent":
|
| 742 |
+
continue
|
| 743 |
+
|
| 744 |
+
# Only allow retries up to configured max.
|
| 745 |
+
if (
|
| 746 |
+
verification.get("callback_attempts", 0)
|
| 747 |
+
>= self.settings.callback_max_retries
|
| 748 |
+
):
|
| 749 |
+
continue
|
| 750 |
+
|
| 751 |
+
verification["callback_attempts"] += 1
|
| 752 |
+
|
| 753 |
+
callbacks.append(
|
| 754 |
+
{
|
| 755 |
+
"request_id": verification["request_id"],
|
| 756 |
+
"callback_url": callback_url,
|
| 757 |
+
"callback_secret": verification.get(
|
| 758 |
+
"callback_secret"
|
| 759 |
+
),
|
| 760 |
+
"attempt": verification[
|
| 761 |
+
"callback_attempts"
|
| 762 |
+
],
|
| 763 |
+
"payload": self._verification_result_locked(
|
| 764 |
+
verification
|
| 765 |
+
),
|
| 766 |
+
}
|
| 767 |
+
)
|
| 768 |
+
|
| 769 |
+
return callbacks
|
| 770 |
+
|
| 771 |
+
def mark_callback_result(
|
| 772 |
+
self,
|
| 773 |
+
request_id: str,
|
| 774 |
+
success: bool,
|
| 775 |
+
error: Optional[str] = None,
|
| 776 |
+
) -> None:
|
| 777 |
+
with self.lock:
|
| 778 |
+
verification = self.verifications.get(request_id)
|
| 779 |
+
|
| 780 |
+
if verification is None:
|
| 781 |
+
return
|
| 782 |
+
|
| 783 |
+
if success:
|
| 784 |
+
verification["callback_status"] = "sent"
|
| 785 |
+
verification["callback_last_error"] = None
|
| 786 |
+
self.total_callbacks_sent += 1
|
| 787 |
+
else:
|
| 788 |
+
verification["callback_status"] = "failed"
|
| 789 |
+
verification["callback_last_error"] = error
|
| 790 |
+
self.total_callback_failures += 1
|
| 791 |
+
|
| 792 |
+
def _verification_public_locked(
|
| 793 |
+
self, verification: dict
|
| 794 |
+
) -> dict:
|
| 795 |
+
result = self._verification_result_locked(
|
| 796 |
+
verification
|
| 797 |
+
)
|
| 798 |
+
|
| 799 |
+
result["callback_status"] = verification.get(
|
| 800 |
+
"callback_status"
|
| 801 |
+
)
|
| 802 |
+
result["callback_attempts"] = verification.get(
|
| 803 |
+
"callback_attempts", 0
|
| 804 |
+
)
|
| 805 |
+
result["callback_last_error"] = verification.get(
|
| 806 |
+
"callback_last_error"
|
| 807 |
+
)
|
| 808 |
+
|
| 809 |
+
return result
|
| 810 |
+
|
| 811 |
+
def _dispatch_callbacks(self, callbacks: Optional[List[dict]]) -> None:
|
| 812 |
+
if not callbacks:
|
| 813 |
+
return
|
| 814 |
+
|
| 815 |
+
for callback in callbacks:
|
| 816 |
+
thread = threading.Thread(
|
| 817 |
+
target=self._send_callback,
|
| 818 |
+
args=(callback,),
|
| 819 |
+
daemon=True,
|
| 820 |
+
)
|
| 821 |
+
thread.start()
|
| 822 |
+
|
| 823 |
+
def _send_callback(self, callback: dict) -> None:
|
| 824 |
+
request_id = callback["request_id"]
|
| 825 |
+
callback_url = callback["callback_url"]
|
| 826 |
+
callback_secret = callback.get("callback_secret")
|
| 827 |
+
payload = callback["payload"]
|
| 828 |
+
|
| 829 |
+
body = json.dumps(payload).encode("utf-8")
|
| 830 |
+
|
| 831 |
+
headers = {
|
| 832 |
+
"Content-Type": "application/json",
|
| 833 |
+
"User-Agent": "dataset-verification-coordinator/1",
|
| 834 |
+
"X-Verification-Request-ID": request_id,
|
| 835 |
+
}
|
| 836 |
+
|
| 837 |
+
if callback_secret:
|
| 838 |
+
headers["X-Verification-Callback-Secret"] = callback_secret
|
| 839 |
+
|
| 840 |
+
request = urllib.request.Request(
|
| 841 |
+
callback_url,
|
| 842 |
+
data=body,
|
| 843 |
+
headers=headers,
|
| 844 |
+
method="POST",
|
| 845 |
+
)
|
| 846 |
+
|
| 847 |
+
try:
|
| 848 |
+
with urllib.request.urlopen(
|
| 849 |
+
request,
|
| 850 |
+
timeout=self.settings.callback_timeout_seconds,
|
| 851 |
+
) as response:
|
| 852 |
+
if response.status < 200 or response.status >= 300:
|
| 853 |
+
raise RuntimeError(
|
| 854 |
+
f"callback returned HTTP {response.status}"
|
| 855 |
+
)
|
| 856 |
+
|
| 857 |
+
self.mark_callback_result(
|
| 858 |
+
request_id=request_id,
|
| 859 |
+
success=True,
|
| 860 |
+
)
|
| 861 |
+
|
| 862 |
+
logger.info(
|
| 863 |
+
f"Verification callback delivered: {request_id}"
|
| 864 |
+
)
|
| 865 |
+
|
| 866 |
+
except Exception as exc:
|
| 867 |
+
logger.warning(
|
| 868 |
+
f"Verification callback failed for {request_id}: {exc}"
|
| 869 |
+
)
|
| 870 |
+
self.mark_callback_result(
|
| 871 |
+
request_id=request_id,
|
| 872 |
+
success=False,
|
| 873 |
+
error=str(exc),
|
| 874 |
+
)
|
| 875 |
+
|
| 876 |
+
# ------------------------------------------------------------------
|
| 877 |
+
# Admin / status
|
| 878 |
+
# ------------------------------------------------------------------
|
| 879 |
+
|
| 880 |
def list_workers(self) -> List[dict]:
|
| 881 |
with self.lock:
|
| 882 |
now = self.clock()
|
| 883 |
+
return [
|
| 884 |
+
self._worker_public_locked(
|
| 885 |
+
worker["worker_id"], now
|
| 886 |
+
)
|
| 887 |
+
for worker in self.workers.values()
|
| 888 |
+
]
|
| 889 |
|
| 890 |
def list_jobs(self) -> List[dict]:
|
| 891 |
with self.lock:
|
| 892 |
result = []
|
| 893 |
+
|
| 894 |
for job in self.jobs.values():
|
| 895 |
item = {
|
| 896 |
"job_id": job["job_id"],
|
| 897 |
"status": job["status"],
|
| 898 |
+
"submitted_at": iso_from_ts(
|
| 899 |
+
job["submitted_at"]
|
| 900 |
+
),
|
| 901 |
"python_version": job["python_version"],
|
| 902 |
"platform": job["platform"],
|
| 903 |
"retry_count": job["retry_count"],
|
| 904 |
"claimed_by": job.get("claimed_by"),
|
| 905 |
+
"claim_deadline": (
|
| 906 |
+
iso_from_ts(job["claim_deadline"])
|
| 907 |
+
if job.get("claim_deadline")
|
| 908 |
+
else None
|
| 909 |
+
),
|
| 910 |
+
"matching_worker_ids": self._matching_worker_ids_locked(
|
| 911 |
+
job
|
| 912 |
+
),
|
| 913 |
+
"last_abandon_reason": job.get(
|
| 914 |
+
"last_abandon_reason"
|
| 915 |
+
),
|
| 916 |
}
|
| 917 |
+
|
| 918 |
+
if (
|
| 919 |
+
job["status"] == "complete"
|
| 920 |
+
and job.get("result")
|
| 921 |
+
):
|
| 922 |
item["result"] = job["result"]
|
| 923 |
+
|
| 924 |
result.append(item)
|
| 925 |
+
|
| 926 |
return result
|
| 927 |
|
| 928 |
+
def list_verifications(self) -> List[dict]:
|
| 929 |
+
with self.lock:
|
| 930 |
+
return [
|
| 931 |
+
self._verification_public_locked(v)
|
| 932 |
+
for v in self.verifications.values()
|
| 933 |
+
]
|
| 934 |
+
|
| 935 |
def get_status(self) -> dict:
|
| 936 |
with self.lock:
|
| 937 |
now = self.clock()
|
| 938 |
+
|
| 939 |
+
queued = sum(
|
| 940 |
+
1
|
| 941 |
+
for j in self.jobs.values()
|
| 942 |
+
if j["status"] == "queued"
|
| 943 |
+
)
|
| 944 |
+
claimed = sum(
|
| 945 |
+
1
|
| 946 |
+
for j in self.jobs.values()
|
| 947 |
+
if j["status"] == "claimed"
|
| 948 |
+
)
|
| 949 |
+
complete = sum(
|
| 950 |
+
1
|
| 951 |
+
for j in self.jobs.values()
|
| 952 |
+
if j["status"] == "complete"
|
| 953 |
+
)
|
| 954 |
+
|
| 955 |
claimed_by_worker = {}
|
| 956 |
+
|
| 957 |
for j in self.jobs.values():
|
| 958 |
if j["status"] == "claimed":
|
| 959 |
wid = j.get("claimed_by")
|
| 960 |
if wid is not None:
|
| 961 |
+
claimed_by_worker[wid] = (
|
| 962 |
+
claimed_by_worker.get(wid, 0) + 1
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
workers = []
|
| 966 |
+
|
| 967 |
+
for wid, worker in self.workers.items():
|
| 968 |
+
workers.append(
|
| 969 |
+
{
|
| 970 |
+
"worker_id": wid,
|
| 971 |
+
"url": worker["url"],
|
| 972 |
+
"platform": worker["environment"].get(
|
| 973 |
+
"platform"
|
| 974 |
+
),
|
| 975 |
+
"os_version": worker["environment"].get(
|
| 976 |
+
"os_version"
|
| 977 |
+
),
|
| 978 |
+
"python_versions": worker[
|
| 979 |
+
"environment"
|
| 980 |
+
].get("python_versions", []),
|
| 981 |
+
"status": self._status_locked(
|
| 982 |
+
wid, now
|
| 983 |
+
),
|
| 984 |
+
"claimed_jobs": claimed_by_worker.get(
|
| 985 |
+
wid, 0
|
| 986 |
+
),
|
| 987 |
+
"max_concurrent_jobs": worker[
|
| 988 |
+
"environment"
|
| 989 |
+
].get("max_concurrent_jobs", 1),
|
| 990 |
+
"last_seen_at": iso_from_ts(
|
| 991 |
+
worker["last_seen_at"]
|
| 992 |
+
),
|
| 993 |
+
"registered_at": iso_from_ts(
|
| 994 |
+
worker["registered_at"]
|
| 995 |
+
),
|
| 996 |
+
}
|
| 997 |
+
)
|
| 998 |
+
|
| 999 |
+
self._finalize_ready_verifications_locked()
|
| 1000 |
+
|
| 1001 |
+
verification_counts = {
|
| 1002 |
+
"pending": sum(
|
| 1003 |
+
1
|
| 1004 |
+
for v in self.verifications.values()
|
| 1005 |
+
if v["status"] == "pending"
|
| 1006 |
+
),
|
| 1007 |
+
"complete": sum(
|
| 1008 |
+
1
|
| 1009 |
+
for v in self.verifications.values()
|
| 1010 |
+
if v["status"] == "complete"
|
| 1011 |
+
),
|
| 1012 |
+
}
|
| 1013 |
+
|
| 1014 |
return {
|
| 1015 |
"uptime_seconds": now - self.start_time,
|
| 1016 |
"total_submitted": self.total_submitted,
|
| 1017 |
"total_completed": self.total_completed,
|
| 1018 |
+
"jobs_by_status": {
|
| 1019 |
+
"queued": queued,
|
| 1020 |
+
"claimed": claimed,
|
| 1021 |
+
"complete": complete,
|
| 1022 |
+
},
|
| 1023 |
"workers": workers,
|
| 1024 |
"claimed_by_worker": claimed_by_worker,
|
| 1025 |
+
"verification_requests": {
|
| 1026 |
+
"total": self.total_verification_requests,
|
| 1027 |
+
"by_status": verification_counts,
|
| 1028 |
+
},
|
| 1029 |
+
"callbacks": {
|
| 1030 |
+
"sent": self.total_callbacks_sent,
|
| 1031 |
+
"failures": self.total_callback_failures,
|
| 1032 |
+
},
|
| 1033 |
}
|
| 1034 |
|
| 1035 |
+
# ------------------------------------------------------------------
|
| 1036 |
+
# Background cleanup/retry handling
|
| 1037 |
+
# ------------------------------------------------------------------
|
| 1038 |
+
|
| 1039 |
def process_expired_claims(self) -> None:
|
| 1040 |
+
callback_payload = None
|
| 1041 |
+
|
| 1042 |
with self.lock:
|
| 1043 |
now = self.clock()
|
| 1044 |
+
|
| 1045 |
for job in list(self.jobs.values()):
|
| 1046 |
+
if (
|
| 1047 |
+
job["status"] == "claimed"
|
| 1048 |
+
and job.get("claim_deadline")
|
| 1049 |
+
and now >= job["claim_deadline"]
|
| 1050 |
+
):
|
| 1051 |
+
self._abandon_claim_locked(
|
| 1052 |
+
job, "claim timeout", now
|
| 1053 |
+
)
|
| 1054 |
+
|
| 1055 |
+
callback_payload = self._collect_ready_callbacks_locked()
|
| 1056 |
+
|
| 1057 |
+
self._dispatch_callbacks(callback_payload)
|
| 1058 |
|
| 1059 |
def cleanup_completed(self) -> None:
|
| 1060 |
with self.lock:
|
| 1061 |
now = self.clock()
|
| 1062 |
+
|
| 1063 |
for job_id in list(self.jobs):
|
| 1064 |
job = self.jobs[job_id]
|
| 1065 |
+
|
| 1066 |
+
if (
|
| 1067 |
+
job["status"] == "complete"
|
| 1068 |
+
and job.get("completed_at")
|
| 1069 |
+
and (
|
| 1070 |
+
now - job["completed_at"]
|
| 1071 |
+
) > self.settings.retention_seconds
|
| 1072 |
+
):
|
| 1073 |
del self.jobs[job_id]
|
| 1074 |
|
| 1075 |
+
for request_id in list(self.verifications):
|
| 1076 |
+
verification = self.verifications[request_id]
|
| 1077 |
+
|
| 1078 |
+
reference_ts = (
|
| 1079 |
+
verification.get("completed_at")
|
| 1080 |
+
or verification.get("submitted_at")
|
| 1081 |
+
)
|
| 1082 |
+
|
| 1083 |
+
if (
|
| 1084 |
+
reference_ts
|
| 1085 |
+
and (
|
| 1086 |
+
now - reference_ts
|
| 1087 |
+
)
|
| 1088 |
+
> self.settings.verification_retention_seconds
|
| 1089 |
+
):
|
| 1090 |
+
del self.verifications[request_id]
|
| 1091 |
+
|
| 1092 |
+
def _abandon_claim_locked(
|
| 1093 |
+
self, job: dict, reason: str, now: float
|
| 1094 |
+
) -> None:
|
| 1095 |
+
if (
|
| 1096 |
+
job.get("retry_count", 0)
|
| 1097 |
+
>= self.settings.max_retries
|
| 1098 |
+
):
|
| 1099 |
job["status"] = "complete"
|
| 1100 |
job["result"] = {
|
| 1101 |
"job_id": job["job_id"],
|
|
|
|
| 1104 |
"exit_code": 1,
|
| 1105 |
"timed_out": False,
|
| 1106 |
"category": "infra_failure",
|
| 1107 |
+
"failure_reason": (
|
| 1108 |
+
f"job abandoned more than "
|
| 1109 |
+
f"{self.settings.max_retries} times "
|
| 1110 |
+
f"({reason})"
|
| 1111 |
+
),
|
| 1112 |
"network_activity_detected": None,
|
| 1113 |
"filesystem_state": None,
|
| 1114 |
}
|
|
|
|
| 1117 |
job["claimed_worker_url"] = None
|
| 1118 |
job["claimed_at"] = None
|
| 1119 |
job["claim_deadline"] = None
|
| 1120 |
+
|
| 1121 |
self.total_completed += 1
|
| 1122 |
+
|
| 1123 |
else:
|
| 1124 |
+
job["retry_count"] = (
|
| 1125 |
+
job.get("retry_count", 0) + 1
|
| 1126 |
+
)
|
| 1127 |
job["status"] = "queued"
|
| 1128 |
job["claimed_by"] = None
|
| 1129 |
job["claimed_worker_url"] = None
|
|
|
|
| 1131 |
job["claim_deadline"] = None
|
| 1132 |
job["last_abandon_reason"] = reason
|
| 1133 |
|
| 1134 |
+
# ------------------------------------------------------------------
|
| 1135 |
+
# Worker matching/status
|
| 1136 |
+
# ------------------------------------------------------------------
|
| 1137 |
+
|
| 1138 |
+
def _matching_worker_ids_locked(
|
| 1139 |
+
self, job: dict
|
| 1140 |
+
) -> List[int]:
|
| 1141 |
matching = []
|
| 1142 |
+
|
| 1143 |
for worker_id, worker in self.workers.items():
|
| 1144 |
+
if (
|
| 1145 |
+
job.get("platform")
|
| 1146 |
+
!= worker["environment"].get("platform")
|
| 1147 |
+
):
|
| 1148 |
continue
|
| 1149 |
+
|
| 1150 |
+
if (
|
| 1151 |
+
job.get("python_version")
|
| 1152 |
+
in worker["environment"].get(
|
| 1153 |
+
"python_versions", []
|
| 1154 |
+
)
|
| 1155 |
+
):
|
| 1156 |
matching.append(worker_id)
|
| 1157 |
+
|
| 1158 |
return matching
|
| 1159 |
|
| 1160 |
+
def _status_locked(
|
| 1161 |
+
self, worker_id: int, now: float
|
| 1162 |
+
) -> str:
|
| 1163 |
worker = self.workers.get(worker_id)
|
| 1164 |
+
|
| 1165 |
if worker is None:
|
| 1166 |
return "unresponsive"
|
| 1167 |
+
|
| 1168 |
+
if worker.get("reported_done"):
|
| 1169 |
+
return "unresponsive"
|
| 1170 |
+
|
| 1171 |
+
# IMPORTANT FIX:
|
| 1172 |
+
# Check the previously recorded heartbeat timestamp before
|
| 1173 |
+
# comparing it. Poll/register requests themselves refresh it.
|
| 1174 |
+
if self._worker_is_stale_locked(worker, now):
|
| 1175 |
return "unresponsive"
|
| 1176 |
+
|
| 1177 |
for job in self.jobs.values():
|
| 1178 |
+
if (
|
| 1179 |
+
job["status"] == "claimed"
|
| 1180 |
+
and job.get("claimed_by") == worker_id
|
| 1181 |
+
and job.get("claimed_worker_url")
|
| 1182 |
+
== worker["url"]
|
| 1183 |
+
):
|
| 1184 |
return "busy"
|
| 1185 |
+
|
| 1186 |
return "idle"
|
| 1187 |
|
| 1188 |
+
def _worker_public_locked(
|
| 1189 |
+
self, worker_id: int, now: float
|
| 1190 |
+
) -> dict:
|
| 1191 |
worker = self.workers[worker_id]
|
| 1192 |
+
|
| 1193 |
return {
|
| 1194 |
"worker_id": worker["worker_id"],
|
| 1195 |
"url": worker["url"],
|
| 1196 |
"environment": worker["environment"],
|
| 1197 |
+
"registered_at": iso_from_ts(
|
| 1198 |
+
worker["registered_at"]
|
| 1199 |
+
),
|
| 1200 |
+
"last_seen_at": iso_from_ts(
|
| 1201 |
+
worker["last_seen_at"]
|
| 1202 |
+
),
|
| 1203 |
+
"status": self._status_locked(
|
| 1204 |
+
worker_id, now
|
| 1205 |
+
),
|
| 1206 |
+
"stale": self._worker_is_stale_locked(
|
| 1207 |
+
worker, now
|
| 1208 |
+
),
|
| 1209 |
}
|
| 1210 |
|
| 1211 |
@staticmethod
|
|
|
|
| 1223 |
}
|
| 1224 |
|
| 1225 |
|
| 1226 |
+
# ==================== GLOBAL STORE / BACKGROUND LOOP ====================
|
| 1227 |
+
|
| 1228 |
settings = Settings()
|
| 1229 |
store = MemoryStore(settings)
|
| 1230 |
|
| 1231 |
+
|
| 1232 |
def _background_loop():
|
| 1233 |
while True:
|
| 1234 |
time.sleep(1)
|
| 1235 |
+
try:
|
| 1236 |
+
store.process_expired_claims()
|
| 1237 |
+
except Exception:
|
| 1238 |
+
logger.exception("Error processing expired claims")
|
| 1239 |
+
|
| 1240 |
+
try:
|
| 1241 |
+
store.cleanup_completed()
|
| 1242 |
+
except Exception:
|
| 1243 |
+
logger.exception("Error cleaning up completed data")
|
| 1244 |
+
|
| 1245 |
+
|
| 1246 |
+
threading.Thread(
|
| 1247 |
+
target=_background_loop,
|
| 1248 |
+
daemon=True,
|
| 1249 |
+
name="dataset-verification-background",
|
| 1250 |
+
).start()
|
| 1251 |
|
|
|
|
| 1252 |
|
| 1253 |
+
# ==================== API ROUTER ====================
|
| 1254 |
+
|
| 1255 |
router = APIRouter()
|
| 1256 |
security = HTTPBearer(auto_error=False)
|
| 1257 |
|
| 1258 |
+
|
| 1259 |
+
def worker_auth(
|
| 1260 |
+
credentials: HTTPAuthorizationCredentials = Depends(security),
|
| 1261 |
+
):
|
| 1262 |
expected = settings.github_shared_secret
|
|
|
|
|
|
|
|
|
|
| 1263 |
|
| 1264 |
+
if (
|
| 1265 |
+
not expected
|
| 1266 |
+
or not credentials
|
| 1267 |
+
or credentials.scheme.lower() != "bearer"
|
| 1268 |
+
or not secrets.compare_digest(
|
| 1269 |
+
credentials.credentials.encode(),
|
| 1270 |
+
expected.encode(),
|
| 1271 |
+
)
|
| 1272 |
+
):
|
| 1273 |
+
raise HTTPException(
|
| 1274 |
+
status_code=401,
|
| 1275 |
+
detail="Unauthorized",
|
| 1276 |
+
)
|
| 1277 |
+
|
| 1278 |
+
|
| 1279 |
+
def desktop_auth(
|
| 1280 |
+
credentials: HTTPAuthorizationCredentials = Depends(security),
|
| 1281 |
+
):
|
| 1282 |
expected = settings.desktop_api_key
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1283 |
|
| 1284 |
+
if (
|
| 1285 |
+
not expected
|
| 1286 |
+
or not credentials
|
| 1287 |
+
or credentials.scheme.lower() != "bearer"
|
| 1288 |
+
or not secrets.compare_digest(
|
| 1289 |
+
credentials.credentials.encode(),
|
| 1290 |
+
expected.encode(),
|
| 1291 |
+
)
|
| 1292 |
+
):
|
| 1293 |
+
raise HTTPException(
|
| 1294 |
+
status_code=401,
|
| 1295 |
+
detail="Unauthorized",
|
| 1296 |
+
)
|
| 1297 |
+
|
| 1298 |
+
|
| 1299 |
+
# ==================== V1 ENDPOINTS (PRESERVED) ====================
|
| 1300 |
+
|
| 1301 |
+
@router.post(
|
| 1302 |
+
"/worker/register",
|
| 1303 |
+
dependencies=[Depends(worker_auth)],
|
| 1304 |
+
)
|
| 1305 |
def worker_register(body: WorkerRegisterRequest):
|
| 1306 |
+
return store.register_worker(
|
| 1307 |
+
body.worker_id,
|
| 1308 |
+
body.url,
|
| 1309 |
+
body.environment.model_dump(),
|
| 1310 |
+
)
|
| 1311 |
+
|
| 1312 |
|
| 1313 |
+
@router.post(
|
| 1314 |
+
"/worker/poll",
|
| 1315 |
+
dependencies=[Depends(worker_auth)],
|
| 1316 |
+
)
|
| 1317 |
def worker_poll(body: PollRequest):
|
| 1318 |
try:
|
| 1319 |
+
response = store.poll_job(
|
| 1320 |
+
body.worker_id,
|
| 1321 |
+
body.url,
|
| 1322 |
+
)
|
| 1323 |
+
|
| 1324 |
if response is None:
|
| 1325 |
return {"job": None}
|
| 1326 |
+
|
| 1327 |
if response.get("shutdown"):
|
| 1328 |
return response
|
| 1329 |
+
|
| 1330 |
return {"job": response}
|
| 1331 |
+
|
| 1332 |
except KeyError:
|
| 1333 |
+
raise HTTPException(
|
| 1334 |
+
status_code=404,
|
| 1335 |
+
detail="Worker not registered",
|
| 1336 |
+
)
|
| 1337 |
+
|
| 1338 |
|
| 1339 |
+
@router.post(
|
| 1340 |
+
"/worker/result",
|
| 1341 |
+
dependencies=[Depends(worker_auth)],
|
| 1342 |
+
)
|
| 1343 |
def worker_result(
|
| 1344 |
worker_id: int = Query(...),
|
| 1345 |
url: str = Query(...),
|
| 1346 |
result: ResultObject = Body(...),
|
| 1347 |
):
|
| 1348 |
try:
|
| 1349 |
+
store.report_result(
|
| 1350 |
+
worker_id,
|
| 1351 |
+
url,
|
| 1352 |
+
result,
|
| 1353 |
+
)
|
| 1354 |
+
|
| 1355 |
+
return {
|
| 1356 |
+
"status": "complete",
|
| 1357 |
+
"job_id": result.job_id,
|
| 1358 |
+
}
|
| 1359 |
+
|
| 1360 |
except KeyError:
|
| 1361 |
+
raise HTTPException(
|
| 1362 |
+
status_code=404,
|
| 1363 |
+
detail="Job not found",
|
| 1364 |
+
)
|
| 1365 |
+
|
| 1366 |
except PermissionError:
|
| 1367 |
+
raise HTTPException(
|
| 1368 |
+
status_code=409,
|
| 1369 |
+
detail="Job not claimed by this worker",
|
| 1370 |
+
)
|
| 1371 |
+
|
| 1372 |
|
| 1373 |
+
@router.post(
|
| 1374 |
+
"/worker/done",
|
| 1375 |
+
dependencies=[Depends(worker_auth)],
|
| 1376 |
+
)
|
| 1377 |
def worker_done(body: DoneRequest):
|
| 1378 |
+
released = store.report_done(
|
| 1379 |
+
body.worker_id,
|
| 1380 |
+
body.url,
|
| 1381 |
+
)
|
| 1382 |
+
|
| 1383 |
+
return {
|
| 1384 |
+
"released_job_ids": released
|
| 1385 |
+
}
|
| 1386 |
+
|
| 1387 |
|
| 1388 |
+
@router.post(
|
| 1389 |
+
"/desktop/job",
|
| 1390 |
+
dependencies=[Depends(desktop_auth)],
|
| 1391 |
+
)
|
| 1392 |
def desktop_submit_job(body: JobSubmission):
|
| 1393 |
try:
|
| 1394 |
job_id = store.submit_job(body)
|
|
|
|
|
|
|
|
|
|
| 1395 |
|
| 1396 |
+
return {
|
| 1397 |
+
"job_id": job_id,
|
| 1398 |
+
"status": "queued",
|
| 1399 |
+
}
|
| 1400 |
+
|
| 1401 |
+
except ValueError:
|
| 1402 |
+
raise HTTPException(
|
| 1403 |
+
status_code=409,
|
| 1404 |
+
detail="job_id already exists",
|
| 1405 |
+
)
|
| 1406 |
+
|
| 1407 |
+
|
| 1408 |
+
@router.post(
|
| 1409 |
+
"/desktop/jobs",
|
| 1410 |
+
dependencies=[Depends(desktop_auth)],
|
| 1411 |
+
)
|
| 1412 |
+
def desktop_submit_jobs_batch(
|
| 1413 |
+
body: JobBatchSubmission,
|
| 1414 |
+
):
|
| 1415 |
try:
|
| 1416 |
+
job_ids = store.submit_jobs_batch(
|
| 1417 |
+
body.jobs
|
| 1418 |
+
)
|
| 1419 |
+
|
| 1420 |
+
return {
|
| 1421 |
+
"job_ids": job_ids,
|
| 1422 |
+
"status": "queued",
|
| 1423 |
+
}
|
| 1424 |
+
|
| 1425 |
except ValueError as e:
|
| 1426 |
+
raise HTTPException(
|
| 1427 |
+
status_code=409,
|
| 1428 |
+
detail=str(e),
|
| 1429 |
+
)
|
| 1430 |
+
|
| 1431 |
|
| 1432 |
+
@router.get(
|
| 1433 |
+
"/desktop/job/{job_id}",
|
| 1434 |
+
dependencies=[Depends(desktop_auth)],
|
| 1435 |
+
)
|
| 1436 |
def desktop_get_result(job_id: str):
|
| 1437 |
status, data = store.get_job(job_id)
|
| 1438 |
+
|
| 1439 |
if status is None:
|
| 1440 |
+
raise HTTPException(
|
| 1441 |
+
status_code=404,
|
| 1442 |
+
detail="Job not found",
|
| 1443 |
+
)
|
| 1444 |
+
|
| 1445 |
if status == "complete":
|
| 1446 |
+
return {
|
| 1447 |
+
"status": "complete",
|
| 1448 |
+
"result": data,
|
| 1449 |
+
}
|
| 1450 |
+
|
| 1451 |
+
return {
|
| 1452 |
+
"status": "pending",
|
| 1453 |
+
**data,
|
| 1454 |
+
}
|
| 1455 |
+
|
| 1456 |
|
| 1457 |
+
@router.get(
|
| 1458 |
+
"/desktop/workers",
|
| 1459 |
+
dependencies=[Depends(desktop_auth)],
|
| 1460 |
+
)
|
| 1461 |
def desktop_list_workers():
|
| 1462 |
return store.list_workers()
|
| 1463 |
|
| 1464 |
+
|
| 1465 |
+
@router.get(
|
| 1466 |
+
"/desktop/jobs",
|
| 1467 |
+
dependencies=[Depends(desktop_auth)],
|
| 1468 |
+
)
|
| 1469 |
def desktop_list_jobs():
|
| 1470 |
return store.list_jobs()
|
| 1471 |
|
| 1472 |
+
|
| 1473 |
+
@router.get(
|
| 1474 |
+
"/desktop/status",
|
| 1475 |
+
dependencies=[Depends(desktop_auth)],
|
| 1476 |
+
)
|
| 1477 |
def desktop_status():
|
| 1478 |
return store.get_status()
|
| 1479 |
|
| 1480 |
|
| 1481 |
+
# ==================== V2 ENDPOINTS (PRESERVED) ====================
|
| 1482 |
|
| 1483 |
+
@router.post(
|
| 1484 |
+
"/worker/jobs/batch",
|
| 1485 |
+
dependencies=[Depends(worker_auth)],
|
| 1486 |
+
)
|
| 1487 |
+
def worker_poll_batch(
|
| 1488 |
+
body: WorkerBatchPollRequest,
|
| 1489 |
+
):
|
| 1490 |
try:
|
| 1491 |
+
jobs = store.poll_jobs_batch(
|
| 1492 |
+
body.worker_id,
|
| 1493 |
+
body.url,
|
| 1494 |
+
body.batch_size,
|
| 1495 |
+
)
|
| 1496 |
+
|
| 1497 |
+
if (
|
| 1498 |
+
jobs
|
| 1499 |
+
and isinstance(jobs[0], dict)
|
| 1500 |
+
and jobs[0].get("shutdown")
|
| 1501 |
+
):
|
| 1502 |
+
return jobs[0]
|
| 1503 |
+
|
| 1504 |
return {"jobs": jobs}
|
| 1505 |
+
|
| 1506 |
except KeyError:
|
| 1507 |
+
raise HTTPException(
|
| 1508 |
+
status_code=404,
|
| 1509 |
+
detail="Worker not registered",
|
| 1510 |
+
)
|
| 1511 |
+
|
| 1512 |
+
|
| 1513 |
+
@router.post(
|
| 1514 |
+
"/worker/results/batch",
|
| 1515 |
+
dependencies=[Depends(worker_auth)],
|
| 1516 |
+
)
|
| 1517 |
+
def worker_results_batch(
|
| 1518 |
+
body: WorkerBatchResultRequest,
|
| 1519 |
+
):
|
| 1520 |
+
try:
|
| 1521 |
+
store.report_results_batch(
|
| 1522 |
+
body.worker_id,
|
| 1523 |
+
body.url,
|
| 1524 |
+
body.results,
|
| 1525 |
+
)
|
| 1526 |
+
|
| 1527 |
+
job_ids = [
|
| 1528 |
+
r.job_id for r in body.results
|
| 1529 |
+
]
|
| 1530 |
|
| 1531 |
+
return {
|
| 1532 |
+
"status": "complete",
|
| 1533 |
+
"job_ids": job_ids,
|
| 1534 |
+
}
|
| 1535 |
+
|
| 1536 |
+
except KeyError as e:
|
| 1537 |
+
raise HTTPException(
|
| 1538 |
+
status_code=404,
|
| 1539 |
+
detail=str(e),
|
| 1540 |
+
)
|
| 1541 |
+
|
| 1542 |
+
except PermissionError as e:
|
| 1543 |
+
raise HTTPException(
|
| 1544 |
+
status_code=409,
|
| 1545 |
+
detail=str(e),
|
| 1546 |
+
)
|
| 1547 |
|
| 1548 |
+
|
| 1549 |
+
# ==================== NEW LOGICAL VERIFICATION API ====================
|
| 1550 |
+
|
| 1551 |
+
@router.post(
|
| 1552 |
+
"/desktop/verification",
|
| 1553 |
+
dependencies=[Depends(desktop_auth)],
|
| 1554 |
+
)
|
| 1555 |
+
def desktop_submit_verification(
|
| 1556 |
+
body: VerificationSubmission,
|
| 1557 |
+
):
|
| 1558 |
"""
|
| 1559 |
+
Additive logical verification endpoint.
|
| 1560 |
+
|
| 1561 |
+
This does NOT replace /desktop/jobs.
|
| 1562 |
+
|
| 1563 |
+
One logical verification request can contain many ordinary coordinator
|
| 1564 |
+
jobs. The coordinator tracks them together and exposes one request_id.
|
| 1565 |
+
When all underlying jobs complete, the request becomes complete.
|
| 1566 |
+
|
| 1567 |
+
Optional callback:
|
| 1568 |
+
callback_url
|
| 1569 |
+
callback_secret
|
| 1570 |
+
|
| 1571 |
+
The callback is POSTed as JSON and includes:
|
| 1572 |
+
X-Verification-Request-ID
|
| 1573 |
+
X-Verification-Callback-Secret (when configured)
|
| 1574 |
"""
|
| 1575 |
try:
|
| 1576 |
+
return store.submit_verification(body)
|
| 1577 |
+
|
| 1578 |
+
except ValueError as e:
|
| 1579 |
+
raise HTTPException(
|
| 1580 |
+
status_code=409,
|
| 1581 |
+
detail=str(e),
|
| 1582 |
+
)
|
| 1583 |
+
|
| 1584 |
+
|
| 1585 |
+
@router.get(
|
| 1586 |
+
"/desktop/verification/{request_id}",
|
| 1587 |
+
dependencies=[Depends(desktop_auth)],
|
| 1588 |
+
)
|
| 1589 |
+
def desktop_get_verification(request_id: str):
|
| 1590 |
+
"""
|
| 1591 |
+
Poll one logical verification request.
|
| 1592 |
+
|
| 1593 |
+
This lets the desktop client/plugin either:
|
| 1594 |
+
1. submit once and poll this endpoint, or
|
| 1595 |
+
2. submit once with callback_url and receive the POST asynchronously.
|
| 1596 |
+
"""
|
| 1597 |
+
result = store.get_verification(request_id)
|
| 1598 |
+
|
| 1599 |
+
if result is None:
|
| 1600 |
+
raise HTTPException(
|
| 1601 |
+
status_code=404,
|
| 1602 |
+
detail="Verification request not found",
|
| 1603 |
+
)
|
| 1604 |
+
|
| 1605 |
+
return result
|
| 1606 |
+
|
| 1607 |
+
|
| 1608 |
+
@router.get(
|
| 1609 |
+
"/desktop/verifications",
|
| 1610 |
+
dependencies=[Depends(desktop_auth)],
|
| 1611 |
+
)
|
| 1612 |
+
def desktop_list_verifications():
|
| 1613 |
+
"""
|
| 1614 |
+
Administrative visibility into logical verification requests.
|
| 1615 |
+
"""
|
| 1616 |
+
return store.list_verifications()
|
| 1617 |
+
|
| 1618 |
+
|
| 1619 |
+
@router.post(
|
| 1620 |
+
"/desktop/verification/{request_id}/callback",
|
| 1621 |
+
dependencies=[Depends(desktop_auth)],
|
| 1622 |
+
)
|
| 1623 |
+
def desktop_set_verification_callback(
|
| 1624 |
+
request_id: str,
|
| 1625 |
+
body: VerificationCallbackConfig,
|
| 1626 |
+
):
|
| 1627 |
+
"""
|
| 1628 |
+
Optional fallback for callers that submit without a callback and want
|
| 1629 |
+
to attach one later.
|
| 1630 |
+
|
| 1631 |
+
If the logical verification is already complete, the callback dispatch
|
| 1632 |
+
is attempted immediately.
|
| 1633 |
+
"""
|
| 1634 |
+
callback_jobs = None
|
| 1635 |
+
|
| 1636 |
+
with store.lock:
|
| 1637 |
+
verification = store.verifications.get(
|
| 1638 |
+
request_id
|
| 1639 |
+
)
|
| 1640 |
+
|
| 1641 |
+
if verification is None:
|
| 1642 |
+
raise HTTPException(
|
| 1643 |
+
status_code=404,
|
| 1644 |
+
detail="Verification request not found",
|
| 1645 |
+
)
|
| 1646 |
+
|
| 1647 |
+
verification["callback_url"] = body.callback_url
|
| 1648 |
+
verification["callback_secret"] = (
|
| 1649 |
+
body.callback_secret
|
| 1650 |
+
)
|
| 1651 |
+
|
| 1652 |
+
if verification["callback_status"] == "sent":
|
| 1653 |
+
return {
|
| 1654 |
+
"status": "already_sent",
|
| 1655 |
+
"request_id": request_id,
|
| 1656 |
+
}
|
| 1657 |
+
|
| 1658 |
+
# Let the standard callback collector prepare one attempt
|
| 1659 |
+
# if the request is already complete.
|
| 1660 |
+
callback_jobs = store._collect_ready_callbacks_locked()
|
| 1661 |
+
|
| 1662 |
+
store._dispatch_callbacks(callback_jobs)
|
| 1663 |
+
|
| 1664 |
+
return {
|
| 1665 |
+
"status": "callback_configured",
|
| 1666 |
+
"request_id": request_id,
|
| 1667 |
+
}
|