Skip to content

Decode dictionary-encoded fixed-size Parquet columns with one column resize per call - #124859

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:parquet-dictionary-fixed-size-decode
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:parquet-dictionary-fixed-size-decode

Conversation

@groeneai

@groeneai groeneai commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124666
Related: #115819
Related: #128262

Changelog category (leave one):

  • Performance Improvement

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

Reading dictionary-encoded numeric Parquet columns is faster: the output column is now sized once per decoded range instead of once per RLE or bit-packed run. ClickBench queries over hits.parquet that read numeric columns, such as SELECT SUM(AdvEngineID), COUNT(*), AVG(ResolutionWidth) FROM hits, are 5-8% faster.

Description

BitPackedRLEDecoder::decodeAndIndex (#115819) appends every RLE or bit-packed run through Dictionary::appendRepeated / appendIndexes, and each call switches on the dictionary mode, grows the column through the virtual IColumn::insertRawUninitialized and switches on the value size. Runs are short (39 to 91 values on average on hits.parquet); #115819 named this as a follow-up.

For fixed-size dictionaries with 1, 2, 3, 4, 8 or 16-byte values, the column is now resized once per call and each run is filled in place: an RLE run from a local copy of the value, a bit-packed run unpacked in batches of up to 256 indexes with unpack from #128262, checked against the dictionary size, then gathered. A corrupt index is rejected with the same INCORRECT_DATA error as before. Other dictionaries keep the existing path.

ClickBench hits.parquet, release build, Xeon 6975P-C, one clickhouse-local per run, 1 core, 24 alternating pairs, NUMA-local binaries; patched/master (fd1c83b13f53), geometric mean with 95% CI:

Query patched/master
q3 SUM(AdvEngineID), COUNT(*), AVG(ResolutionWidth) 0.917 [0.909, 0.924]
q4 AVG(UserID) 0.952 [0.944, 0.959]
q30 (90 sums of ResolutionWidth) 0.916 [0.911, 0.921]
q11 / q12 (filtered reads) 0.999 [0.994, 1.003] / 0.999 [0.995, 1.004]
q21 (String, control) 1.001 [0.994, 1.008]
A/A q4 1.000 [0.996, 1.003]

4-core runs on this shared host agree with wide intervals (q4 0.951 [0.911, 0.992]). All 77 non-String hits.parquet columns hash identically with and without the patch. A new stateless test covers every specialized value size, Nullable, runs split between calls and corrupt indexes; parquet_dictionary_decode.xml is a new performance test.

Analysis and patch by @ snelheidai in #124666 and #128262.

🤖 Generated with Claude Code


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

groeneai and others added 4 commits October 9, 2026 04:13
…resize per call

`BitPackedRLEDecoder::decodeAndIndex` appended every RLE or bit-packed run
separately through `Dictionary::appendRepeated` / `appendIndexes`. Each of
those calls switches on the dictionary mode, grows the column through the
virtual `IColumn::insertRawUninitialized` and switches on the value size.
Runs are short (about 39 values per bit-packed run and 91 per RLE run on
`hits.parquet`), so this fixed cost was a large part of decoding numeric
columns. ClickHouse#115819 named this as a follow-up ("batching the per-run
`insertRawUninitialized` bookkeeping").

For `Dictionary::Mode::FixedSize` with value size 1, 2, 3, 4, 8 or 16 (the
sizes `appendIndexes` / `appendRepeated` already specialize), the new
`decodeAndIndexFixedSize<value_size>` resizes the column once per call and
fills each run in place: an RLE run from a local copy of the dictionary
value, a bit-packed run by unpacking and gathering in one loop with the bit
position, data pointer and bit width in locals. Each index is clamped to
`limit - 1` before the gather, so a corrupt index never reads outside the
dictionary, and the run is still rejected afterwards with the same
`INCORRECT_DATA` error as before.

String dictionaries, `Mode::Column`, other value sizes, `bit_width == 0`
and an empty dictionary keep the existing per-run path (the latter rejects
every index without reading the dictionary, so errors are unchanged). As in
`Int96Converter` and `DeltaBinaryPackedDecoder`, an exception leaves an
uninitialized tail in the column; the read is aborted in that case.

Analysis and the original patch by @ snelheidai in ClickHouse#124666.

Closes ClickHouse#124666

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The fixed-size path gathers through a clamped index and rejects the run
afterwards, so a regression test must feed it an index past the end of the
dictionary. The test writes a 3-entry Int32 dictionary column, checks that
the bit-packed pattern for indexes 0,1,2 is present, overwrites one byte of
it with 0xFF (four copies of index 3) through `RawBLOB`, and expects
`INCORRECT_DATA`. No binary file is committed.

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

The fixed-size path gathers each bit-packed value through an index clamped to
the last dictionary entry and rejects the run only after the gather. The
existing corrupt case uses index 3 of a 3-entry dictionary, whose unclamped
read still lands inside the prefetched column chunk, so it passes with or
without the clamp. The new case rewrites the first data page's run to a
32-bit-wide bit-packed group whose first index is 0xFFFFFFFF: with the clamp
the read stays inside the dictionary and the run is rejected with
`INCORRECT_DATA`; without it the read lands about 16 GiB past the dictionary.
A guard query fails the test if the writer stops producing the patched layout.

Also update the `PageDecoder::decodeAndIndex` comment: bit-packed indexes are
no longer always gathered from a stack buffer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten two comments in decodeAndIndexFixedSize to bare invariants (drop the design notes).

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 9, 2026
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (rounds 1-3): 3 fixed, 1 disputed, 1 noted; round 3 clean
  • ❌ No test for a corrupt bit-packed index (Gate B, round 1): AGREE, fixed. 05339 now builds a corrupt file in SQL; deleting the bounds check fails the test.
  • ❌ The clamp itself was not test-live (Gate B, round 2): AGREE, fixed. Index 3 on a 3-entry dictionary stays inside the same buffer, so a second file uses bit width 32 and a first index of 0xFFFFFFFF; removing the clamp now fails the test.
  • ⚠️ Tests do not prove the single resize (Gate B, round 1): DISAGREE. A correctness test cannot tell the two apart; parquet_dictionary_decode.xml can (1 core: numeric queries 0.81-0.93, String control 1.007).
  • 💡 The decodeAndIndex doc in Decoding.h still described the stack-buffer gather; reworded (round 2).
  • 💡 The run loop of decodeAndIndex now appears twice; a shared policy would have to own the different bit-packed inner loops, so I kept the second loop.

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? The benchmark: ClickBench hits.parquet, 16 alternating pairs. 1 core: q3 0.807, q4 0.935, q30 0.815; 4 cores: q3 0.816, q4 0.917, q30 0.882, all CIs below 1.0; A/A 0.996 [0.973, 1.019].
b Root cause explained? Each RLE or bit-packed run (39 to 91 values on average) paid a mode switch, a virtual insertRawUninitialized resize and a value-size switch, plus a member bit_idx store per value.
c Fix matches root cause? Yes. For fixed-size dictionaries of 1/2/3/4/8/16 bytes the column is resized once per call and each run is filled in place; nothing else changes.
d Test intent preserved / new tests added? New stateless test: a hash per value size, a block size that splits runs between calls, Nullable, and two corrupt files (an index one past the dictionary; a 32-bit index 0xFFFFFFFF). New tests/performance/parquet_dictionary_decode.xml.
e Both directions demonstrated? Timings above. The test passes on both binaries; dropping the bit_idx write-back, breaking the RLE fill, removing the post-loop check or removing the clamp each fail it.
f Fix is general across code paths? BitPackedRLEDecoder is the only decodeAndIndex override and Reader.cpp its only caller; Strings, Mode::Column, other value sizes, bit_width == 0 and empty dictionaries keep the existing path.
g Fix generalizes across inputs (params/datatypes/wrappers)? Identical results with and without the patch for all 77 non-String hits.parquet columns and 24 types (FixedString, Decimal, Int128, UInt256, UUID, IPv4/6, dates, floats, Nullable, Array, Map, Tuple, LowCardinality) at several block sizes, with WHERE and PREWHERE.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or on-disk change; the error on a corrupt index is unchanged.
i Invariants and contracts preserved? Every gather is clamped to limit - 1 (limit == dictionary.count, data.size() == count * value_size); bit_idx, run_length and data advance as before. On an exception the column keeps an uninitialized tail, as Int96Converter already does, and the read is aborted.

Session id: cron:clickhouse-impl-slot-40:20261009-035400

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [755db44]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
04011_predicate_statistics_log FAIL cidb
01414_push_predicate_when_contains_with_clause NOT_FAILED cidb
01513_optimize_aggregation_in_order_memory_long NOT_FAILED cidb
03273_group_by_in_order_still_used_when_group_by_key_doesnt_match_order_by_key NOT_FAILED cidb
02884_create_view_with_sql_security_option NOT_FAILED cidb

AI Review

Summary

The PR sizes the output column once per decoded range for fixed-size Parquet dictionaries, then fills RLE runs or gathers bounds-checked batches of bit-packed indexes. No actionable findings at 755db441f8c998cc203a5e01aed832ff2b01feac. The updated benchmarks report a 5–8% improvement on affected ClickBench queries, and the added stateless test covers specialized value sizes, nullable values, partial runs, and corrupt indexes. An independent standalone check using the exact decoder code passed under ASan/UBSan: 6,336 streams, 152,660 mixed skip/decode operations, and 90 corrupt batches rejected.

Missing context / blind spots
  • ⚠️ Full PR-head CI is still pending. No local ClickHouse build is available, so the SQL regression test was not rerun here; the standalone check uses minimal column/dictionary adapters. Completed native Parquet stateless CI results would close this validation gap. The author reports the current regression tests pass.
Final Verdict

Status: ✅ Approve. No code changes requested; full CI results remain pending.

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 755db441f with master a0b5e3cec (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 20409c648; 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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR only changes the Parquet reader: it adds a specialised loop that decodes and looks up fixed-size dictionary values in BitPackedRLEDecoder, plus new tests. The three flagged ClickBench queries (Q28, Q33, Q34) are heavy GROUP BY queries on the hits table and do not run that code. I'm assuming the clickbench benchmark reads the MergeTree hits table, not hits.parquet; I didn't check the benchmark setup. Their similar +7-9% slowdowns most likely come from two source runs sharing one machine and from Q33/Q34 already being noisy on master. So I downgraded the Q33 regression to not_sure, and agree with the automatic hold-back on Q34 (inside master's recent range) and Q28 (the tests disagree). The benchmarks used here don't cover the PR's intended Parquet speedup; to measure it, use the new parquet_dictionary_decode performance test.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1033 1109 +7.4% 0.0095 aggregation: The two tests disagree and the measurements were noisy. This regex-plus-GROUP BY query reads the MergeTree hits table and never runs the Parquet dictionary decoder this PR changes.
⚠️ 33 not_sure 1029 1106 +7.5% 0.0003 aggregation: The +7.5% comes from a heavy GROUP BY on hits, which the Parquet BitPackedRLEDecoder change cannot reach. The query's history is noisy and two source runs shared one machine, so this is not a PR effect.
⚠️ 34 not_sure 1020 1110 +8.8% <0.0001 aggregation: The +8.8% falls inside master's recent range of 964-1136 ms, so it was held back on purpose. I am not contesting that: the query never runs the changed Parquet decode path.

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: 89fd3ce8-2728-451b-a11f-45bde463fdbf
  • MIRAI run: 30d6063f-9ecc-4efd-8a5d-08687c147eb9
  • PR check IDs:
    • clickbench_519824_1791541393
    • clickbench_519837_1791541393
    • clickbench_519843_1791541393
    • tpch_adapted_1_official_519849_1791541393
    • tpch_adapted_1_official_519881_1791541393
    • tpch_adapted_1_official_519895_1791541393

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d3c7f91

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
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05316_secret_arguments_declared_by_engines test regression from merged #123364, not from this PR: under DatabaseReplicated the final query_log count returns 0 2 instead of 0 1 (the password stays hidden; the CREATE DICTIONARY row is counted twice). 21/21 reruns pass; the same diff is on 33 PRs in this lane today a fix task is created (investigating at full effort, fixing-PR link to follow here)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05210_lightweight_update_materialized_cte_in_ignore flaky, not from this PR: Code: 60 UNKNOWN_TABLE for the initiator-local _materialized_cte_c_* table when a follower replica takes a read (issue #112642). 118/118 reruns pass; 11 PRs in 30 days #123121 (mine, open)
Stateless tests (arm_asan_ubsan, azure, sequential) job timeout, not from this PR: the job hit its 9000 s limit at test 1174 of 1180 with no failed test; the same lane timed out on 17 true-master runs in 5 days #123849 (mine, open)
Mergeable Check, PR praktika rollups of the three rows above, no independent failure #123121, #123849; a fix task is created (05316)

Session id: cron:our-pr-ci-monitor:20261009-140011

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05316_secret_arguments_declared_by_engines (DatabaseReplicated 0 1 -> 0 2) from the CI finish ledger above: #124928 (external, open).

groeneai and others added 2 commits November 2, 2026 13:56
…fixed-size-decode

# Conflicts:
#	src/Processors/Formats/Impl/Parquet/Decoding.cpp
…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]>
@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

I merged master (it conflicted with #128262 in Decoding.cpp) and applied the batched unpack from #128262 (comment) in 755db44: the clamp is gone and the batch maximum is checked before the gather.

x86 re-measurement: Xeon 6975P-C, release, hits.parquet, 1 core, 24 alternating pairs, both binaries in page cache on the benchmark's NUMA node; geometric mean of new/old with 95% CI.

Query batched / per-value loop (both master + this PR) this PR / master
q3 0.924 [0.918, 0.929] 0.917 [0.909, 0.924]
q4 0.944 [0.934, 0.954] 0.952 [0.944, 0.959]
q30 0.922 [0.914, 0.929] 0.916 [0.911, 0.921]
q12 0.983 [0.962, 1.005] 0.999 [0.995, 1.004]
q11 0.981 [0.967, 0.995] 0.999 [0.994, 1.003]
q21 (control) 1.010 [0.976, 1.046] 1.001 [0.994, 1.008]

Q12 is not slower here. In its profile decodeAndIndexFixedSize is under 1% of samples: MobilePhoneModel <> '' becomes PREWHERE, so most reads take the filtered skipOrDecode path, and MobilePhone is Int16 in hits.parquet, so a 1-byte special case would not reach it. Before I placed the binaries NUMA-locally, an A/A of two copies of one binary read 0.970 [0.963, 0.978] on q4; afterwards 1.000 [0.996, 1.003].

05339 (both corrupt-index cases), 05482 and 05320 pass. With the batch check removed, the _bad read is no longer rejected and the _wide read crashes the server. The description now has the numbers against current master.

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 755db44

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
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04011_predicate_statistics_log flaky, not from this PR (the test reads MergeTree only, no Parquet): the q6 conjunction total_selectivity line flips 1 1 to 0 1. CI's settings diagnosis reproduced it 36/36 with the drawn settings, 0/37 without, and isolated index_granularity_bytes 116964 (the test pins index_granularity but not index_granularity_bytes). First failure in 30 days a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above, no independent failure a fix task is created (04011)

Session id: cron:our-pr-ci-monitor:20261102-193004

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 04011_predicate_statistics_log created: #128769

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. groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements

Projects

None yet

1 participant