Skip to content

Fix inconsistent AST formatting for lambda after a function-call comma - #104626

Merged
PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-104605-inconsistent-ast-substring-lambda
May 13, 2026
Merged

PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-104605-inconsistent-ast-substring-lambda

Conversation

@groeneai

@groeneai groeneai commented May 11, 2026 •

Copy link
Copy Markdown
Collaborator

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 the
two 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) -> body inside an outer parenthesized expression is allowed
there). So when executeQueryImpl re-parsed the formatted query as part of
the format/re-parse round-trip check, it raised Inconsistent AST formatting
LOGICAL_ERROR and aborted the server in debug / sanitizer builds.

The reproducer from the issue:

SELECT substring(x, `x` -> `x`);

The bug lives in step 3 of Layer::parseLambda in
src/Parsers/ExpressionListParsers.cpp. After mergeElement pushes the
current operand onto elements, the old 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.

With this fix, f(x, y -> z) parses as f(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) -> z standalone, () -> 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 -> ...) — these
    used 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.sql
covers 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):

  • 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 Inconsistent AST formatting LOGICAL_ERROR when parsing a function
call 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

  • Documentation is written (mandatory for new features)

cc @PedroTadim @alexey-milovidov @george-larionov @evillique

Session: cron:clickhouse-ci-task-worker:20260511-174500

Version info

  • Merged into: 26.5.1.614

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
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique @alexey-milovidov @george-larionov — could you review this? It fixes a parser bug where f(x, y -> z) (lambda after a comma in a function-call arg list) silently merged the preceding identifiers into the lambda's left-hand side, producing a single-arg call that failed the format/re-parse round-trip check and aborted the server in debug builds. The fix changes step 3 of Layer::parseLambda to wrap only the just-merged operand (the lambda's lhs) into the tuple, preserving prior elements as siblings in the surrounding function's argument list.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (per worker procedure):

  • (a) Deterministic repro? Yes. SELECT substring(x, \x` -> `x`)aborts the server withInconsistent AST formatting LOGICAL_ERRORon master HEAD; with this fix the same query returnsUNKNOWN_IDENTIFIER` and the server keeps running.
  • (b) Root cause? Step 3 of Layer::parseLambda consumed all accumulated elements (prior comma-separated function args) into the lambda's lhs tuple, silently changing a 2-arg call into a 1-arg lambda. The formatter then emitted f((x, y) -> z), which is not valid in a function-arg position, so the executeQueryImpl round-trip check failed.
  • (c) Fix matches root cause? Yes. Step 3 now wraps only the last element (the just-merged current operand, which is the lambda's lhs) into a one-element tuple, leaving earlier elements untouched.
  • (d) Test intent preserved / new test added? Yes. New stateless test 04227_inconsistent_ast_function_lambda_after_comma_104605 covers the original reproducer, three sibling variants (f(a, x -> y), f(a, b, c -> d), arrayMap(arr, x -> ...)), three formatQuerySingleLine round-trip checks, and three legitimate forms that must keep working (arrayMap(x -> ..., [arr]), arrayMap((x, y) -> ..., a, b), arrayFilter). Existing lambda/AST-formatting tests (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 pass locally — 31/31.
  • (e) Demonstrated in both directions? Yes — verified locally on the same debug build: query crashes pre-fix, returns clean semantic error post-fix; new test passes 50/50 with full setting randomization.
  • (f) Fix is general? Yes. The bug had one entry point (Layer::parseLambda in src/Parsers/ExpressionListParsers.cpp) and the fix targets that root cause. All sibling manifestations (any function call where bare-identifier args precede a lambda — substring, arrayMap(arr, lambda), generic f(a, b, c -> d)) are covered by the same one-line change. Legitimate forms (f(x -> y, arr), f(a, (x, y) -> z), standalone (x, y) -> z) are unchanged because step 2 (existing tuple-lhs handler) and step 1 (empty lhs) still cover those paths.

Session: cron:clickhouse-ci-task-worker:20260511-174500

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

clickhouse-gh Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7becda5]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL IGNORED

AI Review

Summary

This PR fixes the Inconsistent AST formatting round-trip exception for lambda-after-comma function-call forms by handling the state-0 closing bracket in SubstringLayer and PositionLayer only when a lambda is pending on the operator stack. The current code and tests preserve the intended lambda-merging behavior, keep the parser-backtracking guard behavior for bare one-argument substring/position forms, and I did not find unresolved correctness, safety, or metadata issues.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 11, 2026
…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
@groeneai

Copy link
Copy Markdown
Collaborator Author

Updated approach: revert parseLambda change, fix the round-trip at the right layer

After the previous commit landed, CI reported 4 Fast test regressions (02476_fix_lambda_parsing, 02418_aggregate_combinators, 02718_array_fold, 01144_multiple_joins_rewriter_v2_and_lambdas). I had over-rotated: removing the merging in parseLambda broke the documented f(a, b, c -> body) ≡ f((a, b, c) -> body) syntactic sugar that higher-order functions rely on (mapApply(k, v -> ..., x), arrayFold(acc, x -> ..., arr, init), arrayMap(x, y -> ..., a, b)).

Root-cause refined

The actual round-trip failure is not in parseLambda. The merging is intentional and well-established. The failure is in SubstringLayer (and PositionLayer by the same pattern):

  1. substring(x, + '\u0060' + x + '\u0060' + -> + '\u0060' + x + '\u0060' + ) parses (via the merging) to substring(lambda(tuple(x, x), x)) — a 1-argument call.
  2. The formatter emits SELECT substring((x, x) -> x) faithfully.
  3. Re-parsing that string fails: SubstringLayer::parse at state 0 has no handler for ), so the 1-argument form is rejected with SYNTAX_ERROR.
  4. The round-trip check in executeQueryImpl raises Inconsistent AST formatting LOGICAL_ERROR and aborts the server.

Fix

  • Reverted the change in Layer::parseLambda step 3 — merging is preserved.
  • Added a state-0 ) handler to both SubstringLayer and PositionLayer. The 1-argument form now parses to a 1-argument call; the analyzer then rejects it with a meaningful error:
    • Original reproducer SELECT substring(x, + '\u0060' + x + '\u0060' + -> + '\u0060' + x + '\u0060' + ) → BAD_ARGUMENTS ("Lambda multiple arguments with same name x")
    • SELECT substring(s, x -> x) → ILLEGAL_TYPE_OF_ARGUMENT ("Function substring can't have lambda-expressions as arguments")
    • SELECT substring('abc') → NUMBER_OF_ARGUMENTS_DOESNT_MATCH
  • I checked the other special-cased layers (ExtractLayer, OverlayLayer, CastLayer, TrimLayer, DateAddLayer, DateDiffLayer). Either they delegate to LayerWithSeparator (which already accepts the one-arg form) or they reject the malformed input earlier and never reach the round-trip check. No other layers need changing.

Pre-PR validation gate

  1. Deterministic repro? Yes — SELECT substring(x, + '\u0060' + x + '\u0060' + -> + '\u0060' + x + '\u0060' + ) aborts the server reproducibly before the fix; with the fix it reproducibly returns BAD_ARGUMENTS.
  2. Root cause explained? Yes — see above.
  3. Fix matches root cause? Yes — the round-trip invariant is restored at exactly the two layers where it was broken; the merging sugar (the path that produces the 1-argument call) is unchanged.
  4. Test intent preserved? Yes — 02476_fix_lambda_parsing (the regression test for the merging) and the four originally-failing tests pass again. New test 04227_inconsistent_ast_function_lambda_after_comma_104605 covers the issue.
  5. Demonstrated in both directions? Yes — the original reproducer aborts without the fix and returns a sensible error with it; new test passes 50/50 with --test-runs 50 under full setting randomization; the 4 originally-failing CI tests now all pass locally.
  6. General, not narrow? Reviewed all other special layers for the same round-trip bug class; only SubstringLayer and PositionLayer are affected.

Branch updated: commit 6c169537369. Re-running CI.

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
@groeneai

Copy link
Copy Markdown
Collaborator Author

Third revision — commit 587a3c23a7a narrows the state-0 closing-bracket handler.

Why a third revision

The previous commit (6c169537) accepted ) unconditionally at state 0 in SubstringLayer / PositionLayer. That regressed 02154_parser_backtracking lines 23-25, which depend on position(x), position(x y), position(x IN y) (where each outer call collapses to a one-arg shape) failing at parse time with SYNTAX_ERROR to prevent exponential parser backtracking. Under the permissive handler those parsed successfully and only failed later with UNKNOWN_IDENTIFIER -> grep -cF 'Syntax error' returned 0 instead of 1.

The narrow fix

Gate the state-0 ) handler on previousType() == OperatorType::Lambda. The handler is only needed when the parser has just collapsed f(a, b, c -> body) into f(lambda(tuple(a, b, c), body)) via the documented merging sugar — at that point a lambda operator is pending on the operator stack. Bare one-argument calls like substring(x) or position(x) have no pending operator and continue to fail at parse time as before.

else if (previousType() == OperatorType::Lambda
    && ParserToken(TokenType::ClosingRoundBracket).ignore(pos, expected))
{
    if (!mergeElement())
        return false;
    finished = true;
}

Pre-PR validation gate

