Skip to content

Fix Inconsistent AST formatting for APPLY with a matcher-valued lambda body - #114205

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-apply-matcher-lambda-paren-round-trip
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-apply-matcher-lambda-paren-round-trip

Conversation

@groeneai

@groeneai groeneai commented Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed the formatting of an APPLY column transformer whose lambda body is a matcher and which is followed by another transformer, as in SELECT * APPLY (x -> COLUMNS('a')) APPLY toString. The parentheses around the lambda were dropped, so formatQuery returned text that parses back as a different query (the following transformer was absorbed into the lambda body), and in debug builds the query hit the Inconsistent AST formatting LOGICAL_ERROR. Those parentheses are now always printed.

Description

SELECT * APPLY (x -> COLUMNS('a')) APPLY toString FROM (SELECT 1 AS a) aborts the server in
debug builds, and in a release build formatQuery on it returns text that parses back as a
different query. Pre-existing on master, both analyzers, plain SQL with no settings. Found by
AST fuzzer (amd_debug):
CI report,
STID 1941-1bfa. Related: #100576.

Root cause: ASTColumnsApplyTransformer::formatImpl printed the lambda bare, opening ( only
when column_name_prefix was set, so the user's parentheses were dropped:

in : SELECT * APPLY (x -> COLUMNS('a')) APPLY toString FROM t
out: SELECT * APPLY x -> COLUMNS('a') APPLY toString FROM t

On re-parse ParserColumnsTransformers sees no (, so it hands the tail to ParserExpression,
and because the lambda body is itself a matcher the matcher grammar absorbs the following
APPLY toString into it. Two ColumnsApplyTransformer children collapse into one. The formatted
text is idempotent, so only the AST differs.

The fix prints those parentheses unconditionally: they are the transformer grammar's own
delimiter, which is why the sibling column_name_prefix branch has always emitted them and that
spelling never aborted. Since they now delimit the lambda, ASTFunction's own parenthesis for a
lambda at a list position is suppressed, so the output carries exactly one pair. The
function-name forms are byte-identical, and appendColumnName is untouched so result column
names do not shift.

Validated on two debug builds: without the change the reproducer gives rc=134 and the new test
fails; with it the query runs and the test passes. Across a 444-query sweep on both analyzers,
192 round-trip aborts drop to 0 and no query that already worked changes its result or error code.

Not fixed here: with the legacy analyzer, APPLY (x -> <matcher>, 'prefix') still fails with
Can't set alias from applyColumnsTransformer, a separate pre-existing defect.

Validation detail
probe without the fix with the fix
reproducer rc=134, Inconsistent AST formatting rc=0, returns 1
new test 04846 (analyzer 1 / 0) fails / fails passes / passes
18-cell carrier matrix (6 matcher bodies x 3 following transformers) 18 abort 0 abort
444-query sweep, both analyzers 192 round-trip aborts 0
non-aborting queries in that sweep - 0 output changes, 0 error-code changes
APPLY toString / APPLY sum / APPLY quantile(0.5) / APPLY (toString, 'p_') - byte-identical output
result column names, 6 queries x 2 analyzers, incl. the prefix form - byte-identical
04846, 50 randomized runs; and 50 more with enable_analyzer=0 - 50/50 and 50/50
inconsistent_ast (8), ast_json (49), columns_transformer, columns_matcher, analyzer_projection_names - all pass

Four .reference files shift by one line each, all of them formatter output of an APPLY
lambda: 01470_columns_transformers2, 04320_ast_json_review_hardening,
04339_ast_json_review_followup_hardening, 04344_ast_json_select_child_typing.


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

…a body

SELECT * APPLY (x -> COLUMNS('a')) APPLY toString FROM (SELECT 1 AS a)
aborted the server in debug builds with the Inconsistent AST formatting
logical error, on both analyzers, from plain SQL with no settings. Found
by AST fuzzer (amd_debug), STID 1941-1bfa.

ASTColumnsApplyTransformer::formatImpl printed the lambda bare, opening
'(' only when column_name_prefix was set, so the parentheses the user
wrote were dropped:

  in : SELECT * APPLY (x -> COLUMNS('a')) APPLY toString FROM t
  out: SELECT * APPLY x -> COLUMNS('a') APPLY toString FROM t

On re-parse ParserColumnsTransformers sees no '(', leaves
with_open_round_bracket false and hands the tail to ParserExpression.
Because the lambda body is itself a matcher, the matcher grammar absorbs
the following APPLY toString into the lambda body rather than leaving it
as the next sibling transformer. Two ColumnsApplyTransformer children
collapse into one, the tree hash differs, and the round-trip check in
executeQuery aborts. The formatted text is idempotent, so only the AST
comparison catches this.

Print those parentheses unconditionally. They are the transformer
grammar's own delimiter, which is why the sibling column_name_prefix
branch has always emitted them and why that spelling never aborted.
A type-narrowed variant that parenthesizes only matcher-valued bodies
was rejected: it would have to enumerate every current and future
matcher node, and unconditional parentheses always re-parse.
Changing the parser to stop before a following transformer keyword was
also rejected, since it would alter the accepted language and
reinterpret already-persisted view definitions.

Formatted output changes only for APPLY <lambda>. The function-name
forms (APPLY toString, APPLY sum, APPLY quantile(0.5)) and both
column_name_prefix forms stay byte-identical, and appendColumnName is
untouched so result column names do not shift.

Validated on two debug builds: without the change the reproducer gives
rc=134 and the new test fails on both analyzers; with it the query runs
and the test passes. A 444-query sweep over matcher body kinds,
following-transformer kinds and prefix variants goes from 192 round-trip
aborts to 0, with no output or error-code change for any query that
already worked. Four existing reference files shift by one line each,
all of them formatter output of an APPLY lambda.

Remaining known gap, out of scope here: with the legacy analyzer,
APPLY (x -> <matcher>, 'prefix') still fails on Can't set alias, raised
by applyColumnsTransformer calling setAlias on a matcher node. That is a
separate pre-existing defect, unchanged by this commit and reproducible
on pristine master.
The previous commit made ASTColumnsApplyTransformer::formatImpl emit the
lambda's parentheses but forwarded the format frame unchanged, so
ASTFunction added its own pair on top:

  in : SELECT id, t.* APPLY x -> toString(x) FROM t
  out: SELECT id, t.* APPLY ((x -> toString(x))) FROM t

ASTFunction's lambda branch brackets a lambda when need_parens is set or
when list_element_index > 0, and nothing between ASTExpressionList and
the transformer clears either flag. On master formatImpl emitted no
bracket of its own, so that pair was the only one and the output was
correct; with the new bracket it became redundant. Reset both flags for
the lambda's frame, mirroring what decideParensEmission does in
IAST.cpp when it takes over paren emission from a nested node.
current_function is deliberately left alone: ASTFunction uses it to
decide whether a nested IN needs isolating parentheses inside an
argument list, which the transformer's brackets do not provide.

This also drops one redundant pair from APPLY (<lambda>, 'prefix') at a
select-list position > 0, which master already printed as
APPLY ((x -> f(x)), 'prefix') from the same ASTFunction branch. It
corrects the previous commit's claim that both column_name_prefix forms
stay byte-identical: the index-0 form does, the later-position form now
loses the redundant pair. Both re-parse to the same AST before and
after, and result column names are unchanged in either position.

04846 gains a select-list-index > 0 carrier and an arrayMap-nested
carrier, and its round-trip assertions now compare the parsed AST via
parseQueryToJSON instead of comparing formatted text to itself. Text
idempotence held before the fix as well, so those assertions could not
have detected the original defect; six of the nine AST assertions return
0 on the pre-fix binary. The internal check the test mirrors likewise
compares the tree hash before it reaches any string comparison.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 7 findings adjudicated)

This PR went through an independent cold review plus a second-model gate over two rounds before
being opened. Round 1 found two substantive gaps and sent the change back; round 2 returned
0 gate findings. Verdicts below; the ones marked fixed are already in the diff.

# Finding Severity Verdict
❌ The new ( was emitted with the format frame forwarded unchanged, so ASTFunction added its own pair on top for a lambda at a select-list position > 0 or inside another lambda: APPLY ((x -> toString(x))). Not an abort, but a formatting regression on shapes that were correct before. major AGREE, fixed
❌ 7 of the test's round-trip assertions compared format(q) with format(format(q)). The pre-fix text is idempotent, so they could not have detected the defect; and the internal check compares the tree hash (executeQuery.cpp:1380) before it reaches any string comparison (:1393). major AGREE, fixed — replaced with 9 parseQueryToJSON(q) = parseQueryToJSON(formatQuerySingleLine(q)) assertions, 6 of which return 0 on the pre-fix binary
⚠️ func_name is emitted without backQuoteIfNeed and column_name_prefix without escaping, so a quoted UDF name or a prefix containing ' formats to text that does not re-parse. blocker DISAGREE — real, but pre-existing and byte-identical to the base: git show <base>:src/Parsers/ASTColumnsTransformers.cpp lines 30-57 already emit both raw. The only edit on the prefix path moves its ) into the shared tail, and with_round_brackets is unconditionally true when the prefix is non-empty, so both prefix spellings format identically to before. It is also a different mechanism from the dropped lambda delimiter this PR fixes, so folding it in would break the one-concern rule. Noted, not blocking.
💡 Changelog category is Bug Fix (... official stable release) but the entry described only the debug-build LOGICAL_ERROR, which is #ifndef NDEBUG (executeQuery.cpp:1326). nit AGREE, fixed — the entry now leads with the release-build symptom: formatQuery returned text that parses back as a different query.
💡 The Can't set alias residual was in the commit message but not the PR body. nit AGREE, fixed
💡 In function-call form (EXPLAIN SYNTAX, allow_operators = false) the lambda already prints as lambda(tuple(x), body), which is self-delimiting, so the new bracket is redundant there. nit DISAGREE — cosmetic. That spelling re-parses to the same tree and formats back to itself; the parenthesized flag is not part of the tree hash. Narrowing the condition adds a branch for no correctness gain.
💡 A user's explicit inner parentheses are preserved rather than canonicalized: APPLY ((x -> f(x))) keeps both pairs. nit DISAGREE — deliberate. The re-parse marks the lambda parenthesized, decideParensEmission then emits exactly one flag paren under the transformer's own, so the output is stable under re-format and the tree is unchanged.

Also verified independently while reviewing, none of it a finding: the reference-churn set is
complete (an independent scan of every *.reference for APPLY-lambda text finds 6 files; 4 are
churned, the 5th is the new test, the 6th is 02378_analyzer_projection_names whose APPLY text
is echoed input and correctly unchanged); test number 04846 is free on master, in open PRs of
any author, and across live worktrees; the parenthesized spelling has been accepted by the parser
since 2020 so persisted definitions stay readable both ways; ProjectionsDescription/
ReplicatedMergeTreeTableMetadata compare projections after parse-then-format on the local
binary, so a formatter change cannot make the strict metadata check disagree; no
SettingsChangesHistory entry applies; and the added source comments are 4 lines against 9 lines
of code, each stating a standing grammar or frame invariant.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * APPLY (x -> COLUMNS('a')) APPLY toString FROM (SELECT 1 AS a) gives rc=134 on every run of a debug build. No settings, no DDL, no randomization needed.
b Root cause explained? Yes. ASTColumnsApplyTransformer::formatImpl printed the lambda bare, opening ( only for the column_name_prefix case, so the user's parentheses were dropped. On re-parse ParserColumnsTransformers finds no (, leaves with_open_round_bracket false and hands the tail to ParserExpression; since the lambda body is itself a matcher, the matcher grammar absorbs the following APPLY toString into it. Two ColumnsApplyTransformer children collapse into one, the tree hash differs, and the round-trip check in executeQuery aborts.
c Fix matches root cause? Yes. The parentheses are the transformer grammar's own delimiter, so the formatter is fixed at the single point where the information was lost. Not a guard at the assertion site, not an assertion suppression, and not a parser change (a non-greedy parser would alter the accepted language and reinterpret existing queries).
d Test intent preserved / new tests added? Yes. New stateless test 04846_inconsistent_ast_apply_matcher_lambda_paren_round_trip covers all 18 carriers, format-then-parse AST equality, over-reach guards and result column names. Parallel-safe, no no-parallel tag. Every assertion is proven able to redden: the AST round-trip assertions return 0 on the pre-fix binary (6 of 9) and the concrete-text assertions change on a mutation arm that emits the parentheses without resetting the format frame (6 of 22). The four .reference edits are one-line formatter-output updates; before replacing each file I asserted the pre-fix output equalled the committed reference, so no assertion was weakened and no test was removed.
e Both directions demonstrated? Yes, on two Build-ID-verified debug binaries. Without the fix: reproducer rc=134, Inconsistent AST formatting in the log, and the new test differs from its reference on both analyzers. With the fix: rc=0, and the test matches on both analyzers.
f Fix is general across code paths? Yes. formatImpl is the single carrier of this invariant; the sibling EXCEPT, REPLACE and ColumnsTransformerList formatters emit no lambda (verified by grep on the modified file). The paren-emission chain was traced end to end, and both format-frame flags that ASTFunction reads before adding its own parenthesis for a lambda are reset, so the output carries exactly one pair wherever the transformer sits (select-list index 0 or later, and nested inside another lambda). appendColumnName, writeJSON/readJSON and updateTreeHashImpl are separate contracts and are deliberately untouched, with result column names asserted unchanged in the test so a regression there would redden.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 6 matcher body kinds (regexp matcher, column-list matcher, *, t.*, qualified matcher, nested matcher plus transformer) against 9 following-transformer kinds including STRICT variants, on both analyzers: a 444-query sweep goes from 192 round-trip aborts to 0, with 0 output changes and 0 error-code changes among the queries that already worked. Non-matcher lambda bodies and all four non-lambda APPLY shapes are covered as guards.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or default changed, so no SettingsChangesHistory.cpp entry applies. No serialization-format change: this is SQL text only, and the AST JSON path is untouched. The parser already accepted the parenthesized form, so no query that parses today stops parsing. Known bounded limitation: view metadata written before this change keeps the ambiguous text, and such a view cannot be created today because CREATE VIEW with that spelling already fails at creation time.
i Invariants and contracts preserved? Yes. The invariant is that the formatted form of an APPLY <lambda> transformer re-parses to an equal tree; it now holds for all 444 swept queries. formatImpl has no early return and no error path. The column_name_prefix branch output is byte-identical, result column names are byte-identical across both analyzers, and every changed form is idempotent under re-format.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique @george-larionov, could you review this? The APPLY transformer's formatter dropped the parentheses around a lambda, so with a matcher-valued body the following transformer was absorbed into the lambda on re-parse and one ColumnsApplyTransformer child was lost; the parentheses are now always printed, and ASTFunction's own pair for a lambda at a list position is suppressed so the output carries exactly one.

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

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8f1849b]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Can't set alias 'A' of B (STID: 1493-3091) FAIL cidb
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Can't set alias 'A' of B (STID: 1493-3091) FAIL cidb

AI Review

Summary

This PR fixes ASTColumnsApplyTransformer::formatImpl so APPLY lambdas are always delimited by the transformer’s own parentheses, and it resets the formatter frame that previously made ASTFunction add a second pair in list-position and nested-lambda carriers. The current diff matches the described root cause, the regression test exercises the failing matcher-valued carriers plus the duplicate-parentheses follow-up, and I did not find a remaining correctness, compatibility, or metadata issue that needs a review comment.

Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 13/13 (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 Aug 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8f1849b9a with master c26092991 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 702.05 MiB 699.03 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

7 translation units recompiled, 8 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7a6387f

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

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Logical error: Can't set alias 'A' of B (STID 1493-3091) trunk bug, reproduces on pristine master #109223 (ours, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / same STID 1493-3091 same defect, second flavour #109223 (ours, open)
Stress test (amd_tsan) / Hung check failed, possible deadlock found trunk bug: a cancelled DROP TABLE of a TimeSeries table never returns, teardown convoys behind the DDL guard a fix task owns this line and is in progress at full effort (fixing-PR link to follow on this PR)
Stress test (arm_asan_ubsan, s3) / Sanitizer (STID 2064-22d0) trunk bug: LeakSanitizer indirect leaks from a materialized-CTE reference cycle #113397 (external, open)

Two rows are easy to misattribute, so the evidence is spelled out.

The AST fuzzer rows are NOT caused by this PR, even though this PR edits
ASTColumnsTransformers.cpp and the failing query is an APPLY transformer query. I minimized the
fuzzer query to EXPLAIN AST optimize = 1 SELECT * APPLY (x -> COLUMNS('a'), 'f_') APPLY toString FROM (SELECT 1 AS a) AS t and ran it on two independent pre-fix binaries: the pristine master debug
snapshot at 604017b70059 aborts (exit 134, Logical error: 'Can't set alias 'f_a' of COLUMNS('a')'),
and the official master release build 26.8.1.1152 returns
Code: 49 ... Can't set alias 'f_a' of COLUMNS('a') ... (LOGICAL_ERROR). A positive control
(EXPLAIN AST SELECT 1) printed a normal AST on both, so the probe was live. The defect is that
applyColumnsApplyTransformer calls setAlias on the transformer result, and an APPLY lambda body
that expands to a COLUMNS matcher is not an ASTWithAlias. My open #109223 adds the
setTransformerAlias guard on exactly that call site; verified on that PR's own amd_debug build,
where the same query returns Code: 36 ... which does not support aliases (BAD_ARGUMENTS) instead of
aborting. This PR only changes how the transformer is FORMATTED, which is why the fuzzer reaches the
pre-existing abort more often here. STID 1493-3091 is 2 rows / 1 PR / 0 master in 30 days, so the
sibling STIDs of the same family (1493-3ccb on 6 unrelated PRs) are the breadth, not this hash.

The hung check is one specific trunk defect, not the umbrella. I parsed each hung_check.log
per Row N: block rather than reading the pooled frame list. On both this PR's amd_tsan arm and
the sibling arms, the root is the single longest-running query, DROP TABLE prometheus;, with
is_cancelled = 1 and frames DatabaseCatalog::waitTableFinallyDropped <-
waitForTableToBeActuallyDroppedOrDetached <- StorageTimeSeries::dropInnerTableIfAny; every other
hung row is a DROP DATABASE ... SYNC or DETACH DATABASE blocked in DatabaseCatalog::getDDLGuard
with strictly smaller elapsed, and the carrier is 04811_promql_topk_bottomk_limitk. Here that root
sat 974 s. The umbrella name Hung check failed, possible deadlock found is 942 rows / 512 PRs /
129 master across 13 flavours in 30 days and pools many unrelated defects, so it is not this
sub-signature's breadth; test_context_raw is truncated for this signature, so breadth has to come
from the artifacts. The fix task owning this row has the mechanism proven at frame level and is being
worked now.

Session id: cron:our-pr-ci-monitor:20260811-033000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the hung DROP TABLE of a TimeSeries table (waitTableFinallyDropped): #114302 (external, open).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 858f642

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

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Logical error: Can't set alias 'A' of B (STID 1493-3091) pre-existing trunk defect in the APPLY column transformer, newly reachable because this branch fixes the earlier round-trip abort that used to end the query first fixing PR #109223 (ours, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / same STID 1493-3091 same defect, different fuzzed spelling fixing PR #109223 (ours, open)
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) / 04676_adaptive_aggregation_replicated_argument flaky: reference diff on the seal normalization assertion lines; the in-job diagnosis reran it 40 times and 2 failed fixing PR #115204 (ours, open)
Stateless tests (amd_tsan, parallel) / 04676_adaptive_aggregation_replicated_argument flaky: same test, same reference diff; 6 reruns all passed fixing PR #115204 (ours, open)

Notes for readers:

Session id: cron:our-pr-ci-monitor:20260818-000000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8f1849b

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

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Can't set alias 'f_dummy' of COLUMNS('a') (STID 1493-3091) pre-existing trunk defect, newly reachable: the alias throw at IAST.h:147 via applyColumnsTransformer.cpp:82 reproduces on pristine master, and on the base the same spelling died earlier inside the Inconsistent AST formatting abort that this PR removes #109223 (ours, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / Can't set alias 'f_257' of COLUMNS('a') (STID 1493-3091) same defect, same STID #109223 (ours, open)
Sync - CH Inc sync (private, not actionable)

The two 04676_adaptive_aggregation_replicated_argument rows owned on the previous head are no
longer present at this head: both lanes pass, and the string does not appear anywhere in this
head's report.

Coverage: 177 leaves, 157 OK, 18 skipped each with a genuine reason, 0 dropped, both aggregators
green.

Session id: cron:our-pr-ci-monitor:20260818-210000

This branch has not been deployed

No deployments
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-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants