Skip to content

Add server setting additional_memory_tracking_per_thread - #104965

Closed
alexey-milovidov wants to merge 144 commits into
masterfrom
additional-memory-tracking-per-thread
Closed

alexey-milovidov wants to merge 144 commits into
masterfrom
additional-memory-tracking-per-thread

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 14, 2026 •

Copy link
Copy Markdown
Member

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 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-wide MemoryTracker for each worker thread of a PipelineExecutor, including query, merge, and mutation pipelines. The global tracked memory becomes a tighter upper bound on actual consumption when max_untracked_memory for 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 of num_threads * 4 MiB trip 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_usage in system.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):

  • Improvement

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-wide MemoryTracker for each worker thread of a PipelineExecutor, 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

  • Documentation is written (mandatory for new features)
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):

  • Fast test
  • Integration tests
  • Stateless tests
  • Stateful tests
  • Unit tests
  • Performance tests
  • All with ASan
  • All with TSan
  • All with MSan
  • All with UBSan
  • All with Coverage
  • All with Aarch64

Exclude tests:

  • Fast test
  • Integration tests
  • Stateless tests
  • Stateful tests
  • Performance tests
  • All with ASan
  • All with TSan
  • All with MSan
  • All with UBSan
  • All with Coverage
  • All with Aarch64

Extra options:

  • Add tests with aarch64 builds
  • do not test (only style check)
  • disable merge-commit (no merge from master before tests)
  • disable CI cache (job reuse)

Only specified batches in multi-batch jobs:

  • 1
  • 2
  • 3
  • 4

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

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

clickhouse-gh Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ed5b503]

Summary: ✅


AI Review

Summary

Adds additional_memory_tracking_per_thread to reserve memory on the server-wide MemoryTracker for pipeline workers, including global overcommit accounting and preservation across memory-worker corrections. Reviewed PR head ed5b503f12559136c90ec3de871fe9e0ae5c8234, the current implementation, regression coverage, and all prior discussion. No remaining actionable findings; previous findings are addressed or their explanations hold against the current code.

Missing context / blind spots
  • ⚠️ Tests were not run locally. Current-head CI is still in progress; completed sanitizer, functional, integration, and performance jobs are needed to finish runtime validation.
Final Verdict

Status: ✅ Approve. No code changes requested; CI completion remains pending.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 14, 2026
Comment thread src/Common/ThreadPool.cpp Resolved
@alexey-milovidov alexey-milovidov added the memory When memory usage is higher than expected label May 14, 2026
alexey-milovidov and others added 2 commits May 14, 2026 18:16
…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]>
Comment thread src/Core/ServerSettings.cpp Resolved
alexey-milovidov and others added 2 commits May 14, 2026 23:54
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]>
Comment thread programs/server/Server.cpp Resolved
alexey-milovidov and others added 8 commits May 15, 2026 06:45
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]>
@alexey-milovidov

alexey-milovidov commented May 15, 2026 •

Copy link
Copy Markdown
Member Author

Do not disable this setting for tests; it should be on.
It is only ok to edit specific tests.

@azat azat self-assigned this May 15, 2026

@azat azat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, this does not cover allocations not from pipeline, and also may lead to significant memory over accounting

I think this should be a better alternative - #104125

@alexey-milovidov

alexey-milovidov commented May 15, 2026 •

Copy link
Copy Markdown
Member Author

and also may lead to significant memory over accounting

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?

@azat

azat commented May 15, 2026

Copy link
Copy Markdown
Member

is way more complex and it is still a draft, how could it be a better alternative?

  • This solution does not cover lots of other thread pools (remote IO, IO, e.t.c.), that can allocate enough memory
  • It will not have huge memory reservations (only up to 4MiB*used CPUs)
    • Right now it does not reserve memory at all, I've tried it in one of iterations, but decided to revert for now, until the performance will be on par

Also it is interesting that performance shows some difference here, probably because some lightweight queries may never enter MemoryTracker before

