Skip to content

Leave a correlated subquery alone when it is resolved from the cache - #118321

Merged
alexey-milovidov merged 6 commits into
masterfrom
correlated-scalar-subquery-twice-111937
Sep 26, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
correlated-scalar-subquery-twice-111937

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

A correlated scalar subquery is no scalar the analyzer can evaluate - the planner decorrelates it - so where the analyzer resolves such a subquery for the first time it skips the scalar evaluation. The path that answers from the already-resolved-expression cache did not, and the second occurrence of one subquery in a single expression went through it:

CREATE TABLE t (id UInt32) ENGINE = MergeTree ORDER BY id;
INSERT INTO t SELECT number FROM numbers(10);

SELECT o.id, if(1 = 1, (SELECT count() FROM t AS i WHERE i.id = o.id),
                       (SELECT count() FROM t AS i WHERE i.id = o.id))
FROM t AS o SETTINGS allow_experimental_correlated_subqueries = 1;
-- Code: 36. DB::Exception: Cannot evaluate correlated scalar subquery. (BAD_ARGUMENTS)

The same subquery under a non-constant condition, or added to itself, resolves without hitting that path and always worked. The cached path now applies the same test as the first resolution does.

Closes: #111937

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 Cannot evaluate correlated scalar subquery for a query that uses one correlated scalar subquery twice in the same expression, for example in both branches of if(1 = 1, ..., ...).


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

Version info

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

A correlated scalar subquery is no scalar the analyzer can evaluate - the
planner decorrelates it - so where the analyzer resolves such a subquery for
the first time it skips the scalar evaluation. The path that answers from the
already-resolved-expression cache did not, and the second occurrence of one
subquery in a single expression went through it:

    SELECT o.id, if(1 = 1, (SELECT count() FROM t AS i WHERE i.id = o.id),
                           (SELECT count() FROM t AS i WHERE i.id = o.id))
    FROM t AS o SETTINGS allow_experimental_correlated_subqueries = 1;

    Code: 36. Cannot evaluate correlated scalar subquery

The same subquery under a non-constant condition, or added to itself, resolves
without hitting that path and always worked. The cached path now applies the
same test as the first resolution does.

Closes: #111937

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 [9d69c58]

Summary: ✅


AI Review

Summary

This PR fixes the cache-hit path in QueryAnalyzer::resolveExpressionNode so a correlated subquery that has already been resolved is not sent through evaluateScalarSubqueryIfNeeded on a later occurrence. That matches the first-resolution path, avoids the Cannot evaluate correlated scalar subquery exception described in the PR, and the new stateless test covers the constant-if/multiIf regression plus sibling repeated-subquery shapes. I did not find a correctness, compatibility, or test-coverage issue in the current diff.

Final Verdict

✅ No blocking issues found.

LLVM Coverage Report

Measured on commit 9d69c58.

Metric Baseline Current Δ
Lines 88.10% 88.20% +0.10%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 7/10 (70.00%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 9d69c58eb615cd6aa52cb88d68624698e0c2875f 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 04:18
Correlated subqueries exist only in the analyzer, so in the `old analyzer` job
the test failed with `Missing columns: 'o.id'` from
`ExecuteScalarSubqueriesVisitor`. Set `enable_analyzer` in the test, as the
sibling correlated-subquery tests do, so it keeps exercising the analyzer path
there instead of being skipped.

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

Copy link
Copy Markdown
Member Author

🕵 The two AST fuzzer failures on 518eff24 are unrelated to this change (it only touches correlated-subquery resolution in QueryAnalyzer) and both already have tracking issues:

@groeneai, could you take a look at the oracle mismatch and provide a fix in a separate PR if the existing issue does not already cover it? Please link it here.

The Stateless tests (amd_llvm_coverage, old analyzer, ...) failure was ours and is fixed: correlated subqueries exist only in the analyzer, so the test now sets enable_analyzer like the sibling correlated-subquery tests do. Master was also merged in.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged, I am investigating the AST fuzzer (amd_release, oracle) mismatch and will follow up here with a PR or with my findings.

One measured note so the coverage question is not left implicit: the failing statement is 02346_text_index_partially_materialized.sql:101, whose index is text(tokenizer = ngrams(3), support_phrase_search = 0, ...) with no postprocessor, while #117075 and its fix #119367 are specifically the postprocessor path. So I am testing whether the two share a mechanism rather than assuming it. The clean fixture on master agrees at 20 on every path I tried (index, not(not(p)), use_skip_indexes = 0, query_plan_direct_read_from_text_index = 0, use_skip_indexes_on_data_read = 0), so the divergence needs some part of the fuzzer's state or settings, and that is what I am binding now.

@groeneai

Copy link
Copy Markdown
Collaborator

On the coverage question: #117075 and its fix #119367 do not cover this one.

The failing statement is 02346_text_index_partially_materialized.sql:101, over an index declared text(tokenizer = ngrams(3), support_phrase_search = 0, posting_list_block_size = 10000000, posting_list_codec = 'none'), i.e. no postprocessor. Every hunk #119367 changes in optimizeDirectReadFromTextIndex.cpp is inside if (apply_postprocessor), and apply_postprocessor = needApplyPostprocessor(function_name) && has_postprocessor with has_postprocessor = postprocessor && postprocessor->hasActions() (:752, :759, :835). Its other two non-test files only add a drop_empty_tokens parameter defaulted to false and reached solely from that branch. So on this fixture none of that code runs, and the shape is a different one: an index that cannot answer a phrase query at all, rather than one whose postprocessed tokens are rejoined wrongly.

What I have so far on the mismatch itself, so the state is not misread as unowned: it does not reproduce on master. Replaying the fixture with the 569 non-default session settings from the job's own dump, both arms and p AND 1 / p OR 0 return 20, as does the same data with use_skip_indexes = 0, and ProfileEvents['TextIndexReadPostings'] is 16 on all four arms (8 phrase tokens times 2 parts), so the index path is genuinely exercised and the agreement is not vacuous. A sweep of index_granularity over 1, 2, 8, 64, 1024, 8192, 65536 crossed with compact and wide parts is 20 everywhere too, and 150 repetitions of each arm produced no divergence. That leaves the amd_release build and the fuzzer session's accumulated state as the remaining differences from the job, which is where I am looking next.

I will open a separate PR against master and link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

On the mismatch itself: it is a real wrong-results bug, and it is already fixed on master by your #116381, which merged about 90 minutes after this run. So no separate PR from me, and I am withdrawing the one I said I would open.

What the arm actually returned, from the job's own server.log.zst (lines 965196-965327, query id 22038b27-fb62-4c5a-8abc-353416a2fd13): reference 30, not(not(p)) 0, p AND 1 30, p OR 0 30, with all four reading the same 3000 rows from three parts. So NOT(NOT p) was the wrong arm, not the reference, and the exception's row counts (1 and 1) hide that because count() always returns one row.

Mechanism, since it is not the obvious one. hasPhrase with two arguments tokenizes with splitByNonAlpha (src/Functions/hasPhrase.cpp:187), under which 'ello50 wor' is not a token phrase of 'hello50 world50', so it is false on every row. The index tokenizer only reaches the row-level function as an injected third argument, from processAndOptimizeTextIndexFunctions. Before #116381, cloneDAGWithInversionPushDown cancelled a pair of not unconditionally, so selectConditions (optimizeDirectReadFromTextIndex.cpp:633) saw not(not(hasPhrase(...))) as a text-search atom and made that node itself a replacement key; replaceNodes returns early for a key without descending into its children (:132-135), so the injected hasPhrase(text, 'ello50 wor', 'ngrams(3)') never became the executed predicate and the bare two-argument form ran instead. Your boolean_context || !need_inversion guard leaves the inner not opaque, that node stops being a replacement key, and the inner hasPhrase is rewritten normally.

Timing and CIDB agree with that. 518eff24 is 639 commits behind 8696d4ff and does not contain it. This exact signature appears 3 times in the 30 days I checked, all before the merge (2026-08-30 on #114577, 2026-09-03 on #117590, and this one), and 0 times in the 1645 oracle-arm runs since, which had no Identity WHERE mismatch of any kind.

One thing that may be worth your time: this text-index symptom is a second, independent consequence of that root cause, and 05043_not_in_value_position_key_condition pins only the index-analysis one. I can send a test-only PR asserting the hasPhrase identity over a support_phrase_search = 0 text index if you want that path covered too.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118321&sha=518eff241122633d224affa709900640c1544c07&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, thanks for the thorough root cause. Agreed that it is the double-not cancellation fixed by #116381 and not the postprocessor path of #117075, and that #119367 does not cover it.

Yes, please send the test-only PR asserting the hasPhrase identity over a support_phrase_search = 0 text index. 05043_not_in_value_position_key_condition pins only the index-analysis consequence, so the direct-read rewrite deserves its own pin. Link it here when it is up.

Status of this PR: the two remaining reds on ea765ad0 (03100_lwu_deletes_4_index in the amd_debug, parallel and amd_tsan, s3 storage jobs, read_rows of 0 instead of 8 under min_bytes_for_wide_part = 0 + patch_parts_version = 'v1') are the accounting defect fixed by #119400, which merged on 2026-09-12. Master is merged in as of c0d7b2c8, so they should clear on the next run. The PR itself is unchanged: QueryAnalyzer.cpp plus the 05095 test, which still passes locally on the merged tree.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. It will be test-only, with no src/ change: the arms p vs NOT(NOT p) over text(tokenizer = ngrams(3), support_phrase_search = 0) with no postprocessor, so what gets pinned is the direct-read rewrite rather than the index-analysis consequence that 05043_not_in_value_position_key_condition already covers. I will confirm the oracle reddens on a pre-#116381 tree before sending it, and link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

#120836.

As promised before sending it, the oracle reddens on a pre-#116381 tree: with that one line reverted locally, not not p and prewhere not not p report 0 instead of 10 (20 of 20 randomized runs failed), while 50 of 50 randomized runs pass on master.

pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Sep 19, 2026
`AST fuzzer (amd_release, oracle)` on ClickHouse#118321 reported an `Identity WHERE (NOT(NOT p))` mismatch
seeded from `02346_text_index_partially_materialized.sql`: `hasPhrase(text, 'ello50 wor')` counted
30 rows while `NOT (NOT hasPhrase(text, 'ello50 wor'))` counted 0.

`hasPhrase` with two arguments tokenizes with `splitByNonAlpha`, under which `'ello50 wor'` is not a
phrase of `'hello50 world50'`; the index tokenizer reaches the row-level function only as a third
argument injected by `processTextIndexFunction`. Because the index declares
`support_phrase_search = 0`, `getDirectReadMode` returns `Hint`, the only mode that keeps the
original predicate beside the index virtual column, so that injection is observable. Before ClickHouse#116381,
index analysis cancelled a pair of `not` unconditionally, so `not(not(hasPhrase(...)))` canonicalised
to the bare atom, the outer `not` node became the replacement key, and `replaceNodes` returned early
on it without descending into its children, so the injected three-argument call never reached the
executed predicate. `EXPLAIN actions = 1` shows both sides:

  before  Filter column: __text_index_idx_hasPhrase_5d43... AND NOT NOT hasPhrase(text, 'ello50 wor')
  after   Filter column: NOT NOT (__text_index_idx_hasPhrase_5d43... AND hasPhrase(text, 'ello50 wor', 'ngrams(3)'))

ClickHouse#116381 fixed this on master by blocking only the unsound half of the cancellation, so this commit
adds no source change. `05043_not_in_value_position_key_condition` pins the index-analysis consequence
of that fix; the direct-read rewrite had no test of its own. `hasAnyTokens` and `hasAllTokens` take
the same injected tokenizer argument, but over a plain text index `getDirectReadMode` gives them
`Exact` mode, which drops the original predicate, so this seam is reachable only for a non-positional
`hasPhrase` and no sibling arm is added.

With the one line of ClickHouse#116381 reverted locally, `not not p` and `prewhere not not p` report 0 instead
of 10 (20 of 20 randomized runs fail); on master 50 of 50 randomized runs pass.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118321&sha=518eff241122633d224affa709900640c1544c07&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29
Related: ClickHouse#118321
Related: ClickHouse#116381

Co-Authored-By: Claude Opus 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118321&sha=d13d44ffd9c9a4266b597efc01539ad75b751bf0&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%202%2F6%29 (test_storage_nats/test_nats_jetstream_credentials_rotation.py::test_jetstream_unacked_messages_survive_rotation, return code 153) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is unrelated to this PR, which only touches correlated-subquery resolution in QueryAnalyzer. The other red, Build profile diff, was a CI logs cluster query error (infrastructure). I merged master (9d69c58eb615); 05095_correlated_scalar_subquery_twice passes locally on the merged tree.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. This is the EINTR signature that your own #120202 fixed, observed on a tree that predates it, so there is no new PR from me.

  • The red is Code: 665 ... Cannot connect to Nats last error: (unix/sock.c:56): poll error: 4. Return code 153 is not a module-level death: it is 665 % 256, the client exit status truncated to POSIX range. praktika labelled the result retry_ok (it passed on retry) and had already matched it to Flaky test: test_storage_nats/test_nats_jetstream_credentials_rotation.py — Cannot connect to Nats ... poll error: 4 #120201.
  • Fix-presence measured on the tree rather than by timestamp: d13d44ff pins contrib/nats-io at 3e3a3f10, and b3bd92eaff7c is not an ancestor of it (merge base 0b3b89d0, 2026-09-19 18:34:46Z, 1253 commits behind). Master and your current head 9d69c58e pin b88704df, which has the retry.
  • The reported line number is an independent check. In 3e3a3f10, nats_setError(NATS_IO_ERROR, "poll error: %d", ...) is src/unix/sock.c:56, exactly what the stack prints. In b88704df that call is line 64, and EINTR can no longer reach it because poll is retried in the new do/while. So sock.c:56 together with errno 4 can only come from the pre-bump submodule.
  • In the CI database, after the Retry poll on EINTR in the vendored nats-io client #120202 merge there are three poll error rows of any errno, all of them sock.c:56 with errno 4, the last at 2026-09-21 22:31:08, on heads pinning 3e3a3f10 or the older cf441828. None reports the post-bump line sock.c:64, and neither rotation test has a FAIL or ERROR row after that one.

Your master merge already moved the pin to b88704df, so the current head carries the retry.

@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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
Merged via the queue into master with commit e57232c Sep 26, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the correlated-scalar-subquery-twice-111937 branch September 26, 2026 06:12
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 26, 2026
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