Repository navigation
Push down string filters from PREWHERE into the scan - #115848
Conversation
Add the `apply_string_filters_during_scan` setting (disabled by default). When a PREWHERE condition contains a conjunct that searches for a non-empty substring in a `String` (or `Nullable(String)`) column (`LIKE`, `position`, `startsWith`, `endsWith`, or equality with a non-empty string), the reader checks every value against this condition during deserialization and reads non-matching values as empty strings, avoiding the copy of their data. This is correct because such conditions never match an empty string, and the rows with non-matching values are guaranteed to be filtered out by PREWHERE. The filter is disabled adaptively at runtime if it turns out to be non-selective. Supported for reading from `MergeTree` (wide and compact parts, both string serialization versions) and from the `Parquet` format (plain, delta-length and dictionary encodings; for dictionary-encoded pages the filter is only checked once per dictionary entry). Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [62a3c83] Summary: ✅
AI ReviewSummaryThis PR adds Findings
Final VerdictChanges requested: the remaining gaps are user-visible performance-contract issues in two important paths, so I would not merge the PR as-is. LLVM Coverage ReportMeasured on commit 62a3c83.
Changed lines: Changed C/C++ lines covered: 648/748 (86.63%) · Uncovered code |
Checking every value with a separate substring search turned out to be slower than the unfiltered read on ClickBench: the baseline is one bulk copy of the column plus one bulk scan by the `like` function, while a search per short value pays the searcher setup cost millions of times. Instead, when the filter has a substring condition and the value sizes are known (the default `with_size_stream` serialization), scan each buffer of concatenated values only once with the searcher of the longest such condition, map the found occurrences to values (an occurrence crossing a boundary between values is not a match), and copy only the matching values. This pays the same single scan as the unfiltered read, but skips copying the non-matching values. On ClickBench `hits` with `PREWHERE URL LIKE '%google%'`-style queries (Q20-Q23) this makes queries 1.1-1.25 times faster and reduces memory usage by 45-58%, where the per-value check was 10-15% slower than the baseline. Co-Authored-By: Claude Fable 5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=4 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
The WHERE to PREWHERE optimization does not move conditions involving all queried columns, because without other columns to skip reading there is nothing to gain. With `apply_string_filters_during_scan` this is no longer true: a substring search condition makes the scan itself cheaper, because the reader skips copying the non-matching values. So when the setting is enabled, relax the rule for conditions that can be used as a string filter during the scan (`like`, `position`, `startsWith`, `endsWith` on a String column with a non-empty needle). Plain equality with a string constant is deliberately not accepted for the relaxation, although the scan filter supports it: it is too common, and it would change the plans of too many queries where the primary key index does the job anyway. This makes ClickBench Q20 (`SELECT COUNT(*) FROM hits WHERE URL LIKE '%google%'`) use PREWHERE and the string filter as written: 1.25 times faster and 59% less memory on the 100M-row hits table. Co-Authored-By: Claude Fable 5 <[email protected]>
|
We can also push down filter from the previous stages of the |
…pushdown # Conflicts: # src/Processors/QueryPlan/ReadFromMergeTree.cpp
|
🕵 @CurtizJ Good idea — pushing the row filter accumulated from the earlier PREWHERE steps into string deserialization (so already-filtered-out rows are decoded as empty strings too) composes naturally with this mechanism. It needs the per-granule row mask to be threaded down to the serialization, which is a larger change, so it is better done as a follow-up to keep this PR reviewable. |
…on path If deserialization throws before the first value is fully read into an empty `ColumnString`, `offsets` is empty and `offsets.back()` reads out of bounds. Restore `data` to the end of the last complete row, or to zero when there is none. Addresses an AI review finding on #115848
…und the mask, fix clang-tidy - `Dictionary::index` now reports its statistics via `StringValueFilter::updateStats` and stops applying `string_value_filter_mask` once the filter disables itself, same as the non-dictionary decoding paths. - `Dictionary::decodedFootprintUpperBound` accounts for the per-entry `string_value_filter_mask` that `buildStringValueFilterMask` allocates in the memory-bounded pruning path. - Save the result of `StringConverter::isTrivial` into a variable in `PlainStringDecoder::decode`, so that the clang static analyzer can see that `filter` is non-null in the non-trivial branch (fixes the `Build (arm_tidy)` failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115848&sha=ee0ee6e525752defaf2f214ad601467da72d024d&name_0=PR&name_1=Build%20%28arm_tidy%29). Addresses AI review findings on #115848
…pushdown # Conflicts: # src/DataTypes/Serializations/SerializationString.cpp # src/Storages/MergeTree/MergeTreeReaderCompact.cpp
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes474 object files changed (+280.64 KiB total), 2 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units3778 translation units recompiled, 19141 s compile time in total, 3776 of them have a recent master baseline. Symbol sizes
|
…pushdown # Conflicts: # src/Processors/Formats/Impl/Parquet/Decoding.cpp # src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp
- `Parquet`: do not build or reserve for `string_value_filter_mask` once the shared `StringValueFilter` has disabled itself, so dictionary pages really revert to plain decoding after the adaptive disable (review comment on `Reader.cpp`). - `05028_string_filters_during_scan_merge_tree`: disable sparse serialization for the test tables. With the randomized `ratio_of_defaults_for_sparse_serialization = 0.0` the `String` columns were written with the sparse serialization, which the scan filter does not support, so the check that the optimization is applied reported zeros. - `03634_autopr_input_bytes_estimation*`: disable `apply_string_filters_during_scan`. The estimation of the input bytes is based on the in-memory size of the read blocks, which becomes much smaller than the data read from disk when non-matching values are replaced by empty strings. The interaction is documented in the description of the setting.
…ing filter - `Dictionary::appendRepeated` (`Mode::StringPlain`) now consults `string_value_filter_mask` and reports the run to `StringValueFilter::updateStats`. Repeated dictionary indexes - the `bit_width == 0` pages and every RLE run of `BitPackedRLEDecoder::decodeAndIndex` - went through this method, so they neither skipped the copy of non-matching values nor took part in the adaptive disable. - `Dictionary::index` and `Dictionary::appendIndexes` take `use_string_value_filter`, and the whole-dictionary materialization done for row group pruning (`hashDictionaryValues`) passes false. That pass visits every distinct value once, so it used to drive the adaptive disable by the dictionary's value mix instead of the row frequencies of the scan. - `05029_string_filters_during_scan_parquet`: cases for a dictionary of long RLE runs, for a single-valued (zero bit width) column, and for the interaction of dictionary pruning with the shared filter. - `05030_string_filters_move_to_prewhere`: pin `optimize_move_to_prewhere` and the sparse serialization, both of which are randomized in tests. - The remaining `autopr_input_bytes_estimation` tests that read a filtered string column disable `apply_string_filters_during_scan` for the same reason as `03634`.
…rage The `Parquet` reference gains the new dictionary-run and pruning cases, and `05055_string_filters_move_to_prewhere` also pins `query_plan_optimize_prewhere`, which is randomized as well and moves the condition to `PREWHERE` at the plan level.
…EWHERE `extractStringValueFilters` walked the whole top-level `PREWHERE` conjunction and attached the filter to the column, but the row is rejected only after the whole expression has been evaluated. Another expression on the same column therefore observed the empty string substituted by the scan: `PREWHERE throwIf(empty(s), '...') = 0 AND s LIKE '%needle%'` started to throw for every row that the `LIKE` rejects. Now the extraction records, for every candidate column, the nodes of the extracted predicates that read it, and drops the column if any other node of the expression reads it as well. Both call sites (`ReadFromMergeTree` and `Parquet::Reader::preparePrewhere`) go through this function. Added a regression test; it throws without the fix. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…string read `readFilteredStringValue` computed `istr.position() + size` to decide whether the value fits into the buffer. When the read buffer is empty its pointers are null, and offsetting a null pointer is undefined behavior, which UBSan reported as `applying non-zero offset 21 to null pointer` in `SerializationString.cpp`. Use `istr.available()` instead, which subtracts the two pointers. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115848&sha=bed7cee3155ecc8f71dc589044f203f6a17943ee&name_0=PR&name_1=Stateless%20tests%20(arm_asan_ubsan,%20targeted) #115848 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Merged
The remaining red was @groeneai, investigate the failure: https://github.com/ClickHouse/ClickHouse/actions/runs/33586773938/job/100127618556 ( |
# Conflicts: # src/Storages/MergeTree/IMergeTreeReader.cpp
…KFilter` will read the column `optimizePrewhere` runs before `installTopKDynamicFilter`, so a pending TopN dynamic filter on the same column was not counted among the columns read before the moved conditions. The condition that uses all queried columns was then moved to `PREWHERE`, but `extractStringValueFilters` dropped the scan-time filter after `__topKFilter` was prepended. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| return false; | ||
|
|
||
| if (where_optimizer_context.columns_read_before_filter | ||
| && where_optimizer_context.columns_read_before_filter->contains(argument.getColumnName())) |
There was a problem hiding this comment.
This still keys “already read before the filter” by the logical input name, not by the storage column. That leaves a gap for same-storage subcolumns such as payload.size0: PREWHERE payload.size0 > 0 does not block moving WHERE payload LIKE '%needle%', because payload.size0 != payload here, but MergeTreeSplitPrewhereIntoReadSteps groups adjacent same-storage predicates into one step and IMergeTreeReader then disables the scan-time filter once it sees both reads touching storage column payload.
The end result is the relaxed WHERE → PREWHERE move with none of the intended scan-time win. Please resolve columns_read_before_filter to storage names (or compare against getNameInStorage() here) before treating a predicate as eligible for the all-queried-columns relaxation.
There was a problem hiding this comment.
🕵 This PR is already in the merge queue, so its branch cannot be updated. The change is in the follow-up #124503 (commit 0185c5f): columns_read_before_filter is now mapped to storage columns, and is_string_column compares getNameInStorage. One note: I could not reproduce the exact scenario. When the existing PREWHERE or the row policy reads a subcolumn such as s.null, that subcolumn is added to the queried columns, so the LIKE on s no longer covers all queried columns. The ordinary rule then moves it to PREWHERE even with apply_string_filters_during_scan = 0, and the relaxation is never reached. The fix keeps the check correct anyway.
| { | ||
| case parq::Type::BYTE_ARRAY: | ||
| return std::make_unique<DeltaLengthByteArrayDecoder>(data, string_converter); | ||
| return std::make_unique<DeltaLengthByteArrayDecoder>(data, string_converter, string_value_filter); |
There was a problem hiding this comment.
PageDecoderInfo::makeDecoder still drops string_value_filter on the DELTA_BYTE_ARRAY branch. So on Parquet string pages encoded with DELTA_BYTE_ARRAY, apply_string_filters_during_scan quietly becomes a no-op: DeltaByteArrayDecoder::decode always reconstructs and materializes the full value, and this path never contributes to the adaptive-disable stats either.
That leaves a fairly common string encoding outside the new Parquet support surface even though the setting now advertises generic Parquet support. Please either plumb the filter through DeltaByteArrayDecoder or narrow the user-facing support/tests to the encodings that are actually covered.
There was a problem hiding this comment.
🕵 This PR is already in the merge queue, so its branch cannot be updated. The filter is now passed to DeltaByteArrayDecoder for BYTE_ARRAY pages in the follow-up #124503 (commit 38b5b1f). Each value is still rebuilt, because it depends on the previous one, but values that do not match are inserted as empty strings and the filter's statistics are updated. The new test 05334_string_filters_parquet_delta_byte_array uses a pyarrow-written DELTA_BYTE_ARRAY file and checks that results match with the setting on and off, and that the StringValueFilter* profile events are counted.
alexey-milovidov
left a comment
There was a problem hiding this comment.
LGTM, and this is good start.
…an-pushdown-review-followup Apply string filters during scan to DELTA_BYTE_ARRAY Parquet pages (follow-up to ClickHouse#115848)
The optimization was added in ClickHouse#115848. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pr115848 Add 1 tests for coverage gaps in PR ClickHouse#115848
Implements pushing down of string filtering into the scan phase.
When a query has a substring search condition on a
String(orNullable(String)) column inPREWHERE(LIKE,position,startsWith,endsWith, or equality with a non-empty string), and this condition does not match an empty string, the filter is pushed down into the column deserialization: every value is checked against the filter, and if it does not match, the value is read as an empty string, without copying its data into the column. This makes reading faster and lowers memory usage when the condition is selective. The result of the query does not change, because the condition is a conjunct ofPREWHERE, which is guaranteed to filter out the rows with non-matching values, and because such conditions never match an empty string, so even a keptPREWHEREcolumn is bit-identical.The optimization works for reading from
MergeTreeand fromParquet.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added setting
apply_string_filters_during_scan(disabled by default): substring search conditions onStringcolumns (LIKE,position,startsWith,endsWith) fromPREWHEREare pushed down into the column scan, and non-matching values are read as empty strings without copying their data. Works for reading fromMergeTreeand from theParquetformat.Implementation details
StringValueFilter(src/Common/) holds the extracted conditions (substring / prefix / suffix / equality, all with non-empty needles, so that an empty string never matches) and checks values with a bounds-safe substring searcher. A single filter object is shared by all readers of a column within one query and disables itself adaptively when the observed fraction of matching values makes the check unprofitable (more than half of the values match).extractStringValueFilters(src/Interpreters/) walks the top-levelANDchain of thePREWHEREactions and extracts filters fromlike(with fixed substrings parsed out of the pattern, honoring escaping),startsWith,endsWith,equalswith a non-empty string, bareposition, and comparisons ofpositionwith a constant that reject the zero result (e.g.position(s, 'x') > 0,position(s, 'x') = 5, but notposition(s, 'x') = 0).MergeTree: the filters are attached toMergeTreeReaderSettingsinReadFromMergeTree::initializePipeline, only whenprewhere_info->need_filteris set (rows are guaranteed to be physically filtered). The readers apply a filter to a column only when it is a fullString/Nullable(String)column with the plain serialization (not sparse), is not requested together with another column reading from the same storage column (e.g. the.sizesubcolumn, which could share deserialized data through caches), and is not overwritten by an on-fly mutation (PREWHEREis then evaluated on mutated values). Renamed columns are handled by keying the filter by the name in the part. Both string serialization versions are supported (single_streamandwith_size_stream), for wide and compact parts.Parquet(native reader): the filters are attached to the prewhere-step string leaves and applied in the plain and delta-length page decoders per value; for dictionary-encoded pages the filter is checked only once per dictionary entry, and the per-row gather materializes empty strings for non-matching entries.StringValueFilterValuesChecked,StringValueFilterValuesReplaced,StringValueFilterBytesSkipped.clickhouse-test.Testing
Nullable(String), escapedLIKEpatterns, conditions that must not be pushed down (position(s, 'x') = 0,NOT,OR, patterns matching an empty string),ANDchains, multiple columns, and both Parquet page encodings; every query is checked with the setting enabled and disabled, plus profile events assert that the optimization actually fires.prewherewere run locally with the setting forced on: the results are identical to the run with the setting disabled.Workflow [PR]
Sync PR [sync-upstream/pr/115848]
ClickBench results
Measured on the
hitstable (100M rows, 96-core aarch64, hot cache, interleaved A/B runs, query condition cache disabled to measure the scan itself). The affected queries are those with substring conditions (URL LIKE '%google%',Title LIKE '%Google%'), written with explicitPREWHERE; the remaining 39 queries do not extract any filter and are unaffected.MergeTree (min of 5 runs):
count() PREWHERE URL LIKE '%google%'Title LIKE '%Google%')SELECT *)The filter replaces ~99.98M of 100M values and skips copying 8.4-8.8 GiB per query. The initial per-value implementation was 10-15% slower than the baseline on MergeTree (a substring search per short value loses to the baseline's bulk copy plus one bulk scan in
like); the bulk-scan implementation (one scan per buffer of concatenated values) turned it into the win above.Parquet (
file('hits.parquet'), same queries, quieter round): Q20 1.57×, Q21 1.18×, Q22 1.12×, Q23 ~1× (dominated by reading the other 100 columns).When the setting is enabled, the
WHEREtoPREWHEREoptimization also moves suitable substring search conditions even when they use all queried columns (normally that is pointless, but with the string filter the scan itself becomes cheaper). This makes the officialWHERE-form of Q20 usePREWHEREand the string filter as written: 1.25× faster (min of 5 runs, 0.119 s → 0.095 s) and −59% memory. Plain equality with a string constant is deliberately excluded from this relaxation: it is too common, and it would change the plans of too many queries where the primary key index does the job anyway. In Q23 the top-k dynamic filter occupiesPREWHEREand theLIKEstays inWHERE, which is unaffected.Version info
26.10.1.1778-master(included in26.10and later)