Files
ai-agent/backend/perf/calls.py
gabrielvidalandClaude Opus 5.5 a1dc1d8c88 perf(hub): cheap conversation widgets — cached + delta /calls, stale-while-revalidate rollups, perf reads beside writes
- /api/perf/conversation/{sid}/calls: per-call view cache on (updated, len(data)),
  ?since= delta with a cursor (client polls since = cursor - 30), marks memo,
  (sid, updated) index. 260 calls: ~1 s → 3.7 ms cached, 0.7 ms per empty poll.
- _Memo: max_stale (soft key = summaries_version) + slots; project costs and
  the related index use it (151 cost rebuilds x ~10 s in 40 min on prod).
- PerfStore: per-thread read-only connections, so a slow ingest no longer
  parks pool threads (14 seen in query) and starves conversation reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 20:43:55 +01:00

667 lines
29 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Per-call records from every runner's call probe (agent-probe, ``GET
/callmeta``, ``sidecar/callprobe.py``): what each shell call of Claude Code,
opencode, Codex or pi — and every process it started — cost, plus each turn
boundary.
Tables (in ``perf.db``, beside the 5-s samples):
- ``perf_calls`` — one row per tool call (``tool_use_id``): its conversation,
the subagent that made it (``agent_id``), the turn (``prompt_id``), whether
the kernel saw it whole (``source = 'kernel'``) or it was sampled, its exit
code and totals; ``data`` keeps the probe's record (every process). A call
is re-sent while it runs: the newest version wins.
- ``perf_call_procs`` — one row per process of a call (label, own CPU, peak
RSS, exit status): the *programs* ranking.
- ``perf_marks`` — turn / subagent boundaries. claude-probe's carried the
account's plan and its official ``/usage`` reading at that moment;
agent-probe's don't — ``fill_marks`` derives them from the hub's usage
history (measured: account-wide, whole percents).
- ``perf_cursors`` — how far each runner's records were read.
Kept forever (a call is ~1–3 KB); a runner that resets its store (a fresh
install) is read again from its start."""
from __future__ import annotations
import bisect
import json
import threading
import time
from collections import OrderedDict
from . import shellsplit
from . import storage
PAGE = 1000
PAGES_PER_POLL = 5
SCHEMA = """
CREATE TABLE IF NOT EXISTS perf_calls (
tool_use_id TEXT PRIMARY KEY,
runner TEXT NOT NULL,
sid TEXT NOT NULL,
agent_id TEXT, agent_type TEXT, prompt_id TEXT,
tool TEXT, command TEXT, label TEXT,
background INTEGER DEFAULT 0,
status TEXT, source TEXT,
started REAL, ended REAL, duration_ms INTEGER,
exit_code INTEGER,
cpu REAL DEFAULT 0, -- CPU seconds, every process of the call
peak_rss INTEGER DEFAULT 0,
read_bytes INTEGER DEFAULT 0, write_bytes INTEGER DEFAULT 0,
gpu REAL DEFAULT 0, gpu_mem INTEGER DEFAULT 0,
procs INTEGER DEFAULT 0,
updated REAL,
data TEXT
);
CREATE INDEX IF NOT EXISTS perf_calls_sid ON perf_calls (sid, started);
CREATE INDEX IF NOT EXISTS perf_calls_started ON perf_calls (started);
-- the /calls delta (`updated > since`): 0.01 ms instead of a walk of the session's rows
CREATE INDEX IF NOT EXISTS perf_calls_sid_updated ON perf_calls (sid, updated);
CREATE TABLE IF NOT EXISTS perf_call_procs (
tool_use_id TEXT NOT NULL,
pid INTEGER NOT NULL,
started REAL NOT NULL,
sid TEXT NOT NULL,
label TEXT NOT NULL,
depth INTEGER,
cpu REAL DEFAULT 0, -- its own
peak_rss INTEGER DEFAULT 0,
wall REAL,
exit_code INTEGER, signal INTEGER,
exact INTEGER DEFAULT 0,
PRIMARY KEY (tool_use_id, pid, started)
);
CREATE INDEX IF NOT EXISTS perf_call_procs_started ON perf_call_procs (started);
CREATE TABLE IF NOT EXISTS perf_call_parts (
tool_use_id TEXT NOT NULL,
idx INTEGER NOT NULL,
sid TEXT NOT NULL,
label TEXT NOT NULL, -- `npm run build`, `pytest`: what the ranking groups
text TEXT,
started REAL,
wall REAL,
cpu REAL DEFAULT 0, -- its processes' own CPU, summed
peak_rss INTEGER DEFAULT 0,
exit_code INTEGER,
procs INTEGER DEFAULT 0,
PRIMARY KEY (tool_use_id, idx)
);
CREATE INDEX IF NOT EXISTS perf_call_parts_started ON perf_call_parts (started);
CREATE TABLE IF NOT EXISTS perf_marks (
key TEXT PRIMARY KEY,
runner TEXT NOT NULL,
sid TEXT NOT NULL,
event TEXT, prompt_id TEXT, agent_id TEXT,
t REAL,
plan TEXT, usage TEXT
);
CREATE INDEX IF NOT EXISTS perf_marks_sid ON perf_marks (sid, t);
CREATE TABLE IF NOT EXISTS perf_cursors (
runner TEXT PRIMARY KEY,
last INTEGER DEFAULT 0,
at REAL
);
"""
_UPSERT_CALL = """
INSERT INTO perf_calls (tool_use_id, runner, sid, agent_id, agent_type, prompt_id, tool, command,
label, background, status, source, started, ended, duration_ms, exit_code, cpu, peak_rss,
read_bytes, write_bytes, gpu, gpu_mem, procs, updated, data)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT (tool_use_id) DO UPDATE SET
runner = excluded.runner, sid = excluded.sid, agent_id = excluded.agent_id,
agent_type = excluded.agent_type, prompt_id = excluded.prompt_id, tool = excluded.tool,
command = excluded.command, label = excluded.label, background = excluded.background,
status = excluded.status, source = excluded.source, started = excluded.started,
ended = excluded.ended, duration_ms = excluded.duration_ms, exit_code = excluded.exit_code,
cpu = excluded.cpu, peak_rss = excluded.peak_rss, read_bytes = excluded.read_bytes,
write_bytes = excluded.write_bytes, gpu = excluded.gpu, gpu_mem = excluded.gpu_mem,
procs = excluded.procs, updated = excluded.updated, data = excluded.data
"""
def ensure_schema(store) -> None:
store.script(SCHEMA)
_SUBCOMMAND = {"npm": 2, "pnpm": 2, "yarn": 2, "bun": 2, "uv": 2, "git": 1, "docker": 1,
"cargo": 1, "go": 1, "make": 1, "python3": 1, "python": 1, "node": 1,
"kubectl": 1, "gh": 2, "tea": 2, "npx": 1, "uvx": 1, "systemctl": 1}
def part_label(text: str, prog: str | None) -> str:
"""A part's name in the rankings: its program, plus the subcommand for
the programs whose subcommand is the point (``npm run build``, ``git push``)."""
if not prog:
return (text.split(" ")[0] if text else "bash")[:60]
words = text.split()
i = next((k for k, w in enumerate(words) if w == prog or w.endswith("/" + prog)), 0)
keep = _SUBCOMMAND.get(prog, 0)
tail = [w for w in words[i + 1:i + 1 + keep] if not w.startswith("-") and len(w) < 30
and not any(c in w for c in "/<>|&;$'\"=")]
return " ".join([prog, *tail])[:60]
def _label(command: str, tool: str = "Bash") -> str:
"""A call's name: its first part that runs a program (a file tool's: the tool)."""
if tool and tool != "Bash":
return tool
parts = shellsplit.split(command)
prog = next((p for p in parts if p["program"]), None)
if prog is None:
return (parts[0]["text"].split(" ")[0] if parts else "bash")[:60]
return part_label(prog["text"], prog["program"])
def ingest(store, runner: str, records: list[dict]) -> int:
"""Store a page of ``/callmeta`` records (newer versions of a call win)."""
calls, procs, marks, parts, disk = [], [], [], [], []
now = time.time()
for r in records:
d = r.get("data") or {}
if r.get("kind") == "call" and d.get("toolUseId"):
tid = d["toolUseId"]
sid = d.get("sessionId") or r.get("session") or ""
t = d.get("totals") or {}
io = t.get("io") or {}
raw_procs = d.get("procs") or []
# Drop the redundant `procs` array from `perf_calls.data`: every
# child process row already lives in `perf_call_procs`.
slim = {k: v for k, v in d.items() if k != "procs"} if "procs" in d else d
calls.append((
tid, runner, sid,
d.get("agentId"), d.get("agentType"), d.get("promptId"),
d.get("tool") or "Bash", (d.get("command") or "")[:4000],
_label(d.get("command") or "", d.get("tool") or "Bash"), 1 if d.get("background") else 0,
d.get("status"), d.get("source"), d.get("startedAt"), d.get("endedAt"),
d.get("durationMs"), d.get("exitCode"), t.get("cpu") or 0,
t.get("peakRss") or 0, io.get("read_bytes") or 0, io.get("write_bytes") or 0,
t.get("gpuS") or 0, t.get("gpuMem") or 0, t.get("procs") or 0, now,
json.dumps(slim, separators=(",", ":"))))
if isinstance(d.get("files"), dict):
disk.append((d["files"].get("net") or 0, tid))
shell_pid = (raw_procs or [{}])[0].get("pid")
for p in raw_procs:
if p.get("pid") == shell_pid:
continue
wall = (p["endedAt"] - p["startedAt"]) if p.get("endedAt") and p.get("startedAt") else None
procs.append((tid, p["pid"], round(p.get("startedAt") or 0, 3),
d.get("sessionId") or "", (p.get("label") or "?")[:80],
p.get("depth"), p.get("cpuOwn") or 0, p.get("peakRss") or 0,
wall, p.get("exitCode"), p.get("signal"),
1 if p.get("exact") else 0))
if d.get("status") in ("done", "capped", "error", "detached"):
for i, part in enumerate(shellsplit.components(d.get("command") or "", raw_procs)):
if not part["pids"]:
continue
label = "(other)" if part.get("other") else part_label(part["text"], part["program"])
wall = (part["endedAt"] - part["startedAt"]) if part["endedAt"] and part["startedAt"] else None
parts.append((tid, i, sid, label, part["text"][:300], part["startedAt"], wall,
part["cpu"], part["peakRss"], part["exitCode"], len(part["pids"])))
elif r.get("kind") == "mark" and r.get("key"):
marks.append((r["key"], runner, d.get("sessionId") or r.get("session") or "",
d.get("event"), d.get("promptId"), d.get("agentId"), d.get("at"),
json.dumps(d["plan"]) if d.get("plan") else None,
json.dumps(d["usage"]) if d.get("usage") else None))
ids = sorted({c[0] for c in calls})
stmts: list[tuple[str, list]] = [(_UPSERT_CALL, calls)]
if ids:
for table in ("perf_call_procs", "perf_call_parts"):
stmts.append((f"DELETE FROM {table} WHERE tool_use_id IN ({','.join('?' * len(ids))})",
[tuple(ids)]))
stmts += [("INSERT OR REPLACE INTO perf_call_procs VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", procs),
("INSERT OR REPLACE INTO perf_call_parts VALUES (?,?,?,?,?,?,?,?,?,?,?)", parts),
("INSERT OR REPLACE INTO perf_marks VALUES (?,?,?,?,?,?,?,?,?)", marks)]
stmts.append(("UPDATE perf_calls SET disk_net = ? WHERE tool_use_id = ?", disk))
stmts += storage.records(runner, records, now) # what sessions keep on disk
store.write(stmts)
return len(records)
def cursor(store, runner: str) -> int:
rows = store.query("SELECT last FROM perf_cursors WHERE runner = ?", (runner,))
return rows[0][0] if rows else 0
def set_cursor(store, runner: str, last: int) -> None:
store.write([("INSERT OR REPLACE INTO perf_cursors VALUES (?,?,?)",
[(runner, last, time.time())])])
def pull(store, runner: str, fetch) -> int:
"""Read a runner's new records: ``fetch(after) → /callmeta`` body.
Returns how many were stored."""
n = 0
after = cursor(store, runner)
for _ in range(PAGES_PER_POLL):
body = fetch(after)
if not body.get("enabled", True) and not body.get("records"):
break
head = body.get("head")
if head is not None and head < after: # the runner's store was reset
after = 0
set_cursor(store, runner, 0)
continue
recs = body.get("records") or []
if recs:
n += ingest(store, runner, recs)
after = body.get("last") or recs[-1]["id"]
set_cursor(store, runner, after)
if len(recs) < PAGE:
break
return n
# ── reads ────────────────────────────────────────────────────────────────────
def view(row: dict) -> dict:
"""One call as the conversation shows it: totals, its parts with the
processes each ran, the processes themselves."""
d = row
procs = d.get("procs") or []
t = d.get("totals") or {}
io = t.get("io") or {}
started, ended = d.get("startedAt"), d.get("endedAt")
wall = d["durationMs"] / 1000 if d.get("durationMs") is not None and not d.get("background") \
else ((ended - started) if ended and started else None)
return {
"toolUseId": d.get("toolUseId"), "sessionId": d.get("sessionId"),
"agentId": d.get("agentId"), "agentType": d.get("agentType"),
"promptId": d.get("promptId"), "status": d.get("status"),
"source": d.get("source") or "sampled", "background": bool(d.get("background")),
"seen": bool(d.get("seen")), "startedAt": started, "endedAt": ended,
"wall": round(wall, 3) if wall is not None else None,
"exitCode": d.get("exitCode"), "signal": d.get("signal"),
"cpu": t.get("cpu") or 0, "peakRss": t.get("peakRss") or 0,
"readBytes": io.get("read_bytes") or 0, "writeBytes": io.get("write_bytes") or 0,
"gpuSeconds": t.get("gpuS") or 0, "gpuMem": t.get("gpuMem") or 0,
"procs": t.get("procs") or len(procs), "liveProcs": d.get("liveProcs") or 0,
"ran": d.get("ran"), "overflow": d.get("overflow") or 0,
"tool": d.get("tool") or "Bash", "filePath": d.get("filePath"),
"agent": d.get("agent"), "adopted": bool(d.get("adopted")),
"files": d.get("files") if isinstance(d.get("files"), dict) else None,
"command": (d.get("command") or "")[:400] or None,
"script": d.get("script"), "scriptGuess": bool(d.get("scriptGuess")),
"components": shellsplit.components(d.get("command") or "", procs),
"processes": [{k: p.get(k) for k in ("pid", "ppid", "depth", "label", "argv",
"startedAt", "endedAt", "cpu", "cpuOwn",
"peakRss", "exitCode", "signal", "exact",
"cpuUnseen", "gpuS", "gpuMem")}
| {"readBytes": (p.get("io") or {}).get("read_bytes"),
"writeBytes": (p.get("io") or {}).get("write_bytes")}
for p in procs],
}
def _reconstruct_procs(d: dict, proc_rows: list[tuple]) -> list[dict]:
"""Rebuild a call's process list from ``perf_call_procs`` rows when the
redundant ``procs`` array was stripped from ``perf_calls.data``.
``perf_call_procs`` intentionally excludes the wrapper shell (depth 0) so
shells don't pollute the program ranking; when totals indicate a shell row
was present, synthesize a lightweight depth-0 entry so ``shellsplit`` and
process counts stay consistent."""
out: list[dict] = []
has_root = False
for pid, started, label, depth, cpu, peak_rss, wall, exit_code, signal, exact in proc_rows:
if depth == 0:
has_root = True
ended = (started + wall) if (started is not None and wall is not None) else None
out.append({
"pid": pid, "ppid": None, "depth": depth, "label": label, "argv": None,
"startedAt": started, "endedAt": ended, "cpu": cpu, "cpuOwn": cpu,
"peakRss": peak_rss, "exitCode": exit_code, "signal": signal,
"exact": bool(exact),
})
total_procs = (d.get("totals") or {}).get("procs") or 0
if not has_root and (out or total_procs > 0):
out.insert(0, {
"pid": 0, "ppid": 0, "depth": 0,
"label": _label(d.get("command") or "", d.get("tool") or "Bash"),
"argv": None, "startedAt": d.get("startedAt"), "endedAt": d.get("endedAt"),
"cpu": 0, "cpuOwn": 0, "peakRss": 0,
"exitCode": d.get("exitCode"), "signal": d.get("signal"),
"exact": d.get("source") == "kernel",
})
return out
# A call's view (its parts through ``shellsplit.components``, its processes)
# is most of a read's cost — 2 495 calls: ~3 s — and the Bash cards poll it
# every 5 s while a conversation runs. Views are cached per call, keyed on
# its stamp ``(updated, len(data))``: ``updated`` is the ingest time, bumped on
# every upsert (its ``perf_call_procs`` are rewritten in that same ingest);
# ``dedup_procs_data`` rewrites ``data`` without touching ``updated``, hence
# the length. An LRU of a few sessions bounds the memory (the 2 495-call one
# keeps ~16 MB of views). A cached view is shared by every response: never
# mutate one.
VIEW_CACHE_SESSIONS = 4
class _SessionViews:
__slots__ = ("lock", "views")
def __init__(self):
self.lock = threading.Lock() # one read of a session at a time
self.views: dict[str, tuple[tuple, dict]] = {} # tid → (stamp, view)
class _ViewCache:
def __init__(self, sessions: int = VIEW_CACHE_SESSIONS):
self._max = sessions
self._lock = threading.Lock()
self._sessions: OrderedDict[tuple, _SessionViews] = OrderedDict()
def session(self, store, sid: str) -> _SessionViews:
key = (id(store), sid)
with self._lock:
sv = self._sessions.get(key)
if sv is None:
sv = self._sessions[key] = _SessionViews()
self._sessions.move_to_end(key)
while len(self._sessions) > self._max:
self._sessions.popitem(last=False)
return sv
def clear(self) -> None:
with self._lock:
self._sessions.clear()
_views = _ViewCache()
def _build_views(store, rows: list[tuple[str, str]]) -> dict[str, dict]:
"""``tid → view`` for ``(tool_use_id, data)`` rows (a row that won't
parse is left out)."""
parsed: list[tuple[str, dict]] = []
need_procs: list[str] = []
for tid, raw in rows:
try:
d = json.loads(raw)
except (ValueError, TypeError):
continue
if not isinstance(d, dict):
continue
parsed.append((tid, d))
if "procs" not in d:
need_procs.append(tid)
procs_by_tid: dict[str, list[tuple]] = {}
for i in range(0, len(need_procs), 500):
chunk = need_procs[i:i + 500]
q = (
"SELECT tool_use_id, pid, started, label, depth, cpu, peak_rss,"
" wall, exit_code, signal, exact FROM perf_call_procs"
f" WHERE tool_use_id IN ({','.join('?' * len(chunk))})"
" ORDER BY started"
)
for r in store.query(q, tuple(chunk)):
procs_by_tid.setdefault(r[0], []).append(r[1:])
out: dict[str, dict] = {}
for tid, d in parsed:
try:
if "procs" not in d:
d["procs"] = _reconstruct_procs(d, procs_by_tid.get(tid, []))
out[tid] = view(d)
except (ValueError, TypeError, KeyError):
continue
return out
def calls_since(store, sid: str, since: float | None = None) -> tuple[list[dict], float | None]:
"""The conversation's calls as ``view`` shows them, in start order, and the
read's cursor.
``since`` unset: every call, and the cursor is the newest ``updated``
among them (None: no call yet). ``since`` set: only the calls ingested
(``updated``) after it, and the cursor is the newest ``updated`` among
those — ``since`` itself when nothing changed.
The client's contract: read whole once, then poll with
``since = cursor - 30`` and merge the answer into what it holds by
``toolUseId`` (a call is re-sent while it runs; the newest version wins).
The 30 s overlap is not optional: ``updated`` is stamped when an ingest
starts, and two runners' ingests can commit out of that order, so a row
stamped just before the cursor may only become visible after a read that
already saw a later one. Calls are never deleted, so a delta has nothing
to remove."""
if since is None:
q, args = ("SELECT tool_use_id, updated, data FROM perf_calls"
" WHERE sid = ? ORDER BY started", (sid,))
else:
q, args = ("SELECT tool_use_id, updated, data FROM perf_calls"
" WHERE sid = ? AND updated > ? ORDER BY started", (sid, since))
sv = _views.session(store, sid)
# The query runs under the session's lock too: a read that queried before
# a concurrent one can't then store its older views over the newer ones.
with sv.lock:
rows = store.query(q, args)
cache = sv.views
stamps = [(tid, (updated, len(raw) if raw else 0)) for tid, updated, raw in rows]
miss = [(tid, raw) for (tid, stamp), (_, _, raw) in zip(stamps, rows)
if (cache.get(tid) or (None,))[0] != stamp]
built = _build_views(store, miss) if miss else {}
if since is None:
# A full read sees every call: drop the ones that are gone.
keep = {tid for tid, _ in stamps}
if len(cache) > len(keep):
cache = sv.views = {t: e for t, e in cache.items() if t in keep}
out = []
for tid, stamp in stamps:
v = built.get(tid)
if v is not None:
cache[tid] = (stamp, v)
else:
hit = cache.get(tid)
if hit is None or hit[0] != stamp:
continue # unparseable data: skipped, as ever
v = hit[1]
out.append(v)
cursor = max((u for _, u, _ in rows if u is not None), default=since)
return out, cursor
def conversation_calls(store, sid: str) -> list[dict]:
"""Every call of the conversation (``calls_since`` without a cursor)."""
return calls_since(store, sid)[0]
def dedup_procs_data(store_or_path, *, batch_size: int = 500, sleep_s: float = 0.0) -> int:
"""Safely and idempotently strip the redundant ``procs`` array from existing
``perf_calls.data`` JSON blobs in batches (keeping all rows and every other
field intact). Accepts either a :class:`PerfStore` or a path to ``perf.db``.
Returns how many rows were updated."""
import pathlib # noqa: PLC0415
import sqlite3 # noqa: PLC0415
own_conn = isinstance(store_or_path, (str, pathlib.Path))
if own_conn:
conn = sqlite3.connect(str(store_or_path), check_same_thread=False)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA busy_timeout=5000")
conn.execute("PRAGMA journal_size_limit=16777216")
else:
conn = None
total = 0
last_id = ""
try:
while True:
sql = (
"SELECT tool_use_id, data FROM perf_calls"
" WHERE tool_use_id > ? AND data LIKE '%\"procs\"%'"
" ORDER BY tool_use_id LIMIT ?"
)
if own_conn:
rows = conn.execute(sql, (last_id, batch_size)).fetchall()
else:
rows = store_or_path.query(sql, (last_id, batch_size))
if not rows:
break
last_id = rows[-1][0]
updates: list[tuple[str, str]] = []
for tid, raw in rows:
if not raw:
continue
try:
d = json.loads(raw)
except (ValueError, TypeError):
continue
if not isinstance(d, dict) or "procs" not in d:
continue
d.pop("procs", None)
updates.append((json.dumps(d, separators=(",", ":")), tid))
if updates:
if own_conn:
conn.executemany("UPDATE perf_calls SET data = ? WHERE tool_use_id = ?", updates)
conn.commit()
else:
store_or_path.write([("UPDATE perf_calls SET data = ? WHERE tool_use_id = ?", updates)])
total += len(updates)
if sleep_s > 0:
time.sleep(sleep_s)
if total:
if own_conn:
conn.execute("PRAGMA incremental_vacuum(2000)").fetchall()
conn.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchall()
else:
store_or_path.incremental_vacuum(2000)
store_or_path.wal_checkpoint("TRUNCATE")
finally:
if own_conn and conn is not None:
conn.close()
return total
def _mark_rows(store, sid: str) -> list[tuple]:
return store.query("SELECT event, prompt_id, agent_id, t, plan, usage FROM perf_marks"
" WHERE sid = ? ORDER BY t", (sid,))
def _parse_marks(rows: list[tuple]) -> list[dict]:
return [{"event": e, "promptId": p, "agentId": a, "at": t,
"plan": json.loads(pl) if pl else None, "usage": json.loads(u) if u else None}
for e, p, a, t, pl, u in rows]
def conversation_marks(store, sid: str) -> list[dict]:
return _parse_marks(_mark_rows(store, sid))
# ── backfill: conversations from before the probe ────────────────────────────
READING_MAX_AGE_S = 3 * 3600 # an older reading says nothing about that moment
def _iso(ts) -> float | None:
from datetime import datetime # noqa: PLC0415
try:
return datetime.fromisoformat(str(ts).replace("Z", "+00:00")).timestamp()
except (TypeError, ValueError):
return None
def _reading(series: dict, t: float) -> dict | None:
"""The account's last official reading at or before ``t`` (and at most
``READING_MAX_AGE_S`` old), per window, out of ``usage_store.series``."""
windows = {}
for w, pts in series.items():
i = bisect.bisect_right(pts, t, key=lambda p: p[0])
if i and pts[i - 1][0] >= t - READING_MAX_AGE_S:
at, pct, resets = pts[i - 1]
windows[w] = {"pct": pct, "resetsAt": resets, "at": at}
return {"windows": windows} if windows else None
def _plan(usage_store, account: str, t: float) -> dict | None:
from usage import plans # noqa: PLC0415
plan = plans.public(plans.at(usage_store, account, t))
return {"planDisplayName": plan["displayName"] or plan["label"],
"tier": plan["tier"], "account": account} if plan else None
def _account(deps, sid: str) -> str:
return (deps.meta_store.peek(sid) or {}).get("account") or "personal"
def fill_marks(deps, sid: str, marks: list[dict]) -> list[dict]:
"""agent-probe's marks carry no plan or usage reading (the hub has both):
each mark without them gets the plan in force and the account's official
reading at its moment, from the usage history — like ``derived_marks``."""
todo = [m for m in marks if m.get("at") and not m.get("plan") and not m.get("usage")]
if not todo:
return marks
account = _account(deps, sid)
ts = [m["at"] for m in todo]
series = deps.usage_store.series(account, min(ts) - READING_MAX_AGE_S, max(ts))
for m in todo:
m["plan"] = _plan(deps.usage_store, account, m["at"])
m["usage"] = _reading(series, m["at"])
m["derived"] = True
return marks
def derived_marks(deps, sid: str) -> list[dict]:
"""A conversation the call probe never saw: the account's official usage
reading at its start and its end and the plan in force then, from the hub's
usage history (``usage/``) — measured, account-wide, whole percents."""
from . import views # noqa: PLC0415
t = views.titles(deps).get(sid)
if not t:
return []
summary = next((s for _, s in deps.store.all_summaries()
if s.get("sessionId") == sid and not s.get("isSidechain")), None) or {}
t0, t1 = _iso(summary.get("startedAt")), _iso(summary.get("endedAt") or t.get("endedAt"))
account = _account(deps, sid)
out = []
for event, at in (("start", t0), ("end", t1)):
if at is None:
continue
out.append({"event": event, "promptId": None, "agentId": None, "at": at,
"plan": _plan(deps.usage_store, account, at),
"usage": _reading(deps.usage_store.series(account, at - READING_MAX_AGE_S, at), at),
"derived": True})
return out
# ── the turn marks a /calls read sends ──────────────────────────────────────
# ``fill_marks`` reads the usage history per mark and ``derived_marks`` the
# whole summary catalog (``views.titles``, rebuilt on every transcript write):
# too much for a 5-s poll. Each conversation's answer is kept until its
# ``perf_marks`` rows change — a new turn shows at once — and at most
# ``MARKS_TTL_S`` (what the history says about a moment hardly moves; a
# conversation the probe never saw gets its "end" reading a minute late).
MARKS_TTL_S = 60.0
MARKS_CACHE_SIZE = 64
_marks_cache: OrderedDict[tuple, tuple[list[tuple], float, list[dict]]] = OrderedDict()
_marks_lock = threading.Lock()
def turn_marks(deps, sid: str) -> list[dict]:
"""The conversation's turn marks with the plan and usage reading at each:
agent-probe's, filled in from the usage history (``fill_marks``); from
before the probe, its start and end (``derived_marks``). Memoized: see
``MARKS_TTL_S``. The list is shared — don't mutate it."""
rows = _mark_rows(deps.perf_store, sid)
key = (id(deps.perf_store), sid)
now = time.monotonic()
with _marks_lock:
hit = _marks_cache.get(key)
if hit is not None and hit[0] == rows and now - hit[1] < MARKS_TTL_S:
_marks_cache.move_to_end(key)
return hit[2]
marks = _parse_marks(rows)
try:
marks = fill_marks(deps, sid, marks) if marks else derived_marks(deps, sid)
except Exception as e: # noqa: BLE001 — the calls still answer
print(f"[perf] derived marks {sid}: {e}", flush=True)
with _marks_lock:
_marks_cache[key] = (rows, now, marks)
_marks_cache.move_to_end(key)
while len(_marks_cache) > MARKS_CACHE_SIZE:
_marks_cache.popitem(last=False)
return marks