Skip to content

Do not share the output buffer of a gRPC call with its fatal error callback - #128018

Merged
CheSema merged 5 commits into
ClickHouse:masterfrom
groeneai:grpc-fatal-error-callback-race
Nov 4, 2026
Merged

CheSema merged 5 commits into
ClickHouse:masterfrom
groeneai:grpc-fatal-error-callback-race

Conversation

@groeneai

@groeneai groeneai commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

When any thread of a gRPC query hits a fatal error, or receives SIGTSTP (the "print a stack trace" signal), SignalListener::onFault runs the query's fatal error callback on the signal listener thread while the gRPC call thread is still running. Call::onFatalError then wrote result and finalized the call's output buffer concurrently with the call thread writing into them. Stress test (amd_tsan) reported it as ThreadSanitizer: data race (GRPCServer.cpp:1374 vs Call::sendResult <- Call::onFatalError) instead of the job's actual crash: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=103402&sha=1aba14a95c8dff9125f973707ff65c4911c8839a&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29. In debug and sanitizer builds the call thread's next write also aborts with Logical error: 'Cannot write to finalized buffer'.

The callback now sends its own FatalError result and never touches result or the output buffers. Everything it uses (the responder, the logs queue, the logs taken from it but not sent yet, the write state) lives in CallResponder, guarded by one mutex, so the fatal message still carries every log line. The callback captures CallResponder by weak_ptr, because it can outlive the call (as in TCPHandler, #94292). It waits at most 1 s for the mutex, since the faulting thread can be the call thread itself, and it cancels the query; an inline INSERT checks for that before each block. CallResponder::close() cancels and waits for a pending write, and no read is started after the call is finished.

The new integration test test_grpc_fatal_error sends SIGTSTP to a pipeline thread of an ExecuteQueryWithStreamOutput call, with and without output compression, and of an ExecuteQuery call, and to the call thread of an inline INSERT. On master the server aborts in the streaming cases, the non-streaming query and the insert keep running, and the TSan build reports the race. With the fix all four cases pass in debug and TSan builds with no TSan report, as do test_grpc_protocol and test_grpc_protocol_ssl.


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

Version info

  • Merged into: 26.11.1.1349-master (included in 26.11 and later)

groeneai and others added 2 commits October 28, 2026 01:36
…llback

`SignalListener::onFault` runs the query's fatal error callback on the signal
listener thread while the gRPC call thread can still be running (a fault in a
pipeline thread, or a SIGTSTP stack-trace request). `Call::onFatalError` then
mutated `result` and finalized the call's write buffer concurrently with the
call thread writing output into it: a data race (TSan, STID 0250-04e2 in
`Stress test (amd_tsan)`), and the call thread's next write threw
`Cannot write to finalized buffer` (an abort in debug/sanitizer builds).

The callback now sends its own `FatalError` result and never touches `result`
or the output buffers. Writes to the responder are serialized by a mutex held
in a `shared_ptr` the callback captures weakly (the callback can outlive the
call, as in TCPHandler); the callback uses the call only while it is not
closed and gives up after 1 s instead of waiting for a call thread that may be
the faulting one. It also cancels the query, which nobody can receive the rest
of. Logs taken from the logs queue but not sent yet wait under the same mutex,
so the fatal message still carries them for every call type (a non-streaming
call sends its logs only with the final message). The logs queue is set up
before the callback is installed, and transport compression is applied under
the mutex unless the callback has already finished the call. When the callback
finished the call first, the call thread's final result is not sent and its
output buffer is never finalized, so `close()` cancels it (a compressing output
buffer would otherwise be destroyed neither finalized nor canceled).

The new integration test `test_grpc_fatal_error` sends SIGTSTP to a pipeline
thread of a gRPC query in three cases: `ExecuteQueryWithStreamOutput` without
and with output compression, and `ExecuteQuery`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the ResponderLock comment to one line and drop four comments that restate the code next to them.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds before publication; the fixes are in this PR)
Finding Verdict
❌ After the fatal callback finished the call, close() destroyed a compressing output buffer that was neither finalized nor canceled (chassert in ~WriteBuffer) AGREE: close() cancels it; new lz4 test case
⚠️ The log oracle could pass without the unsent_logs hop AGREE: the test asserts the query's executeQuery log line reaches the FatalError message
⚠️ That oracle waited with a fixed sleep (.claude/CLAUDE.md: never wait with a fixed time.sleep) AGREE: the test waits until the query has read enough rows that the call thread must have pulled some
⚠️ Input-streaming Read concurrent with the fatal Finish DISAGREE: gRPC core allows send and receive batches to be synchronized independently (grpc.h:236-240); every send is serialized here
⚠️ The test does not force the write-start interleaving DISAGREE: the test fails on master in all cases and builds; forcing that window needs a test-only pause point in sendResult

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. tgkill SIGTSTP to the QueryPullPipeEx thread of a running gRPC SELECT number, sleepEachRow(0.1) FROM numbers(1200) SETTINGS max_block_size = 1, max_threads = 1. On master every run fails: debug aborts on Cannot write to finalized buffer (streaming output), the non-streaming query keeps running after the FatalError was sent, TSan reports the race.
b Root cause explained? SignalListener::onFault runs the query's gRPC fatal error callback on the signal listener thread while the call thread keeps producing output. Call::onFatalError wrote result, finalized the output buffer and wrote to the responder with no synchronization against the call thread doing the same.
c Fix matches root cause? Yes. The callback builds and sends its own result and never touches result or the output buffers; the only shared state (responder writes, not yet sent logs) is guarded by one mutex, captured weakly as in TCPHandler.
d Test intent preserved / new tests added? New integration test test_grpc_fatal_error: streaming calls with and without output compression, and a non-streaming call. It checks that the server survives, the query stops, the client gets FatalError with the fatal log lines and the query's own executeQuery log line, and there is no Cannot write to finalized buffer, no WriteBuffer is neither finalized nor canceled and no sanitizer report.
e Both directions demonstrated? Master: both streaming cases fail (server abort), the non-streaming case fails (query still running after 30 s), the TSan build reports the race. Fix: 20/20 debug runs, 3/3 TSan runs, no TSan report.
f Fix is general across code paths? Only TCPHandler (already serialized) and GRPCServer register a fatal error callback. All four gRPC call types, the exception and finish paths, and INSERT (logs drained only at the end) go through the same locked write start.
g Fix generalizes across inputs (params/datatypes/wrappers)? Stream, simple and stream IO calls measured, the streaming call also with lz4 output compression. The fatal path does not touch the output buffers, and close() cancels one that the final result did not finalize; transport compression is applied under the mutex. Data types: N/A (no value handling).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, protocol or format change. Only the fatal path changes: the FatalError message no longer carries the partial output of the current block, and the query is cancelled when the process survives.
i Invariants and contracts preserved? One outstanding write at a time; no write after writeAndFinish; the responder is not destroyed while the fatal path writes; every drained log line is sent exactly once; lock order is responder mutex, then logs queue mutex; the call thread never waits, logs or runs user code under the mutex.

