Skip to content

Take the serialization of a column from the data part in the MergeTree readers - #120632

Merged
grantholly-clickhouse merged 17 commits into
masterfrom
share-part-serializations-in-mergetree-readers
Oct 7, 2026
Merged

grantholly-clickhouse merged 17 commits into
masterfrom
share-part-serializations-in-mergetree-readers

Conversation

@Avogar

@Avogar Avogar commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

IMergeTreeReader rebuilds the serialization of every column it reads, and a reader is created per read task and per filter step, so one query repeats this many times over. For a JSON column that serialization is proportional to the number of typed paths - one per path plus a whole JSONExtractTree - so with a few hundred paths the readers spend their time building an object the data part is already holding.

Now the reader takes the serialization from the part, which built it with the same call and shares it across all parts with the same schema, and composes the requested subcolumn from it. The column and its serialization are resolved in one pass, and the presence checks of a subcolumn and the resolution of a dynamic one stop building a serialization too.

A serialization is taken from the part only when supportsPooling holds, because all readers of the part use one object at once, while a poolable one is what the pool hands out to every caller anyway.

Changelog category (leave one):

  • Performance Improvement

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

Reading columns and subcolumns of MergeTree tables no longer rebuilds the serialization of a column for every reader: the serialization the data part already holds is reused. The gain is largest for JSON columns with many typed paths, where the whole set of path serializations used to be rebuilt per read task and per filter step.


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

Version info

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

…ders

`IMergeTreeReader` rebuilt the serialization of every column it reads:
`getSerializationInPart` called `IDataType::getSerialization`, which
builds the whole serialization of the column and composes the requested
subcolumn from it. A reader is created per read task and per filter step,
so for a `JSON` column every one of them rebuilt a serialization per typed
path and a whole JSON extract tree; with a few hundred typed paths that
dominated the read.

The part already holds the serialization of every column it stores, built
with the same call and interned across the parts with the same schema, so
take it from there and compose the requested subcolumn from it. Only a
serialization that is safe to use concurrently can be taken, which is what
`supportsPooling` tells: one serialization of the part is used by all of
its readers at once, while a poolable one is shared by all of its users
anyway. A subcolumn is always composed from the serialization of its
column and never looked up by its own full name, which a column of the
part can be named after.

The column and its serialization are now resolved in one pass, which
shares the lookup of the column in the part and the enumeration of its
parent, and removes the duplicated handling of a column missing from the
part. Resolving a dynamic subcolumn and answering whether a subcolumn is
present in the part - in `MergeTreeReaderCompact` and in
`injectRequiredColumnsRecursively` - no longer build a serialization
either.

Debug build, 100 compact parts of a `JSON` with 256 typed paths, single
thread: reading a typed path 0.136 -> 0.046 s, four typed paths
0.476 -> 0.131 s, a filter on a typed path 0.138 -> 0.052 s, and a
dynamic path, where reading the data dominates, 0.345 -> 0.233 s.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [49db709]

Summary: ✅


AI Review

Summary

This PR changes IMergeTreeReader to reuse part-owned serializations when that is safe, resolves subcolumns against the serialization the part actually holds, and adds focused coverage for wrapped JSON and Quantized(...) subcolumns. I did not find a new correctness, concurrency, or compatibility issue in the current diff, and the previously raised reader/cache concerns appear addressed in the latest code.

Final Verdict

✅ No new blocking findings in the current revision.

LLVM Coverage Report

Measured on commit 49db709.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.20% +0.10%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 108/110 (98.18%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Sep 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 49db709d9 with master 7405dae03 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

290 object files changed (+300.90 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/PatchParts/MergeTreePatchReader.cpp.o 206.29 KiB 251.22 KiB +44.94 KiB (+21.78%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/AlterConversions.cpp.o 244.75 KiB 271.79 KiB +27.04 KiB (+11.05%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeBlockReadUtils.cpp.o 176.84 KiB 203.60 KiB +26.75 KiB (+15.13%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp.o 973.46 KiB 999.52 KiB +26.06 KiB (+2.68%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeSequentialSource.cpp.o 403.63 KiB 426.87 KiB +23.24 KiB (+5.76%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/PatchParts/RangesInPatchParts.cpp.o 256.80 KiB 279.32 KiB +22.52 KiB (+8.77%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeDataPartWide.cpp.o 313.31 KiB 335.39 KiB +22.08 KiB (+7.05%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromTextIndexCount.cpp.o 337.15 KiB 359.10 KiB +21.95 KiB (+6.51%)
src/CMakeFiles/dbms.dir/Storages/StorageMergeTreeIndex.cpp.o 520.64 KiB 542.56 KiB +21.92 KiB (+4.21%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeDataPartCompact.cpp.o 237.46 KiB 259.19 KiB +21.73 KiB (+9.15%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReadPoolBase.cpp.o 427.80 KiB 448.35 KiB +20.55 KiB (+4.80%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeData.cpp.o 4.18 MiB 4.20 MiB +19.73 KiB (+0.46%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

3121 translation units recompiled, 18245 s compile time in total, 3121 of them have a recent master baseline.

Job report

@alexey-milovidov alexey-milovidov self-assigned this Sep 22, 2026
alexey-milovidov and others added 2 commits September 23, 2026 02:27
… column into the read task

Addresses the review concern that `injectRequiredColumnsRecursively`, now resolving the subcolumn against the
serialization the part holds, would miss `vec.quantized` and inject the full `vec` column. The part attaches the
`Quantize` serialization to its column when loading `columns.txt`, and a `Quantized` column is always dense, so the
serialization the part holds is exactly that custom one and exposes the companion subcolumns.

The test reads `vec.quantized` (plain and in `PREWHERE`) after `DETACH`/`ATTACH` and checks that it reads far fewer
compressed bytes than reading `vec`. It fails when the subcolumn lookup in `injectRequiredColumnsRecursively` is forced
to miss.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

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
  • StressHouse run: 07b858e3-3a22-4397-a435-70d9dee5d0fe
  • MIRAI run: 827af006-80a9-4d4d-b56b-19c2912918e7
  • PR check IDs:
    • clickbench_3365114_1791209591
    • clickbench_3365120_1791209591
    • clickbench_3365126_1791209591
    • tpch_adapted_1_official_3365137_1791209592
    • tpch_adapted_1_official_3365170_1791209591
    • tpch_adapted_1_official_3365185_1791209591

…ations-in-mergetree-readers

Resolved conflicts with #110957 (`JSON` subcolumn serialization cache): the
general part-serialization path of this PR (`tryGetSerializationFromPart`)
covers the `containsObjectType` branch added on master, so that branch is
dropped. Kept master's sharing of `serializations_of_full_columns` for
full-column requests in `Compact` parts and its `withRegularSubcolumns`
presence checks in `MergeTreeReaderCompact`, combined with `hasSubcolumnInPart`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120632&sha=04e24771f7c7ab4344dddfa9c77da5e27403abba&name_0=PR&name_1=Stress%20test%20%28arm_msan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

Stress test (arm_msan) failed with Cannot start clickhouse-server: on restart the server cannot load rdb_05059_rename_replicated_database_stale_cluster_test_1_renamed because it references the named collection coll_05059_rename_replicated_database_stale_cluster_test_1, which was already dropped (NAMED_COLLECTION_DOESNT_EXIST). The test 05059_rename_replicated_database_stale_cluster.sh strands a Replicated database whose metadata names a dropped collection when it is interrupted in the stress run; the same failure hit PR #109227 (Stress test (amd_msan), 2026-09-19). This PR only changes how MergeTree readers obtain serializations, so it is unrelated. The perf reds (lower_upper_utf8_mixed_ascii, "too long"/unstable queries) are also outside the code this PR touches.

The CH Inc sync status was failing because the private sync branch had diverged; I merged the new PR head and private master into it (clickhouse-private 3556d1a874b1).

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. No fix is in progress for this one. My open #115049 lets startup skip a database whose named collection is missing only for engines that keep no local metadata, deliberately not Replicated. #112805 registers a dependency only for a collection passed as a database engine argument, while the collection_name setting of Replicated is resolved in DatabaseReplicated::fillClusterAuthInfo without one, so DROP NAMED COLLECTION is not refused while such a database exists. I'm investigating how 05059 ends up in that state and I'll follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in #122753 (test only).

05059_rename_replicated_database_stale_cluster.sh drops its named collection in a separate client call after the two DROP DATABASE ... SYNC calls, whatever they returned. In this run the stress runner's random client killer terminated the client of the first DROP DATABASE ..._renamed SYNC before the statement reached the server, the script went on, and DROP NAMED COLLECTION succeeded while the renamed Replicated database still used the collection. The 2026-09-19 hit on #109227 was a Keeper fault on the same statement. The PR keeps the collection until both databases are dropped.

On the server side, DROP NAMED COLLECTION is not refused while a Replicated database references the collection through the collection_name setting, and #112805 does not cover that case (its diff does not touch DatabaseReplicated).

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai. #122753 has merged, so I merged master into this branch (f0c48dd, clean merge) to pull in the 05059_rename_replicated_database_stale_cluster.sh fix. The rebuilt binary passes 05241_vector_search_quantize_codec_read_task_subcolumn and the Dynamic/Variant/JSON subcolumn tests locally (23/23).

alexey-milovidov and others added 3 commits October 1, 2026 11:56
…test

The performance harness expands every `{name}` in a query as a substitution
placeholder, so the `'{'` / `'}'` string literals in the fill query made the
test fail with `Failed to substitute parameters (KeyError: ...)` in both
performance shards that ran it. Double the braces, as other tests do.

https://s3.amazonaws.com/clickhouse-test-reports/PRs/120632/f0c48dd7c22286eed2ce169ab7bc7fba373e8c55/pr/performance_comparison_amd_release_master_head_1_6/report.html
#120632

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Reusing the serialization the part holds was introduced for the types
containing an object only, gated on `containsObjectType`, and in three
places: the reader, which took it for such a column when it was poolable;
`LoadedMergeTreeDataPartInfoForReader::getSerialization`, which composed a
subcolumn from the serialization of its column after a lookup by the full
name of the subcolumn missed; and the enumeration of the subcolumns of a
column in `SharedPartColumns`, which attached the type for such a column.

The reader now reuses the serialization of every column whose serialization
is safe to share and composes subcolumns from it, so the first two have no
remaining caller - a lookup by the full name of a subcolumn, which the
second does first, is also what the general rule has to avoid, because a
column of the part can be named after a subcolumn of another column. The
third changes nothing: the subcolumns a type exposes do not depend on the
type being attached to the enumerated data, which
`SharedPartColumns.TypedJSONSubcolumnsAreIncluded` keeps checking.

With presence answered against the serialization of the part, the lookups
of the full name of a subcolumn in the compact reader are redundant too.

`containsObjectType` has no users left and is removed.

The performance test added here is dropped in favour of
`json_subcolumn_serialization_cache`, which measures the same thing across
the three layouts of a part.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ations-in-mergetree-readers

Resolved the conflict in `IMergeTreeReader.cpp` in favour of the PR: the
general reuse via `tryGetSerializationFromPart` replaces master's type-gated
reuse, and already handles the case fixed on master (flattened `Nested`
members in Wide parts), since `tryGetSerialization` returns null for the
synthetic `Nested` column that does not exist in the part.
… to `forEachSubcolumn` in `SharedPartColumns`

The serializations of the subcolumns of a wrapped `JSON`, such as
`Variant(JSON(...), UInt8)`, depend on the enclosing types:
`SerializationVariant::enumerateStreams` builds the variant types only when
the type is attached, and without them `VariantSubcolumnCreator::create`
does not set `nullable_added`. Without the type, the serializations of the
subcolumns that `SharedPartColumns` caches for the part differ from the ones
`IDataType::getSubcolumnSerialization` builds from the serialization of the
column.

This restores the type-gated threading and `containsObjectType`, and adds
`SharedPartColumns.WrappedJSONSubcolumnsMatchOnTheFlySerializations`, which
fails without it for `JSON(typed UInt64).typed` and `UInt8`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
@Avogar
Avogar removed this pull request from the merge queue due to a manual request Oct 2, 2026
@Avogar Avogar added the hold Skip for auto-updating. label Oct 2, 2026
The serialization of a subcolumn can depend on the types enclosing it:
`SerializationVariant::enumerateStreams` wraps an element into `Nullable`
only when its type allows it, and `VariantSubcolumnCreator::create` leaves
`nullable_added` unset without a type. The serializations enumerated without
one therefore differ from the ones `getSubcolumnSerialization` builds from
the serialization of the column, which always has it.

`SharedPartColumns` passed the type only for a column whose type contains an
`Object`, which is not the property that matters: the same difference arises
for any `Variant`, `Variant(UInt64, UInt8)` included, and `Object` is not
even special there - it reports `canBeInsideNullable`, like a number does. So
the type is passed unconditionally and `containsObjectType`, whose only user
this was, is removed. `SharedPartColumns.VariantSubcolumnsMatchOnTheFlySerializations`
covers it with no `Object` involved.

The remaining two enumerations that passed no type - in `getSubcolumnNames`
and in the collection of the tuple elements on the path to a subcolumn - use
the names alone, but pass it now as well, so that a caller reading the type
of an enumerated subcolumn always gets one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

@Avogar, thanks! This PR is good to merge.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approved.

…art in a test

The review asked whether the compact reader still finds `vec.quantized` after the part is
loaded back from disk, since `05241_vector_search_quantize_codec_read_task_subcolumn` forces
wide parts. Add a compact part with substream marks to the test, read `vec.quantized` together
with `vec.size0` in both orders and under `PREWHERE` before and after `DETACH`/`ATTACH`, and
check the results do not change.

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

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120632&sha=7d49335031d0f7286aa3048434424f2816be3396&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20targeted%29 (test_hive_query/test.py::test_selected_rows_not_double_counted). All the tests passed. The module fixture failed in cluster.shutdown because Docker could not stop the hdfs1 container (tried to kill container, but did not receive an exit event), and the error is attributed to the last test of the module. The same test has also failed in unrelated PRs (#100185, #120311, #119229). Please provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. I am investigating the test_hive_query teardown failure (Docker could not stop hdfs1 in cluster.shutdown); I will follow up here with a PR (or my findings) shortly.

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

The fix is in #123638. When docker compose stop failed, the docker compose kill fallback in ClickHouseCluster.shutdown() failed too, because hdfs1 exited just before its kill arrived (is not running), and that error escaped the teardown. The fallback is now retried with the existing retry() helper, and each attempt kills only the containers that are still running.

The test_hive_query failures in #100185, #120311 and #119229 have other causes (a use_count() == 1 logical error, DROP TABLE errors, a cluster.start() minio failure), so this change does not fix them.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (466246a). The only red check on eecce9f was Performance Comparison (amd_release, master_head, 4/6), where is_valid_utf8 query #0 regressed. That query computes isValidUTF8 over numbers(), so it never reaches the MergeTree readers this PR changes. The comparison baseline is master_head, which already had UTF-8 helper changes (e.g. 9861d3a) that this branch did not, so the regression should go away after the merge. @groeneai, thanks for #123638, which fixes the test_hive_query teardown failure.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (8a05af9). The only red check on 466246a was Build (amd_fuzzers): the clickhouse_fuzzer link hit relocation R_X86_64_PC32 out of range in libclang_rt_asan.a, the image-size overflow that is unrelated to this PR and already fixed on master by 8ef38ed ("Leave the SanitizerCoverage PC table out of the fuzzer build"). The merge was clean, the PR diff is unchanged, and the touched translation units compile.

alexey-milovidov and others added 2 commits October 6, 2026 07:48
…` in test `05241`

Older rows from reruns against the same server could make the scalar subquery
return more than one row or duplicate the output.

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

Copy link
Copy Markdown
Member

🕵 The only CI failure, 03759_distinct_json_paths_optimization in Stateless tests (amd_debug, parallel), also fails on master and in other PRs (#115722, #123449, #124056, #120906) since 2026-10-05. It is unrelated to this PR, and a fix is open in #123942. I also merged master and addressed the query_log isolation comment on test 05241.

@grantholly-clickhouse
grantholly-clickhouse added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit bee7f61 Oct 7, 2026
150 checks passed
@grantholly-clickhouse
grantholly-clickhouse deleted the share-part-serializations-in-mergetree-readers branch October 7, 2026 04:13
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 4, 2026
Conflicts, all context-only:
- SerializationVariant.cpp, SerializationVariantElement.cpp: 26.8 has
  `clone()` without the clone context (ClickHouse#126298 is not in 26.8); keep it and
  add only the copies of the new `variant(s)_absent_in_storage` flags.
- MergeTreeReaderWide.cpp: 26.8 has `addStream`, not
  `FileStreams::getOrCreate` (ClickHouse#114252 is not in 26.8); add only the new
  `isReadWithTypeInPart` before it.

Semantic fix: `IMergeTreeReader::hasSubcolumnInPart` (ClickHouse#120632) is not in
26.8, so `isReadWithTypeInPart` uses `type->hasSubcolumn`, as the 26.8
readers already do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 4, 2026
Conflicts, all context-only:
- SerializationVariant.cpp, SerializationVariantElement.cpp: 26.9 has
  `clone()` without the clone context (ClickHouse#126298 is not in 26.9); keep it and
  add only the copies of the new `variant(s)_absent_in_storage` flags.
- MergeTreeReaderWide.cpp: 26.9 has `addStream`, not
  `FileStreams::getOrCreate` (ClickHouse#114252 is not in 26.9); add only the new
  `isReadWithTypeInPart` before it.

Semantic fix: `IMergeTreeReader::hasSubcolumnInPart` (ClickHouse#120632) is not in
26.9, so `isReadWithTypeInPart` uses `type->hasSubcolumn`, as the 26.9
readers already do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants