Files
ai-agent/backend/test_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

469 lines
26 KiB
Python

"""perf/calls + perf/shellsplit: the call probe's records — splitting a command
line into its parts, putting each process under its part, storing the records
a runner's /callmeta hands out, and the rankings built on them."""
import json
import time
import unittest
from unittest import mock
from perf import calls, shellsplit
from perf import conversation as conv_view
from perf import views
from perf.poller import LAB
from test_perf import A, Deps, snap
def proc(pid, label, *, ppid, depth, start, end, own, rss=4 << 20, code=0, argv=None):
return {"pid": pid, "ppid": ppid, "depth": depth, "label": label, "argv": argv or label,
"startedAt": start, "endedAt": end, "cpuOwn": own, "cpu": own,
"peakRss": rss, "exitCode": code, "exact": True, "via": "kernel"}
def call_record(tid, command, procs, *, at, agent=None, status="done", exit_code=0, rid=1):
return {"id": rid, "at": at, "kind": "call", "session": A, "key": tid, "data": {
"v": 1, "tool": "Bash", "toolUseId": tid, "sessionId": A, "agentId": agent,
"agentType": "Explore" if agent else None, "promptId": "p1", "command": command,
"background": False, "status": status, "seen": True, "source": "kernel",
"startedAt": at, "endedAt": at + 5, "durationMs": 5000, "exitCode": exit_code,
"totals": {"cpu": sum(p["cpuOwn"] for p in procs), "peakRss": max(p["peakRss"] for p in procs),
"procs": len(procs), "io": {"read_bytes": 10, "write_bytes": 20},
"gpuS": 0, "gpuMem": 0},
"procs": procs}}
BUILD = "cd /x && npm run build 2>&1 | tail -20; echo done"
def build_procs(t):
return [proc(10, "npm run build", ppid=1, depth=0, start=t, end=t + 5, own=0.01,
argv="/bin/bash -c eval 'cd /x && npm run build'"),
proc(11, "npm run build", ppid=10, depth=1, start=t + 0.1, end=t + 4.9, own=0.4),
proc(12, "vite", ppid=11, depth=2, start=t + 0.3, end=t + 4.8, own=9.5,
rss=900 << 20),
proc(13, "tail", ppid=10, depth=1, start=t + 0.1, end=t + 4.95, own=0.01)]
class SplitTests(unittest.TestCase):
def test_parts_and_operators(self):
parts = shellsplit.split(BUILD)
self.assertEqual([p["text"] for p in parts],
["cd /x", "npm run build 2>&1", "tail -20", "echo done"])
self.assertEqual([p["op"] for p in parts], ["&&", "|", ";", None])
self.assertEqual([p["program"] for p in parts], [None, "npm", "tail", None])
def test_quotes_heredocs_redirections_and_subshells(self):
self.assertEqual(len(shellsplit.split('echo "a && b | c"')), 1)
self.assertEqual([p["program"] for p in shellsplit.split(
"python3 - <<'EOF'\nx && y | z\nEOF\nls")], ["python3", "ls"])
bg = shellsplit.split("vite --port 5000 > /tmp/log 2>&1 &")
self.assertTrue(bg[0]["background"])
self.assertEqual(bg[0]["program"], "vite")
sub = shellsplit.split("(cd a; make -j4) | tee log")
self.assertEqual([(p["program"], p["depth"]) for p in sub],
[(None, 1), ("make", 1), ("tee", 0)])
self.assertEqual(shellsplit.split("FOO=1 rtk git status")[0]["program"], "git")
self.assertEqual(shellsplit.split("timeout 30 npx vitest run")[0]["program"], "vitest")
self.assertIsNone(shellsplit.split("for f in *.py; do wc -l $f; done")[0]["program"])
def test_processes_go_under_their_part(self):
comps = shellsplit.components(BUILD, build_procs(1000.0))
by = {c["text"]: c for c in comps}
self.assertTrue(by["cd /x"]["builtin"])
self.assertEqual(by["npm run build 2>&1"]["pids"], [11, 12])
self.assertAlmostEqual(by["npm run build 2>&1"]["cpu"], 9.9)
self.assertEqual(by["npm run build 2>&1"]["peakRss"], 900 << 20)
self.assertEqual(by["tail -20"]["pids"], [13])
self.assertTrue(by["echo done"]["builtin"])
self.assertFalse(any(c.get("other") for c in comps))
def test_unnamed_processes_join_the_running_part_or_other(self):
t = 1000.0
procs = [proc(10, "bash", ppid=1, depth=0, start=t, end=t + 2, own=0.01),
proc(20, "ls", ppid=10, depth=1, start=t + 0.1, end=t + 0.2, own=0.01, code=2),
proc(21, "mystery", ppid=10, depth=1, start=t + 0.5, end=t + 1, own=0.3)]
comps = shellsplit.components("ls /nope; echo after", procs)
self.assertEqual(comps[0]["exitCode"], 2)
self.assertIn(21, comps[0]["pids"]) # started after ls: joins the running part
def test_an_alias_takes_its_own_part_not_the_cd_before_it(self):
# `dev-down` / `dev-up` exec into `uv run … dev_env.py`: no process
# names them, yet each is the next part with a program
t = 1000.0
cmd = "cd /x && dev-down 5300 && dev-up | tail -3"
shell = f"/bin/bash -c source /snap.sh && eval '{cmd}'"
procs = [proc(10, "bash", ppid=1, depth=0, start=t, end=t + 30, own=0.01, argv=shell),
proc(20, "dev_env.py", ppid=10, depth=1, start=t + 0.1, end=t + 1, own=0.3,
argv="uv run --script /s/dev_env.py --as-down 5300"),
proc(21, "git", ppid=20, depth=2, start=t + 0.2, end=t + 0.3, own=0.01),
proc(30, "dev_env.py", ppid=10, depth=1, start=t + 1.1, end=t + 25, own=4.0,
argv="uv run --script /s/dev_env.py --as-up"),
proc(31, "tail", ppid=10, depth=1, start=t + 1.1, end=t + 25, own=0.01)]
by = {c["text"]: c for c in shellsplit.components(cmd, procs)}
self.assertTrue(by["cd /x"]["builtin"])
self.assertEqual(by["dev-down 5300"]["pids"], [20, 21])
self.assertEqual(by["dev-up"]["pids"], [30])
self.assertEqual(by["tail -3"]["pids"], [31])
def test_a_subshell_fork_still_joins_the_running_part(self):
t = 1000.0
cmd = 'echo "$(git rev-parse HEAD)" && ls'
shell = f"/bin/bash -c eval '{cmd}'"
procs = [proc(10, "bash", ppid=1, depth=0, start=t, end=t + 1, own=0.01, argv=shell),
proc(20, "bash", ppid=10, depth=1, start=t + 0.1, end=t + 0.3, own=0.01, argv=shell),
proc(21, "git", ppid=20, depth=2, start=t + 0.1, end=t + 0.2, own=0.01),
proc(30, "ls", ppid=10, depth=1, start=t + 0.4, end=t + 0.5, own=0.01)]
comps = shellsplit.components(cmd, procs)
self.assertEqual(comps[0]["pids"], [20, 21])
self.assertEqual(comps[1]["pids"], [30])
def test_a_daemonized_descendant_stays_under_the_part_that_forked_it(self):
# `git fetch` leaves `git maintenance run --auto --detach` behind; it
# daemonizes, launchd reaps it (ppid 1), and its `git gc` runs on
# long after the call. It is the fetch's, not the next `git` part's.
t = 1000.0
cmd = "git fetch -q origin && git log --oneline -3 origin/x; git log --oneline -1"
shell = f"/bin/zsh -c eval '{cmd}'"
procs = [proc(10, "git", ppid=9, depth=0, start=t, end=t + 3.52, own=0.01, argv=shell),
proc(20, "git", ppid=10, depth=1, start=t + 0.10, end=t + 3.33, own=0.11,
argv="git fetch -q origin"),
proc(21, "git", ppid=20, depth=2, start=t + 3.33, end=t + 3.33, own=0.0,
argv="git maintenance run --auto --quiet --detach"),
proc(22, "git", ppid=1, depth=3, start=t + 3.34, end=t + 26.54, own=0.0,
argv="git maintenance run --auto --quiet --detach"),
proc(30, "git", ppid=10, depth=1, start=t + 3.34, end=t + 3.35, own=0.01,
argv="git log --oneline -3 origin/x"),
proc(23, "git", ppid=22, depth=4, start=t + 3.34, end=t + 26.53, own=4.56,
argv="git gc --auto --quiet --no-detach"),
proc(31, "git", ppid=10, depth=1, start=t + 3.35, end=t + 3.36, own=0.01,
argv="git log --oneline -1"),
proc(24, "git", ppid=23, depth=5, start=t + 4.33, end=t + 20.58, own=22.59,
rss=995 << 20, argv="git pack-objects --local --quiet")]
by = {c["text"]: c for c in shellsplit.components(cmd, procs)}
self.assertEqual(by["git fetch -q origin"]["pids"], [20, 21, 22, 23, 24])
self.assertAlmostEqual(by["git fetch -q origin"]["cpu"], 27.27, delta=0.02)
self.assertEqual(by["git log --oneline -3 origin/x"]["pids"], [30])
self.assertEqual(by["git log --oneline -1"]["pids"], [31])
self.assertNotIn(True, [c.get("other") for c in by.values()])
def test_a_process_the_shell_lost_track_of_keeps_its_own_part(self):
# depth 1 with an unknown ppid is still one of the shell's children
t = 1000.0
procs = [proc(10, "bash", ppid=1, depth=0, start=t, end=t + 2, own=0.01),
proc(20, "sleep", ppid=1, depth=1, start=t + 0.1, end=t + 1, own=0.01)]
comps = shellsplit.components("sleep 1 &", procs)
self.assertEqual(comps[0]["pids"], [20])
class WrapperTests(unittest.TestCase):
def test_a_wrapped_program_takes_its_own_part(self):
t = 1000.0
cmd = "grep x f | head; cd .. && npx tsc --noEmit 2>&1 | grep error | head"
procs = [proc(10, "bash", ppid=1, depth=0, start=t, end=t + 60, own=0.01),
proc(20, "grep", ppid=10, depth=1, start=t + 0.1, end=t + 0.2, own=0.01),
proc(21, "head", ppid=10, depth=1, start=t + 0.1, end=t + 0.2, own=0.01),
proc(30, "npm exec tsc", ppid=10, depth=1, start=t + 1, end=t + 50, own=0.5,
argv="npm exec tsc --noEmit"),
proc(31, "tsc", ppid=30, depth=2, start=t + 1.2, end=t + 49, own=50.0,
rss=1 << 30),
proc(32, "grep", ppid=10, depth=1, start=t + 1, end=t + 50, own=0.01),
proc(33, "head", ppid=10, depth=1, start=t + 1, end=t + 50, own=0.01)]
comps = {c["text"]: c for c in shellsplit.components(cmd, procs)}
self.assertEqual(comps["npx tsc --noEmit 2>&1"]["pids"], [30, 31])
self.assertAlmostEqual(comps["npx tsc --noEmit 2>&1"]["cpu"], 50.5)
self.assertLess(comps["head"]["cpu"], 1)
class CallStoreTests(unittest.TestCase):
def setUp(self):
self.deps = Deps()
self.store = self.deps.perf_store
self._titles = views.titles
views.titles = lambda deps: {}
def tearDown(self):
views.titles = self._titles
def test_ingest_newest_version_wins_and_parts_are_ranked(self):
t = time.time() - 60
running = call_record("toolu_1", BUILD, build_procs(t)[:2], at=t, status="running", rid=1)
done = call_record("toolu_1", BUILD, build_procs(t), at=t, rid=2)
sub = call_record("toolu_2", "pytest -q", [
proc(30, "pytest", ppid=1, depth=0, start=t + 10, end=t + 12, own=0.01),
proc(31, "pytest", ppid=30, depth=1, start=t + 10.1, end=t + 11.9, own=1.5, code=1)],
at=t + 10, agent="a1", exit_code=1, rid=3)
calls.ingest(self.store, LAB, [running, done, sub])
out = calls.conversation_calls(self.store, A)
self.assertEqual([c["toolUseId"] for c in out], ["toolu_1", "toolu_2"])
self.assertEqual(out[0]["status"], "done")
self.assertEqual(len(out[0]["processes"]), 4)
self.assertEqual(out[1]["agentType"], "Explore")
self.assertEqual(out[1]["exitCode"], 1)
self.assertEqual(out[0]["wall"], 5.0)
rows = {r["label"]: r for r in views.commands(self.deps, "1h", "tool")["rows"]}
self.assertEqual(set(rows), {"npm run build", "tail", "pytest"})
self.assertAlmostEqual(rows["npm run build"]["cpuSeconds"], 9.9, places=1)
self.assertEqual(rows["npm run build"]["example"]["toolUseId"], "toolu_1")
progs = {r["label"] for r in views.commands(self.deps, "1h", "program")["rows"]}
self.assertEqual(progs, {"npm run build", "vite", "tail", "pytest"})
cv = conv_view.conversation(self.deps, A)
self.assertEqual(cv["commands"][0]["toolUseId"], "toolu_1")
self.assertEqual(cv["heaviest"][0]["label"], "npm run build")
def test_sampled_bash_shells_are_never_ranked_and_go_after_a_day(self):
now = time.time()
self.store.record(LAB, snap(now - 30)) # a sampled `npm run build` shell
self.assertEqual(views.commands(self.deps, "1h", "tool")["rows"], [])
self.store.prune(now + 2 * 86400)
self.assertEqual(self.store.query("SELECT COUNT(*) FROM perf_procs WHERE kind = 'tool'"),
[(0,)])
def test_programs_outside_bash_calls_stay_ranked_after_the_probe(self):
now = time.time()
calls.ingest(self.store, LAB, [call_record("toolu_0", "pytest", [
proc(60, "bash", ppid=1, depth=0, start=now - 120, end=now - 119, own=0.01),
proc(61, "pytest", ppid=60, depth=1, start=now - 120, end=now - 119, own=0.5)],
at=now - 120)])
s = snap(now - 30)
s["sessions"][0]["processes"][0]["inTool"] = False # claude itself
s["sessions"][0]["processes"][1]["inTool"] = True # a Bash call's shell
s["sessions"][0]["processes"].append(dict(s["sessions"][0]["processes"][1], pid=102,
label="vite", kind=None, inTool=True))
for r in s["sessions"][0]["processes"] + s["sessions"][1]["processes"]:
r["startedAt"] = now - 60
self.store.record(LAB, s)
progs = {r["label"] for r in views.commands(self.deps, "1h", "program")["rows"]}
self.assertIn("claude", progs) # sampled, outside any call
self.assertNotIn("vite", progs) # inside a call: the probe's
self.assertIn("pytest", progs) # the probe's exact record
def test_pull_follows_the_cursor_and_restarts_after_a_reset(self):
t = time.time()
recs = [call_record(f"toolu_{i}", "ls", [proc(50 + i, "ls", ppid=1, depth=0, start=t,
end=t + 1, own=0.01)], at=t, rid=i)
for i in range(1, 4)]
asked = []
def fetch(after):
asked.append(after)
got = [r for r in recs if r["id"] > after]
return {"records": got, "last": got[-1]["id"] if got else after,
"head": recs[-1]["id"], "enabled": True}
self.assertEqual(calls.pull(self.store, LAB, fetch), 3)
self.assertEqual(calls.cursor(self.store, LAB), 3)
self.assertEqual(calls.pull(self.store, LAB, fetch), 0)
# the runner's store was wiped: its head is behind our cursor
recs[:] = [call_record("toolu_new", "ls", recs[0]["data"]["procs"], at=t, rid=1)]
calls.pull(self.store, LAB, fetch)
self.assertIn("toolu_new", {c["toolUseId"] for c in calls.conversation_calls(self.store, A)})
def test_marks_keep_plan_and_usage(self):
calls.ingest(self.store, LAB, [{"id": 1, "at": 1, "kind": "mark", "session": A,
"key": "k1", "data": {
"event": "prompt", "sessionId": A, "promptId": "p1",
"at": 100.0, "plan": {"planDisplayName": "Max"},
"usage": {"windows": {"seven_day": {"pct": 27}}}}}])
m = calls.conversation_marks(self.store, A)
self.assertEqual(m[0]["plan"]["planDisplayName"], "Max")
self.assertEqual(m[0]["usage"]["windows"]["seven_day"]["pct"], 27)
def test_agent_probe_marks_get_plan_and_usage_from_the_history(self):
"""agent-probe's marks carry neither: the hub fills them in from its
usage history, as for a conversation from before the probe."""
import tempfile # noqa: PLC0415
from usage.store import UsageStore # noqa: PLC0415
us = UsageStore(tempfile.mktemp(suffix=".db"))
us.add_plan({"account": "work", "since": 0, "tier": "max_20x", "windows": ["seven_day"],
"data": {"displayName": "Max"}})
us.add_points([("work", "seven_day", 1000.0, 27.0, 9e9, "live"),
("work", "seven_day", 2000.0, 28.0, 9e9, "live"),
("work", "five_hour", 1500.0, 60.0, 9e9, "live")])
class Meta:
def peek(self, sid):
return {"account": "work"} if sid == A else None
class D:
usage_store, meta_store = us, Meta()
calls.ingest(self.store, LAB, [
{"id": i, "at": 1, "kind": "mark", "session": A, "key": f"k{i}", "data": {
"v": 1, "agent": "claude-code", "event": e, "sessionId": A, "promptId": "p1", "at": t}}
for i, (e, t) in enumerate((("prompt", 1200.0), ("stop", 2100.0)), 1)])
m = calls.fill_marks(D, A, calls.conversation_marks(self.store, A))
self.assertEqual(m[0]["plan"], {"planDisplayName": "Max", "tier": "max_20x", "account": "work"})
self.assertEqual(m[0]["usage"]["windows"], {"seven_day": {"pct": 27.0, "resetsAt": 9e9, "at": 1000.0}})
self.assertEqual(m[1]["usage"]["windows"]["seven_day"]["pct"], 28.0)
self.assertEqual(m[1]["usage"]["windows"]["five_hour"]["pct"], 60.0)
self.assertTrue(all(x["derived"] for x in m))
# claude-probe's recorded ones are left as they are
kept = [{"event": "prompt", "at": 1200.0, "plan": {"planDisplayName": "Pro"}, "usage": None}]
self.assertEqual(calls.fill_marks(D, A, kept)[0]["plan"], {"planDisplayName": "Pro"})
def test_agent_and_adopted_calls(self):
t = time.time()
r = call_record("proc:4242@1730", "npm test", build_procs(t), at=t)
r["data"].update(agent="opencode", adopted=True, sessionId="oc:4100@1729")
calls.ingest(self.store, LAB, [r])
v = calls.conversation_calls(self.store, "oc:4100@1729")
self.assertEqual((v[0]["agent"], v[0]["adopted"]), ("opencode", True))
def test_part_labels(self):
self.assertEqual(calls.part_label("npm run build 2>&1", "npm"), "npm run build")
self.assertEqual(calls.part_label("git push origin HEAD", "git"), "git push")
self.assertEqual(calls.part_label("/usr/bin/python3 -m http.server", "python3"),
"python3")
self.assertEqual(calls.part_label("tail -20", "tail"), "tail")
class CallReadCacheTests(unittest.TestCase):
"""GET /calls is polled every 5 s while a conversation runs: each call's
view is cached on (updated, len(data)), a ``since`` read returns only what
was ingested after it, and the turn marks are memoized."""
def setUp(self):
self.deps = Deps()
self.store = self.deps.perf_store
calls._views.clear()
calls._marks_cache.clear()
p = mock.patch.object(views, "titles", lambda deps: {})
p.start()
self.addCleanup(p.stop)
def ingest_at(self, now, *records):
with mock.patch.object(calls.time, "time", return_value=now):
calls.ingest(self.store, LAB, list(records))
def data(self, tid):
return self.store.query("SELECT data FROM perf_calls WHERE tool_use_id = ?", (tid,))[0][0]
def set_data(self, tid, raw):
self.store.write([("UPDATE perf_calls SET data = ? WHERE tool_use_id = ?", [(raw, tid)])])
def test_a_view_is_rebuilt_only_when_updated_or_the_data_length_moves(self):
t = time.time() - 60
self.ingest_at(5000.0, call_record("toolu_1", BUILD, build_procs(t)[:2], at=t,
status="running", rid=1))
first = calls.conversation_calls(self.store, A)[0]
self.assertEqual(first["status"], "running")
self.assertIs(calls.conversation_calls(self.store, A)[0], first) # cached
# a newer version of the call (a new ingest: `updated` moves)
self.ingest_at(5010.0, call_record("toolu_1", BUILD, build_procs(t), at=t, rid=2))
done = calls.conversation_calls(self.store, A)[0]
self.assertIsNot(done, first)
self.assertEqual((done["status"], len(done["processes"])), ("done", 4))
# `updated` alone moves: rebuilt, same content
self.store.write([("UPDATE perf_calls SET updated = updated + 1 WHERE tool_use_id = ?",
[("toolu_1",)])])
again = calls.conversation_calls(self.store, A)[0]
self.assertIsNot(again, done)
self.assertEqual(again, done)
# `data` rewritten without touching `updated`, as dedup_procs_data does:
# an old row that still carried its procs, then stripped of them
old = json.loads(self.data("toolu_1"))
old["procs"] = build_procs(t)
self.set_data("toolu_1", json.dumps(old))
fat = calls.conversation_calls(self.store, A)[0]
self.assertIsNot(fat, again)
self.assertEqual(fat["processes"][0]["argv"], "/bin/bash -c eval 'cd /x && npm run build'")
self.assertEqual(calls.dedup_procs_data(self.store), 1)
slim = calls.conversation_calls(self.store, A)[0]
self.assertIsNot(slim, fat)
self.assertEqual(slim, again)
# a same-length rewrite with the same `updated` is, by design, not seen
same = self.data("toolu_1").replace('"status":"done"', '"status":"dune"')
self.set_data("toolu_1", same)
self.assertIs(calls.conversation_calls(self.store, A)[0], slim)
def test_the_cache_keeps_a_few_sessions(self):
t = time.time() - 60
sids = [f"s{i}" for i in range(calls.VIEW_CACHE_SESSIONS + 1)]
for i, sid in enumerate(sids):
r = call_record(f"toolu_{i}", "ls", build_procs(t)[:1], at=t, rid=i)
r["data"]["sessionId"] = sid
self.ingest_at(5000.0, r)
first = {sid: calls.conversation_calls(self.store, sid)[0] for sid in sids}
# the newest sessions are still cached, the first one fell off
self.assertIs(calls.conversation_calls(self.store, sids[-1])[0], first[sids[-1]])
self.assertIsNot(calls.conversation_calls(self.store, sids[0])[0], first[sids[0]])
def test_a_delta_returns_only_what_was_ingested_after_since(self):
t = time.time() - 60
self.ingest_at(1000.0,
call_record("toolu_1", BUILD, build_procs(t), at=t, rid=1),
call_record("toolu_2", "pytest -q", build_procs(t + 10)[:2], at=t + 10,
status="running", rid=2))
full, cursor = calls.calls_since(self.store, A)
self.assertEqual(([c["toolUseId"] for c in full], cursor), (["toolu_1", "toolu_2"], 1000.0))
# nothing new: no call, the cursor stays where the client put it
self.assertEqual(calls.calls_since(self.store, A, 1000.0), ([], 1000.0))
self.ingest_at(1010.0, call_record("toolu_2", "pytest -q", build_procs(t + 10), at=t + 10,
rid=3))
delta, cursor = calls.calls_since(self.store, A, 1000.0)
self.assertEqual([(c["toolUseId"], c["status"]) for c in delta], [("toolu_2", "done")])
self.assertEqual(cursor, 1010.0)
# the client's overlap (cursor - 30) brings both back, in start order
overlap, cursor = calls.calls_since(self.store, A, 1010.0 - 30)
self.assertEqual([c["toolUseId"] for c in overlap], ["toolu_1", "toolu_2"])
self.assertEqual(cursor, 1010.0)
# the delta refreshed the cache: a whole read reuses its view
self.assertIs(calls.conversation_calls(self.store, A)[1], delta[0])
# a conversation without calls
self.assertEqual(calls.calls_since(self.store, "nobody"), ([], None))
self.assertEqual(calls.calls_since(self.store, "nobody", 5.0), ([], 5.0))
def test_the_route_answers_whole_or_delta_with_marks_and_storage(self):
from perf import routes as perf_routes # noqa: PLC0415
import schemas # noqa: PLC0415
t = time.time() - 60
self.ingest_at(1000.0, call_record("toolu_1", BUILD, build_procs(t), at=t, rid=1),
{"id": 2, "at": 1, "kind": "mark", "session": A, "key": "k1", "data": {
"event": "prompt", "sessionId": A, "promptId": "p1", "at": 100.0,
"plan": {"planDisplayName": "Max"}, "usage": None}})
def get(since=None):
body = json.loads(perf_routes.perf_conversation_calls(self.deps, None, A, since).body)
schemas.PerfCalls.model_validate(body)
return body
whole = get()
self.assertEqual((whole["delta"], whole["cursor"], len(whole["calls"])), (False, 1000.0, 1))
self.assertEqual(whole["marks"][0]["plan"], {"planDisplayName": "Max"})
self.assertEqual(whole["storage"], {})
delta = get(1000.0)
self.assertEqual((delta["delta"], delta["cursor"], delta["calls"]), (True, 1000.0, []))
self.assertEqual(delta["marks"], whole["marks"]) # marks come whole, always
def test_turn_marks_are_kept_until_a_new_mark_or_the_ttl(self):
def mark(i, at):
return {"id": i, "at": 1, "kind": "mark", "session": A, "key": f"k{i}", "data": {
"event": "prompt", "sessionId": A, "promptId": f"p{i}", "at": at,
"plan": {"planDisplayName": "Max"}, "usage": None}}
self.ingest_at(1000.0, mark(1, 100.0))
with mock.patch.object(calls, "fill_marks", wraps=calls.fill_marks) as fill:
first = calls.turn_marks(self.deps, A)
self.assertIs(calls.turn_marks(self.deps, A), first)
self.assertEqual(fill.call_count, 1)
self.ingest_at(1010.0, mark(2, 200.0)) # a new turn: at once
self.assertEqual(len(calls.turn_marks(self.deps, A)), 2)
self.assertEqual(fill.call_count, 2)
with mock.patch.object(calls, "MARKS_TTL_S", 0.0): # past the TTL
calls.turn_marks(self.deps, A)
self.assertEqual(fill.call_count, 3)
# a conversation the probe never saw: derived once, then kept
derived = [{"event": "start", "promptId": None, "agentId": None, "at": 1.0,
"plan": None, "usage": None, "derived": True}]
with mock.patch.object(calls, "derived_marks", return_value=derived) as dm:
self.assertEqual(calls.turn_marks(self.deps, "other"), derived)
calls.turn_marks(self.deps, "other")
self.assertEqual(dm.call_count, 1)
# a failing derivation still answers (empty), the calls aren't held up
with mock.patch.object(calls, "derived_marks", side_effect=RuntimeError("boom")):
self.assertEqual(calls.turn_marks(self.deps, "third"), [])
if __name__ == "__main__":
unittest.main()