Skip to content

Do not share a join-tree table expression with an IN argument - #112219

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-99931-in-argument-shared-with-join-tree
Sep 6, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-99931-in-argument-shared-with-join-tree

Conversation

@groeneai

@groeneai groeneai commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #99931
Related: #107603

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):

Fixes a LOGICAL_ERROR (Column identifier ... is already registered), a
MULTIPLE_EXPRESSIONS_FOR_ALIAS error and a NOT_FOUND_COLUMN_IN_BLOCK error for a query whose
IN / NOT IN / GLOBAL IN right operand names a table expression that also appears in the
FROM section, for example SELECT l.x FROM l JOIN (SELECT x FROM r) AS r ON l.x = r.x WHERE l.x IN r.
Also makes ORDER BY <alias> WITH FILL ... INTERPOLATE (<alias> ...) inside a CTE or any other
copied subquery raise INVALID_WITH_FILL_EXPRESSION, as the same query already does when it is not
copied: the check was silently skipped for the copy, and such a query returned rows instead of the
error.

Description

Root cause

When the right operand of an IN-family function is an identifier, resolveFunction allows it to be
resolved as a table expression (allow_table_expressions at
src/Analyzer/Resolve/resolveFunction.cpp:1199). The resolution at
src/Analyzer/Resolve/QueryAnalyzer.cpp:3137-3139 returns the join tree's own node pointer - the
alias path deliberately does not clone for a table-expression lookup
(tryResolveIdentifierFromAliases, :1173-1177), and the name / db.table paths return the
registered node directly. The block clones only for CTEs (:3153) and materialized CTEs (:3183), so
a plain subquery-with-alias, bare table alias or table function ends up as one shared node in two
places in the query tree
(visible as the same QUERY id twice in EXPLAIN QUERY TREE run_passes = 1).

The same invariant is already written down in the tree, for a neighbouring mechanism:
IdentifierResolveScope.h:260-265 explains why the identifier-resolve cache must hand out a copy of
any subquery-bearing tree, and names the three downstream stages that rewrite each instance
independently. That cache never sees a table expression - canCacheIdentifier rejects such a lookup
outright (IdentifierResolveScope.cpp:190-195, with the same reasoning spelled out in the comment
there) - but the same three stages break for the sharing this PR fixes:

stage symptom before this PR
createUniqueAliasesIfNecessary Logical error: 'Column identifier __table1.<col> is already registered' (PlannerContext.cpp:42 <- CollectTableExpressionData.cpp:164) - aborts the server on debug/sanitizer builds
GLOBAL IN external-table rewriting Code: 179 Duplicate aliases __table2 for table expressions in FROM section are not allowed
rewrite_in_to_join Code: 10 Columns [__table2.dummy] are not found in blocks [__table1.dummy], []

The second and third are reachable on release builds too, for queries that are legal SQL and that
ClickHouse answers correctly when the same subquery is spelled out instead of referenced by alias.

Fix

Clone the resolved node when it is a table expression (isTableExpressionNodeType) that is a member
of registered_table_expression_nodes in the current or any enclosing scope. This is the single
retrieval site both consuming paths reach, so one hunk fixes all three symptoms: the
rewrite_in_to_join path resolves the operand itself and then clears is_special_function_in
(resolveFunction.cpp:915/:923) before the regular IN block runs, so a clone placed inside that
block cannot help it. The detector is spelling-independent, so the alias, bare-name and db.table
spellings and the TABLE / TABLE_FUNCTION / QUERY / UNION node types are all covered.

The change is a strict extension of the two pre-existing cloning rules earlier in the same if
chain (plain CTE at :3153, materialized CTE at :3183) - rewriting any of the failing shapes to
use a CTE already makes every symptom disappear on master, because that path forces the clone.

The branch fires for every IN-family argument that names a join-tree table expression, which is a
superset of the failing shapes: a bare table alias on the right of IN (... JOIN r AS r ... WHERE x IN r) and an IN naming the LEFT table expression already work on master, because
createUniqueAliasesIfNecessary skips a plain TABLE argument (:120) and the left side does not
collide. Those now get a copy too. Both are kept as explicit controls in the test and are
byte-identical before and after. The cost is one clone() of an already-resolved table expression
per such argument at analysis time - the same cost the CTE spelling of the identical query already
pays on master.

Relationship to #107603

#107603 (also mine, still open) clones the same shared node inside the regular IN block of
resolveFunction.cpp, which covers the first symptom but not the rewrite_in_to_join path. This PR
supersedes that hunk
: its committed test
(04338_in_set_source_aliases_from_table.sql, 4 assertions, Logical error: 'No set is registered for key ...' before the fix) passes byte-identically against master + this change without its
resolveFunction.cpp hunk, and all four of its shapes are carried into the test added here so nothing
is lost if it is closed.

Its second hunk, SortNode::cloneImpl carrying column_name, is carried here as well, since master
still lacks it and this is now the branch that supersedes #107603. column_name is derived from the
original AST identifier rather than from a child node, so the base clone machinery does not reproduce
it, and dropping it does change a user-visible verdict.

PlannerSorting.cpp:173/:176 puts SortNode::column_name into SortColumnDescription::alias (the
identifier name, a) while SortColumnDescription::column_name gets
calculateActionNodeName(expression), which for a resolved column is the column identifier
(__table1.a). InterpolateDescription::result_columns_set is keyed on the identifier name
(Planner.cpp:1070, InterpolateDescription.cpp:27-34). So for
ORDER BY a WITH FILL ... INTERPOLATE (a AS a) inside a cloned subquery, the conflict check at
FillingTransform.cpp:259-270 finds a through alias and correctly raises
INVALID_WITH_FILL_EXPRESSION; with column_name dropped by the clone, alias is empty, the check
is skipped and the query returns rows instead. The column_name half of that pair only substitutes
for a constant ORDER BY expression, where the two names coincide.

This is reachable on master today through the existing CTE clone paths
(QueryAnalyzer.cpp:3153, :4170), so the fix also changes that case, and the test added here pins
both spellings. column_name is likewise printed by EXPLAIN QUERY TREE
(SortNode::dumpTreeImpl).

Whether to close #107603 is of course for a maintainer to decide.

Verification

Both directions were measured against a pristine origin/master binary built in the same run
(8780cd4022ebb73d... vs 9cdc70208d665069...), and each hunk was reverted individually to confirm it is
load-bearing. On the base binary the failure reproduces for WHERE, HAVING, ORDER BY, QUALIFY,
join ON, a comma join, inside a lambda, NOT IN, a numbers() table-function source, and with the
shared column typed Nullable, LowCardinality, LowCardinality(Nullable) or Array; all are
correct with the fix, and each is asserted against the row set the equivalent spelled-out subquery
returns rather than merely against "no crash". Ten control shapes (unshared IN (SELECT ...), the CTE
path, a Set-engine right operand, a union-subquery alias, tuple IN, the old analyzer, ...) are
byte-identical before and after.

The new test passes 50/50 under randomized settings. The targeted suites from the plan (every
stateless test using IN t<N> / GLOBAL IN t<N>, every test naming
allow_experimental_correlated_subqueries or GLOBAL IN, plus the sibling fixes' regression tests
and the PreparedSets alias-stability test - 282 tests) were run on both binaries with identical
failing sets; every failure in that set also fails on the pristine base binary and is caused by the
local sandbox lacking a second listener on 127.0.0.2 for the shard / distributed /
parallel-replicas tests.


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

Version info

  • Merged into: 26.9.1.858 (included in 26.9 and later)

groeneai and others added 3 commits July 27, 2026 18:48
When the right operand of an `IN`-family function is an identifier, `resolveFunction`
allows it to be resolved as a table expression, and that resolution returns the join
tree's own node pointer: the alias path deliberately does not clone for a
table-expression lookup, and the surrounding block clones only for CTEs and
materialized CTEs. A plain subquery-with-alias, bare table alias or table function
therefore ends up as one shared node in two places in the query tree.

`IdentifierResolveScope.h` already states the invariant this violates and names the
three stages that rewrite each `IN` argument instance independently. All three break:
`createUniqueAliasesIfNecessary` strips the shared node's alias and renumbers its inner
table, so the planner throws `Column identifier ... is already registered`; the
`GLOBAL IN` external-table rewrite collides on the generated `FROM` alias with
`MULTIPLE_EXPRESSIONS_FOR_ALIAS`; and `rewrite_in_to_join` produces
`NOT_FOUND_COLUMN_IN_BLOCK`. The latter two are reachable on release builds for queries
that are answered correctly when the same subquery is spelled out instead of referenced
by alias.

Clone the resolved node when it is a table expression that is registered in the join
tree of the current or an enclosing scope. This is the single retrieval site both
consuming paths reach - the `rewrite_in_to_join` path resolves the operand itself and
clears `is_special_function_in` before the regular `IN` block runs - so one change
covers all three symptoms, and the detector is independent of how the table expression
is spelled.

`SortNode::cloneImpl` is fixed to carry `column_name`, which is derived from the
original AST identifier rather than from a child node and so is not reproduced by the
base clone machinery. It is read by the planner and printed by `EXPLAIN`, and this
change routes more nodes through cloning.

This supersedes the narrower clone in ClickHouse#107603, whose committed test passes against this
change without its own hunk; its shapes are carried into the test added here.
Review round 1 on the test file only; no source change.

Add the no-old-analyzer tag. The file names the IN right operand as a bare
table-expression identifier and uses QUALIFY, neither of which exists in the
old analyzer, and its own enable_analyzer = 0 control asserts UNKNOWN_TABLE.
Without the tag the file failed deterministically on the old-analyzer lanes.
Those lanes call force_ok_exit, so the red would not have blocked a merge and
nobody would have been paged for it.

Pin SortNode::cloneImpl carrying column_name. The planner puts column_name
into SortColumnDescription::alias, and that is the name FillingTransform
matches against the INTERPOLATE outputs; column_name holds the column
identifier instead, so it cannot substitute for it. Every spelling of
ORDER BY <ident> WITH FILL ... INTERPOLATE (<same ident> AS ...) that does not
go through a clone already raises INVALID_WITH_FILL_EXPRESSION, so a clone that
drops column_name silently loses a legitimate check. The new group asserts the
uncloned spelling, the CTE clone and the IN-argument clone, keeps a control
interpolating a different column, and pins column_name a second way through
EXPLAIN QUERY TREE. Reverting the SortNode hunk fails the file on the CTE
assertion and flips the EXPLAIN check.

Split the GLOBAL IN group into its three identifier spellings. The group was
labelled "bare table name" but declared an alias and used it, so only the alias
path (tryResolveIdentifierFromAliases) was covered. The bare one-part and
two-part db.table spellings resolve through tryResolveIdentifierFromTableExpression
instead, and the PR's generality claim rests on that independence. All three
abort with Code 179 on the base and return the correct rows with the fix.

Co-Authored-By: Claude Fable 5 <[email protected]>
The stress runner appends ignore_drop_queries_probability=0.2 as a
client option to every statement of every non-upgrade thread
(ci/jobs/scripts/stress/stress.py), including the odd threads that
share one database across the whole suite (--database=test_{i}).

When the roll fires, InterpreterDropQuery reports success without
dropping a disk-backed table, so the test's own cleanup silently does
nothing. In a shared database the next run of the file then hits
Code 57 TABLE_ALREADY_EXISTS on its unguarded CREATE statements.
Measured: with the injection forced to fire, two consecutive runs in
one database fail on the second run without the pins and pass with
them.

Statement-level SETTINGS rather than a file-level SET, so the
injection stays active for the rest of the file.

Also record in the header comment why the exists consumer of the same
resolution site cannot carry the bug the test covers: its argument is
always a parsed subquery, never an identifier.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

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

Three rounds before this PR was opened, on ef207d2baceb8a, c4b77333c62dc0 and d1c129ae7868e1.
Each round is an independent cold read of the resulting code plus a second-model gate pass over the
same diff, adjudicated against the recorded measurements. 15 findings: 12 AGREE, 1 DISAGREE, 2
dropped
(7 in round 1, 3 in round 2, 5 in round 3).
Every AGREEd blocker and major was fixed and re-measured before this PR existed. The src/ diff has
been byte-identical since round 1: both later rounds moved only the test file, which is why the two
code hunks were re-adjudicated three times rather than changed.

The notes call out the places where a round corrected a conclusion of an earlier round or of mine,
since those are the ones worth a reviewer's attention.

Round 1 (7 findings: 6 AGREE, 1 dropped as superseded)

Finding Verdict
❌ The new test needed no-old-analyzer. 17 of its statements name the IN operand as a bare table-expression identifier and 13 use QUALIFY; both are analyzer-only, and the old-analyzer lanes set allow_experimental_analyzer = 0 server-side with no .oldanalyzer.reference fallback, so the file failed deterministically there. The test's own enable_analyzer = 0 control asserts UNKNOWN_TABLE for exactly that shape. Proven both ways afterwards: with that profile installed the file reports SKIPPED (old-analyzer), and with the tag removed on the same server it reports FAIL return code: 60. AGREE, fixed
❌ The SortNode::cloneImpl hunk had been described as unobservable, on the argument that FillingTransform checks alias and column_name as a pair. That argument is wrong, and it was mine as much as the author's. The pair members are different strings: SortColumnDescription::alias receives SortNode::column_name (the identifier name a) while column_name receives calculateActionNodeName, the column identifier __table1.a; INTERPOLATE's output set is keyed on the identifier name. So dropping column_name in a clone turns a correct INVALID_WITH_FILL_EXPRESSION into a silently accepted query, and that is reachable on master today through the pre-existing CTE clone. Now measured (a dedicated mutant returns rows where the fix raises 475), pinned by a committed assertion plus an EXPLAIN QUERY TREE check, and disclosed in the description and the changelog entry. AGREE, fixed
⚠️ The group labelled "bare table name" actually declared and used an alias. Alias lookup and one-/two-part name lookup are distinct resolution paths reaching the new guard, and the PR's generality claim rests on covering all three spellings, so each now has its own live statement. All three abort with Code: 179 on the base binary. AGREE, fixed
💡 The Closes / Related lines sat inside the template's HTML comment, where they neither render nor auto-close. Checked against 86 recently merged PRs carrying a Closes reference: the three whose line is only inside the comment have no linked issue. Moved below the marker. AGREE, fixed
💡 Two code citations pointed a few lines above the statement they named. Corrected. AGREE, fixed
💡 Non-ASCII punctuation in the description. Removed. AGREE, fixed

Round 2 (3 findings: 2 AGREE, 1 dropped as a confirmation)

Finding Verdict
⚠️ The test's eight cleanup DROP statements inherit the stress runner's ignore_drop_queries_probability = 0.2, which is appended as a client option to every statement of every non-upgrade thread, including the threads that share one database across the whole suite. InterpreterDropQuery reports success either way, so a skipped drop leaks the table and the next run of the file hits Code: 57 TABLE_ALREADY_EXISTS on its unguarded CREATE. 0.8**4 = 0.41, i.e. a ~59% failure rate, invisible to a local run and to the randomized-settings 50/50 because the setting comes from the runner rather than from settings randomization. The obvious counter-argument (the file carries the shard tag, so perhaps stress skips it) does not hold: args.shard is auto-detected from listen_host, and the stress runner never passes --no-shard. Fixed with statement-level SETTINGS ignore_drop_queries_probability = 0 on all eight, then verified with the injection forced to 1: both-unpinned fails the second consecutive run in one database, both-pinned passes twice and leaves no tables. AGREE, fixed
💡 exists is the second consumer of the fixed resolution site and is untested, but it structurally cannot carry the bug: its argument is always a parsed subquery, never an identifier. Recorded as one clause in the test's header comment rather than as a statement. AGREE, fixed
💡 Re-derived the cloneImpl clone-fidelity sweep independently and reached the same conclusion, so this was a confirmation rather than a finding. dropped

Two claims a fix round then refuted by measurement, both reported rather than worked around, and
both reflected in what this PR does and does not assert:

  • The per-test-database leftover-tables check in tests/clickhouse-test that the round-2 finding
    cited is dead code: it compares an absolute path against "02800", so it is never true. The
    pins stay, because the shared-database half of the argument stands on its own, and nothing here
    relies on that check. It is a pre-existing harness defect, tracked separately.
  • "Each of the two pins is separately load-bearing" is not provable: a pinned prologue cleans up
    whatever an unpinned epilogue leaks, and vice versa, so only the pair is. Both are kept anyway,
    since the epilogue pin is the one that protects co-scheduled tests in a shared database. The claim
    made is the provable one.

Round 3 (5 findings, all nits: 4 AGREE, 1 DISAGREE)

Finding Verdict
💡 The cloneImpl clone-fidelity sweep was reported as covering 17 bodies; it covers 20, across 16 translation units. Corrected, and the four apparent omissions the sweep passed over are now enumerated with the reason each is faithful or dead, so a reader can check the conclusion instead of taking it. AGREE, fixed
💡 The test's composition was described as "8 clause-position carriers"; the file has 29 labelled statements of which ten are controls, and eight clause positions were measured with a representative subset kept in the file, as the file's own header comment states. Reworded to the derivable numbers. AGREE, fixed
💡 The round-1 citation correction had been applied to the description but not to the sibling gate comment, which still carried the pre-round-1 line numbers. Corrected there too. AGREE, fixed
💡 The new code comments name createUniqueAliasesIfNecessary, GLOBAL IN, rewrite_in_to_join, column_name, PlannerSorting and EXPLAIN without inline code formatting, unlike the neighbouring in-tree comment that states the same invariant and unlike this PR's own commit messages and description. Recorded as noted-not-blocking rather than fixed: it is a nit with no substantive finding to fold it into, and re-spinning the branch for comment punctuation costs a full re-review. Happy to push it if a reviewer wants it. AGREE, noted
An unused #include <iostream> sits at the top of SortNode.cpp, but it is pre-existing on master and 40 lines away from this change, so removing it would add an unrelated hunk to a two-hunk diff. DISAGREE (out of scope)

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT t1.dummy FROM system.one AS t1 INNER JOIN (SELECT * FROM system.one) AS t2 ON t1.dummy = t2.dummy WHERE t1.dummy IN t2; through clickhouse local on a debug binary aborts with RC=134 and Logical error: 'Column identifier __table1.dummy is already registered' on every run, at default settings. No randomization, no timing, no load.
b Root cause explained? Yes. resolveFunction.cpp:1199 allows an IN argument identifier to resolve as a table expression; the resolution at QueryAnalyzer.cpp:3137-3139 hands back the join tree's own node pointer (the alias path deliberately does not clone for a table-expression lookup, :1173-1177) and the block clones only for CTEs (:3153) and materialized CTEs (:3183). One node then sits in two places in the tree, and the three stages that rewrite each IN argument independently mutate the join tree by accident. IdentifierResolveScope.h:260-265 already states that invariant and names exactly those three consumers.
c Fix matches root cause? Yes. It restores the stated invariant at the retrieval site that violates it, by extending the adjacent pre-existing CTE cloning rule to the case it misses. Not a guard at the throw site: that alternative was measured to leave the GLOBAL IN (Code: 179) and rewrite_in_to_join (Code: 10) symptoms broken, since neither goes through createUniqueAliasesIfNecessary.
d Test intent preserved / new tests added? New tests added, nothing weakened. 04650_in_argument_shared_with_join_tree.{sql,reference}: 29 labelled statements, of which ten are explicit controls. Eight clause positions were measured (WHERE, HAVING, ORDER BY, QUALIFY, join ON, comma join, inside a lambda, NOT IN) and a representative subset is kept in the file, as its header comment states; plus the table-function source, all three GLOBAL IN identifier spellings, the rewrite_in_to_join mode, the four shapes carried from #107603, and the SortNode clone-fidelity group. Every carrier asserts the row set the equivalent spelled-out subquery returns, not just the absence of a crash.
e Both directions demonstrated? Yes, against a pristine origin/master binary built in the same run. Base 8780cd4022ebb73d...: RC=134 / Code: 179 / Code: 10 / RC=134 for the four shapes, and the committed test file's output truncated after line 4. Fix 9cdc70208d665069...: RC=0 for all four, test output byte-identical to its .reference, [ OK ] under the runner. Each hunk was reverted individually (6a879fc4f339..., 100e2dc37617...) to confirm which one is load-bearing.
f Fix is general across code paths? Yes. One hunk at the single retrieval site both consuming paths funnel through fixes all three symptoms and reverting it restores all three - the rewrite_in_to_join path clears is_special_function_in (resolveFunction.cpp:915/:923) before the regular IN block, which is why a clone inside that block cannot reach it. The detector is spelling-independent (alias, bare name, db.table) and isTableExpressionNodeType covers TABLE / TABLE_FUNCTION / QUERY / UNION. All 20 cloneImpl bodies under src/Analyzer/ (16 translation units) were swept member-by-member against their headers for the same clone-fidelity class. The four apparent omissions are all faithful or dead: ApplyColumnTransformerNode::apply_transformer_type and TableNode::storage_metadata are re-derived by the constructor the clone calls, ConstantNode::cached_ast/hash_ast are a memo keyed on getTreeHash, and TableFunctionNode::table_function has no live reader (isResolved() has no call site on a table-function node and getTableFunction() no non-AST caller). SortNode::column_name was the only real gap and it is fixed here.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Measured with the shared column typed Nullable(Int32), LowCardinality(String), LowCardinality(Nullable(String)) and Array(Int32); with an empty right side; with a three-way join carrying two shared arguments; and with the db.table spelling of the GLOBAL IN mode. All correct with the fix; the base binary aborts.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. No new setting, no default change, no serialization format change, so no SettingsChangesHistory.cpp entry is needed. The change replaces an accidentally shared node with a copy inside one analyzer resolve step.
i Invariants and contracts preserved? Yes. The invariant restored is stated verbatim in-tree (IdentifierResolveScope.h:260-265). clone() preserves resolution state (QueryNode::cloneImpl copies projection_columns / is_subquery / is_cte / settings_changes; TableNode::cloneImpl copies storage / storage_id / storage_lock / storage_snapshot) and cloneAndReplace remaps weak pointers so column sources inside the clone point at the clone, so no re-resolve is added - and none may be, since the CTE branch's resolveQuery exists only to un-set isCTE on an unresolved body. Aliases are untouched, so getTreeHash / isEqual with compare_aliases = true stay well-defined and createUniqueAliasesIfNecessary assigns the clone's aliases on its own re-visit; that is what the two mutation-path regression tests and the PreparedSets alias-stability test cover.

Session id: cron:clickhouse-impl-slot-42:20260727-134400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy @novikd - could you review this? When the right operand of an IN-family function is an identifier naming a table expression that is already in the join tree, identifier resolution hands back the join tree's own node pointer instead of a copy, so the three stages that rewrite each IN argument independently (createUniqueAliasesIfNecessary, the GLOBAL IN external-table rewrite, rewrite_in_to_join) mutate the join tree by accident; the fix clones at that retrieval site.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [971c569]

Summary: ✅


AI Review

Summary

This PR fixes analyzer alias sharing for IN-family right operands that reference a join-tree table expression, and it also preserves SortNode::column_name across clones so copied WITH FILL ... INTERPOLATE subqueries keep raising INVALID_WITH_FILL_EXPRESSION. The analyzer change itself looks coherent, but the latest test-only follow-up dropped the ignore_drop_queries_probability = 0 pins from the new stateless test, so the PR still adds a flaky stress-runner path.

