workbox 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
workbox/runner.py ADDED
@@ -0,0 +1,618 @@
1
+ """The Workbox runner (specs/jobs.md §8): runs one job inside its machine and reports to Workbox.
2
+
3
+ Started as `workbox-runner` with WORKBOX_JOB_ID, WORKBOX_URL and WORKBOX_TOKEN set. It checks in, fetches
4
+ the code and inputs, installs requirements, runs the command (or the notebook), reports its output, metrics,
5
+ samples and GPU use every few seconds, obeys a stop and the time limit, saves the outputs however the job
6
+ ends, and finishes. Metrics come from the `workbox` helper, and also from what tools already print and from
7
+ TensorBoard event files, so charts work without code changes. It uses only the standard library, so it never clashes with a job's own packages.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import ast
13
+ import hashlib
14
+ import json
15
+ import math
16
+ import os
17
+ import re
18
+ import shlex
19
+ import signal
20
+ import subprocess
21
+ import sys
22
+ import threading
23
+ import time
24
+ import urllib.error
25
+ import urllib.request
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ HOME = Path.home()
30
+ WORK = HOME / "work"
31
+ INPUTS = HOME / "inputs"
32
+ STATE = HOME / ".workbox"
33
+ EVENTS = STATE / "events.jsonl"
34
+ LOG_FILE = STATE / "job.log"
35
+ STOP_GRACE_SECONDS = 30
36
+ MAX_LINE = 4000
37
+ # What one report may carry (runnerReportSchema); the rest goes in the next one.
38
+ MAX_REPORT_LINES = 1000
39
+ MAX_REPORT_METRICS = 1000
40
+ MAX_REPORT_SAMPLES = 50
41
+ TENSORBOARD_SCAN_SECONDS = 10
42
+
43
+
44
+ class Failure(Exception):
45
+ """A failure the runner can name (specs/jobs.md §9): Workbox turns its kind into advice."""
46
+
47
+ def __init__(self, kind: str, detail: str) -> None:
48
+ super().__init__(detail)
49
+ self.kind = kind
50
+
51
+
52
+ class Workbox:
53
+ """Calls to POST /api/<api>/<step> with the machine's token: the runner's (/api/runner) or a box's (/api/box)."""
54
+
55
+ def __init__(self, api: str = "runner") -> None:
56
+ self.url = os.environ["WORKBOX_URL"].rstrip("/")
57
+ self.token = os.environ["WORKBOX_TOKEN"]
58
+ self.api = api
59
+
60
+ def post(self, step: str, body: Any = None, attempts: int = 5) -> dict[str, Any]:
61
+ data = json.dumps(body or {}).encode()
62
+ for attempt in range(attempts):
63
+ request = urllib.request.Request(
64
+ f"{self.url}/api/{self.api}/{step}",
65
+ data=data,
66
+ method="POST",
67
+ headers={"Authorization": f"Bearer {self.token}", "Content-Type": "application/json"},
68
+ )
69
+ try:
70
+ with urllib.request.urlopen(request, timeout=30) as response:
71
+ return json.loads(response.read() or b"{}")
72
+ except urllib.error.HTTPError as error:
73
+ # 401: the job has ended or the token expired; 400: a bad request, which a retry won't fix.
74
+ if error.code in (400, 401, 404):
75
+ return {"stop": True, "error": error.code}
76
+ except (urllib.error.URLError, TimeoutError, OSError):
77
+ pass
78
+ time.sleep(min(2**attempt, 15))
79
+ return {}
80
+
81
+
82
+ # Lines that carry metrics (specs/jobs.md §9): a progress bar ("450/1000 ["), a Lightning bar with its
83
+ # epoch, a step ("step=120", "iter 120:") and name=value or name: value pairs.
84
+ PROGRESS = re.compile(r"\|\s*(\d+)/(\d+)\s*\[")
85
+ LIGHTNING = re.compile(r"^Epoch (\d+):.*?\|\s*(\d+)/(\d+)\s*\[(.*)\]\s*$")
86
+ STEP = re.compile(r"\b(?:global_step|step|iter|iteration)\b\s*[=:]?\s*(\d+)", re.IGNORECASE)
87
+ PAIR = re.compile(r"([A-Za-z_][\w./-]{0,80})\s*[=:]\s*(-?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?)(?![\w.])")
88
+ NOT_METRICS = {"epoch", "v_num", "step", "global_step", "iter", "iteration", "total_flos"}
89
+
90
+
91
+ def finite(value: Any) -> float | None:
92
+ try:
93
+ number = float(value)
94
+ except (TypeError, ValueError):
95
+ return None
96
+ return number if math.isfinite(number) else None
97
+
98
+
99
+ class Readings:
100
+ """Metrics read from what the job prints: the Hugging Face Trainer's log dictionaries, PyTorch Lightning's
101
+ progress bar, and name=value pairs on a line with a step. A metric the helper reports is left to it."""
102
+
103
+ def __init__(self) -> None:
104
+ self.metrics: list[dict[str, Any]] = []
105
+ self.last_step: dict[str, int | None] = {}
106
+ self.helper: set[str] = set()
107
+ # Where the training bar is: the longest one, since evaluation bars are shorter.
108
+ self.progress: int | None = None
109
+ self.progress_total = 0
110
+
111
+ def add(self, name: str, step: int | None, value: Any) -> None:
112
+ number = finite(value)
113
+ name = name[:100]
114
+ if number is None or name.lower() in NOT_METRICS or name in self.helper:
115
+ return
116
+ # A bar repeats its numbers on every refresh: one point per step is enough.
117
+ if step is not None and self.last_step.get(name) == step:
118
+ return
119
+ self.last_step[name] = step
120
+ self.metrics.append({"name": name, "step": step, "value": number})
121
+
122
+ def line(self, line: str) -> None:
123
+ text = line.strip()
124
+ if bar := PROGRESS.search(text):
125
+ done, total = int(bar.group(1)), int(bar.group(2))
126
+ if total >= self.progress_total:
127
+ self.progress, self.progress_total = done, total
128
+ if text.startswith("{") and text.endswith("}") and ":" in text:
129
+ try:
130
+ logged = ast.literal_eval(text)
131
+ except (ValueError, SyntaxError, MemoryError, RecursionError):
132
+ logged = None
133
+ if isinstance(logged, dict):
134
+ step = logged.get("step", self.progress)
135
+ for name, value in logged.items():
136
+ if isinstance(name, str) and isinstance(value, (int, float)) and not isinstance(value, bool):
137
+ self.add(name, step if isinstance(step, int) else None, value)
138
+ return
139
+ if lightning := LIGHTNING.match(text):
140
+ epoch, done, total, postfix = lightning.groups()
141
+ step = int(epoch) * int(total) + int(done)
142
+ for name, value in PAIR.findall(postfix):
143
+ self.add(name, step, value)
144
+ return
145
+ if step := STEP.search(text):
146
+ for name, value in PAIR.findall(text):
147
+ self.add(name, int(step.group(1)), value)
148
+
149
+ def take(self) -> list[dict[str, Any]]:
150
+ metrics, self.metrics = self.metrics, []
151
+ return metrics
152
+
153
+
154
+ class Output:
155
+ """Collects the command's output lines for the next report, keeps them all in the log file, and reads
156
+ metrics from them."""
157
+
158
+ def __init__(self) -> None:
159
+ self.lines: list[str] = []
160
+ self.secrets: list[str] = []
161
+ self.readings = Readings()
162
+ self.lock = threading.Lock()
163
+ STATE.mkdir(parents=True, exist_ok=True)
164
+ self.file = open(LOG_FILE, "a", encoding="utf-8")
165
+
166
+ def hide(self, values: list[str]) -> None:
167
+ """Secret values never reach the log: longest first, so one inside another is still hidden."""
168
+ self.secrets = sorted((value for value in values if len(value) >= 4), key=len, reverse=True)
169
+
170
+ def redact(self, text: str) -> str:
171
+ for value in self.secrets:
172
+ text = text.replace(value, "****")
173
+ return text
174
+
175
+ def add(self, line: str) -> None:
176
+ line = self.redact(line.rstrip("\n"))[:MAX_LINE]
177
+ with self.lock:
178
+ self.lines.append(line)
179
+ self.file.write(line + "\n")
180
+ self.file.flush()
181
+ try:
182
+ self.readings.line(line)
183
+ except Exception: # noqa: BLE001 - a line that looks like a metric must never stop the job
184
+ pass
185
+
186
+ def take(self) -> tuple[list[str], list[dict[str, Any]]]:
187
+ """The lines for the next report, at most MAX_REPORT_LINES, and the metrics read from them so far."""
188
+ with self.lock:
189
+ lines, self.lines = self.lines[:MAX_REPORT_LINES], self.lines[MAX_REPORT_LINES:]
190
+ return lines, self.readings.take()
191
+
192
+ def helper_reported(self, names: set[str]) -> None:
193
+ with self.lock:
194
+ self.readings.helper |= names
195
+
196
+
197
+ class TensorBoard:
198
+ """Scalars from TensorBoard event files anywhere in ~/work, read as they are written. TensorBoard is in
199
+ every Workbox image; with another image, or no event files, it reads nothing."""
200
+
201
+ def __init__(self) -> None:
202
+ self.loaders: dict[Path, Any] = {}
203
+ self.next_scan = 0.0
204
+
205
+ def take(self) -> list[dict[str, Any]]:
206
+ try:
207
+ from tensorboard.backend.event_processing.event_file_loader import EventFileLoader
208
+ from tensorboard.util import tensor_util
209
+ except Exception: # noqa: BLE001 - not installed
210
+ return []
211
+ if time.time() >= self.next_scan:
212
+ self.next_scan = time.time() + TENSORBOARD_SCAN_SECONDS
213
+ for file in WORK.rglob("events.out.tfevents.*"):
214
+ if file not in self.loaders:
215
+ self.loaders[file] = EventFileLoader(str(file))
216
+ metrics: list[dict[str, Any]] = []
217
+ for loader in self.loaders.values():
218
+ try:
219
+ for event in loader.Load():
220
+ if event.WhichOneof("what") != "summary":
221
+ continue
222
+ for value in event.summary.value:
223
+ kind = value.WhichOneof("value")
224
+ if kind == "simple_value":
225
+ number = finite(value.simple_value)
226
+ elif kind == "tensor" and value.metadata.plugin_data.plugin_name == "scalars":
227
+ number = finite(tensor_util.make_ndarray(value.tensor).item())
228
+ else:
229
+ continue
230
+ if number is not None:
231
+ metrics.append({"name": value.tag[:100], "step": int(event.step), "value": number})
232
+ except Exception: # noqa: BLE001 - a file still being written, or not an event file
233
+ continue
234
+ return metrics
235
+
236
+
237
+ def download(url: str, target: Path) -> None:
238
+ target.parent.mkdir(parents=True, exist_ok=True)
239
+ with urllib.request.urlopen(url, timeout=600) as response, open(target, "wb") as file:
240
+ while chunk := response.read(1 << 20):
241
+ file.write(chunk)
242
+
243
+
244
+ def upload(url: str, source: Path) -> bool:
245
+ with open(source, "rb") as file:
246
+ request = urllib.request.Request(url, data=file, method="PUT", headers={"Content-Length": str(source.stat().st_size)})
247
+ try:
248
+ with urllib.request.urlopen(request, timeout=1800):
249
+ return True
250
+ except (urllib.error.URLError, OSError):
251
+ return False
252
+
253
+
254
+ def sh(command: str, output: Output, cwd: Path = WORK) -> int:
255
+ """Runs a setup command, sending its output to the log."""
256
+ output.add(f"$ {command}")
257
+ process = subprocess.Popen(["bash", "-lc", command], cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
258
+ assert process.stdout
259
+ for line in process.stdout:
260
+ output.add(line)
261
+ return process.wait()
262
+
263
+
264
+ def fetch_code(code: dict[str, Any], output: Output) -> str | None:
265
+ """Puts the job's code in ~/work, and returns the commit when it came from Git."""
266
+ WORK.mkdir(parents=True, exist_ok=True)
267
+ if archive := code.get("archive"):
268
+ # A box's ~/work, packed by its agent (Run as job, specs/boxes.md §11).
269
+ packed = STATE / "code.tar.gz"
270
+ try:
271
+ download(archive, packed)
272
+ except (urllib.error.URLError, OSError) as error:
273
+ raise Failure("code_unavailable", f"downloading the box's files: {error}") from error
274
+ if subprocess.run(["tar", "-xzf", str(packed), "-C", str(HOME)]).returncode != 0:
275
+ raise Failure("code_unavailable", "unpacking the box's files failed")
276
+ packed.unlink(missing_ok=True)
277
+ output.add("Unpacked the box's files.")
278
+ return None
279
+ if git := code.get("git"):
280
+ if sh(f"git clone --depth 1 --branch {shlex.quote(git['branch'])} {shlex.quote(git['url'])} .", output) != 0:
281
+ raise Failure("code_unavailable", f"git clone of {git['url']} ({git['branch']}) failed")
282
+ return subprocess.run(["git", "rev-parse", "HEAD"], cwd=WORK, capture_output=True, text=True).stdout.strip() or None
283
+ for file in code.get("files", []):
284
+ try:
285
+ download(file["url"], WORK / file["path"])
286
+ except (urllib.error.URLError, OSError) as error:
287
+ raise Failure("code_unavailable", f"downloading {file['path']}: {error}") from error
288
+ output.add(f"Downloaded {len(code.get('files', []))} files.")
289
+ return None
290
+
291
+
292
+ def fetch_inputs(sources: list[str], job_inputs: list[dict[str, Any]], output: Output) -> None:
293
+ """Downloads every input into ~/inputs/<name>: Hugging Face, https:// and earlier jobs' outputs."""
294
+ INPUTS.mkdir(parents=True, exist_ok=True)
295
+ for source in sources:
296
+ try:
297
+ fetch_input(source, output)
298
+ except Exception as error: # noqa: BLE001 - any failure here is the download's
299
+ raise Failure("download_failed", f"{source}: {error}") from error
300
+ for job_input in job_inputs:
301
+ name = job_input["source"].rstrip("/").split("/")[-1]
302
+ for file in job_input["files"]:
303
+ try:
304
+ download(file["url"], INPUTS / name / file["path"])
305
+ except (urllib.error.URLError, OSError) as error:
306
+ raise Failure("download_failed", f"{job_input['source']}: {error}") from error
307
+
308
+
309
+ def fetch_input(source: str, output: Output) -> None:
310
+ """One input into ~/inputs/<name>: a Hugging Face model or dataset, or a file over https://."""
311
+ name = source.rstrip("/").split("/")[-1]
312
+ output.add(f"Downloading {source}")
313
+ if source.startswith("hf://"):
314
+ from huggingface_hub import snapshot_download
315
+
316
+ repo = source.removeprefix("hf://")
317
+ kind = "dataset" if repo.startswith("datasets/") else None
318
+ repo = repo.removeprefix("datasets/").removeprefix("models/")
319
+ try:
320
+ snapshot_download(repo, repo_type=kind or "model", local_dir=INPUTS / name)
321
+ except Exception: # noqa: BLE001 - a name without datasets/ may still be a dataset
322
+ if kind:
323
+ raise
324
+ snapshot_download(repo, repo_type="dataset", local_dir=INPUTS / name)
325
+ elif source.startswith("https://"):
326
+ download(source, INPUTS / name)
327
+
328
+
329
+ def install_requirements(output: Output) -> None:
330
+ if (WORK / "requirements.txt").exists():
331
+ if sh("uv pip install -r requirements.txt", output) != 0:
332
+ raise Failure("install_failed", "uv pip install -r requirements.txt failed")
333
+
334
+
335
+ def gpu_metrics() -> list[dict[str, Any]]:
336
+ """GPU use and memory, from the machine itself. Nothing on a machine without a GPU."""
337
+ try:
338
+ import pynvml # nvidia-ml-py
339
+
340
+ pynvml.nvmlInit()
341
+ metrics = []
342
+ for index in range(pynvml.nvmlDeviceGetCount()):
343
+ handle = pynvml.nvmlDeviceGetHandleByIndex(index)
344
+ use = pynvml.nvmlDeviceGetUtilizationRates(handle)
345
+ memory = pynvml.nvmlDeviceGetMemoryInfo(handle)
346
+ suffix = f"_{index}" if index else ""
347
+ metrics.append({"name": f"gpu_use{suffix}", "value": use.gpu})
348
+ metrics.append({"name": f"gpu_memory_gb{suffix}", "value": round(memory.used / 1e9, 2)})
349
+ metrics.append({"name": f"gpu_memory_total_gb{suffix}", "value": round(memory.total / 1e9, 2)})
350
+ return metrics
351
+ except Exception: # noqa: BLE001 - no GPU, or no driver
352
+ return []
353
+
354
+
355
+ class Events:
356
+ """Reads what the `workbox` helper wrote since the last report: metrics and samples."""
357
+
358
+ def __init__(self) -> None:
359
+ self.offset = 0
360
+ # The background reporter and the final reports both read; each event must go out once.
361
+ self.lock = threading.Lock()
362
+
363
+ def take(self) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
364
+ metrics: list[dict[str, Any]] = []
365
+ samples: list[dict[str, Any]] = []
366
+ if not EVENTS.exists():
367
+ return metrics, samples
368
+ with self.lock, open(EVENTS, encoding="utf-8") as file:
369
+ file.seek(self.offset)
370
+ for line in file:
371
+ if not line.endswith("\n"):
372
+ break
373
+ self.offset += len(line.encode())
374
+ try:
375
+ event = json.loads(line)
376
+ except json.JSONDecodeError:
377
+ continue
378
+ if event.get("type") == "metric":
379
+ metrics += [{"name": name[:100], "step": event.get("step"), "value": value} for name, value in event["values"].items()]
380
+ elif event.get("type") == "sample":
381
+ image = event.get("image")
382
+ samples.append(
383
+ {
384
+ "step": event.get("step"),
385
+ "name": event.get("name"),
386
+ "text": event.get("text"),
387
+ "image": f"samples/{Path(image).name}" if image else None,
388
+ }
389
+ )
390
+ return metrics, samples
391
+
392
+
393
+ def output_kind(path: str) -> str:
394
+ if path.startswith("samples/"):
395
+ return "sample"
396
+ if path.endswith(".ipynb"):
397
+ return "notebook"
398
+ if path.endswith(".log"):
399
+ return "log"
400
+ if path.endswith((".pt", ".pth", ".ckpt", ".safetensors", ".bin", ".h5", ".keras", ".msgpack")):
401
+ return "checkpoint"
402
+ return "file"
403
+
404
+
405
+ def sha256(file: Path) -> str:
406
+ digest = hashlib.sha256()
407
+ with open(file, "rb") as handle:
408
+ while chunk := handle.read(1 << 20):
409
+ digest.update(chunk)
410
+ return digest.hexdigest()
411
+
412
+
413
+ def send_files(workbox: Workbox, files: dict[str, Path], output: Output) -> None:
414
+ """Records files as the job's outputs and uploads them through the links Workbox answers with."""
415
+ if not files:
416
+ return
417
+ listed = [{"path": path, "size": file.stat().st_size, "sha256": sha256(file), "kind": output_kind(path)} for path, file in files.items()]
418
+ answer = workbox.post("outputs", {"files": listed})
419
+ for item in answer.get("uploads", []):
420
+ if not upload(item["url"], files[item["path"]]):
421
+ output.add(f"Couldn't save {item['path']}.")
422
+
423
+
424
+ def save_outputs(workbox: Workbox, patterns: list[str], extra: dict[str, Path], sent: set[str], output: Output) -> None:
425
+ """Uploads the job's outputs, the log and the sample images not sent while it ran. Runs however the job ended."""
426
+ files: dict[str, Path] = {}
427
+ for pattern in patterns:
428
+ found = WORK / pattern
429
+ if found.is_dir():
430
+ for file in found.rglob("*"):
431
+ if file.is_file():
432
+ files[file.relative_to(WORK).as_posix()] = file
433
+ elif found.is_file():
434
+ files[pattern] = found
435
+ files.update({path: file for path, file in extra.items() if file.is_file()})
436
+ samples = STATE / "samples"
437
+ if samples.is_dir():
438
+ files.update({path: file for file in samples.iterdir() if file.is_file() and (path := f"samples/{file.name}") not in sent})
439
+ send_files(workbox, files, output)
440
+
441
+
442
+ # What the end of a failed job's output says went wrong, checked in order (specs/jobs.md §9).
443
+ DOWNLOAD_ERRORS = (
444
+ "RepositoryNotFoundError",
445
+ "GatedRepoError",
446
+ "HfHubHTTPError",
447
+ "LocalEntryNotFoundError",
448
+ "Max retries exceeded",
449
+ "ConnectionError",
450
+ "urllib.error.URLError",
451
+ "Temporary failure in name resolution",
452
+ )
453
+
454
+
455
+ def classify(lines: list[str], exit_code: int | None) -> str:
456
+ """The kind of a failure, from the end of its output and how the command exited."""
457
+ text = "\n".join(lines[-200:])
458
+ if "CUDA out of memory" in text or "OutOfMemoryError" in text or "RESOURCE_EXHAUSTED" in text:
459
+ return "out_of_memory"
460
+ # Killed by the system for using all of the machine's memory: SIGKILL (137, or -9 from Python).
461
+ if exit_code in (137, -9) or "MemoryError" in text:
462
+ return "out_of_ram"
463
+ if "ModuleNotFoundError" in text or "ImportError" in text:
464
+ return "missing_package"
465
+ if any(marker in text for marker in DOWNLOAD_ERRORS):
466
+ return "download_failed"
467
+ if "FileNotFoundError" in text or "No such file or directory" in text:
468
+ return "missing_file"
469
+ return "exit"
470
+
471
+
472
+ def attach(gateway: dict[str, Any]) -> None:
473
+ """The gateway on a job's machine, with the terminal and SSH, so people can attach (specs/boxes.md §6)."""
474
+ import asyncio
475
+
476
+ from workbox.box import LOGS, start_sshd
477
+ from workbox.box import Log as BoxLog
478
+ from workbox.gateway import Gateway, Tool
479
+
480
+ def serve() -> None:
481
+ ssh_port = start_sshd(gateway["ssh"], BoxLog()) if gateway.get("ssh") else None
482
+ tools = [Tool(**tool) for tool in gateway["tools"]]
483
+ server = Gateway(os.environ["WORKBOX_JOB_ID"], gateway["key"], tools, gateway["opens"], gateway.get("origins", []), ssh_port, WORK, LOGS)
484
+ asyncio.run(server.serve(int(os.environ.get("WORKBOX_GATEWAY_PORT", "9000"))))
485
+
486
+ threading.Thread(target=serve, daemon=True).start()
487
+
488
+
489
+ def main() -> None:
490
+ workbox = Workbox()
491
+ output = Output()
492
+ events = Events()
493
+ tensorboard = TensorBoard()
494
+ STATE.mkdir(parents=True, exist_ok=True)
495
+
496
+ plan = workbox.post("checkin")
497
+ if plan.get("stop") or "spec" not in plan:
498
+ # Printed for the provider's own log: nothing else would say why the machine did no work.
499
+ if "error" in plan:
500
+ print(f"workbox-runner: Workbox refused the check-in ({plan['error']}); stopping.", flush=True)
501
+ elif plan.get("stop"):
502
+ print("workbox-runner: Workbox says this job isn't to run; stopping.", flush=True)
503
+ else:
504
+ print(f"workbox-runner: couldn't reach Workbox at {workbox.url}; stopping.", flush=True)
505
+ return
506
+ spec = plan["spec"]
507
+ if plan.get("gateway"):
508
+ attach(plan["gateway"])
509
+ # The secrets the job asked for: in the environment from here on, so Hugging Face downloads use HF_TOKEN.
510
+ secrets: dict[str, str] = plan.get("secrets", {})
511
+ os.environ.update(secrets)
512
+ output.hide(list(secrets.values()))
513
+ every = plan.get("reportSeconds", 2)
514
+ deadline = time.time() + spec["minutes"] * 60
515
+ stop = threading.Event()
516
+ state = {"phase": None, "commit": None}
517
+ # What is waiting for a report beyond what one may carry, and the sample images already uploaded.
518
+ waiting: dict[str, list[dict[str, Any]]] = {"metrics": [], "samples": []}
519
+ sent: set[str] = set()
520
+ report_lock = threading.Lock()
521
+
522
+ def report(phase: str | None = None) -> None:
523
+ with report_lock:
524
+ helper, samples = events.take()
525
+ output.helper_reported({metric["name"] for metric in helper})
526
+ lines, read = output.take()
527
+ metrics = waiting["metrics"] + helper + read + tensorboard.take() + gpu_metrics()
528
+ samples = waiting["samples"] + samples
529
+ metrics, waiting["metrics"] = metrics[:MAX_REPORT_METRICS], metrics[MAX_REPORT_METRICS:]
530
+ samples, waiting["samples"] = samples[:MAX_REPORT_SAMPLES], samples[MAX_REPORT_SAMPLES:]
531
+ # A sample's image is uploaded before the sample is reported, so the page can show it at once.
532
+ images = {sample["image"]: STATE / sample["image"] for sample in samples if sample["image"] and sample["image"] not in sent}
533
+ send_files(workbox, {path: file for path, file in images.items() if file.is_file()}, output)
534
+ sent.update(images)
535
+ post(phase, lines, metrics, samples)
536
+
537
+ def post(phase: str | None, lines: list[str], metrics: list[dict[str, Any]], samples: list[dict[str, Any]]) -> None:
538
+ body: dict[str, Any] = {"logs": lines, "metrics": metrics, "samples": samples}
539
+ if phase:
540
+ body["phase"] = phase
541
+ if state["commit"]:
542
+ body["commit"], state["commit"] = state["commit"], None
543
+ if workbox.post("report", body).get("stop"):
544
+ stop.set()
545
+
546
+ def reporter() -> None:
547
+ while not stop.is_set() and state["phase"] != "done":
548
+ time.sleep(every)
549
+ report()
550
+
551
+ threading.Thread(target=reporter, daemon=True).start()
552
+ notebook = spec.get("notebook")
553
+ executed = f"{Path(notebook).stem}.executed.ipynb" if notebook else None
554
+ extra = {"logs/job.log": LOG_FILE}
555
+ if executed:
556
+ extra[executed] = WORK / executed
557
+
558
+ exit_code: int | None = None
559
+ reason = "exit"
560
+ detail = ""
561
+ kind = "runner"
562
+ try:
563
+ try:
564
+ state["commit"] = fetch_code(plan["code"], output)
565
+ fetch_inputs(spec["inputs"], plan.get("jobInputs", []), output)
566
+ install_requirements(output)
567
+ except Failure as error:
568
+ reason, detail, kind = "error", f"preparing: {error}", error.kind
569
+ raise
570
+ except Exception as error: # noqa: BLE001
571
+ reason, detail = "error", f"preparing: {error}"
572
+ raise
573
+
574
+ report("running")
575
+ command = ["papermill", notebook, executed] if notebook else ["bash", "-lc", spec["run"]]
576
+ # The job's own code never sees the runner's token.
577
+ env = {**os.environ, **spec["env"], "WORKBOX_EVENTS": str(EVENTS), "PYTHONUNBUFFERED": "1"}
578
+ env.pop("WORKBOX_TOKEN", None)
579
+ process = subprocess.Popen(command, cwd=WORK, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, start_new_session=True)
580
+ def read(stream: Any) -> None:
581
+ for line in stream:
582
+ output.add(line)
583
+
584
+ reader = threading.Thread(target=read, args=(process.stdout,), daemon=True)
585
+ reader.start()
586
+ while process.poll() is None:
587
+ if stop.is_set() or time.time() > deadline:
588
+ reason = "stopped" if stop.is_set() else "time_up"
589
+ os.killpg(process.pid, signal.SIGTERM)
590
+ try:
591
+ process.wait(STOP_GRACE_SECONDS)
592
+ except subprocess.TimeoutExpired:
593
+ os.killpg(process.pid, signal.SIGKILL)
594
+ break
595
+ time.sleep(0.5)
596
+ exit_code = process.wait()
597
+ reader.join(timeout=5)
598
+ except Exception as error: # noqa: BLE001 - the job still saves and finishes
599
+ if reason != "error":
600
+ reason, detail = "error", str(error)
601
+ output.add(f"Workbox: {detail}")
602
+ finally:
603
+ report("saving")
604
+ save_outputs(workbox, spec["outputs"], extra, sent, output)
605
+ state["phase"] = "done"
606
+ report()
607
+ failure = None
608
+ if reason == "error" or (reason == "exit" and exit_code != 0):
609
+ tail = LOG_FILE.read_text(encoding="utf-8", errors="replace").splitlines()[-200:] if LOG_FILE.exists() else []
610
+ failure = {"kind": kind if reason == "error" else classify(tail, exit_code), "detail": output.redact(detail + "\n" + "\n".join(tail))[-20000:]}
611
+ answer = workbox.post("finish", {"exitCode": exit_code, "reason": reason, **({"failure": failure} if failure else {})})
612
+ # `keep` in the spec: a failed job's machine stays a while for people to attach to, then goes.
613
+ if keep := answer.get("keepSeconds"):
614
+ time.sleep(float(keep))
615
+
616
+
617
+ if __name__ == "__main__":
618
+ sys.exit(main())