Skip to content

Dynamic queries spilling based on workloads - #119443

Merged
azat merged 73 commits into
ClickHouse:masterfrom
azat:workload-dynamic-spilling
Oct 14, 2026
Merged

azat merged 73 commits into
ClickHouse:masterfrom
azat:workload-dynamic-spilling

Conversation

@azat

@azat azat commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Based on and includes: #109367

Changelog category (leave one):

  • New Feature

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

Dynamic queries spilling under memory pressure based on workloads. You can set max_memory_before_spill/max_memory_to_spill_ratio in WORKLOAD and once the memory will reach this soft limit it will automatically start memory spilling. It supports memory for ORDER BY/GROUP BY/IN/DISTINCT/JOIN (grace_hash)

Demo

A query with 1GiB of RAM and 50 concurrency, max_memory=16Gi, max_memory_before_spill=8Gi - https://pastila.nl/?00e9fbb6/355bea08815529acab79d9968a7a6643#54K/0It7EjXidz7kEB9Ysg==GCM

  • with spilling - 100% success rate (100 out of 100)
  • without spilling - only 9% success rate (27 out of 282)

Followup

Refs


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

Version info

  • Merged into: 26.10.1.2388-master (included in 26.10 and later)

serxa and others added 19 commits July 3, 2026 21:28
Extend the space-shared memory scheduler with a reclaimable-memory
aggregate and a soft limit that asks queries to spill before the hard
`max_memory` limit forces a kill.

Two new messages extend the existing two-way scheduler/query protocol:
- query to scheduler `IAllocationQueue::setReclaimable(total)` reports the
  portion of an allocation that can be spilled or discarded on request. It
  is clamped to the allocation size, aggregated bottom-up as a new
  `reclaimable` field on every `ISpaceSharedNode` (like `allocated`, via
  `Update::reclaimable_delta`), and is advisory: it never blocks or fails.
- scheduler to query `ResourceAllocation::spillAllocation(at_least)` asks an
  allocation to reclaim memory. It mirrors `killAllocation` (fast, scheduler
  thread, just records the request); the query's later decrease is the
  acknowledgement. `MemoryReservation::spillAllocation` is a no-op for now;
  the query side is wired up in a separate change.

`AllocationLimit` gains a `soft_limit`. When `allocated` exceeds it and the
subtree has reclaimable memory, `checkSoftLimit` selects a victim via
`selectAllocationToSpill` and signals it, one spill at a time (a boolean
guard, cleared on any decrease under the node, when back under the soft
limit, or on detach). With no soft limit configured, or with nothing
reclaimable, behavior is exactly as before (fail-close): the hard limit
remains the sole enforcement mechanism.

Victim selection descends one root-to-leaf path using a reclaimable-filtered
ordered set at each node, kept in the same order as the primary running set,
so the spill victim matches the kill order deterministically (largest usage,
least precedence, largest allocation) and idle/unreclaimable subtrees are
skipped. The sets are intrusive (no allocation in normal operation) and are
maintained on paths that are already O(log N).

`checkSoftLimit` runs from `approveIncrease`/`approveDecrease` and, only when
a reclaimable report is propagated, from `propagateUpdate`. That gate is a
deadlock-avoidance invariant: `reclaimable_delta` originates solely in
`AllocationQueue::processActivation`, which propagates without the queue
mutex held, whereas other propagation paths may hold it and descending into
`selectAllocationToSpill` (which locks the queue) would self-deadlock.

Invariants I1-I8 are documented on `ISpaceSharedNode`. Adds gtests covering
fail-close, largest-first selection, fair descent skipping unreclaimable
subtrees, re-signalling until under the soft limit, and a parametrized
throughput test (`SCHED_PERF_ITERS`).

RFC: ClickHouse#109064

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Wire the `AllocationLimit` soft limit to two new workload settings so the
spill threshold can be configured per workload:

- `max_memory_before_spill` - absolute soft limit in bytes.
- `max_memory_to_spill_ratio` - soft limit as a fraction of this workload's
  own `max_memory` hard limit (ignored when `max_memory` is unlimited).

The effective soft limit is the smaller of the two (unlimited, i.e.
disabled, when neither is set), mirroring how `max_memory` /
`max_memory_ratio` combine for the hard limit. `hasAllocationLimit` now
also returns true when only a soft limit is set, so a workload can spill
without a hard cap (the `AllocationLimit` caps nothing but still signals).

The value flows through `WorkloadSettings::getSoftAllocationLimit` into the
`AllocationLimit` constructor and `updateSemaphore` (via `updateSoftLimit`),
alongside the existing hard-limit wiring.

These settings have no user-visible effect until the query side reacts to
`spillAllocation` (a later change); `MemoryReservation::spillAllocation` is
still a no-op. User-facing documentation is added together with that
reaction to avoid documenting a setting that does nothing end to end.

Adds gtests: the absolute and ratio settings each drive a spill signal with
the expected `at_least` amount.

RFC: ClickHouse#109064

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Replace the single throughput smoke test with several that measure how the
spill machinery scales with the shape of the workload hierarchy.

`selectAllocationToSpill` (the spill victim descent) is measured in a tight
loop entirely on the scheduler thread, so the numbers isolate the traversal
from cross-thread round-trip and event-queue costs, swept independently over:
- hierarchy depth (internal fair nodes on the root-to-leaf path);
- width (sibling queues under one fair node), each with a reclaimable
  allocation;
- number of reclaimable allocations in a single queue.

Because each node keeps a reclaimable-filtered ordered set and the descent
takes its extremum, selection stays about constant with width and with the
number of allocations, and grows linearly with depth. A separate end-to-end
increase/decrease churn test, swept over depth, reports realistic throughput
including the scheduler round-trip.

`SCHED_PERF_ITERS` (default 1000) selects the iteration count; use a large
value against a non-sanitizer release build for a representative measurement.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Two correctness/liveness fixes in the reclaimable-memory spill machinery:

- `AllocationQueue::approveDecrease` now clamps an allocation's `reclaimable`
  down to the new `allocated` on a non-removing shrink (invariant I3), dropping
  it from `reclaimable_allocations` at zero and propagating the delta via
  `pending_reclaimable_delta`. Previously a spill-signalled allocation that
  decreased before re-reporting could linger with `reclaimable > allocated`
  (even `allocated == 0`) and be re-picked as a spill victim for memory it had
  already released.
- `AllocationLimit::propagateUpdate` now reopens the one-at-a-time spill gate on
  a reported reclaimable decrease (the acknowledgement), not only on an
  `allocated` decrease. Previously a victim that lowered its `reclaimable` to 0
  without decreasing could leave the workload above the soft limit indefinitely.

Adds gtest coverage `ReclaimableClampedOnShrink` and
`SpillReSelectsWhenVictimReportsZeroReclaimable`, and makes
`SpillReSignalsUntilUnderSoftLimit` deterministic.

Related: ClickHouse#109064

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Document the `max_memory_before_spill` and `max_memory_to_spill_ratio` workload
settings and add a `Spilling reclaimable memory` section to the workload
scheduling documentation.

Related: ClickHouse#109064

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Reword comments in the reclaimable-memory spill code to be self-contained
technical descriptions and drop internal shorthand ("D2", "Progress strategy",
"cooperative domain") that only makes sense alongside external design notes.
References to invariants defined in `ISpaceSharedNode.h` are kept. Also
documents that the `spill_requested` gate is now cleared on a decrease in
reported reclaimable, not only on an `allocated` decrease.

Related: ClickHouse#109064

Co-Authored-By: Claude Opus 4.8 <[email protected]>
`AllocationLimit::propagateUpdate` ran `checkSoftLimit` only for reclaimable
reports (`reclaimable_delta != 0`), so structure changes never re-evaluated
the soft limit. Reproduced liveness gap: `CREATE OR REPLACE WORKLOAD` that
first sets `max_memory_before_spill` on a workload with no prior limit takes
the Add path of `updateSchedulingSettings`, which inserts a fresh
`AllocationLimit` and re-links the existing branch under it via `attachChild`;
that attach propagates with `reclaimable_delta == 0`, so a subtree already
over the new threshold with reclaimable memory would not receive a spill
signal until some unrelated resize or `setReclaimable`. The same gap applied
to attaching a reclaimable subtree under an existing limit, and to a detach
that leaves the remaining subtree over the soft limit (where `spill_requested`
is cleared but nothing re-signals).

Fix: run `checkSoftLimit` at the end of `propagateUpdate` also when the update
carries `attached`/`detached`. This is deadlock-safe by field, not by call
path: `attached`/`detached` originate exclusively in `attachChild`/
`removeChild` tree-restructure code on the scheduler thread (the queue is a
leaf and never attaches/detaches under its own lock), and a non-zero
`reclaimable_delta` originates exclusively in
`AllocationQueue::processActivation`, which propagates outside the queue lock.
The only mutex-held propagations are the pure `increase` relays from
`updateMinMaxAllocated`, `updateQueueLimit` and the in-lock part of
`AllocationQueue::approveDecrease`, which carry none of these fields; the
comment in `propagateUpdate` previously misattributed attach/detach to this
unsafe set and is corrected.

The new `MemoryReservationSpillOnSoftLimitEnableTransition` test reproduces
the enable transition and hangs without the fix.

Co-Authored-By: Claude Fable 5 (1M context) <[email protected]>
Add three columns so operators can observe the spill machinery:
- `reclaimable` - the portion of `allocated` under a space-shared node that
  queries reported as spillable (the aggregate that drives victim selection);
- `spills` - the number of spill requests issued by a node due to its soft
  memory limit being exceeded (the spill-side counterpart of `killers`);
- `soft_limit` - the effective spill threshold of an `allocation_limit` node,
  i.e. the smaller of `max_memory_before_spill` and
  `max_memory_to_spill_ratio * max_memory`.

Without them a user who sets the soft-limit workload settings cannot tell
whether reclaimable memory is being reported or whether spill requests fire.
The fields are read inside `forEachNode`, which executes the visitor on the
scheduler thread, the same way the existing space-shared counters are read.

Co-Authored-By: Claude Fable 5 (1M context) <[email protected]>
- `measureDescent`: use `EXPECT_NE` and always fulfill the promise. The
  previous `ASSERT_NE` would return from the scheduler-thread lambda before
  `set_value`, turning an assertion failure into a hung `fut.get()` (a stuck
  CI job instead of a red test).
- Add `MemoryReservationSpillSmallerSettingWins`: with both
  `max_memory_before_spill` and `max_memory_to_spill_ratio` set, the smaller
  resulting threshold applies, as documented.
- Docs: state explicitly that currently no operators report reclaimable
  memory, so the soft limit has no user-visible effect yet.

Co-Authored-By: Claude Fable 5 (1M context) <[email protected]>
`ConcurrentSpillChurn`: eight query threads churn allocation sizes and
reclaimable reports across four sibling queues while the workload sits around
a small soft limit, so spill signals fire concurrently with increases,
decreases, re-keying, clamping and removals; a ninth thread concurrently
moves the soft limit up and down (as `CREATE OR REPLACE WORKLOAD` would).
Under ThreadSanitizer this exercises every cross-thread path of the feature:
`setReclaimable` against approvals, `checkSoftLimit` from all of its trigger
sites, and `spillAllocation` callbacks racing allocation owners. Asserts that
spills fired and that all aggregates return to zero once the allocations are
gone (leaked intrusive-set links would also trip destructor asserts).

Passes 50 consecutive repeats under ThreadSanitizer with zero data races.

Co-Authored-By: Claude Fable 5 (1M context) <[email protected]>
The spill gate rate-limits signals to progress events and is deliberately
not tied to the victim's identity, so after an unrelated decrease the next
check may signal a different allocation while an earlier victim has not
reacted yet. The `spill_requested` comment claimed "at most one spill signal
is outstanding at a time", which is not what the code does.

- Correct the `spill_requested` comment and document the rationale (no
  victim pointer, a stalled victim must not freeze the episode, overshoot
  bounded by coalescing).
- `spillAllocation` contract: repeated signals may arrive, each carrying the
  then-current need; implementations must coalesce to the maximum, never
  accumulate.
- Add `SpillGateReopensOnUnrelatedDecrease` pinning the semantics.

Co-Authored-By: Claude Fable 5 (1M context) <[email protected]>
Comments referred to numbered invariants ("invariant I6", "(I8)") and to a
test by name. Such tokens read as citations and add nothing where the
sentence already states the fact. Spell out the invariant inline where
needed (e.g. `reclaimable <= allocated`), drop the rest, and turn the
numbered list on `ISpaceSharedNode` into plain bullets.

Co-Authored-By: Claude Fable 5 (1M context) <[email protected]>
A spill signal was one-way: `AllocationLimit` could not tell when the victim
was done, so its gate reopened heuristically on every decrease and on any
drop of the reclaimable aggregate, allowing premature signals to other
allocations while the victim was still spilling.

The reply now travels the same path as the state it describes, like eviction
completion already does via `DecreaseRequest::removing_allocation`:

- `IAllocationQueue::finishSpill(allocation, reclaimable_total)` is the reply
  to `spillAllocation`. It updates the reported reclaimable like
  `setReclaimable` and marks the propagated update with a new
  `Update::spilled` flag. Removing an allocation that reported reclaimable
  memory marks the update as well: an allocation that left the queue can no
  longer spill, so a victim removed mid-spill does not leave gates closed.
- `AllocationLimit` holds `spill_requested` until an update with `spilled`
  arrives (or the subtree detaches, or `allocated` drops to the soft limit).
  Since at most one spill request is outstanding per subtree, the flag needs
  no victim identity. Unrelated decreases and reports no longer reopen the
  gate.
- When the reply arrives together with a still-pending decrease (the query
  issues decreases for the freed memory before finishing, per the
  `finishSpill` contract), the re-evaluation is deferred to that decrease's
  approval, so the next victim is selected against the updated `allocated`
  rather than a stale excess.

No allocations anywhere on the path: a preallocated flag per queue, drained
with the existing activation.

Tests: `SpillGateHeldUntilVictimReply` (replaces the previous gate-semantics
test), `SpillReplyDeferredToPendingDecrease`, `SpillGateReopensWhenVictimRemoved`;
declines are now expressed via `finishSpill(0)`; the concurrency stress
exercises replies, including the deferred path. 145 tests pass under
ThreadSanitizer with 50 repeats of the spill set, zero data races.

Co-Authored-By: Claude Fable 5 (1M context) <[email protected]>
The spill reply reopened the gate immediately, but the victim's decrease is
applied only at its approval, and events are processed before approvals. A
trigger arriving in that window (e.g. a reclaimable report from a sibling
queue) evaluated the soft limit against an `allocated` that still contained
the released memory and issued a spill signal with a stale, too-large
excess.

`checkSoftLimit` now returns while `decrease != nullptr`: every pending
decrease ends in an `approveDecrease` at this node, whose trailing call
re-evaluates with the updated `allocated`. This replaces the previous
special case that deferred only the reply-carrying update and could not
cover other triggers in the window.

`NoSpillSignalWhileVictimDecreaseIsPending` reproduces the window
deterministically by parking the scheduler thread so the reply and a sibling
report are queued ahead of the approval; it fails with the stale excess
without the fix.

Co-Authored-By: Claude Fable 5 (1M context) <[email protected]>
…reservations

# Conflicts:
#	src/Common/Scheduler/Nodes/tests/gtest_space_shared_scheduler.cpp
`master` moved the documentation from the Docusaurus tree under
`docs/en/**/*.md` to the Mintlify tree at `docs/**/*.mdx`, deleting every
file this branch edits. The edits are replayed at the new paths:

- `docs/en/operations/workload-scheduling.md` -> `docs/concepts/features/configuration/server-config/workload-scheduling.mdx`
…reservations

# Conflicts:
#	src/Common/Scheduler/Nodes/tests/gtest_space_shared_scheduler.cpp
`ManualAllocation` came from master where `ResourceAllocation::spillAllocation`
did not exist; on this branch it is a pure virtual, making the mock abstract.

Co-Authored-By: Claude Fable 5 (1M context) <[email protected]>
… into reclaimable_memory_reservations

# Conflicts:
#	src/Common/Scheduler/Nodes/tests/gtest_space_shared_scheduler.cpp
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [57b158a]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
string_bytes_functions #0 FAIL dashboard
iceberg_suite_s3_rw_features #5 unstable query history
iceberg_suite_s3_rw_features #9 unstable query history

AI Review

Summary

Adds workload soft memory limits and scheduled spilling for sorting, aggregation, joins, DISTINCT, and IN sets. At head 57b158a985a18d01bb7389776f733a7af0971ba1, explicit group_by_overflow_mode = 'any' still produces incorrect aggregate results after a workload spill. Two previously discussed operational limitations also remain.

Findings

❌ Blockers

  • AggregatingTransform.cpp:1522: Explicit group_by_overflow_mode = 'any' never captures a retained-key seed. With one stream and max_rows_to_group_by = 1, a block of UInt64 keys [1, 2] sets no_more_keys. A workload spill empties the table without reseeding; a second identical block drops both admitted keys' rows, leaving counts at 1 instead of 2. Preserve the admitted keys or reject spilling in this state, and add a regression that forces the spill between blocks without LIMIT.

