Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # backend/perf/views.py
331 lines
16 KiB
Python
331 lines
16 KiB
Python
"""What the Performance dashboard reads: the live view (the poller's latest
|
|
snapshots, with titles), the history (stacked per conversation), the
|
|
per-conversation table, the heaviest commands, one conversation's numbers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import time
|
|
from collections.abc import Collection
|
|
|
|
from .poller import LAB
|
|
from .scope import Scope
|
|
from .settings import kept_by_label
|
|
|
|
RANGES = { # key → (seconds, bucket step, table)
|
|
"1h": (3600, 10, "perf_samples"),
|
|
"6h": (6 * 3600, 60, "perf_minutes"),
|
|
"24h": (86400, 300, "perf_minutes"),
|
|
"7d": (7 * 86400, 1800, "perf_minutes"),
|
|
"30d": (30 * 86400, 7200, "perf_minutes"),
|
|
}
|
|
TOTALS_RANGES = {**{k: v[0] for k, v in RANGES.items()}, "all": None}
|
|
TOP_SERIES = 8
|
|
|
|
_titles_cache: tuple[tuple, dict] | None = None
|
|
|
|
|
|
def titles(deps) -> dict[str, dict]:
|
|
"""sessionId → {conversationId, title, endedAt}, newest transcript wins
|
|
(subagents left out); memoized on the summaries + meta versions."""
|
|
global _titles_cache
|
|
from conversations.cards import _conv_title
|
|
from conversations.tree import _conv_id, _is_sidechain_path
|
|
key = (deps.store.summaries_version, deps.meta_store.version)
|
|
if _titles_cache and _titles_cache[0] == key:
|
|
return _titles_cache[1]
|
|
best: dict[str, tuple] = {}
|
|
for path, s in deps.store.all_summaries():
|
|
sid = s.get("sessionId")
|
|
if not sid or s.get("isSidechain") or _is_sidechain_path(path):
|
|
continue
|
|
if sid not in best or (s.get("endedAt") or "") > (best[sid][1].get("endedAt") or ""):
|
|
best[sid] = (path, s)
|
|
out = {sid: {"conversationId": _conv_id(p), "title": _conv_title(deps, s),
|
|
"endedAt": s.get("endedAt")} for sid, (p, s) in best.items()}
|
|
_titles_cache = (key, out)
|
|
return out
|
|
|
|
|
|
def _conv(deps, sid: str) -> dict:
|
|
t = titles(deps).get(sid) or {}
|
|
return {"conversationId": t.get("conversationId"), "title": t.get("title")}
|
|
|
|
|
|
def machines(deps) -> dict[str, dict]:
|
|
out = {LAB: {"id": LAB, "name": "Homelab", "platform": "linux"}}
|
|
for w in deps.worker_store.list():
|
|
out[w["id"]] = {"id": w["id"], "name": w.get("name") or w["id"],
|
|
"platform": w.get("platform")}
|
|
return out
|
|
|
|
|
|
# ---- live ---------------------------------------------------------------------
|
|
|
|
def live(deps, scope: Scope | None = None) -> dict:
|
|
"""``scope``: the profile switch — the machines it shows, and on each
|
|
only the runs (and leftovers) of its conversations; a machine's
|
|
``agents`` add up those runs, its ``host`` stays the whole box."""
|
|
scope = scope or Scope(deps)
|
|
cfg = deps.perf_settings.get()
|
|
now = time.time()
|
|
known = machines(deps)
|
|
state = deps.perf_poller.live()
|
|
ws = deps.worker_store
|
|
out_m, out_s, out_l = [], [], []
|
|
for mid, m in known.items():
|
|
st = state.get(mid) or {}
|
|
snap = st.get("snap") or {}
|
|
online = mid == LAB or ws.online(mid)
|
|
fresh = bool(snap) and now - (st.get("at") or 0) < 60
|
|
sessions = [s for s in (snap.get("sessions") or []) if scope.conv(mid, s["sessionId"])] \
|
|
if fresh else []
|
|
left = [g for g in (snap.get("leftovers") or []) if scope.conv(mid, g["sessionId"])] \
|
|
if fresh else []
|
|
if not (scope.machine(mid) or sessions or left):
|
|
continue
|
|
out_m.append({**m, "online": online, "at": st.get("at"), "owner": scope.guest(mid, None),
|
|
"error": st.get("error"), "unsupported": bool(st.get("unsupported")),
|
|
"host": snap.get("host") if fresh else None,
|
|
"scanMs": snap.get("scanMs"),
|
|
"agents": {"count": len(sessions),
|
|
"cpu": sum(s.get("cpu") or 0 for s in sessions),
|
|
"rss": sum(s.get("rss") or 0 for s in sessions),
|
|
"procs": sum(s.get("procs") or 0 for s in sessions)}})
|
|
for s in sessions:
|
|
out_s.append({**s, "runner": mid, **_conv(deps, s["sessionId"]),
|
|
"guest": scope.guest(mid, s["sessionId"])})
|
|
for g in left:
|
|
out_l.append({**leftover_group(deps, mid, g, cfg), "guest": scope.guest(mid, g["sessionId"])})
|
|
out_s.sort(key=lambda s: -(s.get("rss") or 0))
|
|
out_l.sort(key=lambda g: -(g.get("rss") or 0))
|
|
return {"at": now, "machines": out_m, "sessions": out_s, "leftovers": out_l,
|
|
"settings": cfg}
|
|
|
|
|
|
def leftover_group(deps, runner: str, g: dict, cfg: dict) -> dict:
|
|
"""A leftover group as the API serves it: each process with since when it
|
|
is a leftover, whether it is kept, and when the auto-kill will stop it."""
|
|
procs = deps.perf_store.proc_state(runner, g["processes"])
|
|
rows = []
|
|
for r in g["processes"]:
|
|
since, kept, _ = procs.get((r["pid"], round(r["startedAt"])), (None, 0, None))
|
|
by_label = kept_by_label(r.get("label") or "", cfg["keepLabels"])
|
|
due = None
|
|
if cfg["autoKill"] and since and not kept and not by_label:
|
|
due = since + cfg["autoKillHours"] * 3600
|
|
rows.append({**r, "leftoverSince": since, "kept": bool(kept),
|
|
"keptByLabel": by_label, "autoKillAt": due})
|
|
t = titles(deps).get(g["sessionId"]) or {}
|
|
return {**g, "processes": rows, "runner": runner, "endedAt": t.get("endedAt"),
|
|
**_conv(deps, g["sessionId"])}
|
|
|
|
|
|
# ---- history ------------------------------------------------------------------
|
|
|
|
def history(deps, rng: str, runner: str | None = None, scope: Scope | None = None) -> dict:
|
|
"""``scope``: only its conversations' bands; without a ``runner``, only
|
|
the machines it shows (one picked by name keeps its line)."""
|
|
scope = scope or Scope(deps)
|
|
span, step, table = RANGES.get(rng, RANGES["24h"])
|
|
now = time.time()
|
|
since = (now - span) // step * step
|
|
where, args = "t >= ?", [since]
|
|
if runner:
|
|
where += " AND runner = ?"
|
|
args.append(runner)
|
|
rows = deps.perf_store.query(
|
|
f"SELECT CAST(t / {step} AS INT) * {step}, runner, sid, AVG(cpu), AVG(rss)"
|
|
f" FROM {table} WHERE {where} GROUP BY 1, runner, sid", tuple(args))
|
|
buckets = [since + i * step for i in range(int((now - since) // step) + 1)]
|
|
index = {b: i for i, b in enumerate(buckets)}
|
|
n = len(buckets)
|
|
hosts: dict[str, dict] = {}
|
|
runs: dict[tuple, dict] = {}
|
|
for b, rn, sid, cpu, rss in rows:
|
|
i = index.get(b)
|
|
if i is None:
|
|
continue
|
|
if sid == "":
|
|
if not (runner or scope.machine(rn)):
|
|
continue
|
|
h = hosts.setdefault(rn, {"cpu": [None] * n, "mem": [None] * n})
|
|
h["cpu"][i], h["mem"][i] = _r(cpu), _int(rss)
|
|
elif scope.conv(rn, sid):
|
|
s = runs.setdefault((rn, sid), {"cpu": [0.0] * n, "rss": [0] * n})
|
|
s["cpu"][i], s["rss"][i] = _r(cpu) or 0.0, _int(rss) or 0
|
|
# a window that starts before anything was recorded (a fresh install, a
|
|
# machine paired this morning) starts at its first reading instead
|
|
seen = [i for h in hosts.values() for i, v in enumerate(h["cpu"]) if v is not None]
|
|
seen += [i for s in runs.values() for i, v in enumerate(s["rss"]) if v]
|
|
lead = min(min(seen, default=0), max(0, n - 2))
|
|
if lead:
|
|
buckets, n = buckets[lead:], n - lead
|
|
for h in hosts.values():
|
|
h["cpu"], h["mem"] = h["cpu"][lead:], h["mem"][lead:]
|
|
for s in runs.values():
|
|
s["cpu"], s["rss"] = s["cpu"][lead:], s["rss"][lead:]
|
|
# the busiest by CPU and the heaviest by memory get their own band
|
|
by_cpu = sorted(runs, key=lambda k: -sum(runs[k]["cpu"]))[:TOP_SERIES]
|
|
by_rss = sorted(runs, key=lambda k: -max(runs[k]["rss"]))[:TOP_SERIES]
|
|
top = list(dict.fromkeys(by_cpu + by_rss))
|
|
other = {"cpu": [0.0] * n, "rss": [0] * n}
|
|
for k, s in runs.items():
|
|
if k not in top:
|
|
for i in range(n):
|
|
other["cpu"][i] += s["cpu"][i]
|
|
other["rss"][i] += s["rss"][i]
|
|
known = machines(deps)
|
|
last = {mid: ((st.get("snap") or {}).get("host") or {})
|
|
for mid, st in deps.perf_poller.live().items()}
|
|
return {
|
|
"range": rng, "step": step, "t": buckets,
|
|
"machines": [{**known.get(mid, {"id": mid, "name": mid}),
|
|
"memTotal": last.get(mid, {}).get("memTotal"),
|
|
"cpus": last.get(mid, {}).get("cpus"), **h}
|
|
for mid, h in hosts.items()],
|
|
"series": [{"runner": rn, "sessionId": sid, **_conv(deps, sid), **runs[(rn, sid)],
|
|
"guest": scope.guest(rn, sid)} for rn, sid in top],
|
|
"other": {"cpu": [round(x, 1) for x in other["cpu"]], "rss": other["rss"]},
|
|
}
|
|
|
|
|
|
# ---- totals -------------------------------------------------------------------
|
|
|
|
def _since(rng: str) -> float:
|
|
span = TOTALS_RANGES.get(rng, 86400)
|
|
return 0.0 if span is None else time.time() - span
|
|
|
|
|
|
def only_sessions(sids: Collection[str] | None, col: str = "sid") -> tuple[str, tuple]:
|
|
"""``(" AND <col> IN …", args)`` narrowing a read to these sessions (a
|
|
guest's Stats, dashboards/guest_perf.py) — one JSON parameter, however
|
|
many sessions; ``None`` = every session (the owner's dashboards)."""
|
|
if sids is None:
|
|
return "", ()
|
|
return f" AND {col} IN (SELECT value FROM json_each(?))", (json.dumps(sorted(sids)),)
|
|
|
|
|
|
def conversations(deps, rng: str, scope: Scope | None = None,
|
|
sids: Collection[str] | None = None) -> dict:
|
|
"""Per conversation (and runner): CPU time, peaks, its heaviest command —
|
|
``scope`` = the dashboards' profile switch, ``sids`` narrows it to those
|
|
sessions (a guest's Stats)."""
|
|
scope = scope or Scope(deps)
|
|
since = _since(rng)
|
|
only, only_args = only_sessions(sids)
|
|
rows = deps.perf_store.query(
|
|
"SELECT runner, sid, MIN(first_seen), MAX(last_seen), SUM(cpu_seconds),"
|
|
" MAX(peak_cpu), MAX(peak_rss), MAX(peak_procs), COUNT(*), MAX(harness), MAX(source)"
|
|
f" FROM perf_runs WHERE last_seen >= ?{only} GROUP BY runner, sid", (since, *only_args))
|
|
heavy: dict[str, tuple] = {}
|
|
# each conversation's heaviest part of a command line (the call probe's)
|
|
for sid, label, cpu, rss in deps.perf_store.query(
|
|
"SELECT sid, label, SUM(cpu), MAX(peak_rss) FROM perf_call_parts"
|
|
f" WHERE started >= ?{only} GROUP BY sid, label", (since, *only_args)):
|
|
if sid not in heavy or cpu > heavy[sid][1]:
|
|
heavy[sid] = (label, cpu, rss)
|
|
live = {(s["runner"], s["sessionId"]) for s in live_sessions(deps)}
|
|
out = []
|
|
for rn, sid, first, last, cpu, pcpu, prss, pprocs, n, harness, source in rows:
|
|
if not scope.conv(rn, sid):
|
|
continue
|
|
h = heavy.get(sid)
|
|
out.append({"runner": rn, "sessionId": sid, **_conv(deps, sid),
|
|
"guest": scope.guest(rn, sid), "harness": harness, "source": source, "firstSeen": first,
|
|
"lastSeen": last, "cpuSeconds": round(cpu or 0, 1),
|
|
"peakCpu": _r(pcpu), "peakRss": prss or 0, "peakProcs": pprocs or 0,
|
|
"runs": n, "live": (rn, sid) in live,
|
|
"heaviest": {"label": h[0], "cpuSeconds": round(h[1] or 0, 1),
|
|
"peakRss": h[2] or 0} if h else None})
|
|
out.sort(key=lambda r: -r["cpuSeconds"])
|
|
return {"range": rng, "rows": out}
|
|
|
|
|
|
def commands(deps, rng: str, kind: str = "tool", scope: Scope | None = None,
|
|
sids: Collection[str] | None = None) -> dict:
|
|
"""Commands or programs, grouped by label, heaviest CPU first.
|
|
|
|
From the call probe's exact records (calls.py): ``tool`` groups the
|
|
*parts* of every command line (``cd x && npm run build | tail`` counts
|
|
``npm run build`` and ``tail`` apart), ``program`` each process on its
|
|
own — plus, for programs, the 5-s samples of what runs outside Bash
|
|
calls (``perf_procs``, which the probe doesn't measure). ``sids``
|
|
narrows it to those sessions."""
|
|
scope = scope or Scope(deps)
|
|
since = _since(rng)
|
|
tool = kind != "program"
|
|
table = "perf_call_parts" if tool else "perf_call_procs"
|
|
text = "p.text" if tool else "c.command"
|
|
only, only_args = only_sessions(sids, "p.sid")
|
|
rows = list(deps.perf_store.query(
|
|
f"SELECT p.label, p.sid, {text}, p.cpu, p.peak_rss, COALESCE(p.wall, 0), p.started,"
|
|
f" c.runner, c.tool_use_id FROM {table} p JOIN perf_calls c USING (tool_use_id)"
|
|
f" WHERE p.started >= ?{only}", (since, *only_args)))
|
|
if not tool:
|
|
# programs: the processes outside any Bash call (the agent itself, MCP
|
|
# servers, a browser) are only sampled; every other one is the probe's
|
|
cutoff = deps.perf_store.query("SELECT MIN(started) FROM perf_calls")[0][0]
|
|
only, only_args = only_sessions(sids)
|
|
rows += [r + (None,) for r in deps.perf_store.query(
|
|
"SELECT label, sid, cmd, cpu_seconds, peak_rss, MAX(0, last_seen - started),"
|
|
" last_seen, runner FROM perf_procs WHERE kind IS NULL AND last_seen >= ?"
|
|
f" AND (started < ? OR in_tool = 0){only}",
|
|
(since, cutoff if cutoff is not None else 1e18, *only_args))]
|
|
if not scope.all:
|
|
rows = [r for r in rows if scope.conv(r[7], r[1])]
|
|
groups: dict[str, dict] = {}
|
|
for label, sid, cmd, cpu, rss, dur, last, rn, tid in rows:
|
|
g = groups.setdefault(label, {"label": label, "count": 0, "cpuSeconds": 0.0,
|
|
"maxCpuSeconds": 0.0, "peakRss": 0, "duration": 0.0,
|
|
"lastSeen": 0.0, "_sids": {}, "_runner": {}, "_ex": None})
|
|
g["count"] += 1
|
|
g["cpuSeconds"] += cpu or 0
|
|
g["peakRss"] = max(g["peakRss"], rss or 0)
|
|
g["duration"] += dur or 0
|
|
g["lastSeen"] = max(g["lastSeen"], last or 0)
|
|
g["_sids"][sid] = g["_sids"].get(sid, 0) + (cpu or 0)
|
|
g["_runner"].setdefault(sid, rn)
|
|
if (cpu or 0) >= g["maxCpuSeconds"]:
|
|
g["maxCpuSeconds"] = cpu or 0
|
|
g["_ex"] = (cmd, sid, cpu, rss, dur, rn, tid)
|
|
out = []
|
|
for g in sorted(groups.values(), key=lambda g: -g["cpuSeconds"])[:100]:
|
|
cmd, sid, cpu, rss, dur, rn, tid = g.pop("_ex")
|
|
sids = g.pop("_sids")
|
|
where = g.pop("_runner")
|
|
ranked = sorted(sids, key=lambda s: -sids[s])
|
|
top = ranked[:5]
|
|
# whose runs it was, heaviest first (the row's stacked avatars)
|
|
guests = list(dict.fromkeys(x for x in (scope.guest(where[s], s) for s in ranked) if x))
|
|
out.append({**g, "cpuSeconds": round(g["cpuSeconds"], 1),
|
|
"maxCpuSeconds": round(g["maxCpuSeconds"], 1),
|
|
"avgDuration": round(g.pop("duration") / g["count"], 1),
|
|
"conversations": len(sids), "guests": guests,
|
|
"example": {"cmd": cmd, "runner": rn, "sessionId": sid,
|
|
"guest": scope.guest(rn, sid),
|
|
"cpuSeconds": round(cpu or 0, 1), "peakRss": rss or 0,
|
|
"duration": round(dur or 0, 1), "toolUseId": tid,
|
|
**_conv(deps, sid)},
|
|
"top": [{"sessionId": s, "cpuSeconds": round(sids[s], 1), **_conv(deps, s),
|
|
"guest": scope.guest(where[s], s)} for s in top]})
|
|
out.sort(key=lambda g: -g["cpuSeconds"])
|
|
return {"range": rng, "kind": "tool" if tool else "program", "rows": out[:100]}
|
|
|
|
|
|
def live_sessions(deps) -> list[dict]:
|
|
out = []
|
|
for mid, st in deps.perf_poller.live().items():
|
|
snap = st.get("snap") or {}
|
|
if time.time() - (st.get("at") or 0) < 60:
|
|
out += [{**s, "runner": mid} for s in snap.get("sessions") or []]
|
|
return out
|
|
|
|
|
|
def _r(x) -> float | None:
|
|
return None if x is None else round(float(x), 1)
|
|
|
|
|
|
def _int(x) -> int | None:
|
|
return None if x is None else int(x)
|