Repository navigation
Do not share a join-tree table expression with an IN argument - #112219
alexey-milovidov merged 7 commits into
Conversation
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]>
Internal second-model review (click to expand)Three rounds before this PR was opened, on The notes call out the places where a round corrected a conclusion of an earlier round or of mine, Round 1 (7 findings: 6 AGREE, 1 dropped as superseded)
Round 2 (3 findings: 2 AGREE, 1 dropped as a confirmation)
Two claims a fix round then refuted by measurement, both reported rather than worked around, and
Round 3 (5 findings, all nits: 4 AGREE, 1 DISAGREE)
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-42:20260727-134400 |
|
cc @yakov-olkhovskiy @novikd - could you review this? When the right operand of an |
|
Workflow [PR], commit [971c569] Summary: ✅
AI ReviewSummaryThis PR fixes analyzer alias sharing for Missing context / blind spots
Findings
Final VerdictRequest changes: the analyzer fix looks good, but the new regression test still needs its cleanup LLVM Coverage ReportMeasured on commit 971c569.
Changed lines: Changed C/C++ lines covered: 15/15 (100.00%) · Uncovered code |
|
While verifying the AI review comment on Two spellings of one semantic query behave differently under 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 5Same for Mechanism: The reason I am asking rather than proposing a patch: I cannot find a mechanical rule that separates Row counts are also unaffected in every case (5 vs 5, and 15 vs 15 for the sorting-prefix shape), so That leaves a semantics question that I do not think the code can answer on its own: when a Three directions, each with a measured cost:
My own preference is 1, because a result where the ORDER BY column comes back Happy to prepare whichever direction is preferred as its own PR. If it is better tracked as an |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 12/12 (100.00%) · Uncovered code |
CI finish ledger - d1c129aCI fully finished on this head: 174 check-runs, 0 queued or in progress,
Session id: cron:our-pr-ci-monitor:20260728-130000 |
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (3 of 43)
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_officialFlagged queries (1 of 22)
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
|
|
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. |
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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| 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.
Closes: #99931
Related: #107603
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a
LOGICAL_ERROR(Column identifier ... is already registered), aMULTIPLE_EXPRESSIONS_FOR_ALIASerror and aNOT_FOUND_COLUMN_IN_BLOCKerror for a query whoseIN/NOT IN/GLOBAL INright operand names a table expression that also appears in theFROMsection, for exampleSELECT 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 othercopied subquery raise
INVALID_WITH_FILL_EXPRESSION, as the same query already does when it is notcopied: 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,resolveFunctionallows it to beresolved as a table expression (
allow_table_expressionsatsrc/Analyzer/Resolve/resolveFunction.cpp:1199). The resolution atsrc/Analyzer/Resolve/QueryAnalyzer.cpp:3137-3139returns the join tree's own node pointer - thealias path deliberately does not clone for a table-expression lookup
(
tryResolveIdentifierFromAliases,:1173-1177), and the name /db.tablepaths return theregistered node directly. The block clones only for CTEs (
:3153) and materialized CTEs (:3183), soa 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 idtwice inEXPLAIN QUERY TREE run_passes = 1).The same invariant is already written down in the tree, for a neighbouring mechanism:
IdentifierResolveScope.h:260-265explains why the identifier-resolve cache must hand out a copy ofany subquery-bearing tree, and names the three downstream stages that rewrite each instance
independently. That cache never sees a table expression -
canCacheIdentifierrejects such a lookupoutright (
IdentifierResolveScope.cpp:190-195, with the same reasoning spelled out in the commentthere) - but the same three stages break for the sharing this PR fixes:
createUniqueAliasesIfNecessaryLogical error: 'Column identifier __table1.<col> is already registered'(PlannerContext.cpp:42<-CollectTableExpressionData.cpp:164) - aborts the server on debug/sanitizer buildsGLOBAL INexternal-table rewritingCode: 179 Duplicate aliases __table2 for table expressions in FROM section are not allowedrewrite_in_to_joinCode: 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 memberof
registered_table_expression_nodesin the current or any enclosing scope. This is the singleretrieval site both consuming paths reach, so one hunk fixes all three symptoms: the
rewrite_in_to_joinpath resolves the operand itself and then clearsis_special_function_in(
resolveFunction.cpp:915/:923) before the regularINblock runs, so a clone placed inside thatblock cannot help it. The detector is spelling-independent, so the alias, bare-name and
db.tablespellings and the
TABLE/TABLE_FUNCTION/QUERY/UNIONnode types are all covered.The change is a strict extension of the two pre-existing cloning rules earlier in the same
ifchain (plain CTE at
:3153, materialized CTE at:3183) - rewriting any of the failing shapes touse 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 asuperset of the failing shapes: a bare table alias on the right of
IN(... JOIN r AS r ... WHERE x IN r) and anINnaming the LEFT table expression already work on master, becausecreateUniqueAliasesIfNecessaryskips a plainTABLEargument (:120) and the left side does notcollide. 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 expressionper 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
INblock ofresolveFunction.cpp, which covers the first symptom but not therewrite_in_to_joinpath. This PRsupersedes 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 itsresolveFunction.cpphunk, and all four of its shapes are carried into the test added here so nothingis lost if it is closed.
Its second hunk,
SortNode::cloneImplcarryingcolumn_name, is carried here as well, since masterstill lacks it and this is now the branch that supersedes #107603.
column_nameis derived from theoriginal 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/:176putsSortNode::column_nameintoSortColumnDescription::alias(theidentifier name,
a) whileSortColumnDescription::column_namegetscalculateActionNodeName(expression), which for a resolved column is the column identifier(
__table1.a).InterpolateDescription::result_columns_setis keyed on the identifier name(
Planner.cpp:1070,InterpolateDescription.cpp:27-34). So forORDER BY a WITH FILL ... INTERPOLATE (a AS a)inside a cloned subquery, the conflict check atFillingTransform.cpp:259-270findsathroughaliasand correctly raisesINVALID_WITH_FILL_EXPRESSION; withcolumn_namedropped by the clone,aliasis empty, the checkis skipped and the query returns rows instead. The
column_namehalf of that pair only substitutesfor a constant
ORDER BYexpression, 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 pinsboth spellings.
column_nameis likewise printed byEXPLAIN 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/masterbinary built in the same run(
8780cd4022ebb73d...vs9cdc70208d665069...), and each hunk was reverted individually to confirm it isload-bearing. On the base binary the failure reproduces for
WHERE,HAVING,ORDER BY,QUALIFY,join
ON, a comma join, inside a lambda,NOT IN, anumbers()table-function source, and with theshared column typed
Nullable,LowCardinality,LowCardinality(Nullable)orArray; all arecorrect 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 CTEpath, a
Set-engine right operand, a union-subquery alias, tupleIN, the old analyzer, ...) arebyte-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 namingallow_experimental_correlated_subqueriesorGLOBAL IN, plus the sibling fixes' regression testsand the
PreparedSetsalias-stability test - 282 tests) were run on both binaries with identicalfailing 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.2for theshard/ distributed /parallel-replicas tests.
Workflow [PR]
Sync PR [sync-upstream/pr/112219]
Version info
26.9.1.858(included in26.9and later)