Skip to content

Fix abort in LocalConnection::sendCancel when no query is running (web terminal, SSH, clickhouse-local) - #127364

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-local-connection-cancel-without-query
Oct 28, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-local-connection-cancel-without-query

Conversation

@groeneai

@groeneai groeneai commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #125517

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 an abort of clickhouse-local, and of the whole server for web terminal and SSH sessions, when an INSERT failed after its query had already finished, for example an INSERT whose SELECT names the input table function without reading it.

Description

On 26.3.33.24, echo 1 | clickhouse local --query "INSERT INTO FUNCTION null('x UInt64') WITH unused AS (SELECT * FROM input('x UInt64')) SELECT 1 FORMAT CSV" aborts (optional operator-> called on a disengaged value) instead of reporting an error. On master the same query typed into the web terminal aborts the server.

Found by the stress test of #125517, which drives load through the web terminal: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125517&sha=2b0d93f14784862cba71e73227b2368f107e9a23&name_0=PR&name_1=Stress%20test%20%28amd_debug%29 (Received signal 6, STID 2360-3d86). There the WebSocket closed at the end of an INSERT, and the write of the progress line to the dead terminal threw.

Root cause: LocalConnection::finishQuery resets state, and ClientBase::processInsertQuery calls sendCancel from its catch (...) for any exception, including one thrown after the query is over. LocalConnection::sendCancel dereferenced state unconditionally, while poll, receivePacket and the destructor already treat an empty state as "no query in flight".

Fix: sendCancel returns when there is no query, the same way TCPHandler ignores a Cancel packet between queries. The original exception is still reported.

Validation: the new test aborts (exit 134) on the master binary and passes 50/50 with the fix. The web terminal repro aborts a master server and leaves the fixed server serving queries.

🤖 Generated with Claude Code


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

Version info

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

`LocalConnection::finishQuery` resets `state`, and the next `receivePacket`
reports `EndOfStream`. `ClientBase::processInsertQuery` calls `sendCancel`
from its `catch (...)` for any exception, including one thrown after the
query is over (an `INSERT` whose `SELECT` names `input` without reading it
gets `EndOfStream` instead of a sample block; in the stress test of ClickHouse#125517
the web terminal closed at the end of an `INSERT` and the progress-line
write to the dead PTY threw). `sendCancel` dereferenced the empty optional
and libc++ hardening aborted: `clickhouse-local` itself, or the whole server
for the embedded client of the web terminal and SSH (STID 2360-3d86).

Every other `LocalConnection` entry point already treats an empty `state` as
"no query in flight", and `TCPHandler` ignores a `Cancel` between queries.
Make `sendCancel` do the same; the original exception is still reported.

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; 1 finding).

# Sev Finding Verdict Evidence / action
1 💡 Use Critical Bug Fix because the server can abort DISAGREE I use Critical Bug Fix only when a maintainer asks for it. Bug Fix applies: on 26.3.33.24 the INSERT from the test aborts clickhouse-local (gdb: LocalConnection::sendCancel <- ClientBase::sendCancel).

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

Session id: cron:clickhouse-review-slot-10:20261022-092000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. echo 1 | clickhouse local --query "INSERT INTO FUNCTION null('x UInt64') WITH unused AS (SELECT * FROM input('x UInt64')) SELECT 1 FORMAT CSV" aborts on every run on master and on 26.3.33.24.
b Root cause explained? finishQuery resets LocalConnection::state; an exception thrown after that inside processInsertQuery reaches its catch (...), which calls sendCancel; sendCancel dereferenced the empty optional and libc++ hardening aborted.
c Fix matches root cause? Yes. sendCancel now ignores a cancel with no query in flight, like TCPHandler; the other LocalConnection entry points either already check for an empty state or cannot run with one. The client error is still reported.
d Test intent preserved / new tests added? New 05443_local_cancel_after_insert_finished.sh; it also asserts the error was reached, so it cannot pass on an earlier failure. No existing test changed.
e Both directions demonstrated? Master binary: exit 134, test FAIL 3/3. Fixed build: exit 102 UNEXPECTED_PACKET_FROM_SERVER, test 50/50 OK. Web terminal: master server aborts, fixed server keeps serving.
f Fix is general across code paths? One guard covers clickhouse-local, the web terminal and SSH (all use LocalConnection). The other entry points were checked: they are already guarded or cannot run with an empty state.
g Fix generalizes across inputs (params/datatypes/wrappers)? Input-independent: the guard depends only on whether a query is running.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, protocol or format change.
i Invariants and contracts preserved? sendCancel still cancels a running query; with no query it changes nothing. No lifetime or locking change.

