Skip to content

feat(telemetry): export per-table DB counters and trace the read-counter RPC - #758

Merged
mthines merged 6 commits into
mainfrom
feat/db-table-metrics
Nov 25, 2026
Merged

mthines merged 6 commits into
mainfrom
feat/db-table-metrics

Conversation

@mthines

@mthines mthines commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Why

00124 made read-counter updates on memories HOT to cut Supabase Disk IO, but nothing exported whether that worked — the evidence lives in pg_stat_user_tables / pg_statio_user_tables, readable only by pasting SQL into the Supabase editor. And the fire-and-forget lorekit_record_memory_reads RPC was the one DB write on every list/search/read path that emitted no span.

What changed

  • 00125 lorekit_db_table_stats() — service-role-only reader over a fixed allowlist of 7 request-path tables (memories, memory_read_daily, rate_limit_counters, audit_log, usage_events, api_tokens, memory_citations).
  • lorekit.db.table.* — 11 cumulative sums (tuple ins/upd/hot_upd/del, seq/idx scans, heap/idx block reads and hits, autovacuum runs) + 2 gauges (live/dead tuples), one bounded db.table attribute. Exported by the existing profiling function in the same POST as lorekit.db.query.*; otlp-metrics.ts learned gauges. HOT ratio = rate(tup_hot_upd) / rate(tup_upd).
  • recordMemoryReads now takes the request span and runs the RPC under a detached lorekit.memory.record_reads span (the audit.ts pattern), so a CALL lorekit_record_memory_reads CLIENT span reaches Dash0 without making the read wait.

How to verify

  • cd packages/mcp-core && npx vitest run src/telemetry src/edge (393 pass); node supabase/byod/generate.mjs --check

Notes for reviewers

No user-visible change, so no feature flag and no deployment-verify contract. User-facing docs and llms.txt: N/A — internal telemetry only (contributor docs in docs/otel.md + docs/key-files.md). The export stays OFF until an operator creates the Vault secrets lorekit_profiling_url / lorekit_profiling_key (manual step, documented in docs/otel.md).

Quality notes — reuse: 0 reuse, 0 extend, 13 new · ux: skipped (no UI file)
  • new · db-table-metrics.ts (+5 exports) — sibling of buildDbQueryMetrics, which maps pg_stat_statements; no existing pg_stat_user_tables reader
  • new · edge mirror _shared/telemetry/db-table-metrics.ts — required by the self-contained-Deno rule, drift-checked
  • new · 00125_db_table_stats.sql — lorekit_db_query_stats (00074) reads a different view
📋 Acceptance criteria — 10 criteria · 7 ✅ · 3 ⏭️ · 4 guardrails
Criterion Proof
⏭️ AC‑1 When the migrations are applied, lorekit_db_table_stats() shall return a row per existing allowlisted table whose update counter rises after an update, executable by service_role and not by anon/authenticated (§125 asserts it). check
✅ AC‑2 When stat rows are mapped, the system shall emit lorekit.db.table.* sums and live/dead tuple gauges, each point carrying db.table, and drop rows naming no table (mcp-core spec). check
✅ AC‑3 When a gauge metric is exported, the OTLP payload shall carry it under gauge and sums under sum (mcp-core spec over the edge exporter). check
✅ AC‑4 When the profiling function runs, it shall read lorekit_db_table_stats and export the table metrics in the same POST as the query metrics. check
✅ AC‑5 When reads are recorded for ≥ 1 id, the system shall open a detached CLIENT span and await its flush in the background; for 0 ids it opens none (mcp-core spec). check
⏭️ AC‑6 When the full SQL suite runs on a fresh PG16 cluster, every assertion shall pass, and the BYOD bootstrap shall report no drift. check
✅ AC‑7 When the edge parity spec runs, the new mapper pair shall be drift-checked and in sync. check
✅ AC‑8 When deno check runs over the edge functions, it shall not exceed the baseline. check
✅ AC‑9 When a reader opens docs/otel.md, it shall list every lorekit.db.table.* metric and the Vault step. check
⏭️ AC‑10 telemetry: CALL lorekit_record_memory_reads CLIENT span under the read's trace; lorekit.db.table.tup_hot_upd with db.table=memories. telemetry:`CALL
🛡️ G‑1 Do not modify: applied migrations supabase/migrations/00001–00124 — migrations are append-only (supabase/migrations/REVIEW.md) guardrail
🛡️ G‑2 Do not modify by hand: supabase/byod/bootstrap.sql, packages/web/public/llms.txt — generated files (CLAUDE.md) guardrail
🛡️ G‑3 Keep unchanged: every read endpoint's response and the lorekit_record_memory_reads signature — "No user-visible behaviour change" guardrail
🛡️ G‑4 Never: grant the reader to anon/authenticated; add a tenant-derived metric attribute — CLAUDE.md/docs/otel.md (no tenant dimension); weaken a test or edit sealed check definitions guardrail

