Spaces:
Sleeping

File size: 38,492 Bytes
0681a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfcb19
0681a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfcb19
 
 
 
 
 
 
 
 
0681a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfcb19
 
 
 
0681a6b
 
 
 
 
 
 
3cfcb19
 
 
 
0681a6b
 
 
 
 
 
 
 
 
 
 
 
 
3cfcb19
 
 
 
 
 
 
 
0681a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfcb19
0681a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfcb19
 
0681a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfcb19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0681a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfcb19
 
 
 
 
 
 
 
 
0681a6b
 
 
 
 
3cfcb19
 
 
0681a6b
3cfcb19
 
 
 
0681a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfcb19
 
 
 
 
0681a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfcb19
 
 
 
 
 
 
 
 
0681a6b
 
 
 
3cfcb19
0681a6b
3cfcb19
0681a6b
 
3cfcb19
 
 
 
 
0681a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfcb19
0681a6b
 
 
3cfcb19
0681a6b
 
 
 
 
 
3cfcb19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0681a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfcb19
 
 
 
 
 
 
 
 
 
0681a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
"""Relay v4 store — SSD/disk-backed, batch-first, PUSH delivery.

No artificial caps: payloads/results/artifacts live on disk; RAM holds only the small
index. Disk full is the only size limit, surfaced as an error — never a silent 413.

Push model: every queued cell that matches a registered runner is claimed atomically
and POSTed to that runner's intake URL (a Cloudflare quick tunnel the runner opened
outbound). The runner answers 2xx => the claim stands (claim deadline applies).
Non-2xx/unreachable => the claim rolls back to `queued` with per-worker backoff;
after MAX_PUSH_FAILURES consecutive failures the worker is marked `unresponsive`
and stops receiving pushes. Runner or Space crash => claim deadline / boot-time
recovery requeues the cell.
"""
import hashlib
import json
import logging
import os
import secrets
import threading
import time
import urllib.request
from itertools import product
from pathlib import Path
from typing import Dict, List, Optional

from .models import (ArtifactMeta, BatchSubmission, JobMeta, JobSubmission, ResultObject,
                     SCHEMA)

logger = logging.getLogger("archx_relay")

def now() -> float:
    return time.time()

def iso(ts: Optional[float]) -> Optional[str]:
    if ts is None:
        return None
    from datetime import datetime, timezone
    return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")

def gen_batch_id() -> str:
    return "batch_" + secrets.token_hex(8)

def gen_job_id() -> str:
    return "job_" + secrets.token_hex(6)

def artifact_id() -> str:
    return "art_" + secrets.token_hex(8)

KIND_BY_EXT = {
    ".png": "image", ".jpg": "image", ".jpeg": "image", ".gif": "image",
    ".webp": "image", ".bmp": "image", ".svg": "image", ".tiff": "image",
    ".mp3": "audio", ".wav": "audio", ".flac": "audio", ".ogg": "audio",
    ".m4a": "audio", ".aac": "audio", ".opus": "audio",
}
CT_BY_EXT = {
    ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
    ".webp": "image/webp", ".svg": "image/svg+xml", ".tiff": "image/tiff",
    ".mp3": "audio/mpeg", ".wav": "audio/wav", ".flac": "audio/flac", ".ogg": "audio/ogg",
    ".m4a": "audio/mp4", ".aac": "audio/aac", ".opus": "audio/opus",
}

def push_shutdown(url: str, bearer: str, timeout: float = 5.0):
    """Best-effort /shutdown push to a superseded runner generation. Never raises."""
    try:
        req = urllib.request.Request(
            url.rstrip("/") + "/shutdown", data=b'{"shutdown": true}', method="POST",
            headers={"Authorization": f"Bearer {bearer}", "Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=timeout):
            pass
    except Exception:
        logger.info("shutdown push to superseded runner did not land (it will exit on lifetime)")

def _http_push_json(url: str, payload: dict, bearer: str, timeout: float = 8.0) -> bool:
    try:
        req = urllib.request.Request(
            url, data=json.dumps(payload).encode(), method="POST",
            headers={"Authorization": f"Bearer {bearer}", "Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return 200 <= resp.status < 300
    except Exception as e:
        logger.warning("push to %s failed: %s: %s", url, e.__class__.__name__, str(e)[:120])
        return False

class Store:
    def __init__(self, root: str, push_bearer: str = ""):
        self.root = Path(root)
        for sub in ("state", "jobs", "results", "artifacts", "ledger"):
            (self.root / sub).mkdir(parents=True, exist_ok=True)
        self.retention_seconds = float(os.getenv("RETENTION_SECONDS", "10800"))  # 3h
        self.claim_buffer = float(os.getenv("CLAIM_TIMEOUT_BUFFER_SECONDS", "60"))
        self.max_retries = int(os.getenv("MAX_RETRIES", "3"))
        self.max_push_failures = int(os.getenv("MAX_PUSH_FAILURES", "3"))
        self.push_bearer = push_bearer

        self.lock = threading.RLock()
        self.state_changed = threading.Event()   # internal wake for the push/sweep loop
        self.workers: Dict[int, dict] = {}
        self.jobs: Dict[str, JobMeta] = {}
        self.batches: Dict[str, dict] = {}
        self.start_time = now()
        self.totals = {"batches": 0, "cells": 0, "completed": 0}
        self.push_failures: Dict[int, int] = {}
        self._push_next: Dict[str, float] = {}   # job_id -> earliest next push attempt
        # randomized heartbeat: one sparse ping per worker per window at an
        # os.urandom-backed random offset (never 2s polling — deliberately NOT
        # bot-like). Observational only: never affects push eligibility.
        self.heartbeat_window = float(os.getenv("HEARTBEAT_WINDOW_SECONDS", "1800"))   # 30 min; 0 = off
        self.heartbeat_timeout = float(os.getenv("HEARTBEAT_TIMEOUT_SECONDS", "5.0"))
        self._heartbeat_window_start = 0.0
        self._heartbeat_due: Dict[int, float] = {}    # worker_id -> ping ts in current window
        self._heartbeat_done: set = set()             # pinged this window
        self._heartbeat_inflight: set = set()         # ping in progress

        self._load_state()
        # every queued cell (incl. crash-recovered) needs a push attempt
        for jid, meta in self.jobs.items():
            if meta.status == "queued":
                self._push_next[jid] = 0.0

        self._stop = threading.Event()
        self._bg = threading.Thread(target=self._bg_loop, name="relay-bg", daemon=True)
        self._bg.start()

    # ============ persistence ============
    def _p(self, rel) -> Path:
        return self.root / rel

    def _save_json(self, rel, obj):
        """Atomic write-through via tmp+replace."""
        p = self._p(rel)
        p.parent.mkdir(parents=True, exist_ok=True)
        tmp = p.with_suffix(p.suffix + ".tmp")
        tmp.write_text(json.dumps(obj, separators=(",", ":")))
        os.replace(tmp, p)

    def _load_json(self, rel):
        p = self._p(rel)
        if not p.exists():
            return None
        try:
            return json.loads(p.read_text())
        except Exception as e:
            logger.error("corrupt %s: %s", rel, e)
            return None

    def _event(self, kind: str, **fields):
        try:
            line = json.dumps({"ts": iso(now()), "event": kind, **fields}, separators=(",", ":")) + "\n"
            with open(self._p(f"ledger/events-{int(now())//3600}.jsonl"), "a") as fh:
                fh.write(line)
        except Exception:
            logger.exception("ledger write failed")

    def _flush_state_locked(self):
        self._save_json("state/workers.json", {"schema": SCHEMA, "workers": self.workers})
        self._save_json("state/index.json",
                        {"schema": SCHEMA,
                         "jobs": [m.model_dump() for m in self.jobs.values()],
                         "batches": self.batches,
                         "totals": self.totals})

    def _wake(self):
        self.state_changed.set()

    # ============ crash recovery ============
    def _load_state(self):
        w = self._load_json("state/workers.json") or {}
        self.workers = w.get("workers", {}) if isinstance(w, dict) else {}
        for worker in self.workers.values():
            worker["last_seen_at"] = 0
            worker["reported_done"] = True   # stale generations never match after a reboot

        idx = self._load_json("state/index.json") or {}
        requeued = 0
        for m in idx.get("jobs", []):
            try:
                meta = JobMeta(**m)
            except Exception:
                continue
            if meta.status == "claimed":
                meta.status = "queued"
                meta.retry_count += 1
                meta.claimed_by = None
                meta.claimed_worker_url = None
                meta.claimed_at = None
                meta.claim_deadline = None
                meta.last_abandon_reason = "crash_recovery"
                requeued += 1
            self.jobs[meta.job_id] = meta
        self.batches = idx.get("batches", {}) if isinstance(idx.get("batches"), dict) else {}
        self.totals.update(idx.get("totals", {}))

        # reconcile orphan payloads
        for p in self._p("jobs").glob("*.json"):
            jid = p.name[:-5]
            if jid not in self.jobs:
                payload = self._load_json(f"jobs/{jid}.json")
                if payload:
                    self.jobs[jid] = JobMeta(
                        job_id=jid, base_job_id=payload.get("base_job_id", jid),
                        batch_id=payload.get("batch_id", "unknown"),
                        cell=payload.get("cell", "base"),
                        platform=payload.get("platform", "unknown"),
                        runtime=payload.get("runtime", "unknown"),
                        timeout=float(payload.get("timeout", 60)),
                        submitted_at=float(payload.get("submitted_at", now())),
                        last_abandon_reason="orphan_recovered")
                    requeued += 1
        if requeued:
            logger.warning("crash recovery requeued %d cell(s)", requeued)
        if self.workers or self.jobs:
            logger.info("recovered workers=%d cells=%d batches=%d",
                        len(self.workers), len(self.jobs), len(self.batches))
        self._sweep_locked(force=True)

    # ============ background sweep + push ============
    def _bg_loop(self):
        while not self._stop.wait(1.0):
            try:
                self._push_tick()                      # pushes are the critical path
            except Exception:
                logger.exception("background push tick error")
            try:
                with self.lock:
                    self._expire_claims_locked()
                    self._sweep_locked()
                    self._flush_state_locked()
            except Exception:
                logger.exception("background sweep error")
            try:
                self._heartbeat_tick()             # sparse + randomized; observational
            except Exception:
                logger.exception("background heartbeat tick error")

    def stop(self):
        self._stop.set()
        with self.lock:
            self._flush_state_locked()

    def _push_tick(self):
        """Claim matchable queued cells (under lock), then POST them to runners
        (outside the lock). One push attempt per cell per tick; backoff on failure."""
        with self.lock:
            claimed = self._claim_for_push_locked(max_claims=4)
        if not claimed:
            return
        for job_id, worker_id, urls, payload in claimed:
            ok = False
            for u in urls:                       # tunnel failover: first 2xx wins
                if _http_push_json(u.rstrip("/") + "/job", payload, self.push_bearer,
                                   timeout=8.0):
                    ok = True
                    break
            self._settle_push(job_id, worker_id, urls[0], ok)

    def _claim_for_push_locked(self, max_claims: int = 4):
        t = now()
        claimed = []
        for jid, earliest in list(self._push_next.items()):
            if len(claimed) >= max_claims:
                break
            if earliest > t:
                continue
            meta = self.jobs.get(jid)
            if meta is None or meta.status != "queued":
                del self._push_next[jid]
                continue
            w = self._pick_worker_locked(meta)
            if w is None:
                self._push_next[jid] = t + 5.0     # no eligible runner yet — retry soon
                continue
            payload = self._load_json(f"jobs/{jid}.json")
            if payload is None:
                self._complete_cell_locked(meta, {
                    "job_id": meta.job_id, "exit_code": 1, "timed_out": False,
                    "category": "infra_failure", "steps": [], "filesystem_state": None,
                    "artifacts": [], "failure_reason": "payload missing"})
                del self._push_next[jid]
                continue
            meta.status = "claimed"
            meta.claimed_by = w["worker_id"]
            meta.claimed_worker_url = w["url"]
            meta.claimed_at = t
            meta.claim_deadline = t + meta.timeout + self.claim_buffer
            claimed.append((jid, w["worker_id"], self._worker_urls(w), payload))
            del self._push_next[jid]
        if claimed:
            self._flush_state_locked()
            self._event("cells_claimed", count=len(claimed))
        return claimed

    def _pick_worker_locked(self, meta: JobMeta):
        best = None
        best_inflight = None
        for wid, w in self.workers.items():
            if w.get("reported_done"):
                continue
            if self.push_failures.get(wid, 0) >= self.max_push_failures:
                continue
            if w.get("pull_mode"):
                continue   # polls /worker/next instead of receiving pushes
            env = w.get("environment", {})
            if env.get("platform") != meta.platform:
                continue
            if meta.runtime not in set(env.get("runtimes", [])):
                continue
            inflight = sum(1 for j in self.jobs.values()
                           if j.status == "claimed" and j.claimed_by == wid)
            if inflight >= int(env.get("max_concurrent_jobs", 1)):
                continue
            if (best is None or inflight < best_inflight
                    or (inflight == best_inflight and wid < best["worker_id"])):
                best, best_inflight = w, inflight
        return best

    def claim_next(self, worker_id: int, url: str, limit: int = 1):
        """Pull-mode claim: a registered worker asks for its next cell(s).
        Returns the payload list, or None when the (worker_id, url) pair is not
        the currently registered generation (router maps that to 409)."""
        with self.lock:
            w = self.workers.get(worker_id)
            if not w or w.get("url") != url:
                return None
            if w.get("reported_done"):
                return []
            self._expire_claims_locked()
            env = w.get("environment", {}) or {}
            runtimes = set(env.get("runtimes", []))
            inflight = sum(1 for j in self.jobs.values()
                           if j.status == "claimed" and j.claimed_by == worker_id)
            remaining = max(0, int(env.get("max_concurrent_jobs", 1)) - inflight)
            limit = max(0, min(int(limit), remaining))
            out = []
            if limit <= 0:
                return out
            t = now()
            candidates = [(m.submitted_at, jid, m) for jid, m in self.jobs.items()
                          if m.status == "queued"]
            candidates.sort(key=lambda x: x[0])
            for _, jid, meta in candidates:
                if len(out) >= limit:
                    break
                if env.get("platform") != meta.platform:
                    continue
                if meta.runtime not in runtimes:
                    continue
                payload = self._load_json(f"jobs/{jid}.json")
                if payload is None:
                    self._complete_cell_locked(meta, {
                        "job_id": meta.job_id, "exit_code": 1, "timed_out": False,
                        "category": "infra_failure", "steps": [], "filesystem_state": None,
                        "artifacts": [], "failure_reason": "payload missing"})
                    self._push_next.pop(jid, None)
                    continue
                meta.status = "claimed"
                meta.claimed_by = worker_id
                meta.claimed_worker_url = url
                meta.claimed_at = t
                meta.claim_deadline = t + meta.timeout + self.claim_buffer
                self._push_next.pop(jid, None)
                out.append(payload)
            if out:
                self._flush_state_locked()
                self._event("cells_claimed", count=len(out), mode="pull", worker_id=worker_id)
            return out

    def _settle_push(self, job_id: str, worker_id: int, url: str, ok: bool):
        with self.lock:
            if ok:
                self.push_failures[worker_id] = 0
                w = self.workers.get(worker_id)
                if w and w.get("url") == url:
                    w["last_seen_at"] = now()
                self._flush_state_locked()
                return
            meta = self.jobs.get(job_id)
            if (meta is not None and meta.status == "claimed" and meta.claimed_by == worker_id
                    and meta.claimed_worker_url == url):
                meta.status = "queued"
                meta.claimed_by = None
                meta.claimed_worker_url = None
                meta.claimed_at = None
                meta.claim_deadline = None
            fails = self.push_failures.get(worker_id, 0) + 1
            self.push_failures[worker_id] = fails
            self._push_next[job_id] = now() + min(60.0, 5.0 * (2 ** (fails - 1)))
            if fails >= self.max_push_failures:
                logger.error("worker %d marked unresponsive after %d consecutive push failures",
                             worker_id, fails)
                self._event("worker_unresponsive", worker_id=worker_id, failures=fails)
            self._flush_state_locked()

    # ============ matrix expansion ============
    def _expand_job(self, job: JobSubmission, batch_id: str):
        """One JobSubmission -> N cells (cartesian of matrix dims). Returns payloads."""
        base_id = job.job_id or gen_job_id()
        platforms = (job.matrix.platforms if job.matrix and job.matrix.platforms else [job.platform])
        runtimes = (job.matrix.runtimes if job.matrix and job.matrix.runtimes else [job.runtime])
        case_list = (job.matrix.stdin_cases if job.matrix and job.matrix.stdin_cases else [job.stdin])
        expanded = []
        for platform, runtime, case in product(platforms, runtimes, case_list):
            cell_bits = [platform, runtime]
            case_idx = None
            if case is not None:
                case_idx = case_list.index(case) + 1
                cell_bits.append(f"case-{case_idx}")
            cell = "/".join(cell_bits)
            cell_id = f"{base_id}#{cell}".replace(" ", "-")
            files = dict(job.files)
            files.update(job.files_variants.get(platform, {}))   # OS-specific overlay wins
            expanded.append({
                "job_id": cell_id, "base_job_id": base_id, "batch_id": batch_id, "cell": cell,
                "platform": platform, "runtime": runtime, "files": files,
                "steps": [s.model_dump() for s in job.steps] if job.steps else None,
                "entry_point": job.entry_point,
                "dependencies": job.dependencies, "network_required": job.network_required,
                "stdin": case, "stdin_case": case_idx, "timeout": job.timeout,
                "stop_on_failure": job.stop_on_failure,
                "submitted_at": now(),
            })
        return expanded

    # ============ submission ============
    def submit_batch(self, batch: BatchSubmission) -> dict:
        with self.lock:
            if not batch.jobs:
                raise ValueError("batch must contain at least one job")
            batch_id = batch.batch_id or gen_batch_id()
            if batch_id in self.batches:
                raise ValueError(f"batch_id already exists: {batch_id}")
            cell_metas = []
            for job in batch.jobs:
                for payload in self._expand_job(job, batch_id):
                    if payload["job_id"] in self.jobs:
                        raise ValueError(f"job_id already exists: {payload['job_id']}")
                    self._save_json(f"jobs/{payload['job_id']}.json", payload)
                    meta = JobMeta(job_id=payload["job_id"], base_job_id=payload["base_job_id"],
                                   batch_id=batch_id, cell=payload["cell"],
                                   platform=payload["platform"], runtime=payload["runtime"],
                                   timeout=payload["timeout"], submitted_at=payload["submitted_at"],
                                   stdin_case=payload["stdin_case"])
                    self.jobs[meta.job_id] = meta
                    cell_metas.append(meta)
                    self.totals["cells"] += 1
            self.batches[batch_id] = {
                "batch_id": batch_id, "submitted_at": now(), "status": "pending",
                "completed_at": None, "job_ids": [m.job_id for m in cell_metas],
            }
            self.totals["batches"] += 1
            for m in cell_metas:
                self._push_next[m.job_id] = 0.0
            self._flush_state_locked()
            self._event("batch_submitted", batch_id=batch_id, cells=len(cell_metas))
            self._wake()
            return self._batch_public_locked(batch_id)

    # ============ worker lifecycle ============
    @staticmethod
    def _worker_urls(w: dict) -> List[str]:
        urls = w.get("urls") or []
        if w.get("url") and w["url"] not in urls:
            urls = [w["url"]] + urls
        return urls or [w.get("url", "")]

    def register_worker(self, worker_id: int, url: str, environment: dict,
                        urls: Optional[List[str]] = None):
        """Returns (public_view, old_url_to_supersede|None)."""
        with self.lock:
            prev = self.workers.get(worker_id)
            old_url = prev.get("url") if prev else None
            superseded = bool(prev and prev.get("url") != url)
            all_urls = urls or [url]
            if url not in all_urls:
                all_urls = [url] + list(all_urls)
            self.workers[worker_id] = {
                "worker_id": worker_id, "url": url, "urls": all_urls,
                "environment": environment,
                "registered_at": now(), "last_seen_at": now(), "reported_done": False,
                "pull_mode": url.startswith("pull://")}
            self.push_failures[worker_id] = 0
            # a fresh runner may match everything queued so far
            for jid, meta in self.jobs.items():
                if meta.status == "queued":
                    self._push_next.setdefault(jid, 0.0)
            self._flush_state_locked()
            self._event("worker_register", worker_id=worker_id, superseded=superseded)
            self._wake()
            return self._worker_public(worker_id), (old_url if superseded else None)

    def _worker_public(self, worker_id: int):
        w = self.workers.get(worker_id)
        if not w:
            return None
        return {"worker_id": worker_id, "environment": w["environment"],
                "registered_at": iso(w["registered_at"]), "last_seen_at": iso(w["last_seen_at"]),
                "status": self._worker_status(worker_id),
                "last_heartbeat_at": iso(w.get("last_heartbeat_at")),
                "last_heartbeat_ok_at": iso(w.get("last_heartbeat_ok_at")),
                "last_heartbeat_ok": w.get("last_heartbeat_ok"),
                "heartbeat_failures": w.get("heartbeat_failures", 0)}

    def _worker_status(self, worker_id: int):
        w = self.workers.get(worker_id)
        if not w:
            return "unknown"
        if w.get("reported_done"):
            return "draining"
        if self.push_failures.get(worker_id, 0) >= self.max_push_failures:
            return "unresponsive"
        if any(j.status == "claimed" and j.claimed_by == worker_id for j in self.jobs.values()):
            return "busy"
        return "idle"

    def report_result(self, worker_id: int, url: str, result: ResultObject):
        with self.lock:
            meta = self.jobs.get(result.job_id)
            if meta is None:
                raise KeyError("cell not found")
            if meta.status == "complete":
                # duplicate delivery ⇒ duplicate report; the first result already
                # recorded and counted — swallow quietly, do not double-count
                self._event("result_duplicate_ignored", job_id=meta.job_id,
                            worker_id=worker_id)
                return {"already_recorded": True}
            w = self.workers.get(worker_id)
            known = set(self._worker_urls(w)) if w else set()
            if meta.claimed_by != worker_id or (url not in known and url != meta.claimed_worker_url):
                raise PermissionError("cell not claimed by this worker instance")
            self._complete_cell_locked(meta, result.model_dump())
            self.push_failures[worker_id] = 0
            w = self.workers.get(worker_id)
            if w and url in self._worker_urls(w):
                w["last_seen_at"] = now()
            return {"already_recorded": False}

    def _complete_cell_locked(self, meta: JobMeta, result: dict):
        if meta.status == "complete":
            # defensive: unreachable via report_result's pre-check, but blocks
            # any future path from double-counting totals/batch completion
            self._event("cell_complete_duplicate_ignored", job_id=meta.job_id)
            return
        self._save_json(f"results/{meta.job_id}.json", result)
        meta.status = "complete"
        meta.completed_at = now()
        meta.claimed_by = None
        meta.claimed_worker_url = None
        meta.claimed_at = None
        meta.claim_deadline = None
        self.totals["completed"] += 1
        self._finalize_batches_locked()
        self._flush_state_locked()
        self._event("cell_completed", job_id=meta.job_id, category=result.get("category"))

    def report_done(self, worker_id: int, url: str):
        with self.lock:
            released = []
            w = self.workers.get(worker_id)
            if w and url in self._worker_urls(w):
                w["reported_done"] = True
                w["last_seen_at"] = now()
                for meta in self.jobs.values():
                    if meta.status == "claimed" and meta.claimed_by == worker_id:
                        self._abandon_cell_locked(meta, "worker reported done")
                        released.append(meta.job_id)
            self._flush_state_locked()
            self._wake()
            return released

    # ============ randomized heartbeat ============
    def _heartbeat_tick(self):
        if self.heartbeat_window <= 0:
            return
        t = now()
        if self._heartbeat_window_start == 0.0:
            self._heartbeat_window_start = (t // self.heartbeat_window) * self.heartbeat_window
        if t >= self._heartbeat_window_start + self.heartbeat_window:
            # roll to the CURRENT window (snap, don't step) — fresh dues, fresh offsets
            self._heartbeat_window_start = (t // self.heartbeat_window) * self.heartbeat_window
            self._heartbeat_due.clear()
            with self.lock:
                self._heartbeat_done.clear()
            logger.info("heartbeat: new window, %d worker(s) to schedule", len(self.workers))
        span = max(1, int(self.heartbeat_window))
        due_now = []
        with self.lock:
            for key, w in self.workers.items():
                try:
                    wid = int(w.get("worker_id", key))
                except (TypeError, ValueError):
                    continue
                if w.get("pull_mode") or w.get("reported_done"):
                    continue                              # pull workers check in by polling
                if wid in self._heartbeat_done or wid in self._heartbeat_inflight:
                    continue
                if wid not in self._heartbeat_due:
                    # os.urandom-backed (secrets) — every worker its own offset,
                    # every window different: irregular, never in lockstep
                    self._heartbeat_due[wid] = self._heartbeat_window_start + secrets.randbelow(span)
                elif t >= self._heartbeat_due[wid]:
                    due_now.append(wid)
            for wid in due_now:
                self._heartbeat_due.pop(wid, None)
                self._heartbeat_inflight.add(wid)
        for wid in due_now:
            w = self.workers.get(wid)
            urls = self._worker_urls(w) if w else []
            urls = [u for u in urls if u.startswith(("http://", "https://"))]
            if not urls:
                with self.lock:
                    self._heartbeat_inflight.discard(wid)
                    self._heartbeat_done.add(wid)
                continue
            threading.Thread(target=self._heartbeat_ping, args=(wid, urls),
                             name=f"hb-{wid}", daemon=True).start()

    def _heartbeat_ping(self, worker_id: int, urls: List[str]):
        ok = False
        for u in urls:                                # same tunnel order as pushes
            try:
                req = urllib.request.Request(u.rstrip("/") + "/health", method="GET")
                req.add_header("Authorization", f"Bearer {self.push_bearer}")
                with urllib.request.urlopen(req, timeout=self.heartbeat_timeout) as resp:
                    if resp.status == 200:
                        ok = True
                        break
            except Exception as e:
                # never log the URL; class name only
                logger.info("heartbeat to worker %d: %s", worker_id, e.__class__.__name__)
        with self.lock:
            w = self.workers.get(worker_id)
            if w is not None:
                w["last_heartbeat_at"] = now()
                w["last_heartbeat_ok"] = ok
                if ok:
                    w["last_heartbeat_ok_at"] = now()
                    w["heartbeat_failures"] = 0
                else:
                    w["heartbeat_failures"] = int(w.get("heartbeat_failures", 0)) + 1
            self._event("worker_heartbeat", worker_id=worker_id, ok=ok)
            self._flush_state_locked()
            self._heartbeat_inflight.discard(worker_id)
            self._heartbeat_done.add(worker_id)
        logger.info("heartbeat to worker %d: %s", worker_id, "ok" if ok else "FAILED")

    # ============ expiry / retention ============
    def _abandon_cell_locked(self, meta: JobMeta, reason: str):
        if meta.retry_count >= self.max_retries:
            self._complete_cell_locked(meta, {
                "job_id": meta.job_id, "exit_code": 1, "timed_out": False,
                "category": "infra_failure", "steps": [], "filesystem_state": None,
                "artifacts": [],
                "failure_reason": f"abandoned >{self.max_retries} times ({reason})"})
            return
        meta.retry_count += 1
        meta.status = "queued"
        meta.claimed_by = None
        meta.claimed_worker_url = None
        meta.claimed_at = None
        meta.claim_deadline = None
        meta.last_abandon_reason = reason
        self._push_next[meta.job_id] = now()
        self._wake()

    def _expire_claims_locked(self):
        t = now()
        changed = False
        for meta in self.jobs.values():
            if meta.status == "claimed" and meta.claim_deadline and t >= meta.claim_deadline:
                self._abandon_cell_locked(meta, "claim timeout")
                changed = True
        if changed:
            self._wake()

    def _sweep_locked(self, force: bool = False):
        t = now()
        for jid, meta in list(self.jobs.items()):
            if meta.status == "complete" and meta.completed_at and (t - meta.completed_at) > self.retention_seconds:
                self._delete_cell_files(jid)
                del self.jobs[jid]
        for rid, b in list(self.batches.items()):
            ref = b.get("completed_at") or b["submitted_at"]
            if ref and (t - ref) > self.retention_seconds:
                for jid in b["job_ids"]:
                    self._delete_cell_files(jid)
                    self.jobs.pop(jid, None)
                del self.batches[rid]
        # artifacts
        adir = self._p("artifacts")
        for meta_path in adir.glob("*.json"):
            meta = self._load_json(f"artifacts/{meta_path.name}")
            if meta and (t - meta.get("created_at", t)) > self.retention_seconds:
                aid = meta["artifact_id"]
                self._p(f"artifacts/{aid}.bin").unlink(missing_ok=True)
                meta_path.unlink(missing_ok=True)

    def _delete_cell_files(self, jid):
        self._p(f"jobs/{jid}.json").unlink(missing_ok=True)
        self._p(f"results/{jid}.json").unlink(missing_ok=True)

    # ============ batches ============
    def _batch_public_locked(self, batch_id: str):
        b = self.batches[batch_id]
        results = []
        completed = 0
        for jid in b["job_ids"]:
            meta = self.jobs.get(jid)
            if meta is None:
                results.append({"job_id": jid, "status": "missing"})
                continue
            item = {"job_id": jid, "status": meta.status, "cell": meta.cell,
                    "platform": meta.platform, "runtime": meta.runtime,
                    "stdin_case": meta.stdin_case}
            if meta.status == "complete":
                completed += 1
                item["result"] = self._load_json(f"results/{jid}.json")
            results.append(item)
        return {
            "batch_id": batch_id, "status": b["status"],
            "submitted_at": iso(b["submitted_at"]),
            "completed_at": iso(b.get("completed_at")),
            "job_count": len(b["job_ids"]),
            "completed_job_count": completed,
            "remaining": len(b["job_ids"]) - completed,
            "results": results,
        }

    def _finalize_batches_locked(self):
        for rid, b in self.batches.items():
            if b["status"] == "pending":
                if all(self.jobs.get(jid) is not None and self.jobs[jid].status == "complete" for jid in b["job_ids"]):
                    b["status"] = "complete"
                    b["completed_at"] = now()
                    self._event("batch_complete", batch_id=rid)

    def get_batch(self, batch_id: str, consume: bool = False):
        with self.lock:
            if batch_id not in self.batches:
                return None
            self._finalize_batches_locked()
            public = self._batch_public_locked(batch_id)
            if consume and public["status"] == "complete":
                self._delete_batch_locked(batch_id)
            return public

    def cancel_batch(self, batch_id: str):
        with self.lock:
            if batch_id not in self.batches:
                return None
            b = self.batches[batch_id]
            released = []
            for jid in b["job_ids"]:
                meta = self.jobs.get(jid)
                if meta and meta.status == "queued":
                    self._delete_cell_files(jid)
                    del self.jobs[jid]
                    self._push_next.pop(jid, None)
                    released.append(jid)
            del self.batches[batch_id]
            self._flush_state_locked()
            self._wake()
            self._event("batch_cancelled", batch_id=batch_id, released=len(released))
            return {"status": "cancelled", "batch_id": batch_id, "released_job_ids": released,
                    "note": "claimed cells will fail claim-check on report and be discarded"}

    def _delete_batch_locked(self, batch_id: str):
        b = self.batches.pop(batch_id, None)
        if not b:
            return
        for jid in b["job_ids"]:
            self.jobs.pop(jid, None)
            self._push_next.pop(jid, None)
            self._delete_cell_files(jid)
        self._flush_state_locked()
        self._event("batch_consumed", batch_id=batch_id)

    # ============ artifacts ============
    def store_artifact(self, batch_hint: Optional[str], job_hint: Optional[str],
                       rel_path: str, kind: Optional[str], content_type: Optional[str],
                       data: bytes) -> dict:
        sha = hashlib.sha256(data).hexdigest()
        job = job_hint or "unknown"
        adir = self._p("artifacts")
        for meta_path in adir.glob("*.json"):
            m = self._load_json(f"artifacts/{meta_path.name}")
            if (m and m.get("job_id") == job and m.get("path") == rel_path
                    and m.get("sha256") == sha):
                self._event("artifact_deduped", artifact_id=m["artifact_id"],
                            job_id=job, size=m.get("size"))
                return m   # identical bytes already stored for this cell+path
        ext = Path(rel_path).suffix.lower()
        meta = ArtifactMeta(
            artifact_id=artifact_id(), batch_id=batch_hint or "unknown", job_id=job_hint or "unknown",
            path=rel_path, kind=kind or KIND_BY_EXT.get(ext, "file"),
            content_type=content_type or CT_BY_EXT.get(ext, "application/octet-stream"),
            size=len(data), sha256=hashlib.sha256(data).hexdigest(), created_at=now())
        (self.root / "artifacts" / f"{meta.artifact_id}.bin").write_bytes(data)
        self._save_json(f"artifacts/{meta.artifact_id}.json", meta.model_dump())
        self._event("artifact_stored", artifact_id=meta.artifact_id, job_id=meta.job_id, size=meta.size)
        return meta.model_dump()

    def get_artifact(self, artifact_id: str):
        meta = self._load_json(f"artifacts/{artifact_id}.json")
        if not meta:
            return None, None
        return meta, self.root / "artifacts" / f"{artifact_id}.bin"

    # ============ admin ============
    def get_status(self):
        with self.lock:
            self._finalize_batches_locked()
            queued = sum(1 for j in self.jobs.values() if j.status == "queued")
            claimed = sum(1 for j in self.jobs.values() if j.status == "claimed")
            complete = sum(1 for j in self.jobs.values() if j.status == "complete")
            pending = sum(1 for b in self.batches.values() if b["status"] == "pending")
            return {
                "uptime_seconds": now() - self.start_time,
                "schema": SCHEMA,
                "totals": self.totals,
                "jobs_by_status": {"queued": queued, "claimed": claimed, "complete": complete},
                "pending_batches": pending,
                "workers": [self._worker_public(wid) for wid in self.workers],
                "retention_seconds": self.retention_seconds,
            }