Repository navigation
Move more fields from MergeTreeDataPart into a shared per-table cache - #93694
nikitamikhaylov wants to merge 14 commits into
Conversation
|
Workflow [PR], commit [502e40c] Summary: ❌
AI ReviewSummaryThis PR extends the per-table sharing of Findings
Final VerdictNeeds changes before merge: the new byte metric for |
db7e223 to
2461927
Compare
|
@azat WDYT? 😢 |
azat
left a comment
There was a problem hiding this comment.
In general LGTM, please take a look at the comments
| }; | ||
|
|
||
| mutable std::mutex parts_metadata_cache_mutex; | ||
| mutable std::unordered_set<std::shared_ptr<const NamesAndTypesList>, SharedNamesAndTypesListHash, SharedNamesAndTypesListEqual> columns_list_cache TSA_GUARDED_BY(parts_metadata_cache_mutex); |
There was a problem hiding this comment.
Let's also expose it via system.tables and write a test, similar to getColumnsDescriptionsCacheSize
There was a problem hiding this comment.
And also it make sense to add refcnt as well, to measure how many cache hits we have
There was a problem hiding this comment.
Though it looks OK
SELECT
`table`,
parts,
columns_descriptions_cache_size,
parts / columns_descriptions_cache_size AS q
FROM system.tables
WHERE (q IS NOT NULL) AND (NOT isNaN(q))
ORDER BY q ASC
LIMIT -10
Query id: 50963446-7d1e-4c2e-9263-9a6648822418
┌─table────────────────────────────────────────────┬─parts─┬─columns_descriptions_cache_size─┬─────────────────q─┐
1. │ processors_profile_log_7590787529836127017 │ 817 │ 3 │ 272.3333333333333 │
2. │ aggregated_zookeeper_log_14962686554716995193 │ 584 │ 2 │ 292 │
3. │ asynchronous_insert_log_12366379321827847140 │ 302 │ 1 │ 302 │
4. │ transactions_info_log_2864128213711090115 │ 927 │ 3 │ 309 │
5. │ query_views_log_17494275091474536648 │ 943 │ 3 │ 314.3333333333333 │
6. │ background_schedule_pool_log_8901488774449704592 │ 957 │ 3 │ 319 │
7. │ text_log_8722955205913565286 │ 1046 │ 3 │ 348.6666666666667 │
8. │ text_log_15470189561651757858 │ 1227 │ 3 │ 409 │
9. │ asynchronous_insert_log_4169292021092689014 │ 1551 │ 3 │ 517 │
10. │ asynchronous_insert_log_7963218501266431824 │ 2261 │ 3 │ 753.6666666666666 │
└──────────────────────────────────────────────────┴───────┴─────────────────────────────────┴───────────────────┘5e2eb62 to
0f4c2c3
Compare
Co-authored-by: Azat Khuzhin <[email protected]>
…tainers (cherry picked from commit a2ef2fc24be848cba56a852d502aaefa02aa3a8d)
|
@azat I've added a special allocator that can help counting memory for these shared caches. Look what it can do :) |
azat
left a comment
There was a problem hiding this comment.
I have not looked at MergeTreeData yet, will look after serialization changes.
| /// This allocator allows to track memory usage of containers of arbitrary types. | ||
| /// The usage is simple: container.get_allocator().getBytesAllocated() | ||
| template <typename T> | ||
| struct BytesAwareAllocatorWithMemoryTracking |
There was a problem hiding this comment.
Maybe AllocatorWithMemoryAndUsageTracking will be a better name?
Or something similar
| /// During the container copy, the copied allocator should receive | ||
| /// the previously defined amount of bytes allocated and then live its own life. | ||
| BytesAwareAllocatorWithMemoryTracking<T> allocator; | ||
| allocator.bytes_allocated = bytes_allocated; |
There was a problem hiding this comment.
Should it be allocator.bytes_allocated = std::make_shared<size_t>(*bytes_allocated) ?
| return bytes_allocated == other.bytes_allocated; | ||
| } | ||
|
|
||
| std::shared_ptr<size_t> bytes_allocated = std::make_shared<size_t>(0); |
There was a problem hiding this comment.
Can you add a comment why it is shared_ptr? Apparently for rebind
| BytesAwareAllocatorWithMemoryTracking(BytesAwareAllocatorWithMemoryTracking && other) noexcept | ||
| : bytes_allocated(std::move(other.bytes_allocated)) | ||
| { | ||
| other.bytes_allocated = std::make_shared<size_t>(0); |
There was a problem hiding this comment.
If we move, should be allocate other.bytes_allocated? If not, maybe std::exchange is enough? (same goes for operator=(&&)
This is top-notch! |
|
|
||
| /// Pool for constant serialization objects. | ||
| /// Used to create them only once and share them between different columns. | ||
| class SerializationObjectPool |
There was a problem hiding this comment.
I see there is already a DataTypesCache class. Maybe I can unify it
|
Great work! Have you considered extending this more aggressively to a global cache across tables? I've discussed this with @azat in TG. In my fork, I've implemented a global ColumnsDescription cache using a flyweight design pattern — the shared_ptr custom deleter auto-evicts entries when refcount drops to zero, so we don't need to modify the destructors of parts intrusively. This global cache helps significantly in scenarios where there are many similar tables — for example, when some systems split tables by day (treating each table as a partition for flexible management). In such setups, the per-table cache still results in duplicated metadata across tables with identical schemas. The code looks like this: std::shared_ptr<ColumnsDescription> getColumnsDescription(const NamesAndTypesList & columns)
{
static std::shared_mutex columns_description_pool_mutex;
static absl::flat_hash_map<std::string_view, std::weak_ptr<ColumnsDescription>> columns_description_pool;
auto key = std::make_unique<String>(columns.toString());
{
std::shared_lock<std::shared_mutex> read_lock(columns_description_pool_mutex);
auto it = columns_description_pool.find(*key);
if (it != columns_description_pool.end())
{
if (auto res = it->second.lock())
return res;
}
}
std::unique_lock<std::shared_mutex> write_lock(columns_description_pool_mutex);
auto [it, inserted] = columns_description_pool.emplace(*key, std::weak_ptr<ColumnsDescription>());
if (!inserted)
{
if (auto res = it->second.lock())
return res;
}
CurrentMetrics::add(CurrentMetrics::PartsColumnsDescriptions);
CurrentMetrics::set(CurrentMetrics::PartsColumnsDescriptionsCapacity, columns_description_pool.capacity());
std::shared_ptr<ColumnsDescription> ret{
new ColumnsDescription(columns),
[k = std::move(key)](ColumnsDescription * ptr)
{
{
std::unique_lock<std::shared_mutex> lock(columns_description_pool_mutex);
columns_description_pool.erase(*k);
CurrentMetrics::sub(CurrentMetrics::PartsColumnsDescriptions);
CurrentMetrics::set(CurrentMetrics::PartsColumnsDescriptionsCapacity, columns_description_pool.capacity());
}
delete ptr;
}};
it->second = ret;
return ret;
}I'd love to hear your thoughts on whether a global approach could be integrated here. Also noticed that the serialization object pool you split out in #96563 is already a global pool — so it seems natural to take the same approach for other fields as well, making it consistent across the board. |
|
Hi @amosbird |
|
Thanks for the clarification. Hope to see some future improvements on the global cache path 🙂 |
|
@nikitamikhaylov, |
8f93160 to
0020628
Compare
|
Dear @azat, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
Reconcile the per-table shared-cache changes with master's independent memory work for `IMergeTreeDataPart` metadata, and address review feedback. Conflicts and reconciliation: * `NamesAndTypesList` now derives from a `std::list` using `BytesAwareAllocatorWithMemoryTracking` (keeping master's `VectorWithMemoryTracking` for `NamesAndTypes`); the bytes-aware allocator still delegates allocation to `AllocatorWithMemoryTracking`, so master's memory-tracking guarantees are preserved while `getBytesAllocated` becomes available for the caches. * `getColumnsDescriptionForColumns` combines master's nullable `with_collected_nested` / `share_nested_offsets` with this branch's shared `column_name_to_position` and byte accounting. * `setColumns` keeps master's `ScopedJemallocThreadArena` and the nullable `with_collected_nested` fallback together with the shared caches. * `MergeTreeDataPartWide`/`checkDataPart` adopt master's substreams-based consistency checks, dereferencing the now-shared `columns` member. Review fixes folded in: * `BytesAwareAllocatorWithMemoryTracking::allocate` increments the byte counter only after a successful allocation (no drift on a throwing alloc). * `select_on_container_copy_construction` returns a fresh (zero) counter so a copied container tracks only its own bytes instead of double-counting into the source's counter; move ctor/assignment use `std::exchange`. * Restore metric semantics: `ColumnsDescriptionsCacheSize` stays a count (+/-1) and the byte totals go to a separate `ColumnsDescriptionsCacheBytes` handle; wire `NamesAndTypesCacheSize`/`NamesAndTypesCacheBytes` handles too. * Compute `cache_bytes` after deduplication so a discarded `with_collected_nested` (null when equal to `original`) is not over-counted. * Fix the off-by-one eviction check in `decrefNamesAndTypesListInSharedCache` (the part's `columns` is not reset before the call, so the count is 2). * Fix the `projeciton` typo in `checkDataPart`. Fix the `Build (arm_tidy)` failure (https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=93694&sha=fd89fafb5b4e00fceae8177c3d1673f51cea6d48&name_0=PR&name_1=Build%20%28arm_tidy%29): the allocator's required non-explicit rebind constructor is marked `NOLINT(google-explicit-constructor)` and `NameToPositionMap` uses the transparent `std::equal_to<>`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
* `gtest_bytes_aware_allocator` covers exception-safe byte accounting in `allocate`, container tracking, the copy path (fresh per-copy counter, no double-counting into the source), and the move path. * `04417_names_and_types_cache_in_system_tables` checks that parts with the same structure share a single cache entry and that the `*_cache_size` columns stay count-based while `*_cache_bytes` report byte sizes. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Fix submodule pointer regression that broke CMake configuration in `Fast test` and `Build (arm_tidy)`. Every merge of master into this long-lived branch was silently keeping the branch's stale submodule commits for `contrib/xz`, `contrib/usearch`, `contrib/wasmedge`, and `contrib/wasmtime` instead of master's. The stale `contrib/xz` pointed at a pre-5.8.3 commit missing `contrib/xz/src/liblzma/check/crc32_arm64.h`, so CMake failed with "Cannot find source file" / "No SOURCES given to target: _liblzma". This PR does not touch these contribs, so reset all four gitlinks to master's values. CI report: #93694
… signature `master` changed `IStorage::getInMemoryMetadataPtr` to take `(ContextPtr query_context, bool bypass_metadata_cache)` and to return a lifetime-safe `StorageMetadataHandle` whose rvalue `operator->` is deleted (to catch dangling references into a temporary snapshot). The new call site added by this branch in `checkDataPart.cpp` still used the old no-argument form and bound a reference directly into the returned temporary, which both failed to compile and would have dangled. Store the snapshot in a local so `projections_description` stays valid for the whole loop, and pass `(nullptr, /*bypass_metadata_cache=*/true)` since no query context is available on the data-part check path. Verified locally by compiling `checkDataPart.cpp` (ARM debug build).
| cache_bytes += cache.with_collected_nested->getBytesAllocated(); | ||
| cache_bytes += cache.column_name_to_position->get_allocator().getBytesAllocated(); | ||
|
|
||
| auto [_, inserted] = columns_descriptions_cache.emplace(columns, cache); |
There was a problem hiding this comment.
columns_descriptions_cache_bytes is still missing one whole allocation class here: columns_descriptions_cache.emplace(columns, cache) copies columns into the unordered_map key, and that copied NamesAndTypesList allocates its own list nodes through the key's allocator. cache_bytes only sums the shared value objects, so wide schemas will under-report both system.tables.columns_descriptions_cache_bytes and CurrentMetrics::ColumnsDescriptionsCacheBytes.
Please include the stored key's get_allocator().getBytesAllocated() in the inserted/evicted byte total (for example via the iterator returned by emplace).
|
Dear @azat, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
Closing in favor of #109816 About missing / differences:
|
…d to load A projection part that fails to load before its columns are set (for example because of a corrupted serialization.json) has an empty column list. CHECK TABLE compared the projection's on-disk columns.txt against that empty list and reported a misleading "Columns doesn't match ... Expected: 0 columns" error, hiding the real corruption. Take the expected columns from the projection metadata when the part's own columns are unavailable, so the check proceeds and reports the actual broken file. Extracted from ClickHouse#93694. Co-Authored-By: Claude Fable 5 <[email protected]>
…d to load A projection part that fails to load before its columns are set (for example because of a corrupted serialization.json) has an empty column list. CHECK TABLE compared the projection's on-disk columns.txt against that empty list and reported a misleading "Columns doesn't match ... Expected: 0 columns" error, hiding the real corruption. Take the expected columns from the projection metadata when the part's own columns are unavailable, so the check proceeds and reports the actual broken file. Extracted from ClickHouse#93694. Co-Authored-By: Claude Fable 5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Extending a per-table cache for parts fields, reducing memory usage when tables contain many parts and many columns.
Details
A jemalloc profile report.pdf showed that a big chunk of memory is eaten by IMergeTreeDataPart fields even with an improvement done here #89352 by @azat
Documentation entry for user-facing changes