Session id: cron:clickhouse-impl-slot-4:20261028-003400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vitlibar @CheSema, could you review this and add the can be tested label so CI runs? When a thread of a gRPC query faults, the fatal error callback ran sendResult on the signal listener thread while the call thread kept writing the same result and output buffer; it now sends its own FatalError message, and responder writes plus the pending logs are serialized by one mutex the callback holds weakly.

@clickhouse-gh

clickhouse-gh Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a71b7ec]

Summary: ✅


AI Review

Summary

The PR isolates the gRPC fatal-error callback from the call's output buffers and serializes responder access through CallResponder. The current code also fixes the previously reported inline INSERT cancellation gap and adds regression coverage. No unresolved findings remain at a71b7ec75631a54cbe269e70fb143b99f2c55715.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... labels Oct 28, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4e387ad

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / 05227_mutate_part_ahead_of_table_metadata_version_mergetree flaky, not from this PR (the test is not in its diff, which changes only GRPCServer.cpp and a new integration test): the rewrite dropped the column: 1 instead of 0, failing on 114 PRs in 14 days; the tested merge tree predates the fix #127925 (mine, merged)
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything #126200 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #127925, #126200 (the owners of the rows above)

The new integration test and CH Inc sync passed. The earlier Config Workflow failures were the attempts before the can be tested label.

Session id: cron:our-pr-ci-monitor:20261028-180006

@CheSema CheSema self-assigned this Oct 29, 2026
Comment thread src/Server/GRPCServer.cpp Resolved
…ponder

The fatal error callback now captures only a weak_ptr to CallResponder,
which owns the responder, the logs queue, the unsent logs and the write
state, all guarded by one mutex. The raw Call pointer, call_closed and the
second addLogsToResult overload are gone. After close() the responder is
null, so a late callback does nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Server/GRPCServer.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a71b7ec75 with master 3b3f22da1 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

3 object files changed (+18.94 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Server/GRPCServer.cpp.o 753.04 KiB 771.98 KiB +18.94 KiB (+2.52%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7f1b9c6

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / 05397_clickhouse_local_locked_path_untouched flaky on macOS, not from this PR (its diff changes only GRPCServer.cpp and the new gRPC integration test): the test holds the lock with flock(1), which macOS does not have; it failed on 160 PRs in 14 days, and the tested merge tree predates the fix #128088 (mine, merged)
Mergeable Check, PR praktika rollups of the row above #128088 (the owner of the row above)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261029-173003

@CheSema

CheSema commented Nov 3, 2026

Copy link
Copy Markdown
Member

@groeneai check Fast tests, is it related? Update branch and trigger CI if it is not related.

Comment thread src/Server/GRPCServer.cpp Resolved
groeneai and others added 2 commits November 3, 2026 12:29
…atal error

- `close` cancels a pending write and waits for it, instead of destroying the
  responder that owns its completion tag. The final `sendResult` can throw from
  `finalize` while an intermediate write is in flight.
- If starting a write throws, `sending` is reset and the call stays unfinished
  with its logs unsent, so `close` and `waitWritten` cannot wait forever.
- `read` refuses to start a read once the call is finished.
- `processInput` checks `isQueryCancelled` before pulling each block, so an
  inline `INSERT` stops after `FatalError`, and a call with streaming input
  stops reading.

The new test case sends SIGTSTP to the call thread of an inline `INSERT` over
`ExecuteQuery`; without the check the insert keeps running.

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

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Not related: 05397_clickhouse_local_locked_path_untouched holds its lock with flock(1), which macOS does not have, and #128088 fixed it after CI ran on the previous head. I merged master; CI is running on a71b7ec.

@CheSema CheSema left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@CheSema
CheSema enabled auto-merge November 4, 2026 13:52
@CheSema
CheSema disabled auto-merge November 4, 2026 15:51
@CheSema
CheSema added this pull request to the merge queue Nov 4, 2026
Merged via the queue into ClickHouse:master with commit 08d8752 Nov 4, 2026
184 of 185 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants