Skip to content

Retract pending replica replacements when the hedged factory is stopped - #114065

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:hedged-retract-pending-replica-on-stop
Sep 6, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:hedged-retract-pending-replica-on-stop

Conversation

@groeneai

@groeneai groeneai commented Aug 9, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #113981

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

Fixed LOGICAL_ERROR: There are no events in epoll when a distributed query with
use_hedged_requests is cancelled or completes early (for example because of a LIMIT) while a
replacement replica is still pending. The paths that stop choosing new replicas now also clear the
pending-replacement state, so the receive-timeout exit is no longer suppressed. Closes #113981.

Description

HedgedConnections records a pending replacement per offset in next_replica_in_process. Three
paths stop the replica factory permanently (sendCancel, disconnect, disableChangingReplica) and
none cleared that flag or the queue of offsets awaiting a replacement.

The flag is a promise that a replacement is on its way, and resumePacketReceiver reads it to decide
whether the receive-timeout exit applies. With it still set after the last replica's receiver timed
out, the designed SOCKET_TIMEOUT is skipped and the loop iterates. The epoll is empty by then, so
getReadyFileDescriptor calls Epoll::getManyReady with zero registered events, throwing
LOGICAL_ERROR (an abort under debug and sanitizer builds). The promise cannot be kept: the factory
that would deliver it is stopped.

A private helper now stops the factory and drains the queue, called from all three stop paths.
Retraction is unconditional, since an offset can be queued while the factory is already idle. The
change-replica timeout branch no longer starts a replacement once the query is cancelled. Each call
site keeps its existing epoll handling; the helper performs no epoll operation.

CI reports:

No new test. The abort needs the last replica's deadline to expire inside one loop iteration
(normally checkNewReplica closes that window an iteration later), and I could not make a stateless
test fail before the fix, so I removed the one I wrote rather than ship a test that passes on master
HEAD. Validation targets the state instead: on an instrumented build the stale flag and the
suppression at the receive-timeout guard both go from 12/12 to 0/12. test_hedged_requests (15/15)
and test_hedged_requests_parallel (5/5) pass in full and already assert the property this change
could break: a query which changes replica returns the correct row.

Behaviour delta: a cancelled query whose last replica times out with a replacement pending now gets
SOCKET_TIMEOUT, not the logical error.

Version info

  • Merged into: 26.9.1.861 (included in 26.9 and later)

groeneai and others added 3 commits August 9, 2026 16:19
HedgedConnections marks an offset as awaiting a replacement replica by setting
OffsetState::next_replica_in_process and queueing the offset. That promise is
cleared only when the factory later delivers a new connection, but three paths
stop the factory without clearing it: disconnect(), sendCancel() and
disableChangingReplica(). After the factory is stopped no replacement can
arrive, so the flag stays set forever.

resumePacketReceiver() guards its SOCKET_TIMEOUT exit with
"active_connection_count == 0 && !next_replica_in_process", so a stale flag
suppresses the exit the loop was written to take. getReadyReplicaLocation()
then iterates its unbounded while(true) with the epoll already drained, and
Epoll::getManyReady() throws LOGICAL_ERROR "There are no events in epoll",
which aborts the server in debug and sanitizer builds. Two AST fuzzer
sightings, both entering through RemoteQueryExecutor::finish().

Add a helper that stops the factory and retracts the queued promises, and call
it from all three stop paths. The retraction is unconditional because an offset
can be queued while the factory is already idle (the timeout branch queues
before calling startNewReplica(), which returns CANNOT_CHOOSE when the pool is
exhausted).

The helper performs no epoll operation. Each call site keeps its own
pre-existing handling of the factory descriptor instead: disconnect() and
disableChangingReplica() keep their removals, with both original conditions and
their original position before the factory stop, and sendCancel() keeps having
none. Hoisting a removal into the helper would have made sendCancel() attempt
one, and the guard it would be attempted under does not track membership of the
outer epoll in either direction: the descriptor is added by startNewReplica()
gated on numberOfProcessingReplicas() == 1 and removed by checkNewReplica()
gated on that same proxy reading 0, so instrumenting all four sites shows
sendCancel() reached with the descriptor a member while the guard reads false
(10 of 10 traversals). Epoll::remove() decrements events_count before the
syscall and throws EPOLL_ERROR if it fails, and issue ClickHouse#59169 recorded exactly
that ErrnoException escaping disconnect(), so neither direction of the
disagreement is acceptable on a cancellation path.

Also stop starting a replacement after cancellation: the change-replica
timeout branch no longer marks the offset as pending once cancelled is set,
since the factory has already been stopped by sendCancel(). The timer is
still reset and the ProfileEvent still incremented, because the timeout did
expire.

Measured on a five-replica Distributed query where disableChangingReplica()
removes the factory descriptor while a replacement is queued: the stale state
occurs on 12 of 12 runs before this change and 0 of 12 after it, and the
suppressed SOCKET_TIMEOUT exit at the receive-timeout guard likewise goes from
12 of 12 to 0 of 12. Instrumentation recorded no removal of a non-member
descriptor in any run.

Add a pauseable failpoint in sendCancel() so a test can hold a query in the
window between the factory stop and cancelled = true.

The added stateless test is coverage rather than a regression test, and says so
in its header: the abort needs the last replica's receiver deadline to expire
inside a single loop iteration, which no fixture reproduced deterministically,
so instead of asserting an absence of errors it pins the behaviour this change
could break -- that a replacement the factory can still honour is still waited
for -- and asserts a HedgedRequestsChangeReplica witness so the coverage cannot
lapse silently.
…s comment

Review found the diff shipped a PAUSEABLE_ONCE failpoint and a pauseFailPoint()
call on the sendCancel path with no consumer anywhere in the repository. The
route it was added to enable was measured non-discriminating (both arms 12/12
Code: 279), so it bought no determinism and is removed rather than kept as
speculative plumbing in a hot cancellation path. This drops
src/Common/FailPoint.cpp from the change entirely.

The liveness-check comment in the new test claimed HedgedRequestsChangeReplica
is incremented exactly where the pending flag is set. That is wrong in two ways:
HedgedConnectionsFactory increments the same event from its own connect-phase
change-replica timer, and this change moves the receive-phase increment above
the new post-cancel bail, so it also fires on the path that deliberately does
not set the flag. The assertions and the .reference are unchanged -- the oracle
is a weak but live guard and stays as it is; only the prose is corrected.

Renames HedgedConnections::stopChoosingReplicas to
stopChoosingReplicasAndRetractPending so it is not confused with the factory
method of the same name, which does strictly less.

No behaviour change: the failpoint was inert unless SYSTEM ENABLE FAILPOINT
named it, and the other two edits are textual.

Co-Authored-By: Claude Fable 5 <[email protected]>
HedgedRequestsChangeReplica counts change-replica timeout expiries and is
incremented by the factory's connect-phase timer as well as the receive-phase
one, so >= 1 does not prove a pending replacement was queued. The printed label
now says what the event actually observes; the oracle is unchanged.
@groeneai

groeneai commented Aug 9, 2026 •

Copy link
Copy Markdown
Collaborator Author

Two things raised in pre-publication review that a reviewer may want, kept here rather than in the description.

A cancelled offset-parallel query can now report SOCKET_TIMEOUT in one state where master reported nothing. The state is an offset whose replacement was legitimately queued before the cancel, whose original replica then goes silent for a full receive_timeout (300 s by default) during the post-cancel drain. Previously the stale flag swallowed that stall. Reporting a timeout for a replica silent for 300 s looks like the intended behaviour of the surrounding code, but if you would rather that case stayed silent, say so and I will gate the retraction.

