Repository navigation
Fix inconsistent AST formatting for lambda after a function-call comma - #104626
PedroTadim merged 5 commits into
Conversation
Parsing `f(x, y -> z)` silently merged the leading arguments into the lambda's left-hand side, producing `f(lambda(tuple(x, y), z))` — a one-argument call. The formatter then emitted `f((x, y) -> z)`, which is not parseable in a function-argument position (only `(args) -> body` inside an outer parenthesized expression is allowed there), so the round-trip check in `executeQueryImpl` raised `Inconsistent AST formatting` `LOGICAL_ERROR` and aborted the server in debug / sanitizer builds. The bug was in step 3 of `Layer::parseLambda`: after `mergeElement()` pushed the current operand onto `elements`, the code wrapped *all* accumulated elements (including the prior comma-separated function arguments) into a single tuple to use as the lambda's lhs. Only the last element — the just-merged current operand — actually belongs to the lambda's lhs; earlier elements are siblings in the surrounding function's argument list and must be preserved. After this fix, `f(x, y -> z)` parses as `f(x, lambda(tuple(y), z))`, preserving the function's arity. Legitimate forms (`x -> y` at the start of a function call, `(x, y) -> z` after explicit parentheses, standalone lambdas) are unchanged. Calls that semantically don't accept a lambda in that position (`arrayMap(arr, x -> ...)`, `arrayMap(x -> ..., y -> ...)`) now reach the analyzer with a deterministic AST shape and surface a clear `ILLEGAL_TYPE_OF_ARGUMENT` / `UNKNOWN_IDENTIFIER` error instead of either the round-trip exception or a silent arity rewrite. Closes ClickHouse#104605
|
cc @evillique @alexey-milovidov @george-larionov — could you review this? It fixes a parser bug where |
|
Pre-PR validation gate (per worker procedure):
Session: cron:clickhouse-ci-task-worker:20260511-174500 |
|
Workflow [PR], commit [7becda5] Summary: ❌
AI ReviewSummaryThis PR fixes the Final Verdict
|
…yer/PositionLayer
The previous commit broke the documented lambda-merging behavior that
higher-order functions rely on. `mapApply(k, v -> ..., x)`,
`arrayFold(acc, x -> ..., arr, init)` and similar idioms depend on the
parser collapsing `f(a, b, c -> body)` into `f((a, b, c) -> body)` (a
one-argument call carrying a multi-arg-lambda left-hand side). Removing
that merging regressed four Fast tests:
- 02476_fix_lambda_parsing
- 02418_aggregate_combinators
- 02718_array_fold
- 01144_multiple_joins_rewriter_v2_and_lambdas
Revert the parseLambda change and instead fix the round-trip invariant
at the only two layers where it actually fails: `SubstringLayer` and
`PositionLayer`. Both rejected the one-argument form at state 0
(no `)` handler), so when the formatter emitted `substring((x, y) -> z)`
or `position((x, y) -> z)` for a one-argument call carrying a
merged-tuple lambda, the re-parser threw `SYNTAX_ERROR` and the
round-trip check in `executeQueryImpl` raised an `Inconsistent AST
formatting` `LOGICAL_ERROR`.
Adding a closing-bracket handler at state 0 lets the one-argument form
parse to a one-argument call; the analyzer then rejects it with a clear
`NUMBER_OF_ARGUMENTS_DOESNT_MATCH` / `ILLEGAL_TYPE_OF_ARGUMENT` /
`BAD_ARGUMENTS` (depending on the specific input) instead of an
abortable `LOGICAL_ERROR`.
Other special-cased layers (`ExtractLayer`, `OverlayLayer`,
`CastLayer`, `TrimLayer`, `DateAddLayer`, `DateDiffLayer`) are not
affected: either they delegate to `LayerWithSeparator` which already
accepts the one-argument form, or they reject the malformed input
earlier and never reach the round-trip check.
Verified locally:
- Original reproducer `SELECT substring(x, \`x\` -> \`x\`)` no longer
aborts; analyzer reports `BAD_ARGUMENTS` (lambda duplicate parameter
name).
- 02476, 02418, 02718, 01144 pass again.
- New test 04227 passes 50/50 with full setting randomization.
- `mapApply`, `arrayFold`, `arrayMap` higher-order calls keep working
with the comma-merging sugar.
Closes ClickHouse#104605
Updated approach: revert parseLambda change, fix the round-trip at the right layerAfter the previous commit landed, CI reported 4 Fast test regressions (02476_fix_lambda_parsing, Root-cause refinedThe actual round-trip failure is not in
Fix
Pre-PR validation gate
Branch updated: commit |
The previous commit (6c16953) added an unconditional `)` handler to state 0 in `SubstringLayer` and `PositionLayer`, which made `substring(x)` and `position(x)` parse as one-argument calls. That regressed `02154_parser_backtracking`: lines 23, 24, 25 expect deeply- nested `position(x)`, `position(x y)`, and `position(x IN y)` (where each outer call has only one inner expression) to fail with `SYNTAX_ERROR` to prevent exponential parser backtracking. Under the permissive handler they parsed successfully and only failed later with `UNKNOWN_IDENTIFIER`, so `grep -cF 'Syntax error'` returned 0 instead of the expected 1. The state-0 `)` handler is only needed for one case: the AST shape `substring(lambda(tuple(a, b), body))` / `position(lambda(tuple(a, b), body))` produced by the documented lambda-merging sugar (`f(a, b, c -> body)` parses to `f(lambda(tuple(a, b, c), body))`, used by `mapApply`, `arrayFold`, etc.). The formatter emits `substring((a, b) -> body)` for that shape, and re-parsing it requires accepting `)` at state 0 *after the lambda has been formed*. Gate the handler on `previousType() == OperatorType::Lambda`. Bare one-argument `substring(x)` and `position(x)` (no lambda pending) continue to fail at parse time as before, restoring 02154's backtracking-guard behavior. The round-trip for the formatted lambda output continues to work, and the original reproducer from issue ClickHouse#104605 (`SELECT substring(x, \`x\` -> \`x\`)`) still surfaces as `BAD_ARGUMENTS` (duplicate lambda parameter names) instead of an `Inconsistent AST formatting` `LOGICAL_ERROR`. Test changes: - 04227: drop the two bare-one-argument assertions that were testing an artifact of the permissive handler. The test runner aborts a multi-query batch on the first `SYNTAX_ERROR`, so those assertions can't be expressed this way; the parse-time rejection is exercised by `02154_parser_backtracking` instead. Add an explanatory comment. Verified locally: - `02154_parser_backtracking`, `04227_inconsistent_ast_function_lambda_after_comma_104605`, `02476_fix_lambda_parsing`, `02418_aggregate_combinators`, `02718_array_fold`, `01144_multiple_joins_rewriter_v2_and_lambdas` — all PASS. - 30 randomized iterations across 10 lambda/AST-formatting tests (incl. `03761_inconsistent_ast_formatting`, `03168_inconsistent_ast_formatting`, `02343_analyzer_lambdas`, `02882_formatQuery`, `02128_apply_lambda_parsing`, `01960_lambda_precedence`): 300/300 PASS. - Substring/position function tests (`01033_function_substring`, `00936_substring_utf8_non_const`, `01665_substring_ubsan`, `02346_position_countsubstrings_zero_byte`, `00233_position_function_family`, `03013_position_const_start_pos`): all PASS. - `SELECT substring(x, \`x\` -> \`x\`)` -> `BAD_ARGUMENTS`, not LOGICAL_ERROR. - `SELECT substring(x)` / `SELECT position(x)` -> `SYNTAX_ERROR`, as before this PR. - Higher-order function sugar (`arrayMap`, `arrayFold`, `mapApply`) unchanged. Closes ClickHouse#104605
|
Third revision — commit Why a third revisionThe previous commit ( The narrow fixGate the state-0 else if (previousType() == OperatorType::Lambda
&& ParserToken(TokenType::ClosingRoundBracket).ignore(pos, expected))
{
if (!mergeElement())
return false;
finished = true;
}Pre-PR validation gatea. Deterministic repro? Yes — Verified locally
cc @evillique @alexey-milovidov @george-larionov session: cron:clickhouse-ci-task-worker:20260512-001500 |
Address bot review comment at ClickHouse#104626 (comment) : `previousType() == OperatorType::Lambda` only inspects the top of the `SubstringLayer` / `PositionLayer` operators stack. For lambdas with a non-trivial body (e.g. `x -> x + 1`), the top operator at the closing bracket is `+` (or `AND`, `[]`, …) and `lambda` is still pending below it, so the state-0 closing-bracket branch is skipped and formatted one-argument forms like `substring((a, x) -> x + 1)` or `position((a, x) -> x + 1)` can still trip the AST round-trip invariant. Replace the top-only check with a `hasPendingOperator(OperatorType)` helper on `Layer` that scans the entire `operators` vector. The `mergeElement` call that follows already drains operators in priority order (`+` first, then `lambda`), so accepting the closing bracket based on the deeper check yields the same `ASTFunction("lambda", ...)` AST regardless of the body shape. Bare `substring(x)` / `position(x)` continue to fail with `SYNTAX_ERROR` at parse time (no lambda anywhere on the stack), so `02154_parser_backtracking`'s exponential-backtracking protection is preserved. Extend `04227_inconsistent_ast_function_lambda_after_comma_104605`: - `formatQuerySingleLine` round-trips with `+` and `AND` bodies for both `substring` and `position`, and the 3-arg merging variant (`substring(a, b, x -> x AND y)`). - Direct merged-tuple forms `substring((s, x) -> x + 1)` and `position((h, x) -> x + 1)` now parse (and fail at function resolution with `ILLEGAL_TYPE_OF_ARGUMENT`) instead of failing at parse time with `SYNTAX_ERROR`. Verified locally: - 04227 50/50 with full randomization. - 02154_parser_backtracking, 02476_fix_lambda_parsing, 02418_aggregate_combinators, 02718_array_fold, 01144_multiple_joins_rewriter_v2_and_lambdas all PASS. - Broader lambda / AST formatting suite passes (02343_analyzer_lambdas{,_issue_*}, 01960_lambda_precedence, 02128_apply_lambda_parsing, 03168_inconsistent_ast_formatting, 03761_inconsistent_ast_formatting, 02882_formatQuery). - Bare `substring(x)` / `position(x)` still SYNTAX_ERROR at parse time. See ClickHouse#104605 Co-Authored-By: Claude Opus 4.7 <[email protected]>
Revision 4 (commit
|
|
@groeneai the test |
Under the old analyzer, `SELECT substring(x, \`x\` -> \`x\`)` returns `ILLEGAL_TYPE_OF_ARGUMENT` (code 43): the analyzer rejects lambda-as-substring-argument before resolving the lambda, so the duplicate-parameter-name check on `(x, x) -> x` never fires. The new analyzer resolves the lambda first and rejects the duplicate names as `BAD_ARGUMENTS` (code 36). Both errors are correct outcomes of the analyzer's dispatch ordering. The test only cares that the server does not abort with `LOGICAL_ERROR` (the original Inconsistent AST formatting bug), so accept either code. This fixes the failure on `Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel)` and on `Bugfix validation (functional tests)`. Reproducible: 3/3 reruns of 04227 failed in CI on the old analyzer with "Expected server error code: 36 but got: 43". Local verification with binary at HEAD (4e02a69): - enable_analyzer=1: BAD_ARGUMENTS (code 36, "Lambda (x, x) -> x multiple arguments with same name x") - enable_analyzer=0: ILLEGAL_TYPE_OF_ARGUMENT (code 43, "Function substring can't have lambda-expressions as arguments: While processing substring((x, x) -> x)") 04227 passes 50/50 with full setting randomization on both analyzers. 02154_parser_backtracking protections still fire under enable_analyzer=0 (bare `substring(x)`, `position(x)`, and 14-deep nested `position`s all return SYNTAX_ERROR). The parser change in this PR is unchanged.
|
@PedroTadim thanks for the heads-up — pushed fix-up 7becda5c712. Root cause: analyzer-dependent error code on the duplicate-param-name reproducer. The first query in
Both are correct outcomes — the new analyzer resolves the lambda first and trips on duplicate parameter names; the old analyzer rejects SELECT substring(x, `x` -> `x`); -- { serverError BAD_ARGUMENTS, ILLEGAL_TYPE_OF_ARGUMENT }CIDB confirmed reproducibility: 3/3 reruns of 04227 failed on Local verification on
Pre-PR validation gate:
Parser change in this PR is unchanged. cc @evillique @alexey-milovidov @george-larionov Session: |
LLVM Coverage Report
Changed lines: 91.30% (21/23) | lost baseline coverage: 2 line(s) · Uncovered code |
4b7ab82
…_operators=false` contexts
Inside `CODEC` / `STATISTICS` / `BACKUP_NAME` argument lists, `ASTFunction::formatImpl`
forces `frame.allow_operators = false`, so a multi-argument `Function_tuple` falls back
to its function-call form `tuple(arg, arg, ...)` instead of the operator form
`(arg, arg, ...)`.
`RoundBracketsLayer::getResultImpl` in `src/Parsers/ExpressionListParsers.cpp` sets
`parenthesized = true` on any node it unwraps from a single-element `(expr)`. So when a
query like
CREATE TABLE t (c0 Int CODEC(not((not(materialize(1), materialize(2)))), ZSTD))
ENGINE = Memory
first formats, the parser-synthesized inner `Function_tuple` (lifted from the multi-arg
`not(a, b)`) emits as `tuple(materialize(1), materialize(2))`. Re-parsing the output then
sees `tuple(...)` wrapped in `(...)` from the outer `not(...)` argument list and sets
`parenthesized = true` on the re-parsed `Function_tuple`. The next format pass adds an
extra `(...)` around `tuple(...)` via the `parenthesized` flag's parens emission in
`IAST::decideParensEmission`, breaking the format-parse-format round-trip with
`Logical error: 'Inconsistent AST formatting' (STID 1941-1bfa)` in debug / sanitizer
builds.
Both `tuple(a, b)` and `(tuple(a, b))` denote the same value, so dropping the redundant
outer paren in `allow_operators = false` contexts is semantics-preserving and keeps the
round-trip stable. The new clause mirrors the existing literal-tuple suppression a few
lines above.
The fix is gated on `args.size() > 1` so the single-argument `tuple(x)` form keeps its
existing behaviour, and on `!frame.allow_operators` so plain expression contexts where
the operator form `(a, b)` is canonical are unaffected.
This is a partial fix for chronic STID 1941-1bfa: it addresses the `CODEC` / multi-arg
`not(a, b)` subvariant and the `ALTER TABLE ... MODIFY STATISTICS ... TYPE
concatAssumeInjective((...))` subvariant. The other reported subvariants — `DESCRIBE
TABLE (SELECT ... COLUMNS(multiIf(...)) ...)` and qualifier-chained `db.t.COLUMNS(*)` —
involve different parser/formatter paths (`COLUMNS` matcher / `DESCRIBE` wrapper) and
need separate fixes.
Related: PR ClickHouse#102547 (zoomxi, INSERT-with-SAMPLE-OFFSET), PR ClickHouse#104520 (data-type
collection literals), PR ClickHouse#104626 (lambda-after-comma).
Affected PRs (90-day window per @alexey-milovidov 2026-05-14 directive on PR ClickHouse#100412):
93037, 104440, 104812, 104591, 100177, 100651, 104523, 94517, 103428, 99495, 97540,
103866, 103349, 101447, 102646, 100453, 100386, 99179, 94849, 98677, 99131, 99277,
99275, 99227, 99229, 99246, 98884, 99138, 99021, 99105, 98906, 99055, 99011, 99066,
99033, 97821, 70661, 103389, 103347, 100700, master.
CI report (PR ClickHouse#100412 sighting):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100412&sha=3284612ceea8078d500d582ce82e5ace86b239cf&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
Parsing a function call where a lambda follows a comma —
f(x, y -> z)—silently merged the leading arguments into the lambda's left-hand side,
producing
f(lambda(tuple(x, y), z)): a one-argument call instead of thetwo arguments the user wrote. The formatter then printed this AST as
f((x, y) -> z), which is not valid as a function-argument expression(only
(args) -> bodyinside an outer parenthesized expression is allowedthere). So when
executeQueryImplre-parsed the formatted query as part ofthe format/re-parse round-trip check, it raised
Inconsistent AST formattingLOGICAL_ERRORand aborted the server in debug / sanitizer builds.The reproducer from the issue:
The bug lives in step 3 of
Layer::parseLambdainsrc/Parsers/ExpressionListParsers.cpp. AftermergeElementpushes thecurrent operand onto
elements, the old code wrapped all accumulatedelements (including the prior comma-separated function arguments) into a
single tuple to use as the lambda's lhs. Only the last element — the
just-merged current operand — actually belongs to the lambda's lhs; earlier
elements are siblings in the surrounding function's argument list and must
be preserved.
With this fix,
f(x, y -> z)parses asf(x, lambda(tuple(y), z)),preserving the function's arity. The formatter then emits
f(x, (y -> z))(lambda parenthesised when it is not the first argument),which re-parses to the same AST — the round-trip check passes.
What still works (verified):
arrayMap(x -> x + 1, [1, 2, 3])— lambda as the first argument.arrayMap((x, y) -> x + y, [1, 2], [10, 20])— explicit tuple lhs.(x, y) -> zstandalone,() -> 1,x -> y— all standalone forms.f(a, (x, y) -> z)— non-first lambda with explicit parentheses.What now changes for the better:
substring(x, x -> x),f(a, x -> y),arrayMap(arr, x -> ...)— theseused to silently mutate into a 1-arg call (and crash on the round-trip
check in debug builds). They now preserve their original arity, reach the
analyzer with a deterministic AST shape, and surface a clear semantic error
(
UNKNOWN_IDENTIFIER/ILLEGAL_TYPE_OF_ARGUMENT) instead.New regression test
tests/queries/0_stateless/04227_inconsistent_ast_function_lambda_after_comma_104605.sqlcovers the original reproducer, several siblings (multi-arg variants,
different functions), and both directions of the round-trip via
formatQuerySingleLine.I also ran the surrounding lambda / AST-formatting tests locally
(
02343_analyzer_lambdas,01960_lambda_precedence,02128_apply_lambda_parsing,03168_inconsistent_ast_formatting,03761_inconsistent_ast_formatting,03927_except_all_ast_formatting_roundtrip,02882_formatQuery, …) —all 31 pass.
Closes #104605
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
Inconsistent AST formattingLOGICAL_ERRORwhen parsing a functioncall where a lambda follows a comma, e.g.
SELECT substring(x, \x` -> `x`)`.The parser used to silently merge the preceding arguments into the lambda's
left-hand side, producing a single-argument call that could not be re-parsed
back to the same AST. It now preserves the function's original arity.
Documentation entry for user-facing changes
cc @PedroTadim @alexey-milovidov @george-larionov @evillique
Session: cron:clickhouse-ci-task-worker:20260511-174500
Version info
26.5.1.614