world: install legion at a pinned commit instead of vendoring it

#1
by lewtun HF Staff - opened
README.md CHANGED
@@ -15,11 +15,9 @@ world/ the shared world service (World API v1), one per run
15
  seed/ the bot the code dataset starts from (runtime, modules, deck, tests, docs)
16
  tests/ the world's tests (pytest), with a small test seed in tests/fixtures/
17
  scripts/ smoke-local.py and check-sidecar.py: container-free checks on localhost
18
- src/ legion's World API library, vendored (never edit; vendor.sh)
19
- requirements.txt the world's Python deps with hashes (from legion's uv.lock; vendor.sh)
20
- source-lock.json the legion commit and the sha256 of every vendored file
21
- vendor.sh re-vendor src/ and requirements.txt from a legion checkout
22
- Dockerfile the world image (also the sidecar's); entrypoint.sh starts the world
23
  ```
24
 
25
  ## The world
@@ -153,15 +151,34 @@ workers:
153
  env: {PYBOT_REPO: '${PYBOT_REPO}'} # the task's [environment.env] reads it
154
  ```
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  ## Checks
157
 
158
  ```sh
159
  cd world
160
- pip install --require-hashes --no-deps -r requirements.txt && pip install pytest pytest-asyncio
 
 
161
  python -m pytest # the world's tests (Python 3.12, git, prlimit)
162
  python scripts/smoke-local.py --sidecar # the served world on localhost with a fake Hub
163
  python scripts/check-sidecar.py # the sidecar's checks
164
- ./vendor.sh /path/to/legion # the vendored library matches source-lock.json
165
  ```
166
 
167
  `smoke-local.py` without `--sidecar` runs the bot under `unshare`, which many machines and
 
15
  seed/ the bot the code dataset starts from (runtime, modules, deck, tests, docs)
16
  tests/ the world's tests (pytest), with a small test seed in tests/fixtures/
17
  scripts/ smoke-local.py and check-sidecar.py: container-free checks on localhost
18
+ requirements.txt the world's Python deps with hashes (legion's uv.lock at the pinned commit)
19
+ Dockerfile the world image (also the sidecar's), with legion pinned to a commit;
20
+ entrypoint.sh starts the world
 
 
21
  ```
22
 
23
  ## The world
 
151
  env: {PYBOT_REPO: '${PYBOT_REPO}'} # the task's [environment.env] reads it
152
  ```
153
 
154
+ ## The legion pin
155
+
156
+ The world imports legion's World API library (`legion.world`, `legion.isolation`,
157
+ `legion.worker.sync`) from the installed `legion` package. Its commit is pinned in one place, the
158
+ `legion @ git+https://github.com/huggingface/legion@<commit>` line in `world/Dockerfile`, and
159
+ `requirements.txt` is legion's own `uv.lock` at that commit, exported with hashes. To bump it,
160
+ change the commit there and regenerate `requirements.txt` from a legion clone (in `world/`):
161
+
162
+ ```sh
163
+ lock=$(mktemp -d) && git -C /path/to/legion archive <commit> pyproject.toml uv.lock | tar -x -C "$lock"
164
+ uv export -q --project "$lock" --frozen --no-emit-project --extra controller --no-dev --no-header \
165
+ --prune harbor --prune podman-compose --prune msgboard -o requirements.txt
166
+ ```
167
+
168
+ The prunes drop what the world does not use: Harbor and the board client (msgboard is a git
169
+ dependency, which pip's `--require-hashes` refuses). Then run the checks below, rebuild the image
170
+ and bump this dataset's `revision` in the legion specs that use it.
171
+
172
  ## Checks
173
 
174
  ```sh
175
  cd world
176
+ pip install --require-hashes --no-deps -r requirements.txt
177
+ pip install --no-deps "$(grep -o 'legion @ git+[^"]*' Dockerfile)" # legion at the pinned commit
178
+ pip install pytest pytest-asyncio
179
  python -m pytest # the world's tests (Python 3.12, git, prlimit)
180
  python scripts/smoke-local.py --sidecar # the served world on localhost with a fake Hub
181
  python scripts/check-sidecar.py # the sidecar's checks
 
182
  ```
183
 
184
  `smoke-local.py` without `--sidecar` runs the bot under `unshare`, which many machines and
world/Dockerfile CHANGED
@@ -2,10 +2,12 @@
2
  # docker build -t <registry>/pybot-world:<tag> world/
3
  # The same image runs the bot sandbox sidecar (command `python sandbox.py serve`). The base is
4
  # pinned by digest (3.12: the seed's bot imports `copy`, which the bot sandbox allows only on
5
- # 3.12+); Python deps are legion's own uv.lock (exact versions + hashes, see vendor.sh).
 
6
  FROM python:3.12.15-slim-bookworm@sha256:6a0e06f5ba0b373d051aabd3fffb9b873f27f9a2a3a14bcbe37dee6f0e3bbc70
7
 
8
- # git: the world's bare repo, fetches and pushes to the Hub. util-linux (unshare) ships in the base.
 
9
  RUN apt-get update \
10
  && apt-get install -y --no-install-recommends git \
11
  && rm -rf /var/lib/apt/lists/*
@@ -13,8 +15,11 @@ RUN apt-get update \
13
  COPY requirements.txt /opt/world/requirements.txt
14
  RUN pip install --no-cache-dir --no-deps --require-hashes -r /opt/world/requirements.txt
15
 
16
- # src/: legion's World API library, vendored by vendor.sh (hashes in source-lock.json), never edited.
17
- COPY src/ /opt/world/src/
 
 
 
18
  COPY pybot.py repository.py sandbox.py snapshot.py /opt/world/
19
  COPY seed/ /opt/world/seed/
20
  COPY --chmod=755 entrypoint.sh /usr/local/bin/pybot-entrypoint
@@ -22,8 +27,7 @@ COPY --chmod=755 entrypoint.sh /usr/local/bin/pybot-entrypoint
22
  RUN useradd -m -u 1000 user && mkdir -p /work && chown user:user /work
23
  USER user
24
  # For the sidecar's bare `python sandbox.py serve` (a job command replaces the entrypoint); the
25
- # entrypoint sets its own PYTHONPATH and cwd, so the world does not depend on these.
26
- ENV PYTHONPATH=/opt/world/src
27
  WORKDIR /opt/world
28
  EXPOSE 7860
29
  ENTRYPOINT ["/usr/local/bin/pybot-entrypoint"]
 
2
  # docker build -t <registry>/pybot-world:<tag> world/
3
  # The same image runs the bot sandbox sidecar (command `python sandbox.py serve`). The base is
4
  # pinned by digest (3.12: the seed's bot imports `copy`, which the bot sandbox allows only on
5
+ # 3.12+); Python deps are legion's own uv.lock (exact versions + hashes), and legion itself is
6
+ # installed at the commit that lock comes from (README, "The legion pin").
7
  FROM python:3.12.15-slim-bookworm@sha256:6a0e06f5ba0b373d051aabd3fffb9b873f27f9a2a3a14bcbe37dee6f0e3bbc70
8
 
9
+ # git: the world's bare repo, fetches and pushes to the Hub, and pip's legion checkout.
10
+ # util-linux (unshare) ships in the base.
11
  RUN apt-get update \
12
  && apt-get install -y --no-install-recommends git \
13
  && rm -rf /var/lib/apt/lists/*
 
15
  COPY requirements.txt /opt/world/requirements.txt
16
  RUN pip install --no-cache-dir --no-deps --require-hashes -r /opt/world/requirements.txt
17
 
18
+ # legion's World API library, pinned to a commit (pip cannot hash a git requirement, so it gets its
19
+ # own install). --no-deps: its deps are the hashed ones above; the world needs no Harbor or board.
20
+ RUN pip install --no-cache-dir --no-deps \
21
+ "legion @ git+https://github.com/huggingface/legion@803873b114d5e04a3a01fea5e2e9084a03596fab"
22
+
23
  COPY pybot.py repository.py sandbox.py snapshot.py /opt/world/
24
  COPY seed/ /opt/world/seed/
25
  COPY --chmod=755 entrypoint.sh /usr/local/bin/pybot-entrypoint
 
27
  RUN useradd -m -u 1000 user && mkdir -p /work && chown user:user /work
28
  USER user
29
  # For the sidecar's bare `python sandbox.py serve` (a job command replaces the entrypoint); the
30
+ # entrypoint sets its own cwd, so the world does not depend on it.
 
31
  WORKDIR /opt/world
32
  EXPOSE 7860
33
  ENTRYPOINT ["/usr/local/bin/pybot-entrypoint"]
world/entrypoint.sh CHANGED
@@ -32,7 +32,9 @@ case $PORT in ''|*[!0-9]*|0) die "PORT=$PORT must be a positive integer";; esac
32
  WORLD=${WORLD_DIR:-/opt/world}
33
  WORK=${PYBOT_WORK:-/work}
34
  # Set here, not in the image: pyxis passes the host env (HOME, PYTHONPATH) into the container.
35
- export PYTHONPATH=$WORLD/src HOME=$WORK/home HF_HOME=$WORK/hf TMPDIR=$WORK/tmp
 
 
36
  export PYBOT_WS=$WORK/ws PYTHONUNBUFFERED=1
37
  mkdir -p "$PYBOT_WS" "$HOME" "$HF_HOME" "$TMPDIR" || die "cannot create dirs under $WORK"
38
 
 
32
  WORLD=${WORLD_DIR:-/opt/world}
33
  WORK=${PYBOT_WORK:-/work}
34
  # Set here, not in the image: pyxis passes the host env (HOME, PYTHONPATH) into the container.
35
+ # A host PYTHONPATH must not shadow the image's installed legion.
36
+ unset PYTHONPATH
37
+ export HOME=$WORK/home HF_HOME=$WORK/hf TMPDIR=$WORK/tmp
38
  export PYBOT_WS=$WORK/ws PYTHONUNBUFFERED=1
39
  mkdir -p "$PYBOT_WS" "$HOME" "$HF_HOME" "$TMPDIR" || die "cannot create dirs under $WORK"
40
 
world/scripts/check-sidecar.py CHANGED
@@ -7,7 +7,7 @@ along), and a test cannot import socket or write a file; a tree of 3,000 more fi
7
  main) goes through for both; a bad token or an unreachable sidecar is `busy`, and a refusal logs
8
  its HTTP status; a tar with `../`, a link, too many members or too many bytes is a 400; a timeout
9
  works.
10
- Local path without `unshare` (blocked on many boxes). Needs requirements.txt, 3.12+.
11
  """
12
  import base64
13
  import io
@@ -25,8 +25,8 @@ import urllib.error
25
  import urllib.request
26
  from pathlib import Path
27
 
28
- WORLD = SRC = Path(__file__).resolve().parent.parent # world/
29
- sys.path[:0] = [str(WORLD / "src"), str(SRC)]
30
  LINES = ["Hello", "My name is Sam", "", "What is my name?", "Bye"]
31
 
32
 
@@ -60,7 +60,7 @@ def main():
60
  s.bind(("127.0.0.1", 0))
61
  port = s.getsockname()[1]
62
  srv = subprocess.Popen([sys.executable, str(SRC / "sandbox.py"), "serve"], stderr=subprocess.DEVNULL,
63
- env={"PYTHONPATH": str(WORLD / "src"), "PYBOT_SANDBOX_TOKEN": "tok", "PORT": str(port)})
64
  try:
65
  for _ in range(300):
66
  try:
 
7
  main) goes through for both; a bad token or an unreachable sidecar is `busy`, and a refusal logs
8
  its HTTP status; a tar with `../`, a link, too many members or too many bytes is a 400; a timeout
9
  works.
10
+ Local path without `unshare` (blocked on many boxes). Needs requirements.txt and legion, 3.12+.
11
  """
12
  import base64
13
  import io
 
25
  import urllib.request
26
  from pathlib import Path
27
 
28
+ SRC = Path(__file__).resolve().parent.parent # world/
29
+ sys.path.insert(0, str(SRC))
30
  LINES = ["Hello", "My name is Sam", "", "What is my name?", "Bye"]
31
 
32
 
 
60
  s.bind(("127.0.0.1", 0))
61
  port = s.getsockname()[1]
62
  srv = subprocess.Popen([sys.executable, str(SRC / "sandbox.py"), "serve"], stderr=subprocess.DEVNULL,
63
+ env={"PYBOT_SANDBOX_TOKEN": "tok", "PORT": str(port)})
64
  try:
65
  for _ in range(300):
66
  try:
world/scripts/smoke-local.py CHANGED
@@ -6,7 +6,7 @@ defaults to the real Hub). Checks /healthz, the token (and a per-agent one), /ma
6
  one run_bot call.
7
  With --sidecar, the bot sandbox runs as a 2nd local process (`sandbox.py serve`, given only its
8
  token) and run_bot must succeed through it. Writes nothing outside a temp dir and makes no network
9
- calls beyond localhost. Needs the deps in requirements.txt and git.
10
  """
11
  import json
12
  import os
@@ -20,8 +20,8 @@ import urllib.error
20
  import urllib.request
21
  from pathlib import Path
22
 
23
- WORLD = SRC = Path(__file__).resolve().parent.parent # world/
24
- sys.path[:0] = [str(WORLD / "src"), str(SRC)]
25
  TOOLS = {"open_pr", "review_pr", "merge_pr", "close_pr", "list_prs", "get_pr", "record_verdict",
26
  "verdicts", "run_bot", "world_status"}
27
  TOKEN = "smoke-token"
@@ -66,11 +66,11 @@ def free_port():
66
 
67
 
68
  def start_sidecar(tmp):
69
- """sandbox.py serve with nothing but its token, PORT and the library path; returns (proc, log)."""
70
  port, log = free_port(), tmp / "sidecar.log"
71
  proc = subprocess.Popen([sys.executable, str(SRC / "sandbox.py"), "serve"], cwd=SRC,
72
  stderr=log.open("wb"), env={"PYBOT_SANDBOX_TOKEN": "sidecar-token",
73
- "PORT": str(port), "PYTHONPATH": str(WORLD / "src")})
74
  for _ in range(100):
75
  try:
76
  socket.create_connection(("127.0.0.1", port), timeout=1).close()
 
6
  one run_bot call.
7
  With --sidecar, the bot sandbox runs as a 2nd local process (`sandbox.py serve`, given only its
8
  token) and run_bot must succeed through it. Writes nothing outside a temp dir and makes no network
9
+ calls beyond localhost. Needs the deps in requirements.txt, legion (README) and git.
10
  """
11
  import json
12
  import os
 
20
  import urllib.request
21
  from pathlib import Path
22
 
23
+ SRC = Path(__file__).resolve().parent.parent # world/
24
+ sys.path.insert(0, str(SRC))
25
  TOOLS = {"open_pr", "review_pr", "merge_pr", "close_pr", "list_prs", "get_pr", "record_verdict",
26
  "verdicts", "run_bot", "world_status"}
27
  TOKEN = "smoke-token"
 
66
 
67
 
68
  def start_sidecar(tmp):
69
+ """sandbox.py serve with nothing but its token and PORT; returns (proc, log)."""
70
  port, log = free_port(), tmp / "sidecar.log"
71
  proc = subprocess.Popen([sys.executable, str(SRC / "sandbox.py"), "serve"], cwd=SRC,
72
  stderr=log.open("wb"), env={"PYBOT_SANDBOX_TOKEN": "sidecar-token",
73
+ "PORT": str(port)})
74
  for _ in range(100):
75
  try:
76
  socket.create_connection(("127.0.0.1", port), timeout=1).close()
world/source-lock.json DELETED
@@ -1,23 +0,0 @@
1
- {
2
- "legion_repo": "https://github.com/huggingface/legion",
3
- "legion_commit": "803873b114d5e04a3a01fea5e2e9084a03596fab",
4
- "files": {
5
- "src/legion/__init__.py": "2ca25e640556c716182ea3432836ca462f6ac4f9f048fee06532a6229217549c",
6
- "src/legion/buckets.py": "7cd3362e02cc56bf09db3b434413548c31c407302177def5162d9854a1d70a7f",
7
- "src/legion/isolation.py": "d2aee168504b93602d3fc4a50898539049a4cddcdec9f18364c664acd436d66f",
8
- "src/legion/models.py": "11c3fed632ab8d567fd202d487caf6e3eeb4ef2923adc465205bc3e25527f4b1",
9
- "src/legion/registry.py": "68257009cc7d026bb6ee06e24310b59b427f4f1a07e591ec2d8058e964edc270",
10
- "src/legion/tools/__init__.py": "c0daaebb255a07ea8032d8e00f9752075cabfd33382afdb8d4ddeede7a960dfc",
11
- "src/legion/tools/loader.py": "93f23ceb747fbb6c767f8a46cf2b1b562cafdf6e518290862106d547eb47a0d5",
12
- "src/legion/worker/__init__.py": "c4afc77bc9a814ffb811300094c36e0706c2a6a025703241c69688e3c5d2ff83",
13
- "src/legion/worker/sync.py": "bc2f6dab07d066a103f719174455b37bc784b8cd80794489da2038213fcbc4fa",
14
- "src/legion/world/__init__.py": "3fafd99d4e514f00ebf9b9f5ca2bfadd0fe30f83358bb7ef0bb33c601d5cb14f",
15
- "src/legion/world/admin.py": "aa83dfc00544cc368512896061d3953f1b52a77135639af2b32804eec7f4cda0",
16
- "src/legion/world/lanes.py": "1bd5ba820732c3c57299b51d91a78199d860cea8c0940e9efe0f24d8e90f26ad",
17
- "src/legion/world/protocol.py": "edde06d66578c82e08ace3bcdf113ac9217937a693c0449c7d727efdef9eb9ad",
18
- "src/legion/world/server.py": "896fac8edb9918ab2ccbfb6947d50ad4cca9ad4ce9990bde365a89c0df0a1afd",
19
- "src/legion/world/store.py": "3b4929798dc7710a94fa617d399a275577121457aade45784388e34d6df9a8f8",
20
- "src/legion/world/workspace.py": "a20903edc437c127d8752e1b9c0bac48a64e5caade51e9c5dc7f913d5d09a1f5"
21
- },
22
- "requirements.txt": "03b2bc4359a6929b8a0530546837002c9d5d9da811167257d0cf01f3d801128d"
23
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/src/legion/__init__.py DELETED
@@ -1,3 +0,0 @@
1
- """legion: host coding-harness agent swarms on Hugging Face Jobs."""
2
-
3
- __version__ = "0.0.1"
 
 
 
 
world/src/legion/buckets.py DELETED
@@ -1,35 +0,0 @@
1
- """Spec bucket IDs, resolved by the launcher; URLs may add legion's internal prefixes."""
2
-
3
- import re
4
- from typing import Annotated, Any
5
-
6
- from pydantic import AfterValidator
7
-
8
-
9
- def validate_bucket_id(value: str) -> str:
10
- """An optional `[namespace/]name`, without a URL or a path inside the bucket."""
11
- parts = value.split("/")
12
- if value and (len(parts) > 2 or any(
13
- not re.fullmatch(r"[\w.-]+", p, flags=re.ASCII) or p in (".", "..")
14
- for p in parts)):
15
- raise ValueError("bucket_id must be [namespace/]name, without hf://buckets/ or a prefix")
16
- return value
17
-
18
-
19
- BucketId = Annotated[str, AfterValidator(validate_bucket_id)]
20
-
21
-
22
- def resolve_bucket_id(bucket_id: str, namespace: str, api: Any) -> str:
23
- """Qualify a bare name using the explicit namespace, else HF_TOKEN's account."""
24
- validate_bucket_id(bucket_id)
25
- if not bucket_id or "/" in bucket_id:
26
- return bucket_id
27
- return f"{namespace or api.whoami()['name']}/{bucket_id}"
28
-
29
-
30
- def bucket_url(bucket_id: str) -> str:
31
- """A qualified spec ID as a Hub URL, ready for legion's checkpoint/agent prefixes."""
32
- validate_bucket_id(bucket_id)
33
- if "/" not in bucket_id:
34
- raise ValueError("bucket_id must be qualified by legion launch before use")
35
- return f"hf://buckets/{bucket_id}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/src/legion/isolation.py DELETED
@@ -1,386 +0,0 @@
1
- """Linux process isolation for harness and bot subprocesses. Setup errors abort; there is no unsandboxed fallback.
2
-
3
- unshare creates a user/PID/mount namespace and private procfs. The trusted setup
4
- then builds a small root with read-only runtimes and only the caller's data,
5
- chroots and drops capabilities before executing any agent-supplied code.
6
- """
7
- from __future__ import annotations
8
-
9
- import contextlib
10
- import ctypes
11
- import json
12
- import os
13
- import re
14
- import shutil
15
- import sys
16
- from collections.abc import Iterator
17
- from pathlib import Path
18
-
19
- MS_RDONLY, MS_NOSUID, MS_NODEV, MS_NOEXEC = 1, 2, 4, 8
20
- MS_REMOUNT, MS_BIND = 32, 4096
21
- MS_NOATIME, MS_NODIRATIME, MS_REC, MS_RELATIME, MS_STRICTATIME = 1024, 2048, 16384, 1 << 21, 1 << 24
22
- # statvfs flags of a mount that an unprivileged namespace cannot clear (they are locked) ->
23
- # the mount(2) flags a read-only remount must repeat.
24
- _LOCKED = ((os.ST_RDONLY, MS_RDONLY), (os.ST_NOSUID, MS_NOSUID), (os.ST_NODEV, MS_NODEV),
25
- (os.ST_NOEXEC, MS_NOEXEC), (os.ST_NOATIME, MS_NOATIME),
26
- (os.ST_NODIRATIME, MS_NODIRATIME), (os.ST_RELATIME, MS_RELATIME))
27
-
28
-
29
- DEV_NODES = ("/dev/null", "/dev/zero", "/dev/urandom", "/dev/random")
30
- # The chroot's root is a tmpfs: RAM that counts against the job's memory. Only mount points
31
- # and stray writes outside the bound dirs land there; the cap bounds each sandbox.
32
- TMPFS_SIZE_ENV, TMPFS_SIZE_DEFAULT = "LEGION_ISOLATION_TMPFS_SIZE", "256m"
33
- SANDBOX_TMP = "/tmp" # where `command(tmp=...)` binds the caller's disk-backed temp dir
34
- _SIZE = re.compile(r"[1-9][0-9]*[kmg]?", re.IGNORECASE)
35
- MOUNT_ATTR_RDONLY, AT_FDCWD, AT_RECURSIVE, SYS_MOUNT_SETATTR = 0x1, -100, 0x8000, 442
36
-
37
-
38
- class IsolationSetupError(OSError):
39
- """A sandbox setup step failed: names the step and path (never argv or the env)."""
40
-
41
-
42
- class IsolationMountError(IsolationSetupError):
43
- """A mount(2) call of the sandbox setup failed: names the target and flags, no argv."""
44
-
45
-
46
- @contextlib.contextmanager
47
- def _step(step: str, path) -> Iterator[None]:
48
- """Turn a plain OSError of one setup step into an IsolationSetupError naming it."""
49
- try:
50
- yield
51
- except IsolationSetupError:
52
- raise
53
- except OSError as e:
54
- raise IsolationSetupError(e.errno, f"isolation {step} failed: "
55
- f"{e.strerror or type(e).__name__}: path={path}") from None
56
-
57
-
58
- def enabled() -> bool:
59
- return os.environ.get("LEGION_PROCESS_ISOLATION") == "1"
60
-
61
-
62
- def _libc():
63
- return ctypes.CDLL(None, use_errno=True)
64
-
65
-
66
- def protect_supervisor() -> None:
67
- """Deny same-UID ptrace and /proc/<pid>/{environ,mem,root} on worker/world."""
68
- if not sys.platform.startswith("linux") or _libc().prctl(4, 0, 0, 0, 0) != 0:
69
- raise RuntimeError("PR_SET_DUMPABLE=0 is required for process isolation")
70
-
71
-
72
- def tmpfs_size(env=os.environ) -> str:
73
- """The size cap of a sandbox's tmpfs root: $LEGION_ISOLATION_TMPFS_SIZE (bytes, or with a
74
- k/m/g suffix; never unlimited), else 256m. An unusable value falls back to the default."""
75
- value = (env.get(TMPFS_SIZE_ENV) or "").strip()
76
- if _SIZE.fullmatch(value):
77
- return value.lower()
78
- if value:
79
- print(f"isolation: ignoring {TMPFS_SIZE_ENV}={value!r}; using {TMPFS_SIZE_DEFAULT}",
80
- file=sys.stderr)
81
- return TMPFS_SIZE_DEFAULT
82
-
83
-
84
- def runtime_paths(command: list[str], *, python_only=False) -> list[str]:
85
- paths = ["/usr", "/bin", "/sbin", "/lib", "/lib64", sys.prefix, sys.base_prefix]
86
- # Config files needed by Python, Node, TLS, DNS and git; never a host home or the shared-disk root.
87
- paths += ["/etc/ssl", "/etc/alternatives", "/etc/hosts", "/etc/resolv.conf",
88
- "/etc/nsswitch.conf", "/etc/passwd", "/etc/group", "/etc/localtime"]
89
- if not python_only:
90
- paths.append(str(Path(__file__).resolve().parents[2])) # editable legion install
91
- for binary in (command[0], "node"):
92
- found = shutil.which(binary)
93
- if not found:
94
- continue
95
- target = Path(found).resolve()
96
- modules = next((p for p in target.parents if p.name == "node_modules"), None)
97
- paths.append(str(modules or target.parent))
98
- return sorted({str(Path(p).absolute()) for p in paths if Path(p).exists()}, key=lambda p: (len(p), p))
99
-
100
-
101
- def symlink_chain(path: str | Path) -> tuple[list[tuple[str, str]], str]:
102
- """Resolve `path` one hop at a time: every symlink met on the way (as `(link, target)`,
103
- the target exactly as stored) and the final real path. Components that do not exist are
104
- kept as they are. A loop or more than 40 hops raises."""
105
- links: list[tuple[str, str]] = []
106
- pending = list(Path(os.path.abspath(path)).parts[1:])
107
- current = Path("/")
108
- while pending:
109
- name = pending.pop(0)
110
- if name in ("", "."):
111
- continue
112
- if name == "..":
113
- current = current.parent
114
- continue
115
- candidate = current / name
116
- if not candidate.is_symlink():
117
- current = candidate
118
- continue
119
- target = os.readlink(candidate)
120
- links.append((str(candidate), target))
121
- if len(links) > 40:
122
- raise RuntimeError(f"isolation: too many symlinks resolving {path}")
123
- if os.path.isabs(target):
124
- current = Path("/")
125
- pending = list(Path(target).parts[1:]) + pending
126
- else:
127
- pending = list(Path(target).parts) + pending
128
- return links, str(current)
129
-
130
-
131
- def _within(path: str, roots: list[str]) -> bool:
132
- return any(path == r or path.startswith(r.rstrip("/") + "/") for r in roots)
133
-
134
-
135
- def plan(argv: list[str], *, cwd: Path, readonly=(), writable=(), python_only=False,
136
- private_dirs=(), tmp=None) -> dict:
137
- """Mounts and symlinks for the chroot. Every path is bound at its real location, and each
138
- symlink hop on the way to it (and to the interpreter, the command and node) is recreated
139
- inside, so the original spelling resolves there too (a uv venv's python links through
140
- `cpython-3.12-...` to `cpython-3.12.14-...`)."""
141
- links: dict[str, str] = {}
142
-
143
- def real(p) -> str:
144
- hops, final = symlink_chain(p)
145
- links.update(hops)
146
- return final
147
-
148
- ro = [real(p) for p in runtime_paths(argv, python_only=python_only) + [str(p) for p in readonly]]
149
- rw = [real(p) for p in writable]
150
- probes = [sys.executable, argv[0] if os.path.isabs(argv[0]) else shutil.which(argv[0])]
151
- if not python_only:
152
- probes.append(shutil.which("node"))
153
- for probe in filter(None, probes):
154
- final = real(probe)
155
- if not _within(final, ro + rw):
156
- raise RuntimeError(f"isolation cannot represent {probe}: it resolves to {final}, "
157
- "outside every mounted path")
158
- real(cwd)
159
- def ordered(paths: list[str]) -> list[str]: # parents before nested mounts
160
- return sorted(dict.fromkeys(paths), key=lambda p: (len(p), p))
161
-
162
- # `tmp` (a disk-backed dir) is bound over the sandbox's /tmp, so files written there do not
163
- # fill the tmpfs root. Not when a planned path lives under /tmp itself (a test's tmp_path):
164
- # the bind would hide it, and /tmp stays on the size-capped tmpfs.
165
- tmp_dir = real(tmp) if tmp is not None else None
166
- if tmp_dir is not None and any(_within(p, [SANDBOX_TMP]) for p in [*ro, *rw, *links, real(cwd)]):
167
- tmp_dir = None
168
- return {"readonly": ordered(ro), "writable": list(dict.fromkeys(rw)),
169
- "symlinks": sorted(links.items(), key=lambda kv: (len(kv[0]), kv[0])),
170
- "private_dirs": [str(Path(p).absolute()) for p in private_dirs], "tmp": tmp_dir}
171
-
172
-
173
- def command(argv: list[str], root: Path, *, cwd: Path, readonly=(), writable=(), network=False,
174
- python_only=False, private_dirs=(), tmp=None) -> list[str]:
175
- """Build a trusted invocation. Only explicitly mounted paths survive the chroot. `tmp`: a
176
- disk-backed directory bound writable at the sandbox's /tmp (see `plan`)."""
177
- unshare = shutil.which("unshare")
178
- if not unshare:
179
- raise RuntimeError("unshare is required for process isolation")
180
- config = {"root": str(root.absolute()), "cwd": str(cwd.absolute()),
181
- "readonly_root": not network, "tmpfs_size": tmpfs_size(),
182
- **plan(argv, cwd=cwd, readonly=readonly, writable=writable, python_only=python_only,
183
- private_dirs=private_dirs, tmp=tmp)}
184
- # Slurm sends USR1 to every process on reclaim. Only worker/world supervisors
185
- # handle it; an unshare wrapper must survive long enough for their bounded drain.
186
- return ["/bin/sh", "-c", 'trap "" USR1; exec "$@"', "legion-isolate",
187
- unshare, "--user", "--map-root-user", "--pid", "--fork", "--kill-child=SIGKILL",
188
- "--mount", "--propagation", "private", "--mount-proc", *(["--net"] if not network else []), "--",
189
- sys.executable, "-I", str(Path(__file__).resolve()), json.dumps(config), *argv]
190
-
191
-
192
- def _mount(source, target, kind=None, flags=0, data=None):
193
- def encoded(value):
194
- return os.fsencode(value) if value is not None else None
195
- libc = _libc()
196
- libc.mount.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p,
197
- ctypes.c_ulong, ctypes.c_char_p]
198
- if libc.mount(encoded(source), encoded(target), encoded(kind), flags, encoded(data)) != 0:
199
- errno = ctypes.get_errno()
200
- raise IsolationMountError(errno, f"isolation mount failed: {os.strerror(errno)}: "
201
- f"source={source} target={target} type={kind} "
202
- f"flags={flags:#x}")
203
-
204
-
205
- def readonly_remount_flags(target) -> int:
206
- """MS_REMOUNT|MS_BIND|MS_RDONLY plus nosuid/nodev, and every locked flag the bound mount
207
- already has (statvfs of the bind target): a user namespace cannot clear them, and
208
- leaving them out fails with EPERM. No atime flag on the source means strictatime."""
209
- inherited = os.statvfs(target).f_flag
210
- flags = MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV
211
- for flag, mount_flag in _LOCKED:
212
- if inherited & flag:
213
- flags |= mount_flag
214
- if not inherited & (os.ST_NOATIME | os.ST_RELATIME):
215
- flags |= MS_STRICTATIME
216
- return flags
217
-
218
-
219
- def _readonly_recursive(target) -> bool:
220
- """mount_setattr(AT_RECURSIVE, MOUNT_ATTR_RDONLY): make every submount of a recursive
221
- bind read-only too (a remount only changes the top one). False if the kernel lacks it
222
- (before 5.12); the mountinfo check still refuses a writable submount."""
223
- libc = _libc()
224
- attr = (ctypes.c_uint64 * 4)(MOUNT_ATTR_RDONLY, 0, 0, 0)
225
- libc.syscall.restype = ctypes.c_long
226
- rc = libc.syscall(ctypes.c_long(SYS_MOUNT_SETATTR), ctypes.c_int(AT_FDCWD),
227
- ctypes.c_char_p(os.fsencode(target)), ctypes.c_uint(AT_RECURSIVE),
228
- ctypes.byref(attr), ctypes.c_size_t(ctypes.sizeof(attr)))
229
- # Any failure (ENOSYS before 5.12, EPERM on a locked mount): the mountinfo check that
230
- # follows the binds still refuses a writable submount.
231
- return rc == 0
232
-
233
-
234
- def _unescape(field: str) -> str:
235
- return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), field)
236
-
237
-
238
- def parse_mountinfo(text: str) -> list[tuple[str, set[str]]]:
239
- """(mount point, per-mount options) of each /proc/self/mountinfo line."""
240
- out = []
241
- for line in text.splitlines():
242
- fields = line.split()
243
- if len(fields) >= 6:
244
- out.append((_unescape(fields[4]), set(fields[5].split(","))))
245
- return out
246
-
247
-
248
- def check_mounts(mounts: list[tuple[str, set[str]]], root: str, readonly: list[str],
249
- writable: list[str] = (), extra: list[str] = ()) -> None:
250
- """Fail closed after the binds. Every mount under `root` must be a planned target (or
251
- `extra`: proc, the /dev nodes), or a submount a recursive bind of one brought along
252
- (e.g. a container's zoneinfo file bound over /usr's); and every mount at or under a
253
- read-only target, outside a writable one, must be `ro`."""
254
- def under(path: str, roots) -> bool:
255
- return any(path == r or path.startswith(r.rstrip("/") + "/") for r in roots)
256
-
257
- planned = [*readonly, *writable, *extra]
258
- for point, opts in mounts:
259
- if point == root or not under(point, [root]):
260
- continue
261
- if not under(point, planned):
262
- raise IsolationMountError(1, f"isolation: unexpected mount {point} in the sandbox root")
263
- if under(point, readonly) and not under(point, writable) and "ro" not in opts:
264
- raise IsolationMountError(30, f"isolation: {point} is mounted writable under a "
265
- "read-only path")
266
-
267
-
268
- def _bind(root: Path, source: str, *, readonly: bool, target: Path | None = None):
269
- """Bind `source` at its own path under `root` (or at `target`, a path under `root`)."""
270
- path = Path(source)
271
- if not path.exists():
272
- raise IsolationSetupError(2, f"isolation bind failed: required path is missing: path={source}")
273
- target = target if target is not None else root / path.relative_to("/")
274
- # Create the mount point only when missing: it may already exist on a read-only bind
275
- # (/etc/localtime -> /usr/share/zoneinfo/... under the /usr bind), where touch()'s utime
276
- # fails with EROFS.
277
- with _step("mount point creation", target):
278
- target.parent.mkdir(parents=True, exist_ok=True)
279
- if path.is_dir():
280
- if not target.is_dir():
281
- target.mkdir()
282
- elif not target.exists():
283
- target.touch()
284
- # Recursive: a user namespace refuses (EINVAL) a non-recursive bind of a tree that has
285
- # locked submounts, since it would uncover what they hide. Only explicitly listed paths
286
- # are bound, so a submount comes in only under a path that was asked for.
287
- _mount(source, target, flags=MS_BIND | MS_REC)
288
- if readonly:
289
- # Step two: read-only only works as a remount of the bind, with the locked flags;
290
- # then the submounts the recursive bind brought along, where the kernel can.
291
- _mount(None, target, flags=readonly_remount_flags(target))
292
- _readonly_recursive(target)
293
-
294
-
295
- def _drop_privileges():
296
- libc = _libc()
297
- # NOROOT + locked: exec as namespace uid 0 must never regain capabilities.
298
- if libc.prctl(28, 3, 0, 0, 0) or libc.prctl(38, 1, 0, 0, 0):
299
- raise RuntimeError("cannot lock sandbox privileges")
300
- # All currently defined capabilities fit below 64. EINVAL marks unsupported bits.
301
- for cap in range(64):
302
- if libc.prctl(24, cap, 0, 0, 0) != 0 and ctypes.get_errno() != 22:
303
- raise RuntimeError("cannot drop sandbox capability bounding set")
304
- class Header(ctypes.Structure):
305
- _fields_ = [("version", ctypes.c_uint32), ("pid", ctypes.c_int)]
306
- class Data(ctypes.Structure):
307
- _fields_ = [("effective", ctypes.c_uint32), ("permitted", ctypes.c_uint32),
308
- ("inheritable", ctypes.c_uint32)]
309
- if libc.capset(ctypes.byref(Header(0x20080522, 0)), (Data * 2)()) != 0:
310
- raise RuntimeError("cannot clear sandbox capabilities")
311
-
312
-
313
- OOM_SCORE_ADJ = 800 # sandboxed processes die before the worker (which keeps 0) on an OOM kill
314
-
315
-
316
- def set_oom_score_adj(value: int = OOM_SCORE_ADJ, path: str = "/proc/self/oom_score_adj") -> bool:
317
- """Raise this process's OOM score (inherited by what it execs). Raising needs no
318
- privilege; False when /proc refuses it."""
319
- try:
320
- Path(path).write_text(str(value))
321
- return True
322
- except OSError:
323
- return False
324
-
325
-
326
- def _enter(config, argv):
327
- # Never share a process group with a supervisor outside the PID namespace.
328
- if os.getpgrp() != os.getpid():
329
- os.setsid()
330
- set_oom_score_adj()
331
- root = Path(config["root"])
332
- with _step("root creation", root):
333
- root.mkdir(parents=True, exist_ok=True)
334
- size = config.get("tmpfs_size") or TMPFS_SIZE_DEFAULT
335
- if not _SIZE.fullmatch(size):
336
- raise IsolationSetupError(22, f"isolation tmpfs size is invalid: path={root}")
337
- _mount("tmpfs", root, "tmpfs", MS_NOSUID | MS_NODEV, f"mode=755,size={size}")
338
- for path in config["readonly"]:
339
- _bind(root, path, readonly=True)
340
- for path in config["writable"]:
341
- _bind(root, path, readonly=False)
342
- for link, target in config.get("symlinks", ()):
343
- inside = root / Path(link).relative_to("/")
344
- if os.path.lexists(inside):
345
- continue # already visible through a bind mount
346
- with _step("symlink creation", inside):
347
- inside.parent.mkdir(parents=True, exist_ok=True)
348
- inside.symlink_to(target)
349
- for path in config["private_dirs"]:
350
- with _step("private directory creation", path):
351
- (root / Path(path).relative_to("/")).mkdir(parents=True, exist_ok=True)
352
- for path in ("tmp", "proc", "dev"):
353
- with _step("directory creation", root / path):
354
- (root / path).mkdir(exist_ok=True)
355
- if config.get("tmp"): # the sandbox's /tmp on the caller's disk-backed dir, not the tmpfs
356
- _bind(root, config["tmp"], readonly=False, target=root / SANDBOX_TMP.lstrip("/"))
357
- for path in DEV_NODES:
358
- _bind(root, path, readonly=False)
359
- with _step("symlink creation", root / "dev/fd"):
360
- (root / "dev/fd").symlink_to("/proc/self/fd")
361
- _mount("proc", root / "proc", "proc", MS_NOSUID | MS_NODEV | MS_NOEXEC)
362
- inside = lambda p: os.path.realpath(root / Path(p).relative_to("/"))
363
- check_mounts(parse_mountinfo(Path("/proc/self/mountinfo").read_text()), os.path.realpath(root),
364
- [inside(p) for p in config["readonly"]],
365
- [inside(p) for p in (*config["writable"], *([SANDBOX_TMP] if config.get("tmp") else []))],
366
- [inside(p) for p in ("/proc", *DEV_NODES)])
367
- if config["readonly_root"]:
368
- _mount(None, root, flags=MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV)
369
- with _step("chroot", root):
370
- os.chroot(root)
371
- with _step("chdir", config["cwd"]):
372
- os.chdir(config["cwd"])
373
- _drop_privileges()
374
- os.execvpe(argv[0], argv, dict(os.environ))
375
-
376
-
377
- if __name__ == "__main__":
378
- try:
379
- _enter(json.loads(sys.argv[1]), sys.argv[2:])
380
- except IsolationSetupError as e: # step, path and flags only, never argv or the env
381
- print(f"process isolation failed during setup: {e.strerror}", file=sys.stderr)
382
- raise SystemExit(125) from None
383
- except Exception: # noqa: BLE001 - fail closed, without leaking arguments or paths
384
- # Paths, argv and errors could contain credentials. Fail closed without their values.
385
- print("process isolation failed during setup", file=sys.stderr)
386
- raise SystemExit(125) from None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/src/legion/models.py DELETED
The diff for this file is too large to render. See raw diff
 
world/src/legion/registry.py DELETED
@@ -1,45 +0,0 @@
1
- """The harness and compute-backend registries: adding either is one module plus one entry here
2
- (docs/design.md, "Adding a harness or a compute backend"). The spec loader, controller, worker
3
- and CLI all read these entries. Code is named by import path ("module:function") and imported
4
- only when used, so the controller never imports worker-only dependencies."""
5
-
6
- from __future__ import annotations
7
-
8
- from dataclasses import dataclass
9
- from importlib import import_module
10
- from typing import Any
11
-
12
-
13
- @dataclass(frozen=True)
14
- class HarnessEntry:
15
- adapter: str # "module:function"; function(workdir, agent name, TypeSpec) -> HarnessAdapter
16
- # (harbor's also takes `host=`, the worker's HarborHost)
17
- api: str # the wire API it speaks to its inference endpoints (preflight probes this one)
18
-
19
-
20
- HARNESSES: dict[str, HarnessEntry] = {
21
- # one Harbor Trial per agent on the upstream Harbor task path (legion.harbor). Harbor installs Pi
22
- # (legion.harbor.config.PI_VERSION) in the task's container and the Trial delivers the
23
- # instructions
24
- "harbor": HarnessEntry("legion.worker.adapters.harbor:make_adapter", "chat_completions"),
25
- }
26
-
27
- # `compute.kind` / LEGION_COMPUTE -> "module:function"; function(env, deployment, data_dir) ->
28
- # JobsClient. The function also rejects a controller setup the backend cannot run in.
29
- COMPUTE: dict[str, str] = {
30
- "hf-jobs": "legion.controller.jobs:hub_jobs_client",
31
- "local": "legion.controller.local:local_jobs_client", # docs/local.md
32
- "slurm": "legion.controller.slurm:slurm_jobs_client", # docs/slurm.md
33
- }
34
-
35
- # Inference servers legion starts itself: the `inference` block's key -> "module:function";
36
- # function(env) -> a Starter (legion.controller.servers), which starts a model's servers (or
37
- # reattaches to the running ones), checks them until they answer, and stops them
38
- SERVERS: dict[str, str] = {
39
- "hf_jobs": "legion.controller.hf_jobs_servers:hf_jobs_servers", # docs/open-models.md
40
- }
41
-
42
-
43
- def load(path: str) -> Any:
44
- module, _, name = path.partition(":")
45
- return getattr(import_module(module), name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/src/legion/tools/__init__.py DELETED
@@ -1,55 +0,0 @@
1
- """Runtime tools folder: plain Python functions next to the spec become agent tools.
2
-
3
- What a tool module imports from here: `Context` (the optional run-context argument, never shown
4
- to the model), `ToolError` (raise it to hand the model a clean error message) and `readonly`
5
- (a decorator: the tool changes nothing; informational). The loader,
6
- schema builder, runner and bundle code live in the submodules; this module stays stdlib-only so
7
- the per-call subprocess starts fast.
8
- """
9
-
10
- from __future__ import annotations
11
-
12
- from dataclasses import dataclass, field
13
- from pathlib import Path
14
-
15
- READONLY_ATTR = "__legion_readonly__"
16
-
17
-
18
- @dataclass
19
- class Context:
20
- """What a tool learns about the call. Declare a parameter named `ctx` (or annotated
21
- `Context`) to receive it; the model never sees it.
22
-
23
- - agent, type, swarm: who is calling (the swarm name is the run id).
24
- - workdir: the agent's working directory (also the call's cwd).
25
- - data_dir: a directory for tool state, shared by the agents of this worker, kept across
26
- tools versions, not synced to the bucket.
27
- - tools_dir: the extracted tools folder of this version; tools_version: its content hash.
28
- - env: the agent's environment (what its `bash` sees), also the call's process environment.
29
- """
30
-
31
- agent: str
32
- type: str
33
- swarm: str
34
- workdir: Path
35
- data_dir: Path
36
- tools_dir: Path
37
- tools_version: str
38
- env: dict[str, str] = field(default_factory=dict)
39
-
40
-
41
- Ctx = Context
42
-
43
-
44
- class ToolError(Exception):
45
- """Raise from a tool to return `{"error": message}` to the model (no exception type prefix)."""
46
-
47
-
48
- def readonly[F](fn: F) -> F:
49
- """Mark a tool as read-only (`readonly: true` in the manifest): it changes no state.
50
- Informational: nothing in legion acts on it."""
51
- setattr(fn, READONLY_ATTR, True)
52
- return fn
53
-
54
-
55
- __all__ = ["Context", "Ctx", "ToolError", "readonly"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/src/legion/tools/loader.py DELETED
@@ -1,385 +0,0 @@
1
- """Tools folder -> tool definitions.
2
-
3
- Every `*.py` file at the top of the folder whose name does not start with `_` is a tool module.
4
- Every function defined in it (not imported) whose name does not start with `_` and that has a
5
- docstring is a tool: name = function name, description = the docstring's first paragraph,
6
- parameters = a JSON schema built from the type hints (descriptions from an `Args:` section).
7
- A parameter named `ctx`, or annotated `legion.tools.Context`, is injected at call time and
8
- never shown to the model.
9
-
10
- `load_dir` imports the modules in this process; `describe` runs it in a fresh `python -I`
11
- subprocess (what `legion launch` uses), so a module's side effects, crashes and hangs stay
12
- there. `python -m legion.tools.loader <dir>` prints the manifest as JSON.
13
- """
14
-
15
- from __future__ import annotations
16
-
17
- import importlib
18
- import inspect
19
- import json
20
- import re
21
- import subprocess
22
- import sys
23
- import types
24
- import typing
25
- from dataclasses import asdict, dataclass, field
26
- from pathlib import Path
27
- from typing import Any
28
-
29
- from legion.tools import READONLY_ATTR, Context
30
-
31
- NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
32
- CTX_NAME = "ctx"
33
- DESCRIBE_TIMEOUT_S = 60.0
34
-
35
-
36
- class ToolsError(ValueError):
37
- """The tools folder cannot be loaded; the message says which file and why."""
38
-
39
-
40
- @dataclass
41
- class ToolDef:
42
- name: str
43
- description: str
44
- parameters: dict[str, Any] # JSON schema, type object
45
- module: str # module name inside the folder
46
- function: str
47
- ctx: str | None = None # the parameter that receives the Context, if any
48
- is_async: bool = False
49
- # A built-in served by the worker itself, not the folder (`comms:post`, docs/comms.md).
50
- builtin: str | None = None
51
- # Changes nothing (`@legion.tools.readonly`; informational). In the manifest only when true.
52
- readonly: bool = False
53
-
54
- def openai(self) -> dict[str, Any]:
55
- """The Chat Completions function tool."""
56
- return {"type": "function", "function": {
57
- "name": self.name, "description": self.description, "parameters": self.parameters}}
58
-
59
-
60
- @dataclass
61
- class Manifest:
62
- tools: list[ToolDef] = field(default_factory=list)
63
-
64
- def names(self) -> list[str]:
65
- return [t.name for t in self.tools]
66
-
67
- def get(self, name: str) -> ToolDef | None:
68
- return next((t for t in self.tools if t.name == name), None)
69
-
70
- def to_json(self) -> dict[str, Any]:
71
- # `readonly` only when set, so a folder without it keeps its manifest (and version)
72
- return {"tools": [{k: v for k, v in asdict(t).items() if k != "readonly" or v}
73
- for t in self.tools]}
74
-
75
- @classmethod
76
- def from_json(cls, data: dict[str, Any]) -> Manifest:
77
- return cls([ToolDef(**t) for t in data.get("tools") or []])
78
-
79
-
80
- # --------------------------------------------------------------------------- schema
81
-
82
-
83
- def _first_paragraph(doc: str) -> str:
84
- para: list[str] = []
85
- for line in doc.strip().splitlines():
86
- if not line.strip():
87
- break
88
- para.append(line.strip())
89
- return " ".join(para)
90
-
91
-
92
- _ARGS_HEAD = re.compile(r"^\s*(Args|Arguments|Parameters|Params)\s*:\s*$")
93
- _ARG_LINE = re.compile(r"^\s*\**([A-Za-z_][A-Za-z0-9_]*)\**\s*(\([^)]*\))?\s*:\s*(.*)$")
94
-
95
-
96
- def arg_docs(doc: str) -> dict[str, str]:
97
- """Per-parameter descriptions from a Google-style `Args:` section (continuation lines are
98
- joined; the section ends at a blank line or a less-indented line)."""
99
- out: dict[str, str] = {}
100
- lines = doc.splitlines()
101
- i = next((k for k, line in enumerate(lines) if _ARGS_HEAD.match(line)), None)
102
- if i is None:
103
- return out
104
- head_indent = len(lines[i]) - len(lines[i].lstrip())
105
- current: str | None = None
106
- item_indent = None
107
- for line in lines[i + 1:]:
108
- if not line.strip():
109
- break
110
- indent = len(line) - len(line.lstrip())
111
- if indent <= head_indent:
112
- break
113
- m = _ARG_LINE.match(line)
114
- if m and (item_indent is None or indent <= item_indent):
115
- item_indent = indent
116
- current = m.group(1)
117
- out[current] = m.group(3).strip()
118
- elif current is not None:
119
- out[current] = (out[current] + " " + line.strip()).strip()
120
- return out
121
-
122
-
123
- def _is_context(hint: Any) -> bool:
124
- return hint is Context or (isinstance(hint, type) and issubclass(hint, Context))
125
-
126
-
127
- def nullable(schema: dict[str, Any]) -> dict[str, Any]:
128
- """`schema` that also accepts null (an `Any` schema already does)."""
129
- out = dict(schema)
130
- t = out.get("type")
131
- if isinstance(t, str):
132
- out["type"] = [t, "null"]
133
- elif isinstance(t, list) and "null" not in t:
134
- out["type"] = [*t, "null"]
135
- if "enum" in out and None not in out["enum"]:
136
- out["enum"] = [*out["enum"], None]
137
- return out
138
-
139
-
140
- def type_schema(hint: Any, where: str) -> tuple[dict[str, Any], bool]:
141
- """(JSON schema, nullable) for a type hint. `X | None` / `Optional[X]` is nullable: the
142
- schema accepts null too (`type: [X, "null"]`, None added to an enum). Nullable is not
143
- omittable: only a default makes a parameter optional."""
144
- if hint is inspect.Parameter.empty:
145
- raise ToolsError(f"{where}: needs a type annotation (str, int, float, bool, list[...], dict)")
146
- origin = typing.get_origin(hint)
147
- args = typing.get_args(hint)
148
- if origin in (typing.Union, types.UnionType):
149
- rest = [a for a in args if a is not type(None)]
150
- if len(rest) != 1 or len(rest) == len(args):
151
- raise ToolsError(f"{where}: unions other than `X | None` are not supported")
152
- return nullable(type_schema(rest[0], where)[0]), True
153
- if hint is typing.Any:
154
- return {}, False
155
- if hint is str:
156
- return {"type": "string"}, False
157
- if hint is bool:
158
- return {"type": "boolean"}, False
159
- if hint is int:
160
- return {"type": "integer"}, False
161
- if hint is float:
162
- return {"type": "number"}, False
163
- if hint in (list, typing.List) or origin is list: # noqa: UP006
164
- items = type_schema(args[0], where)[0] if args else {}
165
- return {"type": "array", "items": items}, False
166
- if hint in (dict, typing.Dict) or origin is dict: # noqa: UP006
167
- return {"type": "object"}, False
168
- if origin is typing.Literal:
169
- kinds = {type(a) for a in args}
170
- schema: dict[str, Any] = {"enum": list(args)}
171
- if kinds == {str}:
172
- schema["type"] = "string"
173
- elif kinds == {int}:
174
- schema["type"] = "integer"
175
- return schema, False
176
- raise ToolsError(f"{where}: unsupported type {hint!r}; use str, int, float, bool, "
177
- "list[...], dict, Literal[...] or X | None")
178
-
179
-
180
- def tool_def(fn: Any, module: str) -> ToolDef:
181
- """The ToolDef of one function (raises ToolsError naming module.function)."""
182
- name = fn.__name__
183
- where = f"{module}.{name}"
184
- if not NAME_RE.match(name):
185
- raise ToolsError(f"{where}: tool names must match {NAME_RE.pattern}")
186
- doc = inspect.getdoc(fn) or ""
187
- try:
188
- hints = typing.get_type_hints(fn)
189
- except Exception as e:
190
- raise ToolsError(f"{where}: cannot resolve type hints: {type(e).__name__}: {e}") from e
191
- sig = inspect.signature(fn)
192
- docs = arg_docs(doc)
193
- props: dict[str, Any] = {}
194
- required: list[str] = []
195
- ctx = None
196
- for p in sig.parameters.values():
197
- hint = hints.get(p.name, p.annotation)
198
- if p.name == CTX_NAME or _is_context(hint):
199
- ctx = p.name
200
- continue
201
- if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD):
202
- raise ToolsError(f"{where}: *args / **kwargs are not supported; name every parameter")
203
- if p.kind is p.POSITIONAL_ONLY:
204
- raise ToolsError(f"{where}: positional-only parameters are not supported")
205
- schema, _ = type_schema(hint, f"{where}({p.name})")
206
- schema = dict(schema)
207
- if docs.get(p.name):
208
- schema["description"] = docs[p.name]
209
- if p.default is not p.empty:
210
- try:
211
- json.dumps(p.default)
212
- if p.default is not None:
213
- schema["default"] = p.default
214
- except (TypeError, ValueError):
215
- pass
216
- else: # no default: required, nullable or not (the call has no value to fall back on)
217
- required.append(p.name)
218
- props[p.name] = schema
219
- params: dict[str, Any] = {"type": "object", "properties": props, "additionalProperties": False}
220
- if required:
221
- params["required"] = required
222
- return ToolDef(name=name, description=_first_paragraph(doc), parameters=params, module=module,
223
- function=name, ctx=ctx, is_async=inspect.iscoroutinefunction(fn),
224
- readonly=getattr(fn, READONLY_ATTR, False) is True)
225
-
226
-
227
- def tool_modules(folder: Path) -> list[Path]:
228
- return sorted(p for p in folder.glob("*.py") if not p.name.startswith("_"))
229
-
230
-
231
- _LOADED: set[str] = set()
232
-
233
-
234
- def load_dir(folder: str | Path) -> Manifest:
235
- """Import every tool module of `folder` (put on sys.path first, so modules may import their
236
- `_helpers`) and collect the tools. Raises ToolsError on a bad module or a duplicate name."""
237
- folder = Path(folder).resolve()
238
- if not folder.is_dir():
239
- raise ToolsError(f"tools folder {folder} does not exist")
240
- sys.path.insert(0, str(folder))
241
- for name in _LOADED & set(sys.modules): # an earlier folder's modules (same process)
242
- del sys.modules[name]
243
- importlib.invalidate_caches()
244
- tools: dict[str, ToolDef] = {}
245
- for path in tool_modules(folder):
246
- mod_name = path.stem
247
- _LOADED.add(mod_name)
248
- try:
249
- mod = importlib.import_module(mod_name)
250
- except SyntaxError as e:
251
- raise ToolsError(f"{path.name}: syntax error line {e.lineno}: {e.msg}") from e
252
- except Exception as e:
253
- raise ToolsError(f"{path.name}: import failed: {type(e).__name__}: {e}") from e
254
- if Path(getattr(mod, "__file__", "") or "").resolve() != path:
255
- raise ToolsError(f"{path.name}: module name {mod_name!r} is shadowed by "
256
- f"{getattr(mod, '__file__', None) or 'a built-in module'}; rename the file")
257
- for attr, fn in vars(mod).items():
258
- if attr.startswith("_") or not inspect.isfunction(fn) or fn.__module__ != mod.__name__:
259
- continue
260
- if not inspect.getdoc(fn):
261
- continue # no docstring: a helper, not a tool
262
- t = tool_def(fn, mod_name)
263
- if t.name in tools:
264
- raise ToolsError(f"{path.name}: tool {t.name!r} is also defined in "
265
- f"{tools[t.name].module}.py")
266
- tools[t.name] = t
267
- return Manifest(list(tools.values()))
268
-
269
-
270
- def describe(folder: str | Path, *, python: str | None = None,
271
- timeout: float = DESCRIBE_TIMEOUT_S) -> Manifest:
272
- """`load_dir` in a fresh `python -I` process (cwd: the folder's parent). Raises ToolsError."""
273
- folder = Path(folder).resolve()
274
- if not folder.is_dir():
275
- raise ToolsError(f"tools folder {folder} does not exist")
276
- cmd = [python or sys.executable, "-I", "-B", "-m", "legion.tools.loader", str(folder)]
277
- try:
278
- p = subprocess.run(cmd, check=False, capture_output=True, text=True, timeout=timeout,
279
- cwd=str(folder.parent), stdin=subprocess.DEVNULL)
280
- except subprocess.TimeoutExpired as e:
281
- raise ToolsError(f"loading {folder} took over {timeout:g}s (a module blocks at import?)") from e
282
- try:
283
- out = json.loads(p.stdout.strip().splitlines()[-1]) if p.stdout.strip() else None
284
- except ValueError:
285
- out = None
286
- if not isinstance(out, dict):
287
- tail = (p.stderr or p.stdout or "").strip()[-800:]
288
- raise ToolsError(f"loading {folder} failed (exit {p.returncode}): {tail}")
289
- if "error" in out:
290
- raise ToolsError(out["error"])
291
- return Manifest.from_json(out)
292
-
293
-
294
- def select(manifest: Manifest, wanted: list[str] | str | None, *, where: str = "tools") -> list[ToolDef]:
295
- """The tools a type gets: `all`, a list of names (unknown names raise ToolsError), or none."""
296
- if wanted is None:
297
- return []
298
- if wanted == "all":
299
- return list(manifest.tools)
300
- if isinstance(wanted, str):
301
- raise ToolsError(f"{where}: use a list of tool names or `all`, not {wanted!r}")
302
- unknown = [n for n in wanted if manifest.get(n) is None]
303
- if unknown:
304
- known = ", ".join(manifest.names()) or "none"
305
- raise ToolsError(f"{where}: unknown tool(s) {', '.join(unknown)}; the tools folder has: {known}")
306
- return [t for n in dict.fromkeys(wanted) if (t := manifest.get(n)) is not None]
307
-
308
-
309
- def _main(argv: list[str]) -> int:
310
- if len(argv) != 1:
311
- print(json.dumps({"error": "usage: python -m legion.tools.loader <tools dir>"}))
312
- return 2
313
- import contextlib
314
- import io
315
-
316
- sink = io.StringIO() # prints at import time must not corrupt the JSON line
317
- try:
318
- with contextlib.redirect_stdout(sink):
319
- manifest = load_dir(argv[0])
320
- out: dict[str, Any] = manifest.to_json()
321
- except ToolsError as e:
322
- out = {"error": str(e)}
323
- print(json.dumps(out))
324
- return 0
325
-
326
-
327
- if __name__ == "__main__":
328
- sys.exit(_main(sys.argv[1:]))
329
-
330
-
331
- # --------------------------------------------------------------------------- arguments
332
-
333
- _JSON_TYPES: dict[str, tuple[type, ...]] = {
334
- "string": (str,), "integer": (int,), "number": (int, float), "boolean": (bool,),
335
- "array": (list,), "object": (dict,),
336
- }
337
-
338
-
339
- def _types(schema: dict[str, Any]) -> list[str] | None:
340
- t = schema.get("type")
341
- if isinstance(t, str):
342
- return [t]
343
- return list(t) if isinstance(t, list) else None
344
-
345
-
346
- def _is(value: Any, t: str) -> bool:
347
- if t == "null":
348
- return value is None
349
- if t not in _JSON_TYPES:
350
- return True
351
- return isinstance(value, _JSON_TYPES[t]) and not (t in ("integer", "number") and isinstance(value, bool))
352
-
353
-
354
- def _check(schema: dict[str, Any], value: Any, where: str) -> str | None:
355
- """Type and enum checks; null only where the schema allows it (`X | None`), array items
356
- included. A schema without `type` (`Any`) accepts anything."""
357
- types = _types(schema)
358
- if types is not None and not any(_is(value, t) for t in types):
359
- want = " or ".join("null" if t == "null" else t for t in types)
360
- got = "null" if value is None else f"{type(value).__name__} {json.dumps(value)[:60]}"
361
- return f"{where} must be {want}, got {got}"
362
- if "enum" in schema and value not in schema["enum"]:
363
- return f"{where} must be one of {schema['enum']}, got {json.dumps(value)[:60]}"
364
- if isinstance(value, list) and isinstance(schema.get("items"), dict):
365
- for i, v in enumerate(value):
366
- if err := _check(schema["items"], v, f"{where}[{i}]"):
367
- return err
368
- return None
369
-
370
-
371
- def check_args(params: dict[str, Any], args: Any) -> str | None:
372
- """An error message for arguments that do not fit the tool's schema, else None."""
373
- if not isinstance(args, dict):
374
- return f"arguments must be a JSON object, got {type(args).__name__}"
375
- props = params.get("properties") or {}
376
- unknown = [k for k in args if k not in props]
377
- if unknown:
378
- return f"unknown argument(s) {', '.join(unknown)}; expected: {', '.join(props) or 'none'}"
379
- missing = [k for k in params.get("required") or [] if k not in args]
380
- if missing:
381
- return f"missing required argument(s): {', '.join(missing)}"
382
- for k, v in args.items():
383
- if err := _check(props[k], v, k):
384
- return err
385
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/src/legion/worker/__init__.py DELETED
@@ -1 +0,0 @@
1
- """Worker: hosts agents on one HF Job; see docs/design.md "Architecture"."""
 
 
world/src/legion/worker/sync.py DELETED
@@ -1,1181 +0,0 @@
1
- """Bucket sync: per agent, `<bucket_id>/<swarm>/<type>/<agent>/` holds
2
-
3
- workdir/<path relative to the workdir> (if persist_workdir; the deltas with a base)
4
- workdir.base.tar, workdir.base.json (only with the type's workdir.base, below)
5
- meta.json ({files, bytes, ts} of the mirrored workdir when it last changed)
6
- sessions/<agent>.jsonl, <agent>.state.json (pi session log + worker state)
7
- harness/<path relative to the harness home> (a Trial's Pi sessions)
8
-
9
- The workdir goes through `sync_bucket` (the Python form of `hf buckets sync`), upward with delete so the bucket mirrors the workdir. The handful of
10
- session and harness files go through `batch_bucket_files`, only those whose (mtime, size)
11
- changed since the last push by this worker. `restore` brings all three areas back to the
12
- same absolute paths (workdir and work root are fixed, harness homes are fixed by the image)
13
- before the first resume.
14
-
15
- Restore lists the agent's prefix once, then downloads every file it found in batches
16
- (`restore_batch()`: env `LEGION_RESTORE_BATCH`, default 1000, minimum 1, an invalid value
17
- means the default), `restore_threads()` batches at a time (env `LEGION_RESTORE_THREADS`,
18
- default 4; the type's `worker:` block overrides both), each to a `.legion-part` sibling renamed into place on success. A batch that
19
- fails is retried file by file, with backoff (`RESTORE_BACKOFF`) between rounds: one unreadable
20
- file is skipped and reported in `RestoreResult.failed` instead of aborting the whole restore. A
21
- permanent "not found" (HTTP 404, e.g. xet "CAS Client Error: ... 404 Not Found" on the
22
- reconstruction: the entry's data is gone) is skipped at once, without the backoff rounds (an
23
- already-corrupt copy with ~42k such entries took 636 s to restore with them). Skipped files are
24
- logged as one summary line per agent. Only a failed listing makes `restore` raise.
25
-
26
- Buckets store bytes, not file modes: a restored file comes back 0644, so an executable script
27
- would stop running after a move. Each
28
- push therefore writes `<workdir>/.legion-modes.json` ({relative path: octal mode} for every file
29
- with an executable bit) when it changed, and restore re-applies it after the workdir download.
30
-
31
- Push safety (a periodic sync must never mirror a half-restored workdir over the bucket copy,
32
- deleting entries the in-flight restore has not fetched yet):
33
-
34
- - No push before setup: `AgentRuntime.sync_now` does nothing until the agent's `setup()` has
35
- finished its restore (every caller: the periodic sync, drain, preempt, unassign), and
36
- `BucketSync.push` refuses an agent whose restore is in flight. The bucket copy is the truth
37
- until the restore is done.
38
- - Delete-mirror only from a full baseline: the workdir push deletes remote files missing
39
- locally only when this worker's restore of the agent was complete (the listing succeeded and
40
- no file failed; an empty prefix counts as complete) or when no restore was attempted (a new
41
- agent). After a failed listing, a skipped file or an interrupted restore, pushes upload
42
- changed files but never delete, for as long as this worker holds the agent: a file it could
43
- not fetch stays in the bucket for the next restore.
44
- - `*.legion-part` (restore temporaries) is never uploaded nor deleted by a push; restore removes
45
- stray ones left by a crash.
46
- - Regenerable caches (`workdir_excludes`: `__pycache__/`, `*.pyc`, `node_modules/`, `.venv/`, ...; env
47
- LEGION_SYNC_EXCLUDE adds globs, LEGION_SYNC_EXCLUDE_DEFAULTS=0 drops the defaults) are neither
48
- uploaded nor deleted by the mirror, and restore skips them, also those already in the bucket.
49
- `.git/` and worktrees are never excluded by default.
50
- - The type's `workdir.ephemeral` dirs (root-relative) are excluded like the caches; the agent's
51
- setup empties them (`reset_ephemeral`), so they never come back after a move.
52
- - Each push's modes walk also measures what is mirrored (`WorkdirStats`): above the type's
53
- `workdir.soft_*` the agent gets a note, above `max_*` a `workdir_over_quota` event (each at
54
- most hourly, `BucketSync._quota`). A push is never refused for size.
55
- - Restore sets each workdir file's mtime to the bucket's (the listing carries it), so the first
56
- push after a restore uploads only real changes; session and harness files are marked as
57
- pushed (`_mark`).
58
-
59
- Base tar (the type's `workdir.base: true`; off by default). A restore of N small files costs N
60
- downloads; a base turns most of them into one:
61
-
62
- - A periodic push (never drain, preempt or unassign) makes a base when the agent has none, every
63
- `workdir.base_interval_s` (3600) or when the delta passes `workdir.base_delta_files` (5000,
64
- changed + deleted): an uncompressed tar of the workdir, sorted, regular files and symlinks
65
- with modes and mtimes (excludes and ephemeral dirs left out), written to local disk and
66
- uploaded as `workdir.base.tar`; then `workdir.base.json` `{created_at, files, bytes, deleted,
67
- links}` is written: the commit point. Only from a full baseline (`_mirror`), like deletes.
68
- - Every push after that uploads to `workdir/` only files whose (mtime, size) differ from the
69
- base's local index (`<sessions>/<agent>.base-index.json`), giving a changed file with an mtime
70
- not after the base (`cp -p`) the current time; base paths gone locally go to `deleted`
71
- (tombstones) and new or changed symlinks to `links`, rewriting the manifest when they change;
72
- delta entries not needed any more (in the base, or deleted) are removed from `workdir/`.
73
- - Restore with a manifest: download it and the tar, extract the tar member by member from disk,
74
- apply `deleted` and `links`, then download only the `workdir/` entries newer than
75
- `created_at` (older ones are already in the tar). A failed manifest, tar or member makes the
76
- restore incomplete (no deletes, no new base). Buckets without a manifest restore file by file.
77
- - Crash safety: before the manifest is written the old manifest (or the plain mirror) stays
78
- valid; after it, stale `workdir/` entries are older than `created_at`, ignored by restore and
79
- removed by the next push. Turning `base` off makes the next full-baseline push mirror the whole
80
- workdir to `workdir/` again and delete the base.
81
- """
82
-
83
- from __future__ import annotations
84
-
85
- import asyncio
86
- import fnmatch
87
- import functools
88
- import json
89
- import logging
90
- import os
91
- import re
92
- import shutil
93
- import stat
94
- import tarfile
95
- import threading
96
- import time
97
- from collections import Counter
98
- from concurrent.futures import ThreadPoolExecutor
99
- from dataclasses import dataclass, field
100
- from datetime import UTC, datetime
101
- from pathlib import Path
102
- from typing import TYPE_CHECKING, Protocol
103
-
104
- from legion.models import WorkdirSpec
105
-
106
- if TYPE_CHECKING:
107
- from legion.models import TypeSpec
108
- from legion.worker.agents import AgentRuntime
109
-
110
- log = logging.getLogger(__name__)
111
-
112
- UPLOAD_CHUNK = 200
113
- MODES_FILE = ".legion-modes.json"
114
- BASE_TAR = "workdir.base.tar" # under the agent prefix (module docstring, "Base tar")
115
- BASE_JSON = "workdir.base.json"
116
- RESTORE_BATCH = 1000 # default of LEGION_RESTORE_BATCH
117
- RESTORE_THREADS = 4 # default of LEGION_RESTORE_THREADS
118
- # The type's `worker:` values for this module (sync_exclude, restore_batch, restore_threads),
119
- # set live by `Worker.apply_knobs`; each one present wins over its env variable.
120
- SPEC_KNOBS: dict[str, object] = {}
121
-
122
-
123
- def _env_int(name: str, default: int, cap: int | None = None) -> int:
124
- try:
125
- n = int(os.environ.get(name, ""))
126
- except ValueError:
127
- return default
128
- return min(n, cap or n) if n >= 1 else default
129
-
130
-
131
- def restore_batch() -> int:
132
- """Files per restore download batch: the spec's, else env LEGION_RESTORE_BATCH (>= 1), else
133
- RESTORE_BATCH."""
134
- return SPEC_KNOBS.get("restore_batch") or _env_int("LEGION_RESTORE_BATCH", RESTORE_BATCH)
135
-
136
-
137
- def restore_threads() -> int:
138
- """Batches of one agent's restore downloaded in parallel: the spec's, else env
139
- LEGION_RESTORE_THREADS (>= 1), else RESTORE_THREADS."""
140
- return SPEC_KNOBS.get("restore_threads") or _env_int("LEGION_RESTORE_THREADS", RESTORE_THREADS, 32)
141
-
142
-
143
- RESTORE_BACKOFF = (1.0, 4.0, 10.0) # seconds before each per-file retry round
144
- PART_SUFFIX = ".legion-part"
145
- PUSH_EXCLUDE = ["*" + PART_SUFFIX] # sync_bucket patterns, matched on relative paths
146
- # Regenerable caches left out of the workdir mirror and of restore (module docstring). A trailing
147
- # "/" names a directory at any depth (`workdir_excludes`); other entries are plain globs.
148
- # Not build/, dist/ or target/: sometimes source.
149
- DEFAULT_WORKDIR_EXCLUDE = ["__pycache__/", "*.pyc", ".pytest_cache/", ".mypy_cache/",
150
- ".ruff_cache/", ".hypothesis/", "*.egg-info/", ".cache/",
151
- "node_modules/", ".venv/", "venv/", ".tox/", ".nox/",
152
- ".ipynb_checkpoints/", ".gradle/", ".next/", "*.o"]
153
-
154
-
155
- def _expand(pattern: str) -> list[str]:
156
- """`name/` -> `name/*` and `*/name/*` (the directory at the root and below any directory);
157
- anything else is returned as is. `sync_bucket` globs are fnmatch on the whole relative path,
158
- where `*` also crosses `/`."""
159
- if pattern.endswith("/"):
160
- d = pattern.rstrip("/")
161
- return [f"{d}/*", f"*/{d}/*"]
162
- return [pattern]
163
-
164
-
165
- def workdir_excludes() -> list[str]:
166
- """Globs for the workdir mirror, relative to the workdir, always including `*.legion-part`:
167
- the defaults (unless env LEGION_SYNC_EXCLUDE_DEFAULTS=0) plus the spec's `sync_exclude`, else
168
- the comma-separated LEGION_SYNC_EXCLUDE. `.git/` is never in the defaults."""
169
- pats = list(PUSH_EXCLUDE)
170
- if os.environ.get("LEGION_SYNC_EXCLUDE_DEFAULTS", "1").strip() != "0":
171
- pats += [x for d in DEFAULT_WORKDIR_EXCLUDE for x in _expand(d)]
172
- extra = SPEC_KNOBS.get("sync_exclude")
173
- if extra is None:
174
- extra = os.environ.get("LEGION_SYNC_EXCLUDE", "").split(",")
175
- for item in extra:
176
- if item.strip():
177
- pats += _expand(item.strip())
178
- return pats
179
-
180
-
181
- @functools.lru_cache(maxsize=64)
182
- def _matcher(patterns: tuple[str, ...]):
183
- """One compiled regex for a pattern list (a walk tests every file of a workdir)."""
184
- if not patterns:
185
- return lambda rel: None
186
- return re.compile("|".join(fnmatch.translate(p.replace("\\", "/")) for p in patterns)).match
187
-
188
-
189
- def is_excluded(rel: str, patterns: list[str]) -> bool:
190
- """Does the workdir-relative posix path match one of the patterns (as `sync_bucket` does)?"""
191
- return _matcher(tuple(patterns))(rel) is not None
192
-
193
-
194
- @dataclass
195
- class WorkdirStats:
196
- """What a push mirrors: regular files and their bytes, excluded paths left out, and the
197
- top-level directories with the most files ((name, files), largest first, up to 5)."""
198
-
199
- files: int = 0
200
- bytes: int = 0
201
- top_dirs: list[tuple[str, int]] = field(default_factory=list)
202
-
203
- def summary(self) -> str:
204
- """'182k files, 3100 MB; largest: snaps/ 140k, src/ 2k' (`{workspace}` in loop prompts)."""
205
- top = ", ".join(f"{d}/ {_k(n)}" for d, n in self.top_dirs[:3])
206
- return (f"{_k(self.files)} files, {self.bytes / 2**20:.0f} MB"
207
- + (f"; largest: {top}" if top else ""))
208
-
209
-
210
- def _k(n: int) -> str:
211
- return f"{n / 1000:.0f}k" if n >= 1000 else str(n)
212
-
213
-
214
- QUOTA_NOTE_EVERY = 3600.0 # s, per agent: the over-soft-limit note and workdir_over_quota
215
-
216
-
217
- def quota_note(ws: WorkdirStats, w: WorkdirSpec) -> str | None:
218
- """The note for an agent whose workdir is above its soft limit, else None."""
219
- if ws.files <= w.soft_files and ws.bytes / 2**20 <= w.soft_mb:
220
- return None
221
- where = f", or keep throwaway clones in {w.ephemeral[0]}" if w.ephemeral else ""
222
- return (f"your workspace has {ws.summary()} (soft limit {_k(w.soft_files)} files, "
223
- f"{w.soft_mb:.0f} MB); delete clones you no longer need{where}")
224
-
225
-
226
- def over_hard_limit(ws: WorkdirStats, w: WorkdirSpec) -> bool:
227
- return (ws.files > (w.max_files or 5 * w.soft_files)
228
- or ws.bytes / 2**20 > (w.max_mb or 5 * w.soft_mb))
229
-
230
-
231
- def ephemeral_excludes(spec: TypeSpec) -> list[str]:
232
- """The type's `workdir.ephemeral` dirs as root-anchored globs (never synced nor restored)."""
233
- return [d + "*" for d in (spec.workdir.ephemeral if spec.workdir else [])]
234
-
235
-
236
- def reset_ephemeral(workdir: Path, spec: TypeSpec) -> None:
237
- """Empty (or create) the type's ephemeral dirs: run at every agent setup, so a move or a
238
- restart never brings back their content. Blocking."""
239
- root = workdir.resolve()
240
- for d in spec.workdir.ephemeral if spec.workdir else []:
241
- p = workdir / d
242
- try:
243
- if not p.parent.resolve().is_relative_to(root): # a symlinked parent: leave it
244
- log.warning("ephemeral dir %s is outside %s; not touched", p, root)
245
- continue
246
- if p.is_symlink() or p.is_file():
247
- p.unlink()
248
- elif p.is_dir():
249
- shutil.rmtree(p, ignore_errors=True)
250
- p.mkdir(parents=True, exist_ok=True)
251
- except OSError as e:
252
- log.warning("ephemeral dir %s: %s", p, e)
253
-
254
-
255
- def _walk(workdir: Path, exclude: list[str] | None = None):
256
- """(relative posix path, lstat) of every regular file and symlink under `workdir`, sorted per
257
- directory; excluded directories are not entered, symlinked directories are not followed."""
258
- excl = _matcher(tuple(exclude or ()))
259
- for root, dirs, files in os.walk(workdir):
260
- base = Path(root).relative_to(workdir).as_posix()
261
- base = "" if base == "." else base + "/"
262
- links = [d for d in dirs if os.path.islink(os.path.join(root, d))]
263
- dirs[:] = sorted(d for d in dirs if d not in links and excl(f"{base}{d}/") is None)
264
- for f in sorted(files + links):
265
- rel = base + f
266
- if excl(rel) is not None:
267
- continue
268
- try:
269
- st = os.lstat(os.path.join(root, f))
270
- except OSError:
271
- continue
272
- if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode):
273
- yield rel, st
274
-
275
-
276
- def collect_modes(workdir: Path, stats: WorkdirStats | None = None,
277
- exclude: list[str] | None = None) -> dict[str, str]:
278
- """{relative posix path: "0o755"} for regular files with any executable bit (symlinks and
279
- the manifest itself excluded). `exclude`: paths left out of the walk (excluded directories
280
- are not entered). `stats` gets the walk's counts (`WorkdirStats`)."""
281
- out: dict[str, str] = {}
282
- per_dir: Counter[str] = Counter()
283
- for rel, st in _walk(workdir, exclude):
284
- if not stat.S_ISREG(st.st_mode):
285
- continue
286
- if stats is not None:
287
- stats.files += 1
288
- stats.bytes += st.st_size
289
- if "/" in rel:
290
- per_dir[rel.split("/", 1)[0]] += 1
291
- if st.st_mode & 0o111 and rel != MODES_FILE:
292
- out[rel] = oct(stat.S_IMODE(st.st_mode))
293
- if stats is not None:
294
- stats.top_dirs = per_dir.most_common(5)
295
- return dict(sorted(out.items()))
296
-
297
-
298
- def _write_synced(path: Path, text: str) -> None: # fsync before a later os.replace
299
- with path.open("w") as f:
300
- f.write(text)
301
- f.flush()
302
- os.fsync(f.fileno())
303
-
304
-
305
- def write_modes(workdir: Path, stats: WorkdirStats | None = None,
306
- exclude: list[str] | None = None) -> bool:
307
- """(Re)write the manifest if its content changed, remove it when nothing is executable.
308
- Returns whether the file changed."""
309
- path = workdir / MODES_FILE
310
- modes = collect_modes(workdir, stats, exclude)
311
- old = path.read_text() if path.is_file() else None
312
- if not modes:
313
- if old is not None:
314
- path.unlink()
315
- return True
316
- return False
317
- new = json.dumps(modes, indent=0, sort_keys=True) + "\n"
318
- if new == old:
319
- return False
320
- path.write_text(new)
321
- return True
322
-
323
-
324
- def apply_modes(workdir: Path) -> int:
325
- """chmod the files listed in the manifest (inside the workdir, regular files only)."""
326
- path = workdir / MODES_FILE
327
- try:
328
- modes = json.loads(path.read_text())
329
- except (OSError, ValueError):
330
- return 0
331
- n = 0
332
- root = workdir.resolve()
333
- for rel, mode in (modes.items() if isinstance(modes, dict) else []):
334
- p = workdir / rel
335
- try:
336
- if ".." in Path(rel).parts or not p.resolve().is_relative_to(root) or p.is_symlink() \
337
- or not p.is_file():
338
- continue
339
- os.chmod(p, int(mode, 8) & 0o7777)
340
- n += 1
341
- except (OSError, ValueError, TypeError):
342
- continue
343
- return n
344
-
345
-
346
- class _Padded:
347
- """A file that may shrink while it is read: short reads are padded with zeros, so the tar
348
- stays well formed; the file's new mtime makes the next push send it as a delta."""
349
-
350
- def __init__(self, f) -> None:
351
- self.f = f
352
-
353
- def read(self, n: int = -1) -> bytes:
354
- b = self.f.read(n)
355
- return b + bytes(max(0, n - len(b)))
356
-
357
-
358
- TAR_PER_FILE = 2048 # bytes of tar overhead per member, at most (pax header + padding)
359
-
360
-
361
- def _fits(needs: list[tuple[Path, int]]) -> bool:
362
- """Do these byte counts fit in the free space of their file systems (summed per device)?"""
363
- per: dict[int, list] = {}
364
- for p, n in needs:
365
- p.mkdir(parents=True, exist_ok=True)
366
- per.setdefault(os.stat(p).st_dev, [p, 0])[1] += n
367
- return all(shutil.disk_usage(p).free >= n for p, n in per.values())
368
-
369
-
370
- def write_base_tar(workdir: Path, exclude: list[str], dest: Path,
371
- stop=lambda: False) -> dict[str, list] | None:
372
- """Write an uncompressed tar of the workdir (regular files and symlinks, sorted, with modes
373
- and mtimes) to `dest`; returns the index {relative path: [mtime, size]} of what it holds
374
- (lstat before each read), or None when `stop()` turned true between two members."""
375
- index: dict[str, list] = {}
376
- dest.parent.mkdir(parents=True, exist_ok=True)
377
- with tarfile.open(dest, "w", format=tarfile.PAX_FORMAT) as tf:
378
- for rel, st in _walk(workdir, exclude):
379
- if stop():
380
- return None
381
- ti = tarfile.TarInfo(rel)
382
- ti.mode, ti.mtime = stat.S_IMODE(st.st_mode), int(st.st_mtime)
383
- ti.pax_headers = {"mtime": f"{st.st_mtime_ns / 1e9:.9f}"} # sub-second mtimes
384
- p = workdir / rel
385
- try:
386
- if stat.S_ISLNK(st.st_mode):
387
- ti.type, ti.linkname = tarfile.SYMTYPE, os.readlink(p)
388
- tf.addfile(ti)
389
- else:
390
- with open(p, "rb") as f:
391
- ti.size = st.st_size
392
- tf.addfile(ti, _Padded(f))
393
- except OSError: # gone since the walk (open or readlink, before anything is written)
394
- continue
395
- index[rel] = [st.st_mtime, st.st_size]
396
- return index
397
-
398
-
399
- def extract_base_tar(src: Path, workdir: Path, exclude: list[str],
400
- base: dict) -> tuple[dict[str, list], int]:
401
- """Extract a base tar into the workdir member by member (regular files and symlinks with
402
- their modes and mtimes; nothing outside the workdir, nothing excluded), then apply the
403
- manifest's tombstones (`deleted`) and symlinks (`links`). Returns (the index of the
404
- extracted files {relative path: [mtime, size]}, members that failed)."""
405
- workdir.mkdir(parents=True, exist_ok=True)
406
- root = workdir.resolve()
407
- index: dict[str, list] = {}
408
- bad = 0
409
-
410
- safe: set[str] = set() # parent dirs checked (and made): one realpath per directory
411
-
412
- def target(rel: str, make: bool = True) -> str | None:
413
- """The local path for `rel`, cleared, or None when it must not be written."""
414
- if rel.startswith("/") or ".." in rel.split("/") or is_excluded(rel, exclude):
415
- return None
416
- p = os.path.join(workdir, rel)
417
- parent = os.path.dirname(p)
418
- if parent not in safe:
419
- if not Path(parent).resolve().is_relative_to(root):
420
- return None
421
- if make:
422
- os.makedirs(parent, exist_ok=True)
423
- safe.add(parent)
424
- try:
425
- if stat.S_ISDIR(os.lstat(p).st_mode):
426
- return None # a directory in the way
427
- os.unlink(p) # also read-only files (git objects) and links
428
- except FileNotFoundError:
429
- pass
430
- return p
431
-
432
- with tarfile.open(src, "r:") as tf:
433
- while (m := tf.next()) is not None:
434
- tf.members.clear() # a 500k-file tar keeps no member list in memory
435
- try:
436
- if not (m.isreg() or m.issym()) or (p := target(m.name)) is None:
437
- continue
438
- if m.issym():
439
- os.symlink(m.linkname, p)
440
- else:
441
- with tf.extractfile(m) as f, open(p, "wb") as out:
442
- shutil.copyfileobj(f, out)
443
- os.chmod(p, m.mode & 0o777)
444
- os.utime(p, (m.mtime, m.mtime), follow_symlinks=False)
445
- index[m.name] = [m.mtime, len(os.fsencode(m.linkname)) if m.issym() else m.size]
446
- except OSError as e:
447
- bad += 1
448
- log.debug("base member %s: %s", m.name, e)
449
- for rel in base.get("deleted", []):
450
- try:
451
- target(rel, make=False)
452
- except OSError:
453
- bad += 1
454
- for rel, link in base.get("links", {}).items():
455
- try:
456
- if (p := target(rel)) is not None:
457
- os.symlink(link, p)
458
- except OSError:
459
- bad += 1
460
- return index, bad
461
-
462
-
463
- def _same(a: list | None, mtime: float, size: int) -> bool:
464
- return a is not None and abs(a[0] - mtime) <= 2e-3 and a[1] == size
465
-
466
-
467
- def workdir_delta(workdir: Path, exclude: list[str], index: dict[str, list],
468
- created_at: float) -> tuple[dict[str, float], dict[str, str], list[str]]:
469
- """Against the base's index: (regular files new or changed {rel: mtime}, symlinks new or
470
- changed {rel: target}, base paths gone). A changed file whose mtime is not after the base
471
- (`cp -p`, `tar x`) gets its mtime set to now, since restore only takes deltas newer than the
472
- base."""
473
- files: dict[str, float] = {}
474
- links: dict[str, str] = {}
475
- seen: set[str] = set()
476
- now = max(time.time(), created_at + 1.0)
477
- for rel, st in _walk(workdir, exclude):
478
- seen.add(rel)
479
- if _same(index.get(rel), st.st_mtime, st.st_size):
480
- continue
481
- p = workdir / rel
482
- try:
483
- if stat.S_ISLNK(st.st_mode):
484
- links[rel] = os.readlink(p)
485
- continue
486
- mt = st.st_mtime
487
- if mt <= created_at + 2e-3: # the Hub keeps milliseconds
488
- os.utime(p, (now, now))
489
- mt = now
490
- except OSError:
491
- continue
492
- files[rel] = mt
493
- return files, links, sorted(set(index) - seen)
494
-
495
-
496
- def _load_index(path: Path) -> dict[str, list]:
497
- try:
498
- return json.loads(path.read_text())
499
- except (OSError, ValueError):
500
- return {}
501
-
502
-
503
- @dataclass
504
- class BucketStats:
505
- """Bucket traffic counters for the worker log: store operations (`ops`), the Hub HTTP
506
- requests behind them (`http`, by method and route; xet CAS transfers run in hf_xet and are
507
- not seen here) and HTTP error statuses (`errors`, e.g. 429). Thread-safe."""
508
-
509
- ops: Counter = field(default_factory=Counter)
510
- http: Counter = field(default_factory=Counter)
511
- errors: Counter = field(default_factory=Counter)
512
- _lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
513
-
514
- def add(self, kind: str, key: str, n: int = 1) -> None:
515
- with self._lock:
516
- getattr(self, kind)[key] += n
517
-
518
- def snapshot(self) -> dict[str, Counter]:
519
- with self._lock:
520
- return {"ops": Counter(self.ops), "http": Counter(self.http),
521
- "errors": Counter(self.errors)}
522
-
523
- def since(self, before: dict[str, Counter]) -> dict[str, dict[str, int]]:
524
- now = self.snapshot()
525
- return {k: dict(now[k] - before[k]) for k in now}
526
-
527
-
528
- _BUCKET_ROUTE = re.compile(r"^/api/buckets/[^/]+/[^/]+(?:/([^/]+))?")
529
-
530
-
531
- def http_route(method: str, host: str, path: str) -> str:
532
- """'GET /api/buckets/ns/b/tree/x/y' -> 'GET buckets/tree'; other hosts by first segment."""
533
- m = _BUCKET_ROUTE.match(path)
534
- if m:
535
- return f"{method} buckets/{m.group(1) or ''}".rstrip("/")
536
- first = path.strip("/").split("/", 1)[0]
537
- if host.endswith("huggingface.co"):
538
- return f"{method} {first or '/'}"
539
- return f"{method} {host}/{first}"
540
-
541
-
542
- def count_hub_http(stats: BucketStats) -> None:
543
- """Count every request huggingface_hub's shared client makes (one install per process)."""
544
- import huggingface_hub
545
- from huggingface_hub.utils._http import default_client_factory
546
-
547
- def on_request(request) -> None:
548
- stats.add("http", http_route(request.method, request.url.host, request.url.path))
549
-
550
- def on_response(response) -> None:
551
- if response.status_code >= 400:
552
- req = response.request
553
- route = http_route(req.method, req.url.host, req.url.path)
554
- stats.add("errors", f"{response.status_code} {route}")
555
-
556
- def factory():
557
- client = default_client_factory()
558
- client.event_hooks["request"].append(on_request)
559
- client.event_hooks.setdefault("response", []).append(on_response)
560
- return client
561
-
562
- huggingface_hub.set_client_factory(factory)
563
-
564
-
565
- class BucketStore(Protocol):
566
- """Blocking bucket operations on paths relative to the legion root."""
567
-
568
- def upload(self, files: list[tuple[Path, str]]) -> None: ...
569
- def list(self, prefix: str) -> list[str]: ...
570
- def first(self, prefix: str) -> str | None: ... # one file under prefix (the launch guard)
571
- # optional: `list_info(prefix) -> list[tuple[str, float | None]]`, paths with their mtime
572
- # (POSIX seconds) when the store keeps one; restore uses it to set local mtimes
573
- def download(self, files: list[tuple[str, Path]]) -> None: ...
574
- def sync_up(self, local: Path, prefix: str, *, delete: bool = True,
575
- exclude: list[str] | None = None) -> None:
576
- """Upload new/changed files of a local directory to `prefix`; with `delete`, also
577
- delete remote files missing locally. `exclude`: fnmatch patterns on relative paths,
578
- neither uploaded nor deleted."""
579
- ...
580
-
581
- def sync_down(self, prefix: str, local: Path) -> None: ...
582
- def delete(self, paths: list[str]) -> None:
583
- """Delete files (paths relative to the legion root). Used by the controller's state."""
584
- ...
585
-
586
-
587
- def parse_bucket(url: str) -> tuple[str, str]:
588
- """'hf://buckets/ns/name/some/prefix' -> ('ns/name', 'some/prefix/')."""
589
- rest = url.removeprefix("hf://").removeprefix("buckets/").strip("/")
590
- parts = rest.split("/")
591
- if len(parts) < 2:
592
- raise ValueError(f"bad bucket url {url!r}; expected hf://buckets/<namespace>/<name>[/prefix]")
593
- prefix = "/".join(parts[2:])
594
- return f"{parts[0]}/{parts[1]}", (prefix + "/" if prefix else "")
595
-
596
-
597
- class HubBucketStore:
598
- """huggingface_hub bucket API (batch_bucket_files / list_bucket_tree / download_bucket_files)."""
599
-
600
- def __init__(self, url: str, token: str | None = None, stats: BucketStats | None = None) -> None:
601
- from huggingface_hub import HfApi
602
-
603
- self.bucket_id, self.base = parse_bucket(url)
604
- self.api = HfApi(token=token)
605
- self.stats = stats or BucketStats()
606
-
607
- def upload(self, files: list[tuple[Path, str]]) -> None:
608
- for i in range(0, len(files), UPLOAD_CHUNK):
609
- self.stats.add("ops", "batch_bucket_files")
610
- chunk = files[i : i + UPLOAD_CHUNK]
611
- self.api.batch_bucket_files(self.bucket_id, add=[(str(p), self.base + r) for p, r in chunk])
612
-
613
- def list(self, prefix: str) -> list[str]:
614
- return [r for r, _ in self.list_info(prefix)]
615
-
616
- def first(self, prefix: str) -> str | None:
617
- """One file under `prefix` (None: empty), without listing the rest."""
618
- from huggingface_hub import BucketFile
619
-
620
- self.stats.add("ops", "list_bucket_tree")
621
- full = self.base + prefix
622
- for f in self.api.list_bucket_tree(self.bucket_id, prefix=full, recursive=True):
623
- if isinstance(f, BucketFile) and f.path.startswith(full):
624
- return f.path[len(self.base):]
625
- return None
626
-
627
- def list_info(self, prefix: str) -> list[tuple[str, float | None]]:
628
- from huggingface_hub import BucketFile
629
-
630
- self.stats.add("ops", "list_bucket_tree")
631
- full = self.base + prefix
632
- out: list[tuple[str, float | None]] = []
633
- for f in self.api.list_bucket_tree(self.bucket_id, prefix=full, recursive=True):
634
- if isinstance(f, BucketFile) and f.path.startswith(full):
635
- mt = f.mtime.timestamp() if isinstance(f.mtime, datetime) else None
636
- out.append((f.path[len(self.base):], mt))
637
- return out
638
-
639
- def download(self, files: list[tuple[str, Path]]) -> None:
640
- self.stats.add("ops", "download_bucket_files")
641
- for _, local in files:
642
- local.parent.mkdir(parents=True, exist_ok=True)
643
- self.api.download_bucket_files(self.bucket_id, [(self.base + r, str(p)) for r, p in files])
644
-
645
- def delete(self, paths: list[str]) -> None:
646
- for i in range(0, len(paths), UPLOAD_CHUNK):
647
- self.stats.add("ops", "batch_bucket_files")
648
- chunk = paths[i : i + UPLOAD_CHUNK]
649
- self.api.batch_bucket_files(self.bucket_id, delete=[self.base + r for r in chunk])
650
-
651
- def _url(self, prefix: str) -> str:
652
- return f"hf://buckets/{self.bucket_id}/{self.base}{prefix}".rstrip("/")
653
-
654
- def sync_up(self, local: Path, prefix: str, *, delete: bool = True,
655
- exclude: list[str] | None = None) -> None:
656
- self.stats.add("ops", "sync_bucket_up")
657
- self.api.sync_bucket(str(local), self._url(prefix), delete=delete, exclude=exclude or None,
658
- quiet=True)
659
-
660
- def sync_down(self, prefix: str, local: Path) -> None:
661
- self.stats.add("ops", "sync_bucket_down")
662
- local.mkdir(parents=True, exist_ok=True)
663
- self.api.sync_bucket(self._url(prefix), str(local), quiet=True)
664
-
665
-
666
- @dataclass
667
- class RestoreResult:
668
- workdir: int = 0
669
- sessions: int = 0
670
- harness: int = 0
671
- # bucket paths (relative to the legion root) that could not be downloaded, after retries
672
- failed: list[str] = field(default_factory=list)
673
-
674
-
675
- _NOT_FOUND = re.compile(r"\b404\b|not found", re.IGNORECASE)
676
-
677
-
678
- def _permanent(e: BaseException) -> bool:
679
- """A download error that retrying cannot fix: the entry's data is gone (HTTP 404)."""
680
- resp = getattr(e, "response", None)
681
- if getattr(resp, "status_code", None) == 404:
682
- return True
683
- return bool(_NOT_FOUND.search(str(e)))
684
-
685
-
686
- def _part(p: Path) -> Path:
687
- return p.with_name(p.name + PART_SUFFIX)
688
-
689
-
690
- def download_resilient(store: BucketStore, files: list[tuple[str, Path]], *,
691
- backoff: tuple[float, ...] | None = None, sleep=None,
692
- progress=None) -> tuple[list[tuple[str, Path]], list[str]]:
693
- """Download (remote, local) pairs; returns (downloaded, failed remote paths). Never raises
694
- for a file: batches first, then the files of a failed batch one by one, retried after each
695
- delay in `backoff` unless the error is a permanent "not found" (`_permanent`). Each file lands in a `.legion-part` sibling, renamed into place only
696
- when it arrived, so a failed file never leaves a truncated copy at its real path.
697
- `progress(n)` is called with the number of files each attempt brought in (serialized: the
698
- first pass runs `restore_threads()` batches in parallel threads)."""
699
-
700
- gone: list[str] = [] # permanent "not found": skipped, never retried
701
- lock = threading.Lock() # first-pass batches run in threads
702
-
703
- def attempt(batch: list[tuple[str, Path]]) -> tuple[list[tuple[str, Path]], list[tuple[str, Path]]]:
704
- ok, bad = [], []
705
- try:
706
- store.download([(r, _part(p)) for r, p in batch])
707
- except Exception as e: # noqa: BLE001 - sorted out per file below
708
- err = e
709
- else:
710
- err = None
711
- for r, p in batch:
712
- part = _part(p)
713
- if err is None and part.is_file():
714
- try:
715
- os.replace(part, p)
716
- ok.append((r, p))
717
- continue
718
- except OSError:
719
- pass
720
- part.unlink(missing_ok=True)
721
- bad.append((r, p))
722
- if ok and progress is not None:
723
- with lock:
724
- progress(len(ok))
725
- if err is not None and len(batch) == 1:
726
- log.debug("download of %s failed: %s", batch[0][0], _short(err))
727
- if bad and _permanent(err):
728
- gone.append(bad[0][0])
729
- return ok, []
730
- return ok, bad
731
-
732
- backoff = RESTORE_BACKOFF if backoff is None else backoff
733
- sleep = sleep or time.sleep
734
- done: list[tuple[str, Path]] = []
735
- pending: list[tuple[str, Path]] = []
736
- size = restore_batch()
737
- batches = [files[i : i + size] for i in range(0, len(files), size)]
738
- # the first pass runs `restore_threads()` batches at once (per-request latency, not
739
- # bandwidth, bounds a restore); the per-file retry rounds below stay sequential
740
- with ThreadPoolExecutor(max(1, min(restore_threads(), len(batches)))) as pool:
741
- for ok, bad in pool.map(attempt, batches):
742
- done += ok
743
- pending += bad
744
- if pending: # each file alone, so one bad file costs only itself
745
- retry, pending = pending, []
746
- for f in retry:
747
- ok, bad = attempt([f])
748
- done += ok
749
- pending += bad
750
- for delay in backoff:
751
- if not pending:
752
- break
753
- sleep(delay)
754
- retry, pending = pending, []
755
- for f in retry:
756
- ok, bad = attempt([f])
757
- done += ok
758
- pending += bad
759
- # the caller logs the skipped files (one summary line per agent, `BucketSync._restore_files`)
760
- return done, gone + [r for r, _ in pending]
761
-
762
-
763
- def _clean_parts(root: Path) -> int:
764
- """Remove stray `.legion-part` files under `root` (a crash mid-download leaves them)."""
765
- n = 0
766
- if root.is_dir():
767
- for p in root.rglob("*" + PART_SUFFIX):
768
- try:
769
- if p.is_file() and not p.is_symlink():
770
- p.unlink()
771
- n += 1
772
- except OSError:
773
- pass
774
- return n
775
-
776
-
777
- def _short(e: BaseException) -> str:
778
- return f"{type(e).__name__}: {str(e)[:300]}"
779
-
780
-
781
- class BucketSync:
782
- def __init__(self, store: BucketStore, swarm: str) -> None:
783
- self.store = store
784
- self.swarm = swarm
785
- self.stats: BucketStats = getattr(store, "stats", None) or BucketStats()
786
- self._seen: dict[Path, tuple[int, int]] = {}
787
- # per agent prefix: may the workdir push delete remote files? Absent: no restore was
788
- # attempted (a new agent), deletes allowed. False from the start of a restore until it
789
- # completes with every file; stays False after an incomplete one (module docstring).
790
- self._mirror: dict[str, bool] = {}
791
- self._restoring: set[str] = set() # agent prefixes with a restore in flight
792
- self._meta: dict[str, dict] = {} # per agent prefix: the meta.json last pushed
793
- self._quota_note: dict[str, str] = {} # per agent prefix: the quota note last queued
794
- self._base: dict[str, dict] = {} # per agent prefix: its committed workdir.base.json
795
- self._building: set[str] = set() # agent prefixes with a base tar being made
796
- self.stop_rebase = False # set by drain/preempt: base builds stop, none start
797
- self._quota_at: dict[str, float] = {} # per agent prefix: monotonic time of the last note
798
- # per agent prefix with a restore in flight: [files done, files listed, started (UTC)]
799
- self.restore_progress: dict[str, list] = {}
800
-
801
- def mirror_deletes(self, rt: AgentRuntime) -> bool:
802
- return self._mirror.get(self.prefix(rt), True)
803
-
804
- def prefix(self, rt: AgentRuntime) -> str:
805
- return f"{self.swarm}/{rt.type_name}/{rt.name}/"
806
-
807
- def collect(self, rt: AgentRuntime) -> list[tuple[Path, str]]:
808
- """The agent's session-log, state and harness files, with their bucket paths."""
809
- pre = self.prefix(rt)
810
- out: list[tuple[Path, str]] = []
811
- for p in (rt.log.path, rt.state_path):
812
- if p.is_file():
813
- out.append((p, f"{pre}sessions/{p.name}"))
814
- home = Path(rt.adapter.home)
815
- for p in rt.harness_files():
816
- try:
817
- rel = p.relative_to(home)
818
- except ValueError:
819
- log.warning("%s: harness file %s is outside %s; not synced", rt.name, p, home)
820
- continue
821
- out.append((p, f"{pre}harness/{rel.as_posix()}"))
822
- return out
823
-
824
- def _changed(self, files: list[tuple[Path, str]]) -> list[tuple[Path, str]]:
825
- changed = []
826
- for p, r in files:
827
- try:
828
- st = p.stat()
829
- except OSError:
830
- continue
831
- sig = (st.st_mtime_ns, st.st_size)
832
- if self._seen.get(p) != sig:
833
- changed.append((p, r))
834
- return changed
835
-
836
- def _mark(self, files: list[tuple[Path, str]]) -> None:
837
- for p, _ in files:
838
- try:
839
- st = p.stat()
840
- self._seen[p] = (st.st_mtime_ns, st.st_size)
841
- except OSError:
842
- pass
843
-
844
- async def push(self, rt: AgentRuntime, *, rebase: bool = False) -> int:
845
- """`rebase`: may make a new base tar when one is due (periodic pushes only, so drain
846
- and preempt stay as cheap as a delta)."""
847
- try:
848
- return await self._push(rt, rebase)
849
- except Exception:
850
- self.stats.add("errors", "push_failed")
851
- raise
852
-
853
- async def _push(self, rt: AgentRuntime, rebase: bool = False) -> int:
854
- pre = self.prefix(rt)
855
- if pre in self._restoring: # never mirror a half-restored agent (module docstring)
856
- log.warning("%s: push skipped, its restore is still running", rt.name)
857
- return 0
858
- meta: list[tuple[Path, str]] = []
859
- if rt.spec.persist_workdir and rt.workdir.is_dir():
860
- exclude = workdir_excludes() + ephemeral_excludes(rt.spec)
861
- ws = WorkdirStats()
862
- await asyncio.to_thread(write_modes, rt.workdir, ws, exclude)
863
- rt.workdir_files, rt.workdir_stats = ws.files, ws
864
- self._quota(rt, ws)
865
- stats = {"files": ws.files, "bytes": ws.bytes}
866
- if self._meta.get(pre) != stats: # the workdir's size: predicts a restore's time
867
- path = rt.sessions_dir / f"{rt.name}.meta.json"
868
- path.parent.mkdir(parents=True, exist_ok=True)
869
- path.write_text(json.dumps({**stats, "ts": datetime.now(UTC).isoformat()}))
870
- meta = [(path, pre + "meta.json")]
871
- delete = self.mirror_deletes(rt)
872
- if not delete:
873
- log.info("%s: workdir push without remote deletes (last restore incomplete)",
874
- rt.name)
875
- w = rt.spec.workdir or WorkdirSpec()
876
- if not (w.base and (pre in self._base or (rebase and delete))
877
- and await self._push_base(rt, exclude, w, rebase and delete, ws)):
878
- await asyncio.to_thread(self.store.sync_up, rt.workdir, pre + "workdir",
879
- delete=delete, exclude=exclude)
880
- if pre in self._base and delete: # base turned off: the full mirror replaces it
881
- await asyncio.to_thread(self.store.delete, [pre + BASE_JSON, pre + BASE_TAR])
882
- self._base.pop(pre)
883
- files = self._changed(self.collect(rt)) + meta
884
- if files:
885
- await asyncio.to_thread(self.store.upload, files)
886
- self._mark(files)
887
- if meta:
888
- self._meta[pre] = stats
889
- return len(files)
890
-
891
- def _index_path(self, rt: AgentRuntime) -> Path:
892
- return rt.sessions_dir / f"{rt.name}.base-index.json"
893
-
894
- async def _push_base(self, rt: AgentRuntime, exclude: list[str], w: WorkdirSpec,
895
- may_rebase: bool, ws: WorkdirStats) -> bool:
896
- """Workdir push with a base tar (module docstring, "Base tar"): a new base when due,
897
- then the files changed since the base, and tombstones and symlinks in the manifest.
898
- False: no base yet and none made (stopped, no disk); the caller mirrors file by file."""
899
- pre, dpre = self.prefix(rt), self.prefix(rt) + "workdir/"
900
- base = self._base.get(pre)
901
-
902
- def delta():
903
- index = _load_index(self._index_path(rt))
904
- return workdir_delta(rt.workdir, exclude, index, base["created_at"])
905
-
906
- async def send() -> dict[str, float | None]:
907
- remote = {r[len(dpre):]: mt for r, mt in
908
- await asyncio.to_thread(self.store.list_info, dpre)}
909
- up = [(rt.workdir / r, dpre + r) for r, mt in files.items()
910
- if remote.get(r) is None or abs(remote[r] - mt) > 2e-3]
911
- if up:
912
- await asyncio.to_thread(self.store.upload, up)
913
- return remote
914
-
915
- if base is not None:
916
- files, links, deleted = await asyncio.to_thread(delta)
917
- if may_rebase and (base is None or time.time() - base["created_at"] >= w.base_interval_s
918
- or len(files) + len(links) + len(deleted) > w.base_delta_files):
919
- if not _fits([(rt.sessions_dir, ws.bytes + ws.files * TAR_PER_FILE)]):
920
- log.warning("%s: no new workdir base, not enough free disk for a %s tar",
921
- rt.name, ws.summary())
922
- elif (new := await self._make_base(rt, exclude)) is not None:
923
- base = new
924
- files, links, deleted = await asyncio.to_thread(delta)
925
- if base is None:
926
- return False
927
- remote = await send()
928
- if not self.mirror_deletes(rt): # tombstones and remote deletes: full baseline only
929
- return True
930
- while pre in self._building: # another push is making a base: its manifest goes first
931
- await asyncio.sleep(0.1)
932
- if self._base.get(pre) is not base: # ... and was committed: diff against it
933
- base = self._base[pre]
934
- files, links, deleted = await asyncio.to_thread(delta)
935
- remote = await send()
936
- if base.get("deleted", []) != deleted or base.get("links", {}) != links:
937
- await self._write_base(rt, {**base, "deleted": deleted, "links": links})
938
-
939
- def stale(index: dict[str, list], r: str) -> bool:
940
- """Remote delta not needed: not changed in this walk and, locally, gone or as in the
941
- base (a file a concurrent push uploaded after this walk differs from it: it stays)."""
942
- if r in files or is_excluded(r, exclude):
943
- return False
944
- try:
945
- st = os.lstat(rt.workdir / r)
946
- except OSError:
947
- return True
948
- return _same(index.get(r), st.st_mtime, st.st_size)
949
-
950
- def stale_all() -> list[str]:
951
- index = _load_index(self._index_path(rt))
952
- return [dpre + r for r in remote if stale(index, r)]
953
-
954
- gone = await asyncio.to_thread(stale_all)
955
- if gone: # deltas now in the base, or deleted
956
- await asyncio.to_thread(self.store.delete, gone)
957
- return True
958
-
959
- async def _make_base(self, rt: AgentRuntime, exclude: list[str]) -> dict | None:
960
- """Tar the workdir, upload it, then commit `workdir.base.json` (the commit point); the
961
- local index of the base replaces the old one only after the commit. None when
962
- `stop_rebase` (drain, preempt) stopped it before the upload: nothing was written."""
963
- pre = self.prefix(rt)
964
- tar, idx = rt.sessions_dir / f"{rt.name}.base.tar", self._index_path(rt)
965
- new_idx = idx.with_name(idx.name + ".new")
966
- self._building.add(pre)
967
- try:
968
- t0 = time.time()
969
- index = await asyncio.to_thread(write_base_tar, rt.workdir, exclude, tar,
970
- lambda: self.stop_rebase)
971
- if index is None or self.stop_rebase:
972
- log.info("%s: workdir base build stopped (drain or preempt)", rt.name)
973
- return None
974
- await asyncio.to_thread(_write_synced, new_idx, json.dumps(index))
975
- await asyncio.to_thread(self.store.upload, [(tar, pre + BASE_TAR)])
976
- base = {"created_at": t0, "files": len(index),
977
- "bytes": sum(s for _, s in index.values()), "deleted": [], "links": {}}
978
- await self._write_base(rt, base)
979
- os.replace(new_idx, idx)
980
- finally:
981
- self._building.discard(pre)
982
- tar.unlink(missing_ok=True)
983
- new_idx.unlink(missing_ok=True)
984
- log.info("%s: new workdir base: %d files, %.0f MB in %.1f s", rt.name, base["files"],
985
- base["bytes"] / 2**20, time.time() - t0)
986
- return base
987
-
988
- async def _write_base(self, rt: AgentRuntime, base: dict) -> None:
989
- path = rt.sessions_dir / f"{rt.name}.base.json"
990
- path.parent.mkdir(parents=True, exist_ok=True)
991
- path.write_text(json.dumps(base))
992
- await asyncio.to_thread(self.store.upload, [(path, self.prefix(rt) + BASE_JSON)])
993
- self._base[self.prefix(rt)] = base
994
-
995
- async def _restore_base(self, rt: AgentRuntime,
996
- skip: list[str]) -> tuple[dict | None, list[str], int]:
997
- """Manifest, then tar (extracted while read from disk), tombstones and symlinks.
998
- Returns (the manifest or None when the base could not be restored, failed bucket paths,
999
- files extracted)."""
1000
- pre = self.prefix(rt)
1001
- mpath, tar = rt.sessions_dir / f"{rt.name}.base.json", rt.sessions_dir / f"{rt.name}.base.tar"
1002
- try:
1003
- _, failed = await asyncio.to_thread(download_resilient, self.store,
1004
- [(pre + BASE_JSON, mpath)])
1005
- if failed:
1006
- return None, failed, 0
1007
- base = json.loads(mpath.read_text())
1008
- size = int(base["bytes"])
1009
- if not _fits([(rt.sessions_dir, size + int(base["files"]) * TAR_PER_FILE),
1010
- (rt.workdir, size)]):
1011
- log.error("%s: workdir base not restored: not enough free disk for %d MB "
1012
- "(tar plus files)", rt.name, 2 * size // 2**20)
1013
- return None, [pre + BASE_TAR], 0
1014
- _, failed = await asyncio.to_thread(download_resilient, self.store,
1015
- [(pre + BASE_TAR, tar)])
1016
- if failed:
1017
- return None, failed, 0
1018
- index, bad = await asyncio.to_thread(extract_base_tar, tar, rt.workdir, skip, base)
1019
- except (OSError, ValueError, KeyError, AttributeError, tarfile.TarError) as e:
1020
- log.warning("%s: workdir base not restored: %s", rt.name, _short(e))
1021
- return None, [pre + BASE_TAR], 0
1022
- finally:
1023
- tar.unlink(missing_ok=True)
1024
- await asyncio.to_thread(self._index_path(rt).write_text, json.dumps(index))
1025
- self._base[pre] = base
1026
- if bad:
1027
- log.warning("%s: %d workdir base entries not restored", rt.name, bad)
1028
- return base, [pre + BASE_TAR] if bad else [], len(index)
1029
-
1030
- def _quota(self, rt: AgentRuntime, ws: WorkdirStats) -> None:
1031
- """Above the soft limit: a note in front of the agent's next prompt, and above the hard
1032
- one a `workdir_over_quota` event, each at most hourly. The push itself goes on."""
1033
- w = rt.spec.workdir or WorkdirSpec()
1034
- note, pre, now = quota_note(ws, w), self.prefix(rt), time.monotonic()
1035
- if note is None or now - self._quota_at.get(pre, -QUOTA_NOTE_EVERY) < QUOTA_NOTE_EVERY:
1036
- return
1037
- rt._notes.pop(self._quota_note.pop(pre, None), None) # replace, do not stack
1038
- rt._note(note)
1039
- if note not in rt._notes: # dropped (no turn yet): try again at the next push
1040
- return
1041
- self._quota_at[pre] = now
1042
- self._quota_note[pre] = note
1043
- if over_hard_limit(ws, w):
1044
- rt.emit("workdir_over_quota", {"files": ws.files, "bytes": ws.bytes,
1045
- "top_dirs": [list(t) for t in ws.top_dirs]})
1046
-
1047
- async def restore(self, rt: AgentRuntime) -> RestoreResult:
1048
- try:
1049
- return await self._restore(rt)
1050
- except Exception:
1051
- self.stats.add("errors", "restore_failed")
1052
- raise
1053
-
1054
- async def _restore(self, rt: AgentRuntime) -> RestoreResult:
1055
- pre = self.prefix(rt)
1056
- self._mirror[pre] = False # until this restore completes with every file
1057
- self._restoring.add(pre)
1058
- self.restore_progress[pre] = [0, 0, datetime.now(UTC)]
1059
- try:
1060
- res = await self._restore_files(rt, pre)
1061
- finally:
1062
- self._restoring.discard(pre)
1063
- self.restore_progress.pop(pre, None)
1064
- self._mirror[pre] = not res.failed
1065
- return res
1066
-
1067
- async def _restore_files(self, rt: AgentRuntime, pre: str) -> RestoreResult:
1068
- lister = getattr(self.store, "list_info", None)
1069
- if lister is not None: # raises: the caller starts fresh
1070
- listed = await asyncio.to_thread(lister, pre)
1071
- else:
1072
- listed = [(r, None) for r in await asyncio.to_thread(self.store.list, pre)]
1073
- mtimes = {r: mt for r, mt in listed}
1074
- self._base.pop(pre, None) # known again only if this listing has one
1075
- res = RestoreResult()
1076
- work: list[tuple[str, Path]] = []
1077
- plan: list[tuple[str, Path]] = []
1078
- home = Path(rt.adapter.home)
1079
- n = sum([await asyncio.to_thread(_clean_parts, d) for d in (rt.workdir, rt.sessions_dir)])
1080
- if n:
1081
- log.info("%s: removed %d stray %s file(s)", rt.name, n, PART_SUFFIX)
1082
- skip = workdir_excludes() + ephemeral_excludes(rt.spec)
1083
- for r, _ in listed:
1084
- rel = r[len(pre):]
1085
- area, _, sub = rel.partition("/")
1086
- if rel == "meta.json": # known, the first push after a move need not resend it
1087
- plan.append((r, rt.sessions_dir / f"{rt.name}.meta.json"))
1088
- continue
1089
- if not sub or ".." in Path(sub).parts:
1090
- continue
1091
- if area == "workdir":
1092
- if rt.spec.persist_workdir and not is_excluded(sub, skip):
1093
- work.append((r, rt.workdir / sub))
1094
- elif area == "sessions":
1095
- plan.append((r, rt.sessions_dir / sub))
1096
- elif area == "harness":
1097
- plan.append((r, home / sub))
1098
- prog = self.restore_progress.get(pre)
1099
- if prog is not None:
1100
- prog[1] = len(work) + len(plan)
1101
-
1102
- def progress(n: int) -> None:
1103
- if prog is not None:
1104
- prog[0] += n
1105
-
1106
- if rt.spec.persist_workdir and pre + BASE_JSON in mtimes:
1107
- base, failed, n = await self._restore_base(rt, skip)
1108
- res.workdir, res.failed = n, res.failed + failed
1109
- if prog is not None:
1110
- prog[1] += n
1111
- progress(n)
1112
- if base is not None: # older deltas are already in the tar (or stale)
1113
- work = [(r, p) for r, p in work
1114
- if mtimes.get(r) is None or mtimes[r] > base["created_at"]]
1115
- await asyncio.to_thread(_no_links, rt.workdir, work)
1116
- if work:
1117
- rt.workdir.mkdir(parents=True, exist_ok=True)
1118
- got, failed = await asyncio.to_thread(download_resilient, self.store, work,
1119
- progress=progress)
1120
- res.workdir, res.failed = res.workdir + len(got), res.failed + failed
1121
- await asyncio.to_thread(_set_mtimes, got, mtimes)
1122
- if n := await asyncio.to_thread(apply_modes, rt.workdir):
1123
- log.info("%s: restored the mode of %d file(s)", rt.name, n)
1124
- if plan:
1125
- for _, p in plan:
1126
- _part(p).unlink(missing_ok=True)
1127
- got, failed = await asyncio.to_thread(download_resilient, self.store, plan,
1128
- progress=progress)
1129
- res.failed += failed
1130
- await asyncio.to_thread(_set_mtimes, got, mtimes)
1131
- for r, p in got:
1132
- if r == pre + "meta.json":
1133
- try:
1134
- self._meta[pre] = {k: v for k, v in json.loads(p.read_text()).items()
1135
- if k in ("files", "bytes")}
1136
- except (OSError, ValueError, AttributeError):
1137
- pass
1138
- elif r.startswith(pre + "sessions/"):
1139
- res.sessions += 1
1140
- else:
1141
- res.harness += 1
1142
- self._mark([(p, r) for r, p in got])
1143
- if res.failed:
1144
- self.stats.add("errors", "restore_file_failed", len(res.failed))
1145
- state = f"{pre}sessions/{rt.state_path.name}"
1146
- if state in res.failed:
1147
- log.warning("%s: state file %s not restored; the agent starts a fresh session",
1148
- rt.name, state)
1149
- log.warning("%s: restored workdir=%d sessions=%d harness=%d; %d file(s) skipped "
1150
- "(not found or still failing after retries), e.g. %s", rt.name,
1151
- res.workdir, res.sessions, res.harness, len(res.failed),
1152
- ", ".join(res.failed[:10]))
1153
- else:
1154
- log.info("%s: restored %s", rt.name, res)
1155
- return res
1156
-
1157
-
1158
- def _no_links(workdir: Path, work: list[tuple[str, Path]]) -> None:
1159
- """Deltas over a tar's symlinks: a file or directory replaced a symlink after the base, so
1160
- remove symlinks at a delta's path and its parents, or the download writes through them."""
1161
- for _, p in work:
1162
- parts = p.relative_to(workdir).parts
1163
- for i in range(1, len(parts) + 1):
1164
- q = workdir.joinpath(*parts[:i])
1165
- if q.is_symlink():
1166
- q.unlink()
1167
- break
1168
- if not q.is_dir():
1169
- break
1170
-
1171
-
1172
- def _set_mtimes(files: list[tuple[str, Path]], mtimes: dict[str, float | None]) -> None:
1173
- """Give restored files the bucket's mtime, so the next `sync_up` sees them unchanged."""
1174
- for r, p in files:
1175
- mt = mtimes.get(r)
1176
- if mt is None:
1177
- continue
1178
- try:
1179
- os.utime(p, (mt, mt), follow_symlinks=False)
1180
- except (OSError, NotImplementedError):
1181
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/src/legion/world/__init__.py DELETED
@@ -1,239 +0,0 @@
1
- """`legion.world`: a small base for writing a world in Python (docs/world.md).
2
-
3
- A world is any HTTP server that speaks World API v1 (`legion.world.protocol`); this base is a
4
- convenience, not a requirement. Subclass `World`, mark tool methods with `@tool`, and serve it
5
- with `python -m legion.world serve module:Class` (`legion.world.server`):
6
-
7
- from legion.world import Agent, ToolError, World, tool
8
-
9
- class Counter(World):
10
- name, version = "counter", "0.1.0"
11
-
12
- def __init__(self) -> None:
13
- self.n = 0
14
-
15
- @tool
16
- def bump(self, agent: Agent, by: int = 1) -> dict:
17
- \"\"\"Add `by` to the shared counter and return it.\"\"\"
18
- if by < 1:
19
- raise ToolError("by must be >= 1")
20
- self.n += by
21
- return {"n": self.n, "by": agent.name}
22
-
23
- Tool schemas come from the type hints and docstrings with the tools-folder rules
24
- (legion.tools.loader); a parameter named `agent` (or annotated `Agent`) receives the
25
- caller and is never shown to the model. Override `manifest()` and `call()` to serve tools some
26
- other way. The hooks `on_agent_start`, `on_agent_done` and `on_turn` are sent only when a
27
- subclass overrides them (the manifest lists them in `hooks`).
28
- """
29
-
30
- from __future__ import annotations
31
-
32
- import inspect
33
- import os
34
- import typing
35
- from collections.abc import Callable
36
- from dataclasses import dataclass
37
- from typing import Any
38
-
39
- from legion.world.admin import TYPES, Admin, Knob
40
- from legion.world.protocol import HOOK_EVENTS, STATE_DIR_ENV, WORLD_API
41
-
42
- AGENT_PARAM = "agent"
43
-
44
-
45
- @dataclass(frozen=True)
46
- class Agent:
47
- """Who calls: the legion agent name, its type and swarm, the turn and the request id (as
48
- legion sent them; trust them when the token matched)."""
49
-
50
- name: str
51
- type: str = ""
52
- swarm: str = ""
53
- turn: str = ""
54
- request_id: str = ""
55
-
56
-
57
- class ToolError(Exception):
58
- """Raise from a tool: the agent reads `message` as the tool's error result.
59
- `retry_after_s`: the call cannot succeed before then (a budget, a busy backend); the
60
- server sends it in the error envelope and the worker may hold the tool off until then."""
61
-
62
- def __init__(self, message: str, code: str = "tool_error",
63
- retry_after_s: float | None = None) -> None:
64
- super().__init__(message)
65
- self.code = code
66
- self.message = message
67
- self.retry_after_s = retry_after_s
68
-
69
-
70
- POOLS = ("fast", "slow")
71
-
72
-
73
- def tool(fn: Callable | None = None, *, pool: str = "fast", read_only: bool = False) -> Any:
74
- """Mark a method of a World subclass as a tool: `@tool`, or `@tool(pool="slow",
75
- read_only=True)`. `pool`: the server's thread pool for the call ("slow" for tools that
76
- block for seconds, so they never take the threads of the quick ones). `read_only`: the
77
- tool changes nothing (manifest `annotations.readOnlyHint`; the worker may retry it)."""
78
- if pool not in POOLS:
79
- raise ValueError(f"pool {pool!r} must be one of {POOLS}")
80
-
81
- def mark(f: Callable) -> Callable:
82
- f.__legion_world_tool__ = True # type: ignore[attr-defined]
83
- f.__legion_world_pool__ = pool # type: ignore[attr-defined]
84
- f.__legion_world_read_only__ = read_only # type: ignore[attr-defined]
85
- return f
86
-
87
- return mark if fn is None else mark(fn)
88
-
89
-
90
- def _is_agent(p: inspect.Parameter, hints: dict[str, Any]) -> bool:
91
- hint = hints.get(p.name)
92
- return p.name == AGENT_PARAM or hint is Agent
93
-
94
-
95
- def tool_schema(fn: Callable) -> dict[str, Any]:
96
- """{name, description, parameters} of a tool method (raises legion.tools.loader.ToolsError)."""
97
- from legion.tools.loader import tool_def
98
-
99
- hints = typing.get_type_hints(fn)
100
- sig = inspect.signature(fn)
101
- keep = [p for p in sig.parameters.values() if not _is_agent(p, hints)]
102
-
103
- def shim(*_a: Any, **_k: Any) -> None: ...
104
-
105
- shim.__name__ = fn.__name__
106
- shim.__doc__ = fn.__doc__
107
- shim.__signature__ = sig.replace(parameters=keep) # type: ignore[attr-defined]
108
- shim.__annotations__ = {k: v for k, v in hints.items() if k in {p.name for p in keep}}
109
- d = tool_def(shim, type(getattr(fn, "__self__", fn)).__name__)
110
- return {"name": d.name, "description": d.description, "parameters": d.parameters}
111
-
112
-
113
- class World:
114
- """Base class. Class attributes: `name` (lowercase, `[a-z][a-z0-9-]*`), `version` (any
115
- string; bump it when the tools change, agents are told), `description` (shown to the
116
- agents), `capabilities` (extra names for the manifest)."""
117
-
118
- name: typing.ClassVar[str] = "world"
119
- version: typing.ClassVar[str] = "0.0.0"
120
- description: typing.ClassVar[str] = ""
121
- capabilities: typing.ClassVar[list[str]] = []
122
- # False (default): the server runs one tool call or hook at a time (a global lock), so a
123
- # world needs no locking of its own. True: calls and hooks run concurrently in the
124
- # server's thread pool; the world guards its own state (a slow tool then never holds up
125
- # the hooks or the other agents' calls).
126
- concurrent: typing.ClassVar[bool] = False
127
-
128
- # ------------------------------------------------------------------ tools
129
- def tools(self) -> dict[str, Callable]:
130
- """The bound `@tool` methods, by name (in definition order)."""
131
- found = self.__dict__.get("_legion_tools")
132
- if found is None: # no __init__ needed in subclasses: built on first use
133
- found = {}
134
- for klass in reversed(type(self).__mro__):
135
- for attr, value in vars(klass).items():
136
- if getattr(value, "__legion_world_tool__", False):
137
- found[attr] = getattr(self, attr)
138
- self.__dict__["_legion_tools"] = found
139
- return found
140
-
141
- def hooks(self) -> list[str]:
142
- """The hooks a subclass overrides."""
143
- out = []
144
- for event in HOOK_EVENTS:
145
- meth = f"on_{event}"
146
- if getattr(type(self), meth) is not getattr(World, meth):
147
- out.append(event)
148
- return out
149
-
150
- def manifest(self) -> dict[str, Any]:
151
- """Built on every call (the server serves and dispatches from it), from the class
152
- attributes as they are now; the tool schemas are computed once."""
153
- hooks = self.hooks()
154
- caps = list(dict.fromkeys([*self.capabilities, *(["hooks"] if hooks else [])]))
155
- schemas = self.__dict__.get("_legion_schemas")
156
- if schemas is None:
157
- schemas = [tool_schema(fn) for fn in self.tools().values()]
158
- for t, fn in zip(schemas, self.tools().values(), strict=True):
159
- if getattr(fn, "__legion_world_read_only__", False):
160
- t["annotations"] = {"readOnlyHint": True}
161
- self.__dict__["_legion_schemas"] = schemas
162
- return {"world_api": WORLD_API, "name": self.name, "version": self.version,
163
- "description": self.description, "tools": [dict(t) for t in schemas],
164
- "capabilities": caps, "hooks": hooks}
165
-
166
- def call(self, tool: str, args: dict[str, Any], agent: Agent) -> Any:
167
- """Run `tool` for `agent`; the return value is the result (JSON-serialisable, or a
168
- coroutine the server awaits). Raise ToolError for an error the agent should read;
169
- KeyError for an unknown tool."""
170
- fn = self.tools()[tool]
171
- hints = typing.get_type_hints(fn)
172
- extra = {p.name: agent for p in inspect.signature(fn).parameters.values()
173
- if _is_agent(p, hints)}
174
- return fn(**args, **extra)
175
-
176
- def pool(self, tool: str) -> str:
177
- """The server's thread pool for `tool`: "fast" (default) or "slow" (`@tool(pool=)`)."""
178
- return getattr(self.tools().get(tool), "__legion_world_pool__", "fast")
179
-
180
- def cancellable(self, tool: str) -> bool:
181
- """May the server cancel this tool's `async` work when its caller disconnects (the
182
- HTTP client gave up, e.g. on its own timeout)? Default False: the work always runs to
183
- the end. A world returns True for tools whose work is wasted once nobody reads it."""
184
- return False
185
-
186
- def metrics(self) -> dict[str, float]:
187
- """World-specific numbers for `GET /metrics` (under `world`). Called in a thread,
188
- concurrently with tools, every scrape (about every 30 s): keep it cheap; take your
189
- own lock if you need one. Default: none."""
190
- return {}
191
-
192
- # ------------------------------------------------------------------ admin (docs/world.md)
193
- def state_dir(self) -> str | os.PathLike | None:
194
- """Where `knobs.json` lives (knob values and paused lanes set through the admin API,
195
- read back at the next start). Default: $LEGION_WORLD_STATE_DIR, else None (kept in
196
- memory only). The server may call it before `__init__` ran (to serve /admin while the
197
- world cannot be built): do not rely on attributes `__init__` sets without a fallback."""
198
- return os.environ.get(STATE_DIR_ENV) or None
199
-
200
- @property
201
- def admin(self) -> Admin:
202
- """This world's knobs and paused lanes (the server may install one before __init__)."""
203
- if "_legion_admin" not in self.__dict__:
204
- self.__dict__["_legion_admin"] = Admin(self.state_dir())
205
- return self.__dict__["_legion_admin"]
206
-
207
- def knob(self, name: str, type: type, default: Any, *, min: float | None = None,
208
- max: float | None = None, doc: str = "",
209
- on_change: Callable[[Any], None] | None = None) -> Any:
210
- """Register a runtime knob (int, float, bool or str) and return its current value: the
211
- value set through `PATCH /admin/knobs` if any (it survives restarts), else `default`.
212
- A change calls `on_change(value)` (in a thread; raise to refuse it) and shows in
213
- `self.knobs[name]`."""
214
- if type not in TYPES:
215
- raise ValueError(f"knob {name}: type must be one of int, float, bool, str")
216
- return self.admin.register(Knob(name, type, default, min, max, doc, on_change))
217
-
218
- @property
219
- def knobs(self) -> dict[str, Any]:
220
- """The knobs' current values, by name (live: reflects admin changes)."""
221
- return self.admin.values
222
-
223
- def paused(self, lane: str) -> bool:
224
- """Did an operator pause `lane` (`POST /admin/pause`)? Lanes are names the world
225
- chooses and documents (e.g. "push", "open", "merge")."""
226
- return lane in self.admin.paused
227
-
228
- # ------------------------------------------------------------------ hooks
229
- def on_agent_start(self, agent: Agent) -> None:
230
- """An agent got its first prompt on its worker (again after a relaunch)."""
231
-
232
- def on_agent_done(self, agent: Agent, data: dict[str, Any]) -> None:
233
- """An agent was removed from the swarm (scale down, `legion stop --delete`, `legion-agent remove`)."""
234
-
235
- def on_turn(self, agent: Agent, data: dict[str, Any]) -> None:
236
- """An agent's turn ended: `data` has status, tool_calls, turn."""
237
-
238
-
239
- __all__ = ["Admin", "Agent", "ToolError", "World", "tool", "tool_schema"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/src/legion/world/admin.py DELETED
@@ -1,170 +0,0 @@
1
- """Runtime knobs and lane pauses of a world (docs/world.md, "Admin API").
2
-
3
- A world registers knobs (`World.knob`) and consults pauses (`World.paused`); operators change
4
- them through the server's `/admin` routes. Values set there and the paused lanes are written to
5
- `knobs.json` in the world's state dir (`World.state_dir()`) and read back at the next start, so a
6
- requeued world keeps them; the defaults a world passes (often from its environment) apply only
7
- to knobs nobody set.
8
- """
9
-
10
- from __future__ import annotations
11
-
12
- import json
13
- import logging
14
- import os
15
- import re
16
- import threading
17
- from collections.abc import Callable
18
- from dataclasses import dataclass
19
- from pathlib import Path
20
- from typing import Any
21
-
22
- log = logging.getLogger("legion.world")
23
-
24
- KNOBS_FILE = "knobs.json"
25
- LANE_RE = re.compile(r"^[a-z][a-z0-9_.-]{0,63}$")
26
- TYPES = (int, float, bool, str)
27
-
28
-
29
- @dataclass
30
- class Knob:
31
- name: str
32
- type: type
33
- default: Any
34
- min: float | None = None
35
- max: float | None = None
36
- doc: str = ""
37
- on_change: Callable[[Any], None] | None = None
38
-
39
- def check(self, value: Any) -> Any:
40
- """`value` as this knob's type (raises ValueError)."""
41
- t = self.type
42
- if t is bool or t is str:
43
- ok = isinstance(value, t)
44
- else: # int or float: JSON numbers, not booleans; 2.0 is an int, 2.5 is not
45
- ok = isinstance(value, int | float) and not isinstance(value, bool) and (
46
- t is float or float(value).is_integer())
47
- if not ok:
48
- raise ValueError(f"{self.name}: expected {t.__name__}, got {json.dumps(value)}")
49
- value = t(value)
50
- if self.min is not None and value < self.min:
51
- raise ValueError(f"{self.name}: {value} is below the minimum {self.min:g}")
52
- if self.max is not None and value > self.max:
53
- raise ValueError(f"{self.name}: {value} is above the maximum {self.max:g}")
54
- return value
55
-
56
- def describe(self, value: Any) -> dict[str, Any]:
57
- return {"value": value, "default": self.default, "type": self.type.__name__,
58
- "min": self.min, "max": self.max, "doc": self.doc}
59
-
60
-
61
- class Admin:
62
- """Knobs (name -> value) and paused lanes (lane -> reason), persisted in
63
- `<state dir>/knobs.json` when a state dir is given. Thread-safe."""
64
-
65
- def __init__(self, state_dir: str | os.PathLike | None = None) -> None:
66
- self.path: Path | None = None
67
- self.knobs: dict[str, Knob] = {}
68
- self.values: dict[str, Any] = {}
69
- self.stored: dict[str, Any] = {} # values set through the admin API
70
- self.paused: dict[str, str] = {}
71
- self.lock = threading.RLock()
72
- if state_dir is not None:
73
- self.attach(state_dir)
74
-
75
- def attach(self, state_dir: str | os.PathLike) -> None:
76
- """Read `knobs.json` from `state_dir` and save there from now on. Lanes paused before
77
- (while the world could not be built) stay paused."""
78
- path = Path(state_dir) / KNOBS_FILE
79
- knobs: dict[str, Any] = {}
80
- paused: dict[str, str] = {}
81
- try:
82
- data = json.loads(path.read_text())
83
- if not isinstance(data, dict):
84
- raise ValueError("not a JSON object") # noqa: TRY004 (handled below)
85
- knobs, paused = data.get("knobs") or {}, data.get("paused") or {}
86
- if not isinstance(knobs, dict) or not isinstance(paused, dict) or not all(
87
- isinstance(k, str) and isinstance(v, str) for k, v in paused.items()):
88
- raise ValueError('expected {"knobs": {name: value}, "paused": {lane: reason}}')
89
- except FileNotFoundError:
90
- pass
91
- except (OSError, ValueError) as e: # never park the world over this file
92
- log.warning("%s: unreadable (%s); starting from the defaults", path, e)
93
- knobs, paused = {}, {}
94
- with self.lock:
95
- self.path = path
96
- self.stored = dict(knobs)
97
- self.paused = {**paused, **self.paused}
98
-
99
- def register(self, knob: Knob) -> Any:
100
- with self.lock:
101
- value = knob.check(knob.default)
102
- if knob.name in self.stored:
103
- try:
104
- value = knob.check(self.stored[knob.name])
105
- except ValueError as e:
106
- log.warning("%s: stored value ignored: %s", KNOBS_FILE, e)
107
- self.knobs[knob.name] = knob
108
- self.values[knob.name] = value
109
- return value
110
-
111
- def describe(self) -> dict[str, dict[str, Any]]:
112
- with self.lock:
113
- return {n: k.describe(self.values[n]) for n, k in self.knobs.items()}
114
-
115
- def set(self, updates: dict[str, Any]) -> list[dict[str, Any]]:
116
- """Validate every update, apply them (on_change callbacks included) and save, all or
117
- nothing. Returns [{name, old, new}]; raises ValueError (nothing changed) on a bad value
118
- or a failing on_change (those already applied get on_change(old) back)."""
119
- if not isinstance(updates, dict) or not updates:
120
- raise ValueError("expected {knob: value, ...}")
121
- with self.lock:
122
- unknown = sorted(set(updates) - set(self.knobs))
123
- if unknown:
124
- raise ValueError(f"unknown knob(s) {', '.join(unknown)}; knobs: "
125
- f"{', '.join(self.knobs) or 'none'}")
126
- checked = {n: self.knobs[n].check(v) for n, v in updates.items()}
127
- changes: list[dict[str, Any]] = []
128
- for n, v in checked.items():
129
- try:
130
- if self.knobs[n].on_change is not None:
131
- self.knobs[n].on_change(v)
132
- except Exception as e: # noqa: BLE001 (any refusal rolls the patch back)
133
- for c in reversed(changes):
134
- try:
135
- if self.knobs[c["name"]].on_change is not None:
136
- self.knobs[c["name"]].on_change(c["old"])
137
- except Exception:
138
- log.exception("knob %s: restoring %r failed", c["name"], c["old"])
139
- raise ValueError(f"{n}: the world refused {json.dumps(v)}: {e}") from None
140
- changes.append({"name": n, "old": self.values[n], "new": v})
141
- for c in changes:
142
- self.values[c["name"]] = self.stored[c["name"]] = c["new"]
143
- self._save()
144
- return changes
145
-
146
- def pause(self, lanes: list[str], reason: str = "") -> None:
147
- self._lanes(lanes)
148
- with self.lock:
149
- self.paused.update(dict.fromkeys(lanes, reason))
150
- self._save()
151
-
152
- def resume(self, lanes: list[str]) -> None:
153
- self._lanes(lanes)
154
- with self.lock:
155
- for lane in lanes:
156
- self.paused.pop(lane, None)
157
- self._save()
158
-
159
- @staticmethod
160
- def _lanes(lanes: Any) -> None:
161
- if not isinstance(lanes, list) or not lanes or not all(
162
- isinstance(x, str) and LANE_RE.match(x) for x in lanes):
163
- raise ValueError(f"lanes: expected a list of names matching {LANE_RE.pattern}")
164
-
165
- def _save(self) -> None:
166
- if self.path is None:
167
- return
168
- tmp = self.path.with_suffix(".tmp")
169
- tmp.write_text(json.dumps({"knobs": self.stored, "paused": self.paused}, indent=1))
170
- tmp.replace(self.path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/src/legion/world/lanes.py DELETED
@@ -1,385 +0,0 @@
1
- """External-write lanes for worlds: bounded concurrency, a circuit breaker and a persistent outbox.
2
-
3
- A world that writes to an outside service (a Git host, an API with one token) gives each kind
4
- of write its own lane, so one kind never starves another:
5
-
6
- lanes = Lanes({"push": Lane(slots=1), "merge": Lane(slots=1),
7
- "comment": Lane(slots=1, gap_s=1.0)}, dir=state_dir)
8
- with lanes.hold("push", deadline=time.monotonic() + 20) as slot: # LaneBusy past deadline
9
- ...write...; slot.ok() # or slot.fail("transient") / slot.fail("final")
10
- lanes.outbox("comment", drain=post).put(key=pr, payload=text) # persistent, never drops
11
-
12
- `Lane.slots`, `Lane.gap_s` and `Lane.paused` are plain attributes (`Lane.configure()` changes
13
- the first two and wakes waiters); the breaker never changes them, it only lowers what is
14
- effective while tripped.
15
- """
16
- from __future__ import annotations
17
-
18
- import collections
19
- import contextlib
20
- import json
21
- import logging
22
- import os
23
- import threading
24
- import time
25
- import uuid
26
- from pathlib import Path
27
-
28
- log = logging.getLogger("legion.world.lanes")
29
- POLL_S = 0.25 # longest single wait: notices pause flips, configure() and a test's fake clock
30
-
31
-
32
- class LaneBusy(Exception):
33
- """No slot within the deadline; `reason` is "slots", "gap" or "paused"."""
34
-
35
- def __init__(self, lane: str, reason: str, retry_after_s: float) -> None:
36
- super().__init__(f"lane {lane} busy ({reason}); retry in {retry_after_s:.0f} s")
37
- self.lane, self.reason, self.retry_after_s = lane, reason, retry_after_s
38
-
39
-
40
- class Breaker:
41
- """Transient failures of one lane, or of a group of lanes that trip together."""
42
-
43
- def __init__(self, trip_after: int, trip_window_s: float, quiet_s: float) -> None:
44
- self.trip_after, self.trip_window_s, self.quiet_s = trip_after, trip_window_s, quiet_s
45
- self.name = ""
46
- self.lock = threading.Lock() # a leaf lock: taken with a lane's cond held
47
- self.failures = collections.deque() # clock times of recent transient failures
48
- self.tripped = False
49
-
50
- def failure(self, now: float) -> None:
51
- with self.lock:
52
- self.failures.append(now)
53
- while self.failures and self.failures[0] < now - self.trip_window_s:
54
- self.failures.popleft()
55
- if not self.tripped and len(self.failures) >= self.trip_after:
56
- self.tripped = True
57
- log.warning("lanes %s: tripped after %d transient failures in %.0f s; 1 slot and "
58
- "a gap until %.0f quiet s", self.name, len(self.failures),
59
- self.trip_window_s, self.quiet_s)
60
-
61
- def is_tripped(self, now: float) -> bool:
62
- """Ends a trip after quiet_s without a transient failure."""
63
- with self.lock:
64
- if self.tripped and now - self.failures[-1] >= self.quiet_s:
65
- self.tripped = False
66
- self.failures.clear()
67
- log.warning("lanes %s: recovered after %.0f quiet s", self.name, self.quiet_s)
68
- return self.tripped
69
-
70
-
71
- class Lane:
72
- """One kind of external write.
73
-
74
- Breaker: `trip_after` transient failures within `trip_window_s` trip the lane to
75
- min(slots, 1) slot and at least `trip_gap_s` between writes; after `quiet_s` without a
76
- transient failure it returns to `slots` and `gap_s`. `Lanes(breaker_groups=)` makes lanes
77
- share one breaker (the first lane's trip_after, trip_window_s and quiet_s)."""
78
-
79
- def __init__(self, slots: int = 1, gap_s: float = 0.0, *, trip_after: int = 3,
80
- trip_window_s: float = 900.0, trip_gap_s: float = 5.0, quiet_s: float = 600.0,
81
- retry_after_s: float = 60.0) -> None:
82
- self.slots, self.gap_s, self.paused = slots, gap_s, False
83
- self.breaker = Breaker(trip_after, trip_window_s, quiet_s)
84
- self.trip_gap_s, self.retry_after_s = trip_gap_s, retry_after_s
85
- self.name, self.clock, self.paused_fn = "", time.monotonic, None # set by Lanes
86
- self.cond = threading.Condition()
87
- self.in_flight, self.last_at = 0, float("-inf")
88
- self.stats = {"waits_total": 0, "wait_s_total": 0.0, "ok": 0, "transient": 0, "final": 0}
89
-
90
- def configure(self, slots: int | None = None, gap_s: float | None = None) -> None:
91
- with self.cond:
92
- if slots is not None:
93
- self.slots = slots
94
- if gap_s is not None:
95
- self.gap_s = gap_s
96
- self.cond.notify_all()
97
-
98
- def is_paused(self) -> bool:
99
- return self.paused or bool(self.paused_fn and self.paused_fn(self.name))
100
-
101
- def _effective(self, now):
102
- """(slots, gap_s) in force now (cond held)."""
103
- if self.breaker.is_tripped(now):
104
- return min(self.slots, 1), max(self.gap_s, self.trip_gap_s)
105
- return self.slots, self.gap_s
106
-
107
- def acquire(self, deadline: float | None, pausable: bool = True) -> None:
108
- with self.cond:
109
- start = now = self.clock()
110
- while True:
111
- slots, gap = self._effective(now)
112
- reason = ("paused" if pausable and self.is_paused() else
113
- "slots" if self.in_flight >= slots else
114
- "gap" if now < self.last_at + gap else None)
115
- if reason is None:
116
- break
117
- if deadline is not None and now >= deadline:
118
- self.stats["waits_total"] += 1
119
- self.stats["wait_s_total"] += now - start
120
- retry = (self.last_at + gap - now) if reason == "gap" else self.retry_after_s
121
- raise LaneBusy(self.name, reason, max(1.0, retry))
122
- self.cond.wait(POLL_S if deadline is None else min(POLL_S, deadline - now))
123
- now = self.clock()
124
- if now > start:
125
- self.stats["waits_total"] += 1
126
- self.stats["wait_s_total"] += now - start
127
- self.in_flight += 1
128
- self.last_at = now
129
-
130
- def release(self) -> None:
131
- with self.cond:
132
- self.in_flight -= 1
133
- self.cond.notify_all()
134
-
135
- def report(self, kind: str) -> None:
136
- """Count an outcome: "ok", "transient" (feeds the breaker) or "final"."""
137
- with self.cond:
138
- self.stats[kind] += 1
139
- if kind == "transient":
140
- self.breaker.failure(self.clock())
141
-
142
- def metrics(self) -> dict:
143
- with self.cond:
144
- now = self.clock()
145
- slots, _ = self._effective(now)
146
- return {"slots": self.slots, "effective_slots": slots, "in_flight": self.in_flight,
147
- **self.stats, "tripped": int(self.breaker.is_tripped(now)),
148
- "paused": int(self.is_paused())}
149
-
150
-
151
- class Slot:
152
- """A held slot: report the write's outcome with ok() or fail()."""
153
-
154
- def __init__(self, lane: Lane) -> None:
155
- self.lane = lane
156
-
157
- def ok(self) -> None:
158
- self.lane.report("ok")
159
-
160
- def fail(self, kind: str = "transient") -> None:
161
- if kind not in ("transient", "final"):
162
- raise ValueError("kind must be transient or final")
163
- self.lane.report(kind)
164
-
165
-
166
- class Outbox:
167
- """Writes for one lane that must happen eventually, drained by a background thread.
168
-
169
- `drain(key, payloads)` makes one write of the queued payloads of `key` (more than one when
170
- they piled up: the world joins them; at most max_batch of them and max_chars characters,
171
- or one) and returns "ok", "transient" or "final" (an exception counts as transient), or
172
- "split": retry the key's payloads one per write (e.g. the service refused a joined write). Transient failures retry forever with capped doubling backoff; only
173
- ok and final remove payloads. Stored as JSON lines in `path` (keys: str or int), compacted
174
- on load and when mostly settled."""
175
-
176
- def __init__(self, lanes: Lanes, name: str, path: Path, drain, backoff=(5.0, 600.0),
177
- max_batch: int = 10, max_chars: int = 60_000) -> None:
178
- self.lanes, self.name, self.path, self.drain = lanes, name, path, drain
179
- self.backoff, self.max_batch, self.max_chars = backoff, max_batch, max_chars
180
- self.lock = threading.Lock()
181
- self.entries = {} # key -> {"payloads", "queued_at", "tries", "next_at"} in put order
182
- self.lines = 0 # lines in the file
183
- self._load()
184
- self.stop, self.wake = threading.Event(), threading.Event()
185
- self.thread = threading.Thread(target=self._run, name=f"lane-{name}-outbox", daemon=True)
186
- if drain is not None:
187
- self.thread.start()
188
-
189
- def _entry(self, key, ts):
190
- return self.entries.setdefault(key, {"payloads": [], "queued_at": ts, "tries": 0,
191
- "next_at": 0.0, "batch": self.max_batch})
192
-
193
- def _load(self):
194
- if self.path.exists():
195
- for line in self.path.read_text().splitlines():
196
- try:
197
- op = json.loads(line)
198
- if "put" in op:
199
- self._entry(op["put"], op["ts"])["payloads"].append(op["payload"])
200
- elif op["done"] in self.entries:
201
- entry = self.entries[op["done"]]
202
- del entry["payloads"][:op["n"]]
203
- if not entry["payloads"]:
204
- del self.entries[op["done"]]
205
- except (ValueError, KeyError, TypeError): # a line cut by a crash
206
- log.warning("lane %s outbox: skipped an unreadable line", self.name)
207
- self._compact()
208
-
209
- def _compact(self):
210
- """Rewrite the file with the pending payloads only (lock held, or during __init__)."""
211
- self.path.parent.mkdir(parents=True, exist_ok=True)
212
- tmp = self.path.with_name(f"{self.path.name}.{uuid.uuid4().hex}.tmp")
213
- with open(tmp, "w") as out:
214
- for key, e in self.entries.items():
215
- out.writelines(json.dumps({"put": key, "payload": payload, "ts": e["queued_at"]}) + "\n" for payload in e["payloads"])
216
- out.flush()
217
- os.fsync(out.fileno()) # the data is on disk before the name points at it
218
- os.replace(tmp, self.path)
219
- self.lines = sum(len(e["payloads"]) for e in self.entries.values())
220
-
221
- def _append(self, op):
222
- with open(self.path, "a") as out:
223
- out.write(json.dumps(op) + "\n")
224
- self.lines += 1
225
-
226
- def put(self, key, payload) -> None:
227
- """Queue payload for key; joins payloads of the same key still waiting."""
228
- with self.lock:
229
- ts = self.lanes.wall()
230
- self._append({"put": key, "payload": payload, "ts": ts})
231
- self._entry(key, ts)["payloads"].append(payload)
232
- self.wake.set()
233
-
234
- def depth(self) -> tuple[int, float]:
235
- """(pending payloads, age in seconds of the oldest)."""
236
- with self.lock:
237
- now = self.lanes.wall()
238
- return (sum(len(e["payloads"]) for e in self.entries.values()),
239
- max((now - e["queued_at"] for e in self.entries.values()), default=0.0))
240
-
241
- def _settle(self, key, n, kind):
242
- with self.lock:
243
- entry = self.entries.get(key)
244
- if entry is None:
245
- return
246
- if kind == "split":
247
- entry["batch"] = 1
248
- return
249
- if kind == "transient":
250
- entry["tries"] += 1
251
- delay = min(self.backoff[1], self.backoff[0] * 2 ** (entry["tries"] - 1))
252
- entry["next_at"] = self.lanes.wall() + delay
253
- log.warning("lane %s outbox: write for %r failed; retry %d in %.0f s",
254
- self.name, key, entry["tries"], delay)
255
- return
256
- if kind == "final":
257
- log.warning("lane %s outbox: dropped %d payload(s) for %r: final", self.name, n, key)
258
- del entry["payloads"][:n]
259
- entry["tries"], entry["next_at"] = 0, 0.0
260
- if kind != "ok":
261
- entry["batch"] = 1 # the rest of a refused batch goes one by one
262
- if not entry["payloads"]:
263
- del self.entries[key]
264
- self._append({"done": key, "n": n})
265
- pending = sum(len(e["payloads"]) for e in self.entries.values())
266
- if self.lines > 2 * pending + 1000:
267
- self._compact()
268
-
269
- def _batch(self, key):
270
- """The payloads of key for the next write (lock held): oldest first, within the
271
- entry's batch size and max_chars, at least one."""
272
- entry = self.entries.get(key)
273
- if entry is None:
274
- return []
275
- out, chars = [], 0
276
- for payload in entry["payloads"][:entry["batch"]]:
277
- chars += len(payload if isinstance(payload, str) else json.dumps(payload))
278
- if out and chars > self.max_chars:
279
- break
280
- out.append(payload)
281
- return out
282
-
283
- def _run(self):
284
- while not self.stop.is_set():
285
- try:
286
- self._step()
287
- except Exception: # keep the thread alive: a disk error, a bad drain result
288
- log.exception("lane %s outbox: drain loop failed", self.name)
289
- self.stop.wait(POLL_S)
290
-
291
- def _step(self):
292
- with self.lock:
293
- now = self.lanes.wall()
294
- due = [(e["queued_at"], i, k) for i, (k, e) in enumerate(self.entries.items())
295
- if e["next_at"] <= now]
296
- key = min(due)[2] if due else None
297
- if key is None:
298
- self.wake.wait(POLL_S)
299
- self.wake.clear()
300
- return
301
- try:
302
- with self.lanes.hold(self.name, deadline=self.lanes.clock() + 1.0) as slot:
303
- with self.lock: # taken with the slot held: joins what piled up meanwhile
304
- payloads = self._batch(key)
305
- if not payloads:
306
- return
307
- try:
308
- kind = self.drain(key, payloads) or "ok"
309
- except Exception:
310
- log.exception("lane %s outbox: drain failed", self.name)
311
- kind = "transient"
312
- if kind not in ("ok", "transient", "final", "split"):
313
- raise ValueError(f"drain returned {kind!r}")
314
- if kind == "split" and len(payloads) == 1:
315
- kind = "transient"
316
- if kind == "ok":
317
- slot.ok()
318
- elif kind != "split":
319
- slot.fail(kind)
320
- except LaneBusy:
321
- self.stop.wait(POLL_S)
322
- return
323
- self._settle(key, len(payloads), kind)
324
-
325
- def close(self, timeout: float = 5.0) -> None:
326
- self.stop.set()
327
- self.wake.set()
328
- if self.thread.is_alive() and self.thread is not threading.current_thread():
329
- self.thread.join(timeout)
330
-
331
-
332
- class Lanes:
333
- """Named lanes sharing a clock, an optional `paused(name)` callback and a state dir for
334
- outboxes (`<dir>/outbox-<name>.jsonl`). `breaker_groups`: tuples of lane names that share
335
- one breaker (writes that fail together, e.g. two kinds that move the same refs)."""
336
-
337
- def __init__(self, lanes: dict[str, Lane], dir: str | Path | None = None,
338
- clock=time.monotonic, wall=time.time, paused=None,
339
- breaker_groups: list[tuple[str, ...]] = ()) -> None:
340
- self.lanes, self.dir, self.clock, self.wall = lanes, Path(dir) if dir else None, clock, wall
341
- self.outboxes: dict[str, Outbox] = {}
342
- for name, lane in lanes.items():
343
- lane.name, lane.clock, lane.paused_fn = name, clock, paused
344
- lane.breaker.name = name
345
- for group in breaker_groups: # a transient failure in any of them trips them all
346
- shared = lanes[group[0]].breaker
347
- shared.name = "+".join(group)
348
- for name in group[1:]:
349
- lanes[name].breaker = shared
350
-
351
- def __getitem__(self, name: str) -> Lane:
352
- return self.lanes[name]
353
-
354
- @contextlib.contextmanager
355
- def hold(self, name: str, deadline: float | None = None, pausable: bool = True):
356
- """Hold a slot of lane `name`, waiting until `deadline` (on `clock`; None: no limit);
357
- raises LaneBusy. `pausable=False` ignores the pause (e.g. closing what was opened)."""
358
- lane = self.lanes[name]
359
- lane.acquire(deadline, pausable)
360
- try:
361
- yield Slot(lane)
362
- finally:
363
- lane.release()
364
-
365
- def outbox(self, name: str, drain=None, **kwargs) -> Outbox:
366
- """The lane's outbox; the first call with `drain` starts its drainer thread."""
367
- if name not in self.outboxes:
368
- if self.dir is None:
369
- raise ValueError("Lanes(dir=...) is needed for an outbox")
370
- self.outboxes[name] = Outbox(self, name, self.dir / f"outbox-{name}.jsonl", drain, **kwargs)
371
- return self.outboxes[name]
372
-
373
- def metrics(self) -> dict[str, dict]:
374
- out = {}
375
- for name, lane in self.lanes.items():
376
- box = self.outboxes.get(name)
377
- depth, age = box.depth() if box else (0, 0.0)
378
- out[name] = {**lane.metrics(), "outbox_depth": depth, "outbox_oldest_age_s": age}
379
- return out
380
-
381
- def close(self, timeout: float = 5.0) -> None:
382
- """Stop the drainer threads; what is queued stays on disk for the next start."""
383
- end = time.monotonic() + timeout
384
- for box in self.outboxes.values():
385
- box.close(max(0.0, end - time.monotonic()))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/src/legion/world/protocol.py DELETED
@@ -1,208 +0,0 @@
1
- """World API v1 (docs/world.md): the names both sides agree on and the manifest model.
2
-
3
- A world is any HTTP server that answers two routes with a shared secret:
4
-
5
- GET /manifest -> {"world_api": "v1", "name", "version", "tools": [...], ...}
6
- POST /tools/<name> {"args": {...}} -> {"ok": true, "result": ...}
7
- | {"ok": false, "error": {"code", "message"}}
8
- POST /hooks {"event", "agent", "type", "swarm", "data"} (optional)
9
-
10
- Every request carries `X-World-Token` (the secret, or on `/manifest` and tool calls the calling
11
- agent's own `agent_token`); a tool call also names the calling agent
12
- (`X-Legion-Agent`, `X-Legion-Type`, `X-Legion-Swarm`, `X-Legion-Turn`, `X-Request-Id`). This module
13
- is pydantic-only, so the worker, the controller and a world written with `legion.world` share it.
14
- """
15
-
16
- from __future__ import annotations
17
-
18
- import hashlib
19
- import hmac
20
- import re
21
- from typing import Any
22
-
23
- from pydantic import BaseModel, Field, field_validator, model_validator
24
-
25
- WORLD_API = "v1"
26
-
27
- TOKEN_HEADER = "X-World-Token"
28
- AGENT_HEADER = "X-Legion-Agent"
29
- TYPE_HEADER = "X-Legion-Type"
30
- SWARM_HEADER = "X-Legion-Swarm"
31
- TURN_HEADER = "X-Legion-Turn"
32
- REQUEST_HEADER = "X-Request-Id"
33
-
34
- # Environment of a world legion starts (and of `python -m legion.world serve`), and of the workers.
35
- TOKEN_ENV = "LEGION_WORLD_TOKEN"
36
- PORT_ENV = "LEGION_WORLD_PORT"
37
- HOST_ENV = "LEGION_WORLD_HOST"
38
- SWARM_ENV = "LEGION_SWARM"
39
- STATE_DIR_ENV = "LEGION_WORLD_STATE_DIR" # knobs.json (World.state_dir)
40
- # The /admin secret of a world (docs/world.md, "Admin API"); never derived from the world
41
- # secret, which every worker holds. Unset: /admin answers 403.
42
- ADMIN_TOKEN_ENV = "LEGION_WORLD_ADMIN_TOKEN"
43
-
44
- # Hooks legion sends to a world that lists them in its manifest's `hooks` (POST /hooks).
45
- HOOK_EVENTS = ("agent_start", "agent_done", "turn")
46
-
47
- WORLD_NAME_RE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
48
- TOOL_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
49
-
50
-
51
- class WorkspaceUpload(BaseModel):
52
- """`x-legion-workspace` on a tool (worlds with workspace-upload-v1): the worker uploads the
53
- local clone named by argument `arg` (`default` when absent), unless the value is in `skip`
54
- or starts with `skip_prefix`."""
55
-
56
- arg: str
57
- default: str | None = None
58
- skip: list[str] = Field(default_factory=list)
59
- skip_prefix: str | None = None
60
-
61
-
62
- class WorldTool(BaseModel):
63
- """One tool: a Chat Completions function (`parameters` is a JSON schema of type object),
64
- plus optional legion metadata: `x-legion-workspace` and `x-legion-timeout_s` (the least HTTP
65
- timeout the worker gives this tool's calls), and `annotations.readOnlyHint` (the tool
66
- changes nothing: the worker may retry it once)."""
67
-
68
- model_config = {"extra": "ignore", "populate_by_name": True}
69
-
70
- name: str
71
- description: str = ""
72
- parameters: dict[str, Any] = Field(default_factory=lambda: {"type": "object", "properties": {}})
73
- workspace: WorkspaceUpload | None = Field(None, alias="x-legion-workspace")
74
- timeout_s: float | None = Field(None, alias="x-legion-timeout_s", gt=0)
75
- annotations: dict[str, Any] = Field(default_factory=dict) # MCP-style, e.g. readOnlyHint
76
-
77
- @property
78
- def read_only(self) -> bool:
79
- return self.annotations.get("readOnlyHint") is True
80
-
81
- @model_validator(mode="before")
82
- @classmethod
83
- def _old_keys(cls, v: Any) -> Any:
84
- # the keys' former prefix: ignored as unknown otherwise, and the upload/timeout silently off
85
- old = sorted(k for k in v if isinstance(k, str) and k.startswith("x-flock-")) if isinstance(v, dict) else []
86
- if old:
87
- raise ValueError(f"{', '.join(old)}: renamed to x-legion-*")
88
- return v
89
-
90
- @field_validator("name")
91
- @classmethod
92
- def _name(cls, v: str) -> str:
93
- if not TOOL_NAME_RE.match(v):
94
- raise ValueError(f"tool name {v!r} must match {TOOL_NAME_RE.pattern}")
95
- return v
96
-
97
- @field_validator("parameters")
98
- @classmethod
99
- def _params(cls, v: dict[str, Any]) -> dict[str, Any]:
100
- if v.get("type", "object") != "object":
101
- raise ValueError("parameters must be a JSON schema of type object")
102
- props = v.get("properties", {})
103
- if not isinstance(props, dict):
104
- raise ValueError("parameters.properties must be an object") # noqa: TRY004 (pydantic)
105
- return {**v, "type": "object", "properties": props}
106
-
107
-
108
- class WorldManifest(BaseModel):
109
- """What `GET /manifest` returns. Unknown fields are ignored (changes within v1 are
110
- additive); unknown capabilities and hooks are kept but never used."""
111
-
112
- model_config = {"extra": "ignore"}
113
-
114
- world_api: str
115
- name: str
116
- version: str
117
- description: str = "" # shown to the agents above the tool list
118
- tools: list[WorldTool] = Field(default_factory=list)
119
- capabilities: list[str] = Field(default_factory=list)
120
- hooks: list[str] = Field(default_factory=list) # which of HOOK_EVENTS to send
121
-
122
- @field_validator("world_api")
123
- @classmethod
124
- def _api(cls, v: str) -> str:
125
- if v != WORLD_API:
126
- raise ValueError(f"world_api {v!r} is not supported (this legion speaks {WORLD_API!r})")
127
- return v
128
-
129
- @field_validator("name")
130
- @classmethod
131
- def _name(cls, v: str) -> str:
132
- if not WORLD_NAME_RE.match(v):
133
- raise ValueError(f"name {v!r} must match {WORLD_NAME_RE.pattern}")
134
- return v
135
-
136
- @field_validator("version")
137
- @classmethod
138
- def _version(cls, v: str) -> str:
139
- if not v.strip():
140
- raise ValueError("version must not be empty")
141
- return v
142
-
143
- @field_validator("tools")
144
- @classmethod
145
- def _unique(cls, v: list[WorldTool]) -> list[WorldTool]:
146
- seen: set[str] = set()
147
- for t in v:
148
- if t.name in seen:
149
- raise ValueError(f"tool {t.name!r} is listed twice")
150
- seen.add(t.name)
151
- return v
152
-
153
- def names(self) -> list[str]:
154
- return [t.name for t in self.tools]
155
-
156
- def get(self, name: str) -> WorldTool | None:
157
- return next((t for t in self.tools if t.name == name), None)
158
-
159
-
160
- def agent_token(secret: str, agent: str) -> str:
161
- """One agent's own world token: a world accepts it instead of its secret on `/manifest` and
162
- tool calls whose `X-Legion-Agent` is `agent`, so a token in an agent's hands acts only as it."""
163
- return hmac.new(secret.encode(), f"legion-world-agent\0{agent}".encode(),
164
- hashlib.sha256).hexdigest()
165
-
166
-
167
- def credential_id(token: str, origin: str) -> str:
168
- """Names a (secret, origin) pair without revealing the secret: the controller writes it
169
- into the world block, a worker compares it with its own secret's before sending it."""
170
- return hmac.new(token.encode(), f"legion-world-credential\0{origin}".encode(),
171
- hashlib.sha256).hexdigest()[:32]
172
-
173
-
174
- WORLD_HOST_VAR = "${WORLD_HOST}" # in world.url: the host is read from LEGION_WORLD_HOST_FILE
175
- WORLD_HOST_FILE_ENV = "LEGION_WORLD_HOST_FILE"
176
- DEFAULT_PORT = 7860 # what an old host-only host file means (the url's own port)
177
-
178
-
179
- def fill_host(url: str, var: str, host: str) -> str:
180
- """`url` with `var` (`${WORLD_HOST}`, `${CTL_HOST}`) replaced by a host file's first word:
181
- `host:port` (the jobs bind a free port) also replaces the url's port after `var`; an old
182
- host-only file keeps the url's port (DEFAULT_PORT in every spec)."""
183
- return re.sub(re.escape(var) + (r"(:\d+)?" if ":" in host else ""), lambda _: host, url)
184
-
185
-
186
- def origin_matches(origin: str, endpoint: str) -> bool:
187
- """A secret bound to `origin` may go to `endpoint`: the same URL, or, for a world.url with
188
- ${WORLD_HOST} (a world whose host moves, docs/slurm.md), what fill_host can make of it (any host, or host:port in place of the url's port)."""
189
- if origin == endpoint:
190
- return True
191
- if WORLD_HOST_VAR not in origin:
192
- return False
193
- pre, _, post = origin.partition(WORLD_HOST_VAR)
194
- host, port = r"[A-Za-z0-9.-]+", r":[0-9]+"
195
- rest = re.sub(r"^:\d+", "", post) # a host:port file replaces this port
196
- return bool(re.fullmatch(re.escape(pre) + host + "(?:" + re.escape(post) + "|" + port + re.escape(rest) + ")", endpoint))
197
-
198
-
199
- def manifest_error(exc: Exception) -> str:
200
- """One line from a pydantic ValidationError (or anything else)."""
201
- errors = getattr(exc, "errors", None)
202
- if callable(errors):
203
- parts = []
204
- for e in errors()[:3]:
205
- where = ".".join(str(x) for x in e.get("loc", ()))
206
- parts.append(f"{where + ': ' if where else ''}{e.get('msg')}")
207
- return "; ".join(parts)
208
- return str(exc)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/src/legion/world/server.py DELETED
@@ -1,698 +0,0 @@
1
- """Serve a `legion.world.World` over HTTP (World API v1, docs/world.md).
2
-
3
- `python -m legion.world serve module:Class` imports `module` from the current directory, instantiates
4
- `Class` (or takes a World instance named so) and serves it with uvicorn on
5
- `$LEGION_WORLD_HOST:$LEGION_WORLD_PORT` (default 127.0.0.1:8765), requiring `X-World-Token` to
6
- equal `$LEGION_WORLD_TOKEN`. Synchronous tools and hooks run one at a time (a lock), so a world
7
- needs no locking of its own, unless it is `concurrent`; they run in two thread pools, "fast"
8
- and "slow" (`@tool(pool=)`), so slow tools never starve the fast ones; `async def` tools run on the event loop. An `async` tool the world marks `cancellable(name)` is
9
- cancelled when its caller disconnects (checked every second), so a call nobody waits for any
10
- more stops instead of running to the end.
11
- `GET /metrics` (same token) reports calls, errors, latencies and bytes per tool over the last
12
- 5 minutes, the pools' queues, event-loop lag, RSS, CPU and the world's own `metrics()` (JSON, or
13
- Prometheus text for `Accept: text/plain`).
14
- Parked mode: `serve` binds the port first and builds the world in a background thread, retrying
15
- with backoff while that raises; meanwhile `/manifest`, tools and hooks answer 503 (`parked`).
16
- `GET /healthz` (no token) says "ready" or "parked". `/admin/*` (the admin secret, never the world
17
- token) reads and sets the world's knobs and pauses its lanes (`legion.world.admin`).
18
- Needs the `controller` extra (FastAPI, uvicorn).
19
- """
20
-
21
- from __future__ import annotations
22
-
23
- import asyncio
24
- import contextlib
25
- import hmac
26
- import importlib
27
- import inspect
28
- import json
29
- import logging
30
- import math
31
- import os
32
- import re
33
- import resource
34
- import sys
35
- import threading
36
- import time
37
- import uuid
38
- from collections import Counter, deque
39
- from collections.abc import Callable
40
- from typing import Any
41
-
42
- from anyio import CapacityLimiter, to_thread
43
- from fastapi import FastAPI, Request
44
- from fastapi.responses import JSONResponse, PlainTextResponse, Response
45
- from starlette.datastructures import Headers
46
-
47
- from legion.tools.loader import check_args
48
- from legion.world import Admin, Agent, ToolError, World
49
- from legion.world.protocol import (
50
- ADMIN_TOKEN_ENV,
51
- AGENT_HEADER,
52
- HOOK_EVENTS,
53
- HOST_ENV,
54
- PORT_ENV,
55
- REQUEST_HEADER,
56
- SWARM_HEADER,
57
- TOKEN_ENV,
58
- TOKEN_HEADER,
59
- TURN_HEADER,
60
- TYPE_HEADER,
61
- agent_token,
62
- )
63
- from legion.world.workspace import MAX_BYTES
64
-
65
- log = logging.getLogger("legion.world")
66
-
67
- DEFAULT_PORT = 8765
68
- FAST_THREADS = 40 # tools that answer in well under a second, and hooks
69
- SLOW_THREADS = 64 # tools that block for seconds or minutes (`@tool(pool="slow")`)
70
- # Admission control (docs/world.md): a tool call is refused with 429 when the fast pool's oldest
71
- # queued call waited longer than this, or the slow pool holds its threads plus this many queued.
72
- FAST_MAX_WAIT_ENV, FAST_MAX_WAIT_S = "LEGION_WORLD_FAST_MAX_WAIT_S", 2.0
73
- SLOW_QUEUE_ENV, SLOW_QUEUE = "LEGION_WORLD_SLOW_QUEUE", 8
74
- RETRY_AFTER_ENV, RETRY_AFTER_S = "LEGION_WORLD_RETRY_AFTER_S", 30.0
75
- REFUSAL_LOG_EVERY_S = 10.0 # at most one WARNING per pool this often about refused calls
76
- # Parked mode: a world whose construction raises is built again after 30 s, doubling to 10 min.
77
- PARK_FIRST_S, PARK_CAP_S = 30.0, 600.0
78
- ADMIN_MAX_BYTES = 64 << 10 # an /admin request body
79
-
80
-
81
- WINDOW_S = 300.0 # /metrics: calls, latencies, bytes and queue waits over the last 5 minutes
82
- MAX_SAMPLES = 20_000 # per log, besides the window: bounded when nobody scrapes /metrics
83
-
84
-
85
- class _Metrics:
86
- """What GET /metrics reports. `call` and `lag` run on the event loop; `waited` runs in a
87
- pool thread (a deque append is atomic)."""
88
-
89
- def __init__(self, clock: Any = time.monotonic) -> None:
90
- self.clock = clock
91
- self.started = clock()
92
- self.calls: dict[str, deque] = {} # tool -> (t, latency_s or None if refused, code, in, out)
93
- self.totals: dict[str, list[int]] = {} # tool -> [calls, errors] since start
94
- self.waits: dict[str, deque] = {p: deque(maxlen=MAX_SAMPLES) for p in ("fast", "slow")} # pool -> (t, wait_s)
95
- self.lags: deque = deque(maxlen=MAX_SAMPLES) # (t, event-loop lag in s)
96
- self.overloaded = 0
97
- self.refused = {"fast": 0, "slow": 0} # pool -> calls refused with 429 since start
98
- self.uploads = {"v1": 0, "v2": 0} # workspace uploads received, by format
99
- self.cpu_mark = (time.monotonic(), sum(os.times()[:2]))
100
-
101
- def _trim(self, q: deque, now: float) -> deque:
102
- while q and q[0][0] < now - WINDOW_S:
103
- q.popleft()
104
- return q
105
-
106
- def call(self, tool: str, latency: float | None, code: str | None, n_in: int, n_out: int) -> None:
107
- now = self.clock()
108
- self._trim(self.calls.setdefault(tool, deque(maxlen=MAX_SAMPLES)), now).append((now, latency, code, n_in, n_out))
109
- totals = self.totals.setdefault(tool, [0, 0])
110
- totals[0] += 1
111
- totals[1] += code is not None
112
-
113
- def waited(self, pool: str, wait: float) -> None:
114
- self.waits[pool].append((self.clock(), wait))
115
-
116
- def lag(self, lag: float) -> None:
117
- now = self.clock()
118
- self._trim(self.lags, now).append((now, lag))
119
-
120
- async def sample_lag(self) -> None:
121
- """Every second: how late a 1 s sleep wakes up (the event loop's lag)."""
122
- loop = asyncio.get_running_loop()
123
- while True:
124
- t = loop.time()
125
- await asyncio.sleep(1)
126
- self.lag(max(0.0, loop.time() - t - 1))
127
-
128
- def snapshot(self, pools: dict[str, dict[str, float]]) -> dict[str, Any]:
129
- now = self.clock()
130
- tools = {}
131
- for name, q in self.calls.items():
132
- rows = list(self._trim(q, now))
133
- lat = sorted(r[1] for r in rows if r[1] is not None)
134
- tools[name] = {
135
- "calls": len(rows), "errors_by_code": dict(Counter(r[2] for r in rows if r[2])),
136
- "latency_p50_s": _pct(lat, 0.5), "latency_p95_s": _pct(lat, 0.95),
137
- "latency_max_s": lat[-1] if lat else 0.0,
138
- "bytes_in": sum(r[3] for r in rows), "bytes_out": sum(r[4] for r in rows),
139
- "calls_total": self.totals[name][0], "errors_total": self.totals[name][1]}
140
- for pool, stats in pools.items():
141
- waits = sorted(w for _, w in list(self._trim(self.waits[pool], now)))
142
- stats.update(queue_wait_p95_s=_pct(waits, 0.95),
143
- overloaded_429_total=self.refused[pool],
144
- queue_wait_max_s=max(waits[-1] if waits else 0.0, stats["queue_wait_oldest_s"]))
145
- lags = [g for _, g in self._trim(self.lags, now)]
146
- wall, cpu = time.monotonic(), sum(os.times()[:2])
147
- cpu_pct = 100 * (cpu - self.cpu_mark[1]) / max(1e-9, wall - self.cpu_mark[0])
148
- self.cpu_mark = (wall, cpu)
149
- return {"uptime_s": now - self.started, "rss_mb": _rss_mb(), "cpu_pct": cpu_pct,
150
- "loop_lag_s": lags[-1] if lags else 0.0, "loop_lag_max_s": max(lags, default=0.0),
151
- "overloaded_429_total": self.overloaded, "upload_v1_total": self.uploads["v1"],
152
- "upload_v2_total": self.uploads["v2"], "window_s": WINDOW_S,
153
- "tools": tools, "pools": pools}
154
-
155
-
156
- def _finite(v: Any) -> bool:
157
- """A number JSON and Prometheus text can carry (no bool, NaN or inf)."""
158
- return isinstance(v, int | float) and not isinstance(v, bool) and math.isfinite(v)
159
-
160
-
161
- def _pct(values: list[float], q: float) -> float:
162
- """Nearest-rank percentile of sorted `values` (0.0 when empty)."""
163
- return values[max(0, math.ceil(q * len(values)) - 1)] if values else 0.0
164
-
165
-
166
- def _rss_mb() -> float:
167
- try:
168
- with open("/proc/self/statm") as f:
169
- return int(f.read().split()[1]) * os.sysconf("SC_PAGE_SIZE") / 2**20
170
- except (OSError, ValueError, IndexError): # not Linux: the peak instead
171
- return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024
172
-
173
-
174
- def _lv(v: Any) -> str: # Prometheus label-value escaping
175
- return '"' + str(v).replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"'
176
-
177
-
178
- def _prometheus(m: dict[str, Any]) -> str:
179
- """The /metrics JSON as Prometheus text exposition (untyped samples), lines grouped per metric name."""
180
- groups: dict[str, list[str]] = {}
181
-
182
- def add(metric: str, labels: str, v: Any) -> None:
183
- groups.setdefault(metric, []).append(f"{metric}{labels} {v}")
184
-
185
- for key, value in m.items():
186
- if key in ("tools", "pools"):
187
- label = key[:-1]
188
- for name, stats in value.items():
189
- for k, v in stats.items():
190
- if k == "errors_by_code":
191
- for c, n in v.items():
192
- add("legion_world_tool_errors", f"{{tool={_lv(name)},code={_lv(c)}}}", n)
193
- else:
194
- add(f"legion_world_{label}_{k}", f"{{{label}={_lv(name)}}}", v)
195
- elif key == "world":
196
- for k, v in value.items():
197
- add(f"legion_world_world_{re.sub(r'[^A-Za-z0-9_]', '_', k)}", "", v)
198
- else:
199
- add(f"legion_world_{key}", "", value)
200
- return "\n".join(l for g in groups.values() for l in g) + "\n"
201
-
202
-
203
- _SECRET_NAME = re.compile(r"TOKEN|SECRET|PASSWORD|INVITE|API_KEY|_KEY$", re.IGNORECASE)
204
-
205
-
206
- def _secret_values(env=None) -> list[str]:
207
- """Values of the world process's secret-looking variables (8+ chars), longest first."""
208
- env = os.environ if env is None else env
209
- return sorted({v for k, v in env.items() if _SECRET_NAME.search(k) and len(v) >= 8},
210
- key=len, reverse=True)
211
-
212
-
213
- def redact(value: Any, secrets: list[str] | None = None) -> Any:
214
- """`value` (JSON-able) with every secret value replaced by "[redacted]"."""
215
- secrets = _secret_values() if secrets is None else secrets
216
- if not secrets:
217
- return value
218
- text = json.dumps(value, default=str)
219
- if not any(s in text for s in secrets):
220
- return value
221
- for s in secrets:
222
- text = text.replace(json.dumps(s)[1:-1], "[redacted]")
223
- return json.loads(text)
224
-
225
-
226
- def _ok_body(result: Any) -> bytes:
227
- """The success envelope for `result`, serialized and redacted (in a worker thread)."""
228
- return json.dumps({"ok": True, "result": redact(json.loads(json.dumps(result, default=str)))}
229
- ).encode()
230
-
231
-
232
- def _error(code: str, message: str, status: int = 200,
233
- retry_after_s: float | None = None) -> JSONResponse:
234
- error: dict[str, Any] = {"code": code, "message": message}
235
- if retry_after_s is not None:
236
- error["retry_after_s"] = retry_after_s
237
- return JSONResponse({"ok": False, "error": error}, status_code=status)
238
-
239
-
240
- class _Auth:
241
- """`X-World-Token`: the world secret on every route but `/healthz` (none) and `/admin/*`
242
- (the admin secret), or on `/manifest` and `/tools/*` the caller's `agent_token` for its
243
- `X-Legion-Agent`. An empty world secret: open; an empty admin secret: /admin is 403."""
244
-
245
- def __init__(self, app: Any, token: str, admin: str) -> None:
246
- self.app, self.token, self.admin = app, token, admin
247
-
248
- async def __call__(self, scope: dict, receive: Any, send: Any) -> None:
249
- if scope["type"] == "http":
250
- path = scope["path"]
251
- admin = path == "/admin" or path.startswith("/admin/")
252
- need = "" if path == "/healthz" else self.admin if admin else self.token
253
- if admin and not need:
254
- await _error("forbidden", f"no admin secret: set {ADMIN_TOKEN_ENV} on the world",
255
- 403)(scope, receive, send)
256
- return
257
- headers = Headers(scope=scope)
258
- got, agent = headers.get(TOKEN_HEADER, ""), headers.get(AGENT_HEADER, "")
259
- own = bool(agent) and (path == "/manifest" or path.startswith("/tools/")) \
260
- and hmac.compare_digest(got, agent_token(need, agent))
261
- if need and not (hmac.compare_digest(got, need) or own):
262
- await _error("unauthorized", f"missing or wrong {TOKEN_HEADER}", 401)(
263
- scope, receive, send)
264
- return
265
- await self.app(scope, receive, send)
266
-
267
-
268
- DISCONNECT_POLL_S = 1.0
269
-
270
-
271
- class _Gone(Exception):
272
- """The caller disconnected before the tool finished."""
273
-
274
-
275
- async def _unless_gone(aw: Any, request: Request) -> Any:
276
- """Await `aw`, cancelling it if the client disconnects first (raises _Gone)."""
277
- task = asyncio.ensure_future(aw)
278
- try:
279
- while True:
280
- done, _ = await asyncio.wait({task}, timeout=DISCONNECT_POLL_S)
281
- if done:
282
- return task.result()
283
- if await request.is_disconnected():
284
- task.cancel()
285
- await asyncio.wait({task})
286
- raise _Gone
287
- except asyncio.CancelledError:
288
- task.cancel() # this handler cancelled: the tool's work goes too
289
- raise
290
-
291
-
292
- def _agent(headers: Any) -> Agent:
293
- return Agent(name=headers.get(AGENT_HEADER, ""), type=headers.get(TYPE_HEADER, ""),
294
- swarm=headers.get(SWARM_HEADER, ""), turn=headers.get(TURN_HEADER, ""),
295
- request_id=headers.get(REQUEST_HEADER, ""))
296
-
297
-
298
- def create_app(world: World | Callable[[Admin], World], token: str | None) -> FastAPI:
299
- """The ASGI app for `world`. `token` None or "": no authentication (tests, a trusted
300
- network); otherwise every route needs `X-World-Token: <token>`. `/admin/*` needs the admin
301
- secret, $LEGION_WORLD_ADMIN_TOKEN (unset: 403).
302
- `world` may be a builder, `build(admin) -> World`: the app starts parked and builds the
303
- world in a thread once it runs, again with backoff while that raises."""
304
- metrics = _Metrics()
305
- build = None if isinstance(world, World) else world
306
- world = world if isinstance(world, World) else None
307
- parked_admin = Admin() # /admin while no world is built; the builder hands it to the world
308
- park: dict[str, Any] = {"error": "the world is starting", "attempt": 0, "retry_at": 0.0}
309
- stop = threading.Event()
310
-
311
- def builder() -> None:
312
- nonlocal world
313
- delay = PARK_FIRST_S
314
- while not stop.is_set():
315
- park["attempt"] += 1
316
- try:
317
- built = build(parked_admin)
318
- except BaseException as e: # SystemExit too: a parked error, not a dead thread
319
- log.exception("world: construction failed (attempt %d); retrying in %g s",
320
- park["attempt"], delay)
321
- line = (f"{type(e).__name__}: {e}".strip().splitlines() or [""])[0][:300]
322
- park.update(error=redact(line), retry_at=time.monotonic() + delay)
323
- if stop.wait(delay):
324
- return
325
- delay = min(delay * 2, PARK_CAP_S)
326
- continue
327
- world = built
328
- log.info("world %s %s: ready after %d attempt(s)", built.name, built.version,
329
- park["attempt"])
330
- return
331
-
332
- @contextlib.asynccontextmanager
333
- async def lifespan(_app: FastAPI) -> Any:
334
- task = asyncio.create_task(metrics.sample_lag())
335
- if build is not None:
336
- threading.Thread(target=builder, name="world-build", daemon=True).start()
337
- try:
338
- yield
339
- finally:
340
- stop.set()
341
- task.cancel()
342
-
343
- def admin() -> Admin:
344
- return world.admin if world is not None else parked_admin
345
-
346
- def parked() -> Response | None:
347
- """503 while the world is not built (parked mode), else None."""
348
- if world is not None:
349
- return None
350
- left = max(0.0, park["retry_at"] - time.monotonic())
351
- resp = JSONResponse({"ok": False, "parked": True, "error": park["error"],
352
- "attempt": park["attempt"], "next_retry_s": math.ceil(left)}, 503)
353
- resp.headers["Retry-After"] = str(max(1, math.ceil(left)))
354
- return resp
355
-
356
- app = FastAPI(title="world", docs_url=None, redoc_url=None, openapi_url=None,
357
- lifespan=lifespan)
358
- lock = threading.Lock()
359
- # Separate thread budgets: a slow tool (minutes) never takes a fast tool's or a hook's thread.
360
- limiters = {"fast": CapacityLimiter(FAST_THREADS), "slow": CapacityLimiter(SLOW_THREADS)}
361
- queued: dict[str, dict[object, float]] = {p: {} for p in limiters} # pool -> call -> since
362
- queued_lock = threading.Lock()
363
-
364
- async def run(pool: str, fn, *args: Any) -> Any:
365
- pool = pool if pool in limiters else "fast"
366
- key, since = object(), metrics.clock()
367
- with queued_lock:
368
- queued[pool][key] = since
369
-
370
- def started(*a: Any) -> Any: # in the pool thread: the call left the queue
371
- with queued_lock:
372
- queued[pool].pop(key, None)
373
- metrics.waited(pool, metrics.clock() - since)
374
- return locked(fn, *a)
375
-
376
- try:
377
- return await to_thread.run_sync(started, *args, limiter=limiters[pool])
378
- finally: # cancelled while queued
379
- with queued_lock:
380
- queued[pool].pop(key, None)
381
-
382
- fast_max_wait = float(os.environ.get(FAST_MAX_WAIT_ENV) or FAST_MAX_WAIT_S)
383
- slow_queue = int(os.environ.get(SLOW_QUEUE_ENV) or SLOW_QUEUE)
384
- retry_after = float(os.environ.get(RETRY_AFTER_ENV) or RETRY_AFTER_S)
385
-
386
- def overloaded(pool: str) -> str | None:
387
- """Why a new call to `pool` is refused now, or None."""
388
- stats = pool_stats()[pool]
389
- if pool == "slow" and stats["in_flight"] >= stats["limit"] + slow_queue:
390
- return f"{stats['in_flight']:.0f} slow calls running or queued"
391
- if pool == "fast" and stats["queue_wait_oldest_s"] > fast_max_wait:
392
- return f"calls wait {stats['queue_wait_oldest_s']:.1f} s for a thread"
393
- return None
394
-
395
- refusal_log = {p: [-math.inf, 0] for p in limiters} # pool -> [last WARNING at, refused then]
396
-
397
- def log_refusal(pool: str, name: str, why: str) -> None:
398
- """A WARNING with the reason, at most every REFUSAL_LOG_EVERY_S per pool (event loop)."""
399
- now, (last, mark) = metrics.clock(), refusal_log[pool]
400
- if now - last >= REFUSAL_LOG_EVERY_S:
401
- log.warning("%s pool overloaded (%s): refused %s; %d more since the last line",
402
- pool, why, name, metrics.refused[pool] - mark - 1)
403
- refusal_log[pool] = [now, metrics.refused[pool]]
404
-
405
- def pool_stats() -> dict[str, dict[str, float]]:
406
- now = metrics.clock()
407
- with queued_lock:
408
- waiting = {p: (len(q), min(q.values(), default=now)) for p, q in queued.items()}
409
- return {p: {"in_flight": lim.borrowed_tokens + waiting[p][0], "queued": waiting[p][0],
410
- "limit": lim.total_tokens, "queue_wait_oldest_s": now - waiting[p][1]}
411
- for p, lim in limiters.items()}
412
-
413
- cache: dict[str, Any] = {"version": None}
414
-
415
- def served() -> dict[str, Any]:
416
- """The manifest as served now, serialized once per manifest version (on the event
417
- loop: a health check never waits for a thread): what GET /manifest advertises is what
418
- is called. Building the dict is cheap; serializing it is not. Rebuilt only when
419
- `version` changes: a world that changes its description or capabilities at runtime
420
- must bump `version`."""
421
- m = world.manifest()
422
- knobs = list(world.admin.knobs)
423
- if cache["version"] != (m.get("version"), knobs):
424
- caps = list(dict.fromkeys([*(m.get("capabilities") or []), "metrics-v1", "admin-v1"]))
425
- body = {**m, "capabilities": caps, "knobs": knobs}
426
- cache.update(version=(m.get("version"), knobs), body=json.dumps(body).encode(), schemas={
427
- t["name"]: t.get("parameters") or {"type": "object", "properties": {}}
428
- for t in m.get("tools") or []})
429
- return cache
430
-
431
- def locked(fn, *args: Any) -> Any:
432
- if getattr(world, "concurrent", False): # the world guards its own state
433
- return fn(*args)
434
- with lock:
435
- return fn(*args)
436
-
437
- # plain ASGI (not @app.middleware): a client's disconnect still reaches the route
438
- app.add_middleware(_Auth, token=token or "", admin=os.environ.get(ADMIN_TOKEN_ENV) or "")
439
-
440
- @app.get("/healthz")
441
- async def healthz() -> dict:
442
- return {"status": "parked" if world is None else "ready"}
443
-
444
- @app.get("/manifest")
445
- async def manifest() -> Response:
446
- if resp := parked():
447
- return resp
448
- return Response(served()["body"], media_type="application/json")
449
-
450
- # ------------------------------------------------------------------ admin (docs/world.md)
451
- def admin_error(e: Exception) -> JSONResponse:
452
- return JSONResponse({"ok": False, "error": str(e)}, 400)
453
-
454
- async def admin_body(request: Request) -> Any:
455
- """The JSON body (None if it is not JSON); ValueError over ADMIN_MAX_BYTES."""
456
- data = bytearray()
457
- async for chunk in request.stream():
458
- data.extend(chunk)
459
- if len(data) > ADMIN_MAX_BYTES:
460
- raise ValueError(f"the body is over {ADMIN_MAX_BYTES} bytes")
461
- try:
462
- return json.loads(data)
463
- except ValueError:
464
- return None
465
-
466
- @app.get("/admin/knobs")
467
- async def get_knobs() -> dict:
468
- return admin().describe()
469
-
470
- @app.patch("/admin/knobs")
471
- async def patch_knobs(request: Request) -> Response:
472
- try: # in a thread: a knob's on_change may take the world's locks
473
- changes = await asyncio.to_thread(admin().set, await admin_body(request))
474
- except ValueError as e:
475
- return admin_error(e)
476
- return JSONResponse({"ok": True, "changes": changes, "knobs": admin().describe()})
477
-
478
- @app.get("/admin/paused")
479
- async def get_paused() -> dict:
480
- return {"parked": world is None, "paused": dict(admin().paused)}
481
-
482
- @app.post("/admin/{action}")
483
- async def pause_resume(action: str, request: Request) -> Response:
484
- if action not in ("pause", "resume"):
485
- return JSONResponse({"ok": False, "error": f"no admin action {action!r}"}, 404)
486
- try:
487
- body = await admin_body(request)
488
- body = body if isinstance(body, dict) else {}
489
- if action == "pause":
490
- await asyncio.to_thread(admin().pause, body.get("lanes"), str(body.get("reason") or ""))
491
- else:
492
- await asyncio.to_thread(admin().resume, body.get("lanes"))
493
- except ValueError as e:
494
- return admin_error(e)
495
- return JSONResponse({"ok": True, "paused": dict(admin().paused)})
496
-
497
- @app.get("/metrics")
498
- async def get_metrics(request: Request) -> Response:
499
- try:
500
- custom = await asyncio.to_thread(world.metrics) if world is not None else {}
501
- except Exception:
502
- log.exception("world.metrics() failed")
503
- custom = {}
504
- m = {**metrics.snapshot(pool_stats()), "parked": int(world is None),
505
- "attempt": park["attempt"], "paused": len(admin().paused),
506
- "world": {k: v for k, v in (custom or {}).items() if _finite(v)}}
507
- if "text/plain" in request.headers.get("accept", ""):
508
- return PlainTextResponse(_prometheus(m), media_type="text/plain; version=0.0.4")
509
- return JSONResponse(m)
510
-
511
- @app.post("/tools/{name}")
512
- async def call(name: str, request: Request) -> Response:
513
- if resp := parked():
514
- return resp
515
- t0 = metrics.clock()
516
- pool = getattr(world, "pool", lambda _: "fast")(name)
517
- pool = pool if pool in limiters else "fast"
518
- # Decided from the path alone, before the body (an upload can be 100+ MB) is read.
519
- if why := overloaded(pool):
520
- metrics.overloaded += 1
521
- metrics.refused[pool] += 1
522
- log_refusal(pool, name, why)
523
- n = 0
524
- async for chunk in request.stream(): # drained unparsed: the client reads the 429
525
- n += len(chunk)
526
- if n > MAX_BYTES * 2:
527
- break
528
- resp = _error("overloaded", f"world {world.name} is overloaded ({why}); retry in "
529
- f"{retry_after:g} s", 429, retry_after_s=retry_after)
530
- resp.headers["Retry-After"] = str(math.ceil(retry_after))
531
- latency = None
532
- else:
533
- resp = await _call(name, request)
534
- latency = metrics.clock() - t0
535
- if name in served()["schemas"]:
536
- code = json.loads(resp.body)["error"]["code"] if isinstance(resp, JSONResponse) else None
537
- n_in = request.headers.get("content-length", "")
538
- metrics.call(name, latency, code, int(n_in) if n_in.isdigit() else 0, len(resp.body))
539
- return resp
540
-
541
- async def _call(name: str, request: Request) -> Response:
542
- try:
543
- limit = MAX_BYTES * 4 // 3 + (4 << 20) if "workspace-upload-v1" in world.capabilities else 1 << 20
544
- data = bytearray()
545
- async for chunk in request.stream():
546
- data.extend(chunk)
547
- if len(data) > limit:
548
- return _error("bad_request", "tool request is too large", 413)
549
- body = await asyncio.to_thread(json.loads, data) # MBs for an upload: off the loop
550
- except ValueError:
551
- return _error("bad_request", "the body must be JSON: {\"args\": {...}}", 400)
552
- args = body.get("args") if isinstance(body, dict) else None
553
- args = {} if args is None else args
554
- agent = _agent(request.headers)
555
- if not agent.name:
556
- return _error("no_agent", f"{AGENT_HEADER} is required", 400)
557
- tools = served()["schemas"]
558
- if name not in tools:
559
- return _error("unknown_tool", f"no tool {name!r}; tools: {', '.join(tools) or 'none'}",
560
- 404)
561
- if err := check_args(tools[name], args):
562
- return _error("bad_args", f"{name}: {err}")
563
- pool = getattr(world, "pool", lambda _: "fast")(name)
564
- try:
565
- if isinstance(body, dict) and "workspace" in body:
566
- handler = getattr(world, "call_workspace", None)
567
- if "workspace-upload-v1" not in world.capabilities or handler is None:
568
- return _error("bad_request", "this world does not accept workspace uploads", 400)
569
- v2 = isinstance(body["workspace"], dict) and "patch" in body["workspace"]
570
- if v2 and "workspace-upload-v2" not in world.capabilities:
571
- return _error("need_full", "this world takes full-tree uploads (v1) only")
572
- metrics.uploads["v2" if v2 else "v1"] += 1
573
- result = await run(pool, handler, name, args, agent, body["workspace"])
574
- else:
575
- result = await run(pool, world.call, name, args, agent)
576
- if inspect.isawaitable(result):
577
- if getattr(world, "cancellable", lambda _: False)(name):
578
- try:
579
- result = await _unless_gone(result, request)
580
- except _Gone:
581
- log.info("tool %s for %s: caller gone, cancelled", name, agent.name)
582
- return _error("cancelled", "the caller disconnected", 499)
583
- else:
584
- result = await result
585
- out = await asyncio.to_thread(_ok_body, result)
586
- except ToolError as e:
587
- return _error(e.code, redact(e.message), retry_after_s=e.retry_after_s)
588
- except Exception:
589
- # The exception text can hold paths, command output or credentials: it stays in
590
- # the world's log, under an id the agent can quote.
591
- ref = uuid.uuid4().hex[:8]
592
- log.exception("tool %s failed for %s (error id %s)", name, agent.name, ref)
593
- return _error("internal", f"the tool failed with an internal error (error id {ref})")
594
- return Response(out, media_type="application/json")
595
-
596
- @app.post("/hooks")
597
- async def hooks(request: Request) -> Any:
598
- if resp := parked():
599
- return resp
600
- try:
601
- body = await request.json()
602
- except ValueError:
603
- return {"ok": False}
604
- event = body.get("event") if isinstance(body, dict) else None
605
- if event not in HOOK_EVENTS or event not in world.hooks():
606
- return {"ok": True, "ignored": True}
607
- agent = Agent(name=str(body.get("agent") or ""), type=str(body.get("type") or ""),
608
- swarm=str(body.get("swarm") or ""), turn=str(body.get("turn") or ""))
609
- fn = getattr(world, f"on_{event}")
610
- hook_args = (agent,) if event == "agent_start" else (agent, body.get("data") or {})
611
- try:
612
- result = await run("fast", fn, *hook_args)
613
- if inspect.isawaitable(result): # an `async def` hook
614
- await result
615
- except Exception:
616
- log.exception("hook %s failed for %s", event, agent.name)
617
- return {"ok": True}
618
-
619
- return app
620
-
621
-
622
- def resolve_target(target: str, path: str | None = None) -> Any:
623
- """The World subclass or instance `module:attr` names, imported from `path` (default: the
624
- current directory)."""
625
- module_name, _, attr = target.partition(":")
626
- if not module_name or not attr:
627
- raise ValueError(f"{target!r}: expected module:Class, e.g. taskboard:TaskBoard")
628
- where = path or os.getcwd()
629
- if where not in sys.path:
630
- sys.path.insert(0, where)
631
- obj = getattr(importlib.import_module(module_name), attr)
632
- if not (isinstance(obj, World) or isinstance(obj, type) and issubclass(obj, World)):
633
- raise TypeError(f"{target!r} is not a legion.world.World (subclass or instance)")
634
- return obj
635
-
636
-
637
- def build(obj: Any, admin: Admin | None = None) -> World:
638
- """An instance of the World subclass `obj` (an instance is returned as is). `admin`: the
639
- knobs and pauses it gets, attached to its `state_dir()` before `__init__` runs."""
640
- if isinstance(obj, World):
641
- return obj
642
- if admin is None:
643
- return obj()
644
- world = obj.__new__(obj) # the admin goes in first: __init__ registers its knobs
645
- if admin.path is None and (d := world.state_dir()):
646
- admin.attach(d)
647
- world.__dict__["_legion_admin"] = admin
648
- world.__init__()
649
- return world
650
-
651
-
652
- def load(target: str, path: str | None = None, admin: Admin | None = None) -> World:
653
- """`module:Class` (or `module:instance`) from `path`, built."""
654
- return build(resolve_target(target, path), admin)
655
-
656
-
657
- def stop_on_usr1() -> None:
658
- """SIGUSR1 (a Spot notice on Slurm: the watcher signals every process of the job) shuts
659
- the server down like SIGTERM, once: later USR1s are ignored (docs/slurm.md)."""
660
- import signal
661
-
662
- sent = []
663
-
664
- def handler(signum, frame) -> None:
665
- if not sent:
666
- sent.append(signum)
667
- print("world: SIGUSR1: shutting down", flush=True)
668
- os.kill(os.getpid(), signal.SIGTERM) # uvicorn's own graceful shutdown
669
-
670
- signal.signal(signal.SIGUSR1, handler)
671
-
672
-
673
- def serve(target: str, *, host: str | None = None, port: int | None = None,
674
- token_env: str = TOKEN_ENV, insecure: bool = False) -> None:
675
- import uvicorn
676
-
677
- from legion.isolation import enabled, protect_supervisor
678
-
679
- if enabled():
680
- protect_supervisor()
681
-
682
- token = os.environ.get(token_env, "")
683
- if not token and not insecure:
684
- raise SystemExit(f"{token_env} is not set: a world needs its shared secret "
685
- "(or pass --insecure for a world without one)")
686
- obj = resolve_target(target) # a bad target exits here; only __init__ may park
687
- host = host or os.environ.get(HOST_ENV) or "127.0.0.1"
688
- port = port or int(os.environ.get(PORT_ENV) or DEFAULT_PORT)
689
-
690
- def built(admin: Admin) -> World:
691
- world = build(obj, admin)
692
- print(f"world {world.name} {world.version} on http://{host}:{port}", flush=True)
693
- return world
694
-
695
- stop_on_usr1()
696
- # the port is bound first; the world is built (and rebuilt while that raises) in a thread
697
- uvicorn.run(create_app(built, token or None), host=host, port=port, log_level="warning",
698
- access_log=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/src/legion/world/store.py DELETED
@@ -1,179 +0,0 @@
1
- """`legion.world.store`: a small `(kind, key) -> JSON` table on SQLite in WAL mode (docs/world.md).
2
-
3
- For worlds that keep their state in memory and want saves that cost O(changes): the world reads
4
- its own dicts, marks the rows it changed with `dirty(kind, key)`, and a saver calls
5
- `flush(read)`, which upserts (or deletes) only those rows in one transaction. `backup_to(path)`
6
- writes a consistent copy while others write (SQLite online backup API), for archives.
7
-
8
- Rows moved out of the hot set (`put(..., cold=True)`) stay readable with `get` and
9
- `iter(kind, cold=True)`; `iter(kind)` (the hot rows) is what a world loads at start.
10
-
11
- store = Store(ws / "state.db")
12
- state = {key: value for key, value in store.iter("prs")}
13
- state["7"] = {...}; store.dirty("prs", "7")
14
- store.flush(lambda kind, key: state.get(key)) # None deletes the row
15
- """
16
-
17
- from __future__ import annotations
18
-
19
- import contextlib
20
- import json
21
- import sqlite3
22
- import threading
23
- import time
24
- from collections.abc import Callable, Iterator
25
- from pathlib import Path
26
- from typing import Any
27
-
28
- SCHEMA = """
29
- CREATE TABLE IF NOT EXISTS rows (
30
- kind TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,
31
- cold INTEGER NOT NULL DEFAULT 0, ts REAL NOT NULL,
32
- PRIMARY KEY (kind, key));
33
- """
34
- UPSERT = ("INSERT INTO rows (kind, key, value, cold, ts) VALUES (?, ?, ?, ?, ?) "
35
- "ON CONFLICT (kind, key) DO UPDATE SET value = excluded.value, cold = excluded.cold, "
36
- "ts = excluded.ts")
37
-
38
-
39
- class Store:
40
- """Thread-safe: one connection behind a lock (writes are short: dirty rows only)."""
41
-
42
- def __init__(self, path: str | Path) -> None:
43
- self.path = Path(path)
44
- self._lock = threading.Lock()
45
- # (kind, key) -> generation of its newest change; _written: generation last committed,
46
- # so a flush that lost a race never commits an older value over a newer one.
47
- self._dirty: dict[tuple[str, str], int] = {}
48
- self._written: dict[tuple[str, str], int] = {}
49
- self._gen = 0
50
- self._flushing = 0 # flushes between their read and their commit
51
- self._db = sqlite3.connect(self.path, check_same_thread=False, isolation_level=None)
52
- self._db.execute("PRAGMA journal_mode=WAL")
53
- self._db.execute("PRAGMA synchronous=NORMAL") # WAL: durable at checkpoints, never corrupt
54
- self._db.execute("PRAGMA journal_size_limit=4194304") # truncate the WAL after big writes
55
- self._db.executescript(SCHEMA)
56
-
57
- def get(self, kind: str, key: str) -> Any:
58
- """The row's value (hot or cold), or None."""
59
- with self._lock:
60
- row = self._db.execute("SELECT value FROM rows WHERE kind = ? AND key = ?",
61
- (kind, key)).fetchone()
62
- return None if row is None else json.loads(row[0])
63
-
64
- def iter(self, kind: str, cold: bool = False) -> Iterator[tuple[str, Any]]:
65
- """(key, value) of the hot rows of `kind` (cold=True: the cold rows), in first-write
66
- order."""
67
- with self._lock:
68
- rows = self._db.execute("SELECT key, value FROM rows WHERE kind = ? AND cold = ? "
69
- "ORDER BY rowid", (kind, int(cold))).fetchall()
70
- for key, value in rows:
71
- yield key, json.loads(value)
72
-
73
- def put(self, kind: str, key: str, value: Any, cold: bool = False) -> None:
74
- """Write one row now (and drop its dirty mark: this is its newest value)."""
75
- self.write([(kind, key, value)], cold=cold)
76
-
77
- def delete(self, kind: str, key: str) -> None:
78
- self.write([(kind, key, None)])
79
-
80
- def write(self, rows: list[tuple[str, str, Any]], cold: bool = False) -> None:
81
- """Upsert (value None: delete) several rows in one transaction."""
82
- with self._lock:
83
- self._gen += 1
84
- encoded = [(kind, key, self._gen, None if value is None else json.dumps(value))
85
- for kind, key, value in rows]
86
- self._commit(encoded, cold)
87
-
88
- def dirty(self, kind: str, key: str) -> None:
89
- """Mark a row changed; the next flush writes it."""
90
- with self._lock:
91
- self._gen += 1
92
- self._dirty.pop((kind, key), None) # re-insert: keeps the newest change last
93
- self._dirty[(kind, key)] = self._gen
94
-
95
- @property
96
- def pending(self) -> int:
97
- """Rows marked dirty and not yet flushed."""
98
- return len(self._dirty)
99
-
100
- def flush(self, read: Callable[[str, str], Any], lock=None) -> int:
101
- """Write every dirty row in one transaction: `read(kind, key)` gives its current value
102
- (None: delete it). `lock` guards what `read` reads: it is held only while the rows are
103
- read and encoded, not during the commit. A row changed again meanwhile stays dirty. On a
104
- failed commit nothing is written and the rows stay dirty. Returns the rows written."""
105
- with lock or contextlib.nullcontext(), self._lock:
106
- rows = []
107
- for (kind, key), gen in self._dirty.items():
108
- value = read(kind, key)
109
- rows.append((kind, key, gen, None if value is None else json.dumps(value)))
110
- if not rows:
111
- return 0
112
- self._flushing += 1
113
- with self._lock:
114
- try:
115
- self._commit(rows, False)
116
- finally:
117
- self._flushing -= 1
118
- if not self._flushing: # no older read left in flight: nothing to guard against
119
- self._written.clear()
120
- return len(rows)
121
-
122
- def _commit(self, rows, cold):
123
- """Write rows (kind, key, generation, encoded value or None) in one transaction,
124
- skipping any already written at a newer generation; then drop their dirty marks."""
125
- rows = [r for r in rows if self._written.get(r[:2], 0) < r[2]]
126
- now = time.time()
127
- self._db.execute("BEGIN IMMEDIATE")
128
- try:
129
- for kind, key, _, value in rows:
130
- if value is None:
131
- self._db.execute("DELETE FROM rows WHERE kind = ? AND key = ?", (kind, key))
132
- else:
133
- self._db.execute(UPSERT, (kind, key, value, int(cold), now))
134
- self._db.execute("COMMIT")
135
- except BaseException:
136
- self._db.execute("ROLLBACK")
137
- raise
138
- for kind, key, gen, _ in rows:
139
- self._written[(kind, key)] = gen
140
- if self._dirty.get((kind, key), gen + 1) <= gen:
141
- del self._dirty[(kind, key)]
142
-
143
- def backup_to(self, path: str | Path) -> None:
144
- """Consistent copy of the database, WAL included (SQLite online backup API). Holds the
145
- store's lock for the copy: writers wait."""
146
- backup_to(self._db, path, self._lock)
147
-
148
- def size(self) -> int:
149
- """Bytes on disk (database plus WAL)."""
150
- return sum(p.stat().st_size for p in (self.path, self.path.with_name(self.path.name + "-wal"))
151
- if p.exists())
152
-
153
- def checkpoint(self) -> None:
154
- """Fold the WAL into the database file and truncate it."""
155
- with self._lock:
156
- self._db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
157
-
158
- def close(self) -> None:
159
- self.checkpoint()
160
- with self._lock:
161
- self._db.close()
162
-
163
-
164
- def backup_to(db: sqlite3.Connection | str | Path, path: str | Path, lock=None) -> None:
165
- """Copy database `db` (a connection, or a file another process may be writing) to `path`."""
166
- path = Path(path)
167
- path.unlink(missing_ok=True)
168
- src = db if isinstance(db, sqlite3.Connection) else sqlite3.connect(db)
169
- dst = sqlite3.connect(path)
170
- try:
171
- if lock is None:
172
- src.backup(dst)
173
- else:
174
- with lock:
175
- src.backup(dst)
176
- finally:
177
- dst.close()
178
- if src is not db:
179
- src.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/src/legion/world/workspace.py DELETED
@@ -1,168 +0,0 @@
1
- """Bounded local git snapshots for worlds advertising workspace-upload-v1 and -v2.
2
-
3
- The worker captures files itself; an agent supplies a path within its own workspace,
4
- never a server path or a repository base SHA. Only git-tracked/nonignored files are
5
- included, and symlinks and git metadata are refused. Transport lives outside tool args.
6
- v1 sends every file (base64); v2 sends a binary git patch against the base (`capture_v2`),
7
- which the world applies on its own checkout of that base (`apply_patch`).
8
- """
9
- from __future__ import annotations
10
-
11
- import base64
12
- import os
13
- import re
14
- import subprocess
15
- import tempfile
16
- import threading
17
- from pathlib import Path, PurePosixPath
18
-
19
- MAX_BYTES = 128 << 20
20
- MAX_FILES = 10000
21
- PATCH_MAX_BYTES = 20 << 20 # a larger v2 patch is sent as a v1 snapshot instead
22
- APPLY_MAX_MEMORY = 2 << 30 # address space of `git apply`: a binary delta can expand a lot
23
- APPLY_SLOTS = threading.BoundedSemaphore(4) # `git apply` runs at once, world-wide
24
- # The agent owns its clone's config: never run a command it configured (fsmonitor, filters,
25
- # external diff, textconv) or let its diff settings change the patch format.
26
- SAFE = ("-c", "core.fsmonitor=false", "-c", "diff.noprefix=false", "-c", "diff.mnemonicPrefix=false",
27
- "-c", "diff.relative=false")
28
-
29
-
30
- def git(root: Path, *args: str, data: bytes | None = None, env: dict | None = None) -> str:
31
- return git_bytes(root, *args, data=data, env=env).decode().strip()
32
-
33
-
34
- def git_bytes(root: Path, *args: str, data: bytes | None = None, env: dict | None = None) -> bytes:
35
- try:
36
- p = subprocess.run(["git", *SAFE, "-C", str(root), *args], input=data,
37
- capture_output=True, timeout=30, check=False, env=env)
38
- except subprocess.TimeoutExpired: # a ValueError reaches the agent as a tool error
39
- raise ValueError("workspace capture timed out after 30 s: the clone is too large or "
40
- "slow; trim it") from None
41
- if p.returncode:
42
- raise ValueError("expected a local git clone with a committed base")
43
- return p.stdout
44
-
45
-
46
- def _clone(workdir: Path, path: str) -> tuple[Path, str, list[str]]:
47
- """The clone's root, its base (merge base with origin/main) and the files to upload."""
48
- root = (workdir / path).resolve()
49
- if not root.is_relative_to(workdir.resolve()) or not root.is_dir():
50
- raise ValueError("path must be a git clone inside your workspace")
51
- top = Path(git(root, "rev-parse", "--show-toplevel")).resolve()
52
- if top != root:
53
- raise ValueError("path must name the root of your clone")
54
- # The world verifies this commit against its own repository, including ancestry.
55
- base = git(root, "merge-base", "HEAD", "refs/remotes/origin/main")
56
- names = git(root, "ls-files", "-z", "--cached", "--others", "--exclude-standard").split("\0")
57
- files, total = [], 0
58
- for name in dict.fromkeys(names):
59
- if not name:
60
- continue
61
- rel = PurePosixPath(name)
62
- if rel.is_absolute() or ".." in rel.parts or ".git" in rel.parts:
63
- raise ValueError("unsafe file path")
64
- f = root / name
65
- if f.is_symlink() or not f.resolve().is_relative_to(root):
66
- raise ValueError("symlinks are not supported")
67
- if not f.exists(): # tracked deletion
68
- continue
69
- if not f.is_file() or len(files) >= MAX_FILES:
70
- raise ValueError("unsupported file or too many files")
71
- total += f.stat().st_size
72
- if total > MAX_BYTES:
73
- raise ValueError("workspace snapshot exceeds 128 MiB")
74
- files.append(name)
75
- return root, base, files
76
-
77
-
78
- def capture(workdir: Path, path: str) -> dict:
79
- root, base, names = _clone(workdir, path)
80
- return {"base_sha": base,
81
- "files": {n: base64.b64encode((root / n).read_bytes()).decode("ascii") for n in names}}
82
-
83
-
84
- def capture_v2(workdir: Path, path: str, cap: int = PATCH_MAX_BYTES) -> dict | None:
85
- """The clone as `{"base_sha", "patch"}`: the same files `capture` would send, staged into a
86
- temporary index, as a base64 `git diff --binary` against the base. None when the patch is
87
- over `cap` bytes (send `capture` instead)."""
88
- root, base, names = _clone(workdir, path)
89
- if any("\n" in n for n in names):
90
- return None # hash-object --stdin-paths reads lines
91
- objects = (root / git(root, "rev-parse", "--git-path", "objects")).resolve()
92
- with tempfile.TemporaryDirectory() as tmp:
93
- (Path(tmp) / "objects").mkdir()
94
- # New blobs go to a temporary object store (the clone's is borrowed), never the clone.
95
- env = {**os.environ, "GIT_INDEX_FILE": str(Path(tmp) / "index"),
96
- "GIT_OBJECT_DIRECTORY": str(Path(tmp) / "objects"),
97
- "GIT_ALTERNATE_OBJECT_DIRECTORIES": str(objects)}
98
- # hash-object --no-filters instead of `git add`: add would run the clone's clean filters.
99
- shas = git(root, "hash-object", "-w", "--no-filters", "--stdin-paths",
100
- data="".join(n + "\n" for n in names).encode(), env=env).split()
101
- info = "".join(f"{'100755' if (root / n).stat().st_mode & 0o100 else '100644'} {sha}\t{n}\0"
102
- for n, sha in zip(names, shas, strict=True))
103
- git(root, "update-index", "-z", "--index-info", data=info.encode(), env=env)
104
- patch = git_bytes(root, "diff", "--cached", "--binary", "--full-index", "--find-renames",
105
- "--no-ext-diff", "--no-textconv", "--no-color", base, env=env)
106
- if len(patch) > cap:
107
- return None
108
- return {"base_sha": base, "patch": base64.b64encode(patch).decode("ascii")}
109
-
110
-
111
- # git reads modes as octal and keeps only the type bits (0120000, 120755 are symlinks): any
112
- # new mode that is not exactly a regular file's is refused.
113
- _MODES = re.compile(rb"^(?:new file mode |new mode |index \S+ )(.*)$", re.MULTILINE)
114
- _SIZES = re.compile(rb"^(?:literal|delta) (\d+)$", re.MULTILINE)
115
-
116
-
117
- def apply_patch(snapshot: dict, tree: Path) -> list[str]:
118
- """Apply a v2 upload onto `tree`, a git checkout of its `base_sha` (the world's own), in the
119
- worktree (not the index), so the world's excludes apply when it stages the tree. Returns
120
- the paths that differ from the base (added, modified, deleted), as `unpack` callers expect.
121
- ValueError for an invalid patch; symlinks and submodules are refused as in v1."""
122
- try:
123
- patch = base64.b64decode(snapshot.get("patch") or "", validate=True)
124
- except (ValueError, TypeError) as exc:
125
- raise ValueError("invalid workspace patch") from exc
126
- if git(tree, "rev-parse", "HEAD") != snapshot.get("base_sha"):
127
- raise ValueError("the tree is not a checkout of the patch's base")
128
- if any(m not in (b"100644", b"100755") for m in _MODES.findall(patch)):
129
- raise ValueError("symlinks are not supported")
130
- # shortcut: agents send patches directly (legion.harbor's world.call), and a binary delta can
131
- # expand past its declared size, up to the file-size and memory limits below, with at most
132
- # APPLY_SLOTS applies at once; decode delta headers if that bound is too loose.
133
- if (patch.count(b"\ndiff --git ") + patch.startswith(b"diff --git ") > MAX_FILES
134
- or sum(int(n) for n in _SIZES.findall(patch)) > MAX_BYTES):
135
- raise ValueError("workspace snapshot exceeds 128 MiB or 10,000 files")
136
- if patch: # prlimit, not preexec_fn: the world's server is threaded
137
- with APPLY_SLOTS:
138
- p = subprocess.run(["prlimit", f"--fsize={MAX_BYTES}", f"--as={APPLY_MAX_MEMORY}",
139
- "git", "-C", str(tree), "apply", "--binary",
140
- "--whitespace=nowarn", "-"],
141
- input=patch, capture_output=True, timeout=120, check=False)
142
- if p.returncode:
143
- raise ValueError("the workspace patch does not apply to its base")
144
- for top, dirs, files in os.walk(tree):
145
- if top == str(tree) and ".git" in dirs:
146
- dirs.remove(".git")
147
- if any(os.path.islink(os.path.join(top, n)) for n in dirs + files):
148
- raise ValueError("symlinks are not supported")
149
- names = git(tree, "ls-files", "-z", "--modified", "--deleted", "--others", "--exclude-standard")
150
- return sorted({n for n in names.split("\0") if n})
151
-
152
-
153
- def unpack(snapshot: dict, root: Path) -> None:
154
- files = snapshot.get("files")
155
- if not isinstance(files, dict) or len(files) > MAX_FILES:
156
- raise ValueError("invalid workspace snapshot")
157
- total = 0
158
- for name, encoded in files.items():
159
- rel = PurePosixPath(name)
160
- if rel.is_absolute() or ".." in rel.parts or ".git" in rel.parts or "\\" in name:
161
- raise ValueError("unsafe file path")
162
- data = base64.b64decode(encoded, validate=True)
163
- total += len(data)
164
- if total > MAX_BYTES:
165
- raise ValueError("workspace snapshot exceeds 128 MiB")
166
- target = root / rel
167
- target.parent.mkdir(parents=True, exist_ok=True)
168
- target.write_bytes(data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/tests/conftest.py CHANGED
@@ -1,4 +1,4 @@
1
- """Puts the world's modules and the vendored legion library on sys.path; test helpers."""
2
  from __future__ import annotations
3
 
4
  import shutil
@@ -6,7 +6,7 @@ import sys
6
  from pathlib import Path
7
 
8
  ROOT = Path(__file__).resolve().parents[1] # world/
9
- sys.path[:0] = [str(ROOT), str(ROOT / "src")]
10
 
11
 
12
  class FakeBucket:
 
1
+ """Puts the world's modules on sys.path (legion is the installed package, README); test helpers."""
2
  from __future__ import annotations
3
 
4
  import shutil
 
6
  from pathlib import Path
7
 
8
  ROOT = Path(__file__).resolve().parents[1] # world/
9
+ sys.path.insert(0, str(ROOT))
10
 
11
 
12
  class FakeBucket:
world/vendor.sh DELETED
@@ -1,81 +0,0 @@
1
- #!/bin/bash
2
- # vendor.sh: (re)build src/ (legion's World API library) and requirements.txt in this directory
3
- # from a legion checkout. The world's own code (pybot.py and the modules next to it) is never
4
- # touched here.
5
- #
6
- # ./vendor.sh LEGION_DIR check + vendor at the commit in source-lock.json;
7
- # fails (nothing written) if any file's sha256 differs
8
- # ./vendor.sh LEGION_DIR --lock REV re-pin: vendor REV and rewrite source-lock.json
9
- #
10
- # Reads LEGION_DIR with `git archive` only (never checks out or switches branches there).
11
- # Needs git, python3, and uv (requirements.txt is `uv export` of legion's own uv.lock).
12
- set -euo pipefail
13
- die() { echo "vendor.sh: $*" >&2; exit 1; }
14
- [ $# -ge 1 ] || die "usage: vendor.sh LEGION_DIR [--lock REV]"
15
- LEGION=$1
16
- ROOT=$(cd "$(dirname "$0")" && pwd)
17
- LOCK=$ROOT/source-lock.json
18
-
19
- # What the world imports, transitively (pybot.py, repository.py, sandbox.py, snapshot.py and
20
- # legion.world.server.serve).
21
- FILES=(
22
- src/legion/__init__.py
23
- src/legion/buckets.py
24
- src/legion/isolation.py
25
- src/legion/models.py
26
- src/legion/registry.py
27
- src/legion/tools/__init__.py
28
- src/legion/tools/loader.py
29
- src/legion/worker/__init__.py
30
- src/legion/worker/sync.py
31
- src/legion/world/__init__.py
32
- src/legion/world/admin.py
33
- src/legion/world/lanes.py
34
- src/legion/world/protocol.py
35
- src/legion/world/server.py
36
- src/legion/world/store.py
37
- src/legion/world/workspace.py
38
- )
39
-
40
- if [ "${2:-}" = --lock ]; then
41
- [ -n "${3:-}" ] || die "--lock needs a revision"
42
- REV=$3
43
- else
44
- REV=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["legion_commit"])' "$LOCK")
45
- fi
46
- COMMIT=$(git -C "$LEGION" rev-parse --verify "$REV^{commit}") || die "$REV is not a commit in $LEGION"
47
-
48
- TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
49
- mkdir -p "$TMP/world" "$TMP/proj"
50
- git -C "$LEGION" archive "$COMMIT" "${FILES[@]}" | tar -x -C "$TMP/world"
51
- git -C "$LEGION" archive "$COMMIT" pyproject.toml uv.lock | tar -x -C "$TMP/proj"
52
- # The world needs legion's core and `controller` deps (fastapi, uvicorn), not Harbor or the board
53
- # client (msgboard is a git dependency, which pip's --require-hashes refuses): pruned.
54
- (cd "$TMP/proj" && uv export -q --frozen --no-emit-project --extra controller --no-dev --no-header \
55
- --prune harbor --prune podman-compose --prune msgboard -o "$TMP/requirements.txt")
56
-
57
- python3 - "$TMP" "$LOCK" "$COMMIT" "${2:-}" <<'PY'
58
- import hashlib, json, sys
59
- from pathlib import Path
60
- tmp, lock, commit, mode = Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3], sys.argv[4]
61
- sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
62
- got = {p.relative_to(tmp / "world").as_posix(): sha(p)
63
- for p in sorted((tmp / "world").rglob("*")) if p.is_file()}
64
- got = {"files": got, "requirements.txt": sha(tmp / "requirements.txt")}
65
- if mode == "--lock":
66
- lock.write_text(json.dumps({"legion_repo": "https://github.com/huggingface/legion",
67
- "legion_commit": commit, **got}, indent=2) + "\n")
68
- sys.exit(0)
69
- want = json.loads(lock.read_text())
70
- bad = sorted(k for k in want["files"].keys() | got["files"].keys()
71
- if want["files"].get(k) != got["files"].get(k))
72
- if want["requirements.txt"] != got["requirements.txt"]:
73
- bad.append("requirements.txt")
74
- if bad:
75
- sys.exit("vendor.sh: sha256 mismatch against source-lock.json: " + ", ".join(bad))
76
- PY
77
-
78
- rm -rf "$ROOT/src"
79
- mv "$TMP/world/src" "$ROOT/src"
80
- cp "$TMP/requirements.txt" "$ROOT/requirements.txt"
81
- echo "vendored legion $COMMIT: $(find "$ROOT/src" -type f | wc -l) files"