Settings → Models opens on the presets (where each lands right now) and on who uses which; /settings/models/presets/<id> edits a ladder. The composer's model picker lists presets above the models and sends preset:<id>; a conversation sent on one shows its route (header pill, Details Routing card) and the step-down divider. Cards carry meta.queued / route; the reply box offers a conversation its own harness's entry of a shared model. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
442 lines
17 KiB
Python
442 lines
17 KiB
Python
"""Starts waiting for a slot: the hub's queue behind each machine's agent
|
|
limit (``plugins/run_limits.py`` — the ``runs.limits`` provider, the
|
|
``agent-limits`` plugin).
|
|
|
|
**The budget.** One per runner (a worker's id, ``local`` = the lab): every
|
|
live hub-launched run counts 1, and so does each native subagent its
|
|
transcript shows in flight (``runningAgents``). A launch — a new
|
|
conversation, or a turn that restarts a session with no live process — that
|
|
would go over waits here instead (:func:`gate`), first in, first out, and
|
|
starts when the machine is back under its limit (:func:`pump`: on a run's
|
|
exit, on a limits change, and every :data:`TICK_S`; a machine that went
|
|
offline keeps its queue until it is back). A follow-up into a live
|
|
run never waits (it starts no process); a fork isn't gated (it counts once
|
|
it runs).
|
|
|
|
**What is kept.** The send's own arguments (``runs/service._send_message``),
|
|
so the start replays the whole send path — routing pinned to the runner it
|
|
was queued for, account, scope, attachments — with the session id already
|
|
handed to the caller. The file is :data:`core.config.RUN_QUEUE_PATH`, so a
|
|
hub restart keeps the queue. A start that fails stays listed with its error
|
|
(*Retry* / *Cancel*) and no longer holds the line.
|
|
|
|
**Quota holds.** A second reason to wait, beside the agent limit: a start
|
|
sent on a preset whose every route is full and whose ladder says *wait*
|
|
(``models/ladders.py``) is kept here too (:func:`hold`) until its earliest
|
|
reset, then replayed — the send resolves the ladder again. A held item never
|
|
stands in a machine's line (it has no position) and takes no slot.
|
|
|
|
``GET /api/runs/queue``, ``POST …/{sid}/start`` (start now, over the limit)
|
|
and ``DELETE …/{sid}`` are in ``runs/routes.py``; SSE ``{"type":
|
|
"run-queue"}`` says the queue moved.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import json
|
|
import logging
|
|
import os
|
|
import pathlib
|
|
import threading
|
|
import time
|
|
from typing import Any
|
|
|
|
from fastapi import HTTPException
|
|
|
|
from core import liveruns
|
|
from core.config import RUN_QUEUE_PATH
|
|
from plugins import run_limits
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
LOCAL = "local"
|
|
TICK_S = 5.0
|
|
# A launch the gate let through counts until its runner's next polls list it.
|
|
STARTING_S = 20.0
|
|
PREVIEW = 300
|
|
|
|
_lock = threading.RLock()
|
|
_items: list[dict[str, Any]] | None = None
|
|
_starting: dict[str, dict[str, float]] = {} # runner → {sid: monotonic}
|
|
_wake = threading.Event()
|
|
_pump_lock = threading.Lock()
|
|
|
|
|
|
# ── the file ─────────────────────────────────────────────────────────────────
|
|
def _path() -> pathlib.Path:
|
|
return pathlib.Path(os.environ.get("RUN_QUEUE_PATH") or RUN_QUEUE_PATH)
|
|
|
|
|
|
def _load() -> list[dict[str, Any]]:
|
|
global _items
|
|
if _items is None:
|
|
try:
|
|
raw = json.loads(_path().read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
raw = []
|
|
_items = [i for i in raw if isinstance(i, dict) and i.get("sessionId")
|
|
and isinstance(i.get("kwargs"), dict)] if isinstance(raw, list) else []
|
|
return _items
|
|
|
|
|
|
def _save() -> None:
|
|
p = _path()
|
|
try:
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = p.with_suffix(".tmp")
|
|
tmp.write_text(json.dumps(_items or []), encoding="utf-8")
|
|
os.replace(tmp, p)
|
|
except OSError as e:
|
|
log.warning("run queue not saved: %s", e)
|
|
|
|
|
|
def reset() -> None:
|
|
"""Forget everything in memory (tests)."""
|
|
global _items
|
|
with _lock:
|
|
_items = None
|
|
_starting.clear()
|
|
|
|
|
|
def _now() -> str:
|
|
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
def _publish(deps) -> None:
|
|
try:
|
|
deps.hub.publish({"type": "run-queue"})
|
|
except Exception: # noqa: BLE001 — no hub (tests)
|
|
pass
|
|
|
|
|
|
# ── the budget ───────────────────────────────────────────────────────────────
|
|
def _subagents(deps, sids) -> int:
|
|
"""Native subagents in flight under ``sids``, per their transcripts."""
|
|
n = 0
|
|
try:
|
|
from conversations import ids
|
|
from conversations.catalog import _session_conv_map
|
|
convs = _session_conv_map(deps)
|
|
for sid in sids:
|
|
conv = convs.get(sid)
|
|
summ = deps.store.get_summary(ids.path_of(conv)) if conv else None
|
|
n += len((summ or {}).get("runningAgents") or [])
|
|
except Exception: # noqa: BLE001 — an unreadable transcript counts nothing
|
|
log.debug("subagent count failed", exc_info=True)
|
|
return n
|
|
|
|
|
|
def usage(deps, runner: str | None) -> dict[str, int]:
|
|
"""``{conversations, subagents, total}`` on ``runner`` (None / ``local`` =
|
|
the lab) right now."""
|
|
rid = runner or LOCAL
|
|
live = set(liveruns.on(None if rid == LOCAL else rid))
|
|
now = time.monotonic()
|
|
with _lock:
|
|
st = _starting.get(rid) or {}
|
|
for sid in [s for s, at in st.items() if now - at > STARTING_S or s in live]:
|
|
st.pop(sid, None)
|
|
convs = len(live) + len(st)
|
|
subs = _subagents(deps, live)
|
|
return {"conversations": convs, "subagents": subs, "total": convs + subs}
|
|
|
|
|
|
def _reserve(rid: str, sid: str) -> None:
|
|
with _lock:
|
|
_starting.setdefault(rid, {})[sid] = time.monotonic()
|
|
|
|
|
|
def _release(rid: str, sid: str) -> None:
|
|
with _lock:
|
|
(_starting.get(rid) or {}).pop(sid, None)
|
|
|
|
|
|
# ── the gate ─────────────────────────────────────────────────────────────────
|
|
def _waiting(rid: str) -> list[dict[str, Any]]:
|
|
return [i for i in _load() if i.get("runner") == rid and not i.get("error")
|
|
and not i.get("hold")]
|
|
|
|
|
|
def hold(deps, sid: str, runner: str | None, kind: str, kwargs: dict[str, Any], *,
|
|
until: float, why: str = "", run_as: str | None = None,
|
|
title: str | None = None) -> dict[str, Any] | None:
|
|
"""Keep a start until ``until`` (an epoch): a preset waiting for its
|
|
first route to reset. Returns what to hand back to the caller
|
|
(``{worker, position: 0, limit: 0, running: 0, reason: "quota", until,
|
|
why}``), or None when it can't be kept (the caller then launches)."""
|
|
try:
|
|
kw = json.loads(json.dumps(kwargs))
|
|
except (TypeError, ValueError):
|
|
return None
|
|
rid = runner or LOCAL
|
|
iso = datetime.datetime.fromtimestamp(float(until), datetime.timezone.utc) \
|
|
.strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
with _lock:
|
|
items = _load()
|
|
items[:] = [i for i in items if i["sessionId"] != sid]
|
|
items.append({"sessionId": sid, "runner": rid, "kind": kind, "at": _now(),
|
|
"runAs": run_as, "title": title,
|
|
"prompt": str(kw.get("prompt") or "")[:PREVIEW], "kwargs": kw,
|
|
"hold": {"until": float(until), "why": str(why)[:200]}})
|
|
_save()
|
|
_publish(deps)
|
|
return {"worker": rid, "position": 0, "limit": 0, "running": 0,
|
|
"reason": "quota", "until": iso, "why": str(why)[:200]}
|
|
|
|
|
|
def gate(deps, sid: str, runner: str | None, kind: str, kwargs: dict[str, Any],
|
|
*, run_as: str | None = None, title: str | None = None) -> dict[str, Any] | None:
|
|
"""None: launch now (the slot is taken). Else the start was queued —
|
|
``{worker, position, limit, running}`` to hand back to the caller.
|
|
|
|
Never raises: with no limit on ``runner``, or on any trouble here, the
|
|
launch goes ahead."""
|
|
try:
|
|
rid = runner or LOCAL
|
|
limit = run_limits.limit_for(deps, runner)
|
|
if not limit:
|
|
return None
|
|
try:
|
|
kw = json.loads(json.dumps(kwargs))
|
|
except (TypeError, ValueError):
|
|
return None # can't be kept: don't hold it
|
|
with _lock:
|
|
ahead = _waiting(rid)
|
|
same = next((i for i in _load() if i["sessionId"] == sid), None)
|
|
if same is not None:
|
|
# One more turn into a conversation already waiting: one start,
|
|
# both messages.
|
|
old, new = str(same["kwargs"].get("prompt") or ""), str(kw.get("prompt") or "")
|
|
if new.strip() and new.strip() not in old: # a re-send adds nothing
|
|
same["kwargs"]["prompt"] = f"{old}\n\n{new}".strip()
|
|
same["prompt"] = same["kwargs"]["prompt"][:PREVIEW]
|
|
same.pop("error", None)
|
|
_save()
|
|
pos = 1 + [i["sessionId"] for i in _waiting(rid)].index(sid)
|
|
use = usage(deps, runner)
|
|
_publish(deps)
|
|
return {"worker": rid, "position": pos, "limit": limit, "running": use["total"]}
|
|
use = usage(deps, runner)
|
|
if not ahead and use["total"] < limit:
|
|
_reserve(rid, sid)
|
|
return None
|
|
_load().append({"sessionId": sid, "runner": rid, "kind": kind, "at": _now(),
|
|
"runAs": run_as, "title": title,
|
|
"prompt": str(kw.get("prompt") or "")[:PREVIEW], "kwargs": kw})
|
|
_save()
|
|
pos = len(ahead) + 1
|
|
_publish(deps)
|
|
return {"worker": rid, "position": pos, "limit": limit, "running": use["total"]}
|
|
except Exception: # noqa: BLE001 — the queue never breaks a send
|
|
log.exception("run gate failed for %s — launching", sid)
|
|
return None
|
|
|
|
|
|
# ── reading it ───────────────────────────────────────────────────────────────
|
|
def _public(item: dict[str, Any], position: int | None) -> dict[str, Any]:
|
|
kw = item.get("kwargs") or {}
|
|
return {"sessionId": item["sessionId"], "worker": item.get("runner"),
|
|
"kind": item.get("kind") or "new", "at": item.get("at"),
|
|
"runAs": item.get("runAs"), "title": item.get("title"),
|
|
"prompt": item.get("prompt") or "", "model": kw.get("model"),
|
|
"harness": kw.get("harness") or "claude",
|
|
"projects": kw.get("projects") or [],
|
|
"position": position, "error": item.get("error"),
|
|
**_hold_public(item)}
|
|
|
|
|
|
def _hold_public(item: dict[str, Any]) -> dict[str, Any]:
|
|
h = item.get("hold")
|
|
if not h:
|
|
return {}
|
|
iso = datetime.datetime.fromtimestamp(float(h.get("until") or 0), datetime.timezone.utc) \
|
|
.strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
return {"reason": "quota", "until": iso, "why": h.get("why") or ""}
|
|
|
|
|
|
def listing(deps, run_as: str | None = None, *, everyone: bool = True) -> list[dict[str, Any]]:
|
|
"""The queue, oldest first — everyone's, or only ``run_as``'s."""
|
|
out = []
|
|
with _lock:
|
|
pos: dict[str, int] = {}
|
|
for i in _load():
|
|
p = None
|
|
if not i.get("error") and not i.get("hold"):
|
|
p = pos[i["runner"]] = pos.get(i["runner"], 0) + 1
|
|
if everyone or i.get("runAs") == run_as:
|
|
out.append(_public(i, p))
|
|
return out
|
|
|
|
|
|
def count(runner: str | None = None, *, waiting: bool = False) -> int:
|
|
"""How many are listed (``waiting``: for a slot — without the ones whose
|
|
start failed and the quota holds)."""
|
|
with _lock:
|
|
return sum(1 for i in _load() if (runner is None or i.get("runner") == runner)
|
|
and not (waiting and (i.get("error") or i.get("hold"))))
|
|
|
|
|
|
def _take(sid: str) -> dict[str, Any] | None:
|
|
with _lock:
|
|
items = _load()
|
|
hit = next((i for i in items if i["sessionId"] == sid), None)
|
|
if hit is not None:
|
|
items.remove(hit)
|
|
_save()
|
|
return hit
|
|
|
|
|
|
def _owned(item: dict[str, Any] | None, run_as: str | None, everyone: bool) -> bool:
|
|
return item is not None and (everyone or item.get("runAs") == run_as)
|
|
|
|
|
|
# ── starting ─────────────────────────────────────────────────────────────────
|
|
def _start(deps, item: dict[str, Any], *, nowait: bool = False) -> dict[str, Any]:
|
|
"""Replay the queued send. On a refusal the item goes back, marked with
|
|
the error, and the HTTPException is raised. A quota hold's replay
|
|
resolves its preset again and may be held once more (``nowait`` — *Start
|
|
now* — runs it whatever the quota says)."""
|
|
from runs.service import _send_message
|
|
sid, rid = item["sessionId"], item["runner"]
|
|
kw = dict(item["kwargs"])
|
|
prompt = kw.pop("prompt", "")
|
|
_reserve(rid, sid)
|
|
try:
|
|
out = _send_message(deps, prompt, **kw, _admitted=True, _nowait=nowait,
|
|
**({"_sid": sid} if item.get("kind") != "resume" else {}))
|
|
except Exception as e: # noqa: BLE001
|
|
_release(rid, sid)
|
|
d = getattr(e, "detail", None)
|
|
msg = (d.get("message") if isinstance(d, dict) else d) or str(e) or "launch failed"
|
|
with _lock:
|
|
_load().append({**item, "error": str(msg)[:500], "failedAt": _now()})
|
|
_save()
|
|
_publish(deps)
|
|
raise
|
|
if out.get("queued"):
|
|
_release(rid, sid)
|
|
return out # every route still full: held again, until the next reset
|
|
deps.meta_store.update(sid, {"queued": False})
|
|
try:
|
|
deps.hub.publish({"type": "meta", "id": sid})
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
_publish(deps)
|
|
return out
|
|
|
|
|
|
def start_now(deps, sid: str, run_as: str | None = None, *, everyone: bool = True) -> dict:
|
|
"""Start a queued run at once, over its machine's limit (also the retry
|
|
of one that failed)."""
|
|
with _lock:
|
|
hit = next((i for i in _load() if i["sessionId"] == sid), None)
|
|
if not _owned(hit, run_as, everyone):
|
|
raise HTTPException(404, {"message": "not in the queue", "kind": "not_queued"})
|
|
item = _take(sid)
|
|
item.pop("error", None)
|
|
item.pop("failedAt", None)
|
|
return _start(deps, item, nowait=True)
|
|
|
|
|
|
def cancel(deps, sid: str, run_as: str | None = None, *, everyone: bool = True) -> dict:
|
|
with _lock:
|
|
hit = next((i for i in _load() if i["sessionId"] == sid), None)
|
|
if not _owned(hit, run_as, everyone):
|
|
raise HTTPException(404, {"message": "not in the queue", "kind": "not_queued"})
|
|
item = _take(sid)
|
|
# A conversation that never started ends here; a waiting turn just goes.
|
|
patch: dict[str, Any] = {"queued": False}
|
|
if item.get("kind") != "resume":
|
|
patch["state"] = "interrupted"
|
|
deps.meta_store.update(sid, patch)
|
|
try:
|
|
deps.hub.publish({"type": "meta", "id": sid})
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
_publish(deps)
|
|
return {"ok": True, "sessionId": sid}
|
|
|
|
|
|
def pump(deps) -> int:
|
|
"""Start what now fits, each runner's oldest first. Returns how many
|
|
started. One pump at a time; a start that fails is marked and skipped."""
|
|
started = 0
|
|
if not _pump_lock.acquire(blocking=False):
|
|
return 0
|
|
try:
|
|
started += _pump_holds(deps)
|
|
with _lock:
|
|
runners = list(dict.fromkeys(i["runner"] for i in _load()
|
|
if not i.get("error") and not i.get("hold")))
|
|
for rid in runners:
|
|
while True:
|
|
runner = None if rid == LOCAL else rid
|
|
if runner and not _online(deps, runner):
|
|
break # asleep or off the network: its queue waits for it
|
|
limit = run_limits.limit_for(deps, runner)
|
|
with _lock:
|
|
head = next(iter(_waiting(rid)), None)
|
|
if head is None:
|
|
break
|
|
if limit and usage(deps, runner)["total"] >= limit:
|
|
break
|
|
item = _take(head["sessionId"])
|
|
if item is None:
|
|
break
|
|
try:
|
|
_start(deps, item)
|
|
started += 1
|
|
except Exception as e: # noqa: BLE001 — listed with its error
|
|
log.warning("queued run %s didn't start: %s", item["sessionId"],
|
|
getattr(e, "detail", e))
|
|
finally:
|
|
_pump_lock.release()
|
|
return started
|
|
|
|
|
|
def _pump_holds(deps) -> int:
|
|
"""Replay the quota holds whose reset has passed."""
|
|
now = time.time()
|
|
with _lock:
|
|
due = [i["sessionId"] for i in _load() if i.get("hold") and not i.get("error")
|
|
and float(i["hold"].get("until") or 0) <= now]
|
|
n = 0
|
|
for sid in due:
|
|
item = _take(sid)
|
|
if item is None:
|
|
continue
|
|
try:
|
|
out = _start(deps, item)
|
|
n += 0 if out.get("queued") else 1
|
|
except Exception as e: # noqa: BLE001 — listed with its error
|
|
log.warning("held run %s didn't start: %s", sid, getattr(e, "detail", e))
|
|
return n
|
|
|
|
|
|
def _online(deps, runner: str) -> bool:
|
|
try:
|
|
return bool(deps.worker_store.online(runner))
|
|
except Exception: # noqa: BLE001 — unknown reads as up: the start says why not
|
|
return True
|
|
|
|
|
|
def wake() -> None:
|
|
"""Something that may free a slot happened (a run ended, limits moved)."""
|
|
_wake.set()
|
|
|
|
|
|
def _loop(deps) -> None:
|
|
while True:
|
|
_wake.wait(TICK_S)
|
|
_wake.clear()
|
|
try:
|
|
if count():
|
|
pump(deps)
|
|
except Exception: # noqa: BLE001
|
|
log.exception("run queue pump failed")
|
|
|
|
|
|
def start(deps) -> None:
|
|
threading.Thread(target=_loop, args=(deps,), daemon=True, name="run-queue").start()
|