Skip to content

Restore SQL user-defined functions that an earlier version accepted - #122912

Merged
fm4v merged 5 commits into
ClickHouse:masterfrom
groeneai:restore-sql-udf-accepted-by-older-version
Oct 1, 2026
Merged

fm4v merged 5 commits into
ClickHouse:masterfrom
groeneai:restore-sql-udf-accepted-by-older-version

Conversation

@groeneai

@groeneai groeneai commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120483 (comment)

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed RESTORE of system.functions failing, and aborting the whole restore, when the backup holds a SQL user-defined function whose definition the version that created it accepted but CREATE FUNCTION now rejects, for example CREATE FUNCTION f AS lambda(identity(x), x) created on 25.5 or earlier.

Description

On 25.6 and later, RESTORE of a backup taken on 25.5 or earlier fails with BAD_ARGUMENTS and aborts the whole restore when it holds a function such as CREATE FUNCTION f AS lambda(identity(x), x) (measured on 26.9.1.1629). On master the same happens for CREATE FUNCTION f AS JSONExtractString((x, y), x) created on 26.4 (the linked Cloud upgrade).

Root cause. UserDefinedSQLFunctionFactory::restore registers every restored definition through the check for a new CREATE FUNCTION. Each tightening of that check (22.2: exactly two lambda arguments; #80431: the argument list is a tuple; #120483: the core is a lambda, the tuple has no parameters) made definitions stored under older rules unrestorable, although startup loading never validates them.

Change. CREATE FUNCTION now calls createFunction, which applies every rule. Registration, shared with RESTORE, checks only what DDL expansion relies on: a core with at least two arguments, the first a function of distinct identifiers (a stored f(g(1), 2) makes CREATE TABLE ... DEFAULT hit undefined behavior, (x, x) -> x silently drops an argument). So a later CREATE FUNCTION rule, #121370's included, cannot break restores again. Restored functions behave as after an in-place upgrade (a query calling a non-lambda one raises the existing LOGICAL_ERROR).

Validation. A new backward-compatibility test creates such functions and a control on 25.3, stores one that only 21.10 to 22.1 accepted, backs up, upgrades, then restores the old backup onto existing and dropped functions, and a new backup; CREATE FUNCTION still rejects the legacy ones. It fails on master and 26.9 at the first restore, passes with the fix; requiring exactly two arguments, rejecting #121370's dotted arguments on restore, or skipping the rules on CREATE fails it.

Not changed: a name that became a built-in (#121340): it would shadow the built-in, and DROP FUNCTION refuses it.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/122912]

Version info

  • Merged into: 26.10.1.1203-master (included in 26.10 and later)

groeneai and others added 2 commits September 29, 2026 15:13
`RESTORE TABLE system.functions` registers every restored definition through
`registerFunction`, whose `checkCanBeRegistered` runs `validateSQLFunction`,
the check for a new `CREATE FUNCTION`. Each time that check was tightened,
definitions stored under the older rules became unrestorable, and the first of
them aborted the whole restore:

- ClickHouse#80431 (25.6) requires the argument list to be a `tuple`, so a backup taken
  on 25.5 or earlier that holds `CREATE FUNCTION f AS lambda(identity(x), x)`
  fails on 25.6 and later with `Lambda must have valid arguments`.
- ClickHouse#120483 (master) requires the core to be a `lambda` and the tuple to have no
  parameters, so a Cloud upgrade from 26.4 failed with
  `Expected lambda expression, got: JSONExtractString((x, y), x): While
  restoring data of table system.functions`:
  ClickHouse#120483 (comment)

Loading the same definitions from disk or Keeper at startup never validates
them, so an in-place upgrade keeps them and `BACKUP` writes them out unchanged.

`restore` now passes `is_restore`, and `validateSQLFunction` then skips exactly
those two rules. The structural rules stay (the core is a function with two
arguments, the argument list holds unique identifiers, the body exists, no
self-recursion): no version accepted a definition that fails them, and the DDL
expansion in `UserDefinedSQLFunctionVisitor::tryToReplaceFunction` relies on
them without checks. `CREATE FUNCTION` is unchanged. Tables are re-created by
`RESTORE` under `LoadingStrictnessLevel::SECONDARY_CREATE`, which skips some
sanity checks for the same reason.

The new backward-compatibility test creates three such definitions and a
control on 25.3, backs them up, upgrades, and restores; it fails on master and
on 26.9.1.1629 at the first restore.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the validateSQLFunction comment to one line and write `lambda` and `tuple` as code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 29, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings over one full pass and one re-check of the final description), plus my own cold review of the diff: no blocker, no major.

# Sev Finding Verdict Evidence / action
1 💡 The description listed "no self-recursion" among the retained rules, but the existing check accepts a body whose root is the self-call (02125_recursive_sql_user_defined_functions.sql creates x -> 02125_function(x)) AGREE, fixed before publication The description now says the self-recursion check is unchanged.
2 💡 The new comment above validateSQLFunction should write lambda and tuple as code AGREE, fixed before push Comment-only change.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-10:20260929-152300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A server holding CREATE FUNCTION f AS JSONExtractString((x, y), x) in user_defined/, then BACKUP TABLE system.functions, DROP FUNCTION, RESTORE: master fails with the reported Code: 36 ... Expected lambda expression ... While restoring data of table system.functions. The new test fails at its first RESTORE on master and on 26.9.1.1629 every run.
b Root cause explained? restore registers stored definitions through the check for a new CREATE FUNCTION; #80431 (25.6) and #120483 (master) tightened it after such definitions could be stored; startup loading never validates, so they survive an in-place upgrade and BACKUP, and the first one aborts RESTORE.
c Fix matches root cause? Yes. restore passes is_restore, and only the rules added after definitions could be stored (core named lambda, argument list a plain tuple) are skipped. No tolerance path, no setting, CREATE FUNCTION unchanged.
d Test intent preserved / new tests added? New backward-compatibility integration test: three definitions 25.3 accepted plus a control, restored onto existing and dropped functions and from a new backup; CREATE FUNCTION still rejects each definition.
e Both directions demonstrated? Fails on master and on 26.9 at the first restore; passes with the fix 5/5 (3 in one session). Reverting any one of the three exemptions fails it at its own row.
f Fix is general across code paths? The only other registerFunction caller is CREATE FUNCTION (unchanged). Disk and Keeper storage, RESTORE ... ON CLUSTER and replicated UDF storage all restore through this one call; Keeper storage measured, existing backup / replicated-UDF integration tests pass.
g Fix generalizes across inputs (params/datatypes/wrappers)? All three older shapes (non-lambda core, non-tuple argument list, parametric argument list) plus a lambda control; a definition no version accepted (f(g(1), 2)) is still rejected on restore. Type wrappers do not apply (AST shape check).
h Backward compatible? (maintainer-approved exception only) Yes. RESTORE accepts strictly more; no setting, format or protocol change.
i Invariants and contracts preserved? The structural rules that DDL expansion of a stored function dereferences without checks stay enforced on restore; name-collision and exists checks unchanged; the error path unchanged. A restored non-lambda function raises the same pre-existing LOGICAL_ERROR on call as after an in-place upgrade.

Session id: cron:clickhouse-impl-slot-5:20260929-140400

@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [49b7e8c]

Summary: ✅


AI Review

Summary

This PR separates SQL UDF validation for new definitions from restore-time registration, so RESTORE only enforces the AST shape that the inliner dereferences while CREATE FUNCTION keeps the stricter current rules. I re-checked the earlier review thread against the current code and tests; the duplicate-parameter restore gap is fixed, and I did not find any remaining blocker or major issue in the current diff.

Final Verdict

✅ No remaining findings.

LLVM Coverage Report

Measured on commit 49b7e8c.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 26/26 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 29, 2026
@groeneai
groeneai requested review from vdimir and vitlibar September 29, 2026 16:23
@clickhouse-gh clickhouse-gh Bot added the comp-udf User-defined functions (SQL UDFs, executable UDFs) and UDF framework. label Sep 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 49b7e8c2d with master e28af044e (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

31 translation units recompiled, 228 s compile time in total, 31 of them have a recent master baseline.

Job report

throw Exception(ErrorCodes::BAD_ARGUMENTS, "Expected function, got: {}", function->formatForErrorMessage());

if (lambda_function->name != "lambda")
if (!is_restore && lambda_function->name != "lambda")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai are you sure there are no other cases missing?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

No, there were more. I checked every rule on the restore path against the versions that could store a definition:

  • 21.10 to 22.1 accepted a core with more than two arguments, e.g. lambda(tuple(x), x, 1), and the 22.2 arity check rejected it on restore. Covered now.
  • Reject lambda arguments a SQL user defined function cannot use #121370's rules (single-part argument names, nested lambda argument lists) would have done the same once merged. They go into validateSQLFunction, which RESTORE no longer runs, so neither PR needs another change.
  • The shape that RESTORE still checks held in every version: a definition without it threw or crashed the server in CREATE FUNCTION (fixed in 22.2 and 22.5), so none was stored.
  • Not covered: a function whose name later became a built-in (RESTORE fails with FUNCTION_ALREADY_EXISTS when a backup contains a UDF whose name is a built-in in the restoring version #121340). That is a name conflict, not a definition rule. Restoring it would shadow the built-in (a stored stddev UDF wins over the stddev aggregate, measured), and DROP FUNCTION refuses to remove it (Cannot drop system function). Tell me if you want it handled in this PR.

The test now also restores a stored three-argument core and #121370's two shapes, and checks that RESTORE still refuses f(g(1), 2): 5e6d67d.


/// Register function for function_name in factory for specified create_function_query.
bool registerFunction(const ContextMutablePtr & current_context, const String & function_name, ASTPtr create_function_query, bool throw_if_exists, bool replace_if_exists);
bool registerFunction(const ContextMutablePtr & current_context, const String & function_name, ASTPtr create_function_query, bool throw_if_exists, bool replace_if_exists, bool is_restore = false);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai I don't like the bool is_restore parameter. Is there a better way to do this?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Replaced in ca702c0. CREATE FUNCTION now calls a new createFunction, which runs validateSQLFunction with all its rules and then registerFunction. registerFunction, which restore also uses, keeps the name checks and checks only the shape that UserDefinedSQLFunctionVisitor dereferences without checks: a core with at least two arguments, the first a function whose arguments are identifiers. There is no flag, and a rule added to CREATE FUNCTION later cannot affect RESTORE.

groeneai and others added 2 commits September 29, 2026 20:28
…ions

Replace the `is_restore` flag with a separate entry point for new definitions.
`createFunction`, called by `CREATE FUNCTION`, applies every rule of
`validateSQLFunction`. `registerFunction`, used by both `CREATE FUNCTION` and
`RESTORE`, checks only the shape that `UserDefinedSQLFunctionVisitor`
dereferences without checks: a function core with at least two arguments, the
first a function whose arguments are identifiers.

A rule added to `CREATE FUNCTION` later can no longer make stored definitions
unrestorable. This also covers a core with more than two arguments, which
versions 21.10 to 22.1 accepted before the arity check of 22.2, and the argument
rules pending in ClickHouse#121370. The test gains rows for both.

Review: ClickHouse#122912 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nctions

Every version since 21.10 rejected duplicate lambda parameters in `CREATE FUNCTION`,
so only a hand-written storage file can hold such a definition. `RESTORE` rejected it
until the previous change, and should keep doing so: `UserDefinedSQLFunctionVisitor`
maps parameters to arguments with `emplace`, so `(x, x) -> x` silently ignores its
second argument when expanded, e.g. `DEFAULT f(a, 7)` is stored as `DEFAULT a`.

The test now also restores a backup holding `(x, x) -> x` and expects `BAD_ARGUMENTS`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim

Copy link
Copy Markdown
Member

@fm4v the PR looks good to me. Can you give a review?

@fm4v
fm4v added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit df7b331 Oct 1, 2026
149 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-udf User-defined functions (SQL UDFs, executable UDFs) and UDF framework. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants