Skip to content

Fix segfault when a lambda is passed in a non-lambda argument position - #109840

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/arrayfold-lambda-accumulator-segfault
Jul 14, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/arrayfold-lambda-accumulator-segfault

Conversation

@groeneai

@groeneai groeneai commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fixed a server crash when a lambda expression was passed where a higher-order function expects a concrete value (for example the accumulator of arrayFold, as in arrayFold(lambda, arr, another_lambda)). Such queries are now rejected with ILLEGAL_TYPE_OF_ARGUMENT instead of crashing when enable_analyzer = 0.

Description

Found by the AST fuzzer:

EXPLAIN PIPELINE SELECT arrayFold((acc, x) -> plus(toString(NULL, toLowCardinality(4), 4, 'aaaa', 4, 4, 4, 1), x), range(number), ((acc, x) -> if(x % 2, arrayPushFront(acc, x), arrayPushBack(acc, x)))) FROM system.numbers LIMIT 0

Minimal reproducer (segfault before this change, with enable_analyzer = 0):

SELECT arrayFold((acc, x) -> x, [1, 2, 3], ((acc, x) -> x));

Root cause. In the old analyzer, ActionsMatcher::visit creates a placeholder DataTypeFunction with null argument types for each lambda child, expecting the function's getLambdaArgumentTypes to fill them in. When a lambda is placed where the function does not expect one (e.g. the arrayFold accumulator), getLambdaArgumentTypes leaves those argument types null. The code then dereferences the null DataTypePtr while building the ActionsDAG (the crash surfaced in isDynamic/WhichDataType during IFunctionOverloadResolver::build, and also in FunctionCaptureOverloadResolver), crashing the server.

Fix. After getLambdaArgumentTypes, if the placeholder's argument types are still null the function did not expect a lambda at this position, so throw ILLEGAL_TYPE_OF_ARGUMENT. This mirrors the analyzer path, which already rejects the same case in resolveFunction (Function '...' does not expect a lambda expression as argument N).

CI provenance: STID 1179-32dd, AST fuzzer (amd_debug), https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109589&sha=3a4cec287850f25c1b5081ad08b05638056279c1&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29

Version info

  • Merged into: 26.7.1.947 (included in 26.7 and later)

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-local --enable_analyzer=0 -q "SELECT arrayFold((acc, x) -> x, [1,2,3], ((acc, x) -> x))" segfaults every time (also the original fuzzer EXPLAIN query).
b Root cause explained? Old analyzer ActionsMatcher::visit makes a placeholder DataTypeFunction with null arg types per lambda child, expecting getLambdaArgumentTypes to fill them. For a lambda in a non-lambda slot (e.g. arrayFold accumulator) they stay null; the null DataTypePtr is dereferenced while building the ActionsDAG (isDynamic/WhichDataType, FunctionCaptureOverloadResolver) -> segfault.
c Fix matches root cause? Yes. After getLambdaArgumentTypes, reject with ILLEGAL_TYPE_OF_ARGUMENT if the placeholder's arg types are still null — exactly the condition that makes the deref unsafe.
d Test intent preserved / new tests added? New test 04344_lambda_in_non_lambda_argument_position added: asserts the crash query now throws ILLEGAL_TYPE_OF_ARGUMENT (both analyzers) and that valid arrayFold still works.
e Both directions demonstrated? Yes. Without fix: segfault (RC 139). With fix: Code: 43 ILLEGAL_TYPE_OF_ARGUMENT; valid arrayFold((acc,x)->acc+x, [1,2,3,4], toInt64(0)) returns 10.
f Fix is general across code paths? Yes. The guard sits at the single choke point all higher-order functions pass through in the old analyzer; verified arrayFilter/arraySort/arrayMap/mapApply/arrayReduce with a misplaced lambda now all error cleanly rather than crash. Matches the analyzer-path guard in resolveFunction.
g Fix generalizes across inputs? Yes. The check is on the lambda placeholder's argument types being null, independent of value/wrapper types; covers all HOFs and any lambda-in-value-position, not just the one fuzzed input.
h Backward compatible? Yes. Only converts a crash into a clean exception; no setting/format/behavior change for valid queries.
i Invariants and contracts preserved? Yes. Enforces the invariant that the lambda placeholder's argument types are non-null before they are dereferenced, on the error path only; valid lambda handling is unchanged.

Session id: cron:clickhouse-worker-slot-5:20260708-201000

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd — could you review this? In the old analyzer, a lambda passed in a non-lambda argument position (e.g. the arrayFold accumulator) left the lambda placeholder's DataTypeFunction argument types null, and the null DataTypePtr was later dereferenced while building the ActionsDAG, segfaulting the server. This rejects it with ILLEGAL_TYPE_OF_ARGUMENT, mirroring the analyzer-path guard in resolveFunction. Found by the AST fuzzer (STID 1179-32dd).

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

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [39754b9]

Summary: ✅


AI Review

Summary

This PR hardens higher-order-function lambda validation in both analyzers by rejecting lambdas in non-lambda argument positions before any lambda body is traversed. I re-checked the previously reported arrayFold(..., another_lambda) cross-lambda crash path against the current code and the new regression coverage, and I did not find a remaining correctness issue in the touched paths.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 8, 2026
Comment thread src/Interpreters/ActionsVisitor.cpp Resolved
A lambda passed where a higher-order function expects a concrete value (for
example the accumulator of arrayFold: arrayFold(lambda, arr, another_lambda))
segfaulted the server. ActionsMatcher / QueryAnalyzer create a placeholder
DataTypeFunction with null argument types for each lambda child, expecting the
function's getLambdaArgumentTypes to fill them in. When the function does not
expect a lambda at that position it leaves those types null.

Validating one lambda at a time inside the recursion loop was too late: an
unresolved trailing lambda placeholder can be copied into an earlier lambda's
argument type, so we recursed into the earlier lambda's body before rejecting
the trailing one. Inside that body the accumulator looked like an ordinary
identifier of type Function((?, ?) -> ?), the inner higher-order call took the
non-lambda path, and FunctionArrayMapped::getReturnTypeImpl dereferenced the
still-null return type (FunctionArrayMapped.h:229).

Validate all lambda arguments in a separate pass right after
getLambdaArgumentTypes and before visiting/resolving any lambda body, rejecting
the null placeholders with ILLEGAL_TYPE_OF_ARGUMENT. Applied to both the old
analyzer (ActionsVisitor) and the new analyzer (resolveFunction).

Found by the AST fuzzer:
EXPLAIN PIPELINE SELECT arrayFold((acc, x) -> plus(toString(NULL, toLowCardinality(4), 4, 'aaaa', 4, 4, 4, 1), x), range(number), ((acc, x) -> if(x % 2, arrayPushFront(acc, x), arrayPushBack(acc, x)))) FROM system.numbers LIMIT 0

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix/arrayfold-lambda-accumulator-segfault branch from e5ae70f to c7d6899 Compare July 8, 2026 23:27
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-local -q "SELECT arrayFold((acc, x) -> arrayFilter(acc, [(x, x)]), [1], ((a, b) -> b)) SETTINGS enable_analyzer = 0" segfaults 100% on the prior revision (SIGSEGV / RC 139); enable_analyzer = 1 segfaults too.
b Root cause explained? getLambdaArgumentTypes only fills placeholder types for positions that expect a lambda; arrayFold's 3rd arg (accumulator) stays a DataTypeFunction with null inner types. That placeholder is copied into the 1st lambda's acc type. Validating lambdas one-at-a-time inside the recursion loop rejects the 3rd lambda too late: we first visit the 1st lambda's body, arrayFilter(acc, ...) sees acc as a non-lambda Function((?,?)->?), takes the non-lambda path, and FunctionArrayMapped::getReturnTypeImpl dereferences the null data_type_function->getReturnType() (FunctionArrayMapped.h:229 -> removeLowCardinality/removeNullable(null)).
c Fix matches root cause? Yes. Validate ALL lambda arguments in a separate pass immediately after getLambdaArgumentTypes and before visiting/resolving any lambda body, rejecting null placeholders with ILLEGAL_TYPE_OF_ARGUMENT. This is exactly the pre-validation pass requested in the review.
d Test intent preserved / new tests added? Yes. Regression test extended with the new reproducer under both analyzers; existing cases and valid arrayFold retained.
e Both directions demonstrated? Yes. Prior revision: SIGSEGV. This revision: Code 43 ILLEGAL_TYPE_OF_ARGUMENT for both reproducers x {analyzer 0, analyzer 1}; valid arrayFold((acc,x)->acc+x,[1,2,3,4],toInt64(0)) returns 10; test passes 5/5.
f Fix is general across code paths? Yes. Same interleaving bug existed in the new analyzer (QueryAnalyzer::resolveFunction), whose null-check was also inside the resolve loop. Added a symmetric pre-pass there; both analyzer paths now covered. Crash sink (getReturnTypeImpl) needs no change once the null placeholder is rejected upstream.
g Fix generalizes across inputs? Checked other lambda-in-non-lambda positions (e.g. arrayReduce(x->x,[1])) still reject cleanly; valid nested lambdas (arrayMap(x->arrayFilter(y->y>x,[1,2,3]),[1,2])) still work under both analyzers. The check is over the placeholder argument-type vector, independent of element datatype.
h Backward compatible? Yes. Only converts a segfault into a clean ILLEGAL_TYPE_OF_ARGUMENT for input that never had defined behavior. No setting/format/default change.
i Invariants and contracts preserved? Yes. The pre-pass only reads argument_types filled by getLambdaArgumentTypes and throws before any body traversal / DAG construction; it does not alter the resolution of well-formed lambdas. Downstream code that assumed non-null lambda return types now has that assumption enforced.

Session id: cron:clickhouse-worker-slot-2:20260708-230700

The pre-validation pass added by this PR rejects a lambda in a non-lambda
argument position with ILLEGAL_TYPE_OF_ARGUMENT (43) before the argument-count
check that previously raised NUMBER_OF_ARGUMENTS_DOESNT_MATCH (42). The query's
argument count is valid; the actual defect is a lambda passed as argument 3, so
43 is the more accurate code. Accept both so the regression test is robust to
validation ordering.

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

clickhouse-gh Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.90% +0.10%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 24/29 (82.76%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 39754b9

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Sync — CH Inc sync (private, not actionable by us)

All other checks green (Style, Fast test, Bugfix validation both arches, full functional/stress/fuzzer matrix). The prior PR-caused Fast-test reconciliation (03913 expected error code 42 → 42 OR 43) is confirmed resolved on this SHA. Ready for review.

Session id: cron:our-pr-ci-monitor:20260709-073000

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Shouldn't we do argument type check in arrayFold function implementation (and other IFunctions?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good question. I looked at pushing it into arrayFold (and the other higher-order functions) and concluded the resolver is the right layer. Two reasons:

  1. getReturnTypeImpl is too late. The crash is not in arrayFold's own return-type computation; it is in the nested function during resolution of arrayFold's first lambda body. For arrayFold((acc, x) -> arrayFilter(acc, [(x, x)]), [1], ((a, b) -> b)), getLambdaArgumentTypes copies the unresolved arg-3 placeholder (a DataTypeFunction with null inner types) into acc. When we then resolve the first lambda body, arrayFilter(acc, ...) takes the non-lambda path and FunctionArrayMapped::getReturnTypeImpl dereferences the null getReturnType(). arrayFold::getReturnTypeImpl is never reached, so a guard there cannot help.

  2. The only in-function hook early enough is getLambdaArgumentTypes (it runs before any body is resolved). A guard there is feasible, but it would have to be duplicated in every higher-order function, and that layer only sees a DataTypes vector; the fact that an AST lambda was placed in a value position lives in the resolver (function_lambda_arguments_indexes). The null-inner DataTypeFunction placeholder is itself a resolver construct. So the resolver is the one place that both knows a lambda was misplaced and runs before any body is visited.

The current fix is one central pre-pass right after getLambdaArgumentTypes, symmetric across the old (ActionsVisitor) and new (resolveFunction) analyzers, covering all higher-order functions with a single guard rather than N per-function copies.

That said, if you'd prefer the check pushed into each function's getLambdaArgumentTypes, I'm happy to move it. Let me know which you want.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Then check can be done in FunctionArrayMapped?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

arrayFold is not a FunctionArrayMapped. It is a separate FunctionArrayFold (src/Functions/array/arrayFold.cpp), so a guard in FunctionArrayMapped would not cover it, and arrayFold is the only function in this reproducer that accepts a lambda in a value position (its accumulator, the last argument).

FunctionArrayMapped also cannot itself be the source of this bug. Its getLambdaArgumentTypes already requires every data argument to be an Array ("Argument N of function ... must be Array"), so it can never carry a bare lambda in a non-lambda slot. It only shows up as the nested victim: arrayFilter(acc, ...) inside arrayFold's first lambda body, whose getReturnTypeImpl dereferences the null data_type_function->getReturnType() at FunctionArrayMapped.h:229.

So a check in FunctionArrayMapped would guard the crash site, not the root:

  • it does not cover the actual source (arrayFold's accumulator);
  • it does not cover other victims: arrayFold as the nested function also dereferences a null lambda return type (accumulator_type->equals(*lambda_type) in arrayFold.cpp), and any future higher-order function would need its own guard;
  • it reports the error from deep inside the nested call instead of at the misplaced lambda argument.

The resolver pre-pass is the single place that runs before any lambda body is resolved, knows an AST lambda was placed in a value position, and covers every higher-order function uniformly with the error reported at the correct argument.

I can additionally add a defensive null-check at FunctionArrayMapped.h:229 (and in arrayFold) as belt-and-suspenders so the HOF machinery is self-protecting, keeping the resolver pre-pass as the primary rejection. If you would rather drop the pre-pass and rely only on per-function guards, I can do that, but it duplicates the check across each HOF and loses the correct error location.

@vdimir vdimir self-assigned this Jul 9, 2026
@vdimir
vdimir enabled auto-merge July 14, 2026 13:34
@alexey-milovidov
alexey-milovidov merged commit 9892982 into ClickHouse:master Jul 14, 2026
173 of 174 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 14, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…da-accumulator-segfault

Fix segfault when a lambda is passed in a non-lambda argument position
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 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.

4 participants