Skip to content

Fix a data race on the gRPC output buffer with the Pretty squash thread - #128292

Merged
CheSema merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/grpc-pretty-squash-race
Nov 6, 2026
Merged

CheSema merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/grpc-pretty-squash-race

Conversation

@groeneai

@groeneai groeneai commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #128018

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 lost, duplicated or corrupted rows when a Pretty* result was streamed over gRPC (ExecuteQueryWithStreamOutput) while consecutive blocks were squashed (output_format_pretty_squash_consecutive_ms, enabled by default).

Description

On 26.3 and 26.8, streaming a Pretty* result over gRPC (ExecuteQueryWithStreamOutput) can lose, duplicate or corrupt rows, because the call thread copied and reset its output buffer while the Pretty squash thread was writing into it.

Found by Stress test (amd_tsan), STID 2046-35c1, on an unrelated PR (the stress test runs .sql tests over gRPC since #125517): report.

With output_format_pretty_squash_consecutive_ms != 0, PrettyBlockOutputFormat renders squashed blocks from a background thread into the call's output buffer, under IOutputFormat::writing_mutex. Between blocks, Call::generateOutput read that buffer (has_output), and Call::sendResult copied it and called restart() without the mutex. On the exception path the buffer was finalized while the writer could still render a pending chunk.

  • IOutputFormat::lockWriting() exposes the writing lock to the owner of the output buffer.
  • generateOutput no longer reads the buffer: has_output only duplicated the "nothing to send" check of sendResult.
  • sendResult copies the output in addOutputToResult, which holds the lock whenever the format exists.
  • onException destroys the format, which joins the writer, before the buffer is finalized.

Validation: the new test 05473_grpc_pretty_squash_output (unary, streamed and failing queries) produces data race reports in 5/5 runs on the TSan binary of the failing CI run, and none with the fix; it passes 50/50 on a debug build. Streaming 100 PrettyCompact queries of 30 rows, one row per block, with a 1 ms squash delay, returned wrong rows for up to 31 of them on 26.3.60.2 and 9 on 26.8.34.13, and was correct 100/100 with the fix. test_grpc_protocol passes.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits October 30, 2026 20:33
With a `Pretty` format and `output_format_pretty_squash_consecutive_ms != 0`,
`PrettyBlockOutputFormat` renders the squashed blocks from a background thread
into the gRPC call's output buffer, under `IOutputFormat::writing_mutex`. The
call thread read that buffer between the format calls without the mutex
(`has_output` in `Call::generateOutput`, the copy and `restart()` in
`Call::sendResult` for streaming calls), and finalized it on the exception path
while the writer could still render a pending chunk (TSan STID 2046-35c1 in
`Stress test (amd_tsan)`, where ClickHouse#125517 runs `.sql` tests over gRPC).

- `IOutputFormat::lockWriting()` exposes the writing lock to the owner of the
  output buffer.
- `Call::generateOutput` no longer reads the buffer: `has_output` only
  duplicated the "nothing to send" check of `sendResult`.
- `Call::sendResult` holds the lock while it copies a non-final message.
- `Call::onException` destroys the format (joining its writer) before the
  buffer is finalized.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The exception case of 05473 used to arrive ~50 ms after the writer had
rendered the last row, so there was no pending chunk to race with. Now
row 2 throws right after row 1, and the squash delay sweeps 1..5 ms, so
the writer's timer can fire while the call handles the exception.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review (2 nits, neither blocking).

# Sev Finding Verdict Evidence / action
1 💡 In 05473_grpc_pretty_squash_output.sh the shared query template keeps a {} placeholder that is only formatted with an empty string AGREE, noted, not blocking test behaviour unaffected
2 💡 #128018 (mine, a different race: the fatal error callback) edits the same has_output() call sites in GRPCServer.cpp AGREE, noted, not blocking textual conflict only; resolved by whichever PR lands second

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20261030-212400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On the TSan binary of the failing CI run, 05473_grpc_pretty_squash_output produces data race reports in 5/5 runs (79-117 per run), including the CI frame (has_output in Call::generateOutput vs PrettyBlockOutputFormat::writingThread).
b Root cause explained? Yes. The gRPC call reads, copies and resets its output buffer between format calls (and finalizes it on an exception), while the Pretty squash thread renders into the same buffer under IOutputFormat::writing_mutex, which the call does not hold.
c Fix matches root cause? Yes. The owner of the buffer takes the same mutex for the non-final copy, the unlocked read is removed, and the writer is joined before the buffer is finalized. Squashing is not disabled, the output is unchanged.
d Test intent preserved / new tests added? New test: unary (the CI stack), streaming (nothing lost or duplicated), failing query over a 1..5 ms squash sweep, liveness.
e Both directions demonstrated? Yes. Base: reports 5/5; fix: 0 reports 5/5, server exits 0. Per hunk: without the lock 5/5 red, without the onException reset 5/5 red. Streamed rows wrong on 26.3.60.2 / 26.8.34.13, correct 100/100 (TSan) and 300/300 (debug) with the fix.
f Fix is general across code paths? Yes. Every access to the buffer was checked: both has_output sites, the non-final copy (pull loop, executor callback), the final copy from finishQuery (finalized first) and onException (format destroyed first), totals/extremes (own buffers), close(), compressed output. Other handlers do not drain their buffer between format calls.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. All Pretty* variants share the writer thread (CI hit PrettySpaceNoEscapes, the test uses PrettyCompactNoEscapes); unary, streaming, exceptions, gzip/zstd output compression; without squashing or with other formats the lock is uncontended.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change. A failed query's pending squashed chunk is dropped instead of racing into the final message, as in HTTP.
i Invariants and contracts preserved? Yes. writing_mutex covers every buffer access by the writer and its owner until the format is finalized or destroyed; it is held only around buffer operations, takes no other lock, and is released before waiting on the gRPC write.

Session id: cron:clickhouse-impl-slot-6:20261030-205600

@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bed1b38]

Summary: ✅


AI Review

Summary

Reviewed #128292 at bed1b38e0d4c901e828495d09536c155605d22ee, including the complete discussion and current code. The change serializes gRPC output-buffer access with the Pretty writer and stops that writer before exception cleanup finalizes the buffer. No actionable findings remain.

Missing context / blind spots
  • ⚠️ Current-head gRPC and sanitizer CI jobs are still pending. Runtime validation relies on the author's reported current-head TSan and debug runs, including reproducing the race after removing the lock. No local ClickHouse binary/build is available; completed sanitizer CI would independently confirm these results.
Final Verdict

Status: ✅ Approve. No code changes requested; required CI checks still need to complete.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CheSema @vitlibar, could you review this and add the can be tested label so CI runs? With Pretty squashing on, the writer thread renders into the gRPC call's output buffer under IOutputFormat::writing_mutex while Call::sendResult copied and reset that buffer without it; the call now takes that lock through a new IOutputFormat::lockWriting() and destroys the format before finalizing on an exception. It touches the same has_output() lines as my #128018.

@clickhouse-gh clickhouse-gh Bot added the comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... label Oct 30, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bed1b38e0 with master bdbd1b837 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of b02fbee24; 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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9266e61

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
Upgrade check (amd_release) / Cannot submit the mutation that has to survive the upgrade, Cannot list the mutations left unfinished by the stress phase, Cannot count the mutations left unfinished by the stress phase, Cannot list the row policies left by the stress phase, Cannot run the mutation entries left behind by the killed mutations not from this PR: the stress phase runs the previous release v26.10.2.103-stable, before this PR's build is installed. Three fault injected errors carried Query pipeline: dumps of about 52k lines each, server memory went from 33 to 50 GiB in 6 s, and the memory cgroup killed the server (anon-rss:54031244kB), so every later probe got Connection refused #125706 (mine, merged; not in a 26.10 release yet)
Performance Comparison (arm_release, master_head, 4/6) / prewhere_subcolumns #1 not from this PR: select * from test where n.null reads a Nullable subcolumn of a MergeTree table and never reaches the gRPC or output format code this PR changes. Confirmed +32.2% (+28.0% after the server restart). The same query has been reported slower on arm on 11 unrelated PRs since 2026-10-30 23:19Z, after at most one such run per day before a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the rows above #125706 (merged) for the Upgrade check rows; a fix task is created for the prewhere_subcolumns #1 row

The first run of this head stopped at Config Workflow / Pre Hooks because the can be tested label was not set yet; the run after the label was added is the one above. CIDB has no other FAIL or ERROR row in that run.

Session id: cron:our-pr-ci-monitor:20261031-140009

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the prewhere_subcolumns #1 row of Performance Comparison (arm_release, master_head, 4/6): #128387. The two servers ended with different part layouts (a background merge sometimes finished before merges were stopped), so the query read 784908 rows on one and 130818 on the other; the change is test-only.

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

#128018 is merged, so this PR now conflicts in generateOutput. Please merge master and resolve both has_output() sites:

  • pulling loop: call_responder->takeLogsFromQueue(); sendResult();
  • completed branch: if (result.has_progress() || call_responder->hasUnsentLogs()) sendResult();

After #128018, onFatalError no longer calls sendResult, so a final message is sent only after the format is finalized or destroyed. Please state that rule in the comment above the lock in sendResult: the lock skip depends on it.

Nits: remove the unused {} placeholder in the test query; add Related: https://github.com/ClickHouse/ClickHouse/pull/128018 to the description.

groeneai and others added 2 commits November 4, 2026 17:56
…y-squash-race

# Conflicts:
#	src/Server/GRPCServer.cpp
…st placeholder

`Call::sendResult` sends a final message only from `finishQuery`, after `generateOutput`
has finalized the output format, and from `onException`, after the format is destroyed.
The fatal error callback sends its own result and does not touch the output buffer. So no
writing thread can be running when the final message finalizes the buffer.

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

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, done:

  • Merged master in 25231e5. Both has_output() sites are resolved as you wrote: the pulling loop is call_responder->takeLogsFromQueue(); sendResult();, and the completed branch is if (result.has_progress() || call_responder->hasUnsentLogs()) sendResult();.
  • 198ac6a: the comment above the lock in sendResult now states the rule (a final message is sent only after the format is finalized or destroyed, so it does not take the lock). The unused {} placeholder is gone from the test query.
  • Added Related: https://github.com/ClickHouse/ClickHouse/pull/128018 to the description.

On a debug build of the merged head, 05473_grpc_pretty_squash_output passes 20/20, and test_grpc_protocol with test_grpc_fatal_error passes 49/49.

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

Readability suggestion for sendResult, since you will touch it for the merge anyway:

  • Take the lock whenever output_format_processor is set, not only for intermediate messages. It is safe: sendResult runs only on the call thread and never under writing_mutex, and for a final message the writer is already stopped. Then the code does not depend on the final-message rule, and the comment I asked for is not needed.
  • Move the copy into a helper, e.g. addOutputToResult(bool final). The helper can return early on !write_buffer || write_buffer->isCanceled(), the lock lives for the whole helper, and the 30-line re-indent goes away. Keep the lock before the isCanceled check: WriteBuffer::next cancels the buffer when nextImpl throws, and that can happen on the writer thread.

The helper takes the format's writing lock whenever the output format exists, for
intermediate and final messages alike, so the copy no longer depends on how the final
message is ordered against the format's finalization. The lock is taken before the
`isCanceled` check because `WriteBuffer::next` cancels the buffer when `nextImpl`
throws, which can happen on the format's writing thread. `sendResult` runs only on the
call thread and never under the writing mutex, so the lock cannot deadlock.

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

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, done in bed1b38:

  • sendResult now calls addOutputToResult(send_final_message). The helper takes the writing lock whenever output_format_processor is set, before the !write_buffer || write_buffer->isCanceled() early return, so the re-indent and the final-message comment are gone.
  • I checked the safety argument: sendResult is called only from generateOutput (the pulling loop and the CompletedPipelineExecutor cancel callback, which runs on the calling thread), finishQuery and sendException, all on the call thread, and the call thread holds writing_mutex only inside IOutputFormat methods, which do not call back into Call.
  • The branch has no conflict with master now, so I did not merge it again.

On a TSan build of this head, 05473_grpc_pretty_squash_output has no reports in 10/10 runs, and removing the lock from the helper brings them back (3/3 runs). On a debug build it passes 20/20, and test_grpc_protocol and test_grpc_fatal_error pass. The sendResult bullet in the description is updated.

@CheSema
CheSema added this pull request to the merge queue Nov 6, 2026
Merged via the queue into ClickHouse:master with commit 3cd0dd7 Nov 6, 2026
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 6, 2026
qoega added a commit that referenced this pull request Nov 6, 2026
Preserve the `Call::onException` memory exception guard before master
stops the output format writer. Keep master's `addOutputToResult` locking
and the PR's context/admission cleanup.

Related: #128292
Related: #123112
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-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants