Skip to content

Fix NOT_IMPLEMENTED for correlated subqueries when join_algorithm lacks hash - #111093

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-103294-correlated-subquery-join-algorithm
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-103294-correlated-subquery-join-algorithm

Conversation

@groeneai

@groeneai groeneai commented Jul 20, 2026 •

Copy link
Copy Markdown
Collaborator

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 a NOT_IMPLEMENTED error ("Can't execute any of specified algorithms...") for correlated subqueries with a non-trivial correlation when join_algorithm did not include hash or parallel_hash (e.g. auto, grace_hash, partial_merge, full_sorting_merge).

Description

When a correlated subquery has a non-trivial correlation (e.g. an inequality), it is decorrelated into an internal join. With correlated_subqueries_use_in_memory_buffer enabled (the default), that internal join is restricted to hash-family algorithms so the buffered input stream is fully evaluated before the subquery runs. The restriction did this with an unconditional std::erase_if on the join's algorithm list: if the user's join_algorithm enabled neither hash nor parallel_hash, the list became empty and chooseJoinAlgorithm threw a misleading NOT_IMPLEMENTED.

The internal decorrelation join must still run in that case, so it now falls back to hash when the restriction would otherwise empty the list. Hash join always supports this join and satisfies the in-memory buffer requirement.

Reproducer (failed before, works now):

SET enable_analyzer = 1, allow_experimental_correlated_subqueries = 1, join_algorithm = 'full_sorting_merge';
SELECT number FROM numbers(2) AS t WHERE exists((SELECT number FROM numbers(2) WHERE number >= t.number));

Closes: #103294

…ks hash

A correlated subquery with a non-trivial correlation is decorrelated into an
internal join. With correlated_subqueries_use_in_memory_buffer enabled (default),
that join is restricted to hash-family algorithms via std::erase_if. When the
user's join_algorithm enabled neither hash nor parallel_hash (auto, grace_hash,
partial_merge, full_sorting_merge), the algorithm list became empty and
chooseJoinAlgorithm threw a misleading NOT_IMPLEMENTED on a valid query.

Fall back to hash join when the restriction would otherwise empty the list.
Hash join always supports this internal join and satisfies the in-memory buffer
requirement.

Closes: ClickHouse#103294

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET enable_analyzer=1, allow_experimental_correlated_subqueries=1, join_algorithm='full_sorting_merge'; SELECT number FROM numbers(2) AS t WHERE exists((SELECT number FROM numbers(2) WHERE number >= t.number)); throws NOT_IMPLEMENTED every time on master.
b Root cause explained? A non-trivial (inequality) correlation makes expression substitution fail, so referenced_input_subplan=true. With the defaults (correlated_subqueries_use_in_memory_buffer=1, correlated_subqueries_default_join_kind=RIGHT), buildLogicalJoin (PlannerCorrelatedSubqueries.cpp:594) erases every algorithm except HASH/PARALLEL_HASH. If join_algorithm has neither, the list becomes empty, so chooseJoinAlgorithm (PlannerJoins.cpp:1428) iterates zero algorithms and throws NOT_IMPLEMENTED (:1441).
c Fix matches root cause? Yes. The fix is at the site that produces the empty list: after the erase_if, if the list is empty, fall back to {HASH}. Not a band-aid: it restores the buffer optimization's intent (a hash-family algorithm that fully materializes the build side).
d Test intent preserved / new tests added? New test 04546_correlated_subquery_join_algorithm_no_hash added, covering the full triggering matrix (auto, grace_hash, partial_merge, full_sorting_merge, combinations) plus the never-affected hash/parallel_hash. No existing test weakened.
e Both directions demonstrated? Yes. clickhouse-test 04546: FAIL on unfixed binary, OK on fixed; 50/50 randomized runs pass on the fixed binary.
f Fix is general across code paths? Yes. Exactly one erase_if(join_algorithms) site exists in the file. The sibling CROSS-JOIN decorrelation branch never restricts join_algorithms (CROSS is always executed by hash join). The fix is at the origin of the empty list, not a guard at the distant throw.
g Fix generalizes across inputs? Yes. Verified across the full join_algorithm matrix (auto, grace_hash, partial_merge, full_sorting_merge, combinations lacking hash-family, and hash/parallel_hash); all succeed with correct results, hash-family paths byte-identical. Scalar correlated subquery correctness also verified.
h Backward compatible? Yes. No setting default, format, wire, or metadata change, so no SettingsChangesHistory.cpp entry. Queries that previously threw now return the correct result; previously-working queries are unchanged.
i Invariants and contracts preserved? Yes. The buffer optimization requires a hash-family algorithm that fully consumes the build side; HASH satisfies it (tryCreateJoin returns HashJoin unconditionally). setOptimized() still fires. This internal decorrelation join is synthesized, matching the established practice of not constraining these joins by user settings into an unexecutable state.

Session id: cron:clickhouse-author-slot-3:20260720-145100

@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; 2 findings across 1 full pass + 1 delta recheck; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 💡 Test opening comment restates the PR narrative in unnecessary detail (04546...sql:1-6) AGREE — fixed Trimmed the 6-line comment to 2 lines (one-line intent + issue link). Test-comment only; queries and .reference unchanged.
2 ❌ "The diff does not contain the claimed production-code fix" DISAGREE Artifact of the --delta recheck scope, which was scoped to the comment-trim commit only, so the reviewer did not see the source hunk. git show HEAD -- src/Planner/PlannerCorrelatedSubqueries.cpp contains the empty-vector {HASH} fallback (+5); the full Gate B pass reviewed the complete 3-file / 63-insertion diff. Source fix IS present in HEAD.

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-author-slot-3:20260720-145100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @yakov-olkhovskiy — could you review this? It fixes issue #103294: with the in-memory buffer opt, the internal decorrelation join is restricted to hash-family algorithms via std::erase_if, which emptied the algorithm list (and threw a misleading NOT_IMPLEMENTED) when the user's join_algorithm had neither hash nor parallel_hash. It now falls back to hash join when the restriction would otherwise leave the list empty.

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d9fd5a7]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
01666_merge_tree_max_query_limit FAIL cidb
Stateless tests (amd_tsan, s3 storage, parallel, 3/3) FAIL
02354_vector_search_quantize_codec_pq_multigranule FAIL cidb
Integration tests (amd_msan, 1/8) FAIL
test_postgresql_replica_database_engine/test_3.py::test_quoting_publication FAIL cidb
test_postgresql_replica_database_engine/test_3.py::test_single_table_engine_with_non_default_schema FAIL cidb
test_postgresql_replica_database_engine/test_3.py::test_two_schemas_same_table_name_single_storage FAIL cidb
test_postgresql_replica_database_engine/test_3.py::test_two_schemas_same_table_name_database_engine FAIL cidb
test_postgresql_replica_database_engine/test_3.py::test_default_schema_preserves_legacy_identity FAIL cidb
test_postgresql_replica_database_engine/test_3.py::test_use_extended_date_and_time_types_setting FAIL cidb
test_postgresql_replica_database_engine/test_3.py::test_use_extended_date_and_time_types_setting_table_engine_rejected FAIL cidb
test_postgresql_replica_database_engine/test_3.py::test_use_extended_date_and_time_types_setting_alter_database_rejected FAIL cidb
test_postgresql_replica_database_engine/test_3.py::test_use_extended_date_and_time_types_setting_alter_database_atomic FAIL cidb
test_postgresql_replica_database_engine/test_3.py::test_backup_database FAIL cidb
22 more test cases not shown

AI Review

Summary

This PR fixes a real planner bug in correlated subquery decorrelation: when correlated_subqueries_use_in_memory_buffer = 1 and the synthesized internal RIGHT ANY JOIN filters join_algorithms down to hash-family implementations, a user setting such as auto, grace_hash, partial_merge, or full_sorting_merge could leave the algorithm list empty and make a valid query fail with NOT_IMPLEMENTED. The fallback to JoinAlgorithm::HASH is scoped to the only buffered execution mode that exists, preserves the planner invariant that the correlated input must be fully materialized before the subquery runs, and the added stateless test covers the affected settings matrix. I did not find any remaining correctness, safety, or metadata issues in the current PR head.

Final Verdict
  • Status: ✅ Approve

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 82d7b8e

Every failure below has an owner: a fixing PR, 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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Logical error "Got read request from replica for unknown stream" (STID 5217-505b) + Server died crash (parallel-replicas reading-coordinator trunk bug; 18 unrelated PRs in 14d, cannot be caused by this correlated-subquery diff) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04507_mvt_encode_state_serialize crash victim same as above (server aborted mid-run by the STID 5217 LOGICAL_ERROR)
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) / Server died + Unknown error crash (chronic coverage/WasmEdge partial-result Int256xFloat64 abort; 251 unrelated PRs + master in 14d) #109747 (ours, open)

Session id: cron:our-pr-ci-monitor:20260720-213000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — d9fd5a7

Every failure below has an owner: a fixing PR (ours 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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit fails 3/3 reruns under parallel replicas on coverage builds #112385 (ours, merged 2026-07-29 15:37Z) - this build predates the fix
Integration tests (amd_msan, 1/8) / 32 test_postgresql_replica_database_engine/test_3.py::* tests one event, not 32: the server died and every later test in the shard failed on its own setup with Code: 210 Connection reset #112381 (external, merged 2026-07-29 01:39:36Z) - this job started 01:21:07Z, 18 minutes before the merge, so it predates the fix
Stateless tests (amd_tsan, s3 storage, parallel, 3/3) / 02354_vector_search_quantize_codec_pq_multigranule randomization-caused CANNOT_READ_ALL_DATA: the runner minimized it to merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability=0.75 plus min_columns_to_activate_adaptive_write_buffer=1 (16/16 fail with them, 18/18 pass without) a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260729-164745

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stateless tests (amd_tsan, s3 storage, parallel, 3/3) / 02354_vector_search_quantize_codec_pq_multigranule failure on this pull request: #112818 (external, open).

It corrects the read bound of the per-part product quantization codebook, which is the Cannot read all data of type FixedString. Bytes read:49152. String size:65536 that failure reports. Unrelated to this pull request, whose diff touches only the correlated-subquery planner and its own stateless test.

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 4, 2026
@PedroTadim

Copy link
Copy Markdown
Member

This PR is no longer needed

@PedroTadim PedroTadim closed this Oct 9, 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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

std::erase_if on join_algorithms may empty the list, causing NOT_IMPLEMENTED exception on valid correlated subqueries

4 participants