Repository navigation
Retract pending replica replacements when the hedged factory is stopped - #114065
alexey-milovidov merged 4 commits into
Conversation
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.
|
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 A related pool-hygiene defect exists but is not introduced here. If a cancelled query throws
|
|
cc @azat @KochetovNicolai, could you review this? |
|
Workflow [PR], commit [8c3d5fe] Summary: ✅
AI ReviewSummaryThis PR retracts stale pending hedged replacements when the replica factory is stopped, which does address the empty- Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 22/27 (81.48%) · Uncovered code |
|
|
||
| /// 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()) |
There was a problem hiding this comment.
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:
- offset
0hits the receive-data timeout, sonext_replica_in_processis set and0is pushed intooffsets_queue; - before that replacement connects, the original replica for offset
0produces its first data/progress packet, socan_change_replicaflips tofalsehere; - another offset is still changeable, so this branch does not retract offset
0's queued replacement; - when that queued connection later becomes
READY,processNewReplicaStateunconditionallyemplace_back(connection)and incrementsactive_connection_countfor offset0.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units8 translation units recompiled, 16 s compile time in total, 8 of them have a recent master baseline. |
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.
|
Removed the test; source change unmodified.
The description now carries the CI reports for both sightings, which is the hook's no-new-tests path. |
CI finish ledger - 8c3d5feCI 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
Session id: cron:our-pr-ci-monitor:20260811-170000 |
Closes: #113981
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
LOGICAL_ERROR: There are no events in epollwhen a distributed query withuse_hedged_requestsis cancelled or completes early (for example because of aLIMIT) while areplacement 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
HedgedConnectionsrecords a pending replacement per offset innext_replica_in_process. Threepaths stop the replica factory permanently (
sendCancel,disconnect,disableChangingReplica) andnone cleared that flag or the queue of offsets awaiting a replacement.
The flag is a promise that a replacement is on its way, and
resumePacketReceiverreads it to decidewhether the receive-timeout exit applies. With it still set after the last replica's receiver timed
out, the designed
SOCKET_TIMEOUTis skipped and the loop iterates. The epoll is empty by then, sogetReadyFileDescriptorcallsEpoll::getManyReadywith zero registered events, throwingLOGICAL_ERROR(an abort under debug and sanitizer builds). The promise cannot be kept: the factorythat 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
checkNewReplicacloses that window an iteration later), and I could not make a statelesstest 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 changecould 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
26.9.1.861(included in26.9and later)