Skip to content

Reject parser-impossible lambda shapes in the AST JSON format - #120483

Merged
PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-json-ast-lambda-shape-120380
Sep 17, 2026
Merged

PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-json-ast-lambda-shape-120380

Conversation

@groeneai

@groeneai groeneai commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #120380

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 crash and a LOGICAL_ERROR when a lambda function reached query analysis without the lambda(tuple(...), body) shape the SQL parser always produces. Two routes are closed: an AST deserialized from JSON (dialect = clickhouse_json) could mark a function of any shape with is_lambda_function, and CREATE FUNCTION f AS g(tuple(x), x) was accepted although the core is not a lambda, so the first call to f raised LOGICAL_ERROR. Both are now rejected with BAD_ARGUMENTS. Closes #120380.

Description

Every parser producer of is_lambda_function builds lambda(tuple(args...), body): the -> operator, APPLY (x -> ...) and LambdaNode::toAST. ASTFunction::readJSON restored the flag as a plain bool, and QueryTreeBuilder::buildExpression trusts it ahead of isASTLambdaFunction, the only shape predicate, so the dialect could hand query analysis a node no parse produces.

On a debug build, 1/1 each: arguments absent gives Assertion 'px != 0' failed (a null dereference in release), truncated to one child Code: 1001 ... vector::at out of range, and arguments[0] as an identifier a bad cast to ASTFunction. The first shape also killed a server over HTTP, since enable_json_ast_dialect is readonly = 0.

Three neighbouring reads, all reachable without the flag, are fixed too. isASTLambdaFunction did not require the argument tuple's own arguments list although consumers dereference it. extractNamesFromLambda dereferenced two optional lists on name == "lambda" alone, reached by a skip index expression through IndexDescription::initExpressionInfo. And SQL UDF registration checked every clause of the core except its own name, so g(tuple(x), x) registered and then raised LOGICAL_ERROR in QueryAnalyzer::tryGetLambdaFromUserDefinedSQLFunctions at first use, from plain SQL with no experimental setting.

Each check sits at the boundary its shape enters. 27 pure-SQL lambda shapes still round-trip byte-identically, including empty-argument lambdas, APPLY(lambda(1)(tuple(x), x + 1)) and skip index / ALIAS / PROJECTION / TTL definitions. Rows are added to 04339_ast_json_review_followup_hardening; 05218_ast_json_lambda_shape_query_analysis.sh covers what only the dialect reaches, through clickhouse-local because most of those shapes take the process down. Both fail unfixed.

Say if you prefer Critical Bug Fix. Not a regression of #119851, which touched only ASTColumnsApplyTransformer::formatImpl.


Workflow [PR]
Sync PR [sync-upstream/pr/120483]

Version info

  • Merged into: 26.10.1.14 (included in 26.10 and later)

groeneai and others added 7 commits September 16, 2026 14:11
Every parser producer of `is_lambda_function` builds the lambda definition
shape `lambda(tuple(args...), body)`: the `->` operator
(ExpressionListParsers.cpp), `APPLY (x -> ...)` which sets the flag only after
checking that exact shape (ExpressionElementParsers.cpp), and
`LambdaNode::toAST`. `ASTFunction::readJSON` restored the flag as a plain bool
and never re-checked the shape, while `QueryTreeBuilder::buildExpression` puts
the flag FIRST in `isLambdaFunction() || isASTLambdaFunction(*function)`, so it
short-circuits the only shape predicate and then dereferences `arguments`,
indexes it with `.at(0)` / `.at(1)` and casts `children[0]` to `ASTFunction`
with none of the three established. A `dialect = clickhouse_json` payload could
therefore reach query analysis with a node no parse can produce.

Measured on a debug build, each shape 1/1: with the flag set and `arguments`
absent, `Assertion 'px != 0' failed` (a plain null dereference in a release
build, where BOOST_ASSERT is compiled out under NDEBUG); with `arguments`
truncated to one child, `Code: 1001 ... vector::at out of range`; with
`arguments[0]` replaced by an identifier, `Bad cast from type DB::ASTIdentifier
to DB::ASTFunction`. The first shape also took down a server over HTTP, since
`enable_json_ast_dialect` is `readonly = 0` and any client can set it per query.

Reject the flagged non-lambda shape in `readJSON`, next to the `kind`/flag pair
the same function already validates. Rejecting at the boundary keeps the
parser-impossible node away from every consumer, rather than hardening the two
casts in the analyzer: a 90-day CIDB sweep for that bad cast returns zero rows,
so the JSON reader is the only producer of the shape.

Two neighbouring reads of the same family, both reachable with no flag involved,
are fixed alongside. `isASTLambdaFunction` did not require the argument tuple's
own `arguments` list although consumers dereference it
(ActionsVisitor.cpp:1537), so the predicate now guarantees what they read, which
also makes the boundary check total for a flagged payload. And
`extractNamesFromLambda` dereferenced `node.arguments` and
`lambda_args_tuple->arguments` on `name == "lambda"` alone, entered from six
call sites; a skip index expression reaches it through
`IndexDescription::initExpressionInfo`, and a JSON payload whose index
expression is a bare `lambda` function aborted there. `ASTFunction::arguments`
is legitimately null, because a function written without parentheses has none,
so those are missing null checks rather than guards against corrupt state. The
helper still throws instead of returning for a malformed shape, so the
`arguments->children[1]` reads that follow it in its callers stay unreachable.

The pre-existing `ASTColumnsApplyTransformer::readJSON` guard is not subsumed
and is kept: it still fires for an `APPLY` lambda that carries neither the flag
nor `kind = LAMBDA_FUNCTION`, which the new check never inspects.

Legal round trips are unaffected. 24 pure-SQL lambda shapes produce
byte-identical output before and after, including `lambda(tuple(), 1)`, whose
empty argument list survives the JSON round trip non-null, `lambda(1, 2)`,
multi-argument lambdas, `APPLY`, and skip index / ALIAS column / PROJECTION /
TTL definitions. The check is keyed on the flag rather than on the function name
precisely because `SELECT lambda(1, 2)` and `ENGINE = lambda` are
parser-producible and must keep round-tripping.

Coverage: one row per shape appended to
04339_ast_json_review_followup_hardening, which reaches the boundary through
`formatQueryFromJSON` and so cannot abort the test server, plus
05218_ast_json_lambda_shape_query_analysis.sh for the shapes that are only
reachable by executing the dialect. That test routes through `clickhouse-local`
because each shape took its own process down, and its oracle fails both when the
expected error is missing and when the process is signalled.

Closes: ClickHouse#120380
Reported-by: @clickgapai

Co-Authored-By: Claude Opus 5 <[email protected]>
…nd trips non-vacuous

`extractNamesFromLambda` rejects an argument tuple that carries no argument
list of its own, but nothing measured that condition: deleting it left every
test green. The shape reaches it with no `is_lambda_function` anywhere in the
payload, because `ReplaceAliasByExpressionMatcher::visit` dispatches on
`function.name == "lambda"` alone, so the boundary check on that flag is not on
this route; a skip index expression gets there through
`IndexDescription::initExpressionInfo`. Add that payload to
05218_ast_json_lambda_shape_query_analysis: written in function-call syntax so
no flag is produced, with the tuple node's `arguments` member removed, which
walks past the two-argument check and past the `tuple` type check and stops only
at the third. Measured with only that sub-expression deleted, the new line is
the only one that changes, from `rejected: TYPE_MISMATCH` to
`KILLED_BY_SIGNAL rc=134`, and 04339 stays green throughout: `formatQueryFromJSON`
never builds an `IndicesDescription`, so no round-trip row can reach this code.

Swap one 04339 round-trip row for a shape the new checks actually run on.
`SELECT lambda(tuple(x), x + 1)` and `SELECT lambda(tuple(), 1)` both parse
through `ParserFunction` as ordinary calls and carry no flag, so they round trip
identically with or without this change, and the first is redundant with the
pre-existing `arrayMap(x -> (x + 1), [1, 2, 3])` row. `SELECT arrayMap(() -> 1, [1])`
replaces it: the arrow operator sets the flag, and `Layer::parseLambda` builds
the argument tuple with a non-null but EMPTY argument list, which is exactly the
shape the strengthened `isASTLambdaFunction` must keep accepting. The row would
fail if that predicate required a non-empty list. The flagless
`lambda(tuple(), 1)` row stays, since it pins the round trip that keying the
check on the function name instead of the flag would have broken.

Co-Authored-By: Claude Opus 5 <[email protected]>
`isASTLambdaFunction` decides the whole `is_lambda_function` boundary check and
two of its clauses had no oracle. The only row with a non-`lambda` name also
omitted `arguments`, so deleting `name == "lambda"` left it rejected by the
arguments clause and nothing reddened; no flagged payload anywhere in `tests/`
carried three outer arguments, so weakening `children.size() == 2` to `>= 2`
kept every test green while `QueryTreeBuilder` reads only the first two children
and silently drops the third. Add one row per clause, each well formed in every
other respect so it can only be rejected by the clause it targets. Measured on a
separate binary per mutation: deleting only the name clause turns the first row
into `f(tuple(x), x)`, weakening only the argument count turns the second into
`lambda(tuple(x), x, x)`, and in both arms every other row of 04339 and every
line of 05218 stay green, so each row reddens through its own clause alone.
`ASTCreateSQLFunctionQuery::readJSON` reads the core with the untyped
`readChild("function_core")`, unlike `function_name` one line above it, so a
`clickhouse_json` payload can hand registration an `ASTFunction` with no
argument list at all. `validateSQLFunction` bound
`lambda_function->arguments->children` before checking its size, so that member
being null took the whole process down inside
`UserDefinedSQLFunctionFactory::registerFunction`: `Assertion 'px != 0' failed`
in a debug or sanitizer build, and a plain null pointer dereference under
NDEBUG, where the assertion compiles out.

The parser cannot produce the shape. In an expression context an `ASTFunction`
always receives a non-null, possibly empty, argument list from `makeASTFunction`
and `ParserFunction`, and the only site that replaces an empty list with null,
`setNoEmptyArgs`, is called from the data-type and index-type parsers, never for
a function core. So this is a JSON-boundary hole and the remedy is the missing
null check rather than a behavioural change: the outer check now guards
`arguments` exactly as the inner argument-tuple check six lines below it already
does, and it keeps the same code and message so every existing expectation still
holds. A well-formed `CREATE FUNCTION` through the dialect still succeeds, and a
core with an empty but present list still reports the same `BAD_ARGUMENTS`.

Measured on a binary built with only `!lambda_function->arguments ||` deleted,
used as both the server and `clickhouse-local`: exactly the new 05218 row turns
into `KILLED_BY_SIGNAL rc=134` while every other row of 05218 and all of 04339
stay green. With the whole change reverted the same row reddens, so the row
cannot pass for any other reason. The row lives in 05218 rather than 04339
because the payload takes its own process down before the fix, so it must not
run against the suite's shared server, and because `formatQueryFromJSON` never
reaches registration.

Also drop an over-claiming phrase from the 04339 section comment: the first
entry of its enumeration varies two parts of the shape, not one.

Co-Authored-By: Claude Opus 5 <[email protected]>
Three gaps left by the previous rounds, all on the same clickhouse_json door.

The boundary check on is_lambda_function constrained the name, the arity and
the argument tuple, but not `parameters`, which readJSON restores a few lines
earlier. isASTLambdaFunction says nothing about it and QueryTreeBuilder's lambda
branch reads only `arguments`, so a flagged lambda carrying parameters was
accepted and its parameter list silently discarded during analysis. It formats
as lambda(7)(tuple(x), x), which the lambda operator has no syntax for. The same
function already rejects the mirror case for window payloads for this reason.

validateSQLFunction checked every structural clause of a CREATE FUNCTION core
except its own name: that it is an ASTFunction, that arguments has arity two,
that argument zero is a tuple with its own argument list, that every tuple
element is a unique identifier, and that the body is non-null. A JSON core
f(tuple(x), x) therefore registered and was persisted, and the first use raised
LOGICAL_ERROR in QueryAnalyzer::tryGetLambdaFromUserDefinedFunction, which
aborts every debug and sanitizer build. Registration is the only gate before
persistence, so the name test belongs there rather than at the consumer. The
clause-by-clause checks are left alone so the messages SQL users already get
for the other malformed shapes do not change.

The APPLY row in 04344 documented ASTColumnsApplyTransformer's own argument-tuple
guard, but its payload was not brace-balanced and so failed JSON parsing before
any readJSON ran, leaving that guard without an oracle. The payload now renames
the lambda's argument list away instead of re-parenting its children, and drops
the flag and the kind, so it reaches the guard it documents; removing only that
guard reddens the row, and removing only the boundary check leaves it green.
…tuple

The previous round rejected a flagged lambda carrying `parameters`, on the
premise that no parser producer of is_lambda_function sets it on such a node.
That premise was wrong about the second producer. The APPLY column transformer
parses an arbitrary expression and sets the flag after testing only the name,
isASTLambdaFunction and tuple arity, and the generic function layer accepts the
parametric spelling, so

    SELECT * APPLY(lambda(1)(tuple(x), x + 1)) FROM t

parses, returns 2, and parseQueryToJSON emits that node with both
is_lambda_function and parameters. The clause therefore rejected the format's
own output: the round trip raised BAD_ARGUMENTS where it had round-tripped
before. Nor did it close a clickhouse_json-specific hole, because the effect it
named, query analysis discarding the parameter list, is reachable flagless from
plain SQL through the same QueryTreeBuilder branch. The clause is reverted and a
positive round-trip row now guards the spelling.

What is genuinely parser-impossible is the mirror shape one level down: an
argument tuple carrying its own parameter list. `tuple` is routed to TupleLayer,
which has no second-group handling at all, and Layer::parseLambda builds the
argument tuple itself, so no parse produces tuple(7)(x) in that position.
isASTLambdaFunction constrained the tuple's name and its argument list but not
its parameters, and QueryTreeBuilder's lambda branch reads only `arguments`, so
a flagged payload was accepted and the list silently discarded. The predicate
now requires it absent, which closes that shape for every consumer of the
predicate, including the JSON boundary check.

validateSQLFunction had the same omission and is the only gate before
persistence, so it gets the clause too, keeping its existing message. Without
it, such a core registers and is stored as the formatted text

    CREATE FUNCTION udf_tuple_params AS lambda(tuple(7)(x), x)

which does not parse back: tryLoadObject fails it with SYNTAX_ERROR and returns
nullptr, loadObjectsImpl skips it, and the function is absent from
system.functions after a restart while its .sql file stays on disk.

Tests: 04339 loses the parametric-lambda row and gains that shape as a positive
round trip plus the parametric argument tuple as a negative; 05218 gains the
flagless CREATE FUNCTION core, so each new row is an oracle of exactly one of
the two sites. Reverting either clause alone reddens exactly its own row, the
first because the payload then formats.
Drop the clause restating the exception message below it; keep the parser invariant as one line.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Six review rounds before publication: each round is an independent model reviewing the resulting code
(engine: codex) plus my own cold review of the tree before reading the implementation notes. No round
adjudicated its own code. Row 9 is a verdict of mine that the next round measured to be wrong and
reverted; it is kept in the log rather than deleted.

# Sev Finding Verdict Evidence / action
1 ⚠️ The new !lambda_args_tuple->arguments guard in extractNamesFromLambda has no oracle: removing that sub-expression alone leaves every test green, although a flagless skip index payload still terminates the unfixed process (RequiredSourceColumnsVisitor.cpp:33) AGREE, fixed @ 915a509eaadd8 Raised independently by both reviewers. A case for that payload was added to 05218, and its redness arm changes exactly one line, from rejected: TYPE_MISMATCH to KILLED_BY_SIGNAL rc=134
2 💡 The two added positive rows in 04339 cannot exercise the fix: both parse as ordinary function calls, so no is_lambda_function flag is set and neither new check is on their path (04339_ast_json_review_followup_hardening.sql:25) AGREE, fixed @ 915a509eaadd8 Replaced the redundant row with a flagged zero-argument arrow lambda, whose argument tuple carries a non-null but empty list, so the row reddens if the predicate had required a non-empty list
3 💡 The changelog category should be Critical Bug Fix (crash, data loss, RBAC) rather than Bug Fix DISAGREE The terminating shapes need the experimental, non-default enable_json_ast_dialect, and the ungated route this diff also guards (formatQueryFromJSON) does not terminate: the formatter's operator section is behind isOperator() && arguments (ASTFunction.cpp:572) and isAcceptableArgumentsForLambdaExpression null-checks the tuple list (:479). #114429 shipped the same defect class in the same family under Bug Fix and merged. I do not self-assign Critical Bug Fix; the PR body names the gating, and I will switch the category if a maintainer prefers it. Round-6 correction to my own evidence: row 8's route needs no setting at all, so the gating argument covers the JSON routes only
4 💡 The Closes: relationship line was inside the template's HTML comment, so the issue was not linked visibly AGREE, applied in the PR body Moved to a visible line below the comment block, in the full-URL form
5 ⚠️ Two clauses of the new boundary predicate have no oracle: the only non-lambda name row also omits arguments, and no flagged payload has three outer arguments, so weakening children.size() == 2 to >= 2 keeps every test green while QueryTreeBuilder silently drops the third (ASTFunction.cpp:1187) AGREE, fixed @ 5d7fe6cda071c Confirmed by parsing every flagged negative row rather than by inspection: both clauses were unpinned. Two otherwise-valid flagged rows were added, each varying one clause and each measured red on its own single-clause mutant, with no other row of either test moving. Both shapes are already rejected by the shipped code, so this was oracle debt and no source change followed
6 💡 RequiredSourceColumnsVisitor.cpp:30 reports "First argument of lambda must be a tuple" for a condition that now also fires when the first argument IS a tuple but carries no argument list of its own Noted, deliberately not changed The identical message guards the identical predicate at ActionsVisitor.cpp:1534 and ExpressionElementParsers.cpp:1900, so changing it here alone would diverge from both sibling sites
7 ❌ A fourth route of the same family still terminates the process, with no flag and no lambda-name test anywhere on it: ASTCreateSQLFunctionQuery::readJSON takes function_core through the untyped readChild, and validateSQLFunction then binds lambda_function->arguments->children before checking the size, so a clickhouse_json CREATE FUNCTION whose core is a Function with no arguments dies (UserDefinedSQLFunctionFactory.cpp:74) AGREE, fixed @ 1587fc956fc31 Verified end to end before accepting it: ASTFromJSON.cpp:178 registers the node, ASTCreateSQLFunctionQuery.cpp:91 reads the core untyped, and registerFunction reaches the validator at :169. The remedy is the null check the same function already applies to the inner tuple list six lines below, plus a case in the isolated test
8 ❌ A fifth route of the same family: the hardened UDF validator checks every structural clause of a CREATE FUNCTION core except that the outer function is itself named lambda, so a clickhouse_json core f(tuple(x), x) registers, and the first use of the function raises LOGICAL_ERROR (UserDefinedSQLFunctionFactory.cpp:69) AGREE, fixed @ 381ae29b33ec6 Read the validator and both ends before accepting it: QueryAnalyzer.cpp:628-632 throws LOGICAL_ERROR "SQL user defined function ... must represent lambda expression", which aborts every debug and sanitizer build. Same door and same error class as the reported defect, in the function this PR already hardens. Remedy is a name check at the top of the validator plus a case in the isolated test
9 ⚠️ The new boundary check accepts a flagged lambda that also carries parameters, which query analysis then silently drops (ASTFunction.cpp:261) AGREE, then RETRACTED and reverted in round 5, see row 11 parameters is restored at :230 before the check at :261, isASTLambdaFunction says nothing about parameters, and QueryTreeBuilder's lambda branch reads only arguments; no producer of the flag was believed to emit parameters (Layer::parseLambda, the APPLY parser, LambdaNode::toAST). Round 5 measured that last clause to be false
10 ⚠️ This PR removes the only oracle of the pre-existing APPLY guard: the negative row at 04344_ast_json_select_child_typing.sql:78 keeps is_lambda_function, so the child check now rejects it before the transformer's own guard runs AGREE on the debt, fixed @ 381ae29b33ec6; my stated cause was wrong Raised independently by both reviewers. The guard is load-bearing (applyColumnsTransformer.cpp:54-56 dereferences that list) and had no oracle, which is what the fix addresses. But measurement showed this PR did not take the oracle away: the row's payload was never brace-balanced, so it had been satisfying its serverError BAD_ARGUMENTS on a JSON syntax error since it was written. Reverting only the transformer guard reddens the repaired row; reverting only the boundary check leaves it green
11 ❌ The parameters rejection added for row 9 rejects a shape the SQL parser does produce: APPLY(lambda(1)(tuple(x), x + 1)) parses into a flagged lambda carrying parameters, so formatQueryFromJSON now refuses parseQueryToJSON's own output (ASTFunction.cpp:261) AGREE, fixed @ 065801a625f6a Raised independently by both reviewers this round, and it retracts row 9. The flag has two producers, not one: ParserColumnsTransformers (ExpressionElementParsers.cpp:1889-1911) sets it on any expression that parsed as an ASTFunction named lambda, never testing parameters. Measured: the SQL query returns 2 while the JSON round trip raises BAD_ARGUMENTS. The clause and its negative row go; a positive round-trip row for the parser-produced spelling takes their place
12 ⚠️ Not symmetric with row 11: an argument tuple carrying parameters is parser-impossible and still accepted, and the UDF validator has the same omission, so such a core registers and is persisted as text that does not parse back (ASTFunction.cpp:1190, UserDefinedSQLFunctionFactory.cpp:84) AGREE, fixed @ 065801a625f6a tuple is routed to TupleLayer, which has no parametric form at all, and Layer::parseLambda builds the argument tuple itself, so rejecting this shape cannot break a round trip. The stored lambda(tuple(7)(x), x) does not re-parse, so UserDefinedSQLObjectsDiskStorage::tryLoadObject skips the object and the function disappears at the next load. One clause at each site, one negative row each
13 💡 The isolated test's introduction claims every shape below took the process down, which is not true of its CREATE FUNCTION case (registration succeeds; the LOGICAL_ERROR lands at the first use), and one comment has a verb-tense slip AGREE, fixed @ 065801a625f6a Both reviewers; folded into the round-5 pass rather than bounced on its own
14 💡 A flagless APPLY lambda still bypasses the argument-tuple parameters rejection: the boundary check is conditioned on is_lambda_function, and the transformer's own guard tests only that the lambda has at least two arguments, so the parameter list is dropped (ASTColumnsTransformers.cpp:351) AGREE on the mechanism, severity reduced to a nit, deliberately not changed Confirmed by reading, and the round-6 reviewer's proposed remedy would be sound; declined on consequence and scope. The payload formats as SELECT * APPLY x -> (x + 1), which is exactly what applyColumnsApplyTransformer executes, so the only loss is a parameter list no consumer reads: nothing terminates, nothing is persisted. Changing that pre-existing guard also moves which arm rejects the 04344 row two rounds reworked, so it needs its own both-directions measurement rather than a last-round edit

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per
finding. Findings on hunks unchanged by a fix round are auto-dropped.

