You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
MergeTreeReaderWide recomputes stream file names (getStreamNameForColumn) on every read: 7-15% of time with small blocks #124792
MergeTreeReaderWide::readData recomputes the file name of every substream on every call. With small blocks this is 7–15% of query time.
For each substream it touches, one readRows call computes IMergeTreeDataPart::getStreamNameForColumn up to four times:
in deserialize_settings.getter, only to check streams.isPrefetched;
again inside MergeTreeReaderWide::getStream;
in get_avg_value_size_hint_callback and update_avg_value_size_hint_callback, which then look up avg_value_size_hints by String.
Each computation is non-trivial: ISerialization::getFileNameForStream builds the name (getNameForSubstreamPath, escapeForFileName, Nested::extractTableName / Nested::splitName), and IMergeTreeDataPart::getStreamNameOrHash concatenates the extension and looks it up in the std::map<String, ...> of checksums, falling back to sipHash128String and a second lookup. Then getOrAddStream / streams.find does another lookup by String.
The same pattern applies to the substreams cache: ISerialization::SubstreamsCache is a std::unordered_map<String, ...>, and getSubstreamsCacheKeyForStream builds the key string with getNameForSubstreamPath on every getElementFromSubstreamsCache, addElementToSubstreamsCache and addColumnWithNumReadRowsToSubstreamsCache call. For sparse columns, readOrGetCachedSparseOffsets adds another round.
None of this depends on the block. The stream for a given (column, substream path) is fixed for the lifetime of the reader.
Measurement. Inclusive share of getStreamNameForColumn with max_threads = 1, max_block_size = 1 on a 1M-row ClickBench hits subset (setup in the umbrella issue): Q3 14%, Q10 15.4%, Q19 10.3%, Q30 10.2%, Q34 7%, Q36 8.9%. The substream cache functions add 3–6% on top. Functions only in this path, such as escapeForFileName, getNameForSubstreamPath, fmt::vformat from getFileNameForStream, Nested::splitName and std::string::push_back, appear near the top of the flat profile.
SELECTSUM(AdvEngineID), COUNT(*), AVG(ResolutionWidth) FROM hits_1m SETTINGS max_threads =1, max_block_size =1;
-- 19.8 s, i.e. ~20 µs per block
Possible fix. Resolve stream names once per (column, substream path) when the reader is created, or on first use, and cache the resolved MergeTreeReaderStream * (plus the avg-size-hint slot) in a small per-column array. The serialization callbacks can then take the stream directly. The substreams cache could similarly be keyed by a precomputed key or a substream index instead of a freshly built string.
#131011 resolves the streams that addStreams enumerates, but the streams found while deserializing the prefix (dynamic JSON paths, Dynamic variants) are still resolved on every call: for every block, their data getter, mark seeks and size-hint callbacks go through getStreamNameForColumn, the checksums lookup and the avg_value_size_hints lookup. This costs time at the default block size too: after the revert #127836, q0 of tests/performance/json_subcolumns_required_conversions.xml went from 0.160 s to 0.190 s on amd and from 0.213 s to 0.254 s on arm (master perf CI, 2026-11-03). After #131011 it is at about 0.18 s and 0.24 s.
The patch below resolves such a path on first use in readData, with the same functions as addStreams, and keeps it in the column's ResolvedSubstreams under the key #131011 uses (getSubstreamsCacheKeyForStream). It needs no synchronization, which is why #131011 left these streams out: only the callbacks of readData insert, and they run on the reading thread after deserializeBinaryBulkStatePrefix has waited for all prefix tasks of the column. The prefix callbacks still resolve these paths without inserting.
Server time from query_log on master c64ec9cb4d17 with and without the patch (the reader and the JSON/Dynamic serializations are unchanged on master since), local Release builds, 4-vCPU x86. Times are medians; the change is the geometric mean of the paired ratios with its 95% CI:
SELECT json of the same table (400 dynamic paths), 15 pairs
3132 ms
2898 ms
−7.7% (95% CI −8.8% to −6.6%)
json_shared_data_wide.xml q0 / q1 / q2, 15 pairs
16 / 3 / 79 ms
15 / 3 / 77 ms
all CIs include 0
3M-row Dynamic column, SELECT d / SELECT d.String, 15 pairs
44 / 27 ms
45 / 27 ms
both CIs include 0
With the official builds on the same host, q0 takes 195 ms before the revert (88f0adf4bacb) and 215 ms on c64ec9cb4d17, so the patch should bring it back to about the time before the revert (I did not build the patch with ThinLTO). Peak memory of SELECT json stays at about 175 MB. None of the 1054 stateless tests matching json, dynamic or variant fails only with the patch; 61 fail with both binaries on my single-node server because they need ZooKeeper, remote shards, S3 or the filesystem prefetch log.
diff --git a/src/Storages/MergeTree/MergeTreeReaderWide.cpp b/src/Storages/MergeTree/MergeTreeReaderWide.cpp
index 190636635dd..a270e7e47ee 100644
--- a/src/Storages/MergeTree/MergeTreeReaderWide.cpp+++ b/src/Storages/MergeTree/MergeTreeReaderWide.cpp@@ -1001,6 +1001,12 @@ const MergeTreeReaderWide::ResolvedSubstreams * MergeTreeReaderWide::findResolve
return it == resolved_substreams_by_column.end() ? nullptr : &it->second;
}
+MergeTreeReaderWide::ResolvedSubstreams * MergeTreeReaderWide::findResolvedSubstreams(const String & column_name)+{+ const auto it = resolved_substreams_by_column.find(column_name);+ return it == resolved_substreams_by_column.end() ? nullptr : &it->second;+}+
const MergeTreeReaderWide::ResolvedSubstream & MergeTreeReaderWide::resolveSubstream(
const ResolvedSubstreams * substreams,
const NameAndTypePair & name_and_type,
@@ -1022,6 +1028,25 @@ const MergeTreeReaderWide::ResolvedSubstream & MergeTreeReaderWide::resolveSubst
return computed;
}
+const MergeTreeReaderWide::ResolvedSubstream & MergeTreeReaderWide::resolveAndAddSubstream(+ ResolvedSubstreams & substreams,+ const NameAndTypePair & name_and_type,+ const ISerialization::SubstreamPath & substream_path)+{+ auto cache_key = ISerialization::getSubstreamsCacheKeyForStream(substream_path);+ if (const auto it = substreams.find(cache_key); it != substreams.end())+ return it->second;++ /// A substream that `addStreams` couldn't enumerate: it became known when the prefix was deserialized.+ /// Resolved exactly as there, but only once, instead of for every granule.+ ResolvedSubstream resolved{+ .stream_name = IMergeTreeDataPart::getStreamNameForColumn(name_and_type, substream_path, DATA_FILE_EXTENSION, data_part_info_for_read->getChecksums(), storage_settings),+ .cache_key = cache_key};+ if (resolved.stream_name)+ resolved.avg_value_size_hint = &avg_value_size_hints[*resolved.stream_name];+ return substreams.emplace(std::move(cache_key), std::move(resolved)).first->second;+}+
double * MergeTreeReaderWide::avgValueSizeHintSlot(const ResolvedSubstream & resolved)
{
if (resolved.avg_value_size_hint || !resolved.stream_name)
@@ -1548,12 +1573,14 @@ void MergeTreeReaderWide::readData(
deserializePrefix(serialization, name_and_type, from_mark, deserialize_binary_bulk_state_map, cache, deserialize_states_cache, {});
- /// The substreams of the column resolved in `addStreams`; a path not found there (a dynamic subcolumn) is- /// resolved on the spot into `computed`, see `resolveSubstream`.- const auto * resolved_substreams = findResolvedSubstreams(name_and_type.name);+ /// The substreams of the column resolved in `addStreams`; a path not found there (a dynamic subcolumn) is resolved+ /// once and added, see `resolveAndAddSubstream`. Without entries for the column, `computed` is filled on the spot.+ auto * resolved_substreams = findResolvedSubstreams(name_and_type.name);
const auto resolve = [&](const ISerialization::SubstreamPath & substream_path, ResolvedSubstream & computed) -> const ResolvedSubstream &
{
- return resolveSubstream(resolved_substreams, name_and_type, substream_path, computed);+ if (resolved_substreams)+ return resolveAndAddSubstream(*resolved_substreams, name_and_type, substream_path);+ return resolveSubstream(nullptr, name_and_type, substream_path, computed);
};
deserialize_settings.getter = [&](const ISerialization::SubstreamPath & substream_path)
diff --git a/src/Storages/MergeTree/MergeTreeReaderWide.h b/src/Storages/MergeTree/MergeTreeReaderWide.h
index 83982d1ac40..bee6e77e908 100644
--- a/src/Storages/MergeTree/MergeTreeReaderWide.h+++ b/src/Storages/MergeTree/MergeTreeReaderWide.h@@ -109,15 +109,17 @@ private:
};
/// The resolved substreams of one column by their substreams cache key, the only rendering of a path that is
- /// injective (several paths may share a file). Filled in `addStreams` and read-only afterwards, so the reading- /// threads look paths up without synchronization; a path missing from it (a dynamic subcolumn discovered by- /// the prefix) is resolved the slow way by the caller.+ /// injective (several paths may share a file). Filled in `addStreams`. A path missing from it (a dynamic+ /// subcolumn discovered by the prefix) is resolved the slow way by the callers that can run on the prefixes+ /// thread pool, and resolved once and added by the callbacks of `readData`: they run on the reading thread+ /// only, after the prefix of the column is deserialized, when no other thread looks paths up.
using ResolvedSubstreams = std::unordered_map<String, ResolvedSubstream>;
std::unordered_map<String, ResolvedSubstreams> resolved_substreams_by_column;
/// The resolved substreams of a column, or nullptr for a column `addStreams` wasn't called for.
const ResolvedSubstreams * findResolvedSubstreams(const String & column_name) const;
+ ResolvedSubstreams * findResolvedSubstreams(const String & column_name);
/// The substream of `substream_path`: its entry in `substreams` (nullptr for a column without entries), or,
/// for a path unknown there, `computed` filled on the spot, which must outlive the returned reference.
@@ -127,6 +129,13 @@ private:
const ISerialization::SubstreamPath & substream_path,
ResolvedSubstream & computed) const;
+ /// The entry of `substream_path` in `substreams`, resolved and added first if there is none. Only for the callbacks+ /// of `readData`, see `ResolvedSubstreams`. The reference stays valid: inserting into an `unordered_map` moves no element.+ const ResolvedSubstream & resolveAndAddSubstream(+ ResolvedSubstreams & substreams,+ const NameAndTypePair & name_and_type,+ const ISerialization::SubstreamPath & substream_path);+
/// The slot of the average value size hint of `resolved`, or nullptr when the part has no file for it.
/// Called on the reading thread only, see the body.
double * avgValueSizeHintSlot(const ResolvedSubstream & resolved);
@groeneai could you check this and, if it holds up, open a PR? If #132369 is merged first, resolveAndAddSubstream should take the hint slot with getStreamKey, as addStreams does in that PR.
It holds up. I opened #132877 with this change: a substream that only the prefix lists is added to the column's ResolvedSubstreams on first use in readData, through the existing resolveSubstream and avgValueSizeHintSlot.
Local Release A/B, 40 pairs in both orientations, PR / master: json_subcolumns_required_conversions q0 0.892 [0.883, 0.900], SELECT json of that table 0.878 [0.847, 0.910]; wide_part_many_substreams and json_shared_data_wide within noise. A TSan build with the prefixes pool active reported nothing.
On #132369: it changes avgValueSizeHintSlot to take the substream path, so whichever of the two PRs merges second does not compile until the new call passes it, rather than silently using a different key.
Activity
Avoid building stream names and substreams cache keys on every read
Make the lookup of memoized stream names cheaper
snelheidai commentedon Nov 18, 2026
#131011 resolves the streams that
addStreamsenumerates, but the streams found while deserializing the prefix (dynamic JSON paths,Dynamicvariants) are still resolved on every call: for every block, their data getter, mark seeks and size-hint callbacks go throughgetStreamNameForColumn, the checksums lookup and theavg_value_size_hintslookup. This costs time at the default block size too: after the revert #127836, q0 oftests/performance/json_subcolumns_required_conversions.xmlwent from 0.160 s to 0.190 s on amd and from 0.213 s to 0.254 s on arm (master perf CI, 2026-11-03). After #131011 it is at about 0.18 s and 0.24 s.The patch below resolves such a path on first use in
readData, with the same functions asaddStreams, and keeps it in the column'sResolvedSubstreamsunder the key #131011 uses (getSubstreamsCacheKeyForStream). It needs no synchronization, which is why #131011 left these streams out: only the callbacks ofreadDatainsert, and they run on the reading thread afterdeserializeBinaryBulkStatePrefixhas waited for all prefix tasks of the column. The prefix callbacks still resolve these paths without inserting.Server time from
query_logon masterc64ec9cb4d17with and without the patch (the reader and the JSON/Dynamicserializations are unchanged on master since), local Release builds, 4-vCPU x86. Times are medians; the change is the geometric mean of the paired ratios with its 95% CI:json_subcolumns_required_conversionsq0 (32 dynamic paths), 20 pairsSELECT jsonof the same table (400 dynamic paths), 15 pairsjson_shared_data_wide.xmlq0 / q1 / q2, 15 pairsDynamiccolumn,SELECT d/SELECT d.String, 15 pairsWith the official builds on the same host, q0 takes 195 ms before the revert (
88f0adf4bacb) and 215 ms onc64ec9cb4d17, so the patch should bring it back to about the time before the revert (I did not build the patch with ThinLTO). Peak memory ofSELECT jsonstays at about 175 MB. None of the 1054 stateless tests matchingjson,dynamicorvariantfails only with the patch; 61 fail with both binaries on my single-node server because they need ZooKeeper, remote shards, S3 or the filesystem prefetch log.Patch (applies cleanly to master 108a2e1)
@groeneai could you check this and, if it holds up, open a PR? If #132369 is merged first,
resolveAndAddSubstreamshould take the hint slot withgetStreamKey, asaddStreamsdoes in that PR.groeneai commentedon Nov 19, 2026
It holds up. I opened #132877 with this change: a substream that only the prefix lists is added to the column's
ResolvedSubstreamson first use inreadData, through the existingresolveSubstreamandavgValueSizeHintSlot.Local Release A/B, 40 pairs in both orientations, PR / master:
json_subcolumns_required_conversionsq0 0.892 [0.883, 0.900],SELECT jsonof that table 0.878 [0.847, 0.910];wide_part_many_substreamsandjson_shared_data_widewithin noise. A TSan build with the prefixes pool active reported nothing.On #132369: it changes
avgValueSizeHintSlotto take the substream path, so whichever of the two PRs merges second does not compile until the new call passes it, rather than silently using a different key.