world: install legion at a pinned commit instead of vendoring it (#1)
Browse files- world: install legion at a pinned commit instead of vendoring it (5bac4c2f0c79c321e056756ee53381d828992ac3)
Files changed (24)
- README.md+24-7
- world/Dockerfile+10-6
- world/entrypoint.sh+3-1
- world/scripts/check-sidecar.py+4-4
- world/scripts/smoke-local.py+5-5
- world/source-lock.jsonDeleted-23
- world/src/legion/__init__.pyDeleted-3
- world/src/legion/buckets.pyDeleted-35
- world/src/legion/isolation.pyDeleted-386
- world/src/legion/models.pyDeleted
- world/src/legion/registry.pyDeleted-45
- world/src/legion/tools/__init__.pyDeleted-55
- world/src/legion/tools/loader.pyDeleted-385
- world/src/legion/worker/__init__.pyDeleted-1
- world/src/legion/worker/sync.pyDeleted-1181
- world/src/legion/world/__init__.pyDeleted-239
- world/src/legion/world/admin.pyDeleted-170
- world/src/legion/world/lanes.pyDeleted-385
- world/src/legion/world/protocol.pyDeleted-208
- world/src/legion/world/server.pyDeleted-698
- world/src/legion/world/store.pyDeleted-179
- world/src/legion/world/workspace.pyDeleted-168
- world/tests/conftest.py+2-2
- world/vendor.shDeleted-81
14 unmodified lines1516171819202122181920212223127 unmodified lines15115215315415515615715815916016116216316416516616716816917017117217317417516017617717817918018116418218318414 unmodified lines seed/ the bot the code dataset starts from (runtime, modules, deck, tests, docs) tests/ the world's tests (pytest), with a small test seed in tests/fixtures/ scripts/ smoke-local.py and check-sidecar.py: container-free checks on localhost src/ legion's World API library, vendored (never edit; vendor.sh) requirements.txt the world's Python deps with hashes (from legion's uv.lock; vendor.sh) source-lock.json the legion commit and the sha256 of every vendored file vendor.sh re-vendor src/ and requirements.txt from a legion checkout Dockerfile the world image (also the sidecar's); entrypoint.sh starts the world requirements.txt the world's Python deps with hashes (legion's uv.lock at the pinned commit) Dockerfile the world image (also the sidecar's), with legion pinned to a commit; entrypoint.sh starts the world```
## The world127 unmodified lines env: {PYBOT_REPO: '${PYBOT_REPO}'} # the task's [environment.env] reads it```
## The legion pin
The world imports legion's World API library (`legion.world`, `legion.isolation`,`legion.worker.sync`) from the installed `legion` package. Its commit is pinned in one place, the`legion @ git+https://github.com/huggingface/legion@<commit>` line in `world/Dockerfile`, and`requirements.txt` is legion's own `uv.lock` at that commit, exported with hashes. To bump it,change the commit there and regenerate `requirements.txt` from a legion clone (in `world/`):
```shlock=$(mktemp -d) && git -C /path/to/legion archive <commit> pyproject.toml uv.lock | tar -x -C "$lock"uv export -q --project "$lock" --frozen --no-emit-project --extra controller --no-dev --no-header \ --prune harbor --prune podman-compose --prune msgboard -o requirements.txt```
The prunes drop what the world does not use: Harbor and the board client (msgboard is a gitdependency, which pip's `--require-hashes` refuses). Then run the checks below, rebuild the imageand bump this dataset's `revision` in the legion specs that use it.
## Checks
```shcd worldpip install --require-hashes --no-deps -r requirements.txt && pip install pytest pytest-asynciopip install --require-hashes --no-deps -r requirements.txtpip install --no-deps "$(grep -o 'legion @ git+[^"]*' Dockerfile)" # legion at the pinned commitpip install pytest pytest-asynciopython -m pytest # the world's tests (Python 3.12, git, prlimit)python scripts/smoke-local.py --sidecar # the served world on localhost with a fake Hubpython scripts/check-sidecar.py # the sidecar's checks./vendor.sh /path/to/legion # the vendored library matches source-lock.json```
`smoke-local.py` without `--sidecar` runs the bot under `unshare`, which many machines and1 unmodified line2345567889101112131 unmodified line151617161718192021222324251 unmodified line2728292526303132331 unmodified line# docker build -t <registry>/pybot-world:<tag> world/# The same image runs the bot sandbox sidecar (command `python sandbox.py serve`). The base is# pinned by digest (3.12: the seed's bot imports `copy`, which the bot sandbox allows only on# 3.12+); Python deps are legion's own uv.lock (exact versions + hashes, see vendor.sh).# 3.12+); Python deps are legion's own uv.lock (exact versions + hashes), and legion itself is# installed at the commit that lock comes from (README, "The legion pin").FROM python:3.12.15-slim-bookworm@sha256:6a0e06f5ba0b373d051aabd3fffb9b873f27f9a2a3a14bcbe37dee6f0e3bbc70
# git: the world's bare repo, fetches and pushes to the Hub. util-linux (unshare) ships in the base.# git: the world's bare repo, fetches and pushes to the Hub, and pip's legion checkout.# util-linux (unshare) ships in the base.RUN apt-get update \ && apt-get install -y --no-install-recommends git \ && rm -rf /var/lib/apt/lists/*1 unmodified lineCOPY requirements.txt /opt/world/requirements.txtRUN pip install --no-cache-dir --no-deps --require-hashes -r /opt/world/requirements.txt
# src/: legion's World API library, vendored by vendor.sh (hashes in source-lock.json), never edited.COPY src/ /opt/world/src/# legion's World API library, pinned to a commit (pip cannot hash a git requirement, so it gets its# own install). --no-deps: its deps are the hashed ones above; the world needs no Harbor or board.RUN pip install --no-cache-dir --no-deps \ "legion @ git+https://github.com/huggingface/legion@803873b114d5e04a3a01fea5e2e9084a03596fab"
COPY pybot.py repository.py sandbox.py snapshot.py /opt/world/COPY seed/ /opt/world/seed/COPY --chmod=755 entrypoint.sh /usr/local/bin/pybot-entrypoint1 unmodified lineRUN useradd -m -u 1000 user && mkdir -p /work && chown user:user /workUSER user# For the sidecar's bare `python sandbox.py serve` (a job command replaces the entrypoint); the# entrypoint sets its own PYTHONPATH and cwd, so the world does not depend on these.ENV PYTHONPATH=/opt/world/src# entrypoint sets its own cwd, so the world does not depend on it.WORKDIR /opt/worldEXPOSE 7860ENTRYPOINT ["/usr/local/bin/pybot-entrypoint"]31 unmodified lines3233343536353738394031 unmodified linesWORLD=${WORLD_DIR:-/opt/world}WORK=${PYBOT_WORK:-/work}# Set here, not in the image: pyxis passes the host env (HOME, PYTHONPATH) into the container.# A host PYTHONPATH must not shadow the image's installed legion.unset PYTHONPATHexport PYTHONPATH=$WORLD/src HOME=$WORK/home HF_HOME=$WORK/hf TMPDIR=$WORK/tmpexport HOME=$WORK/home HF_HOME=$WORK/hf TMPDIR=$WORK/tmpexport PYBOT_WS=$WORK/ws PYTHONUNBUFFERED=1mkdir -p "$PYBOT_WS" "$HOME" "$HF_HOME" "$TMPDIR" || die "cannot create dirs under $WORK"
6 unmodified lines789101011121311 unmodified lines2526272829282930313227 unmodified lines60616263636465666 unmodified linesmain) goes through for both; a bad token or an unreachable sidecar is `busy`, and a refusal logsits HTTP status; a tar with `../`, a link, too many members or too many bytes is a 400; a timeoutworks.Local path without `unshare` (blocked on many boxes). Needs requirements.txt, 3.12+.Local path without `unshare` (blocked on many boxes). Needs requirements.txt and legion, 3.12+."""import base64import io11 unmodified linesimport urllib.requestfrom pathlib import Path
WORLD = SRC = Path(__file__).resolve().parent.parent # world/sys.path[:0] = [str(WORLD / "src"), str(SRC)]SRC = Path(__file__).resolve().parent.parent # world/sys.path.insert(0, str(SRC))LINES = ["Hello", "My name is Sam", "", "What is my name?", "Bye"]
27 unmodified lines s.bind(("127.0.0.1", 0)) port = s.getsockname()[1] srv = subprocess.Popen([sys.executable, str(SRC / "sandbox.py"), "serve"], stderr=subprocess.DEVNULL, env={"PYTHONPATH": str(WORLD / "src"), "PYBOT_SANDBOX_TOKEN": "tok", "PORT": str(port)}) env={"PYBOT_SANDBOX_TOKEN": "tok", "PORT": str(port)}) try: for _ in range(300): try:5 unmodified lines678991011127 unmodified lines2021222324232425262738 unmodified lines666768696970717273737475765 unmodified linesone run_bot call.With --sidecar, the bot sandbox runs as a 2nd local process (`sandbox.py serve`, given only itstoken) and run_bot must succeed through it. Writes nothing outside a temp dir and makes no networkcalls beyond localhost. Needs the deps in requirements.txt and git.calls beyond localhost. Needs the deps in requirements.txt, legion (README) and git."""import jsonimport os7 unmodified linesimport urllib.requestfrom pathlib import Path
WORLD = SRC = Path(__file__).resolve().parent.parent # world/sys.path[:0] = [str(WORLD / "src"), str(SRC)]SRC = Path(__file__).resolve().parent.parent # world/sys.path.insert(0, str(SRC))TOOLS = {"open_pr", "review_pr", "merge_pr", "close_pr", "list_prs", "get_pr", "record_verdict", "verdicts", "run_bot", "world_status"}TOKEN = "smoke-token"38 unmodified lines
def start_sidecar(tmp): """sandbox.py serve with nothing but its token, PORT and the library path; returns (proc, log).""" """sandbox.py serve with nothing but its token and PORT; returns (proc, log).""" port, log = free_port(), tmp / "sidecar.log" proc = subprocess.Popen([sys.executable, str(SRC / "sandbox.py"), "serve"], cwd=SRC, stderr=log.open("wb"), env={"PYBOT_SANDBOX_TOKEN": "sidecar-token", "PORT": str(port), "PYTHONPATH": str(WORLD / "src")}) "PORT": str(port)}) for _ in range(100): try: socket.create_connection(("127.0.0.1", port), timeout=1).close()1234567891011121314151617181920212223{ "legion_repo": "https://github.com/huggingface/legion", "legion_commit": "803873b114d5e04a3a01fea5e2e9084a03596fab", "files": { "src/legion/__init__.py": "2ca25e640556c716182ea3432836ca462f6ac4f9f048fee06532a6229217549c", "src/legion/buckets.py": "7cd3362e02cc56bf09db3b434413548c31c407302177def5162d9854a1d70a7f", "src/legion/isolation.py": "d2aee168504b93602d3fc4a50898539049a4cddcdec9f18364c664acd436d66f", "src/legion/models.py": "11c3fed632ab8d567fd202d487caf6e3eeb4ef2923adc465205bc3e25527f4b1", "src/legion/registry.py": "68257009cc7d026bb6ee06e24310b59b427f4f1a07e591ec2d8058e964edc270", "src/legion/tools/__init__.py": "c0daaebb255a07ea8032d8e00f9752075cabfd33382afdb8d4ddeede7a960dfc", "src/legion/tools/loader.py": "93f23ceb747fbb6c767f8a46cf2b1b562cafdf6e518290862106d547eb47a0d5", "src/legion/worker/__init__.py": "c4afc77bc9a814ffb811300094c36e0706c2a6a025703241c69688e3c5d2ff83", "src/legion/worker/sync.py": "bc2f6dab07d066a103f719174455b37bc784b8cd80794489da2038213fcbc4fa", "src/legion/world/__init__.py": "3fafd99d4e514f00ebf9b9f5ca2bfadd0fe30f83358bb7ef0bb33c601d5cb14f", "src/legion/world/admin.py": "aa83dfc00544cc368512896061d3953f1b52a77135639af2b32804eec7f4cda0", "src/legion/world/lanes.py": "1bd5ba820732c3c57299b51d91a78199d860cea8c0940e9efe0f24d8e90f26ad", "src/legion/world/protocol.py": "edde06d66578c82e08ace3bcdf113ac9217937a693c0449c7d727efdef9eb9ad", "src/legion/world/server.py": "896fac8edb9918ab2ccbfb6947d50ad4cca9ad4ce9990bde365a89c0df0a1afd", "src/legion/world/store.py": "3b4929798dc7710a94fa617d399a275577121457aade45784388e34d6df9a8f8", "src/legion/world/workspace.py": "a20903edc437c127d8752e1b9c0bac48a64e5caade51e9c5dc7f913d5d09a1f5" }, "requirements.txt": "03b2bc4359a6929b8a0530546837002c9d5d9da811167257d0cf01f3d801128d"}123"""legion: host coding-harness agent swarms on Hugging Face Jobs."""
__version__ = "0.0.1"1234567891011121314151617181920212223242526272829303132333435"""Spec bucket IDs, resolved by the launcher; URLs may add legion's internal prefixes."""
import refrom typing import Annotated, Any
from pydantic import AfterValidator
def validate_bucket_id(value: str) -> str: """An optional `[namespace/]name`, without a URL or a path inside the bucket.""" parts = value.split("/") if value and (len(parts) > 2 or any( not re.fullmatch(r"[\w.-]+", p, flags=re.ASCII) or p in (".", "..") for p in parts)): raise ValueError("bucket_id must be [namespace/]name, without hf://buckets/ or a prefix") return value
BucketId = Annotated[str, AfterValidator(validate_bucket_id)]
def resolve_bucket_id(bucket_id: str, namespace: str, api: Any) -> str: """Qualify a bare name using the explicit namespace, else HF_TOKEN's account.""" validate_bucket_id(bucket_id) if not bucket_id or "/" in bucket_id: return bucket_id return f"{namespace or api.whoami()['name']}/{bucket_id}"
def bucket_url(bucket_id: str) -> str: """A qualified spec ID as a Hub URL, ready for legion's checkpoint/agent prefixes.""" validate_bucket_id(bucket_id) if "/" not in bucket_id: raise ValueError("bucket_id must be qualified by legion launch before use") return f"hf://buckets/{bucket_id}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386"""Linux process isolation for harness and bot subprocesses. Setup errors abort; there is no unsandboxed fallback.
unshare creates a user/PID/mount namespace and private procfs. The trusted setupthen builds a small root with read-only runtimes and only the caller's data,chroots and drops capabilities before executing any agent-supplied code."""from __future__ import annotations
import contextlibimport ctypesimport jsonimport osimport reimport shutilimport sysfrom collections.abc import Iteratorfrom pathlib import Path
MS_RDONLY, MS_NOSUID, MS_NODEV, MS_NOEXEC = 1, 2, 4, 8MS_REMOUNT, MS_BIND = 32, 4096MS_NOATIME, MS_NODIRATIME, MS_REC, MS_RELATIME, MS_STRICTATIME = 1024, 2048, 16384, 1 << 21, 1 << 24# statvfs flags of a mount that an unprivileged namespace cannot clear (they are locked) -># the mount(2) flags a read-only remount must repeat._LOCKED = ((os.ST_RDONLY, MS_RDONLY), (os.ST_NOSUID, MS_NOSUID), (os.ST_NODEV, MS_NODEV), (os.ST_NOEXEC, MS_NOEXEC), (os.ST_NOATIME, MS_NOATIME), (os.ST_NODIRATIME, MS_NODIRATIME), (os.ST_RELATIME, MS_RELATIME))
DEV_NODES = ("/dev/null", "/dev/zero", "/dev/urandom", "/dev/random")# The chroot's root is a tmpfs: RAM that counts against the job's memory. Only mount points# and stray writes outside the bound dirs land there; the cap bounds each sandbox.TMPFS_SIZE_ENV, TMPFS_SIZE_DEFAULT = "LEGION_ISOLATION_TMPFS_SIZE", "256m"SANDBOX_TMP = "/tmp" # where `command(tmp=...)` binds the caller's disk-backed temp dir_SIZE = re.compile(r"[1-9][0-9]*[kmg]?", re.IGNORECASE)MOUNT_ATTR_RDONLY, AT_FDCWD, AT_RECURSIVE, SYS_MOUNT_SETATTR = 0x1, -100, 0x8000, 442
class IsolationSetupError(OSError): """A sandbox setup step failed: names the step and path (never argv or the env)."""
class IsolationMountError(IsolationSetupError): """A mount(2) call of the sandbox setup failed: names the target and flags, no argv."""
@contextlib.contextmanagerdef _step(step: str, path) -> Iterator[None]: """Turn a plain OSError of one setup step into an IsolationSetupError naming it.""" try: yield except IsolationSetupError: raise except OSError as e: raise IsolationSetupError(e.errno, f"isolation {step} failed: " f"{e.strerror or type(e).__name__}: path={path}") from None
def enabled() -> bool: return os.environ.get("LEGION_PROCESS_ISOLATION") == "1"
def _libc(): return ctypes.CDLL(None, use_errno=True)
def protect_supervisor() -> None: """Deny same-UID ptrace and /proc/<pid>/{environ,mem,root} on worker/world.""" if not sys.platform.startswith("linux") or _libc().prctl(4, 0, 0, 0, 0) != 0: raise RuntimeError("PR_SET_DUMPABLE=0 is required for process isolation")
def tmpfs_size(env=os.environ) -> str: """The size cap of a sandbox's tmpfs root: $LEGION_ISOLATION_TMPFS_SIZE (bytes, or with a k/m/g suffix; never unlimited), else 256m. An unusable value falls back to the default.""" value = (env.get(TMPFS_SIZE_ENV) or "").strip() if _SIZE.fullmatch(value): return value.lower() if value: print(f"isolation: ignoring {TMPFS_SIZE_ENV}={value!r}; using {TMPFS_SIZE_DEFAULT}", file=sys.stderr) return TMPFS_SIZE_DEFAULT
def runtime_paths(command: list[str], *, python_only=False) -> list[str]: paths = ["/usr", "/bin", "/sbin", "/lib", "/lib64", sys.prefix, sys.base_prefix] # Config files needed by Python, Node, TLS, DNS and git; never a host home or the shared-disk root. paths += ["/etc/ssl", "/etc/alternatives", "/etc/hosts", "/etc/resolv.conf", "/etc/nsswitch.conf", "/etc/passwd", "/etc/group", "/etc/localtime"] if not python_only: paths.append(str(Path(__file__).resolve().parents[2])) # editable legion install for binary in (command[0], "node"): found = shutil.which(binary) if not found: continue target = Path(found).resolve() modules = next((p for p in target.parents if p.name == "node_modules"), None) paths.append(str(modules or target.parent)) return sorted({str(Path(p).absolute()) for p in paths if Path(p).exists()}, key=lambda p: (len(p), p))
def symlink_chain(path: str | Path) -> tuple[list[tuple[str, str]], str]: """Resolve `path` one hop at a time: every symlink met on the way (as `(link, target)`, the target exactly as stored) and the final real path. Components that do not exist are kept as they are. A loop or more than 40 hops raises.""" links: list[tuple[str, str]] = [] pending = list(Path(os.path.abspath(path)).parts[1:]) current = Path("/") while pending: name = pending.pop(0) if name in ("", "."): continue if name == "..": current = current.parent continue candidate = current / name if not candidate.is_symlink(): current = candidate continue target = os.readlink(candidate) links.append((str(candidate), target)) if len(links) > 40: raise RuntimeError(f"isolation: too many symlinks resolving {path}") if os.path.isabs(target): current = Path("/") pending = list(Path(target).parts[1:]) + pending else: pending = list(Path(target).parts) + pending return links, str(current)
def _within(path: str, roots: list[str]) -> bool: return any(path == r or path.startswith(r.rstrip("/") + "/") for r in roots)
def plan(argv: list[str], *, cwd: Path, readonly=(), writable=(), python_only=False, private_dirs=(), tmp=None) -> dict: """Mounts and symlinks for the chroot. Every path is bound at its real location, and each symlink hop on the way to it (and to the interpreter, the command and node) is recreated inside, so the original spelling resolves there too (a uv venv's python links through `cpython-3.12-...` to `cpython-3.12.14-...`).""" links: dict[str, str] = {}
def real(p) -> str: hops, final = symlink_chain(p) links.update(hops) return final
ro = [real(p) for p in runtime_paths(argv, python_only=python_only) + [str(p) for p in readonly]] rw = [real(p) for p in writable] probes = [sys.executable, argv[0] if os.path.isabs(argv[0]) else shutil.which(argv[0])] if not python_only: probes.append(shutil.which("node")) for probe in filter(None, probes): final = real(probe) if not _within(final, ro + rw): raise RuntimeError(f"isolation cannot represent {probe}: it resolves to {final}, " "outside every mounted path") real(cwd) def ordered(paths: list[str]) -> list[str]: # parents before nested mounts return sorted(dict.fromkeys(paths), key=lambda p: (len(p), p))
# `tmp` (a disk-backed dir) is bound over the sandbox's /tmp, so files written there do not # fill the tmpfs root. Not when a planned path lives under /tmp itself (a test's tmp_path): # the bind would hide it, and /tmp stays on the size-capped tmpfs. tmp_dir = real(tmp) if tmp is not None else None if tmp_dir is not None and any(_within(p, [SANDBOX_TMP]) for p in [*ro, *rw, *links, real(cwd)]): tmp_dir = None return {"readonly": ordered(ro), "writable": list(dict.fromkeys(rw)), "symlinks": sorted(links.items(), key=lambda kv: (len(kv[0]), kv[0])), "private_dirs": [str(Path(p).absolute()) for p in private_dirs], "tmp": tmp_dir}
def command(argv: list[str], root: Path, *, cwd: Path, readonly=(), writable=(), network=False, python_only=False, private_dirs=(), tmp=None) -> list[str]: """Build a trusted invocation. Only explicitly mounted paths survive the chroot. `tmp`: a disk-backed directory bound writable at the sandbox's /tmp (see `plan`).""" unshare = shutil.which("unshare") if not unshare: raise RuntimeError("unshare is required for process isolation") config = {"root": str(root.absolute()), "cwd": str(cwd.absolute()), "readonly_root": not network, "tmpfs_size": tmpfs_size(), **plan(argv, cwd=cwd, readonly=readonly, writable=writable, python_only=python_only, private_dirs=private_dirs, tmp=tmp)} # Slurm sends USR1 to every process on reclaim. Only worker/world supervisors # handle it; an unshare wrapper must survive long enough for their bounded drain. return ["/bin/sh", "-c", 'trap "" USR1; exec "$@"', "legion-isolate", unshare, "--user", "--map-root-user", "--pid", "--fork", "--kill-child=SIGKILL", "--mount", "--propagation", "private", "--mount-proc", *(["--net"] if not network else []), "--", sys.executable, "-I", str(Path(__file__).resolve()), json.dumps(config), *argv]
def _mount(source, target, kind=None, flags=0, data=None): def encoded(value): return os.fsencode(value) if value is not None else None libc = _libc() libc.mount.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_ulong, ctypes.c_char_p] if libc.mount(encoded(source), encoded(target), encoded(kind), flags, encoded(data)) != 0: errno = ctypes.get_errno() raise IsolationMountError(errno, f"isolation mount failed: {os.strerror(errno)}: " f"source={source} target={target} type={kind} " f"flags={flags:#x}")
def readonly_remount_flags(target) -> int: """MS_REMOUNT|MS_BIND|MS_RDONLY plus nosuid/nodev, and every locked flag the bound mount already has (statvfs of the bind target): a user namespace cannot clear them, and leaving them out fails with EPERM. No atime flag on the source means strictatime.""" inherited = os.statvfs(target).f_flag flags = MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV for flag, mount_flag in _LOCKED: if inherited & flag: flags |= mount_flag if not inherited & (os.ST_NOATIME | os.ST_RELATIME): flags |= MS_STRICTATIME return flags
def _readonly_recursive(target) -> bool: """mount_setattr(AT_RECURSIVE, MOUNT_ATTR_RDONLY): make every submount of a recursive bind read-only too (a remount only changes the top one). False if the kernel lacks it (before 5.12); the mountinfo check still refuses a writable submount.""" libc = _libc() attr = (ctypes.c_uint64 * 4)(MOUNT_ATTR_RDONLY, 0, 0, 0) libc.syscall.restype = ctypes.c_long rc = libc.syscall(ctypes.c_long(SYS_MOUNT_SETATTR), ctypes.c_int(AT_FDCWD), ctypes.c_char_p(os.fsencode(target)), ctypes.c_uint(AT_RECURSIVE), ctypes.byref(attr), ctypes.c_size_t(ctypes.sizeof(attr))) # Any failure (ENOSYS before 5.12, EPERM on a locked mount): the mountinfo check that # follows the binds still refuses a writable submount. return rc == 0
def _unescape(field: str) -> str: return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), field)
def parse_mountinfo(text: str) -> list[tuple[str, set[str]]]: """(mount point, per-mount options) of each /proc/self/mountinfo line.""" out = [] for line in text.splitlines(): fields = line.split() if len(fields) >= 6: out.append((_unescape(fields[4]), set(fields[5].split(",")))) return out
def check_mounts(mounts: list[tuple[str, set[str]]], root: str, readonly: list[str], writable: list[str] = (), extra: list[str] = ()) -> None: """Fail closed after the binds. Every mount under `root` must be a planned target (or `extra`: proc, the /dev nodes), or a submount a recursive bind of one brought along (e.g. a container's zoneinfo file bound over /usr's); and every mount at or under a read-only target, outside a writable one, must be `ro`.""" def under(path: str, roots) -> bool: return any(path == r or path.startswith(r.rstrip("/") + "/") for r in roots)
planned = [*readonly, *writable, *extra] for point, opts in mounts: if point == root or not under(point, [root]): continue if not under(point, planned): raise IsolationMountError(1, f"isolation: unexpected mount {point} in the sandbox root") if under(point, readonly) and not under(point, writable) and "ro" not in opts: raise IsolationMountError(30, f"isolation: {point} is mounted writable under a " "read-only path")
def _bind(root: Path, source: str, *, readonly: bool, target: Path | None = None): """Bind `source` at its own path under `root` (or at `target`, a path under `root`).""" path = Path(source) if not path.exists(): raise IsolationSetupError(2, f"isolation bind failed: required path is missing: path={source}") target = target if target is not None else root / path.relative_to("/") # Create the mount point only when missing: it may already exist on a read-only bind # (/etc/localtime -> /usr/share/zoneinfo/... under the /usr bind), where touch()'s utime # fails with EROFS. with _step("mount point creation", target): target.parent.mkdir(parents=True, exist_ok=True) if path.is_dir(): if not target.is_dir(): target.mkdir() elif not target.exists(): target.touch() # Recursive: a user namespace refuses (EINVAL) a non-recursive bind of a tree that has # locked submounts, since it would uncover what they hide. Only explicitly listed paths # are bound, so a submount comes in only under a path that was asked for. _mount(source, target, flags=MS_BIND | MS_REC) if readonly: # Step two: read-only only works as a remount of the bind, with the locked flags; # then the submounts the recursive bind brought along, where the kernel can. _mount(None, target, flags=readonly_remount_flags(target)) _readonly_recursive(target)
def _drop_privileges(): libc = _libc() # NOROOT + locked: exec as namespace uid 0 must never regain capabilities. if libc.prctl(28, 3, 0, 0, 0) or libc.prctl(38, 1, 0, 0, 0): raise RuntimeError("cannot lock sandbox privileges") # All currently defined capabilities fit below 64. EINVAL marks unsupported bits. for cap in range(64): if libc.prctl(24, cap, 0, 0, 0) != 0 and ctypes.get_errno() != 22: raise RuntimeError("cannot drop sandbox capability bounding set") class Header(ctypes.Structure): _fields_ = [("version", ctypes.c_uint32), ("pid", ctypes.c_int)] class Data(ctypes.Structure): _fields_ = [("effective", ctypes.c_uint32), ("permitted", ctypes.c_uint32), ("inheritable", ctypes.c_uint32)] if libc.capset(ctypes.byref(Header(0x20080522, 0)), (Data * 2)()) != 0: raise RuntimeError("cannot clear sandbox capabilities")
OOM_SCORE_ADJ = 800 # sandboxed processes die before the worker (which keeps 0) on an OOM kill
def set_oom_score_adj(value: int = OOM_SCORE_ADJ, path: str = "/proc/self/oom_score_adj") -> bool: """Raise this process's OOM score (inherited by what it execs). Raising needs no privilege; False when /proc refuses it.""" try: Path(path).write_text(str(value)) return True except OSError: return False
def _enter(config, argv): # Never share a process group with a supervisor outside the PID namespace. if os.getpgrp() != os.getpid(): os.setsid() set_oom_score_adj() root = Path(config["root"]) with _step("root creation", root): root.mkdir(parents=True, exist_ok=True) size = config.get("tmpfs_size") or TMPFS_SIZE_DEFAULT if not _SIZE.fullmatch(size): raise IsolationSetupError(22, f"isolation tmpfs size is invalid: path={root}") _mount("tmpfs", root, "tmpfs", MS_NOSUID | MS_NODEV, f"mode=755,size={size}") for path in config["readonly"]: _bind(root, path, readonly=True) for path in config["writable"]: _bind(root, path, readonly=False) for link, target in config.get("symlinks", ()): inside = root / Path(link).relative_to("/") if os.path.lexists(inside): continue # already visible through a bind mount with _step("symlink creation", inside): inside.parent.mkdir(parents=True, exist_ok=True) inside.symlink_to(target) for path in config["private_dirs"]: with _step("private directory creation", path): (root / Path(path).relative_to("/")).mkdir(parents=True, exist_ok=True) for path in ("tmp", "proc", "dev"): with _step("directory creation", root / path): (root / path).mkdir(exist_ok=True) if config.get("tmp"): # the sandbox's /tmp on the caller's disk-backed dir, not the tmpfs _bind(root, config["tmp"], readonly=False, target=root / SANDBOX_TMP.lstrip("/")) for path in DEV_NODES: _bind(root, path, readonly=False) with _step("symlink creation", root / "dev/fd"): (root / "dev/fd").symlink_to("/proc/self/fd") _mount("proc", root / "proc", "proc", MS_NOSUID | MS_NODEV | MS_NOEXEC) inside = lambda p: os.path.realpath(root / Path(p).relative_to("/")) check_mounts(parse_mountinfo(Path("/proc/self/mountinfo").read_text()), os.path.realpath(root), [inside(p) for p in config["readonly"]], [inside(p) for p in (*config["writable"], *([SANDBOX_TMP] if config.get("tmp") else []))], [inside(p) for p in ("/proc", *DEV_NODES)]) if config["readonly_root"]: _mount(None, root, flags=MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV) with _step("chroot", root): os.chroot(root) with _step("chdir", config["cwd"]): os.chdir(config["cwd"]) _drop_privileges() os.execvpe(argv[0], argv, dict(os.environ))
if __name__ == "__main__": try: _enter(json.loads(sys.argv[1]), sys.argv[2:]) except IsolationSetupError as e: # step, path and flags only, never argv or the env print(f"process isolation failed during setup: {e.strerror}", file=sys.stderr) raise SystemExit(125) from None except Exception: # noqa: BLE001 - fail closed, without leaking arguments or paths # Paths, argv and errors could contain credentials. Fail closed without their values. print("process isolation failed during setup", file=sys.stderr) raise SystemExit(125) from None123456789101112131415161718192021222324252627282930313233343536373839404142434445"""The harness and compute-backend registries: adding either is one module plus one entry here(docs/design.md, "Adding a harness or a compute backend"). The spec loader, controller, workerand CLI all read these entries. Code is named by import path ("module:function") and importedonly when used, so the controller never imports worker-only dependencies."""
from __future__ import annotations
from dataclasses import dataclassfrom importlib import import_modulefrom typing import Any
@dataclass(frozen=True)class HarnessEntry: adapter: str # "module:function"; function(workdir, agent name, TypeSpec) -> HarnessAdapter # (harbor's also takes `host=`, the worker's HarborHost) api: str # the wire API it speaks to its inference endpoints (preflight probes this one)
HARNESSES: dict[str, HarnessEntry] = { # one Harbor Trial per agent on the upstream Harbor task path (legion.harbor). Harbor installs Pi # (legion.harbor.config.PI_VERSION) in the task's container and the Trial delivers the # instructions "harbor": HarnessEntry("legion.worker.adapters.harbor:make_adapter", "chat_completions"),}
# `compute.kind` / LEGION_COMPUTE -> "module:function"; function(env, deployment, data_dir) -># JobsClient. The function also rejects a controller setup the backend cannot run in.COMPUTE: dict[str, str] = { "hf-jobs": "legion.controller.jobs:hub_jobs_client", "local": "legion.controller.local:local_jobs_client", # docs/local.md "slurm": "legion.controller.slurm:slurm_jobs_client", # docs/slurm.md}
# Inference servers legion starts itself: the `inference` block's key -> "module:function";# function(env) -> a Starter (legion.controller.servers), which starts a model's servers (or# reattaches to the running ones), checks them until they answer, and stops themSERVERS: dict[str, str] = { "hf_jobs": "legion.controller.hf_jobs_servers:hf_jobs_servers", # docs/open-models.md}
def load(path: str) -> Any: module, _, name = path.partition(":") return getattr(import_module(module), name)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455"""Runtime tools folder: plain Python functions next to the spec become agent tools.
What a tool module imports from here: `Context` (the optional run-context argument, never shownto the model), `ToolError` (raise it to hand the model a clean error message) and `readonly`(a decorator: the tool changes nothing; informational). The loader,schema builder, runner and bundle code live in the submodules; this module stays stdlib-only sothe per-call subprocess starts fast."""
from __future__ import annotations
from dataclasses import dataclass, fieldfrom pathlib import Path
READONLY_ATTR = "__legion_readonly__"
@dataclassclass Context: """What a tool learns about the call. Declare a parameter named `ctx` (or annotated `Context`) to receive it; the model never sees it.
- agent, type, swarm: who is calling (the swarm name is the run id). - workdir: the agent's working directory (also the call's cwd). - data_dir: a directory for tool state, shared by the agents of this worker, kept across tools versions, not synced to the bucket. - tools_dir: the extracted tools folder of this version; tools_version: its content hash. - env: the agent's environment (what its `bash` sees), also the call's process environment. """
agent: str type: str swarm: str workdir: Path data_dir: Path tools_dir: Path tools_version: str env: dict[str, str] = field(default_factory=dict)
Ctx = Context
class ToolError(Exception): """Raise from a tool to return `{"error": message}` to the model (no exception type prefix)."""
def readonly[F](fn: F) -> F: """Mark a tool as read-only (`readonly: true` in the manifest): it changes no state. Informational: nothing in legion acts on it.""" setattr(fn, READONLY_ATTR, True) return fn
__all__ = ["Context", "Ctx", "ToolError", "readonly"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385"""Tools folder -> tool definitions.
Every `*.py` file at the top of the folder whose name does not start with `_` is a tool module.Every function defined in it (not imported) whose name does not start with `_` and that has adocstring is a tool: name = function name, description = the docstring's first paragraph,parameters = a JSON schema built from the type hints (descriptions from an `Args:` section).A parameter named `ctx`, or annotated `legion.tools.Context`, is injected at call time andnever shown to the model.
`load_dir` imports the modules in this process; `describe` runs it in a fresh `python -I`subprocess (what `legion launch` uses), so a module's side effects, crashes and hangs staythere. `python -m legion.tools.loader <dir>` prints the manifest as JSON."""
from __future__ import annotations
import importlibimport inspectimport jsonimport reimport subprocessimport sysimport typesimport typingfrom dataclasses import asdict, dataclass, fieldfrom pathlib import Pathfrom typing import Any
from legion.tools import READONLY_ATTR, Context
NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")CTX_NAME = "ctx"DESCRIBE_TIMEOUT_S = 60.0
class ToolsError(ValueError): """The tools folder cannot be loaded; the message says which file and why."""
@dataclassclass ToolDef: name: str description: str parameters: dict[str, Any] # JSON schema, type object module: str # module name inside the folder function: str ctx: str | None = None # the parameter that receives the Context, if any is_async: bool = False # A built-in served by the worker itself, not the folder (`comms:post`, docs/comms.md). builtin: str | None = None # Changes nothing (`@legion.tools.readonly`; informational). In the manifest only when true. readonly: bool = False
def openai(self) -> dict[str, Any]: """The Chat Completions function tool.""" return {"type": "function", "function": { "name": self.name, "description": self.description, "parameters": self.parameters}}
@dataclassclass Manifest: tools: list[ToolDef] = field(default_factory=list)
def names(self) -> list[str]: return [t.name for t in self.tools]
def get(self, name: str) -> ToolDef | None: return next((t for t in self.tools if t.name == name), None)
def to_json(self) -> dict[str, Any]: # `readonly` only when set, so a folder without it keeps its manifest (and version) return {"tools": [{k: v for k, v in asdict(t).items() if k != "readonly" or v} for t in self.tools]}
@classmethod def from_json(cls, data: dict[str, Any]) -> Manifest: return cls([ToolDef(**t) for t in data.get("tools") or []])
# --------------------------------------------------------------------------- schema
def _first_paragraph(doc: str) -> str: para: list[str] = [] for line in doc.strip().splitlines(): if not line.strip(): break para.append(line.strip()) return " ".join(para)
_ARGS_HEAD = re.compile(r"^\s*(Args|Arguments|Parameters|Params)\s*:\s*$")_ARG_LINE = re.compile(r"^\s*\**([A-Za-z_][A-Za-z0-9_]*)\**\s*(\([^)]*\))?\s*:\s*(.*)$")
def arg_docs(doc: str) -> dict[str, str]: """Per-parameter descriptions from a Google-style `Args:` section (continuation lines are joined; the section ends at a blank line or a less-indented line).""" out: dict[str, str] = {} lines = doc.splitlines() i = next((k for k, line in enumerate(lines) if _ARGS_HEAD.match(line)), None) if i is None: return out head_indent = len(lines[i]) - len(lines[i].lstrip()) current: str | None = None item_indent = None for line in lines[i + 1:]: if not line.strip(): break indent = len(line) - len(line.lstrip()) if indent <= head_indent: break m = _ARG_LINE.match(line) if m and (item_indent is None or indent <= item_indent): item_indent = indent current = m.group(1) out[current] = m.group(3).strip() elif current is not None: out[current] = (out[current] + " " + line.strip()).strip() return out
def _is_context(hint: Any) -> bool: return hint is Context or (isinstance(hint, type) and issubclass(hint, Context))
def nullable(schema: dict[str, Any]) -> dict[str, Any]: """`schema` that also accepts null (an `Any` schema already does).""" out = dict(schema) t = out.get("type") if isinstance(t, str): out["type"] = [t, "null"] elif isinstance(t, list) and "null" not in t: out["type"] = [*t, "null"] if "enum" in out and None not in out["enum"]: out["enum"] = [*out["enum"], None] return out
def type_schema(hint: Any, where: str) -> tuple[dict[str, Any], bool]: """(JSON schema, nullable) for a type hint. `X | None` / `Optional[X]` is nullable: the schema accepts null too (`type: [X, "null"]`, None added to an enum). Nullable is not omittable: only a default makes a parameter optional.""" if hint is inspect.Parameter.empty: raise ToolsError(f"{where}: needs a type annotation (str, int, float, bool, list[...], dict)") origin = typing.get_origin(hint) args = typing.get_args(hint) if origin in (typing.Union, types.UnionType): rest = [a for a in args if a is not type(None)] if len(rest) != 1 or len(rest) == len(args): raise ToolsError(f"{where}: unions other than `X | None` are not supported") return nullable(type_schema(rest[0], where)[0]), True if hint is typing.Any: return {}, False if hint is str: return {"type": "string"}, False if hint is bool: return {"type": "boolean"}, False if hint is int: return {"type": "integer"}, False if hint is float: return {"type": "number"}, False if hint in (list, typing.List) or origin is list: # noqa: UP006 items = type_schema(args[0], where)[0] if args else {} return {"type": "array", "items": items}, False if hint in (dict, typing.Dict) or origin is dict: # noqa: UP006 return {"type": "object"}, False if origin is typing.Literal: kinds = {type(a) for a in args} schema: dict[str, Any] = {"enum": list(args)} if kinds == {str}: schema["type"] = "string" elif kinds == {int}: schema["type"] = "integer" return schema, False raise ToolsError(f"{where}: unsupported type {hint!r}; use str, int, float, bool, " "list[...], dict, Literal[...] or X | None")
def tool_def(fn: Any, module: str) -> ToolDef: """The ToolDef of one function (raises ToolsError naming module.function).""" name = fn.__name__ where = f"{module}.{name}" if not NAME_RE.match(name): raise ToolsError(f"{where}: tool names must match {NAME_RE.pattern}") doc = inspect.getdoc(fn) or "" try: hints = typing.get_type_hints(fn) except Exception as e: raise ToolsError(f"{where}: cannot resolve type hints: {type(e).__name__}: {e}") from e sig = inspect.signature(fn) docs = arg_docs(doc) props: dict[str, Any] = {} required: list[str] = [] ctx = None for p in sig.parameters.values(): hint = hints.get(p.name, p.annotation) if p.name == CTX_NAME or _is_context(hint): ctx = p.name continue if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD): raise ToolsError(f"{where}: *args / **kwargs are not supported; name every parameter") if p.kind is p.POSITIONAL_ONLY: raise ToolsError(f"{where}: positional-only parameters are not supported") schema, _ = type_schema(hint, f"{where}({p.name})") schema = dict(schema) if docs.get(p.name): schema["description"] = docs[p.name] if p.default is not p.empty: try: json.dumps(p.default) if p.default is not None: schema["default"] = p.default except (TypeError, ValueError): pass else: # no default: required, nullable or not (the call has no value to fall back on) required.append(p.name) props[p.name] = schema params: dict[str, Any] = {"type": "object", "properties": props, "additionalProperties": False} if required: params["required"] = required return ToolDef(name=name, description=_first_paragraph(doc), parameters=params, module=module, function=name, ctx=ctx, is_async=inspect.iscoroutinefunction(fn), readonly=getattr(fn, READONLY_ATTR, False) is True)
def tool_modules(folder: Path) -> list[Path]: return sorted(p for p in folder.glob("*.py") if not p.name.startswith("_"))
_LOADED: set[str] = set()
def load_dir(folder: str | Path) -> Manifest: """Import every tool module of `folder` (put on sys.path first, so modules may import their `_helpers`) and collect the tools. Raises ToolsError on a bad module or a duplicate name.""" folder = Path(folder).resolve() if not folder.is_dir(): raise ToolsError(f"tools folder {folder} does not exist") sys.path.insert(0, str(folder)) for name in _LOADED & set(sys.modules): # an earlier folder's modules (same process) del sys.modules[name] importlib.invalidate_caches() tools: dict[str, ToolDef] = {} for path in tool_modules(folder): mod_name = path.stem _LOADED.add(mod_name) try: mod = importlib.import_module(mod_name) except SyntaxError as e: raise ToolsError(f"{path.name}: syntax error line {e.lineno}: {e.msg}") from e except Exception as e: raise ToolsError(f"{path.name}: import failed: {type(e).__name__}: {e}") from e if Path(getattr(mod, "__file__", "") or "").resolve() != path: raise ToolsError(f"{path.name}: module name {mod_name!r} is shadowed by " f"{getattr(mod, '__file__', None) or 'a built-in module'}; rename the file") for attr, fn in vars(mod).items(): if attr.startswith("_") or not inspect.isfunction(fn) or fn.__module__ != mod.__name__: continue if not inspect.getdoc(fn): continue # no docstring: a helper, not a tool t = tool_def(fn, mod_name) if t.name in tools: raise ToolsError(f"{path.name}: tool {t.name!r} is also defined in " f"{tools[t.name].module}.py") tools[t.name] = t return Manifest(list(tools.values()))
def describe(folder: str | Path, *, python: str | None = None, timeout: float = DESCRIBE_TIMEOUT_S) -> Manifest: """`load_dir` in a fresh `python -I` process (cwd: the folder's parent). Raises ToolsError.""" folder = Path(folder).resolve() if not folder.is_dir(): raise ToolsError(f"tools folder {folder} does not exist") cmd = [python or sys.executable, "-I", "-B", "-m", "legion.tools.loader", str(folder)] try: p = subprocess.run(cmd, check=False, capture_output=True, text=True, timeout=timeout, cwd=str(folder.parent), stdin=subprocess.DEVNULL) except subprocess.TimeoutExpired as e: raise ToolsError(f"loading {folder} took over {timeout:g}s (a module blocks at import?)") from e try: out = json.loads(p.stdout.strip().splitlines()[-1]) if p.stdout.strip() else None except ValueError: out = None if not isinstance(out, dict): tail = (p.stderr or p.stdout or "").strip()[-800:] raise ToolsError(f"loading {folder} failed (exit {p.returncode}): {tail}") if "error" in out: raise ToolsError(out["error"]) return Manifest.from_json(out)
def select(manifest: Manifest, wanted: list[str] | str | None, *, where: str = "tools") -> list[ToolDef]: """The tools a type gets: `all`, a list of names (unknown names raise ToolsError), or none.""" if wanted is None: return [] if wanted == "all": return list(manifest.tools) if isinstance(wanted, str): raise ToolsError(f"{where}: use a list of tool names or `all`, not {wanted!r}") unknown = [n for n in wanted if manifest.get(n) is None] if unknown: known = ", ".join(manifest.names()) or "none" raise ToolsError(f"{where}: unknown tool(s) {', '.join(unknown)}; the tools folder has: {known}") return [t for n in dict.fromkeys(wanted) if (t := manifest.get(n)) is not None]
def _main(argv: list[str]) -> int: if len(argv) != 1: print(json.dumps({"error": "usage: python -m legion.tools.loader <tools dir>"})) return 2 import contextlib import io
sink = io.StringIO() # prints at import time must not corrupt the JSON line try: with contextlib.redirect_stdout(sink): manifest = load_dir(argv[0]) out: dict[str, Any] = manifest.to_json() except ToolsError as e: out = {"error": str(e)} print(json.dumps(out)) return 0
if __name__ == "__main__": sys.exit(_main(sys.argv[1:]))
# --------------------------------------------------------------------------- arguments
_JSON_TYPES: dict[str, tuple[type, ...]] = { "string": (str,), "integer": (int,), "number": (int, float), "boolean": (bool,), "array": (list,), "object": (dict,),}
def _types(schema: dict[str, Any]) -> list[str] | None: t = schema.get("type") if isinstance(t, str): return [t] return list(t) if isinstance(t, list) else None
def _is(value: Any, t: str) -> bool: if t == "null": return value is None if t not in _JSON_TYPES: return True return isinstance(value, _JSON_TYPES[t]) and not (t in ("integer", "number") and isinstance(value, bool))
def _check(schema: dict[str, Any], value: Any, where: str) -> str | None: """Type and enum checks; null only where the schema allows it (`X | None`), array items included. A schema without `type` (`Any`) accepts anything.""" types = _types(schema) if types is not None and not any(_is(value, t) for t in types): want = " or ".join("null" if t == "null" else t for t in types) got = "null" if value is None else f"{type(value).__name__} {json.dumps(value)[:60]}" return f"{where} must be {want}, got {got}" if "enum" in schema and value not in schema["enum"]: return f"{where} must be one of {schema['enum']}, got {json.dumps(value)[:60]}" if isinstance(value, list) and isinstance(schema.get("items"), dict): for i, v in enumerate(value): if err := _check(schema["items"], v, f"{where}[{i}]"): return err return None
def check_args(params: dict[str, Any], args: Any) -> str | None: """An error message for arguments that do not fit the tool's schema, else None.""" if not isinstance(args, dict): return f"arguments must be a JSON object, got {type(args).__name__}" props = params.get("properties") or {} unknown = [k for k in args if k not in props] if unknown: return f"unknown argument(s) {', '.join(unknown)}; expected: {', '.join(props) or 'none'}" missing = [k for k in params.get("required") or [] if k not in args] if missing: return f"missing required argument(s): {', '.join(missing)}" for k, v in args.items(): if err := _check(props[k], v, k): return err return None1"""Worker: hosts agents on one HF Job; see docs/design.md "Architecture"."""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181"""Bucket sync: per agent, `<bucket_id>/<swarm>/<type>/<agent>/` holds
workdir/<path relative to the workdir> (if persist_workdir; the deltas with a base) workdir.base.tar, workdir.base.json (only with the type's workdir.base, below) meta.json ({files, bytes, ts} of the mirrored workdir when it last changed) sessions/<agent>.jsonl, <agent>.state.json (pi session log + worker state) harness/<path relative to the harness home> (a Trial's Pi sessions)
The workdir goes through `sync_bucket` (the Python form of `hf buckets sync`), upward with delete so the bucket mirrors the workdir. The handful ofsession and harness files go through `batch_bucket_files`, only those whose (mtime, size)changed since the last push by this worker. `restore` brings all three areas back to thesame absolute paths (workdir and work root are fixed, harness homes are fixed by the image)before the first resume.
Restore lists the agent's prefix once, then downloads every file it found in batches(`restore_batch()`: env `LEGION_RESTORE_BATCH`, default 1000, minimum 1, an invalid valuemeans the default), `restore_threads()` batches at a time (env `LEGION_RESTORE_THREADS`,default 4; the type's `worker:` block overrides both), each to a `.legion-part` sibling renamed into place on success. A batch thatfails is retried file by file, with backoff (`RESTORE_BACKOFF`) between rounds: one unreadablefile is skipped and reported in `RestoreResult.failed` instead of aborting the whole restore. Apermanent "not found" (HTTP 404, e.g. xet "CAS Client Error: ... 404 Not Found" on thereconstruction: the entry's data is gone) is skipped at once, without the backoff rounds (analready-corrupt copy with ~42k such entries took 636 s to restore with them). Skipped files arelogged as one summary line per agent. Only a failed listing makes `restore` raise.
Buckets store bytes, not file modes: a restored file comes back 0644, so an executable scriptwould stop running after a move. Eachpush therefore writes `<workdir>/.legion-modes.json` ({relative path: octal mode} for every filewith an executable bit) when it changed, and restore re-applies it after the workdir download.
Push safety (a periodic sync must never mirror a half-restored workdir over the bucket copy,deleting entries the in-flight restore has not fetched yet):
- No push before setup: `AgentRuntime.sync_now` does nothing until the agent's `setup()` has finished its restore (every caller: the periodic sync, drain, preempt, unassign), and `BucketSync.push` refuses an agent whose restore is in flight. The bucket copy is the truth until the restore is done.- Delete-mirror only from a full baseline: the workdir push deletes remote files missing locally only when this worker's restore of the agent was complete (the listing succeeded and no file failed; an empty prefix counts as complete) or when no restore was attempted (a new agent). After a failed listing, a skipped file or an interrupted restore, pushes upload changed files but never delete, for as long as this worker holds the agent: a file it could not fetch stays in the bucket for the next restore.- `*.legion-part` (restore temporaries) is never uploaded nor deleted by a push; restore removes stray ones left by a crash.- Regenerable caches (`workdir_excludes`: `__pycache__/`, `*.pyc`, `node_modules/`, `.venv/`, ...; env LEGION_SYNC_EXCLUDE adds globs, LEGION_SYNC_EXCLUDE_DEFAULTS=0 drops the defaults) are neither uploaded nor deleted by the mirror, and restore skips them, also those already in the bucket. `.git/` and worktrees are never excluded by default.- The type's `workdir.ephemeral` dirs (root-relative) are excluded like the caches; the agent's setup empties them (`reset_ephemeral`), so they never come back after a move.- Each push's modes walk also measures what is mirrored (`WorkdirStats`): above the type's `workdir.soft_*` the agent gets a note, above `max_*` a `workdir_over_quota` event (each at most hourly, `BucketSync._quota`). A push is never refused for size.- Restore sets each workdir file's mtime to the bucket's (the listing carries it), so the first push after a restore uploads only real changes; session and harness files are marked as pushed (`_mark`).
Base tar (the type's `workdir.base: true`; off by default). A restore of N small files costs Ndownloads; a base turns most of them into one:
- A periodic push (never drain, preempt or unassign) makes a base when the agent has none, every `workdir.base_interval_s` (3600) or when the delta passes `workdir.base_delta_files` (5000, changed + deleted): an uncompressed tar of the workdir, sorted, regular files and symlinks with modes and mtimes (excludes and ephemeral dirs left out), written to local disk and uploaded as `workdir.base.tar`; then `workdir.base.json` `{created_at, files, bytes, deleted, links}` is written: the commit point. Only from a full baseline (`_mirror`), like deletes.- Every push after that uploads to `workdir/` only files whose (mtime, size) differ from the base's local index (`<sessions>/<agent>.base-index.json`), giving a changed file with an mtime not after the base (`cp -p`) the current time; base paths gone locally go to `deleted` (tombstones) and new or changed symlinks to `links`, rewriting the manifest when they change; delta entries not needed any more (in the base, or deleted) are removed from `workdir/`.- Restore with a manifest: download it and the tar, extract the tar member by member from disk, apply `deleted` and `links`, then download only the `workdir/` entries newer than `created_at` (older ones are already in the tar). A failed manifest, tar or member makes the restore incomplete (no deletes, no new base). Buckets without a manifest restore file by file.- Crash safety: before the manifest is written the old manifest (or the plain mirror) stays valid; after it, stale `workdir/` entries are older than `created_at`, ignored by restore and removed by the next push. Turning `base` off makes the next full-baseline push mirror the whole workdir to `workdir/` again and delete the base."""
from __future__ import annotations
import asyncioimport fnmatchimport functoolsimport jsonimport loggingimport osimport reimport shutilimport statimport tarfileimport threadingimport timefrom collections import Counterfrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import TYPE_CHECKING, Protocol
from legion.models import WorkdirSpec
if TYPE_CHECKING: from legion.models import TypeSpec from legion.worker.agents import AgentRuntime
log = logging.getLogger(__name__)
UPLOAD_CHUNK = 200MODES_FILE = ".legion-modes.json"BASE_TAR = "workdir.base.tar" # under the agent prefix (module docstring, "Base tar")BASE_JSON = "workdir.base.json"RESTORE_BATCH = 1000 # default of LEGION_RESTORE_BATCHRESTORE_THREADS = 4 # default of LEGION_RESTORE_THREADS# The type's `worker:` values for this module (sync_exclude, restore_batch, restore_threads),# set live by `Worker.apply_knobs`; each one present wins over its env variable.SPEC_KNOBS: dict[str, object] = {}
def _env_int(name: str, default: int, cap: int | None = None) -> int: try: n = int(os.environ.get(name, "")) except ValueError: return default return min(n, cap or n) if n >= 1 else default
def restore_batch() -> int: """Files per restore download batch: the spec's, else env LEGION_RESTORE_BATCH (>= 1), else RESTORE_BATCH.""" return SPEC_KNOBS.get("restore_batch") or _env_int("LEGION_RESTORE_BATCH", RESTORE_BATCH)
def restore_threads() -> int: """Batches of one agent's restore downloaded in parallel: the spec's, else env LEGION_RESTORE_THREADS (>= 1), else RESTORE_THREADS.""" return SPEC_KNOBS.get("restore_threads") or _env_int("LEGION_RESTORE_THREADS", RESTORE_THREADS, 32)
RESTORE_BACKOFF = (1.0, 4.0, 10.0) # seconds before each per-file retry roundPART_SUFFIX = ".legion-part"PUSH_EXCLUDE = ["*" + PART_SUFFIX] # sync_bucket patterns, matched on relative paths# Regenerable caches left out of the workdir mirror and of restore (module docstring). A trailing# "/" names a directory at any depth (`workdir_excludes`); other entries are plain globs.# Not build/, dist/ or target/: sometimes source.DEFAULT_WORKDIR_EXCLUDE = ["__pycache__/", "*.pyc", ".pytest_cache/", ".mypy_cache/", ".ruff_cache/", ".hypothesis/", "*.egg-info/", ".cache/", "node_modules/", ".venv/", "venv/", ".tox/", ".nox/", ".ipynb_checkpoints/", ".gradle/", ".next/", "*.o"]
def _expand(pattern: str) -> list[str]: """`name/` -> `name/*` and `*/name/*` (the directory at the root and below any directory); anything else is returned as is. `sync_bucket` globs are fnmatch on the whole relative path, where `*` also crosses `/`.""" if pattern.endswith("/"): d = pattern.rstrip("/") return [f"{d}/*", f"*/{d}/*"] return [pattern]
def workdir_excludes() -> list[str]: """Globs for the workdir mirror, relative to the workdir, always including `*.legion-part`: the defaults (unless env LEGION_SYNC_EXCLUDE_DEFAULTS=0) plus the spec's `sync_exclude`, else the comma-separated LEGION_SYNC_EXCLUDE. `.git/` is never in the defaults.""" pats = list(PUSH_EXCLUDE) if os.environ.get("LEGION_SYNC_EXCLUDE_DEFAULTS", "1").strip() != "0": pats += [x for d in DEFAULT_WORKDIR_EXCLUDE for x in _expand(d)] extra = SPEC_KNOBS.get("sync_exclude") if extra is None: extra = os.environ.get("LEGION_SYNC_EXCLUDE", "").split(",") for item in extra: if item.strip(): pats += _expand(item.strip()) return pats
@functools.lru_cache(maxsize=64)def _matcher(patterns: tuple[str, ...]): """One compiled regex for a pattern list (a walk tests every file of a workdir).""" if not patterns: return lambda rel: None return re.compile("|".join(fnmatch.translate(p.replace("\\", "/")) for p in patterns)).match
def is_excluded(rel: str, patterns: list[str]) -> bool: """Does the workdir-relative posix path match one of the patterns (as `sync_bucket` does)?""" return _matcher(tuple(patterns))(rel) is not None
@dataclassclass WorkdirStats: """What a push mirrors: regular files and their bytes, excluded paths left out, and the top-level directories with the most files ((name, files), largest first, up to 5)."""
files: int = 0 bytes: int = 0 top_dirs: list[tuple[str, int]] = field(default_factory=list)
def summary(self) -> str: """'182k files, 3100 MB; largest: snaps/ 140k, src/ 2k' (`{workspace}` in loop prompts).""" top = ", ".join(f"{d}/ {_k(n)}" for d, n in self.top_dirs[:3]) return (f"{_k(self.files)} files, {self.bytes / 2**20:.0f} MB" + (f"; largest: {top}" if top else ""))
def _k(n: int) -> str: return f"{n / 1000:.0f}k" if n >= 1000 else str(n)
QUOTA_NOTE_EVERY = 3600.0 # s, per agent: the over-soft-limit note and workdir_over_quota
def quota_note(ws: WorkdirStats, w: WorkdirSpec) -> str | None: """The note for an agent whose workdir is above its soft limit, else None.""" if ws.files <= w.soft_files and ws.bytes / 2**20 <= w.soft_mb: return None where = f", or keep throwaway clones in {w.ephemeral[0]}" if w.ephemeral else "" return (f"your workspace has {ws.summary()} (soft limit {_k(w.soft_files)} files, " f"{w.soft_mb:.0f} MB); delete clones you no longer need{where}")
def over_hard_limit(ws: WorkdirStats, w: WorkdirSpec) -> bool: return (ws.files > (w.max_files or 5 * w.soft_files) or ws.bytes / 2**20 > (w.max_mb or 5 * w.soft_mb))
def ephemeral_excludes(spec: TypeSpec) -> list[str]: """The type's `workdir.ephemeral` dirs as root-anchored globs (never synced nor restored).""" return [d + "*" for d in (spec.workdir.ephemeral if spec.workdir else [])]
def reset_ephemeral(workdir: Path, spec: TypeSpec) -> None: """Empty (or create) the type's ephemeral dirs: run at every agent setup, so a move or a restart never brings back their content. Blocking.""" root = workdir.resolve() for d in spec.workdir.ephemeral if spec.workdir else []: p = workdir / d try: if not p.parent.resolve().is_relative_to(root): # a symlinked parent: leave it log.warning("ephemeral dir %s is outside %s; not touched", p, root) continue if p.is_symlink() or p.is_file(): p.unlink() elif p.is_dir(): shutil.rmtree(p, ignore_errors=True) p.mkdir(parents=True, exist_ok=True) except OSError as e: log.warning("ephemeral dir %s: %s", p, e)
def _walk(workdir: Path, exclude: list[str] | None = None): """(relative posix path, lstat) of every regular file and symlink under `workdir`, sorted per directory; excluded directories are not entered, symlinked directories are not followed.""" excl = _matcher(tuple(exclude or ())) for root, dirs, files in os.walk(workdir): base = Path(root).relative_to(workdir).as_posix() base = "" if base == "." else base + "/" links = [d for d in dirs if os.path.islink(os.path.join(root, d))] dirs[:] = sorted(d for d in dirs if d not in links and excl(f"{base}{d}/") is None) for f in sorted(files + links): rel = base + f if excl(rel) is not None: continue try: st = os.lstat(os.path.join(root, f)) except OSError: continue if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode): yield rel, st
def collect_modes(workdir: Path, stats: WorkdirStats | None = None, exclude: list[str] | None = None) -> dict[str, str]: """{relative posix path: "0o755"} for regular files with any executable bit (symlinks and the manifest itself excluded). `exclude`: paths left out of the walk (excluded directories are not entered). `stats` gets the walk's counts (`WorkdirStats`).""" out: dict[str, str] = {} per_dir: Counter[str] = Counter() for rel, st in _walk(workdir, exclude): if not stat.S_ISREG(st.st_mode): continue if stats is not None: stats.files += 1 stats.bytes += st.st_size if "/" in rel: per_dir[rel.split("/", 1)[0]] += 1 if st.st_mode & 0o111 and rel != MODES_FILE: out[rel] = oct(stat.S_IMODE(st.st_mode)) if stats is not None: stats.top_dirs = per_dir.most_common(5) return dict(sorted(out.items()))
def _write_synced(path: Path, text: str) -> None: # fsync before a later os.replace with path.open("w") as f: f.write(text) f.flush() os.fsync(f.fileno())
def write_modes(workdir: Path, stats: WorkdirStats | None = None, exclude: list[str] | None = None) -> bool: """(Re)write the manifest if its content changed, remove it when nothing is executable. Returns whether the file changed.""" path = workdir / MODES_FILE modes = collect_modes(workdir, stats, exclude) old = path.read_text() if path.is_file() else None if not modes: if old is not None: path.unlink() return True return False new = json.dumps(modes, indent=0, sort_keys=True) + "\n" if new == old: return False path.write_text(new) return True
def apply_modes(workdir: Path) -> int: """chmod the files listed in the manifest (inside the workdir, regular files only).""" path = workdir / MODES_FILE try: modes = json.loads(path.read_text()) except (OSError, ValueError): return 0 n = 0 root = workdir.resolve() for rel, mode in (modes.items() if isinstance(modes, dict) else []): p = workdir / rel try: if ".." in Path(rel).parts or not p.resolve().is_relative_to(root) or p.is_symlink() \ or not p.is_file(): continue os.chmod(p, int(mode, 8) & 0o7777) n += 1 except (OSError, ValueError, TypeError): continue return n
class _Padded: """A file that may shrink while it is read: short reads are padded with zeros, so the tar stays well formed; the file's new mtime makes the next push send it as a delta."""
def __init__(self, f) -> None: self.f = f
def read(self, n: int = -1) -> bytes: b = self.f.read(n) return b + bytes(max(0, n - len(b)))
TAR_PER_FILE = 2048 # bytes of tar overhead per member, at most (pax header + padding)
def _fits(needs: list[tuple[Path, int]]) -> bool: """Do these byte counts fit in the free space of their file systems (summed per device)?""" per: dict[int, list] = {} for p, n in needs: p.mkdir(parents=True, exist_ok=True) per.setdefault(os.stat(p).st_dev, [p, 0])[1] += n return all(shutil.disk_usage(p).free >= n for p, n in per.values())
def write_base_tar(workdir: Path, exclude: list[str], dest: Path, stop=lambda: False) -> dict[str, list] | None: """Write an uncompressed tar of the workdir (regular files and symlinks, sorted, with modes and mtimes) to `dest`; returns the index {relative path: [mtime, size]} of what it holds (lstat before each read), or None when `stop()` turned true between two members.""" index: dict[str, list] = {} dest.parent.mkdir(parents=True, exist_ok=True) with tarfile.open(dest, "w", format=tarfile.PAX_FORMAT) as tf: for rel, st in _walk(workdir, exclude): if stop(): return None ti = tarfile.TarInfo(rel) ti.mode, ti.mtime = stat.S_IMODE(st.st_mode), int(st.st_mtime) ti.pax_headers = {"mtime": f"{st.st_mtime_ns / 1e9:.9f}"} # sub-second mtimes p = workdir / rel try: if stat.S_ISLNK(st.st_mode): ti.type, ti.linkname = tarfile.SYMTYPE, os.readlink(p) tf.addfile(ti) else: with open(p, "rb") as f: ti.size = st.st_size tf.addfile(ti, _Padded(f)) except OSError: # gone since the walk (open or readlink, before anything is written) continue index[rel] = [st.st_mtime, st.st_size] return index
def extract_base_tar(src: Path, workdir: Path, exclude: list[str], base: dict) -> tuple[dict[str, list], int]: """Extract a base tar into the workdir member by member (regular files and symlinks with their modes and mtimes; nothing outside the workdir, nothing excluded), then apply the manifest's tombstones (`deleted`) and symlinks (`links`). Returns (the index of the extracted files {relative path: [mtime, size]}, members that failed).""" workdir.mkdir(parents=True, exist_ok=True) root = workdir.resolve() index: dict[str, list] = {} bad = 0
safe: set[str] = set() # parent dirs checked (and made): one realpath per directory
def target(rel: str, make: bool = True) -> str | None: """The local path for `rel`, cleared, or None when it must not be written.""" if rel.startswith("/") or ".." in rel.split("/") or is_excluded(rel, exclude): return None p = os.path.join(workdir, rel) parent = os.path.dirname(p) if parent not in safe: if not Path(parent).resolve().is_relative_to(root): return None if make: os.makedirs(parent, exist_ok=True) safe.add(parent) try: if stat.S_ISDIR(os.lstat(p).st_mode): return None # a directory in the way os.unlink(p) # also read-only files (git objects) and links except FileNotFoundError: pass return p
with tarfile.open(src, "r:") as tf: while (m := tf.next()) is not None: tf.members.clear() # a 500k-file tar keeps no member list in memory try: if not (m.isreg() or m.issym()) or (p := target(m.name)) is None: continue if m.issym(): os.symlink(m.linkname, p) else: with tf.extractfile(m) as f, open(p, "wb") as out: shutil.copyfileobj(f, out) os.chmod(p, m.mode & 0o777) os.utime(p, (m.mtime, m.mtime), follow_symlinks=False) index[m.name] = [m.mtime, len(os.fsencode(m.linkname)) if m.issym() else m.size] except OSError as e: bad += 1 log.debug("base member %s: %s", m.name, e) for rel in base.get("deleted", []): try: target(rel, make=False) except OSError: bad += 1 for rel, link in base.get("links", {}).items(): try: if (p := target(rel)) is not None: os.symlink(link, p) except OSError: bad += 1 return index, bad
def _same(a: list | None, mtime: float, size: int) -> bool: return a is not None and abs(a[0] - mtime) <= 2e-3 and a[1] == size
def workdir_delta(workdir: Path, exclude: list[str], index: dict[str, list], created_at: float) -> tuple[dict[str, float], dict[str, str], list[str]]: """Against the base's index: (regular files new or changed {rel: mtime}, symlinks new or changed {rel: target}, base paths gone). A changed file whose mtime is not after the base (`cp -p`, `tar x`) gets its mtime set to now, since restore only takes deltas newer than the base.""" files: dict[str, float] = {} links: dict[str, str] = {} seen: set[str] = set() now = max(time.time(), created_at + 1.0) for rel, st in _walk(workdir, exclude): seen.add(rel) if _same(index.get(rel), st.st_mtime, st.st_size): continue p = workdir / rel try: if stat.S_ISLNK(st.st_mode): links[rel] = os.readlink(p) continue mt = st.st_mtime if mt <= created_at + 2e-3: # the Hub keeps milliseconds os.utime(p, (now, now)) mt = now except OSError: continue files[rel] = mt return files, links, sorted(set(index) - seen)
def _load_index(path: Path) -> dict[str, list]: try: return json.loads(path.read_text()) except (OSError, ValueError): return {}
@dataclassclass BucketStats: """Bucket traffic counters for the worker log: store operations (`ops`), the Hub HTTP requests behind them (`http`, by method and route; xet CAS transfers run in hf_xet and are not seen here) and HTTP error statuses (`errors`, e.g. 429). Thread-safe."""
ops: Counter = field(default_factory=Counter) http: Counter = field(default_factory=Counter) errors: Counter = field(default_factory=Counter) _lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
def add(self, kind: str, key: str, n: int = 1) -> None: with self._lock: getattr(self, kind)[key] += n
def snapshot(self) -> dict[str, Counter]: with self._lock: return {"ops": Counter(self.ops), "http": Counter(self.http), "errors": Counter(self.errors)}
def since(self, before: dict[str, Counter]) -> dict[str, dict[str, int]]: now = self.snapshot() return {k: dict(now[k] - before[k]) for k in now}
_BUCKET_ROUTE = re.compile(r"^/api/buckets/[^/]+/[^/]+(?:/([^/]+))?")
def http_route(method: str, host: str, path: str) -> str: """'GET /api/buckets/ns/b/tree/x/y' -> 'GET buckets/tree'; other hosts by first segment.""" m = _BUCKET_ROUTE.match(path) if m: return f"{method} buckets/{m.group(1) or ''}".rstrip("/") first = path.strip("/").split("/", 1)[0] if host.endswith("huggingface.co"): return f"{method} {first or '/'}" return f"{method} {host}/{first}"
def count_hub_http(stats: BucketStats) -> None: """Count every request huggingface_hub's shared client makes (one install per process).""" import huggingface_hub from huggingface_hub.utils._http import default_client_factory
def on_request(request) -> None: stats.add("http", http_route(request.method, request.url.host, request.url.path))
def on_response(response) -> None: if response.status_code >= 400: req = response.request route = http_route(req.method, req.url.host, req.url.path) stats.add("errors", f"{response.status_code} {route}")
def factory(): client = default_client_factory() client.event_hooks["request"].append(on_request) client.event_hooks.setdefault("response", []).append(on_response) return client
huggingface_hub.set_client_factory(factory)
class BucketStore(Protocol): """Blocking bucket operations on paths relative to the legion root."""
def upload(self, files: list[tuple[Path, str]]) -> None: ... def list(self, prefix: str) -> list[str]: ... def first(self, prefix: str) -> str | None: ... # one file under prefix (the launch guard) # optional: `list_info(prefix) -> list[tuple[str, float | None]]`, paths with their mtime # (POSIX seconds) when the store keeps one; restore uses it to set local mtimes def download(self, files: list[tuple[str, Path]]) -> None: ... def sync_up(self, local: Path, prefix: str, *, delete: bool = True, exclude: list[str] | None = None) -> None: """Upload new/changed files of a local directory to `prefix`; with `delete`, also delete remote files missing locally. `exclude`: fnmatch patterns on relative paths, neither uploaded nor deleted.""" ...
def sync_down(self, prefix: str, local: Path) -> None: ... def delete(self, paths: list[str]) -> None: """Delete files (paths relative to the legion root). Used by the controller's state.""" ...
def parse_bucket(url: str) -> tuple[str, str]: """'hf://buckets/ns/name/some/prefix' -> ('ns/name', 'some/prefix/').""" rest = url.removeprefix("hf://").removeprefix("buckets/").strip("/") parts = rest.split("/") if len(parts) < 2: raise ValueError(f"bad bucket url {url!r}; expected hf://buckets/<namespace>/<name>[/prefix]") prefix = "/".join(parts[2:]) return f"{parts[0]}/{parts[1]}", (prefix + "/" if prefix else "")
class HubBucketStore: """huggingface_hub bucket API (batch_bucket_files / list_bucket_tree / download_bucket_files)."""
def __init__(self, url: str, token: str | None = None, stats: BucketStats | None = None) -> None: from huggingface_hub import HfApi
self.bucket_id, self.base = parse_bucket(url) self.api = HfApi(token=token) self.stats = stats or BucketStats()
def upload(self, files: list[tuple[Path, str]]) -> None: for i in range(0, len(files), UPLOAD_CHUNK): self.stats.add("ops", "batch_bucket_files") chunk = files[i : i + UPLOAD_CHUNK] self.api.batch_bucket_files(self.bucket_id, add=[(str(p), self.base + r) for p, r in chunk])
def list(self, prefix: str) -> list[str]: return [r for r, _ in self.list_info(prefix)]
def first(self, prefix: str) -> str | None: """One file under `prefix` (None: empty), without listing the rest.""" from huggingface_hub import BucketFile
self.stats.add("ops", "list_bucket_tree") full = self.base + prefix for f in self.api.list_bucket_tree(self.bucket_id, prefix=full, recursive=True): if isinstance(f, BucketFile) and f.path.startswith(full): return f.path[len(self.base):] return None
def list_info(self, prefix: str) -> list[tuple[str, float | None]]: from huggingface_hub import BucketFile
self.stats.add("ops", "list_bucket_tree") full = self.base + prefix out: list[tuple[str, float | None]] = [] for f in self.api.list_bucket_tree(self.bucket_id, prefix=full, recursive=True): if isinstance(f, BucketFile) and f.path.startswith(full): mt = f.mtime.timestamp() if isinstance(f.mtime, datetime) else None out.append((f.path[len(self.base):], mt)) return out
def download(self, files: list[tuple[str, Path]]) -> None: self.stats.add("ops", "download_bucket_files") for _, local in files: local.parent.mkdir(parents=True, exist_ok=True) self.api.download_bucket_files(self.bucket_id, [(self.base + r, str(p)) for r, p in files])
def delete(self, paths: list[str]) -> None: for i in range(0, len(paths), UPLOAD_CHUNK): self.stats.add("ops", "batch_bucket_files") chunk = paths[i : i + UPLOAD_CHUNK] self.api.batch_bucket_files(self.bucket_id, delete=[self.base + r for r in chunk])
def _url(self, prefix: str) -> str: return f"hf://buckets/{self.bucket_id}/{self.base}{prefix}".rstrip("/")
def sync_up(self, local: Path, prefix: str, *, delete: bool = True, exclude: list[str] | None = None) -> None: self.stats.add("ops", "sync_bucket_up") self.api.sync_bucket(str(local), self._url(prefix), delete=delete, exclude=exclude or None, quiet=True)
def sync_down(self, prefix: str, local: Path) -> None: self.stats.add("ops", "sync_bucket_down") local.mkdir(parents=True, exist_ok=True) self.api.sync_bucket(self._url(prefix), str(local), quiet=True)
@dataclassclass RestoreResult: workdir: int = 0 sessions: int = 0 harness: int = 0 # bucket paths (relative to the legion root) that could not be downloaded, after retries failed: list[str] = field(default_factory=list)
_NOT_FOUND = re.compile(r"\b404\b|not found", re.IGNORECASE)
def _permanent(e: BaseException) -> bool: """A download error that retrying cannot fix: the entry's data is gone (HTTP 404).""" resp = getattr(e, "response", None) if getattr(resp, "status_code", None) == 404: return True return bool(_NOT_FOUND.search(str(e)))
def _part(p: Path) -> Path: return p.with_name(p.name + PART_SUFFIX)
def download_resilient(store: BucketStore, files: list[tuple[str, Path]], *, backoff: tuple[float, ...] | None = None, sleep=None, progress=None) -> tuple[list[tuple[str, Path]], list[str]]: """Download (remote, local) pairs; returns (downloaded, failed remote paths). Never raises for a file: batches first, then the files of a failed batch one by one, retried after each delay in `backoff` unless the error is a permanent "not found" (`_permanent`). Each file lands in a `.legion-part` sibling, renamed into place only when it arrived, so a failed file never leaves a truncated copy at its real path. `progress(n)` is called with the number of files each attempt brought in (serialized: the first pass runs `restore_threads()` batches in parallel threads)."""
gone: list[str] = [] # permanent "not found": skipped, never retried lock = threading.Lock() # first-pass batches run in threads
def attempt(batch: list[tuple[str, Path]]) -> tuple[list[tuple[str, Path]], list[tuple[str, Path]]]: ok, bad = [], [] try: store.download([(r, _part(p)) for r, p in batch]) except Exception as e: # noqa: BLE001 - sorted out per file below err = e else: err = None for r, p in batch: part = _part(p) if err is None and part.is_file(): try: os.replace(part, p) ok.append((r, p)) continue except OSError: pass part.unlink(missing_ok=True) bad.append((r, p)) if ok and progress is not None: with lock: progress(len(ok)) if err is not None and len(batch) == 1: log.debug("download of %s failed: %s", batch[0][0], _short(err)) if bad and _permanent(err): gone.append(bad[0][0]) return ok, [] return ok, bad
backoff = RESTORE_BACKOFF if backoff is None else backoff sleep = sleep or time.sleep done: list[tuple[str, Path]] = [] pending: list[tuple[str, Path]] = [] size = restore_batch() batches = [files[i : i + size] for i in range(0, len(files), size)] # the first pass runs `restore_threads()` batches at once (per-request latency, not # bandwidth, bounds a restore); the per-file retry rounds below stay sequential with ThreadPoolExecutor(max(1, min(restore_threads(), len(batches)))) as pool: for ok, bad in pool.map(attempt, batches): done += ok pending += bad if pending: # each file alone, so one bad file costs only itself retry, pending = pending, [] for f in retry: ok, bad = attempt([f]) done += ok pending += bad for delay in backoff: if not pending: break sleep(delay) retry, pending = pending, [] for f in retry: ok, bad = attempt([f]) done += ok pending += bad # the caller logs the skipped files (one summary line per agent, `BucketSync._restore_files`) return done, gone + [r for r, _ in pending]
def _clean_parts(root: Path) -> int: """Remove stray `.legion-part` files under `root` (a crash mid-download leaves them).""" n = 0 if root.is_dir(): for p in root.rglob("*" + PART_SUFFIX): try: if p.is_file() and not p.is_symlink(): p.unlink() n += 1 except OSError: pass return n
def _short(e: BaseException) -> str: return f"{type(e).__name__}: {str(e)[:300]}"
class BucketSync: def __init__(self, store: BucketStore, swarm: str) -> None: self.store = store self.swarm = swarm self.stats: BucketStats = getattr(store, "stats", None) or BucketStats() self._seen: dict[Path, tuple[int, int]] = {} # per agent prefix: may the workdir push delete remote files? Absent: no restore was # attempted (a new agent), deletes allowed. False from the start of a restore until it # completes with every file; stays False after an incomplete one (module docstring). self._mirror: dict[str, bool] = {} self._restoring: set[str] = set() # agent prefixes with a restore in flight self._meta: dict[str, dict] = {} # per agent prefix: the meta.json last pushed self._quota_note: dict[str, str] = {} # per agent prefix: the quota note last queued self._base: dict[str, dict] = {} # per agent prefix: its committed workdir.base.json self._building: set[str] = set() # agent prefixes with a base tar being made self.stop_rebase = False # set by drain/preempt: base builds stop, none start self._quota_at: dict[str, float] = {} # per agent prefix: monotonic time of the last note # per agent prefix with a restore in flight: [files done, files listed, started (UTC)] self.restore_progress: dict[str, list] = {}
def mirror_deletes(self, rt: AgentRuntime) -> bool: return self._mirror.get(self.prefix(rt), True)
def prefix(self, rt: AgentRuntime) -> str: return f"{self.swarm}/{rt.type_name}/{rt.name}/"
def collect(self, rt: AgentRuntime) -> list[tuple[Path, str]]: """The agent's session-log, state and harness files, with their bucket paths.""" pre = self.prefix(rt) out: list[tuple[Path, str]] = [] for p in (rt.log.path, rt.state_path): if p.is_file(): out.append((p, f"{pre}sessions/{p.name}")) home = Path(rt.adapter.home) for p in rt.harness_files(): try: rel = p.relative_to(home) except ValueError: log.warning("%s: harness file %s is outside %s; not synced", rt.name, p, home) continue out.append((p, f"{pre}harness/{rel.as_posix()}")) return out
def _changed(self, files: list[tuple[Path, str]]) -> list[tuple[Path, str]]: changed = [] for p, r in files: try: st = p.stat() except OSError: continue sig = (st.st_mtime_ns, st.st_size) if self._seen.get(p) != sig: changed.append((p, r)) return changed
def _mark(self, files: list[tuple[Path, str]]) -> None: for p, _ in files: try: st = p.stat() self._seen[p] = (st.st_mtime_ns, st.st_size) except OSError: pass
async def push(self, rt: AgentRuntime, *, rebase: bool = False) -> int: """`rebase`: may make a new base tar when one is due (periodic pushes only, so drain and preempt stay as cheap as a delta).""" try: return await self._push(rt, rebase) except Exception: self.stats.add("errors", "push_failed") raise
async def _push(self, rt: AgentRuntime, rebase: bool = False) -> int: pre = self.prefix(rt) if pre in self._restoring: # never mirror a half-restored agent (module docstring) log.warning("%s: push skipped, its restore is still running", rt.name) return 0 meta: list[tuple[Path, str]] = [] if rt.spec.persist_workdir and rt.workdir.is_dir(): exclude = workdir_excludes() + ephemeral_excludes(rt.spec) ws = WorkdirStats() await asyncio.to_thread(write_modes, rt.workdir, ws, exclude) rt.workdir_files, rt.workdir_stats = ws.files, ws self._quota(rt, ws) stats = {"files": ws.files, "bytes": ws.bytes} if self._meta.get(pre) != stats: # the workdir's size: predicts a restore's time path = rt.sessions_dir / f"{rt.name}.meta.json" path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps({**stats, "ts": datetime.now(UTC).isoformat()})) meta = [(path, pre + "meta.json")] delete = self.mirror_deletes(rt) if not delete: log.info("%s: workdir push without remote deletes (last restore incomplete)", rt.name) w = rt.spec.workdir or WorkdirSpec() if not (w.base and (pre in self._base or (rebase and delete)) and await self._push_base(rt, exclude, w, rebase and delete, ws)): await asyncio.to_thread(self.store.sync_up, rt.workdir, pre + "workdir", delete=delete, exclude=exclude) if pre in self._base and delete: # base turned off: the full mirror replaces it await asyncio.to_thread(self.store.delete, [pre + BASE_JSON, pre + BASE_TAR]) self._base.pop(pre) files = self._changed(self.collect(rt)) + meta if files: await asyncio.to_thread(self.store.upload, files) self._mark(files) if meta: self._meta[pre] = stats return len(files)
def _index_path(self, rt: AgentRuntime) -> Path: return rt.sessions_dir / f"{rt.name}.base-index.json"
async def _push_base(self, rt: AgentRuntime, exclude: list[str], w: WorkdirSpec, may_rebase: bool, ws: WorkdirStats) -> bool: """Workdir push with a base tar (module docstring, "Base tar"): a new base when due, then the files changed since the base, and tombstones and symlinks in the manifest. False: no base yet and none made (stopped, no disk); the caller mirrors file by file.""" pre, dpre = self.prefix(rt), self.prefix(rt) + "workdir/" base = self._base.get(pre)
def delta(): index = _load_index(self._index_path(rt)) return workdir_delta(rt.workdir, exclude, index, base["created_at"])
async def send() -> dict[str, float | None]: remote = {r[len(dpre):]: mt for r, mt in await asyncio.to_thread(self.store.list_info, dpre)} up = [(rt.workdir / r, dpre + r) for r, mt in files.items() if remote.get(r) is None or abs(remote[r] - mt) > 2e-3] if up: await asyncio.to_thread(self.store.upload, up) return remote
if base is not None: files, links, deleted = await asyncio.to_thread(delta) if may_rebase and (base is None or time.time() - base["created_at"] >= w.base_interval_s or len(files) + len(links) + len(deleted) > w.base_delta_files): if not _fits([(rt.sessions_dir, ws.bytes + ws.files * TAR_PER_FILE)]): log.warning("%s: no new workdir base, not enough free disk for a %s tar", rt.name, ws.summary()) elif (new := await self._make_base(rt, exclude)) is not None: base = new files, links, deleted = await asyncio.to_thread(delta) if base is None: return False remote = await send() if not self.mirror_deletes(rt): # tombstones and remote deletes: full baseline only return True while pre in self._building: # another push is making a base: its manifest goes first await asyncio.sleep(0.1) if self._base.get(pre) is not base: # ... and was committed: diff against it base = self._base[pre] files, links, deleted = await asyncio.to_thread(delta) remote = await send() if base.get("deleted", []) != deleted or base.get("links", {}) != links: await self._write_base(rt, {**base, "deleted": deleted, "links": links})
def stale(index: dict[str, list], r: str) -> bool: """Remote delta not needed: not changed in this walk and, locally, gone or as in the base (a file a concurrent push uploaded after this walk differs from it: it stays).""" if r in files or is_excluded(r, exclude): return False try: st = os.lstat(rt.workdir / r) except OSError: return True return _same(index.get(r), st.st_mtime, st.st_size)
def stale_all() -> list[str]: index = _load_index(self._index_path(rt)) return [dpre + r for r in remote if stale(index, r)]
gone = await asyncio.to_thread(stale_all) if gone: # deltas now in the base, or deleted await asyncio.to_thread(self.store.delete, gone) return True
async def _make_base(self, rt: AgentRuntime, exclude: list[str]) -> dict | None: """Tar the workdir, upload it, then commit `workdir.base.json` (the commit point); the local index of the base replaces the old one only after the commit. None when `stop_rebase` (drain, preempt) stopped it before the upload: nothing was written.""" pre = self.prefix(rt) tar, idx = rt.sessions_dir / f"{rt.name}.base.tar", self._index_path(rt) new_idx = idx.with_name(idx.name + ".new") self._building.add(pre) try: t0 = time.time() index = await asyncio.to_thread(write_base_tar, rt.workdir, exclude, tar, lambda: self.stop_rebase) if index is None or self.stop_rebase: log.info("%s: workdir base build stopped (drain or preempt)", rt.name) return None await asyncio.to_thread(_write_synced, new_idx, json.dumps(index)) await asyncio.to_thread(self.store.upload, [(tar, pre + BASE_TAR)]) base = {"created_at": t0, "files": len(index), "bytes": sum(s for _, s in index.values()), "deleted": [], "links": {}} await self._write_base(rt, base) os.replace(new_idx, idx) finally: self._building.discard(pre) tar.unlink(missing_ok=True) new_idx.unlink(missing_ok=True) log.info("%s: new workdir base: %d files, %.0f MB in %.1f s", rt.name, base["files"], base["bytes"] / 2**20, time.time() - t0) return base
async def _write_base(self, rt: AgentRuntime, base: dict) -> None: path = rt.sessions_dir / f"{rt.name}.base.json" path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(base)) await asyncio.to_thread(self.store.upload, [(path, self.prefix(rt) + BASE_JSON)]) self._base[self.prefix(rt)] = base
async def _restore_base(self, rt: AgentRuntime, skip: list[str]) -> tuple[dict | None, list[str], int]: """Manifest, then tar (extracted while read from disk), tombstones and symlinks. Returns (the manifest or None when the base could not be restored, failed bucket paths, files extracted).""" pre = self.prefix(rt) mpath, tar = rt.sessions_dir / f"{rt.name}.base.json", rt.sessions_dir / f"{rt.name}.base.tar" try: _, failed = await asyncio.to_thread(download_resilient, self.store, [(pre + BASE_JSON, mpath)]) if failed: return None, failed, 0 base = json.loads(mpath.read_text()) size = int(base["bytes"]) if not _fits([(rt.sessions_dir, size + int(base["files"]) * TAR_PER_FILE), (rt.workdir, size)]): log.error("%s: workdir base not restored: not enough free disk for %d MB " "(tar plus files)", rt.name, 2 * size // 2**20) return None, [pre + BASE_TAR], 0 _, failed = await asyncio.to_thread(download_resilient, self.store, [(pre + BASE_TAR, tar)]) if failed: return None, failed, 0 index, bad = await asyncio.to_thread(extract_base_tar, tar, rt.workdir, skip, base) except (OSError, ValueError, KeyError, AttributeError, tarfile.TarError) as e: log.warning("%s: workdir base not restored: %s", rt.name, _short(e)) return None, [pre + BASE_TAR], 0 finally: tar.unlink(missing_ok=True) await asyncio.to_thread(self._index_path(rt).write_text, json.dumps(index)) self._base[pre] = base if bad: log.warning("%s: %d workdir base entries not restored", rt.name, bad) return base, [pre + BASE_TAR] if bad else [], len(index)
def _quota(self, rt: AgentRuntime, ws: WorkdirStats) -> None: """Above the soft limit: a note in front of the agent's next prompt, and above the hard one a `workdir_over_quota` event, each at most hourly. The push itself goes on.""" w = rt.spec.workdir or WorkdirSpec() note, pre, now = quota_note(ws, w), self.prefix(rt), time.monotonic() if note is None or now - self._quota_at.get(pre, -QUOTA_NOTE_EVERY) < QUOTA_NOTE_EVERY: return rt._notes.pop(self._quota_note.pop(pre, None), None) # replace, do not stack rt._note(note) if note not in rt._notes: # dropped (no turn yet): try again at the next push return self._quota_at[pre] = now self._quota_note[pre] = note if over_hard_limit(ws, w): rt.emit("workdir_over_quota", {"files": ws.files, "bytes": ws.bytes, "top_dirs": [list(t) for t in ws.top_dirs]})
async def restore(self, rt: AgentRuntime) -> RestoreResult: try: return await self._restore(rt) except Exception: self.stats.add("errors", "restore_failed") raise
async def _restore(self, rt: AgentRuntime) -> RestoreResult: pre = self.prefix(rt) self._mirror[pre] = False # until this restore completes with every file self._restoring.add(pre) self.restore_progress[pre] = [0, 0, datetime.now(UTC)] try: res = await self._restore_files(rt, pre) finally: self._restoring.discard(pre) self.restore_progress.pop(pre, None) self._mirror[pre] = not res.failed return res
async def _restore_files(self, rt: AgentRuntime, pre: str) -> RestoreResult: lister = getattr(self.store, "list_info", None) if lister is not None: # raises: the caller starts fresh listed = await asyncio.to_thread(lister, pre) else: listed = [(r, None) for r in await asyncio.to_thread(self.store.list, pre)] mtimes = {r: mt for r, mt in listed} self._base.pop(pre, None) # known again only if this listing has one res = RestoreResult() work: list[tuple[str, Path]] = [] plan: list[tuple[str, Path]] = [] home = Path(rt.adapter.home) n = sum([await asyncio.to_thread(_clean_parts, d) for d in (rt.workdir, rt.sessions_dir)]) if n: log.info("%s: removed %d stray %s file(s)", rt.name, n, PART_SUFFIX) skip = workdir_excludes() + ephemeral_excludes(rt.spec) for r, _ in listed: rel = r[len(pre):] area, _, sub = rel.partition("/") if rel == "meta.json": # known, the first push after a move need not resend it plan.append((r, rt.sessions_dir / f"{rt.name}.meta.json")) continue if not sub or ".." in Path(sub).parts: continue if area == "workdir": if rt.spec.persist_workdir and not is_excluded(sub, skip): work.append((r, rt.workdir / sub)) elif area == "sessions": plan.append((r, rt.sessions_dir / sub)) elif area == "harness": plan.append((r, home / sub)) prog = self.restore_progress.get(pre) if prog is not None: prog[1] = len(work) + len(plan)
def progress(n: int) -> None: if prog is not None: prog[0] += n
if rt.spec.persist_workdir and pre + BASE_JSON in mtimes: base, failed, n = await self._restore_base(rt, skip) res.workdir, res.failed = n, res.failed + failed if prog is not None: prog[1] += n progress(n) if base is not None: # older deltas are already in the tar (or stale) work = [(r, p) for r, p in work if mtimes.get(r) is None or mtimes[r] > base["created_at"]] await asyncio.to_thread(_no_links, rt.workdir, work) if work: rt.workdir.mkdir(parents=True, exist_ok=True) got, failed = await asyncio.to_thread(download_resilient, self.store, work, progress=progress) res.workdir, res.failed = res.workdir + len(got), res.failed + failed await asyncio.to_thread(_set_mtimes, got, mtimes) if n := await asyncio.to_thread(apply_modes, rt.workdir): log.info("%s: restored the mode of %d file(s)", rt.name, n) if plan: for _, p in plan: _part(p).unlink(missing_ok=True) got, failed = await asyncio.to_thread(download_resilient, self.store, plan, progress=progress) res.failed += failed await asyncio.to_thread(_set_mtimes, got, mtimes) for r, p in got: if r == pre + "meta.json": try: self._meta[pre] = {k: v for k, v in json.loads(p.read_text()).items() if k in ("files", "bytes")} except (OSError, ValueError, AttributeError): pass elif r.startswith(pre + "sessions/"): res.sessions += 1 else: res.harness += 1 self._mark([(p, r) for r, p in got]) if res.failed: self.stats.add("errors", "restore_file_failed", len(res.failed)) state = f"{pre}sessions/{rt.state_path.name}" if state in res.failed: log.warning("%s: state file %s not restored; the agent starts a fresh session", rt.name, state) log.warning("%s: restored workdir=%d sessions=%d harness=%d; %d file(s) skipped " "(not found or still failing after retries), e.g. %s", rt.name, res.workdir, res.sessions, res.harness, len(res.failed), ", ".join(res.failed[:10])) else: log.info("%s: restored %s", rt.name, res) return res
def _no_links(workdir: Path, work: list[tuple[str, Path]]) -> None: """Deltas over a tar's symlinks: a file or directory replaced a symlink after the base, so remove symlinks at a delta's path and its parents, or the download writes through them.""" for _, p in work: parts = p.relative_to(workdir).parts for i in range(1, len(parts) + 1): q = workdir.joinpath(*parts[:i]) if q.is_symlink(): q.unlink() break if not q.is_dir(): break
def _set_mtimes(files: list[tuple[str, Path]], mtimes: dict[str, float | None]) -> None: """Give restored files the bucket's mtime, so the next `sync_up` sees them unchanged.""" for r, p in files: mt = mtimes.get(r) if mt is None: continue try: os.utime(p, (mt, mt), follow_symlinks=False) except (OSError, NotImplementedError): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239"""`legion.world`: a small base for writing a world in Python (docs/world.md).
A world is any HTTP server that speaks World API v1 (`legion.world.protocol`); this base is aconvenience, not a requirement. Subclass `World`, mark tool methods with `@tool`, and serve itwith `python -m legion.world serve module:Class` (`legion.world.server`):
from legion.world import Agent, ToolError, World, tool
class Counter(World): name, version = "counter", "0.1.0"
def __init__(self) -> None: self.n = 0
@tool def bump(self, agent: Agent, by: int = 1) -> dict: \"\"\"Add `by` to the shared counter and return it.\"\"\" if by < 1: raise ToolError("by must be >= 1") self.n += by return {"n": self.n, "by": agent.name}
Tool schemas come from the type hints and docstrings with the tools-folder rules(legion.tools.loader); a parameter named `agent` (or annotated `Agent`) receives thecaller and is never shown to the model. Override `manifest()` and `call()` to serve tools someother way. The hooks `on_agent_start`, `on_agent_done` and `on_turn` are sent only when asubclass overrides them (the manifest lists them in `hooks`)."""
from __future__ import annotations
import inspectimport osimport typingfrom collections.abc import Callablefrom dataclasses import dataclassfrom typing import Any
from legion.world.admin import TYPES, Admin, Knobfrom legion.world.protocol import HOOK_EVENTS, STATE_DIR_ENV, WORLD_API
AGENT_PARAM = "agent"
@dataclass(frozen=True)class Agent: """Who calls: the legion agent name, its type and swarm, the turn and the request id (as legion sent them; trust them when the token matched)."""
name: str type: str = "" swarm: str = "" turn: str = "" request_id: str = ""
class ToolError(Exception): """Raise from a tool: the agent reads `message` as the tool's error result. `retry_after_s`: the call cannot succeed before then (a budget, a busy backend); the server sends it in the error envelope and the worker may hold the tool off until then."""
def __init__(self, message: str, code: str = "tool_error", retry_after_s: float | None = None) -> None: super().__init__(message) self.code = code self.message = message self.retry_after_s = retry_after_s
POOLS = ("fast", "slow")
def tool(fn: Callable | None = None, *, pool: str = "fast", read_only: bool = False) -> Any: """Mark a method of a World subclass as a tool: `@tool`, or `@tool(pool="slow", read_only=True)`. `pool`: the server's thread pool for the call ("slow" for tools that block for seconds, so they never take the threads of the quick ones). `read_only`: the tool changes nothing (manifest `annotations.readOnlyHint`; the worker may retry it).""" if pool not in POOLS: raise ValueError(f"pool {pool!r} must be one of {POOLS}")
def mark(f: Callable) -> Callable: f.__legion_world_tool__ = True # type: ignore[attr-defined] f.__legion_world_pool__ = pool # type: ignore[attr-defined] f.__legion_world_read_only__ = read_only # type: ignore[attr-defined] return f
return mark if fn is None else mark(fn)
def _is_agent(p: inspect.Parameter, hints: dict[str, Any]) -> bool: hint = hints.get(p.name) return p.name == AGENT_PARAM or hint is Agent
def tool_schema(fn: Callable) -> dict[str, Any]: """{name, description, parameters} of a tool method (raises legion.tools.loader.ToolsError).""" from legion.tools.loader import tool_def
hints = typing.get_type_hints(fn) sig = inspect.signature(fn) keep = [p for p in sig.parameters.values() if not _is_agent(p, hints)]
def shim(*_a: Any, **_k: Any) -> None: ...
shim.__name__ = fn.__name__ shim.__doc__ = fn.__doc__ shim.__signature__ = sig.replace(parameters=keep) # type: ignore[attr-defined] shim.__annotations__ = {k: v for k, v in hints.items() if k in {p.name for p in keep}} d = tool_def(shim, type(getattr(fn, "__self__", fn)).__name__) return {"name": d.name, "description": d.description, "parameters": d.parameters}
class World: """Base class. Class attributes: `name` (lowercase, `[a-z][a-z0-9-]*`), `version` (any string; bump it when the tools change, agents are told), `description` (shown to the agents), `capabilities` (extra names for the manifest)."""
name: typing.ClassVar[str] = "world" version: typing.ClassVar[str] = "0.0.0" description: typing.ClassVar[str] = "" capabilities: typing.ClassVar[list[str]] = [] # False (default): the server runs one tool call or hook at a time (a global lock), so a # world needs no locking of its own. True: calls and hooks run concurrently in the # server's thread pool; the world guards its own state (a slow tool then never holds up # the hooks or the other agents' calls). concurrent: typing.ClassVar[bool] = False
# ------------------------------------------------------------------ tools def tools(self) -> dict[str, Callable]: """The bound `@tool` methods, by name (in definition order).""" found = self.__dict__.get("_legion_tools") if found is None: # no __init__ needed in subclasses: built on first use found = {} for klass in reversed(type(self).__mro__): for attr, value in vars(klass).items(): if getattr(value, "__legion_world_tool__", False): found[attr] = getattr(self, attr) self.__dict__["_legion_tools"] = found return found
def hooks(self) -> list[str]: """The hooks a subclass overrides.""" out = [] for event in HOOK_EVENTS: meth = f"on_{event}" if getattr(type(self), meth) is not getattr(World, meth): out.append(event) return out
def manifest(self) -> dict[str, Any]: """Built on every call (the server serves and dispatches from it), from the class attributes as they are now; the tool schemas are computed once.""" hooks = self.hooks() caps = list(dict.fromkeys([*self.capabilities, *(["hooks"] if hooks else [])])) schemas = self.__dict__.get("_legion_schemas") if schemas is None: schemas = [tool_schema(fn) for fn in self.tools().values()] for t, fn in zip(schemas, self.tools().values(), strict=True): if getattr(fn, "__legion_world_read_only__", False): t["annotations"] = {"readOnlyHint": True} self.__dict__["_legion_schemas"] = schemas return {"world_api": WORLD_API, "name": self.name, "version": self.version, "description": self.description, "tools": [dict(t) for t in schemas], "capabilities": caps, "hooks": hooks}
def call(self, tool: str, args: dict[str, Any], agent: Agent) -> Any: """Run `tool` for `agent`; the return value is the result (JSON-serialisable, or a coroutine the server awaits). Raise ToolError for an error the agent should read; KeyError for an unknown tool.""" fn = self.tools()[tool] hints = typing.get_type_hints(fn) extra = {p.name: agent for p in inspect.signature(fn).parameters.values() if _is_agent(p, hints)} return fn(**args, **extra)
def pool(self, tool: str) -> str: """The server's thread pool for `tool`: "fast" (default) or "slow" (`@tool(pool=)`).""" return getattr(self.tools().get(tool), "__legion_world_pool__", "fast")
def cancellable(self, tool: str) -> bool: """May the server cancel this tool's `async` work when its caller disconnects (the HTTP client gave up, e.g. on its own timeout)? Default False: the work always runs to the end. A world returns True for tools whose work is wasted once nobody reads it.""" return False
def metrics(self) -> dict[str, float]: """World-specific numbers for `GET /metrics` (under `world`). Called in a thread, concurrently with tools, every scrape (about every 30 s): keep it cheap; take your own lock if you need one. Default: none.""" return {}
# ------------------------------------------------------------------ admin (docs/world.md) def state_dir(self) -> str | os.PathLike | None: """Where `knobs.json` lives (knob values and paused lanes set through the admin API, read back at the next start). Default: $LEGION_WORLD_STATE_DIR, else None (kept in memory only). The server may call it before `__init__` ran (to serve /admin while the world cannot be built): do not rely on attributes `__init__` sets without a fallback.""" return os.environ.get(STATE_DIR_ENV) or None
@property def admin(self) -> Admin: """This world's knobs and paused lanes (the server may install one before __init__).""" if "_legion_admin" not in self.__dict__: self.__dict__["_legion_admin"] = Admin(self.state_dir()) return self.__dict__["_legion_admin"]
def knob(self, name: str, type: type, default: Any, *, min: float | None = None, max: float | None = None, doc: str = "", on_change: Callable[[Any], None] | None = None) -> Any: """Register a runtime knob (int, float, bool or str) and return its current value: the value set through `PATCH /admin/knobs` if any (it survives restarts), else `default`. A change calls `on_change(value)` (in a thread; raise to refuse it) and shows in `self.knobs[name]`.""" if type not in TYPES: raise ValueError(f"knob {name}: type must be one of int, float, bool, str") return self.admin.register(Knob(name, type, default, min, max, doc, on_change))
@property def knobs(self) -> dict[str, Any]: """The knobs' current values, by name (live: reflects admin changes).""" return self.admin.values
def paused(self, lane: str) -> bool: """Did an operator pause `lane` (`POST /admin/pause`)? Lanes are names the world chooses and documents (e.g. "push", "open", "merge").""" return lane in self.admin.paused
# ------------------------------------------------------------------ hooks def on_agent_start(self, agent: Agent) -> None: """An agent got its first prompt on its worker (again after a relaunch)."""
def on_agent_done(self, agent: Agent, data: dict[str, Any]) -> None: """An agent was removed from the swarm (scale down, `legion stop --delete`, `legion-agent remove`)."""
def on_turn(self, agent: Agent, data: dict[str, Any]) -> None: """An agent's turn ended: `data` has status, tool_calls, turn."""
__all__ = ["Admin", "Agent", "ToolError", "World", "tool", "tool_schema"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170"""Runtime knobs and lane pauses of a world (docs/world.md, "Admin API").
A world registers knobs (`World.knob`) and consults pauses (`World.paused`); operators changethem through the server's `/admin` routes. Values set there and the paused lanes are written to`knobs.json` in the world's state dir (`World.state_dir()`) and read back at the next start, so arequeued world keeps them; the defaults a world passes (often from its environment) apply onlyto knobs nobody set."""
from __future__ import annotations
import jsonimport loggingimport osimport reimport threadingfrom collections.abc import Callablefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any
log = logging.getLogger("legion.world")
KNOBS_FILE = "knobs.json"LANE_RE = re.compile(r"^[a-z][a-z0-9_.-]{0,63}$")TYPES = (int, float, bool, str)
@dataclassclass Knob: name: str type: type default: Any min: float | None = None max: float | None = None doc: str = "" on_change: Callable[[Any], None] | None = None
def check(self, value: Any) -> Any: """`value` as this knob's type (raises ValueError).""" t = self.type if t is bool or t is str: ok = isinstance(value, t) else: # int or float: JSON numbers, not booleans; 2.0 is an int, 2.5 is not ok = isinstance(value, int | float) and not isinstance(value, bool) and ( t is float or float(value).is_integer()) if not ok: raise ValueError(f"{self.name}: expected {t.__name__}, got {json.dumps(value)}") value = t(value) if self.min is not None and value < self.min: raise ValueError(f"{self.name}: {value} is below the minimum {self.min:g}") if self.max is not None and value > self.max: raise ValueError(f"{self.name}: {value} is above the maximum {self.max:g}") return value
def describe(self, value: Any) -> dict[str, Any]: return {"value": value, "default": self.default, "type": self.type.__name__, "min": self.min, "max": self.max, "doc": self.doc}
class Admin: """Knobs (name -> value) and paused lanes (lane -> reason), persisted in `<state dir>/knobs.json` when a state dir is given. Thread-safe."""
def __init__(self, state_dir: str | os.PathLike | None = None) -> None: self.path: Path | None = None self.knobs: dict[str, Knob] = {} self.values: dict[str, Any] = {} self.stored: dict[str, Any] = {} # values set through the admin API self.paused: dict[str, str] = {} self.lock = threading.RLock() if state_dir is not None: self.attach(state_dir)
def attach(self, state_dir: str | os.PathLike) -> None: """Read `knobs.json` from `state_dir` and save there from now on. Lanes paused before (while the world could not be built) stay paused.""" path = Path(state_dir) / KNOBS_FILE knobs: dict[str, Any] = {} paused: dict[str, str] = {} try: data = json.loads(path.read_text()) if not isinstance(data, dict): raise ValueError("not a JSON object") # noqa: TRY004 (handled below) knobs, paused = data.get("knobs") or {}, data.get("paused") or {} if not isinstance(knobs, dict) or not isinstance(paused, dict) or not all( isinstance(k, str) and isinstance(v, str) for k, v in paused.items()): raise ValueError('expected {"knobs": {name: value}, "paused": {lane: reason}}') except FileNotFoundError: pass except (OSError, ValueError) as e: # never park the world over this file log.warning("%s: unreadable (%s); starting from the defaults", path, e) knobs, paused = {}, {} with self.lock: self.path = path self.stored = dict(knobs) self.paused = {**paused, **self.paused}
def register(self, knob: Knob) -> Any: with self.lock: value = knob.check(knob.default) if knob.name in self.stored: try: value = knob.check(self.stored[knob.name]) except ValueError as e: log.warning("%s: stored value ignored: %s", KNOBS_FILE, e) self.knobs[knob.name] = knob self.values[knob.name] = value return value
def describe(self) -> dict[str, dict[str, Any]]: with self.lock: return {n: k.describe(self.values[n]) for n, k in self.knobs.items()}
def set(self, updates: dict[str, Any]) -> list[dict[str, Any]]: """Validate every update, apply them (on_change callbacks included) and save, all or nothing. Returns [{name, old, new}]; raises ValueError (nothing changed) on a bad value or a failing on_change (those already applied get on_change(old) back).""" if not isinstance(updates, dict) or not updates: raise ValueError("expected {knob: value, ...}") with self.lock: unknown = sorted(set(updates) - set(self.knobs)) if unknown: raise ValueError(f"unknown knob(s) {', '.join(unknown)}; knobs: " f"{', '.join(self.knobs) or 'none'}") checked = {n: self.knobs[n].check(v) for n, v in updates.items()} changes: list[dict[str, Any]] = [] for n, v in checked.items(): try: if self.knobs[n].on_change is not None: self.knobs[n].on_change(v) except Exception as e: # noqa: BLE001 (any refusal rolls the patch back) for c in reversed(changes): try: if self.knobs[c["name"]].on_change is not None: self.knobs[c["name"]].on_change(c["old"]) except Exception: log.exception("knob %s: restoring %r failed", c["name"], c["old"]) raise ValueError(f"{n}: the world refused {json.dumps(v)}: {e}") from None changes.append({"name": n, "old": self.values[n], "new": v}) for c in changes: self.values[c["name"]] = self.stored[c["name"]] = c["new"] self._save() return changes
def pause(self, lanes: list[str], reason: str = "") -> None: self._lanes(lanes) with self.lock: self.paused.update(dict.fromkeys(lanes, reason)) self._save()
def resume(self, lanes: list[str]) -> None: self._lanes(lanes) with self.lock: for lane in lanes: self.paused.pop(lane, None) self._save()
@staticmethod def _lanes(lanes: Any) -> None: if not isinstance(lanes, list) or not lanes or not all( isinstance(x, str) and LANE_RE.match(x) for x in lanes): raise ValueError(f"lanes: expected a list of names matching {LANE_RE.pattern}")
def _save(self) -> None: if self.path is None: return tmp = self.path.with_suffix(".tmp") tmp.write_text(json.dumps({"knobs": self.stored, "paused": self.paused}, indent=1)) tmp.replace(self.path)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385"""External-write lanes for worlds: bounded concurrency, a circuit breaker and a persistent outbox.
A world that writes to an outside service (a Git host, an API with one token) gives each kindof write its own lane, so one kind never starves another:
lanes = Lanes({"push": Lane(slots=1), "merge": Lane(slots=1), "comment": Lane(slots=1, gap_s=1.0)}, dir=state_dir) with lanes.hold("push", deadline=time.monotonic() + 20) as slot: # LaneBusy past deadline ...write...; slot.ok() # or slot.fail("transient") / slot.fail("final") lanes.outbox("comment", drain=post).put(key=pr, payload=text) # persistent, never drops
`Lane.slots`, `Lane.gap_s` and `Lane.paused` are plain attributes (`Lane.configure()` changesthe first two and wakes waiters); the breaker never changes them, it only lowers what iseffective while tripped."""from __future__ import annotations
import collectionsimport contextlibimport jsonimport loggingimport osimport threadingimport timeimport uuidfrom pathlib import Path
log = logging.getLogger("legion.world.lanes")POLL_S = 0.25 # longest single wait: notices pause flips, configure() and a test's fake clock
class LaneBusy(Exception): """No slot within the deadline; `reason` is "slots", "gap" or "paused"."""
def __init__(self, lane: str, reason: str, retry_after_s: float) -> None: super().__init__(f"lane {lane} busy ({reason}); retry in {retry_after_s:.0f} s") self.lane, self.reason, self.retry_after_s = lane, reason, retry_after_s
class Breaker: """Transient failures of one lane, or of a group of lanes that trip together."""
def __init__(self, trip_after: int, trip_window_s: float, quiet_s: float) -> None: self.trip_after, self.trip_window_s, self.quiet_s = trip_after, trip_window_s, quiet_s self.name = "" self.lock = threading.Lock() # a leaf lock: taken with a lane's cond held self.failures = collections.deque() # clock times of recent transient failures self.tripped = False
def failure(self, now: float) -> None: with self.lock: self.failures.append(now) while self.failures and self.failures[0] < now - self.trip_window_s: self.failures.popleft() if not self.tripped and len(self.failures) >= self.trip_after: self.tripped = True log.warning("lanes %s: tripped after %d transient failures in %.0f s; 1 slot and " "a gap until %.0f quiet s", self.name, len(self.failures), self.trip_window_s, self.quiet_s)
def is_tripped(self, now: float) -> bool: """Ends a trip after quiet_s without a transient failure.""" with self.lock: if self.tripped and now - self.failures[-1] >= self.quiet_s: self.tripped = False self.failures.clear() log.warning("lanes %s: recovered after %.0f quiet s", self.name, self.quiet_s) return self.tripped
class Lane: """One kind of external write.
Breaker: `trip_after` transient failures within `trip_window_s` trip the lane to min(slots, 1) slot and at least `trip_gap_s` between writes; after `quiet_s` without a transient failure it returns to `slots` and `gap_s`. `Lanes(breaker_groups=)` makes lanes share one breaker (the first lane's trip_after, trip_window_s and quiet_s)."""
def __init__(self, slots: int = 1, gap_s: float = 0.0, *, trip_after: int = 3, trip_window_s: float = 900.0, trip_gap_s: float = 5.0, quiet_s: float = 600.0, retry_after_s: float = 60.0) -> None: self.slots, self.gap_s, self.paused = slots, gap_s, False self.breaker = Breaker(trip_after, trip_window_s, quiet_s) self.trip_gap_s, self.retry_after_s = trip_gap_s, retry_after_s self.name, self.clock, self.paused_fn = "", time.monotonic, None # set by Lanes self.cond = threading.Condition() self.in_flight, self.last_at = 0, float("-inf") self.stats = {"waits_total": 0, "wait_s_total": 0.0, "ok": 0, "transient": 0, "final": 0}
def configure(self, slots: int | None = None, gap_s: float | None = None) -> None: with self.cond: if slots is not None: self.slots = slots if gap_s is not None: self.gap_s = gap_s self.cond.notify_all()
def is_paused(self) -> bool: return self.paused or bool(self.paused_fn and self.paused_fn(self.name))
def _effective(self, now): """(slots, gap_s) in force now (cond held).""" if self.breaker.is_tripped(now): return min(self.slots, 1), max(self.gap_s, self.trip_gap_s) return self.slots, self.gap_s
def acquire(self, deadline: float | None, pausable: bool = True) -> None: with self.cond: start = now = self.clock() while True: slots, gap = self._effective(now) reason = ("paused" if pausable and self.is_paused() else "slots" if self.in_flight >= slots else "gap" if now < self.last_at + gap else None) if reason is None: break if deadline is not None and now >= deadline: self.stats["waits_total"] += 1 self.stats["wait_s_total"] += now - start retry = (self.last_at + gap - now) if reason == "gap" else self.retry_after_s raise LaneBusy(self.name, reason, max(1.0, retry)) self.cond.wait(POLL_S if deadline is None else min(POLL_S, deadline - now)) now = self.clock() if now > start: self.stats["waits_total"] += 1 self.stats["wait_s_total"] += now - start self.in_flight += 1 self.last_at = now
def release(self) -> None: with self.cond: self.in_flight -= 1 self.cond.notify_all()
def report(self, kind: str) -> None: """Count an outcome: "ok", "transient" (feeds the breaker) or "final".""" with self.cond: self.stats[kind] += 1 if kind == "transient": self.breaker.failure(self.clock())
def metrics(self) -> dict: with self.cond: now = self.clock() slots, _ = self._effective(now) return {"slots": self.slots, "effective_slots": slots, "in_flight": self.in_flight, **self.stats, "tripped": int(self.breaker.is_tripped(now)), "paused": int(self.is_paused())}
class Slot: """A held slot: report the write's outcome with ok() or fail()."""
def __init__(self, lane: Lane) -> None: self.lane = lane
def ok(self) -> None: self.lane.report("ok")
def fail(self, kind: str = "transient") -> None: if kind not in ("transient", "final"): raise ValueError("kind must be transient or final") self.lane.report(kind)
class Outbox: """Writes for one lane that must happen eventually, drained by a background thread.
`drain(key, payloads)` makes one write of the queued payloads of `key` (more than one when they piled up: the world joins them; at most max_batch of them and max_chars characters, or one) and returns "ok", "transient" or "final" (an exception counts as transient), or "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 ok and final remove payloads. Stored as JSON lines in `path` (keys: str or int), compacted on load and when mostly settled."""
def __init__(self, lanes: Lanes, name: str, path: Path, drain, backoff=(5.0, 600.0), max_batch: int = 10, max_chars: int = 60_000) -> None: self.lanes, self.name, self.path, self.drain = lanes, name, path, drain self.backoff, self.max_batch, self.max_chars = backoff, max_batch, max_chars self.lock = threading.Lock() self.entries = {} # key -> {"payloads", "queued_at", "tries", "next_at"} in put order self.lines = 0 # lines in the file self._load() self.stop, self.wake = threading.Event(), threading.Event() self.thread = threading.Thread(target=self._run, name=f"lane-{name}-outbox", daemon=True) if drain is not None: self.thread.start()
def _entry(self, key, ts): return self.entries.setdefault(key, {"payloads": [], "queued_at": ts, "tries": 0, "next_at": 0.0, "batch": self.max_batch})
def _load(self): if self.path.exists(): for line in self.path.read_text().splitlines(): try: op = json.loads(line) if "put" in op: self._entry(op["put"], op["ts"])["payloads"].append(op["payload"]) elif op["done"] in self.entries: entry = self.entries[op["done"]] del entry["payloads"][:op["n"]] if not entry["payloads"]: del self.entries[op["done"]] except (ValueError, KeyError, TypeError): # a line cut by a crash log.warning("lane %s outbox: skipped an unreadable line", self.name) self._compact()
def _compact(self): """Rewrite the file with the pending payloads only (lock held, or during __init__).""" self.path.parent.mkdir(parents=True, exist_ok=True) tmp = self.path.with_name(f"{self.path.name}.{uuid.uuid4().hex}.tmp") with open(tmp, "w") as out: for key, e in self.entries.items(): out.writelines(json.dumps({"put": key, "payload": payload, "ts": e["queued_at"]}) + "\n" for payload in e["payloads"]) out.flush() os.fsync(out.fileno()) # the data is on disk before the name points at it os.replace(tmp, self.path) self.lines = sum(len(e["payloads"]) for e in self.entries.values())
def _append(self, op): with open(self.path, "a") as out: out.write(json.dumps(op) + "\n") self.lines += 1
def put(self, key, payload) -> None: """Queue payload for key; joins payloads of the same key still waiting.""" with self.lock: ts = self.lanes.wall() self._append({"put": key, "payload": payload, "ts": ts}) self._entry(key, ts)["payloads"].append(payload) self.wake.set()
def depth(self) -> tuple[int, float]: """(pending payloads, age in seconds of the oldest).""" with self.lock: now = self.lanes.wall() return (sum(len(e["payloads"]) for e in self.entries.values()), max((now - e["queued_at"] for e in self.entries.values()), default=0.0))
def _settle(self, key, n, kind): with self.lock: entry = self.entries.get(key) if entry is None: return if kind == "split": entry["batch"] = 1 return if kind == "transient": entry["tries"] += 1 delay = min(self.backoff[1], self.backoff[0] * 2 ** (entry["tries"] - 1)) entry["next_at"] = self.lanes.wall() + delay log.warning("lane %s outbox: write for %r failed; retry %d in %.0f s", self.name, key, entry["tries"], delay) return if kind == "final": log.warning("lane %s outbox: dropped %d payload(s) for %r: final", self.name, n, key) del entry["payloads"][:n] entry["tries"], entry["next_at"] = 0, 0.0 if kind != "ok": entry["batch"] = 1 # the rest of a refused batch goes one by one if not entry["payloads"]: del self.entries[key] self._append({"done": key, "n": n}) pending = sum(len(e["payloads"]) for e in self.entries.values()) if self.lines > 2 * pending + 1000: self._compact()
def _batch(self, key): """The payloads of key for the next write (lock held): oldest first, within the entry's batch size and max_chars, at least one.""" entry = self.entries.get(key) if entry is None: return [] out, chars = [], 0 for payload in entry["payloads"][:entry["batch"]]: chars += len(payload if isinstance(payload, str) else json.dumps(payload)) if out and chars > self.max_chars: break out.append(payload) return out
def _run(self): while not self.stop.is_set(): try: self._step() except Exception: # keep the thread alive: a disk error, a bad drain result log.exception("lane %s outbox: drain loop failed", self.name) self.stop.wait(POLL_S)
def _step(self): with self.lock: now = self.lanes.wall() due = [(e["queued_at"], i, k) for i, (k, e) in enumerate(self.entries.items()) if e["next_at"] <= now] key = min(due)[2] if due else None if key is None: self.wake.wait(POLL_S) self.wake.clear() return try: with self.lanes.hold(self.name, deadline=self.lanes.clock() + 1.0) as slot: with self.lock: # taken with the slot held: joins what piled up meanwhile payloads = self._batch(key) if not payloads: return try: kind = self.drain(key, payloads) or "ok" except Exception: log.exception("lane %s outbox: drain failed", self.name) kind = "transient" if kind not in ("ok", "transient", "final", "split"): raise ValueError(f"drain returned {kind!r}") if kind == "split" and len(payloads) == 1: kind = "transient" if kind == "ok": slot.ok() elif kind != "split": slot.fail(kind) except LaneBusy: self.stop.wait(POLL_S) return self._settle(key, len(payloads), kind)
def close(self, timeout: float = 5.0) -> None: self.stop.set() self.wake.set() if self.thread.is_alive() and self.thread is not threading.current_thread(): self.thread.join(timeout)
class Lanes: """Named lanes sharing a clock, an optional `paused(name)` callback and a state dir for outboxes (`<dir>/outbox-<name>.jsonl`). `breaker_groups`: tuples of lane names that share one breaker (writes that fail together, e.g. two kinds that move the same refs)."""
def __init__(self, lanes: dict[str, Lane], dir: str | Path | None = None, clock=time.monotonic, wall=time.time, paused=None, breaker_groups: list[tuple[str, ...]] = ()) -> None: self.lanes, self.dir, self.clock, self.wall = lanes, Path(dir) if dir else None, clock, wall self.outboxes: dict[str, Outbox] = {} for name, lane in lanes.items(): lane.name, lane.clock, lane.paused_fn = name, clock, paused lane.breaker.name = name for group in breaker_groups: # a transient failure in any of them trips them all shared = lanes[group[0]].breaker shared.name = "+".join(group) for name in group[1:]: lanes[name].breaker = shared
def __getitem__(self, name: str) -> Lane: return self.lanes[name]
@contextlib.contextmanager def hold(self, name: str, deadline: float | None = None, pausable: bool = True): """Hold a slot of lane `name`, waiting until `deadline` (on `clock`; None: no limit); raises LaneBusy. `pausable=False` ignores the pause (e.g. closing what was opened).""" lane = self.lanes[name] lane.acquire(deadline, pausable) try: yield Slot(lane) finally: lane.release()
def outbox(self, name: str, drain=None, **kwargs) -> Outbox: """The lane's outbox; the first call with `drain` starts its drainer thread.""" if name not in self.outboxes: if self.dir is None: raise ValueError("Lanes(dir=...) is needed for an outbox") self.outboxes[name] = Outbox(self, name, self.dir / f"outbox-{name}.jsonl", drain, **kwargs) return self.outboxes[name]
def metrics(self) -> dict[str, dict]: out = {} for name, lane in self.lanes.items(): box = self.outboxes.get(name) depth, age = box.depth() if box else (0, 0.0) out[name] = {**lane.metrics(), "outbox_depth": depth, "outbox_oldest_age_s": age} return out
def close(self, timeout: float = 5.0) -> None: """Stop the drainer threads; what is queued stays on disk for the next start.""" end = time.monotonic() + timeout for box in self.outboxes.values(): box.close(max(0.0, end - time.monotonic()))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208"""World API v1 (docs/world.md): the names both sides agree on and the manifest model.
A world is any HTTP server that answers two routes with a shared secret:
GET /manifest -> {"world_api": "v1", "name", "version", "tools": [...], ...} POST /tools/<name> {"args": {...}} -> {"ok": true, "result": ...} | {"ok": false, "error": {"code", "message"}} POST /hooks {"event", "agent", "type", "swarm", "data"} (optional)
Every request carries `X-World-Token` (the secret, or on `/manifest` and tool calls the callingagent's own `agent_token`); a tool call also names the calling agent(`X-Legion-Agent`, `X-Legion-Type`, `X-Legion-Swarm`, `X-Legion-Turn`, `X-Request-Id`). This moduleis pydantic-only, so the worker, the controller and a world written with `legion.world` share it."""
from __future__ import annotations
import hashlibimport hmacimport refrom typing import Any
from pydantic import BaseModel, Field, field_validator, model_validator
WORLD_API = "v1"
TOKEN_HEADER = "X-World-Token"AGENT_HEADER = "X-Legion-Agent"TYPE_HEADER = "X-Legion-Type"SWARM_HEADER = "X-Legion-Swarm"TURN_HEADER = "X-Legion-Turn"REQUEST_HEADER = "X-Request-Id"
# Environment of a world legion starts (and of `python -m legion.world serve`), and of the workers.TOKEN_ENV = "LEGION_WORLD_TOKEN"PORT_ENV = "LEGION_WORLD_PORT"HOST_ENV = "LEGION_WORLD_HOST"SWARM_ENV = "LEGION_SWARM"STATE_DIR_ENV = "LEGION_WORLD_STATE_DIR" # knobs.json (World.state_dir)# The /admin secret of a world (docs/world.md, "Admin API"); never derived from the world# secret, which every worker holds. Unset: /admin answers 403.ADMIN_TOKEN_ENV = "LEGION_WORLD_ADMIN_TOKEN"
# Hooks legion sends to a world that lists them in its manifest's `hooks` (POST /hooks).HOOK_EVENTS = ("agent_start", "agent_done", "turn")
WORLD_NAME_RE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")TOOL_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
class WorkspaceUpload(BaseModel): """`x-legion-workspace` on a tool (worlds with workspace-upload-v1): the worker uploads the local clone named by argument `arg` (`default` when absent), unless the value is in `skip` or starts with `skip_prefix`."""
arg: str default: str | None = None skip: list[str] = Field(default_factory=list) skip_prefix: str | None = None
class WorldTool(BaseModel): """One tool: a Chat Completions function (`parameters` is a JSON schema of type object), plus optional legion metadata: `x-legion-workspace` and `x-legion-timeout_s` (the least HTTP timeout the worker gives this tool's calls), and `annotations.readOnlyHint` (the tool changes nothing: the worker may retry it once)."""
model_config = {"extra": "ignore", "populate_by_name": True}
name: str description: str = "" parameters: dict[str, Any] = Field(default_factory=lambda: {"type": "object", "properties": {}}) workspace: WorkspaceUpload | None = Field(None, alias="x-legion-workspace") timeout_s: float | None = Field(None, alias="x-legion-timeout_s", gt=0) annotations: dict[str, Any] = Field(default_factory=dict) # MCP-style, e.g. readOnlyHint
@property def read_only(self) -> bool: return self.annotations.get("readOnlyHint") is True
@model_validator(mode="before") @classmethod def _old_keys(cls, v: Any) -> Any: # the keys' former prefix: ignored as unknown otherwise, and the upload/timeout silently off old = sorted(k for k in v if isinstance(k, str) and k.startswith("x-flock-")) if isinstance(v, dict) else [] if old: raise ValueError(f"{', '.join(old)}: renamed to x-legion-*") return v
@field_validator("name") @classmethod def _name(cls, v: str) -> str: if not TOOL_NAME_RE.match(v): raise ValueError(f"tool name {v!r} must match {TOOL_NAME_RE.pattern}") return v
@field_validator("parameters") @classmethod def _params(cls, v: dict[str, Any]) -> dict[str, Any]: if v.get("type", "object") != "object": raise ValueError("parameters must be a JSON schema of type object") props = v.get("properties", {}) if not isinstance(props, dict): raise ValueError("parameters.properties must be an object") # noqa: TRY004 (pydantic) return {**v, "type": "object", "properties": props}
class WorldManifest(BaseModel): """What `GET /manifest` returns. Unknown fields are ignored (changes within v1 are additive); unknown capabilities and hooks are kept but never used."""
model_config = {"extra": "ignore"}
world_api: str name: str version: str description: str = "" # shown to the agents above the tool list tools: list[WorldTool] = Field(default_factory=list) capabilities: list[str] = Field(default_factory=list) hooks: list[str] = Field(default_factory=list) # which of HOOK_EVENTS to send
@field_validator("world_api") @classmethod def _api(cls, v: str) -> str: if v != WORLD_API: raise ValueError(f"world_api {v!r} is not supported (this legion speaks {WORLD_API!r})") return v
@field_validator("name") @classmethod def _name(cls, v: str) -> str: if not WORLD_NAME_RE.match(v): raise ValueError(f"name {v!r} must match {WORLD_NAME_RE.pattern}") return v
@field_validator("version") @classmethod def _version(cls, v: str) -> str: if not v.strip(): raise ValueError("version must not be empty") return v
@field_validator("tools") @classmethod def _unique(cls, v: list[WorldTool]) -> list[WorldTool]: seen: set[str] = set() for t in v: if t.name in seen: raise ValueError(f"tool {t.name!r} is listed twice") seen.add(t.name) return v
def names(self) -> list[str]: return [t.name for t in self.tools]
def get(self, name: str) -> WorldTool | None: return next((t for t in self.tools if t.name == name), None)
def agent_token(secret: str, agent: str) -> str: """One agent's own world token: a world accepts it instead of its secret on `/manifest` and tool calls whose `X-Legion-Agent` is `agent`, so a token in an agent's hands acts only as it.""" return hmac.new(secret.encode(), f"legion-world-agent\0{agent}".encode(), hashlib.sha256).hexdigest()
def credential_id(token: str, origin: str) -> str: """Names a (secret, origin) pair without revealing the secret: the controller writes it into the world block, a worker compares it with its own secret's before sending it.""" return hmac.new(token.encode(), f"legion-world-credential\0{origin}".encode(), hashlib.sha256).hexdigest()[:32]
WORLD_HOST_VAR = "${WORLD_HOST}" # in world.url: the host is read from LEGION_WORLD_HOST_FILEWORLD_HOST_FILE_ENV = "LEGION_WORLD_HOST_FILE"DEFAULT_PORT = 7860 # what an old host-only host file means (the url's own port)
def fill_host(url: str, var: str, host: str) -> str: """`url` with `var` (`${WORLD_HOST}`, `${CTL_HOST}`) replaced by a host file's first word: `host:port` (the jobs bind a free port) also replaces the url's port after `var`; an old host-only file keeps the url's port (DEFAULT_PORT in every spec).""" return re.sub(re.escape(var) + (r"(:\d+)?" if ":" in host else ""), lambda _: host, url)
def origin_matches(origin: str, endpoint: str) -> bool: """A secret bound to `origin` may go to `endpoint`: the same URL, or, for a world.url with ${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).""" if origin == endpoint: return True if WORLD_HOST_VAR not in origin: return False pre, _, post = origin.partition(WORLD_HOST_VAR) host, port = r"[A-Za-z0-9.-]+", r":[0-9]+" rest = re.sub(r"^:\d+", "", post) # a host:port file replaces this port return bool(re.fullmatch(re.escape(pre) + host + "(?:" + re.escape(post) + "|" + port + re.escape(rest) + ")", endpoint))
def manifest_error(exc: Exception) -> str: """One line from a pydantic ValidationError (or anything else).""" errors = getattr(exc, "errors", None) if callable(errors): parts = [] for e in errors()[:3]: where = ".".join(str(x) for x in e.get("loc", ())) parts.append(f"{where + ': ' if where else ''}{e.get('msg')}") return "; ".join(parts) return str(exc)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698"""Serve a `legion.world.World` over HTTP (World API v1, docs/world.md).
`python -m legion.world serve module:Class` imports `module` from the current directory, instantiates`Class` (or takes a World instance named so) and serves it with uvicorn on`$LEGION_WORLD_HOST:$LEGION_WORLD_PORT` (default 127.0.0.1:8765), requiring `X-World-Token` toequal `$LEGION_WORLD_TOKEN`. Synchronous tools and hooks run one at a time (a lock), so a worldneeds no locking of its own, unless it is `concurrent`; they run in two thread pools, "fast"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)` iscancelled when its caller disconnects (checked every second), so a call nobody waits for anymore stops instead of running to the end.`GET /metrics` (same token) reports calls, errors, latencies and bytes per tool over the last5 minutes, the pools' queues, event-loop lag, RSS, CPU and the world's own `metrics()` (JSON, orPrometheus text for `Accept: text/plain`).Parked mode: `serve` binds the port first and builds the world in a background thread, retryingwith backoff while that raises; meanwhile `/manifest`, tools and hooks answer 503 (`parked`).`GET /healthz` (no token) says "ready" or "parked". `/admin/*` (the admin secret, never the worldtoken) reads and sets the world's knobs and pauses its lanes (`legion.world.admin`).Needs the `controller` extra (FastAPI, uvicorn)."""
from __future__ import annotations
import asyncioimport contextlibimport hmacimport importlibimport inspectimport jsonimport loggingimport mathimport osimport reimport resourceimport sysimport threadingimport timeimport uuidfrom collections import Counter, dequefrom collections.abc import Callablefrom typing import Any
from anyio import CapacityLimiter, to_threadfrom fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponse, PlainTextResponse, Responsefrom starlette.datastructures import Headers
from legion.tools.loader import check_argsfrom legion.world import Admin, Agent, ToolError, Worldfrom legion.world.protocol import ( ADMIN_TOKEN_ENV, AGENT_HEADER, HOOK_EVENTS, HOST_ENV, PORT_ENV, REQUEST_HEADER, SWARM_HEADER, TOKEN_ENV, TOKEN_HEADER, TURN_HEADER, TYPE_HEADER, agent_token,)from legion.world.workspace import MAX_BYTES
log = logging.getLogger("legion.world")
DEFAULT_PORT = 8765FAST_THREADS = 40 # tools that answer in well under a second, and hooksSLOW_THREADS = 64 # tools that block for seconds or minutes (`@tool(pool="slow")`)# Admission control (docs/world.md): a tool call is refused with 429 when the fast pool's oldest# queued call waited longer than this, or the slow pool holds its threads plus this many queued.FAST_MAX_WAIT_ENV, FAST_MAX_WAIT_S = "LEGION_WORLD_FAST_MAX_WAIT_S", 2.0SLOW_QUEUE_ENV, SLOW_QUEUE = "LEGION_WORLD_SLOW_QUEUE", 8RETRY_AFTER_ENV, RETRY_AFTER_S = "LEGION_WORLD_RETRY_AFTER_S", 30.0REFUSAL_LOG_EVERY_S = 10.0 # at most one WARNING per pool this often about refused calls# Parked mode: a world whose construction raises is built again after 30 s, doubling to 10 min.PARK_FIRST_S, PARK_CAP_S = 30.0, 600.0ADMIN_MAX_BYTES = 64 << 10 # an /admin request body
WINDOW_S = 300.0 # /metrics: calls, latencies, bytes and queue waits over the last 5 minutesMAX_SAMPLES = 20_000 # per log, besides the window: bounded when nobody scrapes /metrics
class _Metrics: """What GET /metrics reports. `call` and `lag` run on the event loop; `waited` runs in a pool thread (a deque append is atomic)."""
def __init__(self, clock: Any = time.monotonic) -> None: self.clock = clock self.started = clock() self.calls: dict[str, deque] = {} # tool -> (t, latency_s or None if refused, code, in, out) self.totals: dict[str, list[int]] = {} # tool -> [calls, errors] since start self.waits: dict[str, deque] = {p: deque(maxlen=MAX_SAMPLES) for p in ("fast", "slow")} # pool -> (t, wait_s) self.lags: deque = deque(maxlen=MAX_SAMPLES) # (t, event-loop lag in s) self.overloaded = 0 self.refused = {"fast": 0, "slow": 0} # pool -> calls refused with 429 since start self.uploads = {"v1": 0, "v2": 0} # workspace uploads received, by format self.cpu_mark = (time.monotonic(), sum(os.times()[:2]))
def _trim(self, q: deque, now: float) -> deque: while q and q[0][0] < now - WINDOW_S: q.popleft() return q
def call(self, tool: str, latency: float | None, code: str | None, n_in: int, n_out: int) -> None: now = self.clock() self._trim(self.calls.setdefault(tool, deque(maxlen=MAX_SAMPLES)), now).append((now, latency, code, n_in, n_out)) totals = self.totals.setdefault(tool, [0, 0]) totals[0] += 1 totals[1] += code is not None
def waited(self, pool: str, wait: float) -> None: self.waits[pool].append((self.clock(), wait))
def lag(self, lag: float) -> None: now = self.clock() self._trim(self.lags, now).append((now, lag))
async def sample_lag(self) -> None: """Every second: how late a 1 s sleep wakes up (the event loop's lag).""" loop = asyncio.get_running_loop() while True: t = loop.time() await asyncio.sleep(1) self.lag(max(0.0, loop.time() - t - 1))
def snapshot(self, pools: dict[str, dict[str, float]]) -> dict[str, Any]: now = self.clock() tools = {} for name, q in self.calls.items(): rows = list(self._trim(q, now)) lat = sorted(r[1] for r in rows if r[1] is not None) tools[name] = { "calls": len(rows), "errors_by_code": dict(Counter(r[2] for r in rows if r[2])), "latency_p50_s": _pct(lat, 0.5), "latency_p95_s": _pct(lat, 0.95), "latency_max_s": lat[-1] if lat else 0.0, "bytes_in": sum(r[3] for r in rows), "bytes_out": sum(r[4] for r in rows), "calls_total": self.totals[name][0], "errors_total": self.totals[name][1]} for pool, stats in pools.items(): waits = sorted(w for _, w in list(self._trim(self.waits[pool], now))) stats.update(queue_wait_p95_s=_pct(waits, 0.95), overloaded_429_total=self.refused[pool], queue_wait_max_s=max(waits[-1] if waits else 0.0, stats["queue_wait_oldest_s"])) lags = [g for _, g in self._trim(self.lags, now)] wall, cpu = time.monotonic(), sum(os.times()[:2]) cpu_pct = 100 * (cpu - self.cpu_mark[1]) / max(1e-9, wall - self.cpu_mark[0]) self.cpu_mark = (wall, cpu) return {"uptime_s": now - self.started, "rss_mb": _rss_mb(), "cpu_pct": cpu_pct, "loop_lag_s": lags[-1] if lags else 0.0, "loop_lag_max_s": max(lags, default=0.0), "overloaded_429_total": self.overloaded, "upload_v1_total": self.uploads["v1"], "upload_v2_total": self.uploads["v2"], "window_s": WINDOW_S, "tools": tools, "pools": pools}
def _finite(v: Any) -> bool: """A number JSON and Prometheus text can carry (no bool, NaN or inf).""" return isinstance(v, int | float) and not isinstance(v, bool) and math.isfinite(v)
def _pct(values: list[float], q: float) -> float: """Nearest-rank percentile of sorted `values` (0.0 when empty).""" return values[max(0, math.ceil(q * len(values)) - 1)] if values else 0.0
def _rss_mb() -> float: try: with open("/proc/self/statm") as f: return int(f.read().split()[1]) * os.sysconf("SC_PAGE_SIZE") / 2**20 except (OSError, ValueError, IndexError): # not Linux: the peak instead return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024
def _lv(v: Any) -> str: # Prometheus label-value escaping return '"' + str(v).replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"'
def _prometheus(m: dict[str, Any]) -> str: """The /metrics JSON as Prometheus text exposition (untyped samples), lines grouped per metric name.""" groups: dict[str, list[str]] = {}
def add(metric: str, labels: str, v: Any) -> None: groups.setdefault(metric, []).append(f"{metric}{labels} {v}")
for key, value in m.items(): if key in ("tools", "pools"): label = key[:-1] for name, stats in value.items(): for k, v in stats.items(): if k == "errors_by_code": for c, n in v.items(): add("legion_world_tool_errors", f"{{tool={_lv(name)},code={_lv(c)}}}", n) else: add(f"legion_world_{label}_{k}", f"{{{label}={_lv(name)}}}", v) elif key == "world": for k, v in value.items(): add(f"legion_world_world_{re.sub(r'[^A-Za-z0-9_]', '_', k)}", "", v) else: add(f"legion_world_{key}", "", value) return "\n".join(l for g in groups.values() for l in g) + "\n"
_SECRET_NAME = re.compile(r"TOKEN|SECRET|PASSWORD|INVITE|API_KEY|_KEY$", re.IGNORECASE)
def _secret_values(env=None) -> list[str]: """Values of the world process's secret-looking variables (8+ chars), longest first.""" env = os.environ if env is None else env return sorted({v for k, v in env.items() if _SECRET_NAME.search(k) and len(v) >= 8}, key=len, reverse=True)
def redact(value: Any, secrets: list[str] | None = None) -> Any: """`value` (JSON-able) with every secret value replaced by "[redacted]".""" secrets = _secret_values() if secrets is None else secrets if not secrets: return value text = json.dumps(value, default=str) if not any(s in text for s in secrets): return value for s in secrets: text = text.replace(json.dumps(s)[1:-1], "[redacted]") return json.loads(text)
def _ok_body(result: Any) -> bytes: """The success envelope for `result`, serialized and redacted (in a worker thread).""" return json.dumps({"ok": True, "result": redact(json.loads(json.dumps(result, default=str)))} ).encode()
def _error(code: str, message: str, status: int = 200, retry_after_s: float | None = None) -> JSONResponse: error: dict[str, Any] = {"code": code, "message": message} if retry_after_s is not None: error["retry_after_s"] = retry_after_s return JSONResponse({"ok": False, "error": error}, status_code=status)
class _Auth: """`X-World-Token`: the world secret on every route but `/healthz` (none) and `/admin/*` (the admin secret), or on `/manifest` and `/tools/*` the caller's `agent_token` for its `X-Legion-Agent`. An empty world secret: open; an empty admin secret: /admin is 403."""
def __init__(self, app: Any, token: str, admin: str) -> None: self.app, self.token, self.admin = app, token, admin
async def __call__(self, scope: dict, receive: Any, send: Any) -> None: if scope["type"] == "http": path = scope["path"] admin = path == "/admin" or path.startswith("/admin/") need = "" if path == "/healthz" else self.admin if admin else self.token if admin and not need: await _error("forbidden", f"no admin secret: set {ADMIN_TOKEN_ENV} on the world", 403)(scope, receive, send) return headers = Headers(scope=scope) got, agent = headers.get(TOKEN_HEADER, ""), headers.get(AGENT_HEADER, "") own = bool(agent) and (path == "/manifest" or path.startswith("/tools/")) \ and hmac.compare_digest(got, agent_token(need, agent)) if need and not (hmac.compare_digest(got, need) or own): await _error("unauthorized", f"missing or wrong {TOKEN_HEADER}", 401)( scope, receive, send) return await self.app(scope, receive, send)
DISCONNECT_POLL_S = 1.0
class _Gone(Exception): """The caller disconnected before the tool finished."""
async def _unless_gone(aw: Any, request: Request) -> Any: """Await `aw`, cancelling it if the client disconnects first (raises _Gone).""" task = asyncio.ensure_future(aw) try: while True: done, _ = await asyncio.wait({task}, timeout=DISCONNECT_POLL_S) if done: return task.result() if await request.is_disconnected(): task.cancel() await asyncio.wait({task}) raise _Gone except asyncio.CancelledError: task.cancel() # this handler cancelled: the tool's work goes too raise
def _agent(headers: Any) -> Agent: return Agent(name=headers.get(AGENT_HEADER, ""), type=headers.get(TYPE_HEADER, ""), swarm=headers.get(SWARM_HEADER, ""), turn=headers.get(TURN_HEADER, ""), request_id=headers.get(REQUEST_HEADER, ""))
def create_app(world: World | Callable[[Admin], World], token: str | None) -> FastAPI: """The ASGI app for `world`. `token` None or "": no authentication (tests, a trusted network); otherwise every route needs `X-World-Token: <token>`. `/admin/*` needs the admin secret, $LEGION_WORLD_ADMIN_TOKEN (unset: 403). `world` may be a builder, `build(admin) -> World`: the app starts parked and builds the world in a thread once it runs, again with backoff while that raises.""" metrics = _Metrics() build = None if isinstance(world, World) else world world = world if isinstance(world, World) else None parked_admin = Admin() # /admin while no world is built; the builder hands it to the world park: dict[str, Any] = {"error": "the world is starting", "attempt": 0, "retry_at": 0.0} stop = threading.Event()
def builder() -> None: nonlocal world delay = PARK_FIRST_S while not stop.is_set(): park["attempt"] += 1 try: built = build(parked_admin) except BaseException as e: # SystemExit too: a parked error, not a dead thread log.exception("world: construction failed (attempt %d); retrying in %g s", park["attempt"], delay) line = (f"{type(e).__name__}: {e}".strip().splitlines() or [""])[0][:300] park.update(error=redact(line), retry_at=time.monotonic() + delay) if stop.wait(delay): return delay = min(delay * 2, PARK_CAP_S) continue world = built log.info("world %s %s: ready after %d attempt(s)", built.name, built.version, park["attempt"]) return
@contextlib.asynccontextmanager async def lifespan(_app: FastAPI) -> Any: task = asyncio.create_task(metrics.sample_lag()) if build is not None: threading.Thread(target=builder, name="world-build", daemon=True).start() try: yield finally: stop.set() task.cancel()
def admin() -> Admin: return world.admin if world is not None else parked_admin
def parked() -> Response | None: """503 while the world is not built (parked mode), else None.""" if world is not None: return None left = max(0.0, park["retry_at"] - time.monotonic()) resp = JSONResponse({"ok": False, "parked": True, "error": park["error"], "attempt": park["attempt"], "next_retry_s": math.ceil(left)}, 503) resp.headers["Retry-After"] = str(max(1, math.ceil(left))) return resp
app = FastAPI(title="world", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan) lock = threading.Lock() # Separate thread budgets: a slow tool (minutes) never takes a fast tool's or a hook's thread. limiters = {"fast": CapacityLimiter(FAST_THREADS), "slow": CapacityLimiter(SLOW_THREADS)} queued: dict[str, dict[object, float]] = {p: {} for p in limiters} # pool -> call -> since queued_lock = threading.Lock()
async def run(pool: str, fn, *args: Any) -> Any: pool = pool if pool in limiters else "fast" key, since = object(), metrics.clock() with queued_lock: queued[pool][key] = since
def started(*a: Any) -> Any: # in the pool thread: the call left the queue with queued_lock: queued[pool].pop(key, None) metrics.waited(pool, metrics.clock() - since) return locked(fn, *a)
try: return await to_thread.run_sync(started, *args, limiter=limiters[pool]) finally: # cancelled while queued with queued_lock: queued[pool].pop(key, None)
fast_max_wait = float(os.environ.get(FAST_MAX_WAIT_ENV) or FAST_MAX_WAIT_S) slow_queue = int(os.environ.get(SLOW_QUEUE_ENV) or SLOW_QUEUE) retry_after = float(os.environ.get(RETRY_AFTER_ENV) or RETRY_AFTER_S)
def overloaded(pool: str) -> str | None: """Why a new call to `pool` is refused now, or None.""" stats = pool_stats()[pool] if pool == "slow" and stats["in_flight"] >= stats["limit"] + slow_queue: return f"{stats['in_flight']:.0f} slow calls running or queued" if pool == "fast" and stats["queue_wait_oldest_s"] > fast_max_wait: return f"calls wait {stats['queue_wait_oldest_s']:.1f} s for a thread" return None
refusal_log = {p: [-math.inf, 0] for p in limiters} # pool -> [last WARNING at, refused then]
def log_refusal(pool: str, name: str, why: str) -> None: """A WARNING with the reason, at most every REFUSAL_LOG_EVERY_S per pool (event loop).""" now, (last, mark) = metrics.clock(), refusal_log[pool] if now - last >= REFUSAL_LOG_EVERY_S: log.warning("%s pool overloaded (%s): refused %s; %d more since the last line", pool, why, name, metrics.refused[pool] - mark - 1) refusal_log[pool] = [now, metrics.refused[pool]]
def pool_stats() -> dict[str, dict[str, float]]: now = metrics.clock() with queued_lock: waiting = {p: (len(q), min(q.values(), default=now)) for p, q in queued.items()} return {p: {"in_flight": lim.borrowed_tokens + waiting[p][0], "queued": waiting[p][0], "limit": lim.total_tokens, "queue_wait_oldest_s": now - waiting[p][1]} for p, lim in limiters.items()}
cache: dict[str, Any] = {"version": None}
def served() -> dict[str, Any]: """The manifest as served now, serialized once per manifest version (on the event loop: a health check never waits for a thread): what GET /manifest advertises is what is called. Building the dict is cheap; serializing it is not. Rebuilt only when `version` changes: a world that changes its description or capabilities at runtime must bump `version`.""" m = world.manifest() knobs = list(world.admin.knobs) if cache["version"] != (m.get("version"), knobs): caps = list(dict.fromkeys([*(m.get("capabilities") or []), "metrics-v1", "admin-v1"])) body = {**m, "capabilities": caps, "knobs": knobs} cache.update(version=(m.get("version"), knobs), body=json.dumps(body).encode(), schemas={ t["name"]: t.get("parameters") or {"type": "object", "properties": {}} for t in m.get("tools") or []}) return cache
def locked(fn, *args: Any) -> Any: if getattr(world, "concurrent", False): # the world guards its own state return fn(*args) with lock: return fn(*args)
# plain ASGI (not @app.middleware): a client's disconnect still reaches the route app.add_middleware(_Auth, token=token or "", admin=os.environ.get(ADMIN_TOKEN_ENV) or "")
@app.get("/healthz") async def healthz() -> dict: return {"status": "parked" if world is None else "ready"}
@app.get("/manifest") async def manifest() -> Response: if resp := parked(): return resp return Response(served()["body"], media_type="application/json")
# ------------------------------------------------------------------ admin (docs/world.md) def admin_error(e: Exception) -> JSONResponse: return JSONResponse({"ok": False, "error": str(e)}, 400)
async def admin_body(request: Request) -> Any: """The JSON body (None if it is not JSON); ValueError over ADMIN_MAX_BYTES.""" data = bytearray() async for chunk in request.stream(): data.extend(chunk) if len(data) > ADMIN_MAX_BYTES: raise ValueError(f"the body is over {ADMIN_MAX_BYTES} bytes") try: return json.loads(data) except ValueError: return None
@app.get("/admin/knobs") async def get_knobs() -> dict: return admin().describe()
@app.patch("/admin/knobs") async def patch_knobs(request: Request) -> Response: try: # in a thread: a knob's on_change may take the world's locks changes = await asyncio.to_thread(admin().set, await admin_body(request)) except ValueError as e: return admin_error(e) return JSONResponse({"ok": True, "changes": changes, "knobs": admin().describe()})
@app.get("/admin/paused") async def get_paused() -> dict: return {"parked": world is None, "paused": dict(admin().paused)}
@app.post("/admin/{action}") async def pause_resume(action: str, request: Request) -> Response: if action not in ("pause", "resume"): return JSONResponse({"ok": False, "error": f"no admin action {action!r}"}, 404) try: body = await admin_body(request) body = body if isinstance(body, dict) else {} if action == "pause": await asyncio.to_thread(admin().pause, body.get("lanes"), str(body.get("reason") or "")) else: await asyncio.to_thread(admin().resume, body.get("lanes")) except ValueError as e: return admin_error(e) return JSONResponse({"ok": True, "paused": dict(admin().paused)})
@app.get("/metrics") async def get_metrics(request: Request) -> Response: try: custom = await asyncio.to_thread(world.metrics) if world is not None else {} except Exception: log.exception("world.metrics() failed") custom = {} m = {**metrics.snapshot(pool_stats()), "parked": int(world is None), "attempt": park["attempt"], "paused": len(admin().paused), "world": {k: v for k, v in (custom or {}).items() if _finite(v)}} if "text/plain" in request.headers.get("accept", ""): return PlainTextResponse(_prometheus(m), media_type="text/plain; version=0.0.4") return JSONResponse(m)
@app.post("/tools/{name}") async def call(name: str, request: Request) -> Response: if resp := parked(): return resp t0 = metrics.clock() pool = getattr(world, "pool", lambda _: "fast")(name) pool = pool if pool in limiters else "fast" # Decided from the path alone, before the body (an upload can be 100+ MB) is read. if why := overloaded(pool): metrics.overloaded += 1 metrics.refused[pool] += 1 log_refusal(pool, name, why) n = 0 async for chunk in request.stream(): # drained unparsed: the client reads the 429 n += len(chunk) if n > MAX_BYTES * 2: break resp = _error("overloaded", f"world {world.name} is overloaded ({why}); retry in " f"{retry_after:g} s", 429, retry_after_s=retry_after) resp.headers["Retry-After"] = str(math.ceil(retry_after)) latency = None else: resp = await _call(name, request) latency = metrics.clock() - t0 if name in served()["schemas"]: code = json.loads(resp.body)["error"]["code"] if isinstance(resp, JSONResponse) else None n_in = request.headers.get("content-length", "") metrics.call(name, latency, code, int(n_in) if n_in.isdigit() else 0, len(resp.body)) return resp
async def _call(name: str, request: Request) -> Response: try: limit = MAX_BYTES * 4 // 3 + (4 << 20) if "workspace-upload-v1" in world.capabilities else 1 << 20 data = bytearray() async for chunk in request.stream(): data.extend(chunk) if len(data) > limit: return _error("bad_request", "tool request is too large", 413) body = await asyncio.to_thread(json.loads, data) # MBs for an upload: off the loop except ValueError: return _error("bad_request", "the body must be JSON: {\"args\": {...}}", 400) args = body.get("args") if isinstance(body, dict) else None args = {} if args is None else args agent = _agent(request.headers) if not agent.name: return _error("no_agent", f"{AGENT_HEADER} is required", 400) tools = served()["schemas"] if name not in tools: return _error("unknown_tool", f"no tool {name!r}; tools: {', '.join(tools) or 'none'}", 404) if err := check_args(tools[name], args): return _error("bad_args", f"{name}: {err}") pool = getattr(world, "pool", lambda _: "fast")(name) try: if isinstance(body, dict) and "workspace" in body: handler = getattr(world, "call_workspace", None) if "workspace-upload-v1" not in world.capabilities or handler is None: return _error("bad_request", "this world does not accept workspace uploads", 400) v2 = isinstance(body["workspace"], dict) and "patch" in body["workspace"] if v2 and "workspace-upload-v2" not in world.capabilities: return _error("need_full", "this world takes full-tree uploads (v1) only") metrics.uploads["v2" if v2 else "v1"] += 1 result = await run(pool, handler, name, args, agent, body["workspace"]) else: result = await run(pool, world.call, name, args, agent) if inspect.isawaitable(result): if getattr(world, "cancellable", lambda _: False)(name): try: result = await _unless_gone(result, request) except _Gone: log.info("tool %s for %s: caller gone, cancelled", name, agent.name) return _error("cancelled", "the caller disconnected", 499) else: result = await result out = await asyncio.to_thread(_ok_body, result) except ToolError as e: return _error(e.code, redact(e.message), retry_after_s=e.retry_after_s) except Exception: # The exception text can hold paths, command output or credentials: it stays in # the world's log, under an id the agent can quote. ref = uuid.uuid4().hex[:8] log.exception("tool %s failed for %s (error id %s)", name, agent.name, ref) return _error("internal", f"the tool failed with an internal error (error id {ref})") return Response(out, media_type="application/json")
@app.post("/hooks") async def hooks(request: Request) -> Any: if resp := parked(): return resp try: body = await request.json() except ValueError: return {"ok": False} event = body.get("event") if isinstance(body, dict) else None if event not in HOOK_EVENTS or event not in world.hooks(): return {"ok": True, "ignored": True} agent = Agent(name=str(body.get("agent") or ""), type=str(body.get("type") or ""), swarm=str(body.get("swarm") or ""), turn=str(body.get("turn") or "")) fn = getattr(world, f"on_{event}") hook_args = (agent,) if event == "agent_start" else (agent, body.get("data") or {}) try: result = await run("fast", fn, *hook_args) if inspect.isawaitable(result): # an `async def` hook await result except Exception: log.exception("hook %s failed for %s", event, agent.name) return {"ok": True}
return app
def resolve_target(target: str, path: str | None = None) -> Any: """The World subclass or instance `module:attr` names, imported from `path` (default: the current directory).""" module_name, _, attr = target.partition(":") if not module_name or not attr: raise ValueError(f"{target!r}: expected module:Class, e.g. taskboard:TaskBoard") where = path or os.getcwd() if where not in sys.path: sys.path.insert(0, where) obj = getattr(importlib.import_module(module_name), attr) if not (isinstance(obj, World) or isinstance(obj, type) and issubclass(obj, World)): raise TypeError(f"{target!r} is not a legion.world.World (subclass or instance)") return obj
def build(obj: Any, admin: Admin | None = None) -> World: """An instance of the World subclass `obj` (an instance is returned as is). `admin`: the knobs and pauses it gets, attached to its `state_dir()` before `__init__` runs.""" if isinstance(obj, World): return obj if admin is None: return obj() world = obj.__new__(obj) # the admin goes in first: __init__ registers its knobs if admin.path is None and (d := world.state_dir()): admin.attach(d) world.__dict__["_legion_admin"] = admin world.__init__() return world
def load(target: str, path: str | None = None, admin: Admin | None = None) -> World: """`module:Class` (or `module:instance`) from `path`, built.""" return build(resolve_target(target, path), admin)
def stop_on_usr1() -> None: """SIGUSR1 (a Spot notice on Slurm: the watcher signals every process of the job) shuts the server down like SIGTERM, once: later USR1s are ignored (docs/slurm.md).""" import signal
sent = []
def handler(signum, frame) -> None: if not sent: sent.append(signum) print("world: SIGUSR1: shutting down", flush=True) os.kill(os.getpid(), signal.SIGTERM) # uvicorn's own graceful shutdown
signal.signal(signal.SIGUSR1, handler)
def serve(target: str, *, host: str | None = None, port: int | None = None, token_env: str = TOKEN_ENV, insecure: bool = False) -> None: import uvicorn
from legion.isolation import enabled, protect_supervisor
if enabled(): protect_supervisor()
token = os.environ.get(token_env, "") if not token and not insecure: raise SystemExit(f"{token_env} is not set: a world needs its shared secret " "(or pass --insecure for a world without one)") obj = resolve_target(target) # a bad target exits here; only __init__ may park host = host or os.environ.get(HOST_ENV) or "127.0.0.1" port = port or int(os.environ.get(PORT_ENV) or DEFAULT_PORT)
def built(admin: Admin) -> World: world = build(obj, admin) print(f"world {world.name} {world.version} on http://{host}:{port}", flush=True) return world
stop_on_usr1() # the port is bound first; the world is built (and rebuilt while that raises) in a thread uvicorn.run(create_app(built, token or None), host=host, port=port, log_level="warning", access_log=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179"""`legion.world.store`: a small `(kind, key) -> JSON` table on SQLite in WAL mode (docs/world.md).
For worlds that keep their state in memory and want saves that cost O(changes): the world readsits own dicts, marks the rows it changed with `dirty(kind, key)`, and a saver calls`flush(read)`, which upserts (or deletes) only those rows in one transaction. `backup_to(path)`writes a consistent copy while others write (SQLite online backup API), for archives.
Rows moved out of the hot set (`put(..., cold=True)`) stay readable with `get` and`iter(kind, cold=True)`; `iter(kind)` (the hot rows) is what a world loads at start.
store = Store(ws / "state.db") state = {key: value for key, value in store.iter("prs")} state["7"] = {...}; store.dirty("prs", "7") store.flush(lambda kind, key: state.get(key)) # None deletes the row"""
from __future__ import annotations
import contextlibimport jsonimport sqlite3import threadingimport timefrom collections.abc import Callable, Iteratorfrom pathlib import Pathfrom typing import Any
SCHEMA = """CREATE TABLE IF NOT EXISTS rows ( kind TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, cold INTEGER NOT NULL DEFAULT 0, ts REAL NOT NULL, PRIMARY KEY (kind, key));"""UPSERT = ("INSERT INTO rows (kind, key, value, cold, ts) VALUES (?, ?, ?, ?, ?) " "ON CONFLICT (kind, key) DO UPDATE SET value = excluded.value, cold = excluded.cold, " "ts = excluded.ts")
class Store: """Thread-safe: one connection behind a lock (writes are short: dirty rows only)."""
def __init__(self, path: str | Path) -> None: self.path = Path(path) self._lock = threading.Lock() # (kind, key) -> generation of its newest change; _written: generation last committed, # so a flush that lost a race never commits an older value over a newer one. self._dirty: dict[tuple[str, str], int] = {} self._written: dict[tuple[str, str], int] = {} self._gen = 0 self._flushing = 0 # flushes between their read and their commit self._db = sqlite3.connect(self.path, check_same_thread=False, isolation_level=None) self._db.execute("PRAGMA journal_mode=WAL") self._db.execute("PRAGMA synchronous=NORMAL") # WAL: durable at checkpoints, never corrupt self._db.execute("PRAGMA journal_size_limit=4194304") # truncate the WAL after big writes self._db.executescript(SCHEMA)
def get(self, kind: str, key: str) -> Any: """The row's value (hot or cold), or None.""" with self._lock: row = self._db.execute("SELECT value FROM rows WHERE kind = ? AND key = ?", (kind, key)).fetchone() return None if row is None else json.loads(row[0])
def iter(self, kind: str, cold: bool = False) -> Iterator[tuple[str, Any]]: """(key, value) of the hot rows of `kind` (cold=True: the cold rows), in first-write order.""" with self._lock: rows = self._db.execute("SELECT key, value FROM rows WHERE kind = ? AND cold = ? " "ORDER BY rowid", (kind, int(cold))).fetchall() for key, value in rows: yield key, json.loads(value)
def put(self, kind: str, key: str, value: Any, cold: bool = False) -> None: """Write one row now (and drop its dirty mark: this is its newest value).""" self.write([(kind, key, value)], cold=cold)
def delete(self, kind: str, key: str) -> None: self.write([(kind, key, None)])
def write(self, rows: list[tuple[str, str, Any]], cold: bool = False) -> None: """Upsert (value None: delete) several rows in one transaction.""" with self._lock: self._gen += 1 encoded = [(kind, key, self._gen, None if value is None else json.dumps(value)) for kind, key, value in rows] self._commit(encoded, cold)
def dirty(self, kind: str, key: str) -> None: """Mark a row changed; the next flush writes it.""" with self._lock: self._gen += 1 self._dirty.pop((kind, key), None) # re-insert: keeps the newest change last self._dirty[(kind, key)] = self._gen
@property def pending(self) -> int: """Rows marked dirty and not yet flushed.""" return len(self._dirty)
def flush(self, read: Callable[[str, str], Any], lock=None) -> int: """Write every dirty row in one transaction: `read(kind, key)` gives its current value (None: delete it). `lock` guards what `read` reads: it is held only while the rows are read and encoded, not during the commit. A row changed again meanwhile stays dirty. On a failed commit nothing is written and the rows stay dirty. Returns the rows written.""" with lock or contextlib.nullcontext(), self._lock: rows = [] for (kind, key), gen in self._dirty.items(): value = read(kind, key) rows.append((kind, key, gen, None if value is None else json.dumps(value))) if not rows: return 0 self._flushing += 1 with self._lock: try: self._commit(rows, False) finally: self._flushing -= 1 if not self._flushing: # no older read left in flight: nothing to guard against self._written.clear() return len(rows)
def _commit(self, rows, cold): """Write rows (kind, key, generation, encoded value or None) in one transaction, skipping any already written at a newer generation; then drop their dirty marks.""" rows = [r for r in rows if self._written.get(r[:2], 0) < r[2]] now = time.time() self._db.execute("BEGIN IMMEDIATE") try: for kind, key, _, value in rows: if value is None: self._db.execute("DELETE FROM rows WHERE kind = ? AND key = ?", (kind, key)) else: self._db.execute(UPSERT, (kind, key, value, int(cold), now)) self._db.execute("COMMIT") except BaseException: self._db.execute("ROLLBACK") raise for kind, key, gen, _ in rows: self._written[(kind, key)] = gen if self._dirty.get((kind, key), gen + 1) <= gen: del self._dirty[(kind, key)]
def backup_to(self, path: str | Path) -> None: """Consistent copy of the database, WAL included (SQLite online backup API). Holds the store's lock for the copy: writers wait.""" backup_to(self._db, path, self._lock)
def size(self) -> int: """Bytes on disk (database plus WAL).""" return sum(p.stat().st_size for p in (self.path, self.path.with_name(self.path.name + "-wal")) if p.exists())
def checkpoint(self) -> None: """Fold the WAL into the database file and truncate it.""" with self._lock: self._db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
def close(self) -> None: self.checkpoint() with self._lock: self._db.close()
def backup_to(db: sqlite3.Connection | str | Path, path: str | Path, lock=None) -> None: """Copy database `db` (a connection, or a file another process may be writing) to `path`.""" path = Path(path) path.unlink(missing_ok=True) src = db if isinstance(db, sqlite3.Connection) else sqlite3.connect(db) dst = sqlite3.connect(path) try: if lock is None: src.backup(dst) else: with lock: src.backup(dst) finally: dst.close() if src is not db: src.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""Bounded local git snapshots for worlds advertising workspace-upload-v1 and -v2.
The worker captures files itself; an agent supplies a path within its own workspace,never a server path or a repository base SHA. Only git-tracked/nonignored files areincluded, and symlinks and git metadata are refused. Transport lives outside tool args.v1 sends every file (base64); v2 sends a binary git patch against the base (`capture_v2`),which the world applies on its own checkout of that base (`apply_patch`)."""from __future__ import annotations
import base64import osimport reimport subprocessimport tempfileimport threadingfrom pathlib import Path, PurePosixPath
MAX_BYTES = 128 << 20MAX_FILES = 10000PATCH_MAX_BYTES = 20 << 20 # a larger v2 patch is sent as a v1 snapshot insteadAPPLY_MAX_MEMORY = 2 << 30 # address space of `git apply`: a binary delta can expand a lotAPPLY_SLOTS = threading.BoundedSemaphore(4) # `git apply` runs at once, world-wide# The agent owns its clone's config: never run a command it configured (fsmonitor, filters,# external diff, textconv) or let its diff settings change the patch format.SAFE = ("-c", "core.fsmonitor=false", "-c", "diff.noprefix=false", "-c", "diff.mnemonicPrefix=false", "-c", "diff.relative=false")
def git(root: Path, *args: str, data: bytes | None = None, env: dict | None = None) -> str: return git_bytes(root, *args, data=data, env=env).decode().strip()
def git_bytes(root: Path, *args: str, data: bytes | None = None, env: dict | None = None) -> bytes: try: p = subprocess.run(["git", *SAFE, "-C", str(root), *args], input=data, capture_output=True, timeout=30, check=False, env=env) except subprocess.TimeoutExpired: # a ValueError reaches the agent as a tool error raise ValueError("workspace capture timed out after 30 s: the clone is too large or " "slow; trim it") from None if p.returncode: raise ValueError("expected a local git clone with a committed base") return p.stdout
def _clone(workdir: Path, path: str) -> tuple[Path, str, list[str]]: """The clone's root, its base (merge base with origin/main) and the files to upload.""" root = (workdir / path).resolve() if not root.is_relative_to(workdir.resolve()) or not root.is_dir(): raise ValueError("path must be a git clone inside your workspace") top = Path(git(root, "rev-parse", "--show-toplevel")).resolve() if top != root: raise ValueError("path must name the root of your clone") # The world verifies this commit against its own repository, including ancestry. base = git(root, "merge-base", "HEAD", "refs/remotes/origin/main") names = git(root, "ls-files", "-z", "--cached", "--others", "--exclude-standard").split("\0") files, total = [], 0 for name in dict.fromkeys(names): if not name: continue rel = PurePosixPath(name) if rel.is_absolute() or ".." in rel.parts or ".git" in rel.parts: raise ValueError("unsafe file path") f = root / name if f.is_symlink() or not f.resolve().is_relative_to(root): raise ValueError("symlinks are not supported") if not f.exists(): # tracked deletion continue if not f.is_file() or len(files) >= MAX_FILES: raise ValueError("unsupported file or too many files") total += f.stat().st_size if total > MAX_BYTES: raise ValueError("workspace snapshot exceeds 128 MiB") files.append(name) return root, base, files
def capture(workdir: Path, path: str) -> dict: root, base, names = _clone(workdir, path) return {"base_sha": base, "files": {n: base64.b64encode((root / n).read_bytes()).decode("ascii") for n in names}}
def capture_v2(workdir: Path, path: str, cap: int = PATCH_MAX_BYTES) -> dict | None: """The clone as `{"base_sha", "patch"}`: the same files `capture` would send, staged into a temporary index, as a base64 `git diff --binary` against the base. None when the patch is over `cap` bytes (send `capture` instead).""" root, base, names = _clone(workdir, path) if any("\n" in n for n in names): return None # hash-object --stdin-paths reads lines objects = (root / git(root, "rev-parse", "--git-path", "objects")).resolve() with tempfile.TemporaryDirectory() as tmp: (Path(tmp) / "objects").mkdir() # New blobs go to a temporary object store (the clone's is borrowed), never the clone. env = {**os.environ, "GIT_INDEX_FILE": str(Path(tmp) / "index"), "GIT_OBJECT_DIRECTORY": str(Path(tmp) / "objects"), "GIT_ALTERNATE_OBJECT_DIRECTORIES": str(objects)} # hash-object --no-filters instead of `git add`: add would run the clone's clean filters. shas = git(root, "hash-object", "-w", "--no-filters", "--stdin-paths", data="".join(n + "\n" for n in names).encode(), env=env).split() info = "".join(f"{'100755' if (root / n).stat().st_mode & 0o100 else '100644'} {sha}\t{n}\0" for n, sha in zip(names, shas, strict=True)) git(root, "update-index", "-z", "--index-info", data=info.encode(), env=env) patch = git_bytes(root, "diff", "--cached", "--binary", "--full-index", "--find-renames", "--no-ext-diff", "--no-textconv", "--no-color", base, env=env) if len(patch) > cap: return None return {"base_sha": base, "patch": base64.b64encode(patch).decode("ascii")}
# git reads modes as octal and keeps only the type bits (0120000, 120755 are symlinks): any# new mode that is not exactly a regular file's is refused._MODES = re.compile(rb"^(?:new file mode |new mode |index \S+ )(.*)$", re.MULTILINE)_SIZES = re.compile(rb"^(?:literal|delta) (\d+)$", re.MULTILINE)
def apply_patch(snapshot: dict, tree: Path) -> list[str]: """Apply a v2 upload onto `tree`, a git checkout of its `base_sha` (the world's own), in the worktree (not the index), so the world's excludes apply when it stages the tree. Returns the paths that differ from the base (added, modified, deleted), as `unpack` callers expect. ValueError for an invalid patch; symlinks and submodules are refused as in v1.""" try: patch = base64.b64decode(snapshot.get("patch") or "", validate=True) except (ValueError, TypeError) as exc: raise ValueError("invalid workspace patch") from exc if git(tree, "rev-parse", "HEAD") != snapshot.get("base_sha"): raise ValueError("the tree is not a checkout of the patch's base") if any(m not in (b"100644", b"100755") for m in _MODES.findall(patch)): raise ValueError("symlinks are not supported") # shortcut: agents send patches directly (legion.harbor's world.call), and a binary delta can # expand past its declared size, up to the file-size and memory limits below, with at most # APPLY_SLOTS applies at once; decode delta headers if that bound is too loose. if (patch.count(b"\ndiff --git ") + patch.startswith(b"diff --git ") > MAX_FILES or sum(int(n) for n in _SIZES.findall(patch)) > MAX_BYTES): raise ValueError("workspace snapshot exceeds 128 MiB or 10,000 files") if patch: # prlimit, not preexec_fn: the world's server is threaded with APPLY_SLOTS: p = subprocess.run(["prlimit", f"--fsize={MAX_BYTES}", f"--as={APPLY_MAX_MEMORY}", "git", "-C", str(tree), "apply", "--binary", "--whitespace=nowarn", "-"], input=patch, capture_output=True, timeout=120, check=False) if p.returncode: raise ValueError("the workspace patch does not apply to its base") for top, dirs, files in os.walk(tree): if top == str(tree) and ".git" in dirs: dirs.remove(".git") if any(os.path.islink(os.path.join(top, n)) for n in dirs + files): raise ValueError("symlinks are not supported") names = git(tree, "ls-files", "-z", "--modified", "--deleted", "--others", "--exclude-standard") return sorted({n for n in names.split("\0") if n})
def unpack(snapshot: dict, root: Path) -> None: files = snapshot.get("files") if not isinstance(files, dict) or len(files) > MAX_FILES: raise ValueError("invalid workspace snapshot") total = 0 for name, encoded in files.items(): rel = PurePosixPath(name) if rel.is_absolute() or ".." in rel.parts or ".git" in rel.parts or "\\" in name: raise ValueError("unsafe file path") data = base64.b64decode(encoded, validate=True) total += len(data) if total > MAX_BYTES: raise ValueError("workspace snapshot exceeds 128 MiB") target = root / rel target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(data)112341 unmodified line67899101112"""Puts the world's modules and the vendored legion library on sys.path; test helpers.""""""Puts the world's modules on sys.path (legion is the installed package, README); test helpers."""from __future__ import annotations
import shutil1 unmodified linefrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1] # world/sys.path[:0] = [str(ROOT), str(ROOT / "src")]sys.path.insert(0, str(ROOT))
class FakeBucket:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081#!/bin/bash# vendor.sh: (re)build src/ (legion's World API library) and requirements.txt in this directory# from a legion checkout. The world's own code (pybot.py and the modules next to it) is never# touched here.## ./vendor.sh LEGION_DIR check + vendor at the commit in source-lock.json;# fails (nothing written) if any file's sha256 differs# ./vendor.sh LEGION_DIR --lock REV re-pin: vendor REV and rewrite source-lock.json## Reads LEGION_DIR with `git archive` only (never checks out or switches branches there).# Needs git, python3, and uv (requirements.txt is `uv export` of legion's own uv.lock).set -euo pipefaildie() { echo "vendor.sh: $*" >&2; exit 1; }[ $# -ge 1 ] || die "usage: vendor.sh LEGION_DIR [--lock REV]"LEGION=$1ROOT=$(cd "$(dirname "$0")" && pwd)LOCK=$ROOT/source-lock.json
# What the world imports, transitively (pybot.py, repository.py, sandbox.py, snapshot.py and# legion.world.server.serve).FILES=( src/legion/__init__.py src/legion/buckets.py src/legion/isolation.py src/legion/models.py src/legion/registry.py src/legion/tools/__init__.py src/legion/tools/loader.py src/legion/worker/__init__.py src/legion/worker/sync.py src/legion/world/__init__.py src/legion/world/admin.py src/legion/world/lanes.py src/legion/world/protocol.py src/legion/world/server.py src/legion/world/store.py src/legion/world/workspace.py)
if [ "${2:-}" = --lock ]; then [ -n "${3:-}" ] || die "--lock needs a revision" REV=$3else REV=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["legion_commit"])' "$LOCK")fiCOMMIT=$(git -C "$LEGION" rev-parse --verify "$REV^{commit}") || die "$REV is not a commit in $LEGION"
TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXITmkdir -p "$TMP/world" "$TMP/proj"git -C "$LEGION" archive "$COMMIT" "${FILES[@]}" | tar -x -C "$TMP/world"git -C "$LEGION" archive "$COMMIT" pyproject.toml uv.lock | tar -x -C "$TMP/proj"# The world needs legion's core and `controller` deps (fastapi, uvicorn), not Harbor or the board# client (msgboard is a git dependency, which pip's --require-hashes refuses): pruned.(cd "$TMP/proj" && uv export -q --frozen --no-emit-project --extra controller --no-dev --no-header \ --prune harbor --prune podman-compose --prune msgboard -o "$TMP/requirements.txt")
python3 - "$TMP" "$LOCK" "$COMMIT" "${2:-}" <<'PY'import hashlib, json, sysfrom pathlib import Pathtmp, lock, commit, mode = Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3], sys.argv[4]sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()got = {p.relative_to(tmp / "world").as_posix(): sha(p) for p in sorted((tmp / "world").rglob("*")) if p.is_file()}got = {"files": got, "requirements.txt": sha(tmp / "requirements.txt")}if mode == "--lock": lock.write_text(json.dumps({"legion_repo": "https://github.com/huggingface/legion", "legion_commit": commit, **got}, indent=2) + "\n") sys.exit(0)want = json.loads(lock.read_text())bad = sorted(k for k in want["files"].keys() | got["files"].keys() if want["files"].get(k) != got["files"].get(k))if want["requirements.txt"] != got["requirements.txt"]: bad.append("requirements.txt")if bad: sys.exit("vendor.sh: sha256 mismatch against source-lock.json: " + ", ".join(bad))PY
rm -rf "$ROOT/src"mv "$TMP/world/src" "$ROOT/src"cp "$TMP/requirements.txt" "$ROOT/requirements.txt"echo "vendored legion $COMMIT: $(find "$ROOT/src" -type f | wc -l) files"README.md+24-7
world/Dockerfile+10-6
world/entrypoint.sh+3-1
world/scripts/check-sidecar.py+4-4
world/scripts/smoke-local.py+5-5
world/source-lock.jsonDeleted-23
world/src/legion/__init__.pyDeleted-3
world/src/legion/buckets.pyDeleted-35
world/src/legion/isolation.pyDeleted-386
world/src/legion/models.pyDeleted
world/src/legion/registry.pyDeleted-45
world/src/legion/tools/__init__.pyDeleted-55
world/src/legion/tools/loader.pyDeleted-385
world/src/legion/worker/__init__.pyDeleted-1
world/src/legion/worker/sync.pyDeleted-1181
world/src/legion/world/__init__.pyDeleted-239
world/src/legion/world/admin.pyDeleted-170
world/src/legion/world/lanes.pyDeleted-385
world/src/legion/world/protocol.pyDeleted-208
world/src/legion/world/server.pyDeleted-698
world/src/legion/world/store.pyDeleted-179
world/src/legion/world/workspace.pyDeleted-168
world/tests/conftest.py+2-2
world/vendor.shDeleted-81