Skip to content

Do not lose the LIMIT stop of a distributed-plan in-memory exchange when its port closes concurrently - #122453

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-inmemory-exchange-lost-stop
Oct 4, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-inmemory-exchange-lost-stop

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117764

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

04891_distributed_plan_limit_early_stop fails on master in two ways since #117764 made it assert the stop per exchange stream:

  • Local arm, MISMATCH missing=[...] after ~100 s: master, amd_debug, master, amd_tsan, #121119, amd_debug. One in-memory exchange source finished without detaching its reader, so its producer stage and every stage feeding it read their whole input.
  • Remote arm, unexpected=['exchange_1__0_0']: master, amd_tsan. The engine was right: the LIMIT fired while a join bucket was still reading its build side, and the stop closed that input too.

Root cause of the first: SourceFromInMemoryExchange::prepare decided the detach on one read of its output port, then ISource::prepare read the port again and returned Finished. Executor threads prepare connected processors concurrently and InputPort::close is lock-free, so a close landing between the two reads finished the source without detachReader, and a finished node is never prepared again. The race exists since the detach was added in dd3d060e23c4; #117661 removed the executor teardown cancel that used to detach at the end of the consumer task, which turned it into a 100 s stall.

Change: the detach is decided on the result of ISource::prepare (Finished while the source has not ended by itself). Both tests now allow, but do not require, the dimension-table streams.

Validation on a debug build: with a 5 ms sleep between the two reads, the unfixed code fails 17 of 17 runs of 04891 (local arm, ~104 s); the same sleep in the fixed code passes 20 of 20 with all 12 streams stopped. Without the sleep, 100 of 100 randomized runs of both tests pass, 200 of 200 at -j 16, and both tests still fail when nothing is stopped (probe table cut to one block).


Workflow [PR]
Sync PR [sync-upstream/pr/122453]

Version info

  • Merged into: 26.10.1.1466-master (included in 26.10 and later)

SourceFromInMemoryExchange::prepare decided the reader detach on one read of
its output port and then returned ISource::prepare, which reads the port again
and returns Finished. Executor threads prepare connected processors
concurrently (ExecutingGraph::updateNode takes only a shared nodes_mutex plus
the node's own status_mutex) and InputPort::close is a lock-free flag update,
so a LIMIT or join closing its inputs between the two reads finished the
source without detachReader. A Finished node ignores later port updates, so
the producer's SinkFromInMemoryExchange never saw isReaderDetached and its
stage, and every stage feeding it, read their whole input.

The race exists since the detach was added in dd3d060. Until ClickHouse#117661 the
unconditional cancel in ~CompletedPipelineExecutor ran onCancel, and with it
detachReader, at the end of every consumer task, which bounded it; since then
the producer runs to the end of its input. On master this shows as
04891_distributed_plan_limit_early_stop failing its local arm after ~100 s
with one exchange path missing from the stop oracle.

Decide the detach on the result of ISource::prepare: Finished while the source
has not ended by itself means the port was closed. A source that ends with its
data still logs nothing, which the oracles rely on.

The remote arm of the same test also failed once with
unexpected=['exchange_1__0_0']: under TSan a dimension reader started late,
the LIMIT fired while that join bucket was still reading its build side, and
the stop correctly closed that input too. So both 04891 and 05024 now allow,
but do not require, the dimension-table shuffles (exchange_1 in 04891,
exchange_1 and exchange_3 in 05024, derived from the task layouts of 46 runs
with no variation).

Validated with a temporary 5 ms sleep between the two reads: unfixed 17/17
runs of 04891 red on the local arm (~104 s), fixed 20/20 green with the same
sleep. Without it: 100/100 randomized runs of both tests, 200/200 at -j 16,
and both tests still red with the probe table cut to one block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 26, 2026
@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; 1 finding), plus my own cold review (1 nit shown).

# Sev Finding Verdict Evidence / action
1 ⚠️ The tests do not force the close between the two port reads, so a revert is caught only at the race's natural rate; add a failpoint test (04891_distributed_plan_limit_early_stop.sh) DISAGREE The fix removes the first read, so the fixed prepare() has no point between two reads. A pause before the one remaining read comes before both reads once the fix is reverted, so that test passes on the reverted code. A pause inside prepare() also parks an executor thread while it holds the node's lock, against IProcessor.h ("Synchronous work must only use CPU"). I forced the interleaving instead with a temporary 5 ms delay at the old point: unfixed 17/17 red, fixed 20/20 green. The existing local arm still detects a revert: the unfixed code failed it 3 times in 6 days, twice on master.
2 💡 A cancelled source that still holds a chunk now also logs NoMoreDataNeeded ... detaching reader and calls detachReader() a second time AGREE, no change detachReader() is idempotent, and the tests read successful queries only.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20260926-175300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A temporary 5 ms sleep between the two reads of the output port in the unfixed SourceFromInMemoryExchange::prepare makes 17 of 17 runs of 04891_distributed_plan_limit_early_stop fail with local exchanges: MISMATCH missing=[...] unexpected=[] after ~104 s (--test-runs 20 -j 10; 3 more runs died in setup on this host's zoneinfo/UTC time-zone draw and are not counted).
b Root cause explained? The source decided the detach on one read of getPort().isFinished() and then returned ISource::prepare(), which reads the flag again. A downstream InputPort::close() (lock-free) from another executor thread between the two reads finishes the source without detachReader(); a Finished node is never prepared again, so the producer's sink never sees the detach and its stage reads its whole input. #117661 removed the teardown cancel that used to detach at the end of the consumer task.
c Fix matches root cause? Yes. The detach is decided on the same observation that ends the source (ISource::prepare() returning Finished with finished unset); the separate read is gone. No retry, no teardown guard.
d Test intent preserved / new tests added? Preserved. Both oracles still require both stop actions on every stream between the LIMIT and the scan; only the dimension-table streams became allowed-but-not-required, because a join bucket still building its side is legitimately stopped (the master amd_tsan failure). With the probe table cut to one block both tests still fail (12/12, 11/12 and 20/21 streams missing, unexpected=[]).
e Both directions demonstrated? Yes, with the same 5 ms sleep: unfixed 17/17 red (115 of 204 expected detach lines), fixed 20/20 green (240 of 240), each server's buildId() checked against its binary.
f Fix is general across code paths? The in-memory source is the only exchange endpoint that takes its terminal decision on a second read. The in-memory sink reads a monotonic flag once; the streaming source reads the port once and sends the stop from work(); the streaming sink has its own flag; the persisted exchange has no detach protocol.
g Fix generalizes across inputs (params/datatypes/wrappers)? Not a data-path change. Both exchange kinds and both arms were exercised; the expected and optional stream sets were derived from the task layouts of 46 runs with no variation.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; the trace message text is unchanged.
i Invariants and contracts preserved? At most one detach trace line per source (detach_notified; detachReader() itself is idempotent); finished is read inside the node's own prepare, as ISource::prepare does; no new lock. A source that ends with its data still logs nothing, which the oracles rely on.

Session id: cron:clickhouse-impl-slot-7:20260926-165500

@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b674bdf]

Summary: ✅


AI Review

Summary

This PR fixes a real race in SourceFromInMemoryExchange::prepare where a downstream close could land between two reads of the output port and lose the detach signal, causing upstream stages to keep reading past a satisfied LIMIT. The implementation change in src/QueryPipeline/DistributedPlanExecutor.cpp matches that root cause, and the test adjustments in 04891_distributed_plan_limit_early_stop.sh and 05024_distributed_plan_limit_early_stop_idle_sink.sh keep the mandatory probe-side stop assertions while tolerating the legitimate join-build-side timing variation. I did not find a code-level issue that warrants a new inline review comment.

PR Metadata
  • 💡 CI Fix or Improvement does not match the actual change: this PR modifies server behavior in src/QueryPipeline/DistributedPlanExecutor.cpp, not just CI or test infrastructure. A better replacement is:
    • Changelog category: Performance Improvement
    • Changelog entry: Distributed-plan queries with LIMIT now propagate early stop through in-memory exchanges, so upstream stages stop reading unnecessary data instead of continuing to scan whole inputs.
Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit b674bdf.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.50% 79.50% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 26, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b674bdf77 with master b1f44e396 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 15 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 692be26

Every failure below has an owner: a fixing PR (mine 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
Integration tests (amd_tsan, 2/6) lost runner, so this shard produced no test signal: its Run step started at 20:45:57Z and never reported a conclusion, Post Checkout code never started, the job log returns 404 and the shard wrote no row to CIDB. The other five amd_tsan shards and all four arm_binary, distributed plan shards passed on this head. It was not retried: 14 s after attempt 2 finished, attempt 3 re-ran only Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) and the two summary jobs after it, and retry_infra_failures.yml only considers attempts 1 and 2 a fix task is moved to pending (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR rollups, red only because of the row above a fix task is moved to pending (the same one as for the row above)

All 173 check runs completed (129 pass, 41 not selected, 3 red), Finish Workflow is green and
CH Inc sync passed. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20260927-020134

@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Oct 2, 2026
@alexey-milovidov alexey-milovidov self-assigned this Oct 3, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 3, 2026
Merged via the queue into ClickHouse:master with commit 98cee6e Oct 4, 2026
149 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-ci 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.

3 participants