Skip to content

Keep the correlated column of a subquery out of the subcolumn rewrite - #118287

Merged
alexey-milovidov merged 7 commits into
masterfrom
correlated-positional-tuple-element-111729
Sep 25, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
correlated-positional-tuple-element-111729

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

A correlated subquery lists the outer columns it reads, and decorrelation joins exactly those columns in. When the subquery reads a tuple element of such a column through its position - o.p.1, which is tupleElement(o.p, 1) - optimize_functions_to_subcolumns replaced the function with a subcolumn read of the column. The list then named a column the subquery no longer reads, so decorrelation looked for the subcolumn in a join that carries the whole column:

CREATE TABLE tc (p Tuple(a Int32, b String)) ENGINE = Memory;
INSERT INTO tc VALUES ((1, 'x'));

SELECT count() FROM tc AS o WHERE EXISTS (SELECT 1 FROM tc AS i WHERE i.p.a = o.p.1)
SETTINGS allow_experimental_correlated_subqueries = 1;
-- Code: 10. DB::Exception: Not found column __table1.`p.a` in block __table4.`p.a` Int32 Int32(size = 0).

Accessing the same element by name (o.p.a) resolves to that subcolumn during analysis, which the list records, so only the positional form failed. The first pass of the rewrite now counts a use of a correlated column as one it cannot optimize, which leaves every use of that column alone - the same conservative answer it already gives for an index column, or for a column that is also read in full elsewhere.

rewrite_in_to_join builds such a correlated subquery out of x IN (subquery), so p.2 IN (SELECT 'x') failed the same way and is fixed as well. Both issues have the same cause: with optimize_functions_to_subcolumns = 0 neither reproduces.

Closes: #111729
Closes: #112129

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 to CHANGELOG.md):

Fixed NOT_FOUND_COLUMN_IN_BLOCK for a correlated subquery that reads a tuple element of an outer column by position (o.p.1), and for the same shape on the left of IN (subquery) under rewrite_in_to_join.


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

Version info

  • Merged into: 26.10.1.646-master (included in 26.10 and later)

A correlated subquery lists the outer columns it reads, and decorrelation joins
exactly those columns in. When the subquery reads a tuple element of such a
column through its position - `o.p.1`, which is `tupleElement(o.p, 1)` -
`optimize_functions_to_subcolumns` replaced the function with a subcolumn read
of the column. The list then named a column the subquery no longer reads, so
decorrelation looked for the subcolumn in a join that carries the whole column:

    CREATE TABLE tc (p Tuple(a Int32, b String)) ENGINE = Memory;
    SELECT count() FROM tc AS o WHERE EXISTS (SELECT 1 FROM tc AS i WHERE i.p.a = o.p.1);
    Code: 10. Not found column __table1.`p.a` in block __table4.`p.a` Int32 Int32(size = 0).

Accessing the same element by name resolves to that subcolumn during analysis,
which the list records, so only the positional form failed. The first pass of
the rewrite now counts a use of a correlated column as one it cannot optimize,
which leaves every use of that column alone - the same conservative answer it
already gives for an index column or a column read in full elsewhere.

`rewrite_in_to_join` builds such a correlated subquery out of `x IN (subquery)`,
so `p.2 IN (SELECT ...)` failed the same way and is fixed as well.

Closes: #111729
Closes: #112129

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [541fb77]

Summary: ✅


AI Review

Summary

