Repository navigation
Share schema-derived per-part metadata across MergeTree data parts - #109816
Conversation
lz4 bundles a legacy xxhash.h and exported its include directory as a plain -I, which shadowed contrib/xxHash for every dbms source including <xxhash.h> (the Parquet writer silently used lz4's old copy). Link ch_contrib::xxHash into dbms and switch Parquet bloom filter hashing to the XXH_INLINE_ variants (same standardized XXH64 algorithm, so the output is unchanged). Co-Authored-By: Claude Fable 5 <[email protected]>
Each data part carried its own copy of the schema-derived metadata built in setColumns (columns, name-to-position map, serializations map, columns substreams), which dominated RSS for tables with many parts and wide schemas. Intern it in a per-table cache instead: an immutable SharedPartColumns bundle keyed by the stored column list (generalizing the previous columns_descriptions_cache), with nested caches sharing the serializations map (keyed on the recursive serialization kind stacks and settings) and the columns substreams (content-keyed). On a synthetic 3000-part 231-column table this cuts live server memory from 840 MiB to 245 MiB (~200 KB per part). ClickHouse/clickhouse-private#59501 Co-Authored-By: Claude Fable 5 <[email protected]>
Key the name-to-position map with views into the bundle's own column list, copy the columns substreams only on a cache miss, build the serializations cache key as a single framed string instead of two strings per column, and reserve the containers when the size is known. Also open the MergeTree jemalloc arena scope inside the cache build paths, so every interned entry lands in the parts arena regardless of the caller. Co-Authored-By: Claude Fable 5 <[email protected]>
A column's substreams depend only on the column and its serialization kinds, so parts whose substream sets differ in other columns (and never match the whole-object cache) can still share the per-column entries. ColumnsSubstreams now stores shared immutable per-column entries plus a prefix array of global positions, and the bundle interns the entries by content. In the fully fragmented regime (a distinct sparse-column set per part) this cuts the per-part metadata residual by ~20% on a synthetic 231-column table; the disk and wire formats are unchanged. Co-Authored-By: Claude Fable 5 <[email protected]>
Replace the flat per-part serializations map with PartSerializations: one immutable interned group per column (the serializations of the column and its subcolumns, keyed by the column's recursive kind stacks and settings) plus one interned name lookup map (which does not depend on the kinds at all, since sparse serialization does not change the subcolumn names). Parts whose kind combinations differ now share everything except a vector of shared pointers. Together with the per-column substream entries this reduces the memory cost of a fully fragmented kind combination from ~209 KB to ~10 KB per part on a synthetic 231-column table. Co-Authored-By: Claude Fable 5 <[email protected]>
Verified the shared structs carry no padding waste (PartSerializations 40 B, ColumnGroup 24 B, ColumnEntry 88 B); what remained was container capacity persisted into long-lived interned objects. Shrink the serialization group vector after building, intern a compact copy of writer-built substream entries (incremental building leaves growth overshoot in the vector and the map), and store the per-part prefix positions as UInt32. Co-Authored-By: Claude Fable 5 <[email protected]>
The bundle was interned into the per-table cache before the part took ownership; an exception while building the serializations destroyed the only outside reference without going through releaseSharedPartColumns, leaving the strong cache entry unreachable until the table is dropped. Install the bundle into the part first (the handover is noexcept), so the part destructor returns it to the cache even when the rest of setColumns fails. Co-Authored-By: Claude Fable 5 <[email protected]>
An allocation profile of the part loading path showed that every part built all its per-column serialization groups (~65 MiB and 625k allocations per 300 fragmented wide parts) and then discarded almost all of them on interning hits, with the transient garbage landing in the MergeTree jemalloc arena where it fragments the long-lived metadata pages. The group keys are computable from the serialization infos alone, so probe the cache first and construct only the missing groups; the groups now store their lookup names so the name map is assembled without re-enumerating subcolumns. Arena scopes now cover only the pieces that survive in the caches; transient build work stays in the default arena. Cuts the serializations build churn about 3x, and to near zero once a table's kind variants are interned. Co-Authored-By: Claude Fable 5 <[email protected]>
…metadata # Conflicts: # src/Storages/MergeTree/MergeTreeDataPartCompact.cpp
blessed/master added ColumnsSubstreams::tryGetColumnSubstreams against the old pair-based storage; the merge auto-merged it as-is but this branch stores the per-column data as shared ColumnEntry objects, so the accessor must read entry->column / entry->substreams. Fixes the merge (the auto-merged form did not compile) and restores the full-part-rewrite decision for Dynamic columns without recorded substreams (test 04401). Co-Authored-By: Claude Fable 5 <[email protected]>
Scope the -Wused-but-marked-unused suppression (needed because XXH_INLINE_ALL marks every XXH function unused) to a push/pop block around the three XXH64 bloom-filter hash calls, instead of ignoring it for the rest of the file. Co-Authored-By: Claude Fable 5 <[email protected]>
Make it structurally impossible for part code to bypass the per-table cache's reference accounting. The part now owns the bundle through SharedPartColumnsHolder: a reference can be minted only by MergeTreeData::getSharedPartColumnsForColumns (the holder constructor is private) and returned only by the holder's destructor or move-assignment (now the sole caller of the private releaseSharedPartColumns), so a reference cannot be duplicated, leaked, or hand-released. Parts are already non-copyable (a static_assert locks that in for the holder), so no reference can escape accounting. The explicit release in ~IMergeTreeDataPart is gone - the holder handles it. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [5ac4619] Summary: ❌
AI ReviewSummaryThis PR interns schema-derived per-part Final Verdict✅ No new findings on the current PR head. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 705/750 (94.00%) · Uncovered code |
…moval The flaky check caught that DETACH PART is asynchronous in two ways: the replaced part object is removed from memory and disk by background cleanup (the part is replaced with a new empty covering part), and detaching and re-attaching the table can even reload the not-yet-removed directory as a covered part. The cache size assertions after DETACH PART now poll until the expected value (printing the observed value, so failures show the actual state) with a short old_parts_lifetime, instead of assuming synchronous destruction. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109816&sha=0d839416b4a4709b4d34db2a797839012464fb75&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29 ClickHouse#109816 Co-Authored-By: Claude Fable 5 <[email protected]>
…t release Address two review findings. First, a column with an explicit all-default SerializationInfo keyed differently from a column with no info entry, although both produce identical serializations; the keys now use an effective per-column kind encoding (the entry's, or a precomputed all-default encoding of the type), so old parts written without serialization.json share groups and whole objects with newer dense parts. The whole-object key also no longer stores column names (positions in the bundle order imply them), making lingering entries an order of magnitude smaller. Second, expired weak cache entries were only swept on insertion; parts now trigger an amortized sweep when they release their bundle reference, so a table that stops inserting but keeps deleting parts reclaims its dead entries after a bounded number of removals. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Perf report memory analysis: |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…rics Tag the eviction test no-shared-merge-tree: the eviction under test is driven by the lifecycle of local part objects, which SharedMergeTree manages through Keeper on its own schedule, so the polls do not converge there and the test exceeded the time budget in the flaky check. Also reduce the poll ceilings so even a non-converging environment stays under the limit. Drop the global system.metrics checks from the correctness test: a global metric being non-zero proves nothing about this test's table in a parallel suite, and a snapshot delta would be racy for the same reason. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Your PR was poisoned by the test |
…on test The randomized `enable_block_number_column` / `enable_block_offset_column` make mutations materialize `_block_number` / `_block_offset`, so the mutated parts store an extra column list and the expected cache sizes are off by one. Co-Authored-By: Claude Opus 5 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 627/670 (93.58%) · Uncovered code |
|
Stress test failure (ubsan) fixed here: #112045 |
… share-part-schema-metadata
`release_sweep_threshold` counted cache entries while `releases_since_sweep` counts part releases, so a table with more entries than remaining parts stopped sweeping after its first release-triggered sweep: with 10k parts and millions of interned entries the threshold was pinned at the cap while fewer than 10k releases could still happen. The bundle now counts its part holders (`onPartAcquire` from the holder, the only way to take a reference) and the threshold is `max(1, min(live_entries, remaining_holders / 2))`, which can never exceed the releases that can still happen: a drain halves down to its last part and a full drain of P parts sweeps O(log P) times. The hard cap is gone with it, and the initial threshold drops to 1 so small tables reclaim on their first release instead of after 64. Also drop a part's interned pieces before the caches sweep: `setColumns` and `setColumnsSubstreams` run again on the same part in the empty-column rewrite paths, and both sweeps (on bundle release and on insertion) can only reclaim an entry that is already expired. Document what a serialization kind is, and correct two stale comments: expired entries are no longer reclaimed on insertion only, and `share_nested_offsets` is no longer alterable on `SharedMergeTree`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…on info
The per-column key recorded the settings of the column's own serialization info entry, but
`SerializationInfoTuple` carries default settings (a `Tuple` cannot be sparse itself) while
`DataTypeTuple::getSerialization` builds every element from that element's info. The
serialization versions of the elements were therefore invisible in the key, and two parts with
the same kind stacks but different versions shared one group.
That is reachable with the documented configuration: inserts use
`map_serialization_version_for_zero_level_parts` while merges use `map_serialization_version`,
so a merged `Tuple(Map(...))` part could adopt the `basic` serialization of an inserted part,
write `basic` maps, and declare `with_buckets` in its `serialization.json`. Once the inserted
parts were gone the merged part no longer read back:
Stream t%2Em%2Em.buckets_info for column t.m with type Map(String, UInt64) is not found
The key now also carries the normalized settings of the whole `SerializationInfoByName`, which
are the effective settings of every recursive element. The entry's own settings stay in the key,
so it cannot under-split however the infos were built.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A custom serialization is attached to the type object (`IDataType::setCustomization`) and decides which streams a column has, but `IDataType::equals` ignores it, so two column lists that differ only in it are equal. Parts loaded from disk rebuild their types from `columns.txt`, without the `SerializationQuantizedVector` that the `Quantized` codec attaches in `ColumnsDescription`, so after a reload a part written next reused the bundle of the loaded part and lost the `<column>.quantized` companion stream. It then answered with quantized codes that differ from the ones the same rows get in a table that was never reloaded, silently changing vector search. Every custom serialization now has an identity (`ISerialization::getCustomSerializationIdentity`, the class by default, overridden by `SerializationQuantizedVector` to carry its parameters), and the bundle key carries the identities of its columns. The default keeps the serializations that `DataTypeFactory` derives from the type itself interned as before. Only one thread sweeps the nested caches in `onPartRelease`: concurrent part removals all cross the release gate, and scanning the caches once per removal serialized them behind the cache locks. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`IDataType::equals` ignores a custom name as well as a custom serialization, and the key hashes only the column names, so `SimpleAggregateFunction(sum, UInt64)` and a plain `UInt64` shared one bundle. A part inserted after a metadata-only `ALTER TABLE ... MODIFY COLUMN` between the two then reused the older part's column list and persisted the older type in its own `columns.txt`. `describeCustomSerializations` becomes `describeCustomizations` and covers both facets. `Bool` was already safe: it is a custom name over `UInt8`, but it carries `SerializationBool` with it, which the serialization identity distinguishes. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… equality `NamesAndTypesList` equality compares types with `IDataType::equals`, which ignores custom names at any depth, so the key needed a patch per facet and each one only closed the depth it looked at: after the custom serializations and the top-level custom names, `Nullable(UInt8)` and `Nullable(Bool)` still shared a bundle, and a part inserted after a metadata-only `ALTER TABLE ... MODIFY COLUMN` between them persisted the older type in its own `columns.txt`. The key is now `describeColumns`: per column its name, its full type name and the identities of the custom serializations attached to it (the type itself and, through `forEachChild`, every nested type), all length-framed. A type name is the canonical text of a declared type and exactly what a part persists, so it separates every custom name at any depth; a serialization attached from outside the type, which no type name shows, is the second component. Two column lists with the same description are interchangeable for a data part. `NamesAndTypesListHash` and the column-list reference in the key go away with it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…bstreams `describeColumns` emitted an identity only for the type nodes that have a custom serialization, so two types with the same name could describe identically with the identity on different nodes. Every node now contributes an entry, empty when it has none. Unreachable today, since the only serialization attached from outside a type is the one of the `Quantized` codec on the column itself, but the description is the interning key and must stay injective. `ColumnsSubstreams::lastEntryForModification` guarded a `const_cast` with a `chassert`, which release builds drop: modifying an entry that another part shares would corrupt it, so it throws now. Interned entries are no longer created as `make_shared<const ColumnEntry>` either, because casting away the constness of an object that is itself const and modifying it is undefined. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The interning ignored `ISerialization::supportsPooling`, which marks a serialization that cannot be cached. `SerializationJSON` returns false for it because its extraction tree accumulates mutable caches, and its parser is chosen from the `allow_simdjson` setting of whatever query built it, so interning pinned one instance and one parser for every part of the schema. A group whose serializations do not all support pooling is now rebuilt for every part and stays out of both caches, and a whole object containing one is not interned either. The probes need no check: what never enters the caches cannot be found in them. This is per group, so one `JSON` column does not cost the other columns of the table their sharing. The gate is conservative for `SerializationQuantizedVector`, which reports no pooling only because it carries no hash: those columns lose the sharing of their groups, not correctness. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…pooling gate `try_emplace` published the cache node before the compact `ColumnEntry` was built, so an allocation that throws (a memory limit, say) left an expired node that was never counted, the next sweep subtracted it anyway, and a retry took the `inserted == false` path and never repaired the count. The entry is built first now and the node is inserted and counted together. The other three caches already built their values before inserting them. `gtest_shared_part_columns` asks the same bundle for its serializations twice: the `JSON` column, whose serialization must not be shared, has to differ between the two, while `id` stays shared. Neutralising the gate makes it fail on exactly that (the same `SerializationJSON` pointer comes back twice). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`description` shadowed the local of the same name in `getEmpty`, which clang 21 rejects under `-Wshadow-uncaptured-local` even though the function is static and clang 22 accepts it, so the fast build failed while the local one did not. The name also read poorly next to `columns_description`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The old analyzer resolves no subcolumn behind a table alias, so `a.vec.quantized` failed with `UNKNOWN_IDENTIFIER` in the old analyzer job. Each side of the join now selects the subcolumn unqualified and the join compares plain columns. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Per-part metadata and the bundle interned for it outlive the query by far and are freed later by a background thread, which cannot credit the bytes back to the per-user tracker. That tracker is reset only once the user has no queries left, so a user who always has one query in flight accumulates the charge until `max_memory_usage_for_user` trips on memory nobody holds. The read path already excludes this in `loadColumnsChecksumsIndexes` and `loadIndex`; every path that builds a part now does the same. `MemoryTrackerBlockerInThread` stops the `User` tracker and the narrower ones, so `total_memory_tracker` still accounts the bytes and the server limit still sees them. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
723c7c2
…-zstd Conflicts: - `src/Storages/MergeTree/IMergeTreeDataPart.cpp`: kept this branch's reworked `detectDefaultCompressionCodec` and adopted master's #109816 change of the removed `columns` member to the `getColumns` accessor. - The legacy `docs/en` tree was removed on master; the four documentation changes of this branch (Native format/protocol specs, `<compression>` server-config section, column compression codecs) were ported to the corresponding files under `docs/reference` and the legacy files deleted. Co-Authored-By: Claude Fable 5 <[email protected]>
…ous part removal 03673_columns_description_cache and 04257_102926_columns_descriptions_cache_nested_eviction assert columns_descriptions_cache_size immediately after ALTER TABLE ... DETACH PART, assuming the detached part's in-memory object is destroyed synchronously. DETACH PART covers the part with a new empty part and moves the old one to Outdated. Its cache entry is released only when the part object dies and MergeTreeData::releaseSharedPartColumns observes use_count() == 1. The trailing clearOldPartsFromFilesystem() is best-effort: grabOldParts skips a part when grab_old_parts_mutex is held by the background cleanup thread, when isSharedPtrUnique is false because a concurrent reader still holds the DataPartPtr, or when an empty covering part still covers an Outdated part. Detaching and re-attaching the table can additionally reload a not-yet-removed directory as a covered part. ClickHouse#109816 diagnosed and fixed exactly this for the third test under the same cache, 04510_shared_part_schema_metadata_eviction, and these two were left behind. Apply the same remedy: convert both to .sh and poll the affected assertions with that test's wait_for_cache_size helper, which prints the observed value on timeout so a failure still shows the actual state. No expected value changes. Only the assertions whose value is produced asynchronously poll; those established synchronously by the preceding statement stay exact reads. One read was dropped from 03673 because it queried system.tables while the table was detached, where there is no row, so it asserted nothing. Only the merge setting is pinned, because both tests detach parts by name. Pinning enable_block_number_column / enable_block_offset_column as 04510 does was measured inert here: that pin exists for materializing mutations, and these two tests only ADD COLUMN, which creates no mutation. Tag both no-shared-merge-tree for the reason 04510 states: this eviction is driven by local part object lifetime, which SharedMergeTree manages through Keeper on its own schedule, so the polls do not converge there inside the time budget. Carry over the no-random-detach tag that ClickHouse#96130 adds to 03673, since that PR reattaches tables before query execution and this test detaches and attaches its own table. Also correct 04257's header comment, which named decrefColumnsDescriptionForColumns; that function no longer exists. Co-Authored-By: Claude Opus 5 <[email protected]>
Related: https://github.com/ClickHouse/clickhouse-private/issues/59501
Each active MergeTree data part kept its own copy of the schema-derived metadata built in
IMergeTreeDataPart::setColumns— the column list, the name-to-position map, theColumnsDescription, the serializations map, and the columns substreams. All of it scales with the column count and is essentially identical across parts of a table, so for tables with many parts (especially wide tables) these per-part copies dominated server memory.This generalizes the existing
columns_descriptions_cacheinto a single per-table interning cache: parts now hold one immutable, reference-countedSharedPartColumnsbundle keyed by the stored column list. The data-dependent members (the serializations map and the columns substreams, which differ between parts when a column is sparse in one part and dense in another) are interned at per-column granularity, so parts whose serialization kinds differ in only some columns still share the pieces of every column they agree on. Everything is allocated in the dedicated MergeTree jemalloc arena, and the reference accounting is encapsulated in a move-only handle so it cannot be bypassed from part code.On a synthetic table of 231 columns × 3000 tiny parts this reduces live server memory from ~840 MiB to ~240 MiB, and the saving no longer depends on how per-part column sparsity happens to be distributed. The on-disk and wire formats are unchanged.
One incidental build-side change is included: linking
ch_contrib::xxHashintodbmsrevealed that lz4's bundled legacyxxhash.hwas shadowingcontrib/xxHash(the Parquet writer had unknowingly been using lz4's copy), so lz4's include directory is now exported as a system include. The Parquet bloom-filter hashing keeps the same standardized XXH64 output.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reduced memory usage of
MergeTreetables with many data parts by sharing the schema-derived per-part metadata (column list, column descriptions, serializations, and columns substreams) across parts of a table instead of copying it into every part. The effect is largest for wide tables with many small parts.Version info
26.8.1.771(included in26.8and later)