`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

It's strange that incrementing a few atomics is comparable to spawning a thread. Then we will have to optimize MemoryTracker.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged current master into the branch (25a05657607). The merge was clean and clickhouse builds. There are no unresolved review threads.

The only red check on c961ec89f19 was Stress test (arm_release): the server was killed by the cgroup OOM killer (report). I don't think this PR caused it:

  • Tracked memory matched RSS for the whole run. In all 822 (total) memory limit exceeded messages, the "would use" value equals the current RSS, and untracked memory stayed within a few MiB. So the speculative reservation neither leaked nor drifted.
  • No LOGICAL_ERROR. The MEMORY_LIMIT_EXCEEDED errors raised from SpeculativeMemoryReservation are the intended behaviour above the limit.
  • Memory grew by about 1 GB/s while 04035_url_cluster_callback_cancel_race.sh was running. It runs urlCluster with max_streams_for_files_processing_in_cluster_functions = 3697, and its queries tracked under 100 MB, so the growth bypassed per-query tracking.
  • Over the last 30 days, the same signal 9 failure of Stress test (arm_release) occurred on 10 different PRs.

@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 04035_url_cluster_callback_cancel_race.sh) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

This run has the signature that #125706 fixes (approved by you, still open).

  • At 16:23:51 the urlCluster secondary query 8e5d2fc0 of 04035_url_cluster_callback_cancel_race.sh hit the injected Query memory tracker: fault injected while PipelineExecutor was building the graph. The constructor's catch appended a Query pipeline: dump of all 25,890 processors, so its exception text is 2,131,696 bytes (query_log).
  • Since Write processors_profile_log entries for queries that fail with an exception #121503, logProcessorProfile copies that text into every processors_profile_log row of the query: 25,890 x 2.13 MB, about 55 GB. SystemLogQueue::add runs under MemoryTrackerBlockerInThread, so the copies count in the total tracker but not in the query's (memory_usage 78 MB).
  • MemoryTracking went from 3.2 GiB at 16:23:51 to 42.5 GiB at 16:24:43. The query thread logged nothing after its exception, and the processors_profile_log flush of 4,182 rows started at 16:24:00 never finished. The memcg killed the server at 16:25:19 with anon-rss 52 GiB.

#125706 appends the dump only to a LOGICAL_ERROR. It now conflicts with #126029 in the same catch block; I will merge master into it and resolve the conflict.

@groeneai

Copy link
Copy Markdown
Collaborator

Merged master into #125706 in 9f112f7 (kept the LOGICAL_ERROR guard, took the printPipeline call from #126029). CI is re-running there.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged current master into the branch (8c5a8f3388f). The merge was clean and clickhouse builds.

The only red check on 25a05657607 was Integration tests (arm_binary, 3/4): test_backward_compatibility/test_custom_s3_disk_remote_url_allow_hosts.py failed with UNACCEPTABLE_URL on the old 26.8.28 server image. This is unrelated to memory tracking. It is fixed on master by #126289, which pins the old image to 26.8.26.12, and the merge pulls that fix in.

Thanks @groeneai for tracking the Stress test (arm_release) OOM to #125706.

alexey-milovidov and others added 2 commits October 20, 2026 16:49
…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]>
alexey-milovidov and others added 2 commits October 22, 2026 16:06
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged current master into the branch (4d519602dbc). The merge was clean and clickhouse builds. CI on the previous head 0f8b255b5c8 had no failed tests, and there are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged current master into the branch (17ce7561d83). The merge was clean, it touches none of the files this PR changes, and clickhouse builds. The only red check on 4d519602dbc was Fast test (arm_darwin): 05397_clickhouse_local_locked_path_untouched failed. That has nothing to do with this PR, and master already skips the test on macOS (59f220cb8187), so the merge pulls that fix in. There are no unresolved review threads.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 8b396031250, which fixes the only red check on 17ce7561d83: Storage memory check failed on 09_cleanup.sql (+1,432 bytes live after the scenario, threshold 1,024; report).

The heap profile showed that 680 bytes of it came from this PR: the thread_local slot of SpeculativeMemoryReservation was created on the first guard and kept for the life of each pool thread. Now the slot is created only when a charge is actually taken, and the owning thread releases it when its last reservation is gone. The rest (~750 bytes) is per-thread LZ4 statistics and thread objects. That part depends on how many pool threads happened to stay alive, and it varied between earlier runs of this PR (+384 and +536 bytes, both passing).

unit_tests_dbms memory-tracker tests pass (66), and so do 04491 and 04492 locally. There are no unresolved review threads.

alexey-milovidov and others added 2 commits October 31, 2026 20:14
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 93b9d69ecda: merged current master (clean, it touches none of this PR's files; the main changed translation units pass -fsyntax-only) and fixed the only red check on 8b396031250.

Stateless tests (arm_asan_ubsan, azure, parallel): 04023_rollup_totals_memory_limit failed 3/3 (report). The query memory limit was reached while reading the MergeTree table from Azure Blob Storage, where the Azure client wraps the exception into Azure::Storage::StorageException → STD_EXCEPTION instead of MEMORY_LIMIT_EXCEEDED. This PR flushes pending allocation reports to the query tracker earlier, which moves where the limit is hit. The test is about WITH ROLLUP WITH TOTALS under a memory limit, so it now uses the Memory engine. With that change it reliably gives MEMORY_LIMIT_EXCEEDED locally.

alexey-milovidov and others added 3 commits November 2, 2026 05:46
…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`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 78ad7d5a574: merged current master to resolve the conflict in PipelineExecutor::executeImpl. master removed spawn_mutex from PipelineExecutor, so the first spawnThreads call no longer takes that lock. The lazy SpeculativeMemoryReservation around processAsyncTasks is unchanged. clickhouse builds, and a quick clickhouse-local run of the 04489 queries gives the expected results (the setting is visible, and the tiny-limit query fails with MEMORY_LIMIT_EXCEEDED). There are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged current master into the branch (ed5b503f125). The merge was clean and clickhouse builds. master changed ThreadPool (job_finished split into slot_freed / all_jobs_finished) and PipelineExecutor (cancelWithException); both merged automatically with this PR's SpeculativeMemoryReservation changes. There are no unresolved review threads.

The only red check on 78ad7d5a574 was La Casa Del Dolor (amd_debug): Logical error: Manifest compaction failed to commit after 100 attempts in compactIcebergManifests (report). It has nothing to do with memory tracking. It is tracked in #126287, and the fix is in progress in #129555.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Unjustified.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... memory When memory usage is higher than expected pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants