lowcomm 0.1.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.
lowcomm/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Low-communication training across heterogeneous, unreliable GPUs."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("lowcomm")
lowcomm/cli.py ADDED
@@ -0,0 +1,456 @@
1
+ """lowcomm: join GPU machines into one pool and run work on it.
2
+
3
+ lowcomm key print a fresh random admin key
4
+ lowcomm coordinator run the coordinator (room + admin servers)
5
+ lowcomm room create NAME --public-url URL
6
+ lowcomm room list | lowcomm room close ROOM_ID
7
+ lowcomm node join a room and run tasks
8
+ lowcomm infer --model M --prompts FILE
9
+
10
+ Secrets never go on the command line, where every user on the machine can see
11
+ them (``ps``). The admin key comes from LOWCOMM_ADMIN_KEY. A room code comes
12
+ from LOWCOMM_CODE, or from a file passed with --code-file.
13
+ """
14
+
15
+ import argparse
16
+ import dataclasses
17
+ import json
18
+ import logging
19
+ import os
20
+ import secrets
21
+ import signal
22
+ import ssl
23
+ import sys
24
+ import threading
25
+ import time
26
+ from collections.abc import Callable
27
+ from pathlib import Path
28
+ from typing import TYPE_CHECKING, TextIO
29
+
30
+ from lowcomm.connector.agent import AgentConfig, Handler, NodeAgent
31
+ from lowcomm.connector.batch import JobFailed, gather, submit_all
32
+ from lowcomm.connector.coordinator import Coordinator, CoordinatorConfig
33
+ from lowcomm.connector.errors import ConnectorError, Unauthorized
34
+ from lowcomm.connector.http import (
35
+ HttpAdminClient,
36
+ HttpCoordinatorClient,
37
+ admin_server,
38
+ is_loopback,
39
+ room_server,
40
+ validate_url,
41
+ )
42
+ from lowcomm.connector.rooms import RoomCode, RoomRegistry
43
+ from lowcomm.connector.tls import (
44
+ PinMismatch,
45
+ cert_fingerprint,
46
+ ensure_self_signed,
47
+ server_context,
48
+ )
49
+ from lowcomm.workloads.inference import KIND, InferenceResult, make_requests
50
+
51
+ if TYPE_CHECKING:
52
+ # torch is imported only by commands that run work, so the coordinator
53
+ # stays small (it may run on a 1 GB VPS).
54
+ import torch
55
+
56
+ log = logging.getLogger("lowcomm")
57
+
58
+ ADMIN_KEY_ENV = "LOWCOMM_ADMIN_KEY"
59
+ CODE_ENV = "LOWCOMM_CODE"
60
+ MIB = 1 << 20
61
+ DEFAULT_MAX_BODY_MIB = 512 # fits a 125M-parameter fp32 pseudo-gradient (~500 MB)
62
+ DEFAULT_ROOMS_FILE = Path.home() / ".lowcomm" / "rooms.json"
63
+ DEFAULT_TLS_DIR = Path.home() / ".lowcomm" / "tls"
64
+
65
+
66
+ def _inference(
67
+ device: "torch.device", dtype: "torch.dtype", allowed_models: frozenset[str] | None
68
+ ) -> Handler:
69
+ # Imported on demand: only nodes that run inference need transformers.
70
+ from lowcomm.workloads.hf import inference_handler
71
+
72
+ return inference_handler(device, dtype, allowed_models)
73
+
74
+
75
+ WORKLOADS: dict[str, Callable[["torch.device", "torch.dtype", frozenset[str] | None], Handler]] = {
76
+ KIND: _inference
77
+ }
78
+
79
+ Command = Callable[[argparse.Namespace, threading.Event], int]
80
+
81
+
82
+ # ---- secrets ----------------------------------------------------------------
83
+
84
+
85
+ def _admin_key() -> str:
86
+ key = os.environ.get(ADMIN_KEY_ENV, "")
87
+ if not key:
88
+ raise SystemExit(f"{ADMIN_KEY_ENV} is not set. Generate one with `lowcomm key`.")
89
+ return key
90
+
91
+
92
+ def _room_code(args: argparse.Namespace) -> RoomCode:
93
+ text = Path(args.code_file).read_text() if args.code_file else os.environ.get(CODE_ENV, "")
94
+ if not text.strip():
95
+ raise SystemExit(f"no room code: set {CODE_ENV} or pass --code-file")
96
+ try:
97
+ code = RoomCode.decode(text)
98
+ except ValueError as e:
99
+ raise SystemExit(f"bad room code: {e}") from None
100
+ # A tunnel's or a home connection's address can change; the room and key don't.
101
+ return dataclasses.replace(code, url=args.url) if args.url else code
102
+
103
+
104
+ def _room_client(args: argparse.Namespace) -> HttpCoordinatorClient:
105
+ code = _room_code(args)
106
+ return HttpCoordinatorClient(
107
+ code.url,
108
+ key=code.key,
109
+ timeout=args.http_timeout,
110
+ max_body_bytes=args.max_body_mib * MIB,
111
+ pin=code.pin,
112
+ )
113
+
114
+
115
+ def _admin_client(args: argparse.Namespace) -> HttpAdminClient:
116
+ return HttpAdminClient(
117
+ f"http://127.0.0.1:{args.admin_port}", key=_admin_key(), timeout=args.http_timeout
118
+ )
119
+
120
+
121
+ # ---- commands ---------------------------------------------------------------
122
+
123
+
124
+ def run_key(args: argparse.Namespace, stop: threading.Event) -> int:
125
+ print(secrets.token_urlsafe(32))
126
+ return 0
127
+
128
+
129
+ def _tls(args: argparse.Namespace) -> tuple[ssl.SSLContext | None, str | None]:
130
+ """The room server's TLS context and, for a self-signed certificate, its pin."""
131
+ if args.tls_self_signed:
132
+ cert, key = ensure_self_signed(Path(args.tls_dir))
133
+ pin = cert_fingerprint(cert)
134
+ log.info("self-signed TLS certificate %s, fingerprint %s", cert, pin)
135
+ return server_context(cert, key), pin
136
+ if args.tls_cert:
137
+ log.info("TLS certificate %s", args.tls_cert)
138
+ return server_context(Path(args.tls_cert), Path(args.tls_key)), None
139
+ return None, None
140
+
141
+
142
+ def run_coordinator(args: argparse.Namespace, stop: threading.Event) -> int:
143
+ admin_key = _admin_key()
144
+ if bool(args.tls_cert) != bool(args.tls_key):
145
+ raise SystemExit("--tls-cert and --tls-key go together")
146
+ if args.tls_cert and args.tls_self_signed:
147
+ raise SystemExit("use either --tls-self-signed or --tls-cert/--tls-key")
148
+ config = CoordinatorConfig(lease_ttl=args.lease_ttl, max_attempts=args.max_attempts)
149
+ registry = RoomRegistry(Path(args.rooms_file), lambda: Coordinator(config))
150
+ tls, pin = _tls(args)
151
+ if tls is None and not is_loopback(args.host):
152
+ log.warning("listening on %s without TLS; expose it only through a TLS tunnel", args.host)
153
+ max_body = args.max_body_mib * MIB
154
+ with (
155
+ room_server(
156
+ registry, host=args.host, port=args.port, max_body_bytes=max_body, tls=tls
157
+ ) as rooms,
158
+ admin_server(registry, admin_key=admin_key, port=args.admin_port, tls_pin=pin) as admin,
159
+ ):
160
+ log.info("rooms served on %s; admin on %s (loopback only)", rooms.url, admin.url)
161
+ log.info("%d room(s) loaded from %s", len(registry.rooms()), args.rooms_file)
162
+ stop.wait()
163
+ log.info("coordinator stopped")
164
+ return 0
165
+
166
+
167
+ def run_room_create(args: argparse.Namespace, stop: threading.Event) -> int:
168
+ try:
169
+ validate_url(args.public_url)
170
+ except ValueError as e:
171
+ raise SystemExit(str(e)) from None
172
+ admin = _admin_client(args)
173
+ pin = admin.tls_pin()
174
+ room = admin.create_room(args.name)
175
+ print(f"room {room.name!r} created (id {room.room_id})\n")
176
+ if pin:
177
+ print(f"codes pin the coordinator's self-signed certificate ({pin[:16]}...)\n")
178
+ print("OWNER code (keep private; submits work and reads results):")
179
+ print(f" {RoomCode(args.public_url, room.owner_key, pin).encode()}\n")
180
+ print("JOIN code (give to people adding machines; can only run tasks):")
181
+ print(f" {RoomCode(args.public_url, room.join_key, pin).encode()}\n")
182
+ print(f"Use a code via the {CODE_ENV} environment variable or --code-file.")
183
+ return 0
184
+
185
+
186
+ def run_room_list(args: argparse.Namespace, stop: threading.Event) -> int:
187
+ for room in _admin_client(args).list_rooms():
188
+ stats = " ".join(f"{k}={v}" for k, v in room.stats.items())
189
+ print(f"{room.room_id} {room.name:<20} {stats}")
190
+ return 0
191
+
192
+
193
+ def run_room_close(args: argparse.Namespace, stop: threading.Event) -> int:
194
+ _admin_client(args).close_room(args.room_id)
195
+ print(f"room {args.room_id} closed; its codes no longer work")
196
+ return 0
197
+
198
+
199
+ def _device(name: str) -> "torch.device":
200
+ import torch
201
+
202
+ if name == "auto":
203
+ if torch.cuda.is_available():
204
+ return torch.device("cuda")
205
+ if torch.backends.mps.is_available():
206
+ return torch.device("mps")
207
+ return torch.device("cpu")
208
+ device = torch.device(name)
209
+ if device.type == "cuda" and not torch.cuda.is_available():
210
+ raise SystemExit(f"device {name} requested but CUDA is not available")
211
+ if device.type == "mps" and not torch.backends.mps.is_available():
212
+ raise SystemExit(f"device {name} requested but the Apple GPU (MPS) is not available")
213
+ return device
214
+
215
+
216
+ def run_node(args: argparse.Namespace, stop: threading.Event) -> int:
217
+ import torch
218
+
219
+ from lowcomm.connector.probe import probe_capabilities
220
+
221
+ api = _room_client(args)
222
+ device = _device(args.device)
223
+ if args.dtype == "auto":
224
+ from lowcomm.workloads.hf import default_dtype
225
+
226
+ dtype = default_dtype(device)
227
+ else:
228
+ dtype = getattr(torch, args.dtype)
229
+ allowed = frozenset(args.allow_model) if args.allow_model else None
230
+ handlers = {name: WORKLOADS[name](device, dtype, allowed) for name in args.workload}
231
+ capabilities = probe_capabilities(device)
232
+ log.info(
233
+ "node on %s (%s), workloads %s, capabilities %s", device, dtype, args.workload, capabilities
234
+ )
235
+ config = AgentConfig(
236
+ poll_interval=args.poll_interval, retry_min=args.retry_min, retry_max=args.retry_max
237
+ )
238
+ try:
239
+ NodeAgent(api, handlers, capabilities, config, stop).run()
240
+ except Unauthorized:
241
+ log.error(
242
+ "the coordinator rejected this room code: the room was closed, or the code is wrong"
243
+ )
244
+ return 2
245
+ except PinMismatch as e:
246
+ log.error("%s", e)
247
+ return 2
248
+ return 0
249
+
250
+
251
+ def _read_prompts(path: str) -> list[str]:
252
+ """One prompt per line; ``.jsonl`` files hold objects with a "prompt" field."""
253
+ text = sys.stdin.read() if path == "-" else Path(path).read_text()
254
+ lines = [line for line in text.splitlines() if line.strip()]
255
+ if not path.endswith(".jsonl"):
256
+ return lines
257
+ prompts = [json.loads(line).get("prompt") for line in lines]
258
+ if not all(isinstance(p, str) for p in prompts):
259
+ raise SystemExit(f"every line of {path} needs a string 'prompt' field")
260
+ return prompts
261
+
262
+
263
+ def _requirement(text: str) -> tuple[str, float]:
264
+ name, sep, value = text.partition("=")
265
+ try:
266
+ if not (sep and name):
267
+ raise ValueError
268
+ return name, float(value)
269
+ except ValueError:
270
+ raise argparse.ArgumentTypeError(f"expected NAME=NUMBER, got {text!r}") from None
271
+
272
+
273
+ def run_infer(args: argparse.Namespace, stop: threading.Event) -> int:
274
+ prompts = _read_prompts(args.prompts)
275
+ if not prompts:
276
+ raise SystemExit("no prompts given")
277
+ api = _room_client(args)
278
+ # Fail before spending GPU time, not after: a bad path would lose the results.
279
+ out = sys.stdout if args.output == "-" else open(args.output, "w") # noqa: SIM115
280
+ try:
281
+ return _infer(args, api, prompts, out, stop)
282
+ finally:
283
+ if out is not sys.stdout:
284
+ out.close()
285
+
286
+
287
+ def _infer(
288
+ args: argparse.Namespace,
289
+ api: HttpCoordinatorClient,
290
+ prompts: list[str],
291
+ out: TextIO,
292
+ stop: threading.Event,
293
+ ) -> int:
294
+ requests = make_requests(
295
+ args.model, prompts, args.chunk_size, args.max_new_tokens, args.temperature, args.seed
296
+ )
297
+ start = time.monotonic()
298
+ try:
299
+ task_ids = submit_all(api, KIND, (r.to_bytes() for r in requests), dict(args.require))
300
+ except OSError as e:
301
+ log.error("cannot reach the coordinator: %s", e)
302
+ return 1
303
+ except ConnectorError as e:
304
+ log.error("the coordinator refused the job: %s", e)
305
+ return 1
306
+ log.info("submitted %d prompts as %d tasks", len(prompts), len(task_ids))
307
+ try:
308
+ raw = gather(
309
+ api, task_ids, poll_interval=args.poll_interval, timeout=args.timeout, stop=stop
310
+ )
311
+ except (JobFailed, TimeoutError, InterruptedError) as e:
312
+ log.error("%s", e)
313
+ return 1
314
+ wall = time.monotonic() - start
315
+ results = [InferenceResult.from_bytes(r) for r in raw]
316
+
317
+ for request, result in zip(requests, results, strict=True):
318
+ for prompt, completion in zip(request.prompts, result.completions, strict=True):
319
+ record = {
320
+ "prompt": prompt,
321
+ "completion": completion,
322
+ "device": result.device,
323
+ "dtype": result.dtype,
324
+ }
325
+ out.write(json.dumps(record) + "\n")
326
+ _summarize(results, wall)
327
+ return 0
328
+
329
+
330
+ def _summarize(results: list[InferenceResult], wall: float) -> None:
331
+ tokens = sum(r.new_tokens for r in results)
332
+ gen = sum(r.generate_seconds for r in results)
333
+ load = sum(r.load_seconds for r in results)
334
+ devices = sorted({r.device for r in results})
335
+ log.info(
336
+ "%d new tokens in %.1fs wall (%.1f tok/s end to end); generation %.1fs, "
337
+ "model loads %.1fs, summed over accepted results (re-run tasks' discarded "
338
+ "results are not counted); devices: %s",
339
+ tokens, wall, tokens / wall, gen, load, devices,
340
+ ) # fmt: skip
341
+
342
+
343
+ # ---- argument parsing -------------------------------------------------------
344
+
345
+
346
+ def build_parser() -> argparse.ArgumentParser:
347
+ parser = argparse.ArgumentParser(prog="lowcomm", description=(__doc__ or "").split("\n\n")[0])
348
+ parser.add_argument("--log-level", default="INFO", choices=["DEBUG", "INFO", "WARNING"])
349
+ commands = parser.add_subparsers(required=True, metavar="COMMAND")
350
+
351
+ def http_options(p: argparse.ArgumentParser) -> None:
352
+ p.add_argument("--http-timeout", type=float, default=30.0, help="seconds per request")
353
+
354
+ def room_options(p: argparse.ArgumentParser) -> None:
355
+ p.add_argument("--code-file", help=f"file holding the room code (default: ${CODE_ENV})")
356
+ p.add_argument("--url", help="override the coordinator URL inside the code")
357
+ p.add_argument("--max-body-mib", type=int, default=DEFAULT_MAX_BODY_MIB)
358
+ http_options(p)
359
+
360
+ def admin_options(p: argparse.ArgumentParser) -> None:
361
+ p.add_argument("--admin-port", type=int, default=8001)
362
+ http_options(p)
363
+
364
+ p = commands.add_parser("key", help="print a fresh random admin key")
365
+ p.set_defaults(run=run_key)
366
+
367
+ p = commands.add_parser("coordinator", help="run the coordinator")
368
+ p.add_argument("--host", default="127.0.0.1", help="room server address")
369
+ p.add_argument("--port", type=int, default=8000, help="room server port (expose this one)")
370
+ p.add_argument("--admin-port", type=int, default=8001, help="admin port (loopback only)")
371
+ p.add_argument("--rooms-file", default=str(DEFAULT_ROOMS_FILE))
372
+ p.add_argument("--lease-ttl", type=float, default=CoordinatorConfig.lease_ttl)
373
+ p.add_argument("--max-attempts", type=int, default=CoordinatorConfig.max_attempts)
374
+ p.add_argument("--max-body-mib", type=int, default=DEFAULT_MAX_BODY_MIB)
375
+ p.add_argument(
376
+ "--tls-self-signed",
377
+ action="store_true",
378
+ help="serve TLS with a self-signed certificate that room codes pin "
379
+ "(for a VPS or a port forward; not needed behind a tunnel)",
380
+ )
381
+ p.add_argument("--tls-dir", default=str(DEFAULT_TLS_DIR), help="where that certificate lives")
382
+ p.add_argument("--tls-cert", help="serve TLS with this certificate (PEM), e.g. Let's Encrypt")
383
+ p.add_argument("--tls-key", help="private key (PEM) for --tls-cert")
384
+ p.set_defaults(run=run_coordinator)
385
+
386
+ room = commands.add_parser("room", help="create, list and close rooms").add_subparsers(
387
+ required=True, metavar="ACTION"
388
+ )
389
+ p = room.add_parser("create", help="create a room and print its codes")
390
+ p.add_argument("name")
391
+ p.add_argument(
392
+ "--public-url", required=True, help="the URL nodes will reach the coordinator at"
393
+ )
394
+ admin_options(p)
395
+ p.set_defaults(run=run_room_create)
396
+ p = room.add_parser("list", help="list rooms with node and task counts")
397
+ admin_options(p)
398
+ p.set_defaults(run=run_room_list)
399
+ p = room.add_parser("close", help="close a room; its codes stop working")
400
+ p.add_argument("room_id")
401
+ admin_options(p)
402
+ p.set_defaults(run=run_room_close)
403
+
404
+ p = commands.add_parser("node", help="join a room and run tasks")
405
+ p.add_argument("--workload", nargs="+", choices=sorted(WORKLOADS), default=sorted(WORKLOADS))
406
+ p.add_argument("--device", default="auto", help="auto, cpu, cuda, cuda:1, mps")
407
+ p.add_argument("--dtype", default="auto", choices=["auto", "float32", "float16", "bfloat16"])
408
+ p.add_argument(
409
+ "--allow-model",
410
+ action="append",
411
+ metavar="MODEL",
412
+ help="only run these models (repeatable); default: any Hub model, safetensors only",
413
+ )
414
+ p.add_argument("--poll-interval", type=float, default=AgentConfig.poll_interval)
415
+ p.add_argument("--retry-min", type=float, default=AgentConfig.retry_min)
416
+ p.add_argument("--retry-max", type=float, default=AgentConfig.retry_max)
417
+ room_options(p)
418
+ p.set_defaults(run=run_node)
419
+
420
+ p = commands.add_parser("infer", help="run batch inference on a room (needs the owner code)")
421
+ p.add_argument("--model", required=True, help="Hugging Face model id")
422
+ p.add_argument("--prompts", required=True, help="text file (one per line), .jsonl, or -")
423
+ p.add_argument("--output", default="-", help="JSONL output file, or - for stdout")
424
+ p.add_argument("--chunk-size", type=int, default=8, help="prompts per task")
425
+ p.add_argument("--max-new-tokens", type=int, default=64)
426
+ p.add_argument("--temperature", type=float, default=0.0, help="0 = greedy")
427
+ p.add_argument("--seed", type=int, default=0)
428
+ p.add_argument(
429
+ "--require",
430
+ type=_requirement,
431
+ action="append",
432
+ default=[],
433
+ metavar="NAME=MIN",
434
+ help="node capability minimum, e.g. gpu_vram_bytes=15e9 (repeatable)",
435
+ )
436
+ p.add_argument("--poll-interval", type=float, default=2.0)
437
+ p.add_argument("--timeout", type=float, default=None, help="give up after this many seconds")
438
+ room_options(p)
439
+ p.set_defaults(run=run_infer)
440
+ return parser
441
+
442
+
443
+ def main(argv: list[str] | None = None) -> int:
444
+ args = build_parser().parse_args(argv)
445
+ logging.basicConfig(
446
+ level=args.log_level, format="%(asctime)s %(levelname)s %(name)s: %(message)s"
447
+ )
448
+ stop = threading.Event()
449
+ for sig in (signal.SIGINT, signal.SIGTERM):
450
+ signal.signal(sig, lambda *_: stop.set())
451
+ command: Command = args.run
452
+ return command(args, stop)
453
+
454
+
455
+ if __name__ == "__main__":
456
+ sys.exit(main())
@@ -0,0 +1 @@
1
+ """The GPU connector: coordinator, wire format, HTTP transport and node agent."""
@@ -0,0 +1,218 @@
1
+ """The node agent: runs on each GPU machine and turns it into part of the pool.
2
+
3
+ Loop: register -> acquire a task -> run its handler -> report the result.
4
+ A background thread sends heartbeats naming the leases currently held. The
5
+ agent survives everything outside its control:
6
+
7
+ - network failure: retry with capped, jittered exponential backoff;
8
+ - coordinator forgot us (restart, or we were silent too long): register again;
9
+ - our lease went stale: drop the result, the coordinator gave the task away;
10
+ - the workload raised: report the failure so the task is retried elsewhere.
11
+ """
12
+
13
+ import logging
14
+ import random
15
+ import threading
16
+ import time
17
+ from collections.abc import Callable, Iterable, Mapping
18
+ from dataclasses import dataclass
19
+ from typing import Protocol
20
+
21
+ from lowcomm.connector.coordinator import Assignment, Registration
22
+ from lowcomm.connector.errors import ConnectorError, StaleLease, UnknownLease, UnknownNode
23
+
24
+ log = logging.getLogger(__name__)
25
+
26
+ Handler = Callable[[bytes], bytes]
27
+
28
+
29
+ class NodeAPI(Protocol):
30
+ """What a node needs from a coordinator, in-process or over the network."""
31
+
32
+ def register(self, capabilities: Mapping[str, float], kinds: Iterable[str]) -> Registration: ...
33
+ def heartbeat(self, node_id: str, lease_ids: Iterable[str]) -> frozenset[str]: ...
34
+ def acquire(self, node_id: str) -> Assignment | None: ...
35
+ def complete(self, lease_id: str, result: bytes) -> None: ...
36
+ def fail(self, lease_id: str, reason: str) -> None: ...
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class AgentConfig:
41
+ poll_interval: float = 1.0
42
+ """Seconds to wait before asking again when there is no work."""
43
+ retry_min: float = 0.5
44
+ retry_max: float = 30.0
45
+ """Backoff bounds, in seconds, while the coordinator is unreachable."""
46
+ heartbeats_per_ttl: int = 3
47
+ """Heartbeats sent per lease TTL, so one or two lost ones don't cost the lease."""
48
+
49
+ def __post_init__(self) -> None:
50
+ if not 0 < self.retry_min <= self.retry_max:
51
+ raise ValueError("need 0 < retry_min <= retry_max")
52
+ if self.poll_interval <= 0 or self.heartbeats_per_ttl < 1:
53
+ raise ValueError("poll_interval and heartbeats_per_ttl must be positive")
54
+
55
+
56
+ class Backoff:
57
+ """Full-jitter exponential backoff: wait a random time up to min(max, min * 2^n)."""
58
+
59
+ def __init__(self, low: float, high: float, rng: random.Random) -> None:
60
+ self._low, self._high, self._rng = low, high, rng
61
+ self._failures = 0
62
+
63
+ def next(self) -> float:
64
+ ceiling = min(self._high, self._low * 2**self._failures)
65
+ self._failures += 1
66
+ return self._rng.uniform(self._low, ceiling)
67
+
68
+ def reset(self) -> None:
69
+ self._failures = 0
70
+
71
+
72
+ class NodeAgent:
73
+ def __init__(
74
+ self,
75
+ api: NodeAPI,
76
+ handlers: Mapping[str, Handler],
77
+ capabilities: Mapping[str, float],
78
+ config: AgentConfig,
79
+ stop: threading.Event,
80
+ rng: random.Random | None = None,
81
+ ) -> None:
82
+ if not handlers:
83
+ raise ValueError("an agent needs at least one workload handler")
84
+ self._api = api
85
+ self._handlers = dict(handlers)
86
+ self._capabilities = dict(capabilities)
87
+ self._config = config
88
+ self._stop = stop
89
+ self._rng = rng or random.Random()
90
+ self._backoff = self._new_backoff()
91
+ # Written by the main loop, read by the heartbeat thread.
92
+ self._lock = threading.Lock()
93
+ self._registration: Registration | None = None
94
+ self._held: set[str] = set()
95
+
96
+ def run(self) -> None:
97
+ """Work until ``stop`` is set. A task in progress is finished first.
98
+
99
+ Errors the agent has no recovery for (anything but network failures and
100
+ a forgotten registration) propagate, after the heartbeat thread stops.
101
+ """
102
+ exiting = threading.Event()
103
+ heartbeat = threading.Thread(
104
+ target=self._heartbeat_loop, args=(exiting,), name="heartbeat", daemon=True
105
+ )
106
+ heartbeat.start()
107
+ try:
108
+ while not self._stop.is_set():
109
+ self._run_once()
110
+ finally:
111
+ exiting.set()
112
+ heartbeat.join()
113
+
114
+ def _run_once(self) -> None:
115
+ try:
116
+ if not self._work():
117
+ self._stop.wait(self._config.poll_interval)
118
+ self._backoff.reset()
119
+ except UnknownNode:
120
+ log.warning("coordinator does not know this node; registering again")
121
+ self._set_registration(None)
122
+ except OSError as e:
123
+ delay = self._backoff.next()
124
+ log.warning("coordinator unreachable (%s); retrying in %.1fs", e, delay)
125
+ self._stop.wait(delay)
126
+
127
+ def _work(self) -> bool:
128
+ """Run at most one task. Returns False if there was none."""
129
+ registration = self._registration or self._register()
130
+ assignment = self._api.acquire(registration.node_id)
131
+ if assignment is None:
132
+ return False
133
+ lease_id = assignment.lease_id
134
+ with self._lock:
135
+ self._held.add(lease_id)
136
+ try:
137
+ log.info("running task %s (%s)", assignment.task_id, assignment.kind)
138
+ try:
139
+ result = self._handlers[assignment.kind](assignment.payload)
140
+ except Exception as e: # a workload bug must not kill the node
141
+ log.exception("task %s failed", assignment.task_id)
142
+ reason = f"{type(e).__name__}: {e}"
143
+ self._report(lambda: self._api.fail(lease_id, reason))
144
+ else:
145
+ self._report(lambda: self._api.complete(lease_id, result))
146
+ finally:
147
+ with self._lock:
148
+ self._held.discard(lease_id)
149
+ return True
150
+
151
+ def _new_backoff(self) -> Backoff:
152
+ return Backoff(self._config.retry_min, self._config.retry_max, self._rng)
153
+
154
+ def _register(self) -> Registration:
155
+ registration = self._api.register(self._capabilities, list(self._handlers))
156
+ log.info("registered as node %s", registration.node_id)
157
+ self._set_registration(registration)
158
+ return registration
159
+
160
+ def _set_registration(self, registration: Registration | None) -> None:
161
+ with self._lock:
162
+ self._registration = registration
163
+
164
+ def _report(self, send: Callable[[], None]) -> None:
165
+ """Send a complete/fail, retrying network errors. Both calls are idempotent,
166
+ so retrying after a lost acknowledgement is safe."""
167
+ backoff = self._new_backoff()
168
+ while not self._stop.is_set():
169
+ try:
170
+ send()
171
+ return
172
+ except (StaleLease, UnknownLease):
173
+ log.warning("lease is no longer ours; result discarded")
174
+ return
175
+ except ConnectorError:
176
+ # Retrying can't fix a rejected report (e.g. result too large). The
177
+ # lease will expire and the coordinator retries or fails the task.
178
+ log.exception("coordinator rejected the report; giving up on this lease")
179
+ return
180
+ except OSError as e:
181
+ delay = backoff.next()
182
+ log.warning("could not report result (%s); retrying in %.1fs", e, delay)
183
+ self._stop.wait(delay)
184
+
185
+ def _heartbeat_loop(self, exiting: threading.Event) -> None:
186
+ last_sent = time.monotonic()
187
+ while not exiting.wait(self._heartbeat_interval()):
188
+ with self._lock:
189
+ registration, held = self._registration, list(self._held)
190
+ if registration is None:
191
+ last_sent = time.monotonic()
192
+ continue
193
+ # Something can starve this thread (CPU oversubscription, code holding
194
+ # the GIL). Report it: early if the delay is under the TTL, otherwise
195
+ # after the fact, since a starved thread can't log until it runs.
196
+ gap = time.monotonic() - last_sent
197
+ if gap > registration.lease_ttl / 2:
198
+ log.warning(
199
+ "heartbeat delayed %.1fs (lease TTL %.1fs); leases at risk",
200
+ gap, registration.lease_ttl,
201
+ ) # fmt: skip
202
+ last_sent = time.monotonic()
203
+ try:
204
+ lost = self._api.heartbeat(registration.node_id, held)
205
+ except (OSError, ConnectorError) as e:
206
+ # Never fatal here: the main loop meets the same condition on its
207
+ # next call and handles it there.
208
+ log.warning("heartbeat failed: %s", e)
209
+ continue
210
+ log.debug("heartbeat renewed %d lease(s)", len(held) - len(lost))
211
+ if lost:
212
+ log.warning("leases lost: %s", sorted(lost))
213
+
214
+ def _heartbeat_interval(self) -> float:
215
+ registration = self._registration
216
+ if registration is None:
217
+ return self._config.poll_interval
218
+ return registration.lease_ttl / self._config.heartbeats_per_ttl