Skip to content

Share the values of a sparse column filtered by its own non-default rows in PREWHERE - #129738

Merged
Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:sparse-prewhere-share-values
Nov 11, 2026
Merged

Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:sparse-prewhere-share-values

Conversation

@groeneai

@groeneai groeneai commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129686
Related: #129705

Changelog category (leave one):

  • Performance Improvement

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

Faster PREWHERE filtering of a sparse column by a condition that keeps exactly its non-default rows (for example PREWHERE s != '' on a sparse String column): the column's values are shared instead of copied.

Description

Depends on #129705 (its commit is the first one here).

A condition such as s != '' on a sparse column is computed on its values only and returned as Sparse(UInt8) sharing the column's offsets, so the PREWHERE filter's sparse indices are exactly the column's non-default rows. filterColumns in MergeTreeRangeReader.cpp still copied every kept value with filter. Now, when the column's offsets equal the filter's sparse indices, it calls index, which shares values since #129705. It runs before the in-place branch, so other sparse columns with the same non-default rows share their values too. On a miss it costs a type check and a size compare (plus an element compare up to the first difference when the sizes match).

Measured locally (pinned cores, ThinLTO clang-22, paired runs, 95% CI), vs #129705 alone unless stated, 1 thread / 16 threads:

  • ClickBench PREWHERE MobilePhoneModel <> '' GROUP BY MobilePhoneModel: -18.3% [-20.8, -15.7] / -12.4% [-16.6, -7.9].
  • WHERE MobilePhoneModel <> '' GROUP BY MobilePhoneModel, UTMSource (moved to PREWHERE): -11.6% / -7.1%.
  • Check before vs after the in-place branch (50M rows, PREWHERE s != '', 1 thread, 3 x 40 runs): a column with the same non-default rows -8.6% to -19%; the filtered column unchanged; a sparse column with other rows -5.3% to +4.0% (no consistent change); peak memory equal.
  • New sparse_column_filter query max(str) ... PREWHERE str != '': -6% to -9% in two runs at every ratio.
  • No sparse_column* perf test row is slower by more than 2% (p < 0.01) in both runs; numeric PREWHERE and the controls are unchanged; results are identical.

Tests: 01780_column_sparse_filter gets sparse-vs-full PREWHERE comparisons (one and two steps, small blocks); each reaches the new branch (checked by making it throw), and the output is identical on master.

Idea and analysis by snelheidai in #129686.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2001-master (included in 26.11 and later)

…ows in `PREWHERE`

A condition such as `s != ''` on a sparse column is computed on its values
only and returned as Sparse(UInt8) sharing the column's offsets, so the
PREWHERE filter's sparse indices are exactly the column's non-default rows.
`filterColumns` copied every kept value with `filter`; when the offsets equal
the sparse indices, use `index`, which shares `values` since the previous commit.

Idea and analysis by snelheidai in ClickHouse#129686.

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

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings) plus my own review (4 nits).

# Sev Finding Verdict Evidence / action
1 ❌ Sharing values keeps a non-type-default values[0], so a later insertDefault differs (ColumnSparse::indexImpl) DISAGREE No producer makes such a column: the constructor, IFunction (res->isDefaultAt(0) check) and every deserialization path put the type default at values[0], and isDefaultAt assumes it. In filterColumns the replaced ColumnSparse::filter already keeps the source values[0], so nothing changes there.
2 ⚠️ The PREWHERE queries do not prove the new branch shares values DISAGREE The SQL test checks results on the new path: making the branch throw reddens every comparison, corrupting the shared result reddens the first. Losing the speed-up is caught by the new sparse_column_filter perf query.
3 💡 Nullable sparse arm dropped (needs serialization_info_version = 'with_types' under random settings) noted Opt-in setting, filter indices come from existing code.
4 💡 On a hit the offsets are compared twice (here and in indexImpl) noted Both linear in the non-default rows; included in the measurements.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261106-134300

@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cb7e101]

Summary: ✅


AI Review

Summary

PR #129738, head cb7e101f65824c4529ef66d7c2c273b64c120ecf, shares sparse column values during PREWHERE filtering when the selected indices exactly match the column's offsets. No actionable findings remain after reviewing the diff, current code, and all prior discussion. The recorded benchmarks support the performance claim.

Missing context / blind spots
  • ⚠️ Current-head CI is still running. 01780_column_sparse_filter passed in AMD debug CI on cbc05b2a412ce6e4c6702c866bef4bf9ed668c89, before the master merge. Completion of current-head CI will validate the merged revision. No local ClickHouse binary is available for independent test or benchmark runs.
Final Verdict

✅ Approve — no new inline findings or thread updates are warranted.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 6, 2026
@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar, could you review this and add the can be tested label so CI runs? A PREWHERE condition such as s != '' on a sparse column gives a filter whose sparse indices are exactly the column's offsets, so filterColumns now calls index (which shares values since #129705) instead of copying every kept value with filter.

@Algunenano Algunenano self-assigned this Nov 6, 2026
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Nov 6, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Nov 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cb7e101f6 with master 0e42176d2 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.57, programs/clickhouse-keeper ×0.72 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.1 s +5.1 s (+251%)
Compile time of recompiled translation units

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

Job report

@snelheidai

Copy link
Copy Markdown

On the order in filterColumns: the check can go before canInplaceFilter, and that is faster. It makes no difference for the column the condition was computed from, but it speeds up another column with exactly the same non-default rows.

  • The filtered column itself always reaches the new branch. IFunction's sparse path returns ColumnSparse::create(res, sparse_offsets, input_rows_count) with that column's own offsets, and FilterWithCachedCount keeps the filter alive in sparse_indices_holder. So during filterColumns that offsets has use_count() > 1, and canInplaceFilter is false.
  • A uniquely owned column with the same non-default rows, read after the PREWHERE step (like u in the new test), currently takes the in-place ColumnSparse::filter. With the check first, index shares its values instead.
Query, PREWHERE s != '' after (PR), ms before, ms Change [95% CI]
sum(u), max_threads = 1 192 164 −14.9% [−15.9%, −13.9%]
max(w), max_threads = 1 569.5 536 −5.9% [−6.3%, −5.5%]
sum(u), max(w) 315.5 297 −6.0% [−7.4%, −4.6%]
max(s), max_threads = 1 (only the filtered column) 196 195 −0.8% [−1.7%, +0.2%]

100M rows in one part: s String non-empty in 5% of rows, u UInt64 and w String non-default in exactly the same rows, all three Sparse. Median server time of 40 paired runs; the change is the geometric mean of the paired ratios. Release build without LTO of master 7a516a1 with this PR, x86 with 4 vCPUs.

In a profile of the sum(u) query, the in-place ColumnSparse::filter takes 12% of the samples with the current order. With the check first it is gone, and the offsets comparison plus index take under 2%. Both orders give the same results, pass 01780_column_sparse_filter and match a non-Sparse copy of the table. For other columns, the check adds a typeid_cast and, for Sparse ones, the offsets comparison, which stops at a size difference or the first different offset.

The measured change, on top of this PR
diff --git a/src/Storages/MergeTree/MergeTreeRangeReader.cpp b/src/Storages/MergeTree/MergeTreeRangeReader.cpp
index 501280925c5..5f8ca58a682 100644
--- a/src/Storages/MergeTree/MergeTreeRangeReader.cpp
+++ b/src/Storages/MergeTree/MergeTreeRangeReader.cpp
@@ -97,7 +97,13 @@ static void filterColumns(Columns & columns, const FilterWithCachedCount & filte
                 throw Exception(ErrorCodes::LOGICAL_ERROR, "Size of column {} doesn't match size of filter {}",
                     column->size(), filter.size());
 
-            if (canInplaceFilter(column, filter.getColumn()))
+            if (const auto * column_sparse = sparse_indices ? typeid_cast<const ColumnSparse *>(column.get()) : nullptr;
+                column_sparse && column_sparse->getOffsetsData() == sparse_indices->getData())
+            {
+                /// The filter keeps exactly the non-default rows of this column, so `index` shares its values.
+                column = column_sparse->index(*sparse_indices, 0);
+            }
+            else if (canInplaceFilter(column, filter.getColumn()))
             {
                 /// The contract is - not to filter in-place if the column is shared. But if there're some shared subcolumns,
                 /// we'll clone them via IColumn::mutate() and then safely filter in-place.
@@ -105,12 +111,6 @@ static void filterColumns(Columns & columns, const FilterWithCachedCount & filte
                 mutable_column->filter(filter_data);
                 column = std::move(mutable_column);
             }
-            else if (const auto * column_sparse = sparse_indices ? typeid_cast<const ColumnSparse *>(column.get()) : nullptr;
-                     column_sparse && column_sparse->getOffsetsData() == sparse_indices->getData())
-            {
-                /// The filter keeps exactly the non-default rows of this column, so `index` shares its values.
-                column = column_sparse->index(*sparse_indices, 0);
-            }
             else
             {
                 column = column->filter(filter_data, filter.countBytesInFilter());

groeneai and others added 2 commits November 10, 2026 14:31
The column the `PREWHERE` condition was computed from never takes the
in-place branch: the filter shares its `offsets`, so `use_count() > 1`.
But another uniquely owned Sparse column with exactly the same non-default
rows did, and the in-place `ColumnSparse::filter` still rewrites its
offsets and filters its values, where `index` shares them. On a miss the
check costs a `typeid_cast` and, for Sparse columns, an offsets comparison
that stops at a size difference or the first different offset.

Asked in ClickHouse#129738 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Algunenano
Algunenano added this pull request to the merge queue Nov 11, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Nov 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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