Missing context / blind spots
  • ⚠️ I could not rerun the new test in this worker because no local clickhouse binary/server is available here; the cleanup finding is based on the current stress.py, InterpreterDropQuery, and the still-pinned DDL-heavy stateless tests already on master.
Findings

⚠️ Majors

  • [tests/queries/0_stateless/04650_in_argument_shared_with_join_tree.sql:13] The new test's cleanup no longer pins ignore_drop_queries_probability, but the stress runner still injects ignore_drop_queries_probability=0.2 for every non-upgrade worker and still runs half of them in a shared --database=test_<i>. Under InterpreterDropQuery, that means DROP TABLE on Memory can become TRUNCATE and DROP TABLE on Set / MergeTree can be silently skipped, so t_04650_* survives and the next iteration of this file can fail on CREATE TABLE ... with TABLE_ALREADY_EXISTS.
    Suggested fix: restore SETTINGS ignore_drop_queries_probability = 0 on both the prologue and epilogue DROP statements.
Final Verdict

Request changes: the analyzer fix looks good, but the new regression test still needs its cleanup DROPs pinned against the stress runner's forced ignore_drop_queries_probability.

LLVM Coverage Report

Measured on commit 971c569.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 15/15 (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 Jul 28, 2026
Comment thread src/Analyzer/SortNode.cpp Resolved
@yariks5s yariks5s self-assigned this Jul 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

While verifying the AI review comment on SortNode::updateTreeHashImpl I found a separate,
pre-existing inconsistency in the INTERPOLATE / ORDER BY ... WITH FILL validation. It is not
caused by this PR (measured byte-identically on the pristine merge-base), and it is not the same
defect the bot reported, so I am not folding it in. But it needs a semantic ruling before anyone
writes a fix, and I would rather ask than guess.

Two spellings of one semantic query behave differently under enable_analyzer = 1:

CREATE TABLE t (a Int64, b Int64) ENGINE = Memory;
INSERT INTO t VALUES (10,1),(30,3),(50,5);

SELECT a, b FROM t ORDER BY a   WITH FILL FROM 10 TO 51 STEP 10 INTERPOLATE (a AS a);
-- Code: 475 INVALID_WITH_FILL_EXPRESSION

SELECT a, b FROM t ORDER BY t.a WITH FILL FROM 10 TO 51 STEP 10 INTERPOLATE (a AS a);
-- 10 1 / 10 0 / 30 3 / 30 0 / 50 5

Same for default.t.a, for a table alias, for SELECT a AS x ... INTERPOLATE (x AS x), for
ORDER BY a+1 with an aliased projection, and for a sorting-prefix column. enable_analyzer = 0
raises 475 for all of them.

Mechanism: SortNode's constructor stores the ORDER BY identifier's literal text
(SortNode.cpp:40, and it stays empty when the child is not an IdentifierNode).
PlannerSorting.cpp:170-184 copies that text into SortColumnDescription::alias, and the guard at
FillingTransform.cpp:255-271 compares it against InterpolateDescription::result_columns_set,
which is keyed on the interpolate target's resolved display name (Planner.cpp:1070). The two
strings coincide only when the user spelled the ORDER BY identifier exactly like the target, so the
guard is effectively spelling-dependent. The old analyzer is unaffected because it derives both
sides from resolved names (InterpreterSelectQuery.cpp:1498 and :1566).

The reason I am asking rather than proposing a patch: I cannot find a mechanical rule that separates
the queries above from ones already pinned as valid. For 04402_..._fill_column_overlap.sql:12 and
04490_..._constant_fill_column.sql:29, the query tree is isomorphic to the case
above, with the SORT expression and the INTERPOLATE expression being the same COLUMN node:

ORDER BY t.a ... INTERPOLATE (a AS a)      04402 line (currently valid)
  SORT with_fill: 1                          SORT with_fill: 1
    EXPRESSION t.a                             EXPRESSION a0
      COLUMN id: 2 (a)     <-- same node         COLUMN id: 2 (number)   <-- same node
  INTERPOLATE                                INTERPOLATE
    EXPRESSION a                               EXPRESSION a4
      COLUMN id: 2 (a)     <-- same node         COLUMN id: 2 (number)   <-- same node

Row counts are also unaffected in every case (5 vs 5, and 15 vs 15 for the sorting-prefix shape), so
nothing is ragged; only the values of the interpolated column change, which is what INTERPOLATE
is for. And INTERPOLATE (a AS a + 100) returns the requested 110 / 130 on the gap rows whether
or not the fill column is separately projected. So the difference really is only which display alias
the user picked.

That leaves a semantics question that I do not think the code can answer on its own: when a
projection column is an alias of the WITH FILL column, is naming it in INTERPOLATE a user error
to reject, or a request to override the generated values? The doc says INTERPOLATE applies to
"columns not participating in ORDER BY WITH FILL"
(docs/reference/statements/select/order-by.mdx:285) without defining when a projection output is
the ORDER BY column rather than a separate column derived from it.

Three directions, each with a measured cost:

  1. Reject more, so every spelling behaves like the bare one. This contradicts the two currently
    passing analyzer lines named above, so those assertions would have to change.
  2. Reject less, dropping the analyzer-side check so the bare spelling behaves like the qualified one.
    This un-rejects 02233_interpolate_1.sql:34 and 02730_with_fill_by_sorting_prefix.sql:60, which
    were deliberately introduced in 37211fac2517da and 095c119289fdb7 and still raise 475 today.
  3. Keep both behaviours and document that the spelling selects them.

My own preference is 1, because a result where the ORDER BY column comes back 10,10,30,30,50 reads
as self-contradictory for a query that asked to fill it, and because it makes the two analyzers
agree. But it narrows accepted behaviour and touches assertions from the commits that introduced the
guard, so I do not want to pick it unilaterally.

Happy to prepare whichever direction is preferred as its own PR. If it is better tracked as an
issue, say so and I will open one.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d1c129a

CI fully finished on this head: 174 check-runs, 0 queued or in progress, Finish Workflow pass,
Config Workflow pass. 156 pass, 18 skipped, 0 failures. CIDB has no FAIL/ERROR row for this
commit.

Check / test Reason Owner / fixing PR
(none) CI fully finished with no failing check at this commit not applicable

Session id: cron:our-pr-ci-monitor:20260728-130000

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 34 queries analysed

Release-transition baseline: compared against the last 26.8 master because no 26.9 master baseline exists at or before the trusted base-commit anchor.

This PR is an analyzer-only fix: it clones a table expression when an IN-family argument aliases a table already in the enclosing query's join tree, plus a SortNode clone that now carries column_name for ORDER BY ... WITH FILL / INTERPOLATE. None of the flagged benchmark queries hit these paths (none re-use a join-tree table as an IN argument, none use WITH FILL/INTERPOLATE), so all four deltas are downgraded to not_sure as run-to-run variance on noisy queries rather than PR effects. The clickbench Q17 ×1.8-faster and TPC-H Q7 +20.9% readings in particular cannot come from a guarded clone the query never executes.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 448 244 -45.5% <0.0001 This PR only adds an analyzer clone guard for IN-arguments that alias a join-tree table plus a SortNode column_name clone fix; ClickBench Q17 has no join, IN, or WITH FILL, so the ×1.8 faster reading is run-to-run variance on a noisy query.
⚠️ 18 not_sure 1098 1042 -5.1% <0.0001 The diff touches only the IN-vs-join-tree clone path and SortNode cloning; Q18 exercises neither, so this -5.1% on an intrinsically noisy query is not a PR effect.
⚠️ 28 not_sure 1120 1052 -6.1% <0.0001 The two tests disagree and the query is noisy; nothing in this analyzer-only diff plausibly touches Q28's path, so not_sure is right.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 67 81 +20.9% <0.0001 TPC-H Q7 uses plain joins with no IN-argument aliasing a join-tree table and no WITH FILL/INTERPOLATE, so this analyzer clone-guard cannot add work to it; the +20.9% (+14 ms) is variance on a noisy query.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 7e5d28b6-c7e9-482d-9284-490ce294911a
  • MIRAI run: 6663b8d4-d410-4988-ab02-c1895b7a3fdd
  • PR check IDs:
    • clickbench_1236519_1788560134
    • clickbench_1236525_1788560134
    • clickbench_1236531_1788560134
    • tpch_adapted_1_official_1236541_1788560134
    • tpch_adapted_1_official_1236554_1788560134
    • tpch_adapted_1_official_1236590_1788560134

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Dear @yariks5s, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
groeneai and others added 3 commits September 4, 2026 17:28
Requested at ClickHouse#112005 (comment),
and ClickHouse#113117 has since removed every carrier on master. This branch still added
the setting to eight `DROP` statements, so it would bring back a convention
master no longer uses.

The pins only ever changed anything under the stress runner, which injects
`ignore_drop_queries_probability=0.2` as a client option
(`ci/jobs/scripts/stress/stress.py`), and the upgrade check, which sets it to 1
(`programs/client/Client.cpp`); neither job compares per-test output. Measured
at the default 0, which is what every results-checking job uses: with and
without the pins the eight statements exit 0, produce byte-identical output and
leave no table behind. Forcing the setting to 1 is the only way to tell the two
apart. The unpinned run then keeps all four tables (`Memory` truncated, `Set`
and `MergeTree` skipped) and a second run in the same database fails with
`TABLE_ALREADY_EXISTS`. That is the behaviour the removal accepts, and it is
what master's own de-pinned tests now do.

The comment that justified the pins goes with them. The note about the `exists`
consumer of the same resolution site stays, because it explains why that
sibling cannot carry the bug and that is still true.

Co-Authored-By: Claude Opus 5 <[email protected]>
`.claude/CLAUDE.md` asks for literal names from the ClickHouse SQL language,
classes and functions to be wrapped in inline code blocks. The comments this PR
added spelled `createUniqueAliasesIfNecessary`, `GLOBAL IN`, `rewrite_in_to_join`,
`column_name`, `PlannerSorting`, `EXPLAIN` and `exists` as plain prose.

Comments only. Every non-comment line of the three files is byte-identical to
the previous commit.

Co-Authored-By: Claude Opus 5 <[email protected]>
Completes the pass started in the previous commit: the rest of this test's
comments still spelled `rewrite_in_to_join`, `QUALIFY`, `MergeTree`,
`ORDER BY`, `INTERPOLATE`, `EXPLAIN`, `SortNode::cloneImpl`, `column_name`,
`SortColumnDescription::alias`, `FillingTransform`, the two resolver entry
points and the quoted diagnostics as plain prose.

Comments only. Every non-comment line is byte-identical to the previous commit
and the reference file is untouched.

Co-Authored-By: Claude Opus 5 <[email protected]>
`CollectSets`, the `Set` engine and the `__table1.number` diagnostic fragment
were the remaining identifier-shaped names. SQL keywords used as English nouns
("an IN argument", "the NOT IN shape") are left as prose, which is what the
stateless suite does elsewhere.

Comments only.

Co-Authored-By: Claude Opus 5 <[email protected]>
-- (The `exists` consumer of the same resolution site cannot carry this: its argument is always a
-- parsed subquery, never an identifier.)

DROP TABLE IF EXISTS t_04650_l;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The new cleanup still needs SETTINGS ignore_drop_queries_probability = 0 here and on the matching trailing DROPs.

The stress runner still injects ignore_drop_queries_probability=0.2 for every non-upgrade worker (ci/jobs/scripts/stress/stress.py:455-458) and still runs half of them in one shared --database=test_<i> (:374-377). InterpreterDropQuery still rewrites a DROP of an in-memory table into TRUNCATE and silently skips a disk-backed table when that probability fires (src/Interpreters/InterpreterDropQuery.cpp:221-231), so this file can leak t_04650_* into the shared database and the next iteration then dies on CREATE TABLE ... with TABLE_ALREADY_EXISTS.

Please restore the pins on both the prologue and epilogue DROPs, like the other DDL-heavy stateless tests that have to survive the stress profile.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Mechanism granted, remedy declined, and two of the three citations are off.

Accurate: src/Interpreters/InterpreterDropQuery.cpp:221-231 is the block that skips a disk-backed DROP and rewrites an in-memory one into TRUNCATE. The stress.py line numbers are not: the 0.2 injection for non-upgrade workers is at ci/jobs/scripts/stress/stress.py:219-222 (:455-458 is make_query_command), and the shared --database=test_<i> for i % 2 == 1 is at :158-161 (:374-377 is thread-pool fault injection). The substance of both holds.

But this pin class was deliberately removed from the tree. #113117 ("Stateless tests: Remove useless ignore_drop_queries_probability = 0") merged on 2026-09-01, stripping it from 14 stateless tests and substituting nothing, including the drop-heavy ones cited here as precedent: 04905_lwu_drop_race_table_lock.sh, 04648_kafka2_race_creation_removal.sh, 03224_invalid_alter.sql. The justification it deleted from 03224 was this ask's own argument: "the stress runner sets it to 0.2, which makes a DROP a no-op". The one deleted from 04648 was stronger still ("for a storage that keeps nothing on disk the injection rewrites DROP into a TRUNCATE that Kafka does not implement. Hence the pin.").

Removing the 8 clauses here was that cleanup reaching this PR: it was asked for on #112005, where I said I would take the pin out of all my open PRs. Restoring it would revert a merged tree-wide cleanup for a single file, so I am not doing that. If the class should return, that is a call on #113117, not on this PR.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

8 object files changed (+1.48 MiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/TimeSeries/AggregateFunctionTi… 4.98 MiB 6.43 MiB +1.45 MiB (+29.13%)
src/Examples/CMakeFiles/clickhouse-examples.dir/__/AggregateFunctions/examples/timeseries_to_grid_t… 63.79 KiB 81.19 KiB +17.40 KiB (+27.28%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov self-assigned this Sep 6, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 6, 2026
Merged via the queue into ClickHouse:master with commit 261c959 Sep 6, 2026
174 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 6, 2026
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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

Logical error: Column identifier A is already registered (STID: 4697-4326)

5 participants