Skip to content

Allow passing bare function names to higher-order functions - #101033

Merged
alexey-milovidov merged 62 commits into
masterfrom
bare-function-name-as-lambda
May 14, 2026
Merged

alexey-milovidov merged 62 commits into
masterfrom
bare-function-name-as-lambda

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 28, 2026 •

Copy link
Copy Markdown
Member

Allow passing a function name directly to a higher-order function instead of writing a lambda expression. For example:

SELECT arrayMap(negate, [1, 2, 3])           -- [-1, -2, -3]
SELECT arrayMap(toString, [1, 2, 3])         -- ['1', '2', '3']
SELECT arrayMap(plus, [1, 2, 3], [10, 20, 30]) -- [11, 22, 33]
SELECT arrayFold(plus, [1, 2, 3, 4, 5], toUInt64(0)) -- 15
SELECT arrayFilter(isNotNull, [1, NULL, 3, NULL, 5]) -- [1, 3, 5]

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):

  • New Feature

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 to arrayMap(x -> negate(x), [1, 2, 3]).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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 of SELECT 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

  • Merged into: 26.5.1.659

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]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [13357b5]

Summary: ✅


AI Review

Summary

This 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 (isHigherOrderFunction gating, UDF resolver paths, executable/WASM handling, BAD_ARGUMENTS handling, and map*Like adapter false positives), and I did not find any new unresolved correctness, safety, or performance regressions in the current diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 28, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The code looks good to me.

alexey-milovidov and others added 2 commits March 28, 2026 23:46
…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]>
alexey-milovidov and others added 8 commits March 29, 2026 23:37
…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
alexey-milovidov and others added 5 commits April 9, 2026 20:12
…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]>
alexey-milovidov and others added 2 commits April 19, 2026 09:48
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]>
alexey-milovidov and others added 2 commits May 12, 2026 10:21
`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]>
zex-hyd pushed a commit to zex-hyd/ClickHouse that referenced this pull request May 12, 2026
`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, the three failures on 97888779e24 look unrelated to this PR's analyzer changes — please investigate each in a separate PR (or link an existing in-flight fix):

  1. Code Review — Copilot review failed after 3 attempts: copilot subprocess exited with non-OK status. Infrastructure failure of the Copilot job, not a content review issue. https://s3.amazonaws.com/clickhouse-test-reports/PRs/101033/97888779e241fc008d3fd4ae1c022f7140d54e69/code_review/job.log

  2. Upgrade check (amd_release) / Error message in clickhouse-server.log — StorageKafka2 ... Exception during get topic partitions from Kafka: Local: Broker transport failure (test 03923_kafka2_keeper_offsets). CIDB shows this fingerprint repeating sporadically across unrelated PRs over the last 30 days (PRs 100272, 104173, 102499, 104301, 97254, 102501), so it's Kafka container startup flakiness, not anything caused by this PR. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101033&sha=97888779e241fc008d3fd4ae1c022f7140d54e69&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29

  3. AST fuzzer (arm_asan_ubsan) / AddressSanitizer (STID: 0988-2212) — use-after-poison in __asan_memcpy; stack is pthread_create → Poco::ThreadPool::ThreadPool → DB::Server::main (server startup at programs/server/Server.cpp:1469). This PR only touches src/Analyzer/Resolve/resolveFunction.cpp, a few IFunction adaptor headers, and the higher-order array functions — none of which is on the server-startup ThreadPool path. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101033&sha=97888779e241fc008d3fd4ae1c022f7140d54e69&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29

Merged master to refresh CI on the latest base.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request May 12, 2026
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, the three CI failures on 35f45e02 are unrelated to this PR's analyzer / higher-order-function rewrite. Please investigate each and provide fixes (or link the in-flight work) in separate PRs.

  1. Stateless tests (amd_msan, WasmEdge, parallel, 1/2) — 04039_merge_tree_snapshot_teardown_race (timeout): Re-runs pass — flagged as transient. Already tracked: Flaky test: 04039_merge_tree_snapshot_teardown_race #104866. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101033&sha=35f45e0299d76a0b6ae25a3d5965700b8757a013&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20WasmEdge%2C%20parallel%2C%201%2F2%29

  2. Unit tests (asan_ubsan, function_prop_fuzzer) — FunctionsStress.stress / AllTests: broken_determinism finding in caseWithExpression, which this PR does not modify. Already tracked: FunctionsStress.stress #104877. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101033&sha=35f45e0299d76a0b6ae25a3d5965700b8757a013&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%2C%20function_prop_fuzzer%29

If a fix is already in progress for either, please link it here.

alexey-milovidov and others added 2 commits May 14, 2026 13:15
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]>
@clickhouse-gh

clickhouse-gh Bot commented May 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 91.00% (91/100) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this May 14, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

@alexey-milovidov
alexey-milovidov merged commit 9821949 into master May 14, 2026
166 of 167 checks passed
@alexey-milovidov
alexey-milovidov deleted the bare-function-name-as-lambda branch May 14, 2026 23:44
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 15, 2026
alexey-milovidov pushed a commit that referenced this pull request May 17, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature 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.

Why can't I use a builtin function name in a higer order function?

3 participants