Skip to content

Unpack bit-packed Parquet dictionary indexes and levels with a loop specialized for each bit width - #128262

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:parquet-unpack-bit-packed-by-width
Nov 2, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:parquet-unpack-bit-packed-by-width

Conversation

@groeneai

@groeneai groeneai commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #128232
Related: #124859

Changelog category (leave one):

  • Performance Improvement

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

Faster reading of dictionary-encoded, Nullable and nested columns from Parquet: bit-packed dictionary indexes and definition/repetition levels are now unpacked by a loop specialized for each bit width. ClickBench queries over hits.parquet such as SELECT AVG(UserID) FROM hits are 8-15% faster.

Description

The native Parquet reader unpacked bit-packed runs of dictionary indexes and definition/repetition levels one value at a time, with the bit width known only at run time and the bit position stored to memory after every value (the load through const char * may alias the decoder). Now unpackBitPacked<W> is instantiated for each width (1-32 for indexes, 1-8 for levels) and chosen once per page: it unpacks each byte-aligned block of 8 values with constant offsets and shifts, keeps the position in a register, and the bounds check is a separate loop over the batch. It reads exactly the bytes the per-value loop read, so the padding requirement is unchanged. The filtered decode path is unchanged.

Measured locally (x86 Xeon 6975P-C, Release, one clickhouse local process per run, 4 threads, paired runs, geometric mean of new/old with 95% CI):

  • SUM(AdvEngineID), COUNT(*), AVG(ResolutionWidth): 0.850 (0.817-0.885); AVG(UserID): 0.924 (0.918-0.930); SUM(ResolutionWidth + k): 0.854 (0.831-0.877); with 1 thread 0.79 / 0.92 / 0.79.
  • COUNT(*) and URL LIKE '%google%': unchanged (0.975 and 0.999, intervals contain 1).
  • 100M rows of Nullable columns: dictionary-encoded 0.772, plain (levels only) 0.953.

The analysis and patch are by @ snelheidai in #128232, measured at 0.905-0.910 on Graviton3 for the same three queries.

Correctness: hashes of all 105 hits.parquet columns are identical. The new test reads index widths 1-18 and level widths 1 and 2, with blocks that start inside a run and under PREWHERE, and checks that an out-of-range level is rejected; widths 19-32 were compared exhaustively against the old loop locally.

Arrow's unpack, used by the ALP decoder, is not reused because #126477 makes the native reader independent of Arrow. #124859 changes the same function; whichever is merged second applies this unpacking to the other's loop.


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

Version info

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

groeneai and others added 2 commits October 30, 2026 16:10
…per bit width

`BitPackedRLEDecoder` unpacked bit-packed runs one value at a time with a
run-time bit width, and kept the bit cursor in a member. The load goes
through `const char *`, which may alias `*this`, so the compiler stored the
cursor to memory for every value, and no shift or byte offset was constant.

Add `unpackBitPacked<W, T>`, instantiated for each width (1..32 for
indexes, 1..8 for levels) and chosen once per page from a table. It
unpacks each byte-aligned block of 8 values with constant offsets and
shifts and keeps the cursor in a register. It reads 8 bytes at the first
byte of each value, exactly the bytes the per-value loop read, so the
padding requirement is unchanged. The bounds check becomes a separate
max-reduction over the unpacked batch. The filtered decode path is
unchanged.

Used by `decodeAndIndex` (fused decode and gather of dictionary indexes)
and by the unfiltered `skipOrDecode` (indexes, definition/repetition
levels, RLE booleans).

Analysis and patch by @ snelheidai in ClickHouse#128232.

New test 05482 reads dictionary indexes of every width from 1 to 18 bits,
a String dictionary, and definition/repetition levels of widths 1 and 2,
with default blocks, 777-row blocks (runs split at bit positions that are
not byte aligned) and PREWHERE, against the source data, and checks that a
definition level out of range in a bit-packed run is rejected. 05320 also
reads its corrupt file without PREWHERE, which covers the bounds check of
the fused decode-and-gather path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Make the unpackBitPacked read-footprint comment a standalone invariant.

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; 2 findings; 1 full pass).

# Sev Finding Verdict Evidence / action
1 ⚠️ The SQL tests also pass with the old per-value loop, so they do not prove the specialized path or the speedup DISAGREE The change preserves behaviour, so no SQL result can differ; the tests guard correctness. Every mutation of the new code (block of 7 values instead of 8, head loop skipped, tail zeroed, index width 18 redirected to 17, level width 2 redirected to 1, either bounds check removed) fails them, which also shows that both the index and the level path go through the width table. The speedup is the paired A/B in the description; the perf CI runs clickbench_parquet_short.xml (dictionary-encoded Q3/Q4).
2 💡 decodeAndIndex looks up the specialized function on every call, not once per page noted, not changed One array load per call; for UInt32 it is the same function as the cached member.

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

Session id: cron:clickhouse-review-slot-8:20261030-162900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @grantholly-clickhouse, could you review this and add the can be tested label so CI runs? It unpacks bit-packed dictionary indexes and definition/repetition levels in BitPackedRLEDecoder with a loop specialized per bit width (chosen once per page, bit position kept in a local, bounds check as a separate pass over the batch), reading the same bytes as before; ClickBench Parquet Q3/Q4/Q30 were 8-15% faster in my local A/B.

@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9d96f32]

Summary: ✅


AI Review

Summary

The PR specializes bit-packed Parquet dictionary-index and repetition/definition-level decoding by bit width while preserving bounds checks and the existing read footprint. Reviewed commit 9d96f32fb0f2; no actionable findings. The reported paired benchmarks support the performance claim, and the regression tests cover split runs, filtering, nested values, and malformed indexes/levels. An independent check of the extracted helper passed 54,720 cases (7,247,040 values) under ASan and UBSan across all supported widths.

Final Verdict

Status: ✅ Approve

@clickhouse-gh

clickhouse-gh Bot commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9d96f32fb with master 4d53227b6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of dcccc2b59; 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.

Object file sizes

4 object files changed (+28.19 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/Parquet/Decoding.cpp.o 391.89 KiB 420.07 KiB +28.19 KiB (+7.19%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@snelheidai

Copy link
Copy Markdown

For the "whichever is merged second applies this unpacking to the other's loop" step, here is that change for #124859's decodeAndIndexFixedSize, measured with both PRs applied. That loop handles the 1/2/3/4/8/16-byte dictionary columns (AdvEngineID, ResolutionWidth, UserID, ...), so until it is changed they keep the per-value unpacking. The patch unpacks each bit-packed run with unpack in batches of up to 256 indexes and checks the batch maximum before the gather, so the clamp is no longer needed:

--- a/src/Processors/Formats/Impl/Parquet/Decoding.cpp
+++ b/src/Processors/Formats/Impl/Parquet/Decoding.cpp
@@ -293,7 +293,6 @@ struct BitPackedRLEDecoder : public PageDecoder
         chassert(to_span.size() == value_size * num_values);
         char * to = to_span.data();
         const char * dict = dictionary.data.data();
-        const T value_mask = T((1ul << bit_width) - 1);
         const size_t width = bit_width;
         const size_t max_index = limit - 1;
 
@@ -315,22 +314,25 @@ struct BitPackedRLEDecoder : public PageDecoder
             }
             else
             {
-                /// A corrupt index is clamped so that the gather stays inside the dictionary; the run is rejected below.
-                const char * run_data = data;
-                size_t pos = bit_idx;
-                size_t max_seen = 0;
-                for (size_t i = 0; i < n; ++i)
+                /// Unpack a batch of indexes with the loop specialized for the bit width, bounds-check the batch,
+                /// then gather it.
+                for (size_t done = 0; done < n;)
                 {
-                    size_t x = 0;
-                    memcpy(&x, run_data + (pos >> 3), 8);
-                    x = (x >> (pos & 7)) & value_mask;
-                    max_seen = std::max(max_seen, x);
-                    memcpy(to + i * value_size, dict + std::min(x, max_index) * value_size, value_size);
-                    pos += width;
+                    constexpr size_t batch = 256;
+                    T buf[batch];
+                    const size_t m = std::min(n - done, batch);
+                    unpack(data, bit_idx, m, buf);
+                    bit_idx += m * width;
+                    T max_seen = 0;
+                    for (size_t i = 0; i < m; ++i)
+                        max_seen = std::max(max_seen, buf[i]);
+                    if (max_seen > max_index)
+                        throw Exception(ErrorCodes::INCORRECT_DATA, "Dict index or rep/def level out of bounds (bp)");
+                    char * dst = to + done * value_size;
+                    for (size_t i = 0; i < m; ++i)
+                        memcpy(dst + i * value_size, dict + size_t(buf[i]) * value_size, value_size);
+                    done += m;
                 }
-                bit_idx = pos;
-                if (max_seen >= limit)
-                    throw Exception(ErrorCodes::INCORRECT_DATA, "Dict index or rep/def level out of bounds (bp)");
 
                 if (!run_length)
                     data += run_bytes;

Time per query, geometric mean of new/old with 95% CI (ClickBench hits as 100 Parquet files, x86 Xeon 8375C with 4 vCPUs, one clickhouse local process per run, 8 interleaved pairs; 12 for Q4 and Q12):

Query median ms, old → new new/old
Q3 SUM(AdvEngineID), COUNT(*), AVG(ResolutionWidth) 122.5 → 116.5 0.950 [0.932, 0.968]
Q4 AVG(UserID) 142.5 → 135.0 0.955 [0.945, 0.966]
Q30 SUM(ResolutionWidth + k) 120.0 → 113.0 0.939 [0.911, 0.967]
Q12 GROUP BY MobilePhone, MobilePhoneModel 309 → 311 1.008 [1.003, 1.013]

Q1, Q2, Q8, Q10 and Q21 were unchanged (intervals contain 1). Q11 was 1.015 [1.006, 1.025] over 8 pairs and 0.996 [0.981, 1.011] in a 12-pair rerun. Both builds were master e4afc4f with both PRs and other open Parquet reader and aggregation PRs applied, so absolute times differ from master; the builds differ only by this diff. Query results were identical, and 05339 (including its corrupt-index cases), 05482 and 05320 pass.

@alexey-milovidov alexey-milovidov self-assigned this Nov 2, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, check the comment above.

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, I checked it. The diff changes decodeAndIndexFixedSize, which exists only in #124859, and calls the unpack added here, so it cannot go into this PR. The two PRs also conflict in Decoding.cpp, so #124859 has to be updated anyway once this one is merged. I'll do that then: resolve the conflict, apply this diff (the batch maximum is checked before the gather, so the clamp can go and the corrupt-index cases of 05339 still cover it), and post an x86 re-measurement there, including Q12, which is 0.8% slower above.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 2, 2026
Merged via the queue into ClickHouse:master with commit b8bb109 Nov 2, 2026
530 of 532 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 2, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 2, 2026
…dSize

Use the bit-width-specialized `unpack` from ClickHouse#128262 for the bit-packed runs of
the fixed-size dictionary path: unpack up to 256 indexes into a stack buffer,
check the batch maximum against the dictionary size, then gather. The check now
precedes the gather, so the per-value clamp is no longer needed.

Patch proposed by snelheidai in
ClickHouse#128262 (comment).

The `Decoding.h` comment is restored to the master wording, which describes
both paths again.

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. pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

4 participants