A related pool-hygiene defect exists but is not introduced here. If a cancelled query throws SOCKET_TIMEOUT for one offset while other connections are active, RemoteQueryExecutor::finish unwinds, its scope guard sets finished, and the destructor skips disconnect(). That SOCKET_TIMEOUT is master's code verbatim, and its guard is already false whenever no replacement is queued, which is the default state. The defect lives in the finish()/destructor interaction, which #110334 is already redesigning.

no-fasttest is kept rather than swapped for linux: both Fast test jobs set fast_tests_only, so no-fasttest also excludes the macOS job, and HedgedConnections is Linux-only, so the witness reads 0 there. 34 other stateless tests using remote() carry it.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @azat @KochetovNicolai, could you review this? HedgedConnections never cleared its per-offset next_replica_in_process promise when a stop path shut the replica factory down, so resumePacketReceiver kept skipping its SOCKET_TIMEOUT exit on a replacement that could no longer arrive and the loop re-entered Epoll::getManyReady on an empty epoll, which is the logical error in #113981.

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

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8c3d5fe]

Summary: ✅


AI Review

Summary

This PR retracts stale pending hedged replacements when the replica factory is stopped, which does address the empty-epoll path in the cancel/stop flow. I still see one correctness blocker in the same state machine: an offset that has already chosen its winner can still attach a late replacement if some other offset is still hedging, so I do not think the patch is safe to merge yet.

Findings

❌ Blockers

  • [src/Client/HedgedConnections.cpp:563] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/114065#discussion_r3745595986] disableChangingReplica only retracts pending replacements when every offset has stopped hedging. If offset 0 hits the receive-data timeout, queues a replacement, and then receives its first data/progress packet before that replacement becomes READY, can_change_replica flips to false but the queued replacement stays alive as long as some other offset is still changeable. processNewReplicaState then later pops that stale queue entry and unconditionally attaches a second connection for the same parallel_replica_offset, breaking the documented OffsetState invariant that active_connection_count <= 1 once can_change_replica is false. That can duplicate rows or otherwise double-process that partition. Retract or tombstone pending replacements for replica_location.offset as soon as that offset stops changing, and discard any later READY connection for a disabled offset instead of attaching it.
Tests
  • ⚠️ I did not find existing coverage for the per-offset race above: "timeout queues a replacement, then first data/progress arrives for that same offset before the replacement becomes READY, while another offset is still allowed to hedge." The current hedged_requests integration tests cover successful hedging, but not this offset-specific disable path.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.80% 91.90% +0.10%
Branches 78.90% 78.90% +0.00%

