Skip to content

Apply the Parquet filter while decoding RLE and dictionary-encoded pages - #123618

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:parquet-prewhere-dictionary-filter-in-decoder
Oct 3, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:parquet-prewhere-dictionary-filter-in-decoder

Conversation

@groeneai

@groeneai groeneai commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix Unexpected number of rows in column subchunk (LOGICAL_ERROR) when filtering a Parquet file whose Bool column is RLE-encoded (pyarrow's default for data page v2). The filter is now applied while decoding RLE-encoded and dictionary-encoded pages, which also makes PREWHERE over dictionary-encoded columns of Parquet files without a page index faster (ClickBench q31 1.92 s to 1.21 s). Closes #123483.

Description

On 26.8.10.6, SELECT count(), countIf(flag) FROM file('f.parquet') WHERE k % 7 = 3 over a 300,000-row file that pyarrow writes with data_page_version='2.0' fails with Unexpected number of rows in column subchunk (LOGICAL_ERROR). Same on 26.3.33.24 and 26.9.1.1629.

Root cause. BitPackedRLEDecoder::decode was the only PageDecoder::decode that ignored its filter argument. It decodes RLE-encoded BOOLEAN pages, so it appended every row and the row-count check threw. It also decodes dictionary indexes, so dictionary-encoded pages were excluded from the filter-in-decoder path and were read with one skip-and-decode per run of passing rows (#123483).

Change. decode now honours the filter: an RLE run fills the passing count, and a bit-packed run extracts only the passing positions using 64-bit masks. Reader.cpp drops the dictionary exclusion. A filtered dictionary read decodes the passing indexes and gathers them once. Unfiltered and all-pass reads keep the fused path of #115819.

Performance (hits.parquet via File(Parquet), 4 threads, Release, paired runs, 95% CI):

query before after ratio
q31 1922 ms 1210 ms 0.64
q32 2226 ms 1622 ms 0.73
q15 1088 ms 904 ms 0.83
PREWHERE WatchID % 1000 = 0 524 ms 504 ms 1.00 (0.93-1.08)
PREWHERE WatchID % 1000 != 0 (99.9% pass) 787 ms 770 ms 1.00 (0.97-1.04)
q3, q24-q27 0.96-1.01

Tests. 05317 covers dictionary pages (filter shapes, lazy materialization, Point dictionaries). 05318 uses two tiny pyarrow fixtures, an index bit width of 0 (as parquet-mr writes) and an RLE Bool column; it fails on master. A performance test covers scattered, dense, sparse, almost-all-passing and all-passing filters. Parquet suite, pyarrow differential and ASan runs are clean.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1426-master (included in 26.10 and later)

groeneai and others added 3 commits October 2, 2026 18:50
`PageDecoder::decode(num_values, col, filter, filter_offset)` must append only the
values whose filter byte is nonzero. `BitPackedRLEDecoder::decode` ignored the
filter (`(void)filter`), the only one of the eight overriders that did. It
decodes two streams:

- RLE-encoded BOOLEAN data pages (pyarrow's default for data page v2). With a
  PREWHERE / WHERE filter on another column, the filter-in-decoder path appended
  every value of the range and the subchunk row-count check threw
  `Unexpected number of rows in column subchunk` (LOGICAL_ERROR), e.g. on
  26.3.33.24 and 26.8.10.6 with default settings.
- Dictionary indexes. Dictionary-encoded pages were excluded from the
  filter-in-decoder path as a workaround (bb5c216, then
  `chassert(!filter)` in 3101453), so a scattered PREWHERE mask read them
  through one `skipToRowOrNextPage` + `readRowsInPage` per run of passing rows.

`decode` now honours the filter through a filtered flavour of `skipOrDecode`
that touches only passing values: an RLE run fills `countBytesInFilter` copies
of its value; a bit-packed run builds a 64-bit mask per 64 values with
`bytes64MaskToBits64Mask` and extracts only the set positions straight from
the packed bits (bounds-checking each one), then advances `bit_idx` by the
whole run like `skip`; bit width 0 writes the passing count of zeros.

`Reader.cpp` drops the dictionary exclusion. A filtered read of a dictionary
page decodes the passing indexes and gathers them with one `Dictionary::index`
(every dictionary mode, including GeoParquet `Mode::Column`). An unfiltered read,
and a subgroup whose rows all pass (`applyPrewhere` keeps an all-ones filter),
keeps the fused `decodeAndIndex` of ClickHouse#115819.

Indexes of non-passing rows are no longer validated, exactly as on the
row-range path's `skip`.

Measured on hits.parquet (14.8 GB, 226 row groups, no page index) through
`File(Parquet)` with `clickhouse local --max_threads 4`, Release builds, paired
rotated runs, geometric mean of per-run ratios with a bootstrap 95% CI, 16 runs
(8 for Q24-Q27):
ClickBench q31 1922 -> 1210 ms (0.636 [0.620, 0.652]), q32 2226 -> 1622 ms
(0.727 [0.700, 0.754]), q15 0.830 [0.808, 0.854]; q3, q24-q27 unchanged
(0.96-1.01, every CI containing 1.0).
`SELECT SUM(AdvEngineID), COUNT(*), AVG(ResolutionWidth), SUM(SearchEngineID)
FROM hits PREWHERE <f>`: `WatchID % 10 != 0` 0.519, `WatchID % 3 = 0` 0.320,
`% 30 = 0` 0.783, `% 100 = 0` 0.940, `% 300 = 0` 0.982, `% 1000 = 0` 0.996,
`% 3000 = 0` 1.022 [0.987, 1.066], `WatchID != 0` 0.936.
A pyarrow file with 20000-row pages (20M rows): `k % 10 = 3` 0.624,
`k % 1000 = 0` 0.903, `k % 100000 = 0` 0.959 [0.904, 1.014].
The issue's patch (decode every index of the range, compact, gather once)
measured 1.155 [1.076, 1.242] on `WatchID % 1000 = 0` and 1.286 on
`% 3000 = 0`; this change is 0.863 / 0.795 of it there.

Tests:
- 05317 generates a ClickHouse-written file without a page index (dense,
  scattered, all-pass, sparse, run-shaped, narrow and lazily materialized
  filters; FixedSize, StringPlain and `Point` dictionaries) and compares with
  the same computation over `numbers()`.
- 05318 uses two tiny fixtures: `05318_parquet_dictionary_bit_width_0.parquet`
  (pyarrow 24, uncompressed, no page index, the one data page of `c` patched
  to index bit width 0, as parquet-mr writes it), and
  `05318_parquet_rle_boolean.parquet` (pyarrow 24, `data_page_version='2.0'`,
  `write_page_index=False`, `use_dictionary=False`, `k` DELTA_BINARY_PACKED,
  3000 rows, `flag` in long runs for the first half and `k % 3 = 0` after).
  On master the Bool queries abort with the LOGICAL_ERROR above.

Closes ClickHouse#123483.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ages

`parquet_prewhere_dictionary_encoded.xml` writes a 50M-row Parquet file
without a page index, whose `a` (300 values), `r` (7 values in runs of 500)
and `s` (1000 strings) columns are dictionary-encoded, and reads them under a
`PREWHERE` on the plain `k` column with a scattered (`k % 3 = 0`), dense
(`k % 10 != 0`), sparse (`k % 1000 = 0`) and almost-all-passing
(`k % 1000 != 0`) filter. These are the reads that now apply the filter while
decoding dictionary indexes; no existing performance test reads a
dictionary-encoded Parquet file without a page index under `PREWHERE`.

Also update a comment in 04041: it said dictionary encoding is disabled
because the filter-in-decoder path requires `!is_dictionary_encoded`, and the
previous commit removed that condition.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…test

The new query reads every subgroup with an all-ones filter, the case where
the reader keeps the fused dictionary gather instead of decoding with the
filter. Removing that shortcut measured 1.036x (95% CI 1.001-1.068) on this
query at max_threads 8 locally, within this box's A/A noise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 2, 2026
@groeneai

groeneai commented Oct 2, 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; 4 findings over 3 rounds) plus my own review (1 finding).

# Sev Finding Verdict Evidence / action
1 ⚠️ Near-all-pass PREWHERE filters on dictionary columns leave the fused gather and were not measured AGREE measured 5 shapes at 99%-99.999% pass: after/before 0.86-1.03, every 95% CI lower bound <= 1.00 (73993f62645a0)
2 ⚠️ No test notices if dictionary pages stop using the filter-in-decoder path AGREE added tests/performance/parquet_prewhere_dictionary_encoded.xml (73993f62645a0) instead of a test hook
3 ⚠️ The performance test cannot fail if the routing is reverted; add a ProfileEvent DISAGREE (hook) / AGREE (all-pass shortcut) Performance Comparison measures a PR against master head, so a later revert shows up as a regression: k % 3 = 0 after/before is 0.65-0.73 at max_threads 8 and 12. An all-pass query now reaches the shortcut on every dictionary page read (55eb791a033bf)
4 ⚠️ Deleting the all-pass shortcut would not fail CI DISAGREE measured with the two lines removed: 1.00-1.06 on the all-pass query at max_threads 8 and 12, below Performance Comparison's 15% floor. The shortcut only keeps master's fused read for all-pass subgroups; the all-pass query shows no regression against master
5 💡 04041 comment cites the removed dictionary condition AGREE comment updated (73993f62645a0)

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

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count(), countIf(flag) FROM file('f.parquet') WHERE k % 7 = 3 on a 300,000-row pyarrow data_page_version='2.0' file throws Unexpected number of rows in column subchunk on every run on 26.3.33.24, 26.8.10.6, 26.9.1.1629 and master.
b Root cause explained? BitPackedRLEDecoder::decode was the only PageDecoder::decode ignoring filter. RLE Bool pages appended every row; dictionary pages had been excluded from the filter-in-decoder path, which made scattered PREWHERE slow.
c Fix matches root cause? Yes: the decoder honours the filter, and the exclusion that worked around it is removed. No setting, no threshold.
d Test intent preserved / new tests added? New 05317 (dictionary pages, 6 filter shapes + lazy materialization) and 05318 (bit width 0 + RLE Bool); 8 mutation arms each redden one of them, the control does not.
e Both directions demonstrated? 05318 fails on master and the release images, passes with the fix.
f Fix is general across code paths? All 8 decode overriders checked; both streams of this decoder (Bool data, dictionary indexes) and all three dictionary modes go through the same change; unfiltered and all-pass reads keep the fused path.
g Fix generalizes across inputs (params/datatypes/wrappers)? Fixed-size, string and Point dictionaries; bit widths 0 to ~15; RLE and bit-packed runs incl. tails and runs split across blocks; dict-to-PLAIN fallback pages; block sizes 100 to 65409; nullable columns stay on the old path.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or stored-state change; results equal the prewhere-off path in a pyarrow differential (24/24).
i Invariants and contracts preserved? A filtered read appends exactly the passing rows in order and leaves the decoder after all num_values values (bit_idx advances like skip); passing indexes are bounds-checked; ASan clean.

Session id: cron:clickhouse-impl-slot-6:20261002-164503

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [461dcee]

Summary: ✅


AI Review

Summary

This PR fixes the Parquet filter-in-decoder contract for BitPackedRLEDecoder, so filtered reads now handle RLE-encoded Bool pages correctly and dictionary-encoded pages can stay on the sequential filter-in-decoder path instead of falling back to row-range iteration. I reviewed the current diff, the added stateless and performance coverage, and the prior PR discussion, and I did not find any unresolved correctness, safety, performance, or PR-metadata issues that warrant changes.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 461dcee.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 65/68 (95.59%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-parquet-reader-v3 Issues related to the native Parquet reader. labels Oct 2, 2026
00900_long_parquet_load_2 loads every file in data_parquet/ and compares
the output with its reference, so the two hand-crafted RLE fixtures added
for 05318 made it fail deterministically. Exclude them like the other
per-test fixtures; 05318 already covers both files.

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

clickhouse-gh Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 461dcee9e with master 3e0ef89a3 (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

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

Job report

@alexey-milovidov alexey-milovidov left a comment

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.

Looks good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 3, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 3, 2026
Merged via the queue into ClickHouse:master with commit 3c43460 Oct 3, 2026
149 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 3, 2026
leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Oct 27, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 8, 2026
…ecoding dictionary indexes

Since ClickHouse#123618 `BitPackedRLEDecoder::decode` applies the row filter while
decoding dictionary indexes. It scanned the byte filter again in every run:
`countBytesInFilter` over each RLE run's slice, and a 64-bit mask built byte
by byte for every bit-packed run shorter than 64 values, plus one more full
`countBytesInFilter` pass to size the output. Runs in pyarrow-written files
are short (~91 values per RLE run, ~39 per bit-packed run on hits.parquet),
so the per-run call and tail overhead dominates when a scattered part of the
rows passes.

The filter range of each `decode` call is now converted to a bitmask once
(`bytes64MaskToBits64Mask` per 64 bytes, which also yields the pass count),
RLE runs count the passing rows with popcount over at most 64-bit windows,
and bit-packed runs read their 64-bit mask window directly. A trailing zero
word lets a window that is not word-aligned read the next word. Nonzero
filter bytes still mean "pass", so filter values above 1 keep working.
Unfiltered decoding and every other decoder are unchanged.

The test covers dictionary-encoded UInt32/UInt16/String columns with RLE and
bit-packed runs shorter and longer than 64 values, filters of several
densities including a non-boolean UInt8 filter, and two block sizes.

Analysis and patch by snelheidai in ClickHouse#128268.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-parquet-reader-v3 Issues related to the native Parquet reader. groeneai-origin-issue PR origin: picked up an external GitHub issue pr-bugfix Pull request with bugfix, not backported by default 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.

Parquet PREWHERE: decode dictionary-encoded pages with the filter in the decoder (ClickBench q31 -34%, q32 -24%)

3 participants