Skip to content

Fix hangs of distributed INSERT, GLOBAL IN / GLOBAL JOIN and file() reads in a workload with few CPU slots - #126572

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:cpu-lease-nested-and-distributed-insert
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:cpu-lease-nested-and-distributed-insert

Conversation

@groeneai

@groeneai groeneai commented Oct 18, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117711
Related: #126336

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a hang of INSERT into Distributed tables and remote(), of GLOBAL IN / GLOBAL JOIN over them, and of queries reading file(), in a workload with fewer CPU slots than the query needs at once (for example max_concurrent_threads = 1): a thread that waits for another pipeline of its query now parks its CPU slot, and a nested pipeline runs on the slot of its thread instead of taking a second one.

Description

On 26.10.2.9, with CREATE RESOURCE cpu (MASTER THREAD, WORKER THREAD) and a workload with max_concurrent_threads = 1, INSERT INTO <Distributed> SELECT ... and INSERT ... FORMAT Native into it run until max_execution_time; master also hangs for remote(), SELECT ... FROM file() with max_threads = 1, and GLOBAL IN / GLOBAL JOIN over remote() or Distributed.

Four holders keep their executor's CPU slot while blocked: DistributedSink waiting for its writing jobs; a writing job's executor idle between blocks; RemoteInserter::onFinish waiting for the shard's EndOfStream; the shard's TCPHandler waiting for the next packet. A nested executeUntil executor (writeToLocal of a background insert, the reader of file(), CreatingSetsTransform filling a GLOBAL IN set) took a second slot on a thread whose outer lease was running. This PR parks the lease around those waits (as #117711 does for I/O), runs a nested executeUntil executor on its caller's lease, renewing it at its own processor boundaries, and keeps the published lease private to the coroutine sending GLOBAL IN tables.

Merge after #126336: each park/unpark otherwise extends a lease by a quantum (#126133). With max_cpus = 0.5: a 20M-row distributed insert uses 1.03-1.12 CPU with this PR alone and 0.56 with #126336 (master with #126336: 0.54); a file() read parsed on the query thread runs at 0.51 instead of 0.39.

Validation: the new test times out on master and passes 50/50 with random settings; each of the five changes has a query that hangs without it. No slowdown above noise in an 8-slot workload or without one.

Not covered: max_threads above the workload's slots (#126512); INSERT ... SELECT into a local table with the default async_insert = 1 and multi-threaded shard inserts (both wait in PushingAsyncPipelineExecutor, a separate fix); nested executors run with execute(); a writing job blocked in RemoteInserter::write on a full socket.


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

groeneai and others added 4 commits October 18, 2026 02:11
In a workload with fewer CPU slots than an `INSERT` into `Distributed` /
`remote()` or a `file()` read needs at once (e.g. `max_concurrent_threads = 1`),
the query hung until `max_execution_time`: a lease that cannot progress keeps
its slot, so the pipeline it waits for never gets one.

- A nested `executeUntil` executor that starts inside another executor's step
  on the same thread (`writeToLocal` of a background insert, the reader of
  `file()` and other sources) runs on that step's lease (`GrantedAllocation`,
  the outer lease stays published), instead of taking a second slot on the
  same thread. Its CPU is reported once, by the outer lease.
- `DistributedSink` parks the inserting thread's lease while it waits for the
  writing jobs (`waitForPool`), and a writing job's executor stays parked while
  the job is idle in the pool between blocks (new `IExecutor` /
  `PushingPipelineExecutor` park API; `executeUntil` unparks on entry, the
  destructor unparks before the release).
- `RemoteInserter::onFinish` parks while it waits for the shard's EndOfStream.
- `TCPHandler` publishes the 1-thread insert executor's lease while it receives
  the next packet and parks it only around the blocking poll.

Each park scope contains only a wait, never CPU work of the lease's pipeline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`GLOBAL IN` / `GLOBAL JOIN` fill their external table by a nested
`PushingPipelineExecutor` (`CreatingSetsTransform`) on the planning thread, so
on master both queries wait for a second CPU slot until `max_execution_time`.
Sized on a release build of master: 10M rows in the subquery hang 5/5, 5M do
not; the test uses 15M. Without the nested-executor change both hang 3/3.

Also write the `TCPHandler` lease publication as an optional `ScopedCPULease`
(same scope, no behaviour change).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The CI profile tests/config/users.d/limits.yaml sets max_rows_to_read
to 20M. The initiator of Q6/Q7 counts 30.1M rows (the 15M-row
subquery, the same rows again when the shard reads the external table
back, and 100k), so both queries failed with TOO_MANY_ROWS in every
lane. A query-level max_rows_to_read = 0 overrides the profile; master
still hangs on both queries with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove a comment duplicating the runs_on_caller_lease field comment and one narrating the TCPHandler receive lambda.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; round 1 on 727d656d24ef: 1 finding; rounds 2 and 3 on bbe3eeaae822 and 2eb1b0a55fcb: 0 findings) plus my own cold review (round 1: 2 major, 3 nits; round 2: 1 major; round 3: 1 blocker found by the round-2 lane runs; round 4: 0 findings).

# Sev Finding Verdict Evidence / action
1 ❌ The test does not run the promised GLOBAL IN / GLOBAL JOIN AGREE Added in bbe3eeaae822: 15M-row subquery, hangs 5/5 on master and 3/3 without the nested-executor change, passes 5/5 with it.
2 ❌ A writing job blocked on a full socket keeps its slot; the earlier probe could not fill the socket AGREE Re-measured up to 80M rows: the initiator spent at most 0.21 s in send (the shard keeps up), so the send never blocks; no change, listed under "Not covered".
3 ❌ The new test was proven only in the default CI flavour AGREE Ran with the CI server configs of the default, distributed plan, DBReplicated, s3 storage, ParallelReplicas and AsyncInsert lanes: no lane-specific failure, but it exposed row 7.
4 ⚠️ Test runtime vs max_execution_time = 60 on slow builds DISAGREE The whole test takes 2.3-3.9 s on a debug build, randomized.
5 💡 TCPHandler lambda repeats one call in both branches AGREE Simplified.
6 💡 Cross-thread lease release can trip a debug chassert on a timed-out insert noted-not-blocking Not introduced here; only reachable after a timeout.
7 ❌ The GLOBAL IN / GLOBAL JOIN queries exceed the CI profile's max_rows_to_read (20M): the initiator counts 30.1M rows, TOO_MANY_ROWS in every lane AGREE Fixed in 2eb1b0a55fcb: max_rows_to_read = 0 on those two queries; 50/50 under the CI profile and 10/10 in each lane configuration above; master still hangs on both with it.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 1-slot workload, INSERT INTO FUNCTION remote('127.0.0.2', t) SELECT number FROM numbers(5000000) SETTINGS workload = 'w1', max_threads = 1, async_insert = 0: Code 159 at 10.1 s 5/5 on master; the new test fails 2/2 on master (timeout at its first query).
b Root cause explained? Each executor has its own CPU lease; a lease that waits (initiator for its writing jobs, an idle writing job, onFinish for EndOfStream, the shard's TCPHandler for the next packet) keeps its slot, and a nested executeUntil executor took a second slot on a thread whose outer lease was running, so the pipeline being waited for never got a grant.
c Fix matches root cause? Yes. Each wait parks the lease only around the blocking call, and a nested executor runs on its caller's lease. No timeout, no widened limit.
d Test intent preserved / new tests added? New test 05406_cpu_lease_park_nested_and_distributed_insert: seven queries (incl. GLOBAL IN and GLOBAL JOIN over remote()); each of the five changes has a query that hangs without it (measured ablations).
e Both directions demonstrated? Yes. Master: every query times out; fix: 50/50 randomized under the CI server profile and 10/10 in each of the distributed plan, DBReplicated, s3 storage, ParallelReplicas and AsyncInsert configurations; each single-change ablation hangs its query 3/3.
f Fix is general across code paths? The nested-executor change is in PipelineExecutor::executeUntil, so it covers every nested user (writeToLocal, file/url/object-storage readers, CreatingSetsTransform: GLOBAL IN / GLOBAL JOIN over remote()/Distributed measured, hang on master 5/5, fixed 5/5, hang again 3/3 without this change; StorageBuffer flush); all four pool->wait() sites of DistributedSink park. Not covered: async executors and max_threads above the slot count (separate PRs).
g Fix generalizes across inputs (params/datatypes/wrappers)? No data/type dependence. Measured: both distributed_foreground_insert values, prefer_localhost_replica 0/1, INSERT SELECT and client data, 1-slot / 8-slot / no workload. With cpu_slot_parking = 0 or no CPU resource, park returns false and nothing changes.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or protocol change.
i Invariants and contracts preserved? A step never runs on a parked lease (executeUntil unparks first), a parked lease is unparked before release, parks equal unparks per query; new lock edges are only caller lock -> lease mutex; the nested step never renews the outer lease, so preemption cannot pop the outer thread's running task.

Session id: cron:clickhouse-impl-self-slot-57:20261018-054400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @serxa @devcrafter, could you review this and add the can be tested label so CI runs? It parks the CPU lease while a distributed insert waits for another pipeline of the query (DistributedSink waiting for its jobs, an idle job executor, RemoteInserter::onFinish, the shard's TCPHandler between packets) and runs a nested executeUntil executor on its caller's lease, so a 1-slot workload no longer hangs; it should go in after #126336.

@clickhouse-gh

clickhouse-gh Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [27064c7]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, parallel) FAIL
04034_autopr_min_rows_per_replica_reuses_index_analysis FAIL cidb

AI Review

Summary

PR #126572 parks CPU leases around inter-pipeline waits and lets nested pipelines share their caller's lease. Review of head 27064c760b0be520c63569381e1b81d2b8700d28 found one remaining resource-accounting regression: cancelling the outer query can leave nested work running without CPU throttling. Changes are required before merge.

Findings

❌ Blockers

  • PipelineExecutor.cpp:147–148 — Shared-lease shutdown is ignored. Outer cancellation frees the CPU allocation. CPULeaseAllocation::renew then returns false and resets the lease, but renewInTask discards that result and nested renewal reports success. An inner pipeline without a process-list element, such as the aggregation inside LoopSource, continues with subsequent renewals doing nothing. This violates the workload's CPU limit. Propagate shutdown and unwind/cancel the nested execution. Inline finding.

    An isolated ARM release run under max_cpus = 0.1 consumed 0.44 CPU-seconds over three seconds before KILL QUERY, then 3.08 afterward while still active with is_cancelled = 1. Disabling cpu_slot_parking kept the control throttled: 0.43 before / 0.41 after. Delayed cancellation occurs in both runs; losing throttling is the regression introduced by sharing the lease.

Tests
  • ⚠️ Add a focused stateless cancellation regression for a long nested aggregation. Cancel while it is renewing/preempted and verify that nested execution stops rather than continuing on a revoked lease. The existing completion/preemption tests do not cover allocation shutdown.
Missing context / blind spots
  • ⚠️ Runtime reproduction used revision 81c3852d1a6d16fc20c99939015a619c05e34d55; the implicated renewal/shutdown code is unchanged at the reviewed head. Repeat the regression against the fixed head.
  • ⚠️ The head CI report is still running, with 107 jobs pending, including release builds, unit tests and flaky checks. Completed results are needed to validate the latest coroutine-local change.
Performance & Safety

Keep the declared merge prerequisite on PR #126336. The description reports that repeated parking otherwise exceeds max_cpus: a distributed insert configured for 0.5 CPU consumes 1.03–1.12 CPU with this PR alone. This is an acknowledged dependency, not an additional inline finding.

Final Verdict

❌ Block. Propagate shared-lease shutdown and add the cancellation regression. Merge PR #126336 first and obtain completed CI results for the final head.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... labels Oct 18, 2026
@serxa serxa self-assigned this Oct 18, 2026
@serxa serxa added the can be tested Allows running workflows for external contributors label Oct 18, 2026
A nested `executeUntil` runs on the lease that the outer executor published
on its thread, but it never renewed it: a long nested call (for example the
aggregation of a view read by `loop`) reported its whole CPU time to the
scheduler only after it returned, so `max_cpus` and `max_burst_cpu_seconds`
did not throttle it and a competing query of a one-slot workload waited for
the whole call.

The nested executor now renews that lease at its own processor boundaries
with `ISlotLease::renewInTask`. It reports the consumption and blocks on
preemption like `renew`, but the thread is inside a task of the outer
executor, so the outer executor is not notified (`ExecutorTasks::preempt`
would hand the running task to another thread) and the thread is never
stopped: a worker that waits longer than the preemption timeout continues on
a borrowed slot, and the outer executor downscales it at its next `renew`.

Measured on a release build, `SELECT * FROM loop(v) LIMIT 1` over a 2.2 s
single-thread aggregation: with `max_cpus = 0.5` it took 2.2 s with 0
preemptions (one 2.13 s report), now 4.2-4.3 s with ~180 preemptions and
~2 ms reports, as on master; in a one-slot workload a 90 ms competing query
waited 1.97 s, now 0.145 s.

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

clickhouse-gh Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 27064c760 with master 02fd3427a (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of c22dc6a90; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

1609 translation units recompiled, 10535 s compile time in total, 1608 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.8 s

Job report

groeneai and others added 4 commits October 18, 2026 23:03
A nested pipeline renews the lease of the outer executor's thread with
`renewInTask`. On a worker thread, a preemption wait that hit
`cpu_slot_preemption_timeout_ms` resumed the thread without a grant, and every
following report could do the same, so the nested work ran far above
`max_cpus` until the call returned. Such a thread now waits for a grant
without a timeout, like the master thread; the outer executor can still
downscale it at its own `renew` after the task.

Measured on a release build with `cpu_slot_preemption_timeout_ms = 1` and a
workload with `max_cpus = 0.1`, `max_burst_cpu_seconds = 1`: one query reads a
1.8 s aggregating view twice through `loop()` with `max_threads = 2`. In runs
where a worker took one of the reads, it used 0.50 CPU for ~3 s (1205-1384
preemptions of ~1 ms on the worker) and then the master stalled ~10 s to repay
it; now the query uses 0.10 CPU in every second after the burst (113
preemptions, the worker waits 23 s for grants).

The new unit test fails without the change: the worker stops waiting after
~3 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
In the sanitizer flaky checks q8 either timed out (asan, 5 of 5: 12.5 s of
CPU in 60 s on an overloaded runner, so 300M rows did not finish) or was
never preempted (tsan, 2 of 20: the thread got less CPU than
`max_cpus = 0.5`, so the limit never applied). The aggregation now reads an
unbounded `numbers()` and stops after 1 s (`timeout_overflow_mode = 'break'`)
under `max_cpus = 0.05`, below what any build gets in that time: 3-6
preemptions on debug and release builds, also with the server's cores
overloaded 5x, and 0 without the nested renewal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`RemoteQueryExecutor` sends external tables from its read context coroutine:
`Connection::sendExternalTablesData` runs a pipeline on the coroutine stack, and
its `WorkloadResources` hides the executor's lease (`current_cpu_lease = nullptr`,
restoring the previous lease on destruction). When the socket is full the
coroutine suspends inside that pipeline, and with a plain `thread_local`:

- the executor thread keeps the hidden (null) lease, so its wait for the shard
  does not park the slot; in a one-slot workload the shard then waits for that
  slot forever (05406 q6 hung to `max_execution_time` in the flaky checks);
- when the query is cancelled, the suspended coroutine is unwound on the
  connection thread, and the destructor writes the executor's lease into that
  thread; the lease is freed with the query, and the next query on the thread
  renews it (segfault in `WorkloadResources::renewCPULease` from
  `TCPHandler::processInsertQuery`, STID 4530-4efa).

Both variables become coroutine-local `FiberLocal` slots, which
`StackfulCoroutine` swaps on resume, suspend and unwind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With random `compile_expressions = 1` and `min_count_to_compile_expression = 0`
the expression is compiled before the aggregation starts. In the asan flaky
check this took 1.07 s (`CompileExpressionsMicroseconds`) of the 1 s time
limit, so the aggregation never ran long enough to be preempted (`05406_q8 1 0`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment on lines +147 to +148
lease->renewInTask(); // The outer executor stops the thread at its own `renew`
return true;

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.

❌ [P1] Propagate shared-lease shutdown to the nested pipeline

Cancelling the outer executor calls ExecutorTasks::finish, which frees its CPU allocation. The next CPULeaseAllocation::renew returns false and resets the lease, but renewInTask discards that result and this branch always returns true. Subsequent renewals do nothing, so the nested pipeline can continue without CPU accounting or throttling until the outer task returns.

This is reachable through the new test's loop over an aggregating view: LoopSource::initLoop constructs the inner QueryPipeline from getPipe without a process-list element, so cancellation of the outer executor does not cancel that inner executor. For example, run this with a query ID in a workload capped having max_cpus = 0.1 and max_burst_cpu_seconds = 0.01, then issue KILL QUERY from another connection:

CREATE VIEW v AS SELECT sum(cityHash64(number)) AS s FROM numbers(100000000000);
SELECT * FROM loop(v) LIMIT 1
SETTINGS workload = 'capped', max_threads = 1,
         compile_expressions = 0, compile_aggregate_expressions = 0
FORMAT Null;

On the ARM release binary for revision 81c3852d (the renewal/shutdown code is unchanged at the current head), server CPU consumption rose from 0.44 CPU-seconds per three seconds before cancellation to 3.08 afterward, while the query remained active with is_cancelled = 1. With cpu_slot_parking = 0, the same control stayed throttled at 0.43 before / 0.41 after. Delayed cancellation already exists in that control; losing CPU throttling is the regression here.

Please propagate allocation shutdown through the in-task renewal and unwind/cancel the nested pipeline, rather than waiting for the outer renewal. Add a focused cancellation regression that verifies the nested work stops and cannot continue on the revoked lease.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@serxa one design decision before I fix the cancellation finding (#126572 (comment)). It is real: after KILL QUERY, SELECT * FROM loop(v) LIMIT 1 (v = SELECT sum(cityHash64(number)) FROM numbers(100000000000), max_threads = 1) in a workload with max_cpus = 0.1 makes the server use 0.96 CPU/s with this PR and 0.14 without it, because the nested pipeline keeps running on the lease that ExecutorTasks::finish has freed.

  1. Continue the nested pipeline on CPU slots of its own, as without this PR. I have this working for one nesting level, but it needs more: with two levels the inner executor keeps its new slot between pulls, so in a one-slot workload its caller can wait for that slot forever. The allocation then has to be parked between calls and give way to a live caller lease, and CPULeaseAllocation::release has to accept a lease released by another thread: master debug already aborts on chassert(thread_time_ns >= lease.last_report_ns) for the query above with max_execution_time = 1, timeout_overflow_mode = 'break', because the unfinished loop() executor is destroyed by the TCPHandler thread.
  2. Cancel the nested pipeline when its lease is revoked. Much smaller, but its caller then sees the nested read end early (loop(), for one, retries such a pass).

Which do you prefer?

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 27064c7

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, parallel) / 04034_autopr_min_rows_per_replica_reuses_index_analysis flaky, not from this PR (it changes CPU lease handling of insert executors): automatic parallel replicas did not engage for query_1 and query_2 (pr_used 0 instead of 1), 7/102 reruns with the same settings failed; also on master and 19 other PRs in the last 30 days #125544 (mine, open)
Mergeable Check, PR praktika rollups of the row above #125544 (the owner of the first row)
Sync - CH Inc sync (private, not actionable by me)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261019-120004

@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Dear @serxa, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@serxa serxa self-assigned this Nov 18, 2026

This branch has not been deployed

No deployments
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 comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants