Repository navigation
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: #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: #109064 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [5dc8cd4] Summary: ✅
AI ReviewSummaryThis PR adds reclaimable-memory accounting and soft-limit spill signaling to the space-shared scheduler, plus workload settings and Findings❌ Blockers
Tests
Final VerdictNot ready. One new hard-limit regression on live detach or reparent operations needs fixing before merge, and the spill path still has four unresolved correctness gaps from earlier review that break the “one outstanding spill per subtree until reply” contract. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 807/868 (92.97%) · Uncovered code |
|
@groeneai, investigate the failure: https://github.com/ClickHouse/ClickHouse/actions/runs/28684807333/job/85086351123 (test_dictionaries_postgresql/test.py::test_invalidate_query) and provide a fix in a separate PR. If the fix is already in progress, link it here. |
|
@serxa investigated Root cause: Fix (separate PR, test-only, not pushed here): #109390. It waits for the invalidate baseline to settle after each reload and verifies the "no update" case via |
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]>
Perf resultsMeasured on a
End-to-end synchronous increase/decrease churn (full round-trip through the scheduler thread), swept over depth:
Observations:
The same trends hold under ThreadSanitizer at roughly 10x the absolute cost (instrumentation), which is useful for regression detection. |
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: #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: #109064 Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Thanks for the review. Addressed the two correctness/liveness findings; on the settings point, some context on the intended split. Fixed — stale reclaimable after a shrink ( Fixed — stalled spill episode ( On the soft-limit settings being inert on the production path: this is intentional, not an oversight. The feature is deliberately split (see the design in #109064): this PR lands the scheduler infrastructure, the workload settings, and their documentation, so the query-side reclaimable-memory reporting and spill reaction can be built and reviewed as a separate, focused change on top. |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
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: #109064
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@serxa re-reviewed at 62b964a.
Otherwise looks good. |
`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]>
| boost::intrusive::set_member_hook<> increasing_hook; | ||
| boost::intrusive::list_member_hook<> decreasing_hook; | ||
| boost::intrusive::list_member_hook<> removing_hook; | ||
| boost::intrusive::set_member_hook<> reclaimable_hook; /// Membership in the queue's reclaimable set (linked iff `reclaimable > 0`). |
There was a problem hiding this comment.
ResourceAllocation now has a sixth intrusive membership, but ~ResourceAllocation still only asserts the five older hooks in src/Common/Scheduler/ResourceAllocation.cpp. If any path forgets to unlink reclaimable_hook, the owner can now die without tripping the existing debug guard, leaving a dangling entry in reclaimable_allocations to be dereferenced later. Please extend the destructor check here with chassert(!reclaimable_hook.is_linked()); so the new hook gets the same protection as the others.
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]>
| // The allocation is leaving the queue, so drop its reported reclaimable from the aggregate. | ||
| // The net delta is drained and propagated to the root at the end of processActivation. | ||
| // (A running allocation that merely shrinks keeps its reclaimable; the query re-reports it.) | ||
| if (allocation.reclaimable != 0) |
There was a problem hiding this comment.
allocation.reclaimable != 0, but the outstanding victim can already have been clamped or re-reported down to 0 before it is removed without ever calling finishSpill.
A concrete trace is: a is spill-signaled, a naturally shrinks to zero reclaimable (or reports setReclaimable(0)) without replying, and then a is cancelled while sibling b is still above the soft limit. This branch sends no Update::spilled, so AllocationLimit::spill_requested stays set forever and b is never asked to spill. The removal path needs to track “this allocation still owes a spill reply” explicitly instead of using reclaimable > 0 as the proxy.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 811/871 (93.11%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds a soft memory limit and spill-victim selection to the workload scheduler (new max_memory_before_spill / max_memory_to_spill_ratio settings). The actual spill hook is a no-op and no operators report reclaimable memory yet, so query execution is unchanged unless a workload opts into memory-reservation spilling — which the ClickBench and TPC-H runs do not. All three flagged clickbench queries show flat CPU time with only wall-clock jitter, so none is attributable to this change: Q4's -24.1% was already correctly suppressed as within-baseline variance, and Q15's flagged +23.3% (thin baseline, flat CPU) is downgraded to not_sure. No real performance impact. clickbenchFlagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…reservations # Conflicts: # src/Common/Scheduler/Nodes/tests/gtest_space_shared_scheduler.cpp
| // An allocation that leaves the queue can no longer spill, so treat its removal as the | ||
| // reply to any spill request it may hold: without this, a victim removed mid-spill (killed | ||
| // or cancelled) would leave the ancestor spill gates closed forever. | ||
| pending_spilled = true; |
There was a problem hiding this comment.
pending_spilled is now set for any removed allocation that still has reclaimable > 0, but that is not equivalent to “the spill-signaled victim replied”. A concrete trace is a=15000 reclaimable, b=7000 reclaimable, soft limit =10000: a gets the first spillAllocation, then b is cancelled before a calls finishSpill. This removal marks Update::spilled, AllocationLimit::propagateUpdate clears spill_requested, and after b's approveDecrease the trailing checkSoftLimit can signal a again even though its original spill is still in flight. That reintroduces multiple concurrent spills in one subtree. This path needs to emit Update::spilled only when the removed allocation actually owes the outstanding reply (e.g. a per-allocation spill-pending bit or epoch), which would also fix the existing “victim removed after reclaimable dropped to 0” case.
`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`
| // Disabled or under the threshold: no episode in progress. | ||
| if (allocated <= soft_limit) | ||
| { | ||
| spill_requested = false; |
There was a problem hiding this comment.
spill_requested on a plain under-threshold transition, not on the spill-signaled allocation's reply. A concrete trace is: a=8000 reclaimable, b=3000, soft=10000; a gets the first spill signal, then b naturally shrinks to 1000, so this branch drops the gate even though a has not called finishSpill yet. If the subtree grows back above soft_limit before a replies and some other reclaimable allocation has become the new extremum, the next checkSoftLimit will signal that allocation too. That breaks the documented “no further victim in this subtree until the reply arrives” contract and allows concurrent spill work across allocations. Can we keep the gate tied to an outstanding-reply bit/token and only clear it on Update::spilled / actual victim removal?
…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
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units34 translation units recompiled, 173 s compile time in total, 34 of them have a recent master baseline. |
|
All the work was cherry-picked into #119443 as the foundation. |
|
JFYI I've actually saved original hashes and did all the rebases on top, so this PR would be automatically marked as merged after mine |
|
Oh, nice! I didn't know it is even possible |
Scheduler-side support for reclaimable memory tracking and dynamic spilling, built on top of the memory reservations subsystem. The design is described in #109064.
Queries can report the portion of an allocation that can be spilled or discarded on request (
IAllocationQueue::setReclaimable), which is aggregated bottom-up as a newreclaimablefield on every scheduler node. EachAllocationLimitgains a soft limit: when a workload's allocated memory exceeds it and the subtree has reclaimable memory, the scheduler asks a victim to reclaim memory (ResourceAllocation::spillAllocation, mirroringkillAllocation) instead of waiting for the hardmax_memorylimit to force a kill. The request is replied: the query finishes it withIAllocationQueue::finishSpillafter issuing the decreases for the freed memory (zero reclaimable doubling as a decline), the reply travels to the root asUpdate::spilledon the same propagation path as the state it describes, and at most one spill request is outstanding per subtree until it arrives; a victim that leaves the queue counts as having replied. Victim selection is deterministic and matches the kill order (largest usage, least precedence, largest allocation), descends a single root-to-leaf path via reclaimable-filtered ordered sets, and is fail-close: with nothing reclaimable, or with no soft limit configured, behavior is exactly as before.The soft limit is configured per workload via two new settings:
max_memory_before_spill(absolute) andmax_memory_to_spill_ratio(a fraction of the workload's ownmax_memory), smaller wins. The new state is observable insystem.scheduler:reclaimable,spills, and the effectivesoft_limit.This is the scheduler side only.
MemoryReservation::spillAllocationis currently a no-op; the query side that reports reclaimable memory and reacts to spill signals is a separate change. Documentation for the scheduler-side workload settings (max_memory_before_spill,max_memory_to_spill_ratio) and aSpilling reclaimable memorysection are included here; the set of operators that can spill will be documented together with the query-side reaction.Invariants for the new machinery are documented on
ISpaceSharedNode(I1-I8). Added unit tests cover fail-close, largest-first selection, fair descent skipping unreclaimable subtrees, the gate held until the victim's reply, the reply deferred to a pending decrease, re-signalling until under the soft limit, clamping reclaimable on a shrink, a declining victim, a victim removed mid-spill, the soft-limit enable transition viaCREATE OR REPLACE WORKLOAD, the settings (absolute, ratio, and smaller-wins combination), a concurrency stress, and a parametrized throughput test. Verified under ThreadSanitizer (145 scheduler/workload gtests, 0 data races).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added workload settings
max_memory_before_spillandmax_memory_to_spill_ratiofor the experimental memory reservation scheduling. They configure a soft memory limit above which a workload's queries are asked to spill reclaimable memory, before the hardmax_memorylimit forces an eviction. This is the scheduler-side foundation: queries do not yet report reclaimable memory or react to spill requests, so the settings have no effect until the query-side change lands.Documentation entry for user-facing changes