a. Deterministic repro? Yes — 02154_parser_backtracking reproduces the regression on commit 6c169537 (line 23 returns 0, expected 1). With 587a3c23a7a it returns 1.
b. Root cause explained? Yes — the state-0 handler was accepting ) for ANY one-argument form, including bare position(x) calls that 02154 deliberately tests for parse-time rejection. Narrowing to "only when a lambda is pending" matches the actual case that needs round-trip support.
c. Fix matches root cause? Yes — checks the exact pre-condition (OperatorType::Lambda on the operator stack) that produces the merged-tuple-lambda AST shape requiring the one-argument round-trip.
d. Test intent preserved? / new tests? 02154_parser_backtracking now passes; 04227_inconsistent_ast_function_lambda_after_comma_104605 still covers the round-trip path; the two bare-one-argument assertions were removed because (i) the test runner aborts a multi-query batch on the first SYNTAX_ERROR so they couldn't be expressed this way, and (ii) 02154 already exercises that parse-time rejection at depth 100. An explanatory comment was added.
e. Demonstrated in both directions? Yes — fails on 6c169537 (lines 23-25 return 0); passes on 587a3c23a7a (all 14 lines return 1).
f. Fix general, not narrow patch? The narrow scope is correct: only SubstringLayer and PositionLayer are the special-cased layers with strict argument counts that reject the one-arg form. Other layers (ExtractLayer, OverlayLayer, CastLayer, TrimLayer, DateAddLayer, DateDiffLayer) either round-trip cleanly already or reject malformed input before the round-trip check — verified in the second commit. Generic functions parsed via FunctionLayer accept any arity, so they don't have this issue.

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(duplicate lambda parameter names), notLOGICAL_ERROR`.
  • SELECT substring(x) / SELECT position(x) -> SYNTAX_ERROR, as on master.
  • Higher-order function sugar (arrayMap(x -> x + 1, [1,2,3]), arrayFold(acc, x -> acc + x, [1,2,3], 0::Int64), mapApply(k, v -> (k, v * 2), map(1, 10, 2, 20))) unchanged.

cc @evillique @alexey-milovidov @george-larionov

session: cron:clickhouse-ci-task-worker:20260512-001500

Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Revision 4 (commit 4e02a695555) — addresses bot review at #104626 (comment)

Replaces the state-0 ) handler's previousType() == OperatorType::Lambda check in SubstringLayer and PositionLayer with a hasPendingOperator(OperatorType::Lambda) helper that scans the entire operators stack. The bot was right: for a non-trivial lambda body (e.g. x -> x + 1) the operators stack at the closing bracket is [..., Lambda, Plus], the top is Plus, and the previous top-only check was skipping a legitimate one-argument-with-merged-tuple-lambda close.

Pre-PR validation gate

(a) Deterministic repro?
Yes — before this commit, SELECT substring((s, x) -> x + 1) fails with SYNTAX_ERROR at parse position 33 on commit 587a3c23a7a; with the fix it parses and the analyzer rejects with ILLEGAL_TYPE_OF_ARGUMENT. Same for position, same for the 3-arg merging variant substring(a, b, x -> x AND y).

(b) Root cause explained?
The parser pushes Lambda (priority 1) when it sees ->, then pushes higher-priority binary operators (Plus priority 11, And etc.) on top while parsing the body — never popping Lambda because they all have priority higher than 1. So at the outer function call's ), the operators stack is [..., Lambda, Plus] with Plus on top. previousType() returns the stack top, which is Plus, so the state-0 ) branch was skipped and the parser fell through to tryParseOperator, which can't consume ), so the parse failed.

(c) Fix matches root cause?
Yes — hasPendingOperator(OperatorType::Lambda) walks the entire vector. mergeElement invoked when we accept the ) already drains operators in priority order (Plus first → Plus(x, 1), then Lambda → Lambda(tuple(s, x), Plus(x, 1))), so the resulting AST is the correct ASTFunction("lambda", [tuple, body]) regardless of body shape. No band-aid.

(d) Test intent preserved?
Yes — the same gating that protects 02154_parser_backtracking against exponential backtracking still holds: bare substring(x) / position(x) has empty operators (no lambda anywhere), so the branch is still skipped and the call falls through to the existing parse-time SYNTAX_ERROR. The 02154 reference (lines 23–25, deeply-nested position(x), position(x y), position(x IN y) must produce Syntax error) is unchanged.

(e) Both directions demonstrated?
Yes — on commit 587a3c23a7a (pre-fix), substring((s, x) -> x + 1) and position((h, x) -> x + 1) fail with SYNTAX_ERROR at the body's closing ); on commit 4e02a695555 (with fix) they parse and reach the analyzer with ILLEGAL_TYPE_OF_ARGUMENT. New test cases in 04227_inconsistent_ast_function_lambda_after_comma_104605 cover both formatQuery round-trip and direct merged-tuple form.

(f) Fix is general, not a narrow patch?
Yes — the same fix is applied to SubstringLayer and PositionLayer, the two special layers that have a state-0 ) handler with a "is lambda pending?" gate. Other special layers in the same file (OverlayLayer, ExtractLayer, CastLayer, TrimLayer, DateAddLayer, DateDiffLayer) either have no state-0 ) branch (they reject malformed input before any round-trip) or do not allow lambdas in the relevant positions; they were re-checked when adding the original gate in commit 6c169537369. The helper is added once on Layer so any future state-0 close-bracket handler can use it cleanly.

Local verification (commit 4e02a695555)

  • 04227_inconsistent_ast_function_lambda_after_comma_104605: 50/50 with full setting randomization
  • 02154_parser_backtracking, 02476_fix_lambda_parsing: 30/30 randomized
  • 02418_aggregate_combinators, 02718_array_fold, 01144_multiple_joins_rewriter_v2_and_lambdas: PASS
  • Broader lambda/AST suite: 02343_analyzer_lambdas, 02343_analyzer_lambdas_issue_28083, 02343_analyzer_lambdas_issue_36677, 01960_lambda_precedence, 02128_apply_lambda_parsing, 03168_inconsistent_ast_formatting, 03761_inconsistent_ast_formatting, 02882_formatQuery — all PASS
  • Bare substring(x) / position(x): still SYNTAX_ERROR at parse time (verified on 4e02a695555 binary)
  • Original repro SELECT substring(x, x->x): no LOGICAL_ERROR, fails with BAD_ARGUMENTS from the duplicate-name lambda check

Higher-order functions arrayMap, arrayFold, arrayFilter, mapApply still parse and execute correctly (covered by the existing tail of 04227).

cc @evillique @alexey-milovidov @george-larionov

Session: cron:clickhouse-ci-task-worker:20260512-011500

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai the test 04227_inconsistent_ast_function_lambda_after_comma_104605 failed

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@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 04227 is SELECT substring(x, \x` -> `x`)`. The two analyzers reject it via different paths, so the error code differs:

analyzer code message
enable_analyzer=1 (default) 36 BAD_ARGUMENTS Lambda (x, x) -> x multiple arguments with same name x
enable_analyzer=0 (old) 43 ILLEGAL_TYPE_OF_ARGUMENT Function substring can't have lambda-expressions as arguments: While processing substring((x, x) -> x)

Both are correct outcomes — the new analyzer resolves the lambda first and trips on duplicate parameter names; the old analyzer rejects substring having a lambda argument before resolving the lambda itself, so the duplicate-name check never fires. The test only cares that the server does not abort with LOGICAL_ERROR (the original "Inconsistent AST formatting" bug), so I changed the expectation to accept either code:

SELECT substring(x, `x` -> `x`); -- { serverError BAD_ARGUMENTS, ILLEGAL_TYPE_OF_ARGUMENT }

CIDB confirmed reproducibility: 3/3 reruns of 04227 failed on Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel) with Expected server error code: 36 but got: 43. The other failing checks (test_short_disconnection_doesnt_stop_restore KEEPER_EXCEPTION, Finish Workflow log-export warning) are unrelated infrastructure noise.

Local verification on 4e02a69 binary:

  • enable_analyzer=1: BAD_ARGUMENTS as expected
  • enable_analyzer=0: ILLEGAL_TYPE_OF_ARGUMENT as expected
  • 04227: 50/50 with full setting randomization, default analyzer
  • 04227: 50/50 with full setting randomization, --client-option enable_analyzer=0
  • 02154 parser-backtracking protections still fire under enable_analyzer=0: bare substring(x), position(x), and 14-deep nested position(...) all SYNTAX_ERROR as before
  • All other queries in 04227 return the same code (43) on both analyzers — only the duplicate-param-name reproducer needed the multi-code expectation

Pre-PR validation gate:

  • (a) Deterministic repro: clickhouse-client --enable_analyzer 0 -q 'SELECT substring(x, \x` -> `x`)'` returns code 43 every time
  • (b) Root cause: analyzer dispatch ordering. Old analyzer's argument-type check fires before lambda resolution; new analyzer's lambda binder fires before argument-type check
  • (c) Fix matches root cause: accept both legitimate error codes; not a band-aid since both are real semantic errors for this input
  • (d) Test intent preserved: still catches the original LOGICAL_ERROR (code 49 — not in the allowed list, would still fail); still catches any new crash class; round-trip invariants on all other queries unchanged
  • (e) Both directions: CI showed FAILS without fix (3/3 reruns code 36 ≠ 43); local shows PASSES with fix (50/50 on both analyzers)
  • (f) Fix is general: covers ALL analyzer-dispatch paths for this input — no narrow patching

Parser change in this PR is unchanged. cc @evillique @alexey-milovidov @george-larionov

Session: cron:clickhouse-ci-task-worker:20260512-081500

@clickhouse-gh

clickhouse-gh Bot commented May 12, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.00% -0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 91.30% (21/23) | lost baseline coverage: 2 line(s) · Uncovered code

Full report · Diff report

@PedroTadim
PedroTadim enabled auto-merge May 13, 2026 13:46
@PedroTadim
PedroTadim added this pull request to the merge queue May 13, 2026
Merged via the queue into ClickHouse:master with commit 4b7ab82 May 13, 2026
163 of 165 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 13, 2026
niyue pushed a commit to niyue/ClickHouse that referenced this pull request May 31, 2026
…_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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

More inconsistent AST formatting

4 participants