Repository navigation
Make correlated-subquery decorrelation joins ignore user join size limits - #103322
KochetovNicolai merged 1 commit into
Conversation
Pre-PR validation gate
Session id: cron:clickhouse-ci-task-worker:20260422-044500 |
|
cc @novikd @vdimir — could you review this? The fix makes |
|
Workflow [PR], commit [583af10] Summary: ✅
AI ReviewSummaryThis PR makes the internal joins created by correlated-subquery decorrelation ignore user Final VerdictStatus: ✅ Approve |
…ds=1 hang Addresses review feedback on PR ClickHouse#103322. The previous iteration made `ChunkBuffer::extractNext` block on a condition variable until all writers signalled `onInputFinish`. That violated the processors-framework contract that synchronous `work` must not wait: with `max_threads = 1` the reader thread would park inside `work` and leave nobody to run the `SaveSubqueryResultToBufferTransform` writers whose `onInputFinish` it was waiting for. Replace the blocking wait with an `eventfd`-based async notification: - `ChunkBuffer` (Linux): one `eventfd` per registered reader. `notifyReadyLocked` writes every `eventfd` when `unfinished_inputs` reaches zero or the buffer is cancelled. `extractNext` no longer blocks; the reader is only called after the executor has delivered the readiness notification. - `ReadFromCommonBufferSource` (Linux): overrides `prepare` to return `Status::Async` while the buffer is not ready, and `schedule` to hand the executor the `eventfd`. The executor parks the source on epoll and is free to run the writers on the same thread, so `max_threads = 1` cannot deadlock. The readiness notification is consumed exactly once, after which subsequent `prepare` cycles go through the normal `ISource::prepare` path. - Each reader needs its own `eventfd` because `epoll_ctl(EPOLL_CTL_ADD, fd, ...)` fails with `EEXIST` on a duplicate registration, and `ReadFromCommonBufferStep::initializePipeline` creates `max_streams` of them. - Non-Linux platforms keep the condition-variable fallback; the processors executor has no epoll-based async path there and the CI configurations that exposed the original race (AST fuzzer under MSan/ASan/TSan) run only on Linux. Add `tests/queries/0_stateless/04110_chunk_buffer_max_threads_1.sql` to cover the single-worker-thread scenario the reviewer asked about. A regression that reintroduced a blocking wait inside synchronous processor `work` would time out on that test instead of finishing. Verified locally: without any fix the existing 04108 test trips `LOGICAL_ERROR: Trying to extract chunk from ChunkBuffer before all inputs are finished (unfinished inputs: 1)` on 26.5.1.1; with this fix 04108 + 04110 pass 30/30 iterations and the existing `03315`/`03399`/`03400`/`03408`/`03411` correlated-subquery tests still pass. Bug: ClickHouse#96445
|
Addressed the deadlock concern in commit 32dcb2c by moving the reader off the synchronous What changed
New low-thread coverage Pre-PR validation
Session: |
- `Thread pool` → `thread pool` (line 31). - `must not crash` → `must not throw an exception` (line 92), matching the exception-based failure mode described in CLAUDE.md. No behavioural change. Follow-up to PR ClickHouse#103322. Session: cron:clickhouse-ci-task-worker:20260422-184500
`04108_chunk_buffer_reader_writer_race` and `04110_chunk_buffer_max_threads_1` both rely on the scalar correlated subquery `(SELECT arr WHERE 7)` that scope- captures a column of the outer table. Correlated subqueries are only supported by the new analyzer. Under the `amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel` CI profile the users' config file sets `allow_experimental_analyzer = 0`, so the query fails with `Code 47 - Missing columns: 'arr'` before the race path is even reached. Add `SET enable_analyzer = 1;` at the top of both tests so the profile default is overridden for this session. The rest of the behaviour (randomised merge-tree settings, the race and the `max_threads = 1` hang checks) is unchanged. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103322&sha=14836f88a5aabbd5e03374fdd44c1a1ec87326c2&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DatabaseReplicated%2C%20WasmEdge%2C%20parallel%29 PR: ClickHouse#103322
|
Pushed v3 commit Problem: The v2 commit added Fix: Add Pre-PR validation gate
No code changes — only the two test files modified. |
Address clickhouse-gh[bot] review (ClickHouse#103322, comment 3127588417): > If `setInputsNumber(0)` happens later (after readers are registered), Linux > readers will see `isReady()==true` in `prepare` and immediately call > `consumeReaderFd`, but no notification was ever written for that reader, so > `read` can block. Take the lock in `setInputsNumber` and call `notifyReadyLocked` when the update puts the buffer into a terminal state — either `isReadyLocked() == true` (`num == 0`) or `cancelled == true`. With the existing `registerReader` check and `onInputFinish` / `cancel` notification paths, a reader now observes the buffer's readiness regardless of the ordering between its own registration and the `setInputsNumber` call. Also refresh the `registerReader` header comment so it documents the broader "safe from either side of the `setInputsNumber` boundary" invariant instead of implying a strict ordering constraint that is no longer required. No change for the common path where `num >= 1`: writers decrement `unfinished_inputs` and the final `onInputFinish` triggers the notification as before. The fix only matters for the `num == 0` / post-cancel edge, where the previous code silently dropped the notification. Verified locally: 04108 and 04110 pass 50 iterations each under the Linux debug build alongside 03808 and the 03315/03399/03400/03408/03411/03412/03413/03414/ 03522/03533/03538 correlated-subquery regression suite.
|
Pushed v4 commit What changed
void setInputsNumber(size_t num)
{
std::lock_guard lock(mutex);
unfinished_inputs = num;
if (isReadyLocked() || cancelled)
notifyReadyLocked();
}Combined with the existing Also refreshed the Pre-PR validation gatea. Deterministic repro. The race the reviewer identified is defensive: today every b. Root cause. c. Fix matches root cause. Yes — the lock+notify on terminal transition closes exactly this window. Cancellation is handled symmetrically (if d. Test intent preserved / new tests. Existing tests are unchanged and continue to exercise the main path ( e. Both directions demonstrated. For the common path: f. Fix is general. The update covers both Branch stateSession id: |
CI Status — covered SHA
|
| Check | Test | Disposition |
|---|---|---|
Fast test |
04108_chunk_buffer_reader_writer_race |
Pre-existing chronic trunk bug — NOT this PR. The crash site is RuntimeFilterLookup.cpp:83 — DB::IRuntimeFilter::find raising Trying to lookup values in runtime filter before building it was finished. That error is unrelated to ChunkBuffer; tracked as STID 2210-585c (already noted in 2026-04-23 update). 30d data: 04108 ran 1176 OK / 2 FAIL / 26 SKIPPED on this PR. The race is intermittent and the same runtime-filter error appears on PRs #105679 and #106008 in the same 30d window with no ChunkBuffer changes. |
Mergeable Check / PR / CH Inc sync |
n/a | Aggregator/infra rollup. |
All bot-review concerns addressed in commits 32dcb2c8 (async deadlock fix), 14836f88 (test nits), 431d8a66 (analyzer pin for old-analyzer profile), 6eb4986e (registerReader/setInputsNumber notify race). PR is currently CLEAN/MERGEABLE pending @novikd / @vdimir / clickhouse-gh[bot] re-approval.
— cron:our-pr-ci-monitor:20260604-073000
|
Mr @groeneai the idea to add a dependency visible to PipelineExecutor is ok, but the implementation is too complex. It can be technically more complex, so synchronization via EventFD is kind of ok as well. But in this case just make a shared state with the atomic counter : how many sources are finished or need data. Signal when the last source is finished, or when any needs data (add a flag into shared state). Also you would need a second EventFD to tell a Source that the data is ready, and sources should implement async as well. Looking at this ^ I still prefer a signaling port(s). Also, join added from correlated subquery should ignore |
| -- And a more vanilla correlated-subquery-with-totals shape, also at `max_threads = 1`, | ||
| -- matching the original bug report repro for issue #96445. | ||
| SELECT (SELECT count(*) FROM (SELECT t0.c0)) AS a0 | ||
| FROM (SELECT 1 AS c0 GROUP BY 1 WITH TOTALS) AS t0 |
There was a problem hiding this comment.
I suspect that WITH TOTALS just initiates the ExecutionGraph, because it may produce NullSink without a parent transform.
There was a problem hiding this comment.
Checked EXPLAIN PIPELINE for this query: it does contain ReadFromCommonBufferSource and SaveSubqueryResultToBufferTransform, so it drives the buffered reader rather than only initializing the graph. I kept it in 04110 and send it to Null (the totals-row formatting can vary), so the assertion is just that the server completes without throwing or hanging.
|
@KochetovNicolai thanks, agreed the eventfd machinery is too complex. I'll switch to signaling ports as you prefer. Plan:
I'll rework the regression tests for the new topology (and revisit the |
KochetovNicolai
left a comment
There was a problem hiding this comment.
Address my comment. Also, fix CI.
|
@KochetovNicolai update before I build the signaling ports: I reverted the eventfd machinery and tested your second point (the correlated-subquery join ignoring What I did: in Why it works: Validation on a debug build with the original repro:
So this single planner change removes the complexity you flagged, fixes both manifestations (including the runtime-filter one that's failing CI here), and drops the non-Linux cv fallback the bot flagged. My question before I proceed: are you happy with break-mode-ignore as the whole fix, or do you still want the signaling ports added as defense-in-depth? I lean toward break-mode-only since it's the minimal change and addresses the shared root cause, but it's your call. I'll hold the ports work until you confirm. (re @ novikd's note on 04110: I checked |
|
@groeneai "are you happy with break-mode-ignore as the whole fix, or do you still want the signaling ports added as defense-in-depth?" - yes, let's implement break-mode-ignore only. It's a scoped fix. |
17f971c to
c5a33e7
Compare
|
Done, break-mode-ignore only. Pushed Validated on a debug build: the break-mode repro crashes the server on every run without the fix and 0/40 with it; both regression tests pass 30/30 and the existing correlated-subquery suite is green. |
c5a33e7 to
2f35eb4
Compare
Pre-PR validation gate (commit 2f35eb4, adds the CROSS-JOIN site)
Session id: cron:clickhouse-worker-slot-3:20260615-115200 |
2f35eb4 to
4d27edf
Compare
|
Pushed The flaky check failed on 04108 with "Test runs too long (> 180s)". The break-mode repro is a row-by-row join ( Verified locally with Session: cron:clickhouse-worker-slot-0:20260615-145200 |
4d27edf to
32269a1
Compare
|
CI follow-up: the previous Tagged both regression tests Rebased onto current master; single commit. |
…mits
Correlated subqueries are decorrelated into two internal joins:
decorrelateQueryPlan builds a CROSS "JOIN to evaluate correlated
expression", and buildLogicalJoin builds the final "JOIN to generate
result stream". Both are implementation details, but each was
constructed with JoinSettings(settings), so they inherited the user's
max_rows_in_join / max_bytes_in_join and join_overflow_mode.
Under join_overflow_mode = 'break' (for example max_bytes_in_join = 1),
such an internal join's build side stops early once the limit is hit and
drops the remaining rows. This is wrong twice over:
1. The subquery silently produces an incomplete result.
2. The early build-side finish lets the probe side start before the
build side has consumed its input. When the right side is buffered
for the common subplan, the reader observes unfinished writer inputs
and aborts with the logical error
"Trying to extract chunk from ChunkBuffer before all inputs are
finished" (STID 2651-2cfd)
and, depending on which consumer reaches the half-built right side
first, the sibling
"Trying to lookup values in runtime filter before building it was
finished" (STID 2210-585c).
Both were found by the AST fuzzer (issue ClickHouse#96445).
Fix: run both internal decorrelation joins unbounded via a shared
helper, makeInternalDecorrelationJoinUnbounded. After building each
join, clear its size limits (max_rows_in_join = max_bytes_in_join = 0,
which SizeLimits treats as unlimited) and set join_overflow_mode = THROW
so a user limit can never short-circuit it. The shared helper keeps the
two sites from diverging.
Regression tests:
- 04108_chunk_buffer_reader_writer_race: parallel reproduction of the
break-mode abort, plus a distinct-correlated-values assertion (the
correlated result must equal the plain scan) so a silent row drop on
either internal join is caught, not only a crash.
- 04110_chunk_buffer_max_threads_1: max_threads = 1 path, the original
issue ClickHouse#96445 GROUP BY WITH TOTALS shape that drives the buffered
reader, and the same distinct-values assertion.
The distinct-values assertion ran its correlated subquery with
max_block_size = 1 over the whole input. With use_query_condition_cache
= 0 and min_bytes_for_wide_part = 0 (both common in CI randomization)
that turned into a per-row re-scan of the wide-part granules, i.e. cost
quadratic in the row count: ~13s on debug for the 16000-row table and
past the 600s per-test hard timeout under sanitizers, surfacing as
flaky-check timeouts. max_block_size = 1 is irrelevant to the bug, which
is triggered by max_rows_in_join = 1 with join_overflow_mode = 'break';
dropping it makes a single run finish in well under a second under every
randomized-setting combination while the assertion still catches a
silent row drop. No test tags are needed.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
32269a1 to
583af10
Compare
|
Pushed The distinct-values assertion in both regression tests ran a per-row correlated subquery with Pre-PR validation gate
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 13/13 (100.00%) | Lost baseline coverage: none · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: This PR is a narrow correctness fix: internal joins built while decorrelating correlated subqueries now ignore user join size limits, and the new behavior only triggers when experimental correlated subqueries are enabled alongside break-mode join size limits. Standard ClickBench and TPC-H queries never exercise that path, so none of the seven flagged speedups (ranging from -10% to -50%) can plausibly be caused by this change. We are treating them as run-to-run/environment variance and have downgraded each to not-sure rather than crediting them to the PR. The functional fix itself looks sound and is well covered by the two added regression tests. clickbenchFlagged queries (4 of 43)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_officialFlagged queries (3 of 22)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
2f4c69b
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong results and a possible logical error for correlated subqueries when a join size limit (
max_rows_in_join/max_bytes_in_join) is set together withjoin_overflow_mode = 'break'. The join created internally to evaluate a correlated subquery now ignores those user limits, so it can no longer stop early and drop rows.Description
Closes: #96445
Correlated subqueries are decorrelated into an internal JOIN built in
buildLogicalJoin. That join is an implementation detail, but it was constructed withJoinSettings(settings), so it inherited the user'smax_rows_in_join/max_bytes_in_joinandjoin_overflow_mode.Under
join_overflow_mode = 'break'(for examplemax_bytes_in_join = 1) the internal join's build side stops early once the limit is hit and drops the remaining rows. That is wrong twice over: the subquery silently produces an incomplete result, and the early build-side finish lets the probe side start before the build side has consumed its input. When the right side is buffered for the common subplan, the reader then observes unfinished writer inputs and aborts withTrying to extract chunk from ChunkBuffer before all inputs are finished(STID 2651-2cfd), or, depending on which consumer reaches the half-built right side first, the siblingTrying to lookup values in runtime filter before building it was finished(STID 2210-585c). Both were found by the AST fuzzer.Fix: run the internal decorrelation join unbounded. After building it, clear its size limits (
max_rows_in_join = max_bytes_in_join = 0, whichSizeLimitstreats as unlimited) and setjoin_overflow_mode = THROWso a limit can never short-circuit it.This replaces the earlier buffer-synchronization approach (eventfd / signaling ports) with a scoped planner fix, per reviewer guidance.
Reproduction (deterministic on a debug build):
Tests:
04108_chunk_buffer_reader_writer_race: parallel reproduction of the break-mode abort.04110_chunk_buffer_max_threads_1:max_threads = 1path plus the original issue Logical error: Trying to extract chunk from ChunkBuffer before all inputs are finished (unfinished inputs: A) (STID: 2651-2cfd) #96445GROUP BY ... WITH TOTALSshape, which drives the buffered reader.AST fuzzer report (PR #102547): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102547&sha=ddd714402413143c15352a8a44d6b2540fd0bc39&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29
Version info
26.6.1.1045