Repository navigation
Add the function composition operator f | g and argument placeholders - #116029
Conversation
`f | g` parses into `compose(f, g)` and is resolved by pure rewriting into an ordinary lambda `(args...) -> g(f(args...))` during query analysis, so no runtime support is needed and the standard lambda machinery (typing, captures, execution) applies unchanged. Operands can be lambdas, names of functions, nested compositions, or expressions with the argument placeholders `_`, `_1`, `_2`, ...: `plus(_, 1)` is lifted to `_1 -> plus(_1, 1)`. Numbered placeholders work at any depth because they become the names of the lambda arguments. Outside a composition, placeholders apply in the lambda position of a higher-order function, gated the same way as the bare-function-name rewrite: the parent must report `isHigherOrderFunction` and the names must not resolve in scope, so every query the rewrite activates on is an error without it and no previously valid query changes meaning. The arity probe shared with the bare-function-name rewrite is factored into `tryGetRegisteredFunctionArity`. Continues and supersedes the approach of #80277 by @yesipoff. Co-Authored-By: Claude Fable 5 <[email protected]>
Also make the substitution treat a nested composition as a binding scope for placeholder-shaped names, and report a composition resolved outside of a function argument position with a dedicated error before its operands are resolved. Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
The rewrites exist only in the analyzer, mirroring the bare-function-name rewrite test; the placeholders test creates a global SQL UDF, so it cannot run in parallel with itself in the flaky check. Co-Authored-By: Claude Fable 5 <[email protected]>
All outputs are produced by the built server and match the hand-computed expectations; the lambda arity mismatch in arrayMap reports ILLEGAL_TYPE_OF_ARGUMENT. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [040361a] Summary: ✅
AI ReviewSummaryThis PR adds the Findings❌ Blockers
Final VerdictStatus: ❌ Block
LLVM Coverage ReportMeasured on commit 040361a.
Changed lines: Changed C/C++ lines covered: 428/471 (90.87%) · Uncovered code |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes6 object files changed (+176.19 KiB total), 1 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units102 translation units recompiled, 563 s compile time in total, 101 of them have a recent master baseline. |
…ft bare placeholders The `f | g` operator parsed into a function node named `compose`, which took the public name away from users: an existing `CREATE FUNCTION compose AS (x, y) -> x + y` could no longer be called, because the rewrite hijacked every `compose(...)` call in a higher-order argument and the standalone check threw before `FunctionFactory` and `UserDefinedSQLFunctionFactory` were consulted. The operator now uses the internal name `__compose` (`function_composition_name`), so `compose` is an ordinary name again. A bare placeholder is now the identity function. It is lifted in the lambda position of a higher-order function, so `SELECT arrayMap(_1, [1, 2, 3])` resolves to `_1 -> _1` instead of failing with `UNKNOWN_IDENTIFIER`, and it is accepted as an operand of the composition operator, so `arrayMap(_1 | plus(_, 1), [1, 2])` composes the identity with `plus(_, 1)` instead of failing with `BAD_ARGUMENTS`. An argument that is already a lambda is left alone: a free placeholder in a lambda body is an ordinary identifier, and lifting it would produce a lambda returning a lambda. Substitution into a subquery no longer rejects a subquery that merely reuses the substituted name locally. `subqueryReferencesIdentifier` first collects the names bound inside the subquery - aliases, CTE names, and lambda arguments - so `(x -> x + 1) | (x -> x + (SELECT max(x) FROM (SELECT 1 AS x)))` is composed as an ordinary lambda. Whether a bare identifier is a column of a table inside the subquery cannot be decided without the catalog, so such a name is still treated as referenced and the composition fails cleanly with `NOT_IMPLEMENTED`. Adds the regressions the review asked for: a user defined function named `compose`, `arrayMap(_1, [1, 2, 3])`, `arrayMap(_1 | plus(_, 1), [1, 2])`, and a composition whose lambda body contains a non-capturing scalar subquery with a local `x`.
|
🕵 Addressed the AI review in 1f17a70 (blocker + 3 majors + the requested regressions), and merged
@groeneai, the only red check on the previous run was |
|
The The single actually hung query, from SELECT 'x Nullable(Int32), y Nullable(Int32)',
sum(length(h3PolygonToCellsWithContainment([
(37.81331899998324, -122.40898669999721),
(-122.35447369999936, 37.71980619999785),
(9007199254740994., 9007199254740992.)], 9, 0)))
FROM numbers(9223372036854775807)
So your conclusion holds and this is unrelated to The fix already in progress is your own #116225. Its check rejects this polygon at the first vertex, whose latitude is -122.4, before Neither is on master yet, so the new run can hit this again. If it does, the owner is still #116225, so I am not opening a separate PR for it. |
…n-operator Conflict in `src/Analyzer/Resolve/resolveFunction.cpp`: this branch extracted the inner-function arity probe of the higher-order rewrite into `tryGetRegisteredFunctionArity`, while master taught the same probe to take the arity of a `CREATE FUNCTION ... LANGUAGE WASM` definition from the stored AST when no WebAssembly engine is registered. Kept the extraction and ported master's `ASTCreateWasmFunctionQuery` case into the helper.
…ubquery guard scope-sensitive Two problems in the composition rewrite, both reported by the AI review. The arguments of the fused lambda were named `__composed_arg_N` unconditionally. The name is unlikely, but not impossible, to occur in a query, and when it does the renaming introduces exactly the capture it exists to prevent: in `SELECT arrayMap((x -> x + 1) | (y -> y + __composed_arg_1), [1]) FROM (SELECT 10 AS __composed_arg_1)` the reference from the right operand bound to the argument of the fused lambda, so the result was `[3]` instead of `[12]`. The preferred name is now disambiguated with a counter until it occurs in neither operand, which is enough: a name absent from both bodies cannot capture anything in them. `subqueryReferencesIdentifier` decided whether a subquery references a name from the outside with one flat set of every name bound anywhere inside it, so a nested binder suppressed the guard for an unrelated free occurrence of the same name: `SELECT arrayMap((x -> x + 1) | (x -> x + (SELECT arrayMap(x -> x, [1])[1] + x)), [1])` has a free outer `x` at the top level of the subquery, but the inner `arrayMap(x -> x, ...)` binder hid it and the rewrite skipped the intended `NOT_IMPLEMENTED` rejection. The walk is now scope sensitive: a lambda argument binds only inside the body of its lambda, and an alias or a CTE name only inside the query that defines it. The names a query level binds now also include the columns the subqueries in its join tree expose, so a name that is merely reused locally, as in `(SELECT max(x) FROM (SELECT 1 AS x))`, is still recognized as bound. New test `05048_function_composition_scoping`.
|
🕵 Addressed the two AI review blockers in 7e713a1 and merged
The merge of |
… tighter subquery guard Three blockers from the review of the function composition operator `f | g`. The operator no longer reserves any name. `__compose` is a legal identifier, so a stored `CREATE FUNCTION __compose AS (x, y) -> x + y` used to become unreachable. What makes a node a composition is now the operator syntax the parser recorded in `is_operator`, checked by the new `isFunctionComposition`, not the name alone, so an ordinary call to a function of that name resolves as usual. `ASTFunction` formats such a node back as `f | g`, so a format and parse round trip keeps the operator instead of degrading it to a call of an unknown function. A name bound in the query keeps priority over the placeholder syntax also when it is bound as a function rather than as an expression. A lambda bound with `WITH (x -> x + 10) AS _1` lives in `ScopeAliases::alias_name_to_lambda_node`, which the expression lookup does not see, so both the higher-order lift and `normalizeOperandToLambda` turned `arrayMap(_1, [1, 2])` and `arrayMap(_1 | toString, [1, 2])` into the identity instead of applying the alias. The lift now consults `isFunctionAliasInScope` as well, and the composition operand tries the scoped resolution before the placeholder fast path. `subqueryReferencesIdentifier` no longer lets a table alias or a CTE name suppress the `NOT_IMPLEMENTED` guard for a bare identifier. `IdentifierResolver::tryBindIdentifierToTableExpression` rejects a one-part expression lookup once column lookup misses, so `FROM (SELECT 1 AS z) AS y` makes `y.z` local but leaves a bare `y` free. The bound names are split accordingly into the ones that bind an expression identifier (lambda arguments, aliases, and the columns a subquery in the join tree projects) and the ones that bind only a qualifier. New test `05054_function_composition_name_and_alias_priority` covers the three cases from the review.
|
🕵 Addressed the three AI review blockers in
New test |
…eries `collectNamesBoundInJoinTree` recorded every alias under the join tree as a qualifier-only name, but the alias of an `ARRAY JOIN` expression binds a bare identifier (`IdentifierResolver::tryBindIdentifierToArrayJoinExpressions`). So `SELECT arrayMap((x -> x + 1) | (y -> y + (SELECT max(y) FROM numbers(1) ARRAY JOIN [5] AS y)), [1])` was rejected with `NOT_IMPLEMENTED` although the inner `y` is local. An unaliased `ARRAY JOIN y` stays conservative, since the joined `y` is itself looked up in that scope. Addresses review feedback on #116029 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…bquery guard A column a join-tree subquery exposes was treated as bound in the query that selects from it, even when the expression behind the column is itself an outer reference to the substituted name, e.g. `y` in `FROM (SELECT y) AS s`. That suppressed the `NOT_IMPLEMENTED` guard, and after fusion the surviving `y` resolved against the enclosing query instead of the lambda input. Check the subqueries of the join tree with only the bindings of the enclosing scopes before collecting the names of the query level. Address review comment by `clickhouse-gh` on `collectProjectionNames`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… tree hashes `is_operator` decides whether a `__compose` node is the function composition operator or an ordinary call to a function of that name, but `ASTFunction::updateTreeHashImpl`, `FunctionNode::isEqualImpl`, and `FunctionNode::updateTreeHashImpl` ignored it, so the two expressions collided: e.g. `MULTIPLE_EXPRESSIONS_FOR_ALIAS` was not raised for them. Take `is_operator` into account for this function name only, so that `a + b` and `plus(a, b)` remain the same expression. Address review comment by `clickhouse-gh` on `FunctionNode::isOperator`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…subqueries A subquery cannot reference the argument of an explicit lambda either (`arrayMap(x -> (SELECT x), [1])` fails), so descending into subqueries would not make placeholders equivalent to explicit lambda arguments. Document the exclusion and add a test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… nested call The placeholder scan of the lambda position of a higher-order function descended into the lambda position of a nested higher-order function call, so in `arrayMap(arrayMap(_ + 1, _1), [[1, 2], [3]])` the `_` of the inner call and the `_1` of the outer one were collected together and rejected as mixed placeholders. Now the scan skips the first argument of a nested call to a higher-order function (unless it is already a lambda): the nested call lifts its own placeholders when it is resolved, so the query above means `arrayMap(x -> arrayMap(y -> y + 1, x), [[1, 2], [3]])`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ames in `f | g` operands An identifier operand of the function composition operator that resolves to a column or an alias is now rejected instead of silently composing the registered function with the same name, mirroring the bare-function-name rewrite for higher-order functions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| { | ||
| resolver = UserDefinedExecutableFunctionFactory::tryGet(function_name, context); | ||
| } | ||
| catch (const Exception & e) |
There was a problem hiding this comment.
This was suspicious, but it came from already existing code.
|
@alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Related: #80277
Continues and supersedes #80277 by @yesipoff (thanks for the idea and the initial implementation — the branch lives in a fork and is 15 months stale, so this is a reimplementation rather than a rebase).
What it does
f | gis a function that appliesfand theng. It can be used wherever a function is expected, that is, as an argument of a higher-order function:Operands can be lambdas, names of functions (builtins, SQL/executable UDFs, and
WITH-bound lambdas), nested compositions, and expressions with the argument placeholders_,_1,_2, ... The placeholders also work on their own in the lambda position of a higher-order function, including inside operators and at any depth:How it works
Both features are pure syntax sugar over lambdas, resolved entirely at query analysis time; there is no runtime
composefunction and no new execution machinery.|tocompose(f, g)(one line in the operator table). The single|was previously a syntax error, and||(concatenation) and|>(pipe operators) are separate tokens, so nothing changes for them.SELECT 1 | 2reports a dedicated error pointing tobitOr.composenode in a function argument position into one ordinary lambda(args...) -> g(f(args...))by substituting the body offfor the argument ofg— the same inlining semantics as SQL user defined functions. The arguments offare renamed to fresh reserved names first, so a column referenced from the body ofgcan never be captured accidentally; member access on the substituted value folds intotupleElementchains._1 ... _n, so numbered placeholders need no substitution at all and work at any depth; the largest number determines the arity, and_introduces one argument per occurrence in the order of occurrence.composeas a 208-line runtime function onColumnFunctionplus ~300 lines of special cases threaded throughQueryAnalyzer.No previously valid query changes meaning: outside a composition, the placeholder lift applies only when the parent function reports
isHigherOrderFunction(the same gate as the existingarrayMap(toUpper, arr)bare-function-name rewrite) and only when the placeholder names do not resolve to anything in scope, so columns and aliases keep priority. Every query the rewrite activates on is an error without it. In particular,_as a lambda parameter (arrayExists(_ -> _ IN (1), x)) and columns named_1keep working — #80277 had to rename such lambda parameters in two existing tests, this implementation keeps them intact (both cases are covered by the new tests).The arity probe shared with the bare-function-name rewrite (builtins, executable/WebAssembly UDFs from the resolver, SQL UDFs from the stored
CREATE FUNCTIONAST) is factored intotryGetRegisteredFunctionArityand reused for composition operands.The feature is analyzer-only, like the bare-function-name rewrite. Documentation is added to the operators reference page.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added the function composition operator
f | g(a function that appliesfand theng) and the argument placeholders_,_1,_2, ...:arrayMap(plus(_, 1) | multiply(_, 2), [1, 2, 3])returns[4, 6, 8]. A composition can be used wherever a function is expected, i.e. as an argument of a higher-order function; operands can be lambdas, names of functions, nested compositions, or expressions with placeholders, which also work on their own:arrayMap(_1 * 2 + 1, [1, 2, 3]). The composition is resolved at query analysis time into an ordinary lambda. Note that the single|is not bitwise OR — use thebitOrfunction for that.Workflow [PR]
Sync PR [sync-upstream/pr/116029]
Version info
26.10.1.2080-master(included in26.10and later)