Skip to content

Stop the Pretty squash thread when its output format is cancelled - #129825

Merged
PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:pretty-squash-stop-on-cancel
Nov 10, 2026
Merged

PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:pretty-squash-stop-on-cancel

Conversation

@groeneai

@groeneai groeneai commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #128292

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

An INSERT into file() (or File, url(), s3(), ...) with a Pretty* format that fails after its first block has a data race: the format's squash thread renders the queued block into the sink's write buffer after the sink has cancelled it. Found by La Casa Del Dolor (amd_tsan) on an unrelated PR: report.

With output_format_pretty_squash_consecutive_ms != 0 (default), PrettyBlockOutputFormat writes squashed blocks from a background thread under writing_mutex. Sinks cancel the format and then its buffer (StorageFileSink::cancelBuffers), relying on a cancelled format no longer touching the buffer, as ParallelFormattingOutputFormat::onCancel guarantees. PrettyBlockOutputFormat had no onCancel, and its thread wrote on any wake-up without re-checking finish, so the destructor's stopThread (or the thread's own timeout) wrote into the cancelled buffer.

  • onCancel sets finish under writing_mutex: when it returns, no write is in progress and none starts later.
  • writingThread exits when it wakes up with finish set; the rest is written by writeSuffix, or not at all for a cancelled format.

This covers every owner that cancels the format before its buffer (file, URL, object storage and message queue sinks). onCancel may now wait for one blocked write to the buffer, like ParallelFormattingOutputFormat::onCancel waits for its collector.

Validation: the new test 05564_pretty_squash_cancelled_insert reproduces the CI race in 19/20 runs on the master TSan build of the base commit and in none on the fixed build. The test has one case per path, a queued block and a block being written, and each change alone fails one of them (onCancel alone the first 5/5, the finish re-check alone the second 10/10, on TSan). It passes 50/50 on a debug build, and so do the other Pretty tests. On a release build the query still fails with its own error, hence not for changelog.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 3 commits November 6, 2026 17:29
With `output_format_pretty_squash_consecutive_ms != 0`, `PrettyBlockOutputFormat`
renders squashed blocks from a background thread under `writing_mutex`. Owners of the
output buffer cancel the format and then the buffer (`StorageFileSink::cancelBuffers`),
relying on a cancelled format no longer touching the buffer, which is what
`ParallelFormattingOutputFormat::onCancel` guarantees by joining its collector.

`PrettyBlockOutputFormat` had no `onCancel`, and the thread wrote on any wake-up of
`wait_for` without re-checking `finish`. A failed `INSERT INTO FUNCTION file(...)` with a
queued block therefore cancelled the buffer, destroyed the format, and the destructor's
`stopThread` wake-up rendered the block into the cancelled buffer: a data race reported by
TSan in `La Casa Del Dolor (amd_tsan)` (STID 1003-46d8). The thread's own timeout firing
between the buffer cancel and the destructor is a second way into the same race.

`onCancel` now sets `finish` under `writing_mutex`, and the thread re-checks `finish` after
every wake-up. Each change alone leaves one of the two paths racing. No join in `onCancel`:
it can run on the writer thread itself, when its write error cancels the query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The first case of 05564 only reaches the destructor's wake-up of the squash thread, so it
stays green when `PrettyBlockOutputFormat::onCancel` is removed and only the `finish`
re-check is left. The second case queues a 100k-row block that the thread starts writing
right away, and throws from the next block 0.8 s later, while the write is still in
progress. Without `onCancel` the sink cancels its buffer under the writing thread: TSan
reports the race (and a single-character write into the cancelled buffer aborts on
`LOGICAL_ERROR`). With it, cancelling the format waits for the write to end.

Measured on TSan: base 9/10 red, the `finish` re-check alone 10/10 red, the fix 0/10;
the whole test is green 10/10 on the fix with randomized settings, and `onCancel` alone
still fails the first case. On other builds the write ends before the cancel, so the
case is a smoke test there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the onCancel comment to its postcondition.

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

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds): 1 finding accepted and fixed in the test, no open findings
Finding Verdict
❌ The test did not fail with onCancel removed (it exercised only the destructor wake-up) AGREE, fixed: a second case cancels the INSERT while the squash thread is writing; it fails with only the finish re-check (10/10 on TSan)
💡 Price: onCancel may wait for one in-progress squashed write Noted: same bound as ParallelFormattingOutputFormat::onCancel
💡 The second case leaves a few-MB file in user_files Noted: per-database name, truncated on rerun

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05564_pretty_squash_cancelled_insert against the master CI TSan binary of the base commit gives the CI report (writingThread -> WriteBuffer::write vs StorageFileSink::cancelBuffers -> WriteBuffer::cancel) in 19/20 runner runs with randomized settings.
b Root cause explained? Yes. The squash thread writes out under writing_mutex; PrettyBlockOutputFormat had no onCancel, and the thread wrote on any wake-up without re-checking finish. After the sink cancels its buffer, the destructor's stopThread wake-up (or the thread's own timeout) renders the queued block into it with no happens-before edge.
c Fix matches root cause? Yes. The format now honours the cancel contract itself (onCancel sets finish under writing_mutex; the thread re-checks finish after every wake-up), the same guarantee ParallelFormattingOutputFormat::onCancel gives. No owner change, no guard at the race site.
d Test intent preserved / new tests added? Yes. New SQL test with one case per path (a queued block; a block being written when the INSERT fails), a TSan detector and a smoke test on other builds; existing Pretty tests unchanged and passing.
e Both directions demonstrated? Yes. Queued-block case: base TSan 19/20 red, fixed TSan 0/10, onCancel alone 5/5 red. Block-being-written case: base TSan 9/10 red, the finish re-check alone 10/10 red, fixed TSan 0/10. Whole test on the fixed TSan build 10/10 green with randomized settings, 0 reports.
f Fix is general across code paths? Yes. It is the only output format whose own thread writes out without stopping on cancel; the format-layer change covers every owner that cancels the format before the buffer (file, URL, object storage, message queue sinks; gRPC was #128292).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. All non-MonoBlock Pretty* variants share the class; MonoBlock and output_format_pretty_squash_consecutive_ms = 0 start no thread and return early. Default and pinned squash settings exercised; 50/50 randomized runs.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change. Output of finalized queries is unchanged (timeout_overflow_mode = 'break' output complete on base and fix; regression suite green).
i Invariants and contracts preserved? Yes. out is written only under writing_mutex and while finish is unset; lock order unchanged (onCancel takes only writing_mutex, whose holders never take the executor or process list locks); the writer drops the mutex before cancelQuery, so its self-cancel over HTTP broken pipe ends without a deadlock (5/5).

Session id: cron:clickhouse-impl-slot-41:20261106-175700

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim @CheSema, could you review this and add the can be tested label so CI runs? La Casa Del Dolor (amd_tsan) found that PrettyBlockOutputFormat had no onCancel, so its squash thread could write into a file() sink buffer after the sink cancelled it; onCancel now sets finish under writing_mutex and the thread re-checks it after every wake-up (same race class as #128292).

@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0a2af49]

Summary: ✅


AI Review

Summary

The PR makes PrettyBlockOutputFormat cancellation wait for active writes and prevents the squash thread from rendering queued data after cancellation. No actionable findings in the current diff. The focused regression covers both queued and active writes, with completed TSan evidence supporting the fix.

Missing context / blind spots
  • ⚠️ Full CI for head 0a2af493983b3381b6e53058469fe26b9ba0c035 is still pending. No local tests were run because this checkout has no built binary. The completed TSan report for the earlier revision contains 50 passing repetitions each of 05564_pretty_squash_cancelled_insert and 05061_pretty_squash_flush.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Nov 6, 2026
@PedroTadim PedroTadim self-assigned this Nov 6, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Nov 6, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov feel free to merge PRs assigned to me

@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai

The fix looks right to me. onCancel sets finish under writing_mutex, and writingThread checks finish again after every wake-up, so nothing writes into the buffer after the sink has cancelled it. writeSuffix still writes the queued chunk itself, under the same mutex, so a normal finish loses nothing. The thread's own cancelQuery path unlocks before cancelling, so onCancel cannot deadlock on it either.

One question about the cost the description mentions. writing_mutex is the lock of every writing method of IOutputFormat (work, flush, finalize, writeFinalProgress), not only of the squashed write. With HTTP and a client that stopped reading, any of them can sit in a blocking socket send while holding it. KILL QUERY, and ProcessList::killAllQueries at shutdown, then wait in onCancel until that send returns, at most send_timeout. Before, onCancel was a no-op and returned at once. ParallelFormattingOutputFormat already behaves like this, so it may be acceptable. Could it be stated in the onCancel comment that the wait can be as long as one blocked write to out, not only the rendering of one squashed block?

@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Nov 6, 2026
`writing_mutex` is held by every writing method of `IOutputFormat`, so
`onCancel` (and with it `KILL QUERY` and `ProcessList::killAllQueries`) waits
for one blocked write to `out`, not only for one squashed render. Measured over
HTTP with a client that stopped reading and `http_send_timeout = 10`: `KILL QUERY`
returns after 19-20 s instead of 0.1 s, while the query itself ends at the same
time as before.

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

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0a2af4939 with master 5c1a21488 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of ad36c6520; 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

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

Job report

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, done in 334fe6c: the onCancel comment now says it waits for any writing method holding writing_mutex, so up to one blocked write to out. The description's sentence says the same now.

I measured it over HTTP with a client that stops reading (http_send_timeout = 10, 3 runs per build):

KILL QUERY returns after query ends after
master 0.1 s 19.5-20.5 s
this PR 18.7-19.8 s 18.8-19.8 s

So the query does not stop later; KILL QUERY now returns when it does. Two details: on the HTTP interface the socket timeout is http_send_timeout (30 s by default, set in HTTPServerRequest), not send_timeout, and WriteBufferFromPocoSocket::nextImpl restarts it after every partial send, which is why one blocked write took about 2 x 10 s here.

@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 334fe6c

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
Integration tests (amd_tsan, targeted) / 26 tests of test_storage_kafka/test_batch_fast.py not from this PR (it changes only PrettyBlockOutputFormat): a librdkafka data race (rd_kafka_toppar_set_fetch_state vs rd_kafka_toppar_fetch_backoff) aborts the Kafka test server under TSan, and the rest of the module then fails with Code: 210 connection refused; the same module wipe hit master Integration tests (amd_tsan, 7/8) and 4 other PRs in the last 14 days #129623 (external, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05515_global_subquery_projection_where not from this PR (the test is not in its diff): Code: 47 UNKNOWN_IDENTIFIER on a _data_<hash> name at the INSERT, deterministic on master in this lane since the test was added #129836 (mine, open)
Mergeable Check, PR praktika rollups of the two rows above #129623 and #129836 (the owners of the rows above)

No job was dropped, and CH Inc sync passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261107-023005

@PedroTadim
PedroTadim enabled auto-merge November 9, 2026 09:16
@PedroTadim
PedroTadim added this pull request to the merge queue Nov 9, 2026
Merged via the queue into ClickHouse:master with commit 8a8883a Nov 10, 2026
187 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 10, 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-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). 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.

3 participants