Skip to content

Introduce the QueryRunner table engine - #107888

Merged
mstetsyuk merged 27 commits into
masterfrom
query-runner
Jul 9, 2026
Merged

mstetsyuk merged 27 commits into
masterfrom
query-runner

Conversation

@mstetsyuk

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):

Introduce the QueryRunner table engine. Records inserted into a QueryRunner table represent queries that the engine executes. The engine can be used for asynchronous query execution, batch execution of generated queries, directing queries to remote clusters, benchmarks, fuzzing, and testing with shadow traffic.

@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0df265d]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel, 2/3) FAIL
Server died FAIL cidb
02527_storage_merge_prewhere_different_type UNKNOWN cidb
03915_exchange_tables_race UNKNOWN cidb
03653_fractional_limit_offset UNKNOWN cidb
03231_csv_dont_infer_bool_from_string UNKNOWN cidb
03825_exists_constant_folded_action_name UNKNOWN cidb
01383_log_broken_table UNKNOWN cidb
Unknown error FAIL cidb
Unit tests (asan_ubsan) FAIL
ThreadPoolCallbackRunner.DroppedSynchronouslyWhileAttachedToAnotherGroup FAIL cidb
AllTests FAIL cidb
Unit tests (tsan) FAIL
ThreadPoolCallbackRunner.DroppedSynchronouslyWhileAttachedToAnotherGroup FAIL cidb
AllTests FAIL cidb
Unit tests (msan) FAIL
ThreadPoolCallbackRunner.DroppedSynchronouslyWhileAttachedToAnotherGroup FAIL cidb
AllTests FAIL cidb
Unit tests (amd_llvm_coverage) FAIL
ThreadPoolCallbackRunner.DroppedSynchronouslyWhileAttachedToAnotherGroup FAIL cidb
AllTests FAIL cidb
LLVM Coverage DROPPED

AI Review

Summary