Changed lines: Changed C/C++ lines covered: 22/27 (81.48%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 9, 2026

/// If we disabled changing replica with all offsets, we need to stop choosing new replicas.
if (hedged_connections_factory.hasEventsInProcess() && offsets_with_disabled_changing_replica == offset_states.size())
if (offsets_with_disabled_changing_replica == offset_states.size())

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.

disableChangingReplica still leaves a queued replacement alive for this specific offset unless every offset has already disabled changing. A concrete trace with max_parallel_replicas > 1 is:

  1. offset 0 hits the receive-data timeout, so next_replica_in_process is set and 0 is pushed into offsets_queue;
  2. before that replacement connects, the original replica for offset 0 produces its first data/progress packet, so can_change_replica flips to false here;
  3. another offset is still changeable, so this branch does not retract offset 0's queued replacement;
  4. when that queued connection later becomes READY, processNewReplicaState unconditionally emplace_back(connection) and increments active_connection_count for offset 0.

That violates the documented OffsetState invariant that active_connection_count <= 1 once can_change_replica is false, and it can start the same parallel_replica_offset twice, producing duplicate rows or other double-processing for that partition. I think we need to retract or tombstone pending replacements for replica_location.offset as soon as that offset stops changing, and discard any later READY connection for a disabled offset instead of attaching it.

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.

disableChangingReplica's all-offsets condition and processNewReplicaState's unconditional attach are both master's code, not this PR's.

processNewReplicaState is byte-identical at the base f9801d56492b and at the head 47663739fa1b (md5 98bc6707648ae5714c76420c1ca27c27 at both revisions), and this diff adds no hunk in it. The condition you cite at :563 is master's :545 verbatim, except that I moved hasEventsInProcess() out of it into the inner epoll guard, which does not touch the quantifier.

In the trace you give, offset 0 is disabled while another offset is still changeable, so offsets_with_disabled_changing_replica == offset_states.size() is false and the retraction does not run. Master behaves identically there, so the residue you describe is reachable without this change, and this change neither introduces nor widens it.

What this change does alter: master retracted offsets_queue only in the CANNOT_CHOOSE branch of processNewReplicaState, so a pending entry could outlive the factory that was supposed to fulfil it. Retraction now also runs at sendCancel, at disconnect, and in the all-offsets branch of disableChangingReplica, which strictly shrinks that set and is what fixes #113981.

On the suggested per-offset retraction: offsets_queue is a std::queue<int>, and the READY branch pairs the arriving connection with offsets_queue.front() positionally, with no identity check and no emptiness guard. Dropping one offset's entry from the middle would attach the next replacement that arrives to a different offset, or reach front() on an empty queue. Tombstoning per offset therefore needs the replacement-pairing model changed too, which is a larger change than tightening this fix.

I have not reproduced a double attach on master, so I am not claiming it as a bug here.

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8c3d5fe31 with master aa1a69b2a (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
Binary Master PR Δ
programs/clickhouse-stripped 690.92 MiB 687.90 MiB -3.03 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

Bugfix validation ran 04860_hedged_pending_replica_retracted_on_stop against
the master-HEAD binary on both arches and it passed every time (4 runs on
amd64, same on aarch64), so the job reported "Bug does not reproduce on this
arch" and new_tests_check.py failed the workflow. That verdict is correct: on a
pr-bugfix PR a new functional test must fail without the fix, and this one
cannot. The abort it relates to needs the last replica's receiver deadline to
expire inside a single loop iteration, which no stateless fixture reached in
118 attempts across 11 shapes.

The test asserted the property the fix could break rather than the bug itself,
and its header said so. That property is already covered by
test_hedged_requests and test_hedged_requests_parallel, whose check_query
asserts the returned row after a change-replica event, so removing the file
loses no coverage.

With no new functional or integration test in the diff, the hook takes its
documented no-new-tests branch and accepts a CI report link as evidence the bug
exists; the PR body now carries the reports for both fuzzer sightings.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Removed the test; source change unmodified.

Bugfix validation ran 04860_hedged_pending_replica_retracted_on_stop against the master-HEAD
binary and it passed on both arches, so new_tests_check.py failed the workflow. That verdict is
correct: on a pr-bugfix PR a new functional test must fail without the fix, and this one cannot.
It asserted the property the fix could break rather than the bug, and that property is already
covered by test_hedged_requests / test_hedged_requests_parallel, whose check_query asserts the
returned row after a change-replica event.

The description now carries the CI reports for both sightings, which is the hook's no-new-tests path.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8c3d5fe

CI is fully finished on this head and every check that ran is green: 151 success, 24 skipped, 0 failure. The praktika report's top-level status is OK with 0 dropped jobs, so the skips are genuine config-level skips ("not affected by the changed files", "no build-affecting changes", "reused from cache"), not a dropped matrix.

Check / test Reason Owner / fixing PR
none no failures on this head -
Sync - CH Inc sync (private, not actionable)

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

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 4, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 6, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 6, 2026
Merged via the queue into ClickHouse:master with commit b2bb5c5 Sep 6, 2026
182 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 6, 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 comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

AST fuzzer: Logical error 'There are no events in epoll' in HedgedConnections::getReadyFileDescriptor during RemoteQueryExecutor::finish

3 participants