Skip to content

Add detached execution for non-readonly queries (detach_non_readonly_queries) - #96823

Closed
pratimapatel2008 wants to merge 63 commits into
ClickHouse:masterfrom
pratimapatel2008:http_async
Closed

pratimapatel2008 wants to merge 63 commits into
ClickHouse:masterfrom
pratimapatel2008:http_async

Conversation

@pratimapatel2008

@pratimapatel2008 pratimapatel2008 commented Feb 13, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category:

  • Experimental Feature

Changelog entry

Adds experimental support for running non-readonly queries (e.g. INSERT, INSERT ... SELECT) in a detached way: when the new setting allow_experimental_detach_queries is enabled, the server returns immediately with the query_id and runs the query in a background thread.

This is distinct from async_insert: async_insert queues and may batch inserts; this setting only detaches execution (return immediately with query_id, run query in a background thread) and does not change insert batching or queue semantics.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Motivation

Clients can submit long-running or heavy writes without blocking on completion. They receive a query_id right away and can use it for tracking or polling; the connection is freed for other work.

Changes

  • Setting: allow_experimental_detach_queries (bool, default false).
  • Behaviour: When the setting is on and the query is non-readonly (e.g. INSERT/UPDATE/DELETE), the handler:
    • Reads and parses the query.
    • Spawns a detached thread to run the query with a copy of the context (progress callback is cleared so the response is not used from another thread).
    • Returns the query_id.
  • Compatibility: Disabled when async_insert=1 so existing async-insert behaviour is unchanged (async_insert defaults to 1, so set async_insert=0 explicitly). Not used for multipart/external data.
  • Tests: tests/queries/0_stateless/03812_detach_non_readonly_queries.sh covers sync vs detach mode, SELECT staying synchronous, and inserts in detached mode.

Usage example

Detached INSERT ... SELECT (query in URL)

curl -sS \
    "http://localhost:8123/?allow_experimental_detach_queries=1&async_insert=0&query=INSERT+INTO+my_table+SELECT+1" \
    -X POST \
    -d ""

Detached with query only in POST body

curl -sS \
    "http://localhost:8123/?allow_experimental_detach_queries=1&async_insert=0" \
    -X POST \
    --data-binary "INSERT INTO my_table SELECT 2"

In a session (SQL)

SET allow_experimental_detach_queries = 1;

Native client (clickhouse-client):

clickhouse-client --allow_experimental_detach_queries 1 --async_insert 0 -q "INSERT INTO my_table SELECT 1"
# or in the query:
clickhouse-client -q "INSERT INTO my_table SELECT 1 SETTINGS allow_experimental_detach_queries=1, async_insert=0"

Closes: #96906

@pratimapatel2008 pratimapatel2008 added the pr-feature Pull request with new product feature label Feb 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Feb 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8c2de6d]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, parallel) FAIL
00084_external_aggregation FAIL cidb
Upgrade check (amd_release) FAIL
Changed settings are not reflected in the settings changes history (see changed_settings.txt) FAIL cidb
New settings are not reflected in settings changes history (see new_settings.txt) FAIL cidb

AI Review

Summary

This PR adds experimental detached execution across HTTP, the native protocol, and interactive clickhouse-local, and the current HEAD fixes most of the earlier lifecycle bugs. I still see two blocker-level gaps before merge: the HTTP body-only path still changes synchronous request semantics by forcing a 128 MiB pre-buffer/read into memory, and the native detach gate still misses queries whose data arrives in follow-up client packets.

Findings

❌ Blockers

  • [src/Server/HTTPHandler.cpp:506] [dismissed by author -- https://github.com/Add detached execution for non-readonly queries (detach_non_readonly_queries) #96823#discussion_r2938266841] The explanation was that the body must be pre-read so inline SETTINGS in body-only queries can influence the detach decision, but the current code still changes the non-detach contract: any body-only request with async_insert=0 is fully buffered and hard-capped at 128 MiB, so large synchronous INSERT ... FORMAT requests now fail with TOO_LARGE_STRING_SIZE where they used to stream. Suggested fix: keep the full-body pre-read strictly inside the detach-only path, or explicitly drop support for body-only detach enablement and parse only enough of the prefix to decide, so the non-detach path keeps streaming semantics.
  • [src/Server/TCPHandler.cpp:735-748] The native detach eligibility still covers only plain INSERT ... FORMAT and input(...), but clickhouse-client sends other query-scoped data after sendQuery too. In particular, ClientBase::sendExternalTables sends --scalar / --external packets after the Query packet (src/Client/ClientBase.cpp:1481-1482), and TCPHandler::processData materializes them into query_state->query_context only later (src/Server/TCPHandler.cpp:2972-2979). Because the detach path copies the context before that happens, detached native SELECT queries that rely on scalars or external tables still cannot observe the client data they were started with. Dropping the callbacks in detachQuery makes this fail closed, but it still violates the detached-query contract for native clients. Suggested fix: either defer the detach decision until all follow-up client data for the query has been received, or make such queries ineligible for detach before returning query_id.
Final Verdict

Changes requested. The remaining problems are confined to two protocol edges, but both are user-visible contract/compatibility bugs in the current HEAD.

pratimapatel2008 added a commit to ClickHouse/clickhouse-docs that referenced this pull request Feb 14, 2026
@pratimapatel2008
pratimapatel2008 force-pushed the http_async branch 2 times, most recently from 35f972e to 25ae197 Compare February 14, 2026 15:05
@pratimapatel2008 pratimapatel2008 changed the title Add detached execution for non-readonly HTTP queries (http_detach_non_readonly_queries) Add detached execution for non-readonly queries (detach_non_readonly_queries) Feb 14, 2026
Comment thread src/Parsers/IAST.cpp Resolved
Comment thread src/Server/HTTPHandler.cpp Resolved
@kavirajk

kavirajk commented Mar 15, 2026 •

Copy link
Copy Markdown
Contributor

After discussion with @pratimapatel2008 we decided to merge the work from other PR as well (which try to solve the same problem)

I added few more things on top of it.

  1. Refactored some helpers that will be common for both TCP and HTTP handler
  2. managing detached query lifecycle correctly
  3. Callback to track when exactly query started (after initial checks like schema validation, role checks, etc) so that ExceptionBeforeStart can never happen after returning query_id to the client.

(3) is important because without that, the following query will fail (because no myx_table exists) even before actually started running but query_id is returned to the client. And only way client can know is looking into query_log and repeating by fixing the query. When testing I found this is bad UX as query didn't even move into Start state.

$ clickhouse-client -q "INSERT INTO myx_table SELECT number from system.numbers WHERE sleepEachRow(1) = 0 LIMIT 30 SETTINGS detach_non_readonly_queries=1, max_block_size=1"
998780e2-8e8b-4e82-9a08-aa6afa10948b

will return query_id happily. But if you look at the query_log, it would fail even before it starts (ExceptionBeforeStart).

(2) makes sure the thread is not leaked and managed similar to other background jobs/threads in ClickHouse (e.g: gradual shutdown during upgrade or restart of ClickHouse process)

Comment thread src/Server/HTTPHandler.cpp Resolved
/// Skip when decompress=1: the body is in compressed format and must be consumed by the normal pipeline, not as raw query text.
/// Skip when async_insert=1: the body is query+data for the async-insert queue and must be read by that pipeline.
bool query_from_body = false;
if (query.empty() && request.getMethod() == HTTPServerRequest::HTTP_POST && !has_external_data

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ This block unconditionally reads the entire POST body into memory (with a hard 128 MiB cap) whenever the query comes from request body (query.empty()), even if detach_non_readonly_queries is disabled. That changes normal HTTP execution semantics from streaming to pre-buffering and can break large body-based inserts (INSERT ... FORMAT with body-only query). Please keep this pre-read strictly inside the detach-only branch (or otherwise preserve streaming for non-detach path).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-checking current HEAD: this is still reproducible.

In src/Server/HTTPHandler.cpp:495-505, the query.empty() branch still reads the whole POST body (with a hard 128 MiB cap) whenever async_insert=0, regardless of allow_experimental_detach_queries. That means the synchronous path still switches from streaming to pre-buffering even when detach is disabled.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is needed because, the settings that control detach vs non-detach (allow_experimental_detach_queries) can be part of query body via inline SETTINGS clause and needs to be extracted before.

And this extraction code path has to be shared on both detach and non-detach cases.

@pratimapatel2008
pratimapatel2008 force-pushed the http_async branch 2 times, most recently from 74ff2a4 to 8e231cc Compare March 18, 2026 00:37
Comment thread src/Server/TCPHandler.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Server/HTTPHandler.cpp Resolved
Two changes:
1. Currently the default case returning false can lead to silent failure
   when new type of Query is added in the future (e.g:
   AST::QueryKind::New). is `QueryKind::New` read query or write query?
2. Make the helper common. So that re-usable on both HTTP and TCP
   handlers without needing duplication.

Signed-off-by: Kaviraj <[email protected]>
Before we return the query_id immediately and that gives some bad UX
experience if the query failed during some validation and checks before
it actually start runnning. For example schema validation, table exists,
ROLE, permission validation.

e.g: this query `SELECT * FROM table_doesnt_exist` with detach enabled
would fail immediately even before query moved in "Started" state.

This PR waits till those checks (No ExceptionBeforeStart) to pass then
return query_id to the user.

Signed-off-by: Kaviraj <[email protected]>
Raw `std::thread` has two main drawbacks
1. It can easily leak
2. No maintainance during ClickHouse server process restart (upgrade or
   rollout)

Make detach query part of `GlobalThreadPool`, now this thread has name
and will be part of managed thread along with other background threads
that ClickHouse manages

Signed-off-by: Kaviraj <[email protected]>
Also fix the QueryKind switch by including Snapshot query explicitly

Signed-off-by: Kaviraj <[email protected]>
1. Tests for background query lifecycle.
2. QueryStarted callback to make sure it waits for query to start before
   returning query_id to the user
3. duplicate query_id behavior

Signed-off-by: Kaviraj <[email protected]>
alexey-milovidov and others added 2 commits July 3, 2026 00:21
The merge of master into this branch retyped `TCPHandler::QueryState::query`
from `String` to `StringWithMemoryTracking`, which no longer implicitly
converts to the `String` parameter of `detachQuery`. This broke the build on
every configuration (`Fast test`, `Build (arm_tidy)`, etc.) with:

    error: no matching function for call to 'detachQuery'
    note: no known conversion from 'StringWithMemoryTracking' to 'String'

Construct the `String` from the query text explicitly at the call site.

Build log: https://s3.amazonaws.com/clickhouse-test-reports/PRs/96823/a0881f308a4bb4f7e87c97ec8feaca6b80163f5b/fast_test/build_clickhouse/build_clickhouse.log

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`LocalConnection` kept only a single `detached_query_completion` handle. When a
second detached query was started while the first was still running, the second
overwrote the first handle: `~LocalConnection` then waited only for the second,
so `clickhouse-local` could exit before the first finished persisting its data.

Store the completion futures in a `std::vector`. On each `sendQuery`, reap only
the entries that are already `ready` (rethrowing the first stored post-start
exception so the user sees it on this interaction) and leave still-running ones
in the background. The destructor now waits for every outstanding entry before
the process exits, restoring the "data is persisted before exit" guarantee.

Addresses the AI review finding on `src/Client/LocalConnection.cpp`
(ClickHouse#96823 (comment)).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

I pushed a maintainer edit to http_async (maintainer_can_modify is on) to unblock CI:

  1. Fixed the build break. The last master merge retyped TCPHandler::QueryState::query from String to StringWithMemoryTracking, which stopped implicitly converting to the String parameter of detachQuery — every build config was failing with no matching function for call to 'detachQuery'. Now constructing the String explicitly at the call site. Also merged current master (the previous head was conflicting).

  2. Addressed AI blocker doc: fix typo #4 (src/Client/LocalConnection.cpp, discussion_r3455850997): LocalConnection kept only one detached-completion handle, so starting a second detached query dropped the first future and ~LocalConnection could exit before the first query persisted its data. Now the futures are held in a std::vector, reaped when ready on each sendQuery, and all outstanding ones are awaited in the destructor.

The remaining AI-review blockers still need your attention — I left them for you because they involve HTTP/native-protocol design decisions rather than mechanical fixes:

  • Repair subtree2 #1 HTTP body pre-buffering (HTTPHandler.cpp:497) — you dismissed this already; leaving as-is. Note the unconditional body pre-read still runs for body-only POST when async_insert=0, changing streaming semantics for large body-only INSERT ... FORMAT even when detach is off.
  • Repair subtree2 #2 HTTP partial-body sync fallback (HTTPHandler.cpp:639) — if the body read hits max_post_body_size (128 MiB), the catch still falls back to synchronous execution with the partially buffered body_data, which can run an INSERT with truncated text-format data. It should fail the request instead of silently truncating.
  • BaseDaemon: terminate on double SIGINT #3 native detach with client data (TCPHandler.cpp:727) — the eligibility check only excludes plain INSERT ... FORMAT. SELECT ... FROM input(...) and native external-table queries also deliver data on following packets, but detach copies the context before the input/external initializers are installed and then continues without draining them. The need_receive_data_for_input flag is only set once the initializer fires (during execution), so this needs AST-level detection of input() and a decision on external tables at the eligibility point.

There is also an open question from @alexey-milovidov on the docs: whether this is needed for clickhouse-client, which already generates its own query_id.

alexey-milovidov and others added 2 commits July 3, 2026 05:42
…s to the 26.7 section

The `allow_experimental_detach_queries` entry in `SettingsChangesHistory.cpp`
was registered under the `26.5` version section, which was correct when the
setting was first added. Since then the `02995_new_settings_history` baseline
was regenerated with `v26.6.1`, so the test now only accepts history entries
for versions greater than `26.6`. As a result the setting was reported as
`PLEASE ADD THE NEW SETTING TO SettingsChangesHistory.cpp: allow_experimental_detach_queries WAS ADDED`
and `Fast test` failed on `02995_new_settings_history`.

Move the entry to the latest `26.7` section so it is recognized as a
current-development change and the check passes.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96823&sha=b31452206e732dfd6b3c3b07e8ac7aba8eee7b09&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Server/HTTPHandler.cpp Resolved
The `Docs check` job failed with:

    1 floating pages found:
      - /opt/clickhouse-docs/docs/operations/settings/detach-queries.md
    Error: Found "floating" pages without sidebars.

The new `docs/en/operations/settings/detach-queries.md` page is not
referenced by the manually curated `operations/settings` category in
`clickhouse-docs/sidebars.js`, so the `checkFloatingPages` plugin flags
it as a floating page and fails the build.

The plugin skips any page whose front matter has `sidebar: false`, which
is the established in-repo pattern for pages intentionally kept out of
the curated left-nav (e.g. `docs/en/interfaces/web-ui-color-coding.md`).
Add `sidebar: false` to the front matter. This keeps the page out of the
settings sidebar (appropriate for an experimental, default-off setting)
while leaving it reachable via the existing direct links from
`docs/en/sql-reference/statements/insert-into.md` and via search, and it
avoids a cross-repo `clickhouse-docs` sidebar change. It is trivially
reversible: to promote the page into the sidebar later, drop this line
and add the entry to `clickhouse-docs/sidebars.js`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96823&sha=b6c90d6589f4d6aea22db1709164395d66eb3330&name_0=PR&name_1=Docs%20check

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Server/HTTPHandler.cpp Resolved
Comment thread src/Client/LocalConnection.cpp Resolved
The master merge surfaced a pre-existing duplicate: `enable_materialized_cte`
was carried in both the `26.4` and `26.3` blocks of `SettingsChangesHistory.cpp`,
while `master` has it only once (in the `26.3` block). The extra copy in the
`26.4` block was an artifact of an earlier conflict resolution and is unrelated
to this feature. Remove it so the entry matches `master` exactly.
The test allocates a PTY for `clickhouse-local` via the `util-linux`
`script -q -c CMD /dev/null` syntax. The BSD `script` shipped on macOS uses a
different argument order (`script FILE CMD`) and has no `-c` flag, so the
invocation produces empty output and the test fails only under
`Fast test (arm_darwin)`. It is stable on all Linux suites (Fast test plus the
Stateless flaky checks). Tag the test `no-darwin`, matching the existing
`04312_client_chime_on_slow_query_92718` PTY test, which does not run on Darwin.
@alexey-milovidov

Copy link
Copy Markdown
Member

Pushed a maintainer edit to http_async (maintainer_can_modify is on) to refresh CI after the branch fell ~7 days behind and went red:

  1. Merged current master (clean, no conflicts).
  2. Fixed the only PR-owned red test, 04053_local_detach_exception_before_start — it failed exclusively under Fast test (arm_darwin). The test allocates a PTY for clickhouse-local with the util-linux script -q -c CMD /dev/null syntax; the BSD script on macOS uses a different argument order (script FILE CMD) and has no -c, so the invocation yields empty output. Tagged it no-darwin, matching the existing 04312_client_chime_on_slow_query_92718 PTY test. It stays green on all Linux suites (Fast test plus the 100-run stateless flaky checks).
  3. Removed a stale duplicate enable_materialized_cte entry that an earlier conflict resolution left in the 26.4 block of SettingsChangesHistory.cpp (master has it only once, in the 26.3 block).

The other CI reds are unrelated / flaky and are not caused by this PR:

  • 04319_skip_unavailable_shards_mode_table_missing (60s socket-poll timeout) and Some queries hung on Fast test (arm_darwin) — no failures for this test on master over the last 14 days; a Darwin-runner flake.
  • Stress test Logical error: Inconsistent KeyCondition behavior (AST fuzzer, in optimizeUseAggregateProjections → markRangesFromPKRange) — a pre-existing master issue that fires 2–8×/day, in projection code unrelated to detached execution.

The three AI-review blockers remain for you, as before — they are HTTP/native-protocol design decisions rather than mechanical fixes: HTTP oversized-body fail-close (HTTPHandler.cpp), native/local detach for queries needing follow-up client data (input() / external tables in TCPHandler.cpp and LocalConnection.cpp), and the body-only inline SETTINGS contract. The docs question about whether this is needed given clickhouse-client generates its own query_id is also still open.

@alexey-milovidov

alexey-milovidov commented Jul 10, 2026 •

Copy link
Copy Markdown
Member

The only failing check on the current head is 04401_distributed_with_fill_const_to_scalar in Stateless tests (amd_asan_ubsan, distributed plan, parallel). This is a pre-existing failure on master, unrelated to this PR: the test (added by #109938) runs a distributed ORDER BY ... WITH FILL query, and the distributed plan shard enables serialize_query_plan, for which serializeSortDescription throws NOT_IMPLEMENTED on WITH FILL. It fails ~6/8 times in that shard on master while staying green in every default-settings shard.

Fix submitted separately in #110044 (pins serialize_query_plan = 0 in the test). This PR is otherwise unaffected.

pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Jul 11, 2026
…an shard

`04401_distributed_with_fill_const_to_scalar` (added by ClickHouse#109938) runs
distributed `ORDER BY ... WITH FILL` queries. The CI `distributed plan`
shard installs `users.d/distributed_plan.xml`, which turns on
`serialize_query_plan` globally. `serializeSortDescription` throws
`NOT_IMPLEMENTED: WITH FILL is not supported in serialized sort description`,
so every `WITH FILL` query fails there. On master the test fails ~6/8 times
in `Stateless tests (amd_asan_ubsan, distributed plan, parallel)` while being
green in every default-settings shard (`serialize_query_plan` defaults to 0).

The test targets the query-tree shard rewrite in `buildQueryTreeForShard`
(the `Bad cast from type DB::FunctionNode to DB::ConstantNode` fix), which is
only exercised with `serialize_query_plan = 0` anyway. Pin the setting to 0 on
each query, mirroring the existing opt-out used by other distributed tests
(e.g. `02535_max_parallel_replicas_custom_key_rmt`,
`03403_parallel_blocks_marshalling_for_distributed`). Results are unchanged, so
the reference file stays identical.

Surfaced on the CI report of PR ClickHouse#96823
(shard `Stateless tests (amd_asan_ubsan, distributed plan, parallel)`).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts:
#	src/Server/HTTPHandler.cpp
@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature and removed pr-feature Pull request with new product feature labels Jul 19, 2026
Comment thread src/Server/HTTPHandler.cpp Resolved
Comment thread src/Client/LocalConnection.cpp Resolved
@mstetsyuk mstetsyuk self-assigned this Jul 22, 2026
…ry entry

The `origin/master` merge kept both the branch-side copy of the
`mysql_datatypes_support_level` history entry (carried in from an
earlier master merge) and the version master subsequently edited in
place, so `SettingsChangesHistory.cpp` ended up with two entries for
the same setting in the same version block. Only master's current
wording is kept, leaving `allow_experimental_detach_queries` as this
pull requests sole net change to that file.
…d clear the file-progress callback

Two review findings:

- `HTTPHandler` decided whether to detach by OR-ing the effective
  `allow_experimental_detach_queries` value with the raw URL parameter of
  the same name. The URL parameter is already applied to the query context
  by `applySettingsChanges` before this point, so the extra term only had
  the effect of making `?allow_experimental_detach_queries=1` win over an
  explicit `SETTINGS allow_experimental_detach_queries = 0` in the query
  text — normal settings precedence stopped working and a client could not
  opt a single query out of detaching enabled by a profile or by the URL.
  Only the effective setting value is consulted now. Covered by the new
  test `04652_detach_queries_inline_settings_opt_out`.

- `Context::createCopy` carries over the file-progress callback as well as
  the query-progress one, but `detachQuery` cleared only the latter. A
  detached file-backed query could therefore keep calling
  `LocalConnection::updateProgress` after `sendQuery` had returned, racing
  with the `state` reset performed by the next interactive query.
  `detachQuery` now clears both callbacks.
…n an oversized POST body

Follow-up on the remaining review findings about queries whose data the
client pushes after the query text.

`Context::createCopy` carries over the external-tables initializer, the
input initializer and the input-blocks reader, all of which capture the
connection's per-query state. A detached `SELECT ... FROM input(...)`
therefore both lost its data and let a background thread reach into a
connection that had already moved on to the next query. The eligibility
check previously excluded only a plain `INSERT ... FORMAT ...` whose data
follows on the same connection.

- New `IAST::usesInputTableFunction` excludes any query referencing the
  `input` table function from detached execution on all three protocols
  (HTTP, native, `clickhouse-local`), so those queries run synchronously.
- `detachQuery` additionally drops the input and external-tables callbacks
  from the detached context, so a case that slips through fails cleanly
  instead of racing with the caller's connection.
- An HTTP body larger than the 128 MiB cap is now rejected with
  `TOO_LARGE_STRING_SIZE` instead of being silently truncated, both when the
  body carries the query and when it carries `INSERT` data. The oversized
  case must not fall back to synchronous execution, because the body has
  already been partially drained by then — reported as a partial insert
  otherwise.
- Documented these limitations, including that a body-only query cannot
  enable detaching with an inline `SETTINGS async_insert = 0`, since the body
  is read only once `async_insert` is already disabled out of band.

New test `04653_detach_queries_input_table_function`.
@alexey-milovidov

Copy link
Copy Markdown
Member

Pushed a maintainer edit to http_async (maintainer_can_modify is on): merged current master (the branch had gone CONFLICTING and was 8 days behind) and addressed the outstanding review findings about data the client pushes after the query.

Merge / cruft

  1. Merged origin/master — CONFLICTING → MERGEABLE.
  2. The merge silently duplicated the mysql_datatypes_support_level entry in SettingsChangesHistory.cpp (the branch carried master's older wording, which master then edited in place). Removed the stale copy, so allow_experimental_detach_queries is again this pull request's only net change to that file.

Review findings addressed
3. HTTPHandler decided whether to detach by OR-ing the effective setting value with the raw allow_experimental_detach_queries URL parameter. That parameter is already applied to the query context by applySettingsChanges earlier, so the extra term only made ?allow_experimental_detach_queries=1 win over an explicit SETTINGS allow_experimental_detach_queries = 0 in the query text — per-query opt-out did not work. Now only the effective value is consulted. New test 04652_detach_queries_inline_settings_opt_out.
4. Context::createCopy also preserves the file-progress callback, but detachQuery cleared only the query-progress one, so a detached file-backed query could keep calling back into the foreground LocalConnection and race with the state reset of the next interactive query. Both callbacks are cleared now.
5. Queries reading from input(...) are no longer eligible for detaching on any protocol (new IAST::usesInputTableFunction, applied in HTTPHandler, TCPHandler and LocalConnection): their data is delivered through setInputInitializer / setInputBlocksReaderCallback, both bound to the caller's connection. detachQuery additionally drops the input and external-tables callbacks from the detached context, so any case that still slips through fails cleanly instead of a background thread reaching into a connection that has moved on. New test 04653_detach_queries_input_table_function.
6. An HTTP body over the 128 MiB cap was silently truncated by LimitReadBuffer (read_no_more stops, it does not raise) — both when the body carries the query and when it carries INSERT data, so a detached insert could report success for partial data. It is now rejected with TOO_LARGE_STRING_SIZE. This deliberately does not fall back to synchronous execution, because the body is already partially drained at that point.
7. Documented the remaining limitations in docs/en/operations/settings/detach-queries.md, including the fact that a body-only query cannot enable detaching through an inline SETTINGS async_insert = 0: the body is read only when async_insert has already been disabled through the URL, session or profile. Removing that ordering constraint would require pre-buffering the body unconditionally, which is the streaming trade-off still open above — left as is.

Verified locally on aarch64 (release): ninja clickhouse clean, and 03812_detach_queries, 04053_local_detach_exception_before_start, 04257_detach_tcp_connection_survives_detach, 04652_detach_queries_inline_settings_opt_out, 04653_detach_queries_input_table_function all pass against a local server. Public CI is running on 8c2de6df635.

Still open for you: whether this feature is wanted in this form at all (my earlier question — clickhouse-client already generates a query_id), and the streaming trade-off of pre-buffering the POST body when the query lives in the body.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 550/598 (91.97%) · Uncovered code

Full report · Diff report

@mstetsyuk

Copy link
Copy Markdown
Member

Continued in #112816

@mstetsyuk mstetsyuk closed this Jul 31, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…an shard

`04401_distributed_with_fill_const_to_scalar` (added by ClickHouse#109938) runs
distributed `ORDER BY ... WITH FILL` queries. The CI `distributed plan`
shard installs `users.d/distributed_plan.xml`, which turns on
`serialize_query_plan` globally. `serializeSortDescription` throws
`NOT_IMPLEMENTED: WITH FILL is not supported in serialized sort description`,
so every `WITH FILL` query fails there. On master the test fails ~6/8 times
in `Stateless tests (amd_asan_ubsan, distributed plan, parallel)` while being
green in every default-settings shard (`serialize_query_plan` defaults to 0).

The test targets the query-tree shard rewrite in `buildQueryTreeForShard`
(the `Bad cast from type DB::FunctionNode to DB::ConstantNode` fix), which is
only exercised with `serialize_query_plan = 0` anyway. Pin the setting to 0 on
each query, mirroring the existing opt-out used by other distributed tests
(e.g. `02535_max_parallel_replicas_custom_key_rmt`,
`03403_parallel_blocks_marshalling_for_distributed`). Results are unchanged, so
the reference file stays identical.

Surfaced on the CI report of PR ClickHouse#96823
(shard `Stateless tests (amd_asan_ubsan, distributed plan, parallel)`).

Co-Authored-By: Claude Opus 4.8 (1M context) <[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 pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add detached execution for non-readonly queries

5 participants