Spaces:
Sleeping

api-relay commited on
Commit
3cfcb19
·
verified ·
1 Parent(s): 9cf7068

Upload 10 files

Browse files
README.md CHANGED
@@ -1,11 +1,3 @@
1
- ---
2
- title: Archx Relay
3
- sdk: docker
4
- emoji: 📚
5
- colorFrom: red
6
- colorTo: yellow
7
- short_description: This space is a relay api relay.
8
- ---
9
  # Archx Relay Space (v4) — deploy & operate
10
 
11
  Pure-push, batch-first relay for the Archx dataset workforce. One contract, no
@@ -111,4 +103,4 @@ Passes locally in ~30 s (Python 3.11+, no network).
111
  deadline requeues them.
112
  - Keep-alive: `.github/workflows/keepalive.yml` pings `/health` once per hour at a
113
  `secrets.randbelow` random offset — not a bot pattern. (A sleeping Space cannot
114
- push jobs; keep the ping or use a non-sleeping Space tier.)
 
 
 
 
 
 
 
 
 
1
  # Archx Relay Space (v4) — deploy & operate
2
 
3
  Pure-push, batch-first relay for the Archx dataset workforce. One contract, no
 
103
  deadline requeues them.
104
  - Keep-alive: `.github/workflows/keepalive.yml` pings `/health` once per hour at a
105
  `secrets.randbelow` random offset — not a bot pattern. (A sleeping Space cannot
106
+ push jobs; keep the ping or use a non-sleeping Space tier.)
projects/dataset_verification/models.py CHANGED
@@ -48,7 +48,8 @@ class BatchSubmission(BaseModel):
48
 
49
  class WorkerRegisterRequest(BaseModel):
50
  worker_id: int
51
- url: str # synthetic instance identity: runner://<os>/<uuid>
 
52
  environment: "Environment"
53
 
54
  class Environment(BaseModel):
 
48
 
49
  class WorkerRegisterRequest(BaseModel):
50
  worker_id: int
51
+ url: str # primary url: runner://<os>/<uuid> or pull:// token
52
+ urls: Optional[List[str]] = None # optional tunnel redundancy: tried in order
53
  environment: "Environment"
54
 
55
  class Environment(BaseModel):
projects/dataset_verification/router.py CHANGED
@@ -55,7 +55,10 @@ desktop_auth = _auth(AGENT_API_KEY)
55
 
56
  def _check_push_url(url: str) -> str | None:
57
  """Quick tunnels are the supported push target. PUSH_URL_HOST_SUFFIX='*' disables
58
- the check (local dev/tests only)."""
 
 
 
59
  suffix = _os.getenv("PUSH_URL_HOST_SUFFIX", ".trycloudflare.com")
60
  if suffix == "*":
61
  return None
@@ -116,17 +119,43 @@ def worker_register(body: WorkerRegisterRequest):
116
  err = _check_push_url(url)
117
  if err:
118
  raise HTTPException(status_code=422, detail=err)
119
- public, old_url = store.register_worker(body.worker_id, url, body.environment.model_dump())
 
 
 
 
 
 
120
  if old_url:
121
  # tell the superseded generation to drain now instead of at its lifetime end
122
  threading.Thread(target=push_shutdown, args=(old_url, RUNNER_API_KEY),
123
  daemon=True).start()
124
  return public
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  @router.post("/worker/result", dependencies=[Depends(worker_auth)])
127
  def worker_result(body: ResultObject, worker_id: int = Query(...), url: str = Query(...)):
128
  try:
129
- store.report_result(worker_id, url, body)
 
 
130
  return {"status": "recorded", "job_id": body.job_id}
131
  except KeyError:
132
  raise HTTPException(status_code=404, detail="cell not found")
 
55
 
56
  def _check_push_url(url: str) -> str | None:
57
  """Quick tunnels are the supported push target. PUSH_URL_HOST_SUFFIX='*' disables
58
+ the check (local dev/tests only). Pull-mode workers register an opaque pull://
59
+ token instead of a reachable URL."""
60
+ if url.startswith("pull://") and len(url) > len("pull://") + 8:
61
+ return None
62
  suffix = _os.getenv("PUSH_URL_HOST_SUFFIX", ".trycloudflare.com")
63
  if suffix == "*":
64
  return None
 
119
  err = _check_push_url(url)
120
  if err:
121
  raise HTTPException(status_code=422, detail=err)
122
+ urls = [u.strip() for u in (body.urls or []) if u and u.strip()]
123
+ for i, u in enumerate(urls):
124
+ err = _check_push_url(u)
125
+ if err:
126
+ raise HTTPException(status_code=422, detail=f"urls[{i}]: {err}")
127
+ public, old_url = store.register_worker(body.worker_id, url,
128
+ body.environment.model_dump(), urls=urls or None)
129
  if old_url:
130
  # tell the superseded generation to drain now instead of at its lifetime end
131
  threading.Thread(target=push_shutdown, args=(old_url, RUNNER_API_KEY),
132
  daemon=True).start()
133
  return public
134
 
135
+ @router.post("/worker/next", dependencies=[Depends(worker_auth)])
136
+ def worker_next(body: dict):
137
+ try:
138
+ worker_id = int(body.get("worker_id") or 0)
139
+ except (TypeError, ValueError):
140
+ raise HTTPException(status_code=422, detail="worker_id must be an int")
141
+ url = str(body.get("url") or "")
142
+ if not worker_id or not url:
143
+ raise HTTPException(status_code=422, detail="worker_id and url are required")
144
+ try:
145
+ limit = int(body.get("limit", 1))
146
+ except (TypeError, ValueError):
147
+ limit = 1
148
+ cells = store.claim_next(worker_id, url, limit=max(1, min(limit, 16)))
149
+ if cells is None:
150
+ raise HTTPException(status_code=409, detail="url mismatch for this worker instance")
151
+ return {"cells": cells}
152
+
153
  @router.post("/worker/result", dependencies=[Depends(worker_auth)])
154
  def worker_result(body: ResultObject, worker_id: int = Query(...), url: str = Query(...)):
155
  try:
156
+ out = store.report_result(worker_id, url, body)
157
+ if out and out.get("already_recorded"):
158
+ return {"status": "already_recorded", "job_id": body.job_id}
159
  return {"status": "recorded", "job_id": body.job_id}
160
  except KeyError:
161
  raise HTTPException(status_code=404, detail="cell not found")
projects/dataset_verification/store.py CHANGED
@@ -78,7 +78,7 @@ def _http_push_json(url: str, payload: dict, bearer: str, timeout: float = 8.0)
78
  with urllib.request.urlopen(req, timeout=timeout) as resp:
79
  return 200 <= resp.status < 300
80
  except Exception as e:
81
- logger.warning("push to %s failed: %s", url, e.__class__.__name__)
82
  return False
83
 
84
  class Store:
@@ -101,6 +101,15 @@ class Store:
101
  self.totals = {"batches": 0, "cells": 0, "completed": 0}
102
  self.push_failures: Dict[int, int] = {}
103
  self._push_next: Dict[str, float] = {} # job_id -> earliest next push attempt
 
 
 
 
 
 
 
 
 
104
 
105
  self._load_state()
106
  # every queued cell (incl. crash-recovered) needs a push attempt
@@ -207,14 +216,21 @@ class Store:
207
  # ============ background sweep + push ============
208
  def _bg_loop(self):
209
  while not self._stop.wait(1.0):
 
 
 
 
210
  try:
211
  with self.lock:
212
  self._expire_claims_locked()
213
  self._sweep_locked()
214
  self._flush_state_locked()
215
- self._push_tick()
216
  except Exception:
217
  logger.exception("background sweep error")
 
 
 
 
218
 
219
  def stop(self):
220
  self._stop.set()
@@ -228,9 +244,14 @@ class Store:
228
  claimed = self._claim_for_push_locked(max_claims=4)
229
  if not claimed:
230
  return
231
- for job_id, worker_id, url, payload in claimed:
232
- ok = _http_push_json(url.rstrip("/") + "/job", payload, self.push_bearer, timeout=8.0)
233
- self._settle_push(job_id, worker_id, url, ok)
 
 
 
 
 
234
 
235
  def _claim_for_push_locked(self, max_claims: int = 4):
236
  t = now()
@@ -261,7 +282,7 @@ class Store:
261
  meta.claimed_worker_url = w["url"]
262
  meta.claimed_at = t
263
  meta.claim_deadline = t + meta.timeout + self.claim_buffer
264
- claimed.append((jid, w["worker_id"], w["url"], payload))
265
  del self._push_next[jid]
266
  if claimed:
267
  self._flush_state_locked()
@@ -276,6 +297,8 @@ class Store:
276
  continue
277
  if self.push_failures.get(wid, 0) >= self.max_push_failures:
278
  continue
 
 
279
  env = w.get("environment", {})
280
  if env.get("platform") != meta.platform:
281
  continue
@@ -290,6 +313,57 @@ class Store:
290
  best, best_inflight = w, inflight
291
  return best
292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  def _settle_push(self, job_id: str, worker_id: int, url: str, ok: bool):
294
  with self.lock:
295
  if ok:
@@ -381,15 +455,28 @@ class Store:
381
  return self._batch_public_locked(batch_id)
382
 
383
  # ============ worker lifecycle ============
384
- def register_worker(self, worker_id: int, url: str, environment: dict):
 
 
 
 
 
 
 
 
385
  """Returns (public_view, old_url_to_supersede|None)."""
386
  with self.lock:
387
  prev = self.workers.get(worker_id)
388
  old_url = prev.get("url") if prev else None
389
  superseded = bool(prev and prev.get("url") != url)
 
 
 
390
  self.workers[worker_id] = {
391
- "worker_id": worker_id, "url": url, "environment": environment,
392
- "registered_at": now(), "last_seen_at": now(), "reported_done": False}
 
 
393
  self.push_failures[worker_id] = 0
394
  # a fresh runner may match everything queued so far
395
  for jid, meta in self.jobs.items():
@@ -406,7 +493,11 @@ class Store:
406
  return None
407
  return {"worker_id": worker_id, "environment": w["environment"],
408
  "registered_at": iso(w["registered_at"]), "last_seen_at": iso(w["last_seen_at"]),
409
- "status": self._worker_status(worker_id)}
 
 
 
 
410
 
411
  def _worker_status(self, worker_id: int):
412
  w = self.workers.get(worker_id)
@@ -425,15 +516,29 @@ class Store:
425
  meta = self.jobs.get(result.job_id)
426
  if meta is None:
427
  raise KeyError("cell not found")
428
- if meta.claimed_by != worker_id or meta.claimed_worker_url != url:
 
 
 
 
 
 
 
 
429
  raise PermissionError("cell not claimed by this worker instance")
430
  self._complete_cell_locked(meta, result.model_dump())
431
  self.push_failures[worker_id] = 0
432
  w = self.workers.get(worker_id)
433
- if w and w["url"] == url:
434
  w["last_seen_at"] = now()
 
435
 
436
  def _complete_cell_locked(self, meta: JobMeta, result: dict):
 
 
 
 
 
437
  self._save_json(f"results/{meta.job_id}.json", result)
438
  meta.status = "complete"
439
  meta.completed_at = now()
@@ -450,17 +555,93 @@ class Store:
450
  with self.lock:
451
  released = []
452
  w = self.workers.get(worker_id)
453
- if w and w["url"] == url:
454
  w["reported_done"] = True
455
  w["last_seen_at"] = now()
456
  for meta in self.jobs.values():
457
- if meta.status == "claimed" and meta.claimed_by == worker_id and meta.claimed_worker_url == url:
458
  self._abandon_cell_locked(meta, "worker reported done")
459
  released.append(meta.job_id)
460
  self._flush_state_locked()
461
  self._wake()
462
  return released
463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464
  # ============ expiry / retention ============
465
  def _abandon_cell_locked(self, meta: JobMeta, reason: str):
466
  if meta.retry_count >= self.max_retries:
@@ -596,6 +777,16 @@ class Store:
596
  def store_artifact(self, batch_hint: Optional[str], job_hint: Optional[str],
597
  rel_path: str, kind: Optional[str], content_type: Optional[str],
598
  data: bytes) -> dict:
 
 
 
 
 
 
 
 
 
 
599
  ext = Path(rel_path).suffix.lower()
