Skip to content

Prevent flickering on certain formats - #93298

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
colesmith54:fix/85733
May 30, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
colesmith54:fix/85733

Conversation

@colesmith54

@colesmith54 colesmith54 commented Jan 1, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Formats such as Hash and Pretty had flickering of the progress bar because the progress was cleared despite no actual output for a block. Added a callback to clear progress just before flush. Closes #85733.

Version info

  • Merged into: 26.6.1.250

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jan 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jan 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [44f5e52]

Summary: ✅


AI Review

Summary

This PR moves progress clearing from onData into a flush callback wrapper to reduce progress flickering for buffered formats. The latest head fixes the earlier wrapper flush/cancel propagation issues, but one new correctness regression remains in the wrapper error path.

Findings

❌ Blockers

  • [src/Client/ClientBase.cpp:389] FlushCallbackWriteBuffer::nextImpl silently returns when nested out is already canceled. This can hide write failures and drop result data without surfacing an exception: if std_out was canceled by a prior write error (for example EPIPE), later queries can appear successful while producing no output.
  • Suggested fix: do not swallow this state. Remove the early return and let out->write raise CANNOT_WRITE_AFTER_BUFFER_CANCELED, or throw explicitly when out->isCanceled().
Final Verdict

Status: ❌ Block
Minimum required action: preserve failure semantics for canceled nested output buffers in FlushCallbackWriteBuffer::nextImpl so output loss cannot be silent.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jan 1, 2026
Comment thread src/Client/ClientBase.cpp Resolved
Comment thread src/Client/ClientBase.cpp Resolved

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

.

@alexey-milovidov

Copy link
Copy Markdown
Member

This can be tested on a query that outputs blocks once in a while:

SELECT number FROM numbers(1e12) WHERE rand() % 1000000000 = 1

has_input = false;
}

void IOutputFormat::flushImpl()

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.

The problem is that this function is to trigger an explicit flush, which the output buffer can flush any time on its own.

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.

Plus, changing the interface of IOutputFormat is too much for this purpose.

I think we need to wrap the WriteBuffer, maybe we already have some neat wrapper for this purpose (hold data in memory until explicitly asked to push it further).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Couldn't find one with that exact purpose so I just wrote one within ClientBase that uses the callback idea

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.

Yes, looks like a good solution.

@colesmith54
colesmith54 force-pushed the fix/85733 branch 2 times, most recently from 5bc8955 to 9be41e9 Compare January 2, 2026 18:08
@colesmith54
colesmith54 marked this pull request as draft January 2, 2026 18:20
@colesmith54
colesmith54 force-pushed the fix/85733 branch 2 times, most recently from 708fc08 to e5c9031 Compare January 2, 2026 18:34
nit: style

nit: style

fix finalize

nit: whitespace

fix
@clickhouse-gh

clickhouse-gh Bot commented Mar 24, 2026

Copy link
Copy Markdown
Contributor

Dear @colesmith54, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

alexey-milovidov and others added 2 commits May 16, 2026 00:13
The progress-flicker fix wrapped `std_out` in a `FlushCallbackWriteBuffer`
that runs a callback (to clear the progress bar) right before each flush.
However, the cleanup in `ClientBase::resetOutput` finalized and destroyed
the wrapper before finalizing `out_file_buf`. Since `out_file_buf` is
constructed from a raw pointer to the wrapper, this left `out_file_buf`
pointing at freed memory — the gzip footer was written into the dangling
wrapper and never reached `std_out`. That caused
`03144_compress_stdout` to fail with "unexpected end of file".

Reorder the cleanup so `out_file_buf` is finalized before the wrapper,
and skip `finalize` when the buffer was already canceled (otherwise the
SIGPIPE path in `02871_clickhouse_client_restart_pager` throws "Cannot
finalize buffer after cancellation").

Also cancel and reset `std_out_wrapper` in the catch block of
`initOutputFormat`. Without this, a failure to construct the output
format (e.g. conflicting Template settings in
`00937_format_schema_rows_template`) left the wrapper in place. The
next `onData`/`onTotals` call would re-enter `initOutputFormat`,
reassign `std_out_wrapper`, and trigger the
"WriteBuffer is neither finalized nor canceled" assertion when the
old wrapper was destroyed.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Client/ClientBase.cpp Resolved
Comment thread src/Client/ClientBase.cpp Resolved
Address two issues in `FlushCallbackWriteBuffer` introduced in this PR:

* `nextImpl` forwarded data to the nested buffer via `out->write(...)` but
  never propagated the explicit flush via `out->next()`. As a result, small
  result blocks were buffered inside the nested buffer (e.g. `std_out`) until
  it filled up, breaking streaming of rows to the pager. This regressed the
  `03701_pager_proper_termination` test, which expects the first row to
  appear in `less` immediately.
* `WriteBufferDecorator::cancelImpl` propagates cancellation to the nested
  buffer. Since the nested buffer here can be the persistent `std_out`, an
  exception during format setup (the `catch (...)` block in
  `initOutputFormat`) would permanently cancel `stdout` for the rest of the
  client session, causing subsequent writes to fail with
  `CANNOT_WRITE_AFTER_BUFFER_CANCELED`.

Override `cancelImpl` to a no-op so the nested buffer (a borrowed reference)
is left untouched, and call `out->next()` after writing in `nextImpl` to
propagate flushes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Client/ClientBase.cpp
if (on_flush_callback)
on_flush_callback();

if (out->isCanceled())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nextImpl silently returns when the nested buffer is already canceled. That changes failure semantics: if std_out was canceled by a previous write exception (for example EPIPE), later queries will appear to succeed but drop all output bytes.

Please propagate this state as an exception (for example by removing this guard and letting out->write fail with CANNOT_WRITE_AFTER_BUFFER_CANCELED, or by throwing explicitly here).

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.

The guard is intentional and complements the cancelImpl override on the same wrapper. Because out here is the shared persistent std_out (AutoCanceledWriteBuffer<WriteBufferFromFileDescriptor>), the wrapper deliberately does not propagate its own cancellation to out — that was the bug fixed in 44f5e52, where an exception during format setup permanently broke stdout for the rest of the client session.

In practice out->isCanceled() should never be true here: AutoCanceledWriteBuffer only auto-cancels in its destructor (not on EPIPE), WriteBufferFromFileDescriptor::nextImpl throws but does not cancel itself, and the wrapper no longer cancels out. Removing the guard would not change observable behavior in any reachable path; the guard is a defensive check against shared-buffer cancellation that — if it ever fires — points at a logic error elsewhere. Switching it to throw would surface that, but the current scope of the PR is restoring streaming behavior, not redesigning ownership of std_out.

@clickhouse-gh

clickhouse-gh Bot commented May 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.20% +0.10%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.70% +0.20%

Changed lines: 93.33% (56/60) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

The latest idea is great! I was thinking about exactly this.

@alexey-milovidov
alexey-milovidov marked this pull request as ready for review May 17, 2026 20:47

@alexey-milovidov alexey-milovidov 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

@alexey-milovidov

Copy link
Copy Markdown
Member

Works perfectly.

@alexey-milovidov
alexey-milovidov merged commit 5f06cad into ClickHouse:master May 30, 2026
166 of 167 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 30, 2026
shevlfs added a commit to shevlfs/ClickHouse that referenced this pull request Aug 30, 2026
Follow-up to the previous commit for issue ClickHouse#80056. Skipping the clearing
of the progress bar before flushing a data block is only valid when the
progress is rendered on a real terminal while the data goes elsewhere.
With `--progress err ... 2>&1 | viewer` the progress goes into the same
pipe as the data even though stdout is not a terminal, and without the
clearing the first row of every flushed block is appended to a stale
progress-bar line: 19 garbled lines per 200000 rows (20 blocks) in a
harness, versus 0 on master. Extend the condition: skip the clearing
only when the progress target is a real terminal (`isatty` on the
`tty_buf` descriptor); `initTTYBuffer` runs at startup, so the
descriptor is available when the output format is initialized.

Why ClickHouse#93298 alone did not fix issue ClickHouse#80056: it moved the clearing into
the pre-flush callback of `std_out_wrapper`, so formats that buffer the
whole result stopped flickering (`Hash` and `Pretty`: 1 erase sequence
per query on master), but formats that flush every block (the streaming
formats with `setAutoFlush`) still cleared the bar once per block: 30
erase sequences for a 30-block `TSV` query on master, and 459 erase
sequences for 471 progress redraws in a 0.66 s run of
`SELECT * FROM system.numbers LIMIT 30000000` with stdout piped to
/dev/null. With this fix the same runs show 1 erase sequence (the final
cleanup) and a stable bar, while the merged-stream case above, the
terminal case (stdout on the terminal), and the pager case keep one
clear per flushed block exactly as master does.

Also align with the file style (`pager_cmd` instead of
`pager_cmd != nullptr`) and improve the test: trap-based cleanup of the
generated helper, a 60 s read timeout instead of 300 s, and a third
deterministic case pinning the merged-stream `--progress err 2>&1`
behavior (the assertions count erase sequences per flushed block, so
they do not depend on timing).

Related: ClickHouse#80056
Related: ClickHouse#93298
Related: ClickHouse#98993
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 28, 2026
…troyed its buffer

`ClientBase::initOutputFormat` creates `output_format` over `std_out_wrapper`
(or `out_file_buf`), and the format keeps a reference to that buffer. For a
binary format on a terminal it then asks whether to output it anyway. In the
web terminal, closing the session closes the PTY, the read of the answer fails
with EIO, and the `catch` destroyed `out_file_buf` and `std_out_wrapper` while
keeping `output_format`. `receiveResult` continues after the `LocalFormatError`,
and `resetOutput` then finalized the format into the freed buffer: a heap
use-after-free (ASan), use-of-uninitialized-value (MSan) and SIGSEGV (debug)
in Stress tests since they run queries over the web terminal (ClickHouse#125517).

Destroy the format first in that `catch`, before the buffers it writes into
(the same order as `resetOutput`). A failure after the format was created now
leaves the same state as a failure before it (ClickHouse#93298), and the next result
packet creates the format again.

The new test opens a web terminal session, runs a `RowBinary` query, waits for
the question and closes the connection; the server must stay alive.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-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.

Using format Hash results in progress bar flickering

3 participants