This PR introduces the QueryRunner table engine, the discard_query_data TCP setting, and SYSTEM WAIT QUERY RUNNER. I don't think the current head is mergeable yet: there are still two self-deadlock paths in normal usage, SQL SECURITY DEFINER regresses for non-UUID databases, and cluster-mode row settings still bypass the initiator's own settings constraints.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterSystemQuery.cpp:2148] SYSTEM WAIT QUERY RUNNER can deadlock when a QueryRunner worker runs it against its own table. waitForQueriesToFinish waits for every issued seq, including the caller's current job, but that seq is retired only after the query returns, so INSERT INTO runner VALUES ('SYSTEM WAIT QUERY RUNNER runner') wedges permanently. Suggested fix: reject self-waits from the same dispatcher or teach PrefixLatch / waitForQueriesToFinish to exclude the caller's in-flight seq.
  • [src/Storages/StorageQueryRunner.cpp:722] Synchronous local jobs can still deadlock by writing back into the same table. A worker executing INSERT INTO runner VALUES ('SELECT 1') on a mode = 'synchronous' table enqueues the nested job and then waits on batch->wait, but the nested job cannot start until the current worker returns, so even threads = 1 wedges the table. Suggested fix: detect reentrant synchronous writes to the same dispatcher and reject them (or run them outside the bounded worker pool), with a regression test.
  • [src/Access/DefinerDependencies.cpp:27] [dismissed by author -- https://github.com/Introduce the QueryRunner table engine #107888#discussion_r3515661265] Skipping every UUIDHelpers::Nil object regresses SQL SECURITY DEFINER safety for Memory and Ordinary databases: DROP USER now succeeds while dependent views / QueryRunner tables still exist, and the PR even adds test_definer_not_tracked_without_table_uuid to lock that behavior in. Those objects later fail when they try to resolve the missing definer, so this is not just an acceptable "deprecated database" corner. Suggested fix: keep the full StorageID, or at least fall back to a name-based key when uuid is Nil.

⚠️ Majors

  • [src/Storages/StorageQueryRunner.cpp:447] [dismissed by author -- https://github.com/Introduce the QueryRunner table engine #107888#discussion_r3474417929] Cluster-mode row settings skip local constraint checks but are still applied to the initiator-side context. That lets an inserter choose source-side log_queries, log_queries_min_type, and TCP timeouts outside their own profile, including suppressing the initiating server's audit row or stretching failover waits far beyond local limits. The destination cluster only validates what it receives after the query is already being dispatched, so it cannot enforce the initiator's constraints. Suggested fix: validate source-side-affecting settings under the inserter's context before applying them, or split remote-query settings from initiator-only settings.
  • [src/Interpreters/InterpreterCreateQuery.cpp:2867] [dismissed by author -- https://github.com/Introduce the QueryRunner table engine #107888#discussion_r3473781817] processSQLSecurityOption clones CURRENT_USER ephemeral definers before StorageQueryRunner rejects SQL SECURITY in cluster mode. CREATE TABLE ... ENGINE = QueryRunner SETTINGS cluster = 'c' DEFINER = CURRENT_USER SQL SECURITY DEFINER therefore fails after inserting <user>:definer, leaving an orphan access entity even though the table was never created. Suggested fix: validate engine-level SQL-security restrictions before cloning ephemeral definers, or roll the cloned user back on constructor failure.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: fix the two self-deadlock paths, restore safe definer dependency handling for non-UUID databases (or reject SQL SECURITY DEFINER there), enforce the initiator's settings constraints before cluster-mode row settings are applied, and avoid leaving cloned ephemeral definers behind on rejected CREATE.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 18, 2026
@mstetsyuk mstetsyuk linked an issue Jun 18, 2026 that may be closed by this pull request
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
mstetsyuk and others added 2 commits June 22, 2026 18:06
Resolved conflicts:
- src/Server/TCPHandler.cpp: kept the branch's discard_query_result gate;
  dropped the obsolete allow_experimental_query_deduplication / sendPartUUIDs
  block that master removed.
- src/Storages/StorageView.cpp, src/Storages/StorageMaterializedView.cpp:
  kept the branch's DefinerDependencies rename over master's local metadata
  variable refactor in drop().

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Server/TCPHandler.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
@mintlify

mintlify Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 7, 2026, 4:41 PM

@mstetsyuk

mstetsyuk commented Jul 9, 2026 •

Copy link
Copy Markdown
Member Author

@groeneai, please confirm that none of the CI failures is due to this PR's changes. I've checked myself, but I need 100% confidence.

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

@mstetsyuk Confirmed: none of the failing checks at HEAD (0df265d) are caused by this PR.

There are two distinct real failures, both pre-existing trunk issues:

1. Unit tests (asan_ubsan / msan / tsan / amd_llvm_coverage) — ThreadPoolCallbackRunner.DroppedSynchronouslyWhileAttachedToAnotherGroup
Fresh trunk flaky: 220 failures across 41 distinct PRs incl. 18 on master, all clustered on 2026-07-08 (CIDB, 30d). This PR touches no ThreadPool/ThreadGroup/callback-runner code (only a 1-line setThreadName.h addition + 3 CurrentMetrics.cpp entries), so it cannot cause this gtest.

2. Stateless tests (amd_llvm_coverage, old analyzer, ... 2/3) — "Server died"
LOGICAL_ERROR abort in the old-analyzer partial-result path: SELECT n * 0.123 FROM (SELECT * FROM tbl_03007_1) -> MultiplyImpl with Int256 * Float64 mismatch in ActionsDAG::evaluatePartialResult -> updateHeader -> InterpreterSelectQuery. The abort log contains zero QueryRunner frames, and the query belongs to 03915_exchange_tables_race. This evaluatePartialResult LOGICAL_ERROR family is trunk-wide: 424 failures / 197 PRs / 66 on master (30d).

Mergeable Check / PR are just red because of the above; CH Inc sync is the private internal sync, not actionable here.

Your own new tests pass at HEAD across all builds: 04337_query_runner (1907 OK), 04336_discard_query_data, 04335_create_table_sql_security_unsupported, and integration test_query_runner (454 OK). Their earlier FAILs in CIDB are all on older commits (<= e2118a7, 2026-07-02), not 0df265d.

@mstetsyuk
mstetsyuk added this pull request to the merge queue Jul 9, 2026
Merged via the queue into master with commit 9a10e05 Jul 9, 2026
169 of 175 checks passed
@mstetsyuk
mstetsyuk deleted the query-runner branch July 9, 2026 09:57
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 9, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @mstetsyuk — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently missing):

  • Why: The PR body is essentially the template comment block plus the claimed changelog category — it does not explain the engine's semantics, the new discard_query_data setting, the SQL SECURITY validation change affecting all engines, or the ViewDefinerDependencies->DefinerDependencies rename. A reviewer must reconstruct the whole design from the diff.

  • Suggested addition:

    Summarize: (1) the QueryRunner engine executes inserted rows as queries locally or on a cluster shard in fire-and-forget mode (settings cluster/shard/mode/threads/max_queue_size; SQL SECURITY INVOKER/DEFINER/NONE for local mode); (2) the new query-level discard_query_data setting suppresses result rows over native TCP for the initial query; (3) SQL SECURITY is now rejected on engines that don't support it (previously silently ignored); (4) ViewDefinerDependencies was generalized to DefinerDependencies (keyed by UUID) so QueryRunner definer tables are also protected from user DROP.

Ignore this if the current title/body is intentional.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Introduce the `QueryRunner` table engine
zoomxi pushed a commit to zoomxi/ClickHouse that referenced this pull request Nov 16, 2026
…tions

With `async_socket_for_remote = 0`, `RemoteQueryExecutor::read` releases
`was_cancelled_mutex` before `connections->receivePacket()` (since
58718f2 in ClickHouse#107888, which fixed a livelock on detach). When `LIMIT`
closes the port, `RemoteSource::onUpdatePorts` calls `finish()` on another
executor thread, and its drain loop reads `hasActiveConnections()` without a
lock while the reader's `receivePacket()` decrements `active_connection_count`
on `EndOfStream` under `cancel_mutex` only. TSan reports it as STID 4761-4859
(Stress test (amd_tsan)). The comment that justified the lock-free accessor
("sendCancel() does not change the state of the replicas") did not cover this
writer. `HedgedConnections` has the same accessor and the same writer
(`finishProcessReplica`).

Make the top-level counter `std::atomic<size_t>` in both classes. This only
makes the existing lock-free read defined: no value changes, because the
counter just guards the drain loop and the next `receivePacket()` re-checks it
under `cancel_mutex` and returns `EndOfStream` once the query is cancelled.
`HedgedConnections::OffsetState::active_connection_count` stays a plain
`size_t`: it is never read by `hasActiveConnections()`.

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

This branch was successfully deployed

1 active deployment
staging - docs — 0df265d3 Deployed Jul 8, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Table engine QueryRunner

5 participants