Skip to content

Show the result in Pretty formats as soon as it arrives - #117005

Merged
alexey-milovidov merged 22 commits into
masterfrom
pretty-flush-squashed-chunk
Oct 9, 2026
Merged

alexey-milovidov merged 22 commits into
masterfrom
pretty-flush-squashed-chunk

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 29, 2026 •

Copy link
Copy Markdown
Member

Pretty formats squash consecutive blocks in a background thread, so that a stream of small blocks is rendered as one table rather than many. That thread wrote the rendered table into the output buffer but never flushed it, and the main thread had already done its auto_flush before the table was written. The table therefore reached the terminal only when the next block arrived and flushed the buffer, or when the query finished.

A query that returns a few rows early and then keeps reading - for example SELECT DISTINCT over a large table - displayed nothing at all until it was cancelled or completed:

:) WITH number % 2 ? 'UTC' : 'Europe/Amsterdam' AS tz SELECT DISTINCT formatDateTime(now(), '%F %T', tz) FROM numbers(1e9)

Cancelling query.
   ┌─formatDateTi⋯%F %T', tz)─┐
1. │ 2026-08-29 01:58:06      │
2. │ 2026-08-28 23:58:06      │
   └──────────────────────────┘
Query was cancelled.

Both rows were ready within milliseconds, but nothing was printed until the query was cancelled.

The fix flushes right after the squashed chunk is rendered. The client wraps its output in a buffer whose flush callback clears the progress indication first, so the table still does not collide with the progress bar.

The same delayed output happened on the framed HTTP path (framing_output_format), for a different reason: there the payload reaches the client only when a packet boundary is taken, and IOutputFormat::work takes the Data boundary right after consume returns - which, for squashed Pretty, has written nothing yet. So the background writer takes its own Data boundary when framing is set.

Caused by: #73852

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

Show the query result in Pretty formats as soon as it arrives. Previously a query that returns a few rows early and then keeps reading, such as SELECT DISTINCT over a large table, displayed nothing until it finished or was cancelled.


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

Version info

  • Merged into: 26.10.1.1960-master (included in 26.10 and later)

`Pretty` formats squash consecutive blocks in a background thread, so that a
stream of small blocks is rendered as one table rather than many. That thread
wrote the rendered table into the output buffer but never flushed it, and the
main thread had already done its `auto_flush` before the table was written.
The table therefore reached the terminal only when the next block arrived and
flushed the buffer, or when the query finished.

A query that returns a few rows early and then keeps reading - for example
`SELECT DISTINCT` over a large table - displayed nothing at all until it was
cancelled or completed:

    :) SELECT DISTINCT number % 2 FROM numbers(1e10)

Flush right after the squashed chunk is rendered. The client wraps its output
in a buffer whose flush callback clears the progress indication first, so the
table still does not collide with the progress bar.
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f22d128]

Summary: ✅


AI Review

Summary

This PR makes squashed Pretty output reach the client immediately by moving the effective flush / framing boundary to the background writer, and it wires background write failures back into both the server-side and client-side cancellation paths so broken pipes stop the query promptly instead of letting it keep scanning. I reviewed the current tree, the PR discussion, and the added stateless coverage, and I did not find remaining correctness, concurrency, or contract issues that warrant a new review comment.

Final Verdict

✅ No new blocking or major findings in the current revision.

LLVM Coverage Report

Measured on commit f22d128.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 43/44 (97.73%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit f22d1289e99ea95a56fffff02d9d019da8990b81 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

…ty` chunk

Under `framing_output_format`, `IOutputFormat::work` takes the `data` boundary right
after `consume` returns, but for squashed `Pretty` output `consume` only appends to
`mono_chunk` and writes no payload. The table rendered later by the background writer
therefore stayed in the framing payload buffer until the next boundary or finalization,
so the framed HTTP path had the same delayed-output problem as the terminal one.

Take a `Data` boundary in `writeMonoChunkIfNeeded` when framing is set (it runs under
`writing_mutex`, like `work`, so the framing format still sees serialized calls), and
cover it by an HTTP test with `framing_output_format=JSONEachPacketString`.

The test is renumbered to 05056, because master now has a test 05049.
…t query

The squashed `Pretty` writer needs to take a framing packet boundary, so
`writeFramingPayloadBoundary` moves from `private` to `protected` in `IOutputFormat`.

The framed part of the test also bounds its endless query with `max_execution_time` and
`cancel_http_readonly_queries_on_client_close`, so the server does not keep reading after
the client is gone.
… the `data` packet

The stateless test server caps `max_rows_to_read` at 20 million in its default profile, so
`numbers(1e18)` over HTTP threw `TOO_MANY_ROWS` before producing anything, and the first line of
the framed output was a `profile_events` packet instead of the `data` packet the test looked for.
`clickhouse-local`, used by the unframed part, has no such cap, which is why only the framed part
failed in the Fast test. Also wait for the `data` packet itself instead of the first line, so
other packet kinds preceding it cannot break the test, and renumber the test to `05061` because
master already has a `05056` test.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117005&sha=e14363c9292adfed1c93987e034d3c3bfb388818&name_0=PR&name_1=Fast%20test
PR: #117005
With more threads the `numbers` sources saturate the machine, and on a loaded host the thread that
pulls the result in `clickhouse-local` may not receive the first block for many seconds, which has
nothing to do with the flush under test. A single thread pulls the result synchronously.
@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Sep 4, 2026
alexey-milovidov and others added 2 commits September 16, 2026 07:29
… of the test

The `clickhouse-local` half inherited the default value of the setting, so with a
profile or a future default of `0` it would take the direct `writeChunk` path and
stop exercising the background writer this PR fixes. Addresses the review thread
on `05061_pretty_squash_flush.sh`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
alexey-milovidov and others added 4 commits September 23, 2026 02:34
…read

The background writer of squashed `Pretty` output swallowed exceptions: if its
write or flush failed (broken pipe, client disconnect), the thread exited and the
query kept running, accumulating chunks that were never written. Capture the
exception in `writingThread` and rethrow it from `write` and `writeSuffix`, which
run under the same `writing_mutex`.

Add `05238_pretty_squash_broken_pipe` (`clickhouse-local ... | head -n 1` hangs
until `timeout` before the fix), and make the unframed half of
`05061_pretty_squash_flush` assert that the table arrived before the query is
cancelled.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ails to write

The exception stored by `writingThread` was rethrown only from the next `write` or from
`writeSuffix`. A query that has already produced all of its output and keeps reading (for example,
`SELECT DISTINCT` over a huge table, whose values are all found in the first blocks) has no next
`write`, so a broken pipe was noticed only when the whole scan finished.

Now the thread also cancels the query through `QueryStatus::cancelQuery` with
`CANCELLED_BY_ERROR` and the stored exception, so the query stops immediately and reports the real
error (`CANNOT_WRITE_TO_FILE_DESCRIPTOR`) instead of `QUERY_WAS_CANCELLED`. The lock is released
before that, so the executor's cancellation never runs under `writing_mutex`.

`05238_pretty_squash_broken_pipe` gets the second case: one large table written at the beginning,
then no more output.

#117005 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
# Conflicts:
#	src/Processors/Formats/Impl/PrettyBlockOutputFormat.cpp
Bartok9 pushed a commit to Bartok9/ClickHouse that referenced this pull request Oct 4, 2026
The test asserts JoinBuildPostProcessingMicroseconds > 0 on the initiator's
query_log row. Under parallel replicas the join-order randomization can put
t_post_build_left, the coordinated read, on the build side. Its marks form
one coordinator segment owned by a remote replica, so when the local
replica's first read request arrives after that replica announces, the local
replica gets 0 marks and builds an empty hash table. The whole build and its
post-build phase then run in the remote replicas' secondary queries, whose
ProfileEvents are forwarded to the client only and are not added to the
initiator's query_log row, so the check reads 0.

Seen in "Stateless tests (arm_binary, ParallelReplicas, s3 storage,
parallel)" on PRs ClickHouse#117005 and ClickHouse#123740 with the output "0 0" instead of "1 0".

Pin enable_parallel_replicas = 0 on the measured join only, as other join
tests asserting join ProfileEvents already do. The test's subject,
SpillingHashJoin running the post-build phase of the wrapped join, does not
depend on how the read is split between replicas.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: 05237_with_expression_alias_scope_descendant in Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) (view 10 / stored alias is bare 0 instead of 100 / 1) and provide a fix in a separate PR. If the fix is already in progress, link it here. According to CIDB, it failed in 187 unrelated PRs between 2026-10-03 and 2026-10-04.

The other failures in this run are unrelated as well, and their fixes have either landed or are in progress: the Build (amd_fuzzers) relocation overflow (#123738, merged), the TimeSeries tests and 04647 under parallel replicas (#123763, merged), 04266_text_index_tokens_cardinality_order (#123688), and 03008_optimize_equal_ranges (#123695). I merged master into this branch to pick up the merged fixes.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

The fix is in progress: #123790 (open), which includes the change from my closed #123774. In its run on 2a290a03b66, 05237_with_expression_alias_scope_descendant passes in the arm_binary DBReplicated 1/2 job.

The failure on e845e2d2f13 (2026-10-03 15:56) has the same diff as on the other PRs (view 10, stored alias is bare 0). The new head b7fda2daee0 includes the revert #123789, so this job will not run on it until #123790 merges.

…ote client, harden the framed test

The remote `clickhouse-client` formats the result itself, and there is no query in its process list,
so `writingThread` could not cancel anything there. A query that has already produced all of its
output then kept running after a broken pipe. Rethrow the background exception from `onProgress`,
which the client calls for every progress packet. Covered by a new case in
`05238_pretty_squash_broken_pipe`.

`wait_for_content` in `05061_pretty_squash_flush` returned success on timeout, so the framed part
could not fail if the `data` packet arrived only after the client was killed. Make the timeout
observable, as in the unframed part.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 6, 2026 19:43
…lient waits for packets

`ClientBase::onProgress` does not pass keep-alive progress updates to the
output format, so the previous `PrettyBlockOutputFormat::onProgress` override
depended on more row-count progress arriving after the write failure. Replace
it with a new non-blocking `IOutputFormat::checkBackgroundError` hook, which
`ClientBase::receiveResult` calls before every poll for packets (at least once
per poll interval, and after every packet), independently of what the server
sends.

The test now also requires the exit code of `CANNOT_WRITE_TO_FILE_DESCRIPTOR`
(75), so a stop for a wrong reason (e.g. `QUERY_WAS_CANCELLED`) fails it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…f the `Pretty` broken pipe test

With `--interactive_delay=3600000000` the server sends no progress packets after the first rendered
chunk, so the remote client has to notice the background write error while it polls the connection.
Without the `checkBackgroundError` call in `ClientBase::receiveResult` this case now times out
(verified locally), so the test locks down the poll-time check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Client/ClientBase.cpp Resolved
alexey-milovidov and others added 3 commits October 7, 2026 17:34
…ground write fails in the client

`checkBackgroundError` was called outside the `LocalFormatError` handling in
`ClientBase::receiveResult`, so the client exited on a broken output pipe without
sending `Cancel`, and the query kept running on the server. This is what the
"Some queries hung" failures of `05238_pretty_squash_broken_pipe` in the flaky checks were.
Handle the error like other local format errors: send `Cancel` and drain the packets.

The test now also checks that the query is gone from `system.processes`, and uses a
smaller `interactive_delay`, because the server checks for `Cancel` only that often.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117005&sha=cfddc2b1573bc97635d569e6a288d623fdc4f363&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29
#117005

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failures and provide fixes in separate PRs. If a fix is already in progress, link it here.

I merged master into this branch.

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

Both failures have open fixes of mine.

  1. AST fuzzer (amd_debug): Fix FunctionDynamicAdaptor exception when nested function returns Nothing type #115982. finalizeAggregation(initializeAggregation('minState', [])) is an Array(Nothing) value, so arrayElement over the Dynamic subcolumn returns Nothing for a variant. onlyNull() is false for bare Nothing, and the adaptor then fails at variant_name_to_discriminator.at("Nothing"). This is the arrayElement([], d) case from that PR's test. Measured:

    SELECT arrayElement(finalizeAggregation(initializeAggregation('minState', [])), json.a.a1)
    FROM (SELECT arrayJoin(['{"a":{"a1":1}}', '{"b":2}'])::JSON AS json)

    On master eef0f171 (debug) this aborts with the same FunctionDynamicAdaptor.cpp:339 frame. With Fix FunctionDynamicAdaptor exception when nested function returns Nothing type #115982 merged into master f40c8b00 it returns \N, \N. I merged master into Fix FunctionDynamicAdaptor exception when nested function returns Nothing type #115982 to refresh its CI, because the last run was from 2026-09-11.

  2. Integration tests (db disk): Fix server startup after an interrupted CREATE OR REPLACE on a plain_rewritable database disk #123832. The dictionary_node log shows the same mechanism as the other db disk hits. The kill landed inside the CREATE OR REPLACE of system.all_trace_log, after _tmp_replace_3add02ea8b608b69_*.sql was copied to all_trace_log.sql and before it was deleted. Every restart then fails with Code: 57 ... Mapping for table with UUID=526d4115-... already exists. Your Fix server startup after an interrupted CREATE OR REPLACE on a non-atomic database disk #123902 fixes the same failure in a different way, so only one of the two is needed. Fix server startup after an interrupted CREATE OR REPLACE on a plain_rewritable database disk #123832 is green and still waiting for a review.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks, @groeneai. Both failures are tracked by your open PRs (#115982 and #123832), so I'm not changing anything in this PR for them. CI on the current head (f22d1289e99) is fully green.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 9, 2026
Merged via the queue into master with commit 4fe89e9 Oct 9, 2026
301 of 302 checks passed
@alexey-milovidov
alexey-milovidov deleted the pretty-flush-squashed-chunk branch October 9, 2026 19:09
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 9, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 11, 2026
…pipe`

The first subtest fails in `Fast test (arm_darwin)` with exit code 241
(MEMORY_LIMIT_EXCEEDED) or the 60 s timeout. `numbers(1e18)` never leaves
the 50 ms squash gap, so the first squashed table holds everything read
before the background thread first writes (17.7M-19.3M rows on Linux), and
`output_format_pretty_max_rows=1e12` renders all of it before the first
byte reaches `head`. Its size depends on host throughput; on the macOS
runner it is not rendered within the timeout or exceeds the memory limit.

Cap reading at 1M rows/s (`timeout_before_checking_execution_speed=0`
because the throttle is otherwise off for the first 10 s): the source then
sleeps longer than the squash window after each block, so every table is
one block (65411 lines). The subtest still writes every block into the
broken pipe and must exit with 75; on 26.9.9.28 (without ClickHouse#117005) it
reports "did not stop" (124).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
qiuyanjun888 pushed a commit to qiuyanjun888/ClickHouse that referenced this pull request Oct 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). 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.

3 participants