This PR keeps FunctionToSubcolumnsPass from rewriting correlated outer-column accesses into subcolumn reads, including the second-pass filter_only case, and adds focused regression coverage for direct tuple access, rewrite_in_to_join, mixed outer-WHERE cases, and the chained JSON-path case. After reading the current diff, the surrounding pass code, and all prior thread replies, I did not find a remaining contract violation or missing evidence that justifies a new inline comment.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 541fb77.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 63/66 (95.45%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 5, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 541fb77187b02dea7cde53d31ea56cebc3de52eb was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

alexey-milovidov and others added 2 commits September 11, 2026 00:18
Review pointed out that the guard added for the direct transformer path does not
cover the chained one, where `optimizeJSONArrayElement` rewrites
`json.a[1].b` into a subcolumn of `json.a`.

That path cannot reach the rewrite for a correlated column today: the subquery's
list of correlated columns is itself a read of the whole column, so the use count
never matches the optimizable count, and the chained path - unlike the direct one,
where `tupleElement` over `Tuple` is in
`transformers_optimize_in_filter_with_full_column` - has no filter-only escape
hatch. Verified with a control binary built without the new guard: the query tree
of a correlated `o.json.a[1].b` is identical either way, and only the subquery's
own access is rewritten.

Still state the invariant explicitly instead of relying on that accident of the
counting, and pin the behaviour with an assertion on the query tree.

Also pin `enable_analyzer` in the test: correlated subqueries are a feature of the
new analyzer, and the test failed in the old analyzer run of
`Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated)`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118287&sha=1029303102b10635bdb4a271efee46dd9887e031&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is a segmentation fault in DB::CrossTabCountsState::merge reached from ColumnAggregateFunction::insertRangeFrom in a sorted merge - unrelated to this pull request, which only changes FunctionToSubcolumnsPass. The same stack trace appeared on several unrelated pull requests before (#109897, #97254, #108944, #109639, #108680, #110321, #101398 on 2026-07-15 and 2026-07-16 per the CI database), and I could not find an open issue tracking it.

The other two failures on that commit are handled here: 05090_correlated_positional_tuple_element failed in the old analyzer run and now pins enable_analyzer, and the integration test Timeout should be covered by the fresh master merge.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. Nothing tracks this and no fix is in progress: no open issue and no open PR (searched open PRs and issues by text and by the touched file). In CIDB this segfault (STID 2844-4ada) has exactly one occurrence in the last 14 days, the one you linked at 1029303102b1.

Closest prior art is my #109200 (merged 2026-07-03), which fixed a SIGSEGV sharing this stack bucket (STID 2844-3b6e): a Variant to Variant conversion produced an aggregate state whose internal representation did not match what the reader assumed, and the fix landed in FunctionsConversion.cpp. The second STID component differs here, so I am treating 4ada as a sibling signature rather than a recurrence of that one. The occurrences you cite on 2026-07-15 and 2026-07-16 postdate that merge, and praktika builds the merge commit rather than the raw head, so I will check per build whether #109200 was actually present in each of them before concluding either way.

I will follow up here with the fix as a separate PR, or with my findings if the crash turns out not to be reproducible.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix: #119401, against master.

Root cause. Not a CrossTab bug and not a ColumnAggregateFunction bug. The CrossTab family keeps two
internal state layouts under one type name (ordinary aggregation vs window), and nothing announces which one
a column holds: neither the type name nor the binary type encoding carries the variant, by design, since all
variants share the serialization format. The local in-memory exchange forwards a producer Chunk unchanged
while the consumer advertises an independently built header, so a contingency window state travels under a
header naming the aggregation variant. Below a sorted gather, MergedData builds destination columns from
that header and merges the foreign states into them, and CrossTabPhiSquaredWindowData holds a Float64
where count_a sits, so HashTable::begin() dereferences a garbage pointer (fault address 0x1). The
serialized leg already reconciles exactly this in NativeReader; the in-memory leg did not, so it was also a
behaviour difference between distributed_plan_execute_locally = 1 and the serialized path. The repro is
deterministic on unpatched master, not intermittent.

One correction on the CI database, because it changes the picture. The seven pull requests you list do
have CrossTabCountsState rows on 2026-07-15 and 2026-07-16, so a text search for the function name returns
exactly them, but they are not this stack: they are 00169_contingency failing with
Code: 241 MEMORY_LIMIT_EXCEEDED, where CrossTabCountsState sits in the allocation stack
(::add -> HashTable::resize, plus ::merge in three of them). Segmentation fault (STID: 2844-4ada)
itself has exactly one occurrence in 240 days, the one you cite.

The merge frame does appear in five distinct segfault buckets in that window, one of them on master:
2844-41fc (2026-03-30, stateless flaky check), 2844-4bb5 (master, 2026-05-01, stress azure amd_tsan),
2844-3ef8 (2026-05-08, stress arm_release), 2844-3b6e (2026-07-02, stress arm_debug) and 2844-4ada. So the
family does recur, but each is a distinct signature, and I am treating 4ada as a sibling of 3b6e rather than
a recurrence of it: 3b6e was fixed by #109200 in the Variant conversion path, the three older buckets
predate that fix, and I have not attributed them.

I also ran the fix-presence probe I promised: relative to the #109200 merge commit a35bec9, the heads
behind those 2026-07 rows are all status=ahead, behind_by=0, so #109200 was already an ancestor of each.
Moot for them in any case, being memory-limit failures rather than crashes.

You are right that nothing tracked this, and I have not opened an issue.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thank you for the root cause and for the correction on the CI database rows: the 2026-07 occurrences I listed were MEMORY_LIMIT_EXCEEDED in 00169_contingency with CrossTabCountsState in the allocation stack, not this segfault, so the crash at 1029303102b1 is the only occurrence of that signature. The fix is #119401, still open at the time of writing; nothing here depends on it, since this pull request only touches FunctionToSubcolumnsPass.

This branch is now merged with master again, and the Style check failure of the previous run (the phrase "new analyzer" in a test comment) is fixed, which unblocks the dropped Bugfix validation jobs.

alexey-milovidov and others added 2 commits September 24, 2026 08:54
…nctionToSubcolumnsPass`

The first pass skipped correlated uses, but a use of the same column in the
outer query's `WHERE` puts the identifier into `filter_only`, and the second
pass then rewrote the correlated use inside the subquery's `WHERE` anyway,
recreating `NOT_FOUND_COLUMN_IN_BLOCK`. Move the stack of correlated columns
into a `CorrelatedColumnsStack` helper and consult it in both passes, and add
the mixed correlated/non-correlated `WHERE` cases to the test.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 9, 2026
The only conflict was `src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp`,
resolved to master's version: ClickHouse#118287 already fixes the same bug there,
with the correlated-column check in both passes. This branch now only adds
the regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 9, 2026
The positional, `tupleElement(o.p, 1)`, named-identifier, inner-positional
and scalar `Tuple` queries are pinned by `05090_correlated_positional_tuple_element`,
added with the fix in ClickHouse#118287. Keep only the shapes it does not cover: named
`tupleElement(o.p, 'a')`, the scope-selectivity checks, `UNION ALL`, `Variant`
and `Map`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). 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

3 participants