Repository navigation
Add detached execution for non-readonly queries (detach_non_readonly_queries) - #96823
pratimapatel2008 wants to merge 63 commits into
Conversation
|
Workflow [PR], commit [8c2de6d] Summary: ❌
AI ReviewSummaryThis PR adds experimental detached execution across HTTP, the native protocol, and interactive Findings❌ Blockers
Final VerdictChanges requested. The remaining problems are confined to two protocol edges, but both are user-visible contract/compatibility bugs in the current |
dbc1da0 to
7d10e1e
Compare
Exception until this is reviewed and merged ClickHouse/ClickHouse#96823
35f972e to
25ae197
Compare
|
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.
(3) is important because without that, the following query will fail (because no will return query_id happily. But if you look at the query_log, it would fail even before it starts ( (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) |
| /// 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 |
There was a problem hiding this comment.
❌ 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).
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
74ff2a4 to
8e231cc
Compare
8e231cc to
85c19ef
Compare
85c19ef to
d6c51bd
Compare
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]>
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]>
Signed-off-by: Kaviraj <[email protected]>
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]>
|
I pushed a maintainer edit to
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:
There is also an open question from @alexey-milovidov on the docs: whether this is needed for |
…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]>
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]>
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.
|
Pushed a maintainer edit to
The other CI reds are unrelated / flaky and are not caused by this PR:
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 ( |
|
The only failing check on the current head is Fix submitted separately in #110044 (pins |
…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
…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`.
|
Pushed a maintainer edit to Merge / cruft
Review findings addressed Verified locally on Still open for you: whether this feature is wanted in this form at all (my earlier question — |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 550/598 (91.97%) · Uncovered code |
|
Continued in #112816 |
…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]>
Changelog category:
Changelog entry
Adds experimental support for running non-readonly queries (e.g.
INSERT,INSERT ... SELECT) in a detached way: when the new settingallow_experimental_detach_queriesis enabled, the server returns immediately with thequery_idand 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
Motivation
Clients can submit long-running or heavy writes without blocking on completion. They receive a
query_idright away and can use it for tracking or polling; the connection is freed for other work.Changes
allow_experimental_detach_queries(bool, defaultfalse).query_id.async_insert=1so existing async-insert behaviour is unchanged (async_insertdefaults to1, so setasync_insert=0explicitly). Not used for multipart/external data.tests/queries/0_stateless/03812_detach_non_readonly_queries.shcovers 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)
Native client (clickhouse-client):
Closes: #96906