Repository navigation
Fix the streaming-insert block wait not expiring under the query profiler - #109602
Conversation
ReadBufferFromFileDescriptor::poll restarted the interrupted poll with the full original timeout after EINTR, resetting the deadline on every signal. Query threads receive periodic query-profiler timer signals (SA_RESTART does not apply to poll), so with a signal period not exceeding the timeout the poll never expired while the fd stayed silent. This reaches users through the streaming-insert block wait (input_format_max_block_wait_ms in IRowInputFormat::read): a stalled input source could delay the partial-block flush indefinitely under the profiler instead of flushing when the wait limit is reached. Re-poll with the remaining time, computed in microseconds from a single monotonic anchor: per-retry whole-millisecond accounting would truncate a sub-millisecond interval to zero and make no progress. The unit test drives both cadences (10 ms and 0.5 ms) with a per-thread kernel timer (SIGEV_THREAD_ID), the same mechanism the query profiler uses. Same defect class as the mariadb-connector-c connect_timeout fix (#109592, upstream https://jira.mariadb.org/browse/CONC-834). Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [1ae1774] Summary: ❌
AI ReviewSummaryThis PR now preserves timeout budgets across the touched Missing context / blind spots
Final Verdict✅ No blocking findings on the current PR head. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 142/170 (83.53%) · Uncovered code |
Co-Authored-By: Claude Fable 5 <[email protected]>
…signals The arm_tidy build fails on `long signal_period_nanoseconds`; use `Int64` instead.
|
📊 Cloud Performance Report ✅ AI verdict: This PR only fixes EINTR/timeout accounting in poll/epoll/select wait loops (query cancellation probes, distributed replica reads, shell sources, system.stack_trace) — none of which change the steady-state latency of single-node ClickBench or TPC-H SELECTs. Every flagged improvement (Q13/16/23/30/31, and TPC-H Q7/Q8) is off the execution hot path, so they are downgraded to not_sure as run-to-run variance; the TPC-H deltas were additionally measured on co-located runs, reinforcing that read. The two envelope-suppressed rows (ClickBench Q18 no_change, Q28 not_sure) are consistent with the same off-path conclusion and were left as decided. clickbenchFlagged queries (6 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_officialFlagged queries (2 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
`ReadBufferFromFileDescriptor::poll` already recomputes its retry timeout from the cumulative elapsed time with microsecond precision, so a periodic signal (the query profiler's) cannot reset its deadline. `Epoll::getManyReady` still subtracted whole elapsed milliseconds per `EINTR` and restarted the stopwatch, so a sub-millisecond signal cadence truncated each interval to zero and the timeout never decreased — the same starvation this branch fixed for `poll`, still reachable through profiled `Epoll` waits such as `PacketReceiver::checkTimeout` and `PollingQueue::getTask`. Mirror the `poll` fix: keep a single stopwatch, track the original timeout in microseconds, and derive the remaining timeout from the cumulative elapsed on each retry. Extend the signal-driven gtest to cover `Epoll::getManyReady`; the sub-millisecond case hangs to the 3 s disarm on the old code and expires at the requested timeout with the fix. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…etManyReady The EINTR deadline accounting introduced for positive timeouts also changed the zero-timeout path: on the first EINTR, `elapsed >= timeout` (with timeout 0) was immediately true, so a non-blocking readiness probe returned "not ready" instead of completing the check. A profiler signal could then hide a pending cancel or an already-ready event for one iteration, affecting zero-timeout callers such as `TCPHandler::receivePacketsExpectCancel` / `Connection::forceConnected` (poll) and `RemoteQueryExecutorReadContext::checkTimeout` / `ConnectionEstablisherAsync::checkTimeout` / `TimerDescriptor::drain` (`getManyReady(..., 0)`). Restrict the deadline accounting to strictly positive timeouts and retry the wait unchanged on EINTR for a zero (non-blocking) or negative (infinite) timeout, as before. Add regression tests: a zero-timeout probe on a ready fd stays ready under a dense signal storm, and basic ready/not-ready probes. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Verified empirically that these two tests pass on the unfixed binary too: an EINTR almost never lands in the tiny window of a non-blocking poll/epoll_wait, so a signal storm does not reliably reproduce the zero-timeout regression, making the tests misleading rather than load-bearing. Keep the deterministic ready/not-ready zero-timeout probes, which guard that the non-blocking path itself is not broken. The regression is a defensive correctness fix for a near-unreachable path and is not deterministically reproducible in a unit test. Co-Authored-By: Claude Opus 4.8 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 116/117 (99.15%) · Uncovered code |
|
Dear @Algunenano, 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. |
There is nothing for me to do... |
…poll::getManyReady`
`Epoll::getManyReady` has two implementations in the same file, behind
`#if defined(OS_LINUX)` and `#elif defined(OS_DARWIN)`. Only the `epoll_wait`
one was fixed. The `kevent` one still did:
timeout = std::max(0, static_cast<int>(timeout - watch.elapsedMilliseconds()));
watch.restart();
which resets the deadline on every `EINTR` and truncates a sub-millisecond
remainder to zero, so a signal period under a millisecond leaves `timeout`
unchanged and the wait never expires. This is reachable on macOS: `QueryProfiler`
runs there too, with a shared background thread delivering the periodic signal
via `pthread_kill`, and `PollingQueue`, `RemoteQueryExecutorReadContext` and
`PacketReceiver` all build on Darwin.
Mirror the accounting from the `epoll_wait` branch: compute the timeout in
microseconds once, keep a single `Stopwatch` without `restart`, and on `EINTR`
derive the remaining time from the cumulative elapsed, breaking with
`ready_size = 0` when the deadline is exhausted. Only a strictly positive
timeout accrues against a deadline; a zero timeout is a non-blocking readiness
probe and a negative one is an infinite wait, and both retry unchanged.
Because `kevent` takes a `timespec`, the remaining time is carried at microsecond
resolution instead of the ceil-to-millisecond that `epoll_wait`'s `int` argument
forces, and `timeout` is no longer mutated.
There is no behavioural test for this path: the signal-driven gtest is guarded by
`#if defined(OS_LINUX)` and CI has no macOS runner, so the change is covered by
the cross-compiled Darwin builds only.
Co-Authored-By: Claude Opus 5 <[email protected]>
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 units11 translation units recompiled, 24 s compile time in total, 11 of them have a recent master baseline. |
`ShellCommandSource::pollWithTimeout` did decrement its budget, so the defect is subtler than a reset deadline: the `Stopwatch` was created inside the retry loop and read with `elapsedMilliseconds`, so an interruption arriving faster than once per millisecond truncated to `0` and `timeout_milliseconds -= 0` left the budget untouched. That is the same query-profiler cadence this pull request already fixes elsewhere. Account against one anchor in microseconds, as `ReadBufferFromFileDescriptor::poll` and `Epoll::getManyReady` now do. `StorageSystemStackTrace::wait` deducted one millisecond per `EINTR` regardless of time actually spent - a signal counter, not a deadline. Under dense signals it gave up long before the timeout, under sparse ones it needed thousands of interruptions to expire, and because it tested `timeout_ms == 0` for equality any path that stepped past zero reached `poll(fd, 1, -1)` and waited forever. Two details worth stating: - The exhausted-timeout return of `pollWithTimeout` changes from the `-1` that `poll` left in `res` (with `errno == EINTR`) to `0`. All three uses are in this file and test `<= 0` or `> 0`, so this is behaviourally equivalent, and `0` is what `poll` itself reports for a timeout. - `timeout_milliseconds` there comes from the unrestricted `command_read_timeout` / `command_write_timeout` settings, so it is clamped before scaling to microseconds and again before narrowing to `poll`'s `int`. Neither function is reachable from `unit_tests_dbms` - one is `static`, the other lives in an anonymous namespace - so this adds no direct test. The existing seven tests still pass, including the sub-millisecond-cadence and zero-timeout cases that this accounting is derived from. Co-Authored-By: Claude Opus 5 <[email protected]>
`getReplicaForReading` wrapped `Poco::Net::Socket::select` in its own `if (n <= 0 && errno == EINTR) continue;` loop, which restarted the wait with the full `receive_timeout` - so a silent replica plus a signalled query thread kept the timeout below from ever firing. Poco does not need that loop. `base/poco/Net/src/Socket.cpp` holds a `remainingTime` budget outside its own retry loop and deducts the measured interval on each `EINTR`, in each of its three branches (`epoll` on Linux, `poll` on Darwin/FreeBSD, `select` elsewhere). What broke is narrower than a missing deadline: once that budget is spent, the final non-blocking wait returns `0` without touching `errno`, which still holds the `EINTR` from Poco's *internal* retry - and the `errno = 0` before the call cannot help, because Poco sets it after. The outer loop read that stale value as "interrupted" and began another full `receive_timeout`. So the loop is redundant on every platform and its only effect was this bug. Deleting it is also strictly better than giving it accounting of its own, which would layer a second deadline on top of Poco's correct one. Nothing else changes. Poco cannot return a negative result to this caller - every branch throws through `SocketImpl::error` on a terminal native error - so the removed retry was not covering another error class. `read_list` is now built once instead of per iteration; the rebuild only ever ran after Poco had already spent the timeout, where it could observe readiness arriving past the deadline and grant another full one. `errno` is not read after the call, so its reset goes with the loop that needed it. No regression test: the loop sits in a private method that needs two or more live replica connections in one executor, and `LOG_ERROR` probes on the entry of `getReplicaForReading`, on the constructor and on `receivePacketUnlocked` produced zero hits for every `remote()` shape I tried, so I could not write a test that fails without this change. Co-Authored-By: Claude Opus 5 <[email protected]>
Related: #109592
Related: https://jira.mariadb.org/browse/CONC-834
Problem. The file-descriptor poll timeout can silently never expire on a query thread.
ReadBufferFromFileDescriptor::pollrestarts the interruptedpollwith the full original timeout afterEINTR, resetting the deadline on every signal. Query threads receive periodic sampling-profiler timer signals (query_profiler_real_time_period_ns, default 1 s; the handler'sSA_RESTARTdoes not apply — persignal(7),pollis never auto-restarted), so whenever the signal period does not exceed the timeout, the wait becomes unbounded while the fd stays silent.The user-visible path is the streaming-insert block wait:
IRowInputFormat::readcallspollwith the remaininginput_format_max_block_wait_msbudget over aStorageFilefd/file or stdin buffer. With the profiler active, a stalled input source delays the partial-block flush indefinitely instead of flushing when the wait limit is reached. (All socket paths useReadBufferFromPocoSocket*::poll, which is already deadline-aware, and are not affected.)Root cause. Same defect class as the MySQL
connect_timeoutfix in #109592 (mariadb-connector-c, upstream CONC-834): anEINTRretry loop that passes the original timeout instead of the remainder. This was the last such site insrc/— a sweep of all timed waits (poll/epoll_wait/select/nanosleep/sigtimedwait/io_uring/timerfd) found every other one deadline-aware (Poco sockets,Epoll,KeeperTCPHandler,ShellCommandSource,base/sleep).Fix. Re-poll with the remaining time computed in microseconds from a single monotonic anchor, reporting a timeout once the budget is exhausted. Per-retry whole-millisecond accounting (as in some existing call sites) would truncate a sub-millisecond retry interval to zero and make no progress under a sub-millisecond signal cadence, so the remainder is derived from the untouched anchor instead.
The unit test (
gtest_fd_read_buffer_poll_under_signals.cpp) waits on a pipe with no writer while a per-thread kernel timer (timer_create+SIGEV_THREAD_ID, the query profiler's own mechanism, so delivery deterministically targets the polling thread) interrupts the poll at two cadences: 10 ms (the classic deadline reset) and 0.5 ms (pins the microsecond-precision accounting). A watchdog thread disarms the timer after 3 s so a regressed build fails the elapsed assertion at ~3.2 s instead of hanging; the fixed poll returns in ~200 ms. Verified in both directions: the naive loop fails both cadences, a millisecond-accounting variant fails exactly the sub-millisecond one.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed the block-wait timeout of streaming inserts (
input_format_max_block_wait_ms) potentially never expiring while the query profiler is active: the file-descriptor poll restarted with the full timeout after every profiler signal, so a stalled input source could delay the partial-block flush indefinitely instead of flushing when the wait limit is reached.Workflow [PR]
Sync PR [sync-upstream/pr/109602]
Version info
26.8.1.1736(included in26.8and later)