Also checked and found already safe, so not raised: the formatter's lambda path (ASTFunction.cpp:882),
resolveFunction.cpp:2160, TrinoFunctionMapper.cpp:79-81, ConstantExpressionTemplate.cpp:87 and
:260, and QueryTreeBuilder.cpp:698, whose else branch guards both dereferences.
src/Parsers/tests/gtest_tree_hash_completeness.cpp, the only gtest that round-trips through
IAST::createFromJSON, never injects is_lambda_function, so the new rejection carries no unit-test
regression.

One class deliberately left out of scope, stated so it is not mistaken for completeness: a JSON-restored
AST can still format to SQL that does not parse back (a windowed or NULLS-modified argument tuple, for
instance), because nothing validates that for this dialect. This PR rejects the lambda shapes whose
consumers dereference what the parser guarantees, not every AST whose text is unparseable.

Five process kills noticed while sweeping this family and deliberately not carried here, all pre-existing
on master and all a different class: deleting a constraint expression's arguments reaches a null deref in
ComparisonGraph.cpp:151, and four others report LOGICAL_ERROR on user input, which aborts debug and
sanitizer builds (InterpreterCreateQuery.cpp:781 and :1201, QueryTreeBuilder::buildJoinTree:1193,
ITableFunctionFileLike::parseArguments:49). Which layer should reject those, and with which code, is a
call for whoever owns the dialect, so I am reporting them rather than picking one here.

Merge-order note, not a finding: #105045 moves extractNamesFromLambda into src/Parsers/ASTFunction.cpp
as getASTLambdaArgumentNames; its copy carries the first of the two null checks here but not the second,
so it does not close this crash, and the two changes will conflict textually if both land. The positive
round-trip row added this round formats through ASTColumnsApplyTransformer::formatImpl, which #114205
also changes, so whichever of those two lands second owes one more reference line. Against current master
this branch merges cleanly.

Session id: cron:clickhouse-review-slot-8:20260916-213013

@clickhouse-gh clickhouse-gh Bot closed this Sep 16, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 1/1, no randomization: a clickhouse_json payload whose sole select expression is {"type":"Function","name":"lambda","is_lambda_function":true} aborts clickhouse-local (exit 134, Assertion 'px != 0' failed), as does a CREATE TABLE ... INDEX idx <bare lambda> payload, a JSON-deserialized CREATE FUNCTION whose core is lambda with no arguments, and a core named f rather than lambda (which registers and then takes the server down at first use); 16 payload shapes measured base vs fix.
b Root cause explained? Every parser producer of is_lambda_function builds lambda(tuple(args...), body) and ASTFunction::readJSON restores the flag without re-checking that shape, while QueryTreeBuilder::buildExpression puts the flag FIRST in isLambdaFunction() || isASTLambdaFunction(*function), short-circuiting the only shape predicate and then dereferencing arguments (null), .at(0)/.at(1) (out of range) and casting children[0] to ASTFunction (bad cast) with none established.
c Fix matches root cause? Yes: the parser-impossible payload is rejected at the JSON boundary where the untrusted value enters, next to the kind/flag pair the same function already validates, and the registration route is closed in validateSQLFunction, the function whose job is to reject a malformed core, before it is persisted rather than at the QueryAnalyzer.cpp:628 site where the consequence lands. No widened bound, no no-random-* tag, no guard at a crash site.
d Test intent preserved / new tests added? No existing assertion weakened: 12 rows added to 04339_ast_json_review_followup_hardening (nine shape rows, one per part of the shape the flag promises, plus three round-trip positives), a new 05218_ast_json_lambda_shape_query_analysis.sh for the shapes only reachable by executing the dialect, routed through clickhouse-local because each took its own process down, and 04344's pre-existing APPLY row repaired, since its payload was never valid JSON so the guard it documents had no oracle at all.
e Both directions demonstrated? Yes, and per condition rather than only per diff: 2 tests passed on the fixed binary against Having 2 errors! 0 tests passed on pristine HEAD (04339 reports The query succeeded but the server error '36' was expected, 05218 prints KILLED_BY_SIGNAL rc=134), and every shipped condition has its own single-condition mutant, built separately, that reddens exactly one assertion while every other line of both tests stays green.
f Fix is general across code paths? The 12 sites that trust this invariant were enumerated and each is closed or shown safe (QueryTreeBuilder.cpp:655/656/693, ActionsVisitor.cpp:1537/:1674, ExpressionElementParsers.cpp:1902, extractNamesFromLambda and its 6 callers, ASTColumnsTransformers.cpp:354 kept and measured still live), plus validateSQLFunction, which sits off that axis and tests nothing about the node beyond as<ASTFunction>(), so no grep for the flag could find it; a 237-variant member-deletion sweep across 29 queries rediscovers both fixed families and finds no remaining instance of this class.
g Fix generalizes across inputs (params/datatypes/wrappers)? All four reported shapes plus three the report did not have, on both analyzer routes (SELECT expression, APPLY transformer) and the metadata routes (skip index, ALIAS column, PROJECTION); lambda(tuple(), 1) keeps round-tripping and SELECT lambda(1, 2) keeps parsing, which is why the check is keyed on the flag rather than on the function name, and the new clauses are keyed on presence and on the name rather than on a value, so they hold for any parameter list and any non-lambda core.
h Backward compatible? (maintainer-approved exception only) Yes: the only payloads whose behaviour changes are ones that abort or raise today, or ones the parser cannot produce at all, and 27 pure-SQL lambda shapes produce byte-identical output before and after (DIFFS=0 / 27), including the parametric lambda(1)(tuple(x), x + 1) spelling through a full formatQueryFromJSON(parseQueryToJSON(...)) round trip; three message-level deltas, and no setting, default or format change, so no SettingsChangesHistory.cpp entry is owed.
i Invariants and contracts preserved? The boundary check runs inside readJSON after arguments is read, so it never sees a half-built node and never runs on the SQL path; extractNamesFromLambda keeps its contract of THROWING rather than returning for a malformed shape; and the registration check throws before the object is written to user_defined/, which matters because the unfixed path persists the core first and then aborts on every use until it is dropped, while the parametric-tuple core is persisted as text tryLoadObject then fails with SYNTAX_ERROR, so the function silently disappears at the next load.

Session id: cron:clickhouse-impl-slot-41:20260916-205400

@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [29d98ac]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR closes several real lambda-shape failures in clickhouse_json deserialization and CREATE FUNCTION validation, but the hardening is not complete yet. One malformed lambda core can still be persisted through CREATE FUNCTION, and one flagless APPLY lambda-mode bypass still lets the AST text diverge from the semantics that applyColumnsApplyTransformer executes, so I would request changes.

Findings

⚠️ Majors

  • [src/Functions/UserDefined/UserDefinedSQLFunctionFactory.cpp:85] validateSQLFunction still accepts compound lambda parameters even though the always-on analyzer rejects them later. ParserExpressionImpl::parseLambda accepts any ASTIdentifier, so CREATE FUNCTION f AS (x.y) -> x.y is parser-producible and passes registration here, but QueryTreeBuilder::buildExpression throws once it sees name_parts.size() > 1. Suggested fix: apply the same single-part identifier check in validateSQLFunction before persisting the definition.

  • [tests/queries/0_stateless/04344_ast_json_select_child_typing.sql:80] The new APPLY regression only covers a missing arguments list. The flagless ASTColumnsApplyTransformer path still accepts a lambda child whose embedded AST is not the parser's one-argument lambda(tuple(arg), body) shape, or whose tuple argument disagrees with lambda_arg, even though formatting uses the embedded AST while execution uses only the body plus the out-of-band lambda_arg. Suggested fix: validate the full parser shape in ASTColumnsApplyTransformer::readJSON and add a negative row that drops the flag but renames the lambda or tuple instead of deleting arguments.

Tests
  • ⚠️ Add a negative CREATE FUNCTION case for a compound lambda parameter such as (x.y) -> x.y, so the validator is measured against the analyzer's actual contract.
  • ⚠️ Add a ColumnsApplyTransformer JSON case that drops is_lambda_function and kind but keeps two lambda children while renaming the lambda or tuple argument, so the flagless APPLY guard proves the full shape rather than only arguments != nullptr.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: reject compound lambda parameter identifiers during CREATE FUNCTION validation, and tighten the flagless ASTColumnsApplyTransformer lambda-mode guard so the embedded lambda shape cannot disagree with lambda_arg.

LLVM Coverage Report

Measured on commit 29d98ac.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 31/31 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 16, 2026

if (!tuple_function_arguments || !tuple_function_arguments->arguments || tuple_function_arguments->name != "tuple")
if (!tuple_function_arguments || !tuple_function_arguments->arguments || tuple_function_arguments->name != "tuple"
|| tuple_function_arguments->parameters)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

After this gate, validateSQLFunction is still weaker than the analyzer on lambda parameter names. ParserExpressionImpl::parseLambda accepts any ASTIdentifier on the left-hand side, so CREATE FUNCTION f AS (x.y) -> x.y is parser-producible and will pass the loop below: each tuple element is an ASTIdentifier, and the duplicate-name check keys on argument_identifier->name() (x.y). But QueryTreeBuilder::buildExpression rejects the stored definition later when name_parts.size() > 1, and enable_analyzer is frozen at 1, so the function is persisted successfully and then fails on every use. If registration is meant to be the gate for malformed lambda cores, the validator needs the same single-part check and a focused regression test here.

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.

Mechanism confirmed, remedy declined, and I measured both before deciding (binary dc56b252, which carries the check I then reverted).

(x.y) -> x.y is not a core that can never execute. It registers, is persisted, reloads, and UserDefinedSQLFunctionVisitor expands it correctly in table DDL: with the core stored, CREATE TABLE t (a UInt8, b UInt8 DEFAULT udf_dot(9)) plus INSERT INTO t (a) VALUES (1) returns 1 9. The same expansion still works on the binary that carries the check (3 7), because loading stored objects does not validate them.

On an ordinary call the analyzer already reports it cleanly: Code: 36. Lambda x.y -> x.y argument identifier must contain single part. Actual x.y. (BAD_ARGUMENTS). No crash, no LOGICAL_ERROR, no silently wrong result. The check would only move an already-clean error earlier, and registerFunction is also the restore path (UserDefinedSQLFunctionFactory::restore), so it would additionally refuse restoring a backup that contains such an object. I implemented it, measured that, and dropped it. My internal second-model review reached the same conclusion independently and rated the caller impact a blocker.

One point of yours does survive, and it is worth stating plainly: this PR's gate covers new registrations only. A core stored by an older binary still reaches query analysis, so CREATE FUNCTION udf AS f(tuple(x), x) created on master and called on this branch still aborts a debug build (measured, rc=134 on this branch's head). Closing that needs the check inside QueryAnalyzer::tryGetLambdaFromUserDefinedSQLFunctions, which is a different change from the one this PR makes and needs a test that can construct the stored state legitimately. I am handling it separately; say if you would rather have it here.

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.

Forget about fixing old binary upgrades.

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.

Understood, dropping it.

Nothing changes in this PR on that ground: the gate here only runs at CREATE FUNCTION, and the shapes it rejects are reachable today through the AST JSON dialect rather than only from an older binary.

-- the boundary check on that flag.
-- ---------------------------------------------------------------------------
SELECT formatQueryFromJSON(replace(parseQueryToJSON('SELECT * APPLY(x -> (x + 1)) FROM t'), '"name":"lambda","arguments":{"type":"ExpressionList","children":[', '"name":"lambda","arguments":{"type":"ExpressionList","children":[]},"unused":[')); -- { serverError BAD_ARGUMENTS }
SELECT formatQueryFromJSON(replace(replace(replace(parseQueryToJSON('SELECT * APPLY(x -> (x + 1)) FROM t'), '"name":"lambda","arguments":{"type":"ExpressionList","children":[', '"name":"lambda","unused":{"type":"ExpressionList","children":['), ',"is_lambda_function":true', ''), ',"kind":"LAMBDA_FUNCTION"', '')); -- { serverError BAD_ARGUMENTS }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This new row only proves the arguments == nullptr case. ASTColumnsApplyTransformer::readJSON still accepts any ASTFunction with two children once is_lambda_function and kind are stripped, even if the child is not actually the parser's one-argument lambda(tuple(arg), body) shape or if its tuple argument disagrees with lambda_arg. That remains a real AST/semantics split: formatImpl serializes the embedded AST, but applyColumnsApplyTransformer executes only arguments->children.at(1) plus the out-of-band lambda_arg, so the same clickhouse_json payload can still format one APPLY(...) and execute another. I think this path needs the same shape check here (name == "lambda", isASTLambdaFunction, exactly one tuple identifier matching lambda_arg) plus a negative row that drops the flag and renames the lambda or tuple instead of removing arguments.

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.

Measured, and the split does not reproduce. I built seven payloads from parseQueryToJSON('SELECT * APPLY(x -> (x + 1)) FROM t') on t (a UInt8, b UInt8) holding (1, 10), dropping is_lambda_function and kind and then varying the child, and compared formatQueryFromJSON against executing the same payload under dialect = clickhouse_json:

flagless payload executing the JSON executing its own formatted SQL
lambda renamed to plus UNKNOWN_IDENTIFIER x same error
tuple identifier renamed to y, body keeps x UNKNOWN_IDENTIFIER x same error
flag and kind dropped, shape intact 2 11 2 11
tuple declares two identifiers Lambda (x, z) -> (x + 1) expect 2 arguments SYNTAX_ERROR
third child in the lambda argument list UNKNOWN_IDENTIFIER x SYNTAX_ERROR
argument list is array(x), not tuple(x) UNKNOWN_IDENTIFIER x SYNTAX_ERROR
self-consistent lambda, stale lambda_arg 2 11, formats y -> (y + 1) 2 11

Every arm either agrees on both paths or is rejected on both. None formats one APPLY and executes another.

The reason is the executor. applyColumnsApplyTransformer is the pre-analyzer expansion; a SELECT reaches QueryTreeBuilder::buildExpression, which builds the lambda from the AST (QueryTreeBuilder.cpp:1210-1213) and never reads lambda_arg. The last row is the proof: the AST declares y, lambda_arg still says x, and both the text and the result follow the AST. That executor's live caller is the INSERT column list through processColumnTransformers, and there the outcome does not depend on lambda_arg either, because the substitution only rewrites children: a bare-identifier body is left untouched and anything else becomes a name no column has (No such column plus(a, 1)). OPTIMIZE ... DEDUPLICATE BY rejects APPLY at the parser.

So the extra guard would reject rows 3 and 7, which round trip and execute correctly today, without removing a defect, which is why I am not adding it. The flagged form of your shape is already rejected by this PR: keep is_lambda_function on the three-child lambda and the boundary check raises BAD_ARGUMENTS.

On the row itself: it does prove more than arguments == nullptr. It renames the argument list away and drops the flag, so it reaches the shape guard rather than the boundary check, and deleting either arm reddens exactly one row.

@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 29d98ac

Every failure below has an owner: a fixing PR (mine 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
Build profile diff infra: the readiness probe reported No connection to LogCluster on all 8 retries, so select() returned None and query() raised RuntimeError: CI logs cluster query failed before any comparison ran (ci/jobs/build_profile_diff_job.py:234, reached from has_pr_data at :723, i.e. the post-ci_build_profiler layout). Nothing about this commit was measured. #120121 (mine, open)
PR rollup: red only because of the row above, no independent failure #120121 (mine, open)

Mergeable Check, Finish Workflow and CH Inc sync are green on this head. The two Bugfix validation (functional tests, *) legs are green too: the 04344_ast_json_select_child_typing row inside them is the expected result, since that check requires the new regression test to fail against master.

Session id: cron:our-pr-ci-monitor:20260917-053047

@PedroTadim PedroTadim self-assigned this Sep 17, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Sep 17, 2026
Merged via the queue into ClickHouse:master with commit f77edf0 Sep 17, 2026
346 of 523 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 17, 2026
@fm4v

fm4v commented Sep 29, 2026

Copy link
Copy Markdown
Member

@groeneai is it expected to get this error on instance upgrade:
Run(): unable to restore the instance aquamarine-kv-86. Error: backup_error=Code: 36. DB::Exception: Expected lambda expression, got: JSONExtractString((x, y), x): While restoring data of table system.functions. (BAD_ARGUMENTS), Stack trace (when copying this message, always include the lines below):

unable to restore the instance Error: backup_error=Code: . DB::Exception: Expected lambda expression, got: JSONExtractString((x, y), x): While restoring data of table system.functi
New backward-compatibility regression, not a known issue. PR #120483 (in 26.10.1.14+) added a check that a SQL UDF body must be a lambda, and that check also runs on RESTORE. A UDF with the body JSONExtractString((x, y), x), accepted by the source's 26.4 build, now fails system.functions and aborts the whole restore on 26.10.1.40078. The closest issue, clickhouse-private#75296 (closed not_planned), is a sibling: different exception and throw site.

In instance text_log, BackupsWorker fails at 20:18:30 with Code: 36 ... Expected lambda expression, got: JSONExtractString((x, y), x): While restoring data of table system.functions. The throw site is UserDefinedSQLFunctionFactory.cpp:75, inside validateSQLFunction, called from registerFunction, called from UserDefinedSQLFunctionFactory::restore (line 311), called from RestorerFromBackup::insertDataToTable. That exact check (if (lambda_function->name != "lambda") throw BAD_ARGUMENTS "Expected lambda expression...") was added by commit 381ae29 in ClickHouse PR #120483 ('Reject parser-impossible lambda shapes', merged into 26.10.1.14). Before that PR, validateSQLFunction checked arity 2, a tuple of identifiers as the first argument, and a non-null body, but not the function name. So CREATE FUNCTION f AS JSONExtractString((x, y), x) was accepted and persisted on the source (26.4). The PR tightened the gate for CREATE FUNCTION, but registerFunction is also the restore path, and restore has no skip or tolerate option. One legacy UDF therefore aborts the entire instance restore. Eight other UDFs (for example access_control and cashflows_npv) were restored before the abort; the offending function is missing from system.functions. HYPOTHESISED: (1) Before 26.10 this UDF would already have raised LOGICAL_ERROR at first use (per the PR description), so it is probably unused on the source. (2) If the UserDefinedSQLObjectsLoader startup path also runs this validation, upgrading the source to 26.10 could break its UDF loading. Not verified.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Not expected, this is a regression from this PR. The name != "lambda" clause I added to validateSQLFunction also runs on RESTORE (UserDefinedSQLFunctionFactory::restore -> registerFunction), so a function that an earlier version accepted now aborts the whole restore. I wrote earlier in this PR that this check only runs at CREATE FUNCTION; that was wrong.

On the two hypotheses, checked on current master (6ee563bc) with CREATE FUNCTION f AS JSONExtractString((x, y), x) placed in user_defined/:

  1. Mostly right. A call through the analyzer fails with LOGICAL_ERROR "SQL user defined function f must represent lambda expression", from a check that predates this PR by years. The call only works where it is expanded textually: in table DDL (DEFAULT f(a, 7) is stored as DEFAULT a, so such tables do not need the function afterwards) and, on 26.4, with enable_analyzer = 0.
  2. Does not happen. Loading at startup does not run this validation: both the disk and the Keeper storage only parse and normalize the stored query. With the disk storage the function above is still loaded and listed in system.functions, so an in-place upgrade keeps it.

I will send a fix so that RESTORE accepts functions stored by an earlier version, and link the PR here. My open #121370 adds one more clause to the same function; the fix will cover it too.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The fix is #122912. On RESTORE only, it skips the rules that a stored definition may predate: the core must be a lambda and its argument tuple must have no parameters (both from this PR), and the argument list must be a tuple (#80431, first released in 25.6). CREATE FUNCTION is unchanged.

Because of the tuple rule, RESTORE already fails the same way on releases since 25.6 for a backup taken on 25.5 or earlier that holds, for example, lambda(identity(x), x); the fix handles that case too. #121370 is still open, so its new rules will get the same exemption in whichever of the two PRs merges second.

clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Oct 1, 2026
`RESTORE TABLE system.functions` registers every restored definition through
`registerFunction`, whose `checkCanBeRegistered` runs `validateSQLFunction`,
the check for a new `CREATE FUNCTION`. Each time that check was tightened,
definitions stored under the older rules became unrestorable, and the first of
them aborted the whole restore:

- ClickHouse#80431 (25.6) requires the argument list to be a `tuple`, so a backup taken
  on 25.5 or earlier that holds `CREATE FUNCTION f AS lambda(identity(x), x)`
  fails on 25.6 and later with `Lambda must have valid arguments`.
- ClickHouse#120483 (master) requires the core to be a `lambda` and the tuple to have no
  parameters, so a Cloud upgrade from 26.4 failed with
  `Expected lambda expression, got: JSONExtractString((x, y), x): While
  restoring data of table system.functions`:
  ClickHouse#120483 (comment)

Loading the same definitions from disk or Keeper at startup never validates
them, so an in-place upgrade keeps them and `BACKUP` writes them out unchanged.

`restore` now passes `is_restore`, and `validateSQLFunction` then skips exactly
those two rules. The structural rules stay (the core is a function with two
arguments, the argument list holds unique identifiers, the body exists, no
self-recursion): no version accepted a definition that fails them, and the DDL
expansion in `UserDefinedSQLFunctionVisitor::tryToReplaceFunction` relies on
them without checks. `CREATE FUNCTION` is unchanged. Tables are re-created by
`RESTORE` under `LoadingStrictnessLevel::SECONDARY_CREATE`, which skips some
sanity checks for the same reason.

The new backward-compatibility test creates three such definitions and a
control on 25.3, backs them up, upgrades, and restores; it fails on master and
on 26.9.1.1629 at the first restore.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR 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.

JSON AST is_lambda_function is shape-unchecked: SIGSEGV in query analysis

4 participants