Skip to content

Share the values of a sparse column in ColumnSparse::index when the rows are its own non-default rows - #129705

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

Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:sparse-index-share-values

Conversation

@groeneai

@groeneai groeneai commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129686

Changelog category (leave one):

  • Performance Improvement

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

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

Description

A condition such as s != '' on a sparse column is computed on its values only and returned as Sparse(UInt8) with the column's own offsets, so FilterTransform calls index with exactly the column's non-default rows. ColumnSparse::indexImpl then copied every value with a virtual insertFrom, although the result is the same values. This happens when the condition stays in WHERE (the filtered column is the only one read, as in ClickBench Q7) or with optimize_move_to_prewhere = 0.

Now, for UInt64 indexes, when there are as many indexes as non-default rows and they equal the offsets (memcmp), indexImpl returns a sparse column that shares values.

Measured locally, master c9e18d01727e vs this PR (Xeon 6975P-C, 16 pinned cores, ThinLTO, 95% CI):

  • New sparse_column_filter query max(str) ... WHERE str != '': 387 -> 317 ms (-18%) at 10% non-default.
  • sparse_column_index_sorted WHERE a != 0 GROUP BY a: -13% / -15% in two runs.
  • ClickBench WHERE MobilePhoneModel <> '' GROUP BY MobilePhoneModel: -15.8% [-18.6, -12.9] at 16 threads, -27.4% at 1 thread; Q7: -8.8% [-16.1, -0.9] and -15.6%.
  • No other query of the four sparse_column* tests and none of the ClickBench controls (Q10, Q11, Q12) is significantly slower; results are identical.

The issue's second part (copying consecutive values with one insertRangeFrom) is not included: with ThinLTO it made the per-row insert lambda out-of-line and sparse_column_index_runs 5-20% slower. Independent of #128852.

Correctness: new ColumnSparse gtests (own rows, a limit below the index count, other rows of the same count, mutating a shared result) fail without the change; a sparse-vs-full SQL differential and the *sparse* stateless tests match master.

Analysis and patch by @ snelheidai in #129686.

🤖 Generated with Claude Code


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

Version info

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

A condition such as `s != ''` on a sparse column is computed on its values
only and returned as Sparse(UInt8) with the column's own offsets, so
FilterTransform calls `index` with exactly the non-default rows of that
column. Return a column that shares `values` instead of copying each value.

Analysis and patch by snelheidai, 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; 0 findings) plus my own review of the diff (2 nits).

# Sev Finding Verdict Evidence / action
1 💡 In IndexSortedRows, the "source unchanged" check cannot catch aliasing, because insertDefault on a sparse column never writes into values AGREE the check before it (the mutated result owns a different values object) is the one that catches aliasing; no change
2 💡 ColumnSparse::filter (the PREWHERE path) still copies values when every non-default row is kept DISAGREE separate change in another call site with its own measurement; #129686 stays open for it

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

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

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT max(str) FROM test_sparse_10 WHERE str != '' SETTINGS max_threads = 1, optimize_move_to_prewhere = 0 (the new sparse_column_filter query) and ClickBench WHERE MobilePhoneModel <> '' / Q7 always run a Filter (WHERE) step that calls index with the column's own offsets (checked with EXPLAIN). The gtest asserts that the result shares values.
b Root cause explained? IFunction computes s != '' on the sparse column's values and returns Sparse(UInt8) with the column's own offsets; SparseFilterDescription turns it into index(offsets); ColumnSparse::indexImpl copied each kept value with a virtual insertFrom, although the result is exactly the source's values.
c Fix matches root cause? Yes. For UInt64 indexes equal to the offsets (memcmp, only when the sizes match) the result shares values instead of copying them. No setting, no guard.
d Test intent preserved / new tests added? Additions only: ColumnSparse.Index cases (own rows, a limit below the index count, same count but other rows, shared-address check) and ColumnSparse.IndexSortedRows (randomized, mutating the shared result must not touch the source). One query appended to the existing sparse_column_filter.xml.
e Both directions demonstrated? Without the shared-values block the new gtests fail 3/3; with it 9/9 x3 and 50/50 shuffled repeats. A check by size only (no memcmp) also fails 3/3. Perf: master vs this PR as in the description, result hashes identical.
f Fix is general across code paths? Every caller of indexImpl<UInt64> (SparseFilterDescription, permute, ColumnReplicated, generic index) gets an exact value check, so it is correct for all. UInt8/16/32 indexes keep the old path. ColumnSparse::filter already filters values in one call.
g Fix generalizes across inputs (params/datatypes/wrappers)? The value column is shared, not read, so its type does not matter; a sparse-vs-full SQL differential covers String, Nullable(String), UInt64, Int32, FixedString(4), filters on the same and on another sparse column, max_block_size 7 / 1000 / 65409, INSERT SELECT, ORDER BY, JOIN (37/37 identical to master). limit = 0 and empty offsets return earlier.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format, serialization or on-disk change.
i Invariants and contracts preserved? index(indexes, limit) equals the full column's index row by row, and the source is never modified: index returns an immutable column, IColumn::mutate clones a shared values, and the gtest checks that the mutated result has its own values and the source is unchanged. No row of the result maps to the shared default value at position 0.

Session id: cron:clickhouse-impl-slot-4:20261106-100400

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @rienath, could you review this and add the can be tested label so CI runs? A filter such as s != '' on a sparse column reaches ColumnSparse::index with the column's own offsets, so indexImpl now shares values in that case instead of copying every value with insertFrom.

@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f637c66]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) DROPPED

AI Review

Summary

The PR avoids copying the payload in ColumnSparse::indexImpl when the requested UInt64 index prefix exactly matches all non-default offsets. It preserves the existing sparse result layout and relies on recursive copy-on-write detachment for subsequent mutation. The added indexing tests and performance query cover the optimization, and the PR provides before/after measurements supporting the claimed improvement. No actionable findings at head f637c66e4463c4de36601d031bf156a7a7b21678.

Missing context / blind spots
  • ⚠️ No local build or clickhouse executable was available, so runtime checks and benchmarks were not independently rerun. Review evidence includes the focused ColumnSparse tests passing in ASan/UBSan, TSan, and MSan CI on 3c8852a86cca976a1667801d9b60c8b619e7ec81, plus the PR's reported benchmark measurements. Local binaries would enable independent reproduction.
Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 6, 2026
@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-data-types Type system & core datatypes used across query planning/execution. labels Nov 6, 2026
@Algunenano Algunenano self-assigned this Nov 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f637c66e4 with master 28cd3f355 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 6ab096772; 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.

Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3c8852a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05401_quota_on_profile_events_query_result_cache flaky, not in this PR's diff (this PR only changes ColumnSparse::indexImpl, its gtest and a perf test): 4 1 instead of 2 1 after count(), because the quota user inherits parallel replicas from the job's default profile and the SelectQuery of a remote replica is charged as well; the rerun failed 43 of 43 with the drawn optimize_trivial_count_query = 0 and passed 53 of 53 without randomized settings. The same test failed on master and on about 20 other unrelated PRs today. The fix merged at 13:24Z, after this run (12:21Z), so the tested tree does not contain it #129672 (mine, merged)
La Casa Del Dolor (amd_tsan) / ThreadSanitizer: data race (STID: 1003-46d8) data race, not in this PR's diff: the Pretty squash thread (PrettyWriter) writes into the WriteBuffer of StorageFileSink while ~StorageFileSink cancels that buffer on the exception path of an INSERT INTO FUNCTION file(..., 'PrettySpaceNoEscapes', ...) that hit TIMEOUT_EXCEEDED; the first CIDB occurrence of this site a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check / PR praktika rollups of the two rows above #129672 (mine, merged) and a fix task is created (the owners of the two rows above)

The Config Workflow / Pre Hooks failure in CIDB comes from the run before the can be tested label was added. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261106-143004

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the La Casa Del Dolor (amd_tsan) / ThreadSanitizer: data race (STID: 1003-46d8) row of the CI finish ledger above: #129825 (mine, open).

@Algunenano
Algunenano added this pull request to the merge queue Nov 11, 2026
Merged via the queue into ClickHouse:master with commit 0e42176 Nov 11, 2026
185 of 186 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label 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-data-types Type system & core datatypes used across query planning/execution. 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.

3 participants