You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
feat(telemetry): export per-table DB counters and trace the read-counter RPC - #758
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
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.
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
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.
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.
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.
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.
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: [])
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
00124 made read-counter updates on
memoriesHOT to cut Supabase Disk IO, but nothing exported whether that worked — the evidence lives inpg_stat_user_tables/pg_statio_user_tables, readable only by pasting SQL into the Supabase editor. And the fire-and-forgetlorekit_record_memory_readsRPC was the one DB write on every list/search/read path that emitted no span.What changed
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 boundeddb.tableattribute. Exported by the existingprofilingfunction in the same POST aslorekit.db.query.*;otlp-metrics.tslearned gauges. HOT ratio =rate(tup_hot_upd) / rate(tup_upd).recordMemoryReadsnow takes the request span and runs the RPC under a detachedlorekit.memory.record_readsspan (theaudit.tspattern), so aCALL lorekit_record_memory_readsCLIENT 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 --checkNotes 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 indocs/otel.md+docs/key-files.md). The export stays OFF until an operator creates the Vault secretslorekit_profiling_url/lorekit_profiling_key(manual step, documented indocs/otel.md).Quality notes — reuse: 0 reuse, 0 extend, 13 new · ux: skipped (no UI file)
db-table-metrics.ts(+5 exports) — sibling ofbuildDbQueryMetrics, which maps pg_stat_statements; no existing pg_stat_user_tables reader_shared/telemetry/db-table-metrics.ts— required by the self-contained-Deno rule, drift-checked00125_db_table_stats.sql—lorekit_db_query_stats(00074) reads a different view📋 Acceptance criteria — 10 criteria · 7 ✅ · 3 ⏭️ · 4 guardrails
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).lorekit.db.table.*sums and live/dead tuple gauges, each point carryingdb.table, and drop rows naming no table (mcp-core spec).gaugeand sums undersum(mcp-core spec over the edge exporter).lorekit_db_table_statsand export the table metrics in the same POST as the query metrics.deno checkruns over the edge functions, it shall not exceed the baseline.lorekit.db.table.*metric and the Vault step.CALL lorekit_record_memory_readsCLIENT span under the read's trace;lorekit.db.table.tup_hot_updwithdb.table=memories.supabase/migrations/00001–00124— migrations are append-only (supabase/migrations/REVIEW.md)supabase/byod/bootstrap.sql,packages/web/public/llms.txt— generated files (CLAUDE.md)lorekit_record_memory_readssignature — "No user-visible behaviour change"anon/authenticated; add a tenant-derived metric attribute — CLAUDE.md/docs/otel.md (no tenant dimension); weaken a test or edit sealed check definitionsChecks-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 UTCDetails
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.
runin Recorded by meansverify-comment.mjs --runexecuted the command and read its exit code;handmeans the agent typed the result.migrations.test.sql §125 on a throwaway PG16 cluster (docs/sandbox.md) + a committed insert/update probecd packages/mcp-core && npx vitest run src/telemetry/db-table-metrics.spec.tscd packages/mcp-core && npx vitest run src/telemetry/otlp-metrics.spec.tsgrep -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'cd packages/mcp-core && npx vitest run src/telemetry/memory-reads.spec.tsfull migrations.test.sql on a throwaway PG16 cluster (docs/sandbox.md) && node supabase/byod/generate.mjs --checkgrep -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.tsnode scripts/ci/deno-check-functions.mjsfor 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'Dash0: CALL lorekit_record_memory_reads span + lorekit.db.table.tup_hot_upd{db.table=memories}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.ymldefaults, untouched, and were not chosen from post-deploy numbers.