Session id: cron:clickhouse-impl-slot-7:20261022-090400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @yakov-olkhovskiy, could you review this and add the can be tested label so CI runs? LocalConnection::sendCancel dereferenced an empty state when ClientBase::processInsertQuery cancelled after finishQuery had already reset it, which aborts clickhouse-local and, via the web terminal or SSH, the whole server; it now ignores a cancel with no query running, like TCPHandler does.

@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d72ee5c]

Summary: ✅


AI Review

Summary

The PR makes LocalConnection::sendCancel ignore cancellation when no query is running, preventing process aborts after query completion while preserving the original exception. It also asserts the existing state preconditions in pullBlock and finishQuery. No actionable findings.

The regression test passes in the current head's Fast test. The original fix also passed 50 debug regression runs.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-local clickhouse-local / embedded modes (incl. local file processing). labels Oct 22, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 59b54c3

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
Bugfix validation (functional tests, amd64) / Start ClickHouse Server infra, not from this PR: the job runs the master-HEAD binary with the test configs of this run's merge commit, which is older than master #125817, and that binary refuses those cache configs at startup (Code: 36, max_file_segment_size must not exceed the size of each SLRU queue) on all 3 attempts, so the regression test never ran #127524 (mine, open)
Bugfix validation (functional tests, aarch64) / Start ClickHouse Server same server start failure #127524 (mine, open)
Finish Workflow / Post Hooks new_tests_check.py reports the two Bugfix validation (functional tests, *) failures above #127524 (mine, open), the owner of those jobs
Stateless tests (amd_debug, sequential) / 05339_iceberg_top_k_query_condition_cache master breakage, not from this PR (it changes only LocalConnection.cpp and the test 05443): the test failed on every master commit from the #126987 merge 41d5f3406f9d until its revert, and the tested merge tree c0e621689583 contains #126987 but not the revert #127378 (external, merged revert)
Stateless tests (amd_debug, distributed plan, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_asan_ubsan, azure, sequential, 2/2) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, AsyncInsert, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, s3 storage, DBReplicated, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Mergeable Check, PR praktika rollups of the rows above #127524, #127378 (the owners of the rows above)

Fast test, Style check, CH Inc sync, the targeted jobs and all five Stateless tests (*, flaky check) jobs (50 of 50 runs each) passed. The Config Workflow / Pre Hooks failures on this head are the earlier attempts stopped at the can be tested label; the current attempt passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261023-013007

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai 🕵️

Looks good. One optional follow-up: pullBlock and finishQuery in LocalConnection.cpp also dereference state without a check:

bool LocalConnection::pullBlock(Block & block)
{
    if (state->executor)
        ...
}

void LocalConnection::finishQuery()
{
    next_packet_type = Protocol::Server::EndOfStream;

    if (state->executor)
        ...
}

They don't seem reachable once a query is over, so this isn't a bug today. Since sendCancel turned out to be reachable that way through an exception path, a chassert(state) (or the same early return) in both would turn a future misuse into a clear error instead of an abort on an empty std::optional. Fine to leave for a separate PR.

Both are reached only from `poll`, which returns early when `state` is
empty, so the assertion holds by construction. It turns a future misuse
into a clear assertion failure in debug builds instead of an abort on an
empty `std::optional`. Suggested in review.

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

Copy link
Copy Markdown
Collaborator Author

Thanks. Added chassert(state) to both in d72ee5c. Both are private and only reached from poll, which returns early on an empty state, so I used the assertion rather than an early return that would hide a misuse. On a debug build it does not fire across 483 stateless tests that call clickhouse-local.

@alexey-milovidov alexey-milovidov self-assigned this Oct 28, 2026
Merged via the queue into ClickHouse:master with commit c9dc0d0 Oct 28, 2026
178 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 28, 2026
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 10, 2026
`LocalConnection` released the query state (the `BlockIO` that owns the
process list entry, and the `QueryScope` of the client thread) only in
`finishQuery` (the `EndOfStream` path), in the next `sendQuery`, or when the
connection was destroyed. A query that failed after `executeQuery` returned
delivered its `Exception` packet and kept its state, so in the web terminal
and the SSH interface it stayed in `system.processes` while the session was
idle at the prompt: it counted toward `max_concurrent_queries_for_user`, and
`KILL QUERY ... SYNC` on it did not return. In the Stress test a leaked web
terminal session kept such a query listed for 45 minutes and failed the hung
check.

Reset the state when the `Exception` packet is handed to the client, as
`finishQuery` does for `EndOfStream` and as `TCPHandler` does with its
per-query state. `sendCancel` can now be reached with no query (the catch of
`ClientBase::processInsertQuery`), so it ignores the cancel then, with the
same guard as ClickHouse#127364.

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 comp-local clickhouse-local / embedded modes (incl. local file processing). 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