Skip to content

Fix a correlated subquery whose PREWHERE references a column of the outer query - #122397

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-correlated-column-in-prewhere
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-correlated-column-in-prewhere

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121230

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 wrong results and Logical error: Trying to execute PLACEHOLDER action for a correlated subquery whose PREWHERE references a column of the outer query: the condition was ignored, or the outer column was taken from the inner table's column of the same name. Such a PREWHERE now throws ILLEGAL_PREWHERE with FINAL or on a table without PREWHERE support, and NOT_IMPLEMENTED with a JOIN inside the subquery, instead of being ignored.

Description

On 26.8.2.7 and 26.3.33.10, SELECT value FROM t AS t1 WHERE exists(SELECT 1 FROM t AS t2 PREWHERE t1.value + 1 = 12) over t = (10), (11) returns both rows instead of 11, and PREWHERE arrayMap(x -> x + t1.value, [1])[1] = 12 throws LOGICAL_ERROR.

Found by the AST fuzzer on #121230, which does not cause it: AST fuzzer (amd_debug, targeted), STID 1611-3e1e and 1611-4266.

Three PREWHERE planner stages assumed every column belongs to a table of the current query:

  1. The PREWHERE table was chosen from the column's source, the outer table, whose read was already planned, so the condition was dropped. Correlated columns are now skipped there.
  2. The PREWHERE DAG names and merges nodes by plain name, so the outer column merged with the inner one of the same name. A correlated column is now named by its identifier.
  3. The DAG was pushed into the storage, where the decorrelation never looks, so its placeholder reached the reader. It now runs as a filter above the read (the existing logical-plan branch), which the decorrelation handles like WHERE. That filter cannot precede FINAL merging, hence the FINAL refusal; a JOIN above it is not decorrelated.

That filter sees raw column names, and the step 2 DAG merges by name, so a column named like an outer identifier (__table1.value) would shadow the outer value; such a subquery is now refused.

04058 case 1 relied on the dropped condition and now uses WHERE. This also fixes the correlated case of the #121230 collision; both PRs' tests pass together.

Validation: 05258 fails on master (server abort) and passes with the fix; 50 randomized runs; 364 PREWHERE/correlated tests give identical results before and after.

🤖 Generated with Claude Code


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

groeneai and others added 3 commits September 26, 2026 01:44
…uter query

A correlated column in PREWHERE went through three planner stages that each
assume every column belongs to a table of the current query:

1. CollectPrewhereTableExpressionVisitor picked the PREWHERE table from the
   column sources, so a correlated column selected the OUTER table. Its table
   expression data is shared with the outer query, whose read is already
   planned, so the condition was silently dropped (wrong result). Correlated
   columns are now skipped when choosing the table.
2. The PREWHERE DAG names table columns by their plain names, and every node,
   including whole expressions, is deduplicated by name. A correlated column,
   or any expression over it, merged with the inner column or expression of
   the same text (wrong result), and a shadowing lambda argument made the
   types disagree (`Unexpected return type`). ActionNodeNameHelper now names a
   correlated column by its column identifier also in that DAG, which is the
   name under which the decorrelation provides the outer value.
3. The PREWHERE DAG was handed to the storage as prewhere_info, which the
   decorrelation never visits, so a PLACEHOLDER reached the MergeTree reader
   and the Merge table filter (`Trying to execute PLACEHOLDER action`, also
   under EXPLAIN). A PREWHERE with a correlated column is now applied by a
   FilterStep directly above the read (the existing build_logical_plan
   branch), which the decorrelation handles like WHERE. With FINAL it is
   refused, because such a filter cannot run before the FINAL merge.

Test 04058 case 1 used PREWHERE on the implicit `system.one` with only outer
columns, which was accepted only because the condition was dropped; it now
uses WHERE, which keeps what that test checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…outer column

The decorrelation joins the outer values to the read under the names of the
correlated columns (for example `__table1.value`). A correlated PREWHERE is
applied by a filter directly above the read, so a table with a column
literally named `__table1.value` produced two columns of that name, and the
filter used the inner one: no rows instead of `11`. Such a PREWHERE now
throws ILLEGAL_PREWHERE. WHERE is not affected, because its filter runs
above the step that renames the columns to their identifiers.

Test 05258 gets that case. Its q5 and q6 now also require `t2.value > 10`:
both sides read the same rows, so before this change the diagonal satisfied
them even when the condition was ignored or the outer column was merged with
the inner one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tion joins them

The decorrelation joins the outer values to the uncorrelated part of a
subquery plan under the names of all correlated columns of the subquery.
The previous check sat in the read of a correlated PREWHERE and compared
only the correlated columns of that query. In a correlated UNION each arm
is a separate query that lists only the outer columns it references, while
every arm is joined with all of them. So an arm that reads a column named
like an outer column referenced only by another arm still got two columns
of that name, and the query failed with UNION_ALL_RESULT_STRUCTURES_MISMATCH
or bound the column by name.

The check now runs at the decorrelation boundary, which sees exactly the
header and the names that are joined, and throws NOT_IMPLEMENTED. It
replaces the PREWHERE-only check and covers its cases. WHERE is not
affected, because its filter runs after the columns are renamed to their
unique identifiers.

Test 05258 gets the UNION case and a control query without the colliding
column; the existing clash query now expects NOT_IMPLEMENTED.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 26, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex; round 1: 1 finding, round 2: 4, round 3: 0) plus my
own cold review in every round.

# Sev Finding Verdict Evidence / action
1 ❌ An inner column named like the plan name of the outer column (`__table1.value`) is read instead of the outer value, because the correlated PREWHERE filter sits below the rename to column identifiers AGREE, fixed @ 73b1824, generalized @ 6695cfd measured: no rows instead of 11; now refused where the decorrelation joins the outer values, pinned in 05258
2 ⚠️ Two 05258 queries (t2.value = t1.value, t2.value + 1 = t1.value + 1) could not fail: an ignored or merged predicate gives the same 10, 11 AGREE, fixed @ 73b1824 AND t2.value > 10 added, expected 11; red with the naming edit reverted
3 ⚠️ The r1 refusal checked only the current UNION arm's outer columns, while the decorrelation joins every arm with all of them AGREE, fixed @ 6695cfd measured: the collision passed the check; the check now runs at the decorrelation boundary with the full list, UNION case pinned in 05258
4 ❌ A table column literally named like an expression's internal name (`plus(__table1.value, 1_UInt8)`) replaces that expression in PREWHERE DISAGREE the PREWHERE DAG reuses nodes by name for every PREWHERE, correlated or not; the same collision exists without a correlated column on master
5 ❌ PREWHERE t1.flag (a bare outer column as the whole condition) throws UNKNOWN_IDENTIFIER DISAGREE identical to the WHERE t1.flag spelling on master; before this PR the PREWHERE spelling silently ignored the condition
6 💡 The where_filters loop adds filters only at FetchColumns noted, no change not reachable for a correlated subquery (remote tables rejected, parallel replicas disabled for correlated queries)
7 💡 The PREWHERE table visitor looks a column up in the correlated set without the empty() shortcut the other two lookups use; the new boundary check re-reads a header the next branch reads again noted, no change cosmetic; one hash per PREWHERE column
8 💡 The Related link to #121230 sits inside the template's HTML comment and would not render DISAGREE the body has a visible Related: line below the template comment

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-10:20260926-053600

@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [caab4a3]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Logical error: Context has expired (STID: 1805-578d) FAIL cidb
Upgrade check (amd_release) FAIL
Cannot check whether the row policies can be applied (see unchecked_row_policy_errors.txt) FAIL cidb

AI Review

Summary

This change fixes dropped predicates and incorrect column binding in correlated subquery PREWHERE conditions, evaluates them through decorrelation, and rejects unsupported cases. No actionable findings remain at caab4a3f2841a606f449abcbcff809ffb6aa5161. The previous scalar name-collision finding is fixed and its review thread has been resolved. All 23 focused local cases passed against the PR's CI binary, including the regression queries and seven additional probes.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: one clickhouse local per query; PREWHERE t1.value + 1 = 12 returns 10, 11 instead of 11, and the lambda form aborts with Trying to execute PLACEHOLDER action on every run (both fuzzer queries from the CI report reproduce on master).
b Root cause explained? Yes: a correlated column picked the outer table as the PREWHERE table (condition dropped), was named like the inner column in the PREWHERE DAG (merged with it), and the DAG went to the storage, where the decorrelation never looks (placeholder executed by the reader or the merge() table filter).
c Fix matches root cause? Yes: each of the three stages is fixed where it goes wrong; no guard at the error site, no new setting.
d Test intent preserved / new tests added? Yes: new 05258 (14 queries, each red on master; q5/q6 also fail without the naming edit). 04058 case 1 was green only because its condition was dropped; it now uses WHERE and still checks what it was written for.
e Both directions demonstrated? Yes: 05258 fails on master (server abort) and passes with the fix; per-query A/B on 100 probe queries. For a UNION whose arm reads a column named like an outer column that only the other arm references, master gives ILLEGAL_PREWHERE and the fix gives NOT_IMPLEMENTED; for its control without that column, master gives ILLEGAL_PREWHERE and the fix returns 1.
f Fix is general across code paths? Yes: the placement change covers every storage that reads PREWHERE (MergeTree, merge(), Buffer, File(Parquet) measured); naming is fixed in the single place that computes action names, and only the PREWHERE DAG combines plain names with outer columns. The name-clash refusal sits where the decorrelation joins the outer values, so it covers every UNION arm; it does not fire for WHERE.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes: outer-only, mixed inner and outer, expressions over both, lambda capture with and without a shadowing argument, scalar subquery, EXISTS, UNION ALL, FINAL (also via final = 1), JOIN in the subquery, system.one, an inner column named like the outer column's generated name (__table1.value), also in a UNION arm when only the other arm references that outer column.
h Backward compatible? (maintainer-approved exception only) Yes: no setting or format change; only queries that returned wrong results or threw change, and four that ignored the condition or read the wrong column now throw: ILLEGAL_PREWHERE for FINAL and for no PREWHERE support; NOT_IMPLEMENTED for a JOIN and for an inner column named like the outer column's generated name, also in a UNION arm. Non-correlated PREWHERE and all WHERE controls are unchanged.
i Invariants and contracts preserved? Yes: the filter uses the existing logical-plan branch, so the row policy order, trivial count/LIMIT refusal and analyze-only path are unchanged; the decorrelation gets a filter step it already supports.

Session id: cron:clickhouse-impl-slot-5:20260926-045300

Comment thread src/Planner/PlannerJoinTree.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6695cfd

Every failure below has an owner: a fixing PR (mine 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
Performance Comparison (arm_release, master_head, 5/6) / optimize_time_filter_with_preimage #4 perf noise: +20.2% dashboard confirmed_regression (0.659 s to 0.793 s) on the single-threaded scan with the optimization off, which this diff does not reach; 65 of 263 arm runs of that query today were over 10% slower, master included #122156 (mine, open)

Session id: cron:our-pr-ci-monitor:20260926-160139

… took

The PREWHERE DAG names table columns by their names and a correlated column by
its identifier. When an inner column literally named like that identifier
(`__table3.value`) was visited first, the correlated column was merged with it:
no PLACEHOLDER was added, the PREWHERE was pushed into the storage, and it
compared the inner column with itself. A scalar subquery returned 1 instead of
NULL. The reverse operand order was already refused at the decorrelation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - caab4a3

Every failure below has an owner: a fixing PR (mine 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
Stress test (amd_tsan) / Logical error: Context has expired (STID: 1805-578d) trunk bug, not from this PR (it changes PREWHERE and correlated-subquery planning only): timeSeriesStoreTags reads the query context after it has expired; the same STID failed on 5 other PRs since 2026-10-17 #126492 (mine, open)
Upgrade check (amd_release) / Cannot check whether the row policies can be applied not from this PR (the probe runs on the old 26.9 server): a table created AS url(...) to a closed port by 05141_create_as_external_engine_requires_select fails both row-policy probes with Code 636, which the runner does not skip #127543 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #126492, #127543 (the owners of the rows above)

Session id: cron:our-pr-ci-monitor:20261023-040008

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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants