Skip to content

Fix ChunkBuffer logical error in correlated subquery with join_kind = left - #108272

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-correlated-subquery-left-join-chunkbuffer
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-correlated-subquery-left-join-chunkbuffer

Conversation

@groeneai

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):

Fix Logical error: Trying to extract chunk from ChunkBuffer before all inputs are finished for correlated subqueries decorrelated with correlated_subqueries_default_join_kind = 'left' inside a set operation (INTERSECT/UNION) when correlated_subqueries_use_in_memory_buffer = 1.

Description

Found by the AST fuzzer (AST fuzzer (amd_debug, targeted)), STID 2651-2cfd.
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108242&sha=fd6fd0abc33aecc2b385c994b2d87c98f53ed3b0&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

Decorrelation of a correlated subquery builds a result JOIN. When the subquery input is buffered in memory (correlated_subqueries_use_in_memory_buffer), the buffer consumer (ReadFromCommonBuffer) may only read after the producer (SaveSubqueryResultToBuffer) has finished. That holds only when the input is on the build side of the result join, i.e. join_kind = right. For join_kind = left the input is on the probe side, so the consumer can start before the producer finished and the query aborts with the logical error above.

The buffer-vs-materialize choice was derived from the optimizer flag which folds in the top-level correlated_subqueries_default_join_kind == right. That top-level value does not reflect the per-branch SETTINGS of a set operation, so a branch decorrelated as left was still buffered. Single-statement left queries materialized correctly; only set-operation branches with a per-branch left setting hit the bug.

The fix decides materialization per decorrelation: a reference built for a left-join decorrelation is flagged to be materialized (never buffered), independently of the global setting. The right-join buffer path is unchanged.

This is the surviving manifestation of the bug class from #96445 / #103322 (which fixed the join-size-limit / break-mode case); this PR fixes the join_kind = left ordering case.

A regression test asserts via EXPLAIN PIPELINE that a left-join decorrelation branch no longer contains ReadFromCommonBuffer, that the right-join branch still does, and that the query executes without the logical error.

… left

Decorrelation of a correlated subquery builds a result JOIN. When the input
stream is buffered in memory (correlated_subqueries_use_in_memory_buffer), the
buffer's consumer (ReadFromCommonBuffer) may only read after the producer
(SaveSubqueryResultToBuffer) has filled it. This holds only when the subquery
input is on the build side of the result join, i.e. join_kind = right. For
join_kind = left the input ends up on the probe side, so the consumer can start
before the producer finished and aborts with:

  Logical error: Trying to extract chunk from ChunkBuffer before all inputs are finished

The buffer-vs-materialize choice was derived from the optimizer flag
correlated_subqueries_use_in_memory_buffer, which folds in the top-level
correlated_subqueries_default_join_kind == right. That top-level value does not
reflect the per-branch SETTINGS of a set operation (INTERSECT/UNION): a branch
decorrelated as join_kind = left was still buffered because the outer plan was
optimized with the default (right). Single-statement left queries materialized
correctly; only set-operation branches with a per-branch left setting hit the bug.

Decide materialization per decorrelation instead of from the global flag: a
CommonSubplanReferenceStep built for a left-join decorrelation is flagged to be
materialized, and is materialized before the buffer optimization regardless of
the global setting. Producers that still have a buffered reference are kept.

