Skip to content

Scheduler: reclaimable memory tracking and dynamic spilling infrastructure - #109367

Closed
serxa wants to merge 19 commits into
masterfrom
reclaimable_memory_reservations
Closed

serxa wants to merge 19 commits into
masterfrom
reclaimable_memory_reservations

Conversation

@serxa

@serxa serxa commented Jul 3, 2026 •

Copy link
Copy Markdown
Member

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 new reclaimable field on every scheduler node. Each AllocationLimit gains 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, mirroring killAllocation) instead of waiting for the hard max_memory limit to force a kill. The request is replied: the query finishes it with IAllocationQueue::finishSpill after issuing the decreases for the freed memory (zero reclaimable doubling as a decline), the reply travels to the root as Update::spilled on 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) and max_memory_to_spill_ratio (a fraction of the workload's own max_memory), smaller wins. The new state is observable in system.scheduler: reclaimable, spills, and the effective soft_limit.

This is the scheduler side only. MemoryReservation::spillAllocation is 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 a Spilling reclaimable memory section 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 via CREATE 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):

  • Experimental Feature

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

Added workload settings max_memory_before_spill and max_memory_to_spill_ratio for 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 hard max_memory limit 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

  • Documentation is written (mandatory for new features)

serxa and others added 2 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: #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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5dc8cd4]

Summary: ✅


AI Review

Summary

This PR adds reclaimable-memory accounting and soft-limit spill signaling to the space-shared scheduler, plus workload settings and system.scheduler introspection for that new state. The general direction is sound, but the current head still has multiple gate/liveness bugs in the spill path and one new regression in the existing hard-limit kill path during live workload-tree detach or reparent operations.

Findings

❌ Blockers

  • [src/Common/Scheduler/Nodes/SpaceShared/AllocationLimit.cpp:233] Structure-only reapply uses the parent increase pointer, but that field is deliberately nullptr while a hard-limit increase is blocked. After a detach frees memory or invalidates the old kill victim, the waiting child->increase is not reconsidered, so the request can stay blocked until some unrelated later decrease happens.

⚠️ Majors

  • [src/Common/Scheduler/Nodes/SpaceShared/AllocationLimit.cpp:203] Any detached descendant clears spill_requested, even if the detached subtree is unrelated to the current spill-signaled victim. A live CREATE OR REPLACE WORKLOAD / workload delete can therefore reopen the spill gate and issue a second spill before the first victim replies.
  • [src/Common/Scheduler/Nodes/SpaceShared/AllocationLimit.cpp:110] Dropping back to or below soft_limit clears spill_requested even when the spill-signaled allocation has not replied yet. If the subtree grows above the soft limit again before finishSpill, the next checkSoftLimit can start a concurrent spill episode.
  • [src/Common/Scheduler/Nodes/SpaceShared/AllocationQueue.cpp:441] Removal only counts as a spill reply while allocation.reclaimable != 0. If the spill-signaled victim first re-reports or is clamped down to 0 reclaimable and is then removed without finishSpill, the ancestor AllocationLimits never receive Update::spilled, so the soft-limit episode can stay stalled forever.
  • [src/Common/Scheduler/Nodes/SpaceShared/AllocationQueue.cpp:450] Any removed allocation that still has reclaimable > 0 emits Update::spilled, even if it was not the spill-signaled victim. Removing an unrelated reclaimable sibling can therefore reopen the gate and allow concurrent spills while the real victim is still in flight.
  • [src/Common/Scheduler/ResourceAllocation.cpp:9] ResourceAllocation gained a sixth intrusive hook, but ~ResourceAllocation still asserts only the older five. If some path forgets to unlink reclaimable_hook, the object can die without tripping the existing debug guard, leaving a dangling entry in reclaimable_allocations.
Tests
  • ⚠️ Add a focused regression for live workload detach or reparent while a hard-limit kill is blocked, proving the waiting child->increase is reconsidered immediately after the structure change.
  • ⚠️ Add a focused regression for live workload detach or reparent while a spill request is outstanding, proving unrelated subtree moves do not reopen the spill gate.
  • ⚠️ Add removal regressions for both remaining queue cases: the victim removed after its reclaimable total already reached 0, and an unrelated reclaimable allocation removed while another victim still owes the spill reply.
Final Verdict

Not 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

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 807/868 (92.97%) · Uncovered code

Full report · Diff report

@serxa

serxa commented Jul 4, 2026

Copy link
Copy Markdown
Member Author

@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.

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator

@serxa investigated test_dictionaries_postgresql/test.py::test_invalidate_query. It is a pre-existing flaky test, unrelated to this PR (Scheduler-only): it fails across 8 unrelated PRs in the last 30 days and 0 times on master, almost always on slow amd_asan_ubsan / amd_msan / old-analyzer runs.

Root cause: dict0 has LIFETIME(1) + an invalidate_query. SYSTEM RELOAD DICTIONARY does a forced full reload but does not run the invalidate query, so the stored invalidate response is left empty. The first periodic check after it always sees a "modified" source and reloads once more. On slow builds that follow-up reload lands after the test's UPDATE value*2 WHERE id != 0 and picks up value 2 for id=1, so the "no update should happen" assertion fails with '2' == '1'. The periodic check runs every 5s, which lines up with the test's fixed sleep(5).

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 last_successful_update_time not advancing. Reproduced deterministically in both directions and passed 25/25 locally.

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]>
@serxa

serxa commented Jul 4, 2026

Copy link
Copy Markdown
Member Author

Perf results

Measured on a RelWithDebInfo non-sanitizer build (build_release) at 2,000,000 iterations (SCHED_PERF_ITERS=2000000), via the tests in this PR.

selectAllocationToSpill (the spill victim descent) is measured in a tight loop on the scheduler thread, isolating the traversal from cross-thread round-trip and event-queue costs:

sweep small mid large trend
depth (internal nodes on the path) 382 ns/op (d=0) 425 ns/op (d=8) 478 ns/op (d=32) linear, ~3 ns per extra level
width (sibling queues under one fair) 389 ns/op (1) 401 ns/op (16) 415 ns/op (256) flat
reclaimable allocations in one queue 413 ns/op (1) 417 ns/op (100) 418 ns/op (1000) flat

End-to-end synchronous increase/decrease churn (full round-trip through the scheduler thread), swept over depth:

depth 0 2 8
per resize 12.9 µs 11.0 µs 12.4 µs

Observations:

  • Spill selection stays about constant with the number of sibling workloads and with the number of allocations per queue: each node keeps a reclaimable-filtered ordered set, so the descent takes its extremum in constant time per level. It grows only with depth, at roughly 3 ns per internal node. The ~380 ns baseline is dominated by formatting the diagnostic details string at the leaf, which in production is paid once per spill episode rather than in a loop.
  • The increase/decrease hot path is bound by cross-thread wakeup latency (~11-13 µs), so the O(depth) aggregation and reclaimable-set maintenance are not measurable against it; adding internal nodes does not slow it down.

The same trends hold under ThreadSanitizer at roughly 10x the absolute cost (instrumentation), which is useful for regression detection.

serxa and others added 2 commits July 12, 2026 14:56
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]>
@serxa

serxa commented Jul 12, 2026

Copy link
Copy Markdown
Member Author

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 (AllocationQueue::approveDecrease): a non-removing decrease now clamps the allocation's reclaimable down to the new allocated (restoring invariant I3) and drops it from reclaimable_allocations when it reaches zero, so a spill-signalled allocation that decreases before re-reporting can no longer linger as a victim for memory it has already released. The negative delta is propagated via pending_reclaimable_delta, like setReclaimable. Covered by the new ReclaimableClampedOnShrink test.

Fixed — stalled spill episode (AllocationLimit::propagateUpdate): a drop in reported reclaimable now reopens the one-at-a-time gate so checkSoftLimit re-targets the next reclaimable allocation. Previously a victim that lowered its reclaimable to 0 without decreasing could keep the workload above the soft limit indefinitely. Covered by the new SpillReSelectsWhenVictimReportsZeroReclaimable test (which hangs without the fix).

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. MemoryReservation::spillAllocation is a documented no-op until then, and the whole path is fail-close — with nothing reporting reclaimable memory the soft limit has no effect and behavior is identical to today. The two settings are now documented as experimental (Spilling reclaimable memory in workload-scheduling.md). We'd rather keep them visible than hide them: they are the configuration surface the query-side change builds on, and they are covered by tests here. Happy to tune the changelog wording if it reads as over-claiming.

@mintlify

mintlify Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 12, 2026, 4:17 PM

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]>
@groeneai

Copy link
Copy Markdown
Collaborator

@serxa re-reviewed at 62b964a.

  • Both correctness/liveness fixes confirmed against the diff and their new tests (`ReclaimableClampedOnShrink`, `SpillReSelectsWhenVictimReportsZeroReclaimable`); resolved those threads.
  • Settings-split rationale accepted: fail-close, documented no-op, experimental settings - reasonable to land infra + settings + docs first.
  • One remaining item, the enable-soft-limit transition flagged inline: adding a soft limit to a workload that previously had no limit node builds a fresh `AllocationLimit` and never runs `checkSoftLimit` on attach, so a subtree already over the new threshold with reclaimable memory does not spill until a later event. Safe hook is after the Add branch relinks in `updateSchedulingSettings` (not in `attachChild`, which can run under the queue mutex). Worth an `ALTER WORKLOAD` regression.

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]>
serxa and others added 2 commits July 15, 2026 09:54
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]>
@serxa
serxa marked this pull request as ready for review July 20, 2026 13:50
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]>
@serxa
serxa marked this pull request as draft July 20, 2026 14:15
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`).

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.

⚠️ 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)

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.

⚠️ This only treats a removal as the spill reply while 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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 811/871 (93.11%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 15 not_sure 215 265 +23.3% <0.0001 This PR only adds soft-limit/spill plumbing to the memory scheduler (a no-op with no operators reporting reclaimable memory), which a plain SELECT does not exercise; CPU time is flat and the baseline is thin, so the +23.3% is run-to-run variance.
⚠️ 28 not_sure 1028 1081 +5.1% 0.0104 Correctly left not_sure: the two tests disagree (borderline) and CPU time is flat (15184 vs 15150 ms). This scheduler-only change cannot touch this query's path, so the +5.1% is noise.

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
  • StressHouse run: ab41d147-0809-405d-a948-6f182e30ecb0
  • MIRAI run: a396715f-85c2-4c6e-aa7d-1f52c8f87e15
  • PR check IDs:
    • clickbench_970007_1785419832
    • clickbench_970014_1785419832
    • clickbench_970025_1785419832
    • tpch_adapted_1_official_970037_1785419832
    • tpch_adapted_1_official_970051_1785419832
    • tpch_adapted_1_official_970078_1785419832

…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;

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.

⚠️ 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;

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.

⚠️ This still clears 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?

serxa and others added 3 commits August 13, 2026 14:32
…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 Aug 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5dc8cd4a7 with master 5f6d1cd38 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 691.74 MiB 688.74 MiB -3.00 MiB (-0.43%)

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 units

34 translation units recompiled, 173 s compile time in total, 34 of them have a recent master baseline.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... label Sep 4, 2026
@azat azat changed the title Scheduler: reclaimable memory tracking and dynamic spilling Scheduler: reclaimable memory tracking and dynamic spilling infrastructure Sep 11, 2026
@azat azat mentioned this pull request Sep 11, 2026
3 of 7 tasks
@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
@serxa

serxa commented Oct 8, 2026

Copy link
Copy Markdown
Member Author

All the work was cherry-picked into #119443 as the foundation.

@serxa serxa closed this Oct 8, 2026
@azat

azat commented Oct 8, 2026

Copy link
Copy Markdown
Member

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

@serxa

serxa commented Oct 8, 2026

Copy link
Copy Markdown
Member Author

Oh, nice! I didn't know it is even possible

This branch was successfully deployed

1 active deployment
staging - docs — 5dc8cd4a Deployed Aug 13, 2026 by mintlify[bot]
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-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants