Skip to content

Apply a sparse PREWHERE filter that keeps few rows by index, as WHERE does - #133292

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:prewhere-sparse-filter-by-index
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:prewhere-sparse-filter-by-index

Conversation

@groeneai

@groeneai groeneai commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #133047

Changelog category (leave one):

  • Performance Improvement

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

Faster PREWHERE with a selective condition on a sparse column (for example s != '', also when moved there from WHERE): when it keeps at most 1/8 of the rows of a block, the columns read after it are filtered by the indices of the kept rows, as WHERE does, and the filter is no longer expanded to one byte per row. Selecting rows of arrays of numbers (sparse filters, sorting) copies each run of consecutive rows at once when it holds 8 or more elements.

Description

Analysis and patch by snelheidai in #133047.

A PREWHERE condition on a sparse column yields a Sparse(UInt8) filter. FilterWithCachedCount expanded it to a full mask for every block, and filterColumns used its row indices only for a sparse column with the same offsets (#129738); every other column was filtered with the mask, at a cost per row instead of per kept row. WHERE uses IColumn::index.

  • filterColumns takes index when the filter keeps at most 1/8 of the rows, and the full mask is built only when needed. Above that the in-place mask filter is faster (index for arrays, strings and tuples was up to 23% slower at 80-99% kept).
  • ColumnArray::index copies each run of consecutive selected rows with one insertRangeFrom when the values are fixed-size and the runs average at least 8 elements (Avoiding multiple copies of data on array high order functions (Part 1) #111581 copies per row), also inside Tuple/Map and in permute. Copying per row left short arrays after a clustered filter below 1/8 up to 13% slower than master. Other nested types keep the gather; the element count is overflow-checked.

PR / master, perf.py, servers run at once, Xeon 6975P-C, 16 pinned cores, ThinLTO clang-23, 4 / 16 threads: ClickBench Q10 0.934 / 0.948, Q11 0.921 / 0.952, max(UserID) ... WHERE MobilePhoneModel <> '' 0.885 / 0.906; queries without a sparse filter 0.98 to 1.03. From 5 to 99% kept rows, random or in runs, no case is slower than master beyond noise (worst cases, 50 runs: 0.86 to 1.03). All 43 ClickBench results are equal.

Tests: 01780_column_sparse_filter compares 14 column kinds read after a sparse PREWHERE with a table without sparse columns, on both sides of the threshold and with runs; a gtest pins the overflow check; prewhere.xml gets the sparse query (0.918 locally); sparse_prewhere_array_runs.xml covers short arrays with runs (0.90 and 0.99 locally).


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

groeneai and others added 3 commits November 20, 2026 17:17
`ColumnArray::indexImpl` built one 8-byte nested index per selected element
and gathered the nested values element by element, and it reserved that
scratch for every element of the whole column whatever `limit` was.

A pre-pass now computes the result offsets and the number of selected
elements. When the nested values are fixed-size (`isFixedAndContiguous`)
and the selected rows hold at least 8 elements on average, each selected
array is copied with one `insertRangeFrom`. This is the per-row copy and
the break-even of `ColumnReplicated::convertToFullColumnArrayImpl`
(ClickHouse#111581). Other nested types, and shorter arrays, keep the element
gather, whose scratch is now reserved for the selected elements only.
The decision is made in the array that holds the values, so an array of
numbers inside a `Tuple`, a `Map` value or an outer `Array` is copied by
range too.

The selected element count is checked against `Offset` overflow and
throws `TOO_LARGE_ARRAY_SIZE`, as `ColumnArray::insertManyFrom` does: an
array of `Tuple()` can claim a huge size without storage, so repeated
indexes could wrap the sum.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A PREWHERE condition on a sparse column yields a `Sparse(UInt8)` filter.
`FilterWithCachedCount` already extracted its kept-row indices, but its
constructor still expanded it to a full one-byte-per-row mask, and
`filterColumns` used the indices only for a `ColumnSparse` whose offsets
equal them (ClickHouse#129738); every other column was filtered with the full mask,
so the cost was per row of the range instead of per kept row. WHERE
(`FilterTransform` + `SparseFilterDescription`) applies the same filter by
`index` to every column.

`filterColumns` now takes `index` for every column when the filter is
sparse; `ColumnSparse::indexImpl` still shares its values when the
indices equal its offsets, so the ClickHouse#129738 case is subsumed.
`FilterWithCachedCount` builds the full mask lazily, on the first
`getData()` / `getColumn()` (several PREWHERE steps, zero-tail collapse,
vector search), and stores the row count separately.

Adds a `prewhere.xml` query with a sparse PREWHERE condition and extends
`01780_column_sparse_filter` with every column kind read after such a
filter.

Analysis and patch by snelheidai in ClickHouse#133047.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the range-copy threshold comment to one line and drop the cross-file reference in filterColumns.

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

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

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

# Sev Finding Verdict Evidence / action
1 ⚠️ The overflow gtest also passes on master, whose whole-column reservation throws first DISAGREE Master refuses that input, so it is not exposed. Removing only the new throw makes the test fail (debug: non-monotonic offsets abort; release: an empty result, no exception)
2 ⚠️ Result equality cannot show that a sparse filter takes index without building the mask DISAGREE Results are equal by design. The shipped prewhere.xml query (0.893 locally) and sparse_column_filter.xml show the speed-up. A throw injected in the sparse branch fails all four sparse queries and none of the twins. ClickBench Q10/Q11 are WHERE queries moved to PREWHERE (0.936 / 0.908)
3 ⚠️ No test of arrays inside Tuple/Map, nor of permute or repeated indexes DISAGREE No wrapper-specific code: Tuple/Map delegate to ColumnArray::index, which arrl covers. The test's own INSERT ... SELECT sorts arrl through permute, and the row hashes check it. The per-row copy assumes no order. perf.py found no result difference for Tuple(UInt64, Array(UInt64)), Map, lazy replication or ORDER BY arrays
4 💡 PR body linked the issue only in prose AGREE, fixed Closes: line added
5 💡 permute (sorting arrays) also reaches the range copy AGREE Named in the description; sorting arrays measured 0.984 / 0.969, no row slower
6 💡 FixedString/Decimal/Dynamic/JSON are not in the type matrix DISAGREE Their index overrides are the ones WHERE already uses with a sparse filter

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

Session id: cron:clickhouse-review-slot-8:20261120-183600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? perf.py (two concurrent servers, Release ThinLTO, master cb8033b vs this PR), 5 fresh-server runs: Q10, Q11, max(UserID) ... WHERE MobilePhoneModel <> '' and max(str) ... PREWHERE str != '' are faster by more than 3-5% at p < 0.01 in at least 4 of 5 runs, at 4 and 16 threads.
b Root cause explained? A sparse PREWHERE filter was expanded to a full mask and every column except a matching sparse one was filtered with it (cost per row of the range), while WHERE uses index (cost per kept row). index on arrays of numbers gathered element by element.
c Fix matches root cause? The mask is built only when needed and filterColumns uses index for every column; the array cost is fixed in ColumnArray::indexImpl itself (range copy for fixed-size values), not by a per-type exception in filterColumns.
d Test intent preserved / new tests added? 01780_column_sparse_filter: additions only, 14 column kinds compared against a table without sparse columns in 4 filter shapes; gtest for the overflow check; prewhere.xml gets one query. Mutants that throw in the new branches turn the new queries red.
e Both directions demonstrated? Faster in the perf A/B above; results identical on both binaries (43/43 ClickBench queries, perf.py result check, the new test block byte-identical on master).
f Fix is general across code paths? Every ColumnArray::index / permute caller gets the range copy (sparse WHERE, joins, lazy replication, sorting); ColumnReplicated keeps its own copy.
g Fix generalizes across inputs (params/datatypes/wrappers)? Numbers, String, Nullable, LowCardinality, short and long Array, Array(String), Map, Tuple; zero tails, mostly-kept, two PREWHERE steps; overflow boundary in the gtest.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or serialization change.
i Invariants and contracts preserved? index of the kept rows equals filter with the mask for every column; the filter's getters return the same values; ColumnArray::index returns the same column (offsets computed once, range copy equals gather), and the element count is checked before any allocation.

Session id: cron:clickhouse-impl-slot-5:20261120-154400

@clickhouse-gh

clickhouse-gh Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0e76c8b]

Summary: ✅


AI Review

Summary

The PR applies selective sparse PREWHERE filters by row index, materializes full masks on demand, and copies consecutive array rows in ranges. No actionable findings at 0e76c8bc2c6121dad686e9a7d1f418f137f6adf6 after reviewing the current code, affected callers, prior discussion, regression coverage, and recorded before/after benchmarks. Local tests and benchmarks were not run because this checkout has no built clickhouse binary.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0e76c8bc2 with master 8e480eac3 (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.

Compile time of recompiled translation units

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

Job report

@stresshouse

stresshouse Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

Only one query was flagged: clickbench Q10 (MobilePhoneModel, COUNT(DISTINCT UserID) with WHERE MobilePhoneModel <> ''), which measured +16.3% slower (107 ms vs 92 ms). This query runs exactly the code the PR changes: the sparse PREWHERE filter is now kept as row indices, and columns such as UserID are filtered with index() when few rows are kept. The PR description names this query as one it speeds up, so a slowdown is the opposite of what was expected. The automatic checks hid it because 107 ms falls inside master's recent range for this query (83–115 ms). That range is wide because master's timing for this query is noisy, and the tested runs shared a machine with another benchmark, so the result is now shown as inconclusive rather than as a regression. A rerun on dedicated hardware, compared against the PR's own prewhere.xml query, would show whether the index-based filtering is actually slower for UserID on this data.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 10 not_sure 92 107 +16.3% <0.0001 cpu: This query runs the sparse PREWHERE path the PR rewrites, yet it measured +16.3% slower where the PR claims a speedup. The result is inside master's current range and no CPU data exists, so treat it as unconfirmed.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: d8fe7993-6c42-44bd-9a3e-63845b462d7c
  • MIRAI run: fe224de9-3cec-4497-9a5a-1b8ee575ca38
  • PR check IDs:
    • clickbench_638109_1795257746
    • clickbench_638115_1795257746
    • tpch_adapted_1_official_638131_1795257746
    • tpch_adapted_1_official_638170_1795257747

`index` writes the kept rows to new columns, while the mask filter moves
them inside the column. When a sparse filter keeps most rows of a block
(a clustered condition), `index` for every column made arrays of numbers,
64-byte strings and `Tuple(UInt64, Array(UInt64))` up to 23% slower than
master at 80-99% of rows kept (reported by snelheidai in ClickHouse#133047 for
arrays). Keeping the mask only for top-level arrays of fixed-size values
left the strings and tuples up to 16% slower.

`index` is now taken when the filter keeps at most 1/8 of the rows, and
always for a sparse column whose non-default rows are the kept ones (it
shares the values). Otherwise the full mask is built and used as on
master.

perf.py, master / index for every column / this commit concurrently,
ThinLTO clang-23, 4 / 16 threads:
- kept fraction 5..99%: with `index` for every column, short arrays are
  slower from 20%, long arrays from 35%, 64-byte strings from 65%; with
  the 1/8 gate no case is slower than master beyond noise (50-run check
  of the worst cases: 0.87..1.03). All 43 ClickBench results are equal.
- ClickBench Q10 0.934 / 0.948, Q11 0.921 / 0.952,
  `max(UserID) ... WHERE MobilePhoneModel <> ''` 0.885 / 0.906, the same
  as with `index` for every column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai
groeneai force-pushed the prewhere-sparse-filter-by-index branch from 116fc46 to 17ce759 Compare November 21, 2026 02:02
@groeneai groeneai changed the title Apply a sparse PREWHERE filter by index to every column, as WHERE does Apply a sparse PREWHERE filter that keeps few rows by index, as WHERE does Nov 21, 2026
Below the 1/8 gate, a sparse `PREWHERE` filter whose kept rows come in
runs (a clustered condition) left short arrays of numbers slower than
master's mask filter: `index` gathered arrays of fewer than 8 elements
value by value through 8-byte nested indexes, while the mask filter
copies whole 64-row chunks (reported by snelheidai in ClickHouse#133047).

The range copy now copies each run of consecutive selected rows with one
`insertRangeFrom` when the runs average at least 8 elements, not only
when the rows do. `permute` takes the same path. Indexes are compared as
`UInt64`, so `UInt32` indexes cannot wrap into a false run.

perf.py, master / previous head / this commit concurrently, ThinLTO
clang-23, 33.5M rows, `max(arraySum(a)) ... PREWHERE f != ''`, 6-12.5%
of rows kept (one 512-1024-row run per granule, 8-row runs, random),
4 / 16 threads, two 50-run rounds: for `Array(UInt8)` and `Array(UInt64)`
with 0-6 elements and `Array(UInt64)` with 8-12, the previous head was up
to 1.06-1.09 of master, this commit 0.86-1.02 (8-row runs 0.86-0.95).
Strings, numbers and tuples of scalars do not reach this code. All
result hashes are equal across the three binaries. The new perf test,
one thread, 3 rounds: 8-row runs 1.03 -> 0.90 of master, one 820-row run
per granule 1.13 -> 0.99.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6904564

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
Stress test (arm_release) / Hung check failed, possible deadlock found not from this PR, which changes ColumnArray::indexImpl and PREWHERE filtering: a TablesStatus request resolves a table created AS url(...) while holding StorageTableFunctionProxy's nested_mutex, and the resolution sits in the HTTP retry backoff of schema inference. SYSTEM STOP MERGES/MOVES/FETCHES, system.replicas, system.mutations and DETACH DATABASE wait on that mutex for up to 2360 s (c_stacktraces.log). First hung check with this stack in 30 days a fix task is created (investigating at full effort, fixing PR link to follow on this PR)
Mergeable Check, PR praktika rollups of the row above a fix task is created (the owner above)

CH Inc sync and Review Threads are green on this head.

Session id: cron:our-pr-ci-monitor:20261121-130022

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for Stress test (arm_release) / Hung check failed, possible deadlock found (a TablesStatus request resolving a url() table-function proxy under nested_mutex): #113389 (external, open).

At its head 511562f0, processTablesStatusRequest loads a table only when its engine is a replicated one, so it no longer executes a table function, and tryGetNested / nestedIfResolved take a separate leaf mutex, so SYSTEM STOP, system.replicas and system.mutations no longer wait for a resolution in progress.

…ilter-by-index

# Conflicts:
#	src/Columns/ColumnArray.cpp

This branch has not been deployed

No deployments
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

Projects

None yet

2 participants