Skip to content

Allow running queries detached from client session - #112816

Merged
mstetsyuk merged 44 commits into
masterfrom
run-query-in-background
Aug 19, 2026
Merged

mstetsyuk merged 44 commits into
masterfrom
run-query-in-background

Conversation

@mstetsyuk

@mstetsyuk mstetsyuk commented Jul 31, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

New setting run_query_in_background. The server accepts the query, immediately returns an empty result, and runs it to completion regardless of what happens to the connection. The result is discarded. Track the query by its query_id in system.processes and system.query_log. Intended for long queries like INSERT ... SELECT, CREATE TABLE … AS SELECT, or CREATE MATERIALIZED VIEW … POPULATE that must not die with a dropped connection.


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

Version info

  • Merged into: 26.8.1.1697 (included in 26.8 and later)

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ffa89f3]

Summary: ✅


AI Review

Summary

This PR adds run_query_in_background, a detached execution path for TCP and HTTP queries. The current head fixes several earlier issues, but the feature still acknowledges queries that depend on session state or client-supplied data it cannot carry into the detached context, and it still schedules work outside the normal ProcessList admission path. I would not merge it as a stable New Feature in this state.

PR Metadata
  • Changelog category should be Experimental Feature, not New Feature: this is a new execution mode with unresolved correctness gaps and a separate admission path.
  • The Changelog entry overstates the contract: it says the server "runs it to completion regardless of what happens to the connection", but queued jobs can still be discarded on shutdown and several query classes still either fail later or change semantics after the success response.
  • Suggested replacement:
    Experimental setting run_query_in_background to let TCP and HTTP clients detach a query from the submitting connection and discard its result. Intended for long-running statements such as INSERT ... SELECT and CREATE TABLE ... AS SELECT; queries that depend on session state or client-streamed input are not supported.
Missing context / blind spots
  • ⚠️ No local build directory was present, and the CI report reachable from the PR only exposed Build profile diff, so I could not run the new stateless tests or a live repro in this environment.
Findings

❌ Blockers

  • [src/Server/TCPHandler.cpp:706, 992-993] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/112816#discussion_r3705096595] Background native queries still skip setExternalTablesInitializer and later drain the client's Data packets with skipData, so client-supplied external tables are ignored after success is returned. Because unqualified resolution checks external tables before ordinary tables, SELECT * FROM external_table can silently read currentDatabase().external_table instead of the supplied external table when a real table with that name exists. Reject background execution when external tables are present, or preload them into the detached context before acknowledging success.
  • [src/Interpreters/Session.cpp:778-785; src/Interpreters/Context.cpp:8037-8050] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/112816#discussion_r3707948071] Detached contexts intentionally drop the session context, so session temporary tables are no longer visible. The unchanged resolver then falls through to the current database, which can make SELECT * FROM t SETTINGS run_query_in_background = 1 read a real db.t instead of the session temporary table t. Background execution needs a pre-ack guard for queries that resolve session temporary tables.
  • [src/Server/TCPHandler.cpp:652-655; src/Server/HTTPHandler.cpp:431-433] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/112816#discussion_r3759984940] The transaction guard only fires when throw_on_unsupported_query_inside_transaction = 1. If a session has an active explicit transaction and turns that setting off, the detached context drops the transaction entirely, so a background INSERT ... SELECT can commit even if the session later rolls back. This should reject any active session transaction, regardless of throw_on_unsupported_query_inside_transaction.
  • [src/Interpreters/executeQuery.cpp:3864; src/Interpreters/Context.cpp:4258-4264; src/Interpreters/ProcessList.cpp:173-258] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/112816#discussion_r3759984947] Accepted background queries are queued in an unbounded side pool before they ever reach ProcessList::insert. While queued they bypass max_concurrent_queries*, queue_max_wait_ms, duplicate-query_id checks, and KILL QUERY, yet the client has already received success. Admission and duplicate-ID checks need to happen before scheduling, or the queue must be bounded and observable/cancelable.

⚠️ Majors

  • [src/Interpreters/executeQuery.cpp:2630-2655; src/Interpreters/InterpreterSetQuery.cpp:90-93; src/Interpreters/InterpreterUseQuery.cpp:18-27; src/Interpreters/Access/InterpreterSetRoleQuery.cpp:32-37; src/Interpreters/InterpreterCreateQuery.cpp:2960-2964] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/112816#discussion_r3767347726] The feature is documented as safe to enable at the user/profile level, but once it is enabled there, every TCP/HTTP query goes down the detached path before any AST-level compatibility check. Session-bound commands such as SET, USE, SET ROLE, and CREATE TEMPORARY TABLE either fail asynchronously or mutate only the detached copy, so the client gets an immediate success for a command that never affects the session. Either reject these query kinds synchronously before dispatch, or stop advertising user/profile-level enablement.
  • [src/Server/TCPHandler.cpp:2679-2685] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/112816#discussion_r3799004691] TCPHandler still chooses detached vs session-attached context from passed_settings[run_query_in_background] before applySettingsChanges loads packet-level profile and other late overrides. A raw native client that sends profile=bg_profile or profile=fg_profile can still get the wrong context type, leading either to A background query context must not be attached to a session or to foreground execution on a detached context. The native path needs the same "temporary context, then decide" flow that the HTTP path now uses.
  • [src/Interpreters/executeQuery.cpp:2646-2653] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/112816#discussion_r3706577778] The streamed-data guard still only inspects ASTInsertQuery, so plain queries that read from input() can be scheduled in background mode even though background TCP queries never install setInputInitializer or setInputBlocksReaderCallback. The client gets a success response and the worker fails later. Reject any query tree that reads from input() before scheduling.
Tests
  • ⚠️ The new stateless coverage does not exercise the still-fragile surfaces above: session temporary tables, native external tables, explicit transactions with throw_on_unsupported_query_inside_transaction = 0, raw-native profile overrides, and plain input() queries. Those are the smallest focused regressions needed once the behavior is fixed.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: reject or preserve session/client-supplied state before returning success (external tables, session temporary tables, session-bound statements, active transactions), derive the native detached/foreground decision from the final effective packet settings, and close the pre-ProcessList admission gap for queued background work. After that, this should still ship as an Experimental Feature, not a stable New Feature.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 421/447 (94.18%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 31, 2026
@mstetsyuk mstetsyuk linked an issue Jul 31, 2026 that may be closed by this pull request
Comment thread src/Interpreters/Session.cpp Resolved
Comment thread src/Server/TCPHandler.cpp Resolved
Comment thread src/Server/TCPHandler.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Interpreters/Session.h Resolved
Comment thread src/Server/TCPHandler.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ffa89f35e with master e654c4469 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 701.98 MiB 698.98 MiB -3.00 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

248 object files changed (+344.55 KiB total), 4 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/Cascades/RuleUtils.cpp.o new 171.60 KiB +171.60 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/Cascades/Rules/ParallelReadImplementatio… 222.70 KiB 61.23 KiB -161.47 KiB (-72.51%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/Cascades/Rules/TwoStageTopN.cpp.o new 107.98 KiB +107.98 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/Cascades/Rules/LocalReadImplementation.c… new 90.19 KiB +90.19 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/Cascades/Optimizer.cpp.o 207.19 KiB 290.14 KiB +82.95 KiB (+40.04%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/Cascades/Rules/ReplicatedReadImplementat… new 82.20 KiB +82.20 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/Cascades/Rules/TopNImplementation.cpp.o 140.55 KiB 106.07 KiB -34.48 KiB (-24.53%)
src/CMakeFiles/dbms.dir/Server/HTTPHandler.cpp.o 791.01 KiB 820.54 KiB +29.54 KiB (+3.73%)
src/CMakeFiles/dbms.dir/Interpreters/executeQuery.cpp.o 950.92 KiB 975.22 KiB +24.30 KiB (+2.56%)
src/CMakeFiles/dbms.dir/Interpreters/ContextTimeSeriesTagsCollector.cpp.o 441.16 KiB 421.89 KiB -19.27 KiB (-4.37%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/Cascades/Task.cpp.o 212.21 KiB 196.00 KiB -16.21 KiB (-7.64%)

738 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1637 translation units recompiled, 10285 s compile time in total, 1634 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Processors/QueryPlan/Optimizations/Cascades/RuleUtils.cpp: 9.7 s
  • src/Processors/QueryPlan/Optimizations/Cascades/Rules/ReplicatedReadImplementation.cpp: 9.1 s
  • src/Processors/QueryPlan/Optimizations/Cascades/Rules/LocalReadImplementation.cpp: 9.1 s

Job report

Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Server/HTTPHandler.cpp Resolved
@mstetsyuk
mstetsyuk requested a review from evillique August 17, 2026 16:17
Comment thread src/Server/TCPHandler.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
auto background_context = Context::createCopy(context);
background_context->makeQueryContext();

context->getBackgroundQueryPool().scheduleOrThrow([query_text = String(query), background_context]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is it possible at this point for the context->getBackgroundQueryPool() to return nullptr due to concurrent shutdown?

@mstetsyuk mstetsyuk Aug 18, 2026 •

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.

It seems not.

Before setting the pointer to null in the context, on shutdown, we do:

global_context->getBackgroundQueryPool().finish();
bool joined_background_queries = global_context->getBackgroundQueryPool().waitUntil(shutdown_deadline);
if (!joined_background_queries)
{
    safeExit(0, LeakCheck::SkipAndReport);
}

And servers are started after the SCOPE_EXIT_SAFE scope is created. So there's no window between the servers being started and the scope being defined where an exception could be thrown to break this invariant.

if (detached && session_context)
{
query_context->setCurrentRoles(session_context->getCurrentRoles());
query_context->setSettings(session_context->getSettingsRef());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks like we can override at least the setting constraints set with a SET command inside the session like this:

-- setup, once (as a user who can manage access)
CREATE SETTINGS PROFILE strict SETTINGS max_result_rows = 10 CONST;

-- in the session
SET profile = 'strict';

-- foreground: rejected
SELECT 1 SETTINGS max_result_rows = 999;
--> SETTING_CONSTRAINT_VIOLATION

-- background: accepted, constraint bypassed
SELECT 1 SETTINGS max_result_rows = 999, run_query_in_background = 1;
--> succeeds; system.query_log shows Settings['max_result_rows'] = '999'

Maybe something like this makes sense?

Suggested change
query_context->setSettings(session_context->getSettingsRef());
/// Carry over the session's profiles, so their constraints come along; setSettings below copies only values.
for (const auto & profile_id : session_context->getSettingsConstraintsAndCurrentProfiles()->current_profiles)
query_context->setCurrentProfile(profile_id, /* check_constraints= */ false);
query_context->setSettings(session_context->getSettingsRef());

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.

Indeed, good catch

@mstetsyuk
mstetsyuk requested a review from evillique August 18, 2026 22:53
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 82fd9f51-12c7-4587-b539-092bfdf81f6a
  • MIRAI run: 8bbb5079-567b-4dd5-a287-021adbbd3287
  • PR check IDs:
    • clickbench_74152_1787132768
    • clickbench_74159_1787132768
    • clickbench_74168_1787132768
    • tpch_adapted_1_official_74176_1787132768
    • tpch_adapted_1_official_74195_1787132768
    • tpch_adapted_1_official_74223_1787132768

@mstetsyuk
mstetsyuk enabled auto-merge August 19, 2026 11:39
@mstetsyuk mstetsyuk added the hold Skip for auto-updating. label Aug 19, 2026
@mstetsyuk
mstetsyuk added this pull request to the merge queue Aug 19, 2026
Merged via the queue into master with commit 8a4c746 Aug 19, 2026
176 of 177 checks passed
@mstetsyuk
mstetsyuk deleted the run-query-in-background branch August 19, 2026 13:58
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 19, 2026
pull Bot pushed a commit to peijunlin2008/ClickHouse that referenced this pull request Sep 6, 2026
This is introduced in v26.8.

As a part of this PR.
ClickHouse#112816

We made some design and implementation tradeoff to make progress on this
feature. Which makes it not super intuitive to use it.

This doc clarifies some of the nuances

Signed-off-by: Kaviraj <[email protected]>
leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Oct 13, 2026
04665 is claimed by two live open PRs (ClickHouse#112846, ClickHouse#112849). The collision is
silent: the filenames differ so git reports no conflict, and
check_gaps_in_tests_numbers only rejects gaps of 100 or more, never
collisions. 04666, 04670, 04674 and 04675 are claimed too, by ClickHouse#112816,
ClickHouse#112458 and unpublished branches respectively.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hold Skip for auto-updating. pr-feature Pull request with new product feature 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.

Allow interactive queries finish in the background

3 participants