Skip to content

Avoid building stream names and substreams cache keys for every block in MergeTreeReaderWide - #124816

Merged
alexey-milovidov merged 7 commits into
masterfrom
faster-stream-names
Oct 12, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
faster-stream-names

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

MergeTreeReaderWide computed IMergeTreeDataPart::getStreamNameForColumn up to four times per substream on every readRows call: in the data getter, again in getStream, and in both callbacks for the average value size hints. Every computation builds the name (escapeForFileName, Nested::splitName, fmt::format), and then looks it up in the std::map of checksums. The substreams caches (ISerialization::SubstreamsCache and SubstreamsDeserializeStatesCache) were keyed by a string, which was also built for every lookup.

Now:

  • The stream names are memoized in the reader for its lifetime, keyed by the column name and the fields of the substream path (cheap hash, exact comparison). The name computed by a caller is passed to getStream, and the element of avg_value_size_hints is remembered.
  • The key of the substreams caches is the SipHash of exactly the same rendering of the substream path that was used before. SipHash is a streaming hash, so the pieces are fed into it without building the string, and two paths share a cache entry exactly when their rendered strings are equal, as before. getNameForSubstreamPath became a template over the sink of the pieces.
  • readRows no longer destroys the per-column cache entries after every call, only clears them.

With max_block_size = 1 the inclusive time of getStreamNameForColumn was 7-15% of ClickBench queries; for Q3 it went from 14% to about 5% (getStreamInfo).

Measured on ClickBench hits (a 1% subset, 1M rows), single-threaded, together with the other PRs for the same issue (#124791): with max_block_size = 16, queries Q3, Q10, Q19, Q30, Q34 are 13-25% faster; with the default max_block_size the times are unchanged.

A performance test with small blocks is added.

Related: #124792
Related: #124791

Changelog category (leave one):

  • Performance Improvement

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

Reduce the per-block overhead of reading MergeTree tables in Wide parts: the names of the column streams and the keys of the substreams caches are no longer built for every block. Queries with small blocks (a low max_block_size) became faster.

🤖 Generated with Claude Code


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

Version info

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

alexey-milovidov and others added 4 commits October 9, 2026 02:18
`MergeTreeReaderWide` computed `IMergeTreeDataPart::getStreamNameForColumn` up to
four times per substream on every `readRows` call: building the name with escaping
and splitting of nested names, then looking it up in the checksums. The substreams
caches were keyed by a string that was also built on every lookup.

Now the stream names are memoized for the lifetime of the reader, and the keys of
the substreams caches are `SipHash` hashes of the same rendering of the substream
path, computed without building the string.

With `max_block_size = 1` this was 7-15% of the time of ClickBench queries.

Related: #124792

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Hashing the key with `SipHash` still took a noticeable time for every lookup. Now the key
is hashed with a cheap hash and compared exactly. Also, the stream name computed by the
callers is passed to `getStream`, and the element of `avg_value_size_hints` for a stream
is remembered, so the callbacks for the size hints don't search the map by name.

Related: #124792

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 9, 2026
# Conflicts:
#	src/Storages/MergeTree/MergeTreeReaderWide.cpp
#	src/Storages/MergeTree/MergeTreeReaderWide.h
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2484fda]

Summary: ✅


AI Review

Summary

This PR memoizes stream-name lookups in MergeTreeReaderWide, switches the per-substream caches to hashed path keys so the rendered key string is no longer materialized on every lookup, and adds a focused small-block performance test. I reviewed the current merged code, the full PR diff, the existing PR discussion, and the current inline-thread state; I did not find a correctness, concurrency, or compatibility regression in the changed paths. The Performance Improvement changelog metadata matches the patch, the changelog entry is specific and user-facing, and the current PR CI report is green.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 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: 329cca57-acd0-43fc-8e11-e26bd7e3c9b8
  • MIRAI run: 9f26bfe5-25eb-44ad-94fe-066177dc2c43
  • PR check IDs:
    • clickbench_893296_1791735054
    • clickbench_893302_1791735054
    • clickbench_893308_1791735054
    • tpch_adapted_1_official_893319_1791735054
    • tpch_adapted_1_official_893331_1791735054
    • tpch_adapted_1_official_893366_1791735054

@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2484fda5b with master 1b9d29136 (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

71 object files changed (+23.74 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReaderWide.cpp.o 412.11 KiB 431.05 KiB +18.95 KiB (+4.60%)

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

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124816&sha=706c1ec64373407746fba9b4110377fdb43ad79a&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel) and provide a fix in a separate PR. If the fix is already in progress, link it here.

05210_lightweight_update_materialized_cte_in_ignore fails with UNKNOWN_TABLE (Unknown table expression identifier '_materialized_cte_c_...') under parallel replicas. It has been failing on master and many unrelated PRs since 2026-10-08, so it is not caused by this PR.

The Stateless tests (arm_asan_ubsan, azure, sequential) failure is a job timeout of that lane, tracked by #123849.

I merged master into this branch to refresh CI.

@groeneai

Copy link
Copy Markdown
Collaborator

Not caused by this PR. The fix is #123121 (mine, open).

The failed run (706c1ec, ParallelReplicas lane) throws UNKNOWN_TABLE on _materialized_cte_c_* in query 26 of the test, the #112642 race: the query sent to the other replicas can start before the initiator has created the materialized CTE's temporary table. #123121 makes the outer plan own the CTE writer, so all reads wait for it. It has been waiting for review since 2026-09-30 (requested from @ novikd and @ devcrafter).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks, @groeneai. The unrelated 05210_lightweight_update_materialized_cte_in_ignore failure is tracked by #123121. After the master merge, the latest CI run of this PR (2484fda5) has no failures.

@alexey-milovidov alexey-milovidov left a comment

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.

Looks good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 12, 2026
Merged via the queue into master with commit 46a479e Oct 12, 2026
173 checks passed
@alexey-milovidov
alexey-milovidov deleted the faster-stream-names branch October 12, 2026 17:03
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 12, 2026
@Avogar

Avogar commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

I want to revert this PR. The idea is fine, but the implementation makes the code worse, and the use case does not justify it.

The main problem is SubstreamKey in MergeTreeReaderWide. It copies five fields out of ISerialization::Substream because stream names happen to depend on exactly those fields today. Which fields of a substream path form a stream name is the business of ISerialization::getFileNameForStream, not of the MergeTree reader. Now the two are coupled by an invariant that nothing checks: the next field that a serialization needs in a stream name will be added in ISerialization.cpp by someone who has no reason to know about a struct in MergeTreeReaderWide.h, and from that moment two different substreams can get one memoized name and the reader silently opens the wrong file. The fields variant_element_name, bucket and object_path_name were all added this way over time, so this is not hypothetical.

The rest of the change does not help readability either: a hand-rolled hash, a multimap with manual equality, a mutex and raw pointers into avg_value_size_hints, all for a memo; plus the substreams cache keys turned into 128-bit hashes and the name renderer turned into a template over a sink, so the same function now serves file names, subcolumn names and cache keys through three flags.

And all of it is for a strange use case. By the numbers in the description the gain exists only with max_block_size of about 16 or below; with the default block size nothing changes, and the Cloud performance report on this PR shows no change either.

If this speedup is wanted, it should be done properly or not at all.

huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 3, 2026
…tream-names"

This reverts commit 46a479e, reversing
changes made to 1e6f88e.

The conflicts with the later changes of ClickHouse#127000 to the same code (the
cache-key rendering of the SHARED paths of JSON and the sub-column sizes
in getAllColumnsSubstreams) are resolved by keeping their behaviour over
the pre-ClickHouse#124816 mechanics: stream names built per call and string keys
of the substreams caches.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
yasserhtd added a commit to yasserhtd/ClickHouse that referenced this pull request Nov 4, 2026
…am cache key

Master reverted the change that made `ISerialization::getSubstreamsCacheKeyForStream` return a 128-bit hash (3013a37,
the revert of ClickHouse#124816), so the key is a `String` again and
`ISerialization::SubstreamsCacheKeyHash` no longer exists. The key is the same injective rendering of the substream
path, so every substream still gets its own stream.

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.

4 participants