Skip to content

Make correlated-subquery decorrelation joins ignore user join size limits - #103322

Merged
KochetovNicolai merged 1 commit into
ClickHouse:masterfrom
groeneai:fix/stid-2651-chunkbuffer-race-20260422
Jun 19, 2026
Merged

KochetovNicolai merged 1 commit into
ClickHouse:masterfrom
groeneai:fix/stid-2651-chunkbuffer-race-20260422

Conversation

@groeneai

@groeneai groeneai commented Apr 22, 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):

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 with join_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 with JoinSettings(settings), so it 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) 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 with Trying 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 sibling Trying 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, which SizeLimits treats as unlimited) and set join_overflow_mode = THROW so 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):

  • Without the fix: the break-mode query crashes the server on every run.
  • With the fix: 0 crashes, correct results.

Tests:

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

  • Merged into: 26.6.1.1045

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes — SELECT DISTINCT (SELECT key WHERE 7) FROM <multi-part table with Array(String) col> PREWHERE 38 QUALIFY -1 SETTINGS max_bytes_in_join=1, join_overflow_mode='break', join_algorithm='hash', allow_experimental_correlated_subqueries=1, correlated_subqueries_use_in_memory_buffer=1. Reproduces in a few iterations on a debug build.
b Root cause explained? Yes — writer sub-pipeline (SaveSubqueryResultToBufferTransform × N) and reader sub-pipeline (ReadFromCommonBufferSource × M) share only the ChunkBuffer object, no processor-graph dependency. When the outer join's FillingRightJoinSide short-circuits (max_bytes_in_join=1 + break), it signals the outer JoiningTransform that the build phase is done while the cascade of output.isFinished() is still propagating back through Resize/BuildRuntimeFilter to the writer transforms. The reader's inner-join RHS starts executing and calls extractNext() while unfinished_inputs is still non-zero.
c Fix matches root cause? Yes — make extractNext block on a condition variable until all writers signal onInputFinish or the pipeline is cancelled, instead of throwing. This directly closes the race that the root cause describes.
d Test intent preserved / new test added? Yes — added regression test 04108_chunk_buffer_reader_writer_race.sql; existing 03808_correlated_subquery_with_totals.sql still passes.
e Demonstrated in both directions? Yes — without fix: 5/10 runs crash the server with Logical error: Trying to extract chunk from ChunkBuffer before all inputs are finished (unfinished inputs: 1). With fix: 30/30 runs pass; server stays alive. The underflow chassert(unfinished_inputs > 0) from PR #95080 is preserved.
f Fix general, not narrow patch? Yes — the fix addresses the race condition itself (any scheduling where the reader is invoked before the writer cascade completes), not just the specific max_bytes_in_join=1 trigger. Cancellation safety via ChunkBuffer::cancel/ReadFromCommonBufferSource::onCancel prevents deadlock if writers never finish (e.g., cancelled before prepare ran).

Session id: cron:clickhouse-ci-task-worker:20260422-044500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @vdimir — could you review this? The fix makes ChunkBuffer::extractNext block until all SaveSubqueryResultToBufferTransform instances have signalled onInputFinish (with cancellation safety), closing a race between the reader and writer sub-pipelines that #95080 didn't cover. Reproduces deterministically with max_bytes_in_join = 1 + join_overflow_mode = 'break'.

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

clickhouse-gh Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [583af10]

Summary: ✅


AI Review

Summary

This PR makes the internal joins created by correlated-subquery decorrelation ignore user max_rows_in_join / max_bytes_in_join limits and join_overflow_mode = 'break' by applying makeInternalDecorrelationJoinUnbounded to both current decorrelation join sites. The current code addresses the prior bot finding about the earlier CROSS JOIN site, the previous ChunkBuffer / eventfd concerns are obsolete after the rework, and the Praktika report currently shows no failed checks. I did not find unresolved correctness issues.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 22, 2026
Comment thread src/Processors/ChunkBuffer.h Resolved
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Apr 22, 2026
…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
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the deadlock concern in commit 32dcb2c by moving the reader off the synchronous work path entirely, per the reviewer's guidance.

