Skip to content

Use Silk fibers in QueryRunner - #111275

Closed
mstetsyuk wants to merge 20 commits into
masterfrom
query-runner-silk
Closed

mstetsyuk wants to merge 20 commits into
masterfrom
query-runner-silk

Conversation

@mstetsyuk

@mstetsyuk mstetsyuk commented Jul 21, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

Silk fibers can now be used in QueryRunner in cluster mode, which means that the ClickHouse server process does not occupy OS threads while waiting for remote clusters to execute QueryRunner's queries - which is important in workloads where QueryRunner has a lot of pending queries.


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

@mstetsyuk
mstetsyuk marked this pull request as draft July 21, 2026 18:50
@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [68f43cc]

Summary: ✅


AI Review

Summary

Adds a Silk fiber scheduler for cluster-mode QueryRunner, a dedicated remote executor, and pending-query and connection limits. Existing-table compatibility and per-query settings regressions remain. The five findings below were rechecked against the current implementation; the author dismissed them, so they are retained here without additional inline comments.

Findings

❌ Blockers

  • src/Storages/StorageQueryRunner.cpp:864 — Existing tables discard previously admissible queries. [dismissed by author -- https://github.com/Use Silk fibers in QueryRunner #111275#discussion_r4264440653] max_queue_size now aliases a total pending limit, but previously excluded running queries. With threads = 1, max_queue_size = 1, a running query plus one queued query previously fit; the second query is now discarded while its submitting INSERT succeeds. Preserve the old admission semantics for existing metadata/defaults and distinguish an explicitly selected pending limit.

⚠️ Majors

  • src/Storages/StorageQueryRunner.cpp:321 and :743 — Row timeout overrides no longer control dispatch. [dismissed by author -- https://github.com/Use Silk fibers in QueryRunner #111275#discussion_r4376979057] Both connection acquisition and execution use the submitting INSERT's settings instead of the effective job settings. A row that raises receive_timeout can consequently time out early; lowering it no longer bounds the wait. Derive timeouts from the job context, as before.

  • src/Storages/StorageQueryRunner.cpp:785 — Initiator logging ignores row overrides. [dismissed by author -- https://github.com/Use Silk fibers in QueryRunner #111275#discussion_r4376979071] A job with settings = {'log_queries': '0'} is still logged locally when the submitting INSERT enables logging. Duration/type filters and log_query_settings likewise use the wrong settings. Restore the effective job settings for logging controls and formatting.

  • src/Storages/QueryRunnerSettings.cpp:23 — Existing thread-scheduled tables lose connection capacity. [dismissed by author -- https://github.com/Use Silk fibers in QueryRunner #111275#discussion_r3625091667] The new default of 100 replaces the inherited distributed_connections_pool_size (normally 1024). Tables configured with more than 100 workers can now block excess workers on the pool. Preserve the inherited limit unless the new engine setting is explicitly supplied.

  • src/Storages/StorageQueryRunner.cpp:944 — Submission work grows with the whole backlog. [dismissed by author -- https://github.com/Use Silk fibers in QueryRunner #111275#discussion_r4230330243] Every submission scans every retained future while holding the common inserter mutex. Building a backlog of N unfinished jobs therefore performs approximately N²/2 probes and serializes inserters. This remains a scaling concern for the advertised large-backlog workload, especially with an unlimited pending limit; its practical cost has not been measured. Retire completions without a full scan, or provide measurements establishing acceptable cost at the intended backlog sizes.

Tests
  • ⚠️ Add a focused regression showing that legacy threads = 1, max_queue_size = 1 still admits a running query and one queued query.
  • ⚠️ Cover different submitting and row-level timeout/logging settings for both schedulers.
  • ⚠️ Exercise test_shutdown with scheduler = 'fibers', including active queries and jobs waiting for a connection. It currently exercises only the default thread scheduler; successful dispatch and waiting tests do not establish cancellation and cleanup behavior.
Missing context / blind spots
  • ⚠️ No local server binary or configured build was available, so these conclusions rely on source tracing and existing coverage. The checkout is a CI merge commit; the dispatcher, settings, scheduler, documentation, and integration-test files were verified against PR head 68f43cceaa8090cc5140a5672efc7a1397f40231. Dependency safety was also checked against the merge's newer Silk revision.
Final Verdict

❌ Block. Preserve existing admission capacity, restore effective job timeout/logging settings, and address or substantiate the remaining connection-capacity and backlog-scaling concerns. Add focused regression coverage, including fiber shutdown.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 21, 2026
@mintlify

mintlify Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 26, 2026, 11:35 AM

Comment thread src/Storages/QueryRunnerSettings.cpp Resolved
Comment thread src/Common/SilkFiberScheduler.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 617/658 (93.77%) · Uncovered code

Full report · Diff report

<clickhouse>
<allow_experimental_silk_runtime>true</allow_experimental_silk_runtime>
<silk>
<!-- Fiber stack size in bytes. The default (320 KiB) leaves enough room for OpenSSL handshakes. -->

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this is insane! can we patch OpenSSL code maybe?..

Comment thread src/Common/StackfulCoroutine.h Resolved
Comment thread src/Common/SilkFiberScheduler.cpp Resolved
CheSema added a commit that referenced this pull request Jul 24, 2026
…e a pointer swap

Adopt the mechanism from #111275: each fetch step creates a ThreadStatus
(the new `NoOSThreadTag` flavor - `thread_id = NO_OS_THREAD`, with
`boundToOSThread` gates skipping the query profiler, taskstats counters
and the group's OS-thread bookkeeping) and attaches it to the submitter's
group once per step. The fiber-switch hooks reduce to a single
`std::swap` of `current_thread` with the slot in the fiber's job header -
measured 9.3 us -> 57 ns per switch - and they no longer construct or
attach anything, which also removes the ThreadGroup mutex from the
switch path.

`ThreadStatus.{h,cpp}`, `ThreadStatusExt.cpp` and
`ThreadGroupSwitcher.{h,cpp}` are adopted from #111275 nearly verbatim
(four of the five post-images byte-identical) so the eventual merge
resolves cleanly by taking upstream.
CheSema added a commit that referenced this pull request Jul 27, 2026
…e a pointer swap

Adopt the mechanism from #111275: each fetch step creates a ThreadStatus
(the new `NoOSThreadTag` flavor - `thread_id = NO_OS_THREAD`, with
`boundToOSThread` gates skipping the query profiler, taskstats counters
and the group's OS-thread bookkeeping) and attaches it to the submitter's
group once per step. The fiber-switch hooks reduce to a single
`std::swap` of `current_thread` with the slot in the fiber's job header -
measured 9.3 us -> 57 ns per switch - and they no longer construct or
attach anything, which also removes the ThreadGroup mutex from the
switch path.

`ThreadStatus.{h,cpp}`, `ThreadStatusExt.cpp` and
`ThreadGroupSwitcher.{h,cpp}` are adopted from #111275 nearly verbatim
(four of the five post-images byte-identical) so the eventual merge
resolves cleanly by taking upstream.

(cherry picked from commit c512b6b)
@mstetsyuk
mstetsyuk force-pushed the query-runner-silk branch from 382ed37 to a7a213e Compare July 30, 2026 21:33
@mstetsyuk
mstetsyuk changed the base branch from master to silk-integration July 30, 2026 21:33
@mstetsyuk

Copy link
Copy Markdown
Member Author

Silk integration into the code base is continued in a separate PR: #112667

Base automatically changed from silk-integration to master August 26, 2026 11:23
@clickhouse-gh clickhouse-gh Bot added the comp-special-table-engines Non-MergeTree table engines used to speed up/distribute execution (paper's 2nd category). label Sep 4, 2026
# Conflicts:
#	src/Storages/StorageQueryRunner.cpp
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Common/SilkFiberScheduler.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/Common/SilkFiberMutex.h Resolved
Comment thread src/Common/SilkFiberMutex.h Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Core/SettingsEnums.h Outdated
Comment on lines +462 to +466
enum class QueryRunnerScheduler : uint8_t
{
FIBERS,
THREADS,
};

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.

Can we make this more generic? I'd need something like this in backups

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.

I think WorkerKind works ok, wdyt?

job_context->setUser(*job.origin->user_id, job.origin->external_roles, job.origin->authentication_grants, job.origin->authentication_valid_until);
}
if (job.origin->roles)
if (job.origin->user_id && job.origin->roles)

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.

why?

@mstetsyuk mstetsyuk Oct 16, 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.

There's a very narrow edge case - I think it was flagged by AI code review at some point.

TLDR: with SQL SECURITY INVOKER and user_id = std::nullopt and roles = std::optional(std::vector<...>{}) (e.g. in startup scripts), we satisfy the original if and call setCurrentRoles, which throws a logical error.

Comment on lines +813 to +815
catch (...)
{
futures.pop_back();

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.

do we expect any other exceptions here? Does silk throw?

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.

Only CANNOT_SCHEDULE_TASK, Silk does not throw.

Comment thread src/Client/MultiplexedConnections.h Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
@mstetsyuk

Copy link
Copy Markdown
Member Author

We can just run queries with run_query_in_background=1. So the "with N queries, how do we wait for 3 * N extra queries (one for each of ASan + UBSan, TSan, MSan builds), which are 2-5x slower, without tying up too many threads (with N = 100, the number of threads is ~~900)" problem no longer exists.

@mstetsyuk mstetsyuk closed this Oct 27, 2026
@clickhouse-gh clickhouse-gh Bot added comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... and removed comp-special-table-engines Non-MergeTree table engines used to speed up/distribute execution (paper's 2nd category). labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants