Upload 10 files
Browse files- space/Dockerfile +10 -0
- space/README.md +106 -0
- space/main.py +40 -0
- space/projects/dataset_verification/__init__.py +0 -0
- space/projects/dataset_verification/models.py +105 -0
- space/projects/dataset_verification/router.py +194 -0
- space/projects/dataset_verification/store.py +823 -0
- space/requirements.txt +4 -0
- space/tests/e2e_test.py +500 -0
- space/tests/heartbeat_test.py +147 -0
space/Dockerfile
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
WORKDIR /app
|
| 3 |
+
COPY requirements.txt .
|
| 4 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 5 |
+
COPY . .
|
| 6 |
+
ENV PERSIST_DIR=/data/relay \
|
| 7 |
+
RETENTION_SECONDS=10800
|
| 8 |
+
EXPOSE 7860
|
| 9 |
+
# Attach Space Persistent Storage at /data for durability across rebuilds.
|
| 10 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
space/README.md
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Archx Relay Space (v4) — deploy & operate
|
| 2 |
+
|
| 3 |
+
Pure-push, batch-first relay for the Archx dataset workforce. One contract, no
|
| 4 |
+
artificial caps, no polling of any kind (the relay pushes jobs to the runner's
|
| 5 |
+
Cloudflare quick-tunnel URL).
|
| 6 |
+
|
| 7 |
+
> v4 = Cloudflare quick tunnels: runners dial out, get an ephemeral
|
| 8 |
+
> `https://<random>.trycloudflare.com` URL, register it, and receive jobs.
|
| 9 |
+
> No new secrets, no Cloudflare account, tunnel dies with the runner.
|
| 10 |
+
> See `../docs/relay-execution-architecture.md` for why (GitHub-hosted runners
|
| 11 |
+
> have no inbound address) and `../docs/deploy.md` for the from-scratch runbook.
|
| 12 |
+
|
| 13 |
+
## Contract (prefix `/dataset_verification`)
|
| 14 |
+
|
| 15 |
+
### Agent endpoints (`AGENT_API_KEY`)
|
| 16 |
+
| Endpoint | Purpose |
|
| 17 |
+
|---|---|
|
| 18 |
+
| `POST /desktop/batch` | Submit a batch. Body: `{batch_id?, jobs:[…]}`. **One batch_id for the whole batch.** |
|
| 19 |
+
| `GET /desktop/batch/{batch_id}` | Poll: `{status, job_count, completed_job_count, remaining, results:[…]}` with `?consume=true` to fetch-and-delete |
|
| 20 |
+
| `DELETE /desktop/batch/{batch_id}` | Cancel pending batch |
|
| 21 |
+
| `GET /desktop/artifact/{artifact_id}` | Stream artifact bytes (images/audio/any file) |
|
| 22 |
+
| `GET /desktop/status` | Schema, counters, per-worker liveness (**URLs redacted**) |
|
| 23 |
+
|
| 24 |
+
### Runner endpoints (`RUNNER_API_KEY`)
|
| 25 |
+
| Endpoint | Purpose |
|
| 26 |
+
|---|---|
|
| 27 |
+
| `POST /worker/register` | Mint/refresh identity; same `worker_id` + new url **supersedes** the old generation (old URL gets a `/shutdown` push) |
|
| 28 |
+
| `POST /worker/result` | Report one **cell** result |
|
| 29 |
+
| `POST /worker/artifact` | Upload artifact bytes (streamed to disk; no size constants) |
|
| 30 |
+
| `POST /worker/done` | Draining; releases claims |
|
| 31 |
+
|
| 32 |
+
Delivery (relay → runner): the relay atomically claims a matchable queued cell and
|
| 33 |
+
`POST`s it to `<runner-tunnel-url>/job` (`Authorization: Bearer RUNNER_API_KEY`).
|
| 34 |
+
`202` → executed; non-2xx/timeout → claim rolls back with backoff; 3 consecutive
|
| 35 |
+
failures → runner `unresponsive` until re-registered. There is **no** poll/stream
|
| 36 |
+
endpoint — runners never call in to ask for work.
|
| 37 |
+
|
| 38 |
+
### Job model
|
| 39 |
+
```jsonc
|
| 40 |
+
{
|
| 41 |
+
"batch_id": "batch_abc", // optional, returned as the batch id
|
| 42 |
+
"jobs": [{
|
| 43 |
+
"job_id": "job_1", // optional
|
| 44 |
+
"platform": "linux", // base (matrix overrides)
|
| 45 |
+
"runtime": "python-3.12", // base (matrix overrides)
|
| 46 |
+
"files": {"main.py": "…"}, // any number of files — multi-file example
|
| 47 |
+
"files_variants": {"windows": {"main.py": "…"}}, // per-OS overlay, applied on top of files
|
| 48 |
+
"entry_point": "python main.py", // single step, OR use steps:
|
| 49 |
+
"steps": [ // shared environment, sequential steps
|
| 50 |
+
{"name": "write", "entry_point": "python write_file.py"},
|
| 51 |
+
{"name": "read", "entry_point": "python read_file.py", "timeout": 30}
|
| 52 |
+
],
|
| 53 |
+
"dependencies": ["numpy"], // pip, installed once per cell venv
|
| 54 |
+
"network_required": false,
|
| 55 |
+
"stdin": "1 2\n", // or supply matrix.stdin_cases
|
| 56 |
+
"matrix": { // one example → many cells, ONE batch_id
|
| 57 |
+
"platforms": ["linux", "windows", "macos"],
|
| 58 |
+
"runtimes": ["python-3.11", "python-3.12", "python-3.13"],
|
| 59 |
+
"stdin_cases": ["1 2\n", "3 4 5\n"]
|
| 60 |
+
},
|
| 61 |
+
"timeout": 60, // per step default
|
| 62 |
+
"stop_on_failure": true
|
| 63 |
+
}]
|
| 64 |
+
}
|
| 65 |
+
```
|
| 66 |
+
Cells are cartesian products: 3 OS × 3 runtimes × 2 stdin cases = 18 cells, one batch.
|
| 67 |
+
Cell ids look like `job_1#windows/python-3.12/case-2`. Linux/Windows path differences
|
| 68 |
+
are solved by `files_variants` (+ caller-side `pathlib` idioms in generated jobs).
|
| 69 |
+
|
| 70 |
+
### Artifacts (images, audio, anything)
|
| 71 |
+
Jobs write deliverables under `outputs/`. The runner uploads them to the relay; the
|
| 72 |
+
agent downloads via `GET /desktop/artifact/{artifact_id}` with byte-exact integrity
|
| 73 |
+
(`X-Artifact-SHA256` header). Typical uses: generated plots for vision analysis,
|
| 74 |
+
generated audio for ASR/tts evals, logs. Artifacts share the 3-hour retention TTL.
|
| 75 |
+
|
| 76 |
+
### No caps
|
| 77 |
+
Request-size middleware is absent; artifact uploads stream to disk in chunks;
|
| 78 |
+
batches are unlimited in count. The only limits are physics: Space RAM (index is
|
| 79 |
+
tiny), Space disk (payloads+artifacts), claim deadlines, and the 3-hour retention.
|
| 80 |
+
If the Space runs out of disk, jobs fail loudly (`infra_failure`) — never silently.
|
| 81 |
+
|
| 82 |
+
## Deploy
|
| 83 |
+
See **`../docs/deploy.md`** — the exact from-scratch runbook (secrets reset →
|
| 84 |
+
Persistent Storage → secrets → deploy → verify → pilot). Short version:
|
| 85 |
+
`.github/workflows/deploy_space.yml` pushes this directory to the HF Space on change;
|
| 86 |
+
the Space needs exactly two secrets (`AGENT_API_KEY`, `RUNNER_API_KEY`) and
|
| 87 |
+
Persistent Storage mounted at `/data`.
|
| 88 |
+
|
| 89 |
+
## Test
|
| 90 |
+
```bash
|
| 91 |
+
cd space
|
| 92 |
+
python tests/e2e_test.py # matrix expansion, push delivery (real worker subprocess),
|
| 93 |
+
# crash -> requeue -> recovery, supersede /shutdown,
|
| 94 |
+
# artifact round-trip, batch consume — all local, no network
|
| 95 |
+
```
|
| 96 |
+
Passes locally in ~30 s (Python 3.11+, no network).
|
| 97 |
+
|
| 98 |
+
## Operations
|
| 99 |
+
- Crash safety: jobs claimed at crash are requeued on boot; orphan payloads are
|
| 100 |
+
reconciled; results are atomic (tmp+rename). A Space rebuild loses nothing queued.
|
| 101 |
+
- Supersede: cron mints new runner generations every 5h; the relay forgets the old
|
| 102 |
+
tunnel URL and pushes `/shutdown` to it; in-flight cells finish or their claim
|
| 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.)
|
space/main.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
import os
|
| 3 |
+
import pkgutil
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from fastapi import FastAPI, Request
|
| 6 |
+
from fastapi.responses import JSONResponse
|
| 7 |
+
|
| 8 |
+
# NO request-size cap. Payload bytes are streamed straight to disk by the
|
| 9 |
+
# artifact endpoint; JSON bodies are the only in-memory part (uvicorn default).
|
| 10 |
+
# Disk is the only size limit — failure surfaces as an error, never a silent truncation.
|
| 11 |
+
|
| 12 |
+
app = FastAPI(title="Archx Relay v4", version="4.0.0")
|
| 13 |
+
|
| 14 |
+
_routers = []
|
| 15 |
+
projects_dir = Path(__file__).parent / "projects"
|
| 16 |
+
if projects_dir.exists():
|
| 17 |
+
for module_info in pkgutil.iter_modules([str(projects_dir)]):
|
| 18 |
+
if not module_info.ispkg:
|
| 19 |
+
continue
|
| 20 |
+
name = module_info.name
|
| 21 |
+
try:
|
| 22 |
+
mod = importlib.import_module(f"projects.{name}.router")
|
| 23 |
+
app.include_router(mod.router, prefix=f"/{name}")
|
| 24 |
+
_routers.append(name)
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(f"Failed to load project '{name}': {e}", flush=True)
|
| 27 |
+
|
| 28 |
+
@app.get("/health")
|
| 29 |
+
def health():
|
| 30 |
+
return {"online": "yes", "projects": _routers}
|
| 31 |
+
|
| 32 |
+
@app.on_event("shutdown")
|
| 33 |
+
def _shutdown():
|
| 34 |
+
for name in _routers:
|
| 35 |
+
try:
|
| 36 |
+
mod = importlib.import_module(f"projects.{name}.router")
|
| 37 |
+
if hasattr(mod, "store"):
|
| 38 |
+
mod.store.stop()
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print(f"shutdown flush failed for {name}: {e}", flush=True)
|
space/projects/dataset_verification/__init__.py
ADDED
|
File without changes
|
space/projects/dataset_verification/models.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Relay v4 models — one clean contract, no artificial caps.
|
| 2 |
+
|
| 3 |
+
Concepts
|
| 4 |
+
--------
|
| 5 |
+
Batch — every submission is a batch; the batch as a whole gets one id.
|
| 6 |
+
Job — one example (multi-file, shared env, steps). Expanded server-side into
|
| 7 |
+
*cells* when it carries a matrix (platform × runtime × stdin_cases).
|
| 8 |
+
Cell — the executable unit (a row in the index). job_id = "<job_id>#<cell>".
|
| 9 |
+
Step — a command sequence executed in the SAME workdir/venv, in order
|
| 10 |
+
(cross-example dependency, e.g. "create file" → "read it").
|
| 11 |
+
Artifact — any file produced under outputs/ — images, audio, logs, binaries.
|
| 12 |
+
Stored on disk, downloaded by agents via streaming GET (no base64 bloat).
|
| 13 |
+
"""
|
| 14 |
+
from typing import Dict, List, Literal, Optional
|
| 15 |
+
from pydantic import BaseModel, Field
|
| 16 |
+
|
| 17 |
+
SCHEMA = 4
|
| 18 |
+
|
| 19 |
+
class JobStep(BaseModel):
|
| 20 |
+
name: str
|
| 21 |
+
entry_point: str
|
| 22 |
+
timeout: float = 60
|
| 23 |
+
dependencies: List[str] = Field(default_factory=list) # pip installs before this step
|
| 24 |
+
|
| 25 |
+
class JobMatrix(BaseModel):
|
| 26 |
+
platforms: List[str] = Field(default_factory=list) # e.g. ["linux", "windows", "macos"]
|
| 27 |
+
runtimes: List[str] = Field(default_factory=list) # e.g. ["python-3.11", "python-3.13", "node-22"]
|
| 28 |
+
stdin_cases: List[str] = Field(default_factory=list) # e.g. ["1 2\n", "3 4 5\n"]
|
| 29 |
+
|
| 30 |
+
class JobSubmission(BaseModel):
|
| 31 |
+
job_id: Optional[str] = None
|
| 32 |
+
platform: str # base platform (used if matrix.platforms empty)
|
| 33 |
+
runtime: str # base runtime tag (used if matrix.runtimes empty)
|
| 34 |
+
files: Dict[str, str] = Field(default_factory=dict) # base files {relpath: text}
|
| 35 |
+
files_variants: Dict[str, Dict[str, str]] = Field(default_factory=dict) # platform -> overlay files
|
| 36 |
+
entry_point: Optional[str] = None # single-step compat
|
| 37 |
+
steps: Optional[List[JobStep]] = None # preferred: shared env, sequential
|
| 38 |
+
dependencies: List[str] = Field(default_factory=list)
|
| 39 |
+
network_required: bool = False
|
| 40 |
+
stdin: Optional[str] = None
|
| 41 |
+
matrix: Optional[JobMatrix] = None
|
| 42 |
+
timeout: float = 60 # per step unless step overrides
|
| 43 |
+
stop_on_failure: bool = True
|
| 44 |
+
|
| 45 |
+
class BatchSubmission(BaseModel):
|
| 46 |
+
batch_id: Optional[str] = None
|
| 47 |
+
jobs: List[JobSubmission] = Field(default_factory=list)
|
| 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):
|
| 56 |
+
platform: str
|
| 57 |
+
os_version: str
|
| 58 |
+
runtimes: List[str] # runtime tags this runner can execute
|
| 59 |
+
max_concurrent_jobs: int = 4
|
| 60 |
+
notes: Optional[str] = None
|
| 61 |
+
|
| 62 |
+
class ResultObject(BaseModel):
|
| 63 |
+
job_id: str # cell id: "<base>#<cell>"
|
| 64 |
+
exit_code: int
|
| 65 |
+
timed_out: bool
|
| 66 |
+
category: Literal["success", "timeout", "dependency_install_failed",
|
| 67 |
+
"infra_failure", "checker_error", "not_applicable"]
|
| 68 |
+
steps: List[Dict] = Field(default_factory=list) # per-step {name,stdout,stderr,exit_code,timed_out}
|
| 69 |
+
filesystem_state: Optional[Dict[str, str]] = None # relpath -> "sha256:.." | "b64:.."
|
| 70 |
+
artifacts: List[Dict] = Field(default_factory=list) # artifact refs declared by runner
|
| 71 |
+
failure_reason: Optional[str] = None
|
| 72 |
+
|
| 73 |
+
WorkerRegisterRequest.model_rebuild()
|
| 74 |
+
|
| 75 |
+
# ---- internal index row (never serialized to callers) ----
|
| 76 |
+
class JobMeta(BaseModel):
|
| 77 |
+
job_id: str # cell id
|
| 78 |
+
base_job_id: str # original job_id from the batch
|
| 79 |
+
batch_id: str
|
| 80 |
+
cell: str # e.g. "linux/python-3.12/case-1" or "base"
|
| 81 |
+
platform: str
|
| 82 |
+
runtime: str
|
| 83 |
+
timeout: float
|
| 84 |
+
status: str = "queued" # queued | claimed | complete
|
| 85 |
+
submitted_at: float
|
| 86 |
+
retry_count: int = 0
|
| 87 |
+
claimed_by: Optional[int] = None
|
| 88 |
+
claimed_worker_url: Optional[str] = None
|
| 89 |
+
claimed_at: Optional[float] = None
|
| 90 |
+
claim_deadline: Optional[float] = None
|
| 91 |
+
completed_at: Optional[float] = None
|
| 92 |
+
last_abandon_reason: Optional[str] = None
|
| 93 |
+
stdin_case: Optional[int] = None
|
| 94 |
+
|
| 95 |
+
# ---- artifact metadata (stored in artifacts/<id>.json; bytes in artifacts/<id>.bin) ----
|
| 96 |
+
class ArtifactMeta(BaseModel):
|
| 97 |
+
artifact_id: str
|
| 98 |
+
batch_id: str
|
| 99 |
+
job_id: str # cell id
|
| 100 |
+
path: str # path inside the job workdir
|
| 101 |
+
kind: str # image | audio | file
|
| 102 |
+
content_type: str
|
| 103 |
+
size: int
|
| 104 |
+
sha256: str
|
| 105 |
+
created_at: float
|
space/projects/dataset_verification/router.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Relay v4 router — push-based, batch-first, artifact-capable.
|
| 2 |
+
|
| 3 |
+
Prefix (mounted by main.py): /dataset_verification
|
| 4 |
+
|
| 5 |
+
Agent endpoints (AGENT_API_KEY):
|
| 6 |
+
POST /desktop/batch submit a batch -> {batch_id, ...}
|
| 7 |
+
GET /desktop/batch/{batch_id} poll; ?consume=true to fetch-and-delete
|
| 8 |
+
DELETE /desktop/batch/{batch_id} cancel a pending batch
|
| 9 |
+
GET /desktop/artifact/{artifact_id} stream artifact bytes (image/audio/file)
|
| 10 |
+
GET /desktop/status schema / counters / worker liveness (URLs redacted)
|
| 11 |
+
|
| 12 |
+
Runner endpoints (RUNNER_API_KEY):
|
| 13 |
+
POST /worker/register mint/refresh identity (same worker_id + new url supersedes old generation)
|
| 14 |
+
POST /worker/result report one cell result
|
| 15 |
+
POST /worker/artifact upload artifact bytes (raw body, streamed to disk)
|
| 16 |
+
POST /worker/done declare draining; releases claims
|
| 17 |
+
GET /health unauthenticated liveness
|
| 18 |
+
|
| 19 |
+
Delivery is PUSH: after a runner registers (or a batch is submitted), the store
|
| 20 |
+
atomically claims matchable queued cells and POSTs them to the runner's own intake
|
| 21 |
+
URL (a Cloudflare quick tunnel the runner opened outbound). There is NO poll/stream
|
| 22 |
+
endpoint — runners never call in to ask for work.
|
| 23 |
+
"""
|
| 24 |
+
import os
|
| 25 |
+
import secrets
|
| 26 |
+
import threading
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
from urllib.parse import urlparse
|
| 29 |
+
|
| 30 |
+
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
| 31 |
+
from fastapi.responses import FileResponse
|
| 32 |
+
|
| 33 |
+
from .models import ResultObject, WorkerRegisterRequest
|
| 34 |
+
from .store import Store, push_shutdown
|
| 35 |
+
import os as _os
|
| 36 |
+
|
| 37 |
+
router = APIRouter()
|
| 38 |
+
store = Store(_os.getenv("PERSIST_DIR", "./persist"),
|
| 39 |
+
push_bearer=_os.getenv("RUNNER_API_KEY", ""))
|
| 40 |
+
|
| 41 |
+
RUNNER_API_KEY = _os.getenv("RUNNER_API_KEY", "")
|
| 42 |
+
AGENT_API_KEY = _os.getenv("AGENT_API_KEY", "")
|
| 43 |
+
|
| 44 |
+
def _auth(expected):
|
| 45 |
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
| 46 |
+
security = HTTPBearer(auto_error=False)
|
| 47 |
+
def dep(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
| 48 |
+
if (not expected or not credentials or credentials.scheme.lower() != "bearer"
|
| 49 |
+
or not secrets.compare_digest(credentials.credentials.encode(), expected.encode())):
|
| 50 |
+
raise HTTPException(status_code=401, detail="Unauthorized")
|
| 51 |
+
return dep
|
| 52 |
+
|
| 53 |
+
worker_auth = _auth(RUNNER_API_KEY)
|
| 54 |
+
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). 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
|
| 65 |
+
p = urlparse(url)
|
| 66 |
+
if p.scheme != "https" or not p.hostname:
|
| 67 |
+
return "push URL must be https://<host>"
|
| 68 |
+
if not p.hostname.endswith(suffix):
|
| 69 |
+
return f"push URL host must end with {suffix}"
|
| 70 |
+
return None
|
| 71 |
+
|
| 72 |
+
# ---------------- agent endpoints ----------------
|
| 73 |
+
|
| 74 |
+
@router.post("/desktop/batch", dependencies=[Depends(desktop_auth)])
|
| 75 |
+
def desktop_submit_batch(body: dict):
|
| 76 |
+
from .models import BatchSubmission
|
| 77 |
+
try:
|
| 78 |
+
batch = BatchSubmission(**body)
|
| 79 |
+
except Exception as e:
|
| 80 |
+
raise HTTPException(status_code=422, detail=str(e))
|
| 81 |
+
try:
|
| 82 |
+
return store.submit_batch(batch)
|
| 83 |
+
except ValueError as e:
|
| 84 |
+
raise HTTPException(status_code=409, detail=str(e))
|
| 85 |
+
|
| 86 |
+
@router.get("/desktop/batch/{batch_id}", dependencies=[Depends(desktop_auth)])
|
| 87 |
+
def desktop_get_batch(batch_id: str, consume: bool = Query(False)):
|
| 88 |
+
res = store.get_batch(batch_id, consume=consume)
|
| 89 |
+
if res is None:
|
| 90 |
+
raise HTTPException(status_code=404, detail="batch not found")
|
| 91 |
+
return res
|
| 92 |
+
|
| 93 |
+
@router.delete("/desktop/batch/{batch_id}", dependencies=[Depends(desktop_auth)])
|
| 94 |
+
def desktop_cancel_batch(batch_id: str):
|
| 95 |
+
res = store.cancel_batch(batch_id)
|
| 96 |
+
if res is None:
|
| 97 |
+
raise HTTPException(status_code=404, detail="batch not found")
|
| 98 |
+
return res
|
| 99 |
+
|
| 100 |
+
@router.get("/desktop/artifact/{artifact_id}", dependencies=[Depends(desktop_auth)])
|
| 101 |
+
def desktop_get_artifact(artifact_id: str):
|
| 102 |
+
meta, path = store.get_artifact(artifact_id)
|
| 103 |
+
if meta is None:
|
| 104 |
+
raise HTTPException(status_code=404, detail="artifact not found or expired")
|
| 105 |
+
return FileResponse(path, media_type=meta["content_type"],
|
| 106 |
+
headers={"X-Artifact-Kind": meta["kind"],
|
| 107 |
+
"X-Artifact-SHA256": meta["sha256"],
|
| 108 |
+
"Content-Disposition": f'inline; filename="{Path(meta["path"]).name}"'})
|
| 109 |
+
|
| 110 |
+
@router.get("/desktop/status", dependencies=[Depends(desktop_auth)])
|
| 111 |
+
def desktop_status():
|
| 112 |
+
return store.get_status()
|
| 113 |
+
|
| 114 |
+
# ---------------- runner endpoints ----------------
|
| 115 |
+
|
| 116 |
+
@router.post("/worker/register", dependencies=[Depends(worker_auth)])
|
| 117 |
+
def worker_register(body: WorkerRegisterRequest):
|
| 118 |
+
url = body.url.strip()
|
| 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")
|
| 162 |
+
except PermissionError:
|
| 163 |
+
raise HTTPException(status_code=409, detail="cell not claimed by this worker instance")
|
| 164 |
+
|
| 165 |
+
@router.post("/worker/artifact", dependencies=[Depends(worker_auth)])
|
| 166 |
+
async def worker_artifact(request: Request,
|
| 167 |
+
job_id: str = Query(""),
|
| 168 |
+
batch_id: str = Query(""),
|
| 169 |
+
path: str = Query(...),
|
| 170 |
+
kind: str = Query(None),
|
| 171 |
+
content_type: str = Query(None)):
|
| 172 |
+
# streamed to disk in chunks — no whole-body RAM spike, no size constants
|
| 173 |
+
tmp = Path(_os.getenv("PERSIST_DIR", "./persist")) / "artifacts" / f".upload-{secrets.token_hex(8)}.bin"
|
| 174 |
+
tmp.parent.mkdir(parents=True, exist_ok=True)
|
| 175 |
+
with open(tmp, "wb") as fh:
|
| 176 |
+
async for chunk in request.stream():
|
| 177 |
+
fh.write(chunk)
|
| 178 |
+
data = tmp.read_bytes() # sha256 needs bytes; artifacts are outputs, typically <100MB
|
| 179 |
+
tmp.unlink()
|
| 180 |
+
meta = store.store_artifact(batch_id or None, job_id or None, path, kind, content_type, data)
|
| 181 |
+
return meta
|
| 182 |
+
|
| 183 |
+
@router.post("/worker/done", dependencies=[Depends(worker_auth)])
|
| 184 |
+
def worker_done(body: dict):
|
| 185 |
+
released = store.report_done(int(body["worker_id"]), body["url"])
|
| 186 |
+
return {"released_job_ids": released}
|
| 187 |
+
|
| 188 |
+
@router.get("/health")
|
| 189 |
+
def health():
|
| 190 |
+
s = store.get_status()
|
| 191 |
+
return {"online": "yes", "schema": s["schema"],
|
| 192 |
+
"pending_batches": s["pending_batches"],
|
| 193 |
+
"queued": s["jobs_by_status"]["queued"],
|
| 194 |
+
"workers_online": sum(1 for w in s["workers"] if w["status"] not in ("unresponsive", "draining"))}
|
space/projects/dataset_verification/store.py
ADDED
|
@@ -0,0 +1,823 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Relay v4 store — SSD/disk-backed, batch-first, PUSH delivery.
|
| 2 |
+
|
| 3 |
+
No artificial caps: payloads/results/artifacts live on disk; RAM holds only the small
|
| 4 |
+
index. Disk full is the only size limit, surfaced as an error — never a silent 413.
|
| 5 |
+
|
| 6 |
+
Push model: every queued cell that matches a registered runner is claimed atomically
|
| 7 |
+
and POSTed to that runner's intake URL (a Cloudflare quick tunnel the runner opened
|
| 8 |
+
outbound). The runner answers 2xx => the claim stands (claim deadline applies).
|
| 9 |
+
Non-2xx/unreachable => the claim rolls back to `queued` with per-worker backoff;
|
| 10 |
+
after MAX_PUSH_FAILURES consecutive failures the worker is marked `unresponsive`
|
| 11 |
+
and stops receiving pushes. Runner or Space crash => claim deadline / boot-time
|
| 12 |
+
recovery requeues the cell.
|
| 13 |
+
"""
|
| 14 |
+
import hashlib
|
| 15 |
+
import json
|
| 16 |
+
import logging
|
| 17 |
+
import os
|
| 18 |
+
import secrets
|
| 19 |
+
import threading
|
| 20 |
+
import time
|
| 21 |
+
import urllib.request
|
| 22 |
+
from itertools import product
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Dict, List, Optional
|
| 25 |
+
|
| 26 |
+
from .models import (ArtifactMeta, BatchSubmission, JobMeta, JobSubmission, ResultObject,
|
| 27 |
+
SCHEMA)
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger("archx_relay")
|
| 30 |
+
|
| 31 |
+
def now() -> float:
|
| 32 |
+
return time.time()
|
| 33 |
+
|
| 34 |
+
def iso(ts: Optional[float]) -> Optional[str]:
|
| 35 |
+
if ts is None:
|
| 36 |
+
return None
|
| 37 |
+
from datetime import datetime, timezone
|
| 38 |
+
return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
|
| 39 |
+
|
| 40 |
+
def gen_batch_id() -> str:
|
| 41 |
+
return "batch_" + secrets.token_hex(8)
|
| 42 |
+
|
| 43 |
+
def gen_job_id() -> str:
|
| 44 |
+
return "job_" + secrets.token_hex(6)
|
| 45 |
+
|
| 46 |
+
def artifact_id() -> str:
|
| 47 |
+
return "art_" + secrets.token_hex(8)
|
| 48 |
+
|
| 49 |
+
KIND_BY_EXT = {
|
| 50 |
+
".png": "image", ".jpg": "image", ".jpeg": "image", ".gif": "image",
|
| 51 |
+
".webp": "image", ".bmp": "image", ".svg": "image", ".tiff": "image",
|
| 52 |
+
".mp3": "audio", ".wav": "audio", ".flac": "audio", ".ogg": "audio",
|
| 53 |
+
".m4a": "audio", ".aac": "audio", ".opus": "audio",
|
| 54 |
+
}
|
| 55 |
+
CT_BY_EXT = {
|
| 56 |
+
".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
|
| 57 |
+
".webp": "image/webp", ".svg": "image/svg+xml", ".tiff": "image/tiff",
|
| 58 |
+
".mp3": "audio/mpeg", ".wav": "audio/wav", ".flac": "audio/flac", ".ogg": "audio/ogg",
|
| 59 |
+
".m4a": "audio/mp4", ".aac": "audio/aac", ".opus": "audio/opus",
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
def push_shutdown(url: str, bearer: str, timeout: float = 5.0):
|
| 63 |
+
"""Best-effort /shutdown push to a superseded runner generation. Never raises."""
|
| 64 |
+
try:
|
| 65 |
+
req = urllib.request.Request(
|
| 66 |
+
url.rstrip("/") + "/shutdown", data=b'{"shutdown": true}', method="POST",
|
| 67 |
+
headers={"Authorization": f"Bearer {bearer}", "Content-Type": "application/json"})
|
| 68 |
+
with urllib.request.urlopen(req, timeout=timeout):
|
| 69 |
+
pass
|
| 70 |
+
except Exception:
|
| 71 |
+
logger.info("shutdown push to superseded runner did not land (it will exit on lifetime)")
|
| 72 |
+
|
| 73 |
+
def _http_push_json(url: str, payload: dict, bearer: str, timeout: float = 8.0) -> bool:
|
| 74 |
+
try:
|
| 75 |
+
req = urllib.request.Request(
|
| 76 |
+
url, data=json.dumps(payload).encode(), method="POST",
|
| 77 |
+
headers={"Authorization": f"Bearer {bearer}", "Content-Type": "application/json"})
|
| 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:
|
| 85 |
+
def __init__(self, root: str, push_bearer: str = ""):
|
| 86 |
+
self.root = Path(root)
|
| 87 |
+
for sub in ("state", "jobs", "results", "artifacts", "ledger"):
|
| 88 |
+
(self.root / sub).mkdir(parents=True, exist_ok=True)
|
| 89 |
+
self.retention_seconds = float(os.getenv("RETENTION_SECONDS", "10800")) # 3h
|
| 90 |
+
self.claim_buffer = float(os.getenv("CLAIM_TIMEOUT_BUFFER_SECONDS", "60"))
|
| 91 |
+
self.max_retries = int(os.getenv("MAX_RETRIES", "3"))
|
| 92 |
+
self.max_push_failures = int(os.getenv("MAX_PUSH_FAILURES", "3"))
|
| 93 |
+
self.push_bearer = push_bearer
|
| 94 |
+
|
| 95 |
+
self.lock = threading.RLock()
|
| 96 |
+
self.state_changed = threading.Event() # internal wake for the push/sweep loop
|
| 97 |
+
self.workers: Dict[int, dict] = {}
|
| 98 |
+
self.jobs: Dict[str, JobMeta] = {}
|
| 99 |
+
self.batches: Dict[str, dict] = {}
|
| 100 |
+
self.start_time = now()
|
| 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
|
| 116 |
+
for jid, meta in self.jobs.items():
|
| 117 |
+
if meta.status == "queued":
|
| 118 |
+
self._push_next[jid] = 0.0
|
| 119 |
+
|
| 120 |
+
self._stop = threading.Event()
|
| 121 |
+
self._bg = threading.Thread(target=self._bg_loop, name="relay-bg", daemon=True)
|
| 122 |
+
self._bg.start()
|
| 123 |
+
|
| 124 |
+
# ============ persistence ============
|
| 125 |
+
def _p(self, rel) -> Path:
|
| 126 |
+
return self.root / rel
|
| 127 |
+
|
| 128 |
+
def _save_json(self, rel, obj):
|
| 129 |
+
"""Atomic write-through via tmp+replace."""
|
| 130 |
+
p = self._p(rel)
|
| 131 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 132 |
+
tmp = p.with_suffix(p.suffix + ".tmp")
|
| 133 |
+
tmp.write_text(json.dumps(obj, separators=(",", ":")))
|
| 134 |
+
os.replace(tmp, p)
|
| 135 |
+
|
| 136 |
+
def _load_json(self, rel):
|
| 137 |
+
p = self._p(rel)
|
| 138 |
+
if not p.exists():
|
| 139 |
+
return None
|
| 140 |
+
try:
|
| 141 |
+
return json.loads(p.read_text())
|
| 142 |
+
except Exception as e:
|
| 143 |
+
logger.error("corrupt %s: %s", rel, e)
|
| 144 |
+
return None
|
| 145 |
+
|
| 146 |
+
def _event(self, kind: str, **fields):
|
| 147 |
+
try:
|
| 148 |
+
line = json.dumps({"ts": iso(now()), "event": kind, **fields}, separators=(",", ":")) + "\n"
|
| 149 |
+
with open(self._p(f"ledger/events-{int(now())//3600}.jsonl"), "a") as fh:
|
| 150 |
+
fh.write(line)
|
| 151 |
+
except Exception:
|
| 152 |
+
logger.exception("ledger write failed")
|
| 153 |
+
|
| 154 |
+
def _flush_state_locked(self):
|
| 155 |
+
self._save_json("state/workers.json", {"schema": SCHEMA, "workers": self.workers})
|
| 156 |
+
self._save_json("state/index.json",
|
| 157 |
+
{"schema": SCHEMA,
|
| 158 |
+
"jobs": [m.model_dump() for m in self.jobs.values()],
|
| 159 |
+
"batches": self.batches,
|
| 160 |
+
"totals": self.totals})
|
| 161 |
+
|
| 162 |
+
def _wake(self):
|
| 163 |
+
self.state_changed.set()
|
| 164 |
+
|
| 165 |
+
# ============ crash recovery ============
|
| 166 |
+
def _load_state(self):
|
| 167 |
+
w = self._load_json("state/workers.json") or {}
|
| 168 |
+
self.workers = w.get("workers", {}) if isinstance(w, dict) else {}
|
| 169 |
+
for worker in self.workers.values():
|
| 170 |
+
worker["last_seen_at"] = 0
|
| 171 |
+
worker["reported_done"] = True # stale generations never match after a reboot
|
| 172 |
+
|
| 173 |
+
idx = self._load_json("state/index.json") or {}
|
| 174 |
+
requeued = 0
|
| 175 |
+
for m in idx.get("jobs", []):
|
| 176 |
+
try:
|
| 177 |
+
meta = JobMeta(**m)
|
| 178 |
+
except Exception:
|
| 179 |
+
continue
|
| 180 |
+
if meta.status == "claimed":
|
| 181 |
+
meta.status = "queued"
|
| 182 |
+
meta.retry_count += 1
|
| 183 |
+
meta.claimed_by = None
|
| 184 |
+
meta.claimed_worker_url = None
|
| 185 |
+
meta.claimed_at = None
|
| 186 |
+
meta.claim_deadline = None
|
| 187 |
+
meta.last_abandon_reason = "crash_recovery"
|
| 188 |
+
requeued += 1
|
| 189 |
+
self.jobs[meta.job_id] = meta
|
| 190 |
+
self.batches = idx.get("batches", {}) if isinstance(idx.get("batches"), dict) else {}
|
| 191 |
+
self.totals.update(idx.get("totals", {}))
|
| 192 |
+
|
| 193 |
+
# reconcile orphan payloads
|
| 194 |
+
for p in self._p("jobs").glob("*.json"):
|
| 195 |
+
jid = p.name[:-5]
|
| 196 |
+
if jid not in self.jobs:
|
| 197 |
+
payload = self._load_json(f"jobs/{jid}.json")
|
| 198 |
+
if payload:
|
| 199 |
+
self.jobs[jid] = JobMeta(
|
| 200 |
+
job_id=jid, base_job_id=payload.get("base_job_id", jid),
|
| 201 |
+
batch_id=payload.get("batch_id", "unknown"),
|
| 202 |
+
cell=payload.get("cell", "base"),
|
| 203 |
+
platform=payload.get("platform", "unknown"),
|
| 204 |
+
runtime=payload.get("runtime", "unknown"),
|
| 205 |
+
timeout=float(payload.get("timeout", 60)),
|
| 206 |
+
submitted_at=float(payload.get("submitted_at", now())),
|
| 207 |
+
last_abandon_reason="orphan_recovered")
|
| 208 |
+
requeued += 1
|
| 209 |
+
if requeued:
|
| 210 |
+
logger.warning("crash recovery requeued %d cell(s)", requeued)
|
| 211 |
+
if self.workers or self.jobs:
|
| 212 |
+
logger.info("recovered workers=%d cells=%d batches=%d",
|
| 213 |
+
len(self.workers), len(self.jobs), len(self.batches))
|
| 214 |
+
self._sweep_locked(force=True)
|
| 215 |
+
|
| 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()
|
| 237 |
+
with self.lock:
|
| 238 |
+
self._flush_state_locked()
|
| 239 |
+
|
| 240 |
+
def _push_tick(self):
|
| 241 |
+
"""Claim matchable queued cells (under lock), then POST them to runners
|
| 242 |
+
(outside the lock). One push attempt per cell per tick; backoff on failure."""
|
| 243 |
+
with self.lock:
|
| 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()
|
| 258 |
+
claimed = []
|
| 259 |
+
for jid, earliest in list(self._push_next.items()):
|
| 260 |
+
if len(claimed) >= max_claims:
|
| 261 |
+
break
|
| 262 |
+
if earliest > t:
|
| 263 |
+
continue
|
| 264 |
+
meta = self.jobs.get(jid)
|
| 265 |
+
if meta is None or meta.status != "queued":
|
| 266 |
+
del self._push_next[jid]
|
| 267 |
+
continue
|
| 268 |
+
w = self._pick_worker_locked(meta)
|
| 269 |
+
if w is None:
|
| 270 |
+
self._push_next[jid] = t + 5.0 # no eligible runner yet — retry soon
|
| 271 |
+
continue
|
| 272 |
+
payload = self._load_json(f"jobs/{jid}.json")
|
| 273 |
+
if payload is None:
|
| 274 |
+
self._complete_cell_locked(meta, {
|
| 275 |
+
"job_id": meta.job_id, "exit_code": 1, "timed_out": False,
|
| 276 |
+
"category": "infra_failure", "steps": [], "filesystem_state": None,
|
| 277 |
+
"artifacts": [], "failure_reason": "payload missing"})
|
| 278 |
+
del self._push_next[jid]
|
| 279 |
+
continue
|
| 280 |
+
meta.status = "claimed"
|
| 281 |
+
meta.claimed_by = w["worker_id"]
|
| 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()
|
| 289 |
+
self._event("cells_claimed", count=len(claimed))
|
| 290 |
+
return claimed
|
| 291 |
+
|
| 292 |
+
def _pick_worker_locked(self, meta: JobMeta):
|
| 293 |
+
best = None
|
| 294 |
+
best_inflight = None
|
| 295 |
+
for wid, w in self.workers.items():
|
| 296 |
+
if w.get("reported_done"):
|
| 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
|
| 305 |
+
if meta.runtime not in set(env.get("runtimes", [])):
|
| 306 |
+
continue
|
| 307 |
+
inflight = sum(1 for j in self.jobs.values()
|
| 308 |
+
if j.status == "claimed" and j.claimed_by == wid)
|
| 309 |
+
if inflight >= int(env.get("max_concurrent_jobs", 1)):
|
| 310 |
+
continue
|
| 311 |
+
if (best is None or inflight < best_inflight
|
| 312 |
+
or (inflight == best_inflight and wid < best["worker_id"])):
|
| 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:
|
| 370 |
+
self.push_failures[worker_id] = 0
|
| 371 |
+
w = self.workers.get(worker_id)
|
| 372 |
+
if w and w.get("url") == url:
|
| 373 |
+
w["last_seen_at"] = now()
|
| 374 |
+
self._flush_state_locked()
|
| 375 |
+
return
|
| 376 |
+
meta = self.jobs.get(job_id)
|
| 377 |
+
if (meta is not None and meta.status == "claimed" and meta.claimed_by == worker_id
|
| 378 |
+
and meta.claimed_worker_url == url):
|
| 379 |
+
meta.status = "queued"
|
| 380 |
+
meta.claimed_by = None
|
| 381 |
+
meta.claimed_worker_url = None
|
| 382 |
+
meta.claimed_at = None
|
| 383 |
+
meta.claim_deadline = None
|
| 384 |
+
fails = self.push_failures.get(worker_id, 0) + 1
|
| 385 |
+
self.push_failures[worker_id] = fails
|
| 386 |
+
self._push_next[job_id] = now() + min(60.0, 5.0 * (2 ** (fails - 1)))
|
| 387 |
+
if fails >= self.max_push_failures:
|
| 388 |
+
logger.error("worker %d marked unresponsive after %d consecutive push failures",
|
| 389 |
+
worker_id, fails)
|
| 390 |
+
self._event("worker_unresponsive", worker_id=worker_id, failures=fails)
|
| 391 |
+
self._flush_state_locked()
|
| 392 |
+
|
| 393 |
+
# ============ matrix expansion ============
|
| 394 |
+
def _expand_job(self, job: JobSubmission, batch_id: str):
|
| 395 |
+
"""One JobSubmission -> N cells (cartesian of matrix dims). Returns payloads."""
|
| 396 |
+
base_id = job.job_id or gen_job_id()
|
| 397 |
+
platforms = (job.matrix.platforms if job.matrix and job.matrix.platforms else [job.platform])
|
| 398 |
+
runtimes = (job.matrix.runtimes if job.matrix and job.matrix.runtimes else [job.runtime])
|
| 399 |
+
case_list = (job.matrix.stdin_cases if job.matrix and job.matrix.stdin_cases else [job.stdin])
|
| 400 |
+
expanded = []
|
| 401 |
+
for platform, runtime, case in product(platforms, runtimes, case_list):
|
| 402 |
+
cell_bits = [platform, runtime]
|
| 403 |
+
case_idx = None
|
| 404 |
+
if case is not None:
|
| 405 |
+
case_idx = case_list.index(case) + 1
|
| 406 |
+
cell_bits.append(f"case-{case_idx}")
|
| 407 |
+
cell = "/".join(cell_bits)
|
| 408 |
+
cell_id = f"{base_id}#{cell}".replace(" ", "-")
|
| 409 |
+
files = dict(job.files)
|
| 410 |
+
files.update(job.files_variants.get(platform, {})) # OS-specific overlay wins
|
| 411 |
+
expanded.append({
|
| 412 |
+
"job_id": cell_id, "base_job_id": base_id, "batch_id": batch_id, "cell": cell,
|
| 413 |
+
"platform": platform, "runtime": runtime, "files": files,
|
| 414 |
+
"steps": [s.model_dump() for s in job.steps] if job.steps else None,
|
| 415 |
+
"entry_point": job.entry_point,
|
| 416 |
+
"dependencies": job.dependencies, "network_required": job.network_required,
|
| 417 |
+
"stdin": case, "stdin_case": case_idx, "timeout": job.timeout,
|
| 418 |
+
"stop_on_failure": job.stop_on_failure,
|
| 419 |
+
"submitted_at": now(),
|
| 420 |
+
})
|
| 421 |
+
return expanded
|
| 422 |
+
|
| 423 |
+
# ============ submission ============
|
| 424 |
+
def submit_batch(self, batch: BatchSubmission) -> dict:
|
| 425 |
+
with self.lock:
|
| 426 |
+
if not batch.jobs:
|
| 427 |
+
raise ValueError("batch must contain at least one job")
|
| 428 |
+
batch_id = batch.batch_id or gen_batch_id()
|
| 429 |
+
if batch_id in self.batches:
|
| 430 |
+
raise ValueError(f"batch_id already exists: {batch_id}")
|
| 431 |
+
cell_metas = []
|
| 432 |
+
for job in batch.jobs:
|
| 433 |
+
for payload in self._expand_job(job, batch_id):
|
| 434 |
+
if payload["job_id"] in self.jobs:
|
| 435 |
+
raise ValueError(f"job_id already exists: {payload['job_id']}")
|
| 436 |
+
self._save_json(f"jobs/{payload['job_id']}.json", payload)
|
| 437 |
+
meta = JobMeta(job_id=payload["job_id"], base_job_id=payload["base_job_id"],
|
| 438 |
+
batch_id=batch_id, cell=payload["cell"],
|
| 439 |
+
platform=payload["platform"], runtime=payload["runtime"],
|
| 440 |
+
timeout=payload["timeout"], submitted_at=payload["submitted_at"],
|
| 441 |
+
stdin_case=payload["stdin_case"])
|
| 442 |
+
self.jobs[meta.job_id] = meta
|
| 443 |
+
cell_metas.append(meta)
|
| 444 |
+
self.totals["cells"] += 1
|
| 445 |
+
self.batches[batch_id] = {
|
| 446 |
+
"batch_id": batch_id, "submitted_at": now(), "status": "pending",
|
| 447 |
+
"completed_at": None, "job_ids": [m.job_id for m in cell_metas],
|
| 448 |
+
}
|
| 449 |
+
self.totals["batches"] += 1
|
| 450 |
+
for m in cell_metas:
|
| 451 |
+
self._push_next[m.job_id] = 0.0
|
| 452 |
+
self._flush_state_locked()
|
| 453 |
+
self._event("batch_submitted", batch_id=batch_id, cells=len(cell_metas))
|
| 454 |
+
self._wake()
|
| 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():
|
| 483 |
+
if meta.status == "queued":
|
| 484 |
+
self._push_next.setdefault(jid, 0.0)
|
| 485 |
+
self._flush_state_locked()
|
| 486 |
+
self._event("worker_register", worker_id=worker_id, superseded=superseded)
|
| 487 |
+
self._wake()
|
| 488 |
+
return self._worker_public(worker_id), (old_url if superseded else None)
|
| 489 |
+
|
| 490 |
+
def _worker_public(self, worker_id: int):
|
| 491 |
+
w = self.workers.get(worker_id)
|
| 492 |
+
if not w:
|
| 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)
|
| 504 |
+
if not w:
|
| 505 |
+
return "unknown"
|
| 506 |
+
if w.get("reported_done"):
|
| 507 |
+
return "draining"
|
| 508 |
+
if self.push_failures.get(worker_id, 0) >= self.max_push_failures:
|
| 509 |
+
return "unresponsive"
|
| 510 |
+
if any(j.status == "claimed" and j.claimed_by == worker_id for j in self.jobs.values()):
|
| 511 |
+
return "busy"
|
| 512 |
+
return "idle"
|
| 513 |
+
|
| 514 |
+
def report_result(self, worker_id: int, url: str, result: ResultObject):
|
| 515 |
+
with self.lock:
|
| 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()
|
| 545 |
+
meta.claimed_by = None
|
| 546 |
+
meta.claimed_worker_url = None
|
| 547 |
+
meta.claimed_at = None
|
| 548 |
+
meta.claim_deadline = None
|
| 549 |
+
self.totals["completed"] += 1
|
| 550 |
+
self._finalize_batches_locked()
|
| 551 |
+
self._flush_state_locked()
|
| 552 |
+
self._event("cell_completed", job_id=meta.job_id, category=result.get("category"))
|
| 553 |
+
|
| 554 |
+
def report_done(self, worker_id: int, url: str):
|
| 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:
|
| 648 |
+
self._complete_cell_locked(meta, {
|
| 649 |
+
"job_id": meta.job_id, "exit_code": 1, "timed_out": False,
|
| 650 |
+
"category": "infra_failure", "steps": [], "filesystem_state": None,
|
| 651 |
+
"artifacts": [],
|
| 652 |
+
"failure_reason": f"abandoned >{self.max_retries} times ({reason})"})
|
| 653 |
+
return
|
| 654 |
+
meta.retry_count += 1
|
| 655 |
+
meta.status = "queued"
|
| 656 |
+
meta.claimed_by = None
|
| 657 |
+
meta.claimed_worker_url = None
|
| 658 |
+
meta.claimed_at = None
|
| 659 |
+
meta.claim_deadline = None
|
| 660 |
+
meta.last_abandon_reason = reason
|
| 661 |
+
self._push_next[meta.job_id] = now()
|
| 662 |
+
self._wake()
|
| 663 |
+
|
| 664 |
+
def _expire_claims_locked(self):
|
| 665 |
+
t = now()
|
| 666 |
+
changed = False
|
| 667 |
+
for meta in self.jobs.values():
|
| 668 |
+
if meta.status == "claimed" and meta.claim_deadline and t >= meta.claim_deadline:
|
| 669 |
+
self._abandon_cell_locked(meta, "claim timeout")
|
| 670 |
+
changed = True
|
| 671 |
+
if changed:
|
| 672 |
+
self._wake()
|
| 673 |
+
|
| 674 |
+
def _sweep_locked(self, force: bool = False):
|
| 675 |
+
t = now()
|
| 676 |
+
for jid, meta in list(self.jobs.items()):
|
| 677 |
+
if meta.status == "complete" and meta.completed_at and (t - meta.completed_at) > self.retention_seconds:
|
| 678 |
+
self._delete_cell_files(jid)
|
| 679 |
+
del self.jobs[jid]
|
| 680 |
+
for rid, b in list(self.batches.items()):
|
| 681 |
+
ref = b.get("completed_at") or b["submitted_at"]
|
| 682 |
+
if ref and (t - ref) > self.retention_seconds:
|
| 683 |
+
for jid in b["job_ids"]:
|
| 684 |
+
self._delete_cell_files(jid)
|
| 685 |
+
self.jobs.pop(jid, None)
|
| 686 |
+
del self.batches[rid]
|
| 687 |
+
# artifacts
|
| 688 |
+
adir = self._p("artifacts")
|
| 689 |
+
for meta_path in adir.glob("*.json"):
|
| 690 |
+
meta = self._load_json(f"artifacts/{meta_path.name}")
|
| 691 |
+
if meta and (t - meta.get("created_at", t)) > self.retention_seconds:
|
| 692 |
+
aid = meta["artifact_id"]
|
| 693 |
+
self._p(f"artifacts/{aid}.bin").unlink(missing_ok=True)
|
| 694 |
+
meta_path.unlink(missing_ok=True)
|
| 695 |
+
|
| 696 |
+
def _delete_cell_files(self, jid):
|
| 697 |
+
self._p(f"jobs/{jid}.json").unlink(missing_ok=True)
|
| 698 |
+
self._p(f"results/{jid}.json").unlink(missing_ok=True)
|
| 699 |
+
|
| 700 |
+
# ============ batches ============
|
| 701 |
+
def _batch_public_locked(self, batch_id: str):
|
| 702 |
+
b = self.batches[batch_id]
|
| 703 |
+
results = []
|
| 704 |
+
completed = 0
|
| 705 |
+
for jid in b["job_ids"]:
|
| 706 |
+
meta = self.jobs.get(jid)
|
| 707 |
+
if meta is None:
|
| 708 |
+
results.append({"job_id": jid, "status": "missing"})
|
| 709 |
+
continue
|
| 710 |
+
item = {"job_id": jid, "status": meta.status, "cell": meta.cell,
|
| 711 |
+
"platform": meta.platform, "runtime": meta.runtime,
|
| 712 |
+
"stdin_case": meta.stdin_case}
|
| 713 |
+
if meta.status == "complete":
|
| 714 |
+
completed += 1
|
| 715 |
+
item["result"] = self._load_json(f"results/{jid}.json")
|
| 716 |
+
results.append(item)
|
| 717 |
+
return {
|
| 718 |
+
"batch_id": batch_id, "status": b["status"],
|
| 719 |
+
"submitted_at": iso(b["submitted_at"]),
|
| 720 |
+
"completed_at": iso(b.get("completed_at")),
|
| 721 |
+
"job_count": len(b["job_ids"]),
|
| 722 |
+
"completed_job_count": completed,
|
| 723 |
+
"remaining": len(b["job_ids"]) - completed,
|
| 724 |
+
"results": results,
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
def _finalize_batches_locked(self):
|
| 728 |
+
for rid, b in self.batches.items():
|
| 729 |
+
if b["status"] == "pending":
|
| 730 |
+
if all(self.jobs.get(jid) is not None and self.jobs[jid].status == "complete" for jid in b["job_ids"]):
|
| 731 |
+
b["status"] = "complete"
|
| 732 |
+
b["completed_at"] = now()
|
| 733 |
+
self._event("batch_complete", batch_id=rid)
|
| 734 |
+
|
| 735 |
+
def get_batch(self, batch_id: str, consume: bool = False):
|
| 736 |
+
with self.lock:
|
| 737 |
+
if batch_id not in self.batches:
|
| 738 |
+
return None
|
| 739 |
+
self._finalize_batches_locked()
|
| 740 |
+
public = self._batch_public_locked(batch_id)
|
| 741 |
+
if consume and public["status"] == "complete":
|
| 742 |
+
self._delete_batch_locked(batch_id)
|
| 743 |
+
return public
|
| 744 |
+
|
| 745 |
+
def cancel_batch(self, batch_id: str):
|
| 746 |
+
with self.lock:
|
| 747 |
+
if batch_id not in self.batches:
|
| 748 |
+
return None
|
| 749 |
+
b = self.batches[batch_id]
|
| 750 |
+
released = []
|
| 751 |
+
for jid in b["job_ids"]:
|
| 752 |
+
meta = self.jobs.get(jid)
|
| 753 |
+
if meta and meta.status == "queued":
|
| 754 |
+
self._delete_cell_files(jid)
|
| 755 |
+
del self.jobs[jid]
|
| 756 |
+
self._push_next.pop(jid, None)
|
| 757 |
+
released.append(jid)
|
| 758 |
+
del self.batches[batch_id]
|
| 759 |
+
self._flush_state_locked()
|
| 760 |
+
self._wake()
|
| 761 |
+
self._event("batch_cancelled", batch_id=batch_id, released=len(released))
|
| 762 |
+
return {"status": "cancelled", "batch_id": batch_id, "released_job_ids": released,
|
| 763 |
+
"note": "claimed cells will fail claim-check on report and be discarded"}
|
| 764 |
+
|
| 765 |
+
def _delete_batch_locked(self, batch_id: str):
|
| 766 |
+
b = self.batches.pop(batch_id, None)
|
| 767 |
+
if not b:
|
| 768 |
+
return
|
| 769 |
+
for jid in b["job_ids"]:
|
| 770 |
+
self.jobs.pop(jid, None)
|
| 771 |
+
self._push_next.pop(jid, None)
|
| 772 |
+
self._delete_cell_files(jid)
|
| 773 |
+
self._flush_state_locked()
|
| 774 |
+
self._event("batch_consumed", batch_id=batch_id)
|
| 775 |
+
|
| 776 |
+
# ============ artifacts ============
|
| 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",
|
| 793 |
+
path=rel_path, kind=kind or KIND_BY_EXT.get(ext, "file"),
|
| 794 |
+
content_type=content_type or CT_BY_EXT.get(ext, "application/octet-stream"),
|
| 795 |
+
size=len(data), sha256=hashlib.sha256(data).hexdigest(), created_at=now())
|
| 796 |
+
(self.root / "artifacts" / f"{meta.artifact_id}.bin").write_bytes(data)
|
| 797 |
+
self._save_json(f"artifacts/{meta.artifact_id}.json", meta.model_dump())
|
| 798 |
+
self._event("artifact_stored", artifact_id=meta.artifact_id, job_id=meta.job_id, size=meta.size)
|
| 799 |
+
return meta.model_dump()
|
| 800 |
+
|
| 801 |
+
def get_artifact(self, artifact_id: str):
|
| 802 |
+
meta = self._load_json(f"artifacts/{artifact_id}.json")
|
| 803 |
+
if not meta:
|
| 804 |
+
return None, None
|
| 805 |
+
return meta, self.root / "artifacts" / f"{artifact_id}.bin"
|
| 806 |
+
|
| 807 |
+
# ============ admin ============
|
| 808 |
+
def get_status(self):
|
| 809 |
+
with self.lock:
|
| 810 |
+
self._finalize_batches_locked()
|
| 811 |
+
queued = sum(1 for j in self.jobs.values() if j.status == "queued")
|
| 812 |
+
claimed = sum(1 for j in self.jobs.values() if j.status == "claimed")
|
| 813 |
+
complete = sum(1 for j in self.jobs.values() if j.status == "complete")
|
| 814 |
+
pending = sum(1 for b in self.batches.values() if b["status"] == "pending")
|
| 815 |
+
return {
|
| 816 |
+
"uptime_seconds": now() - self.start_time,
|
| 817 |
+
"schema": SCHEMA,
|
| 818 |
+
"totals": self.totals,
|
| 819 |
+
"jobs_by_status": {"queued": queued, "claimed": claimed, "complete": complete},
|
| 820 |
+
"pending_batches": pending,
|
| 821 |
+
"workers": [self._worker_public(wid) for wid in self.workers],
|
| 822 |
+
"retention_seconds": self.retention_seconds,
|
| 823 |
+
}
|
space/requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi>=0.115
|
| 2 |
+
uvicorn[standard]>=0.30
|
| 3 |
+
pydantic>=2.7
|
| 4 |
+
huggingface_hub>=1.5.0
|
space/tests/e2e_test.py
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Relay v4 end-to-end test (local disk persist, no external network).
|
| 3 |
+
|
| 4 |
+
Covers:
|
| 5 |
+
1. boot; /health reports schema 4; runner key rejected on agent endpoints (401)
|
| 6 |
+
2. batch with matrix (2 platforms x 2 runtimes x 2 stdin cases) -> 8 cells, ONE batch_id
|
| 7 |
+
3. REAL linux runner (tools/runner/worker.py subprocess, RUNNER_LOCAL_URL — no
|
| 8 |
+
cloudflared in tests) claims the 4 linux cells by PUSH (zero polls), executes them
|
| 9 |
+
for real, and uploads outputs/hello.txt artifacts
|
| 10 |
+
4. artifact round-trip: agent downloads bytes; sha256 matches the result metadata
|
| 11 |
+
5. crash recovery: cell pushed to a black-hole intake (claims, never reports), relay
|
| 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
|
| 26 |
+
import os
|
| 27 |
+
import shutil
|
| 28 |
+
import signal
|
| 29 |
+
import subprocess
|
| 30 |
+
import sys
|
| 31 |
+
import threading
|
| 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__), "..", ".."))
|
| 39 |
+
PORT = 8795
|
| 40 |
+
BASE = f"http://127.0.0.1:{PORT}/dataset_verification"
|
| 41 |
+
PERSIST_DIR = "/tmp/relay_v4_test"
|
| 42 |
+
LINUX_PORT = 8801
|
| 43 |
+
LINUX2_PORT = 8803
|
| 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")
|
| 54 |
+
SPACE_DIR = os.path.join(os.path.dirname(__file__), "..")
|
| 55 |
+
|
| 56 |
+
def req(method, path, body=None, key="agent-key", query="", raw=False, timeout=15):
|
| 57 |
+
from urllib.parse import quote
|
| 58 |
+
data = body if isinstance(body, (bytes, type(None))) else json.dumps(body).encode()
|
| 59 |
+
if query:
|
| 60 |
+
query = "&".join(
|
| 61 |
+
f"{k}={quote(v, safe='')}"
|
| 62 |
+
for k, v in (p.split("=", 1) for p in query.split("&") if p))
|
| 63 |
+
r = urllib.request.Request(BASE + path + (("?" + query) if query else ""), data=data, method=method)
|
| 64 |
+
if key:
|
| 65 |
+
r.add_header("Authorization", f"Bearer {key}")
|
| 66 |
+
if not raw:
|
| 67 |
+
r.add_header("Content-Type", "application/json")
|
| 68 |
+
with urllib.request.urlopen(r, timeout=timeout) as resp:
|
| 69 |
+
payload = resp.read()
|
| 70 |
+
return (resp.status, payload, dict(resp.headers)) if raw else json.loads(payload.decode() or "{}")
|
| 71 |
+
|
| 72 |
+
def boot():
|
| 73 |
+
proc = subprocess.Popen([sys.executable, "-m", "uvicorn", "main:app",
|
| 74 |
+
"--host", "127.0.0.1", "--port", str(PORT)],
|
| 75 |
+
cwd=SPACE_DIR, env=ENV,
|
| 76 |
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 77 |
+
for _ in range(60):
|
| 78 |
+
try:
|
| 79 |
+
urllib.request.urlopen(f"http://127.0.0.1:{PORT}/dataset_verification/health", timeout=1)
|
| 80 |
+
return proc
|
| 81 |
+
except Exception:
|
| 82 |
+
time.sleep(0.5)
|
| 83 |
+
proc.kill()
|
| 84 |
+
raise RuntimeError("boot failed")
|
| 85 |
+
|
| 86 |
+
def start_worker(name, runner_id, runner_os, port, tags="python-3.11,python-3.12"):
|
| 87 |
+
env = dict(os.environ,
|
| 88 |
+
RELAY_URL=BASE, RUNNER_API_KEY="runner-key",
|
| 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):
|
| 128 |
+
self.records = []
|
| 129 |
+
outer = self
|
| 130 |
+
class Handler(BaseHTTPRequestHandler):
|
| 131 |
+
protocol_version = "HTTP/1.1"
|
| 132 |
+
def log_message(self, *a): pass
|
| 133 |
+
def _json(self, code, obj):
|
| 134 |
+
body = json.dumps(obj).encode()
|
| 135 |
+
self.send_response(code)
|
| 136 |
+
self.send_header("Content-Type", "application/json")
|
| 137 |
+
self.send_header("Content-Length", str(len(body)))
|
| 138 |
+
self.end_headers(); self.wfile.write(body)
|
| 139 |
+
def do_GET(self):
|
| 140 |
+
self._json(401, {"detail": "auth required"})
|
| 141 |
+
def do_POST(self):
|
| 142 |
+
length = int(self.headers.get("Content-Length", "0"))
|
| 143 |
+
self.rfile.read(length)
|
| 144 |
+
if self.headers.get("Authorization") != "Bearer runner-key":
|
| 145 |
+
return self._json(401, {"detail": "Unauthorized"})
|
| 146 |
+
path = self.path.rstrip("/")
|
| 147 |
+
outer.records.append(path)
|
| 148 |
+
if path == "/job":
|
| 149 |
+
return self._json(202, {"accepted": True})
|
| 150 |
+
if path == "/shutdown":
|
| 151 |
+
return self._json(200, {"draining": True})
|
| 152 |
+
self._json(404, {"detail": "not found"})
|
| 153 |
+
self.server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
|
| 154 |
+
self.server.daemon_threads = True
|
| 155 |
+
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
| 156 |
+
|
| 157 |
+
def stop(self):
|
| 158 |
+
try:
|
| 159 |
+
self.server.shutdown()
|
| 160 |
+
except Exception:
|
| 161 |
+
pass
|
| 162 |
+
|
| 163 |
+
def wait_for(predicate, timeout_s, what, interval=1.0):
|
| 164 |
+
deadline = time.time() + timeout_s
|
| 165 |
+
while time.time() < deadline:
|
| 166 |
+
if predicate():
|
| 167 |
+
return True
|
| 168 |
+
time.sleep(interval)
|
| 169 |
+
raise RuntimeError(f"timeout waiting for: {what}")
|
| 170 |
+
|
| 171 |
+
def header_ci(headers, name):
|
| 172 |
+
for k, v in headers.items():
|
| 173 |
+
if k.lower() == name.lower():
|
| 174 |
+
return v
|
| 175 |
+
return None
|
| 176 |
+
|
| 177 |
+
def main():
|
| 178 |
+
shutil.rmtree(PERSIST_DIR, ignore_errors=True)
|
| 179 |
+
ok = []
|
| 180 |
+
|
| 181 |
+
proc = boot()
|
| 182 |
+
print("1. booted")
|
| 183 |
+
|
| 184 |
+
health = json.load(urllib.request.urlopen(f"http://127.0.0.1:{PORT}/dataset_verification/health", timeout=5))
|
| 185 |
+
assert health["schema"] == 4, f"schema must be 4, got {health}"
|
| 186 |
+
try:
|
| 187 |
+
req("GET", "/desktop/status", key="runner-key")
|
| 188 |
+
assert False, "runner key must not read agent endpoints"
|
| 189 |
+
except urllib.error.HTTPError as e:
|
| 190 |
+
assert e.code == 401
|
| 191 |
+
ok.append("boot + schema 4 + audience-scoped keys")
|
| 192 |
+
|
| 193 |
+
batch = {
|
| 194 |
+
"batch_id": "batch_v4_e2e0001",
|
| 195 |
+
"jobs": [{
|
| 196 |
+
"job_id": "job_matrix1",
|
| 197 |
+
"platform": "linux",
|
| 198 |
+
"runtime": "python-3.12",
|
| 199 |
+
"files": {"main.py":
|
| 200 |
+
"import pathlib, sys\n"
|
| 201 |
+
"pathlib.Path('outputs').mkdir(exist_ok=True)\n"
|
| 202 |
+
"pathlib.Path('outputs/hello.txt').write_text('hello-linux')\n"
|
| 203 |
+
"print('ok', sys.version_info[0], sys.version_info[1])\n",
|
| 204 |
+
"common.txt": "base-content"},
|
| 205 |
+
"files_variants": {"windows": {"main.py":
|
| 206 |
+
"import pathlib\npathlib.Path('outputs').mkdir(exist_ok=True)\n"
|
| 207 |
+
"pathlib.Path('outputs/hello.txt').write_text('hello-windows')\n"
|
| 208 |
+
"print('ok win')\n"}},
|
| 209 |
+
"steps": [{"name": "run", "entry_point": "python main.py", "timeout": 120}],
|
| 210 |
+
"matrix": {"platforms": ["linux", "windows"],
|
| 211 |
+
"runtimes": ["python-3.11", "python-3.12"],
|
| 212 |
+
"stdin_cases": ["a\n", "b b b\n"]},
|
| 213 |
+
}],
|
| 214 |
+
}
|
| 215 |
+
b = req("POST", "/desktop/batch", batch)
|
| 216 |
+
assert b["job_count"] == 8 and b["batch_id"] == "batch_v4_e2e0001"
|
| 217 |
+
ok.append("matrix expansion 8 cells, one batch_id")
|
| 218 |
+
|
| 219 |
+
worker1 = start_worker("linux1", 1, "linux", LINUX_PORT)
|
| 220 |
+
worker2 = None
|
| 221 |
+
try:
|
| 222 |
+
wait_for(lambda: req("GET", "/desktop/batch/batch_v4_e2e0001")["completed_job_count"] >= 4,
|
| 223 |
+
120, "linux cells complete via push", interval=2.0)
|
| 224 |
+
b_now = req("GET", "/desktop/batch/batch_v4_e2e0001")
|
| 225 |
+
linux_cells = [r for r in b_now["results"] if r["platform"] == "linux"]
|
| 226 |
+
assert all(r["status"] == "complete" for r in linux_cells)
|
| 227 |
+
assert all(r["result"]["category"] == "success" for r in linux_cells)
|
| 228 |
+
art_ref = next((r["result"]["artifacts"][0] for r in linux_cells if r["result"].get("artifacts")), None)
|
| 229 |
+
assert art_ref, "linux cells must upload outputs/hello.txt"
|
| 230 |
+
code, data, headers = req("GET", f"/desktop/artifact/{art_ref['artifact_id']}", raw=True)
|
| 231 |
+
assert code == 200 and hashlib.sha256(data).hexdigest() == art_ref["sha256"]
|
| 232 |
+
assert data.decode().startswith("hello-linux")
|
| 233 |
+
assert header_ci(headers, "X-Artifact-SHA256") == art_ref["sha256"]
|
| 234 |
+
ok.append("linux runner pushed cells (no polls), executed, artifact byte-exact")
|
| 235 |
+
|
| 236 |
+
# ---- windows cells: black-hole claims by push; test reports results over HTTP ----
|
| 237 |
+
bh_win = BlackHole(BH_WIN_PORT)
|
| 238 |
+
req("POST", "/worker/register",
|
| 239 |
+
{"worker_id": 9, "url": f"http://127.0.0.1:{BH_WIN_PORT}",
|
| 240 |
+
"environment": {"platform": "windows", "os_version": "windows-latest",
|
| 241 |
+
"runtimes": ["python-3.11", "python-3.12"], "max_concurrent_jobs": 4}},
|
| 242 |
+
key="runner-key")
|
| 243 |
+
wait_for(lambda: all(r["status"] == "claimed"
|
| 244 |
+
for r in req("GET", "/desktop/batch/batch_v4_e2e0001")["results"]
|
| 245 |
+
if r["platform"] == "windows"),
|
| 246 |
+
30, "windows cells claimed by push", interval=1.0)
|
| 247 |
+
for r in req("GET", "/desktop/batch/batch_v4_e2e0001")["results"]:
|
| 248 |
+
if r["platform"] == "windows" and r["status"] == "claimed":
|
| 249 |
+
req("POST", "/worker/result",
|
| 250 |
+
{"job_id": r["job_id"], "exit_code": 0, "timed_out": False,
|
| 251 |
+
"category": "success",
|
| 252 |
+
"steps": [{"name": "run", "stdout": "ok win", "stderr": "",
|
| 253 |
+
"exit_code": 0, "timed_out": False}],
|
| 254 |
+
"filesystem_state": None, "artifacts": []},
|
| 255 |
+
key="runner-key",
|
| 256 |
+
query=f"worker_id=9&url=http://127.0.0.1:{BH_WIN_PORT}")
|
| 257 |
+
fin = req("GET", "/desktop/batch/batch_v4_e2e0001", query="consume=true")
|
| 258 |
+
assert fin["status"] == "complete" and fin["remaining"] == 0
|
| 259 |
+
bh_win.stop()
|
| 260 |
+
ok.append("windows cells claim/result path + batch consume")
|
| 261 |
+
|
| 262 |
+
# ---- crash recovery ----
|
| 263 |
+
# quiesce the linux runner first so ONLY the black-hole can claim the crash cell
|
| 264 |
+
worker1.terminate()
|
| 265 |
+
try:
|
| 266 |
+
worker1.wait(timeout=30)
|
| 267 |
+
except subprocess.TimeoutExpired:
|
| 268 |
+
worker1.kill()
|
| 269 |
+
crash = {
|
| 270 |
+
"batch_id": "batch_v4_crash",
|
| 271 |
+
"jobs": [{"job_id": "job_crash1", "platform": "linux", "runtime": "python-3.12",
|
| 272 |
+
"files": {"main.py": "print('crash-test')\n"},
|
| 273 |
+
"entry_point": "python main.py", "timeout": 60}]}
|
| 274 |
+
req("POST", "/desktop/batch", crash)
|
| 275 |
+
bh_crash = BlackHole(BH_CRASH_PORT)
|
| 276 |
+
req("POST", "/worker/register",
|
| 277 |
+
{"worker_id": 10, "url": f"http://127.0.0.1:{BH_CRASH_PORT}",
|
| 278 |
+
"environment": {"platform": "linux", "os_version": "ubuntu",
|
| 279 |
+
"runtimes": ["python-3.12"], "max_concurrent_jobs": 1}},
|
| 280 |
+
key="runner-key")
|
| 281 |
+
wait_for(lambda: req("GET", "/desktop/batch/batch_v4_crash")["results"][0]["status"] == "claimed",
|
| 282 |
+
30, "crash cell claimed by black-hole", interval=1.0)
|
| 283 |
+
proc.send_signal(signal.SIGKILL)
|
| 284 |
+
proc.wait()
|
| 285 |
+
bh_crash.stop()
|
| 286 |
+
print(" [crash] relay SIGKILLed with cell claimed; rebooting")
|
| 287 |
+
proc = boot()
|
| 288 |
+
wait_for(lambda: req("GET", "/desktop/batch/batch_v4_crash")["results"][0]["status"] == "queued",
|
| 289 |
+
30, "crash cell requeued after reboot", interval=1.0)
|
| 290 |
+
worker2 = start_worker("linux2", 11, "linux", LINUX2_PORT, tags="python-3.12")
|
| 291 |
+
try:
|
| 292 |
+
wait_for(lambda: req("GET", "/desktop/batch/batch_v4_crash")["status"] == "complete",
|
| 293 |
+
120, "crash cell completed after recovery", interval=2.0)
|
| 294 |
+
ok.append("crash -> requeue -> recovered & completed")
|
| 295 |
+
finally:
|
| 296 |
+
worker2.terminate()
|
| 297 |
+
|
| 298 |
+
# ---- supersede sends /shutdown to the old generation ----
|
| 299 |
+
bh_sup = BlackHole(BH_SUPER_PORT)
|
| 300 |
+
req("POST", "/worker/register",
|
| 301 |
+
{"worker_id": 99, "url": f"http://127.0.0.1:{BH_SUPER_PORT}",
|
| 302 |
+
"environment": {"platform": "linux", "os_version": "ubuntu",
|
| 303 |
+
"runtimes": ["python-3.12"], "max_concurrent_jobs": 1}},
|
| 304 |
+
key="runner-key")
|
| 305 |
+
req("POST", "/worker/register",
|
| 306 |
+
{"worker_id": 99, "url": "http://127.0.0.1:9",
|
| 307 |
+
"environment": {"platform": "linux", "os_version": "ubuntu",
|
| 308 |
+
"runtimes": ["python-3.12"], "max_concurrent_jobs": 1}},
|
| 309 |
+
key="runner-key")
|
| 310 |
+
wait_for(lambda: "/shutdown" in bh_sup.records, 10, "superseded generation receives /shutdown",
|
| 311 |
+
interval=0.5)
|
| 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:
|
| 481 |
+
try:
|
| 482 |
+
worker1.terminate()
|
| 483 |
+
except Exception:
|
| 484 |
+
pass
|
| 485 |
+
if worker2 is not None:
|
| 486 |
+
try:
|
| 487 |
+
worker2.terminate()
|
| 488 |
+
except Exception:
|
| 489 |
+
pass
|
| 490 |
+
try:
|
| 491 |
+
proc.terminate()
|
| 492 |
+
proc.wait(timeout=10)
|
| 493 |
+
except Exception:
|
| 494 |
+
pass
|
| 495 |
+
|
| 496 |
+
print("PASS:", " | ".join(ok))
|
| 497 |
+
return 0
|
| 498 |
+
|
| 499 |
+
if __name__ == "__main__":
|
| 500 |
+
sys.exit(main())
|
space/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())
|