Repository navigation
Reject lambda arguments a SQL user defined function cannot use - #121370
Conversation
validateSQLFunction constrained every lambda argument to be a unique
ASTIdentifier but never tested how many name parts it has, while
QueryTreeBuilder::buildExpression, the only component that can evaluate a lambda
UDF in a query, rejects name_parts.size() > 1 unconditionally and keys its own
duplicate check on name_parts[0]. So
CREATE FUNCTION udf_multipart AS lambda(tuple(x.y), 1)
was accepted, normalized, written to user_defined/ and reloaded after a restart,
and then every call to it raised BAD_ARGUMENTS. The object was permanently
unusable in any SELECT and no setting could rescue it: the analyzer's clause
guards every lambda rather than a UDF core specifically, enable_analyzer is
obsolete and frozen at 1 since v26.9, and the old query analysis was removed in
v26.10.
Registration is the only gate before persistence, so the missing clause belongs
there rather than at the consumer, and one clause covers every producer because
they all converge on registerFunction: both spellings of CREATE FUNCTION, CREATE
OR REPLACE, ON CLUSTER replay and the clickhouse_json AST route. It mirrors the
analyzer's order, ahead of the duplicate check, and reuses its wording. The
clause-by-clause checks around it are left alone so the messages SQL users
already get for the other malformed shapes do not change. After this clause the
two duplicate keys agree, because full_name equals name_parts[0] for every
surviving identifier, where before they disagreed on tuple(a.x, b.x).
The load paths are deliberately untouched. setAllObjects runs
normalizeCreateFunctionQuery only, so a function already stored with this shape
still loads, still lists in system.functions, still reports the same analyzer
error on use and is still droppable, measured across a server restart as well as
a fresh-process reload. What does change is RESTORE, which re-registers through
registerFunction and therefore now fails on a backup that already contains such
a function; every clause already in validateSQLFunction has that property, and
the restored function could not have been called anyway.
The shape was not merely dead. UserDefinedSQLFunctionVisitor keys its parameter
map and its body lookup on full_name, so before this change
CREATE FUNCTION udf_mp AS (x.y) -> x.y + 1
computed in a column DEFAULT, measured as 2, while the same function raised
BAD_ARGUMENTS in a SELECT. Removing that divergence for new functions is the
point of rejecting at CREATE.
Each of the four new rows in 02181 is accepted on master and rejected here,
measured alone against a fresh path so no row's verdict depends on another's. The
fifth row is a negative control: a backquoted `x.y` is one name part, so it must
pass the new clause and fail at the later recursiveness check with
CANNOT_CREATE_RECURSIVE_FUNCTION. Because that row is green both before and
after, it was proved non-vacuous on a build keyed on the spelling,
full_name.find('.') != String::npos, where that row alone reddens while the
other four stay green.
Closes: ClickHouse#121197
Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 1 finding), plus my own cold review of the diff: no blocker, no major, 3 nits, all no-action.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-48:20260921-133900 |
|
Workflow [PR], commit [21899ba] Summary: ✅
AI ReviewSummaryThis PR moves SQL UDF lambda-argument validation into Findings❌ Blockers
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit 21899ba.
Changed lines: Changed C/C++ lines covered: 25/27 (92.59%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260921-124300 |
| CREATE FUNCTION 02181_invalid_lambda AS lambda(x); --{serverError BAD_ARGUMENTS} | ||
| CREATE FUNCTION 02181_invalid_lambda AS lambda(); --{serverError BAD_ARGUMENTS} | ||
| CREATE FUNCTION 02181_invalid_lambda AS lambda(tuple(x)) --{serverError BAD_ARGUMENTS} | ||
| CREATE FUNCTION 02181_invalid_lambda AS lambda(tuple(x)); --{serverError BAD_ARGUMENTS} |
There was a problem hiding this comment.
@groeneai what about arrays and maps? Those should be rejected too
There was a problem hiding this comment.
Measured on the current head, arrays and maps are already rejected, by three separate clauses: the arrow spelling never parses as a lambda, so ([a, b]) -> 1 and (map('a', 1)) -> 1 are SYNTAX_ERROR; lambda(tuple([a, b]), 1) and lambda(tuple(map('a', 1)), 1) hit "Lambda argument must be identifier"; lambda([x], x + 1) hits "Lambda must have valid arguments". I added rows for all three so that coverage is visible rather than incidental.
Your question did find a real hole next to them. The validator only inspected the outer argument list, so a lambda nested in the body, which is exactly where arrays and maps are consumed, was stored and then failed on every call just like the reported case: (x) -> arrayMap(y.z -> y.z + x, [1, 2]), (x) -> mapApply((k.a, v) -> (k.a, v), map('a', 1)), (x) -> (y.z -> y.z + x). 5751216 validates nested lambdas recursively with the rules the analyzer itself applies, at any depth and inside a subquery, and keeps name sets per lambda so (x) -> arrayMap(x -> x + 1, [1, 2]) still registers and evaluates. 02181 now has 12 failing rows, two of them controls that must reach the recursion check instead.
I also moved the changelog category to Improvement: this adds validation for a definition that was accepted and then failed on use, not a wrong result in a release.
| if (!argument_identifier) | ||
| throw Exception(ErrorCodes::BAD_ARGUMENTS, "Lambda argument must be identifier"); | ||
|
|
||
| if (argument_identifier->name_parts.size() > 1) |
There was a problem hiding this comment.
registerFunction is also the RESTORE TABLE system.functions path, and storeObject only applies the default create_function = kCreateIfNotExists policy after this validator runs. That means an older backup that already contains one of these persisted x.y-parameter UDFs will now abort restore (even onto a server that already loaded the same object at startup), which is a backward-compatibility break rather than just "reject new creates". Please keep the create-time check, but add a compatibility path for restore/load of legacy definitions.
validateSQLFunction inspected the outer lambda's argument list only, so a lambda
nested in the body reached persistence with an argument the analyzer refuses.
That is the same defect as the outer case, one level down:
CREATE FUNCTION f AS (x) -> arrayMap(y.z -> y.z + x, [1, 2])
was accepted, written to user_defined/ and reloaded, and then every call raised
BAD_ARGUMENTS from QueryTreeBuilder::buildExpression, which applies its three
lambda argument checks to every lambda it builds rather than to a UDF core
specifically. Measured the same way when the body itself is that lambda, for mapApply, for two
levels of nesting, and for a lambda inside a subquery in the body; with this
change each is refused at DDL time and nothing is written.
Arrays and maps in a parameter position were already refused and are unchanged
here, by three separate clauses: the arrow spelling never parses as a lambda, so
([a, b]) -> 1 is a SYNTAX_ERROR before the validator runs; lambda(tuple([a, b]),
1) and lambda(tuple(map('a', 1)), 1) hit "Lambda argument must be identifier";
lambda([x], x + 1) hits "Lambda must have valid arguments". Rows pin all three so
the coverage is visible rather than incidental.
The per-argument loop is extracted so both levels share one implementation, and
the name set stays per lambda, which keeps shadowing legal exactly as the
analyzer has it: (x) -> arrayMap(x -> x + 1, [1, 2]) still registers and still
evaluates. The duplicate clause now reaches nested lambdas as well, so
(x) -> arrayMap((y, y) -> y, [1, 2]), previously accepted and then rejected on
every call with the analyzer's "multiple arguments with same name y", is refused
at CREATE.
The walk keys on isASTLambdaFunction, the predicate QueryTreeBuilder itself uses
to decide what is a lambda, so it refuses the nested shapes the analyzer refuses
and nothing beyond them. Name resolution in the body stays deferred as before: a
body may still reference a function that does not exist yet.
02099 is the only test in the tree that creates a UDF whose body holds a nested
lambda; its arguments are single-part and it stays green, and no test or
documentation page declares a dotted nested parameter. The last new row is a
negative control that shadows and recurses, so it must pass the new clause and
fail at the recursiveness check with CANNOT_CREATE_RECURSIVE_FUNCTION, which it
does on master and here.
Closes: ClickHouse#121197
Co-Authored-By: Claude Opus 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 9 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - 5751216Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
This pull request changes SQL UDF argument validation only, and Session id: cron:our-pr-ci-monitor:20260922-000113 |
|
On the inliner finding above: the first remedy (teach the inliner lambda scope) is the right one and it reproduces on master, but I do not think it can ship as a small change, and I would like your call on the shape. Nothing below changes this PR, which stays registration-time validation only.
Inward, it overwrites a nested lambda's own parameter. That is the Outward, it splices an argument under a lambda that binds one of the argument's own identifiers. With The two halves are not separable. With Making the substitution capture-avoiding needs the inliner to know what it is splicing before it splices. A collision test on the raw argument rejects valid compositions whose colliding identifier disappears during inlining, for example So: reject, alpha-rename, or leave the AST inliner as it is for these shapes? I will implement whichever you prefer, in its own PR. |
|
@vdimir can you give a final look? Seems good to me |
|
|
||
| void validateNestedLambdaArgumentLists(const IAST & node) | ||
| { | ||
| const auto * nested_lambda = node.as<ASTFunction>(); |
There was a problem hiding this comment.
@groeneai not sure if stack check would be needed here
There was a problem hiding this comment.
No, and the depth exposure here is not new either.
validateSQLFunctionRecursiveness just below does the same unguarded recursion over the same function_body, and the two walks are sequential rather than nested, so peak depth is unchanged from master. The numbers below are measured on master for that reason.
What bounds the tree before either walk runs:
CREATE FUNCTIONgoes throughexecuteQuery, which appliesmax_ast_depth(default 1000) viaIAST::checkDepth, andcheckDepthImplis iterative, so the check itself cannot overflow. With defaults, a body of 500 nestedtoString(calls, or 200 nested lambdas, is rejected withCode: 167 TOO_DEEP_ASTbefore any interpreter runs.- With
max_ast_depth=0 max_parser_depth=0 max_parser_backtracks=0, the parse becomes the binding limit:IParser::Pos::increaseDepthsamplescheckStackSize()and throwsCode: 306 TOO_DEEP_RECURSIONat 4.19 MB of an 8.38 MB stack. 1200 nestedtoString(levels parse and create fine, 1400 die in the parser; 400 nested lambdas create fine, 600 die. That is roughly 3.2 KB of parser stack per nesting level, against one small frame per node in this walk.
Every path that reaches this validator gets its AST from parseQuery (DDL, and backup restore via UserDefinedSQLObjectsBackup), so the parser hits its own check well before a walk with frames this size could. Measured on a debug build of 26.10.1.1, where that parser sampling is every 128 levels.
If you would rather have it unconditionally, checkStackSize() at the top of the function is one line and I will push it.
|
or @alexey-milovidov can review as always |
…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]>
Closes: #121197
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
CREATE FUNCTIONnow rejects a SQL user defined function whose lambda argument cannot be evaluated, both at the top level (lambda(tuple(x.y), 1)) and inside a lambda nested in the body ((x) -> arrayMap(y.z -> y.z + x, [1, 2])). Such a function used to be stored while every call to it failed withBAD_ARGUMENTS. Closes #121197.Description
CREATE FUNCTIONaccepted a UDF whose lambda argument is a compound identifier, stored it, reloaded it after a restart, and then refused every call:validateSQLFunctionrequired each lambda argument to be a unique identifier but never tested how many name parts it has, whileQueryTreeBuilder::buildExpression, the only component that can evaluate a lambda UDF in a query, rejectsname_parts.size() > 1unconditionally. Registration is the only gate before persistence, and every producer converges on it: both spellings,CREATE OR REPLACE,ON CLUSTERreplay, the AST JSON route.The same rules now cover lambdas nested in the body, which the analyzer validates identically:
(x) -> arrayMap(y.z -> y.z + x, [1, 2])and(x) -> (y.z -> y.z + x)were also stored and then failed on every call. Name sets stay per lambda, so(x) -> arrayMap(x -> x + 1, [1, 2])keeps working. Array and map arguments were already refused by three older clauses; rows now pin them.Nothing running breaks: the disk and ZooKeeper load paths do not validate, so a function already stored this way still loads, still lists in
system.functionsand is still droppable, measured across a restart.RESTOREof a backup holding one now fails, exactly as it already does for the five older clauses, and the function could not be called anyway. I can add a restore-only bypass if you would rather have one.Tests: 12 rows in
02181_sql_user_defined_functions_invalid_lambda.sql, all of them failing rows, including two controls that must pass the new clause and stop at the recursion check instead.:ci_links: -->
Workflow [PR]
Sync PR [sync-upstream/pr/121370]
Workflow [PR]
Sync PR [sync-upstream/pr/121370]
Version info
26.10.1.1077-master(included in26.10and later)