Files
gabrielvidalandClaude Opus 5.5 855e0d14a6 feat(storage): Storage dashboard, the conversation's On disk chip + card, a call's disk delta on its Bash row
/dashboards/storage: each runner's filesystems with the sessions' share
(/tmp is RAM on the lab), totals per kind, every scratchpad/worktree/
transcript with its conversation, git state and a stale/holds-work/in-use
verdict, Remove (re-checked by claude-probe, forced only on confirm),
Clean up stale, Measure now, and the runner's auto-clean + agent-nudge
switches. Header chip (what a conversation still keeps), drawer card,
'+1.9 GB' on the Bash strip. A push when a RAM filesystem passes 85 %
(once per crossing). Mock backend + tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 10:09:28 +01:00

201 lines
8.7 KiB
Python

"""The Performance dashboard's clock: poll every runner's ``/procs``, keep the
latest snapshot per machine in memory (the live view), record it
(``store.py``), roll the samples up each minute, prune each hour, and stop
the leftovers that outstayed ``autoKillHours`` (``settings.py``).
The lab sidecar is polled every ``LAB_POLL_S``; a paired worker every
``WORKER_POLL_S`` while it is online (psutil on a Mac is slower than /proc).
A worker whose sidecar predates ``/procs`` answers 404 — it shows as
*needs an update* until it auto-updates to the hub's commit."""
from __future__ import annotations
import os
import threading
import time
from fastapi import HTTPException
from core.config import SIDECAR_TOKEN, SIDECAR_URL
from . import calls
from .settings import kept_by_label
LAB = "lab"
LAB_POLL_S = float(os.environ.get("PERF_POLL_S", "5"))
WORKER_POLL_S = float(os.environ.get("PERF_WORKER_POLL_S", "15"))
AUTOKILL_EVERY_S = 300
class PerfPoller:
def __init__(self, deps):
self.deps = deps
self._lock = threading.Lock()
self._live: dict[str, dict] = {} # runner → {at, snap, error, unsupported}
self._next: dict[str, float] = {}
# ---- the live view ----------------------------------------------------------
def live(self) -> dict[str, dict]:
with self._lock:
return dict(self._live)
def _set(self, runner: str, **st) -> None:
with self._lock:
cur = self._live.setdefault(runner, {})
cur.update(st)
# ---- polling ----------------------------------------------------------------
def _runners(self) -> list[tuple[str, str, str, float]]:
out = [(LAB, SIDECAR_URL, SIDECAR_TOKEN, LAB_POLL_S)] if SIDECAR_URL else []
ws = self.deps.worker_store
out += [(w["id"], w["url"], w["token"], WORKER_POLL_S) for w in ws.list()
if w.get("url") and w.get("token") and ws.online(w["id"])]
return out
def poll_once(self, now: float | None = None) -> None:
from workers.store import sidecar_request
now = now or time.time()
for runner, url, token, every in self._runners():
if self._next.get(runner, 0) > now:
continue
self._next[runner] = now + every
try:
snap = sidecar_request(url, token, "/procs", None, method="GET", timeout=10,
label="sidecar" if runner == LAB else "worker")
except HTTPException as e:
self._set(runner, error=str(e.detail), unsupported=e.status_code == 404)
continue
except Exception as e: # noqa: BLE001 — a poll never kills the thread
self._set(runner, error=str(e))
continue
self._set(runner, at=now, snap=snap, error=None, unsupported=False)
try:
self.deps.perf_store.record(runner, snap)
except Exception as e: # noqa: BLE001
print(f"[perf] record {runner}: {e}", flush=True)
self._pull_calls(runner, url, token)
def _pull_calls(self, runner: str, url: str, token: str) -> None:
"""The runner's call-probe records (``/callmeta``, calls.py) — a
sidecar that predates it answers 404 and is asked again next poll."""
from workers.store import sidecar_request
def fetch(after: int) -> dict:
return sidecar_request(url, token, f"/callmeta?after={after}&limit={calls.PAGE}",
None, method="GET", timeout=10,
label="sidecar" if runner == LAB else "worker")
try:
calls.pull(self.deps.perf_store, runner, fetch)
self._set(runner, callsError=None, callsUnsupported=False)
except HTTPException as e:
self._set(runner, callsError=str(e.detail), callsUnsupported=e.status_code == 404)
except Exception as e: # noqa: BLE001 — never stops the /procs poll
self._set(runner, callsError=str(e))
print(f"[perf] calls {runner}: {e}", flush=True)
def run(self) -> None:
last_roll = last_prune = last_kill = 0.0
while True:
t = time.time()
self.poll_once(t)
try:
if t - last_roll >= 60:
self.deps.perf_store.rollup(t)
last_roll = t
if t - last_prune >= 3600:
self.deps.perf_store.prune(t)
last_prune = t
if t - last_kill >= AUTOKILL_EVERY_S:
self.auto_kill(t)
self.storage_alerts(t)
last_kill = t
except Exception as e: # noqa: BLE001
print(f"[perf] housekeeping: {e}", flush=True)
time.sleep(max(0.5, min(LAB_POLL_S, WORKER_POLL_S) - (time.time() - t)))
def start(self) -> None:
threading.Thread(target=self.run, name="perf-poller", daemon=True).start()
# ---- leftovers --------------------------------------------------------------
def kill(self, runner: str, session_id: str, processes: list[dict] | None,
reason: str = "manual") -> dict:
"""Ask the machine to stop a conversation's leftovers (it re-checks they
still are), and book what it killed."""
from workers.store import sidecar_request
url, token = self._endpoint(runner)
out = sidecar_request(url, token, "/procs/kill",
{"sessionId": session_id, "processes": processes},
timeout=20, label="sidecar" if runner == LAB else "worker")
killed = set(out.get("killed") or [])
snap = (self.live().get(runner) or {}).get("snap") or {}
group = next((g for g in snap.get("leftovers") or []
if g["sessionId"] == session_id), {"processes": []})
self.deps.perf_store.mark_killed(
runner, [(r["pid"], round(r["startedAt"])) for r in group["processes"]
if r["pid"] in killed], reason)
with self._lock:
self._next[runner] = 0 # refresh the live view next tick
return out
def storage_alerts(self, now: float | None = None) -> list[dict]:
"""Push once when a runner's RAM filesystem (/tmp) passes 85 % full
(perf/storage.py; re-armed under 80 %)."""
from . import storage # noqa: PLC0415
from .views import machines # noqa: PLC0415
fresh = storage.due_alerts(self.deps.perf_store, now)
if not fresh:
return []
from notifications.service import _create_notify # noqa: PLC0415
names = machines(self.deps)
for a in fresh:
name = (names.get(a["runner"]) or {}).get("name") or a["runner"]
try:
_create_notify(self.deps, storage.alert_push(a, name))
except Exception as e: # noqa: BLE001
print(f"[perf] storage alert: {e}", flush=True)
return fresh
def refresh(self, runner: str) -> None:
"""Poll this runner (its /procs and /callmeta) on the next tick."""
with self._lock:
self._next[runner] = 0
def _endpoint(self, runner: str) -> tuple[str, str]:
if runner == LAB:
return SIDECAR_URL, SIDECAR_TOKEN
w = self.deps.worker_store.get(runner)
if not w:
raise HTTPException(404, f"unknown runner {runner!r}")
return w["url"], w["token"]
def auto_kill(self, now: float | None = None) -> list[dict]:
"""Stop every leftover past ``autoKillHours`` that isn't kept."""
cfg = self.deps.perf_settings.get()
if not cfg["autoKill"]:
return []
now = now or time.time()
limit = cfg["autoKillHours"] * 3600
done = []
for runner, st in self.live().items():
snap = st.get("snap") or {}
for g in snap.get("leftovers") or []:
state = self.deps.perf_store.proc_state(runner, g["processes"])
due = []
for r in g["processes"]:
since, kept, _ = state.get((r["pid"], round(r["startedAt"])), (None, 0, None))
if kept or kept_by_label(r.get("label") or "", cfg["keepLabels"]):
continue
if since is not None and now - since >= limit:
due.append({"pid": r["pid"], "startedAt": r["startedAt"]})
if not due:
continue
try:
out = self.kill(runner, g["sessionId"], due, reason="auto")
done.append({"runner": runner, "sessionId": g["sessionId"], **out})
except Exception as e: # noqa: BLE001
print(f"[perf] auto-kill {runner}/{g['sessionId']}: {e}", flush=True)
return done