Skip to content

Lazily apply selector and replication indexes in join - #98883

Merged
m-selmi merged 49 commits into
ClickHouse:masterfrom
m-selmi:revisit-lazy-column-replication-usage
May 26, 2026
Merged

m-selmi merged 49 commits into
ClickHouse:masterfrom
m-selmi:revisit-lazy-column-replication-usage

Conversation

@m-selmi

@m-selmi m-selmi commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

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 one
of the following cases is detected:

  • The join sits below a LimitStep or SortingStep with a small limit.
  • The join sits on the probe side of an immediately following join.

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

# Query Off (s) On (s) Δ%
0/1 large_int JOIN small1 ON l.a = s.a LIMIT 80M, 10 0.304 0.211 −30.6%
2/3 large_str JOIN small1 ON l.a = s.a LIMIT 80M, 10 1.275 0.895 −29.8%
4/5 large_int JOIN small1 ON l.a = s.a ORDER BY l.a LIMIT 10 0.327 0.253 −22.6%
6/7 large_str JOIN small1 ON l.a = s.a ORDER BY l.a LIMIT 10 1.279 0.991 −22.5%
8/9 large_int JOIN small1 ON l.a = s.a ORDER BY l.a LIMIT 1000 0.362 0.292 −19.4%
10/11 large_str JOIN small1 ON l.a = s.a ORDER BY l.a LIMIT 1000 1.685 1.350 −19.9%

Single-join, duplicating small side

# Query Off (s) On (s) Δ%
12/13 large_int JOIN small1_dup ON l.a = s.a LIMIT 80M, 10 0.207 0.206 −0.7%
14/15 large_str JOIN small1_dup ON l.a = s.a LIMIT 80M, 10 0.582 0.580 −0.3%
16/17 large_int JOIN small1_dup ON l.a = s.a ORDER BY l.a LIMIT 10 0.389 0.393 +0.9%
18/19 large_str JOIN small1_dup ON l.a = s.a ORDER BY l.a LIMIT 10 1.192 1.188 −0.4%
20/21 large_int JOIN small1_dup ON l.a = s.a ORDER BY l.a LIMIT 1000 0.431 0.429 −0.5%
22/23 large_str JOIN small1_dup ON l.a = s.a ORDER BY l.a LIMIT 1000 1.574 1.532 −2.7%

3-way join, unique small sides

# Query Off (s) On (s) Δ%
24/25 large_int 3-way JOIN small1, small2, small3 LIMIT 80M, 10 0.611 0.352 −42.3%
26/27 large_str 3-way JOIN small1, small2, small3 LIMIT 80M, 10 2.254 1.224 −45.7%
28/29 large_int 3-way JOIN small1, small2, small3 ORDER BY l.a LIMIT 10 0.601 0.367 −38.9%
30/31 large_str 3-way JOIN small1, small2, small3 ORDER BY l.a LIMIT 10 2.163 1.292 −40.3%
32/33 large_int 3-way JOIN small1, small2, small3 ORDER BY l.a LIMIT 1000 0.647 0.421 −34.9%
34/35 large_str 3-way JOIN small1, small2, small3 ORDER BY l.a LIMIT 1000 2.627 1.693 −35.6%
36/37 large_int 3-way JOIN small1, small2, small3 FORMAT NULL 0.721 0.545 −24.4%
38/39 large_str 3-way JOIN small1, small2, small3 FORMAT NULL 2.732 1.961 −28.2%

3-way join, duplicating small sides

# Query Off (s) On (s) Δ%
40/41 large_int 3-way JOIN small1_dup, small2_dup, small3_dup LIMIT 80M, 10 0.321 0.316 −1.6%
42/43 large_str 3-way JOIN small1_dup, small2_dup, small3_dup LIMIT 80M, 10 0.435 0.433 −0.6%
44/45 large_int 3-way JOIN small1_dup, small2_dup, small3_dup ORDER BY l.a LIMIT 10 1.438 1.450 +0.8%
46/47 large_str 3-way JOIN small1_dup, small2_dup, small3_dup ORDER BY l.a LIMIT 10 2.112 2.108 −0.2%
48/49 large_int 3-way JOIN small1_dup, small2_dup, small3_dup ORDER BY l.a LIMIT 1000 1.578 1.565 −0.8%
50/51 large_str 3-way JOIN small1_dup, small2_dup, small3_dup ORDER BY l.a LIMIT 1000 2.542 2.568 +1.0%
52/53 large_int 3-way JOIN small1_dup, small2_dup, small3_dup FORMAT NULL 1.454 1.458 +0.3%
54/55 large_str 3-way JOIN small1_dup, small2_dup, small3_dup FORMAT NULL 2.262 2.007 −11.3%

3-way join, mixed (one unique side + two dup sides)

# Query Off (s) On (s) Δ%
56/57 large_int l JOIN small1 JOIN small2_dup JOIN small3_dup FORMAT NULL 0.787 0.724 −8.0%
58/59 large_str l JOIN small1 JOIN small2_dup JOIN small3_dup FORMAT NULL 2.032 1.764 −13.2%

Changelog category (leave one):

  • Performance Improvement

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 setting query_plan_max_limit_for_join_lazy_indexing.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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 as ColumnReplicated when followed by selective LIMIT/ORDER BY ... LIMIT or another JOIN, controlled by new settings query_plan_min_columns_for_join_lazy_indexing and query_plan_max_limit_for_join_lazy_indexing.

Refactors ColumnReplicated usage so operations like filter/permute/index/replicate no longer auto-compact nested data, adds utilities (transformColumnsWithSharedIndex, convertToFullColumnIfReplicationNotUseful) to share/transforms indexes once, and introduces ScatteredBlock::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

  • Merged into: 26.6.1.146

@clickhouse-gh

clickhouse-gh Bot commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [72d5082]

Summary: ✅


AI Review

Summary

This 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 SpillingHashJoin spill transitions, so this should not be approved yet.

Findings

⚠️ Majors

  • src/Interpreters/SpillingHashJoin.cpp:271 SpillingHashJoin::setEnableLazyColumnsIndexing updates only hash_join/concurrent_join and does not persist the flag for later GraceHashJoin creation in switchToGraceHashJoin. After spill, lazy indexing is silently dropped, so behavior diverges based on memory pressure.
    Suggested fix: store the flag in SpillingHashJoin state and apply it when constructing/switching the active join implementation.
  • src/Columns/ColumnReplicated.cpp:722 transformColumnsWithSharedIndex memoizes only the last seen source index pointer. For non-consecutive reuse patterns (for example A, B, A) it recomputes transformed indexes for A and produces pointer-distinct outputs for logically shared indexes. That defeats downstream shared-index fast paths and adds avoidable transformations.
    Suggested fix: memoize by source pointer for the full call (for example unordered_map<const IColumn *, ColumnPtr>).

💡 Nits

Final Verdict

Status: ⚠️ Request changes
Minimum required actions:

  1. Persist and propagate setEnableLazyColumnsIndexing intent across SpillingHashJoin transitions.
  2. Make transformColumnsWithSharedIndex truly share transformed indexes across all repeated source-index pointers in a call.
  3. Align query_plan_min_columns_for_join_lazy_indexing descriptions with probe-side behavior.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 5, 2026
@m-selmi m-selmi changed the title Lazily apply selector and replication indexes in case of hash join with selective limit Lazily apply selector and replication indexes in join with selective limit Mar 5, 2026
@m-selmi
m-selmi marked this pull request as ready for review March 6, 2026 10:46
@m-selmi
m-selmi requested a review from Avogar March 6, 2026 11:53
@Avogar Avogar self-assigned this Mar 6, 2026
}

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)

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.

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 ColumnReplicated wrapping for ALL columns, bypassing the isLazyReplicationUseful check
  • Use replicateKeepUnusedRows instead of replicate for already-replicated columns

Both are problematic:

  • Wrapping columns where isLazyReplicationUseful returns 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 keep isLazyReplicationUseful check before each ColumnReplicated creation 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 to ColumnReplicated::create(column, indexes) on a regular column in filterBySelectorLazily — 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).

@m-selmi m-selmi Mar 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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 between building the index + accessing the surviving blocks through the index or materializing 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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I created a separate small fix for the last point for now #99564

Comment on lines +14 to +15
<!-- Insert duplicates to trigger the columns replication path -->
<fill_query>INSERT INTO small SELECT number + 100000 FROM numbers(10) ORDER BY rand()</fill_query>

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.

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.

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.

For some reason I don't see results for this performance test in the CI

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

could it be because the test file is new?

Comment on lines +301 to +305
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);

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.

As I described in the previous comment:

  • It would be good to check for isLazyReplicationUseful here.
  • If we want to keep unused values in nested column in ColumnReplicated and deal with the consequences in default implementation for replicated columns in functions.

@Avogar

Avogar commented Apr 7, 2026

Copy link
Copy Markdown
Member

After #99564 is merged, we can finish this PR

@m-selmi

m-selmi commented Apr 7, 2026

Copy link
Copy Markdown
Contributor Author

After #99564 is merged, we can finish this PR

Yes, I will work on it again this week

@m-selmi m-selmi changed the title Lazily apply selector and replication indexes in join with selective limit Lazily apply selector and replication indexes in join Apr 15, 2026
@m-selmi

m-selmi commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Comment thread src/Core/SettingsChangesHistory.cpp Resolved
Comment thread src/Core/SettingsChangesHistory.cpp Resolved

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 3b3bd59. Configure here.

hash_join->setEnableLazyColumnsIndexing(value);
if (concurrent_join)
concurrent_join->setEnableLazyColumnsIndexing(value);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Fix in Cursor Fix in Web

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())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented May 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 92.36% (290/314) | lost baseline coverage: 30 line(s) · Uncovered code

Full report · Diff report

@m-selmi
m-selmi added this pull request to the merge queue May 26, 2026
Merged via the queue into ClickHouse:master with commit becb4f8 May 26, 2026
327 of 328 checks passed
@m-selmi
m-selmi deleted the revisit-lazy-column-replication-usage branch May 26, 2026 08:15
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 26, 2026
@Algunenano

Copy link
Copy Markdown
Member

This is causing multiple crashes -> #106095 Reverting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

6 participants