Skip to content

Do not read the client's stdin again after a read from it failed - #128090

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-client-ask-canceled-input
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-client-ask-canceled-input

Conversation

@groeneai

@groeneai groeneai commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

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

The client no longer reads its stdin again after a read from it failed: it does not ask the binary-format question again after the terminal on stdin was closed, and the next queries get NO_DATA_TO_INSERT instead of reading INSERT data from it.

Description

Related: #127912

Since #127912 (master only, not in any release), closing the terminal on the client's stdin while it asks "Do you want to output it anyway? [y/N]" for a binary output format leads to LOGICAL_ERROR ReadBuffer is canceled. Can't read from it., an abort in debug and sanitizer builds. In the web terminal the server aborts: STID 2508-2bbd, master CI.

Root cause: the failed read (EIO) cancels std_in. #127912 resets output_format when initOutputFormat fails, and receiveResult keeps processing Data packets after the LocalFormatError, so the next block creates the format again, asks the question again and reads the canceled buffer.

The other readers of std_in do the same: isStdinNotEmptyAndValid (the check for INSERT data on stdin, false when the read fails) on its next call, e.g. clickhouse-local --async_insert 1 with two INSERT ... VALUES and stdin open for writing only, and with --ignore-error a later INSERT reading its data from stdin (sendDataFromStdin, and the input() initializer of LocalConnection).

Change: on a canceled input, ask returns the default answer ("N") without asking, isStdinNotEmptyAndValid returns false, and the two INSERT readers throw NO_DATA_TO_INSERT.

Validation: the new test 05464_client_binary_format_question_after_stdin_closed runs the client with stdin and stdout on two terminals and closes the stdin one at the question. Without the fix the question is printed twice and the client aborts (10/10); with the fix it is printed once, no result is printed, and the client exits with the read error, code 74 (50/50 with randomized settings and -j 8). Removing the check, or answering y, makes it fail. The test also runs an INSERT from that terminal after the failed read, in the client and in clickhouse-local; removing either INSERT check makes it fail. 05465_client_unreadable_stdin_checked_twice aborts on master (10/10) and passes with the fix (50/50). The existing terminal and web terminal tests pass.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 28, 2026 20:40
…failed

`ReadBuffer::next` cancels the buffer when the read fails, and a canceled buffer
cannot be read again. When the terminal on stdin is closed while the client asks
whether to output a binary format, reading the answer fails with EIO. Since ClickHouse#127912
the output format is created again for the next block of the result, which asks
the question again and reads the canceled `std_in`: `LOGICAL_ERROR` "ReadBuffer is
canceled" in debug and sanitizer builds (STID 2508-2bbd, the web terminal on
master).

`ask` now returns the default answer without asking when its input is canceled.

The new test runs the client with stdin and stdout on two separate terminals and
closes the one on stdin at the question. A client that starts reading only after
the terminal is gone reads EOF instead of failing and exits with 0; that run does
not reach the failed read, so the test repeats it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The canceled input gives the default answer "N", so the result must not be
printed. Without this check, the test would also pass if the canceled input
were answered with "y".

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)
Finding Verdict
⚠️ The test checked that the question is not asked again and the exit code, but not that the canceled input gets the default answer N: answering y would have passed too. AGREE, fixed: the test now also checks that no result is printed.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test on an unfixed debug client aborts 10/10 with ReadBuffer is canceled. Can't read from it. at ask (Ask.cpp:17) <- initOutputFormat (ClientBase.cpp:1271), the same frames as the master CI stack.
b Root cause explained? The EIO read of the answer cancels std_in. #127912 resets output_format when initOutputFormat fails, receiveResult keeps processing Data packets after the LocalFormatError, so the next block asks the question again and reads the canceled buffer.
c Fix matches root cause? Yes. ask is the only reader of the terminal for answers; it now returns the default answer without asking when its input is canceled. Same consumer-side isCanceled() check as merged #121916, #109708, #111056.
d Test intent preserved / new tests added? New test 05464_client_binary_format_question_after_stdin_closed (stdin and stdout on two terminals, stdin one closed at the question). No existing test changed.
e Both directions demonstrated? Without the fix: question printed twice and abort, 10/10. With the fix: printed once, no result printed, exit code 74, 100/100 with randomized settings (also -j 8). Neutralizing the check: 5/5 fail again; answering y instead of the default: the binary result appears, 5/5 fail.
f Fix is general across code paths? Both ask(ReadBuffer &, WriteBuffer &) callers (binary-format question, AI provider acknowledgment) and every route into the question (receiveResult, the INSERT ... RETURNING drain, logs/profile events) go through the one check; all clients (TCP, local, web terminal, SSH) share ClientBase.
g Fix generalizes across inputs (params/datatypes/wrappers)? Format independent: the check runs before any format handling. A non-canceled input takes the unchanged path (03293_tty_binary_confirmation: y / n / empty answers, 20/20).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, protocol or format change; behavior differs only when the input is already canceled.
i Invariants and contracts preserved? ask still returns false when no answer can be read, as for EOF. On false, initOutputFormat installs NullOutputFormat and the AI path declines the request. The first error (code 74) is still reported.

Session id: cron:clickhouse-impl-slot-6:20261028-205800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @Avogar, could you review this and add the can be tested label so CI runs? Since #127912 resets the output format after a failed initialization, the next Data packet asks the binary-format question again and reads the stdin buffer that the failed read of the first answer canceled (LOGICAL_ERROR, which aborts the server in the web terminal); ask now returns the default answer when its input is already canceled.

@clickhouse-gh

clickhouse-gh Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3bc9335]

Summary: ✅


AI Review

Summary

This PR prevents reads from canceled client input in ask, stdin availability checks, and the native and local INSERT readers. Review of the current diff, surrounding error handling, and prior discussion found no actionable issues. Both new regression tests pass in Fast test at the reviewed head.

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 Oct 28, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 28, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-cli clickhouse-client (interactive CLI) and client library. label Oct 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3bc93356e with master c759533a1 (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

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

Job report

…macOS

The test needs reading the answer from the closed terminal on stdin to fail.
On macOS such a read returns EOF instead (xnu `ptsread` reads nothing once the
master side is closed), and the client was killed by SIGHUP: `Fast test
(arm_darwin)` got exit code -1 instead of 74.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ed4b314

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 src/IO/Ask.cpp and 05464): the test, added by #116042, calls flock(1), which macOS does not have (77 PRs in 14 days) #128088 (mine, open)
Mergeable Check, PR praktika rollups of the row above #128088 (the owner of the row above)

The 05464 failure on Fast test (arm_darwin) at the previous head 94e4c49 is fixed in this PR @ ed4b314: the test is now skipped on macOS, and it passed 50 of 50 runs in each flaky check. CH Inc sync is green.

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

Comment thread src/IO/Ask.cpp
bool ask(std::string question, ReadBuffer & in, WriteBuffer & out)
{
/// A failed read cancels `in`, and nothing can be read from it after that: assume the default answer.
if (in.isCanceled())

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.

@groeneai I see a while (true) right after this. Are you sure the check is only needed 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.

Check if this is needed elsewhere

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The loop is fine: ReadBuffer::next cancels the buffer when the read throws and rethrows it, so a failed read leaves ask with that exception, and EOF gives an empty answer, i.e. "N". The std::cin overload already returns false when !std::cin.good().

It was needed in the other readers of std_in, fixed in fb32def and 3bc9335:

  • isStdinNotEmptyAndValid returns false when reading stdin fails, and its next call read the canceled buffer: clickhouse-local --async_insert 1 -q "...; INSERT INTO t VALUES (1); INSERT INTO t VALUES (2)" 0>/dev/null aborts on master. Now it returns false without reading.
  • With --ignore-error, after the failed read of the answer, an INSERT reading its data from that terminal read it again: sendDataFromStdin in the client, and the input() initializer of LocalConnection in clickhouse-local. Both throw NO_DATA_TO_INSERT now.

Tests: 05465_client_unreadable_stdin_checked_twice (master 10/10 abort, fix 50/50 OK), and a second part of 05464 for the INSERT readers (removing either check fails it).

@PedroTadim

Copy link
Copy Markdown
Member

cc @Avogar @alexey-milovidov

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai 🕵️

Thanks, the fix and the test look right. An input that can't be read anymore should get the default answer.

The cause sits one level up, though. After a LocalFormatError, receiveResult sends Cancel but keeps handing the remaining Data packets to onData. Since #127912 resets output_format after a failed initOutputFormat, every one of those blocks builds the output format again. Asking the question again is one symptom; other failures in initOutputFormat repeat the same way:

  • the INTO OUTFILE file is opened again for every block;
  • with a failure that goes away, later blocks get written after an earlier one was lost, so the output has a gap (the client still exits with the first error);
  • with this PR, the rest of the result is formatted into NullOutputFormat just to drain it.

Once a local format error has cancelled the query, the client only needs to drain the remaining packets. For example, onData could return early when a flag is set where receiveResult records local_format_error. That would also have prevented this abort. I'm fine with keeping the guard in ask and doing that as a follow-up, but could you open one?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'll open the follow-up PR that makes the client only drain the remaining packets after a local format error, and post its link here.

`isStdinNotEmptyAndValid` returns false when reading stdin fails with
`CANNOT_READ_FROM_FILE_DESCRIPTOR`, and that failed read cancels `std_in`.
The next check in the same run (another INSERT) read the canceled buffer,
which aborts debug and sanitizer builds with "ReadBuffer is canceled.
Can't read from it.". Same defect as in `ask`, in the other reader of
`std_in`. Reproduced with `clickhouse-local --async_insert 1` running two
`INSERT ... VALUES` with stdin open for writing only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Do not read the client's input again after reading an answer from it failed Do not read the client's stdin again after a read from it failed Oct 30, 2026
…ailed

After reading the answer to the binary-format question failed (the
terminal on stdin was closed), `--ignore-error` runs the next queries,
and an INSERT that reads its data from stdin read the canceled `std_in`:
`sendDataFromStdin` in the client, and the `input()` initializer of
`LocalConnection` in `clickhouse-local`. Both now fail with
`NO_DATA_TO_INSERT` instead, like an INSERT without data on stdin.

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

Copy link
Copy Markdown
Collaborator Author

The follow-up is open: #128238 (after a local format error the client only drains the rest of the result).

huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 1, 2026
…lient

After a `LocalFormatError` (the client failed to create or write its output
format), `receiveResult` sends `Cancel` but kept passing every remaining
`Data` / `Totals` / `Extremes` packet to `onData` / `onTotals` /
`onExtremes`. When the error came from `initOutputFormat`, `output_format`
is null afterwards, so every remaining block built the output again: the
pager was started again, the `INTO OUTFILE` file was opened again, and a
failure that went away mid-result left an output with a gap while the client
still exited with the first error. Since ClickHouse#127912 the binary-format question
is asked again too, reading the stdin the first failed answer canceled
(`LOGICAL_ERROR 'ReadBuffer is canceled'`, STID 2508-2bbd on master).

A per-query flag is set where a `LocalFormatError` is created (the three
sites: `initOutputFormat`, the write in `onData`, the background error check
in `receiveResult`), checked at the top of the three result callbacks, and
reset in `processParsedSingleQuery`. Setting it at the origins instead of in
`receiveResult` also covers the `INSERT ... RETURNING` drain
(`receiveEndOfQueryForInsert` calls the callbacks directly). `cancelled` is
not reused: it would disable the receive timeout and Ctrl+C handling in the
drain loop, skip waiting for the pager and print "Query was cancelled.".

Requested by @PedroTadim in
ClickHouse#128090 (comment)

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

This branch has not been deployed

No deployments
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-cli clickhouse-client (interactive CLI) and client library. pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants