Repository navigation
Do not leave memory charged to a user after the query that used it - #113647
Conversation
`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]>
|
Workflow [PR], commit [939211e] Summary: ✅
AI ReviewSummaryThis 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 Findings❌ Blockers
Tests
Final VerdictChanges requested. The PR fixes many important accounting holes, but it still misses the block-based async-insert producers entirely, and LLVM Coverage Report |
…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]>
|
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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I'll keep iterating and addressing issues in other PRs. Otherwise this won't ever finish
|
@Algunenano |
That's impossible, sorry. This is forward only |
…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]>
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
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_usertripped 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:
INSERTintoMemory/Set/Join, 1M rowsMemoryeviction on insert, 5 cyclesTRUNCATEofMemory/Set/Join, 5 cyclesSYSTEM RELOAD DICTIONARYCREATE OR REPLACE TABLEOPTIMIZE TABLE ... FINAL, one mergeData 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_userbefore 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:
MemoryandSetpublish 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, asUncompressedCacheCellnow does, which forBlocksandSetmeans telling table-owned instances from the query-local ones a plainINbuilds. Left as a follow-up.Closes: #113060
Closes: #77776
Related: #90269
Related: #113408
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
max_memory_usage_for_userbeing 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_useris 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
26.10.1.1341-master(included in26.10and later)