Repository navigation
Reject parser-impossible lambda shapes in the AST JSON format - #120483
Conversation
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.
Internal second-model review: adjudication log (click to expand)Six review rounds before publication: each round is an independent model reviewing the resulting code
Severity: ❌ blocker / Also checked and found already safe, so not raised: the formatter's lambda path ( One class deliberately left out of scope, stated so it is not mistaken for completeness: a JSON-restored Five process kills noticed while sweeping this family and deliberately not carried here, all pre-existing Merge-order note, not a finding: #105045 moves Session id: cron:clickhouse-review-slot-8:20260916-213013 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260916-205400 |
|
Workflow [PR], commit [29d98ac] Summary: ❌
AI ReviewSummaryThis PR closes several real lambda-shape failures in Findings
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit 29d98ac.
Changed lines: Changed C/C++ lines covered: 31/31 (100.00%) · Uncovered code |
|
|
||
| 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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Forget about fixing old binary upgrades.
There was a problem hiding this comment.
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 } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger - 29d98acEvery 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
Session id: cron:our-pr-ci-monitor:20260917-053047 |
f77edf0
|
@groeneai is it expected to get this error on instance upgrade: 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 In instance text_log, BackupsWorker fails at 20:18:30 with |
|
Not expected, this is a regression from this PR. The On the two hypotheses, checked on current master (
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. |
|
The fix is #122912. On Because of the |
`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]>
Closes: #120380
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a crash and a
LOGICAL_ERRORwhen alambdafunction reached query analysis without thelambda(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 withis_lambda_function, andCREATE FUNCTION f AS g(tuple(x), x)was accepted although the core is not a lambda, so the first call tofraisedLOGICAL_ERROR. Both are now rejected withBAD_ARGUMENTS. Closes #120380.Description
Every parser producer of
is_lambda_functionbuildslambda(tuple(args...), body): the->operator,APPLY (x -> ...)andLambdaNode::toAST.ASTFunction::readJSONrestored the flag as a plain bool, andQueryTreeBuilder::buildExpressiontrusts it ahead ofisASTLambdaFunction, the only shape predicate, so the dialect could hand query analysis a node no parse produces.On a debug build, 1/1 each:
argumentsabsent givesAssertion 'px != 0' failed(a null dereference in release), truncated to one childCode: 1001 ... vector::at out of range, andarguments[0]as an identifier a bad cast toASTFunction. The first shape also killed a server over HTTP, sinceenable_json_ast_dialectisreadonly = 0.Three neighbouring reads, all reachable without the flag, are fixed too.
isASTLambdaFunctiondid not require the argument tuple's ownargumentslist although consumers dereference it.extractNamesFromLambdadereferenced two optional lists onname == "lambda"alone, reached by a skip index expression throughIndexDescription::initExpressionInfo. And SQL UDF registration checked every clause of the core except its own name, sog(tuple(x), x)registered and then raisedLOGICAL_ERRORinQueryAnalyzer::tryGetLambdaFromUserDefinedSQLFunctionsat 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 to04339_ast_json_review_followup_hardening;05218_ast_json_lambda_shape_query_analysis.shcovers what only the dialect reaches, throughclickhouse-localbecause 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 onlyASTColumnsApplyTransformer::formatImpl.Workflow [PR]
Sync PR [sync-upstream/pr/120483]
Version info
26.10.1.14(included in26.10and later)