Repository navigation
Conversation
PacketReceiver::checkTimeout and RemoteQueryExecutorReadContext::checkTimeout inspect the descriptors of one epoll wake and set a member flag as soon as the timer descriptor appears, before it is combined with socket readiness on the next line. Nothing ever clears either flag: each has a single write, two reads and no assignment back to false, and neither clearAsyncEvent() nor AsyncTaskExecutor::restart() resets it. A wake in which the socket and the timer are ready at the same time therefore returns true and delivers its packet correctly, while leaving the connection permanently flagged as timed out. With use_hedged_requests = 1 isPacketReady() is then stuck false, so HedgedConnections::resumePacketReceiver can no longer take the packet-ready branch, falls through to isTimeoutExpired() and throws SOCKET_TIMEOUT; the per-packet setTimeout() re-arm in the packet-ready branch also becomes unreachable, which silently disables the property that receive_timeout is a per-packet idle timeout rather than a total query timeout (4669951). With async_socket_for_remote = 1 the latched flag makes the guard throw on the first later wake in which the socket is not ready, and makes cancelBefore() skip draining the pending packet, so cancellation logs "Connection to ... terminated (NETWORK_ERROR)". The synchronous path has no epoll timer and is unaffected. Timer readiness observed in a single wake only means a receive timeout happened when the socket was not ready in that same wake, so it must not be stored as connection state. Make the observation a function-local in both places and keep a member that records only the verdict of the conjunction, set exclusively in the branch that already declares the timeout. PacketReceiver::setTimeout() clears that verdict, because re-arming the timer starts a new receive interval; the two consumers that need the verdict to persist across calls (HedgedConnections::resumePacketReceiver and cancelBefore(), which uses it to skip a drain that would otherwise block for a full receive_timeout) keep working. ConnectionEstablisherAsync::checkTimeout, the third and only other AsyncTaskExecutor, already uses a function-local for the identical loop and is left unchanged as the reference. Found through intermittent failures of 02805_distributed_queries_timeouts, which is the regression test for the per-packet timeout property the latch was disabling. That test is not modified. Verified by instrumented builds showing that 11 of 12 thrown timeouts on unfixed master arose from a single wake that genuinely observed an idle socket, while with the fix every thrown timeout is backed by such a wake, and by two unit tests covering both carriers and both directions, with each production hunk reverted individually to confirm the corresponding assertion fails. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Both SimultaneousReadinessLeavesNoTimeoutResidue tests armed a 10 ms timer and then slept for a fixed 200 ms without ever asserting that the timer descriptor had become readable. In those tests the socket is deliberately readable, so a sleep that returns early leaves a wake carrying only the socket, and in such a wake the unfixed code satisfies every assertion too: the flag is only set when the timer descriptor appears. The one case that carries the discriminating scenario could therefore degenerate into "a readable socket means no timeout" and stop discriminating, silently. Each case now waits for the timer descriptor with a bounded poll loop and fails if it never becomes readable. With that wait deliberately shortened to a zero budget and no retry, all seven cases fail on that assertion, so it detects the state it exists to detect; with the assertion kept but made unable to fail, the mutants that revert the production hunks still fail exactly the tests they failed before, so it is not what makes them fail. CancelAfterDeclaredTimeoutDoesNotWaitForPendingPacket was the only case calling cancelBefore(), and it covered only the branch that skips the drain after a genuine timeout. An implementation whose guard always skipped the drain passed the whole suite, yet skipping the drain for a connection that never timed out is the mechanism behind the reported "Error occurs on cancellation" NETWORK_ERROR. CancelWithoutDeclaredTimeoutDrainsPendingPacket pins that direction: after a simultaneous-readiness wake, with no timeout declared, cancelBefore() must enter its drain loop, which is observable because the loop's blocking checkTimeout() then throws SOCKET_TIMEOUT out of cancelBefore(). Hardwiring the guard to skip makes it return without throwing and fails only this case. Reverting the async carrier to the latched member fails this case as well, which demonstrates rather than argues the causal link the description draws to the NETWORK_ERROR. Its wall-clock expectation is also replaced by the structural one: entering the drain loop is what throws, so the absence of a throw already carries the signal, while an elapsed-time bound only measures the re-armed timer expiry. No production file changes. The five production files are byte-identical to the previous commit, and rebuilding after deleting every changed object reproduces the same binary bit-for-bit. CI reports for the failures this fixes, each labelled with the statement of 02805_distributed_queries_timeouts that failed: line 4, hedged path: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112083&sha=67a6ecc5b2e584b344f5208cddeee29b4895f14a&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20WasmEdge%2C%20parallel%2C%202%2F2%29 line 4, hedged path: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110215&sha=f34341a1daeac43163f56f8712e96181bcf4f7ac&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20parallel%29 line 5, async path, ClickHouse#109490: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109490&sha=0ad689784288cc72d7976732460395359de7171b&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29 The previous commit also cited a master failure on commit 862617d. That one failed on line 6, the synchronous statement, and carries the "peer: ..., local: ..., 7000 ms" message that only ReadBufferFromPocoSocket emits from a per-recv Poco timeout, not the "(socket description, receive timeout N ms)" message both changed carriers produce. It is not fixed here and is no longer cited as such. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Internal second-model review (2 rounds, 15 findings adjudicated, 13 AGREE / 2 DISAGREE)Every change in this pull request was reviewed by a second model independently of the one that Round 1❌ Blocker: the description cited a CI failure this change cannot fix. The first report ❌ Major: the discriminating test could pass vacuously. Both simultaneous-readiness cases ❌ Major: the cancellation contract was pinned in one direction only. The single case calling ❌ Two majors in the description itself, both fixed: it claimed every stateless test naming Round 2
💡 Three further nits corrected in the description: one latched flag has three reads at the ✅ DISAGREE, with evidence. The bounded wait helper is byte-identical in both test files, but |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260728-043001 |
|
cc @azat @yariks5s - could you review this? Both async remote-read |
|
Workflow [PR], commit [e5af8d3] Summary: ❌
AI ReviewSummaryThis PR fixes a real timeout-state bug in the async remote-read and hedged-read paths by keeping only the declared timeout verdict as persistent state and leaving one-epoll-wake timer readiness local to Final Verdict
|
Build (arm_tidy) failed on this PR with two
readability-make-member-function-const errors (warnings-as-errors) in the
new gtest fixture:
src/Client/tests/gtest_packet_receiver_timeout_latch.cpp:51:10:
method 'checkTimeout' can be made const
src/Client/tests/gtest_packet_receiver_timeout_latch.cpp:54:10:
method 'setTimeout' can be made const
Both accessors reach the receiver through a std::unique_ptr member, so
mutating the pointee from a const method is well-formed and the check is
right: const-qualifying them is behaviour-preserving. The two neighbouring
accessors are already const, so this also makes the fixture consistent.
The sibling gtest is unaffected because it holds its subject by value, where
const would forbid the mutation.
Verified with clang-tidy-21 (the version CI uses) against the build's
compile_commands.json: both new translation units are clean with this change,
and reverting either const reproduces exactly the two CI errors. All 7 tests
in the two new suites still pass.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Trim the historical preambles and the step-by-step restatements of the assertions, keeping the parts that are not clear from the code itself: why the timer readiness is awaited rather than slept on, why the bytes have to be consumed (epoll is level-triggered), and why the presence or absence of a throw is the oracle for the drain loop. Also drop the "()" from method names in the retained comments. No behaviour change: both files still produce the same 7 passing tests, and clang-tidy-21 is clean on both translation units. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
arm_tidy fix pushed:
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 197/210 (93.81%) · Uncovered code |
CI finish ledger - e5af8d3Every failure below has an owner. Only
Nothing else failed: 173 of 174 checks are green, On the one non-green job: it reports Session id: cron:our-pr-ci-monitor:20260728-163000 |
|
@alexey-milovidov we need this PR to fix CI |
No related open issue found. The regression test whose invariant this restores is
02805_distributed_queries_timeouts, added by commit 4669951 ("Fix timeout for hedged requests"), removed for flakiness by #66563 and reintroduced with a wider margin by #67106.CI reports for the failures this fixes (the failing checks belong to unrelated pull requests, so they are linked as reports rather than as pull request references). Each one is labelled with the statement of
02805_distributed_queries_timeoutsthat failed, so the attribution can be checked in one click:HedgedConnections::resumePacketReceiver,Stateless tests (amd_msan, WasmEdge, parallel, 2/2): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112083&sha=67a6ecc5b2e584b344f5208cddeee29b4895f14a&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20WasmEdge%2C%20parallel%2C%202%2F2%29Stateless tests (arm_asan_ubsan, azure, parallel): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110215&sha=f34341a1daeac43163f56f8712e96181bcf4f7ac&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20parallel%29RemoteQueryExecutorReadContext::checkTimeout,Stateless tests (amd_tsan, parallel): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109490&sha=0ad689784288cc72d7976732460395359de7171b&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29The same test has also failed once on its synchronous statement (line 6, on master, commit 862617d). That failure carries the
peer: ..., local: ..., 7000 msmessage, which onlyReadBufferFromPocoSocketemits from aPoco::TimeoutExceptionon a singlerecv, rather than the(socket description, receive timeout N ms)message that both changed carriers produce. It comes from the synchronous path and this change does not address it. That report also contains aRemoteSource: Error occurs on cancellation ... (NETWORK_ERROR)line, so that log alone does not identify the latch: it appears on the synchronous failure too, and on neither of the two hedged failures above. It does appear on the async failure, which is the one path where the latch reachescancelBefore(). The message that identifies a carrier is the timeout message form, not the cancellation log.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a spurious
SOCKET_TIMEOUT("Timeout exceeded while reading from socket") on distributed queries. When one epoll wake reported the receive timer and the socket as ready at the same time, the packet was delivered correctly but the connection was permanently marked as timed out, so a later packet failed the query even though the remote replica was responding on time. Affects reads withuse_hedged_requests = 1and withasync_socket_for_remote = 1.Description
PacketReceiver::checkTimeoutandRemoteQueryExecutorReadContext::checkTimeoutinspect the descriptors returned by one epoll wake, and both set a member flag (is_timeout_expired,is_timer_alarmed) as soon as the timer descriptor appears, before the flag is combined with socket readiness on the next line. Nothing ever clears either flag: each has exactly one write and no assignment back tofalse, and neitherclearAsyncEvent()norAsyncTaskExecutor::restart()resets it.A wake in which the socket and the timer are ready at the same time therefore returns
trueand delivers its packet correctly, while leaving the connection permanently flagged as timed out. What follows depends on the read path:use_hedged_requests = 1,isPacketReady()is stuckfalse, soHedgedConnections::resumePacketReceivercan no longer take the packet-ready branch, falls through toisTimeoutExpired()and throwsSOCKET_TIMEOUT. The per-packetsetTimeout()re-arm in the packet-ready branch also becomes unreachable, which silently disables the property thatreceive_timeoutis a per-packet idle timeout rather than a total query timeout.async_socket_for_remote = 1, the latched flag makes the guard throw on the first later wake in which the socket is not ready, which is the ordinary case while the remote is still producing the result. It also makescancelBefore()skip draining the pending packet, so the connection is torn down unsynchronised and cancellation logsConnection to ... terminated (NETWORK_ERROR).The synchronous path (
use_hedged_requests = 0,async_socket_for_remote = 0) has no epoll timer and is unaffected.Timer readiness observed in a single wake only means "a receive timeout happened" when the socket was not ready in that same wake, so it must not be stored as connection state. This makes the observation a function-local in both places, and keeps a member that records only the verdict of the conjunction, set exclusively in the branch that already declares the timeout.
PacketReceiver::setTimeout()clears that verdict, because re-arming the timer starts a new receive interval.ConnectionEstablisherAsync::checkTimeout, the third and only otherAsyncTaskExecutor, already uses a function-local for the identical loop and is left unchanged as the reference. No setting, no on-disk or wire format and no protocol is affected.One consumer therefore sees a narrower predicate, deliberately.
cancelBefore()skips draining the pending packet when a timeout has been declared, because waiting would exceed the timeout that already fired. Previously it skipped the drain after any wake in which the timer descriptor had merely appeared, including a wake that delivered a packet; now it skips it only after a timeout was actually declared. For a connection that saw such a wake and is later cancelled, cancellation therefore drains the pending packet again, which is what every connection that never hit the coincidence already did, and is the reason theNETWORK_ERRORon cancellation disappears together with the spurious timeout.How it was verified
The end-to-end failure needs a scheduling coincidence and is not reliably reproducible, so the fix was measured rather than raced. Instrumented builds counted, on the hedged path under the same scenario: on unfixed master, 12 thrown timeouts arising from a single wake that genuinely observed "timer expired and no data", so 11 of 12 were spurious; with the fix, 8 thrown timeouts backed by exactly 8 such wakes, while simultaneous-readiness wakes were more than twice as frequent. The invariant the fix establishes is that a thrown timeout always corresponds to a wake that actually observed an idle socket.
Two unit tests (seven cases) drive the production
checkTimeout()andcancelBefore()against a real connected socket pair without a server or a query, and cover both directions: a simultaneous-readiness wake leaves no residue and the receiver stays usable; a genuine timeout is still declared, still throwsSOCKET_TIMEOUT, still persists forHedgedConnections, and still letscancelBefore()skip waiting for a packet that can no longer arrive; and cancelling a connection that never declared a timeout still drains its pending packet, which is the half that keeps the connection synchronised. Instead of sleeping for a fixed interval, each case waits for the timer descriptor to become readable and fails if it does not, so no case can pass on a wake that never carried the timer. Each of the six production hunks was reverted individually and at least one assertion fails per hunk while the rest still pass; two of the six break two assertions each, because the verdict they record is read in two places.Because both unit tests reach internals through a
frienddeclaration added to the production headers, theBugfix validation (unit tests)job cannot build its merge-base "before" binary with only the test files overlaid, and reports that as inconclusive rather than as a reproduction. The equivalent evidence is the mutation run above, which reverts each production hunk on the current tree instead of the whole commit.02805_distributed_queries_timeoutsis the regression test for the per-packet timeout property that the latch was disabling. It is not modified: the fix makes its invariant hold rather than relaxing the test, which had already been widened once and removed once (#66563) for this flakiness. These seven stateless tests were run against a pristine master binary and against the fixed binary, and the failure sets are identical:01602_max_distributed_connections,01731_async_task_queue_wait,01822_async_read_from_socket_crash,01851_hedged_connections_external_tables,02466_distributed_query_profiler,02805_distributed_queries_timeouts,03444_distributed_hedged_requests_async_socket. They were picked by hand as the ones whose subject is the async or hedged remote-read path itself; a plain grep forreceive_timeout,use_hedged_requestsorasync_socket_for_remotematches 46 stateless tests, of which 19 also perform a distributed or remote read, so the seven are a selection rather than the full grep result.