Skip to content

Do not let processes started by the server keep web terminal and SSH sessions open - #126995

Merged
PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:embedded-client-descriptors-cloexec
Nov 2, 2026
Merged

PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:embedded-client-descriptors-cloexec

Conversation

@groeneai

@groeneai groeneai commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #125753

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 web terminal or SSH session that never ended, with its query still running, after the server had started an executable or executable_pool process during that session. The process inherited the session's pseudo-terminal or pipes, so closing the web terminal did not stop its query, and an INSERT fed through ssh never saw the end of its input.

Description

On 26.8.28.14, closing a web terminal while its query prints output leaves the query, the embedded client and the HTTP handler thread stuck until a process that the server started during that session exits; for an executable_pool process that means until the dictionary is reloaded or the server restarts. This is the 05386_webterminal_close_during_query failure on master (2026-10-20), and the 05453_webterminal_close_at_binary_format_question failure with Some queries hung (2026-10-30): 05394 started a pool process inside the session.

openPty opened the pseudo-terminal without O_CLOEXEC, and Poco::Pipe (stdin/stdout/stderr of an SSH exec session without a terminal) used plain pipe(). ShellCommand starts processes with vfork + execv, so the child kept copies. Closing the master then does not hang up the slave, the embedded client blocks writing to a terminal nobody reads, and ~ClientEmbeddedRunner waits for it. Over SSH without a terminal, the child holds the write end of the client's stdin, so the client never sees the end of its input.

The change opens both ends of the pseudo-terminal with O_CLOEXEC and creates Poco pipes with pipe2(O_CLOEXEC) (pipe + FD_CLOEXEC on macOS). dup2 clears the flag on a child's stdio, so the pipes a child needs are unaffected.

The new tests start a pool process inside the session, then close the WebSocket (05427) or end the ssh input (05428). On master both fail 5/5, alone and when run together (the query still runs after 60 s; the pool process holds /dev/ptmx and /dev/pts/N, or the session's stdin pipe), 05427 also fails on 26.8.28.14, and both pass in about 2 s with the fix. 50 randomized runs of each pass, sequentially and with -j 16, as do 05386, 05394 and the other web terminal, SSH and executable tests.


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

Version info

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

groeneai and others added 2 commits October 20, 2026 15:52
…ipes of embedded client sessions

`openPty` opened the pseudo-terminal of a web terminal / SSH session without
`O_CLOEXEC`, and `Poco::Pipe` (the stdin/stdout/stderr of an SSH `exec`
session without a terminal) used plain `pipe()`. `ShellCommand` starts
`executable` / `executable_pool` sources with `vfork` + `execv` and closes no
descriptors, so a process started while such a session existed kept a copy of
its descriptors.

Web terminal / SSH with a PTY: closing the session closes the server's
master, but the master hangs up the slave only when its last reference goes
away. The child still holds one, so nobody reads the terminal any more, the
embedded client's next write blocks forever, `~ClientEmbeddedRunner` waits
for it forever and the query is never cancelled. This is the hang of
`05386_webterminal_close_during_query` on master (5ba211c): `05394`
started a pool process inside the lifetime of 05386's terminal.

SSH `exec` without a PTY: the child holds the write end of the client's
stdin, so the client never sees the end of its input and an `INSERT` fed
through `ssh` never finishes.

Open both PTY ends with `O_CLOEXEC` (atomic on Linux, FreeBSD and macOS) and
create Poco pipes with `pipe2(O_CLOEXEC)`; macOS has no `pipe2`, so set
`FD_CLOEXEC` right after `pipe` there, as `LazyPipeFDs::open` does. `dup2` in
`ShellCommand` and Poco `Process` clears the flag on the child's stdio copies,
so the pipes a child needs are unaffected.

New tests: `05427_webterminal_close_with_started_process` and
`05428_ssh_insert_with_started_process` start a pool process inside the
session, then end the session (close the WebSocket / send EOF) and require
the query to finish.

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

05427 and 05428 both reloaded `executable_pool_simple_implicit_key`. A
reload ends the processes of the previous pool, so when the two tests run
together (Bugfix validation runs the changed tests in parallel) each one
ended the other's witness process and both passed on master. 05428 now
uses `executable_pool_complex_implicit_key`, which no other parallel test
reloads.

05428 also prints the number of running INSERTs before it starts the
process, so a session that never started fails the test instead of
passing it vacuously.

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

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

Pre-publication review by an independent model (engine: codex; 2 findings, then 0 on the re-review of the fix) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The two new tests reload the same executable_pool dictionary and can end each other's witness process, so both can pass on master when run together (Bugfix validation runs them in parallel) AGREE, fixed @ bea8f56 confirmed first (both passed on master 5/5 when run together); 05428 now uses executable_pool_complex_implicit_key, and both fail on master 5/5 when run together
2 ⚠️ 05428 does not assert that the INSERT is running before it starts the process AGREE, fixed @ bea8f56 the observed count is now part of the reference
3 💡 05427 repeats the WebSocket helper of 05386 DISAGREE sharing it means editing 05386, which Bugfix validation would count as a changed test that passes on master
4 💡 replxx's self-pipe is still inherited DISAGREE both ends belong to the same terminal object in the server, so an extra holder cannot block it

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261020-170200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05427 reloads executable_pool_simple_implicit_key and 05428 executable_pool_complex_implicit_key, so a new pool process starts inside the session, and neither test ends the other's process. Each fails 5/5 on master 2a95d09f46c1a (marker query still running after 60 s), alone and when the two run together with -j 2; 05427 also fails 2/2 on the official 26.8.28.14 image.
b Root cause explained? openPty opened the PTY master and slave without O_CLOEXEC, Poco::PipeImpl used plain pipe(), and ShellCommand starts processes with vfork + execv. The child keeps the master, so closing the server's copy does not hang up the slave; the embedded client blocks on a write nobody reads and ~ClientEmbeddedRunner waits for it. Over SSH exec, the child keeps the write end of the client's stdin, so the client never sees EOF. /proc/<pool pid>/fd on master shows /dev/ptmx + /dev/pts/0, or both ends of the session's stdin pipe.
c Fix matches root cause? Yes. The descriptors are created close-on-exec, atomically (O_CLOEXEC, pipe2(O_CLOEXEC)), as sockets (#21695, #125753) and PipeFDs already are. This covers every exec-based spawner, not one call site.
d Test intent preserved / new tests added? Two new tests, one per carrier: 05427 (web terminal PTY), 05428 (SSH exec pipes). 05386 and 05394 are unchanged.
e Both directions demonstrated? Master: 5/5 FAIL each, alone and run together. Fix: 20/20 (also run together), 50/50 randomized, 50 runs with -j 16, each about 2 s. Same config, only the binary differs.
f Fix is general across code paths? openPty is the only PTY source (web terminal and SSH PTY). All three SSH exec pipes are Poco::Pipe. Accepted sockets are already close-on-exec (#125753). No dup of these descriptors in the embedded client code. Other Poco::Pipe users: the watchdog's notify_sync (fork without exec) and Poco Process (unused, and it dup2s onto 0/1/2).
g Fix generalizes across inputs (params/datatypes/wrappers)? No data types involved. Covers both session kinds (PTY, pipes), both failure shapes (blocked output, missing input EOF), and both executable and executable_pool (both use ShellCommand).
h Backward compatible? (maintainer-approved exception only) Yes. Only processes the server starts lose descriptors they never needed. The children that would need the terminal (pager, $EDITOR) are disabled in embedded mode. No setting.
i Invariants and contracts preserved? openPty still returns both fds or -1 with errno, no leak on any path. PipeImpl throws the same exception on failure, and the macOS fallback closes both fds first. dup2 clears the flag on a child's stdio, so child stdio pipes are unaffected.

Session id: cron:clickhouse-impl-slot-6:20261020-162400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @george-larionov, could you review this and add the can be tested label so CI runs? The web terminal PTY and the Poco pipes of SSH exec sessions are now created close-on-exec, so an executable_pool process started during a session no longer holds them open and keeps the session (and its query) alive after the client closes it, as #125753 did for accepted sockets.

@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [15682ce]

Summary: ✅


AI Review

Summary

Reviewed #126995 at 15682cec635d55f0c30fcf038dce88f7dd97dd63, including the full discussion and current diff. The change prevents spawned processes from retaining embedded-client pseudo-terminals and SSH pipes, allowing session teardown and input EOF to complete. No actionable findings remain; the focused regression tests and reported before/after validation support the fix.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-external-dependencies Third-party deps updates in contrib/, vendored code, and platform base libraries. labels Oct 20, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 21, 2026
groeneai and others added 2 commits October 21, 2026 05:55
The CI profile (`tests/config/users.d/limits.yaml`) sets `max_rows_to_read`
to 20 million for every stateless job, and the web terminal session uses that
profile. `numbers(100000000)` was rejected with `TOO_MANY_ROWS` before
printing anything, so the test waited for its output until the 60 second
timeout and failed in Fast test. Set `max_rows_to_read = 0` for that query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`clickhouse-test --trace` (as in CI) sends the bash xtrace of the test to fd 3
(`BASH_XTRACEFD=3` in `shell_config.sh`). The test reused fd 3 for the FIFO
that feeds the INSERT, so the trace lines went into the INSERT as data, which
failed to parse (the table stayed empty), and after closing fd 3 the trace
went to stderr. Use a descriptor allocated by bash instead.

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

clickhouse-gh Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 15682cec6 with master 0ea6ec133 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 267fb186d; 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6dda2aa

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
Stateless tests (amd_tsan, flaky check) / ThreadSanitizer: data race (STID: 3847-3353) data race, not from this PR's diff (close-on-exec PTY and pipe descriptors): concurrent embedded client sessions write the process-wide replxx_last_is_delimiter in ReplxxLineReader::setLastIsDelimiter; the flaky check runs the new web terminal and SSH tests concurrently; the same STID also failed on another PR #125510 (external, open)
Stateless tests (amd_tsan, flaky check) / Server liveness check failed companion of the TSan report above, same job #125510 (external, open)
Stateless tests (amd_tsan, s3 storage, targeted) / ThreadSanitizer: data race (STID: 3653-3ca8) data race, not from this PR's diff: concurrent embedded client sessions share the function-local static counter in ProgressIndication::writeProgress (ProgressIndication.cpp:166) #126055 (mine, open)
Stateless tests (amd_tsan, s3 storage, targeted) / Server liveness check failed companion of the TSan report above, same job #126055 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #125510 (external, open), #126055 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261021-110006

@PedroTadim

PedroTadim commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

@groeneai 🕵️ Reviewed the change — the core fix is correct. ShellCommand spawns executable-dictionary processes via vfork+execv without closing inherited descriptors, so non-CLOEXEC session fds (the PTY master/slave and the Poco pipes behind the embedded client) leak into them and keep the client's output target open, which is why the session does not hang up. Setting close-on-exec on those descriptors is the right fix, and the scope looks complete: the other Poco::Pipe consumers (BaseDaemon's fork-without-exec, Poco::Process which dup2s, the embedded client) are all safe under the global change, and the network socket is already CLOEXEC.

A few points on the non-Linux paths and the tests:

1. O_CLOEXEC on posix_openpt is not portable (base/base/openpty.cpp)

O_CLOEXEC to posix_openpt is a glibc extension. On macOS/BSD, posix_openpt may reject it with EINVAL (so openPty fails and the PTY session can't be created) or silently ignore it (the master fd stays non-close-on-exec and still leaks into the vfork'd processes — i.e. the exact teardown hang this PR fixes persists). The slave side uses open(..., O_CLOEXEC), which is portable, but the master should set the flag explicitly after the call:

int m = posix_openpt(O_RDWR | O_NOCTTY);
...
fcntl(m, F_SETFD, FD_CLOEXEC);

This mirrors the __APPLE__ branch you already added in PipeImpl_POSIX.cpp, so the two paths stay consistent.

2. macOS pipe path: pipe() + fcntl is not atomic (base/poco/Foundation/src/PipeImpl_POSIX.cpp)

On the non-Apple path the atomic pipe2(O_CLOEXEC) closes the window entirely. On macOS, pipe() followed by a separate fcntl(F_SETFD, FD_CLOEXEC) leaves a window in which a concurrent ShellCommand (vfork+execv) can inherit the still-non-CLOEXEC pipe ends and reproduce the leak. macOS lacks pipe2, so the gap is inherent, but it's worth a short comment noting the race is accepted there.

3. macOS pipe path: errno is clobbered on the error branch (base/poco/Foundation/src/PipeImpl_POSIX.cpp)

When fcntl fails, the two close() calls run before throw CreateFileException("anonymous pipe"). CreateFileException formats the current errno, so it reports the error of the last close() rather than the real fcntl failure. Save and restore errno around the cleanup:

int saved_errno = errno;
close(fds[0]);
close(fds[1]);
errno = saved_errno;
throw CreateFileException("anonymous pipe");

4. SSH availability probe hinges on nc (tests/queries/0_stateless/05428_ssh_insert_with_started_process.sh)

echo "" | nc ... conflates "nc is not installed" (exit 127) with "the SSH port is closed": on a runner that has ssh but no nc, the test prints @@SKIP@@: SSH port ... is not available and exits 0, silently skipping a test that could have run, with an inaccurate reason. The availability check shouldn't depend on a second, unrelated tool.

5. Duplicated inline WebSocket helper (tests/queries/0_stateless/05427_webterminal_close_with_started_process.sh)

The ~60-line inline Python WebSocket helper (recv_exact/send_frame/read_frame/read_until) is copy-pasted from 05386 (and 05385/05445/05453); this PR adds a fifth copy. A framing fix would then have to be applied to five near-identical heredocs. Consider extracting it into a shared helper under tests/queries/0_stateless/helpers/ and sourcing it.

Points 1 and 2 are the ones I'd most like addressed, since they concern the macOS paths this PR explicitly set out to handle. The rest are minor / cleanup.

macOS has no pipe2, so a process started by another thread between
pipe() and fcntl() still inherits the pipe. Say so in the fallback.

05428 checked the SSH port with nc, so a runner without nc skipped the
test with a misleading reason. Probe the port with bash's /dev/tcp.

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

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Pushed 15682ce.

  1. I kept O_CLOEXEC in the posix_openpt call, because every platform ClickHouse builds for applies it atomically. glibc (getpt.c#L30), musl (pty.c#L10) and Apple Libc (grantpt.c#L44) all pass the flags straight to open("/dev/ptmx", flags). FreeBSD's posix_openpt(2) has accepted O_CLOEXEC explicitly since FreeBSD 10 (tty_pts.c#L844). Setting the flag with fcntl after the call would open the window from point 2 on Linux as well.
  2. Done: one comment line in the macOS branch (15682ce).
  3. No change: CreateFileException("anonymous pipe") only stores the message (base/poco/Foundation/src/Exception.cpp:27) and never reads errno, so the close() calls cannot change what is reported.
  4. Done: the probe now uses bash's /dev/tcp under timeout 5 instead of nc (15682ce).
  5. Agreed that it should be shared. I left it out of this fix because extracting it means rewriting 05385, 05386, 05445 and 05453, which this PR does not otherwise touch, and 05385 and 05453 are not on 26.8-26.10, where a backport would go. I can do it in a separate test-only PR if you want.

Validated on a rebuild of the new head, with --trace and the CI limits.yaml. 05428 fails 3/3 on current master with the intended diff and passes 20/20 with the fix. 05427 + 05428 at -j2 pass 5/5. 05386, 05394, 05427, 05428, 05453 and 03918 at x20 -j16 pass 120/120.

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 2, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai I am merging this, but can you confirm if there are other places missing O_CLOEXEC flag. Also, for the cases added in this PR, could other callers be negatively impacted by it?

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

Yes, there are more. I measured them on current master (1df150b): I started a process through executable() while the server had embedded Keeper, a FileLog table, an ssd_cache dictionary and a running distributed query, listed its /proc/<pid>/fd, and attributed each descriptor with strace -f -k. Besides the PTY and pipes fixed here, a process started by the server inherits:

Descriptor Created at Effect
Keeper Raft listening socket NuRaft asio_rpc_listener (boost::asio socket() without SOCK_CLOEXEC, contrib/NuRaft/src/asio_service.cxx:1290) After kill -9 of the server, a still-running executable() script keeps the Raft port listening, and the restarted server exits at startup with Code: 568. DB::Exception: Cannot create interserver listener on port <raft port> after trying both IPv6 and IPv4. (RAFT_ERROR). It starts once the script exits.
server log and error log Poco FileStreamBuf::open (base/poco/Foundation/src/FileStream_POSIX.cpp:64) Held open for the life of an executable_pool process, so the space of a rotated and deleted log is freed only when it exits.
ssd_cache dictionary file src/Dictionaries/SSDCacheDictionaryStorage.h:486,488 Same, after the dictionary is dropped.
FileLog inotify instance src/Storages/FileLog/DirectoryWatcherBase.cpp:71 Kernel object only.
epoll of running pipelines and remote reads src/Common/Epoll.cpp:33 (epoll_create1(0)), via PollingQueue, HedgedConnections, ConnectionEstablisherAsync, RemoteQueryExecutorReadContext, TimerDescriptor::drain Kernel object only.
remote read wakeup pipe src/QueryPipeline/RemoteQueryExecutorReadContext.cpp:38 (pipe2(O_NONBLOCK)) None, both ends belong to the same object.
4 x /dev/urandom static std::random_device objects (libc++ opens it without O_CLOEXEC, contrib/llvm-project/libcxx/src/random.cpp:68) None.

Found by grep, not reached by that workload: the ::dup() of the PostgreSQL socket (src/Processors/Sources/PostgreSQLSource.cpp:176), the Keeper snapshot file for chunked transfer (src/Coordination/KeeperStateMachine.cpp:2155), perf_event_open without PERF_FLAG_FD_CLOEXEC (src/Common/ThreadProfileEvents.cpp:298), Poco PollSet and Socket::select (epoll_create(1)), and the replxx per-terminal self-pipe (contrib/replxx/src/terminal.cxx:119). Raft peer connections come from the same asio code (::accept, socket() without the flag); I did not measure a multi-node cluster. Poco stream sockets (client, server, accepted), ReadBufferFromFile/WriteBufferFromFile, PipeFDs, EventFD and the Linux TimerDescriptor are already close-on-exec.

Only the Raft socket has a user-visible effect that I could reproduce, and the sites are spread over contrib (NuRaft/asio, Poco, libc++). One fix that covers all of them is to close every descriptor except 0-2 and the configured extra pipes in the ShellCommand child before execv (close_range, Linux 5.9+). I can send that as a separate PR, or only set close-on-exec on the NuRaft sockets in ClickHouse/NuRaft. Which do you prefer?

Other callers are not affected. openPty has one caller, PtyClientDescriptorSet (web terminal and SSH PTY sessions). The client runs inside the server, and the only children that would use its terminal, the pager (src/Client/ClientBase.cpp:1034) and $EDITOR (src/Client/ReplxxLineReader.cpp:707), are disabled in embedded mode. Poco::Pipe is used by PipeClientDescriptorSet (SSH exec, also in-process), by BaseDaemon::setupWatchdog (fork() without exec, where close-on-exec does not apply), and by Poco's Process::launch, which ClickHouse does not call; it dup2s the pipes onto 0/1/2, which clears the flag, and closes the rest. No caller relies on inheriting these descriptors.

Merged via the queue into ClickHouse:master with commit ab83663 Nov 2, 2026
179 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 2, 2026
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-external-dependencies Third-party deps updates in contrib/, vendored code, and platform base libraries. 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.

4 participants