Repository navigation
Lazily apply selector and replication indexes in join - #98883
Conversation
|
Workflow [PR], commit [72d5082] Summary: ✅ AI ReviewSummaryThis PR adds lazy selector/replication index propagation for JOIN outputs and wires it through query-plan optimization, sorting, buffering, and serialization paths. The overall direction looks good, but there are still unresolved behavior/performance gaps in shared-index handling and Findings
💡 Nits
Final VerdictStatus:
|
| } | ||
|
|
||
| static void replicateColumnLazily(ColumnPtr & column, const IColumn::Offsets & offsets, ColumnPtr & indexes) | ||
| static void replicateColumnLazily(ColumnPtr & column, const IColumn::Offsets & offsets, ColumnPtr & indexes, bool lazy_columns_indexing) |
There was a problem hiding this comment.
I don't really understand the changes in replicateColumnLazily. From what I see, the main optimization is filterBySelectorLazily.
The changes to replicateColumnLazily with lazy_columns_indexing do two things:
- Force
ColumnReplicatedwrapping for ALL columns, bypassing theisLazyReplicationUsefulcheck - Use
replicateKeepUnusedRowsinstead of replicate for already-replicated columns
Both are problematic:
- Wrapping columns where
isLazyReplicationUsefulreturns false (e.g., small integers) adds overhead for blocks that do get materialized — every element access goes through an index indirection instead of a direct memory read. I would keepisLazyReplicationUsefulcheck before eachColumnReplicatedcreation unless there is a noticeable improvement in skipping this check. - Keeping unused rows in the nested column is unsafe because the default function implementation over replicated columns (
IFunction.cpp) extracts the nested column and executes the function directly on it, including the unused rows. This can cause exceptions on values that shouldn't be in the result: https://pastila.nl/?02eaa458/b8d89df4783fe4334f2e1850bf65d86c#Ho/Fxy2zJXcg7W8AgYPFqA==GCM. The same applies toColumnReplicated::create(column, indexes)on a regular column infilterBySelectorLazily— the original column becomes the nested column with unmatched rows as "unused" entries. It can also lead to higher memory usage if unused values are big.
In current ColumnReplicated implementation we assume that we don't have unused values in the nested column. If keeping unused rows does noticeably improve performance, we should change this assumption and probably should change the usual replicate/index/filter/etc methods (that use removeUnusedRowsInIndexedData) and fix the function execution layer by checking for unused rows in the default replicated column implementation in IFunction.cpp and removing unused values (or materializing the column).
There was a problem hiding this comment.
Thanks for the feedback.
- Regarding forcing ColumnReplicated on even small types:
I added it because I found this can be useful when you know you are going to drop most of the column afterwards, especially if there are many columns. I guess basically a tradeoff betweenbuilding the index + accessing the surviving blocks through the indexormaterializing all blocks eagerly: https://pastila.clickhouse.com/?0172a41f/5323cd846a07d9450129fed70f8d019d#GYUbHQQZuJZiqdrvkdDVKQ==GCM - Regarding keeping unused rows:
failing on filtered out rows is a really good point. Since the main optimization of this change is basically avoiding unnecessary intermediate materialization steps, it would only work if we allow keeping unused rows at least in some cases, otherwise the benefit would be lost by filtering the nested column after each step.
In this PR we only have handling for limit but another case could be a chunk going through multiple successive joins, instead of materializing all columns after each join we could intersect the indexes and materialize at the end.
For the memory concerns, I was unsure about this, my idea was that if we verify the extra data will be dropped soon (via a limit for example) it should be fine.
So maybe we can track if a column can/should have unused rows and handle as you suggested. What do you think?
Btw I noticed unused rows can slip in right now already, the first time a ColumnReplicated is created in a join it does not get compacted. Maybe for a quick fix we should compact in in replicateColumnLazily(): https://pastila.clickhouse.com/?00fa8061/44860194499153e2651912b03d6f4399#pbYkcYJe8NKke3+8zJvgVA==GCM
There was a problem hiding this comment.
I created a separate small fix for the last point for now #99564
| <!-- Insert duplicates to trigger the columns replication path --> | ||
| <fill_query>INSERT INTO small SELECT number + 100000 FROM numbers(10) ORDER BY rand()</fill_query> |
There was a problem hiding this comment.
In performance tests we first execute all create_query queries, then all fill_query queries, and only then all query queries. So this additional insert after some queries doesn't make sense.
There was a problem hiding this comment.
For some reason I don't see results for this performance test in the CI
There was a problem hiding this comment.
could it be because the test file is new?
| for (auto & col : columns) | ||
| if (const auto * replicated = typeid_cast<const ColumnReplicated *>(col.get())) | ||
| col = replicated->indexKeepUnusedRows(selector.getIndexes(), /*limit*/ 0); | ||
| else | ||
| col = ColumnReplicated::create(col, indexes_col); |
There was a problem hiding this comment.
As I described in the previous comment:
- It would be good to check for
isLazyReplicationUsefulhere. - If we want to keep unused values in nested column in
ColumnReplicatedand deal with the consequences in default implementation for replicated columns in functions.
|
After #99564 is merged, we can finish this PR |
Yes, I will work on it again this week |
Fix in #102888 |
# Conflicts: # src/Core/Settings.cpp # src/Interpreters/HashJoin/HashJoin.h
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 3b3bd59. Configure here.
| hash_join->setEnableLazyColumnsIndexing(value); | ||
| if (concurrent_join) | ||
| concurrent_join->setEnableLazyColumnsIndexing(value); | ||
| } |
There was a problem hiding this comment.
Lazy indexing flag lost when SpillingHashJoin spills to GraceHashJoin
Low Severity
SpillingHashJoin::setEnableLazyColumnsIndexing only sets the flag on hash_join or concurrent_join, but doesn't store the value as a member field. If the join later transitions to grace_join (spills to disk), the new GraceHashJoin instance never receives the flag and the optimization is silently dropped. The PR discussion also confirms this ("enabling SpillingHashJoin by default disabled the optimization, the parameter is not passed through"). The fix requires storing the value and propagating it if/when grace_join is created.
Reviewed by Cursor Bugbot for commit 3b3bd59. Configure here.
| { | ||
| const auto & replicated_col = typeid_cast<const ColumnReplicated &>(*col); | ||
| const auto & src_index = replicated_col.getIndexesColumn(); | ||
| if (src_index.get() != shared_src_index.get()) |
There was a problem hiding this comment.
transformColumnsWithSharedIndex is documented as applying index_transform once per shared source index, but this implementation caches only the last seen pointer.
For column order A, B, A (where A/B are replicated columns with different source index pointers), index_transform is invoked twice for A, and the two A columns end up with different transformed index pointers. That defeats downstream shared-index fast paths that rely on pointer identity (for example, replicated-argument sharing in IFunction), and causes avoidable extra index transformations.
Please memoize transformed indexes for all seen source pointers in this call (e.g. unordered_map<const IColumn *, ColumnPtr>), similar to the map approach already used in compactReplicatedColumns.
LLVM Coverage Report
Changed lines: 92.36% (290/314) | lost baseline coverage: 30 line(s) · Uncovered code |
becb4f8
|
This is causing multiple crashes -> #106095 Reverting |


Part of #97881
Hash join produces probe side columns by filtering or replicating the input columns.
Materializing these columns can be wasted if they are immedtiatly dropped or filtered/replicated
by a follow up join.
This optimization tells the join to produce
ColumnReplicated(input column + index) instead if oneof the following cases is detected:
Benchmark results for join_lazy_indexing.xml:
100M rows in large tables, 8K-10K rows in small tables. Duplicate small tables have 2x inserts (same data twice).
Single-join, unique small side
large_int JOIN small1 ON l.a = s.a LIMIT 80M, 10large_str JOIN small1 ON l.a = s.a LIMIT 80M, 10large_int JOIN small1 ON l.a = s.a ORDER BY l.a LIMIT 10large_str JOIN small1 ON l.a = s.a ORDER BY l.a LIMIT 10large_int JOIN small1 ON l.a = s.a ORDER BY l.a LIMIT 1000large_str JOIN small1 ON l.a = s.a ORDER BY l.a LIMIT 1000Single-join, duplicating small side
large_int JOIN small1_dup ON l.a = s.a LIMIT 80M, 10large_str JOIN small1_dup ON l.a = s.a LIMIT 80M, 10large_int JOIN small1_dup ON l.a = s.a ORDER BY l.a LIMIT 10large_str JOIN small1_dup ON l.a = s.a ORDER BY l.a LIMIT 10large_int JOIN small1_dup ON l.a = s.a ORDER BY l.a LIMIT 1000large_str JOIN small1_dup ON l.a = s.a ORDER BY l.a LIMIT 10003-way join, unique small sides
large_int 3-way JOIN small1, small2, small3 LIMIT 80M, 10large_str 3-way JOIN small1, small2, small3 LIMIT 80M, 10large_int 3-way JOIN small1, small2, small3 ORDER BY l.a LIMIT 10large_str 3-way JOIN small1, small2, small3 ORDER BY l.a LIMIT 10large_int 3-way JOIN small1, small2, small3 ORDER BY l.a LIMIT 1000large_str 3-way JOIN small1, small2, small3 ORDER BY l.a LIMIT 1000large_int 3-way JOIN small1, small2, small3 FORMAT NULLlarge_str 3-way JOIN small1, small2, small3 FORMAT NULL3-way join, duplicating small sides
large_int 3-way JOIN small1_dup, small2_dup, small3_dup LIMIT 80M, 10large_str 3-way JOIN small1_dup, small2_dup, small3_dup LIMIT 80M, 10large_int 3-way JOIN small1_dup, small2_dup, small3_dup ORDER BY l.a LIMIT 10large_str 3-way JOIN small1_dup, small2_dup, small3_dup ORDER BY l.a LIMIT 10large_int 3-way JOIN small1_dup, small2_dup, small3_dup ORDER BY l.a LIMIT 1000large_str 3-way JOIN small1_dup, small2_dup, small3_dup ORDER BY l.a LIMIT 1000large_int 3-way JOIN small1_dup, small2_dup, small3_dup FORMAT NULLlarge_str 3-way JOIN small1_dup, small2_dup, small3_dup FORMAT NULL3-way join, mixed (one unique side + two dup sides)
large_int l JOIN small1 JOIN small2_dup JOIN small3_dup FORMAT NULLlarge_str l JOIN small1 JOIN small2_dup JOIN small3_dup FORMAT NULLChangelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Implement lazy application of selector and replication indexes in case of JOIN followed by a selective LIMIT or TopN or another JOIN. To control the number of payload columns for enabling lazy selector indexes use the setting
query_plan_min_columns_for_join_lazy_indexing(0 means the optimization is disabled). To control the LIMIT for which the optimization is applied use the settingquery_plan_max_limit_for_join_lazy_indexing.Documentation entry for user-facing changes
Note
Medium Risk
Touches JOIN execution and query-plan optimizations by changing when columns are materialized vs kept as
ColumnReplicated, which can affect correctness/performance in edge cases around filtering, sorting, and limit handling. Risk is mitigated by added settings gates and new functional/performance tests, but behavior changes are broad across pipeline stages.Overview
Implements lazy selector/index application for hash JOIN outputs by introducing a query-plan optimization (
optimizeJoinLazyIndexing) that enables joins to return probe-side columns asColumnReplicatedwhen followed by selectiveLIMIT/ORDER BY ... LIMITor another JOIN, controlled by new settingsquery_plan_min_columns_for_join_lazy_indexingandquery_plan_max_limit_for_join_lazy_indexing.Refactors
ColumnReplicatedusage so operations likefilter/permute/index/replicateno longer auto-compact nested data, adds utilities (transformColumnsWithSharedIndex,convertToFullColumnIfReplicationNotUseful) to share/transforms indexes once, and introducesScatteredBlock::filterBySelectorLazily()plus chunk-level compaction (compactReplicatedColumns) applied in buffering, sorting, and caching paths to reclaim memory when needed.Updates replicated serialization to avoid writing unreferenced nested rows, adjusts unit tests for the new non-compacting semantics, and adds stateless + performance tests covering join lazy indexing behavior.
Reviewed by Cursor Bugbot for commit 3b3bd59. Bugbot is set up for automated code reviews on this repo. Configure here.
Version info
26.6.1.146