Skip to content

Do not finalize the client output format into a canceled buffer - #126142

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-client-finalize-canceled-stdout
Nov 8, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-client-finalize-canceled-stdout

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125973
Related: #125558

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

Regression from #125558, reported in #125973: closing a web terminal while a FORMAT JSON result is streaming aborts a debug or sanitizer server with Logical error: 'Cannot write to canceled buffer' (ClientEmbeddedRunner::clientRoutine -> ClientBase::resetOutput -> IOutputFormat::finalize -> JSONUtils::writeArrayEnd). The same teardown aborts a debug client whose output sink fails: --pager head or INTO OUTFILE ... AND STDOUT piped into head with FORMAT JSON, and INTO OUTFILE '/dev/full' (JSON-family formats, or almost any format with COMPRESSION).

When the sink dies mid-result, the failed flush cancels the buffer at the bottom of the output chain, but resetOutput still finalized what is above it: the format, whose JSON suffix starts with WriteBuffer::write(char) (a logical error on a canceled buffer), and the INTO OUTFILE compression buffer, which stays uncanceled when only its nested file fails, because IOutputFormat::flushImpl flushes the nested buffer directly. #125558 let resetOutput continue past the failed progress-table clear, which exposed this on the web terminal path.

std_out_wrapper and the INTO OUTFILE file now set a flag from cancelImpl. Once it is set, resetOutput skips the format finalize and cancels out_file_buf instead of finalizing it. The flag is atomic because a parallel formatting collector or the Pretty squashing thread may still write until output_format.reset() joins them. The format writes into the same buffers as before, so successful output and its cost are unchanged.

05386 gains the reported scenario, 02871 a --pager head arm, 02346 a closed-stdout arm, and the new no-darwin 05461 (macOS has no /dev/full) /dev/full and compressed /dev/full arms; the last three check the exit code. Without the fix the first aborts a master debug server and the others the debug client; with it all pass 50 randomized runs. Official 26.8 and 26.9 builds report CANNOT_WRITE_TO_FILE_DESCRIPTOR on these paths, so no stable release shows a user-visible difference.


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

Version info

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

@groeneai

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

Final review: head 6165f22, four rounds. Gate B on the last delta: 0 findings.

Finding Verdict
❌ INTO OUTFILE ... AND STDOUT FORMAT JSON | head still finalized into the canceled ForkWriteBuffer (its stdout leg is not std_out_wrapper) AGREE, fixed: the INTO OUTFILE file reports its cancellation too
❌ A wrapper between the format and the INTO OUTFILE buffer hid WriteBufferFromFile from FORMAT SQLite (direct file mode lost) and copied every byte (+13% on RowBinary export) AGREE, fixed: the format writes into the same buffers as on master
❌ With COMPRESSION, a failing INTO OUTFILE file is canceled while the codec above it is not, and the teardown finalized that codec into the canceled file (debug client abort) AGREE, fixed: the teardown cancels out_file_buf once the flag is set
⚠️ The new 02346 arms grep stderr only, so an abort without a Logical error line passes AGREE, fixed: the arms check the client exit code; a compressed /dev/full arm was added
⚠️ system.errors last_error_message is last-writer-wins, so the 05386 oracle could miss an occurrence DISAGREE: CI runs with abort_on_logical_error, so the regression aborts the server first; the counter line is a secondary check
💡 The 05386 system.errors line is redundant in CI for the same reason Noted, not blocking

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a debug build, clickhouse local --pager head -q "SELECT number FROM numbers(1e6) SETTINGS output_format_parallel_formatting = 0 FORMAT JSON" aborts on every run. So do INTO OUTFILE ... AND STDOUT FORMAT JSON piped into head, INTO OUTFILE '/dev/full' FORMAT JSON and INTO OUTFILE '/dev/full' COMPRESSION 'gzip' FORMAT TSV. The new 05386 JSON scenario aborts a master debug server 3/3.
b Root cause explained? Yes. The failed flush cancels the bottom buffer of the output chain (std_out_wrapper, or the INTO OUTFILE file). resetOutput then still finalized what sits above it. The format's JSON suffix starts with WriteBuffer::write(char), which is a LOGICAL_ERROR on a canceled buffer. The compression buffer stays uncanceled because IOutputFormat::flushImpl flushes its nested file directly, so its trailer went into the canceled file. #125558 made the web terminal path reach this.
c Fix matches root cause? Yes. Once a bottom buffer is canceled, nothing above it is finalized: the format finalize is skipped and out_file_buf is canceled. The write(char) invariant check is untouched.
d Test intent preserved / new tests added? Yes. 05386 keeps its scenario and gains the reported JSON scenario. 02871 gains a --pager head + FORMAT JSON arm. 02346 gains closed-stdout, /dev/full and compressed /dev/full arms that check the client exit code.
e Both directions demonstrated? Yes. Base: server abort 3/3 (05386), and client abort (02871, all three 02346 arms, exit 134). Fix: all pass, 150/150 randomized runs.
f Fix is general across code paths? Yes. Every resetOutput caller (web terminal, SSH sessions, clickhouse-client, clickhouse-local) goes through it. The 9-sink matrix (fork + head, /dev/full, compressed, parallel formatting) gives rc 75 on all 9 sinks. 100 neighbour tests pass (pager, web terminal, INTO OUTFILE, SQLite), apart from one that needs psql.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. /dev/full x {TSV, RowBinary, CSV, JSONEachRow, JSON, XML} x {gzip, zstd}: rc 75 on 12/12 (base: 10/12 abort, pre-existing). The JSON family through stdout and pager also passes, as does parallel formatting 0/1. Successful outputs are hash-identical to base, and FORMAT SQLite direct mode is unchanged.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. Delivered output is byte-identical, and the cancel happens only after the sink is gone and an error is already propagating.
i Invariants and contracts preserved? Yes. output_format.reset() still joins background writers. The flag is atomic because background formatting threads may still write until then, and cancellation is monotonic. Canceling the chain never drops deliverable output, because the flag means its bottom is already dead.

Session id: cron:clickhouse-impl-slot-5:20261015-215600

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3d3d937]

Summary: ✅


AI Review

Summary

PR #126142 prevents ClientBase::resetOutput from finalizing output formats and compression buffers after their sink is canceled. No actionable findings in commit 3d3d937899707c880fc11500bdcfaadad0315fb2. All four affected stateless tests pass in the current head's Fast test report; the full CI workflow is still running.

Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat, could you review this and add can be tested? It fixes the #125973 regression from #125558: once a failed write cancels the bottom output buffer, resetOutput no longer finalizes the format or the INTO OUTFILE codec into it.

@clickhouse-gh clickhouse-gh Bot added the comp-cli clickhouse-client (interactive CLI) and client library. label Oct 15, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6165f22

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
Performance Comparison (arm_release, master_head, 1/6, 2/6, 4/6, 5/6) job timeout (7200 s), not from this PR: one of the shard's two Check CI Log cluster probes (setup_log_cluster.sh) blocked about 3645 s on the overloaded CI Logs cluster before any perf query ran, so the job was killed mid-run with no verdicts. Same on dozens of PRs and master between 01:40Z and 05:30Z #126217 (mine, open)
Stateless tests (amd_tsan, flaky check) / ThreadSanitizer: data race (STID: 3090-367c) pre-existing race, not from this PR's change: two concurrent embedded client sessions both write replxx's process-wide terminal state in replxx::read_unicode_character (contrib/replxx/src/terminal.cxx:324, reached from ClientEmbedded::run -> ReplxxLineReader::readOneLine); the new web terminal test runs concurrent sessions, and the same STID also fails on master (Stateless amd_tsan) and in Stress (amd_tsan, arm_tsan) on other PRs #125510 (external, open)
Mergeable Check, PR praktika rollups of the rows above #126217 and #125510 (the owners of the rows above)

Session id: cron:our-pr-ci-monitor:20261016-070011

When the stdout of a client dies mid-result (a web terminal session is
closed, or a `--pager` exits), the first failed flush cancels
`std_out_wrapper`. `ClientBase::resetOutput` then still called
`output_format->finalize()`, and formats whose suffix starts with
`WriteBuffer::write(char)` (JSON, JSONCompact, JSONStrings,
JSONObjectEachRow, ...) hit the `LOGICAL_ERROR` "Cannot write to canceled
buffer" check. Debug and sanitizer builds abort: the whole server for the
web terminal (reachable since ClickHouse#125558 let `resetOutput` continue past the
failed progress-table clear), the client itself for `--pager head`.

The two buffers at the bottom of the client output chain, `std_out_wrapper`
and the `INTO OUTFILE` file, now set one `ClientBase` flag from
`cancelImpl`, and `resetOutput` skips the format finalize once it is set.
The teardown also cancels `out_file_buf` instead of finalizing it once the
flag is set: `IOutputFormat::flushImpl` flushes a compression buffer's
nested buffer directly, so a failing `INTO OUTFILE` file is canceled while
the codec above it is not, and finalizing that codec wrote its trailer into
the canceled file (an abort for `INTO OUTFILE '/dev/full' COMPRESSION ...`
with most formats, already on master). The plain `WriteBuffer::canceled`
flag cannot be read there, because a parallel formatting collector or the
Pretty squashing thread may still be writing until `output_format.reset()`
joins them.

No buffer is added between the format and its sink, so successful output
and its cost are unchanged, and `FORMAT SQLite` still writes the
`INTO OUTFILE` file directly.

Tests: 05386 gains the reported `FORMAT JSON` web terminal scenario plus a
`system.errors` oracle; 02871 gains a `--pager head` + `FORMAT JSON` arm;
02346 gains `INTO OUTFILE ... AND STDOUT` with a closed stdout,
`INTO OUTFILE '/dev/full'` and compressed `INTO OUTFILE '/dev/full'` arms
that check the client exit code.

Closes ClickHouse#125973

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@azat azat self-assigned this Oct 23, 2026
@azat
azat force-pushed the fix-client-finalize-canceled-stdout branch from 6165f22 to ed72572 Compare October 23, 2026 15:27

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

I actually don't like this fix, what we do is workaround our own internal checks, and there are lots of other places as well.

Here we already know that we are writing to partial valid buffer, and we can use this, i.e. have WriteBuffer::tryFinalize (that will not throw LOGICAL_ERROR)/IOutputFormat::tryFinalize.

So we need to have try* variants, otherwise we will have more and more places like this.

But we can merge this as-is and work on the refactoring on top. I will take care.

Since ClickHouse#126638 the client stops quietly with exit code 0 when the reader
of its own stdout goes away, also for the stdout leg of
`INTO OUTFILE ... AND STDOUT`, so the `closed_stdout` arm no longer sees
exit code 75 and `CANNOT_WRITE_TO_FILE_DESCRIPTOR`. The arm still
catches the regression: without the fix the debug client aborts in
`ClientBase::resetOutput` -> `IOutputFormat::finalize` ->
`JSONUtils::writeArrayEnd`.

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

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3d3d93789 with master 5b24a5f36 (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.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.95 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -7.3 s (-5%) in total before that adjustment.

Job report

macOS has no /dev/full, so on Fast test (arm_darwin) `INTO OUTFILE '/dev/full'`
fails to open the file (CANNOT_OPEN_FILE, exit 76) instead of failing to write
to it. The full_file and full_file_gzip arms move unchanged to
05461_into_outfile_full_file, tagged no-darwin; the closed_stdout arm stays
in 02346 and keeps running on macOS.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4c91c4c

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 not from this PR (its diff changes only the client output teardown and its own tests): the test calls flock(1), which macOS does not have, so the expected "Another server instance in same directory is already running" line is missing; it fails the same way on 40+ other PRs #128088 (mine, open)
Mergeable Check, PR praktika rollups of the row above #128088 (the owner of the row above)

02346_into_outfile_and_stdout and the new 05461_into_outfile_full_file pass on this head. Fast test on Linux and all five flaky check jobs are green, and so is CH Inc sync. CIDB has no other FAIL or ERROR row on this head.

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

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

Ok. Somewhat weird. At one hand, we are duplicating the is_cancelled flag, while we can put it into the base class. At the other hand, having atomic flag in the base class could be unjustified.

@alexey-milovidov alexey-milovidov self-assigned this Nov 7, 2026
@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Nov 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 8, 2026
Merged via the queue into ClickHouse:master with commit acc143f Nov 8, 2026
187 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-cli clickhouse-client (interactive CLI) and client library. 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.

resetOutput finalizes JSON over a canceled buffer: LOGICAL_ERROR

4 participants