The right-join buffer path is unchanged.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. The exact AST-fuzzer reproduce commands (two _part_offset-projection tables INTERSECT-ed, each branch a scalar correlated subquery with per-branch SETTINGS correlated_subqueries_default_join_kind = 'left', correlated_subqueries_use_in_memory_buffer = 1) abort with Trying to extract chunk from ChunkBuffer before all inputs are finished 10/10 runs on a debug build. Flipping the branch setting to 'right' is OK 8/8.
b Root cause explained? Decorrelation builds a result JOIN. The buffer consumer (ReadFromCommonBuffer) may only read after the producer (SaveSubqueryResultToBuffer) finished, which holds only when the input is on the build side, i.e. join_kind = right. For join_kind = left the input is on the probe side, so the consumer extracts before the producer finished (unfinished_inputs != 0) and ChunkBuffer::extractNext() throws. The buffer-vs-materialize choice was derived from the optimizer flag folding in the top-level correlated_subqueries_default_join_kind == right, which does not reflect the per-branch SETTINGS of a set operation; so a branch decorrelated as left was still buffered.
c Fix matches root cause? Yes. The decision is now made per decorrelation from the actual branch join kind: a reference built for a left-join decorrelation is flagged and materialized before the buffer optimization, independently of the global setting. Not a symptom guard.
d Test intent preserved / new tests added? New regression test 04401_correlated_subquery_left_join_no_buffer added: asserts via EXPLAIN PIPELINE that the left-join branch contains no ReadFromCommonBuffer, that the right-join branch still does, and that the query executes without the logical error. No existing test weakened; the right-join buffer path is unchanged.
e Both directions demonstrated? Yes. The new test's EXPLAIN buffer-node count is 2 (buffer wrongly used) on the unfixed binary and 0 (materialized) on the fixed binary; the verbatim fuzzer query goes from 10/10 ChunkBuffer aborts (unfixed) to 0 (fixed). Existing correlated-subquery/buffer tests (04108, 04110, 03808, 03701, 03545) pass with the fix.
f Fix is general, not a narrow patch? Yes. The fix targets the buffer-vs-materialize decision itself (both the planner flag and the optimizer's materialize/cleanup passes), so it covers every correlated-subquery shape that takes the left-join + in-memory-buffer path, not just the fuzzer's query. The symmetric right path is intentionally left as-is (it is safe). Note: queries with a _part_offset-projection leak also hit a separate, pre-existing column-mismatch logical error (Invalid number of columns ... Expected 2, found 4) on the left path independent of the buffer; that is a distinct bug, out of scope here.

Session id: cron:clickhouse-worker-slot-3:20260623-072200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @KochetovNicolai — could you review this? It fixes the ChunkBuffer: before all inputs are finished logical error (STID 2651-2cfd) for correlated subqueries decorrelated with correlated_subqueries_default_join_kind = 'left' inside a set operation. The buffer-vs-materialize choice was taken from the optimizer flag that folds in the top-level ...default_join_kind == right, which misses a per-branch left setting in an INTERSECT/UNION branch, so a left-join branch (subquery input on the probe side) was buffered and could read before the producer finished. The fix decides materialization per decorrelation from the actual branch join kind; the right-join buffer path is unchanged.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6eef11f]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_tsan, 3/6) FAIL
test_executable_udf_profile_events/test.py::test_peak_memory_is_max_not_sum FAIL cidb

AI Review

Summary

This PR fixes the ChunkBuffer logical-error exception for left decorrelation inside set-operation branches by carrying the per-decorrelation materialization requirement on CommonSubplanReferenceStep, materializing those references before the buffer optimization, and preserving still-buffered right references until useMemoryBufferForCommonSubplanResult. I did not find a blocker or major correctness issue in the current diff.

Missing context / blind spots
  • ⚠️ I did not run the new stateless test locally because no clickhouse binary is present under the usual build directories; the Praktika PR report currently shows no failed tests.
Final Verdict

✅ No inline findings to post.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.50% 92.60% +0.10%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 50/53 (94.34%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI summary (head 6eef11f)

CI finished. One test failure, not caused by this PR:

The CH Inc sync / Mergeable Check rollup states are the internal-sync / aggregator reflection of that single flaky and an external infra check (fork PRs cannot satisfy CH Inc sync); no other test failed.

Session id: cron:our-pr-ci-monitor:20260623-170000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing in favor of #108554, which fixes the same bug (ChunkBuffer LOGICAL_ERROR for correlated_subqueries_default_join_kind = 'left' inside a set operation, STID 2651-2cfd / #108521) with a smaller, more general change.

#108554 forces the no-swap JoinKind::Right layout for buffered inputs and reads the buffer decision from the top-level query context, so it also covers correlated_subqueries_use_in_memory_buffer = 0 placed in a per-branch SETTINGS clause (which still creates a buffer). #108554 is mergeable and under review; this PR is a superseded, heavier approach that now conflicts with master.

@groeneai groeneai closed this Jul 16, 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 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