600
  meta = ArtifactMeta(
601
  artifact_id=artifact_id(), batch_id=batch_hint or "unknown", job_id=job_hint or "unknown",
 
78
  with urllib.request.urlopen(req, timeout=timeout) as resp:
79
  return 200 <= resp.status < 300
80
  except Exception as e:
81
+ logger.warning("push to %s failed: %s: %s", url, e.__class__.__name__, str(e)[:120])
82
  return False
83
 
84
  class Store:
 
101
  self.totals = {"batches": 0, "cells": 0, "completed": 0}
102
  self.push_failures: Dict[int, int] = {}
103
  self._push_next: Dict[str, float] = {} # job_id -> earliest next push attempt
104
+ # randomized heartbeat: one sparse ping per worker per window at an
105
+ # os.urandom-backed random offset (never 2s polling — deliberately NOT
106
+ # bot-like). Observational only: never affects push eligibility.
107
+ self.heartbeat_window = float(os.getenv("HEARTBEAT_WINDOW_SECONDS", "1800")) # 30 min; 0 = off
108
+ self.heartbeat_timeout = float(os.getenv("HEARTBEAT_TIMEOUT_SECONDS", "5.0"))
109
+ self._heartbeat_window_start = 0.0
110
+ self._heartbeat_due: Dict[int, float] = {} # worker_id -> ping ts in current window
111
+ self._heartbeat_done: set = set() # pinged this window
112
+ self._heartbeat_inflight: set = set() # ping in progress
113
 
114
  self._load_state()
115
  # every queued cell (incl. crash-recovered) needs a push attempt
 
216
  # ============ background sweep + push ============
217
  def _bg_loop(self):
218
  while not self._stop.wait(1.0):
219
+ try:
220
+ self._push_tick() # pushes are the critical path
221
+ except Exception:
222
+ logger.exception("background push tick error")
223
  try:
224
  with self.lock:
225
  self._expire_claims_locked()
226
  self._sweep_locked()
227
  self._flush_state_locked()
 
228
  except Exception:
229
  logger.exception("background sweep error")
230
+ try:
231
+ self._heartbeat_tick() # sparse + randomized; observational
232
+ except Exception:
233
+ logger.exception("background heartbeat tick error")
234
 
235
  def stop(self):
236
  self._stop.set()
 
244
  claimed = self._claim_for_push_locked(max_claims=4)
245
  if not claimed:
246
  return
247
+ for job_id, worker_id, urls, payload in claimed:
248
+ ok = False
249
+ for u in urls: # tunnel failover: first 2xx wins
250
+ if _http_push_json(u.rstrip("/") + "/job", payload, self.push_bearer,
251
+ timeout=8.0):
252
+ ok = True
253
+ break
254
+ self._settle_push(job_id, worker_id, urls[0], ok)
255
 
256
  def _claim_for_push_locked(self, max_claims: int = 4):
257
  t = now()
 
282
  meta.claimed_worker_url = w["url"]
283
  meta.claimed_at = t
284
  meta.claim_deadline = t + meta.timeout + self.claim_buffer
285
+ claimed.append((jid, w["worker_id"], self._worker_urls(w), payload))
286
  del self._push_next[jid]
287
  if claimed:
288
  self._flush_state_locked()
 
297
  continue
298
  if self.push_failures.get(wid, 0) >= self.max_push_failures:
299
  continue
300
+ if w.get("pull_mode"):
301
+ continue # polls /worker/next instead of receiving pushes
302
  env = w.get("environment", {})
303
  if env.get("platform") != meta.platform:
304
  continue
 
313
  best, best_inflight = w, inflight
314
  return best
315
 
316
+ def claim_next(self, worker_id: int, url: str, limit: int = 1):
317
+ """Pull-mode claim: a registered worker asks for its next cell(s).
318
+ Returns the payload list, or None when the (worker_id, url) pair is not
319
+ the currently registered generation (router maps that to 409)."""
320
+ with self.lock:
321
+ w = self.workers.get(worker_id)
322
+ if not w or w.get("url") != url:
323
+ return None
324
+ if w.get("reported_done"):
325
+ return []
326
+ self._expire_claims_locked()
327
+ env = w.get("environment", {}) or {}
328
+ runtimes = set(env.get("runtimes", []))
329
+ inflight = sum(1 for j in self.jobs.values()
330
+ if j.status == "claimed" and j.claimed_by == worker_id)
331
+ remaining = max(0, int(env.get("max_concurrent_jobs", 1)) - inflight)
332
+ limit = max(0, min(int(limit), remaining))
333
+ out = []
334
+ if limit <= 0:
335
+ return out
336
+ t = now()
337
+ candidates = [(m.submitted_at, jid, m) for jid, m in self.jobs.items()
338
+ if m.status == "queued"]
339
+ candidates.sort(key=lambda x: x[0])
340
+ for _, jid, meta in candidates:
341
+ if len(out) >= limit:
342
+ break
343
+ if env.get("platform") != meta.platform:
344
+ continue
345
+ if meta.runtime not in runtimes:
346
+ continue
347
+ payload = self._load_json(f"jobs/{jid}.json")
348
+ if payload is None:
349
+ self._complete_cell_locked(meta, {
350
+ "job_id": meta.job_id, "exit_code": 1, "timed_out": False,
351
+ "category": "infra_failure", "steps": [], "filesystem_state": None,
352
+ "artifacts": [], "failure_reason": "payload missing"})
353
+ self._push_next.pop(jid, None)
354
+ continue
355
+ meta.status = "claimed"
356
+ meta.claimed_by = worker_id
357
+ meta.claimed_worker_url = url
358
+ meta.claimed_at = t
359
+ meta.claim_deadline = t + meta.timeout + self.claim_buffer
360
+ self._push_next.pop(jid, None)
361
+ out.append(payload)
362
+ if out:
363
+ self._flush_state_locked()
364
+ self._event("cells_claimed", count=len(out), mode="pull", worker_id=worker_id)
365
+ return out
366
+
367
  def _settle_push(self, job_id: str, worker_id: int, url: str, ok: bool):
368
  with self.lock:
369
  if ok:
 
455
  return self._batch_public_locked(batch_id)
456
 
457
  # ============ worker lifecycle ============
458
+ @staticmethod
459
+ def _worker_urls(w: dict) -> List[str]:
460
+ urls = w.get("urls") or []
461
+ if w.get("url") and w["url"] not in urls:
462
+ urls = [w["url"]] + urls
463
+ return urls or [w.get("url", "")]
464
+
465
+ def register_worker(self, worker_id: int, url: str, environment: dict,
466
+ urls: Optional[List[str]] = None):
467
  """Returns (public_view, old_url_to_supersede|None)."""
468
  with self.lock:
469
  prev = self.workers.get(worker_id)
470
  old_url = prev.get("url") if prev else None
471
  superseded = bool(prev and prev.get("url") != url)
472
+ all_urls = urls or [url]
473
+ if url not in all_urls:
474
+ all_urls = [url] + list(all_urls)
475
  self.workers[worker_id] = {
476
+ "worker_id": worker_id, "url": url, "urls": all_urls,
477
+ "environment": environment,
478
+ "registered_at": now(), "last_seen_at": now(), "reported_done": False,
479
+ "pull_mode": url.startswith("pull://")}
480
  self.push_failures[worker_id] = 0
481
  # a fresh runner may match everything queued so far
482
  for jid, meta in self.jobs.items():
 
493
  return None
494
  return {"worker_id": worker_id, "environment": w["environment"],
495
  "registered_at": iso(w["registered_at"]), "last_seen_at": iso(w["last_seen_at"]),
496
+ "status": self._worker_status(worker_id),
497
+ "last_heartbeat_at": iso(w.get("last_heartbeat_at")),
498
+ "last_heartbeat_ok_at": iso(w.get("last_heartbeat_ok_at")),
499
+ "last_heartbeat_ok": w.get("last_heartbeat_ok"),
500
+ "heartbeat_failures": w.get("heartbeat_failures", 0)}
501
 
502
  def _worker_status(self, worker_id: int):
503
  w = self.workers.get(worker_id)
 
516
  meta = self.jobs.get(result.job_id)
517
  if meta is None:
518
  raise KeyError("cell not found")
519
+ if meta.status == "complete":
520
+ # duplicate delivery ⇒ duplicate report; the first result already
521
+ # recorded and counted — swallow quietly, do not double-count
522
+ self._event("result_duplicate_ignored", job_id=meta.job_id,
523
+ worker_id=worker_id)
524
+ return {"already_recorded": True}
525
+ w = self.workers.get(worker_id)
526
+ known = set(self._worker_urls(w)) if w else set()
527
+ if meta.claimed_by != worker_id or (url not in known and url != meta.claimed_worker_url):
528
  raise PermissionError("cell not claimed by this worker instance")
529
  self._complete_cell_locked(meta, result.model_dump())
530
  self.push_failures[worker_id] = 0
531
  w = self.workers.get(worker_id)
532
+ if w and url in self._worker_urls(w):
533
  w["last_seen_at"] = now()
534
+ return {"already_recorded": False}
535
 
536
  def _complete_cell_locked(self, meta: JobMeta, result: dict):
537
+ if meta.status == "complete":
538
+ # defensive: unreachable via report_result's pre-check, but blocks
539
+ # any future path from double-counting totals/batch completion
540
+ self._event("cell_complete_duplicate_ignored", job_id=meta.job_id)
541
+ return
542
  self._save_json(f"results/{meta.job_id}.json", result)
543
  meta.status = "complete"
544
  meta.completed_at = now()
 
555
  with self.lock:
556
  released = []
557
  w = self.workers.get(worker_id)
558
+ if w and url in self._worker_urls(w):
559
  w["reported_done"] = True
560
  w["last_seen_at"] = now()
561
  for meta in self.jobs.values():
562
+ if meta.status == "claimed" and meta.claimed_by == worker_id:
563
  self._abandon_cell_locked(meta, "worker reported done")
564
  released.append(meta.job_id)
565
  self._flush_state_locked()
566
  self._wake()
567
  return released
568
 
569
+ # ============ randomized heartbeat ============
570
+ def _heartbeat_tick(self):
571
+ if self.heartbeat_window <= 0:
572
+ return
573
+ t = now()
574
+ if self._heartbeat_window_start == 0.0:
575
+ self._heartbeat_window_start = (t // self.heartbeat_window) * self.heartbeat_window
576
+ if t >= self._heartbeat_window_start + self.heartbeat_window:
577
+ # roll to the CURRENT window (snap, don't step) — fresh dues, fresh offsets
578
+ self._heartbeat_window_start = (t // self.heartbeat_window) * self.heartbeat_window
579
+ self._heartbeat_due.clear()
580
+ with self.lock:
581
+ self._heartbeat_done.clear()
582
+ logger.info("heartbeat: new window, %d worker(s) to schedule", len(self.workers))
583
+ span = max(1, int(self.heartbeat_window))
584
+ due_now = []
585
+ with self.lock:
586
+ for key, w in self.workers.items():
587
+ try:
588
+ wid = int(w.get("worker_id", key))
589
+ except (TypeError, ValueError):
590
+ continue
591
+ if w.get("pull_mode") or w.get("reported_done"):
592
+ continue # pull workers check in by polling
593
+ if wid in self._heartbeat_done or wid in self._heartbeat_inflight:
594
+ continue
595
+ if wid not in self._heartbeat_due:
596
+ # os.urandom-backed (secrets) — every worker its own offset,
597
+ # every window different: irregular, never in lockstep
598
+ self._heartbeat_due[wid] = self._heartbeat_window_start + secrets.randbelow(span)
599
+ elif t >= self._heartbeat_due[wid]:
600
+ due_now.append(wid)
601
+ for wid in due_now:
602
+ self._heartbeat_due.pop(wid, None)
603
+ self._heartbeat_inflight.add(wid)
604
+ for wid in due_now:
605
+ w = self.workers.get(wid)
606
+ urls = self._worker_urls(w) if w else []
607
+ urls = [u for u in urls if u.startswith(("http://", "https://"))]
608
+ if not urls:
609
+ with self.lock:
610
+ self._heartbeat_inflight.discard(wid)
611
+ self._heartbeat_done.add(wid)
612
+ continue
613
+ threading.Thread(target=self._heartbeat_ping, args=(wid, urls),
614
+ name=f"hb-{wid}", daemon=True).start()
615
+
616
+ def _heartbeat_ping(self, worker_id: int, urls: List[str]):
617
+ ok = False
618
+ for u in urls: # same tunnel order as pushes
619
+ try:
620
+ req = urllib.request.Request(u.rstrip("/") + "/health", method="GET")
621
+ req.add_header("Authorization", f"Bearer {self.push_bearer}")
622
+ with urllib.request.urlopen(req, timeout=self.heartbeat_timeout) as resp:
623
+ if resp.status == 200:
624
+ ok = True
625
+ break
626
+ except Exception as e:
627
+ # never log the URL; class name only
628
+ logger.info("heartbeat to worker %d: %s", worker_id, e.__class__.__name__)
629
+ with self.lock:
630
+ w = self.workers.get(worker_id)
631
+ if w is not None:
632
+ w["last_heartbeat_at"] = now()
633
+ w["last_heartbeat_ok"] = ok
634
+ if ok:
635
+ w["last_heartbeat_ok_at"] = now()
636
+ w["heartbeat_failures"] = 0
637
+ else:
638
+ w["heartbeat_failures"] = int(w.get("heartbeat_failures", 0)) + 1
639
+ self._event("worker_heartbeat", worker_id=worker_id, ok=ok)
640
+ self._flush_state_locked()
641
+ self._heartbeat_inflight.discard(worker_id)
642
+ self._heartbeat_done.add(worker_id)
643
+ logger.info("heartbeat to worker %d: %s", worker_id, "ok" if ok else "FAILED")
644
+
645
  # ============ expiry / retention ============
646
  def _abandon_cell_locked(self, meta: JobMeta, reason: str):
647
  if meta.retry_count >= self.max_retries:
 
777
  def store_artifact(self, batch_hint: Optional[str], job_hint: Optional[str],
778
  rel_path: str, kind: Optional[str], content_type: Optional[str],
779
  data: bytes) -> dict:
780
+ sha = hashlib.sha256(data).hexdigest()
781
+ job = job_hint or "unknown"
782
+ adir = self._p("artifacts")
783
+ for meta_path in adir.glob("*.json"):
784
+ m = self._load_json(f"artifacts/{meta_path.name}")
785
+ if (m and m.get("job_id") == job and m.get("path") == rel_path
786
+ and m.get("sha256") == sha):
787
+ self._event("artifact_deduped", artifact_id=m["artifact_id"],
788
+ job_id=job, size=m.get("size"))
789
+ return m # identical bytes already stored for this cell+path
790
  ext = Path(rel_path).suffix.lower()
791
  meta = ArtifactMeta(
792
  artifact_id=artifact_id(), batch_id=batch_hint or "unknown", job_id=job_hint or "unknown",
tests/e2e_test.py CHANGED
@@ -12,6 +12,14 @@ Covers:
12
  SIGKILLed, reboot -> cell requeued -> completed by a real worker
13
  6. supersede: re-register same worker_id with a new url -> old intake gets /shutdown
14
  7. consume batch -> status complete, remaining 0
 
 
 
 
 
 
 
 
15
  """
16
  import hashlib
17
  import json
@@ -24,6 +32,7 @@ import threading
24
  import time
25
  import urllib.error
26
  import urllib.request
 
27
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
28
 
29
  REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
@@ -35,6 +44,10 @@ LINUX2_PORT = 8803
35
  BH_WIN_PORT = 8812
36
  BH_CRASH_PORT = 8810
37
  BH_SUPER_PORT = 8811
 
 
 
 
38
  ENV = dict(os.environ, PERSIST_DIR=PERSIST_DIR,
39
  RUNNER_API_KEY="runner-key", AGENT_API_KEY="agent-key",
40
  PUSH_URL_HOST_SUFFIX="*", RETENTION_SECONDS="10800")
@@ -76,12 +89,39 @@ def start_worker(name, runner_id, runner_os, port, tags="python-3.11,python-3.12
76
  RUNNER_ID=str(runner_id), RUNNER_OS=runner_os,
77
  RUNTIME_TAGS=tags, RUNNER_PORT=str(port),
78
  RUNNER_LOCAL_URL=f"http://127.0.0.1:{port}",
 
79
  MAX_CONCURRENT_JOBS="4", RUNNER_LIFETIME_SECONDS="240",
80
  BASE_VENV_DIR="/tmp/relay_v4_novenv")
81
  logf = open(f"/tmp/relay_v4_{name}.log", "w")
82
  return subprocess.Popen([sys.executable, os.path.join(REPO, "tools", "runner", "worker.py")],
83
  env=env, cwd=REPO, stdout=logf, stderr=subprocess.STDOUT)
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  class BlackHole:
86
  """Accepts /job (202) and /shutdown (200) with correct auth, records posts, never runs cells."""
87
  def __init__(self, port):
@@ -272,6 +312,169 @@ def main():
272
  bh_sup.stop()
273
  ok.append("supersede -> /shutdown pushed to old generation")
274
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
  fin2 = req("GET", "/desktop/batch/batch_v4_crash", query="consume=true")
276
  assert fin2["status"] == "complete"
277
  finally:
 
12
  SIGKILLed, reboot -> cell requeued -> completed by a real worker
13
  6. supersede: re-register same worker_id with a new url -> old intake gets /shutdown
14
  7. consume batch -> status complete, remaining 0
15
+ 8. pull mode: worker registers pull:// (no inbound tunnel), claims via /worker/next,
16
+ executes, reports, batch complete
17
+ 9. hybrid mode: tunnel push + gentle puller backstop in one worker — batch completes
18
+ 10. multi-tunnel failover: relay registered urls=[dead, black-hole]; push lands on the
19
+ second tunnel; /worker/result accepted from any registered url
20
+ 11. duplicate /job delivery to the intake is executed exactly once (5s-sleep cell)
21
+ 12. duplicate /worker/result on a completed cell -> 200 already_recorded; batch counts once
22
+ 13. duplicate /worker/artifact (same job+path+sha256) -> same artifact_id, no second .bin
23
  """
24
  import hashlib
25
  import json
 
32
  import time
33
  import urllib.error
34
  import urllib.request
35
+ from pathlib import Path
36
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
37
 
38
  REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
 
44
  BH_WIN_PORT = 8812
45
  BH_CRASH_PORT = 8810
46
  BH_SUPER_PORT = 8811
47
+ BH_FAIL_PORT = 8813
48
+ HYBRID_PORT = 8814
49
+ DUPE_PORT = 8815
50
+ BH_DUPE2_PORT = 8816
51
  ENV = dict(os.environ, PERSIST_DIR=PERSIST_DIR,
52
  RUNNER_API_KEY="runner-key", AGENT_API_KEY="agent-key",
53
  PUSH_URL_HOST_SUFFIX="*", RETENTION_SECONDS="10800")
 
89
  RUNNER_ID=str(runner_id), RUNNER_OS=runner_os,
90
  RUNTIME_TAGS=tags, RUNNER_PORT=str(port),
91
  RUNNER_LOCAL_URL=f"http://127.0.0.1:{port}",
92
+ RUNNER_MODE="push",
93
  MAX_CONCURRENT_JOBS="4", RUNNER_LIFETIME_SECONDS="240",
94
  BASE_VENV_DIR="/tmp/relay_v4_novenv")
95
  logf = open(f"/tmp/relay_v4_{name}.log", "w")
96
  return subprocess.Popen([sys.executable, os.path.join(REPO, "tools", "runner", "worker.py")],
97
  env=env, cwd=REPO, stdout=logf, stderr=subprocess.STDOUT)
98
 
99
+ def start_worker_hybrid(name, runner_id, runner_os, port, tags="python-3.12"):
100
+ env = dict(os.environ,
101
+ RELAY_URL=BASE, RUNNER_API_KEY="runner-key",
102
+ RUNNER_ID=str(runner_id), RUNNER_OS=runner_os,
103
+ RUNTIME_TAGS=tags, RUNNER_PORT=str(port),
104
+ RUNNER_LOCAL_URL=f"http://127.0.0.1:{port}",
105
+ RUNNER_MODE="hybrid", RUNNER_POLL_SECONDS="2",
106
+ MAX_CONCURRENT_JOBS="2", RUNNER_LIFETIME_SECONDS="240",
107
+ RUNNER_IDLE_TIMEOUT_SECONDS="120",
108
+ BASE_VENV_DIR="/tmp/relay_v4_novenv")
109
+ logf = open(f"/tmp/relay_v4_{name}.log", "w")
110
+ return subprocess.Popen([sys.executable, os.path.join(REPO, "tools", "runner", "worker.py")],
111
+ env=env, cwd=REPO, stdout=logf, stderr=subprocess.STDOUT)
112
+
113
+ def start_worker_pull(name, runner_id, runner_os, tags="python-3.12"):
114
+ env = dict(os.environ,
115
+ RELAY_URL=BASE, RUNNER_API_KEY="runner-key",
116
+ RUNNER_ID=str(runner_id), RUNNER_OS=runner_os,
117
+ RUNTIME_TAGS=tags, RUNNER_MODE="pull", RUNNER_POLL_SECONDS="1",
118
+ MAX_CONCURRENT_JOBS="2", RUNNER_LIFETIME_SECONDS="240",
119
+ RUNNER_IDLE_TIMEOUT_SECONDS="120",
120
+ BASE_VENV_DIR="/tmp/relay_v4_novenv")
121
+ logf = open(f"/tmp/relay_v4_{name}.log", "w")
122
+ return subprocess.Popen([sys.executable, os.path.join(REPO, "tools", "runner", "worker.py")],
123
+ env=env, cwd=REPO, stdout=logf, stderr=subprocess.STDOUT)
124
+
125
  class BlackHole:
126
  """Accepts /job (202) and /shutdown (200) with correct auth, records posts, never runs cells."""
127
  def __init__(self, port):
 
312
  bh_sup.stop()
313
  ok.append("supersede -> /shutdown pushed to old generation")
314
 
315
+ # ---- pull mode: no tunnel, claims via /worker/next ----
316
+ req("POST", "/desktop/batch",
317
+ {"batch_id": "batch_v4_pull",
318
+ "jobs": [{"job_id": "job_pull1", "platform": "linux", "runtime": "python-3.12",
319
+ "files": {"main.py": "print('pull-ok')\n"},
320
+ "entry_point": "python main.py", "timeout": 60}]})
321
+ pull_worker = start_worker_pull("pull1", 21, "linux", tags="python-3.12")
322
+ try:
323
+ wait_for(lambda: req("GET", "/desktop/batch/batch_v4_pull")["status"] == "complete",
324
+ 120, "pull-mode cell completed", interval=2.0)
325
+ ok.append("pull mode: /worker/next claim -> execute -> result -> complete")
326
+ finally:
327
+ pull_worker.terminate()
328
+ try:
329
+ pull_worker.wait(timeout=15)
330
+ except Exception:
331
+ pull_worker.kill()
332
+
333
+ # ---- hybrid mode: push primary + gentle pull backstop in one worker ----
334
+ req("POST", "/desktop/batch",
335
+ {"batch_id": "batch_v4_hybrid",
336
+ "jobs": [{"job_id": "job_hybrid1", "platform": "linux", "runtime": "python-3.12",
337
+ "files": {"main.py": "print('hybrid-ok')\n"},
338
+ "entry_point": "python main.py", "timeout": 60}]})
339
+ hybrid_worker = start_worker_hybrid("hybrid1", 31, "linux", HYBRID_PORT,
340
+ tags="python-3.12")
341
+ try:
342
+ wait_for(lambda: req("GET", "/desktop/batch/batch_v4_hybrid")["status"] == "complete",
343
+ 120, "hybrid-mode cell completed", interval=2.0)
344
+ ok.append("hybrid mode: tunnel push + pull backstop coexist; batch complete")
345
+ finally:
346
+ hybrid_worker.terminate()
347
+ try:
348
+ hybrid_worker.wait(timeout=15)
349
+ except Exception:
350
+ hybrid_worker.kill()
351
+
352
+ # ---- multi-tunnel failover + result from a non-primary registered url ----
353
+ req("POST", "/desktop/batch",
354
+ {"batch_id": "batch_v4_failover",
355
+ "jobs": [{"job_id": "job_failover1", "platform": "linux", "runtime": "python-3.12",
356
+ "files": {"main.py": "print('failover-ok')\n"},
357
+ "entry_point": "python main.py", "timeout": 60}]})
358
+ bh_fail = BlackHole(BH_FAIL_PORT)
359
+ req("POST", "/worker/register",
360
+ {"worker_id": 41, "url": "http://127.0.0.1:9",
361
+ "urls": ["http://127.0.0.1:9", f"http://127.0.0.1:{BH_FAIL_PORT}"],
362
+ "environment": {"platform": "linux", "os_version": "ubuntu",
363
+ "runtimes": ["python-3.12"], "max_concurrent_jobs": 1}},
364
+ key="runner-key")
365
+ wait_for(lambda: "/job" in bh_fail.records, 30,
366
+ "push failed over from dead primary tunnel to second tunnel", interval=1.0)
367
+ cell_id = req("GET", "/desktop/batch/batch_v4_failover")["results"][0]["job_id"]
368
+ req("POST", "/worker/result",
369
+ {"job_id": cell_id, "exit_code": 0, "timed_out": False,
370
+ "category": "success",
371
+ "steps": [{"name": "run", "stdout": "failover-ok", "stderr": "",
372
+ "exit_code": 0, "timed_out": False}],
373
+ "filesystem_state": None, "artifacts": []},
374
+ key="runner-key",
375
+ query=f"worker_id=41&url=http://127.0.0.1:{BH_FAIL_PORT}")
376
+ fin3 = req("GET", "/desktop/batch/batch_v4_failover", query="consume=true")
377
+ assert fin3["status"] == "complete"
378
+ bh_fail.stop()
379
+ ok.append("multi-tunnel failover: push over 2nd tunnel; result accepted from 2nd url")
380
+
381
+ # ---- duplicate /job delivery executes exactly once ----
382
+ counter_file = Path("/tmp/relay_v4_dupe_counter.txt")
383
+ counter_file.unlink(missing_ok=True)
384
+ dupe_worker = start_worker("dupe1", 51, "linux", DUPE_PORT, tags="python-3.12")
385
+ dupe_body = {
386
+ "job_id": "job_dupe1#linux/python-3.12",
387
+ "platform": "linux", "runtime": "python-3.12",
388
+ "files": {"main.py":
389
+ "import time, pathlib\n"
390
+ "time.sleep(5)\n"
391
+ "p = pathlib.Path('/tmp/relay_v4_dupe_counter.txt')\n"
392
+ "p.write_text((p.read_text() if p.exists() else '') + 'x\\n')\n"},
393
+ "steps": [{"name": "run", "entry_point": "python main.py", "timeout": 60}]}
394
+ try:
395
+ time.sleep(2.0) # let the dev worker register and open its intake
396
+ statuses = []
397
+ duplicates = []
398
+ for _ in range(2):
399
+ data = json.dumps(dupe_body).encode()
400
+ r = urllib.request.Request(f"http://127.0.0.1:{DUPE_PORT}/job", data=data,
401
+ method="POST")
402
+ r.add_header("Authorization", "Bearer runner-key")
403
+ r.add_header("Content-Type", "application/json")
404
+ with urllib.request.urlopen(r, timeout=10) as resp:
405
+ body = json.loads(resp.read())
406
+ statuses.append(resp.status)
407
+ duplicates.append(bool(body.get("duplicate")))
408
+ assert statuses == [202, 202], statuses
409
+ assert duplicates == [False, True], f"expected second delivery flagged duplicate, got {duplicates}"
410
+ time.sleep(8.0) # cell sleeps 5s, then writes the counter
411
+ assert counter_file.exists()
412
+ assert counter_file.read_text() == "x\n", (
413
+ f"cell executed more than once: {counter_file.read_text()!r}")
414
+ ok.append("duplicate /job delivery: executed exactly once")
415
+ finally:
416
+ dupe_worker.terminate()
417
+ try:
418
+ dupe_worker.wait(timeout=15)
419
+ except Exception:
420
+ dupe_worker.kill()
421
+ counter_file.unlink(missing_ok=True)
422
+
423
+ # ---- duplicate /worker/result on a completed cell -> already_recorded ----
424
+ # the leg-10 failover worker (id 41) is long dead but still registered with a
425
+ # lower worker_id than our new claimant and would shadow every push until it
426
+ # burns max_push_failures — retire it first, as a superseded generation would
427
+ req("POST", "/worker/done",
428
+ {"worker_id": 41, "url": "http://127.0.0.1:9"}, key="runner-key")
429
+ req("POST", "/desktop/batch",
430
+ {"batch_id": "batch_v4_dupe2",
431
+ "jobs": [{"job_id": "job_dupe2", "platform": "linux", "runtime": "python-3.12",
432
+ "files": {"main.py": "print('dupe2-ok')\n"},
433
+ "entry_point": "python main.py", "timeout": 60}]})
434
+ bh_dupe2 = BlackHole(BH_DUPE2_PORT)
435
+ req("POST", "/worker/register",
436
+ {"worker_id": 52, "url": "http://127.0.0.1:9",
437
+ "urls": ["http://127.0.0.1:9", f"http://127.0.0.1:{BH_DUPE2_PORT}"],
438
+ "environment": {"platform": "linux", "os_version": "ubuntu",
439
+ "runtimes": ["python-3.12"], "max_concurrent_jobs": 1}},
440
+ key="runner-key")
441
+ wait_for(lambda: "/job" in bh_dupe2.records, 30,
442
+ "dupe2 cell pushed via failover", interval=1.0)
443
+ cell_id2 = req("GET", "/desktop/batch/batch_v4_dupe2")["results"][0]["job_id"]
444
+ result_body = {"job_id": cell_id2, "exit_code": 0, "timed_out": False,
445
+ "category": "success",
446
+ "steps": [{"name": "run", "stdout": "dupe2-ok", "stderr": "",
447
+ "exit_code": 0, "timed_out": False}],
448
+ "filesystem_state": None, "artifacts": []}
449
+ first = req("POST", "/worker/result", result_body, key="runner-key",
450
+ query=f"worker_id=52&url=http://127.0.0.1:{BH_DUPE2_PORT}")
451
+ second = req("POST", "/worker/result", result_body, key="runner-key",
452
+ query=f"worker_id=52&url=http://127.0.0.1:{BH_DUPE2_PORT}")
453
+ assert first["status"] == "recorded", first
454
+ assert second["status"] == "already_recorded", second
455
+ b2 = req("GET", "/desktop/batch/batch_v4_dupe2")
456
+ assert b2["completed_job_count"] == 1 and b2["job_count"] == 1
457
+ # ---- duplicate /worker/artifact -> same artifact_id ----
458
+ art_payload = b"dupe-artifact-bytes-\x00\x01\x02"
459
+ from urllib.parse import urlencode
460
+ def put_artifact():
461
+ q = urlencode({"job_id": cell_id2, "batch_id": "batch_v4_dupe2",
462
+ "path": "outputs/dupe.bin", "kind": "file"})
463
+ r = urllib.request.Request(f"{BASE}/worker/artifact?{q}",
464
+ data=art_payload, method="POST")
465
+ r.add_header("Authorization", "Bearer runner-key")
466
+ with urllib.request.urlopen(r, timeout=15) as resp:
467
+ return json.loads(resp.read())
468
+ a1 = put_artifact()
469
+ a2 = put_artifact()
470
+ assert a1["artifact_id"] == a2["artifact_id"], (a1["artifact_id"], a2["artifact_id"])
471
+ ok.append("duplicate /worker/artifact -> same artifact_id, no second .bin")
472
+
473
+ fin4 = req("GET", "/desktop/batch/batch_v4_dupe2", query="consume=true")
474
+ assert fin4["status"] == "complete"
475
+ bh_dupe2.stop()
476
+ ok.append("duplicate /worker/result -> already_recorded; batch counted once")
477
+
478
  fin2 = req("GET", "/desktop/batch/batch_v4_crash", query="consume=true")
479
  assert fin2["status"] == "complete"
480
  finally:
tests/heartbeat_test.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Relay heartbeat test (local, no external network).
3
+
4
+ Boots a relay with HEARTBEAT_WINDOW_SECONDS=2 and verifies:
5
+ 1. a healthy stub worker (GET /health -> 200) receives a heartbeat within a window;
6
+ /desktop/status reports last_heartbeat_ok_at and zero failures
7
+ 2. an unreachable worker accumulates heartbeat_failures (observational only)
8
+ 3. a pull-mode (pull://) worker is NEVER pinged — pull workers check in by polling
9
+ 4. heartbeat never changes push eligibility (status stays idle for a healthy worker)
10
+ """
11
+ import json
12
+ import os
13
+ import shutil
14
+ import signal
15
+ import subprocess
16
+ import sys
17
+ import threading
18
+ import time
19
+ import urllib.error
20
+ import urllib.request
21
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
22
+
23
+ REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
24
+ PORT = 8798
25
+ BASE = f"http://127.0.0.1:{PORT}/dataset_verification"
26
+ PERSIST_DIR = "/tmp/relay_heartbeat_test"
27
+ STUB_OK_PORT = 8821
28
+ STUB_PULL_PORT = 8822
29
+
30
+ ENV = dict(os.environ, PERSIST_DIR=PERSIST_DIR,
31
+ RUNNER_API_KEY="runner-key", AGENT_API_KEY="agent-key",
32
+ PUSH_URL_HOST_SUFFIX="*", RETENTION_SECONDS="10800",
33
+ HEARTBEAT_WINDOW_SECONDS="2", HEARTBEAT_TIMEOUT_SECONDS="1.0")
34
+ SPACE_DIR = os.path.join(os.path.dirname(__file__), "..")
35
+
36
+
37
+ def req(method, path, body=None, key="agent-key", timeout=15):
38
+ data = body if isinstance(body, (bytes, type(None))) else json.dumps(body).encode()
39
+ r = urllib.request.Request(BASE + path, data=data, method=method)
40
+ if key:
41
+ r.add_header("Authorization", f"Bearer {key}")
42
+ if not isinstance(body, bytes):
43
+ r.add_header("Content-Type", "application/json")
44
+ with urllib.request.urlopen(r, timeout=timeout) as resp:
45
+ return json.loads(resp.read().decode() or "{}")
46
+
47
+
48
+ class Stub(BaseHTTPRequestHandler):
49
+ hits = 0
50
+
51
+ def log_message(self, *a):
52
+ pass
53
+
54
+ def do_GET(self):
55
+ if self.path.rstrip("/") == "/health":
56
+ type(self).hits += 1
57
+ body = b'{"ok": true}'
58
+ self.send_response(200)
59
+ else:
60
+ body = b'{"detail": "not found"}'
61
+ self.send_response(404)
62
+ self.send_header("Content-Type", "application/json")
63
+ self.send_header("Content-Length", str(len(body)))
64
+ self.end_headers()
65
+ self.wfile.write(body)
66
+
67
+
68
+ def start_stub(port):
69
+ server = ThreadingHTTPServer(("127.0.0.1", port), Stub)
70
+ server.daemon_threads = True
71
+ threading.Thread(target=server.serve_forever, daemon=True).start()
72
+ return server
73
+
74
+
75
+ def main():
76
+ shutil.rmtree(PERSIST_DIR, ignore_errors=True)
77
+ Stub.hits = 0
78
+ ok = []
79
+
80
+ proc = subprocess.Popen([sys.executable, "-m", "uvicorn", "main:app",
81
+ "--host", "127.0.0.1", "--port", str(PORT)],
82
+ cwd=SPACE_DIR, env=ENV,
83
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
84
+ try:
85
+ for _ in range(60):
86
+ try:
87
+ urllib.request.urlopen(f"{BASE}/health", timeout=1)
88
+ break
89
+ except Exception:
90
+ time.sleep(0.5)
91
+ else:
92
+ proc.kill()
93
+ raise RuntimeError("boot failed")
94
+ print("1. booted (heartbeat window=2s)")
95
+
96
+ stub_ok = start_stub(STUB_OK_PORT)
97
+ stub_pull = start_stub(STUB_PULL_PORT)
98
+ env_desc = {"platform": "linux", "os_version": "ubuntu",
99
+ "runtimes": ["python-3.12"], "max_concurrent_jobs": 1}
100
+ req("POST", "/worker/register",
101
+ {"worker_id": 71, "url": f"http://127.0.0.1:{STUB_OK_PORT}",
102
+ "environment": env_desc}, key="runner-key")
103
+ req("POST", "/worker/register",
104
+ {"worker_id": 72, "url": "http://127.0.0.1:9",
105
+ "environment": env_desc}, key="runner-key")
106
+ req("POST", "/worker/register",
107
+ {"worker_id": 73, "url": "pull://73/deadbeefcafe",
108
+ "environment": env_desc}, key="runner-key")
109
+ ok.append("3 workers registered (healthy / unreachable / pull-mode)")
110
+
111
+ deadline = time.time() + 25
112
+ s71 = s72 = s73 = None
113
+ while time.time() < deadline:
114
+ status = req("GET", "/desktop/status")
115
+ by_id = {w["worker_id"]: w for w in status["workers"]}
116
+ s71, s72, s73 = by_id.get(71, {}), by_id.get(72, {}), by_id.get(73, {})
117
+ if (s71.get("last_heartbeat_ok_at") and int(s72.get("heartbeat_failures", 0)) >= 1):
118
+ break
119
+ time.sleep(0.5)
120
+
121
+ assert s71 and s71.get("last_heartbeat_ok_at"), f"healthy worker never got a heartbeat: {s71}"
122
+ assert int(s71.get("heartbeat_failures", 0)) == 0
123
+ assert s71.get("status") == "idle", s71 # observational: never disturbs eligibility
124
+ ok.append("healthy worker heartbeated; status still idle")
125
+
126
+ assert s72 and int(s72.get("heartbeat_failures", 0)) >= 1, f"unreachable worker never failed: {s72}"
127
+ ok.append("unreachable worker accumulated heartbeat_failures (no eligibility change)")
128
+
129
+ assert s73 and s73.get("last_heartbeat_at") is None, f"pull-mode worker was pinged: {s73}"
130
+ ok.append("pull-mode worker never pinged")
131
+
132
+ assert Stub.hits >= 1, "healthy stub never saw the ping land"
133
+
134
+ stub_ok.shutdown()
135
+ stub_pull.shutdown()
136
+ print("PASS:", " | ".join(ok))
137
+ return 0
138
+ finally:
139
+ proc.send_signal(signal.SIGTERM)
140
+ try:
141
+ proc.wait(timeout=10)
142
+ except Exception:
143
+ proc.kill()
144
+
145
+
146
+ if __name__ == "__main__":
147
+ sys.exit(main())