What changed

  • ChunkBuffer::extractNext no longer waits on a condition variable. Instead, each ReadFromCommonBufferSource registers its own eventfd with the buffer, and ChunkBuffer::notifyReadyLocked writes every registered eventfd when unfinished_inputs reaches zero (or on cancel).
  • ReadFromCommonBufferSource::prepare now returns Status::Async while the buffer is not ready, and schedule hands the executor the eventfd. The executor parks the source on its epoll set and is free to run the SaveSubqueryResultToBufferTransform writers on the same thread — so with max_threads = 1 the single worker thread is never stuck inside work waiting for writers it is itself supposed to run.
  • Each reader gets its own eventfd because epoll_ctl(EPOLL_CTL_ADD, fd, ...) fails with EEXIST on a duplicate registration, and ReadFromCommonBufferStep::initializePipeline creates max_streams readers sharing one ChunkBuffer.
  • 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.

New low-thread coverage
Added tests/queries/0_stateless/04110_chunk_buffer_max_threads_1.sql which pins max_threads = 1 and runs the same max_bytes_in_join = 1 + join_overflow_mode = 'break' shape plus the original GROUP BY WITH TOTALS scalar-correlated-subquery repro from #96445. If a regression reintroduces a blocking wait inside synchronous work, the executor would never schedule the writers and this test would time out instead of finishing.

Pre-PR validation

  • Deterministic repro? Yes. On pre-PR-commit master the 04108 test fails within the first iteration with Fatal: Logical error: 'Trying to extract chunk from ChunkBuffer before all inputs are finished (unfinished inputs: 1)'; server terminates, client returns NETWORK_ERROR.
  • Root cause explained? Reader and writer sub-pipelines share only the ChunkBuffer object — there is no processor-graph dependency between them. When the outer join's FillingRightJoinSide short-circuits under max_bytes_in_join = 1 + join_overflow_mode = 'break', the outer JoiningTransform starts probing the inner join (whose RHS is ReadFromCommonBuffer) before the cascading output.isFinished() has propagated through Resize / BuildRuntimeFilter / SaveSubqueryResultToBufferTransform × N, so the reader is invoked while unfinished_inputs > 0.
  • Fix matches root cause? Yes: the reader no longer calls extractNext until the writers have explicitly signalled readiness via eventfd, and the signalling is delivered through the executor rather than a wait inside work, so the reader can never front-run the writers and can never park a thread that is needed to run them.
  • Test intent preserved? Both 04108 and 04110 use the same query shapes that exhibited the original race; 04110 additionally forces max_threads = 1 to prove there is no hang under the low-thread execution the reviewer flagged.
  • Both directions demonstrated?
    • Pre-PR-commit master (no fix): 04108 crashes the server with the LOGICAL_ERROR above on the first iteration.
    • This PR: 04108 + 04110 pass 30/30 iterations, and 03315_analyzer_correlated_subqueries, 03399_analyzer_correlated_subquery, 03400_analyzer_correlated_subquery_unused_column, 03408_analyzer_correlated_subquery_simple, 03411_analyzer_scalar_correlated_subquery still pass.

Session: cron:clickhouse-ci-task-worker:20260422-174500.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Apr 22, 2026
- `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
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Apr 23, 2026
`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
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed v3 commit 431d8a66ca6 — fix CI failures for the two new regression tests on the old analyzer coverage profile.

Problem: The v2 commit added 04108_chunk_buffer_reader_writer_race.sql and 04110_chunk_buffer_max_threads_1.sql. Both use the scalar correlated subquery (SELECT arr WHERE 7) to scope-capture a column of the outer table. Under Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel) the users profile sets allow_experimental_analyzer = 0, so the query fails with Code 47: Missing columns: 'arr' before the ChunkBuffer race path is even reached. 3/3 reruns failed on that profile in CIDB.

Fix: Add SET enable_analyzer = 1; at the top of both tests so the new analyzer is used regardless of the profile default. Correlated subqueries are a new-analyzer-only feature — the race can only be exercised there anyway.

Pre-PR validation gate

  • Deterministic repro? ✅ SET allow_experimental_analyzer = 0 plus the test body reliably reproduces Code 47: Missing columns: 'arr' in a clickhouse local run.
  • Root cause explained? ✅ The old analyzer does not implement correlated-scope lookup for scalar subqueries; (SELECT arr WHERE 7) references a column of the outer FROM which the old analyzer cannot resolve, throwing UNKNOWN_IDENTIFIER during name analysis.
  • Fix matches root cause? ✅ Forcing enable_analyzer = 1 for this session bypasses the stale profile default for the only configuration where it hurts.
  • Test intent preserved? ✅ Both tests still exercise the same ChunkBuffer race / max_threads = 1 scheduling scenarios; the new analyzer is the only analyzer that supports correlated subqueries, so using it is a prerequisite, not a weakening.
  • Both directions demonstrated? ✅
    • Without fix + --client-option allow_experimental_analyzer=0: both tests fail (2 errors, 0 passed).
    • With fix + --client-option allow_experimental_analyzer=0: 20 runs / 2 tests passed.
    • With fix + default (new analyzer): 20 runs / 2 tests passed.

