Skip to content

Fix SIGSEGV when a lambda is used as a non-lambda argument of a higher-order function - #106271

Closed
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-1719-3ae5-arrayfold-lambda-init
Closed

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-1719-3ae5-arrayfold-lambda-init

Conversation

@groeneai

@groeneai groeneai commented Jun 2, 2026 •

Copy link
Copy Markdown
Collaborator

Passing a lambda where a concrete value is expected, for example as the initial accumulator of arrayFold, used to crash the server with SIGSEGV in removeNullable called from FunctionArrayMapped::getReturnTypeImpl.

Reproducer (found by the AST fuzzer, STID 1719-3ae5):

SELECT arrayFold(arrayExists, range(number), ((acc, x) -> if(x % 2, arraySlice(x, acc), arrayPushBack(acc, x))))
FROM system.numbers LIMIT 0;

arrayCount, arrayFirst, and the analogous WITH (a -> a + 1) AS f SELECT arrayFold(arrayExists, [[1, 2, 3]], f) shape crash the same way.

Root cause: any LambdaNode used as a function argument is assigned a placeholder DataTypeFunction(args=[nullptr...], return=nullptr) in QueryAnalyzer::resolveFunction (resolveFunction.cpp line ~1322). That placeholder is filled in only when the outer function treats the position as a lambda. For arrayFold, the initial accumulator is not a lambda position, so its placeholder stays unresolved. arrayFold::getLambdaArgumentTypes then copies the accumulator type into the synthetic outer lambda's argument list, letting the placeholder leak into another lambda's argument types. When resolveLambda type-checks the body (the synthetic arrayExists(__function_ref_arg_0, __function_ref_arg_1) wrapper), FunctionArrayMapped::getReturnTypeImpl calls removeNullable on the placeholder's null return_type and crashes at DataTypeNullable.cpp:167.

Fix: the existing check at resolveFunction.cpp already rejects null entries in a lambda's argument types with ILLEGAL_TYPE_OF_ARGUMENT ("does not expect a lambda expression as argument N"). Extend it to also reject nested DataTypeFunction values whose return type is null. The user-visible error matches the simpler case.

CI report:

Closes: #109682

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

Fix a server crash when a lambda function is passed where a concrete value is expected by a higher-order function (for example arrayFold(arrayExists, range(number), (acc, x) -> ...)). The query is now rejected with a clear ILLEGAL_TYPE_OF_ARGUMENT error.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

… types

A lambda used where a concrete value is expected (e.g. as the initial
accumulator of arrayFold) is represented in the analyzer by a placeholder
DataTypeFunction with no return type. The check at QueryAnalyzer::resolveFunction
already rejects null entries in a lambda's argument types, but did not look
through nested DataTypeFunction values for the same placeholder shape.

When arrayFold copies the accumulator type into the synthetic outer lambda's
argument list via getLambdaArgumentTypes, an unresolved init lambda would
leak its placeholder DataTypeFunction(args=[nullptr...], return=nullptr) into
the synthetic lambda's argument types. The follow-up resolveLambda would then
type-check the body (e.g. arrayExists(__function_ref_arg_0, ...)) with that
placeholder, and FunctionArrayMapped::getReturnTypeImpl would call
removeNullable on a null DataTypePtr, segfaulting at DataTypeNullable.cpp:167.

Extend the check to also reject nested DataTypeFunction values whose return
type is null. The user-visible error is the same ILLEGAL_TYPE_OF_ARGUMENT
already raised for the simpler case.

Found by AST fuzzer (STID 1719-3ae5) on
https://s3.amazonaws.com/clickhouse-test-reports/PRs/106261/6ce05d7b024f9c6b0cc589474e07333c06b7f3ef/ast_fuzzer_amd_debug_targeted/
(PR ClickHouse#106261).
@groeneai

groeneai commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @novikd @vdimir — could you review this? It extends the analyzer's "lambda where concrete value expected" check to also reject nested DataTypeFunction placeholders, fixing an AST-fuzzer-reproducible SIGSEGV in FunctionArrayMapped::getReturnTypeImpl when a lambda is used as the initial accumulator of arrayFold.

@groeneai

groeneai commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Session: cron:clickhouse-ci-task-worker:20260602-020000

(a) Deterministic repro? Yes. ./build/programs/clickhouse local --query "SELECT arrayFold(arrayExists, range(number), ((acc, x) -> if(x % 2, arraySlice(x, acc), arrayPushBack(acc, x)))) FROM system.numbers LIMIT 0" exits 139 (SIGSEGV) on origin/master and on the ASan binary running on this machine. With the fix, the same query returns Code: 43 ILLEGAL_TYPE_OF_ARGUMENT cleanly. The CTE shape WITH (a -> a + 1) AS f SELECT arrayFold(arrayExists, [[1, 2, 3]], f) and the arrayCount / arrayFirst variants reproduce identically.

(b) Root cause explained? Any LambdaNode used as a function argument is given a placeholder DataTypeFunction(args=[nullptr...], return=nullptr) at QueryAnalyzer::resolveFunction (resolveFunction.cpp line ~1322). The placeholder is only filled in when the outer function recognizes the position as a lambda. For arrayFold, the initial accumulator position is not a lambda position, so the placeholder stays unresolved. Then FunctionArrayFold::getLambdaArgumentTypes copies the accumulator type into the synthetic outer lambda's argument list, propagating the placeholder into another lambda's argument types. resolveLambda later type-checks the body (the synthetic arrayExists(__function_ref_arg_0, __function_ref_arg_1) wrapper produced when a bare function identifier is passed in the lambda slot) using that placeholder, and FunctionArrayMapped::getReturnTypeImpl calls removeNullable on the placeholder's null return_type — which crashes at DataTypeNullable.cpp:167 on type->isNullable().

(c) Fix matches root cause? The existing check at resolveFunction.cpp already raises ILLEGAL_TYPE_OF_ARGUMENT ("does not expect a lambda expression as argument N") for the simpler case where a lambda's argument type is itself null. The fix extends the same check to also reject nested DataTypeFunction placeholder values whose return type is null — exactly the propagation case described in (b). No defensive plumbing in FunctionArrayMapped or FunctionArrayFold; the malformed type is rejected at the point it leaks.

(d) Test intent preserved / new tests added? A new test 04307_arrayfold_unresolved_lambda_init covers the four reproducer shapes (arrayExists / arrayCount / arrayFirst inside arrayFold, plus the WITH lambda CTE shape) with -- { serverError ILLEGAL_TYPE_OF_ARGUMENT } and four sanity calls that must still succeed (arrayFold proper, arrayExists / arrayCount / arrayFirst with a normal lambda). No existing test was modified.

(e) Both directions demonstrated? Yes.

  • Without the fix: the ASan server on this machine (pre-fix binary) returns ATTEMPT_TO_READ_AFTER_EOF on the reproducer (server died).
  • With the fix: my debug server on port 19719 returns Code: 43 ILLEGAL_TYPE_OF_ARGUMENT for the four reproducer shapes, and produces 6\n1\n2\n2\n for the sanity queries — matching the new .reference exactly.

(f) Fix is general, not a narrow patch? Yes. The check sits in QueryAnalyzer::resolveFunction and runs for every higher-order function call (arrayMap, arrayFilter, arrayFold, arrayExists, arrayCount, arrayFirst, arrayLast, arrayCumSum, arraySplit, mapApply, ...). Any path where an unresolved-lambda placeholder propagates into another lambda's argument types is rejected at the analyzer level, not just the specific arrayFold shape from the fuzzer.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e5178d2]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) FAIL
test_s3_aws_sdk_has_slightly_unreliable_behaviour/test.py::test_dataloss FAIL cidb

AI Review

Summary

This PR rejects unresolved DataTypeFunction placeholders created when a LambdaNode is supplied in a value slot of higher-order functions such as arrayFold, and adds focused stateless coverage for the new-analyzer path while keeping the older DataTypeFunction::updateHashImpl regression pinned to the old analyzer. I found no remaining correctness, compatibility, metadata, or test-coverage issues in the current code; the prior bot-authored review findings have been addressed and resolved.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 2, 2026
When an unexpected `LambdaNode` argument's unresolved placeholder
`DataTypeFunction` propagates into the expected lambda's argument types via
`getLambdaArgumentTypes` (e.g. `arrayFold` copies the accumulator type into
its lambda's argument list), the previous inner-types check reported the
expected lambda's outer index, not the actual bad argument.

Move detection to a pre-pass over `function_lambda_arguments_indexes` that
runs immediately after `getLambdaArgumentTypes`. A LambdaNode position whose
`DataTypeFunction` still has all-null argument types and no return type after
that call is the unexpected one. Its original argument index now appears in
the `ILLEGAL_TYPE_OF_ARGUMENT` diagnostic.

The pre-pass also runs before `resolveLambda`, preserving the SIGSEGV
protection: `FunctionArrayMapped::getReturnTypeImpl` no longer sees the null
return type via `removeNullable`.

Add `SET enable_analyzer = 1;` to
`04307_arrayfold_unresolved_lambda_init.sql` — the fix lives in
`QueryAnalyzer::resolveFunction`, and the old analyzer does not do the
bare-function-to-lambda rewrite for `arrayFold(arrayExists, ...)` and
reports an unrelated `UNKNOWN_IDENTIFIER`.
groeneai added 2 commits June 2, 2026 08:44
The pre-pass added in 32a2575 skipped DataTypeFunction values with
an empty argument list, which let zero-argument lambda placeholders such
as `() -> 1` reach `resolveLambda` and crash in
`FunctionArrayMapped::getReturnTypeImpl` with SIGSEGV.

Removing the empty-args early-out is sufficient: `std::all_of` returns
true on an empty range, so a `DataTypeFunction([], nullptr)` is now
classified as unresolved together with the non-empty case.

Regression case added to 04307_arrayfold_unresolved_lambda_init.sql.
The new unresolved-lambda-placeholder pre-pass in
`QueryAnalyzer::resolveFunction` (commits 14d5ddb and 32a2575) fires
earlier than the downstream `NUMBER_OF_ARGUMENTS_DOESNT_MATCH` that the
original null-arg-types guard from PR ClickHouse#96479 produced. The third
`arrayFold` argument in this regression query is a lambda used as the
initial accumulator (a value slot), which is now rejected upstream with
the more semantically accurate `ILLEGAL_TYPE_OF_ARGUMENT` error
("does not expect a lambda expression as argument N").

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106271&sha=02cfedf7885d75af9f9bb520923f28fa6d860a1c

PR: ClickHouse#106271
@groeneai

groeneai commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed the Fast test failure on 03913_data_type_function_null_arg_hash in cbf8a47d037b. The new unresolved-lambda-placeholder pre-pass in QueryAnalyzer::resolveFunction fires earlier than the downstream NUMBER_OF_ARGUMENTS_DOESNT_MATCH path that PR #96479's DataTypeFunction::updateHashImpl null-arg guard produced. The test's third arrayFold argument is a lambda used as the initial accumulator (a value slot), which is now rejected upstream with the more semantically accurate ILLEGAL_TYPE_OF_ARGUMENT ("does not expect a lambda expression as argument N"). The test query still does not crash and still asserts an error, so the regression intent is preserved.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106271&sha=02cfedf7885d75af9f9bb520923f28fa6d860a1c

The previous fixup updated the expected error code on this regression
test from NUMBER_OF_ARGUMENTS_DOESNT_MATCH to ILLEGAL_TYPE_OF_ARGUMENT
to match the new pre-pass in QueryAnalyzer::resolveFunction added by
this PR. That expectation only holds under enable_analyzer = 1.

Under enable_analyzer = 0 the query is still rejected by the old
ActionsVisitor / FunctionArrayFold::getLambdaArgumentTypes path, which
throws NUMBER_OF_ARGUMENTS_DOESNT_MATCH. The functional-test runner
runs this test under the --analyzer variant with enable_analyzer = 0,
so the previous expectation broke that variant.

Pin the test to enable_analyzer = 0 and restore the original error
code. This keeps the test focused on the DataTypeFunction::updateHashImpl
null-argument regression it was originally written for, on the
code path that exhibited the crash. New-analyzer coverage of the
unresolved-lambda placeholder shape lives in the parallel test
04307_arrayfold_unresolved_lambda_init.sql.

Bot review thread: ClickHouse#106271

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 19/22 (86.36%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI has fully finished. The change itself is green; the remaining red checks are unrelated to this PR:

  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6): only test_s3_aws_sdk_has_slightly_unreliable_behaviour::test_dataloss failed, a known flaky test (it failed across ~30 unrelated PRs and master in the same 2026-06-02 window, and touches no analyzer code).
  • CH Inc sync: fork-internal sync check, not runnable for external PRs.
  • Mergeable Check and PR: rollups of the above.

All AST fuzzer variants pass, including AST fuzzer (amd_debug, targeted) and AST fuzzer (amd_debug, targeted, old_compatibility), which are the two checks that originally reproduced the STID 1719-3ae5 crash.

Session: cron:clickhouse-worker-slot-7:20260610-123200

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by #109840 (merged 2026-07-14), which fixes the same root cause more completely.

This PR guarded only the new-analyzer path (resolveFunction.cpp). #109840 applies the same up-front lambda-argument validation in BOTH the new analyzer (resolveFunction.cpp) and the old analyzer (ActionsVisitor.cpp), and adds regression test 04344_lambda_in_non_lambda_argument_position.

Verified on current master (e590300) that both crash families this PR tracked are fixed under both analyzers, returning ILLEGAL_TYPE_OF_ARGUMENT instead of segfaulting:

  • STID 1719-3ae5 (arrayFold accumulator init): arrayFold(arrayExists, range(number), ((acc,x)->...))
  • STID 1719-475c (direct null lambda return type): arrayLastOrNull / arraySplit / arrayLastIndex with a lambda in a non-lambda argument position.

Closing in favor of the merged fix rather than rebasing the redundant subset.

@groeneai groeneai closed this Jul 15, 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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

2 participants