Skip to content

Fix client data race on std_out cancellation hook with parallel formatting - #107828

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix/client-cancellation-hook-race
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix/client-cancellation-hook-race

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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 a data race in the client/local on the result-output buffer's cancellation hook (introduced by the interruptible Ctrl+C output feature) when the result set is written with parallel formatting and a query ends by an exception.

Description

A ThreadSanitizer data race was reported on master by BuzzHouse (amd_tsan):

Both racing stacks reference the same long-lived heap object, the client's persistent stdout AutoCanceledWriteBuffer<WriteBufferFromFileDescriptor> (std_out, allocated once in ClientBase::ClientBase):

  • WRITE (main thread): WriteBufferFromFileDescriptor::setCancellationHook resetting cancellation_hook, from the scope guard at the end of ClientBase::processOrdinaryQuery.
  • READ (collector thread): WriteBufferFromFileDescriptor::nextImpl reading cancellation_hook, via FlushCallbackWriteBuffer::nextImpl from ParallelFormattingOutputFormat::collectorThreadFunction.

Root cause: the interruptible client output feature (PR #106430, issue #22426) installs a cancellation hook on std_out at the start of processOrdinaryQuery and removed 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. 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.

Fix: clear the hook in resetOutput() right after output_format.reset(). output_format.reset() destroys the parallel formatter and joins its collector thread (~ParallelFormattingOutputFormat -> finishAndWait -> collector_thread.join()), so afterwards no other thread can read std_out's hook and the clear is single-threaded. resetOutput() runs on every exit path of processParsedSingleQuery (including the SCOPE_EXIT_SAFE that already parks the formatting threads) and at the start of the next query, so the hook is still always removed and 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 confined to src/Client/ClientBase.cpp and does not touch the low-level WriteBufferFromFileDescriptor (which is used server-wide on a hot single-threaded write path).

…ing collector

The interruptible client output feature (ClickHouse#22426, ClickHouse#106430) installs a cancellation
hook on the persistent std_out WriteBufferFromFileDescriptor at the start of
processOrdinaryQuery and removed it via a scope guard 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 std_out's
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 exception without first
finalizing the output (for example 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. ThreadSanitizer reported this from
BuzzHouse (amd_tsan) on master (STID 5296-4b74).

Clear the hook in resetOutput() right after output_format.reset(), which destroys the
parallel formatter and joins its collector thread, so the hook is only mutated once no
other thread can read it. resetOutput() runs on every exit path of processParsedSingleQuery
(including the SCOPE_EXIT_SAFE that already parks the formatting threads) and at the start
of the next query, so the hook is still always removed and std_out (which outlives a single
query) never carries a stale hook into the next query.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Partial. The race is established by the CI TSan report (STID 5296-4b74, BuzzHouse (amd_tsan), master) with both racing stacks on the same long-lived std_out object, plus code analysis. I built buggy and fixed TSan binaries and exercised the parallel-formatting teardown under cancellation, server-kill (NetException) and formatter-error paths, but could not deterministically trigger the live window locally: every natural end-of-stream/cancellation path joins the collector via finalize() before the old scope guard, so only the exception-without-finalize window races, and it is a narrow timing window (BuzzHouse hit it once). I did not want to ship a band-aid, so the fix targets the exact mechanism in the stacks rather than the symptom.
b Root cause explained? Yes. The hook is installed on the persistent std_out at the start of processOrdinaryQuery and was cleared by SCOPE_EXIT({ std_out->setCancellationHook({}); }) at the end of that scope. The ParallelFormattingOutputFormat collector thread writes through std_out and reads its cancellation_hook in WriteBufferFromFileDescriptor::nextImpl. On exception paths that leave processOrdinaryQuery without first finalizing the output (NetException, or LocalFormatError rethrown from receiveResult), the scope guard clears the hook while the collector is still alive and reading it -> data race on the std::function.
c Fix matches root cause? Yes. The hook is now cleared in resetOutput() immediately after output_format.reset(), which destroys the parallel formatter and joins its collector thread, so the clear is single-threaded with respect to std_out's hook. This removes the unsynchronized concurrent access rather than masking it.
d Test intent preserved / new tests added? The feature's own test (04318_client_cancel_blocked_output.sh) is unchanged and still passes (verified locally on a TSan build: Ctrl+C still terminates the client on the stuck-sink path). No new regression test is added because I could not produce a deterministic local repro of the narrow race window; adding a flaky timing-based test would be unreliable. Open to adding one if a reviewer can suggest a deterministic trigger.
e Both directions demonstrated? Not fully. Verified the fixed binary is TSan-clean and the feature still works (client terminates on Ctrl+C). Could not deterministically reproduce the original race on the buggy binary locally (narrow timing window, see (a)); correctness of the fix rests on the ordering analysis in (b)/(c) plus the CI report.
f Fix is general, not a narrow patch? Yes. std_out is the only long-lived buffer whose per-query hook was cleared while a background thread could read it; the pager and INTO OUTFILE ... AND STDOUT buffers are per-query and are destroyed in resetOutput() after the collector join, so they were never racy. The change is at the single correct ordering point (after the collector is joined) and does not touch the server-wide low-level WriteBufferFromFileDescriptor.

Session id: cron:clickhouse-worker-slot-0:20260618-040800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @azat — could you review? This fixes a TSan data race that BuzzHouse (amd_tsan) found on master in the interruptible-output feature (#106430): the per-query std_out cancellation hook was cleared by a scope guard in processOrdinaryQuery that can fire (on exception paths) while the parallel-formatting collector thread is still reading it. The fix moves the clear into resetOutput(), after output_format.reset() joins the collector.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a232e17]

Summary: ✅


AI Review

Summary

This PR moves the persistent std_out cancellation-hook teardown out of processOrdinaryQuery and into resetOutput, after output_format.reset has joined the ParallelFormattingOutputFormat collector. The current code also preserves interruptible final stdout flushes on normal completion while avoiding the earlier exception-path bug where a stopped query_interrupt_handler looked like a user cancellation. I found no remaining line-level findings.

Missing context / blind spots
  • ⚠️ The full GitHub check suite was still pending when fetched. The direct Praktika PR report for a232e17a90f8e9d648851ec68a36c1783b607505 showed no failed tests at that time, and Style check was successful.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 18, 2026
Comment thread src/Client/ClientBase.cpp Resolved
Addressing review feedback on the previous placement: clearing std_out's
cancellation hook immediately after output_format.reset() removes the race
(the parallel-formatting collector thread is joined by then) but also disables
interruptibility for the remaining resetOutput() flushes - out_file_buf and
std_out_wrapper finalization and the final std_out->next(). If one of those
buffers bytes to a slow or stuck stdout, Ctrl+C could no longer discard the
buffer, regressing the blocked-output behavior from ClickHouse#106430.

Register the clear as a SCOPE_EXIT right after output_format.reset() instead:
it still fires strictly after the collector is joined (so no race), but only
at the end of resetOutput(), after the final flushes, so the hook stays active
through them and Ctrl+C keeps working. Using a scope guard also keeps the
clear on every exit path of resetOutput() (e.g. the SIGPIPE/SIGQUIT restore
can throw), matching the original guard's no-leak guarantee.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Client/ClientBase.cpp Resolved
@azat azat self-assigned this Jun 18, 2026
Reworks the std_out cancellation-hook lifetime to satisfy both the slow-stdout
interruptibility of the blocked-output feature (ClickHouse#106430) and the requirement
that already-produced output is not silently dropped on exception paths.

query_interrupt_handler.cancelled() is true both after a genuine Ctrl+C and
after the normal end-of-query stop() (both leave exit_after_signals <= 0), so it
cannot by itself distinguish "user cancelled" from "query finished". The earlier
revision kept that handler-based hook installed through the resetOutput() teardown
flushes; on exception paths processOrdinaryQuery's scope guard has already run
stop() before resetOutput() runs (via processParsedSingleQuery's scope guard),
making cancelled() unconditionally true and causing the final std_out_wrapper /
out_file_buf finalization and std_out->next() to discard output that was already
produced.

Snapshot whether the interrupt handler is still armed at resetOutput() entry and
choose the cancellation source accordingly: armed (normal completion, reached via
onEndOfStream while the handler is still active) keeps honoring the handler so a
fresh Ctrl+C still discards a flush to a slow/stuck stdout; stopped (exception
paths) falls back to the genuine cancellation flag, which is set only by
cancelQuery(), so completion is never mistaken for cancellation. The hook is still
only mutated after output_format.reset() has joined the parallel-formatting
collector that also reads it, so the original data race (TSan, BuzzHouse
amd_tsan) remains fixed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.20% -0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.50% 77.40% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 13/13 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing as obsolete.

This PR fixed the TSan data race (STID 5296-4b74) on std_out's cancellation hook vs the ParallelFormattingOutputFormat collector thread, introduced by the interruptible-output feature (#106430 / #22426).

That feature was reverted on master by #107845 (merged 2026-06-19). The revert removed the entire setCancellationHook/cancellation_hook mechanism from WriteBufferFromFileDescriptor and ClientBase, i.e. exactly the code this PR patched, so the race can no longer occur (setCancellationHook occurrences on master are now 0, and CIDB shows 0 master sightings since the revert).

If the feature is re-landed, the race fix from this PR (clearing the hook only after output_format.reset() joins the collector, while keeping it active through the final teardown flushes) should be folded into the re-land rather than applied separately.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants