Repository navigation
Re-land: make Ctrl+C terminate the output of a result set in the client promptly - #108078
alexey-milovidov wants to merge 141 commits into
Conversation
…nt promptly" This reverts commit 3498571.
…tting The interruptible-output feature reapplied in the previous commit installed the `std_out` cancellation hook at the start of `processOrdinaryQuery` and cleared it via a `SCOPE_EXIT` at the end of the same scope. When the result set is written with parallel formatting, `ParallelFormattingOutputFormat` runs a background collector thread that writes through `std_out` and reads its `cancellation_hook` in `WriteBufferFromFileDescriptor::nextImpl`. On the normal end-of-stream path the collector is joined by `output_format->finalize` before the scope guard runs, so the clear is safe. But on paths that leave `processOrdinaryQuery` by an exception without first finalizing the output (e.g. a `NetException`, or a `LocalFormatError` rethrown from `receiveResult`), the scope guard cleared the hook while the collector thread was still alive and reading it: a data race on the `std::function`. This is the data race reported by `BuzzHouse (amd_tsan)` (STID 5296-4b74) that led to the original revert. Clear the hook in `resetOutput` right after `output_format.reset()`. `output_format.reset()` destroys the parallel formatter and joins its collector thread, so afterwards no other thread can read `std_out`'s hook and the mutation is single-threaded. The hook is also re-pointed for the teardown flushes that follow: on normal completion the interrupt handler is still armed and is honored, so a fresh Ctrl+C keeps interrupting a flush to a slow or stuck stdout; on exception paths the handler is already stopped (its `cancelled` is then unconditionally true), so the genuine cancellation flag is used instead to avoid discarding already-produced output. `resetOutput` runs on every exit path and at the start of the next query, so `std_out` (which outlives a single query) never carries a stale hook into the next query. This folds in the fix from the closed PR #107828 into the re-land, as recommended there. Related: #106430 Related: #107828 Related: #22426 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [c94d9f1] Summary: ❌
|
…down The per-query pager stdin buffer (`pager_cmd->in`) and the `INTO OUTFILE ... AND STDOUT` stdout buffer install the cancellation hook `query_interrupt_handler.cancelled()` so a stuck pager/terminal cannot defeat a prompt Ctrl+C. But on an exception cleanup path (a `NetException` or a `LocalFormatError` rethrown from `receiveResult`) the `processOrdinaryQuery` scope guard has already called `query_interrupt_handler.stop()`, so `cancelled()` is unconditionally true while the genuine `cancelled` flag is still false. `resetOutput` then finalizes these buffers with a hook that reports cancellation, which would discard already-produced output during cleanup even though the user never cancelled the query. `std_out` already avoids this: `resetOutput` re-points its hook (after the parallel-formatting collector is joined) to fall back to the genuine `cancelled` flag on exception paths while keeping the interrupt handler honored on normal completion. Apply the same `interrupt_handler_armed` re-point to the two sibling per-query buffers so handler teardown is no longer treated as a user cancellation during cleanup. A handle to the `INTO OUTFILE ... AND STDOUT` stdout buffer (wrapped inside `out_file_buf`) is kept so its hook can be re-pointed before it is finalized. This addresses the unresolved review thread on src/Client/ClientBase.cpp:813. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… exception Exercises the exception-cleanup path requested in review: a query that fails mid-stream with `INTO OUTFILE ... AND STDOUT`. Both branches are fed by the same `ForkWriteBuffer`, so the mirrored stdout must stay byte-identical to the file - the per-query stdout buffer's cancellation hook must not treat the stopped interrupt handler as a user cancellation and truncate the output during `resetOutput`. Complements `04318_client_cancel_blocked_output.sh` (which covers prompt Ctrl+C on a blocked sink) by guarding the data-integrity invariant on the exception-cleanup path. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses the review on `WriteBufferFromFileDescriptor::nextImpl`: the responsive path waited for `POLLOUT` and then did a blocking `write` capped at `PIPE_BUF`. A `poll` reporting `POLLOUT` only guarantees room for `PIPE_BUF` bytes on a pipe/FIFO, not on a socket or terminal, so the blocking `write` could still sleep after `poll` returned writable on a slow or stuck terminal/socket. The interrupting signal can be delivered to another thread, so a `write` stuck this way would not consult the cancellation hook and the first Ctrl+C could appear to have no effect - exactly the user-facing promise of the feature. Switch the descriptor to non-blocking mode for the duration of `nextImpl` when a cancellation hook is installed and the descriptor can block (pipe, socket or terminal), and treat `EAGAIN`/`EWOULDBLOCK` like a `poll` timeout (re-poll and re-check the hook). A non-blocking `write` never sleeps, so the hook is always consulted within the poll timeout regardless of the descriptor type, and the `PIPE_BUF` assumption is gone. The original blocking mode is restored on every exit path via `SCOPE_EXIT`. This path is taken only when a cancellation hook is installed, which only happens for the client output buffers; the server's hot single-threaded write path never installs a hook and is unaffected. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The master merge added `04418_numeric_indexed_vector_multiply_zero_integer_bits`, which collides with this PR's `04418_client_exception_cleanup_no_truncation`. Renumber the latter to `04489` (the next free prefix). No content change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The existing `04318_client_cancel_blocked_output` covers pipe/FIFO and pager-pipe sinks. Add a test whose sink is a real terminal (a pty) whose master end is never drained, so the client blocks writing the result set to a stuck terminal - the headline scenario of the feature, and the `isatty()` branch of the responsive write path. A single `SIGINT` must terminate the client. The client's stderr goes to a regular file so its cancellation diagnostics cannot themselves block on the full terminal. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the AI review's Request changes verdict (the blocking Code change ( Test ( Verified locally against a build of this branch: CI reds — all known, unrelated flakes:
|
Addresses the AI review finding on #108078: `ClientBase::resetOutput` calls `output_format->finalize()` before the output cancellation hooks installed on `std_out`, the pager stdin and the `INTO OUTFILE ... AND STDOUT` stdout buffer can be safely re-pointed. That re-pointing has to wait until the parallel-formatting collector that also reads the hook is joined - re-pointing the `std::function` while that thread reads it is exactly the data race that reverted the feature in #107845 - so it runs only after `output_format.reset()`. On an exception path the interrupt handler is already stopped by then, and the live hook returned `query_interrupt_handler.cancelled()`, which is unconditionally true once the handler is stopped. So that `finalize()` flush discarded the already-produced output even though the query was never cancelled, truncating it on paths such as a `NetException` after some result blocks but before `EndOfStream`. Make the live hook lifetime-safe instead of re-pointing it: add `QueryInterruptHandler::isRunning` (armed between `start` and `stop`) and gate the hook on `isRunning() && cancelled()`. While the query runs the handler is armed, so prompt Ctrl+C cancellation is unchanged; once it is stopped during teardown the hook reports no cancellation, so the `finalize()` flush preserves the output. The hook only reads atomics, so it does not reintroduce the collector data race that re-pointing the `std::function` would.
|
Addressed the AI review's Request changes verdict (the stopped-handler cleanup finding at The bug
The gap the review found: the earlier In practice the discarded bytes are the format footer (the client sets The fixMake the hook lifetime-safe instead of re-pointing it. Added
The hook only reads atomics inside the already-installed On the requested regression testI could not build a deterministic stateless/local regression test for this specific path, and after investigation I believe one is not feasible with the current test tooling:
If there is a preferred way to inject an outer exception with a healthy sink (e.g. via an integration test that drops the connection), I'm happy to add it. VerificationBuilt this branch and ran the three client tests against it — all pass with no regression to prompt cancellation: CIThe only reds are the chronic master-wide |
…imit Purely cosmetic: the `INTO OUTFILE ... AND STDOUT` stdout-buffer hook is at the deepest indentation, so put its lambda body on its own line to keep the line under 120 columns. No behavior change.
`f8f01564b63` made the interruptible client write path set `O_NONBLOCK` on the output descriptor for the duration of `nextImpl` (restoring it on exit) so a `write` to a slow or stuck sink would never sleep. But `O_NONBLOCK` is a property of the open file description, not of the file descriptor, and in a terminal session the client's stdout (fd 1) and stderr (fd 2) are dup'd from the same open file description. So flipping `O_NONBLOCK` on `std_out` (fd 1) transiently makes `std_err` / the progress `tty_buf` (fd 2) non-blocking too. When the result set is written through `std_out` while the progress bar is rendered to `tty_buf` concurrently, that progress `write` returns `EAGAIN`, and because `tty_buf` has no cancellation hook the generic write path treats it as fatal and throws `Cannot write to file (fd = 2): ... Resource temporarily unavailable. (CANNOT_WRITE_TO_FILE_DESCRIPTOR)`. This is the failure observed in `01293_client_interactive_vertical_singleline` on `Stateless tests (arm_binary, parallel)`: a low-probability race (CI's own rerun passed 83/83), but a real one - and the same open-file-description flag could in principle leak to the parent shell's terminal. Revert to the previous responsive path: wait for writability with `poll(POLLOUT)` on a 100 ms timeout and do a blocking `write` capped at `PIPE_BUF`, never mutating the descriptor's blocking mode. The headline "stuck terminal" case is still handled by the `poll` timeout: a stuck terminal never reports `POLLOUT`, so `write` is never reached and the cancellation hook is consulted within 100 ms. A slow-but-draining sink blocks only as long as it takes to drain one `PIPE_BUF` chunk. The client's output is always a terminal, a pipe or a regular file, so the residual case the non-blocking mode was meant to cover (a raw socket that becomes unwritable in the window right after `POLLOUT`) does not arise; if it ever needs covering, `send(..., MSG_DONTWAIT)` does it per-call without touching the shared open file description. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108078&sha=f8afbc552ccda38688877bc55afff9d3434692b6&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed The bug it fixes —
|
|
The current head Why the revert's rationale does not hold for a stuck ptyThe revert argues "a stuck tty never reports So
This is a design call for you — I did not push a speculative third mechanismThis path has already been bitten twice by subtle races (#107845 the data race, then the
My recommendation: option 3 is the simplest robust resolution given a portable non-blocking write to a tty is awkward; option 1 if you want to keep the permanently-stuck-tty guarantee. I'm happy to implement whichever you choose. |
The responsive write path (used while a cancellation hook is installed) waited for `POLLOUT` and then did a blocking `write` capped at `PIPE_BUF`. That cap only makes the write bounded for pipes/FIFOs: on a terminal, `poll` reporting `POLLOUT` promises only *some* room, and a blocking tty `write` sleeps until the whole chunk is accepted, so the client could still hang inside `write` on a terminal that stops draining and the first Ctrl+C appeared to have no effect (`04490_client_cancel_blocked_terminal_output` was red on every CI variant of this PR). A non-blocking write is needed, but `O_NONBLOCK` must not be toggled on the descriptor itself: the flag lives on the open file description, which a terminal fd shares with fd 2 and the parent shell, so it leaks to unrelated writers - exactly what broke `01293_client_interactive_vertical_singleline` and was reverted in 3f8b12c. Implement the private-open-file-description mechanism (option 1 of the design discussion in the PR): re-open the terminal via `/proc/self/fd/<fd>` (Linux), which yields an independent open file description on the same terminal, and set `O_NONBLOCK` only there. The responsive path then writes through this private descriptor: on a stuck terminal the write fails with `EAGAIN` (handled like a `poll` timeout, so the cancellation hook stays consulted promptly) and no other descriptor changes behavior. If the re-open fails or on non-Linux platforms (the BSD/macOS `/dev/fd` equivalent behaves like `dup` and shares the open file description, which would reintroduce the leak), the previous `poll` + `PIPE_BUF`-capped blocking write remains as the fallback. Sockets are written with `send(..., MSG_DONTWAIT)`, which is non-blocking per call without touching the open file description; pipes keep the capped blocking write, the one case where the `PIPE_BUF` guarantee is actually valid. Verified locally against a Release build: `04490_client_cancel_blocked_terminal_output` now passes (5/5 runs), `01293_client_interactive_vertical_singleline` stays green (15/15 runs), `04318_client_cancel_blocked_output` and `04489_client_exception_cleanup_no_truncation` pass (3/3 each). Report: #108078 Co-Authored-By: Claude Fable 5 <[email protected]>
…tuck terminal In interactive mode `cancelQuery` printed `Cancelling query.` and the epilogue printed `Query was cancelled.` to `output_stream`/stdout with ordinary blocking writes not covered by the cancellation hook. In the stuck-terminal case the first Ctrl+C could therefore hang on the diagnostic itself right after the result-set write was successfully aborted. Route these diagnostics through the new `WriteBufferFromFileDescriptor::writeBestEffort`: a direct bounded write that goes through the private non-blocking descriptor when the sink is a terminal (or a `PIPE_BUF`-capped write after `POLLOUT` otherwise) and drops the message after a one-second budget if the sink stays unwritable - nothing is reading that terminal anyway. On a live terminal the message appears immediately: `03701_pager_proper_termination` still sees `Query was cancelled.` (5/5 runs locally), and a pty check confirms that with a terminal that stops draining mid-result a single Ctrl+C completes the cancellation, drops the diagnostics and returns the client to a usable prompt. In the embedded client `output_stream` is not the process stdout, so it prints normally there. Report: #108078 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Implemented option 1 (non-blocking write on a private open file description) from the design comment above:
Local verification against a Release build: |
… out of ClientBase.cpp `Build (arm_tidy)` failed with clang-analyzer's `clang-analyzer-unix.Errno`: in `WriteBufferFromFileDescriptor::nextImpl`, when `::send` succeeds and returns `0`, `errno` is left unspecified by that call, yet `(-1 == res || 0 == res) && errno != EINTR` still read it. Since `bytes_to_write` is always `> 0` in this loop, a `0` return from `write`/`send` is always an error and does not need an `errno` check - only the genuine `-1` (possibly-interrupted) case does. `Style check` failed on `src/Client/ClientBase.cpp: uses std::cerr/std::cout`: `printCancellationMessage` compared `&output_stream == &std::cout` to detect the process's real stdout, which is textually forbidden in `src/` outside a fixed exclusion list (`ClientBase.h` is on that list already, `ClientBase.cpp` is not). Moved the comparison into a small `ClientBase::isStandardOutput` helper defined inline in `ClientBase.h`, so `std::cout` is no longer mentioned in the `.cpp` file. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108078&sha=f18ae14fcd42f8f95a2d68394f2dd48e523b8195&name_0=PR
…path for embedded clients too `printCancellationMessage` only used the best-effort bounded write on `std_out` when `output_stream` was literally `std::cout`, so `ClientEmbedded` sessions (e.g. the web terminal's `PtyClientDescriptorSet`) fell through to an ordinary blocking `output_stream << message << std::endl`. Since `std_out` is always constructed from the same paired (fd, stream) argument as `output_stream` - `STDOUT_FILENO`/`std::cout` for the standalone client, the pty/pipe descriptor and its matching stream for `ClientEmbedded` - the two always share the same underlying sink, so the `std::cout` identity check was an unnecessarily narrow proxy that missed the embedded/PTY case: a stuck web terminal could still hang the first Ctrl+C on the "Cancelling query."/"Query was cancelled." diagnostic itself. Drop the check and always route through `std_out` (removing the now-unused `isStandardOutput` helper).
|
🕵 Merged @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108078&sha=bf6f312dbb8f2178fd75d1e683ad5a2778dc0296&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. The new server keeps retrying a replicated mutation that fails with |
|
The fix is in progress in #128105 (CI finished, In this run the previous release left |
…ux-only On macOS and FreeBSD there is no portable way to obtain an independent open file description of an anonymous pipe, so `openTransientNonblockingPipeDescriptor` returns -1 there and the `PIPE_BUF`-capped blocking write remains. Document the narrowed platform coverage explicitly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Addressed the remaining review thread in f002fa6: the comment on The red |
# Conflicts: # src/Client/ClientBase.cpp
`receiveLogsAndProfileEvents` and `receiveEndOfQueryForInsert` kept receiving and formatting the result of `INSERT ... RETURNING` after Ctrl+C: the cancellation hook of `std_out` only discarded the output, the query kept running on the server and the client did not exit. Both loops now check the interrupt handler, call `cancelQuery` (which sends `Cancel`), and drain the remaining packets without formatting the result. `receiveEndOfQueryForInsert` waits for packets with `poll` in bounded intervals (as `receiveResult` does), so a Ctrl+C is noticed while the server is still producing the result. Added `05490_client_cancel_blocked_insert_returning`: `INSERT ... RETURNING ... FROM INFILE` with an undrained stdout; after one `SIGINT` both the client and the server query finish. Without the fix it fails on both checks. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 The |
The bounded-interval `poll` loop added for Ctrl+C during `INSERT ... RETURNING` spun forever on a `LocalConnection` with no query in flight: its `poll` returns `false` once `state` is reset, while `receivePacket` would report `EndOfStream` immediately. This happens when `processInsertQuery` calls `sendCancel` and `receiveEndOfQueryForInsert` after a failure that occurs when the query is already over (`05443_local_cancel_after_insert_finished` timed out in the Fast test). Do not wait on a local connection, and keep the receive timeout that a blocking `receivePacket` applied on a remote one. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108078&sha=5c078078ffaf8b43a49a4cb8c750a10857e7c155&name_0=PR Co-Authored-By: Claude Opus 5.5 <[email protected]>
… flushed epilogue The test was added on master after this branch was created. Its reference pinned the old behaviour where `Processed rows: N` went to the buffered `std::cout` and was only flushed at exit, after all query results. With this PR the epilogue is flushed per query, so the lines now appear in chronological order: the result of the final `SELECT` is printed after the progress lines of the preceding queries and before its own `Processed rows: 1`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108078&sha=542618cc62b7c9246cd2fe94794ee0a0b4ea15a8&name_0=PR&name_1=Fast%20test PR: #108078 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged |
… its output while armed
`receiveLogsAndProfileEvents` may cancel the query itself (a Ctrl+C noticed while
receiving progress, logs, or the result of `INSERT ... RETURNING`). `sendDataFromPipe`
still sent the current block after that, so the server received `Data` after `Cancel`,
dropped the connection, and the client failed with a `NETWORK_ERROR` from
`Connection::sendData` ("Cannot send Cancel due to connection is lost"). This is the
failure of `04365_cancel_insert_when_client_dies_distributed` in CI:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108078&sha=a66770869c84f5601436373a372ee3e4e888a544&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29
Now the input executor is cancelled and the upload stops right there; the response is
drained by `receiveEndOfQueryForInsert` as before.
Also flush the output of `INSERT ... RETURNING` in the exceptional cleanup of
`processInsertQuery` with `resetOutput`, while `query_interrupt_handler` is still armed,
like `receiveResultAndResetOutputOnException` does for `processOrdinaryQuery`. Otherwise
the footer was flushed by the outer `resetOutput` after the handler was stopped, and a
Ctrl+C could not interrupt that flush to a stuck sink.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Client/ClientBase.cpp
…ndOfQueryForInsert` `05493_client_cancel_blocked_insert_returning` timed out intermittently in CI (sanitizer builds): after a Ctrl+C noticed in `receiveLogsAndProfileEvents` during the upload of an `INSERT ... RETURNING`, the last `checkPacket` there could read the type of the final `EndOfStream` packet into the connection. `Connection::poll` looks only at the socket and its read buffer, so the bounded poll loop of `receiveEndOfQueryForInsert` never saw the packet and waited for `receive_timeout` (and once more in the cleanup after the timeout), although the server had already finished the query. Skip the wait when `hasReadPendingData` reports a pending packet. Reproduced locally by pinning the client to a busy CPU (hung on the first attempt, 30/30 clean exits after the fix). Also make the test kill a client that is still running after Ctrl+C, so that a failure is reported instead of hanging in the `wait` of `cleanup`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108078&sha=40351b58ecc6faff42bf656340f8823e01c68720&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20flaky%20check%29 PR: #108078 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…intErrorReport` `ClientEmbedded::processError` wrote the report with a plain blocking write to `error_stream`. After a Ctrl+C the session's terminal may be exactly what stopped draining, so the report could hang the session right after the cancellation was handled. Use the bounded `printErrorReport`, like `Client::processError` and `LocalServer::processError`. The ordinary (blocking) branch of `printErrorReport` now writes to `error_stream`, the stream paired with `stderr_fd`, instead of the process-global `stderr`: for the standalone client and `clickhouse-local` it is `std::cerr`, for the embedded client it is the session's own stream. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 CI on |
|
🕵 Merged |
# Conflicts: # src/Client/ClientBase.h # tests/queries/0_stateless/05454_local_progress_from_pipeline_threads.reference
|
🕵 Merged |
…l-output Conflict in `ClientBase::resetOutput`: kept both the bounded final flush of `std_out` from this branch and the `onQueryOutputReleased` call added on `master`. Co-Authored-By: Claude Fable 5.2 <[email protected]>
The trailing flush of the deferred `ProfileEvents` block was bounded by the one-second best-effort budget unconditionally. A query that received no interrupt and whose log sink is a pipe with a paused reader (e.g. `--server_logs_file=-` with a full stdout pipe) silently lost the requested profile events and still exited successfully. Bound that flush only when `cancelled` or `query_received_interrupt` is set, consistently with `write_epilogue`. Add a regression test with an already-full pipe whose reader resumes after the budget expires. Addresses review: #108078 (comment) Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged Addressed the review thread about deferred profile events in |
Closes: #22426
Related: #106430
Related: #107845
Related: #107828
Description
This re-lands #106430 ("Make Ctrl+C terminate the output of a result set in the client promptly"), which was reverted by #107845, and folds in the data-race fix from the (now closed) #107828 so the feature can land safely this time.
Why it was reverted:
BuzzHouse (amd_tsan)reported a ThreadSanitizer data race on master (STID 5296-4b74) on the client's persistent stdout buffer (std_out, anAutoCanceledWriteBuffer<WriteBufferFromFileDescriptor>). The interruptible-output feature installed a cancellation hook onstd_outat the start ofprocessOrdinaryQueryand cleared it viaSCOPE_EXIT({ std_out->setCancellationHook({}); })at the end of the same scope. When the result set is written with parallel formatting,ParallelFormattingOutputFormatruns a background collector thread that writes throughstd_outand reads itscancellation_hookinWriteBufferFromFileDescriptor::nextImpl. On the normal end-of-stream path the collector is joined byoutput_format->finalizebefore the scope guard runs, so the clear is safe; but on paths that leaveprocessOrdinaryQueryby an exception without first finalizing the output (aNetException, or aLocalFormatErrorrethrown fromreceiveResult), the scope guard cleared the hook while the collector thread was still alive and reading it — a data race on thestd::function.The fix (from #107828): the hook is cleared in
resetOutputright afteroutput_format.reset(), which destroys the parallel formatter and joins its collector thread, so the mutation is single-threaded with respect tostd_out's hook. The hook is also re-pointed for the teardown flushes that follow: on normal completion the interrupt handler is still armed and is honored, so a fresh Ctrl+C keeps interrupting a flush to a slow or stuck stdout; on exception paths the handler is already stopped (itscancelledis then unconditionally true), so the genuine cancellation flag is used instead to avoid discarding already-produced output.resetOutputruns on every exit path and at the start of the next query, sostd_out(which outlives a single query) never carries a stale hook into the next query. The pager andINTO OUTFILE ... AND STDOUTbuffers are per-query and destroyed inresetOutputafter the collector join, so they were never affected.The change is split into two commits: the first reapplies #106430 verbatim (a revert of the revert #107845); the second folds in the #107828 fix, confined to
src/Client/ClientBase.cpp. The low-levelWriteBufferFromFileDescriptor(used server-wide on a hot single-threaded write path) is unchanged by the fix.Revert that motivated this: #107845
TSAN report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=73e97deb9abbc3258e75d297aabfc3fbe7c3ca5e&name_0=MasterCI&name_1=BuzzHouse%20%28amd_tsan%29&name_1=BuzzHouse%20%28amd_tsan%29
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Pressing Ctrl+C in
clickhouse-client/clickhouse-localnow promptly stops printing a large result set, even when the output is being written to a slow or stuck destination such as a slow terminal. Previously the first Ctrl+C could appear to have no effect.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/108078]