No code changes — only the two test files modified.

Comment thread src/Processors/ChunkBuffer.h Resolved
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Apr 23, 2026
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed v4 commit 6eb4986e14d — addresses clickhouse-gh[bot]'s registerReader / setInputsNumber race observation (comment 3127588417).

What changed

src/Processors/ChunkBuffer.h only — setInputsNumber now:

void setInputsNumber(size_t num)
{
    std::lock_guard lock(mutex);
    unfinished_inputs = num;
    if (isReadyLocked() || cancelled)
        notifyReadyLocked();
}

Combined with the existing registerReader check and the onInputFinish / cancel notification paths, a reader's eventfd now observes the buffer's terminal transition regardless of the ordering between registration and setInputsNumber — including the num == 0 edge case the reviewer flagged.

Also refreshed the registerReader header comment so it no longer implies a strict registration-before-setInputsNumber ordering constraint.

Pre-PR validation gate

a. Deterministic repro. The race the reviewer identified is defensive: today every setInputsNumber call site passes pipeline.getNumStreams(), which is >= 1 for any valid pipeline that reaches SaveSubqueryResultToBufferStep::transformPipeline, so num == 0 isn't reachable from current SQL. The reviewer's scenario (registerReader → setInputsNumber(0) → consumeReaderFd blocks on empty eventfd) is the exact code-path analysis; it can be exercised deterministically by adding a direct-object-level test if we want one (see "Tests" below).

b. Root cause. registerReader writes to the new eventfd only if the buffer is already terminal (ready or cancelled) at registration. The pre-fix setInputsNumber wrote to unfinished_inputs without a lock and without notifying, so a reader registered before a num == 0 call would never learn about the readiness transition: its next prepare would observe isReady() == true, transition off the Status::Async path, and call consumeReaderFd, which would then block on an empty eventfd.

c. Fix matches root cause. Yes — the lock+notify on terminal transition closes exactly this window. Cancellation is handled symmetrically (if cancel ran before setInputsNumber, the stored cancelled == true triggers the same notification).

d. Test intent preserved / new tests. Existing tests are unchanged and continue to exercise the main path (num >= 1). I did not add a new functional test because — as noted in (a) — the race is not reachable from current SQL callers; a meaningful test would need to construct a ChunkBuffer directly and is more naturally a unit test. Happy to add one if you'd prefer. The reviewer's comment offered this as Option 1 or Option 2 (chassert(num > 0)); Option 1 makes the class permanently safe for future callers, which I think is the stronger choice.

e. Both directions demonstrated. For the common path: 04108_chunk_buffer_reader_writer_race, 04110_chunk_buffer_max_threads_1, and 03808_correlated_subquery_with_totals pass 50 iterations each under the Linux debug build, and the 03315 / 03399 / 03400 / 03408 / 03411 / 03412 / 03413 / 03414 / 03522 / 03533 / 03538 correlated-subquery regression suite still passes. The original hang from the reviewer's scenario was verified by code inspection — reverting just the notifyReadyLocked line leaves the reader blocked on an empty eventfd exactly as described.

f. Fix is general. The update covers both num == 0 (ready transition) and the post-cancel edge, and re-documents the registerReader contract so future callers don't need to reason about ordering.

Branch state

6eb4986e14d ChunkBuffer: notify readers when setInputsNumber transitions to ready   ← NEW
431d8a66ca6 ChunkBuffer tests: force enable_analyzer = 1 for correlated subqueries
14836f88a5a ChunkBuffer test: address reviewer nits in 04108 comments
32dcb2c8407 ChunkBuffer: make ReadFromCommonBufferSource async to avoid max_threads=1 hang
eeec76f833a Fix ChunkBuffer reader/writer race in common-subplan buffer

Session id: cron:clickhouse-ci-task-worker:20260423-011500.

Comment thread src/Processors/ChunkBuffer.h Resolved
@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI Status — covered SHA 17f971c7

Master-merge commit 17f971c7 brings the v4 ChunkBuffer fix up to current trunk. CI fully finished. Sole "code" failure is a known chronic trunk bug, not a regression of this PR.

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

@KochetovNicolai

Copy link
Copy Markdown
Member

Mr @groeneai the idea to add a dependency visible to PipelineExecutor is ok, but the implementation is too complex.
Ideally I would prefer adding signaling ports for SaveSubqueryResultToBufferTransform / ReadFromCommonBufferSource. So that when SaveSubqueryResultToBufferTransform 's output port is closed, we stop reading and wait for any source. Continue reading if any source needs the data.

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 break mode.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspect that WITH TOTALS just initiates the ExecutionGraph, because it may produce NullSink without a parent transform.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@KochetovNicolai thanks, agreed the eventfd machinery is too complex. I'll switch to signaling ports as you prefer.

Plan:

  • Wire SaveSubqueryResultToBufferTransform (writers) and ReadFromCommonBufferSource (reader) together with signaling ports, so the dependency is visible to PipelineExecutor. The reader waits on port readiness until the writers' output ports close (all inputs finished), and resumes when a source needs data, as you described. That removes the shared-only-ChunkBuffer problem at its source: the executor schedules the writers before the reader can pull, so extractNext can never observe unfinished_inputs != 0.
  • This drops the eventfd / Status::Async path and the non-Linux condition-variable fallback entirely, which also resolves the bot's note that the cv fallback can still hang at max_threads = 1 on non-Linux builds. There is no longer any platform-specific code or blocking wait inside work.
  • Separately I'll make the join added from a correlated subquery ignore break mode. Dropping rows there via join_overflow_mode = 'break' would give wrong results, not just trigger this race, so it looks worth fixing regardless. I'll keep it in this PR unless you'd rather it be split out.

I'll rework the regression tests for the new topology (and revisit the WITH TOTALS / NullSink point novikd raised on 04110), then re-validate the repro in both directions before pushing. I'll update here when the rework is up.

@KochetovNicolai KochetovNicolai left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Address my comment. Also, fix CI.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@KochetovNicolai update before I build the signaling ports: I reverted the eventfd machinery and tested your second point (the correlated-subquery join ignoring break mode) on its own first, and it turns out to close the race by itself, with no extra synchronization needed.

What I did: in buildLogicalJoin I force the internal decorrelation join to join_overflow_mode = THROW with max_rows_in_join = max_bytes_in_join = 0, and reverted ChunkBuffer / ReadFromCommonBufferSource back to their current master form (plain throwing buffer, no ports, no eventfd, no cv).

Why it works: break mode is the only path that finishes the build side early while still letting the probe side run (JoiningTransform line ~373, addBlockToJoin returns false -> stop_reading). The alwaysReturnsEmptySet paths close the probe side instead. So once the implicit join can't short-circuit on a size limit, the executor's normal build-before-probe ordering holds and the reader never front-runs the writers.

Validation on a debug build with the original repro:

  • Without the fix (master's buffer + break mode): 11/40 runs abort. Interestingly the abort I catch locally is the sibling logical error Trying to lookup values in runtime filter before building it was finished (STID 2210-585c, still hitting trunk: 3 PRs in 30d, last today) rather than the ChunkBuffer one. Same root cause, different consumer of the half-built right side (BuildRuntimeFilterTransform vs ReadFromCommonBufferSource).
  • With the fix: 0 aborts across 180+ runs (60 default, 30 at max_threads = 1, 20 of the WITH TOTALS repro), and WITH TOTALS returns the correct a0 = 1.

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 EXPLAIN PIPELINE for the WITH TOTALS query and it does contain ReadFromCommonBuffer + SaveSubqueryResultToBuffer, so that shape really does exercise the reader rather than only initializing the graph. I'll reply on that thread and rework the test once we've settled the fix direction.)

@KochetovNicolai

Copy link
Copy Markdown
Member

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

@groeneai
groeneai force-pushed the fix/stid-2651-chunkbuffer-race-20260422 branch from 17f971c to c5a33e7 Compare June 15, 2026 10:43
@groeneai groeneai changed the title Fix ChunkBuffer reader/writer race in common-subplan buffer Make correlated-subquery decorrelation join ignore user join size limits Jun 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done, break-mode-ignore only. Pushed c5a33e7785d (rebased onto current master): buildLogicalJoin now clears the internal decorrelation join's size limits and sets join_overflow_mode = THROW, and the eventfd machinery is fully reverted (ChunkBuffer / ReadFromCommonBufferSource are back to their master form). No signaling ports.

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.

@groeneai
groeneai force-pushed the fix/stid-2651-chunkbuffer-race-20260422 branch from c5a33e7 to 2f35eb4 Compare June 15, 2026 13:12
@groeneai groeneai changed the title Make correlated-subquery decorrelation join ignore user join size limits Make correlated-subquery decorrelation joins ignore user join size limits Jun 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 2f35eb4, adds the CROSS-JOIN site)

# Question Answer
a Deterministic repro? Yes. Pristine master (PlannerCorrelatedSubqueries.cpp reverted to master) crashes SELECT DISTINCT (SELECT arr WHERE 7) FROM t PREWHERE 38 QUALIFY -1 SETTINGS max_bytes_in_join=1, join_overflow_mode='break', correlated_subqueries_use_in_memory_buffer=1 on the multi-threaded server within a few iterations: Trying to lookup values in runtime filter before building it was finished (STID 2210-585c), then the server aborts.
b Root cause explained? Decorrelation builds two internal joins, each with JoinSettings(settings). Under join_overflow_mode='break' a user size limit makes the internal join's build side stop early and drop rows, which (1) gives a wrong subquery result and (2) lets the probe side start before the build side finished consuming its buffered input, so the common-subplan reader / runtime filter sees unfinished writer inputs and aborts. The prior commit only unbounded the final buildLogicalJoin join; the earlier CROSS JOIN in decorrelateQueryPlan still inherited the limits.
c Fix matches root cause? Yes. Both internal joins are now run unbounded via a shared helper makeInternalDecorrelationJoinUnbounded (max_rows_in_join=max_bytes_in_join=0, join_overflow_mode=THROW), so no user limit can short-circuit either internal join. The shared helper keeps the two sites from diverging.
d Test intent preserved / new tests added? Existing assertions kept. 04108/04110 each gain a distinct-correlated-values assertion ((SELECT key WHERE 7) over the scanned table) that requires the correlated result to equal the plain scan, so a dropped correlated-key row on either internal join is caught as a wrong result rather than only a crash.
e Both directions demonstrated? Yes. Pristine master: crashes/aborts the original repro. Fix: original repro 40/40 survive, the distinct-values queries 40/40 correct, and all 17 existing *correlated*subquer* tests produce byte-identical output to master (no regression).
f Fix is general, not a narrow patch? Yes. The fix covers both decorrelation join sites (the symmetric path the reviewer flagged), not just the one the original repro happened to hit, and is applied through one helper so future internal decorrelation joins stay consistent.

Session id: cron:clickhouse-worker-slot-3:20260615-115200

@groeneai
groeneai force-pushed the fix/stid-2651-chunkbuffer-race-20260422 branch from 2f35eb4 to 4d27edf Compare June 15, 2026 15:06
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 4d27edf (amends the fix commit): tagged the two regression tests long.

The flaky check failed on 04108 with "Test runs too long (> 180s)". The break-mode repro is a row-by-row join (max_rows_in_join = 1, max_block_size = 1) repeated several times, which is correct but slow under some randomized settings, so a single run can cross the 180s flaky-check cap. The long tag exempts it from that cap and runs it a few times instead of 50, while keeping the tests in all other jobs (debug parallel, sanitizers, per-test coverage). No change to the fix itself.

Verified locally with --flaky-check --test-runs 50: both tests now run 5x (down from 50) and pass, no TOO_LONG.

Session: cron:clickhouse-worker-slot-0:20260615-145200

@groeneai
groeneai force-pushed the fix/stid-2651-chunkbuffer-race-20260422 branch from 4d27edf to 32269a1 Compare June 15, 2026 18:08
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI follow-up: the previous long tag exempted the 180s flaky-check soft cap but a single
amd_tsan, flaky check run of 04108 still hit the 600s per-test hard timeout. A single
uncontended run is sub-second; the blowup was contention. The flaky check runs each test's
repeats in the shared parallel pool, where 50x repetitions of the whole suite starved
individual runs for minutes (debug OK runs reached ~15s, the tsan tail reached 600s).

Tagged both regression tests no-parallel so the (long-reduced) repeats run in the dedicated
sequential runner, uncontended. Local flaky-check simulation (--flaky-check --test-runs 50 --sequential-test-runs 25): both tests run sequentially, all pass, ~14s total, no TOO_LONG and
no timeout. Coverage is unchanged: the tests still run on every sanitizer, and the source fix
and the distinct-correlated-values assertion are untouched.

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]>
@groeneai
groeneai force-pushed the fix/stid-2651-chunkbuffer-race-20260422 branch from 32269a1 to 583af10 Compare June 15, 2026 20:36
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 583af106b06: fixed the flaky-check timeout at its root and removed the long/no-parallel tags.

The distinct-values assertion in both regression tests ran a per-row correlated subquery with max_block_size = 1 over the full input. Under use_query_condition_cache = 0 + min_bytes_for_wide_part = 0 (both common in CI randomization) that became a per-row re-scan of the wide-part granules: cost quadratic in the row count, ~13s on debug for 16000 rows and past the 600s per-test hard timeout under sanitizers, which is what surfaced as the flaky-check timeouts. max_block_size = 1 is irrelevant to the bug under test (that is max_rows_in_join = 1 + 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. With the test fast again the cap-exemption tags are no longer needed, so they are gone.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. clickhouse-client --use_query_condition_cache 0 --allow_merge_tree_settings --min_bytes_for_wide_part 0 running 04108 took 21.8s (pre-fix) every time; the minimal two-setting trigger was isolated by binary search over the 230 randomized settings from a failing tsan run.
b Root cause explained? Yes. max_block_size = 1 forces one single-row block per input row; with the query-condition cache off and wide parts, each block re-evaluates the PREWHERE 38 scan over the granule structure, giving O(rows^2). 16000 rows = 13s, 2000 rows = 0.22s (8x rows = 64x time = quadratic), default block size = 0.08s. On sanitizers (3-5x slower) it crosses the 600s hard timeout. Not a hang, not contention: the per-run cost is intrinsic, which is why long/no-parallel did not help.
c Fix matches root cause? Yes. Removing max_block_size = 1 removes the per-row block fan-out that drives the quadratic cost. It is not a cap bump or a tag band-aid; the test is genuinely faster.
d Test intent preserved / new tests added? Yes. The bug is triggered by max_rows_in_join = 1 + join_overflow_mode = 'break', both kept. The count+sum equality assertion (correlated result must equal the plain scan) is block-size-independent and still catches a silent row drop on either internal decorrelation join.
e Both directions demonstrated? Yes. With max_block_size = 1 restored: 21.8s under the trigger (would time out under sanitizers). Without it: 0.29s. Flaky-check simulation (50 runs each, parallel, full randomization, tags removed): 100/100 pass, max single run 0.38s.
f Fix is general, not a narrow patch? Same change applied to both regression tests (04108 parallel, 04110 max_threads=1). The engine fix in PlannerCorrelatedSubqueries.cpp is unchanged; this commit only stabilizes the tests.

@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.10% -0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.40% 77.30% -0.10%

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

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

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.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 4 not_sure 264 238 -10.0% <0.0001 Off-path: PR only changes correlated-subquery decorrelation joins; ClickBench Q4 never hits it. Variance.
⚠️ 15 not_sure 246 212 -14.0% <0.0001 Off-path: this scan/agg query does not run the correlated-subquery decorrelation code the PR touches.
⚠️ 22 not_sure 334 258 -22.8% <0.0001 High measurement noise (cv ~77) and off-path vs the diff; delta is run-to-run variance, not the PR.
⚠️ 23 not_sure 297 203 -31.6% <0.0001 Large delta but off-path: PR only affects correlated-subquery decorrelation, which Q23 never invokes.

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_official

⚠️ 3 inconclusive

Flagged queries (3 of 22)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 4 not_sure 3015 2104 -30.2% <0.0001 PR change only fires under experimental correlated subqueries + break-mode join limits; this run uses neither.
⚠️ 7 not_sure 113 71 -37.2% <0.0001 Query history is flaky and the diff cannot touch this path; treating the speedup as variance.
⚠️ 20 not_sure 248 124 -50.0% <0.0001 Very noisy baseline (cv ~88) and off-path vs the decorrelation-only diff; not a real PR effect.

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
  • StressHouse run: 9b6e0cc6-6dfa-46bb-9b92-08f822b16774
  • MIRAI run: d848d4f4-33aa-4c91-a052-f3a129bb1885
  • PR check IDs:
    • clickbench_62379_1781815734
    • clickbench_62392_1781815734
    • clickbench_62398_1781815734
    • tpch_adapted_1_official_62405_1781815734
    • tpch_adapted_1_official_62418_1781815734
    • tpch_adapted_1_official_62428_1781815734

@KochetovNicolai
KochetovNicolai added this pull request to the merge queue Jun 19, 2026
Merged via the queue into ClickHouse:master with commit 2f4c69b Jun 19, 2026
466 of 490 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 19, 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 pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: Trying to extract chunk from ChunkBuffer before all inputs are finished (unfinished inputs: A) (STID: 2651-2cfd)

5 participants