Skip to content

Fix the streaming-insert block wait not expiring under the query profiler - #109602

Merged
tiandiwonder merged 13 commits into
masterfrom
fix-fd-poll-eintr-deadline
Aug 20, 2026
Merged

tiandiwonder merged 13 commits into
masterfrom
fix-fd-poll-eintr-deadline

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

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::poll restarts the interrupted poll with the full original timeout after EINTR, 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's SA_RESTART does not apply — per signal(7), poll is 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::read calls poll with the remaining input_format_max_block_wait_ms budget over a StorageFile fd/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 use ReadBufferFromPocoSocket*::poll, which is already deadline-aware, and are not affected.)

Root cause. Same defect class as the MySQL connect_timeout fix in #109592 (mariadb-connector-c, upstream CONC-834): an EINTR retry loop that passes the original timeout instead of the remainder. This was the last such site in src/ — 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):

  • 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 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

  • Merged into: 26.8.1.1736 (included in 26.8 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1ae1774]

Summary: ❌

job_name test_name status info comment
Bugfix validation (unit tests) ERROR
Bugfix validation (unit tests) ERROR

AI Review

Summary

This PR now preserves timeout budgets across the touched EINTR-interrupted wait paths: ReadBufferFromFileDescriptor, Epoll on Linux and Darwin, ShellCommandSource, StorageSystemStackTrace, and the MultiplexedConnections wrapper around Poco select. I re-checked the current code against the full PR diff and all prior discussion, and I do not see any remaining correctness or compatibility issues on the current PR head.

Missing context / blind spots
  • ⚠️ The Darwin kevent branch in src/Common/Epoll.cpp is still only compile-validated here; this environment has no runtime macOS coverage for that path.
Final Verdict

✅ No blocking findings on the current PR head.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 142/170 (83.53%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 7, 2026
Co-Authored-By: Claude Fable 5 <[email protected]>
@Algunenano Algunenano self-assigned this Jul 7, 2026
@tiandiwonder tiandiwonder added the can be tested Allows running workflows for external contributors label Jul 8, 2026
…signals

The arm_tidy build fails on `long signal_period_nanoseconds`; use `Int64` instead.
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 35 queries analysed

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.

clickbench

⚠️ 6 inconclusive

Flagged queries (6 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 13 not_sure 422 358 -15.2% <0.0001 This PR only fixes EINTR/timeout accounting in poll/epoll/select wait loops, which a single-node ClickBench scan never exercises; the -15.2% is run-to-run variance.
⚠️ 16 not_sure 734 626 -14.7% <0.0001 The changed signal/timeout wait paths are off the execution hot path for this query, so -14.7% is not attributable to the PR.
⚠️ 23 not_sure 164 77 ×2.1 faster <0.0001 Off-path for this timeout-accounting fix, and the source runs were highly variable, so ×2.1 faster is not a real PR effect.
⚠️ 28 not_sure 1051 1139 +8.4% <0.0001 Borderline +8.4% inside the variance band; the diff cannot affect this query's execution, so treat it as noise.
⚠️ 30 not_sure 279 232 -16.8% <0.0001 The EINTR/timeout wait changes are not on this query's path; -16.8% is run-to-run variance rather than a PR effect.
⚠️ 31 not_sure 408 310 -24.0% <0.0001 This query does not exercise the changed poll/select wait loops, so -24.0% is not attributable to the PR.

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_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 560 68 ×8.2 faster <0.0001 Off-path for a timeout-accounting fix, and this query ran co-located with others on shared hardware, so ×8.2 faster is environmental, not a PR effect.
⚠️ 8 not_sure 166 80 ×2.1 faster <0.0001 The diff cannot change steady-state SELECT latency, and this ran co-located on shared hardware, so ×2.1 faster is not attributable to the PR.

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
  • StressHouse run: 4ffe2880-6b6b-4c20-99a1-9145b75ac67d
  • MIRAI run: a049dada-346d-44a9-98e1-fe2874eb8fbf
  • PR check IDs:
    • clickbench_2026760_1787103895
    • clickbench_2026766_1787103895
    • clickbench_2026772_1787103895
    • tpch_adapted_1_official_2026789_1787103895
    • tpch_adapted_1_official_2026802_1787103895
    • tpch_adapted_1_official_2026830_1787103895

`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]>
Comment thread src/IO/ReadBufferFromFileDescriptor.cpp Resolved
Comment thread src/Common/Epoll.cpp Resolved
tiandiwonder and others added 3 commits July 28, 2026 01:31
…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]>
Comment thread src/Common/Epoll.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 116/117 (99.15%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

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.

@Algunenano

Copy link
Copy Markdown
Member

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...

@Algunenano Algunenano self-assigned this Aug 6, 2026
…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]>
Comment thread src/IO/ReadBufferFromFileDescriptor.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1ae177439 with master a521cf141 (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 701.98 MiB 698.95 MiB -3.02 MiB (-0.43%)

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

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

Job report

tiandiwonder and others added 2 commits August 17, 2026 06:45
`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]>
@tiandiwonder
tiandiwonder added this pull request to the merge queue Aug 20, 2026
Merged via the queue into master with commit 2101f9b Aug 20, 2026
173 of 175 checks passed
@tiandiwonder
tiandiwonder deleted the fix-fd-poll-eintr-deadline branch August 20, 2026 06:53
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 20, 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 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.

3 participants