Skip to content

Do not leave memory charged to a user after the query that used it - #113647

Merged
Algunenano merged 58 commits into
ClickHouse:masterfrom
Algunenano:fix-user-tracker-drift
Oct 2, 2026
Merged

Algunenano merged 58 commits into
ClickHouse:masterfrom
Algunenano:fix-user-tracker-drift

Conversation

@Algunenano

@Algunenano Algunenano commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

Memory charged to a query but freed by another thread, or after its tracker was re-parented, stayed on the per-user tracker until that user had no queries left. A user that always has a query in flight therefore accumulated charges for memory it does not hold, until max_memory_usage_for_user tripped on it, and the opposite case left the tracker reading below what the user actually holds.

Each site now accounts both sides the same way: if an allocation is not charged to the query, the release is not charged either. That covers the data of in-memory table engines, the uncompressed cache, the asynchronous insert queue and its flush context, table metadata, dictionary loading, the lookup table a time zone is used through, and what a merge leaves behind. On top of that, whatever a query still holds when its tracker goes away is settled into the server total, so its user ends the query at zero, and debug builds warn when that amount is large enough to be worth fixing where it happens.

Measured with a query holding a known amount while other queries run, so drift is visible in both directions:

per query before after
async inserts (31 columns) 15-96 KB 0
INSERT into Memory / Set / Join, 1M rows +24 MB / +6.7 MB / +16 MB 0
Memory eviction on insert, 5 cycles +37.2 MB 0
TRUNCATE of Memory / Set / Join, 5 cycles -170 to -201 KB 0
reads through the uncompressed cache up to the cache size 0
SYSTEM RELOAD DICTIONARY 25 KB 0
CREATE OR REPLACE TABLE 20-56 KB 0
first query naming a time zone 4.5 MB 0
OPTIMIZE TABLE ... FINAL, one merge 1,138,002 B 64 B

Data waiting in the asynchronous insert queue keeps counting against the user that pushed it, which it did not while the queue owned it on its own: 46.4 MB of queued data now shows as charged, and stops counting once flushed.

The per-user limit also applies at the boundary between periods now. The first query of a period writes max_memory_usage_for_user before its group is attached to the user, and what it allocated before it had a user is checked against that limit instead of being moved onto the user unchecked, so a query that already went past its own limit is refused there rather than at whatever it allocates next.

Known limitation: Memory and Set publish their data to readers, so a query holding the last reference to a version that was already replaced still frees it against its own tracker. That free saturates at the query root and the remainder goes to the server total, and the query settles when it ends, so the user does not drift; what remains is a transient under-count for that one query, bounded by what it holds. Closing it needs the release to happen inside the owned object, as UncompressedCacheCell now does, which for Blocks and Set means telling table-owned instances from the query-local ones a plain IN builds. Left as a follow-up.

Closes: #113060
Closes: #77776
Related: #90269
Related: #113408

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed max_memory_usage_for_user being exceeded by memory the user no longer holds. Memory that a query allocates but does not free itself, such as the data of in-memory table engines, cache entries and data waiting in the asynchronous insert queue, is now accounted to whoever owns it, and whatever a query leaves behind is settled when it ends. max_memory_usage_for_user is also applied when a query hands over memory it allocated before it had a user.


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

Version info

  • Merged into: 26.10.1.1341-master (included in 26.10 and later)

Algunenano and others added 26 commits August 4, 2026 19:00
`TasksStatsCounters` are created on a thread's first attach to a thread group and
then kept for the lifetime of the thread: nothing releases them on detach, only two
error paths and `MainThreadStatus` teardown. They are therefore freed with no thread
group attached, so the free reaches only the global tracker while the allocation was
charged to whichever query happened to attach to that thread first. That charge is
never reversed and stays on the user's tracker, which matters because the per-user
tracker is only cleared once the user has no queries left.

The counters are per thread, not per query, so exclude them from query accounting.
`total_memory_tracker` still accounts them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…en filled

`logQueryFinishImpl` copies the profile events snapshot into the query log element,
and `elem` is captured by value in the finish callback that `BlockIO` owns, so the
snapshot stays alive until `BlockIO` is destroyed - long after the query is done.
It is about 12 KB per query with `log_profile_events` enabled, and nothing reads it
after the element has been handed to the log, so drop it there instead of carrying it
for every in-flight query.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…g query

The `InsertQuery` key (a cloned AST and a `Settings` copy), the `InsertData` holder, the `Entry` and the
map and list nodes all outlive the query that pushes them and are freed by a flush thread, which cannot
uncharge the query that paid for them. The charge stayed on the per-user tracker, and since that tracker
is only cleared once the user has no queries left, a user who always has one query in flight drifted up
towards `max_memory_usage_for_user` on memory it did not hold.

The inserted data itself stays charged to the user, as before: it is already allocated by the time it
reaches `pushDataChunk`, and `Entry::resetChunk` uncharges it explicitly.

For a wide insert (31 columns, `async_insert=1`) the per-user tracker grew by 28,843 bytes per query
before and 2,843 bytes after.
… detaches

Everything the flush accumulates in its own context - the per-column query access info, the insertion
table, the process list element - is allocated while the thread is attached to the flush thread group and
charged to the inserting user. The context was declared before the `QueryScope`, so it was destroyed
after the thread had detached and its memory tracker had been re-parented to `total_memory_tracker`: the
frees were credited there while the charge stayed on the per-user tracker for good.

Declaring the `QueryScope` first makes the context die while the thread is still attached, so the frees
land where the allocations did. `system.query_thread_log` needs that context when the thread detaches, so
the performance counters are finalized explicitly while it is alive.

This was the bulk of the drift on the asynchronous insert path. Per-user tracker growth per query, for a
single-row insert with `async_insert=1`:

    columns   before   after
         15   15,178       0
         31   32,176       0
         45   47,075       0
         61   63,803       0
         91   95,787       0
…rented

`detachFromGroup` re-parented the thread's memory tracker to `total_memory_tracker` and only then released
`local_data` (which holds the query text for logs), the query id, the query context and the fatal error
callback. Those were allocated on attach while the thread was charged to the query, so their frees were
credited to the global tracker and the charge stayed on the per-user tracker, which is only cleared once
the user has no queries left.

Releasing them before the re-parenting, and flushing the untracked memory they produced, keeps the
accounting symmetric. `finalizePerformanceCounters` above is the last user of the query context, so
nothing below reads them.
`setColumns` copied the `SerializationInfoByName` map, which only copies the pointers: the infos
themselves stay owned by whoever built them while writing the part (`MergeTreeDataWriter`, `MergeTask`,
`MutateTask`), so they were kept alive on the part - and outside the dedicated arena - until a background
thread drops the part, with the charge left on the writer's per-user tracker. There is one info per
column, about 100 bytes per column of drift on the asynchronous insert path.
Each of them restated why a charge that is never reversed stays on the per-user tracker. Keep the reason
where the code needs it and drop the repetition.
The storage object, its settings copy and its metadata live until the table is detached or the server stops,
and are freed by whoever does that, which cannot uncharge the query that ran the CREATE. The charge stayed on
the per-user tracker, which is only cleared once the user has no queries left, so a user creating tables in a
loop drifted up towards `max_memory_usage_for_user` on memory the server holds. `CREATE OR REPLACE TABLE` grew
the per-user tracker by 19,719 bytes at one column and 55,678 at fifty; both are zero now.

`IStorage` copies the metadata instead of adopting the caller's object, so that the copy the table keeps is
allocated with the tracker blocked as in `setInMemoryMetadata`; adopting a charged object that
`setInMemoryMetadata` later frees blocked would leak the charge the other way round.

Table-lifetime allocations also go to the dedicated arena now, so they no longer fragment the per-CPU arenas
that serve queries. That arena is no longer MergeTree-only, so the metric description says so.
Memory that a query allocates and then leaves in a table has to be checked against the memory limits while the
query runs, but must not stay charged to the query afterwards: the table outlives it, and whoever frees the
data cannot uncharge the query, so the bytes sit on the per-user tracker until the user happens to run no
queries at all.

This hands a charge over from the query to the server: the memory stays allocated and `total_memory_tracker`
keeps accounting it for the server-wide limit, while the query's tracker and its parents below the global one
stop counting it. As in `adjustOnBackgroundTaskEnd`, alloc/free cannot be used for this, since they would
change the total as well.
The blocks handed to a Memory table live as long as the table and are freed by whoever drops or truncates it,
which cannot uncharge the query that inserted them, so the charge stayed on the per-user tracker for good: five
inserts of a million rows left 24 MB per insert on the user, and a user inserting into a Memory table drifted
towards `max_memory_usage_for_user` on memory the server holds.

The insert is still accounted while it runs, so `max_memory_usage` still stops an insert that is too large;
only once the blocks belong to the table is their charge handed to the global tracker. `drop` and `truncate`
release them with the tracker blocked, so the query doing that is not credited for memory it never held.

The amount handed over is the table's accounted growth, which is an estimate of what the query was charged, so
a fraction of a percent can be left behind: a ten million row insert leaves about 52 KB of 313 MB.
Same as the Memory engine: the rows go into a set or hash table that lives as long as the table, and the query
that inserted them kept the charge on the per-user tracker for good - 6.7 MB per million-row insert for Set and
16.2 MB for Join. Hand it over once the rows belong to the table, and release it on truncate with the tracker
blocked so the truncating query is not credited for it.

The table's own growth is the estimate here rather than the inserted block's size: the hash structures are
charged to this query too and dominate, so using the block size left tens of megabytes per insert behind.
A decompressed block goes into a cache shared by every query and is freed by whichever query's insertion evicts
it, which cannot uncharge the query that read it. So the charge stayed on the per-user tracker: with a 2 MB
cache the tracker of the user doing the reads sat at 1.37 MB until later queries happened to evict those
entries, and a user who stops reading keeps the charge.

The insert-triggered eviction is already symmetric, since `removeOverflow` runs inside `getOrSet`. Releasing our
own reference is not, so it goes through `releaseCell`: the reader can hold the last reference to an
already-evicted cell, and freeing it charged would credit a query that was never charged for it.
The entry the aggregation leaves behind to size future hash tables lives in a cache shared by every query and
is freed when another query's insertion evicts it, so the charge stayed on the per-user tracker. It is small per
entry and bounded by `max_entries_for_hash_table_stats`, but it is attributed to whichever user happened to run
the aggregation first and is never given back.
`SYSTEM RELOAD DICTIONARY` grew the per-user tracker by 25,280 bytes per reload, whatever the dictionary's size,
and the charge is never reversed: the loader releases the previous version from its own thread, and the tracker
is only cleared once the user has no queries left.

`ExternalLoader::doLoading` already holds a `MemoryTrackerBlockerInThread`, but that only covers the loader
thread, while loading a dictionary with a CLICKHOUSE source runs a query of its own whose pipeline threads
inherit the thread group instead of the thread-local blocker. That was the difference between a CLICKHOUSE
source (25,280 bytes) and a FILE source (7,899); with a CACHE layout, which does not load on reload, there was
no drift at all.

So the loading now runs in a group whose memory tracker parents to `total_memory_tracker` rather than to the
triggering query's, which every thread joining the group inherits. Profile events still roll up to the parent
group, so the reload query still reports the rows the loading read. All three shapes now measure zero.
The query context is created before the query scope exists, so it is never charged to the query. `QueryState`
is then deliberately destroyed before the scope, so that query-owned deallocations land on the query's tracker,
and the context goes with it - crediting the query for 16 KB of `Settings` it never held. Every query did this,
so a user's tracker read ~23 KB per query lower than what the user actually held, which weakens
`max_memory_usage_for_user` in the opposite direction to a leak.

Holding one reference until after the thread detaches makes the two sides symmetric: allocated before the scope
without a charge, released after it without a credit. Measured against a user with a large held allocation, so
that the tracker can move down as well as up, the per-query delta for `SELECT 1` goes from -22,664 bytes to
+552, and the same -23 KB was there before this branch.
Entries are cached without charging the query that populated them, so releasing them must not credit whoever
triggers the removal either - that pushes an unrelated user's tracker below what it actually holds. With 6.4 MB
of uncompressed cache filled by one user, another user's `SYSTEM DROP UNCOMPRESSED CACHE` moved its tracker by
40 bytes instead of the whole cache.

Eviction from `set` was already symmetric, since it runs under the same blocker as the insertion. The explicit
paths were not: `clear`, both `remove` overloads, `removeIfMatches`, and `setMaxCount` / `setMaxSizeInBytes`,
which shrink the cache through `removeOverflow`.
Memory charged to a query but freed by another thread, or after its tracker was re-parented, stayed on the
per-user tracker until that user had no queries left, so `max_memory_usage_for_user` could trip on memory the
user does not hold. When a query's tracker goes away, hand whatever is left of it to the global tracker, which
accounts those bytes either way, and warn in debug builds when the amount is large enough to be worth fixing
where it happens. `setDriftExpected` marks the sites that hand memory over on purpose, such as a merge leaving
behind the part it produced.

Bytes a query frees but never held now go to the global tracker directly instead of being taken off its user,
which used to leave the user reading below what it holds. Inside a query the whole free still goes up, since a
view or a merge can free what the query above it is charged for.

A user's limits and peak now start a new period when its next query arrives rather than when its last one
leaves, which would erase what a thread group that is still alive is charged for.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The rows a `Set` or `Join` table keeps outlive the query that inserted them, so estimating their size from the
table's growth and handing that estimate over was neither exact nor needed: the query is charged while it runs,
which is what enforces the memory limits, and what it leaves behind is settled when it ends. Truncating drops
data the server owns by then, so it is released without crediting the query that asked for the truncate.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The blocks a `Memory` table holds belong to the table, and to the server total once the query that wrote them
has ended, so replacing them - on insert with eviction, on truncate, on mutate or on restore - is released
through one place that does not credit whichever query happens to do it. The insert itself stays charged while
it runs, so the memory limits still apply to it, and what it leaves behind is settled when it ends.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Same as for `Set`: by the time the table is truncated its data is accounted in the server total, so releasing it
must not be taken off the user running the truncate.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…able arena

Not charging the creating query was one-sided: the storage object and its metadata are freed when the table is
dropped or replaced, by a query that would then be credited for memory it never allocated. Charge it, so that
`max_memory_usage` covers a `CREATE` with a wide schema, and let what survives the query be settled when it
ends. The metadata can be adopted rather than copied again now that both sides are accounted the same way.

The arena for table-lifetime state stays: it is about placement, keeping objects that outlive the query out of
the arenas that serve queries, and does not affect accounting.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Everything the queue holds - the key with its copy of the query and the settings, the data holder, the map and
list nodes, and the flush's own context - was allocated by one query and is released by another, which could
not uncharge the first. Whichever side is not charged, both sides must match, so all of it is now allocated and
released without charging any query: the pushing one is not left holding it and the flushing one is not
credited for it.

The data itself keeps belonging to the user that pushed it: an entry holds the thread group of that query, so
the bytes count against `max_memory_usage_for_user` for as long as they wait in the queue, and are released
against the same tracker that was charged for them, instead of against whichever user's tracker the flush
thread happened to be switched to.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The decompressed block goes into a cache shared by every query, so the query that happens to fill it is not
charged for it. The release has to match, and doing it in the reader was both too wide and incomplete: it also
covered the reader's own buffers, and missed the cells released anywhere else, such as an eviction or a drop of
the cache. The cell releases its own bytes instead, wherever its last reference dies, and the reader is left
charged for what is really its own: the input buffer, the codec and the compressed buffer.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Blocking removals in `CacheBase` covered all caches, but only some fill their entries without charging the
query that reads them. For the rest the entry is charged on insertion, so not charging the removal would leave
that charge on the filling user for good, which is the same asymmetry the other way round. Whether a cache's
entries belong to the server is a property of that cache, so it is expressed where the entries are, as
`UncompressedCacheCell` does, not here.

The aggregator's hash table size hint goes back to being charged on insertion for the same reason: it was
blocked on the way in and not on the way out, and what a query leaves behind is settled when it ends anyway.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Checks the three things that were wrong: what a query leaves behind in a table does not stay charged to its
user, data waiting in the asynchronous insert queue does count against it until flushed, and it stops counting
once it is. The user needs a query of its own running the whole time, otherwise its tracker starts a new period
and any drift is hidden, which is what made this class of bug so easy to miss.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The adaptive busy timeout can shorten the wait from the shard's recent history, so the data the test wants to
find waiting in the queue could already be gone.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Algunenano Algunenano added the memory When memory usage is higher than expected label Aug 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [939211e]

Summary: ✅


AI Review

Summary

This PR substantially improves per-user memory accounting by reparenting long-lived allocations and settling residual query drift on teardown, and many earlier review points are fixed in the current code. I still see one remaining blocker in the block-based async-insert path and one new major gap in StorageJoin, plus several author-dismissed follow-ups that still weaken live memory-limit enforcement for reader-held table state.

Findings

❌ Blockers

  • [src/Interpreters/AsynchronousInsertQueue.h:80] pushQueryWithBlock still accepts a default nullptr queued_data_tracker, and the unchanged block-producing async callers (INSERT ... SELECT via src/Processors/Transforms/AsyncInsertQueueTransform.cpp:294 and Prometheus remote-write via src/Storages/TimeSeries/PrometheusRemoteWriteProtocol.cpp:263) still use that path. Their queued Block data therefore stays on the producer query until it ends, then settleDriftOnQueryEnd removes it from the user and the later Entry::resetChunk free runs under MemoryTrackerBlockerInThread, so the queued bytes stop counting against max_memory_usage_for_user while they are still buffered in the async queue.
    Suggested fix: either require every pushQueryWithBlock caller to pass a dedicated Process tracker for queued data, or make pushQueryWithBlock itself create/copy into one so the null path cannot bypass user accounting.

⚠️ Majors

  • [src/Storages/StorageJoin.cpp:230] The blocker around join = std::move(new_data) only protects the storage-held join reference. Reader clones from getJoinLocked share HashJoin::RightTableData via reuseJoinedData, and in HashJoin the storage_join_lock member is destroyed before the shared data member. The last reader can therefore drop the lock first and then free server-owned join state in its own query thread, under-counting live max_memory_usage / max_memory_usage_for_user by up to the size of the shared join data after this swap path.
    Suggested fix: make the final RightTableData release itself non-query-charged (for example by wrapping the owned object's destructor path), rather than only blocking the storage-side swap.
  • [src/Storages/StorageMemory.cpp:256] [dismissed by author -- https://github.com/Do not leave memory charged to a user after the query that used it #113647#discussion_r3729754345] StorageMemory still publishes old BlocksWithCounts states through MultiVersion, so a reader can remain the last owner of table-backed blocks after setData. When that reader later frees the old state in its own query thread, it still gets credited for server-owned bytes it never allocated, which weakens live query-level memory enforcement even if the per-user drift settles at query end.
    Suggested fix: distinguish table-owned Blocks from query-local ones and release the final table-owned state on a non-query-charged path.
  • [src/Storages/StorageSet.cpp:296] [dismissed by author -- https://github.com/Do not leave memory charged to a user after the query that used it #113647#discussion_r3729754351] StorageSet has the same last-owner problem: getSet hands readers a shared_ptr, so after truncate a reader can still be the final owner of the replaced table-backed Set and free it in its own query thread. That transiently under-counts the live query's memory usage and weakens its limits by stale set bytes it never allocated.
    Suggested fix: route the final destruction of table-owned Set instances through a non-query-charged path.
  • [src/Interpreters/AsynchronousInsertQueue.cpp:775] [dismissed by author -- https://github.com/Do not leave memory charged to a user after the query that used it #113647#discussion_r4156731475] entry_data_size still comes only from entry->chunk.byteSize(), even though query_parameters are now intentionally copied under queued_data_tracker and kept until flush. A large {param} payload can therefore exceed async_insert_max_data_size without contributing to data->size_in_bytes, CurrentMetrics::AsynchronousInsertQueueBytes, or the size-based flush trigger.
    Suggested fix: include the parameter payload in queue byte accounting, or track it separately but feed the combined total into the queue-size metric and flush limit.
Tests
  • ⚠️ tests/queries/0_stateless/04757_user_memory_tracker_no_drift.sh exercises inline/native async inserts under a holder query, but it does not cover the still-broken block-based async producers (INSERT ... SELECT, Prometheus remote-write) and it does not exercise the reader-held final-release cases in StorageJoin, StorageMemory, or StorageSet.
Final Verdict

Changes requested. The PR fixes many important accounting holes, but it still misses the block-based async-insert producers entirely, and StorageJoin still lets reader-owned destruction free server state against a live query. The dismissed StorageMemory / StorageSet / parameter-size issues remain real follow-ups in the current code.

LLVM Coverage Report

⚠️ No coverage measurement for commit 939211e: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_8.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 6, 2026
Comment thread src/Common/MemoryTracker.cpp Resolved
…locker

The blocker in `initPerformanceCounters` changed the blocker level mid-attach, which flushed the bytes
allocated since `setParent` into the new group. That broke
`ThreadGroupAttach.PreAttachUntrackedMemoryIsNotChargedToTheGroup` and
`MemoryPressureMonitor.NestedThreadGroupInheritsParentPressure` in release builds. Creating `taskstats`
before the tracker is reparented keeps it off the query without a blocker.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113647&sha=df860b966b217440cd678da7be4ace451ea50f45&name_0=PR&name_1=Unit%20tests%20%28amd_llvm_coverage%29
PR: ClickHouse#113647

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Algunenano

Copy link
Copy Markdown
Member Author

It seems there are tons of warnings in logs, not associated to queries, mostly related to distributed/remote(). Since I don't want to complicate this PR more I'm going to lower the debug log from warning to debug and will continue cleaning up in other, smaller, PRs before enabling it

The drift warnings still fire for queries that leave pooled remote connections behind, and a warning sent to a client fails tests that check stderr. Keep them at debug level until those sites are cleaned up.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

join = std::move(new_data);
{
MemoryTrackerBlockerInThread table_data_not_charged_to_the_query;

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 only protects the storage's own join reference.

getJoinLocked clones a HashJoin and shares the old RightTableData through reuseJoinedData, so a reader can still be the last owner of the table-backed hash state. In HashJoin, storage_join_lock is destroyed before data, which means the last reader releases the read lock first and then frees the shared RightTableData in its own query thread.

That free subtracts table-owned bytes from a live query without any matching add, so max_memory_usage / max_memory_usage_for_user can still be under-counted by up to the size of the shared join state after this swap path. The blocker here fixes the storage-held reference, but not the reader-held one.

To close the ownership invariant, the final RightTableData release itself needs to be non-query-charged (for example, a wrapper that blocks in the owned object's destructor), not only the storage-side swap.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I'll keep iterating and addressing issues in other PRs. Otherwise this won't ever finish


PushResult pushQueryWithInlinedData(ASTPtr query, ContextPtr query_context);
PushResult pushQueryWithBlock(ASTPtr query, Block && block, ContextPtr query_context);
PushResult pushQueryWithBlock(ASTPtr query, Block && block, ContextPtr query_context, std::unique_ptr<MemoryTracker> queued_data_tracker = nullptr);

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.

pushQueryWithBlock only preserves user accounting when the caller has already allocated the block under a dedicated queued_data_tracker. The default nullptr here means the unchanged block-producing async paths still take the old ownership route: src/Processors/Transforms/AsyncInsertQueueTransform.cpp:294 and src/Storages/TimeSeries/PrometheusRemoteWriteProtocol.cpp:263 both call this overload without a tracker.

That reintroduces the user-limit hole for those paths. On INSERT ... SELECT with wait_for_async_insert = 0 (and on remote-write if the wait times out), the queued block stays on the producer query until that query ends, settleDriftOnQueryEnd() settles it off the user, and the later Entry::resetChunk() free runs under MemoryTrackerBlockerInThread, so the queued data no longer counts against max_memory_usage_for_user. Please make every block-producing async producer allocate/copy the queued block under its own Process tracker before enqueueing, or remove the default/null path so new callers cannot silently bypass the hand-off.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I'll keep iterating and addressing issues in other PRs. Otherwise this won't ever finish

@Algunenano
Algunenano dismissed azat’s stale review October 2, 2026 17:00

Applied the required changes

@Algunenano
Algunenano added this pull request to the merge queue Oct 2, 2026
Merged via the queue into ClickHouse:master with commit ae47937 Oct 2, 2026
149 checks passed
@Algunenano
Algunenano deleted the fix-user-tracker-drift branch October 2, 2026 22:32
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
@adtitovich

Copy link
Copy Markdown

@Algunenano
could this be backported to 26.3 LTS? We hit it on 26.3.35.3 (User memory limit exceeded while executing AggregatingTransform).

@Algunenano

Copy link
Copy Markdown
Member Author

could this be backported to 26.3 LTS? We hit it on 26.3.35.3 (User memory limit exceeded while executing AggregatingTransform).

That's impossible, sorry. This is forward only

taozhiyi13 pushed a commit to taozhiyi13/ClickHouse that referenced this pull request Oct 15, 2026
…s off

`detachFromGroup` cleared the query id before resetting `local_data` (two
32-byte `make_shared` allocations) and before turning off per-query jemalloc
collection, so those allocations were sampled into `system.trace_log` with an
empty `query_id` (`JemallocSample` and `MemorySample`). `test_jemalloc_global_profiler`
asserts that no positive-size sample of a profiled query lands outside it, and
failed about once in 2,000 runs since ClickHouse#113647 moved `clearQueryId` up.

`String::clear` keeps the buffer, so clearing the id last does not change
memory accounting.

WIP (impl r0): the new integration test still fails on this tree on an
attach-side `MemorySample` row; see the replan request.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
qoega added a commit to qoega/ClickHouse that referenced this pull request Nov 4, 2026
Use `MemoryTracker::reparent` and the queue and metadata lifetime handling from ClickHouse#113647. Remove the duplicate prerequisite implementations and helper-specific tests while retaining initial `Context` accounting. Honor recovery-user setup batching in HTTP after authentication.

Related: ClickHouse#120422
qoega added a commit that referenced this pull request Nov 4, 2026
Preserve current PostgreSQL catalog execution and gRPC responder and workload lifetimes. Reuse the core context changes and memory accounting from #113647. Avoid copying a query context for Flight `SetSessionOptions` while keeping credential validation.

Related: #120422
Related: #123112
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-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

5 participants