world: decide the open-budget exemption from the applied tree; accept only git-diff patches
Browse filesAlso: drop open_pr's request-id cache (the branch-slug rule already stops a
duplicate PR), close a keep-alive connection whose body was never read, time
out idle connections, bound unknown-base fetches to one per 5 s, install a
hashed dependency lock, remove unused World.tools/knobs, and describe the
current credentials and routes in the README.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Files changed (9)
- README.md+35-56
- world/Dockerfile+2-2
- world/api.py+3-13
- world/pybot.py+18-101
- world/repository.py+4-3
- world/requirements.txt+157-1
- world/server.py+8-1
- world/tests/test_pybot.py+41-75
- world/workspace.py+3-1
1 unmodified line234556781 unmodified line10111213141516171819192021202122232425262728282930293031323334353610 unmodified lines47484947484950515253545556575859606162636419 unmodified lines84858675878889907 unmodified lines989910089901011021031046 unmodified lines11111211310311411511611710711811912012116 unmodified lines1381391401301411421431441451361371381391401411421431441451461471481491501511521531541551561571461471591601611621631641651661671681691701711481491731741751501511521531541551561571581591601611821831621631641651 unmodified line
A swarm of agents builds one chatbot together: a standard-library Python bot in a Hugging Facedataset, changed only through pull requests that other agents review and merge. This repositoryholds both halves that a [legion](https://github.com/huggingface/legion) run needs:holds both halves of a run:
```tasks/pybot-agent/ the Harbor task each agent runs in (one Trial per agent): instruction,1 unmodified line pybot_mcp.py (the pybot tools as an MCP server; task.toml starts it)world/ the shared world service (World API v1), one per run pybot.py the world: PRs, reviews, the merge queue, bot runs, world_status api.py, server.py the tool layer (schemas, knobs, lane pauses) and its HTTP API repository.py the world's bare git repository and the Hub client sandbox.py runs a bot or its tests isolated; `python sandbox.py serve` is the sidecar snapshot.py the world's state archive in a bucket (world.tar.gz) 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 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 requirements.txt the world's Python deps, a hashed lock of huggingface_hub (how to regenerate it is at its top) Dockerfile the world image (also the sidecar's); entrypoint.sh starts the world```
## The world
Agents clone the code dataset (`$PYBOT_REPO`) into `pybot` and never push to it. They workthrough the pybot tools, which the task's MCP server `pybot_mcp.py` serves: it reads`WORLD_URL` and `WORLD_TOKEN`, lists the tools from `GET $WORLD_URL/manifest`, calls`POST $WORLD_URL/tools/<name>`, and adds the caller's clone to `open_pr` and `run_bot` as apatch against its merge-base with `origin/main` (at most 750 KB). Check it with`WORLD_URL` (the world's URL ending in `/world`) and `WORLD_TOKEN` (the agent's credential),lists the tools from `GET $WORLD_URL/manifest`, calls `POST $WORLD_URL/tools/<name>`, and addsthe caller's clone to `open_pr` and `run_bot` as a patch against its merge-base with`origin/main` (at most 750 KB). A call still running after 50 s answers with a ticket that theclient-side tool `pybot_wait` redeems (MCP hosts may give up on a call after 60 s). Check it with`python3 tasks/pybot-agent/pybot_mcp.py --self-test`.
| tool | what it does |10 unmodified linesthe Hub API, and writes its state to `PYBOT_BUCKET` (`world.tar.gz`, restored into an emptyworkspace at start, pushed every `PYBOT_BUCKET_PUSH_S` and at exit).
The world serves `/healthz`, `/manifest`, `/tools/*`, `/metrics` and `/admin/*` on `$PORT`.`X-World-Token` is the world secret (`LEGION_WORLD_TOKEN`) or, on `/manifest` and tool calls,an agent's own token for its `X-Legion-Agent`: HMAC-SHA256(secret, `legion-world-agent\0<agent>`).The world serves on `$PORT` (`world/server.py` has the details):
| route | ||---|---|| `POST /v1/tools/<name>` | flat arguments; the result, or a 4xx/429 error || `GET /world/manifest`, `POST /world/tools/<name>` | the tools, and calls with `{"args": ...}` answered `{"ok", "result" or "error"}` (what the client uses) || `GET /healthz` | no credential: `ready` or `parked` (still starting) || `GET /metrics`, `/admin/*` | `PYBOT_ADMIN_TOKEN` only; `/admin/*` and tool calls answer 503 while the world is still starting |
Agent seat `i` (`agent-<i+1, 3 digits>`: seat 0 is `agent-001`) authenticates with the value of`PYBOT_TOKEN_<i>`, as `X-World-Token` or `Authorization: Bearer`. Each agent gets its own valueas `WORLD_TOKEN`; the admin token never reaches an agent.
Bots run isolated: in this container under `unshare` when it is allowed (Slurm), or in thesidecar, a second container of the same image with command `python sandbox.py serve` that gets19 unmodified linesWorld (one per run; give it about 30 s to stop, so the final push completes):
```shdocker run -p 7860:7860 -e HF_TOKEN -e LEGION_WORLD_TOKEN \docker run -p 7860:7860 -e HF_TOKEN -e PYBOT_TOKEN_0 -e PYBOT_TOKEN_1 -e PYBOT_ADMIN_TOKEN \ -e PYBOT_REPO=<ns>/<name> -e PYBOT_BUCKET=hf://buckets/<ns>/<bucket>/<run> \ -e PYBOT_SANDBOX_URL=http://sandbox:8000 -e PYBOT_SANDBOX_TOKEN \ <registry>/pybot-world:<tag>7 unmodified lines
On HF Jobs, run both jobs in one network group with the sidecar's alias `sandbox` and set`PYBOT_SANDBOX_URL=http://${HF_NETWORK_GROUP_PREFIX}sandbox:8000` (the world expands `${VAR}`s inthe URL). On Slurm, leave `PYBOT_SANDBOX_URL` unset and set `LEGION_WORLD_HOST_FILE` so legion'scontroller can follow the world's `host:port`.the URL). Where `unshare` is allowed (e.g. Slurm), leave `PYBOT_SANDBOX_URL` unset.
Sizing: an 8-CPU world with `PYBOT_CHECKOUT_SLOTS=4` serves 10 agents; at 1,000 agents give theworld about 28 CPUs and 54 GB.6 unmodified lines| variable | default | ||---|---|---|| `HF_TOKEN` | required | Hub write token for `PYBOT_REPO` and the bucket; reaches git through `GIT_ASKPASS`, never argv || `LEGION_WORLD_TOKEN` | required | the world secret (`X-World-Token`); legion's `resources.world.token_env` holds the same value || `PYBOT_TOKEN_<seat>` | required, from seat 0 | each agent's credential (seat 0 is `agent-001`); a new set per run || `PYBOT_REPO` | required | `<ns>/<name>` of the code dataset || `PYBOT_BUCKET` | required (entrypoint) | `hf://buckets/<ns>/<bucket>/<prefix>` for `world.tar.gz`; `off`: no restore, no pushes (smoke tests) || `PYBOT_SANDBOX_URL`, `PYBOT_SANDBOX_TOKEN` | empty | the sidecar; set both (the entrypoint refuses a URL without the token). Empty: `unshare` here || `LEGION_WORLD_ADMIN_TOKEN` | empty: `/admin` off | admin secret for live knobs and lane pauses || `PYBOT_ADMIN_TOKEN` | empty: `/metrics` and `/admin` off | admin secret for metrics, live knobs and lane pauses || `PYBOT_SEED_DIR` | `seed` | the seed whose fixed files (runtime, loader, package initializers) the contract compares; next to `pybot.py` or absolute || `PYBOT_MAX_REVIEWERS` | `2` | reviewers per PR change; one more is refused (`review_full`); 0: unlimited || `PYBOT_PR_OPEN_BUDGET` | `merges` | new PRs per hour may not exceed max(merges in the last hour, `PYBOT_PR_OPEN_FLOOR`); `off` |16 unmodified lines| `PYBOT_ANON_FETCH` | `1` | fetch anonymously first; `0`: always with the token || `PYBOT_FETCH_TTL_S` | `60` | cache of a fetched main || `PYBOT_CALL_BUDGET_S` | `50` | seconds a tool call may spend on Hub waits and push retries (callers wait about 55 s) || `PYBOT_REQUEST_TTL_S` | `21600` | how long `open_pr` idempotency keys are kept || `PYBOT_MAX_FILE_BYTES` | `1048576` | largest file in an uploaded clone || `PYBOT_SAVE_INTERVAL_S` | `2.0` | seconds between state saves (0: every change) || `PYBOT_PACK_LOOSE_MAX` | `20000` | loose objects packed per git maintenance pass (every 30 min) || `PYBOT_OPERATORS` | empty | agent names that may close other agents' PRs (comma-separated) || `PYBOT_PRS_PAUSED`, `PYBOT_PRS_PAUSED_FILE` | empty, `<ws>/prs-paused` | pause `open_pr` and `merge_pr` at start, or while the file exists || `PORT`, `PYBOT_WORK`, `LEGION_WORLD_HOST_FILE`, `WORLD_HOST` | `7860`, `/work`, unset, `$HOSTNAME` | entrypoint only: the port, the state directory, and where to write `host:port` |
## How a legion spec uses it
The world is a resource that the operator starts; every agent runs the task. The spec names thepublished task and the world's URL:
```yamltask: repo: https://huggingface.co/datasets/<ns>/pybot selector: pybot-agent revision: '<commit sha>'resources: world: url: '${WORLD_URL}' # the world's URL (HF Jobs: the world job's public URL) token_env: PYBOT_WORLD_TOKEN # same value as the world's LEGION_WORLD_TOKEN; a new one per run transport: http # backends without mounts (hf-sandbox); `unix` on docker/podmantools: - world.*workers: env: {PYBOT_REPO: '${PYBOT_REPO}'} # the task's [environment.env] reads it```| `PORT`, `PYBOT_WORK` | `7860`, `/work` | entrypoint only: the port and the state directory |
## 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```## Running the task
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.Start the world first; then run one Trial of `tasks/pybot-agent` per agent, each with its ownseat. The launcher's environment gives the task `PYBOT_REPO` (task.toml passes it on), and eachagent's environment needs `WORLD_URL` (`https://<world host>/world`) and `WORLD_TOKEN` (itsseat's `PYBOT_TOKEN_<i>` value) for the pybot MCP server, which task.toml fetches at a pinnedcommit and checks by sha256. A change to `pybot_mcp.py` needs a new pin: commit it, then pointthe commit and sha256 in task.toml at that commit.
## Checks
```shcd worldpip install --require-hashes --no-deps -r requirements.txtpip install --no-deps "$(grep -o 'legion @ git+[^"]*' Dockerfile)" # legion at the pinned commitpip install pytest pytest-asynciopip install pytestpython -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 checks1 unmodified line234556783 unmodified lines12131415151617181 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+). The world's only Python dependency is huggingface_hub (requirements.txt).# 3.12+). The world's only Python dependency is huggingface_hub (requirements.txt: a hashed lock).FROM python:3.12.15-slim-bookworm@sha256:6a0e06f5ba0b373d051aabd3fffb9b873f27f9a2a3a14bcbe37dee6f0e3bbc70
# git: the world's bare repo, fetches and pushes to the Hub.3 unmodified lines && rm -rf /var/lib/apt/lists/*
COPY requirements.txt /opt/world/requirements.txtRUN pip install --no-cache-dir -r /opt/world/requirements.txtRUN pip install --no-cache-dir --no-deps --require-hashes -r /opt/world/requirements.txt
COPY *.py /opt/world/COPY seed/ /opt/world/seed/25 unmodified lines2627282929303132323334255 unmodified lines29029129229429529329429529629722 unmodified lines32032132232432532632732332432531 unmodified lines35735835936536636736836936036136225 unmodified lines
@dataclass(frozen=True)class Agent: """Who calls: the agent's name (from its credential) and the request id, if one was sent.""" """Who calls: the agent's name (from its credential)."""
name: str request_id: str = ""
class ToolError(Exception):255 unmodified lines# ------------------------------------------------------------------ the base class
class World: """Base class. Class attributes: `name`, `description` (shown to the agents); `concurrent` is informational (the server always runs calls concurrently: the world guards its state).""" """Base class. Class attributes: `name`, `description` (shown to the agents). The server runs calls concurrently: the world guards its state."""
name: typing.ClassVar[str] = "world" description: typing.ClassVar[str] = ""22 unmodified lines cls._manifest = {"name": cls.name, "description": cls.description, "tools": tools} return json.loads(json.dumps(cls._manifest))
def tools(self) -> dict[str, Callable]: """The bound `@tool` methods, by name.""" return {name: getattr(self, name) for name in self.tool_functions()}
@classmethod def pool(cls, tool: str) -> str: fn = cls.tool_functions().get(tool)31 unmodified lines 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.""" return self.admin.values
def paused(self, lane: str) -> bool: """Did an operator pause `lane` (`POST /admin/pause`)?""" return lane in self.admin.paused7 unmodified lines89101111121324 unmodified lines38394042434441424324 unmodified lines6869707571727374122 unmodified lines19719819920420520620020120234 unmodified lines23723823924724024124224356 unmodified lines300301302310311312303304305345 unmodified lines651652653664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735654655656257 unmodified lines914915916999917918919920105 unmodified lines102610271028111110291030111411151031103210332 unmodified lines103610371038112411251039104010419 unmodified lines1051105210531141114210541055105612 unmodified lines1069107010711161107210731074107511651076107710781079108020 unmodified lines110111021103119211931104110511062 unmodified lines11091110111112021203111211131114111511161117111811191120112111221123112411251126112711281129121311301131113211331134113511361220113711381139114011 unmodified lines115211531154123811551156115711587 unmodified linesimport concurrent.futuresimport contextlibimport functoolsimport hashlibimport inspectimport jsonimport logging24 unmodified linesMAX_FILE_BYTES = int(os.environ.get("PYBOT_MAX_FILE_BYTES", str(1 << 20)))EXCLUDE = ("__pycache__/", "*.pyc", ".venv/", ".pytest_cache/", ".mypy_cache/", ".ruff_cache/", "*.egg-info/", ".DS_Store")MAX_REQUESTS = 5000 # open_pr idempotency keys (X-Request-Id) kept for retries (oldest dropped)# ... and for at most this long (a client retries within minutes).REQUEST_TTL = float(os.environ.get("PYBOT_REQUEST_TTL_S", "21600"))# state.db (and prs.json, see save.legacy_json) is written by a background thread at most once# per this many seconds while the state changed (0: write synchronously on every change).# close() always writes it.24 unmodified linesMAX_DIFF_BYTES = int(os.environ.get("PYBOT_GET_PR_DIFF_BYTES", "60000"))# State rows in state.db (store.py): these top-level dicts get one row per entry;# every other top-level value (pr_opens, pr_merges) is one row of kind "_".KINDS = ("prs", "requests", "drafts", "inbox")KINDS = ("prs", "drafts", "inbox")COLD_AFTER = 3600.0 # merged/closed PR records leave memory for the cold table after thisVERDICTS_MAX = 2000 # interview verdicts kept (oldest dropped)VERDICT_NOTES = 600 # note characters kept per verdict122 unmodified lines for key, value in self.store.iter(kind): self.state.setdefault(kind, {})[key] = value self.state.update(self.store.iter("_")) # Pruning expects oldest first; an upsert keeps a re-cached key's first position. self.state["requests"] = dict(sorted(self.state["requests"].items(), key=lambda kv: kv[1].get("_ts", 0))) if old_json is not None and self.legacy_json and {**empty, **old_json} != self.state: log.warning("state: prs.json and state.db differ at start; using state.db") self.cold_branches = {rec["branch"] for _, rec in self.store.iter("prs", cold=True)}34 unmodified lines # {"ts", "pr", "code"} and shared-test runs {"ts", "main_sha", "result", "seconds"}. self.merge_refusals = collections.deque(maxlen=1000) self.test_runs = collections.deque(maxlen=200) self.pending = {} # open_pr reservations: token -> (author, branch ref, pr or None, key) self.pending = {} # open_pr reservations: token -> (author, branch ref, pr or None) self.operators = {n.strip() for n in os.environ.get("PYBOT_OPERATORS", "").split(",") if n.strip()} # Pause open_pr/merge_pr: PYBOT_PRS_PAUSED=1 at start, or the flag file, checked per call. self.paused_env = os.environ.get("PYBOT_PRS_PAUSED", "").strip() not in ("", "0")56 unmodified lines on_change=lambda v: setattr(self, "budget_floor", v)) self.open_reserved = set() # new-PR calls past the budget check, Hub PR not yet created self.stopping = threading.Event() with self.lock: # cached results stored in full are slimmed: the first save is already small if self._slim_requests(): self._save() with self.lock: # the archive may predate merges that already landed on the Hub for rec in self.state["prs"].values(): if rec["state"] in ("closing", "merging"): # interrupted: the agent may retry345 unmodified lines finally: tmp.unlink(missing_ok=True)
# -- open_pr idempotency cache ----------------------------------------------------------
@staticmethod def _digest(text): return hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest()
def _slim(self, entry, now): """Strip the description from a cached open_pr result (a replay rebuilds it, see _replay) and stamp it; returns True if the entry changed.""" changed = False if not isinstance(entry.get("_ts"), (int, float)): entry["_ts"] = now changed = True if isinstance(entry.get("description"), str): entry["_description_sha256"] = self._digest(entry["description"]) entry["description"] = None # keeps the key's place in the result changed = True return changed
def _cache_request(self, key, result): """Cache an open_pr result for retries of the same request (call with the lock held).""" now = time.time() entry = dict(result) self._slim(entry, now) requests = self.state["requests"] requests.pop(key, None) requests[key] = entry self._dirty("requests", key) self._prune_requests(now)
def _prune_requests(self, now): """Drop cached results older than REQUEST_TTL, then the oldest past MAX_REQUESTS (entries are in insertion order, so oldest first). Returns True if any was dropped.""" requests = self.state["requests"] cut = now - REQUEST_TTL stale = [] for key, entry in requests.items(): if entry["_ts"] > cut: break stale.append(key) stale += list(requests)[len(stale):max(len(stale), len(requests) - MAX_REQUESTS)] for key in stale: del requests[key] self._dirty("requests", *stale) return bool(stale)
def _slim_requests(self): """Startup: slim every cached result (full entries, which have no timestamp, get the current time) and prune. Returns True if the state changed.""" now = time.time() changed = False for key, entry in self.state["requests"].items(): if self._slim(entry, now): self._dirty("requests", key) changed = True return self._prune_requests(now) or changed
def _replay(self, key, description): """The result an open_pr request already returned (call with the lock held). The description comes from the retried call (the same request carries the same one) or else from the PR record, whichever matches the digest stored with the result.""" entry = self.state["requests"][key] result = {k: v for k, v in entry.items() if not k.startswith("_")} digest = entry.get("_description_sha256") if digest is not None: rec = self.state["prs"].get(str(entry.get("pr"))) or {} candidates = [description, rec.get("description")] result["description"] = next( (c for c in candidates if isinstance(c, str) and self._digest(c) == digest), description) return result
def _event(self, action, agent, **data): with open(self.ws / "prs.jsonl", "a") as out: out.write(json.dumps({"ts": time.time(), "event": action, "agent": agent.name,257 unmodified lines raise ToolError('workspace must be {"base_sha": "<40 hex>", "patch": "<base64>"}', "bad_workspace") if not self.repo.has_commit(base): self.repo.refresh(0) self.repo.fetch(max_age=5) # joins a running fetch; at most one new fetch per 5 s if not self.repo.has_commit(base): raise ToolError(f"unknown base {base[:12]}: fetch origin/main and rebase your branch", "unknown_base")105 unmodified lines "which send it as workspace", "bad_workspace") # Scope new_modules: a PR that adds no module is outside the budget. exempt = self.budget_scope == "new_modules" and not self._adds_module(snapshot) key = agent.request_id branch_ref = f"agents/{agent.name}/{branch}" with self.lock: if key and key in self.state["requests"]: return self._replay(key, description) if pr is None and branch_ref not in self.state["drafts"] and not exempt: self._check_budget(agent) # before any fetch, build or Hub call # The lock is held only for state and the main check; fetches, copies, compiles,2 unmodified lines base = self._workspace(snapshot) token = object() with self.lock: if key and key in self.state["requests"]: return self._replay(key, description) if not self.repo.ancestor(base, "main"): raise ToolError("base is not a main commit; fetch main and rebase your branch") # A parked draft (its Hub PR exists, its head never landed) is reused, never recreated.9 unmodified lines "module; open a new PR to add one", "open_budget") number = draft["pr"] if draft else (pr if old else None) pending = self.pending.values() if key and any(p[3] == key for p in pending): raise ToolError("this request is already in progress", "busy") if number is not None and any(p[2] == number for p in pending): raise ToolError("an update of this PR is already in progress; retry when it finishes") if not old and not draft:12 unmodified lines self._check_budget(agent) self.open_reserved.add(token) old_head = old["head_sha"] if old else None self.pending[token] = (agent.name, branch_ref, number, key) self.pending[token] = (agent.name, branch_ref, number) try: number, sha, main, old_head = self._publish(agent, snapshot, base, title, description, branch_ref, number, old_head, started, token, counted=not exempt) exempt=old.get("budget_exempt", False) if old else exempt) with self.lock: if old and (old["state"] != "open" or old["head_sha"] != old_head): raise ToolError("the PR was merged or closed during the update")20 unmodified lines result["note"] = (f"rebased onto main {main[:12]}; run " f"git -c protocol.version=0 fetch origin refs/pr/{number} " "and continue from FETCH_HEAD") if key: self._cache_request(key, result) self._save() self._event("updated" if old else "opened", agent, **result) return result2 unmodified lines self.pending.pop(token, None) self.open_reserved.discard(token)
def _build(self, agent, snapshot, base, title, main): """Commit the upload on base, replayed onto main (outside the world lock).""" def _build(self, agent, snapshot, base, title, main, exempt=False): """Commit the upload on base, replayed onto main (outside the world lock). exempt: the PR is outside the open budget, so the applied change must add no module.""" with self._checkout_slot(), tempfile.TemporaryDirectory(dir=self.tmp_dir) as tmp: tree = Path(tmp) / "tree" self.repo.checkout(base, tree) self._files(snapshot, tree) self._contract(tree, self.repo.staged(tree)) if exempt: # decided from the applied tree: the patch text may hide an added module added = self.repo.git("diff", "--cached", "--name-only", "-z", "--no-renames", "--diff-filter=A", "HEAD", at=tree).split("\0") if any(MODULE_FILE.fullmatch(name) for name in added): raise ToolError("this change adds a module, so it counts against the open " "budget: send your clone through the pybot tools", "open_budget") # An older base is rebased onto main here, before anything exists on the Hub. return self.repo.commit(tree, base, agent.name, title, onto=main)
def _publish(self, agent, snapshot, base, title, description, branch_ref, pr, old_head, started, token=None, counted=True): token=None, exempt=False): """Publish the upload: update open PR pr (old_head set), finish parked draft pr, or create one Hub PR. At most one create_pull_request per call, and a created PR is never closed by the world: if its head cannot be pushed it is parked as a draft.""" deadline = None for _attempt in range(3): main = self.repo.sha() sha = self._build(agent, snapshot, base, title, main) sha = self._build(agent, snapshot, base, title, main, exempt) if pr is None and self.repo.sha() != main: # nothing on the Hub yet: rebuild on a moved main continue if deadline is None:11 unmodified lines pr = self.repo.hub.open(title, f"Agent: {agent.name}\nBase: {main}\n\n{description}") with self.lock: # the reservation becomes a counted open self.open_reserved.discard(token) if counted: if not exempt: now = time.time() self._recent(self.state["pr_opens"], now).append(now) self._dirty("_", "pr_opens")136 unmodified lines137138139140140141142143144145144145146147148149136 unmodified lines self.git("-c", "protocol.version=2", *options, "fetch", "--no-write-fetch-head", *self.negotiation(), remote, *specs, env=env)
def fetch(self): def fetch(self, max_age=0.0): """Fetch main only. The world writes refs/pr/N itself after every push (update_refs), so PR refs never come from the Hub here; a wildcard over refs/pr/* is also refused by the Hub's git backend once there are many PRs (hang-up / 'expected acknowledgments'). A fetch that started after this call is as fresh as this one: waiters behind it return.""" asked = time.monotonic() A fetch that started after this call (or less than max_age seconds before it, also one still running) is as fresh as this one: waiters behind it return.""" asked = time.monotonic() - max_age with self.refs_lock: if self.fetched > asked: return1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157huggingface_hub==1.33.0# huggingface_hub==1.33.0 and its dependencies for the image (Python 3.12, Linux), installed# with --require-hashes. Regenerate with:# echo huggingface_hub==1.33.0 | uv pip compile --generate-hashes --python-version 3.12 \# --python-platform linux --no-header - -o requirements.txtanyio==4.16.0 \ --hash=sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb \ --hash=sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026 # via httpxcertifi==2026.11.20 \ --hash=sha256:7422df25243767b9877031a2248cb14d09ddac9beee846f4cef3d5c9191d488f \ --hash=sha256:af1cb240a8133f105aa52684a3a3258339d7f2fd0bd4e2812698ff5cf5588c4e # via # httpcore # httpxclick==8.5.1 \ --hash=sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37 \ --hash=sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4 # via huggingface-hubfilelock==4.3.2 \ --hash=sha256:02a8801bc6b2a80921bf3d7895c63084d53bae2a3c86783adce5ae2b89a1825b \ --hash=sha256:4f0a21c70447782453c06bb20a9863ee385ead1abaef22049af79289496851b3 # via huggingface-hubfsspec==2026.9.0 \ --hash=sha256:0f08147951c8cb31d844c3547d631053b127863b60be04cf06e121333ee0e2fe \ --hash=sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f # via huggingface-hubh11==0.16.0 \ --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \ --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86 # via httpcorehf-xet==1.8.0 \ --hash=sha256:07a06d7481702616726c2d8578cfb00052a5b3f21beed6a674592bc837a10330 \ --hash=sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e \ --hash=sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01 \ --hash=sha256:23c262e9f5e137b18dadbce60becfeea84156b0d43119c320bffe260d32cd2fa \ --hash=sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d \ --hash=sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4 \ --hash=sha256:3ecfe2934448cca55a4c42732b60f985266aecb241905945219b3d388aceb7ba \ --hash=sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b \ --hash=sha256:56735c2d4f416d7473fc986586b26a8756e067832ca4b7fdaad32a0d6f2ce740 \ --hash=sha256:62b056aedb89ac809f78940baf465fe553b70c8b25ee56890fbab3039fffec1b \ --hash=sha256:7edeb21c5d381903ee5f4857fc746fa7b52a4b374035e8811ecfb67ee27add0c \ --hash=sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f \ --hash=sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec \ --hash=sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c \ --hash=sha256:c74e3751cbcdae9222c5170e8d788e83201a03dc5e5f4308a20f17a5b6023b56 \ --hash=sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e \ --hash=sha256:f42940869572dc2b05dfe06f4cc398c6291503e086ddc4eddfb7a6ab9409ad01 # via huggingface-hubhttpcore==1.0.9 \ --hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55 \ --hash=sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8 # via httpxhttpx==0.29.0 \ --hash=sha256:6734dcf742ced6e8018e45d3f9f7728975b6b3e1085a24f3e2c056069d858bd1 \ --hash=sha256:700928ee6c1f4213795e67c47eba8f8553639069fea89199f71d654e38edc593 # via huggingface-hubhuggingface-hub==1.33.0 \ --hash=sha256:04e434b06e100eddbce9a6e817d72693a7884b10a79bd67ab48080d5c07eb899 \ --hash=sha256:367be21a201db9523eddf8aeac7048f2602c1b308691c97640d5e72ed188007eidna==3.20 \ --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \ --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c # via # anyio # httpxpackaging==26.4 \ --hash=sha256:81383611a09c1bc0b08b76e0fd5829d7c6824c65b27a6aee339da133f4233ea2 \ --hash=sha256:c4b671c41ddb9bf26e543c37723610d28fb6bf7affc4da17cf048d419d2c062a # via huggingface-hubpyyaml==6.0.4 \ --hash=sha256:070c22b6f490d6cc30912be9fb9ab1af9c752769b39b53616f6510c3f038ee6a \ --hash=sha256:0a3a351f04dc124f9357512bdb80ac37cd1750cf1371da33e7cbb96d80ac865f \ --hash=sha256:0db75f402e99c25239003a499c214a61947b4ef5312af34711d4c63e5c179318 \ --hash=sha256:1088ad740f50c13178dad16fbc2fa1f634c791d42c7009fdb390e38e5b90b788 \ --hash=sha256:12a155bc41509d71a2eb73e2191d9e400c1345ea99ac3d9946c31f40a4c840f8 \ --hash=sha256:131d11bd9b60d705a6388366d77ed67850995a4d2be85fe149785a257c17e531 \ --hash=sha256:132c3c7c37a8e6f334921b05cfea5d26e241d792dcbb4db0462129d25ca53b43 \ --hash=sha256:15c52bb238a15bb4fd7e6342a5ac71d594507667c7fe0e5a5abbc0f6875d1e91 \ --hash=sha256:1631d566655f3af7d6c4a4485267830f6b680d3dc9704b659b3c3f4541b5a3fe \ --hash=sha256:180ac792c958c2173f6e4467c55ae5f73ab1a9a624ee29fc7095c56d5e3a4055 \ --hash=sha256:18ea9bda247857fc0de05181675dc116b54c1b04ca3db71de5d2108c882823b7 \ --hash=sha256:1d2f08c122727c86f8303bb1dd45159ca1de1f2d68798e671ec46974e321008e \ --hash=sha256:1db4d51d3c2c9545dd44c614febc4594240754f74b30d8e501415b118347f0d1 \ --hash=sha256:2018fda285d1289527a389e1b4ace1e2d3af410930f949136b55ecb0747744d1 \ --hash=sha256:2c11be5ab4d9f603a598b5ce93a2064ae38087bdf1b384c5397170054cda4e36 \ --hash=sha256:33506a2620f0e7c49858f09cb44e99f144878d03af3d9c10aa136e9a1d103bcd \ --hash=sha256:34edca7ab64b705ee7c80bf3f9ac609240677db11e83d9317191f483a4b5a433 \ --hash=sha256:3c7129bcee5c88c1450802cc6a95b690ee7c51bfcc7a9b60bbd9549a7a4fcbe6 \ --hash=sha256:41b4669c3a8fd5750e594dff59d3e62d40e321fec467b50449603710ed0a68f3 \ --hash=sha256:45e37dd647db9d67b757444c74060c064ace5fdaa08f42bf4fda3812275d423e \ --hash=sha256:49e38a95e24738908ea852e61df0abc58d1e4d4f974ccdb2386eaee412bedc67 \ --hash=sha256:4a2a8f27d24d4cdc05aa11df5f4c08e13f30d9e6674809b6a5ddcfcba49a653a \ --hash=sha256:4a329472db6c8858ebd94f2214a54c8bff8f035a6cc7af1ab39cc1b33a5f0e56 \ --hash=sha256:4d1e8d6e345b4b4424a05a11e699e999e65a88f422f73636f8a0b354bf219ffa \ --hash=sha256:4d30c2f186612bd2f9f07c08a4c96721af59cfc8da3ec7cb27dfa2834e8bb019 \ --hash=sha256:4d3bbc5e8a84a5a6775adecac786f489510a7159b1c343d6f31426d888cfdd6e \ --hash=sha256:50588147ab2c6a59b5f990a4905db80899a6c2bd197e046a6201f1e67587e794 \ --hash=sha256:52460c6dd874b22d49fda228fac59da74d7a7b06175ffcc80bfa3ba5389d7f73 \ --hash=sha256:5246a0feaaac497b09c9462aa926280ae02fc8791b0099c0a925ebd7c7f249a6 \ --hash=sha256:54c23934cf166bb2090d73d82b1388aadb1cead5e73885223dcfa4a459a22d43 \ --hash=sha256:573debb9fe3075423d4f823795a678580e597218c25baef178d532b124a25a25 \ --hash=sha256:609e8efaffa5662da16b7d53eef76fc4eedbbe56fce5829b67ba808a6e35d399 \ --hash=sha256:60e9da2772e259307650e03c24f50e3bc2d9fa5ed1ba44c47582e13b0e7708d1 \ --hash=sha256:61eef2f08e977b725f37a8d1663f5a222c6f09207ac0794030d5fca062e7c96e \ --hash=sha256:622aa875fa6533f25fedcffe23079357d65a690d462200afed5d8e9d0e01ebee \ --hash=sha256:62c5b5669b05dabf991a705f3a3601f57b65e95121a1d3e3a4ae4446c8632865 \ --hash=sha256:67da066ca12eb60114ea87f2ecbcca622fff0c205c743cc900437127564fabf6 \ --hash=sha256:69380d4bae12aab2a2c9532deff6a2841bc9fda47c333691bd2368b696301768 \ --hash=sha256:6ac167ebebc0c387290406a337b9b5c8c343fa5f7928d5941e45a94b8ba3aa39 \ --hash=sha256:71bb5b87465d88d1dfc577115af6d435bff9b26f2512936f610c26aa55966028 \ --hash=sha256:730788375056c43d3ac15bd894c9cd2fb7a931a38b302f408620c64b3ef176ed \ --hash=sha256:7335809813ec838d9cd334b1744cda33deb141c9ef23a9c0df371c37980d3851 \ --hash=sha256:78be5a1b05a5d1fd46d0290393e5deeb581fa617585462c1b84f7c6b0cb1e489 \ --hash=sha256:84e97378010f3da8daf673b82d39ed638098d236a1b760d61c0c1348a642bd70 \ --hash=sha256:8708f6ab9c2581ffa05f66dae3206bb0385949650537d7295fc7ab0d6454dd70 \ --hash=sha256:872d2a592289061c1b987e335b3568a2616b474be02bd0608d8f551a385441cd \ --hash=sha256:88a089e6424a8a256321270620d5a4328ad5227fb2061b07d33f596894336914 \ --hash=sha256:8e0cd755ce5e9009fd95f9c553e5942478feb8f7dffa19435641fcdc3c20e8ca \ --hash=sha256:914b19e17814315fbcca52031bf79b68237f3d87a948c584a667b18b468e4df7 \ --hash=sha256:93bfb2459195406a518e2f487a9bbf01df240175f31e06f5a252ac6734c7bbf0 \ --hash=sha256:93da48af92c84c4236578e330a514ca324362c0bb62894d8d2343363ed57ff03 \ --hash=sha256:9d4211f080920629a90c9e31c51e326fb70cfae38f18d4128b9913c23642bace \ --hash=sha256:9e7ec9dc75cadd392fd687cc9b8ccf7dd59ada0a991e0d14ae0fad9ecdba00c3 \ --hash=sha256:a266cf55ee5cf63c1803432a61c6386e750e0012ca49d12d26ccb0ffd80b343a \ --hash=sha256:a3cc63af3d639d1609143711837b926183418260aae89ed95193c07b25b99d33 \ --hash=sha256:a56491babf0d976625807953bd192dd9de973fccb3270e77b1a795b152a26175 \ --hash=sha256:a65339c24f2fb8d4419e06ceec1bda98bdcff727b3b533a81d5af6bb2dd34520 \ --hash=sha256:ab874ebcc5c12c31c859a9e9fe159d688df1f7a099818ef8a35906264a8f5d6b \ --hash=sha256:b525488d5addf5d59ff4610cd8b1deab9dc97fe0fb3fb74533d7f65e9792bd92 \ --hash=sha256:b9fe0b8c65a1611053eb7fcaa7c022f655b7eebeb0ea034572615453cae6b843 \ --hash=sha256:c0d68d972f6f6417b4e85e9522f3d57bb4fbc924379766ccd87254a31009c1cd \ --hash=sha256:c24097c0462f66358c99dc83d3e1850e005f6293cfa1df1edb243428da1668bf \ --hash=sha256:c57e40928738c4a202852759f9e1ee2c7063429a9469ee1ac15651bbf7d69963 \ --hash=sha256:c604dc2613c417130479cdd6e55c2faa691b6365aa82b3dafddfcecc2eaf1ac7 \ --hash=sha256:c680622f85979f2ff59b4ae44c1ecb5566b2f0f0ffe5d0dc8b4bb6a0e916dabb \ --hash=sha256:d276f23e2371deb5ee68dd252cc9c2402b806b54d8d2cc7efbb6c34c3a78d886 \ --hash=sha256:d58fe9fa2056fed24f055b74d5dc808fa1f5d084c22e4118f0a08253fe677ffd \ --hash=sha256:e24bf71af8a432d7808fabff134d38dfe16d3cbb41f2873bb4b1e42422de0a1a \ --hash=sha256:e39017e1cef43d03b2ba427f60213e4b36dbc6fb092235fa3de3a510ce064d3c \ --hash=sha256:e956541cc7a3fff2bb5b17aeb6c5bb42c86c8e6dafb5ebdd41a05e72e702076b \ --hash=sha256:ed9b957abb12f6ffcd92d5db32fa3ffd4e4a8423d80ddd51b4efa63b42f6a76b \ --hash=sha256:efe68ed09903cca9ab4117c2b9ea6ee8d369818808945bb5a7fa8009b5630b45 \ --hash=sha256:f1a4a85b419f5cb6470dd4be5f766bc59532f11b9c22c076b58a0348f05dca5f \ --hash=sha256:f5c410f9e2ffc9286279a46f2e8c107edaf3b1123510af59c828a9c15b23c9db \ --hash=sha256:f617e4e5c619fef5284335b24e3af3a77ce08dc5c389ff4b25033bb2749032b7 # via huggingface-hubtqdm==4.70.1 \ --hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73 \ --hash=sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4 # via huggingface-hubtyping-extensions==4.16.0 \ --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \ --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5 # via # anyio # huggingface-hub193 unmodified lines1941951961971981992003 unmodified lines20420520620720820921021110 unmodified lines22222322422522622722811 unmodified lines2402412422432442452464 unmodified lines25125225324925425525625713 unmodified lines271272273274275276277278193 unmodified lines
class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" # keep-alive: every answer has a Content-Length timeout = 60 # per socket read: an idle or stalled connection is dropped
def log_message(self, format, *args): # no access log pass3 unmodified lines self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) if self.close_connection: # so the client opens a new connection for its next request self.send_header("Connection", "close") if retry_after_s is not None and status in (429, 503): self.send_header("Retry-After", str(max(1, math.ceil(retry_after_s)))) self.end_headers()10 unmodified lines raise Refused(413, "too_large", f"the request body must be at most {limit} bytes " "(with Content-Length)") data = self.rfile.read(n) self.body_read = True try: return json.loads(data) if data.strip() else {} except ValueError:11 unmodified lines def route(self, method: str) -> None: app, path = self.server.app, self.path.split("?", 1)[0] upstream = path.startswith("/v1/tools/") self.body_read = False try: if method == "GET" and path == "/healthz": return self.send(200, {"status": "parked" if app.world is None else "ready"})4 unmodified lines app.agent(self.headers) return self.send(200, app.manifest) if method == "POST" and (upstream or path.startswith("/world/tools/")): agent = Agent(app.agent(self.headers), self.headers.get("X-Request-Id") or "") agent = Agent(app.agent(self.headers)) body = self.body(MAX_BODY) if upstream: args = body13 unmodified lines return self.send(status, {"error": error}, e.retry_after_s) return self.send(200, {"ok": False, "error": error}) except Refused as e: if not self.body_read: # a body left unread would be taken as the next request self.close_connection = True error = {"code": e.code, "message": e.message} if e.retry_after_s is not None: error["retry_after_s"] = e.retry_after_s5 unmodified lines6789101112262 unmodified lines275276277278279280281282283284285286287288289342 unmodified lines632633634625635636637638158 unmodified lines7977987997907917928008018028037 unmodified lines8118128138068148158088098108118128138168178181003 unmodified lines18221823182418231825182618271828182718281829183018311832183318341835183618291830183118321833183418351836607 unmodified lines24442445244624502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502244724482449521 unmodified lines29712972297329742975297629772978297929802981298265 unmodified lines30483049305030513052305330543055305630573058305930603061306230633064306530663067306830695 unmodified linesimport osimport reimport shutilimport socketimport subprocessimport sysimport threading262 unmodified lines assert c.get("/metrics", headers={"X-World-Token": "a" * 40}).json()["world"]["open_prs"] == 1 r = c.patch("/admin/knobs", json={"pr.open_floor": 3}, headers={"X-World-Token": "a" * 40}) assert r.json()["ok"] and world.budget_floor == 3 # a refusal before the body is read closes the connection: its body is no next request with socket.create_connection(("127.0.0.1", httpd.server_port), timeout=10) as s: junk = b"GET /healthz HTTP/1.1\r\nHost: x\r\n\r\n" s.sendall(b"POST /world/tools/list_prs HTTP/1.1\r\nHost: x\r\n" b"Content-Length: %d\r\n\r\n%s" % (len(junk), junk)) data = b"" while chunk := s.recv(65536): data += chunk assert data.startswith(b"HTTP/1.1 401") and data.count(b"HTTP/1.1 ") == 1, data finally: httpd.shutdown() httpd.server_close()342 unmodified lines world, clone, _ = setup rec = submit(world, clone) approve(world, rec) assert world.knobs == {"save.interval_s": world.save_interval, "save.legacy_json": True, assert world.admin.values == {"save.interval_s": world.save_interval, "save.legacy_json": True, "review.max_reviewers": 0, "pr.open_floor": 20, "hub.push.slots": 1, "hub.merge.slots": 1, "hub.comment.slots": 1, "hub.comment.gap_s": 0.0} world.admin.set({"hub.push.slots": 2, "hub.comment.gap_s": 0.5})158 unmodified lines assert git(remote, "rev-parse", f"refs/pr/{rec['pr']}") == rec["head_sha"]
def test_refusals_are_logged_and_request_keys_are_bounded(setup, monkeypatch): import pybot
def test_refusals_are_logged(setup): world, clone, _ = setup rec = submit(world, clone) with pytest.raises(ToolError, match="self-review"):7 unmodified lines ("merge_pr_refused", "birch", rec["pr"], "tool_error")] from api import tool_schema
schema = tool_schema(world.tools()["merge_pr"]) schema = tool_schema(world.tool_functions()["merge_pr"]) assert list(schema["parameters"]["properties"]) == ["pr"] # the wrapper keeps the schema monkeypatch.setattr(pybot, "MAX_REQUESTS", 2) for i in range(3): call_workspace(world, "open_pr", {"branch": "greeting", "title": "Bounded keys", "description": "x", "pr": rec["pr"]}, Agent("cedar", request_id=f"req-{i}"), capture(clone)) assert list(world.state["requests"]) == ["req-1", "req-2"]
def test_hub_failure_logs_status_and_headers_but_no_secrets(monkeypatch, caplog):1003 unmodified lines assert len(old.call("list_prs", {}, Agent("cedar"))["inbox"]) == 2
def test_inbox_age_and_idempotent_retry_keep_the_cached_result(setup):def test_inbox_age_and_a_retried_open_pr_opens_no_second_pr(setup): world, clone, _ = setup assert [PybotWorld._age(s) for s in (5, 180, 7200, 200000)] == [ "just now", "3 min ago", "2 h ago", "2 d ago"] first = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings", "description": "Tested."}, Agent("cedar", request_id="k1"), capture(clone)) with world.lock: world._notify("cedar", 99, "merged", "news") retry = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings", "description": "Tested."}, Agent("cedar", request_id="k1"), capture(clone)) assert retry["inbox"] == ["news (just now)"] and retry["pr"] == first["pr"] assert "inbox" not in world.state["requests"]["k1"] args = {"branch": "greeting", "title": "Improve greetings", "description": "Tested."} first = call_workspace(world, "open_pr", args, Agent("cedar"), capture(clone)) with pytest.raises(ToolError, match="branch slug already used"): call_workspace(world, "open_pr", args, Agent("cedar"), capture(clone)) assert world.repo.hub.n == first["pr"] and len(world.state["prs"]) == 1
def _wait(cond, timeout=10):607 unmodified lines assert world.db.read_text() == json.dumps(world.state)
def _open(world, clone, key, description="Tested a conversation.", pr=None, author="cedar"): result = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings", "description": description, "pr": pr}, Agent(author, request_id=key), capture(clone)) return {k: v for k, v in result.items() if k not in ("pr_budget", "inbox")}
def test_idempotent_replay_returns_the_same_result_from_a_slim_cache(setup): world, clone, _ = setup long = "Evidence:\n" + "transcript line\n" * 2000 first = _open(world, clone, "k1", long) assert first["description"] == long entry = world.state["requests"]["k1"] assert entry["description"] is None and len(json.dumps(entry)) < 1500 assert _open(world, clone, "k1", long) == first assert list(_open(world, clone, "k1", long)) == list(first) # same keys, same order # The PR is updated with another description; a late retry of k1 still gets its own. (clone / "bot/modules/greeting.py").write_text('def respond(text, memory):\n return "Hi!"\n') second = _open(world, clone, "k2", "Second version.", pr=first["pr"]) assert second["description"] == "Second version." assert _open(world, clone, "k1", long) == first restarted = PybotWorld(world.ws, world.repo) # replays from prs.json assert _open(restarted, clone, "k1", long) == first assert _open(restarted, clone, "k2", "Second version.", pr=first["pr"]) == second
def test_old_request_cache_is_slimmed_on_load_and_expires(setup, monkeypatch): import pybot
world, clone, _ = setup first = _open(world, clone, "k1", "Original long description " * 200) world.close() state = _on_disk(world) # A cached result stored in full, with no timestamp. state["requests"]["k1"] = dict(first) state["requests"]["old"] = {**first, "description": "y" * 10000} _write_archive(world, state) restarted = PybotWorld(world.ws, world.repo) restarted.close() on_disk = _on_disk(restarted)["requests"] assert all(e["description"] is None and "_ts" in e for e in on_disk.values()) assert len(json.dumps(on_disk)) < 2000 again = PybotWorld(world.ws, world.repo) assert _open(again, clone, "k1", "Original long description " * 200) == first # The rebuilt description falls back to the PR record when the retry's differs. assert _open(again, clone, "k1", "a different text")["description"] == first["description"] monkeypatch.setattr(pybot, "REQUEST_TTL", 60) with again.lock: again.state["requests"]["k1"]["_ts"] -= 120 again._cache_request("new", {"pr": 9, "description": "z"}) assert list(again.state["requests"]) == ["old", "new"]
def test_merge_has_its_own_hub_slot(setup): world, clone, remote = setup rec = submit(world, clone)521 unmodified lines git(clone, "fetch", "-q") (clone / "bot/modules/greeting.py").write_text('def respond(text, memory):\n return "Hey!"\n') assert not world.repo.has_commit(capture(clone)["base_sha"]) world.repo.fetched = time.monotonic() with pytest.raises(ToolError) as e: # the last fetch is under 5 s old: no new one yet call_workspace(world, "run_bot", {"ref_or_path": "pybot", "lines": ["hi"]}, Agent("cedar"), capture(clone)) assert e.value.code == "unknown_base" world.repo.fetched -= 5 out = call_workspace(world, "run_bot", {"ref_or_path": "pybot", "lines": ["hi"]}, Agent("cedar"), capture(clone)) assert out["replies"] == ["Hey!"] and out["sha"] == git(remote, "rev-parse", "main")65 unmodified lines with pytest.raises(ToolError, match="open a new PR to add one") as exc: submit(world, clone, "birch", "greeting-fix", pr=fix["pr"]) assert exc.value.code == "open_budget" # A plain unified diff (no diff --git header) hides the new module from the patch reader: # refused as a workspace, and a module found in the applied tree is never exempt. (clone / "bot/modules/news.py").unlink() plain = (b"--- /dev/null\n+++ b/bot/modules/news.py\n@@ -0,0 +1,2 @@\n" b"+def respond(text, memory):\n+ return None\n") sneaky = {**capture(clone), "patch": base64.b64encode(plain).decode()} assert not world._adds_module(sneaky) with pytest.raises(ToolError, match="diff --git") as exc: call_workspace(world, "open_pr", {"branch": "news", "title": "News", "description": "x"}, Agent("oak"), sneaky) assert exc.value.code == "bad_workspace" _module(clone, "news", None) monkeypatch.setattr(world, "_adds_module", lambda workspace: False) with pytest.raises(ToolError, match="adds a module") as exc: submit(world, clone, "oak", "news") assert exc.value.code == "open_budget" and len(world.state["pr_opens"]) == 1 with pytest.raises(ValueError, match="all or new_modules"): monkeypatch.setenv("PYBOT_PR_OPEN_BUDGET_SCOPE", "some") PybotWorld(world.ws, world.repo)39 unmodified lines40414243444546471 unmodified line495051505253545539 unmodified lines patch = base64.b64decode(workspace.get("patch") or "", validate=True) except (ValueError, TypeError) as exc: raise ValueError("invalid workspace patch") from exc if patch and not patch.startswith(b"diff --git "): # what the file count and checks parse raise ValueError("the patch must be `git diff` output (starting with diff --git)") if git(tree, "rev-parse", "HEAD") != workspace.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)):1 unmodified line # shortcut: 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 if (patch.count(b"\ndiff --git ") + bool(patch) > 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 threadedREADME.md+35-56
world/Dockerfile+2-2
world/api.py+3-13
world/pybot.py+18-101
world/repository.py+4-3
world/requirements.txt+157-1
world/server.py+8-1
world/tests/test_pybot.py+41-75
world/workspace.py+3-1