Skip to content

Fix hung root queries caused by endless loop in hedged connections - #107899

Open
c-end wants to merge 15 commits into
ClickHouse:masterfrom
c-end:cancelled-hedged-connections
Open

c-end wants to merge 15 commits into
ClickHouse:masterfrom
c-end:cancelled-hedged-connections

Conversation

@c-end

@c-end c-end commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

We (Cloudflare) saw some rare cases of initial queries being stuck forever on some of our clusters. The flamegraphs indicated that they were spending all their time in trying to establish (hedged) connections. Which is weird because all the remote queries were long gone, the root queries were well past their max_execution_time and they were basically hanging around until we restarted the server. Looking into some of them with gdb helped identify what I think is a bug and gets fixed by this PR: When HedgedConnectionsFactory::stopChoosingReplicas() cancels an in-progress connection establisher, the establisher ends up with is_cancelled=true and a null result entry. If startNewReplica() is later called during the drain loop in RemoteQueryExecutor::finish(), getNextIndex() still considers the cancelled replica eligible (null entry, zero error count). resumeConnectionEstablisher() sees isCancelled() and returns CANNOT_CHOOSE, but without marking the replica as failed. startNewConnectionImpl() retries the same replica in a tight loop forever. Since finish() holds was_cancelled_mutex, max_execution_time cannot acquire the mutex to cancel the query.

I've added a unit test because I found it quite hard to reliably reproduce this with an integration test. I do have an integration test that covers a part of it but not sure if it's worth adding.

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 rare cases of hung root queries.

@c-end

c-end commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

@azat could you take a look at this?

@azat azat self-assigned this Jun 18, 2026
@azat azat added the can be tested Allows running workflows for external contributors label Jun 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [135ef12]

Summary: ❌

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

AI Review

Summary

The final PR state keeps the deterministic factory regression test and the getNextIndex guard against reusing a cancelled establisher, but it reverts the follow-up HedgedConnections fixes that were handling cancellation, outer-epoll registration, and queued replacement bookkeeping. Because those reverted paths can still hang drain() or attach a second replica to an offset that has already committed, the current merge result does not satisfy the PR's contract of fixing hung root queries.

Findings

❌ Blockers

  • [src/Client/HedgedConnections.cpp:299-300,320-322; src/Common/Epoll.h:75-77] sendCancel stops the factory without removing hedged_connections_factory.getFileDescriptor() from the outer epoll. Epoll::empty() is just a registration count, so after the last packet/timeout fd is removed, drain() can still see a non-empty outer epoll and block forever on the dead nested-epoll fd because stopChoosingReplicas already emptied the inner factory epoll. Suggested fix: remove the factory fd from the outer epoll as part of the cancel/stop path, using registration state that stays balanced across retries.
  • [src/Client/HedgedConnections.cpp:253-258,537-541,551-552,573-575; src/Client/HedgedConnectionsFactory.cpp:388-394] The outer add/remove logic still keys off numberOfProcessingReplicas(), but that function is requested_connections_count - ready_replicas_count, not the number of currently registered factory fds. After any failed hedged attempt, that count stays positive even when no replica is in flight, so a later startNewReplica can skip epoll.add(...) while disconnect / disableChangingReplica still call epoll.remove(...) and throw EPOLL_ERROR on an fd that was never added. Suggested fix: track factory-fd registration explicitly, or base the outer add/remove logic on replicas_in_process_count instead of the historical request counter.
  • [src/Client/HedgedConnections.cpp:396-405,519-542] Timeout events are still processed even after disableChangingReplica has made an offset commit to a replica. If a packet fd and its receive-timeout fd are both ready, consuming the packet first flips can_change_replica to false, but the already queued timeout event still takes the timeout branch, sets next_replica_in_process = true, and starts another hedged connection for the same offset. That can leave two active replicas streaming the same shard. Suggested fix: once can_change_replica is false, ignore or purge timeout events for that offset instead of starting another replica.
  • [src/Client/HedgedConnections.cpp:584-590,603-609] processNewReplicaState(READY) still hands the next ready replacement to offsets_queue.front() without skipping offsets that already committed to a replica. A stale queued offset can therefore consume a fungible ready connection that was really needed by a later offset, while the later offset keeps next_replica_in_process = true; if its active replica then times out, resumePacketReceiver suppresses SOCKET_TIMEOUT and the query can fall back into the same stuck-drain path. Suggested fix: remove or skip stale queued offsets until the front offset still has can_change_replica == true, or clear queued state for an offset in disableChangingReplica.
Final Verdict

Changes requested. The factory-level loop is fixed and the new regression test is solid, but the reverted HedgedConnections paths still leave cancellation and queued-replacement hangs in the current merge result.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 18, 2026
Comment thread src/Client/HedgedConnections.cpp Resolved
@c-end

c-end commented Jun 29, 2026

Copy link
Copy Markdown
Contributor Author

@azat since the AI reviewer seems happy, would you mind taking a look? The test failures look unrelated to me, but happy to fix anything if needed. So far this fix works well in our clusters.

@tuanpach

tuanpach commented Jul 2, 2026

Copy link
Copy Markdown
Member

This PR looks good to me.

@groeneai, please check the CI failure.

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator

@tuanpach both CI reds on 293f422 are pre-existing flakes unrelated to this PR. The diff is entirely client-side (src/Client/Hedged*), which has no path into either failure.

Stress test (arm_release) - Logical error: Unexpected return type from if. Expected UInt64. Got String (STID 2914-4d22). A server-side ActionsDAG type mismatch in the expression executor (if(UInt8, UInt64, v) where column v arrives as String); no connection/failover code is involved. It is a chronic LOGICAL_ERROR class: the "Unexpected return type" family has 77 distinct PRs and 21 master hits in the last 30 days. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107899&sha=293f42290546e04821b9c1cdfb5feb353463cc66&name_0=PR&name_1=Stress%20test%20%28arm_release%29

Integration tests (amd_llvm_coverage, 4/5) - whole-batch Timeout (session-timeout, no individual test FAIL). Chronic coverage-lane slowness (coverage binaries run 3-5x slower than release). 14 distinct PRs and 2 master hits in the last 30 days. Mitigated on master by #108564 (split coverage into more batches, merged 2026-06-28); no coverage timeouts have appeared since 2026-06-26. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107899&sha=293f42290546e04821b9c1cdfb5feb353463cc66&name_0=PR&name_1=Integration%20tests%20%28amd_llvm_coverage%2C%204/5%29

Neither red is caused by this change. A rerun of both jobs on a rebased head should come back green.

@tuanpach

tuanpach commented Jul 2, 2026

Copy link
Copy Markdown
Member

@groeneai, please merge master into this branch.

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator

@tuanpach I'm an outside contributor here, not a ClickHouse maintainer, so I do not have push access to this fork branch (c-end/ClickHouse:cancelled-hedged-connections) and cannot merge master into it myself. The "Allow edits by maintainers" setting grants that access to ClickHouse maintainers, not to me (GitHub returns 403 when I query my permission on the fork).

Who can do the merge:

  • @ c-end (author): click "Update branch" on this PR, or git merge master locally and push.
  • A maintainer (you or @ azat): since "Allow edits by maintainers" is enabled, you can push the merge to the fork branch directly.

CI context: the two reds on 293f422 are both pre-existing flakes unrelated to this client-side (src/Client/Hedged*) change, see my 05:03 comment above. Master now includes #108564 (coverage batch split, merged 2026-06-28), so a refreshed head should rerun green.

Comment thread src/Client/HedgedConnections.cpp Outdated

