Repository navigation
Fix logical error in correlated subquery decorrelation with set operations - #108554
alexey-milovidov merged 26 commits into
Conversation
…tions A set operation (INTERSECT / UNION ALL / EXCEPT) whose branches reference correlated subqueries shares the input subplan through an in-memory producer/consumer buffer: SaveSubqueryResultToBuffer fills it and ReadFromCommonBuffer reads it, and the consumer may only run once every producer stream has finished. The decorrelation result join in buildLogicalJoin was built using correlated_subqueries_default_join_kind. With 'left' the buffer producer (the input stream) ended up on the join's probe side, so when a set operation placed the consumer on the build side of an enclosing join the consumer read the buffer before the producer finished and the server aborted with: Logical error: Trying to extract chunk from ChunkBuffer before all inputs are finished Keep the buffered (referenced) input on the build side regardless of the requested join kind, so the producer is always fully evaluated first. The decorrelation join kind is an internal detail and does not change the result. Closes: ClickHouse#108521 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-3:20260625-195800 |
|
cc @novikd @vdimir — could you review this? It fixes the |
|
Workflow [PR], commit [ab032c8] Summary: ✅
AI ReviewSummaryThis PR hardens correlated-subquery decorrelation when set-operation branches share the outer input through a Findings💡 Nits
Final Verdict✅ No blocking issues in the current patch; the remaining concern is the non-blocking docs clarification above. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 42/42 (100.00%) · Uncovered code |
…gression test The reviewer asked to also cover the use_in_memory_buffer = 0 variant named in issue ClickHouse#108521. With the buffer disabled the optimizer's materialization pass (materializeQueryPlanReferences) inlines the shared subplan reference before useMemoryBufferForCommonSubplanResult runs, so no ChunkBuffer is created and the ordering invariant cannot be violated. The added queries assert that the disabled-buffer variant returns the same rows as the buffered case, and pin enable_parallel_replicas = 0 (as the sibling decorrelation test 03734 does) so the per-part _part_offset row counts stay deterministic under CI randomization. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
CI note: the |
This PR forces JoinKind::Right for buffered correlated-subquery decorrelation (the ChunkBuffer ordering fix). The decorrelation join kind is an internal detail, but it changes the build side of the join, so the row order of these IN->JOIN rewrite results (which had no ORDER BY) is no longer guaranteed and the test became flaky under parallel execution. Add ORDER BY number to the multi-row result queries. The verified result values are unchanged (the .reference numeric output is identical, only the echoed SQL lines gain the ORDER BY clause); only the row order is now deterministic. This also fixes the test's pre-existing non-determinism, which already failed under randomized max_block_size on master regardless of this PR. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Follow-up after the Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260626-003900 |
CI finish ledger — bdbb857Every 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
Session id: cron:our-pr-ci-monitor:20260626-050000 |
…related-subquery-left-join # Conflicts: # tests/queries/0_stateless/03583_rewrite_in_to_join.reference # tests/queries/0_stateless/03583_rewrite_in_to_join.sql
The previous fix read correlated_subqueries_use_in_memory_buffer from the per-branch planner context to decide buffered_input. The optimizer, however, decides buffer-vs-materialize once for the whole plan from the top-level query context (QueryPlanOptimizationSettings: use_in_memory_buffer && default_join_kind == RIGHT). A set-operation branch's own SETTINGS clause never reaches that pass, so when a branch set correlated_subqueries_use_in_memory_buffer = 0 the join was built with buffered_input == false (plain LEFT layout, ordering protection skipped) while the optimizer still created a ChunkBuffer, re-triggering the "Trying to extract chunk from ChunkBuffer before all inputs are finished" LOGICAL_ERROR from issue ClickHouse#108521. Mirror the optimizer's condition exactly: read the setting from the top-level query context (reachable via Context::getQueryContext()) and require default_join_kind == RIGHT, so the safe Right (no-swap) layout and the hash-only ordering protection fire whenever a buffer is actually created, regardless of how the setting was applied. Session-level use_in_memory_buffer = 0 reaches the materialization pass, no buffer is created, and the plain LEFT layout is kept (so 03701 is unaffected). Extend 04411 to cover the per-branch SETTINGS form from ClickHouse#108521 in addition to the session-level and default forms. Closes ClickHouse#108521
|
@groeneai could you make comment in the PR a bit more straightforward and short so it's easier to read. It should not be ad-hoc comments to justify workarounds, only necessary ones to document tricky logic, otherwise change should have clear purpose |
Shorten the buffered_input comment in buildLogicalJoin and the 04411 test header to document only the tricky logic (the layout must follow the top-level buffer decision); the mechanism and motivation are in the commit message and PR description. No behavior change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@vdimir done. Trimmed the in-code comments in |
Decide once, in decorrelateQueryPlan, whether the referenced input subplan will be turned into an in-memory ChunkBuffer, and pass that decision to buildLogicalJoin instead of re-deriving it from settings there. The optimizer buffers the referenced subplan when the top-level query context has correlated_subqueries_use_in_memory_buffer = 1 and correlated_subqueries_default_join_kind = RIGHT (QueryPlanOptimizationSettings). buildLogicalJoin previously re-read those settings to decide the join layout; a set-operation branch's own SETTINGS clause changes the per-branch reads but never reaches the top-level buffer decision, so the two could disagree and the layout could skip the JoinKind::Right protection while a buffer was still created, re-triggering the ChunkBuffer "before all inputs are finished" logical error (issue ClickHouse#108521). Recording the decision at its source (alongside referenced_input_subplan, reading the top-level context the optimizer uses) keeps the layout and the buffer in sync for every placement of the setting. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger — 72f94a3Every failure below has an owner: a fixing PR (ours or external), or the private sync check. No PR-caused failures (this PR's diff is
Session id: cron:our-pr-ci-monitor:20260630-203000 |
|
@groeneai, please update the branch, as all the fixes for unrelated failures are merged. |
|
Branch updated: merged master ( Both fixes for the reds the last ledger recorded are now ancestors of the new head: #112385 ( |
CI finish ledger - da3d895Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be
On the arm_darwin line: #112267 is not its owner. That fix is already present in this build Session id: cron:our-pr-ci-monitor:20260731-230000 |
CI finish ledger - 06ffae7Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Neither test is in this PR's diff, which is 4 files confined to correlated-subquery planning, and neither exercises that code path. A 7 day CIDB sweep keyed on The other 173 checks are green (155 success, 18 skipped) and both aggregators, Config Workflow and Finish Workflow, completed successfully. Session id: cron:our-pr-ci-monitor:20260801-073000 |
…related-subquery-left-join
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 40/40 (100.00%) · Uncovered code |
CI finish ledger - 409f58eEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260801-230000 |
|
Fixing PR for the pre-auth That PR reapplies #110760 (reverted in #112935) together with the fix: |
…related-subquery-left-join
…decorrelation join The buffered path filtered the internal decorrelation join's `join_algorithms` down to `hash` / `parallel_hash`, but never inserted one. With a user `join_algorithm` of `auto` or a merge-only list nothing survived the filter and `chooseJoinAlgorithm` threw `NOT_IMPLEMENTED` (`Can't execute any of specified algorithms...`), so the reproducer from ClickHouse#108521 was still user-visibly broken for a supported setting combination. This join is an internal decorrelation detail, so the public setting must not decide whether it can run at all: force `hash` / `parallel_hash` when the filter leaves the list empty. Extend `04411_chunk_buffer_correlated_subquery_set_operation` with the `join_algorithm = 'auto'` and merge-only (`full_sorting_merge`) cases, asserting the same rows and the same forced RIGHT layout.
The commit 5bcd0e3 was meant to touch only `PlannerCorrelatedSubqueries.cpp` and the `04411_chunk_buffer_correlated_subquery_set_operation` test, but it also swept in 54 unrelated untracked files from the worktree (including a 21 MB binary test artifact). None of them exist on master; this removes them all, restoring the intended 4-file PR diff. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 The previous commit |
|
Confirmed, and thanks for the cleanup. I verified One correction on the cause, because it changes the fix. These were not untracked leftovers in the worktree. All 54 paths are absent from every commit I authored (checked per path against my last one, So the mechanism is a stale base rather than a broad The guard I am adopting is therefore not a cleanliness check but a base check: assert the committed file list equals the intended set before pushing, and reconcile the tree against current master first, since a stale tree resurrects deleted paths silently while |
CI finish ledger - ab032c8Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260804-043000 |
|
Hi — this looks like a backport candidate for |
|
The finding reproduces, but the affected set is four branches, not two: 26.3, 26.5, 26.6 and 26.7. 25.8 is not affected. I ran this PR's own
The exception on all four is the one from #108521: 25.8 does not have the feature: Portability: @alexey-milovidov could you apply |
|
Following up on the two Root cause was not in either test: |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a
LOGICAL_ERROR("Trying to extract chunk from ChunkBuffer before all inputs are finished") when a set operation (INTERSECT/UNION ALL/EXCEPT) combines branches that use correlated subqueries andcorrelated_subqueries_default_join_kind = 'left'.Description
Closes: #108521
A set operation over correlated subqueries shares the input subplan through an in-memory buffer (
SaveSubqueryResultToBufferwrites,ReadFromCommonBufferreads). The reader must run after every writer stream finished, which onlyJoinKind::Rightguarantees. The decorrelation join usedcorrelated_subqueries_default_join_kindto pick the layout, so'left'could place the reader before the writer and abort the server.Fix: when the referenced input is buffered, force the
JoinKind::Right(no-swap) layout. The join kind is an internal detail and does not change the result. Whether a buffer is created is decided once from the top-level query context, so the layout reads the setting from there too; this coverscorrelated_subqueries_use_in_memory_buffer = 0placed in a per-branchSETTINGSclause, which still creates a buffer.This is a pre-existing trunk bug (
allow_experimental_correlated_subqueriesis on by default in 26.6); it recurs on master under the AST fuzzer (STID 2651-2cfd). Reproducer:CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108242&sha=fd6fd0abc33&name_0=PR (STID 2651-2cfd).
Regression test:
04411_chunk_buffer_correlated_subquery_set_operation.