Repository navigation
Allow passing bare function names to higher-order functions - #101033
Conversation
When a function name like `negate` or `toString` is used as an argument to a higher-order function like `arrayMap`, it is now automatically wrapped into a lambda expression. For example: SELECT arrayMap(negate, [1, 2, 3]) is equivalent to: SELECT arrayMap(x -> negate(x), [1, 2, 3]) This also works with binary functions and multiple arrays: SELECT arrayMap(plus, [1, 2, 3], [10, 20, 30]) The transformation only happens when the identifier does not resolve as a column or alias, ensuring backward compatibility. Closes #63498 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Workflow [PR], commit [13357b5] Summary: ✅ AI ReviewSummaryThis PR adds bare-function-name support for higher-order functions by rewriting the first identifier argument into a lambda when safe, with arity derived from the referenced function/UDF and explicit guards for lambda-capable parents only. The current code and tests cover the previously raised correctness risks ( Final VerdictStatus: ✅ Approve |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The code looks good to me.
…er-order functions The original implementation converted any identifier that happens to be a known function name into a lambda expression in ANY function call. This caused failures when identifiers like `url`, `format`, or `e` (Euler's number) appeared as arguments to non-higher-order functions like `equals`. Changes: - Only transform the first argument (position 0), since higher-order functions always expect the lambda there - Verify the parent function actually accepts lambda arguments by probing `getLambdaArgumentTypes` before transforming - Try decreasing lambda arities to correctly handle functions with fixed parameters (e.g. `arrayPartialSort`) - Defer `tryResolveIdentifier` calls until after confirming the parent function is a higher-order function, to avoid allocating tree nodes that shift node IDs in EXPLAIN output https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101033&sha=c71b89eda67306ddaadde4da9e566eb466809ee1&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…transformation - Fix style check / clang-tidy `bugprone-empty-catch` by adding NOLINT and an explanatory comment to the catch block - Use the inner function's `getNumberOfArguments` to determine lambda arity when available, falling back to probe-based detection for variadic functions. This correctly handles functions like `arrayPartialSort` that have fixed non-array parameters - Document the tuple-destructuring limitation (arrays of tuples require explicit lambdas since `Array(Nothing)` probes cannot detect tuple structure) - Add tests for `arrayPartialSort`, `arraySort`, backward compatibility, and non-higher-order function calls Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…dge-case tests When the inner function has a known fixed arity (e.g. `plus` with arity 2), do not fall through to the decreasing-arity probe loop if the parent rejects that arity. This prevents incorrect rewrites for tuple-destructuring cases like `arrayMap(plus, [(1,2),(3,4)])` where the `Array(Nothing)` probe cannot detect tuple element count. Also clarified in the comment that the probe is reliable for non-HOF functions because the default `getLambdaArgumentTypesImpl` throws `ILLEGAL_TYPE_OF_ARGUMENT`. Added test cases: - Tuple-destructuring with fixed-arity function (expects error, no rewrite) - Non-HOF function with function-name argument (no rewrite) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Document the new feature that allows passing function names directly to higher-order functions like `arrayMap`, `arrayFilter`, `arrayFold`, etc., instead of writing explicit lambda expressions. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
These words are used in the new documentation for bare function names as lambda arguments. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…as-lambda # Conflicts: # ci/jobs/scripts/check_style/aspell-ignore/en/aspell-dict.txt
…as-lambda # Conflicts: # ci/jobs/scripts/check_style/aspell-ignore/en/aspell-dict.txt
- Replace `catch (...)` in `probe_parent_accepts_arity` with a targeted `catch (const Exception & e)` that only handles `ILLEGAL_TYPE_OF_ARGUMENT` and `NUMBER_OF_ARGUMENTS_DOESNT_MATCH`, rethrowing all other exceptions. This prevents masking unrelated errors like `std::bad_alloc` or `LOGICAL_ERROR`. - Update documentation to clarify that bare function name syntax works only with built-in functions; user-defined functions (UDFs) require explicit lambda syntax. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…fined functions The `FunctionFactory::instance().has` check only covered built-in functions, so SQL UDFs and executable UDFs were not eligible for the bare-function-to-lambda transformation (e.g. `arrayMap(my_udf, arr)` would fail instead of being rewritten to `arrayMap(x -> my_udf(x), arr)`). Now also check `UserDefinedExecutableFunctionFactory` and `UserDefinedSQLFunctionFactory`. For arity detection, executable UDFs use their resolver's `getNumberOfArguments`; SQL UDFs extract the argument count from the lambda in the `CREATE FUNCTION` AST. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The previous implementation probed `getLambdaArgumentTypes` with synthetic `Array(Nothing)` arguments to detect higher-order functions. That probe relies on the default `getLambdaArgumentTypesImpl` throwing `ILLEGAL_TYPE_OF_ARGUMENT` for non-higher-order functions. Even though the throw is caught, the `DB::Exception` constructor calls `std::_Exit` when `terminate_on_any_exception` is enabled, so any query with a 2+ argument function whose first argument is an identifier matching a known function name (e.g. `equals(database, currentDatabase())` where `database` is an alias for the `currentDatabase` function) would terminate the process. This broke `Tests/02815_no_throw_in_simple_queries` in Fast test, because `SHOW TABLES` and `SELECT * FROM system.tables WHERE database = currentDatabase()` in `clickhouse-local` hit that path. Introduce a non-throwing virtual `isHigherOrderFunction` on `IFunction` / `IFunctionOverloadResolver`, overridden to `true` in `FunctionArrayMapped`, `arrayFold`, and `FunctionMapToArrayAdapter`. The analyzer uses this as the capability check instead of the exception probe. With the probe gone, the transformation now also works for tuple destructuring cases such as `arrayMap(plus, [(1, 10), (2, 20)])` that the synthetic `Array(Nothing)` probe could not detect. Variadic inner functions (arity zero) remain unsupported — users should write an explicit lambda. CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/101033/83d78f5b927b4d3485a0452c30f10fcd0298a05c/fast_test/ PR: #101033 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Exercises `UserDefinedExecutableFunctionFactory` via the globally-configured `test_function` (from `tests/config/test_function.xml`) to verify that the bare-function-to-lambda transformation covers executable UDFs in addition to built-ins and SQL UDFs. Addresses review feedback on PR #101033. PR: #101033 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`UserDefinedExecutableFunctionFactory::tryGet` instantiates `UserDefinedFunction` with empty parameters; its constructor throws `BAD_ARGUMENTS` for any UDF that declares command parameters. Because the bare-function rewrite-candidate check ran before column/alias resolution, an unqualified identifier matching a parameterised executable UDF would fail with `BAD_ARGUMENTS` before the column/alias lookup could even take place — breaking the documented "column/alias names take priority" contract. Mirror the `has`-first pattern already used for WebAssembly UDFs and swallow `BAD_ARGUMENTS` around `tryGet`: parameterised executable UDFs are not eligible for the lambda rewrite anyway (we have no parameters to supply), so dropping the candidate and falling through to identifier resolution is the right behaviour. Add a regression test using a new `test_function_with_parameter` executable UDF. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`AtomicStopwatch::compareAndRestart` and `compareAndRestartDeferred`
computed `UInt64(seconds * 1000000000.0)`, which is undefined behavior
once `seconds * 1e9` exceeds `UInt64::max`. AST fuzzer reaches this path
on `MergeTreeCleanupThread` when the cleanup-interval setting is tuned
to an extreme value and the `UInt64` setting is cast to `double` at the
call site, producing:
```
src/Common/Stopwatch.h:158:35: runtime error: 9.22337e+27 is outside the range of representable values of type 'unsigned long'
#0 AtomicStopwatch::compareAndRestartDeferred(double) src/Common/Stopwatch.h:158:35
ClickHouse#1 DB::MergeTreeCleanupThread::iterate() src/Storages/MergeTree/MergeTreeCleanupThread.cpp:50:55
```
Centralise the conversion in `secondsToNanoseconds`, saturating non-finite-sized
inputs at `UInt64::max / 2`. The saturation point is chosen so that
`current_start_ns + threshold` cannot wrap inside the compare-and-restart
loop, preserving "huge threshold → never restart" semantics rather than
silently flipping the comparison.
Adds a gtest covering both methods at `UInt64::max`, `Int64::max`,
`1e30`, and non-positive inputs.
Reported in PR ClickHouse#101033 CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101033&sha=eef19f6d6cde3553b66443d7ec26b2e035d45225&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29
STID: 3324-4bde
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
@groeneai, the three failures on
Merged master to refresh CI on the latest base. |
Master AST fuzzer hit `Segmentation fault (STID: 0988-2212)` on `AST fuzzer (amd_msan)` for `groupArrayMovingSum` on PR ClickHouse#100394 and on `AST fuzzer (arm_asan_ubsan)` / `amd_debug` for PRs ClickHouse#101033, ClickHouse#101062, ClickHouse#104531 — same bug class as STID 0988-40af / 0988-3351. The fuzzer mutated a query into `groupArrayMovingSumState(...) * N`, which goes through `FunctionBinaryArithmetic::executeAggregateMultiply`. The exponentiation-by-squaring loop called `function->merge(vec_from[i], vec_from[i], arena.get())`, and `MovingImpl::merge` then did `cur_elems.value.insert(rhs_elems.value.begin(), rhs_elems.value.end(), arena)` where `rhs_elems` aliased `cur_elems.value`, so the source iterators referenced the buffer that `insertPrepare` was about to reallocate. The fix in this PR (copy `vec_from` into an independent column before each squaring step) eliminates the self-alias at the call site, so `MovingImpl::merge` is never invoked with `place == rhs` from `executeAggregateMultiply` anymore. The new test exercises every `MovingImpl` instantiation reachable from `groupArrayMovingSum` / `groupArrayMovingAvg`: - integer accumulator, - decimal accumulator (the variant flagged on PR ClickHouse#101062), - windowed parameterisation (`LimitNumElements::value = true`), - the `agg_state_is_const` path through `arrayJoin([state, state])`. Verified locally on Debug build that pre-fix the squaring path aborts with the PODArray `assertNotIntersects` assertion (Server `<Fatal>`), while `state * 1` (no squaring branch) returns `50` — matching the single-state baseline used to derive the reference values. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100394&sha=7309f23dc7ccee494b41416c8fff18c02d0697a7&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29
…g is a lambda `FunctionMapToArrayAdapter` previously delegated `isHigherOrderFunction` to the inner implementation. This is too broad for `MapLikeAdapter`, which is used by `mapContainsKeyLike`, `mapContainsValueLike`, `mapExtractKeyLike`, and `mapExtractValueLike`. Their SQL-level signature is `(Map, String pattern)` — the lambda is synthesised internally — so they must not be reported as higher-order, otherwise the bare-function-name rewrite would attempt to convert their first argument as a lambda. Introduce an adapter trait `first_argument_is_lambda` and make `isHigherOrderFunction` honour it; only `MapLikeAdapter` opts out. Other adapters keep delegating to `impl.isHigherOrderFunction()` as before, so behaviour for `mapApply`, `mapFilter`, `mapExists`, `mapAll`, `mapSort`, etc. is unchanged. Extend `04064_bare_function_name_as_lambda` with positive and negative cases for the `map*Like` family: ordinary usage still works, and passing a bare function name (e.g. `mapContainsKeyLike(negate, 'a%')`) now fails with `UNKNOWN_IDENTIFIER` rather than going through lambda-conversion. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The bare-function-name rewrite probe used `has` + `get` on `UserDefinedWebAssemblyFunctionFactory`, which is a TOCTOU sequence: a concurrent `DROP FUNCTION` between the two calls makes `get` raise `RESOURCE_NOT_FOUND` and preempt the documented "column/alias names take priority" behavior. Add a non-throwing `tryGet` to `UserDefinedWebAssemblyFunctionFactory` that returns `nullptr` when the function is missing (mirroring `UserDefinedExecutableFunctionFactory::tryGet`), and use it from the rewrite probe so the path stays strictly non-throwing. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
LLVM Coverage Report
Changed lines: 91.00% (91/100) · Uncovered code |
…replicas `OptimizeTrivialGroupByLimitPass` runs in the analyzer on the initiator and lowers `max_rows_to_group_by` on the query's local context. That mutation is not propagated to remote replicas, so once CI's `automatic_parallel_replicas_mode=2` randomization is sampled the aggregator on the remotes never applies the cap and `OverflowAny` stays at zero. The test then sees `04229_on 0` instead of `04229_on 1` and fails 3/3 reruns (every PR run hits the same diff). Pin `enable_parallel_replicas = 0` at the query level in both `SETTINGS` clauses so the optimization is exercised on the local-coordinator path it is designed for. Query-level `SETTINGS` takes priority over the runner's session-level injection, so the pin is robust against randomization. No `no-*` tag is added (per `.claude/CLAUDE.md` guidance) and no other randomization is disabled — `max_threads = 1` was already pinned, the rest stays randomized. Locally reproduced with a 3-replica `default_parallel_replicas` cluster on loopback: 5/5 fails without the pin (`04229_on 0`), 20/20 passes with the pin under the same parallel-replicas session settings. Cross-PR scope (CIDB, 30d): seen on PRs #104473, #100146, #101033, #104694, #104966 — all unrelated to the test or its source PR. Reported by @alexey-milovidov on #100146.
Allow passing a function name directly to a higher-order function instead of writing a lambda expression. For example:
These are equivalent to writing lambdas explicitly (
arrayMap(x -> negate(x), [1, 2, 3])), but more concise.The transformation only applies when the identifier does not resolve as a column or alias, so backward compatibility is preserved.
Closes #63498
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Allow passing bare function names to higher-order functions like
arrayMap,arrayFilter, etc. For example,arrayMap(negate, [1, 2, 3])is now equivalent toarrayMap(x -> negate(x), [1, 2, 3]).Documentation entry for user-facing changes
A function name can now be passed directly to higher-order functions instead of wrapping it in a lambda. For example:
SELECT arrayMap(toString, [1, 2, 3])instead ofSELECT arrayMap(x -> toString(x), [1, 2, 3]). This works with any ordinary function. Column and alias names take priority over function names when there is ambiguity.Version info
26.5.1.659