void HedgedConnections::startNewReplica()
{
if (cancelled)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

startNewReplica now clears the queued-offset state after cancellation, but the cancel path still leaves one more way to hang here. If a hedged replica was already in progress, startNewReplica previously added hedged_connections_factory.getFileDescriptor() to the outer HedgedConnections epoll. sendCancel() then calls stopChoosingReplicas() without the matching epoll.remove(...) that disconnect() and disableChangingReplica() do, and Epoll::empty() is only a registration count. Once the last packet receiver/timeout fd is removed, drain() still sees a non-empty outer epoll and blocks forever on this dead nested-epoll fd because the inner factory epoll has already been emptied, so checkNewReplica() never gets a chance to clean it up.

Please remove the factory fd from the outer epoll in sendCancel() before stopChoosingReplicas() when numberOfProcessingReplicas() > 0, the same way the other shutdown paths already do.

Comment thread src/Client/HedgedConnections.cpp Outdated
/// destroyed (especially when the system is under pressure).
if (hedged_connections_factory.hasEventsInProcess())
{
if (hedged_connections_factory.numberOfProcessingReplicas() > 0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

numberOfProcessingReplicas is not the number of nested-factory fds currently registered in the outer HedgedConnections epoll; it is requested_connections_count - ready_replicas_count in HedgedConnectionsFactory::numberOfProcessingReplicas. After any earlier failed hedged attempt, a later startNewReplica can return NOT_READY without re-adding the factory fd at src/Client/HedgedConnections.cpp:569, because this count is already > 1 even though there is only one current in-flight replica. From that state, this new epoll.remove(...) hits EPOLL_CTL_DEL on an fd that was never added and throws EPOLL_ERROR during cancellation instead of cleaning up the query.

Please base the outer add/remove logic on the actual replicas_in_process_count (or an explicit “factory fd is registered” flag), and add a regression that exercises failed hedged attempt -> new NOT_READY start -> sendCancel.

Comment thread src/Client/HedgedConnections.cpp Outdated

void HedgedConnections::startNewReplica()
{
if (cancelled)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

stopFactory() is also called from disableChangingReplica() once every offset has already committed to a replica, but this guard only suppresses new starts after sendCancel(). A packet fd and its receive-timeout fd can still be ready in the outer epoll at the same time; if getReadyReplicaLocation() processes the packet first, disableChangingReplica() resets the timer and stops the factory, but the already-queued timeout event is still consumed on the next loop iteration. Because cancelled is still false on that path, startNewReplica() will call startNewConnection() again, and the factory is still free to choose an untried replica.

That gives the same offset a second active connection after can_change_replica became false, so both replicas can keep streaming and duplicate the shard's data. Please track that replica selection has been stopped independently of cancelled (or ignore timeout events once can_change_replica is false) so queued timeout events are drained instead of starting another replica after hedging has been disabled.

Comment thread src/Client/HedgedConnections.cpp Outdated
/// getReadyReplicaLocation(), this covers a replacement that was already queued/in-flight
/// before the commit and only became ready afterwards (possible with multiple offsets,
/// where disableChangingReplica() does not stop the factory until every offset commits).
if (!offset_states[offset].can_change_replica)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This still leaves stale queue entries for offsets that have already committed to a replica. A concrete trace is:

  1. Offset A times out and queues A; the only spare replica starts connecting.
  2. Offset B then times out and queues B, but there is no second free replica.
  3. A receives data, so disableChangingReplica flips can_change_replica[A] = false, but A stays at the front of offsets_queue.
  4. When the in-flight connection becomes ready, this branch pops A, sees !can_change_replica, and disconnects the ready connection instead of handing it to B.

At that point B.next_replica_in_process is still true, but the factory has no events left, so if B later loses its active replica we suppress the SOCKET_TIMEOUT / can fall into the same stuck-drain path again.

Once an offset can no longer hedge, its queued entries need to be removed or skipped, not allowed to consume the next fungible ready connection. A fix would be to keep popping stale offsets until you find one with can_change_replica == true (or purge this offset from offsets_queue in disableChangingReplica, e.g. via per-offset queued counts).

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 85.90% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 81/90 (90.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Dear @azat, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@abashkeev abashkeev added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 4, 2026
@azat azat self-assigned this Oct 14, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Dear @azat, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

This branch has not been deployed

No deployments
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 comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants