A plugin that provides runs.limits sets how many agents each machine runs at once. A launch over the limit waits in the hub's queue (runs/queue.py) and starts when the machine is back under it; the limit rides every launch to the sidecar, which hands it to the run for the plugin's hooks. SubagentStart / SubagentStop join the script hook events. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
367 lines
19 KiB
Python
367 lines
19 KiB
Python
"""Agent limits (2026-11-29, for the ``agent-limits`` plugin): ``provides:
|
|
runs.limits`` (``plugins/run_limits.py``), the hub's queue behind a machine's
|
|
limit (``runs/queue.py`` — the gate in the send path, the pump, start now,
|
|
cancel), ``agentLimit`` on every launch, the ``/api/runs/queue`` routes, the
|
|
``SubagentStart`` / ``SubagentStop`` script hooks and the sidecar's run env."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
from unittest import mock
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t", "WORKSPACE": TMP, "REPO_DIR": TMP,
|
|
"ARCHIVE_DIR": TMP / "arch", "META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
|
|
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror", "CRON_PATH": TMP / "cron.json",
|
|
"PROFILES_PATH": TMP / "profiles.json", "USERS_PATH": TMP / "users.json",
|
|
"AUTH_PATH": TMP / "auth.json", "INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "",
|
|
"PI_TRANSCRIPTS_DIR": "", "RUN_QUEUE_PATH": TMP / "run-queue.json"}.items():
|
|
os.environ.setdefault(k, str(v))
|
|
|
|
from fastapi import HTTPException # noqa: E402
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import accounts # noqa: E402
|
|
import main # noqa: E402
|
|
import workers # noqa: E402
|
|
from core import liveruns # noqa: E402
|
|
from plugins import run_limits # noqa: E402
|
|
from plugins.manifest import ManifestError, capability_summary, validate_manifest # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
from runs import queue as run_queue # noqa: E402
|
|
from runs.service import _send_message # noqa: E402
|
|
from users.caller import guest_from_record # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
OWNER_H = {"X-Internal-Auth": os.environ["INTERNAL_API_TOKEN"]}
|
|
|
|
MF = {"schema": 1, "id": "agent-limits", "name": "Agent limits",
|
|
"actions": {"limits": {"script": "handlers/limits.py", "readOnly": True},
|
|
"set": {"script": "handlers/limits.py"}},
|
|
"provides": {"runs.limits": "limits"}}
|
|
HANDLER = """import json, sys
|
|
json.load(sys.stdin)
|
|
print(json.dumps({"limits": {"w1": 6, "local": "4", "off": 0, "neg": -2, "bad": "x",
|
|
"big": 100000, "flag": True}}))
|
|
"""
|
|
|
|
|
|
def _write(root: pathlib.Path, manifest: dict, files: dict) -> pathlib.Path:
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
(root / "plugin.json").write_text(json.dumps(manifest))
|
|
for rel, body in files.items():
|
|
p = root / rel
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
p.write_text(body)
|
|
return root
|
|
|
|
|
|
# ── the provider ─────────────────────────────────────────────────────────────
|
|
class Provider(unittest.TestCase):
|
|
def setUp(self):
|
|
run_limits.invalidate()
|
|
self.td = tempfile.TemporaryDirectory()
|
|
self.store = PluginStore(pathlib.Path(self.td.name) / "data")
|
|
self.store.install(OWNER_UID, str(_write(pathlib.Path(self.td.name) / "src", MF,
|
|
{"handlers/limits.py": HANDLER})),
|
|
is_owner=True, approve=True)
|
|
self.p = mock.patch.object(DEPS, "plugin_store", self.store)
|
|
self.p.start()
|
|
|
|
def tearDown(self):
|
|
self.p.stop()
|
|
self.td.cleanup()
|
|
run_limits.invalidate()
|
|
|
|
def test_manifest_validates_and_is_labelled(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = validate_manifest(_write(pathlib.Path(td) / "p", MF, {"handlers/limits.py": HANDLER}))
|
|
with self.assertRaises(ManifestError):
|
|
validate_manifest(_write(pathlib.Path(td) / "q",
|
|
{**MF, "provides": {"runs.limits": "nope"}},
|
|
{"handlers/limits.py": HANDLER}))
|
|
self.assertEqual(mf["provides"], {"runs.limits": "limits"})
|
|
self.assertTrue(any(i["kind"] == "provides" and i.get("privileged") and "at once" in i["label"]
|
|
for i in capability_summary(mf)))
|
|
|
|
def test_limits_cleaned_and_cached(self):
|
|
self.assertEqual(run_limits.limits(DEPS), {"w1": 6, "local": 4, "big": run_limits.MAX_LIMIT})
|
|
self.assertEqual(run_limits.limit_for(DEPS, None), 4)
|
|
self.assertEqual(run_limits.limit_for(DEPS, "w1"), 6)
|
|
self.assertIsNone(run_limits.limit_for(DEPS, "off"))
|
|
with mock.patch("plugins.runner.run_script") as run:
|
|
run_limits.limits(DEPS)
|
|
run.assert_not_called()
|
|
|
|
def test_a_write_drops_the_cache_a_read_doesnt(self):
|
|
run_limits.limits(DEPS)
|
|
rec = {"manifest": MF}
|
|
run_limits.touched(DEPS, rec, action="limits")
|
|
self.assertIsNotNone(run_limits._cache)
|
|
run_limits.touched(DEPS, rec, action="set")
|
|
self.assertIsNone(run_limits._cache)
|
|
|
|
def test_no_provider_or_a_broken_one_is_no_limit(self):
|
|
with mock.patch("plugins.runner.run_script", side_effect=RuntimeError("boom")):
|
|
self.assertEqual(run_limits.limits(DEPS), {})
|
|
run_limits.invalidate()
|
|
with tempfile.TemporaryDirectory() as td, \
|
|
mock.patch.object(DEPS, "plugin_store", PluginStore(pathlib.Path(td))):
|
|
self.assertEqual(run_limits.limits(DEPS), {})
|
|
self.assertFalse(run_limits.has_provider(DEPS))
|
|
|
|
|
|
# ── the queue in the send path ───────────────────────────────────────────────
|
|
class Queue(unittest.TestCase):
|
|
"""A real (fake) worker, online, with a limit the tests set."""
|
|
|
|
def setUp(self):
|
|
from _fakeworker import FakeWorker
|
|
run_queue.reset()
|
|
pathlib.Path(os.environ["RUN_QUEUE_PATH"]).unlink(missing_ok=True)
|
|
self.fw = FakeWorker(TMP / "remote-q", TMP / "state-q")
|
|
self.w = workers.pair(DEPS.worker_store, self.fw.pairing_string("work"),
|
|
account=None, name="box", hub_name="t",
|
|
resolve_login=lambda _l: None, valid_account=accounts.valid)
|
|
self.wid = self.w["id"]
|
|
DEPS.profile_store.assign_worker(self.w, "work")
|
|
DEPS.profile_store.patch_runner(self.wid, {"default": True})
|
|
DEPS.worker_store.set_status(self.wid, status="online")
|
|
self.limits: dict[str, int] = {}
|
|
self.subs = 0
|
|
self.patches = [mock.patch.object(run_limits, "limits", side_effect=lambda _d: dict(self.limits)),
|
|
mock.patch.object(run_queue, "_subagents", side_effect=lambda _d, _s: self.subs)]
|
|
for p in self.patches:
|
|
p.start()
|
|
liveruns.update(self.wid, set())
|
|
|
|
def tearDown(self):
|
|
for p in reversed(self.patches):
|
|
p.stop()
|
|
self.fw.stop()
|
|
liveruns.drop(self.wid)
|
|
DEPS.worker_store.delete(self.wid)
|
|
DEPS.profile_store.forget_worker(self.wid)
|
|
run_queue.reset()
|
|
|
|
def _live(self, *sids):
|
|
liveruns.update(self.wid, set(sids))
|
|
|
|
def _spawns(self):
|
|
return [b for path, b in self.fw.calls if path == "/spawn"]
|
|
|
|
def test_no_limit_launches_as_before(self):
|
|
out = _send_message(DEPS, "hi", worker=self.wid)
|
|
self.assertNotIn("queued", out)
|
|
self.assertNotIn("agentLimit", self._spawns()[-1])
|
|
self.assertEqual(run_queue.count(), 0)
|
|
|
|
def test_under_the_limit_launches_and_carries_the_limit(self):
|
|
self.limits = {self.wid: 2}
|
|
out = _send_message(DEPS, "hi", worker=self.wid)
|
|
self.assertNotIn("queued", out)
|
|
self.assertEqual(self._spawns()[-1]["agentLimit"], 2)
|
|
# the launch holds a slot before the runner's next poll lists it
|
|
self.assertEqual(run_queue.usage(DEPS, self.wid)["conversations"], 1)
|
|
|
|
def test_at_the_limit_a_new_run_waits_then_starts_first_in_first_out(self):
|
|
self.limits = {self.wid: 1}
|
|
self._live("a" * 8 + "-0000-0000-0000-000000000000")
|
|
a = _send_message(DEPS, "first", worker=self.wid, stamp={"owner": "me"})
|
|
b = _send_message(DEPS, "second", profile="work") # routed, then pinned
|
|
self.assertEqual(self._spawns(), [])
|
|
self.assertEqual((a["queued"]["position"], b["queued"]["position"]), (1, 2))
|
|
self.assertEqual(a["queued"], {"worker": self.wid, "position": 1, "limit": 1, "running": 1,
|
|
"name": "box"})
|
|
self.assertIsNone(a["pid"])
|
|
m = DEPS.meta_store.get(a["sessionId"])
|
|
self.assertEqual((m["queued"]["position"], m["owner"], m.get("state")), (1, "me", None))
|
|
got = run_queue.listing(DEPS)
|
|
self.assertEqual([(i["sessionId"], i["position"], i["prompt"]) for i in got],
|
|
[(a["sessionId"], 1, "first"), (b["sessionId"], 2, "second")])
|
|
# still full: nothing moves
|
|
self.assertEqual(run_queue.pump(DEPS), 0)
|
|
# the live run ends: one slot — the oldest starts, with its own id
|
|
self._live()
|
|
self.assertEqual(run_queue.pump(DEPS), 1)
|
|
self.assertEqual([s["sessionId"] for s in self._spawns()], [a["sessionId"]])
|
|
self.assertEqual(self._spawns()[0]["prompt"], "first")
|
|
m = DEPS.meta_store.get(a["sessionId"])
|
|
self.assertEqual((m["queued"], m["state"], m["worker"]), (False, "running", self.wid))
|
|
self.assertEqual([i["position"] for i in run_queue.listing(DEPS)], [1])
|
|
# the queue is on disk
|
|
run_queue.reset()
|
|
self.assertEqual([i["sessionId"] for i in run_queue.listing(DEPS)], [b["sessionId"]])
|
|
|
|
def test_subagents_count_in_the_budget(self):
|
|
self.limits = {self.wid: 3}
|
|
self._live("b" * 8 + "-0000-0000-0000-000000000000")
|
|
self.subs = 2
|
|
out = _send_message(DEPS, "hi", worker=self.wid)
|
|
self.assertEqual(out["queued"]["running"], 3)
|
|
self.subs = 1
|
|
self.assertEqual(run_queue.pump(DEPS), 1)
|
|
|
|
def test_an_offline_machine_keeps_its_queue_until_it_is_back(self):
|
|
self.limits = {self.wid: 1}
|
|
self._live("7" * 8 + "-0000-0000-0000-000000000000")
|
|
_send_message(DEPS, "later", worker=self.wid)
|
|
self._live()
|
|
DEPS.worker_store.set_status(self.wid, status="offline")
|
|
self.assertEqual(run_queue.pump(DEPS), 0)
|
|
self.assertEqual([(i["position"], i["error"]) for i in run_queue.listing(DEPS)], [(1, None)])
|
|
DEPS.worker_store.set_status(self.wid, status="online")
|
|
self.assertEqual(run_queue.pump(DEPS), 1)
|
|
|
|
def test_a_raised_or_removed_limit_lets_the_queue_go(self):
|
|
self.limits = {self.wid: 1}
|
|
self._live("c" * 8 + "-0000-0000-0000-000000000000")
|
|
for i in range(3):
|
|
_send_message(DEPS, f"p{i}", worker=self.wid)
|
|
self.limits = {}
|
|
self.assertEqual(run_queue.pump(DEPS), 3)
|
|
self.assertEqual(run_queue.count(), 0)
|
|
|
|
def test_a_turn_into_a_dead_session_waits_a_live_one_doesnt(self):
|
|
sid = "44444444-2222-3333-4444-555555555555"
|
|
other = "d" * 8 + "-0000-0000-0000-000000000000"
|
|
DEPS.meta_store.update(sid, {"worker": self.wid, "account": "work", "state": "finished"})
|
|
self.limits = {self.wid: 1}
|
|
self._live(other)
|
|
out = _send_message(DEPS, "more", session_id=sid, cwd="/r")
|
|
self.assertEqual(out["queued"]["position"], 1)
|
|
self.assertEqual(self.fw.calls, [])
|
|
# one more turn: one start, both messages
|
|
_send_message(DEPS, "and this", session_id=sid, cwd="/r")
|
|
_send_message(DEPS, "and this", session_id=sid, cwd="/r") # a re-send adds nothing
|
|
self.assertEqual([i["prompt"] for i in run_queue.listing(DEPS)], ["more\n\nand this"])
|
|
self.assertEqual(DEPS.meta_store.get(sid)["state"], "finished")
|
|
self._live()
|
|
self.assertEqual(run_queue.pump(DEPS), 1)
|
|
path, body = self.fw.calls[-1]
|
|
self.assertEqual((path, body["sessionId"], body["prompt"]), ("/resume", sid, "more\n\nand this"))
|
|
self.assertEqual(body["agentLimit"], 1)
|
|
# its own run is live: a follow-up starts no process, so it never waits
|
|
live = "55555555-2222-3333-4444-555555555555"
|
|
DEPS.meta_store.update(live, {"worker": self.wid, "account": "work", "state": "running"})
|
|
self._live(live, other)
|
|
self.fw.inbox.add(live)
|
|
self.fw.live.add(live)
|
|
out = _send_message(DEPS, "psst", session_id=live, cwd="/r")
|
|
self.assertNotIn("queued", out)
|
|
|
|
def test_start_now_goes_over_the_limit_and_cancel_drops(self):
|
|
self.limits = {self.wid: 1}
|
|
self._live("e" * 8 + "-0000-0000-0000-000000000000")
|
|
a = _send_message(DEPS, "one", worker=self.wid)
|
|
b = _send_message(DEPS, "two", worker=self.wid, run_as=None)
|
|
out = run_queue.start_now(DEPS, b["sessionId"])
|
|
self.assertEqual(out["sessionId"], b["sessionId"])
|
|
self.assertEqual([s["sessionId"] for s in self._spawns()], [b["sessionId"]])
|
|
run_queue.cancel(DEPS, a["sessionId"])
|
|
self.assertEqual(run_queue.count(), 0)
|
|
self.assertEqual(DEPS.meta_store.get(a["sessionId"])["state"], "interrupted")
|
|
with self.assertRaises(HTTPException) as cm:
|
|
run_queue.cancel(DEPS, a["sessionId"])
|
|
self.assertEqual(cm.exception.status_code, 404)
|
|
|
|
def test_a_start_that_fails_stays_listed_and_frees_the_line(self):
|
|
self.limits = {self.wid: 1}
|
|
self._live("f" * 8 + "-0000-0000-0000-000000000000")
|
|
a = _send_message(DEPS, "one", worker=self.wid)
|
|
b = _send_message(DEPS, "two", worker=self.wid)
|
|
self._live()
|
|
real = run_queue._start
|
|
|
|
def start(deps, item):
|
|
if item["sessionId"] == a["sessionId"]:
|
|
with mock.patch("runs.service._launch",
|
|
side_effect=HTTPException(502, {"message": "no CLI", "kind": "x"})):
|
|
return real(deps, item)
|
|
return real(deps, item)
|
|
with mock.patch.object(run_queue, "_start", side_effect=start):
|
|
self.assertEqual(run_queue.pump(DEPS), 1)
|
|
got = {i["sessionId"]: i for i in run_queue.listing(DEPS)}
|
|
self.assertEqual(list(got), [a["sessionId"]])
|
|
self.assertEqual((got[a["sessionId"]]["error"], got[a["sessionId"]]["position"]), ("no CLI", None))
|
|
self.assertEqual([s["sessionId"] for s in self._spawns()], [b["sessionId"]])
|
|
# Retry = start now
|
|
run_queue.start_now(DEPS, a["sessionId"])
|
|
self.assertEqual(run_queue.count(), 0)
|
|
|
|
def test_a_guest_sees_and_cancels_only_their_own(self):
|
|
self.limits = {self.wid: 1}
|
|
self._live("9" * 8 + "-0000-0000-0000-000000000000")
|
|
mine = _send_message(DEPS, "owner's", worker=self.wid)
|
|
with run_queue._lock:
|
|
run_queue._load().append({"sessionId": "66666666-2222-3333-4444-555555555555",
|
|
"runner": self.wid, "kind": "new", "at": "x", "runAs": "cel",
|
|
"prompt": "cel's", "kwargs": {"prompt": "cel's"}})
|
|
self.assertEqual([i["prompt"] for i in run_queue.listing(DEPS, "cel", everyone=False)], ["cel's"])
|
|
with self.assertRaises(HTTPException):
|
|
run_queue.cancel(DEPS, mine["sessionId"], "cel", everyone=False)
|
|
run_queue.cancel(DEPS, "66666666-2222-3333-4444-555555555555", "cel", everyone=False)
|
|
|
|
def test_routes(self):
|
|
from authz.routes import TABLE
|
|
from runs.routes import run_queue_start
|
|
self.limits = {self.wid: 1}
|
|
self._live("8" * 8 + "-0000-0000-0000-000000000000")
|
|
c = TestClient(main.app, headers=OWNER_H)
|
|
r = c.post("/api/spawn", json={"prompt": "hello", "worker": self.wid})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
sid, q = r.json()["sessionId"], r.json()["queued"]
|
|
self.assertEqual((q["position"], q["limit"]), (1, 1))
|
|
got = c.get("/api/runs/queue").json()
|
|
self.assertEqual([(i["sessionId"], i["workerName"]) for i in got["items"]], [(sid, "box")])
|
|
self.assertEqual(got["machines"], [{"worker": self.wid, "name": "box", "limit": 1,
|
|
"conversations": 1, "subagents": 0, "total": 1, "queued": 1}])
|
|
self.assertEqual(c.post(f"/api/runs/queue/{sid}/start").json()["sessionId"], sid)
|
|
self.assertEqual(c.delete(f"/api/runs/queue/{sid}").status_code, 404)
|
|
with self.assertRaises(HTTPException) as cm:
|
|
run_queue_start(DEPS, guest_from_record({"id": "cel", "name": "Cel"}), sid)
|
|
self.assertEqual(cm.exception.status_code, 403)
|
|
for key in (("GET", "/api/runs/queue"), ("POST", "/api/runs/queue/{sid}/start"),
|
|
("DELETE", "/api/runs/queue/{sid}")):
|
|
self.assertEqual(TABLE[key], "runs.start")
|
|
|
|
|
|
# ── the worker's side ────────────────────────────────────────────────────────
|
|
class Worker(unittest.TestCase):
|
|
def test_subagent_events_take_script_hooks_only(self):
|
|
files = {"hooks/slots.py": "print(1)\n"}
|
|
base = {"schema": 1, "id": "p", "name": "P"}
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = validate_manifest(_write(pathlib.Path(td) / "a", {**base, "harnessHooks": [
|
|
{"id": "start", "event": "SubagentStart", "script": "hooks/slots.py"},
|
|
{"id": "stop", "event": "SubagentStop", "script": "hooks/slots.py"}]}, files))
|
|
self.assertEqual([h["event"] for h in mf["harnessHooks"]], ["SubagentStart", "SubagentStop"])
|
|
with self.assertRaises(ManifestError):
|
|
validate_manifest(_write(pathlib.Path(td) / "b", {**base, "harnessHooks": [
|
|
{"id": "x", "event": "SubagentStart", "commandRegex": "a", "message": "m"}]}, files))
|
|
|
|
def test_the_sidecar_hands_the_limit_to_the_run(self):
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "sidecar"))
|
|
import launch
|
|
self.assertEqual(launch._limit_env({"A": "1"}), {"A": "1"})
|
|
with launch.agent_limit(6):
|
|
env = launch._limit_env({"A": "1", "CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS": "2"})
|
|
self.assertEqual(env["AIA_AGENT_LIMIT"], "6")
|
|
self.assertEqual(env["AIA_RUN_PIDS_DIR"], str(launch.LOG_DIR))
|
|
self.assertEqual(env["CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS"], "2") # the machine's own stays
|
|
self.assertEqual(env["CLAUDE_CODE_WORKFLOW_MAX_CONCURRENT_AGENTS"], "5")
|
|
for bad in (None, 0, -3, "x", True):
|
|
with launch.agent_limit(bad):
|
|
self.assertNotIn("AIA_AGENT_LIMIT", launch._limit_env({}))
|
|
self.assertNotIn("AIA_AGENT_LIMIT", launch._limit_env({}))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|