Files
ai-agent/backend/runs/genprogress.py

131 lines
5.1 KiB
Python

"""
Live generation progress of local-model runs, relayed from the runners.
A run on the EVOX2's llm-server streams for minutes with nothing in its
transcript (a step lands once its stream ends — at ~17 tok/s, ten minutes for
one big ``write``). The sidecar reads the server's slot for each live local run
(provider-evox2's ``sidecar/gen_progress.py``) and hands the reading over with the run on
``/sessions``; the exit watcher (``runs/sidecar_client.py``) feeds those here
every tick. This module:
* keeps the latest reading per session (``snapshot()`` → ``/api/gen-progress``);
* publishes a ``gen-progress`` event with the whole map whenever it moved, so
the viewer's strip and card pills follow the decode live;
* pushes the owner once when a run is really stalled — no server activity and
no transcript growth for ``GEN_STALL_PUSH_S`` (a run waiting on a tool, an
``ask-form wait`` say, is busy, not stalled; the sidecar keeps ``idleSince``
None then). The claim lives in a small locked file, so the deploy cutover's
two backends don't push twice.
"""
from __future__ import annotations
import os
import pathlib
import threading
import time
from accounts.health import _locked_json
STALL_PUSH_S = float(os.environ.get("GEN_STALL_PUSH_S", "1200")) # 0 = off
# How often the exit watcher reads the runners while a local run is live (its
# 2 s otherwise): the sidecar reads llm-server every second, and the readings
# have to reach the viewer about as fast as the transcript's rows do.
RELAY_S = float(os.environ.get("GEN_RELAY_S", "1"))
STATE_PATH = pathlib.Path(os.environ.get("GEN_PROGRESS_STATE_PATH", "/data/gen-progress.json"))
# The reading's fields the viewer shows (the sidecar's bookkeeping stays home).
FIELDS = ("phase", "model", "since", "promptTokens", "promptCached", "promptDone",
"decoded", "cap", "tokPerS", "tool", "toolRunning", "idleSince", "at", "trail")
_lock = threading.Lock()
_by_runner: dict[str | None, dict[str, dict]] = {}
_last_sent: dict[str, dict] | None = None
def snapshot() -> dict[str, dict]:
with _lock:
out: dict[str, dict] = {}
for m in _by_runner.values():
out.update(m)
return out
def _view(p: dict) -> dict:
return {k: p[k] for k in FIELDS if p.get(k) is not None}
def _unclocked(p: dict) -> dict:
"""A reading without its clocks — its own ``at`` and its trail's."""
out = {k: v for k, v in p.items() if k not in ("at", "trail")}
out["trail"] = [{k: v for k, v in t.items() if k != "at"}
for t in p.get("trail") or [] if isinstance(t, dict)]
return out
def _moved(a: dict[str, dict] | None, b: dict[str, dict]) -> bool:
"""Whether anything but the readings' clocks changed (a waiting run's trail
re-stamps every poll; one that caught a short step in between did move)."""
if a is None or a.keys() != b.keys():
return True
return any(_unclocked(a[s]) != _unclocked(b[s]) for s in b)
def update(deps, runner: str | None, sessions: list[dict]) -> None:
"""One runner's live sessions as ``/sessions`` listed them."""
global _last_sent
cur = {s["sessionId"]: _view(s["progress"]) for s in sessions
if s.get("sessionId") and isinstance(s.get("progress"), dict)}
with _lock:
if cur:
_by_runner[runner] = cur
else:
_by_runner.pop(runner, None)
snap = snapshot()
with _lock:
moved = _moved(_last_sent, snap)
if moved:
_last_sent = snap
if moved:
deps.hub.publish({"type": "gen-progress", "progress": snap})
if STALL_PUSH_S > 0:
_stall_pushes(deps, snap)
def _stall_pushes(deps, cur: dict[str, dict], now: float | None = None) -> None:
now = time.time() if now is None else now
due = {sid: p for sid, p in cur.items()
if p.get("idleSince") and now - p["idleSince"] >= STALL_PUSH_S}
if not due:
return
pending = []
with _locked_json(STATE_PATH) as state:
for sid, p in due.items():
key = str(int(p["idleSince"]))
if state.get(sid) == key:
continue
state[sid] = key
pending.append((sid, p))
# Forget runs that are gone, so the file stays a handful of lines.
for sid in [s for s in state if s not in cur]:
state.pop(sid, None)
for sid, p in pending:
_push(deps, sid, p, now)
def stall_message(p: dict, now: float) -> str:
mins = int((now - p["idleSince"]) // 60)
where = {"unreachable": "llm-server doesn't answer",
"idle": "llm-server is idle"}.get(p.get("phase") or "", "the server shows no work")
return (f"No progress for {mins} min on {p.get('model') or 'the local model'}: "
f"{where} and nothing new in the transcript. Interrupt it and resend, "
"or check the EVOX2.")
def _push(deps, sid: str, p: dict, now: float) -> None:
from notifications.service import _create_notify
try:
_create_notify(deps, {"title": "⚠️ Local run stalled", "type": "warn",
"message": stall_message(p, now), "sessionId": sid})
except Exception:
pass