Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 4 additions & 2 deletions docs/key-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down Expand Up @@ -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`) |
Expand Down
63 changes: 57 additions & 6 deletions docs/otel.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**:
Expand Down Expand Up @@ -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
Expand All @@ -283,7 +330,11 @@ select vault.create_secret('<service-role-key>', '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.

Expand Down Expand Up @@ -374,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
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/shared/mirror-pairs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading