Repository navigation
Add server setting additional_memory_tracking_per_thread - #104965
alexey-milovidov wants to merge 144 commits into
Conversation
Each thread accumulates up to `max_untracked_memory` (4 MiB by default) of allocations before reporting them to the server-wide `MemoryTracker`. With many threads, this unreported memory can sum to a large amount, causing the server's tracked memory to under-count actual consumption and leading to OOM. Introduce a server-level setting `additional_memory_tracking_per_thread` (default 4 MiB) and charge this amount to the `MemoryTracker` around every job executed in our `ThreadPool` workers. The global tracked memory becomes a safe upper bound on actual consumption. The speculative allocation uses the throwing path of `CurrentMemoryTracker`, so when it would exceed the limit the corresponding job is treated as failed with `MEMORY_LIMIT_EXCEEDED` — the same behavior as if the job itself had exceeded the limit.
|
Workflow [PR], commit [ed5b503] Summary: ✅
AI ReviewSummaryAdds Missing context / blind spots
Final VerdictStatus: ✅ Approve. No code changes requested; CI completion remains pending. |
…read group
The original commit reserved the memory inside `ThreadPoolImpl::worker`,
before `job_data->job()` ran. The query's thread group is only attached
inside the job itself (via `ThreadGroupSwitcher`), so the speculative
`CurrentMemoryTracker::alloc` ran against the global tracker only and,
when it threw `MEMORY_LIMIT_EXCEEDED`, the job was skipped entirely.
The pipeline jobs submitted by `PullingAsyncPipelineExecutor`,
`PushingAsyncPipelineExecutor` and `PipelineExecutor::spawnThreads`
rely on running to completion to push a "done" sentinel into the
output queue; when their job is skipped, the consumer hangs in
`ConcurrentBoundedQueue::popImpl`. `KILL QUERY ... SYNC` then also
hangs in `PullingAsyncPipelineExecutor::cancel` waiting on the same
unsignalled event. Reproduced with 200 concurrent SELECTs in an 8 GiB
cgroup -- 56 queries hung permanently and could not be killed.
Move the reservation into the per-job lambdas, after the
`ThreadGroupSwitcher` is constructed and inside the same `try` block
that propagates exceptions through the pipeline's normal failure path.
The throw now goes to the query's `MemoryTracker` chain and the
existing `catch` finishes the executor (signalling consumers).
Verified with the same 200-query workload:
* before this commit: 56 hung queries, server unkillable
* after: clean `MEMORY_LIMIT_EXCEEDED` on every query that
hits the limit, server stays alive
With `additional_memory_tracking_per_thread` bumped from the default
4 MiB to 8 MiB, the workload survives end-to-end (cgroup peak 7.99 GiB,
`memory.events:oom_kill = 0`).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* `04238_additional_memory_tracking_per_thread.sql` -- single-query smoke test. Verifies the server setting is visible, and that a query whose `max_memory_usage` cannot accommodate the speculative reservation fails with `MEMORY_LIMIT_EXCEEDED` instead of hanging. A hang would surface as the runner's per-test timeout firing. * `04239_additional_memory_tracking_per_thread_concurrent.sh` -- regression test for the original deadlock: 64 concurrent SELECTs are launched in parallel, each with `max_memory_usage = 1`, so every one trips the speculative reservation inside the pipeline executor. The bug it guards against was that the speculative throw, raised before the query's thread group was attached, was swallowed by the ThreadPool worker -- the pipeline consumer then blocked forever on the empty output queue. The test runs each client through `timeout` and counts how many did not exit (`hung`); the expected count is zero, and a final `SELECT 'survived'` confirms the server is still serving traffic afterwards. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…racking-per-thread
Many stateless tests intentionally use very small `max_memory_usage` values (down to ~10 MiB) to exercise specific memory-limit behaviour. The PR's production default of 4 MiB speculative reservation per thread pushes those queries over their limits and breaks the tests. Affected tests included `01017_uniqCombined_memory_usage`, `01019_Buffer_and_max_memory_usage`, `01062_pm_all_join_with_block_continuation`, `01062_pm_multiple_all_join_same_value`, `01109_inflating_cross_join`, `01278_min_insert_block_size_rows_for_materialized_views`, `03030_system_flush_distributed_settings`, `03217_primary_index_memory_leak`, `03829_insert_deduplication_info_memory`, and `04146_spilling_hash_join_low_threshold`. Set `additional_memory_tracking_per_thread = 0` via a test config so the existing tests keep covering what they were written to cover. The feature itself remains covered by `04238_additional_memory_tracking_per_thread` and `04239_additional_memory_tracking_per_thread_concurrent`, both of which still pass with the setting disabled because they rely on `max_memory_usage = 1` rather than on the speculative reservation specifically tripping the limit. CI report: #104965 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The stateless-test config now sets `additional_memory_tracking_per_thread = 0`
so it does not interfere with the many existing tests that use intentionally
small `max_memory_usage` values. With the speculative reservation off, the
1-byte query limit no longer trips reliably from the reservation itself --
small in-query allocations sit in `max_untracked_memory` (4 MiB by default)
and never reach the query's `MemoryTracker`.
Add `max_untracked_memory = 0` to the failing queries so every allocation
is reported immediately. The first in-query allocation now exceeds the
1-byte limit and throws inside the pipeline lambda, exercising the same
`catch` block (in `PipelineExecutor` / `PullingAsyncPipelineExecutor` /
`PushingAsyncPipelineExecutor`) that the speculative reservation would
have exercised -- which is the actual property the test cares about
(no hang on the consumer's output queue).
Also redirect `wait` stderr in `04239_*_concurrent.sh` so bash's
job-control messages ("Killed", "Terminated") do not contaminate the
test stderr when the OS happens to SIGKILL background clients.
CI report: #104965
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Mirror the stateless-test config in the shared integration-test instance config so the per-thread speculative reservation is also off there. Several existing integration tests intentionally set `max_memory_usage = 1` to verify constraint clamping and early-memory-limit behaviour (`test_early_memory_limit_exception`, `test_settings_constraints_distributed::test_select_clamps_settings`, `test_settings_constraints_distributed_ddl::test_ddl_worker_clamps_settings_constraints`). The production default of 4 MiB speculative reservation pushes those queries over the limit at the local pipeline executor before the constraint clamp can take effect, so they fail with `MEMORY_LIMIT_EXCEEDED`. Disabling the feature in the common config keeps the existing assertions intact; the feature itself is still covered by the dedicated stateless tests `04238_additional_memory_tracking_per_thread` and `04239_additional_memory_tracking_per_thread_concurrent`. CI report: #104965 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The test 04117_max_threads_min_free_memory_per_thread spins up `clickhouse-local` with a tight `max_server_memory_usage = 4G` to make the free-memory limiter actually kick in for `max_threads_min_free_memory_per_thread`. The production default of 4 MiB speculative per-thread reservation interacts badly with that small server limit, intermittently failing the test with `MEMORY_LIMIT_EXCEEDED` before the limiter under test can take effect. Set `additional_memory_tracking_per_thread = 0` in the same temp config so the speculative reservation is off for this test only. The feature itself is still covered by `04238_additional_memory_tracking_per_thread` and `04239_additional_memory_tracking_per_thread_concurrent`. CI report: #104965 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two corrections from the review of #104965: * `programs/server/Server.cpp` cast a `UInt64` setting straight to `int64_t` before storing it in the atomic that the executors read. A misconfigured value above `INT64_MAX` would wrap negative and silently disable the feature via the `> 0` check. Clamp at `INT64_MAX` before the cast. * `tests/queries/0_stateless/04239_additional_memory_tracking_per_thread_concurrent.sh` captured `$?` inside an `if ! wait "$pid"; then` branch, where the status reflects the negated condition (always 0), not the child's real exit code. As a result the timeout-firing path (exit 124) was never seen and `hung` could not increment -- the regression test would silently pass even when queries hung. Capture the real `wait` status into `rc` first. CI report: #104965 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`CurrentMemoryTracker::alloc` first buffers in the per-thread `untracked_memory` counter and only flushes to the parent trackers when `untracked_memory > untracked_memory_limit` (strict `>`). With the default `additional_memory_tracking_per_thread = 4 MiB` and the default `max_untracked_memory = 4 MiB`, our 4 MiB reservation sets `untracked_memory` to exactly 4 MiB, does not exceed the limit, and so never reaches the global tracker. The undercount that this PR is trying to close therefore still remains, and the throwing behaviour the pipeline `catch` block expects can never trigger in the default case. Force a flush right after the speculative `alloc` and re-run the limit check explicitly. If the reservation pushes the query's tracker over its limit, `CurrentMemoryTracker::check` throws `MEMORY_LIMIT_EXCEEDED`, which the surrounding `catch` propagates through the pipeline as before (no consumer hang). The `SCOPE_EXIT` was moved above the `alloc` and guarded by a `reserved` flag so the matching `free` only runs when the allocation succeeded, otherwise we would double-decrement when `CurrentMemoryTracker::alloc` itself throws (it already rolls back internally). CI report: #104965 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…thread` The setting description said the charge is applied for \"every thread executing a job in a \`ThreadPool\`\" and that server-wide tracking becomes a safe upper bound, but the reservation is only wired into the three pipeline executors (\`PipelineExecutor\`, \`PullingAsyncPipelineExecutor\`, \`PushingAsyncPipelineExecutor\`). Other \`ThreadPool\` users (background merges, fetches, etc.) still keep up to \`max_untracked_memory\` per thread unreported. Narrow the documented contract to match the implementation and call out the limitation explicitly so it does not surprise operators. CI report: #104965 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ckhouse-local` `Server.cpp` propagates the server setting `additional_memory_tracking_per_thread` into the global atomic that the pipeline executors read, but `LocalServer.cpp` did not. As a result `clickhouse-local --config-file ...` ignored the setting entirely: the atomic stayed at the 4 MiB default regardless of what the config said. That is why 04117 was still failing on every build after disabling the speculative reservation in its config -- the disablement was a no-op. Apply the same store in `LocalServer::processConfig` (mirroring `Server.cpp`, including the `INT64_MAX` clamp so a huge misconfigured value cannot wrap negative). This also addresses the review comment from `clickhouse-gh` (#104965 (comment)...) on `tests/config/config.d/additional_memory_tracking_per_thread.xml`: the new test `04240_additional_memory_tracking_per_thread_speculative.sh` runs `clickhouse-local` with a private config that re-enables the setting and verifies that the speculative reservation -- not `max_untracked_memory = 0` -- trips the limit and surfaces as a normal `MEMORY_LIMIT_EXCEEDED`. The earlier 04238 / 04239 tests force the same exception path via `max_untracked_memory`, so they pass even if the speculative path is broken; 04240 closes that gap. CI report: #104965 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`04239_additional_memory_tracking_per_thread_concurrent` spawns 64 background `clickhouse-client` processes and gives them 15 s to finish. Under the flaky check that runs alongside many other parallel tests, the per-process startup overhead alone can take longer than that, so up to 24 / 64 clients failed to return inside the window and the test reported a phantom hang (`hung=24` vs the expected `hung=0`). The regression we are guarding against would manifest as queries never finishing at all -- so finishing slowly under heavy CI load is fine, but finishing slowly inside a tight timeout is a false alarm. Lower the concurrency to 32 (still 128 worker jobs across the 4-thread queries -- more than enough to surface the original deadlock) and raise the timeout to 60 s so the test has room to breathe. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104965&sha=51217d026f4482d5c6bde582e9e0a11be51a7fcd&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29 PR: #104965 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Do not disable this setting for tests; it should be on. |
Memory overaccounting is the goal of this PR. It is exactly what it does - makes sure we track enough additional memory per thread. Your PR #104125 is way more complex and it is still a draft, how could it be a better alternative? |
Also it is interesting that performance shows some difference here, probably because some lightweight queries may never enter |
`04028_arrow_stream_format_detection_memory.sh` uses `clickhouse-local` with a deliberately tight `max_memory_usage = 100Mi` to guard against the regression of issue #65036 (ArrowStream format detection allocating ~514 MiB). With the production default of `additional_memory_tracking_per_thread = 4 MiB` and randomized `max_threads`, each pipeline worker thread charges 4 MiB upfront against the query tracker, pushing the cap over the edge intermittently: Code: 241. DB::Exception: Query memory limit exceeded: would use 100.02 MiB (attempt to allocate chunk of 4.00 MiB), maximum: 100.00 MiB. The retry harness reran the same randomized settings 89 times without a single failure, confirming the flake is at the edge of the limit rather than a systematic over-allocation. Mirror the workaround used in `04117_max_threads_min_free_memory_per_thread.sh`: generate a private config that sets `additional_memory_tracking_per_thread = 0` and pass it via `--config-file`. The stateless-test server config already disables the setting (`tests/config/config.d/additional_memory_tracking_per_thread.xml`), but it is not picked up by `clickhouse-local`, which reads its own config. Failing CI report: #104965 (Stateless tests (arm_binary, parallel) at commit 6e029d8). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
It's strange that incrementing a few atomics is comparable to spawning a thread. Then we will have to optimize MemoryTracker. |
|
🕵 Merged current The only red check on
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=104965&sha=c961ec89f199a260af8a1a01a5598486d51bfc81&name_0=PR&name_1=Stress%20test%20(arm_release) (untracked memory growth during |
|
This run has the signature that #125706 fixes (approved by you, still open).
#125706 appends the dump only to a |
|
🕵 Merged current The only red check on Thanks @groeneai for tracking the |
…itches the parent `MemoryTrackerSwitcher` used to set the thread's `untracked_memory` (and its per-CPU contribution) aside and restore it after the switched scope. While the switcher was alive, the bytes deferred before the switch and the bytes deferred inside the scope were both unreported, so together they could exceed the one buffer per thread that `additional_memory_tracking_per_thread` covers (e.g. in `Aggregator::executeOnBlock`). Report the deferred bytes to the previous parent before switching instead. The destructor already flushes before restoring the parent, so the saved untracked memory and per-CPU state are always zero now; remove them together with the now unused `PerCPUMemoryThreadState::save` / `restore`. Add a regression with real trackers that checks the totals while the switcher is alive, and update the per-CPU test that pinned the old save/restore behaviour. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…uery on a thread The per-thread slot held only the most recent reservation, so after A -> B -> A on one pooled thread (A's suspended guard still alive), A's next activation missed its live state and took a second charge for the same untracked-memory buffer. The slot now keeps all live states and looks them up by the credited query tracker. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged current |
|
🕵 Merged current |
…comes empty The `thread_local` slot was created on the first guard and kept for the lifetime of the thread. Pooled threads outlive their queries, so every pool thread that ever ran a pipeline worker kept its idle slot (a `shared_ptr`, a mutex and a vector) forever. `Storage memory check` caught it as memory left live after the `09_cleanup.sql` scenario: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=104965&sha=17ce7561d83b85043183c9ef0e1a918763a7028c&name_0=PR&name_1=Storage%20memory%20check Create the slot only when a charge is actually taken, and release it on the owning thread when its last reservation is gone. Only the owning thread inserts into its slot, so an empty slot seen there stays empty. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed The heap profile showed that 680 bytes of it came from this PR: the
|
On `Stateless tests (arm_asan_ubsan, azure, parallel)` the query memory limit was reached while reading the `MergeTree` table from Azure Blob Storage. The Azure client wraps the exception into `Azure::Storage::StorageException`, so the server reported `STD_EXCEPTION` instead of `MEMORY_LIMIT_EXCEEDED`. This PR flushes pending allocation reports to the query tracker earlier, which moved the point where the limit is hit into the read path. The test checks `WITH ROLLUP WITH TOTALS` under a memory limit, and the storage engine does not matter for that, so use the `Memory` engine. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=104965&sha=8b3960312503a30779f8ac524d7054e652ee956d&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20parallel%29 #104965 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed
|
…cessor work `04491_additional_memory_tracking_per_thread_speculative` and `04492_additional_memory_tracking_per_thread_oversized` used to pass even when the execution-phase reservations in `PipelineExecutor::spawnThreads` and the single-thread branch of `PipelineExecutor::executeImpl` were removed, because the separate reservation guarding finalization threw the same `MEMORY_LIMIT_EXCEEDED`. The queries now evaluate a nonconstant `throwIf` that fails on the first row, so a missing early reservation surfaces as `FUNCTION_THROW_IF_VALUE_IS_NON_ZERO`. `04491` also covers the single-thread branch. Verified locally that both tests fail with those guards removed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… reservation tests `numbers_mt(1000)` with the default `max_block_size` is reduced to a single stream, so the `max_threads = 8` queries in `04491` and `04492` ran through the single-thread branch of `PipelineExecutor::executeImpl` and did not cover the reservation in `PipelineExecutor::spawnThreads`. Add `max_block_size = 100` so the pipeline has several streams. Verified locally: with only the `spawnThreads` guard removed, both queries now report `FUNCTION_THROW_IF_VALUE_IS_NON_ZERO` and the tests fail. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…racking-per-thread Resolved the conflict in `PipelineExecutor::executeImpl`: master removed `spawn_mutex`, so the initial `spawnThreads` call no longer takes the lock; kept the PR's lazy `SpeculativeMemoryReservation` around `processAsyncTasks`.
|
🕵 Pushed |
|
🕵 Merged current The only red check on |
|
Unjustified. |
Each thread accumulates up to
max_untracked_memory(4 MiB by default) of allocations before reporting them to the server-wideMemoryTracker. With many threads, this unreported memory can sum to a large amount, causing the server's tracked memory usage to under-count actual consumption and leading to OOM.This PR introduces a server-level setting
additional_memory_tracking_per_thread(default 4 MiB) and speculatively charges this amount to the server-wideMemoryTrackerfor each worker thread of aPipelineExecutor, including query, merge, and mutation pipelines. The global tracked memory becomes a tighter upper bound on actual consumption whenmax_untracked_memoryfor those workers does not exceed this setting; operators that permit a larger per-query value must raise the server setting accordingly.The reservation is charged on the server-wide (total) tracker only — deliberately not through the query's tracker chain. Query-level accounting feeds heuristics that compare memory deltas against byte thresholds (conversion of aggregation hash tables to two-level via
group_by_two_level_threshold_bytes, spill-to-disk decisions), and phantom reservations ofnum_threads * 4 MiBtrip those thresholds immediately: an earlier revision of this PR that charged the query tracker showed consistent slowdowns of GROUP BY queries in performance tests for exactly this reason. The reservation itself does not alter query-level or user-level accounting (max_memory_usage,memory_usageinsystem.processes); however, every pipeline worker flushes its pending real allocation reports before releasing its outermost reservation, so those counters and memory-based heuristics can become visible sooner while a worker yields, downscales, or completes.The speculative reservation uses the throwing path of the memory tracker, so when it would exceed the server memory limit the corresponding job is treated as failed with
MEMORY_LIMIT_EXCEEDED— the same behavior as if the job itself had exceeded the limit.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a new server setting
additional_memory_tracking_per_thread(default 4 MiB) which speculatively reserves this amount on the server-wideMemoryTrackerfor each worker thread of aPipelineExecutor, including query, merge, and mutation pipelines. When it is at least the workers'max_untracked_memory, it makes server-wide tracked memory a tighter upper bound on actual consumption and reduces the risk of OOM with many concurrent pipeline workers. The reservation does not alter query-level or user-level accounting, but workers flush pending real allocation reports before releasing their outermost reservation, so those counters can become visible sooner while a worker yields, downscales, or completes.Documentation entry for user-facing changes
Modify your CI run
NOTE: If your merge the PR with modified CI you MUST KNOW what you are doing
NOTE: Checked options will be applied if set before CI RunConfig/PrepareRunConfig step
Include tests (required builds will be added automatically):
Exclude tests:
Extra options:
Only specified batches in multi-batch jobs:
Workflow [PR]
Sync PR [sync-upstream/pr/104965]