Skip to content

Re-land: make Ctrl+C terminate the output of a result set in the client promptly - #108078

Open
alexey-milovidov wants to merge 141 commits into
masterfrom
reland-client-cancel-output
Open

alexey-milovidov wants to merge 141 commits into
masterfrom
reland-client-cancel-output

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 21, 2026 •

Copy link
Copy Markdown
Member

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, an AutoCanceledWriteBuffer<WriteBufferFromFileDescriptor>). The interruptible-output feature installed a cancellation hook on std_out at the start of processOrdinaryQuery and cleared it via SCOPE_EXIT({ std_out->setCancellationHook({}); }) 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 (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.

The fix (from #107828): the hook is cleared in resetOutput right after output_format.reset(), which destroys the parallel formatter and joins its collector thread, so the mutation is single-threaded with respect to std_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 (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. The pager and INTO OUTFILE ... AND STDOUT buffers are per-query and destroyed in resetOutput after 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-level WriteBufferFromFileDescriptor (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):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Pressing Ctrl+C in clickhouse-client/clickhouse-local now 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

  • Documentation is written (mandatory for new features)

Workflow [PR]
Sync PR [sync-upstream/pr/108078]

alexey-milovidov and others added 2 commits June 21, 2026 22:15
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c94d9f1]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
05872_client_deferred_profile_events_paused_pipe_reader FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 21, 2026
Comment thread src/Client/ClientBase.cpp Resolved
alexey-milovidov and others added 6 commits June 29, 2026 21:14
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review's Request changes verdict (the blocking WriteBufferFromFileDescriptor finding) and re-merged master.

Code change (f8f01564b63): made the interruptible write path genuinely non-blocking. Previously the responsive path did poll(POLLOUT) then a blocking write capped at PIPE_BUF; POLLOUT only guarantees room for PIPE_BUF bytes on a pipe/FIFO, so on a socket or terminal that blocking write could still sleep after poll returned writable, and the first Ctrl+C (delivered to another thread) would not be honored. Now, while a cancellation hook is installed and the descriptor can block (pipe/socket/terminal), nextImpl sets O_NONBLOCK for the duration of the call (restored on every exit path via SCOPE_EXIT) and treats EAGAIN/EWOULDBLOCK like a poll timeout. A non-blocking write never sleeps, so the hook is consulted within the 100 ms bound regardless of descriptor type. This path is client-only — the server never installs a hook, so its hot single-threaded write is unchanged.

Test (aa8b664e65b): added 04490_client_cancel_blocked_terminal_output.sh, a pty-backed test covering the headline "stuck terminal" case (the existing 04318 covers pipe/FIFO and pager pipes). Also renumbered the exception-cleanup test to 04489 to avoid a collision introduced by the master merge.

Verified locally against a build of this branch: 04318, 04489, and the new 04490 all pass.

CI reds — all known, unrelated flakes:

  • Stress test (amd_tsan) / Stress test (arm_tsan) — "Hung check failed, possible deadlock found", the chronic master-wide flake #107941 (stack trace is server-side AST-fuzzer execution, which never touches the client cancellation hook). BuzzHouse (amd_tsan) — the job whose data race motivated the original revert — is green.
  • Upgrade check (amd_release) — the 192.0.2.1 remote MySQL/PostgreSQL connection-error flake tracked by #108560.

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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review's Request changes verdict (the stopped-handler cleanup finding at ClientBase.cpp:1886 / the inline thread at :816) in a3076bc3b4a.

The bug

resetOutput() re-points the output cancellation hooks to a teardown-safe hook, but only after output_format.reset(). That ordering is deliberate: the re-point must wait until the parallel-formatting collector that also reads the hook has been joined, because mutating the std::function while that thread reads it is exactly the data race that reverted the feature in #107845.

The gap the review found: the earlier output_format->finalize() call in resetOutput() (which is itself what joins the collector) flushes any pending bytes through std_out / the pager stdin / the INTO OUTFILE ... AND STDOUT stdout buffer while those still carry the live hook. On an outer exception path — a NetException or a rethrown LocalFormatError that unwound out of processOrdinaryQuery, whose SCOPE_EXIT already stopped the interrupt handler — the live hook returned query_interrupt_handler.cancelled(), which is unconditionally true once the handler is stopped. So that finalize() discarded the already-produced output even though the query was never cancelled, contrary to the intent stated in the surrounding comments.

In practice the discarded bytes are the format footer (the client sets setAutoFlush(), so each data block is flushed to the descriptor as it arrives), so footer-bearing formats (JSON, Pretty, XML, …) would lose their closing bytes; footer-less formats (TSV, CSV) lose nothing.

The fix

Make the hook lifetime-safe instead of re-pointing it. Added QueryInterruptHandler::isRunning() (armed between start() and stop()) and gated the three live hooks on isRunning() && cancelled():

  • While the query runs the handler is armed, so the hook is identical to cancelled() — prompt Ctrl+C cancellation is unchanged.
  • Once the handler is stopped during teardown, the hook reports no cancellation, so the finalize() flush preserves the output.

The hook only reads atomics inside the already-installed std::function; it does not re-point the function, so it does not reintroduce the collector data race (that is the whole reason the teardown re-pointing must stay where it is). stop() clears running before exit_after_signals so a concurrent reader never observes a running-and-cancelled state during teardown.

On the requested regression test

I 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:

  • A server-side exception (and any clickhouse-local query error) is delivered as a Protocol::Server::Exception packet → onReceiveExceptionFromServer() calls resetOutput() while the handler is still armed, so the stopped-handler finalize() never runs with pending output. (This is why the existing 04489 test, which uses a server-side throwIf, exercises the armed path and passes regardless of the bug.)
  • The stopped-handler path is only reached by an exception that unwinds out of processOrdinaryQuery: a NetException mid-receive (a connection drop, not deterministically reproducible) or a mid-stream client LocalFormatError (output formats tolerate all uniform data — I tried JSON/maps with non-string keys/output_format_json_validate_utf8/Npy/Parquet/CapnProto/Decimal overflow and none throw mid-stream). Both of those also disrupt the very output sink whose preservation a test would assert.

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.

Verification

Built this branch and ran the three client tests against it — all pass with no regression to prompt cancellation: 04318_client_cancel_blocked_output, 04489_client_exception_cleanup_no_truncation, 04490_client_cancel_blocked_terminal_output.

CI

The only reds are the chronic master-wide Stress test (amd_tsan) / Stress test (arm_tsan) "Hung check failed" flake #107941 (the dumped stacks are server-side AST-fuzzer execution — QueryAnalyzer::resolveQuery / executeASTFuzzerQueries / TCPHandler — which never touch the client cancellation hook), plus the 192.0.2.1 upgrade-check connection-error flake #108560. BuzzHouse (amd_tsan) — the job whose data race motivated the original revert — is green.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 3f8b12c2736: reverted the O_NONBLOCK mechanism from f8f01564b63, which was the root cause of the only PR-related CI red.

The bug it fixes — 01293_client_interactive_vertical_singleline (Stateless tests (arm_binary, parallel))

Error on processing query: Code: 75. DB::ErrnoException: Cannot write to file (fd = 2): ,
errno: 11, strerror: Resource temporarily unavailable. (CANNOT_WRITE_TO_FILE_DESCRIPTOR)

errno 11 is EAGAIN, which a write only returns when the descriptor is non-blocking. The only code that put any client descriptor into non-blocking mode was f8f01564b63, which did fcntl(fd, F_SETFL, O_NONBLOCK) on std_out (fd 1) for the duration of nextImpl.

O_NONBLOCK is a property of the open file description, not of the file descriptor. In a terminal session the client's stdout (fd 1) and stderr (fd 2) are dup'd from the same open file description, and the interactive progress bar's tty_buf is built on stderr_fd (ClientBase.cpp tty_fd = stderr_fd). So while the result set is written through std_out (fd 1), flipping O_NONBLOCK there transiently makes fd 2 non-blocking too; a concurrent progress write to tty_buf (fd 2) then returns EAGAIN, and because tty_buf has no cancellation hook the generic write path treats it as fatal and throws on fd 2.

It is a low-probability race — CI's own auto-rerun passed it 83/83 — but a real one, and the same open-file-description flag could in principle also leak to the parent shell's terminal. Across the last 90 days this test failed on three PRs with three different signatures; this EAGAIN-on-fd-2 signature is unique to this PR and matches the O_NONBLOCK mechanism exactly.

On the original review concern that motivated O_NONBLOCK

The earlier review asked for genuine non-blocking because "POLLOUT only guarantees PIPE_BUF room on a pipe, so a blocking write could still sleep on a socket/terminal after poll returned writable." For the client's output the reverted poll(POLLOUT, 100 ms) + blocking write capped at PIPE_BUF is sufficient:

  • Stuck terminal (the headline case): a stuck tty never reports POLLOUT, so write is never reached; the poll times out every 100 ms and the cancellation hook is consulted — Ctrl+C is honored without ever calling write.
  • Slow-but-draining sink: a PIPE_BUF-capped write blocks only as long as it takes to drain one ~4 KiB chunk; the next poll re-checks the hook.
  • Pager pipe / FIFO: POLLOUT guarantees PIPE_BUF room, so the capped write does not block at all.

The only case O_NONBLOCK covered that poll+cap does not is a raw socket that becomes unwritable in the window right after POLLOUT — and the client's output is always a terminal, a pipe or a regular file, never a raw socket. If that ever needs covering, send(..., MSG_DONTWAIT) does it per-call without mutating the shared open file description. This poll+cap path is exactly what shipped (and passed full CI) in #106430; the data-race fix and the teardown-hook fixes are untouched.

Remaining CI reds — all known, unrelated flakes

  • Stress test (amd_tsan) / Stress test (arm_tsan) — "Hung check failed, possible deadlock found", the chronic master-wide flake Hung check failed, possible deadlock found #107941; the stacks are server-side AST-fuzzer query execution, which never touches the client cancellation hook.
  • Upgrade check (amd_release) — Error message in clickhouse-server.log: a stateless test's throwIf inside a mutation (MutatePlainMergeTreeTask → FUNCTION_THROW_IF_VALUE_IS_NON_ZERO) leaving expected error lines in the log; an upgrade-check log-scan issue unrelated to the client, addressed separately.
  • AST fuzzer (amd_debug) — Logical error: Inconsistent KeyCondition behavior in ReadFromMergeTree::selectRangesToRead; server-side query planning, unrelated to client output.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The current head 3f8b12c2736 (the O_NONBLOCK revert) does fix 01293_client_interactive_vertical_singleline, but it re-breaks the pty test this PR added for the headline #22426 case, 04490_client_cancel_blocked_terminal_output. On 3f8b12c2736 that test fails widely — every flaky-check variant (amd_asan_ubsan/tsan/msan/debug, 5–7 hits each) and the regular parallel runs (amd_debug, amd_tsan, amd_asan_ubsan distributed-plan, arm_binary, amd_llvm_coverage), all with FAIL: client is still running after Ctrl+C. It was green on the O_NONBLOCK build (f8afbc552cc). (The only other reds are unrelated flakes: AST fuzzer arm_asan_ubsan STID 0993-2cc2 is the tracked #108210 server-side Block structure mismatch — no client frames; and a one-off 00147_global_in_aggregate_function on arm_binary that did not recur.)

Why the revert's rationale does not hold for a stuck pty

The revert argues "a stuck tty never reports POLLOUT, so write is never reached." That is true only once the tty output buffer is already full. The failure is the write that transitions the buffer from "some room (POLLOUT)" to "full": poll(POLLOUT) reports the descriptor writable when there is some room but less than PIPE_BUF, and a blocking tty write(min(remaining, PIPE_BUF)) then queues bytes until all requested bytes are accepted — so it sleeps waiting for room that never opens (the test never reads the pty master), while SIGINT is delivered to the signal-handling thread, not to the thread stuck in write. The client never returns to the poll/hook loop → "still running after Ctrl+C". This is exactly what 04490's own comment already states: "a poll() reporting POLLOUT does not guarantee room for a whole chunk, so the write must be non-blocking for a single Ctrl+C to be honored." The revert removed the non-blocking write, so the test's premise no longer holds.

So 01293 and 04490 are two sides of one tradeoff:

  • O_NONBLOCK on std_out → interrupts a stuck tty (04490 green), but in a real terminal fd 1 and fd 2 share one open file description, so it transiently makes the progress tty_buf (fd 2) non-blocking → EAGAIN → 01293 red.
  • poll + blocking PIPE_BUF write → never touches the OFD flags (01293 green), but blocks unrecoverably on a fully-stuck tty → 04490 red.

This is a design call for you — I did not push a speculative third mechanism

This path has already been bitten twice by subtle races (#107845 the data race, then the O_NONBLOCK OFD leak), so rather than risk a third regression I left it for you to decide. The options, with their downsides:

  1. Non-blocking write on a private open file description. Keep the non-blocking write but set O_NONBLOCK on a re-opened, private OFD so it cannot leak to fd 2 or the parent shell. On Linux open("/proc/self/fd/<fd>", …) gives an independent OFD; note the BSD/macOS /dev/fd/<fd> equivalent behaves like dup for pipes/ttys (shares the OFD), so this is clean on Linux but needs care elsewhere. Correct and keeps the strong guarantee, at the cost of a re-open and platform handling.
  2. Tolerate EAGAIN in the generic write path. Restore O_NONBLOCK on the shared fd and make the hookless nextImpl path treat EAGAIN/EWOULDBLOCK as retryable (poll + retry) instead of fatal, so a stray EAGAIN on fd 2 is no longer thrown. Small and arguably more robust, but it touches the server-wide hot write path you wanted to keep unchanged and still briefly flips the flag on the shared terminal OFD (your parent-shell concern).
  3. Scope 04490 to a slow-but-draining terminal. The poll+PIPE_BUF path does handle a slow (draining) terminal and a paused-then-resumed pager — it blocks only per ~4 KiB chunk, then re-checks the hook. If prompt cancellation of a permanently stuck real terminal is not a goal (it needs a non-blocking write, i.e. option 1/2), 04490 could be relaxed to an intermittently-drained pty to match the shipped behavior.

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.

Comment thread src/Client/ClientBase.cpp Resolved
alexey-milovidov and others added 2 commits July 15, 2026 05:21
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Implemented option 1 (non-blocking write on a private open file description) from the design comment above:

  • f8b69f4 - the responsive write path re-opens the terminal via /proc/self/fd/<fd> (Linux) and sets O_NONBLOCK only on that private open file description, so a stuck terminal fails the write with EAGAIN (re-checked against the cancellation hook) while fd 2 and the parent shell are structurally unaffected - the leak that broke 01293_client_interactive_vertical_singleline cannot recur. Sockets use send(..., MSG_DONTWAIT); pipes keep the PIPE_BUF-capped blocking write, where that guarantee is actually valid; non-Linux platforms and a failed re-open keep the previous bounded fallback.
  • f18ae14 - the interactive Cancelling query. / Query was cancelled. diagnostics are printed best-effort through the same non-blocking path with a one-second budget, so the first Ctrl+C cannot re-block on the stuck terminal (the second review-bot thread).

Local verification against a Release build: 04490_client_cancel_blocked_terminal_output 5/5 (the sole CI red), 01293_client_interactive_vertical_singleline 15/15, 04318_client_cancel_blocked_output 3/3, 04489_client_exception_cleanup_no_truncation 3/3, 03701_pager_proper_termination 5/5, plus a manual pty check of the interactive stuck-terminal path (single Ctrl+C completes cancellation and the client returns to a usable prompt). This keeps the strong stuck-terminal guarantee; options 2/3 remain available if preferred.

… 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
Comment thread src/Client/ClientBase.cpp Resolved
…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).
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (f7c725663bb, conflict-free; ClientBase.cpp and WriteBufferFromFileDescriptor.cpp compile). This brings in #128088, which fixes the 05397_clickhouse_local_locked_path_untouched failure in Fast test (arm_darwin) (flock is missing on macOS; it fails on many PRs).

@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 Cannot mutate part all_3_3_0: none of its columns (v) would remain ... Empty parts are not allowed. (NO_SUCH_COLUMN_IN_TABLE), which comes from the check added to MutateTask.cpp. This PR changes only the client, clickhouse-local and WriteBufferFromFileDescriptor, so it does not touch this server mutation path.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in progress in #128105 (CI finished, Upgrade check (amd_release) is green on its head).

In this run the previous release left test_3 detached: 01160_table_dependencies ran ATTACH DATABASE test_3, and loading t_projection_positional (created by 05182 under SET enable_positional_arguments_for_projections = 1) failed with NOT_AN_AGGREGATE, because only the upgraded server had that setting in its profile. The kill step therefore did not see the interrupted mutation of 05259 in test_3.t_replicated, and the upgraded server re-attached the database and retried it. The MutateTask.cpp check works as intended. #128105 puts the setting into a users.d file that both servers read.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the remaining review thread in f002fa6: the comment on openTransientNonblockingPipeDescriptor now says the competing-pipe-writer guarantee is Linux-only. This change only touches a comment.

The red Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) check is 05386_webterminal_close_during_query. The web terminal query is still listed in system.processes (expected 0, got 1). This test is flaky on master and on many other PRs (11 failures in the last 30 days). @groeneai is already fixing it in #128209 ("Fix a web terminal query that failed on the client side staying in system.processes"). It is unrelated to this PR.

Comment thread src/Client/ClientBase.cpp Resolved
alexey-milovidov and others added 3 commits November 3, 2026 00:45
# 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The Stress test (amd_msan) failure Logical error: Cannot write to canceled buffer (STID 4158-307c, https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108078&sha=f002fa6f4a8161efefca3ce7a74bf244a20a49d0&name_0=PR&name_1=Stress%20test%20%28amd_msan%29) is not caused by this PR. It also happens on master and in many other PRs, and it is tracked in #125973. The fix is in progress in #126142.

alexey-milovidov and others added 3 commits November 4, 2026 07:49
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (conflict-free, clickhouse builds) and updated the reference of 05454_local_progress_from_pipeline_threads in a667708. That test was added on master after this branch was created, and the Fast test failure (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108078&sha=542618cc62b7c9246cd2fe94794ee0a0b4ea15a8&name_0=PR&name_1=Fast%20test) came from its reference. The reference expected the old behaviour, where Processed rows: N sat in the buffered std::cout until exit. This PR flushes the epilogue after each query, so the result of the final SELECT now appears in chronological order, after the progress lines of the earlier queries. The updated test passes 10 out of 10 runs locally.

Comment thread src/Client/ClientBase.cpp Resolved
Comment thread src/Client/ClientBase.cpp Resolved
alexey-milovidov and others added 2 commits November 7, 2026 01:28
… 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]>
Comment thread src/Client/ClientBase.cpp Resolved
alexey-milovidov and others added 3 commits November 8, 2026 20:30
# 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI on 0c4f0de93ae finished: all tests pass, and there are no unresolved review threads. The only red check is Build profile diff (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108078&sha=0c4f0de93ae8b86c68eeb7b11e37e6d34faf0b3f&name_0=PR&name_1=Build%20profile%20diff). It failed with LogClusterNotReady: the endpoint never became ready, which means the CI logs cluster was unavailable. This PR did not cause it. The fix is in progress in #129675. Nothing needs to change in this PR.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (596b18a1fb9, conflict-free; clickhouse builds, and 04836, 05408 and 05454 pass locally). This refreshes CI and clears the unknown mergeability state. The only red check on 0c4f0de93ae was Build profile diff, which failed with LogClusterNotReady (the CI logs cluster was unavailable). This PR did not cause it, and #129675 is still open to fix it. There are no unresolved review threads.

# Conflicts:
#	src/Client/ClientBase.h
#	tests/queries/0_stateless/05454_local_progress_from_pipeline_threads.reference
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (b0626a8cc54) in 42eca2ec595. Two conflicts: the ClientBase.h include list (kept <iostream> from this PR plus <algorithm> / <array> from master), and the reference of 05454_local_progress_from_pipeline_threads. For the reference I took the master version, because master now pipes that test through sort (36cdd15), so this PR no longer needs its own reordering of that reference. All of the changed translation units compile.

Comment thread src/Client/ClientBase.cpp Resolved
alexey-milovidov and others added 2 commits November 24, 2026 01:39
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (7692306d05f) in 4c28005dc8c. One conflict, in ClientBase::resetOutput: kept both the bounded final flush of std_out from this PR and the onQueryOutputReleased call added on master. clickhouse builds.

Addressed the review thread about deferred profile events in c94d9f1595a: the trailing flush is bounded only after an interrupt, and 05872_client_deferred_profile_events_paused_pipe_reader covers a full pipe whose reader resumes late. Locally 05872, 04672, 04758, 05054, 05223 and 05407 pass.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-cli clickhouse-client (interactive CLI) and client library. pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Pressing Ctrl+C in client should terminate the output of resultset.

3 participants