⚠️ Majors

  • ExecutionThreadContext.cpp:115 [dismissed by author -- https://github.com/Dynamic queries spilling based on workloads #119443#discussion_r3990451654]: Workload spills ignore need_reserved_memory_bytes; with insufficient headroom between soft and hard limits, conversion or repartitioning can throw MEMORY_LIMIT_EXCEEDED before reclaiming memory. Threshold tuning mitigates this but does not reserve the headroom reported by the operator.
  • AggregatingTransform.cpp:1691 [dismissed by author -- https://github.com/Dynamic queries spilling based on workloads #119443#discussion_r4232127186]: The last producer calls AdaptiveAggregationSpillable::finish before the merge drains the shared backlog. In workload-only mode, those resident bytes disappear from reclaimable accounting and have no merge-phase spill owner, so cross-query pressure can still evict a query holding spillable state. Keep ownership/accounting through the merge handoff.
Missing context / blind spots
  • ⚠️ Verification was static; no local ClickHouse binary or configured build was available. Run the focused explicit-any regression to validate the reported execution trace.
Final Verdict

Status: ❌ Block. Preserve explicit any overflow semantics across workload spills and add the focused regression. The two deferred concerns above remain summary-only.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Sep 11, 2026
@azat
azat force-pushed the workload-dynamic-spilling branch from 082ee54 to 7dc9cc5 Compare September 11, 2026 12:50
@serxa serxa self-assigned this Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... label Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 57b158a985a18d01bb7389776f733a7af0971ba1 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@serxa serxa mentioned this pull request Sep 19, 2026
24 of 33 tasks
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 20, 2026
47 of 72 tasks
Comment thread src/Interpreters/Aggregator.cpp Resolved
Comment thread src/Interpreters/Aggregator.cpp Resolved
@azat
azat force-pushed the workload-dynamic-spilling branch from edb9b82 to e1d327c Compare October 14, 2026 07:30
Comment thread src/Interpreters/Aggregator.cpp Resolved
/// table can actually be flushed to disk: the seed is needed to re-fill it after the flush.
if (!aggregator_params.shared_kept_keys_for_overflow_any || !aggregator_params.max_bytes_before_external_group_by)
/// Scheduler spills are possible even with `max_bytes_before_external_group_by` disabled.
if (!aggregator_params.shared_kept_keys_for_overflow_any || !aggregator_params.tmp_data_scope)

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] Preserve explicit any overflow keys across workload spills

This seed remains restricted to the trivial GROUP BY … LIMIT optimization. Ordinary GROUP BY with max_rows_to_group_by = 1 and group_by_overflow_mode = 'any' leaves shared_kept_keys_for_overflow_any false. With one stream, a first UInt64 key block [1, 2] sets no_more_keys, but captures no seed. A workload spill then empties the table in Aggregator::spill: spillAllowedUnderKeptKeysCutoff accepts the null shared control, and reseedKeptKeysAfterSpill does nothing. A second [1, 2] block cannot find either admitted key and discards both rows, leaving their counts at 1 instead of 2. This violates the setting's promise to continue aggregating admitted keys, even when both external aggregation thresholds are disabled. Set min_bytes_to_spill = 0 to exercise this with a small table.

Preserve the per-stream admitted keys for explicit any too, or decline scheduler spills in this unsupported state. Please add a regression that forces a workload spill between repeated-key blocks without LIMIT, using the paused-input approach from 05394_workload_memory_spilling_kept_keys.sh.

@azat azat Oct 14, 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 that it is pre existing bug in adaptive aggregation that should be fixed separately

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.

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.

@azat
azat enabled auto-merge October 14, 2026 14:16
@azat
azat disabled auto-merge October 14, 2026 14:16
@azat
azat enabled auto-merge October 14, 2026 15:03
@azat
azat disabled auto-merge October 14, 2026 15:05
@azat
azat enabled auto-merge October 14, 2026 15:08
@azat
azat disabled auto-merge October 14, 2026 15:37
@azat
azat added this pull request to the merge queue Oct 14, 2026
@azat azat changed the title Dynamic queries spilling under memory pressure based on workloads Dynamic queries spilling based on workloads Oct 14, 2026
Merged via the queue into ClickHouse:master with commit f0439bf Oct 14, 2026
174 of 176 checks passed
@azat
azat deleted the workload-dynamic-spilling branch October 14, 2026 16:39
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
harikrishnan94 added a commit that referenced this pull request Oct 14, 2026
Master moved the spilling of joins under memory pressure to `ISpillable` (#119443). `SpillingHashJoin` conflicted. It takes master's `getMemoryStats` and `spill`, with the in-memory `HashJoin` in place of `ConcurrentHashJoin`: after the switch, the blocks of workers not yet converted count as spillable when the join has more than one build worker. A switch that `spill` requests now starts with at least two buckets and converts every worker under the exclusive lock, before other build threads see the grace join, as master does for the slots of `ConcurrentHashJoin`.

PR: #115605

Co-Authored-By: Claude Opus 5.5 <[email protected]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... 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.

Automatically make queries use spilling when reaching memory limits Spill interface for spillable joins

6 participants