Files
gabrielvidalandClaude Opus 5.5 8796561113 feat(indexer): parser version per row; a bump re-parses in the background
A PARSER_VERSION change used to wipe every summary and re-parse all ~6,600
conversations (lists partial for 11-18 min), and during deploy.sh's
blue-green overlap the old and new containers each saw a mismatch and wiped
each other, leaving the rows the old one wrote last stale until their file
changed.

- `transcripts.parser_version` (INTEGER), written with every parse. The
  first start adds it with the global `meta` version (46 on the lab) as its
  DEFAULT: O(1), no row rewritten, nothing re-parsed. The meta row stays
  (a pre-per-row image beside this one wipes on a mismatch).
- A covering index `transcripts_book (path, mtime, size, parser_version)`:
  the sweep's change index and the upgrade queue never read the blobs.
- A bump wipes nothing: every row keeps serving its summary while
  `Indexer.upgrade_rows`, between two sweeps, re-parses older rows most
  recently active first at REPARSE_DUTY (env, 0.5) of a core, written
  compare-and-set on (mtime, size, version < own). A container never
  re-parses a row a newer version wrote, so no ping-pong.
- MIN_SERVABLE_VERSION (0): rows below it are hidden and re-parsed by the
  sweep first, for a change that can't be served stale.
- aiagent_index_rows_stale / aiagent_index_rows_upgraded_total metrics.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:56:08 +01:00

150 lines
6.2 KiB
Python

"""The hub's Prometheus registry — one place that names every metric.
Its own ``CollectorRegistry`` (not the library's global one), so a test that
builds the app twice never trips over a duplicate name, plus the stock
process / platform / GC collectors (``process_cpu_seconds_total``,
``process_resident_memory_bytes`` …).
**Labels stay bounded.** ``route`` is a template (``/api/conversation/{sid}``),
never a raw path; ``caller`` is one of :data:`CALLERS`; ``page`` comes from the
browser but is checked against a template shape and folded to ``other`` past
:data:`MAX_PAGES` distinct values. A label that could take a conversation id or
a user id would grow the series without bound — keep it that way."""
from __future__ import annotations
import re
import threading
from prometheus_client import (CollectorRegistry, Counter, Gauge, Histogram,
GCCollector, PlatformCollector, ProcessCollector)
from prometheus_client.exposition import generate_latest
REGISTRY = CollectorRegistry(auto_describe=True)
ProcessCollector(registry=REGISTRY)
PlatformCollector(registry=REGISTRY)
GCCollector(registry=REGISTRY)
#: Who made a request, coarsely: the owner (browser, CLI or host), a guest, a
#: worker's tunnel or link, Prometheus itself, nobody signed in.
CALLERS = ("owner", "guest", "worker", "metrics", "anon")
# Seconds. The low end is where a cached list answers, the high end the
# "/api/health took 43 s" incidents (CLAUDE.md → Performance).
_LATENCY = (.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 30)
_LAG = (.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10)
_VITAL = (.05, .1, .25, .5, 1, 2, 3, 4, 6, 10, 20)
HTTP = Histogram(
"aiagent_http_request_duration_seconds",
"Time to answer one HTTP request, by route template.",
("route", "method", "caller", "code"), buckets=_LATENCY, registry=REGISTRY)
STREAMS = Gauge(
"aiagent_http_streams_open",
"Long-lived requests open now (SSE streams, worker long-polls).",
("route",), registry=REGISTRY)
LOOP_LAG = Histogram(
"aiagent_event_loop_lag_seconds",
"How late the event loop ran a timer: the time nothing else was served.",
buckets=_LAG, registry=REGISTRY)
THREADS_BUSY = Gauge(
"aiagent_threadpool_busy",
"Worker threads busy running sync handlers (anyio's default limiter).",
registry=REGISTRY)
THREADS_SIZE = Gauge(
"aiagent_threadpool_size", "The sync-handler thread pool's size.", registry=REGISTRY)
SSE_SUBSCRIBERS = Gauge(
"aiagent_sse_subscribers", "Clients subscribed to the event hub now.", registry=REGISTRY)
SSE_EVENTS = Counter(
"aiagent_sse_events_total", "Events the hub fanned out, by type.", ("type",),
registry=REGISTRY)
SSE_RESUMES = Counter(
"aiagent_sse_resumes_total",
"Streams reopened with Last-Event-ID: replayed from the ring, or told to resync.",
("result",), registry=REGISTRY)
WATCH_TICK = Histogram(
"aiagent_watcher_tick_seconds",
"One transcript-watcher tick: stat what inotify reported, re-index, publish.",
buckets=_LATENCY, registry=REGISTRY)
WATCH_CHANGED = Counter(
"aiagent_watcher_transcripts_changed_total",
"Transcripts the watcher found changed and re-indexed.", registry=REGISTRY)
INDEX_ROWS_STALE = Gauge(
"aiagent_index_rows_stale",
"Stored summaries an older parser version wrote, still to re-parse.",
registry=REGISTRY)
INDEX_ROWS_UPGRADED = Counter(
"aiagent_index_rows_upgraded_total",
"Stored summaries the upgrade pass re-parsed at this parser version.",
registry=REGISTRY)
PUBLISH_LAG = Histogram(
"aiagent_transcript_publish_lag_seconds",
"From a transcript's write (its mtime) to the hub publishing it.",
buckets=_LAG, registry=REGISTRY)
MEMO_BUILD = Histogram(
"aiagent_memo_build_seconds",
"One whole-catalog build behind a _Memo (a cache miss), by builder.",
("memo",), buckets=_LATENCY, registry=REGISTRY)
CONV_READS = Counter(
"aiagent_conversation_reads_total",
"Open-thread reads: a delta from the client's rev, or the whole thread.",
("kind",), registry=REGISTRY)
RUNS_STARTED = Counter(
"aiagent_runs_started_total", "Conversations started through /api/spawn, by origin.",
("origin",), registry=REGISTRY)
# What the browser reports (telemetry/ingest.py).
WEB_VITAL = Histogram(
"aiagent_web_vital_seconds",
"Core web vitals the browser measured (LCP, INP, FCP, TTFB), by page and device.",
("name", "page", "device"), buckets=_VITAL, registry=REGISTRY)
WEB_CLS = Histogram(
"aiagent_web_cls", "Cumulative layout shift, by page and device.", ("page", "device"),
buckets=(.01, .05, .1, .25, .5, 1), registry=REGISTRY)
WEB_UPDATE_LAG = Histogram(
"aiagent_web_update_lag_seconds",
"From a transcript event reaching the browser to the open thread showing it.",
("device",), buckets=_LAG, registry=REGISTRY)
WEB_ERRORS = Counter(
"aiagent_web_errors_total", "Uncaught JS errors and rejections, by page.", ("page",),
registry=REGISTRY)
WEB_LONG_TASKS = Counter(
"aiagent_web_long_tasks_total", "Main-thread tasks over 50 ms, by page and device.",
("page", "device"), registry=REGISTRY)
WEB_STREAM = Counter(
"aiagent_web_stream_total",
"The browser's event stream: reconnects, resyncs, whole-thread reads.",
("kind",), registry=REGISTRY)
USAGE_EVENTS = Counter(
"aiagent_usage_events_total", "Feature-usage records taken in, by kind.", ("kind",),
registry=REGISTRY)
DEVICES = ("phone", "tablet", "desktop")
MAX_PAGES = 80
_PAGE_RE = re.compile(r"^/[A-Za-z0-9/:_\-.*]{0,80}$")
_pages: set[str] = set()
_pages_lock = threading.Lock()
def page_label(page: object) -> str:
"""A browser-sent page template as a label: its shape checked, the count of
distinct ones capped (past :data:`MAX_PAGES` everything new is ``other``)."""
if not isinstance(page, str) or not _PAGE_RE.match(page):
return "other"
with _pages_lock:
if page in _pages:
return page
if len(_pages) >= MAX_PAGES:
return "other"
_pages.add(page)
return page
def device_label(device: object) -> str:
return device if device in DEVICES else "desktop"
def render() -> bytes:
"""The text exposition of every metric (``GET /api/metrics``)."""
return generate_latest(REGISTRY)