Skip to content

Decode Parquet columns densely after a scattered PREWHERE when the file has a page index or NULLs - #128139

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:parquet-prewhere-dense-decode-page-index
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:parquet-prewhere-dense-decode-page-index

Conversation

@groeneai

@groeneai groeneai commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #123483
Related: #123618

Changelog category (leave one):

  • Performance Improvement

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

Reading Parquet files with a PREWHERE that keeps a scattered part of the rows is up to 3x faster when the column chunks have a page index (written by default by ClickHouse, Spark and parquet-mr) or can contain NULLs.

Description

Patch by @ snelheidai in #123483, cost rule re-tuned.

Root cause. #123618 applies the mask in the page decoders only to chunks without an offset index or null map. Others take the run loop of Reader::decodePrimitiveColumn: a seek and decode per run of passing rows, thousands per row subgroup when 10-90% of scattered rows pass.

Change. When runs of passing rows plus gaps average at most 16 rows (runs * 16 >= last - first), rows from the first to the last passing row are decoded, except pages without passing rows (an unfetched page is never read), then filtered once with IColumn::filter; a null map maps the mask to non-null values. Arrays, strings, values wider than 16 bytes, types whose conversion can reject a value (DATE, INT96, wide decimals, geometries) and sparser or denser masks keep the current path, so a row filtered out is never converted.

Performance (Xeon 6975P-C, Release, 4 threads, geomean of 12 paired ratios, 95% CI):

query before after ratio
50M rows, 4 numeric columns (2 nullable), 50% pass 4026 ms 2559 ms 0.63 (0.59-0.66)
same, 10%/90% pass 1694/1932 ms 1451/1870 ms 0.83/0.95
3 dictionary-encoded columns, 50% pass 1946 ms 628 ms 0.32 (0.30-0.35)
TPC-DS SF1 q37/q82, instructions 3.07/3.13 G 1.86/1.93 G 0.61/0.62

At 5% or 99% pass: current path, +0.3-0.5% instructions. Results are identical; peak memory within 6 MiB at default settings.

Tests. 05457_parquet_prewhere_page_index_nullable compares PREWHERE reads of files with and without a page index (NULLs, all-NULL pages, small pages) with the source table, incl. a value the read type cannot hold in filtered-out rows only; seven mutations of the new code fail it. parquet_prewhere_plain_columns.xml gains four page-index queries.


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

groeneai and others added 5 commits October 29, 2026 06:02
When a column chunk has an offset index or needs a null map, the filter
is not applied inside the page decoders, and `decodePrimitiveColumn`
seeks and decodes once per run of passing rows. With a PREWHERE that
keeps 10-90% of scattered rows that is thousands of tiny decodes per
row subgroup.

Count the runs with one pass over the mask. When seeking to each run
costs more than decoding the failing rows between them, decode the pages
that hold passing rows as whole ranges and remove the failing rows with
`IColumn::filter`; for nullable columns the mask is mapped to the
non-null values. Pages without passing rows are still skipped, so a
range never covers a page whose prefetch was reset or which the offset
index does not list. Arrays, strings, values wider than 16 bytes and
sparse masks keep the current path.

The filtered values column is reserved for exactly the passing non-null
values, and the page scan starts at the first page that can overlap the
subgroup.

The patch is from @ snelheidai in ClickHouse#123483.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The dense path decodes and filters every row from the first to the last
passing one, so compare the cost of seeking to each run with that, not
only with decoding the failing rows. With 99% of rows passing, the old
rule chose the dense path and was about 9% slower than reading run by run.
Masks whose runs and gaps together average more than 16 rows keep the
current path.

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

The dense path converts every decoded row, also the rows an earlier
PREWHERE step removed, and the run loop never converts those. A value
that the read type cannot hold, such as a DATE before 1970 read as Date
or an INT96 timestamp after 2262, made a query fail although its row is
filtered out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A geometry column read as Point decodes to a 16-byte tuple, so the
dense path took it and converted the rows an earlier PREWHERE step
removed too. Converting a geometry of another kind throws, so a mixed
column read as Point failed although only points pass the filter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the design notes on the dense Parquet decode path to one line each.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)
Finding Verdict
❌ The dense path converted values of rows an earlier PREWHERE step removed, so a DATE before 1970 read as Date or an INT96 past 2262 in such a row failed the query Agree, fixed: types whose conversion can reject a value keep the run loop; covered in 05457
❌ The same for a mixed geometry column read as Point (a 16-byte tuple, so the dense path took it) Agree, fixed: geometry conversion counts as one that can reject a value; covered in 05457
⚠️ The dense transient is up to 16x the reader's rows_pass memory charge Disagree: one column of at most max_block_size rows at a time, measured peak within a few MiB of master at default settings, incl. a 1-in-16 mask
⚠️ No assertion that the dense branch is taken Disagree: results are identical by design; the extended parquet_prewhere_plain_columns.xml measures the path, and mutations of the dense path fail 05457

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Release A/B on a 50M-row ClickHouse-written file (page index, 2 nullable columns), PREWHERE f < 50, max_threads = 4: user-space instructions 46.0 G before, 26.3 G after; time 4026 ms vs 2559 ms (0.63, 95% CI 0.59-0.66, 12 pairs).
b Root cause explained? With an offset index or a null map the mask is not applied inside the page decoders, so Reader::decodePrimitiveColumn seeks and decodes once per run of passing rows; a scattered 10-90% mask means thousands of runs per row subgroup.
c Fix matches root cause? Yes. When runs plus gaps average at most 16 rows the rows between the first and the last passing row are decoded once and filtered with IColumn::filter; every other mask keeps the existing loop. No setting, no decoder change.
d Test intent preserved / new tests added? New 05457_parquet_prewhere_page_index_nullable (also passes on master: results are unchanged); each of seven mutations of the new code fails it. Four queries added to the existing parquet_prewhere_plain_columns.xml.
e Both directions demonstrated? Performance: slower before / faster after on every measured scattered mask, instruction counts included. Correctness: the intact new path and master pass 05457, the mutated new path fails it (wrong size LOGICAL_ERROR, a read of a skipped page, Code: 9, Code: 321 when a filtered-out pre-1970 DATE is converted, Code: 36 when a filtered-out line string is read as Point).
f Fix is general across code paths? Covers offset-index chunks, null maps, group_nullable leaves, dictionary indexes read as replicated and the first row subgroup of a chunk. Arrays, strings, values wider than 16 bytes and converters that can reject a value (DATE, INT96, wide decimals, geometries) keep the existing loop.
g Fix generalizes across inputs (params/datatypes/wrappers)? Int8-Int64, Float32, Decimal64/128, FixedString(3), UUID, Nullable with all-NULL pages; PLAIN, dictionary, DELTA_BINARY_PACKED, BYTE_STREAM_SPLIT; page index on and off; 4 KiB pages; filter bytes above 1; masks from 0.1% to 100% incl. period-16 edges. Differential vs master: identical on debug and ASan.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or protocol change, identical results.
i Invariants and contracts preserved? Each row subgroup yields exactly the passing rows in order, null map and values aligned (two LOGICAL_ERROR checks plus the existing final size check); a decoded range never covers a page without passing rows, so an unfetched page is never read; the null map is filtered before the NULL-into-non-Nullable check; a filtered-out row is never converted.

Session id: cron:clickhouse-impl-slot-5:20261029-103200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @grantholly-clickhouse, could you review this and add the can be tested label so CI runs? With an offset index or a null map the Parquet reader v3 still decodes a scattered PREWHERE mask run by run; this decodes the rows from the first to the last passing row once (skipping pages without passing rows) and applies IColumn::filter, 0.63x time on a 50%-pass scan and 0.61x instructions on TPC-DS q37.

@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3d7080d]

Summary: ✅


AI Review

⚠️ Review sessions stopped as a cybersecurity risk

The model provider stopped these review sessions as a possible cybersecurity risk:

  • attempt 1: gpt-6.1-sol

This summary comes from a session with gpt-5.4. A session is typically stopped when it reaches a memory-safety finding, and the finding is lost with it, so this review can miss a real defect. Please review the change in detail, and run the review internally with a model that has cyber access.

Summary

This PR adds a dense post-PREWHERE decode path for fixed-size Parquet primitives when the surviving rows are scattered, including the offset-index-aware page splitting and the nullable-column post-filtering needed to keep the existing correctness guarantees. I reviewed the new run counting, page-range construction, null-map/value filtering, and converter guardrails against the surrounding page and row-subgroup invariants, and I did not find any blocker or major issue in the current diff.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-parquet-reader-v3 Issues related to the native Parquet reader. labels Oct 29, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3d7080dc1 with master 4553bee2f (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e3d8ff7

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
Fast test (arm_darwin) / 05397_clickhouse_local_locked_path_untouched fails on macOS for every PR, not from this PR (its diff changes only the Parquet reader and its own tests): the expected Another server instance in same directory is already running line is missing. 168 failures in 160 PRs since 2026-10-28 19:35 UTC, all in this job, 0 on master #128088 (mine, open)
Stress test (arm_asan_ubsan) / Received signal 6 (internal) (STID: 1202-2b88) crash, not from this PR: the libc++ hardening check vector[] index out of bounds aborts in DB::highlight (ClientBaseHelpers.cpp:597, query highlighting in the embedded client). The fix merged at 13:17 UTC; the tree this job built (4bda4792cf9f) does not contain it #127906 (mine, merged)
Integration tests (amd_tsan, targeted) / test_storage_kafka/test_batch_slow_6.py::test_kafka_rebalance (2 parametrizations) not from this PR: a ThreadSanitizer data race inside the vendored librdkafka (rd_kafka_toppar_set_fetch_state vs rd_kafka_toppar_fetch_backoff, both writing the fetch backoff timestamp) aborted the Kafka test server, so the teardown DROP DATABASE got ATTEMPT_TO_READ_AFTER_EOF ClickHouse/librdkafka#24 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #128088, #127906, ClickHouse/librdkafka#24 (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head; the earlier Config Workflow failures were the attempts before the can be tested label.

Session id: cron:our-pr-ci-monitor:20261029-160007

groeneai and others added 2 commits November 16, 2026 16:56
…nse-decode-page-index

# Conflicts:
#	src/Processors/Formats/Impl/Parquet/Decoding.h
Master now enforces clang-tidy `modernize-use-nodiscard` (ClickHouse#126158), so the
`canRejectValues` overrides get `[[nodiscard]]` like the neighbouring
`isTrivial` overrides, and bans plain `std::vector` in `src/Processors/Formats`
(ClickHouse#126530), so the decode ranges use `VectorWithMemoryTracking`.

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

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-parquet-reader-v3 Issues related to the native Parquet reader. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants