Skip to content

Fix hang in --queries-file / -q when stdin is a pipe with no data - #96494

Merged
alexey-milovidov merged 110 commits into
masterfrom
fix-stdin-hang-insert-queries-file
Nov 22, 2026
Merged

alexey-milovidov merged 110 commits into
masterfrom
fix-stdin-hang-insert-queries-file

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Feb 9, 2026 •

Copy link
Copy Markdown
Member

ClientBase eagerly called isStdinNotEmptyAndValid to check for trailing stdin data on every INSERT. That helper calls !std_in.eof(), which performs a blocking read(0, ...). When stdin is a pipe that is open but has no data and no EOF (common in CI, Docker, stress tests, and --queries-file invocations), the read blocks indefinitely and the client hangs until it is killed by timeout.

Concretely, this caused an exception (signal 11 after timeout) in the stress test 03538_analyzer_scalar_correlated_subquery_fix: the process hung on read(0, ...) and was killed.

The fix replaces the eager blocking probe with a non-blocking one: poll(timeout=0) first asks "does stdin appear to have data right now?", and only when it does we fall through to isStdinNotEmptyAndValid to confirm and consume it. This:

  • avoids the hang on open empty pipes — poll returns 0 immediately;
  • preserves deterministic rejection of inlined data + stdin mixed input — when stdin actually contains data (the case asserted by 04064_inline_insert_data), poll returns POLLIN and we still throw NOT_IMPLEMENTED;
  • is best-effort by design: a slow producer pipe (e.g. (sleep 1; echo) | clickhouse-client ...) may not have written by the time poll runs, in which case the trailing stdin payload is ignored. This is preferable to the alternative of a hard hang, and is documented in the helper.

Covered cases (is_async_insert_with_inlined_data, is_inline_insert_data, and the appending-stdin path in sendData) all go through the same probe so the hang is closed for --queries-file, -q, and --inline-insert-data modes.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=b9e68f4b9b0b33c7db43b00afb3eff4ff2050694&name_0=MasterCI&name_1=Stress%20test%20%28amd_debug%29

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

Fixed a hang in clickhouse-client for INSERT queries in --queries-file/-q/--inline-insert-data mode when stdin is an open pipe with no data and no EOF (common in CI, Docker, and stress tests).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Version info

  • Merged into: 26.12.1.161-master (included in 26.12 and later)

`ClientBase::sendData` eagerly called `isStdinNotEmptyAndValid` to check
if stdin had additional data for INSERT queries. This function calls
`!std_in.eof()` which performs a blocking `read()` on stdin. When stdin
is a pipe that has no data and hasn't been closed (common in CI, Docker,
subprocess environments), the read blocks indefinitely.

This caused the stress test crash (signal 11) for test
`03538_analyzer_scalar_correlated_subquery_fix` because the process
hung on `read(0, ...)`, then was killed by timeout.

The fix:
- Make the stdin check lazy (lambda) so it's only evaluated when needed
- Skip the stdin check entirely when INSERT has inline data — inline
  data terminated by semicolon is already complete
- Remove blocking stdin check in async insert path too

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=b9e68f4b9b0b33c7db43b00afb3eff4ff2050694&name_0=MasterCI&name_1=Stress%20test%20%28amd_debug%29

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

clickhouse-gh Bot commented Feb 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a268c52]

Summary: ✅


AI Review

Summary

PR #96494, head a268c52a54a92e8344212295c8ac173d14bb5c1b, avoids blocking on unused, open stdin when an INSERT already contains inline data. Two previously discussed concerns remain: delayed stdin can be omitted from supported legacy inserts, and can bypass the inline/async mixed-input rejection. Both were dismissed by the author; no new inline findings were identified.

Findings

❌ Blockers

  • src/Client/ClientBase.cpp:2790 — Supported inline-query + stdin inserts can silently lose rows. [dismissed by author -- https://github.com/Fix hang in --queries-file / -q when stdin is a pipe with no data #96494#discussion_r3185484391]

    With async_insert=0 and send_table_structure_on_insert_with_inline_data=1, INSERT INTO t FORMAT Values (24) supports appending (42) from stdin, as exercised by 02270_stdin_with_query_or_infile_data.sh. If the producer has not written when the zero-time probe runs, StdinState::Ambiguous becomes have_data_in_stdin=false. sendDataFrom then sends the terminating empty block at line 3044, and line 2914 skips stdin. The insert can succeed with only (24); later bytes are dropped or remain available to a subsequent insert in the same client session. The author's explanation correctly identifies the indistinguishability of unused stdin and a delayed writer, but does not preserve this supported append behavior. Make stdin participation an explicit source policy, retaining a way to request the previous append semantics while allowing unused inherited stdin to be ignored. FROM INFILE is excluded from this finding: current master deliberately ignores stdin for that source.

  • src/Client/ClientBase.cpp:3338 and line 3352 — Inline/async mixed-input rejection depends on producer timing. [dismissed by author -- https://github.com/Fix hang in --queries-file / -q when stdin is a pipe with no data #96494#discussion_r3182365728]

    When stdin already contains bytes, these branches reject inline data plus stdin with NOT_IMPLEMENTED. With the same payload produced after the probe, StdinState::Ambiguous bypasses that rejection and the query succeeds using only inline data. The external payload is never consumed by that insert. The intentional empty-pipe tradeoff explains the mechanism, but the same mixed input still changes from an explicit error to successful omission based on scheduling. Define source selection explicitly so inline/async modes consistently reject or deliberately ignore external input according to that policy, rather than inferring participation from instantaneous readiness. A finite polling delay would only move the race window.

Tests
  • ⚠️ Add a focused delayed-writer regression for the selected source policy: cover legacy inline-query + stdin with async_insert=0, and the inline/async guards. Synchronize the producer so it writes after source selection, then assert the expected rows or explicit error. Existing empty-FIFO success cases and already-readable socket rejection cases do not cover this boundary.
Final Verdict

Status: ❌ Block. Define an explicit stdin-source policy that preserves a way to consume supported delayed stdin without making complete inline inserts hang, apply it consistently to the inline/async guards, and add the focused regression coverage above. The dismissed threads remain closed.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Feb 9, 2026
@alexey-milovidov
alexey-milovidov marked this pull request as draft February 10, 2026 10:04
alexey-milovidov and others added 5 commits February 10, 2026 16:42
The previous commit made `isStdinNotEmptyAndValid` lazy and removed
stdin handling after inline INSERT data and in the async insert path.
This fixed the hang but broke two tests:
- `02270_stdin_with_query_or_infile_data` (stdin + inline data)
- `02884_async_insert_native_protocol_1` (async insert mixed data detection)

Instead, add a `non_blocking` mode to `isStdinNotEmptyAndValid` that
uses `poll` with zero timeout to check if stdin has data available
before committing to the blocking `read` in `eof`. This avoids the
hang on empty pipes while preserving all existing stdin functionality.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/Client/ClientBase.cpp Resolved
Comment thread src/Client/ClientBase.cpp Resolved
Comment thread src/Client/ClientBase.cpp Resolved
alexey-milovidov and others added 5 commits March 28, 2026 23:51
…false

Separate the error handling in the non-blocking stdin check:
- `EINTR`: retry the `poll` call
- `ret == -1` (other errors): throw `ErrnoException` instead of returning false
- `POLLERR`/`POLLNVAL`: throw with revents info
- `ret == 0` (no data available): return false (the intended non-blocking path)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The non-blocking `poll` is a point-in-time snapshot, so very-late-arriving
stdin data could be missed. Document that this only affects the rare
combined-source pattern (INSERT with INFILE or inline data + additional
piped stdin), while the common stdin-only INSERT path is unaffected
because `sendDataFromStdin` is called unconditionally.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Instead of using `poll(timeout=0)` which introduces a race condition
(late-arriving stdin data could be missed), simply skip the stdin
check entirely when the INSERT query already has inline data or INFILE.

The blocking `read()` in `isStdinNotEmptyAndValid` hangs when stdin is a
pipe without data/EOF (stress tests, CI, Docker, `--queries-file`).
The combined-source pattern (inline data + stdin) was the only case
affected; when there is no inline data or INFILE, `sendDataFromStdin`
is called unconditionally.

This addresses the review feedback about the `poll(timeout=0)` race
and is a simpler, more correct solution.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Client/ClientBase.cpp Resolved
When INSERT already has inline data or INFILE, use `poll(timeout=0)`
to check if stdin also has data, instead of calling the blocking
`isStdinNotEmptyAndValid` which does `read(0, ...)`. This prevents
indefinite hangs when stdin is a pipe without data/EOF (common in
stress tests, CI, Docker, `--queries-file` mode).

When there is no other data source (no inline data, no INFILE),
the blocking check is kept — that is the existing behavior where
stdin is the only source and we must wait for it.

This also restores the async insert mixed-data check: when
`is_async_insert_with_inlined_data` is true, we use the non-blocking
poll to detect stdin data and throw `NOT_IMPLEMENTED` if found.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Client/ClientBase.cpp Resolved
alexey-milovidov and others added 5 commits March 29, 2026 06:52
…taAvailableNonBlocking`

Retry `poll` on `EINTR` instead of throwing, since signal delivery is
normal during stdin probing. Surface `POLLERR`/`POLLNVAL` as an
exception instead of silently returning false.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
… pipe

Verifies that `--queries-file` with INSERT having inline VALUES does not
hang when stdin is a pipe with no data and no EOF (the original bug
scenario from stress tests and CI environments).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The test opened a FIFO on fd 3 (`exec 3<>"$FIFO"`), but shell_config.sh
sets `BASH_XTRACEFD=3` for bash tracing. This caused bash trace output
to be written into the FIFO, which the client then read as stdin data
for INSERT, producing a parse error.

Use fd 4 instead to avoid the conflict.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Address review feedback: add test coverage for `async_insert=1` with
inline INSERT data and stdin as an empty pipe. The async insert path
has its own stdin check that must also use non-blocking poll.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Client/ClientBase.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master to clear the only CI failure: 05218_text_index_substreams_opened_lazily in Stateless tests (amd_debug, sequential). It fails only when use_columns_cache = 1 is randomized on, and has nothing to do with this client-side stdin change. The test fix landed on master in #127781. The merge applied without conflicts, and ClientBase.cpp compiles on the merged tree.

Comment thread src/Client/ClientBase.cpp Resolved
`POLLERR` does not imply that no bytes remain readable: a socket whose peer
sent data and then reset the connection reports `POLLIN | POLLERR | POLLHUP`,
and the data is still readable. `getStdinStateNonBlocking` returned
`EndOfFile` in this case, so already-available stdin input was ignored and
inline/async inserts bypassed the mixed-input rejection. Check `POLLIN`
before `POLLERR`/`POLLHUP`; keep `POLLNVAL` and error-only as end of file.

Add a regression case with a TCP socket as stdin reset by its peer.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96494&sha=0627229ef06a4486cbdf98bbcc79c4cbad16811d&name_0=PR&name_1=Build%20profile%20diff and provide a fix in a separate PR. If the fix is already in progress, link it here. The Build profile diff job failed with LogClusterNotReady: the endpoint never became ready, which is CI infrastructure and unrelated to this PR. Possibly related: #126200

@groeneai

Copy link
Copy Markdown
Collaborator

The Build profile diff red on 0627229 is not caused by this PR. Its job log shows all 8 SELECT 1 readiness probes failing (No connection to LogCluster, 2026-10-27 09:49-09:52 UTC) until has_pr_data raises LogClusterNotReady. The read-only CI logs service is at its total memory limit and rejects every query, the probe included: HTTP 500, Code: 241 ... current RSS: 212.92 GiB, maximum: 212.40 GiB (re-checked at 2026-10-28 05:20 UTC). No Build profile diff run in CIDB has been green since 2026-10-26 22:42 UTC.

The fix in progress is my open PR #126200: a readiness probe that the server rejects for its own load (exception code 202 or 241) ends the job green with CI logs cluster unavailable, nothing compared, while every other not-ready cause stays red. The memory exhaustion of the read-only service itself is on the cluster side.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (now f277f46e) to pull in the fix for the flaky 05227_mutate_part_ahead_of_table_metadata_version_mergetree that failed in Fast test (arm_darwin). That test exercises MergeTree mutations and is unrelated to this client stdin change. Its fix is commit 1033610 on master. The Build profile diff red is the CI logs cluster running out of memory, which @groeneai is tracking in #126200. The merge had no conflicts, and ClientBase.cpp compiles on the merged tree.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only CI failure on head c01ad4b6 is ThreadSanitizer: data race in Stress test (amd_tsan) (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96494&sha=c01ad4b627400f978cc7d57fc8638fcb29f88c7c&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29). The race is in ClientBase::onProgress (processed_rows_from_progress), called by LocalConnection::sendQuery from pipeline threads. This PR changes only the stdin probing for INSERT queries, so it does not cause the race. A fix is in progress in #128019. Review threads: none open. The branch already contains today's master.

…rt-queries-file

Resolve conflict in `ClientBase::sendData`: master now skips the stdin check
entirely for `INSERT ... FROM INFILE`; keep that and apply this PR's
non-blocking check only for inline data.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master to resolve the conflict in ClientBase::sendData. master (#126564) now skips the stdin check entirely for INSERT ... FROM INFILE. I kept that, and the PR's non-blocking poll check now applies only to inline data. Locally (aarch64 release build), 04064_queries_file_no_stdin_hang, 04064_inline_insert_data, 05409_local_infile_ignores_stdin and 02270_stdin_with_query_or_infile_data pass. The remaining Stress test (amd_tsan) data race in ClientBase::onProgress is unrelated and tracked by #128019 / #128395.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (now 94233e6f) to clear the CI red. 05474_parquet_corpus_writers failed in Stateless tests (amd_debug, parallel) and Stateless tests (arm_binary, parallel) because the reference expected INCORRECT_DATA for the polars 0.20 u64 > 9223372036854775807 rows, but the query now returns ok. This PR only touches ClientBase stdin probing, so it does not cause this. It was fixed on master by e514655b5bac (Update the polars 0.20 rows of 05474_parquet_corpus_writers). The Finish Workflow / new_tests_check.py red was a knock-on failure: both Bugfix validation jobs were dropped because of the earlier failure. They should run again on the new head. There are no open review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (now 732256ab) to clear the CI red. The only failure was 05141_parquet_time_stats_pruning in Stateless tests (arm_asan_ubsan, azure, parallel), which is unrelated to this PR and passed 0 of 3 reruns as a failure. It is fixed on master by #130688. The merge was clean and ClientBase.cpp builds.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (now e6256de9) to clear the CI red. The only failure was Stress test (amd_tsan), which hit a TSan heap-use-after-free in DeltaLakeMetadataDeltaKernel::prepareReadingFromFormat. That is unrelated to this PR, which only changes stdin probing in ClientBase. It is fixed on master by #131029. The merge was clean, ClientBase.cpp builds, and the PR diff is unchanged.

@alexey-milovidov
alexey-milovidov marked this pull request as ready for review November 16, 2026 16:41
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Fixed the CH Inc sync conflict: the sync PR https://github.com/ClickHouse/clickhouse-private/pull/49085 conflicted with private master. I overlaid the 3 PR files onto private master (ClientBase.cpp merged cleanly, diff identical to the public PR diff), committed it as a merge of the old sync tip, private master and public head a268c52a, and pushed f222ee52. The sync PR is now MERGEABLE. All public CI checks pass and there are no open review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check on head a268c52a is CH Inc sync (tests failed (1 new, 6 known)). The failing tests in the sync PR https://github.com/ClickHouse/clickhouse-private/pull/49085 are test_distributed_cache/* integration tests (errors at setup under ASan/UBSan and MSan) and 03144_parallel_alter_add_drop_column_zookeeper_on_steroids (CANNOT_ASSIGN_ALTER from StorageSharedMergeTree::alter). This PR only changes stdin probing in ClientBase, so it does not cause them. I restarted the failed jobs of the sync workflow run. All public CI checks pass and there are no open review threads.

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Nov 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 22, 2026
Merged via the queue into master with commit 903285f Nov 22, 2026
380 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-stdin-hang-insert-queries-file branch November 22, 2026 03:47
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 22, 2026
@stresshouse

stresshouse Bot commented Nov 22, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

no significant changes detected. K_source=4 K_base=27 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: e3c2158d-dd0d-47f7-a105-06572440c311
  • MIRAI run: 06ce16e6-d746-4d6e-b2b3-037eff7d901f
  • PR check IDs:
    • clickbench_750710_1795322725
    • clickbench_750724_1795322725
    • tpch_adapted_1_official_750735_1795322725
    • tpch_adapted_1_official_750775_1795322725

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-cli clickhouse-client (interactive CLI) and client library. 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.

5 participants