Repository navigation
Dynamic queries spilling based on workloads - #119443
Conversation
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
|
Workflow [PR], commit [57b158a] Summary: ❌
AI ReviewSummaryAdds workload soft memory limits and scheduled spilling for sorting, aggregation, joins, Findings❌ Blockers
Missing context / blind spots
Final VerdictStatus: ❌ Block. Preserve explicit |
082ee54 to
7dc9cc5
Compare
Build profile diff (arm_release)Commit See the job log for details. |
edb9b82 to
e1d327c
Compare
| /// 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) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
It seems that it is pre existing bug in adaptive aggregation that should be fixed separately
There was a problem hiding this comment.
f0439bf
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]>
Enable the global profiler and the peak/limit flushes, attach the raw `.heap` files as `jemalloc.tar.zst`, and symbolize the latest one when the server died or the total limit was hit. Refs: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119443&sha=976ddf998db2cc7d9640d646357403f3a5afe565&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 PR: ClickHouse#119443 Co-Authored-By: Claude Fable 5.1 <[email protected]>
Based on and includes: #109367
Changelog category (leave one):
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_ratioinWORKLOADand once the memory will reach this soft limit it will automatically start memory spilling. It supports memory forORDER 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==GCMFollowup
need_reserved_memory_bytesin decisions or reimplementgrace_hashspilling and get rid of itRefs
Workflow [PR]
Sync PR [sync-upstream/pr/119443]
Version info
26.10.1.2388-master(included in26.10and later)