⚠️ Verified with open items — 7 of 10 criteria proven by recorded test runs

Checks-only run: each criterion is a command run on this branch, and on the base first where it can run there. Not run on this machine: AC-1, AC-6, AC-10. Passes on the base too, so the run does not show the change: AC-8. Recorded by hand, not run by the script: AC-1, AC-6, AC-10.

8c96b4c · checks-only · 0 findings · updated 2026-11-25 19:02 UTC

Details

How I tested it. No UI file in the diff, so no browser or environment ran. A criterion is ✅ only when its command passed on the branch; the Before column is the same command on the base, where a fail shows the test catches the change. run in Recorded by means verify-comment.mjs --run executed the command and read its exit code; hand means the agent typed the result.

AC Command Before (base) After (branch) Evidence Recorded by
AC‑1 migrations.test.sql §125 on a throwaway PG16 cluster (docs/sandbox.md) + a committed insert/update probe fails (catches it) ⏭️ not run ran locally on PG16: §125 assertions green, probe rate_limit_counters ins/upd 2/3 → 3/4 (rises=yes); no committed runner — CI Integration smoke runs migrations.test.sql, the rises probe is local-only hand
AC‑2 cd packages/mcp-core && npx vitest run src/telemetry/db-table-metrics.spec.ts fails (catches it) ✅ pass base: Test Files 1 failed (1) → head: Tests 7 passed (7) run
AC‑3 cd packages/mcp-core && npx vitest run src/telemetry/otlp-metrics.spec.ts fails (catches it) ✅ pass base: Tests 1 failed | 1 passed (2) → head: Tests 2 passed (2) run
AC‑4 grep -q "rpc<DbTableStatRow\[\]>('lorekit_db_table_stats'" supabase/functions/profiling/index.ts && grep -q 'buildDbTableMetrics(tableRows, now)' supabase/functions/profiling/index.ts && echo 'profiling reads + exports table metrics' fails (catches it) ✅ pass base: exit 1 → head: profiling reads + exports table metrics run
AC‑5 cd packages/mcp-core && npx vitest run src/telemetry/memory-reads.spec.ts fails (catches it) ✅ pass base: Tests 3 failed (3) → head: Tests 3 passed (3) run
AC‑6 full migrations.test.sql on a throwaway PG16 cluster (docs/sandbox.md) && node supabase/byod/generate.mjs --check fails (catches it) ⏭️ not run ran locally: SQL exit=0, bootstrap=ok; no committed runner — CI Integration smoke re-runs it hand
AC‑7 grep -q "edge: 'supabase/functions/_shared/telemetry/db-table-metrics.ts', driftChecked: true" packages/cli/src/shared/mirror-pairs.mjs && cd packages/mcp-core && npx vitest run src/edge/edge-parity.spec.ts fails (catches it) ✅ pass base: exit 1 → head: Tests 38 passed (38) run
AC‑8 node scripts/ci/deno-check-functions.mjs ⚠️ passes (does not catch it) ✅ pass base: Edge typecheck: no function exceeds its baseline. → head: Edge typecheck: no function exceeds its baseline. run
AC‑9 for m in tup_ins tup_upd tup_hot_upd tup_del seq_scan idx_scan heap_blks_read heap_blks_hit idx_blks_read idx_blks_hit autovacuum_count live_tup dead_tup; do grep -q "lorekit.db.table.$m" docs/otel.md || exit 1; done; grep -q lorekit_profiling_key docs/otel.md && echo 'all 13 metrics + Vault step documented' fails (catches it) ✅ pass base: exit 1 → head: all 13 metrics + Vault step documented run
AC‑10 Dash0: CALL lorekit_record_memory_reads span + lorekit.db.table.tup_hot_upd{db.table=memories} n/a ⏭️ not run needs a deployed edge function (span) and the two Vault secrets (metrics); verify after merge hand

Re-run: /aw-verify run checks

🚦 Deployment contract — no flag (before/after), root spans lorekit.memories + lorekit.mcp on api
{
  "service": "api",
  "root_spans": ["lorekit.memories", "lorekit.mcp"],
  "env": "production",
  "reversibility": "redeploy",
  "model": "claude-opus-5-5"
}

Contract added after merge (atelier did not require one for a non-user-visible change); thresholds are release.yml defaults, untouched, and were not chosen from post-deploy numbers.

@mthines

mthines commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner Author

Atelier: Merged. And delivered. Build done, Ready done, Merge done, Deliver done.

Done: merged, and main's pipeline is green for the merge commit.

Atelier · head 38bde3d · updated Nov 25, 2026 7:26pm

Run details
Stage Outcome Head When Why
✅ Build done 8c96b4c Nov 25, 2026 7:08pm PR #758 opened; verify report complete; AC-10 telemetry unsatisfiable pre-deploy (carried to Needs you); not user-visible, no flag/contract
✅ Ready done 8c96b4c Nov 25, 2026 7:10pm undrafted; prepare: already green (CI green at head, 0 open threads, mergeable clean); proof complete (--proven)
✅ Merge done 8c96b4c Nov 25, 2026 7:11pm merged 38bde3d
✅ Deliver done 38bde3d Nov 25, 2026 7:26pm pipeline green

CI at 8c96b4c: 🟢 1 required check ran and passed at 8c96b4c (CI Summary)

Re-run /atelier <this PR> to resume at the first incomplete stage.

@mthines
mthines marked this pull request as ready for review November 25, 2026 19:08
@dash0-dev

dash0-dev Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Darkplane AutoMerge

Darkplane AutoMerge did not approve this pull request. Score 60.1 of 100, threshold 75. Blast radius 70, Evidence quality 80, Change footprint 30.


Evidence

Good Blast radius scored 70.

The change is mostly additive. It adds a service-role-only SQL function in 00125_db_table_stats.sql with a fixed table allowlist and no table locks, plus new mappers in db-table-metrics.ts and a second concurrent read in profiling/index.ts. It also touches the hot read path: recordMemoryReads in memory-reads.ts gained a span argument, so the four memories handlers and mcp/tools.ts changed. That tracing is wrapped in try/catch, but it spans many files, and the migration, bootstrap.sql and the shared otlp-metrics.ts would all need reverting together.

Good Evidence quality scored 80.

CI is green, including Typecheck, Test & Lint (affected), Edge typecheck (deno check), Integration smoke (local Supabase) and Migration order. New specs cover db-table-metrics.ts, memory-reads.ts and otlp-metrics.ts, and the PR's verify report says they fail on base and pass on head. Gaps: there is no human review, the live telemetry check (AC-10) can't run before deploy, the "update counter rises" probe is local-only, and the profiling/index.ts wiring is checked only by grep.

Low Change footprint scored 30.

This is a hand-written feature spanning 21 files (about 1,080 lines). It adds migration 00125_db_table_stats.sql with a new security definer function, and new db-table-metrics.ts modules in supabase/functions/_shared/telemetry and packages/mcp-core. It also changes the shared OTLP builder in otlp-metrics.ts (a new gauge path), profiling/index.ts, memory-reads.ts and supabase/byod/bootstrap.sql. Mitigating factors: the new function is a read-only, service-role-only, fixed-allowlist query, the diff includes about 360 lines of tests, and the handler edits are one line each. I did not read the diffs for profiling/index.ts or memory-reads.ts.

An AI evaluator produced these scores from the diff, the repository history, and the pull request text. The pull request text is author-controlled, so treat the scores as signals rather than proof. Reviewed for commit 8c96b4c.

Was this decision right? Give feedback

@mthines
mthines merged commit 38bde3d into main Nov 25, 2026
20 checks passed
@mthines

mthines commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner Author
DEPLOYMENT ESCALATE
change:   feat(telemetry): export per-table DB counters and trace the read-counter RPC (#758) · flag none · production
mode:     no flag — before/after only, attribution weaker
deploy:   live at 2026-11-25T19:36:33Z
baseline: 329 requests, 0 errors, 442.8 ms
step   test n/err/ms    control n/err/ms   verdict
100 %  92/3/2859.1      0/0/0              ROLLBACK latency x6.5 (+2416 ms) vs baseline
criteria: 10 on the PR, 4 guardrails
  ⏭️ AC-1 check — not watched
  ✅ AC-2 check — not watched
  ✅ AC-3 check — not watched
  ✅ AC-4 check — not watched
  ✅ AC-5 check — not watched
  ⏭️ AC-6 check — not watched
  ✅ AC-7 check — not watched
  ✅ AC-8 check — not watched
  ✅ AC-9 check — not watched
  ⏭️ AC-10 telemetry `CALL — not watched
  G-1 guardrail — guardrail
  G-2 guardrail — guardrail
  G-3 guardrail — guardrail
  G-4 guardrail — guardrail
result:   ROLLBACK verdict (latency x6.5 (+2416 ms) vs baseline); rollback needs a human (reversibility: redeploy)
cause:    not this change — DB pressure. Self time unchanged (3–24 ms/request); all extra latency is lorekit.io.wait_ms. /memories like-for-like 954 → 1123 ms (+18%); the 6.5× is route mix (baseline pooled fast /mcp, after window mostly /memories). Untouched /memories/activity 5 → 2613 ms; the 3 errors are statement timeouts in lorekit_memory_delivery_cost (/memories/utility). Revert PR NOT opened: reverting would not fix it.
notify:   PR comment only (release.yml notify: [])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant