Skip to content

Fix "No more packets are available." logical error on distributed LIMIT queries - #110334

Merged
azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-distributed-limit-no-more-packets-race
Aug 10, 2026
Merged

azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-distributed-limit-no-more-packets-race

Conversation

@groeneai

@groeneai groeneai commented Jul 14, 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 a rare Logical error: 'No more packets are available.' raised for a valid distributed query with a LIMIT, which aborted the server in debug and sanitizer builds.

Description

RemoteQueryExecutor::read() checks was_cancelled under was_cancelled_mutex and releases it before the blocking connections->receivePacket(), because finish() and cancel() take the same mutex and must not wait for a receive. When a LIMIT closes the output port, RemoteSource::onUpdatePorts() runs finish() on another pipeline thread, which cancels and drains the same connections. A reader that passed its check before that then found no active connections and threw LOGICAL_ERROR.

Both IConnections implementations now report end-of-stream when the query was already cancelled. Only a non-cancelled query reaching that point is a real logic error.

The regression test pins the interleaving with two pauseable failpoints instead of timing, runs under both use_hedged_requests values, requires the query to exit successfully, and asserts that Cancelling query because enough data has been read is in system.text_log for the query, so a run that never reaches the cancel path fails instead of passing.

Validated on a two-shard debug build: passes with the fix (3/3, both modes); with the two EndOfStream guards removed the server aborts at MultiplexedConnections.cpp:397 (use_hedged_requests=0) and HedgedConnections.cpp:374 (=1).

Found by the stress test (arm_release), STID 4846-402d:

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. Pauseable failpoint remote_query_executor_receive_packet_pause in read()'s race window + a sibling shard satisfying LIMIT 1 triggers finish()/drain. Aborts on attempt 1 without the fix.
b Root cause explained? TOCTOU: read() releases was_cancelled_mutex before the lock-free receivePacket() (required so a concurrent cancel can unblock the socket); onUpdatePorts()->finish() drains connections when the LIMIT closes the port; receivePacket() then sees 0 active connections and threw LOGICAL_ERROR.
c Fix matches root cause? Yes. Zero active connections is only a logic error when not cancelled; when cancelled==true (set by finish()/cancel() before draining) we report end-of-stream instead of throwing, mirroring drain().
d Test intent preserved / new tests added? New regression test 04512_distributed_limit_no_more_packets_race. A non-cancelled reader still throws LOGICAL_ERROR, so genuine read-past-end bugs are still detected.
e Demonstrated both directions? Yes. Without fix (Build c257f9c5): abort on attempt 1. With fix (Build a07a2c94): 0 crashes / 40 iterations, correct results.
f Fix general, not a narrow patch? Applied to BOTH MultiplexedConnections and HedgedConnections receivePacketUnlocked() (the two IConnections implementations that raise this error).
g Generalizes across inputs? Independent of query shape / types: covers any distributed SELECT ... LIMIT on the sync read path (async_socket_for_remote=0). Both connection classes handled.
h Backward compatible? Yes. No setting/format/protocol change; strictly converts a spurious abort into normal end-of-stream on an already-cancelled stream.
i Invariants preserved? cancelled is monotonic and set under the connections cancel_mutex before draining; end-of-stream on a cancelled+drained connection matches drain()'s contract. was_cancelled is checked immediately after receivePacket() returns, so the empty result is handled identically to the existing cancel path.

Session id: cron:clickhouse-worker-slot-2:20260714-021100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @KochetovNicolai — could you review? This fixes a TOCTOU race in the synchronous distributed-read path: RemoteQueryExecutor::read() releases was_cancelled_mutex before the lock-free receivePacket(), so a concurrent finish()/drain (triggered when a LIMIT closes the output port) can empty the connections and make receivePacket() raise LOGICAL_ERROR "No more packets are available.". The fix reports end-of-stream instead of throwing when the connections were already cancelled, matching drain().

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1f153b5]

Summary: ❌

job_name test_name status info comment
Stress test (amd_asan_ubsan) FAIL
Sanitizer (STID: 1367-26c6) FAIL cidb
Stress test (amd_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb
Stress test (arm_asan_ubsan) FAIL
Sanitizer (STID: 2064-22d0) FAIL cidb

AI Review

Summary

This PR converts the synchronous distributed LIMIT cancel/drain race into normal end-of-stream handling by treating cancelled && !hasActiveConnections() as EndOfStream in both MultiplexedConnections and HedgedConnections, and it adds a deterministic two-shard regression test that pins the interleaving with failpoints. I re-checked the current diff against the prior review threads and did not find any remaining blockers or majors; the test now covers both use_hedged_requests modes, asserts successful client completion, and verifies that the cancel path actually ran. Residual scope note: the regression coverage is intentionally limited to the synchronous async_socket_for_remote=0 path, which matches the bug the PR describes.

Final Verdict

✅ No new findings. The current revision matches the stated bug-fix contract and looks ready from a correctness-review perspective.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.00% 79.00% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both points addressed in ce114e4.

  1. Cancel/drain synchronization instead of sleep 1. Added a second pauseable failpoint remote_query_executor_finish_drain_pause on the drain path in RemoteQueryExecutor::finish(), reached only after that executor has cancelled and fully drained its connections (cancelled == true, hasActiveConnections() == false) - exactly the state the reader observes when it wakes. The test now WAITs for that failpoint before releasing the paused reader, so the reader provably resumes only after the drain the fix depends on, not on a timer. The new failpoint is gated on a per-executor flag in_receive_packet_window, set only by the reader actually parked in read()'s race window, so a sibling shard's finish() (which also cancels and drains) cannot satisfy the wait.

  2. Both IConnections impls. The query now runs under use_hedged_requests=0 (MultiplexedConnections) and use_hedged_requests=1 (HedgedConnections), both with async_socket_for_remote=0 to select the synchronous read() path. Verified locally on a debug build, two-shard cluster: removing the fix aborts in both MultiplexedConnections::receivePacketUnlocked and HedgedConnections::receivePacketUnlocked with Logical error: 'No more packets are available.'; with the fix the server stays alive in both modes. In every run the two WAIT FAILPOINT ... PAUSE returned without timeout, confirming the interleaving is deterministic.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Two failpoints (remote_query_executor_receive_packet_pause + new remote_query_executor_finish_drain_pause) pause the reader in read()'s window and the same executor's finish() after it drains; WAIT ... PAUSE on both makes the interleaving exact. The failure fires every run without the fix.
b Root cause explained? read() releases was_cancelled_mutex, then calls receivePacket() lock-free. When a LIMIT closes the port, onUpdatePorts -> finish() on the same executor cancels and drains all connections. A reader caught in that window then finds no active connections and threw LOGICAL_ERROR, though the query was cancelled (nothing more to read).
c Fix matches root cause? Yes. On zero active connections, if the connection set is already cancelled, report EndOfStream instead of throwing; only a non-cancelled query there is a real logic error. Applied in both MultiplexedConnections and HedgedConnections.
d Test intent preserved / new tests added? This PR IS the regression test hardening. It still asserts the server survives the race; it now does so deterministically (no sleep) and under both connection impls.
e Both directions demonstrated? Yes. Debug build, two-shard cluster: fix removed -> abort in MultiplexedConnections::receivePacketUnlocked (hedged=0) and HedgedConnections::receivePacketUnlocked (hedged=1) with No more packets are available.; fix present -> server alive both modes, clickhouse-test 5/5 OK.
f Fix is general across code paths? Yes. Both IConnections implementations that reach the hasActiveConnections()==false branch are fixed, and the test now exercises both.
g Fix generalizes across inputs? The condition is data-type independent (it is a connection/cancel state check, not a value path); the race depends on cancel timing, not on column types or setting values.
h Backward compatible? Yes. New behavior only replaces a debug/sanitizer abort with the normal end-of-stream that release builds already tolerated; no setting, format, or protocol change.
i Invariants and contracts preserved? Yes. receivePacketUnlocked returns EndOfStream only after sendCancel() set cancelled and connections drained, matching drain()'s contract. The test-only flag/pause are no-ops when the failpoints are disabled (ordinary runs), so the production drain contract is unchanged.

Session id: cron:clickhouse-worker-slot-0:20260714-081900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Two-shard test_cluster_two_shards, SELECT x FROM dist LIMIT 1 with async_socket_for_remote=0, failpoint remote_query_executor_receive_packet_pause parks the reader and remote_query_executor_finish_drain_pause gates on the parked executor's own drain. Aborts every run without the fix.
b Root cause explained? The drain-pause flag in_receive_packet_window was set before the pause and cleared only after receivePacket() returned, so it advertised "somewhere inside receivePacket()". With both failpoints PAUSEABLE_ONCE a sibling shard's normal receivePacket() could satisfy the drain-pause WAIT, releasing the parked reader before its own finish() drained.
c Fix matches root cause? Yes. The flag is cleared immediately after the pause returns, before receivePacket(), so it strictly means "parked at the pause right now".
d Test intent preserved? Yes. The test still deterministically hits the cancel/drain race the code fix addresses, now correctly pinned to the parked reader, under both IConnections impls.
e Demonstrated both directions? Yes. Fix removed: hedged=0 aborts at MultiplexedConnections.cpp:398, hedged=1 at HedgedConnections.cpp:375; fix present: both alive, 3 iterations each, WAIT PAUSE r=0 (no timeout).
f Fix general, not narrow patch? Yes. The synchronization change is impl-agnostic and the test exercises both MultiplexedConnections and HedgedConnections.
g Generalizes across inputs? N/A (test-synchronization robustness fix, not a data-path code bug).
h Backward compatible? Yes. in_receive_packet_window is a test-only flag gating disabled-by-default failpoints; no behavior change in ordinary runs.
i Invariants preserved? Yes. The flag is still set/cleared on the same thread that reads; no lock or ownership change. receivePacket() semantics unchanged.

Session id: cron:clickhouse-worker-slot-1:20260714-101300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Two failpoints (remote_query_executor_receive_packet_pause, remote_query_executor_finish_drain_pause) + the per-executor in_receive_packet_window flag make the cancel/drain interleaving deterministic; SYSTEM WAIT FAILPOINT ... PAUSE returns without timeout in both hedged modes.
b Root cause explained? Yes. This round is a test-assertion fix: wait $QPID 2>/dev/null swallowed the background query's non-zero exit, so a release build (LOGICAL_ERROR returned to a live server) passed CI; only the debug/ASan abort variant was caught.
c Fix matches root cause? Yes. The query's exit status is now required to be 0 via if ! wait "$QPID" (no `` masking); the error is surfaced on failure.
d Test intent preserved? Strengthened. SELECT 'ok' is kept only as a separate server-liveness check; the assertion now covers both the abort and the error-return variants of the bug.
e Demonstrated in both directions? Yes. Fix present: ok, RC=0, server alive, both modes exit 0. Fix removed (both if (cancelled) EndOfStream blocks deleted, debug Build ID 014bef01): Logical error: 'No more packets are available.' in MultiplexedConnections::receivePacketUnlocked:392, background query exits non-zero, assertion fails.
f Fix general, not a narrow patch? N/A (test-assertion change; the underlying fix already covers both MultiplexedConnections and HedgedConnections, run here under use_hedged_requests={0,1}).
g Generalizes across inputs? Both IConnections implementations exercised via use_hedged_requests={0,1} with async_socket_for_remote=0.
h Backward compatible? N/A (test-only change).
i Invariants preserved? N/A (test-only change).

Session id: cron:clickhouse-worker-slot-0:20260714-143800

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 1f41bbf

All public CI checks pass on this head (Finish Workflow + Mergeable Check green). No failed tests to own.

Check / test Reason Owner / fixing PR
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260714-220000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 1f41bbf

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
CH Inc sync - CH Inc sync (private, not actionable by us)

Finish Workflow and Mergeable Check are green; all functional/integration/stress checks pass on this head.

Session id: cron:our-pr-ci-monitor:20260715-010000

@azat azat self-assigned this Jul 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 7992f74

Every failure below has an owner: a fixing PR (ours or external). No failure is PR-caused (this PR's diff is the distributed-LIMIT drain fix in RemoteQueryExecutor/HedgedConnections/MultiplexedConnections + the 04512 regression test).

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 01730_distributed_group_by_no_merge_order_by_long flaky (MEMORY_LIMIT_EXCEEDED) #109847 (external, open)
Mergeable Check / PR (aggregators) reflect the single flaky FT above #109847 (external, open)
CH Inc sync - CH Inc sync (private, not actionable)

01730_distributed_group_by_no_merge_order_by_long is a chronic MEMORY_LIMIT_EXCEEDED flaky (19 master hits + ~24 unrelated PRs in 30d), unrelated to this PR's changed files. Its engine-level fix is #109847 (aggregation hash-table stats cache key). All other public checks pass.

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.30% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c1cf381

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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit trunk regression, not caused by this diff (fires on master and on ~50 unrelated PRs in the same window) #112385 (mine, merged 2026-07-29 15:37Z); this build predates it, so a rerun after the next master merge picks it up
Integration tests (arm_binary, distributed plan, 2/4) / test_system_stop.py::test_refresh_survives_unready_dependencies, ::test_stopped_table_releases_hash_ring_slot master regression in the s3_queue streaming-stop path, root-caused to the ObjectStorageQueueSource::FileIterator out-of-bounds abort; 90 and 41 hits over 64 and 39 unrelated PRs plus master in 30 days #108977 (mine, open)
Sync - CH Inc sync (private, not actionable)

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c1cf381

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit fails 3/3 reruns under parallel replicas on coverage builds #112385 (ours, merged 2026-07-29 15:37Z) - this build predates the fix
Integration tests (arm_binary, distributed plan, 2/4) / test_storage_s3_queue/test_system_stop.py::test_stopped_table_releases_hash_ring_slot and ::test_refresh_survives_unready_dependencies server abort in ObjectStorageQueueSource::FileIterator::next; the second test is collateral, failing on its own setup after the server died #108977 (ours, open)

Session id: cron:our-pr-ci-monitor:20260729-164745

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

Egh, one problem of parallel invocation of onUpdatePorts (sigh)

The patch looks OK, but the bug fix is wrong, since

[2026-07-29 10:42:24] 2026-07-29 07:42:24 [ip-172-31-22-76] 2026.07.29 12:42:16.800454 [ 674 ] {1795dbd5-707e-47ca-84ca-5129420799e2} executeQuery: Code: 36. DB::Exception: Cannot find fail point remote_query_executor_receive_packet_pause. (BAD_ARGUMENTS) (version 26.8.1.334 (official build)) (from [::ffff:127.0.0.1]:50248) (comment: 04512_distributed_limit_no_more_packets_race.sh-test_8rx21250) (query 1, line 1) (in query: SYSTEM ENABLE FAILPOINT remote_query_executor_receive_packet_pause), Stack trace (when copying this message, always include the lines below):
[2026-07-29 10:42:24] 2026-07-29 07:42:24

Though the test looks good, but let's make sure that logs for this query contains "Cancelling query because enough data has been read"

Also trim the comments, git commit/PR description, it contains more text that I can read.
And please squash everything the history is useless.

And also keep on eye on CI, if it hanged for days - rebase

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

That Cannot find fail point is Bugfix validation, which downloads a master-HEAD binary and runs only the changed tests against it (bugfix_validation.py: find_master_builds), then inverts the verdict. That binary predates the failpoints this PR adds, so the arming genuinely fails there. libfiu is on by default, so no build class lacks the mechanism.

Your objection holds anyway: the test proceeded after the failed arming, so it could pass without exercising the race. Fixed three ways: a failed SYSTEM ENABLE FAILPOINT now fails the test, every SYSTEM WAIT is checked, and each mode asserts Cancelling query because enough data has been read in system.text_log for its query id.

Verified the assertion discriminates: it is 0 for the same query without LIMIT (cancel path not taken) and 1 with it. Renaming both failpoints to nonexistent names now fails the test, where it previously printed the error and passed.

Comments, commit message and description trimmed. Squashed to one commit, rebased on master.

@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit 1f153b5 - the build was skipped, reused from cache, or predates profile upload.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e6218a7

CI fully finished on this head (the head that addresses @azat's change requests) and it is clean. Every failure line would have an owner; there are none.

Check / test Reason Owner / fixing PR
(none) 158 success, 17 skipped, 0 failures; CIDB reports 0 FAIL/ERROR rows for this commit -

Config Workflow and Finish Workflow both concluded success, so the job matrix really ran (not a dropped/void run).

Session id: cron:our-pr-ci-monitor:20260810-010000

Comment on lines +640 to +641
/// "somewhere inside `receivePacket`"; see its declaration. Kept inside the failpoint action
/// so an ordinary read does not touch it.

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.

"Kept inside the failpoint action so an ordinary read does not touch it."

Feedback for you, this comment is 100% obvious, please stop writing things like this.

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.

The whole comment is useless, it should EXPLAIN why we have this failpoint here, not some random comment for new code

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.

Rewritten to say why the failpoint is there: it parks the reader in the window between the was_cancelled check and receivePacket, which is the window a parallel onUpdatePorts can cancel and drain in.

Comment thread src/Client/HedgedConnections.cpp Outdated
throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot receive packets: no query sent.");
if (!hasActiveConnections())
{
/// A concurrent cancel (`RemoteQueryExecutor::finish`) invalidates every replica, so for an

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.

Add a note about onUpdatePorts()

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.

Added, on both guards: RemoteQueryExecutor::finish cancels and drains these connections from another pipeline thread via onUpdatePorts when LIMIT closes the port, so a reader already past its own check can arrive here with no replica left.

Also corrected a wrong claim in the description while re-reading it: receivePacket and sendCancel share cancel_mutex, so cancellation cannot unblock an in-progress receive. read releases was_cancelled_mutex because finish and cancel take that mutex, not to allow that.

…IT queries

RemoteQueryExecutor::read() checks was_cancelled under was_cancelled_mutex and releases it
before the blocking connections->receivePacket(), because finish() and cancel() take the same
mutex and must not wait for a receive. When a LIMIT closes the output port,
RemoteSource::onUpdatePorts() runs finish() on another pipeline thread and cancels and drains
the same connections. A reader that passed its check before that then found no active
connections and threw LOGICAL_ERROR "No more packets are available.", aborting the server in
debug and sanitizer builds and returning the error to the client in release builds.

Report end-of-stream instead when the query was already cancelled, in both IConnections
implementations. Only a non-cancelled query reaching that point is a real logic error.

The regression test makes the interleaving deterministic with two pauseable failpoints instead
of timing, runs under both use_hedged_requests values, requires the query to exit successfully,
and asserts that the cancellation was logged so a run that never reaches the cancel path, or one
where the failpoints are unavailable, fails instead of passing silently.

Found by the stress test (arm_release), STID 4846-402d.
@groeneai
groeneai force-pushed the fix-distributed-limit-no-more-packets-race branch from e6218a7 to 1f153b5 Compare August 10, 2026 12:35
return ReadResult(Block());
}

/// Parks the reader in the window this fix is about: `was_cancelled` has just been checked

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.

Ok for now, but for future, "this fix is about" is no good, when someone will read the code he/she will not have any context about this, yes blame will tell, but this is one extra step that pollute context.

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.

So, please gather all my push backs of your comments/commits descriptions style and save this into your memory.

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.

Recorded, consolidated with your earlier push-backs on 102926, 106261 and 107307 into one rule: a source comment states the local invariant standing on its own, and it fails if it is obvious from the code below it, or if it only makes sense in terms of a fix. Motivation and history go in the commit message.

Left the wording here as is per "ok for now"; the rule applies from my next PR.

@azat
azat enabled auto-merge August 10, 2026 12:45
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1f153b5

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
Stress test (amd_tsan) / Hung check failed, possible deadlock found cancelled DROP TABLE prometheus never returns from DatabaseCatalog::waitTableFinallyDropped; the test-database teardown convoys behind it on the DDL guard (trunk bug, reproduced on master) a fix task owns it (root cause proven and written up at #114064 (comment), no fix PR yet); fixing-PR link to follow here
Stress test (amd_asan_ubsan) / Sanitizer (STID: 1367-26c6) LeakSanitizer indirect-only leaks whose blocks carry MaterializedCTE + ConstantNode + QueryTreeBuilder frames (one MaterializedCTE/QueryPlan retain cycle; STID is a report-shape hash, not a root cause) fixing PR 113397 (external, open) - same retain cycle, weak-ptr fix in MaterializingCTEStep + addPlansForMaterializingCTEs
Stress test (arm_asan_ubsan) / Sanitizer (STID: 2064-22d0) same CTE retain cycle as above, different report-shape hash fixing PR 113397 (external, open) - same retain cycle, weak-ptr fix in MaterializingCTEStep + addPlansForMaterializingCTEs

None is caused by this PR. The hung root is is_cancelled = 1 at 2606.00s on DROP TABLE prometheus, with the rest of the hung set strictly shorter DDL-guard victims in one test
database; both leak reports were frame-checked for the CTE cycle rather than matched on STID.

Session id: cron:our-pr-ci-monitor:20260810-173000

@azat
azat added this pull request to the merge queue Aug 10, 2026
Merged via the queue into ClickHouse:master with commit 259bc44 Aug 10, 2026
177 of 181 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 Aug 10, 2026
Comment on lines +20 to +40
FP_RECV="remote_query_executor_receive_packet_pause"
FP_DRAIN="remote_query_executor_finish_drain_pause"

function cleanup()
{
$CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT $FP_RECV" 2>/dev/null ||:
$CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT $FP_DRAIN" 2>/dev/null ||:
wait 2>/dev/null ||:
$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.src" 2>/dev/null ||:
$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.dist" 2>/dev/null ||:
}
trap cleanup EXIT

$CLICKHOUSE_CLIENT --query "
DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.src;
CREATE TABLE ${CLICKHOUSE_DATABASE}.src (x UInt64) ENGINE = MergeTree ORDER BY x;
INSERT INTO ${CLICKHOUSE_DATABASE}.src SELECT number FROM numbers(100000);
DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.dist;
CREATE TABLE ${CLICKHOUSE_DATABASE}.dist AS ${CLICKHOUSE_DATABASE}.src
ENGINE = Distributed(test_cluster_two_shards, ${CLICKHOUSE_DATABASE}, src);
"

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.

@groeneai, rewrite this test; it is very bad. It will stop the worker thread of executor during the processor's work at the failpoint. It breaks the semantics of a work method.

Remember: Work should never wait for some action, sleep, use condvar etc.

Look into comment in IProcessor

  • Synchronous work must only use CPU - don't do any sleep, IO wait, network wait.

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.

@groeneai Also look into all tests you committed during the last 4 months and clean up the same problem.

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.

Acknowledged. Both pause sites #110334 added are affected, not only the one this test drives: remote_query_executor_receive_packet_pause sits under ISource::work() -> tryGenerate() -> RemoteQueryExecutor::read(), and remote_query_executor_finish_drain_pause under RemoteSource::work()/onUpdatePorts() -> finish().

This PR is merged, so I will do both parts in a follow-up PR: rewrite 04512 so the deterministic synchronization point is outside work(), and audit the tests I committed since May for the same shape (a PAUSE failpoint whose site is reachable from a work()/onUpdatePorts() frame). I will link it here with the audit result.

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.

Done in #119030.

Both pause sites this PR added are gone, along with five more of the same shape. Each rendezvous is replaced by injecting, on the same thread, the exact action the external actor used to perform, so nothing waits inside work(): 04512's failpoint now calls finish() inline in RemoteQueryExecutor::read(), and the four KILL QUERY tests call Context::killCurrentQuery() at the same point instead of parking. 04162's rendezvous was a duration rather than an action, so it moved off the pipeline onto the refresh BackgroundSchedulePool thread.

Audit result, on the criterion I gave above (my tests since 2026-05-08 that arm a PAUSE failpoint, then whether the paused site is reachable from a work() / tryGenerate() / onFinish() / onUpdatePorts() frame): 15 of my test files arm one, and 9 failpoints in 8 of them have an in-work() site. 7 are fixed in that PR. The remaining two, 04905_lwu_drop_race_table_lock and 03100_lwu_57_lock_acquire_timeout, both need a query-thread rendezvous on the lightweight-update lock path, which means two new production failpoints plus a 582-line test, so I split them into a follow-up PR instead of burying them here and will link it in this thread. One more, replicated_merge_tree_insert_retry_pause in 03916, is armed but never reached, so nothing parks in it.

One borderline I would rather you ruled on than decided silently: 05060_distributed_sync_insert_cancel_does_not_wait parks distributed_sink_pause_before_push, which runs on a DistributedInsertThreads pool thread and so is not itself in a work() frame, but the pipeline worker that called DistributedSink::consume() does sit in waitForJobs() for as long as the park lasts. I left it as it is because that wait is distributed_foreground_insert's own production behaviour rather than something the failpoint introduces. If you would rather it moved too, I will do that.

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.

Done in #119069.

It needed one new failpoint rather than the two I predicted above, and not on the lightweight-update path. Both lock families are already taken while the pipeline is built and released only by its teardown: the table share lock into the pipeline's resources, the lightweight-update lock into the patch sink. So one pause in BlockIO::onFinish, after releaseQuerySlot() and before that teardown, holds both on the query thread with no work() frame, and serves both tests. Neither reference file changes, and 03100_lwu_57 keeps all 22 of its assertions.

Since that site is query plumbing rather than something lightweight-update specific, the pause is gated on a query-id prefix outside the fiu evaluation, the way QueryMetricLog::finishQuery already is; ungated, the one-shot arm could be consumed by any completed pipeline. If you would rather the hook sat at the end of CompletedPipelineExecutor::execute() or in TCPHandler, it is a one-line move and neither test changes.

That is the audit finished: these two were the remainder.

otselnik pushed a commit to otselnik/ClickHouse that referenced this pull request Sep 10, 2026
04512_distributed_limit_no_more_packets_race parked a PipelineExecutor worker inside
IProcessor::work(): SYSTEM WAIT FAILPOINT ... PAUSE blocked RemoteQueryExecutor::read() on an
unbounded condvar while the test cancelled and drained the connections from outside. src/Processors/
IProcessor.h states synchronous work() must only use CPU, no sleep, IO wait or network wait, and a
parked work() holds a thread-pool slot for as long as the test takes to notice and resume it.

The defect the test covers is a state, not an interleaving. The fix in ClickHouse#110334 lives in
MultiplexedConnections::receivePacketUnlocked and HedgedConnections::receivePacketUnlocked: with
!hasActiveConnections() and cancelled, return EndOfStream instead of throwing LOGICAL_ERROR
"No more packets are available.". A reader only has to arrive at receivePacket with the connections
cancelled and drained; which thread produced that state is irrelevant. So a single non-blocking ONCE
failpoint now calls finish() inline at the same point - the exact call RemoteSource::onUpdatePorts()
makes - and the reader continues into the fixed predicate on its own thread. was_cancelled_mutex is
not held there (the injection sits between two LockAndBlocker scopes) and finish() takes it itself.
Both of its exits reach cancelled && !hasActiveConnections(): the drain loop invalidates each replica
on EndOfStream, and the drain_was_skipped branch disconnects them.

This deletes both PAUSEABLE_ONCE failpoints, the second pause site in finish() and the
in_receive_packet_window member that existed only to keep the two parks paired.

The test drops LIMIT 1 and max_block_size=1: with the cancel injected in place, a LIMIT could
satisfy itself and cancel both executors before either reader entered the loop, so the failpoint
would never fire, whereas without a LIMIT both readers must enter it and the injection sits at the
top before the first receivePacket. The system.text_log positive control is replaced by reading
`enabled` from system.fail_points before and after the query with no DISABLE in between: 1 then 0 can
only happen through a fire, while `enabled = 0` alone is also what an un-armed failpoint reads. Both
use_hedged_requests values are kept because each connection class carries its own copy of the fixed
predicate.

Reported by @Michicosun on ClickHouse#110334.

Co-Authored-By: Claude Opus 5 <[email protected]>
otselnik pushed a commit to otselnik/ClickHouse that referenced this pull request Sep 10, 2026
The mid-loop failpoint in AggregatingInOrderTransform::consume() existed so that
test_aggregating_in_order_transform_kill_query could issue KILL QUERY while the transform sat
between key intervals. It parked a PipelineExecutor worker inside IProcessor::work() on an unbounded
condvar, which src/Processors/IProcessor.h forbids: synchronous work() must only use CPU, no sleep,
IO wait or network wait.

The external actor only performed a cancellation, so the failpoint now performs that same
cancellation in place: Context::killCurrentQuery() is what KILL QUERY itself reaches
(ProcessList::sendCancelToQuery -> QueryStatus::cancelQuery(CANCELLED_BY_USER)), and calling it on
the query's own thread is an existing pattern (src/Server/HTTPHandler.cpp). Nothing it takes is held
by a worker during work(): cancelQuery() takes cancel_mutex, snapshots the executors under
executors_mutex and releases that before cancelling each one, and PipelineExecutor::cancel() is an
atomic status update plus tasks.finish() plus ExecutingGraph::cancel() under processors_mutex, which
is only taken in updatePipeline()/removeGroup() after work() has returned. This transform does not
override onCancel().

The interval-5 guard stays, so the cancel still lands mid-loop and the next iteration's isCancelled()
check logs "Cancelled between key intervals" exactly once. The test keeps all three of its existing
assertions and its QUERY/table/settings, drops the thread and the pool that only served the pause
protocol, and gains a bracketed system.fail_points `enabled` 1 -> 0 oracle so a run in which the
failpoint never fired cannot pass.

Reported by @Michicosun on ClickHouse#110334.

Co-Authored-By: Claude Opus 5 <[email protected]>
otselnik pushed a commit to otselnik/ClickHouse that referenced this pull request Sep 10, 2026
… output formats

Both output formats had a mid-row-loop pause failpoint so that their kill-query tests could issue
KILL QUERY while the format was halfway through writing a chunk to the wire. IOutputFormat::consume()
runs inside IProcessor::work(), so the park was an unbounded condvar wait in a frame whose contract
(src/Processors/IProcessor.h) allows only CPU work.

Both sites now inject the same cancellation the tests used to send from outside, via
Context::killCurrentQuery() on the query's own thread; the row loop's own per-row isCancelled() check
then throws QUERY_WAS_CANCELLED on the next iteration, exactly as before. The lock analysis is the
one in the previous commit, and neither format overrides onCancel().

Both tests keep every existing oracle verbatim, because they are protocol-specific and already
correct: MySQL keeps rows_seen == CANCEL_AT_ROW + 1 (the per-row check is at the top of the loop, so
the row the hook fires on is still sent), PostgreSQL keeps asserting NetworkSendBytes == 0 on its
ExceptionWhileProcessing row instead of a row count because psycopg2 buffers execution, and both keep
the system.processes count, the QUERY_WAS_CANCELLED log assertion and the single-chunk check. Only the
mechanism changes: the thread, the ThreadPoolExecutor, the WAIT FAILPOINT block and the KILL QUERY are
gone, and a bracketed system.fail_points `enabled` 1 -> 0 oracle is added.

Neither protocol lets a client supply a query id, and both tests used to read the server-assigned one
from system.processes while the query was parked. With nothing parked, the id now comes from the
ExceptionWhileProcessing row in system.query_log after a flush, and is asserted non-empty before the
assertions that depend on it.

Reported by @Michicosun on ClickHouse#110334.

Co-Authored-By: Claude Opus 5 <[email protected]>
otselnik pushed a commit to otselnik/ClickHouse that referenced this pull request Sep 10, 2026
…ndow

Both Delta Lake sinks paused in their commit window (data files finalized, delta_transaction->commit
not yet called) so that test_write_cancel_during_commit_keeps_data could KILL the INSERT while the
commit was in flight. SinkToStorage::onFinish() runs under ExceptionKeepingTransform::work(), so the
park violated the IProcessor contract that synchronous work() may only use CPU.

Both sites now call Context::killCurrentQuery() in place, at exactly the same point, which is the same
cancellation KILL QUERY delivers; the lock analysis is the one two commits back, and neither sink
overrides onCancel(). The injection point is unchanged on purpose: the behaviour under test is that the
post-commit clearing of the tracked sinks runs with the query already cancelled, so a late cancel has
no tracked buffers left to unlink and the Delta log cannot end up pointing at removed data files.

The test keeps its post-condition assertions verbatim for both `partitioned` values (the committed rows
are readable and at least one parquet survives) and drops the thread, the WAIT FAILPOINT, the KILL
QUERY, the ASYNC-kill sleep and the NOTIFY that only served the pause protocol. A bracketed
system.fail_points `enabled` 1 -> 0 oracle replaces them, so a run in which the cancel never fired
fails instead of passing on assertions a plain successful INSERT also satisfies.

Reported by @Michicosun on ClickHouse#110334.

Co-Authored-By: Claude Opus 5 <[email protected]>
otselnik pushed a commit to otselnik/ClickHouse that referenced this pull request Sep 10, 2026
04162_system_cancel_view_during_refresh used the infinite_sleep failpoint to hold a refresh alive
until SYSTEM CANCEL VIEW arrived. That site is inside FunctionSleep::execute, reached through
ExpressionTransform::work(), and it sits before sleep()'s max_microseconds bound check and before its
sliced wait loop, so it bypassed exactly the machinery that keeps sleep() from occupying a worker
indefinitely. src/Processors/IProcessor.h forbids waiting inside work() at all.

Here the rendezvous is a duration, not an action, so it cannot be injected in place; it moves to a
thread that is allowed to wait. What the test needs is a cancel that finds a live, published executor,
which is what the asserted "Cancelling refresh in <db>.<view>" line requires, and that state already
exists on the RefreshTask (BackgroundSchedulePool) thread before any worker starts: the executor is
constructed and initialized, published to execution.executor under executor_mutex, that mutex is
released, the clearing SCOPE_EXIT is registered, and only then does executor.execute() run. A new
PAUSEABLE_ONCE failpoint parks in that gap. interruptExecution() can therefore take executor_mutex and
cancel; cancelling a not-yet-started executor is explicitly supported by PipelineExecutor::cancel, and
interruptExecution() also kills the refresh query, so the released executor.execute() unwinds and the
post-pipeline interrupt re-check raises the QUERY_WAS_CANCELLED the test asserts on.

The two existing refresh_mv_pause_* failpoints could not be reused: both sit after executor.execute()
has returned, where the SCOPE_EXIT has already cleared execution.executor, so interruptExecution() is a
no-op there and the asserted log line is never written.

Because no pipeline runs while parked, the test drops sleepEachRow(0) and the max_block_size /
max_threads settings it needed, and drops the read_rows > 0 wait: progress can no longer be observed,
and the property it stood in for (the cancel has a concrete pipeline to interrupt) is now guaranteed by
where the failpoint fires. `wait_status c Running` replaces it as the "the parked refresh is ours"
check. All three assertions are kept verbatim, and a bracketed system.fail_points `enabled` 1 -> 0
oracle is added so a run that never parked fails instead of passing vacuously.

Reported by @Michicosun on ClickHouse#110334.

Co-Authored-By: Claude Opus 5 <[email protected]>
otselnik pushed a commit to otselnik/ClickHouse that referenced this pull request Sep 10, 2026
The park sits between the executor's publication and executor.execute(), so the refresh owns a live
executor that has not run yet and read_rows must be 0. Nothing in the test observed that. Every other
assertion holds equally if the park moves to after executor.execute() returns: execution.executor is
still published there, so "Cancelling refresh in <db>.c" is still logged, and
execution.interrupt_execution still raises QUERY_WAS_CANCELLED on the post-pipeline re-check.

The previous commit dropped the merged test's read_rows > 0 wait because progress can no longer be
observed once no pipeline runs while parked. Its mirror image is observable, and is what belongs here.
The value is stable rather than racy: execution.progress.reset() is the first statement of
executeRefreshUnlocked, the same call that parks, and SYSTEM WAIT FAILPOINT PAUSE has already returned
when the value is read, so the refresh thread is provably parked and nothing can advance the counter.

Verified by moving the park to immediately after executor.execute(), inside the same block: the new
line goes 0 -> 1 while the three original columns stay 1 1 1, so it is the only assertion that sees
that placement. Moving the park before the publication instead reddens only the third column, so the
two directions now bracket the placement.

Reported by @Michicosun on ClickHouse#110334.

Co-Authored-By: Claude Opus 5 <[email protected]>
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Sep 16, 2026
…on-cancel

Conflicts in `FailPoint.cpp` and `RemoteQueryExecutor.cpp`: master (ClickHouse#119069, after the
review request on ClickHouse#110334 that no test may park a pipeline worker inside `IProcessor::work`)
removed the `remote_query_executor_receive_packet_pause` reader park and the
`in_receive_packet_window` flag that guarded this PR's `finish` and `cancel` holds, replacing
04512's fixture with the inline `remote_query_executor_cancel_and_drain_in_receive_window`.

Resolved by taking master's failpoint and dropping the reader park here too. The three holds
stay, guarded by a new executor-local pin instead: `remote_query_executor_finish_entry_hold`
fires once, and the executor that fires it sets `owns_test_holds`, so the drain hold and the
cancel-gate hold can only be consumed by that executor and not by the sibling shard. Every
`finish` entry of the pinned executor waits at the entry hold while it is armed, because
`work` and `onUpdatePorts` can enter `finish` on different threads and a second one running
ahead into the drain would defeat the interleaving.

`05076` no longer arms the reader park; scenario A pins through the entry hold and releases
it before waiting for the drain hold, scenario B is unchanged apart from the dropped park.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
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.

5 participants