Skip to content

sql: track SQL-defined functions in the registry and refuse to pin builtin relations - #41025

Open
mgree wants to merge 7 commits into
builtin-registry-agg-table-sqlfrom
builtin-registry-sql-defined
Open

mgree wants to merge 7 commits into
builtin-registry-agg-table-sqlfrom
builtin-registry-sql-defined

Conversation

@mgree

@mgree mgree commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

PR 3 of SQL-923.

Description

The builtin registry tracks scalar functions, aggregate and table functions (#40912), and now SQL-defined functions. Each pin records the SQL-defined builtins it may have inlined, so a later change to one can be traced to the pins it affects.

To know what a pin inlined, catalog items now keep the ids planning resolves inside the bodies of the SQL-defined functions they call, transitively. Planning already computed these for an RBAC check and discarded them. They are now kept in memory next to resolved_ids, outside uses(), since a builtin body's references are not user-visible dependencies. Pinning walks the export, the user views and pending replacements planning inlines into it, and these function bodies. It also records what the keys of imported indexes inline.

Pinning rejects any object that depends on a builtin relation, directly, through user views, or through a function body. That includes builtin views that read no collection, such as mz_timezone_names, which leave no import behind once inlined, and reads that constant folding removes. Recording such views instead could come later without invalidating existing pins.

Pinning also rejects any object that reaches an unstable builtin, including through a function body. (Even with unsafe_enable_unstable_dependencies, since pinning such an object will always be a footgun.) In practice this makes objects calling the has_*_privilege family unpinnable.

Verification

New tests of the rebuilt registry and of pinning: recorded SQL-defined functions through views, nested calls captured from function bodies and refused when folding hides them, functions inlined into imported index keys, pending replacements, and the refusals for builtin relations and unstable builtins.

@mgree
mgree marked this pull request as ready for review November 23, 2026 18:07
@mgree
mgree requested review from a team as code owners November 23, 2026 18:07
@mgree
mgree changed the base branch from main to builtin-registry-agg-table-sql November 23, 2026 18:08
@mgree
mgree added this pull request to stack #40921 November 23, 2026 18:08
@def-

def- commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

QA LLM Review

1. MEDIUM -- Constant folding hides nested SQL functions from the pin

src/adapter/src/optimize/pinned.rs:162

A materialized view selecting mz_catalog.has_role(NULL::oid, 1::oid, 'USAGE') pins a constant NULL and records only mz_catalog.has_role. The result comes from the SQL body of pg_catalog.pg_has_role, so a migration selecting pins by that function's name misses this one.

Details

The outer function delegates directly to pg_has_role at src/sql/src/func.rs:4481. Its NULL branch precedes the read of mz_roles at src/sql/src/func.rs:2793. The new test accepts the body because name resolution sees that collection at src/adapter/src/optimize/pinned_tests.rs:1299, but constant folding removes the read before the pin checks its imports. Recording the nested function IDs gathered during planning, or rejecting these pins based on the dependencies before optimization, would cover this case.

2. MEDIUM -- Pins omit SQL functions embedded in imported index keys

src/compute-types/src/plan/pinned.rs:465

Give a table with a bigint column n a single index on pg_catalog.pg_encoding_to_char(n). A materialized view that reads SELECT n FROM t through that index stores the expanded function body in its pin, but its inlined_builtins set is empty. Replanning just the pins that list the function leaves this reader with a stale index key.

Details

The optimizer copies the index key into the import at src/adapter/src/optimize/dataflows.rs:329, and pinning serializes it at src/compute-types/src/plan/pinned.rs:406. The dependency walk starts only from exports, and the view's SQL references just the table. If the rebuilt index has a different key expression, instantiating the reader returns ImportDrift at src/compute-types/src/plan/pinned.rs:689. Include the dependencies of imported index keys when collecting the pin's builtins.

3. MEDIUM -- The registry skips nonconstant views that fold into pinned results

src/catalog/tests/builtin_registry.rs:168

A materialized view selecting EXISTS (SELECT 1 FROM pg_catalog.pg_database WHERE datistemplate) pins the constant false. That value comes from the definition of pg_database, yet the registry omits its SQL. A change to how the view computes datistemplate can therefore pass the registry check while the pin retains the old answer.

Details

pg_database reads two catalog collections but defines datistemplate as literal FALSE at src/catalog/src/builtin/pg_catalog.rs:1425. The filter eliminates both imports, so the builtin-collection check at src/compute-types/src/plan/pinned.rs:358 accepts the plan. The catalog walk records pg_database in the pin, but the snapshot only covers views whose definition reads no collection. Track the SQL of these views too, or reject pins that rely on an untracked view definition.

@mgree
mgree force-pushed the builtin-registry-sql-defined branch from 0537fa1 to c52b23a Compare November 23, 2026 21:48
@mgree mgree changed the title sql: track SQL-defined functions and constant builtin views in the registry sql: track SQL-defined functions in the registry and refuse to pin builtin relations Nov 23, 2026
@def-

def- commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

QA LLM Review

1. MEDIUM -- Metric sinks can pin builtin relations through replacement materialized views

src/adapter/src/optimize/pinned.rs:158

A metric sink can read a pending replacement materialized view whose gauge value is count(*) over mz_catalog.mz_timezone_names. Pinning accepts the sink and embeds the timezone count. Reusing that pin after the timezone list changes would publish the old count.

Details

The metric-sink planner accepts the replacement as long as its columns match the sink schema (src/sql/src/plan/statement/ddl.rs:4428). The optimizer explicitly inlines a pending replacement's definition (src/adapter/src/optimize/dataflows.rs:359), but the pin's dependency walk stops at every materialized view. The timezone rows come from a generated VALUES list, so no system import reaches the fallback check. Follow the query dependencies of pending replacements here, or reject pins that reach one.

mgree and others added 7 commits November 23, 2026 18:40
This PR extends the builtin registry to cover SQL-defined builtin functions and constant builtin views (views that read no collection, such as the time zone views generated from chrono-tz). Their SQL text goes in the source half of the snapshot, so a change needs a person to decide whether pinned plans must pick it up. Builtins in unstable schemas like mz_internal are excluded because persistent user objects can't depend on them. A new adapter test fails if a stable function's body ever reaches an unstable one in a way a pin could capture.

Pins now record which builtins they inlined, in a new inlined_builtins field. A later LIR_VERSION migration can then replan only the pins a change affects, not every pin. The way to create a pin is now PinnedDataflow::pin, which takes a PinningContext, and CatalogState is that context. Callers can't skip the inlining information by accident.
Pinning now rejects an item that depends, directly or through user views,
on any builtin relation, including a builtin view that reads no collection.
Such a view leaves no import behind once inlined, so only the catalog walk
can tell. Constant builtin views are therefore no longer recorded in the
builtin registry, and `InlinedBuiltinKind` keeps only `Func`. Recording
them can be added later without invalidating existing pins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Catalog items now keep the ids planning resolves inside the bodies of the
SQL-defined functions they call, transitively, in a new in-memory field
next to `resolved_ids`. They stay out of `uses()`: a builtin body's
references are not user-visible dependencies.

Pinning reads them, recording nested SQL-defined builtins and rejecting
builtin relations and unstable builtins reached through a body, even when
constant folding removed the call. It also records the builtins inlined
into the keys of imported indexes, which a reader copies into its plan.
This replaces the test that required SQL bodies inlining builtins to read a
collection, which constant folding defeated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Planning cannot read a pending replacement's collection, so it inlines the
replacement's definition, as it does a user view's. The pinning walk now
does the same, so a metric sink over a replacement that reads a builtin
relation is refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… test order-independent

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…and imports

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mgree
mgree force-pushed the builtin-registry-sql-defined branch from b46c056 to 937f58f Compare November 23, 2026 23:51

@ggevay ggevay left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the rework, this looks good to me. Minor comments inline.

// Constant folding can remove the read, though, so refuse on the
// reference, which keeps the rule that nothing depending on a
// builtin relation is pinned.
if referenced.is_relation() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could pin_rejects_builtin_relations also cover a builtin relation that is read only inside a function body, such as mz_roles in a materialized view over pg_catalog.pg_get_userbyid(NULL::oid)?

Two checks reject that view today: this one, and the walk's uses(), which includes what the unoptimized plan reads inside function and cast bodies. With either one disabled, the tests and 23 extra cases give the same results. With both disabled, the view is pinned and the tests still pass.

Keeping both seems right to me: this branch doesn't depend on what uses() contains, and uses() may change (SQL-439).

Separately, the doc of function_body_references says that uses() leaves these ids out. That holds for the functions and types that a body names, not for the relations that it reads.

let stmt = mz_sql::parse::parse(create_sql)?.into_element().ast;
let (stmt, resolved_ids) = mz_sql::names::resolve(catalog, stmt)?;
let (plan, _sql_impl_ids) =
let (plan, function_body_ids) =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two comments in src/sql/src/plan/statement.rs (lines 484 and 553) still say that these ids are only for the restrict_to_user_objects RBAC check. Pinning now uses them too.

Comment on lines +131 to +133
// Mirrors `DataflowBuilder::import_into_dataflow`, which inlines
// user views and pending replacements, whose collections cannot
// be read yet, and imports everything else.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this comment say what the walk follows, and how that differs from import_into_dataflow? "Mirrors" reads as if both inlined the same items. They differ in three ways:

  • import_into_dataflow imports an indexed user view through its index. The walk goes into the view's definition anyway.
  • import_into_dataflow also inlines builtin views. The walk stops at a builtin view and rejects the pin.
  • import_into_dataflow reads a view's locally optimized expression. The walk follows uses(), so it also sees reads that optimization removes.

We have many dependency traversals with slightly different rules (SQL-439), so it helps when each one states its own.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants