- /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>
90 lines
3.7 KiB
Python
90 lines
3.7 KiB
Python
"""A build-once-per-version memo shared by the catalog rollups."""
|
||
|
||
import threading
|
||
import time
|
||
|
||
from telemetry import metrics as tm
|
||
|
||
|
||
class _Memo:
|
||
"""One expensive whole-catalog build, memoized on a version key.
|
||
|
||
Every list/detail refetch the SSE bus triggers lands right after a
|
||
transcript write (a version bump), so several requests used to miss the
|
||
cache together and each run the same full build in parallel — N clients =
|
||
N× the CPU on one GIL. Callers with the same key now share a single build:
|
||
the first builds, the rest wait on the lock and take its result.
|
||
|
||
**Stale-while-revalidate** (``max_stale`` seconds, off by default): the
|
||
key splits in two. ``key`` is the *hard* part — a change rebuilds at once,
|
||
single-flight as above. ``soft`` (``get(key, …, soft=v)``, typically
|
||
``summaries_version``, which moves on every transcript write) only ages
|
||
the value: one whose hard part matches and that is younger than
|
||
``max_stale`` is returned as-is whatever its soft part; past that age the
|
||
first caller rebuilds, and every caller arriving meanwhile with the same
|
||
hard part gets the stale value instead of waiting on the lock. The age
|
||
counts from the build's *start* (the snapshot it read). For rollups that
|
||
may lag a minute (project $, the related index), not for anything a
|
||
click must see change.
|
||
|
||
``slots``: how many hard keys are kept (the newest builds). 1 (the
|
||
default) = one value at a time; more stops two views of the same rollup
|
||
(``?account=`` A from one tab, B from another) from evicting each other
|
||
on every request."""
|
||
|
||
def __init__(self, build, max_stale: float | None = None, slots: int = 1):
|
||
self._build = build
|
||
# The builder's name labels its cache misses (aiagent_memo_build_seconds).
|
||
self._name = getattr(build, "__name__", "memo")[:40]
|
||
self._lock = threading.Lock()
|
||
self._max_stale = max_stale
|
||
self._slots = max(1, slots)
|
||
# hard key → (soft, built_at, value); replaced whole (never mutated),
|
||
# so a lock-free read sees a consistent dict
|
||
self._hits: dict = {}
|
||
|
||
def _usable(self, hit, soft, now: float) -> bool:
|
||
return hit is not None and (hit[0] == soft or (
|
||
self._max_stale is not None and now - hit[1] < self._max_stale))
|
||
|
||
def get(self, key, *args, soft=None):
|
||
hit = self._hits.get(key)
|
||
if hit is not None:
|
||
if hit[0] == soft:
|
||
return hit[2]
|
||
if self._max_stale is not None:
|
||
if time.monotonic() - hit[1] < self._max_stale:
|
||
return hit[2]
|
||
# Too old: the first caller rebuilds, the rest keep the stale value.
|
||
if not self._lock.acquire(blocking=False):
|
||
return hit[2]
|
||
try:
|
||
return self._build_locked(key, soft, args)
|
||
finally:
|
||
self._lock.release()
|
||
with self._lock:
|
||
return self._build_locked(key, soft, args)
|
||
|
||
def _build_locked(self, key, soft, args):
|
||
started = time.monotonic()
|
||
hit = self._hits.get(key)
|
||
if self._usable(hit, soft, started):
|
||
return hit[2]
|
||
t0 = time.perf_counter()
|
||
val = self._build(*args)
|
||
hits = {k: v for k, v in self._hits.items() if k != key}
|
||
while len(hits) >= self._slots:
|
||
hits.pop(min(hits, key=lambda k: hits[k][1])) # the oldest build
|
||
hits[key] = (soft, started, val)
|
||
self._hits = hits
|
||
try:
|
||
tm.MEMO_BUILD.labels(self._name).observe(time.perf_counter() - t0)
|
||
except Exception:
|
||
pass
|
||
return val
|
||
|
||
def clear(self) -> None:
|
||
"""Forget every value (tests)."""
|
||
with self._lock:
|
||
self._hits = {}
|