Skip to content

Parquet dictionary filter: do not sort the dictionary value hashes for a few lookups - #123579

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:parquet-dictionary-filter-lazy-sort-123487
Oct 3, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:parquet-dictionary-filter-lazy-sort-123487

Conversation

@groeneai

@groeneai groeneai commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #123487
Related: #115744

Changelog category (leave one):

  • Performance Improvement

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

Row group pruning by dictionaries in the Parquet reader is faster for an equality or a short IN list on a column with large dictionaries, such as WHERE UserID = ... over ClickBench hits.parquet: the hashes of the dictionary values are no longer sorted unless a column chunk is checked against many values.

Description

Proposed by @ snelheidai in #123487 (analysis and patch); the numbers below are my own.

hashDictionaryValues sorted the hashes of every dictionary-filtered column chunk (#115744) for binary search. A chunk is usually probed once, by the 1-5 constants of one condition, so the O(n log n) sort cost more than the lookups it served.

Change. The vector stays unsorted: DictionaryValueHashes::containsAny answers up to max(8, log2(n)) probes in total by a linear scan, then sorts once and uses the existing merge search. Pruning decisions are unchanged; nothing new is allocated.

Measured (release, clickhouse local on 4 CPUs, median of 15 (q20: 8) alternating processes of 5 runs each, identical results):

Query Before After
16 row groups of 100000 distinct UInt64, id = const 16 ms 7 ms
same, id IN (5 constants) 16 ms 7 ms
ClickBench q20 on hits.parquet 135.5 ms 74.5 ms
512-value dictionaries, nothing pruned 658 ms 659 ms
IN of 5000 values 20 ms 20 ms
20 OR'ed equalities (worst case) 20 ms 22 ms (ratio CI 0.96-1.21)

On 384 cores the first two go from 8 to 6 ms; q20's wall time is flat (row groups are pruned in parallel) but it uses 346 instead of 578 ms of CPU.

Validation. New test 05317_parquet_dictionary_filter_several_conditions_on_one_column checks results and rows_read with the dictionary filter on and off for 1, 2x10 and 20 conditions on one column; breaking the scan or the sorted search reddens it, and it passes on the old binary. Existing Parquet dictionary filter tests pass; the perf test gets a large-dictionary fixture with the first two queries.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits October 2, 2026 15:07
…r a few lookups

`hashDictionaryValues` sorted the hashes of every dictionary-filtered column chunk so that
`DictionaryValueHashes::containsAny` could binary-search them (ClickHouse#115744). A chunk's value set lives
for one row group filter evaluation and is usually probed once, by the 1-5 constants of one
condition, so the O(n log n) sort dominated the cost of the dictionary filter.

Keep the vector unsorted and let `containsAny` answer up to max(8, log2(n)) probes in total by a
linear scan; the first call that would exceed that sorts the vector once, and the existing merge
search is used from then on. A sort costs about log2(n) scans, so the scans never cost more than
the sort they avoid, and a large probe set (an over-cap `IN` set) sorts on its first call exactly
as before. Both paths compute membership in the same set, so pruning decisions are unchanged, and
nothing new is allocated, so the pruning memory reservation still covers the vector.

On 16 row groups of 100000 distinct UInt64 values (release build, 4 CPUs), one equality goes from
16 to 7 ms and from 43.5 to 2.9 ms of query CPU; ClickBench q20 on hits.parquet from 135.5 to
74.5 ms.

The new test covers the scan, the switch to sorting and the sorted search, and the performance
test gets a fixture with large dictionaries.

Proposed by snelheidai in ClickHouse#123487 (analysis and patch).

Closes: ClickHouse#123487

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the obvious field comment on DictionaryValueHashes and condense the scan-threshold comment to one line.

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; 1 finding) plus my own cold review (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new tests do not fail if eager sorting is restored (05317 .sh, perf XML) DISAGREE 05317 guards correctness of both paths (mutation-live); the speed is guarded by the two new queries in parquet_dictionary_filter.xml, about 2.3x slower with the eager sort restored.
2 💡 The scan does one pass over the hashes per probe instead of one pass for all probes noted, not blocking At most max(8, log2(n)) passes; the measured gain already holds.
3 💡 Worst case: probes exhaust the scan budget, then the sort runs anyway noted, not blocking Needs several unfolded conditions on one column; measured 20 -> 22 ms (ratio CI 0.96-1.21), listed in the description.
4 💡 The sorted search in a call after the switch (test case 5) is reached by construction but not mutated on its own noted, not blocking That loop is unchanged master code, also covered by 05024.

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

Session id: cron:clickhouse-review-slot-10:20261002-151300

@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 (performance): release, 4 CPUs, 16 row groups of 100000 distinct UInt64, WHERE id = const: 16 ms -> 7 ms (CPU 43.5 -> 2.9 ms), every rep.
b Root cause explained? hashDictionaryValues sorted every dictionary-filtered column chunk's hashes before knowing how many probes would come; a chunk is usually probed by 1-5 constants, so the O(n log n) sort dominated.
c Fix matches root cause? Yes: the sort is deferred to the first lookup for which scanning would cost more (more than max(8, log2(n)) probes in total); the lookup that sees the probe count makes the decision.
d Test intent preserved / new tests added? New test 05317_parquet_dictionary_filter_several_conditions_on_one_column covers the scan, the switch to sorting and the sorted search; three mutations (one per path) each redden it. Perf test extended with a large-dictionary fixture.
e Both directions demonstrated? Timing: before/after in alternating reps, identical results. The new test passes on the old binary (pruning unchanged) and fails under each mutation.
f Fix is general across code paths? containsAny is the only reader of the hash vector; the bloom filter path and the over-cap IN path are unchanged (a large probe set sorts on the first call, as before).
g Fix generalizes across inputs (params/datatypes/wrappers)? Type-independent (works on the hash vector); null-as-default is still checked first. 1, 2x10, 20 probes and a 5000-value IN run; the existing family (strings, fixed-size, nullable, large IN) passes.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or result change.
i Invariants and contracts preserved? The result is set membership regardless of order; the merge search runs only on a sorted vector; no allocation added, so the pruning memory reservation still covers the vector; the value set is used by one thread.

Session id: cron:clickhouse-impl-slot-40:20261002-133800

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [40e4916]

Summary: ✅


AI Review

Summary

This PR makes the Parquet dictionary filter defer sorting each row group's hashed dictionary values until the accumulated lookup pattern makes sorting cheaper than repeated linear scans. I did not find a violated correctness, memory-accounting, or concurrency contract in the changed code: the mutable lazy-sort state stays inside one DictionaryLookup, the pruning-memory reservation still covers the same persistent buffer, the new stateless test exercises the scan-to-sort transition across repeated predicates on one column, and the PR description provides concrete before/after evidence for the claimed Performance Improvement.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 40e4916.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 21/22 (95.45%) · Uncovered code

Full report · Diff report

@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 2, 2026
size_t scanned_probes = 0;

/// Whether any of `probes` is among the dictionary's values.
/// Sorting costs about log2(n) scans, so the first max(8, log2(n)) probes scan the unsorted `hashes`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see, so if we have a small number of hashes to check, we aren't going to first sort the hashes before checking.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did not tune it: the threshold comes from the patch in #123487, and I kept it after measuring. The reasoning is a comparison count. Sorting n hashes costs about n * log2(n) comparisons and one scan costs n, so for up to about log2(n) probes scanning is no dearer than sorting first; bit_width(n) is that log2, and 8 is a round minimum for small dictionaries, where both costs are negligible. The budget is per column chunk across all its lookups, so it also bounds the worst case: at most max(8, log2(n)) scans before a sort that happens anyway.

In wall time the bound is conservative. A standalone microbenchmark (clang-22 with ClickHouse's libc++, -O2, random 64-bit values, one core of a Xeon 6975P-C):

n sort one scan sort / scan budget
1024 5.0 us 0.09 us 54 11
16384 270 us 1.6 us 164 15
100000 1.81 ms 10.0 us 180 17
1000000 19.5 ms 267 us 73 20

So at n = 100000 the worst case adds about 17 / 180, i.e. 10% of a sort, consistent with the 20 OR'ed equalities row in the description (20 -> 22 ms). A budget at the real break-even would also scan IN lists of a few dozen constants, but would let that worst case approach 2x. I kept the conservative value; if mid-size IN lists matter more to you, it is a one-constant change.

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 33 queries analysed

This PR changes only how the Parquet reader checks column-chunk dictionaries when pruning row groups on equality/IN filters: it now scans small probe sets and sorts only after several lookups. None of the flagged ClickBench or TPC-H queries run that code, and every flag stays not_sure. The ClickBench slowdowns (+5.1% to +15.4%, Q16/18/28/32/33/34) line up with two of the PR's runs sharing one machine, and four of them are still inside master's current range. The TPC-H Q1 (-18.5%) and Q7 (-16.0%) speedups are measured against unstable baselines, and the PR's own parquet_dictionary_filter perf test is the right place to judge its effect.

clickbench

⚠️ 6 inconclusive

Flagged queries (6 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 548 619 +13.1% <0.0001 The +13.1% sits inside master's current range. This MergeTree GROUP BY query never runs the Parquet dictionary-filter code this PR changes, so there is no reason to contest the suppression.
⚠️ 18 not_sure 895 1033 +15.4% <0.0001 The +15.4% comes on an unstable baseline with noisy measurements. The query does not use Parquet row-group pruning, which is the only runtime code this PR touches.
⚠️ 28 not_sure 1068 1122 +5.1% <0.0001 The +5.1% is borderline: the two tests disagree and the measurements were very noisy. The changed Parquet dictionary-filter code is not on this query's path.
⚠️ 32 not_sure 741 845 +14.0% <0.0001 The +14.0% falls within master's current range. The query does not run the Parquet dictionary-filter code this PR changes, so the suppression stands.
⚠️ 33 not_sure 1153 1224 +6.2% <0.0001 The +6.2% is inside master's current range. This GROUP BY over URL has no equality or IN filter, so the Parquet dictionary filter cannot be involved.
⚠️ 34 not_sure 1136 1232 +8.4% <0.0001 The +8.4% is inside master's current range. This query has no equality or IN filter, so the changed dictionary-lookup code never runs.

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

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 53 -18.5% <0.0001 The -18.5% is measured against an unstable baseline on a fast, noisy query. TPC-H Q1 does not read Parquet through the dictionary-filter path, so this PR cannot explain the shift.
⚠️ 7 not_sure 81 68 -16.0% <0.0001 The -16.0% (13 ms) is measured against an unstable baseline that shifted during the comparison window. The join query does not touch Parquet dictionary filtering.

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.

Debug info
  • StressHouse run: 9cc6ffb3-e70b-4868-9aa5-fd1a8b27ea14
  • MIRAI run: 14e5a307-b27f-4a92-ad1c-b0d2300781a1
  • PR check IDs:
    • clickbench_2944181_1790964680
    • clickbench_2944187_1790964681
    • clickbench_2944198_1790964681
    • tpch_adapted_1_official_2944224_1790964681
    • tpch_adapted_1_official_2944238_1790964681
    • tpch_adapted_1_official_2944252_1790964681

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 40e491654 with master 1b7e6cd8a (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, 23 s compile time in total, 8 of them have a recent master baseline.

Job report

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 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 dictionary filter: avoid sorting dictionary hashes for a few probes (ClickBench q20 3.9x faster)

4 participants