From 28095ed25c9ac365ffbac166bbc1b2ba2991562e Mon Sep 17 00:00:00 2001 From: mthines Date: Wed, 25 Nov 2026 19:42:45 +0100 Subject: [PATCH 1/6] feat(db): add lorekit_db_table_stats reader for per-table counters (00125) --- supabase/byod/bootstrap.sql | 113 ++++++++++++++++++- supabase/migrations/00125_db_table_stats.sql | 102 +++++++++++++++++ supabase/tests/migrations.test.sql | 63 +++++++++++ 3 files changed, 277 insertions(+), 1 deletion(-) create mode 100644 supabase/migrations/00125_db_table_stats.sql diff --git a/supabase/byod/bootstrap.sql b/supabase/byod/bootstrap.sql index 1388d19b..08b468ce 100644 --- a/supabase/byod/bootstrap.sql +++ b/supabase/byod/bootstrap.sql @@ -2,7 +2,7 @@ -- -- ⚠ GENERATED FILE — DO NOT EDIT BY HAND. -- Generated by `node supabase/byod/generate.mjs` from the --- 119 migrations in supabase/migrations/ (newest: 00124_memories_hot_read_counters.sql). +-- 120 migrations in supabase/migrations/ (newest: 00125_db_table_stats.sql). -- CI fails when this file and the migrations disagree; edit a migration (or add -- one) and regenerate instead. -- @@ -26995,6 +26995,117 @@ insert into supabase_migrations.schema_migrations (version, name) values ('00124', 'memories_hot_read_counters') on conflict (version) do nothing; +-- ───────────────────────────────────────────────────────────────────────────── +-- 00125_db_table_stats.sql +-- ───────────────────────────────────────────────────────────────────────────── + +-- 00125 — per-table counters for the query-profiling export. +-- +-- WHY. 00124 made read-counter updates on `memories` HOT to cut the project's +-- Disk IO. Whether that worked — and which table the IO goes to — lives in +-- `pg_stat_user_tables` / `pg_statio_user_tables`, which nothing exported: +-- checking meant an operator pasting SQL into the Supabase editor. The +-- `profiling` Edge Function (00074) already ships `pg_stat_statements` to Dash0 +-- on a pg_cron tick; this adds a second reader it calls on the same tick, so +-- the HOT ratio (rate(tup_hot_upd) / rate(tup_upd)), dead tuples and disk block +-- reads per table become `lorekit.db.table.*` metrics beside +-- `lorekit.db.query.*`. +-- +-- WHAT. `lorekit_db_table_stats()` — one row per table in a FIXED allowlist, +-- service-role only. Same posture as `lorekit_db_query_stats()`: +-- * an operator surface: the counters describe the cluster, not a caller's +-- data, so `anon` / `authenticated` cannot execute it; +-- * bounded: every row becomes a metric SERIES in Dash0, so the table list is +-- a constant here, never "every table" (a new table would silently grow the +-- bill) and never caller-supplied; +-- * cumulative: the counters are exported as they are, with the database's +-- `stats_reset` as each series start, so Dash0 does the differencing and +-- reads a reset as a new series (00074, otlp-metrics.ts). +-- +-- The allowlist is the tables written on the request path: `memories` (writes +-- and the 00124 read counters), `memory_read_daily` (the daily read rollup), +-- `rate_limit_counters` (every authenticated request, UNLOGGED since 00124), +-- `audit_log`, `usage_events`, `api_tokens` and `memory_citations`. A table in +-- the list that does not exist (BYOD, an older schema) simply returns no row. +-- +-- Turned on by the same two Vault secrets as the query export +-- (`lorekit_profiling_url`, `lorekit_profiling_key` — see 00074). This +-- migration turns nothing on by itself. +-- +-- LOCK WINDOW. Creates one function and sets its grants: catalog rows only, no +-- lock on any table. + +create or replace function lorekit_db_table_stats() +returns table ( + table_name text, + n_tup_ins bigint, + n_tup_upd bigint, + n_tup_hot_upd bigint, + n_tup_del bigint, + n_live_tup bigint, + n_dead_tup bigint, + seq_scan bigint, + idx_scan bigint, + autovacuum_count bigint, + heap_blks_read bigint, + heap_blks_hit bigint, + idx_blks_read bigint, + idx_blks_hit bigint, + stats_since timestamptz +) +language sql +stable +security definer +set search_path = public, pg_catalog +as $$ + select + s.relname::text, + s.n_tup_ins, + s.n_tup_upd, + s.n_tup_hot_upd, + s.n_tup_del, + s.n_live_tup, + s.n_dead_tup, + s.seq_scan, + -- NULL for a table with no index; 0 is the honest cumulative value. + coalesce(s.idx_scan, 0), + s.autovacuum_count, + io.heap_blks_read, + io.heap_blks_hit, + coalesce(io.idx_blks_read, 0), + coalesce(io.idx_blks_hit, 0), + -- Table counters reset with the database's stats (pg_stat_reset()), so + -- the database's reset time is each series' start. NULL until a reset has + -- ever happened; the mapper reads that as "since the epoch". + (select d.stats_reset from pg_stat_database d where d.datname = current_database()) + from pg_stat_user_tables s + join pg_statio_user_tables io on io.relid = s.relid + where s.schemaname = 'public' + and s.relname in ( + 'memories', + 'memory_read_daily', + 'rate_limit_counters', + 'audit_log', + 'usage_events', + 'api_tokens', + 'memory_citations' + ) + order by s.relname; +$$; + +comment on function lorekit_db_table_stats() is + 'Cumulative pg_stat_user_tables + pg_statio_user_tables counters for a fixed ' + 'allowlist of request-path tables, for the profiling Edge Function.'; + +-- Service-role only — the same grant shape as lorekit_db_query_stats (00074). +revoke all on function lorekit_db_table_stats() from public; +revoke all on function lorekit_db_table_stats() from anon, authenticated; +grant execute on function lorekit_db_table_stats() to service_role; +; +insert into supabase_migrations.schema_migrations (version, name) +values ('00125', 'db_table_stats') +on conflict (version) do nothing; + -- ───────────────────────────────────────────────────────────────────────────── -- storage-overlay.sql — BYOD only: drop foreign keys into auth.users -- ───────────────────────────────────────────────────────────────────────────── diff --git a/supabase/migrations/00125_db_table_stats.sql b/supabase/migrations/00125_db_table_stats.sql new file mode 100644 index 00000000..132bfaf6 --- /dev/null +++ b/supabase/migrations/00125_db_table_stats.sql @@ -0,0 +1,102 @@ +-- 00125 — per-table counters for the query-profiling export. +-- +-- WHY. 00124 made read-counter updates on `memories` HOT to cut the project's +-- Disk IO. Whether that worked — and which table the IO goes to — lives in +-- `pg_stat_user_tables` / `pg_statio_user_tables`, which nothing exported: +-- checking meant an operator pasting SQL into the Supabase editor. The +-- `profiling` Edge Function (00074) already ships `pg_stat_statements` to Dash0 +-- on a pg_cron tick; this adds a second reader it calls on the same tick, so +-- the HOT ratio (rate(tup_hot_upd) / rate(tup_upd)), dead tuples and disk block +-- reads per table become `lorekit.db.table.*` metrics beside +-- `lorekit.db.query.*`. +-- +-- WHAT. `lorekit_db_table_stats()` — one row per table in a FIXED allowlist, +-- service-role only. Same posture as `lorekit_db_query_stats()`: +-- * an operator surface: the counters describe the cluster, not a caller's +-- data, so `anon` / `authenticated` cannot execute it; +-- * bounded: every row becomes a metric SERIES in Dash0, so the table list is +-- a constant here, never "every table" (a new table would silently grow the +-- bill) and never caller-supplied; +-- * cumulative: the counters are exported as they are, with the database's +-- `stats_reset` as each series start, so Dash0 does the differencing and +-- reads a reset as a new series (00074, otlp-metrics.ts). +-- +-- The allowlist is the tables written on the request path: `memories` (writes +-- and the 00124 read counters), `memory_read_daily` (the daily read rollup), +-- `rate_limit_counters` (every authenticated request, UNLOGGED since 00124), +-- `audit_log`, `usage_events`, `api_tokens` and `memory_citations`. A table in +-- the list that does not exist (BYOD, an older schema) simply returns no row. +-- +-- Turned on by the same two Vault secrets as the query export +-- (`lorekit_profiling_url`, `lorekit_profiling_key` — see 00074). This +-- migration turns nothing on by itself. +-- +-- LOCK WINDOW. Creates one function and sets its grants: catalog rows only, no +-- lock on any table. + +create or replace function lorekit_db_table_stats() +returns table ( + table_name text, + n_tup_ins bigint, + n_tup_upd bigint, + n_tup_hot_upd bigint, + n_tup_del bigint, + n_live_tup bigint, + n_dead_tup bigint, + seq_scan bigint, + idx_scan bigint, + autovacuum_count bigint, + heap_blks_read bigint, + heap_blks_hit bigint, + idx_blks_read bigint, + idx_blks_hit bigint, + stats_since timestamptz +) +language sql +stable +security definer +set search_path = public, pg_catalog +as $$ + select + s.relname::text, + s.n_tup_ins, + s.n_tup_upd, + s.n_tup_hot_upd, + s.n_tup_del, + s.n_live_tup, + s.n_dead_tup, + s.seq_scan, + -- NULL for a table with no index; 0 is the honest cumulative value. + coalesce(s.idx_scan, 0), + s.autovacuum_count, + io.heap_blks_read, + io.heap_blks_hit, + coalesce(io.idx_blks_read, 0), + coalesce(io.idx_blks_hit, 0), + -- Table counters reset with the database's stats (pg_stat_reset()), so + -- the database's reset time is each series' start. NULL until a reset has + -- ever happened; the mapper reads that as "since the epoch". + (select d.stats_reset from pg_stat_database d where d.datname = current_database()) + from pg_stat_user_tables s + join pg_statio_user_tables io on io.relid = s.relid + where s.schemaname = 'public' + and s.relname in ( + 'memories', + 'memory_read_daily', + 'rate_limit_counters', + 'audit_log', + 'usage_events', + 'api_tokens', + 'memory_citations' + ) + order by s.relname; +$$; + +comment on function lorekit_db_table_stats() is + 'Cumulative pg_stat_user_tables + pg_statio_user_tables counters for a fixed ' + 'allowlist of request-path tables, for the profiling Edge Function.'; + +-- Service-role only — the same grant shape as lorekit_db_query_stats (00074). +revoke all on function lorekit_db_table_stats() from public; +revoke all on function lorekit_db_table_stats() from anon, authenticated; +grant execute on function lorekit_db_table_stats() to service_role; diff --git a/supabase/tests/migrations.test.sql b/supabase/tests/migrations.test.sql index 3db30a99..245c26b4 100644 --- a/supabase/tests/migrations.test.sql +++ b/supabase/tests/migrations.test.sql @@ -12501,6 +12501,69 @@ end; $$; +-- ── 125. per-table stats reader is bounded, operator-only and faithful (00125) ── +-- `lorekit_db_table_stats()` feeds `lorekit.db.table.*`. Three properties: +-- it is unreachable from PostgREST's tenant roles (it describes the cluster), +-- it returns exactly the allowlisted tables (every row is a metric series), and +-- each value is the catalog's own counter, not a re-derivation. A counter +-- rising after a write is NOT assertable here: this file is one transaction +-- and Postgres publishes table stats only when a transaction ends. +do $$ +declare + v_count int; + v_bad text; + v_allowed text[] := array['api_tokens', 'audit_log', 'memories', 'memory_citations', + 'memory_read_daily', 'rate_limit_counters', 'usage_events']; +begin + select count(*) into v_count + from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname = 'public' and p.proname = 'lorekit_db_table_stats' and p.prosecdef; + assert v_count = 1, + format('125 AC-1: lorekit_db_table_stats must exist once as SECURITY DEFINER (found %s)', v_count); + + assert not has_function_privilege('anon', 'lorekit_db_table_stats()', 'execute'), + '125 AC-1: anon must NOT be able to execute lorekit_db_table_stats'; + assert not has_function_privilege('authenticated', 'lorekit_db_table_stats()', 'execute'), + '125 AC-1: authenticated must NOT be able to execute lorekit_db_table_stats'; + assert has_function_privilege('service_role', 'lorekit_db_table_stats()', 'execute'), + '125 AC-1: service_role MUST be able to execute lorekit_db_table_stats'; + + -- Exactly the allowlisted tables that exist — no more (cardinality), no + -- fewer (a silently missing series looks like a quiet table). + select string_agg(table_name, ',' order by table_name) into v_bad + from lorekit_db_table_stats() where table_name <> all (v_allowed); + assert v_bad is null, format('125 AC-1: a table outside the allowlist was returned: %s', v_bad); + + select count(*) into v_count from lorekit_db_table_stats(); + assert v_count = (select count(*) from pg_stat_user_tables + where schemaname = 'public' and relname = any (v_allowed)), + format('125 AC-1: expected one row per existing allowlisted table, got %s', v_count); + assert v_count = cardinality(v_allowed), + format('125 AC-1: every allowlisted table exists in this schema, so all %s must be returned (got %s)', + cardinality(v_allowed), v_count); + + -- Faithful: each counter is the catalog's value (idx counters coalesced). + perform pg_stat_clear_snapshot(); + select string_agg(r.table_name, ',') into v_bad + from lorekit_db_table_stats() r + join pg_stat_user_tables s on s.schemaname = 'public' and s.relname = r.table_name + join pg_statio_user_tables io on io.relid = s.relid + where (r.n_tup_ins, r.n_tup_upd, r.n_tup_hot_upd, r.n_tup_del, r.n_live_tup, r.n_dead_tup, + r.seq_scan, r.idx_scan, r.autovacuum_count, + r.heap_blks_read, r.heap_blks_hit, r.idx_blks_read, r.idx_blks_hit) + is distinct from + (s.n_tup_ins, s.n_tup_upd, s.n_tup_hot_upd, s.n_tup_del, s.n_live_tup, s.n_dead_tup, + s.seq_scan, coalesce(s.idx_scan, 0), s.autovacuum_count, + io.heap_blks_read, io.heap_blks_hit, coalesce(io.idx_blks_read, 0), coalesce(io.idx_blks_hit, 0)); + assert v_bad is null, format('125 AC-1: counters differ from pg_stat_user_tables for: %s', v_bad); + + assert not exists (select 1 from lorekit_db_table_stats() + where stats_since is distinct from + (select stats_reset from pg_stat_database where datname = current_database())), + '125 AC-1: stats_since must be this database''s stats_reset'; +end; +$$; + rollback; \echo 'migrations.test.sql: all assertions passed' From 68e034568242a5c468e59c34a923577ad51892c6 Mon Sep 17 00:00:00 2001 From: mthines Date: Wed, 25 Nov 2026 19:44:40 +0100 Subject: [PATCH 2/6] feat(profiling): export lorekit.db.table.* per-table counters beside query stats --- packages/cli/src/shared/mirror-pairs.mjs | 1 + .../src/telemetry/db-table-metrics.spec.ts | 93 ++++++++++++ .../src/telemetry/db-table-metrics.ts | 134 +++++++++++++++++ .../src/telemetry/otlp-metrics.spec.ts | 75 ++++++++++ .../_shared/telemetry/db-table-metrics.ts | 140 ++++++++++++++++++ .../_shared/telemetry/otlp-metrics.ts | 56 ++++--- supabase/functions/profiling/index.ts | 36 +++-- 7 files changed, 502 insertions(+), 33 deletions(-) create mode 100644 packages/mcp-core/src/telemetry/db-table-metrics.spec.ts create mode 100644 packages/mcp-core/src/telemetry/db-table-metrics.ts create mode 100644 packages/mcp-core/src/telemetry/otlp-metrics.spec.ts create mode 100644 supabase/functions/_shared/telemetry/db-table-metrics.ts diff --git a/packages/cli/src/shared/mirror-pairs.mjs b/packages/cli/src/shared/mirror-pairs.mjs index c19e7002..bd2b7d30 100644 --- a/packages/cli/src/shared/mirror-pairs.mjs +++ b/packages/cli/src/shared/mirror-pairs.mjs @@ -87,6 +87,7 @@ export const mirrorPairs = [ { core: 'packages/mcp-core/src/auth/account-wide-tools.ts', edge: 'supabase/functions/_shared/auth/account-wide-tools.ts', driftChecked: true }, { core: 'packages/mcp-core/src/telemetry/io-ledger.ts', edge: 'supabase/functions/_shared/telemetry/io-ledger.ts', driftChecked: true }, { core: 'packages/mcp-core/src/telemetry/db-query-metrics.ts', edge: 'supabase/functions/_shared/telemetry/db-query-metrics.ts', driftChecked: true }, + { core: 'packages/mcp-core/src/telemetry/db-table-metrics.ts', edge: 'supabase/functions/_shared/telemetry/db-table-metrics.ts', driftChecked: true }, // Retention-policy candidate/precedence logic. The SQL RPC // (`lorekit_groom_candidates`, migration 00088) is authoritative; this is the // unit-testable mirror the edge groom/policy handlers use to resolve a diff --git a/packages/mcp-core/src/telemetry/db-table-metrics.spec.ts b/packages/mcp-core/src/telemetry/db-table-metrics.spec.ts new file mode 100644 index 00000000..aaf50645 --- /dev/null +++ b/packages/mcp-core/src/telemetry/db-table-metrics.spec.ts @@ -0,0 +1,93 @@ +import { describe, it, expect } from 'vitest'; + +import { buildDbTableMetrics, DB_TABLE_METRIC_NAMES, type DbTableStatRow } from './db-table-metrics.js'; + +const NOW = Date.parse('2026-11-25T17:00:00.000Z'); +const RESET = '2026-11-01T00:00:00.000Z'; + +function row(overrides: Partial = {}): DbTableStatRow { + return { + table_name: 'memories', + n_tup_ins: 100, + n_tup_upd: 50, + n_tup_hot_upd: 45, + n_tup_del: 2, + n_live_tup: 98, + n_dead_tup: 7, + seq_scan: 3, + idx_scan: 900, + autovacuum_count: 4, + heap_blks_read: 12, + heap_blks_hit: 3400, + idx_blks_read: 8, + idx_blks_hit: 5100, + stats_since: RESET, + ...overrides, + }; +} + +const metric = (rows: readonly DbTableStatRow[], name: string) => + buildDbTableMetrics(rows, NOW).find((m) => m.name === `lorekit.db.table.${name}`); + +describe('buildDbTableMetrics', () => { + it('emits every lorekit.db.table.* measure, one point per table', () => { + const metrics = buildDbTableMetrics([row(), row({ table_name: 'audit_log' })], NOW); + expect(metrics.map((m) => m.name)).toEqual(DB_TABLE_METRIC_NAMES); + expect(DB_TABLE_METRIC_NAMES).toEqual([ + 'lorekit.db.table.tup_ins', + 'lorekit.db.table.tup_upd', + 'lorekit.db.table.tup_hot_upd', + 'lorekit.db.table.tup_del', + 'lorekit.db.table.seq_scan', + 'lorekit.db.table.idx_scan', + 'lorekit.db.table.heap_blks_read', + 'lorekit.db.table.heap_blks_hit', + 'lorekit.db.table.idx_blks_read', + 'lorekit.db.table.idx_blks_hit', + 'lorekit.db.table.autovacuum_count', + 'lorekit.db.table.live_tup', + 'lorekit.db.table.dead_tup', + ]); + expect(metrics.every((m) => m.points.length === 2)).toBe(true); + }); + + it('carries each column into its own measure', () => { + expect(metric([row()], 'tup_upd')?.points[0].value).toBe(50); + expect(metric([row()], 'tup_hot_upd')?.points[0].value).toBe(45); + expect(metric([row()], 'heap_blks_read')?.points[0].value).toBe(12); + expect(metric([row()], 'idx_blks_hit')?.points[0].value).toBe(5100); + expect(metric([row()], 'dead_tup')?.points[0].value).toBe(7); + }); + + it('exports counters as sums and the live/dead tuple estimates as gauges', () => { + const metrics = buildDbTableMetrics([row()], NOW); + const gauges = metrics.filter((m) => m.kind === 'gauge').map((m) => m.name); + expect(gauges).toEqual(['lorekit.db.table.live_tup', 'lorekit.db.table.dead_tup']); + expect(metrics.filter((m) => m.kind === 'sum')).toHaveLength(11); + expect(metrics.every((m) => m.valueType === 'int')).toBe(true); + }); + + it('labels every point with db.table and nothing tenant-derived', () => { + for (const m of buildDbTableMetrics([row({ table_name: 'rate_limit_counters' })], NOW)) { + expect(m.points[0].attributes).toEqual({ 'db.table': 'rate_limit_counters', 'db.system': 'postgresql' }); + } + }); + + it('drops a row that names no table', () => { + const metrics = buildDbTableMetrics([row({ table_name: null }), row({ table_name: '' }), row()], NOW); + expect(metrics.every((m) => m.points.length === 1)).toBe(true); + expect(buildDbTableMetrics([row({ table_name: null })], NOW)).toEqual([]); + expect(buildDbTableMetrics([], NOW)).toEqual([]); + }); + + it('starts each series at the stats reset, or the epoch when never reset', () => { + expect(metric([row()], 'tup_ins')?.points[0]).toMatchObject({ startTimeMs: Date.parse(RESET), timeMs: NOW }); + expect(metric([row({ stats_since: null })], 'tup_ins')?.points[0].startTimeMs).toBe(0); + expect(metric([row({ stats_since: 'not a date' })], 'tup_ins')?.points[0].startTimeMs).toBe(0); + }); + + it('reads a missing or bigint-as-string counter as a number', () => { + expect(metric([row({ idx_scan: null })], 'idx_scan')?.points[0].value).toBe(0); + expect(metric([row({ n_tup_upd: '9007' as unknown as number })], 'tup_upd')?.points[0].value).toBe(9007); + }); +}); diff --git a/packages/mcp-core/src/telemetry/db-table-metrics.ts b/packages/mcp-core/src/telemetry/db-table-metrics.ts new file mode 100644 index 00000000..ec8f54b0 --- /dev/null +++ b/packages/mcp-core/src/telemetry/db-table-metrics.ts @@ -0,0 +1,134 @@ +// `lorekit_db_table_stats()` rows → OTel metrics (`lorekit.db.table.*`). +// +// The per-table half of LoreKit's query-level profiling (migration 00125). The +// impure halves are `supabase/functions/profiling/index.ts` (the RPC read) and +// `supabase/functions/_shared/telemetry/otlp-metrics.ts` (the POST); this module +// is the mapping in between, kept pure so the unit, the series start and the +// attribute set are unit-tested rather than only seen as a wrong number on a +// dashboard. Sibling of `db-query-metrics.ts`, which maps `pg_stat_statements`. +// +// Most counters are cumulative since the database's last `pg_stat_reset()` and +// go out as cumulative monotonic sums with that reset as the series start, so +// Dash0 does the differencing and reads a reset as a new series. The HOT-update +// ratio is then `rate(tup_hot_upd) / rate(tup_upd)`. +// +// `n_live_tup` / `n_dead_tup` are not counters — they are estimates of the +// table's current state, and they go DOWN when autovacuum runs — so they go out +// as gauges. +// +// Mirrored self-contained into the Deno edge tree +// (supabase/functions/_shared/telemetry/db-table-metrics.ts) because the edge +// runtime cannot cross-import this package. `edge-parity.spec.ts` asserts the +// two copies stay identical; the vitest suite here is the behavioural guard. + +/** One row of `lorekit_db_table_stats()`, as PostgREST returns it. */ +export interface DbTableStatRow { + table_name: string | null; + n_tup_ins: number | null; + n_tup_upd: number | null; + n_tup_hot_upd: number | null; + n_tup_del: number | null; + n_live_tup: number | null; + n_dead_tup: number | null; + seq_scan: number | null; + idx_scan: number | null; + autovacuum_count: number | null; + heap_blks_read: number | null; + heap_blks_hit: number | null; + idx_blks_read: number | null; + idx_blks_hit: number | null; + /** `pg_stat_database.stats_reset` as an ISO string, null until a reset has ever happened. */ + stats_since: string | null; +} + +/** One datapoint. Matches `otlp-metrics.ts`'s `SumPoint`. */ +export interface DbTablePoint { + attributes: Record; + value: number; + startTimeMs: number; + timeMs: number; +} + +/** A cumulative sum or a gauge. Matches `otlp-metrics.ts`'s `SumMetric`. */ +export interface DbTableMetric { + name: string; + unit: string; + description: string; + valueType: 'int' | 'double'; + kind: 'sum' | 'gauge'; + points: DbTablePoint[]; +} + +type Measure = { + column: Exclude; + name: string; + unit: string; + kind: 'sum' | 'gauge'; + description: string; +}; + +const MEASURES: readonly Measure[] = [ + { column: 'n_tup_ins', name: 'tup_ins', unit: '{row}', kind: 'sum', description: 'Cumulative rows inserted.' }, + { column: 'n_tup_upd', name: 'tup_upd', unit: '{row}', kind: 'sum', description: 'Cumulative rows updated, HOT updates included.' }, + { column: 'n_tup_hot_upd', name: 'tup_hot_upd', unit: '{row}', kind: 'sum', description: 'Cumulative rows updated in place (HOT): no index entries written.' }, + { column: 'n_tup_del', name: 'tup_del', unit: '{row}', kind: 'sum', description: 'Cumulative rows deleted.' }, + { column: 'seq_scan', name: 'seq_scan', unit: '{scan}', kind: 'sum', description: 'Cumulative sequential scans started.' }, + { column: 'idx_scan', name: 'idx_scan', unit: '{scan}', kind: 'sum', description: 'Cumulative index scans started.' }, + { column: 'heap_blks_read', name: 'heap_blks_read', unit: '{block}', kind: 'sum', description: 'Cumulative table blocks read from disk (not in shared buffers).' }, + { column: 'heap_blks_hit', name: 'heap_blks_hit', unit: '{block}', kind: 'sum', description: 'Cumulative table blocks found in shared buffers.' }, + { column: 'idx_blks_read', name: 'idx_blks_read', unit: '{block}', kind: 'sum', description: 'Cumulative index blocks read from disk, all indexes of the table.' }, + { column: 'idx_blks_hit', name: 'idx_blks_hit', unit: '{block}', kind: 'sum', description: 'Cumulative index blocks found in shared buffers, all indexes of the table.' }, + { column: 'autovacuum_count', name: 'autovacuum_count', unit: '{run}', kind: 'sum', description: 'Cumulative autovacuum runs on the table.' }, + { column: 'n_live_tup', name: 'live_tup', unit: '{row}', kind: 'gauge', description: 'Estimated live rows.' }, + { column: 'n_dead_tup', name: 'dead_tup', unit: '{row}', kind: 'gauge', description: 'Estimated dead rows awaiting vacuum.' }, +]; + +/** Every metric name this module can emit, in emission order. */ +export const DB_TABLE_METRIC_NAMES: readonly string[] = MEASURES.map((m) => `lorekit.db.table.${m.name}`); + +function num(v: number | string | null | undefined): number { + const n = typeof v === 'string' ? Number(v) : v; + return typeof n === 'number' && Number.isFinite(n) ? n : 0; +} + +/** + * The series start: the database's last stats reset, or the UNIX epoch when it + * was never reset. Never the observation time, which would make every point a + * zero-length series (the same rule as `db-query-metrics.ts`). + */ +function seriesStartMs(row: DbTableStatRow): number { + if (!row.stats_since) return 0; + const parsed = Date.parse(row.stats_since); + return Number.isFinite(parsed) ? parsed : 0; +} + +/** + * Map stat rows to `lorekit.db.table.*`. + * + * A row with no `table_name` cannot be tied to a series and is dropped. The + * attribute set is `db.table` and `db.system` only: the reader returns a fixed + * table allowlist, so the cardinality is bounded by that list, and nothing here + * is tenant-derived. + * + * @param nowMs the observation time on every point — passed in so one scrape's + * points share one timestamp and the mapping stays pure. + * @returns one metric per measure; empty when no row is usable. + */ +export function buildDbTableMetrics(rows: readonly DbTableStatRow[], nowMs: number): DbTableMetric[] { + const usable = rows.filter((row) => typeof row.table_name === 'string' && row.table_name.length > 0); + if (usable.length === 0) return []; + + return MEASURES.map((m) => ({ + name: `lorekit.db.table.${m.name}`, + unit: m.unit, + description: m.description, + valueType: 'int' as const, + kind: m.kind, + points: usable.map((row) => ({ + attributes: { 'db.table': row.table_name as string, 'db.system': 'postgresql' }, + value: num(row[m.column]), + startTimeMs: seriesStartMs(row), + timeMs: nowMs, + })), + })); +} diff --git a/packages/mcp-core/src/telemetry/otlp-metrics.spec.ts b/packages/mcp-core/src/telemetry/otlp-metrics.spec.ts new file mode 100644 index 00000000..7aeb8ee6 --- /dev/null +++ b/packages/mcp-core/src/telemetry/otlp-metrics.spec.ts @@ -0,0 +1,75 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import path from 'node:path'; + +/** + * EXECUTING cover for the edge OTLP metrics envelope + * (`supabase/functions/_shared/telemetry/otlp-metrics.ts`): a cumulative sum + * goes out under `sum` with temporality CUMULATIVE and `isMonotonic`, a gauge + * under `gauge` with neither — the shape `lorekit.db.table.live_tup` / + * `dead_tup` (00125) depend on. A gauge sent as a monotonic sum would be + * differenced by the backend into nonsense whenever autovacuum lowered it. + * + * Loaded by a DYNAMIC import over a computed path, as `otel-detached-child.spec.ts` + * does and for the same reason: `supabase/` is another NX project, so a static + * relative specifier is a module-boundary error. + */ + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..'); +const { buildOtlpMetricsPayload } = (await import( + pathToFileURL(path.join(repoRoot, 'supabase', 'functions', '_shared', 'telemetry', 'otlp-metrics.ts')).href +)) as { + buildOtlpMetricsPayload: (metrics: readonly unknown[], opts?: { environmentOverride?: string }) => unknown; +}; + +let hadDeno: boolean; + +beforeEach(() => { + hadDeno = 'Deno' in globalThis; + (globalThis as Record).Deno = { env: { get: () => undefined } }; +}); + +afterEach(() => { + if (!hadDeno) delete (globalThis as Record).Deno; +}); + +const point = { attributes: { 'db.table': 'memories' }, value: 7, startTimeMs: 1000, timeMs: 2000 }; + +function metricsOf(payload: unknown): Array> { + const p = payload as { resourceMetrics: Array<{ scopeMetrics: Array<{ metrics: Array> }> }> }; + return p.resourceMetrics[0].scopeMetrics[0].metrics; +} + +describe('buildOtlpMetricsPayload', () => { + it('renders a metric without a kind as a cumulative monotonic sum (unchanged default)', () => { + const [m] = metricsOf(buildOtlpMetricsPayload([ + { name: 'lorekit.db.query.calls', unit: '{call}', description: 'd', valueType: 'int', points: [point] }, + ])); + expect(m.gauge).toBeUndefined(); + expect(m.sum).toMatchObject({ aggregationTemporality: 2, isMonotonic: true }); + expect((m.sum as { dataPoints: unknown[] }).dataPoints[0]).toMatchObject({ + asInt: '7', + startTimeUnixNano: '1000000000', + timeUnixNano: '2000000000', + attributes: [{ key: 'db.table', value: { stringValue: 'memories' } }], + }); + }); + + it('renders kind "gauge" under gauge, with no temporality or monotonic flag', () => { + const [sum, gauge] = metricsOf(buildOtlpMetricsPayload([ + { name: 'lorekit.db.table.tup_upd', unit: '{row}', description: 'd', valueType: 'int', kind: 'sum', points: [point] }, + { name: 'lorekit.db.table.dead_tup', unit: '{row}', description: 'd', valueType: 'int', kind: 'gauge', points: [point] }, + ])); + expect(sum.sum).toBeDefined(); + expect(gauge.sum).toBeUndefined(); + expect(gauge).toMatchObject({ name: 'lorekit.db.table.dead_tup', unit: '{row}' }); + expect(gauge.gauge).toEqual({ + dataPoints: [{ + startTimeUnixNano: '1000000000', + timeUnixNano: '2000000000', + asInt: '7', + attributes: [{ key: 'db.table', value: { stringValue: 'memories' } }], + }], + }); + }); +}); diff --git a/supabase/functions/_shared/telemetry/db-table-metrics.ts b/supabase/functions/_shared/telemetry/db-table-metrics.ts new file mode 100644 index 00000000..ae857ff7 --- /dev/null +++ b/supabase/functions/_shared/telemetry/db-table-metrics.ts @@ -0,0 +1,140 @@ +// Mirror of packages/mcp-core/src/telemetry/db-table-metrics.ts, self-contained +// for the Deno edge tree (which cannot cross-import the Node package). Keep it +// behaviourally identical: `edge-parity.spec.ts` compares the two with comments +// stripped, and the vitest suite over the mcp-core copy is the shared guard. +// The edge is the only caller: `profiling/index.ts` feeds it the RPC rows. +// +// `lorekit_db_table_stats()` rows → OTel metrics (`lorekit.db.table.*`). +// +// The per-table half of LoreKit's query-level profiling (migration 00125). The +// impure halves are `supabase/functions/profiling/index.ts` (the RPC read) and +// `supabase/functions/_shared/telemetry/otlp-metrics.ts` (the POST); this module +// is the mapping in between, kept pure so the unit, the series start and the +// attribute set are unit-tested rather than only seen as a wrong number on a +// dashboard. Sibling of `db-query-metrics.ts`, which maps `pg_stat_statements`. +// +// Most counters are cumulative since the database's last `pg_stat_reset()` and +// go out as cumulative monotonic sums with that reset as the series start, so +// Dash0 does the differencing and reads a reset as a new series. The HOT-update +// ratio is then `rate(tup_hot_upd) / rate(tup_upd)`. +// +// `n_live_tup` / `n_dead_tup` are not counters — they are estimates of the +// table's current state, and they go DOWN when autovacuum runs — so they go out +// as gauges. +// +// Mirrored self-contained into the Deno edge tree +// (supabase/functions/_shared/telemetry/db-table-metrics.ts) because the edge +// runtime cannot cross-import this package. `edge-parity.spec.ts` asserts the +// two copies stay identical; the vitest suite here is the behavioural guard. + +/** One row of `lorekit_db_table_stats()`, as PostgREST returns it. */ +export interface DbTableStatRow { + table_name: string | null; + n_tup_ins: number | null; + n_tup_upd: number | null; + n_tup_hot_upd: number | null; + n_tup_del: number | null; + n_live_tup: number | null; + n_dead_tup: number | null; + seq_scan: number | null; + idx_scan: number | null; + autovacuum_count: number | null; + heap_blks_read: number | null; + heap_blks_hit: number | null; + idx_blks_read: number | null; + idx_blks_hit: number | null; + /** `pg_stat_database.stats_reset` as an ISO string, null until a reset has ever happened. */ + stats_since: string | null; +} + +/** One datapoint. Matches `otlp-metrics.ts`'s `SumPoint`. */ +export interface DbTablePoint { + attributes: Record; + value: number; + startTimeMs: number; + timeMs: number; +} + +/** A cumulative sum or a gauge. Matches `otlp-metrics.ts`'s `SumMetric`. */ +export interface DbTableMetric { + name: string; + unit: string; + description: string; + valueType: 'int' | 'double'; + kind: 'sum' | 'gauge'; + points: DbTablePoint[]; +} + +type Measure = { + column: Exclude; + name: string; + unit: string; + kind: 'sum' | 'gauge'; + description: string; +}; + +const MEASURES: readonly Measure[] = [ + { column: 'n_tup_ins', name: 'tup_ins', unit: '{row}', kind: 'sum', description: 'Cumulative rows inserted.' }, + { column: 'n_tup_upd', name: 'tup_upd', unit: '{row}', kind: 'sum', description: 'Cumulative rows updated, HOT updates included.' }, + { column: 'n_tup_hot_upd', name: 'tup_hot_upd', unit: '{row}', kind: 'sum', description: 'Cumulative rows updated in place (HOT): no index entries written.' }, + { column: 'n_tup_del', name: 'tup_del', unit: '{row}', kind: 'sum', description: 'Cumulative rows deleted.' }, + { column: 'seq_scan', name: 'seq_scan', unit: '{scan}', kind: 'sum', description: 'Cumulative sequential scans started.' }, + { column: 'idx_scan', name: 'idx_scan', unit: '{scan}', kind: 'sum', description: 'Cumulative index scans started.' }, + { column: 'heap_blks_read', name: 'heap_blks_read', unit: '{block}', kind: 'sum', description: 'Cumulative table blocks read from disk (not in shared buffers).' }, + { column: 'heap_blks_hit', name: 'heap_blks_hit', unit: '{block}', kind: 'sum', description: 'Cumulative table blocks found in shared buffers.' }, + { column: 'idx_blks_read', name: 'idx_blks_read', unit: '{block}', kind: 'sum', description: 'Cumulative index blocks read from disk, all indexes of the table.' }, + { column: 'idx_blks_hit', name: 'idx_blks_hit', unit: '{block}', kind: 'sum', description: 'Cumulative index blocks found in shared buffers, all indexes of the table.' }, + { column: 'autovacuum_count', name: 'autovacuum_count', unit: '{run}', kind: 'sum', description: 'Cumulative autovacuum runs on the table.' }, + { column: 'n_live_tup', name: 'live_tup', unit: '{row}', kind: 'gauge', description: 'Estimated live rows.' }, + { column: 'n_dead_tup', name: 'dead_tup', unit: '{row}', kind: 'gauge', description: 'Estimated dead rows awaiting vacuum.' }, +]; + +/** Every metric name this module can emit, in emission order. */ +export const DB_TABLE_METRIC_NAMES: readonly string[] = MEASURES.map((m) => `lorekit.db.table.${m.name}`); + +function num(v: number | string | null | undefined): number { + const n = typeof v === 'string' ? Number(v) : v; + return typeof n === 'number' && Number.isFinite(n) ? n : 0; +} + +/** + * The series start: the database's last stats reset, or the UNIX epoch when it + * was never reset. Never the observation time, which would make every point a + * zero-length series (the same rule as `db-query-metrics.ts`). + */ +function seriesStartMs(row: DbTableStatRow): number { + if (!row.stats_since) return 0; + const parsed = Date.parse(row.stats_since); + return Number.isFinite(parsed) ? parsed : 0; +} + +/** + * Map stat rows to `lorekit.db.table.*`. + * + * A row with no `table_name` cannot be tied to a series and is dropped. The + * attribute set is `db.table` and `db.system` only: the reader returns a fixed + * table allowlist, so the cardinality is bounded by that list, and nothing here + * is tenant-derived. + * + * @param nowMs the observation time on every point — passed in so one scrape's + * points share one timestamp and the mapping stays pure. + * @returns one metric per measure; empty when no row is usable. + */ +export function buildDbTableMetrics(rows: readonly DbTableStatRow[], nowMs: number): DbTableMetric[] { + const usable = rows.filter((row) => typeof row.table_name === 'string' && row.table_name.length > 0); + if (usable.length === 0) return []; + + return MEASURES.map((m) => ({ + name: `lorekit.db.table.${m.name}`, + unit: m.unit, + description: m.description, + valueType: 'int' as const, + kind: m.kind, + points: usable.map((row) => ({ + attributes: { 'db.table': row.table_name as string, 'db.system': 'postgresql' }, + value: num(row[m.column]), + startTimeMs: seriesStartMs(row), + timeMs: nowMs, + })), + })); +} diff --git a/supabase/functions/_shared/telemetry/otlp-metrics.ts b/supabase/functions/_shared/telemetry/otlp-metrics.ts index 102c3fca..ac0503ec 100644 --- a/supabase/functions/_shared/telemetry/otlp-metrics.ts +++ b/supabase/functions/_shared/telemetry/otlp-metrics.ts @@ -7,8 +7,7 @@ * `otel.ts`, so a metric and a span leaving the same isolate describe the same * resource — the property that lets Dash0 line them up as one service. * - * Only cumulative monotonic sums are modelled, because that is the only shape - * the one caller needs. `pg_stat_statements` counters are cumulative since the + * Cumulative monotonic sums are the main shape. `pg_stat_statements` counters are cumulative since the * last reset, so exporting them as cumulative sums lets Dash0 do the * differencing (`rate()`) and, crucially, handle a counter RESET correctly on * its own: `startTimeUnixNano` carries the stats-reset time, so a reset moves @@ -16,8 +15,10 @@ * negative traffic. Computing deltas ourselves would mean persisting the * previous snapshot somewhere and getting reset detection wrong in a new place. * - * Histograms and gauges are absent on purpose. Add one when something needs it, - * not before. + * Gauges exist for the one value that is a current estimate rather than a + * counter — the live/dead tuple counts of `lorekit.db.table.*` (00125), which go + * DOWN when autovacuum runs and so must not be read as a monotonic sum. + * Histograms are absent on purpose. Add one when something needs it, not before. * * Required secrets (same ones the span exporter uses — nothing new): * OTEL_EXPORTER_OTLP_ENDPOINT @@ -64,6 +65,12 @@ export interface SumMetric { * durations are `double`. */ valueType: 'int' | 'double'; + /** + * `sum` (the default) is a cumulative monotonic sum. `gauge` is a value as of + * `timeMs` that may go down; its `startTimeMs` is sent but carries no + * meaning for the backend. + */ + kind?: 'sum' | 'gauge'; points: SumPoint[]; } @@ -114,26 +121,29 @@ export function buildOtlpMetricsPayload( resource: { attributes: buildResourceAttributes(opts) }, scopeMetrics: [{ scope: { name: `lorekit-${resolveServiceName()}`, version: '1.0.0' }, - metrics: metrics.map((m) => ({ - name: m.name, - unit: m.unit, - description: m.description, - sum: { - aggregationTemporality: AGGREGATION_TEMPORALITY_CUMULATIVE, - // These only ever go up (within a series — a reset starts a new - // one, which is what startTimeUnixNano communicates). - isMonotonic: true, - dataPoints: m.points.map((p) => ({ - startTimeUnixNano: toUnixNano(p.startTimeMs), - timeUnixNano: toUnixNano(p.timeMs), - ...renderValue(p.value, m.valueType), - attributes: Object.entries(p.attributes).map(([key, value]) => ({ - key, - value: toOtlpValue(value), - })), + metrics: metrics.map((m) => { + const dataPoints = m.points.map((p) => ({ + startTimeUnixNano: toUnixNano(p.startTimeMs), + timeUnixNano: toUnixNano(p.timeMs), + ...renderValue(p.value, m.valueType), + attributes: Object.entries(p.attributes).map(([key, value]) => ({ + key, + value: toOtlpValue(value), })), - }, - })), + })); + const head = { name: m.name, unit: m.unit, description: m.description }; + if (m.kind === 'gauge') return { ...head, gauge: { dataPoints } }; + return { + ...head, + sum: { + aggregationTemporality: AGGREGATION_TEMPORALITY_CUMULATIVE, + // These only ever go up (within a series — a reset starts a new + // one, which is what startTimeUnixNano communicates). + isMonotonic: true, + dataPoints, + }, + }; + }), }], }], }; diff --git a/supabase/functions/profiling/index.ts b/supabase/functions/profiling/index.ts index f533c854..a9a3bf03 100644 --- a/supabase/functions/profiling/index.ts +++ b/supabase/functions/profiling/index.ts @@ -12,10 +12,11 @@ * cannot see: they time each round-trip from the caller's side, one request at * a time. * - * Read `lorekit_db_query_stats()` → map to cumulative sums - * (`_shared/telemetry/db-query-metrics.ts`) → POST as OTLP metrics - * (`_shared/telemetry/otlp-metrics.ts`). Full rationale in docs/otel.md → - * "Query-level profiling". + * Read `lorekit_db_query_stats()` and `lorekit_db_table_stats()` (00125) → map + * to `lorekit.db.query.*` (`_shared/telemetry/db-query-metrics.ts`) and + * `lorekit.db.table.*` (`_shared/telemetry/db-table-metrics.ts`) → POST both in + * one OTLP metrics request (`_shared/telemetry/otlp-metrics.ts`). Full rationale + * in docs/otel.md → "Query-level profiling". * * OPERATOR SURFACE, service-role only. The rows are cross-tenant query shapes, * so no user JWT and no `lk_*` API token can reach this — the counters describe @@ -32,6 +33,7 @@ import { traceRequest, resolveEnvironmentOverride, createTracedClient } from '../_shared/telemetry/otel.ts'; import { exportMetrics } from '../_shared/telemetry/otlp-metrics.ts'; import { buildDbQueryMetrics, type DbQueryStatRow } from '../_shared/telemetry/db-query-metrics.ts'; +import { buildDbTableMetrics, type DbTableStatRow } from '../_shared/telemetry/db-table-metrics.ts'; import { resolveRestAuth } from '../_shared/api/auth.ts'; /** @@ -89,22 +91,34 @@ Deno.serve((req: Request) => // resolves to `PostgrestResponse`), so a set-returning function is // `DbQueryStatRow[]`. Passing the bare row type here would compile and then // hand `buildDbQueryMetrics` a single object where it expects an array. - const { data, error } = await createTracedClient(resolved.db, span) - .rpc('lorekit_db_query_stats', { p_limit: limit }); + // + // The two reads are independent, so they run concurrently; either failing + // fails the scrape the same way, since a half export would read on a + // dashboard as one family of metrics quietly stopping. + const db = createTracedClient(resolved.db, span); + const [queries, tables] = await Promise.all([ + db.rpc('lorekit_db_query_stats', { p_limit: limit }), + db.rpc('lorekit_db_table_stats'), + ]); + const error = queries.error ?? tables.error; if (error) { span.error(`ProfilingReadFailed: ${error.message}`); return json({ error: 'stats_read_failed', message: error.message }, 500); } - const rows = data ?? []; - const metrics = buildDbQueryMetrics(rows, Date.now()); + const rows = queries.data ?? []; + const tableRows = tables.data ?? []; + // One timestamp for the whole scrape, so both families line up. + const now = Date.now(); + const metrics = [...buildDbQueryMetrics(rows, now), ...buildDbTableMetrics(tableRows, now)]; const result = await exportMetrics(metrics, { environmentOverride: resolveEnvironmentOverride(req), }); span.setAttributes({ 'lorekit.profiling.statements': rows.length, + 'lorekit.profiling.tables': tableRows.length, 'lorekit.profiling.datapoints': result.points, 'lorekit.profiling.exported': result.exported, }); @@ -112,6 +126,7 @@ Deno.serve((req: Request) => const body = { exported: result.exported, statements: rows.length, + tables: tableRows.length, datapoints: result.points, metrics: metrics.map((m) => m.name), ...(result.error ? { reason: result.error } : {}), @@ -124,8 +139,9 @@ Deno.serve((req: Request) => // reporting success while nothing reaches Dash0, visible only as a // dashboard that quietly stopped updating. // - // 503 — nothing to send, or nowhere to send it. pg_stat_statements is not - // installed or unreadable, or OTEL_EXPORTER_OTLP_ENDPOINT is unset. + // 503 — nothing to send, or nowhere to send it. Neither reader returned + // a row (pg_stat_statements absent AND no allowlisted table), or + // OTEL_EXPORTER_OTLP_ENDPOINT is unset. // A configuration gap on THIS side. // 502 — the export was attempted and Dash0 rejected it or was // unreachable. A problem on the far side (or a bad payload). From d5bc0dc78f3cb2066ed2546b9dd4d0e1ad4a0f44 Mon Sep 17 00:00:00 2001 From: mthines Date: Wed, 25 Nov 2026 19:46:25 +0100 Subject: [PATCH 3/6] feat(telemetry): trace lorekit_record_memory_reads on a detached span --- .../src/telemetry/memory-reads.spec.ts | 129 ++++++++++++++++++ .../_shared/telemetry/memory-reads.ts | 37 ++++- supabase/functions/mcp/tools.ts | 12 +- supabase/functions/memories/handlers/get.ts | 2 +- supabase/functions/memories/handlers/list.ts | 2 +- supabase/functions/memories/handlers/read.ts | 2 +- .../functions/memories/handlers/search.ts | 2 +- 7 files changed, 169 insertions(+), 17 deletions(-) create mode 100644 packages/mcp-core/src/telemetry/memory-reads.spec.ts diff --git a/packages/mcp-core/src/telemetry/memory-reads.spec.ts b/packages/mcp-core/src/telemetry/memory-reads.spec.ts new file mode 100644 index 00000000..934c63d5 --- /dev/null +++ b/packages/mcp-core/src/telemetry/memory-reads.spec.ts @@ -0,0 +1,129 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import path from 'node:path'; + +/** + * EXECUTING cover for `recordMemoryReads` + * (`supabase/functions/_shared/telemetry/memory-reads.ts`): the fire-and-forget + * `lorekit_record_memory_reads` RPC must reach Dash0 as a + * `CALL lorekit_record_memory_reads` CLIENT span, under a detached + * `lorekit.memory.record_reads` span that keeps the request's trace id. + * + * Before this, the call used the raw client and emitted no span at all — the + * one database write on every list/search/read path that the traces could not + * see. A plain `child()` span would not fix it: the request batch is flushed + * before the background call resolves (see `otel-detached-child.spec.ts`). + * + * Loaded by a dynamic import over a computed path, like that spec, because + * `supabase/` is another NX project. + */ + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..'); +const telemetryDir = path.join(repoRoot, 'supabase', 'functions', '_shared', 'telemetry'); +const { Span, ExportBatch } = (await import(pathToFileURL(path.join(telemetryDir, 'otel.ts')).href)) as { + Span: new ( + name: string, + ctx: { traceId: string; spanId: string; sampled: boolean }, + batch: unknown, + kind?: number, + ) => unknown; + ExportBatch: new () => { drain(): unknown[] }; +}; +const { recordMemoryReads } = (await import(pathToFileURL(path.join(telemetryDir, 'memory-reads.ts')).href)) as { + recordMemoryReads: (db: unknown, span: unknown, ids: readonly string[], kind: string, client?: string | null) => void; +}; + +const TRACE_ID = 'c'.repeat(32); +const SPAN_KIND_CLIENT = 3; + +let posted: string[]; +let realFetch: typeof globalThis.fetch; +let hadDeno: boolean; + +beforeEach(() => { + posted = []; + realFetch = globalThis.fetch; + hadDeno = 'Deno' in globalThis; + (globalThis as Record).Deno = { + env: { + get: (k: string) => (k === 'OTEL_EXPORTER_OTLP_ENDPOINT' ? 'https://otlp.test.invalid' : undefined), + }, + }; + globalThis.fetch = ((_url: string, init?: { body?: string }) => { + posted.push(String(init?.body ?? '')); + return Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve('') }); + }) as unknown as typeof globalThis.fetch; +}); + +afterEach(() => { + globalThis.fetch = realFetch; + if (!hadDeno) delete (globalThis as Record).Deno; +}); + +type OtlpSpan = { name: string; kind: number; traceId: string; parentSpanId?: string; spanId: string }; + +function exportedSpans(): OtlpSpan[] { + const out: OtlpSpan[] = []; + const walk = (node: unknown): void => { + if (Array.isArray(node)) return void node.forEach(walk); + if (node && typeof node === 'object') { + const o = node as Record; + if (typeof o.name === 'string' && typeof o.spanId === 'string') out.push(o as unknown as OtlpSpan); + Object.values(o).forEach(walk); + } + }; + posted.forEach((body) => walk(JSON.parse(body))); + return out; +} + +function fakeDb(calls: Array<{ fn: string; args: unknown }>, result: Promise = Promise.resolve({ data: null, error: null })) { + return { + rpc: (fn: string, args: unknown) => { + calls.push({ fn, args }); + return result; + }, + }; +} + +describe('recordMemoryReads', () => { + it('exports a CALL lorekit_record_memory_reads CLIENT span under a detached span of the request trace', async () => { + const batch = new ExportBatch(); + const request = new Span('lorekit.memory.list', { traceId: TRACE_ID, spanId: 'd'.repeat(16), sampled: true }, batch, 1); + const calls: Array<{ fn: string; args: unknown }> = []; + + recordMemoryReads(fakeDb(calls), request, ['m1', 'm2'], 'bulk'); + + await vi.waitFor(() => expect(posted.length).toBeGreaterThan(0)); + expect(calls).toEqual([{ fn: 'lorekit_record_memory_reads', args: { p_memory_ids: ['m1', 'm2'], p_read_kind: 'bulk', p_client: null } }]); + + const spans = exportedSpans(); + const bg = spans.find((s) => s.name === 'lorekit.memory.record_reads'); + const call = spans.find((s) => s.name === 'CALL lorekit_record_memory_reads'); + expect(bg?.traceId).toBe(TRACE_ID); + expect(bg?.parentSpanId).toBe('d'.repeat(16)); + expect(call?.kind).toBe(SPAN_KIND_CLIENT); + expect(call?.parentSpanId).toBe(bg?.spanId); + // Nothing landed in the request's own batch: it may already be flushed. + expect(batch.drain()).toEqual([]); + }); + + it('still ends and exports the span when the RPC throws, and never throws itself', async () => { + const request = new Span('lorekit.memory.read', { traceId: TRACE_ID, spanId: 'e'.repeat(16), sampled: true }, new ExportBatch(), 1); + + expect(() => recordMemoryReads(fakeDb([], Promise.reject(new Error('boom'))), request, ['m1'], 'targeted', 'mcp')).not.toThrow(); + + await vi.waitFor(() => expect(exportedSpans().some((s) => s.name === 'lorekit.memory.record_reads')).toBe(true)); + }); + + it('opens no span and makes no call for zero ids', async () => { + const calls: Array<{ fn: string; args: unknown }> = []; + const detachedChild = vi.fn(); + + recordMemoryReads(fakeDb(calls), { detachedChild }, [], 'bulk'); + + await new Promise((r) => setTimeout(r, 10)); + expect(detachedChild).not.toHaveBeenCalled(); + expect(calls).toEqual([]); + expect(posted).toEqual([]); + }); +}); diff --git a/supabase/functions/_shared/telemetry/memory-reads.ts b/supabase/functions/_shared/telemetry/memory-reads.ts index e39c8de6..89925ed0 100644 --- a/supabase/functions/_shared/telemetry/memory-reads.ts +++ b/supabase/functions/_shared/telemetry/memory-reads.ts @@ -17,6 +17,7 @@ import { background } from '../runtime/background.ts'; import type { DbClient } from '../db/db-client.ts'; +import { createTracedClient, type Span } from './otel.ts'; import type { UsageClient } from './usage-stats.ts'; /** @@ -46,22 +47,44 @@ export type MemoryReadKind = 'targeted' | 'bulk'; * * Never throws. A failing counter update must not fail the read it is * measuring — same posture as `recordUsageEvent`. + * + * Traced on a DETACHED child of `span` (`lorekit.memory.record_reads`), the + * `audit.ts` pattern: the request span's batch is flushed when the handler + * returns, before this background call resolves, so a plain `child()` span + * would be lost. The detached span's own batch is flushed when the call ends, + * which is what gives the RPC its `CALL lorekit_record_memory_reads` CLIENT + * span — and keeps its time off the request's `self_time_ms`, since the read + * deliberately does not wait for it. */ export function recordMemoryReads( db: DbClient, + span: Span, memoryIds: readonly string[], readKind: MemoryReadKind, client: UsageClient | null = null, ): void { if (memoryIds.length === 0) return; - const p = Promise.resolve( - db.rpc('lorekit_record_memory_reads', { - p_memory_ids: memoryIds as string[], - p_read_kind: readKind, - p_client: client, - }), - ).then(() => { /* fire-and-forget */ }, () => { /* swallow */ }); + const { span: bg, flush } = span.detachedChild('lorekit.memory.record_reads', { + 'lorekit.read.kind': readKind, + 'lorekit.read.count': memoryIds.length, + }); + const p = (async () => { + try { + await createTracedClient(db, bg).rpc('lorekit_record_memory_reads', { + p_memory_ids: memoryIds as string[], + p_read_kind: readKind, + p_client: client, + }); + } catch { + // Swallowed: a counter write must never fail the read it measures. + } finally { + bg.end(); + // Awaited: this task is the isolate's keep-alive, so an export left + // running here could be torn down mid-flight. + await flush(); + } + })(); const host = background(); if (host) host.waitUntil(p); diff --git a/supabase/functions/mcp/tools.ts b/supabase/functions/mcp/tools.ts index 1efe13a1..658dc12a 100644 --- a/supabase/functions/mcp/tools.ts +++ b/supabase/functions/mcp/tools.ts @@ -419,7 +419,7 @@ export async function toolRead( // (migration 00099). Only the WINNER is counted: the rows precedence // discarded were never shown to the caller, and counting them would inflate // the `opened_count / read_count` ratio `/insights` is built on. - recordMemoryReads(db, [winner.id], 'targeted', 'mcp'); + recordMemoryReads(db, span, [winner.id], 'targeted', 'mcp'); // `superseded_by` (00120): the records that say they replace this one, read // under the SAME tenant filter as the read above. const links = await fetchSupersededBy(tracedDb, [winner.id], (q) => @@ -502,7 +502,7 @@ async function toolReadRefs( ]) ).flat(); - if (rows.length > 0) recordMemoryReads(db, rows.map((r) => r.id), 'targeted', 'mcp'); + if (rows.length > 0) recordMemoryReads(db, span, rows.map((r) => r.id), 'targeted', 'mcp'); // One `superseded_by` query for the whole batch, never one per ref. const links = await fetchSupersededBy(tracedDb, rows.map((r) => r.id), (q) => userId ? applyTenantScope(q, userId, orgIds, keyScoping) : q); @@ -683,7 +683,7 @@ export async function toolList( // tool, not signalled per response. // memory.list (order=rank) is a BULK read for the per-memory counter // (migration 00077) — one statement for the whole page. - recordMemoryReads(db, page.map(({ entry }) => entry.id), 'bulk'); + recordMemoryReads(db, span, page.map(({ entry }) => entry.id), 'bulk'); return { entries, hasMore: false, nextCursor: null }; } @@ -719,7 +719,7 @@ export async function toolList( // `ListRow.id` is optional only because the interface is shared with a // legacy shape that predates it — the query above always selects `id`, so // filtering `undefined` here is a type narrowing, not an expected drop. - recordMemoryReads(db, (page.entries as ListRow[]).map((row) => row.id).filter((id): id is string => id !== undefined), 'bulk'); + recordMemoryReads(db, span, (page.entries as ListRow[]).map((row) => row.id).filter((id): id is string => id !== undefined), 'bulk'); const links = await supersededBy((page.entries as ListRow[]).map((row) => row.id)); return { ...page, @@ -877,7 +877,7 @@ export async function toolSearch( const page = buildPage(rows, pageLimit, 'updated_at'); span.setAttributes({ 'lorekit.result.count': page.entries.length }); // memory.search is a BULK read for the per-memory counter (migration 00077). - recordMemoryReads(db, page.entries.map((e) => e.id), 'bulk'); + recordMemoryReads(db, span, page.entries.map((e) => e.id), 'bulk'); // `superseded_by` (00120): one query over the page, same tenant filter. const links = await fetchSupersededBy(tracedDb, page.entries.map((e) => e.id), (q) => userId ? applyTenantScope(q, userId, orgIds, keyScoping) : q); @@ -993,7 +993,7 @@ export async function toolListArchived( span.setAttributes({ 'lorekit.result.count': rows.length }); // memory.list_archived is a BULK read for the per-memory counter // (migration 00077). - recordMemoryReads(db, rows.map((r) => r.id), 'bulk'); + recordMemoryReads(db, span, rows.map((r) => r.id), 'bulk'); const entries = rows.map(({ id: _id, ...rest }) => rest); return { entries }; } diff --git a/supabase/functions/memories/handlers/get.ts b/supabase/functions/memories/handlers/get.ts index c14f97d3..8a249bc5 100644 --- a/supabase/functions/memories/handlers/get.ts +++ b/supabase/functions/memories/handlers/get.ts @@ -56,6 +56,6 @@ export async function handleGet( // caller-supplied X-LoreKit-Client header decides whether this counts as an // agent opening the lesson (migration 00099's last_opened_at) or a human // browsing the dashboard. - recordMemoryReads(db, [(data as { id: string }).id], 'targeted', parseUsageClient(req.headers.get(CLIENT_HEADER))); + recordMemoryReads(db, span, [(data as { id: string }).id], 'targeted', parseUsageClient(req.headers.get(CLIENT_HEADER))); return res; } diff --git a/supabase/functions/memories/handlers/list.ts b/supabase/functions/memories/handlers/list.ts index ec882a08..5f4100e7 100644 --- a/supabase/functions/memories/handlers/list.ts +++ b/supabase/functions/memories/handlers/list.ts @@ -313,7 +313,7 @@ async function respondWithPage( // lesson) fire from the CLI's `read` command — without this it would look // exactly like a bulk list and unseen_days could never resolve it. const readKind = scopeFilter && params.key ? 'targeted' : 'bulk'; - recordMemoryReads(db, page.entries.map((e) => e.id), readKind, parseUsageClient(req.headers.get(CLIENT_HEADER))); + recordMemoryReads(db, span, page.entries.map((e) => e.id), readKind, parseUsageClient(req.headers.get(CLIENT_HEADER))); return res; } diff --git a/supabase/functions/memories/handlers/read.ts b/supabase/functions/memories/handlers/read.ts index 95a7a4a0..a814b5e8 100644 --- a/supabase/functions/memories/handlers/read.ts +++ b/supabase/functions/memories/handlers/read.ts @@ -146,7 +146,7 @@ export async function handleRead( // wants, the same intent memory.read's singular path already counts as // targeted). if (rows.length > 0) { - recordMemoryReads(db, rows.map((r) => r.id), 'targeted', parseUsageClient(req.headers.get(CLIENT_HEADER))); + recordMemoryReads(db, span, rows.map((r) => r.id), 'targeted', parseUsageClient(req.headers.get(CLIENT_HEADER))); } return res; } diff --git a/supabase/functions/memories/handlers/search.ts b/supabase/functions/memories/handlers/search.ts index 486591c4..0099cc75 100644 --- a/supabase/functions/memories/handlers/search.ts +++ b/supabase/functions/memories/handlers/search.ts @@ -79,7 +79,7 @@ export async function handleSearch( const res = ok({ ...page, entries: page.entries.map((e) => withSupersededBy(shapeMemoryRow(e), links)) }, cors); res.headers.set('X-LoreKit-Result-Count', String(page.entries.length)); // memory.search is a BULK read for the per-memory counter (migration 00077). - recordMemoryReads(db, page.entries.map((e) => e.id), 'bulk'); + recordMemoryReads(db, span, page.entries.map((e) => e.id), 'bulk'); // Scope attribution for the router's usage event — see SCOPE_COUNT_HEADER / // RESOLVED_SCOPE_HEADER (migration 00078). The router cannot read `scopes` // itself (it must not consume this POST body), so this handler — which just From 0fbac2a1393acd8e63f6b9f8f67bcd0744b82fca Mon Sep 17 00:00:00 2001 From: mthines Date: Wed, 25 Nov 2026 19:47:01 +0100 Subject: [PATCH 4/6] docs(otel): document lorekit.db.table.* and the traced read-counter call --- CLAUDE.md | 2 +- docs/key-files.md | 6 ++-- docs/otel.md | 59 +++++++++++++++++++++++++++++++++--- supabase/functions/CLAUDE.md | 2 +- 4 files changed, 61 insertions(+), 8 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 215aa8b8..cd51df96 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -356,7 +356,7 @@ concurrent queries and drives self time negative. **Profiles are NOT a signal LoreKit can emit** — Dash0 collects them with a host-level eBPF agent and every runtime here is managed serverless. Query-level profiling (`pg_stat_statements` → the three -`lorekit.db.query.*` cumulative sums, via the service-role-only `profiling` function, OFF until two +`lorekit.db.query.*` cumulative sums, plus per-table `lorekit.db.table.*` counters (00125), via the service-role-only `profiling` function, OFF until two Vault secrets exist) is the substitute. Read [docs/otel.md](./docs/otel.md) → "Query-level profiling" and [docs/decisions.md](./docs/decisions.md#profiling-is-sql-level-because-there-is-no-host-to-profile) diff --git a/docs/key-files.md b/docs/key-files.md index 54408842..82cea5ec 100644 --- a/docs/key-files.md +++ b/docs/key-files.md @@ -34,8 +34,10 @@ else. Grouped loosely by subsystem in migration/PR order. | `supabase/functions/_shared/telemetry/span-semconv.ts` | Pure, import-free semconv rendering for edge spans: `querySummary` (the DB span name), `renderStatement` / `conditionSql` / `postgrestLogicToSql` (a parameterised `db.query.text` — no filter value reaches the span name or the statement; an unparseable `.or()` string collapses to `(?)`), `redactUrls` (strips request URLs, and the filter values in their query strings, from a recorded `error.message`; Postgres's own wording can still echo a value), `resolveServerAddress` (never names a BYOD host), `errorTypeFrom` / `errorTypeOf` (the bounded `error.type` — catch blocks pass `errorTypeOf(e)`, which falls back to a PostgREST error object's `code`), `httpRouteFor`. Executed by `packages/mcp-core/src/telemetry/span-semconv.spec.ts` | | `packages/mcp-core/src/telemetry/io-ledger.ts` | Pure `mergeBusyMs` / `attributeIoTime` — the self-time split behind `lorekit.self_time_ms`. The closest thing to a CPU profile a managed Deno isolate can produce (no host for Dash0's eBPF profiler, no userland V8 profiler, and OTLP profiles have no JS exporter). Intervals are MERGED, never summed: handlers issue concurrent queries, so adding two overlapping 40 ms calls claims 80 ms of wait in a request that waited 40 and drives self time negative on exactly the requests worth profiling. Mirrored into `supabase/functions/_shared/telemetry/io-ledger.ts`, guarded by `edge-parity.spec.ts` | | `packages/mcp-core/src/telemetry/db-query-metrics.ts` | Pure `buildDbQueryMetrics` — `pg_stat_statements` rows → the three cumulative sums (`lorekit.db.query.time` in **seconds**, `.calls`, `.rows`). Holds the decisions that are silent when wrong: the ms→s conversion, the EPOCH (not `now`) fallback for a never-reset counter — `startTimeMs === timeMs` is a zero-length series a backend divides by zero over — `queryid` kept as a STRING (int64), and the bounded attribute set with deliberately NO tenant dimension. Mirrored into `supabase/functions/_shared/telemetry/db-query-metrics.ts`, guarded by `edge-parity.spec.ts` | -| `supabase/functions/profiling/index.ts` | Query-level profiling export: read `lorekit_db_query_stats()` → map → POST as OTLP metrics. SERVICE-ROLE only (the counters are the whole cluster's, so an `lk_ro_*` tenant token is refused too) and deliberately NOT behind `createRouter` — a cron poke is not a tenant request and must not land in `usage_events`. Distinguishes `503` (nothing to send / nowhere to send it) from `502` (Dash0 rejected it), because a `200` on either is the silent failure the endpoint exists to prevent | +| `packages/mcp-core/src/telemetry/db-table-metrics.ts` | Pure `buildDbTableMetrics` — `lorekit_db_table_stats()` rows → `lorekit.db.table.*`: eleven cumulative sums (tuples inserted/updated/HOT-updated/deleted, seq/index scans, heap/index blocks read/hit, autovacuum runs) and two GAUGES (`live_tup`, `dead_tup`), which go down on vacuum and so must not be sums. Attributes are `db.table` + `db.system` only. Mirrored into `supabase/functions/_shared/telemetry/db-table-metrics.ts`, guarded by `edge-parity.spec.ts` | +| `supabase/functions/profiling/index.ts` | Query-level profiling export: read `lorekit_db_query_stats()` and `lorekit_db_table_stats()` (00125) concurrently → map → POST both families as one OTLP metrics request. SERVICE-ROLE only (the counters are the whole cluster's, so an `lk_ro_*` tenant token is refused too) and deliberately NOT behind `createRouter` — a cron poke is not a tenant request and must not land in `usage_events`. Distinguishes `503` (nothing to send / nowhere to send it) from `502` (Dash0 rejected it), because a `200` on either is the silent failure the endpoint exists to prevent | | `supabase/migrations/00074_db_query_stats.sql` | `lorekit_db_query_stats(p_limit)` — top-N statements of the current database by cumulative exec time, service-role only (PostgREST publishes anything `anon`/`authenticated` can execute), capped at 200 rows INSIDE the function so a caller cannot ask for unbounded metric cardinality, and never raising: a missing extension, one installed but absent from `shared_preload_libraries` (SQLSTATE `55000` — the case the presence check cannot see), an old version without `toplevel`, or a privilege refusal all yield zero rows. Excludes BOTH its own RPC name and the view's, or the exporter climbs its own top-N at one scrape every 5 minutes (00124) and reports on itself forever. Plus `lorekit_export_db_query_stats()` + the pg_cron job (every 5 minutes since 00124) — inert until the `lorekit_profiling_url` / `lorekit_profiling_key` Vault secrets exist, so the migration turns nothing on | +| `supabase/migrations/00125_db_table_stats.sql` | `lorekit_db_table_stats()` — `pg_stat_user_tables` + `pg_statio_user_tables` for a FIXED allowlist of request-path tables (`memories`, `memory_read_daily`, `rate_limit_counters`, `audit_log`, `usage_events`, `api_tokens`, `memory_citations`), service-role only, with the database's `stats_reset` as the series start. The allowlist is a constant because every table is 13 metric series. Enabled by the same Vault secrets as 00074 | | `supabase/migrations/00001_memories.sql` | `memories` table, FTS, RLS | | `supabase/migrations/00002_api_tokens.sql` | `api_tokens` table, RLS | | `supabase/migrations/00068_api_token_scoping.sql` | API key scoping: `api_tokens.scopes` / `org_access` / `org_ids` + their CHECKs, the two request-time predicates `lorekit_api_token_scope_allowed` / `lorekit_api_token_org_allowed`, and the owner-only `lorekit_api_token_set_scoping` RPC. Empty `scopes` = unrestricted; tenancy is authoritative over `org_scope_bindings` auto-routing — see `docs/decisions.md#api-token-scoping-scopes--orgs` | @@ -107,7 +109,7 @@ else. Grouped loosely by subsystem in migration/PR order. | `packages/web/src/components/lore/DuplicateClusters.tsx` | The compact TRIGGER — a single-row toolbar button, not the panel itself (see `docs/decisions.md`: an Explorer PANEL entry point, not an instrument — a grouping over lesson bodies is not a `?filters=` dimension). Opens COLLAPSED and the disclosure (`PREFERENCE_KEYS.explorerClustersOpen`, lifted to `LoreExplorer`) IS the React Query `enabled` flag it shares with `DuplicateClustersSidebar`, so a folded trigger issues no clustering request at all — the load-bearing part, pinned by the `FoldedMeansNotFetched` interaction test. Only renders the summary badge once opened at least once this session | | `packages/web/src/components/lore/DuplicateClustersSidebar.tsx` | The non-modal SIDEBAR the trigger reveals — a flex sibling of the Explorer's results column (never `position:fixed`, no backdrop), so a reader keeps clicking lesson rows while it is open. One `role="radiogroup"` of clusters; picking one hands the whole `DuplicateCluster` back to `LoreExplorer` BY VALUE (re-picking the held one clears the selection), which is what swaps the Explorer's own results list to that cluster's members (`renderResults`) instead of a nested detail pane — opening a member is the same click as opening any other lesson. Read-only, and its footnote says so plus which question a saturated window answered | | `packages/web/src/lib/explorer-instruments.ts` | The pure model behind the Explorer's instrument panel, and the place the rule lives: **an instrument is a filter INPUT, not a view** — every selection it makes is written to the same `?filters=` / `?range=` state the menu and the date picker write, so the list stays the single output. The test that keeps analytics on `/insights` rather than creeping in here: *can you click it and end up holding lore?* `MATRIX_AXES` is derived from `FILTER_FIELDS` (minus `pr`, whose per-value cardinality makes a grid of one-cell columns), so a dimension the bar can filter by is exactly one the matrix can pivot on. `buildMatrixGrid` decides every visible property of the grid — which values appear, in what order, how many were dropped; `heatStep` roots the ratio because memory counts are heavily skewed and a linear ramp paints the whole tail the same near-black; `dayIndexAt` and `brushRange` are the whole of a pointer gesture's correctness | -| `supabase/functions/_shared/telemetry/memory-reads.ts` | `recordMemoryReads` — the single edge writer for per-memory read counters (`memories.read_count`/`.last_read_at`) and the `memory_read_daily` rollup (migration 00084). Called once per read-tool call (`memory.read`/`memory.list`/`memory.search`/`memory.list_archived`, both transports) with every memory id that call actually returned — one statement regardless of array size, never one per row. Fail-safe like `recordUsageEvent`: a counter write must never fail the read it measures | +| `supabase/functions/_shared/telemetry/memory-reads.ts` | `recordMemoryReads` — the single edge writer for per-memory read counters (`memories.read_count`/`.last_read_at`) and the `memory_read_daily` rollup (migration 00084). Called once per read-tool call (`memory.read`/`memory.list`/`memory.search`/`memory.list_archived`, both transports) with every memory id that call actually returned — one statement regardless of array size, never one per row. Fail-safe like `recordUsageEvent`: a counter write must never fail the read it measures. Traced on a DETACHED child of the request span (`lorekit.memory.record_reads` → `CALL lorekit_record_memory_reads`), the `audit.ts` pattern, because the request batch is flushed before this background call resolves | | `packages/web/src/lib/audit-log.ts` | Server actions: `recordAuditEvent` (non-throwing writer), `listAuditLog(filters)` (RLS-scoped, keyset-paginated reader returning `{ rows, nextCursor, hasMore }`) — powers Settings → Audit Logs | | `packages/web/src/lib/audit-actions.ts` | `AuditAction` union (re-declared, no `@lorekit/core` dependency in `web`) + `AUDIT_ACTION_META` single-record badge metadata; includes `'github_app.installation_linked'` | | `supabase/migrations/00014_orgs.sql` | `orgs` + `org_members(role)` tables (RLS, member-scoped select policies) and `lorekit_member_org_ids(uuid)` — the single `SECURITY DEFINER` membership-truth function (org-sharing Phase 1 foundations; see plan `.agent/claude/memory-scope-sharing-ualfuz/plan.md`) | diff --git a/docs/otel.md b/docs/otel.md index 20175e97..4708dbd3 100644 --- a/docs/otel.md +++ b/docs/otel.md @@ -215,9 +215,11 @@ they time each round-trip from the caller's side, one request at a time. pg_cron (every 5 minutes — 00124; was every minute) └── lorekit_export_db_query_stats() ← inert without vault secrets └── pg_net → POST /functions/v1/profiling - └── lorekit_db_query_stats(20) ← top-N reader RPC - └── buildDbQueryMetrics() ← pure mapper - └── POST → Dash0 /v1/metrics + ├── lorekit_db_query_stats(20) ← top-N reader RPC + │ └── buildDbQueryMetrics() ← pure mapper + ├── lorekit_db_table_stats() ← per-table reader RPC (00125) + │ └── buildDbTableMetrics() ← pure mapper + └── one POST → Dash0 /v1/metrics ``` Three metrics, all **cumulative monotonic sums**: @@ -258,6 +260,51 @@ A consequence worth knowing: a dropped scrape costs **resolution, not data** — the next scrape still carries the full cumulative total. That is why the cron poke is fire-and-forget. +### Per-table counters (00125) + +The same scrape also reads `lorekit_db_table_stats()`: `pg_stat_user_tables` and +`pg_statio_user_tables` for a **fixed allowlist** of the tables written on the +request path — `memories`, `memory_read_daily`, `rate_limit_counters`, +`audit_log`, `usage_events`, `api_tokens`, `memory_citations`. It answers what +`pg_stat_statements` cannot: whether a table's updates are HOT (00124's whole +point), how many dead tuples autovacuum is chasing, and which table's blocks are +read from disk rather than shared buffers — the per-table view of a Disk IO +budget. Service-role only, like the query reader. + +Every point carries `db.table` and `db.system=postgresql`, nothing else. + +| Metric | Kind | Unit | Source column | +|--------|------|------|---------------| +| `lorekit.db.table.tup_ins` | sum | `{row}` | `n_tup_ins` | +| `lorekit.db.table.tup_upd` | sum | `{row}` | `n_tup_upd` (HOT updates included) | +| `lorekit.db.table.tup_hot_upd` | sum | `{row}` | `n_tup_hot_upd` | +| `lorekit.db.table.tup_del` | sum | `{row}` | `n_tup_del` | +| `lorekit.db.table.seq_scan` | sum | `{scan}` | `seq_scan` | +| `lorekit.db.table.idx_scan` | sum | `{scan}` | `idx_scan` (0 for a table with no index) | +| `lorekit.db.table.heap_blks_read` | sum | `{block}` | `heap_blks_read` — table blocks read from disk | +| `lorekit.db.table.heap_blks_hit` | sum | `{block}` | `heap_blks_hit` | +| `lorekit.db.table.idx_blks_read` | sum | `{block}` | `idx_blks_read` — all of the table's indexes | +| `lorekit.db.table.idx_blks_hit` | sum | `{block}` | `idx_blks_hit` | +| `lorekit.db.table.autovacuum_count` | sum | `{run}` | `autovacuum_count` | +| `lorekit.db.table.live_tup` | **gauge** | `{row}` | `n_live_tup` (an estimate) | +| `lorekit.db.table.dead_tup` | **gauge** | `{row}` | `n_dead_tup` (an estimate; drops when vacuum runs) | + +The sums are cumulative since the database's last `pg_stat_reset()` +(`pg_stat_database.stats_reset`, the epoch when never reset), exported the same +way as the query sums. The two tuple counts are gauges because they go down: as +a monotonic sum, every vacuum would read as a counter reset. + +Useful queries: + +- HOT ratio: `rate(tup_hot_upd) / rate(tup_upd)` by `db.table` — near 1 for + `memories` once 00124's fillfactor room is in use. +- Disk reads: `rate(heap_blks_read) + rate(idx_blks_read)` by `db.table`. +- Buffer hit ratio: `rate(heap_blks_hit) / (rate(heap_blks_hit) + rate(heap_blks_read))`. + +Adding a table means a new migration that redefines the allowlist: it is a +constant in the function, never caller-supplied, because each table is 13 more +series. + ### Cardinality Each statement is one series **per metric**, so top-N is the dial. The endpoint @@ -283,7 +330,11 @@ select vault.create_secret('', 'lorekit_profiling_key'); The gate is in one place, so this is the whole switch: no migration re-run and no schedule edit. Turn it off again by deleting either secret. -Requires the `pg_stat_statements` extension (Supabase preloads it). It needs no +The same two secrets switch on both families, `lorekit.db.query.*` and +`lorekit.db.table.*`; there is no separate switch for the table counters. + +Requires the `pg_stat_statements` extension (Supabase preloads it) for the query +family; the table family reads built-in views and needs nothing. It needs no new Dash0 credentials — the `profiling` function exports through the same `OTEL_EXPORTER_OTLP_*` secrets every other function already uses. diff --git a/supabase/functions/CLAUDE.md b/supabase/functions/CLAUDE.md index f9ce91bf..f128132e 100644 --- a/supabase/functions/CLAUDE.md +++ b/supabase/functions/CLAUDE.md @@ -72,7 +72,7 @@ resource-attribute list: a metric on a different resource than the spans beside it silently stops correlating in Dash0. The `profiling` function is the operator surface for query-level profiling -(`pg_stat_statements` → Dash0 metrics). It is service-role ONLY and deliberately +(`pg_stat_statements` and per-table `pg_stat_user_tables` counters → Dash0 metrics). It is service-role ONLY and deliberately does not use `createRouter` — a cron poke is not a tenant request and must not land in `usage_events`. See [docs/otel.md](../../docs/otel.md) → "Query-level profiling". From df3666b650006620665cfc591ee28039b13fced4 Mon Sep 17 00:00:00 2001 From: mthines Date: Wed, 25 Nov 2026 19:54:58 +0100 Subject: [PATCH 5/6] fix(profiling): say so when only the table metrics export --- docs/otel.md | 4 ++-- supabase/functions/profiling/index.ts | 19 ++++++++++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/docs/otel.md b/docs/otel.md index 4708dbd3..8c42b412 100644 --- a/docs/otel.md +++ b/docs/otel.md @@ -425,10 +425,10 @@ cron job reporting success while nothing reaches Dash0: | Status | Meaning | |--------|---------| -| `200` | Exported | +| `200` | Exported. With `pg_stat_statements` absent or unreadable, only `lorekit.db.table.*` is sent: the body carries `warnings` and the span a `WARN` log | | `401` | Not the service-role key. A user JWT and an `lk_*` token are both refused — these counters are the cluster's, not a caller's | | `502` | Dash0 rejected the payload or was unreachable | -| `503` | Nothing to send, or nowhere to send it: `pg_stat_statements` absent/unreadable, or `OTEL_EXPORTER_OTLP_ENDPOINT` unset | +| `503` | Nothing to send, or nowhere to send it: neither reader returned a row, or `OTEL_EXPORTER_OTLP_ENDPOINT` unset | The reader never raises. A missing extension, one installed but absent from `shared_preload_libraries`, a version too old for `toplevel`, or a privilege diff --git a/supabase/functions/profiling/index.ts b/supabase/functions/profiling/index.ts index a9a3bf03..785cf919 100644 --- a/supabase/functions/profiling/index.ts +++ b/supabase/functions/profiling/index.ts @@ -92,9 +92,9 @@ Deno.serve((req: Request) => // `DbQueryStatRow[]`. Passing the bare row type here would compile and then // hand `buildDbQueryMetrics` a single object where it expects an array. // - // The two reads are independent, so they run concurrently; either failing - // fails the scrape the same way, since a half export would read on a - // dashboard as one family of metrics quietly stopping. + // The two reads are independent, so they run concurrently. Either one + // ERRORING fails the scrape the same way: a half export after a failed read + // would read on a dashboard as one family of metrics quietly stopping. const db = createTracedClient(resolved.db, span); const [queries, tables] = await Promise.all([ db.rpc('lorekit_db_query_stats', { p_limit: limit }), @@ -123,12 +123,25 @@ Deno.serve((req: Request) => 'lorekit.profiling.exported': result.exported, }); + // `pg_stat_statements` absent or unreadable is NOT an error: 00074's reader + // turns it into zero rows, and the table family still exports. It is a + // half export by configuration, so it is said out loud — a WARN log and a + // `warnings` entry — rather than hidden behind a bare 200. + const warnings: string[] = []; + if (rows.length === 0) { + warnings.push('pg_stat_statements returned no rows: lorekit.db.query.* not exported'); + span.log('WARN', 'Profiling: pg_stat_statements returned no rows; only lorekit.db.table.* exported', { + 'lorekit.profiling.tables': tableRows.length, + }); + } + const body = { exported: result.exported, statements: rows.length, tables: tableRows.length, datapoints: result.points, metrics: metrics.map((m) => m.name), + ...(warnings.length ? { warnings } : {}), ...(result.error ? { reason: result.error } : {}), }; From 8c96b4c21fc57d14d390ce69bf05bfd8545670bb Mon Sep 17 00:00:00 2001 From: mthines Date: Wed, 25 Nov 2026 19:55:17 +0100 Subject: [PATCH 6/6] fix(db): use the standard search_path on lorekit_db_table_stats --- supabase/byod/bootstrap.sql | 2 +- supabase/migrations/00125_db_table_stats.sql | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/supabase/byod/bootstrap.sql b/supabase/byod/bootstrap.sql index 08b468ce..9b226c14 100644 --- a/supabase/byod/bootstrap.sql +++ b/supabase/byod/bootstrap.sql @@ -27056,7 +27056,7 @@ returns table ( language sql stable security definer -set search_path = public, pg_catalog +set search_path = public as $$ select s.relname::text, diff --git a/supabase/migrations/00125_db_table_stats.sql b/supabase/migrations/00125_db_table_stats.sql index 132bfaf6..3c0a99e2 100644 --- a/supabase/migrations/00125_db_table_stats.sql +++ b/supabase/migrations/00125_db_table_stats.sql @@ -55,7 +55,7 @@ returns table ( language sql stable security definer -set search_path = public, pg_catalog +set search_path = public as $$ select s.relname::text,