mirror of
https://github.com/supabase/supabase.git
synced 2026-10-06 01:45:10 +03:00
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Bug fix (performance), plus a regression-guard test suite and docs. ## What is the current behavior? Studio's introspection queries in `@supabase/pg-meta` do `O(catalog)` work for per-table requests. On databases with very large catalogs (hundreds of thousands of relations/constraints — real deployments reach this) they take tens of seconds per dashboard interaction, trip `statement_timeout`, and create heavy CPU/memory pressure when several tabs open concurrently. Two instances of the same bug class: **1. Table Editor query (`getTableEditorSql`)** — fetches metadata for ONE table by OID, but five catalog scans are unscoped and only filtered at the top-level join: - `primary_keys` CTE — scans all of `pg_index` (`where i.indisprimary`) - `index_cols` CTE — scans all unique indexes - `relationships` CTE — scans every FK in `pg_constraint` (and is scanned twice by the two subplans) - `uniques` subquery (inside `columns`) — scans all single-column unique constraints - `check_constraints` subquery (inside `columns`) — scans all single-column check constraints The planner cannot push the outer join qual into grouped / `distinct on` subqueries, so each is computed over the full catalog and thrown away. `tables-paginated.ts` was previously rewritten to avoid exactly this pattern; the single-table query never got the same treatment. **2. Entity definitions (`getTableDefinitionSql` / `getEntityDefinitionsSql`)** — the vendored `pg_get_tabledef` plpgsql function scans the entire `information_schema.columns` view once **per column** (plus `information_schema.tables` once per call) just to decide whether a name needs double-quoting — a pure string property of a name it already holds — and its per-index partial-index lookup casts `relnamespace::regnamespace::text` across every `pg_class` row. On a 12K-table catalog this makes a single entity's DDL cost ~3.7s and a default 100-entity definitions page ~6 minutes. ## What is the new behavior? **Fix 1 — scope the Table Editor CTEs to the requested OID** (`id` is validated non-null and interpolated via `literal()`, same as the existing `base_table_info` filter): - `primary_keys` / `index_cols`: `and i.indrelid = <id>` - `relationships`: `and (c.conrelid = <id> or c.confrelid = <id>)` - `uniques` / `check_constraints`: `and conrelid = <id>` Semantics are unchanged: the top-level select already filtered every CTE to the target table, so rows for other tables were computed and discarded. The `pg_index`/`pg_constraint` lookups become index scans returning a handful of rows. One residual scan is structural: PostgreSQL has no index on `pg_constraint.confrelid`, so the incoming-FK half of `relationships` is a single filtered seq scan of `pg_constraint` — still one cheap pass instead of materializing every FK row twice. **Fix 2 — remove the O(catalog) scans inside `pg_get_tabledef`**: the information_schema uppercase checks are replaced with direct regex tests on the name in hand (preserving the original's `quote_ident` behavior for schemas that need quoting), and the partial-index lookup is scoped by the already-resolved table OID. Original statements are kept as comments, matching the vendored file's convention. **Regression guard** — so this bug class stays out: - `test/db/stress-catalog.ts` builds a synthetic catalog (default 2,000 tables with PKs, unique + check constraints, FK chains and an FK hub; `PG_META_STRESS_TABLES` scales it to incident size). - `test/db/plan-guard.ts` provides `EXPLAIN (ANALYZE, FORMAT JSON)`-based budget assertions: a query's plan may only seq-scan a scaling catalog if its budget entry carries a written structural justification (e.g. no index on `pg_constraint.confrelid`; no index on `pg_class.relnamespace` for per-schema listings), plus a per-query time bound (the only guard available for opaque plpgsql internals like `pg_get_tabledef`). - `test/sql/studio/catalog-plan-guard.test.ts` applies budgets to the hot-path studio queries: table editor, constraints, FK listing, entity types, tables-paginated, columns, indexes, table/entity definitions, views. Reverting either fix makes the suite fail immediately with the offending scans listed. - `test/sql/studio/table-editor.test.ts` (new — none existed) asserts the Table Editor query's semantics: primary keys, unique indexes, both FK directions, `is_unique`, check definitions, column comments. - A new package `README.md` documents the plan-guard budget entry as a requirement for any new introspection query. ### Validation (synthetic 12,000-table catalog, PostgreSQL 17.6) - **Output equivalence, fix 1:** for 12 relation types (regular, composite PK, partitioned parent + partition, view, materialized view, constraint-free table, FK hub/chain/tail, and a fixture with enums/domains/generated/identity columns and duplicate check constraints), the `entity` jsonb from the old and new query is byte-identical. - **Output equivalence, fix 2:** byte-identical DDL across 13 fixture combinations (serial/identity/generated/array columns, case-sensitive and keyword names, mixed-case schemas, partitions, unlogged + reloptions, partial/expression indexes, external PK/FK/comments/trigger variants). - **Performance, fix 1:** Table Editor query `EXPLAIN ANALYZE` ~1,630ms → ~30ms (~50×); the gap grows with catalog size since the old query is O(catalog) per call. - **Performance, fix 2:** single entity definition 3,672ms → 63ms; a 100-entity definitions page ~6min → 0.87s. The plan-guard bound for `getEntityDefinitionsSql` tightens accordingly from 15s/25 entities to 3s/100 entities (330ms measured at default test scale). Verified locally: `catalog-plan-guard` (12 tests), `table-editor`, `tables-paginated` (16 tests) pass; `typecheck` clean. ### Rollout Per review, the new behavior ships **dark** behind the `pgMetaScopedIntrospection` ConfigCat flag (default off = legacy SQL, kept as full duplicated templates in pg-meta and verified byte-identical to the pre-PR queries). Studio reads the flag in the query hooks and threads it through (flag state is part of the React Query keys). The rollout is staged in the ConfigCat dashboard via user-email targeting (like every other ConfigCat flag): target the reporting user's email first, then a percentage rollout, then 100%. Server-side AI callers of `getEntityDefinitionsSql` stay on the legacy path. Once fully rolled out, delete the legacy templates + flag in a cleanup PR. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Closes: PGMETA-122 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Bug Fixes** - Improved table editor SQL to correctly scope primary keys, indexes, uniques, checks, and relationships to the selected table. - Optimized table definition SQL to reduce unnecessary catalog scanning for uppercase-name detection and partial-index detection. - **Tests** - Added SQL generator tests for table editor metadata (keys, indexes, relationships, comments, and constraints). - Added catalog query plan guard coverage with a stress catalog and EXPLAIN-based scoping/performance budgets. - **Documentation** - Expanded documentation on catalog query plan safeguards and how to keep new introspection queries properly scoped. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
181 lines
7.3 KiB
TypeScript
181 lines
7.3 KiB
TypeScript
/**
|
|
* Shared EXPLAIN plan-budget harness for hot-path Studio introspection queries.
|
|
*
|
|
* ── THE RULE ──────────────────────────────────────────────────────────────
|
|
* Every new introspection query added under `src/sql/` that is executed on a
|
|
* user's live catalog (Table Editor, Database pages, entity lists, definitions,
|
|
* ...) MUST get a budget entry in `test/sql/studio/catalog-plan-guard.test.ts`.
|
|
*
|
|
* Seq scans over catalogs that SCALE with schema size -- pg_class, pg_attribute,
|
|
* pg_index, pg_constraint, pg_attrdef, pg_description, pg_depend, pg_policy,
|
|
* pg_trigger, pg_rewrite, ... -- are only acceptable with a written STRUCTURAL
|
|
* justification (e.g. "no index exists on pg_constraint.confrelid"). An unscoped
|
|
* O(catalog) scan with no such justification is a bug: a production catalog had
|
|
* ~267K pg_class rows and unscoped CTEs turned a single Table Editor open into
|
|
* 30-58s of seq scans. Scope your query to the requested OID/schema instead.
|
|
*
|
|
* Tiny, fixed-size system catalogs (see TINY_NON_SCALING_CATALOGS) are always
|
|
* tolerated: the planner full-scans them because they hold a handful of rows and
|
|
* do not grow with the number of tables.
|
|
* ────────────────────────────────────────────────────────────────────────────
|
|
*/
|
|
|
|
import type { createTestDatabase } from './utils'
|
|
|
|
type TestDatabase = Awaited<ReturnType<typeof createTestDatabase>>
|
|
|
|
/**
|
|
* Tiny, fixed-size system catalogs (a handful of schemas/FDWs/enums/procs) that
|
|
* PostgreSQL's planner will always choose to seq scan regardless of query
|
|
* scoping, because a full scan of a handful of rows is cheaper than an index
|
|
* scan. These don't grow with table count and are unrelated to the O(catalog)
|
|
* regression this harness guards against, which is specifically about catalogs
|
|
* that scale with the number of tables/columns/indexes/constraints (pg_class,
|
|
* pg_attribute, pg_index, pg_constraint, ...).
|
|
*/
|
|
export const TINY_NON_SCALING_CATALOGS = new Set([
|
|
'pg_namespace',
|
|
'pg_foreign_table',
|
|
'pg_foreign_server',
|
|
'pg_foreign_data_wrapper',
|
|
'pg_enum',
|
|
'pg_proc',
|
|
])
|
|
|
|
/**
|
|
* Recursively walk an EXPLAIN (FORMAT JSON) plan tree and collect the relation
|
|
* name of every `Seq Scan` node. Returns one entry per seq-scan node (so a
|
|
* relation scanned twice appears twice).
|
|
*/
|
|
export function collectSeqScans(
|
|
node: unknown,
|
|
out: Array<string | undefined> = []
|
|
): Array<string | undefined> {
|
|
if (Array.isArray(node)) {
|
|
for (const item of node) collectSeqScans(item, out)
|
|
} else if (node !== null && typeof node === 'object') {
|
|
const obj = node as Record<string, unknown>
|
|
if (obj['Node Type'] === 'Seq Scan') {
|
|
out.push(obj['Relation Name'] as string | undefined)
|
|
}
|
|
for (const key of Object.keys(obj)) {
|
|
collectSeqScans(obj[key], out)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
export type ExplainResult = {
|
|
/** The top-level plan node (`{ Plan, "Execution Time", ... }`). */
|
|
plan: { Plan: unknown; 'Execution Time': number }
|
|
/** Relation name of every seq-scan node found in the plan (one per node). */
|
|
seqScans: Array<string | undefined>
|
|
/** Measured execution time in milliseconds. */
|
|
executionTimeMs: number
|
|
}
|
|
|
|
/**
|
|
* Run `EXPLAIN (ANALYZE, FORMAT JSON)` on a SQL fragment and return the plan
|
|
* together with the flattened list of seq-scanned relations and the measured
|
|
* execution time.
|
|
*/
|
|
export async function explainAnalyze(
|
|
db: TestDatabase,
|
|
sqlFragment: string
|
|
): Promise<ExplainResult> {
|
|
const [row] = await db.executeQuery<Array<Record<string, any>>>(
|
|
`explain (analyze, format json) ${sqlFragment}`
|
|
)
|
|
const [plan] = row['QUERY PLAN'] as Array<{ Plan: unknown; 'Execution Time': number }>
|
|
return {
|
|
plan,
|
|
seqScans: collectSeqScans(plan.Plan),
|
|
executionTimeMs: plan['Execution Time'],
|
|
}
|
|
}
|
|
|
|
export type PlanBudget = {
|
|
/**
|
|
* Seq scans on scaling catalogs that are structurally unavoidable, keyed by
|
|
* relation name. `max` caps how many seq-scan nodes on that relation are
|
|
* allowed; `reason` is the written structural justification (shown on
|
|
* failure). Prefix a reason with `KNOWN ISSUE:` to flag a suspected unscoped
|
|
* scan that still needs a follow-up fix.
|
|
*/
|
|
allowedSeqScans?: Record<string, { max: number; reason: string }>
|
|
/** Upper bound on measured execution time, in ms. Defaults to 1000. */
|
|
maxExecutionTimeMs?: number
|
|
}
|
|
|
|
/**
|
|
* Assert an EXPLAIN result stays within its plan budget:
|
|
* - tiny non-scaling catalogs are always tolerated,
|
|
* - every other seq scan must match an `allowedSeqScans` entry and stay at or
|
|
* under its `max`,
|
|
* - execution time must stay under `maxExecutionTimeMs` (default 1000ms).
|
|
*
|
|
* Failures are actionable: they name the offending relations, dump the full
|
|
* seq-scan list, and restate the rule so the developer knows to scope the query
|
|
* or add a justified budget entry.
|
|
*
|
|
* Throws an `Error` describing the first violation; the caller (a vitest `test`)
|
|
* surfaces it as a failed assertion.
|
|
*/
|
|
export function assertPlanWithinBudget(result: ExplainResult, budget: PlanBudget = {}): void {
|
|
const allowed = budget.allowedSeqScans ?? {}
|
|
const maxExecutionTimeMs = budget.maxExecutionTimeMs ?? 1000
|
|
|
|
const seqScans = result.seqScans
|
|
const seqScanList = JSON.stringify(seqScans)
|
|
|
|
// Count seq-scan nodes per relation, ignoring tolerated tiny catalogs.
|
|
const counts = new Map<string, number>()
|
|
const offending: string[] = []
|
|
for (const relation of seqScans) {
|
|
if (!relation) {
|
|
offending.push('(unknown relation)')
|
|
continue
|
|
}
|
|
if (TINY_NON_SCALING_CATALOGS.has(relation)) continue
|
|
if (!(relation in allowed)) {
|
|
offending.push(relation)
|
|
continue
|
|
}
|
|
counts.set(relation, (counts.get(relation) ?? 0) + 1)
|
|
}
|
|
|
|
if (offending.length > 0) {
|
|
throw new Error(
|
|
`Unexpected seq scan(s) on scaling catalog(s): ${offending.join(', ')}.\n` +
|
|
`RULE: scope your query to the requested OID/schema so it uses an index, ` +
|
|
`or -- if the scan is structurally unavoidable -- add a justified budget ` +
|
|
`entry to allowedSeqScans with a written reason.\n` +
|
|
`Tolerated tiny non-scaling catalogs: ${[...TINY_NON_SCALING_CATALOGS].join(', ')}.\n` +
|
|
`Declared allowedSeqScans: ${Object.keys(allowed).join(', ') || '(none)'}.\n` +
|
|
`All seq scans in plan: ${seqScanList}`
|
|
)
|
|
}
|
|
|
|
for (const [relation, { max, reason }] of Object.entries(allowed)) {
|
|
const found = counts.get(relation) ?? 0
|
|
if (found > max) {
|
|
throw new Error(
|
|
`Too many seq-scan nodes on ${relation}: found ${found}, budget allows ${max}.\n` +
|
|
`Reason on file: "${reason}".\n` +
|
|
`A higher count usually means a new unscoped scan crept in -- scope it or ` +
|
|
`raise the budget with justification.\n` +
|
|
`All seq scans in plan: ${seqScanList}`
|
|
)
|
|
}
|
|
}
|
|
|
|
if (result.executionTimeMs >= maxExecutionTimeMs) {
|
|
throw new Error(
|
|
`Query took ${result.executionTimeMs.toFixed(1)}ms, budget is ${maxExecutionTimeMs}ms. ` +
|
|
`At stress scale this signals O(catalog) work -- scope the query to the ` +
|
|
`requested OID/schema.\n` +
|
|
`All seq scans in plan: ${seqScanList}`
|
|
)
|
|
}
|
|
}
|