Skip to content

Skip Parquet row groups by statistics for a String ORDER BY key without the per-row filter - #124827

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/parquet-top-k-string-statistics
Oct 31, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/parquet-top-k-string-statistics

Conversation

@groeneai

@groeneai groeneai commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124560
Related: #104216
Related: #122064

Changelog category (leave one):

  • Performance Improvement

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

ORDER BY <String column> LIMIT n over Parquet files skips row groups by the min/max statistics of the sort column, as it already did for numeric keys, without the per-row filter that use_top_k_dynamic_filtering_for_variable_length_types controls: SELECT Title FROM file('hits.parquet') ORDER BY Title DESC LIMIT 10 skips 203 of its 226 row groups and is about 10 times faster at 4 threads. Closes #124560.

Description

Proposed by @ snelheidai in #124560; numbers below are mine.

With use_top_k_dynamic_filtering_for_variable_length_types = 0 (the default since #104216), tryTopKForFormatSource returned before creating the threshold tracker for a String key, so Parquet reads skipped no row groups by statistics. The setting targets the per-row __topKFilter; the per-row-group check costs one comparison per row group.

Change. A String key (also Nullable / LowCardinality) gets the threshold with FormatTopKFilterInfo::filter_rows = false: the reader orders and skips row groups by statistics, but installs no per-row filter and does not force the offset index. Excluded: collations, LIMIT + OFFSET >= 1500 (there PartialSortingTransform filters rows itself, but not with a tracker), Memory tables (they would get a per-row filter) and URL reads (unchanged). If all row groups share the bound on the threshold side, the file order is kept. For the query condition cache such a read is a plain read: skipped row groups count as matched, and it takes the plain branches of #122064 (File) and #124808 (data lakes), whatever use_query_condition_cache_for_top_k is.

FIXED_LEN_BYTE_ARRAY read as String no longer uses statistics for TopN: the cast strips trailing zero bytes that the statistics keep, so ORDER BY f, v LIMIT 3 could lose rows (reproducible today with the opt-in).

Measured (release, hits.parquet, 4 threads, 11 alternating runs, identical results):

Query Before After Skipped
ORDER BY Title DESC LIMIT 10 3605 ms 343 ms 203/226
ORDER BY URL DESC LIMIT 10 3424 ms 339 ms 220
ORDER BY URL LIMIT 10 3606 ms 3137 ms 40
ClickBench Q25 / MobilePhoneModel LIMIT 300 870 / 340 ms 867 / 338 ms 0

At 16 threads: 0.20-0.46x. New test 05339_parquet_top_k_string_statistics (fails on the old binary) and perf test parquet_top_k_string.xml.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits October 9, 2026 04:06
…ut the per-row filter

With `use_top_k_dynamic_filtering_for_variable_length_types = 0` (the default), `tryTopKForFormatSource`
returned before creating the threshold tracker for a `String` sort key, so the Parquet reader got no
threshold at all: no skipping of row groups by min/max statistics and no sort-key-ordered admission.
The setting exists because the per-row `__topKFilter` comparison can cost more than it saves; the
per-row-group statistics check is O(row groups) and does not have that cost.

Now a `String` key (through `Nullable` / `LowCardinality`) gets the threshold with
`FormatTopKFilterInfo::filter_rows = false`: the reader orders, admits and skips row groups by
statistics, but installs no `__topKFilter` and does not force the offset index. Not for a collated
order (the reader cannot use the statistics), not for `LIMIT + OFFSET >= 1500` (there
`PartialSortingTransform` filters rows by its own threshold, which it does not do once a tracker is
set), and only for sources that can use statistics (`ReadFromFile`, `ReadFromObjectStorageStep`; a
Memory table would otherwise get a per-row filter).

When all row groups of a file share the bound on the threshold side, the reader keeps the file order: no
row of that file is beyond that bound. For the query condition cache a statistics-only read is a plain
read: the row groups it skipped are reported as matched, all four cache gates (File and object storage,
read and write) treat it as a read without TopN, and a `File` read makes no TopK cache key for it
(tracking the best values for that key would compare every returned row).

`FIXED_LEN_BYTE_ARRAY` read as `String` no longer uses statistics for TopN: the cast strips trailing
zero bytes from the values, but the statistics keep them, so a row group whose padded minimum ties
the threshold could be skipped and rows that win on a later sort column lost. This was reachable with
the opt-in and would otherwise have become reachable by default.

Adds `tests/performance/parquet_top_k_string.xml`.

Closes ClickHouse#124560

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove a duplicate cache-write note and the design rationale of the filter-less TopK cache key (both in the commit message); shorten the FIXED_LEN_BYTE_ARRAY and PartialSortingTransform notes 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 9, 2026
@groeneai

groeneai commented Oct 9, 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; r1: 3 findings, r2: 3 findings, r3: 0 findings, r4 after the rebase onto #122064: 0 findings) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ use_query_condition_cache_for_top_k docs say TopK reads ignore the cache when it is off, but statistics-only String reads use it AGREE, fixed @ r1 documented in the setting and the query condition cache guide; behaviour kept as on master (compatibility <= 26.7 sets the setting to 0)
2 ⚠️ test proves skipping only for plain String, not Nullable / LowCardinality AGREE, fixed @ r1 rows_read assertions for the three wrappers + a mutant that drops the wrapper strip
3 ⚠️ cache-hit assertions race with parallel tests that clear the cache DISAGREE only one parallel-phase test clears the cache (03229, once; 04836 runs the clears as a denied user); one clear spoils at most one of three attempts; 50 randomized + 50 flaky-check runs green
4 💡 same-bound comment says "none can be skipped", false for multi-file reads (shared threshold) AGREE, fixed @ r1 comment states the per-file invariant
5 ⚠️ no assertion that object storage gets the statistics-only threshold AGREE, fixed @ r2 two-object S3 arm asserts 10 skipped row groups and no per-row filter; red with the object storage override returning false
6 ⚠️ cache bookkeeping for row groups skipped after their read started is not exercised AGREE, fixed @ r2 the second object is skipped only at that stage; deleting either skipped_by_top_k store reddens the cache-correctness lines (20/20)
7 💡 filter_rows comment says the returned rows do not depend on the threshold AGREE, fixed @ r2 comment corrected
8 💡 the S3 arm's exact count (10) becomes up to 17 once #124195 (strict skip for one sort column) lands AGREE, noted, not blocking correct and deterministic on master; whichever of the two PRs merges second updates the reference (they conflict in tryTopKForFormatSource, so it gets a fresh CI run)

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

Session id: cron:clickhouse-review-slot-8:20261009-043300

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [794a551]

Summary: ✅


AI Review

Summary

Enables statistics-only TopK pruning for String keys in Parquet reads without enabling per-row filtering, preserves predicate-only query condition cache entries, and prevents unsafe pruning when FIXED_LEN_BYTE_ARRAY values are read as String. No actionable findings in the current diff; the supplied performance measurements and focused regression coverage support the change.

Final Verdict

Status: ✅ Approve

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: SELECT s FROM file('t.parquet') ORDER BY s DESC LIMIT 3 at 1 thread reads 20000 rows on master and 2000 with the change, every run. The FIXED_LEN_BYTE_ARRAY case returns wrong rows on master with the opt-in, deterministically.
b Root cause explained? tryTopKForFormatSource returned before creating the tracker for a variable-length key without the opt-in, so one gate turned off both the per-row filter and the per-row-group statistics check.
c Fix matches root cause? The gate is split where it is made: a String key gets the threshold with filter_rows = false, and the per-row reader paths are gated on that flag.
d Test intent preserved / new tests added? New 05339_parquet_top_k_string_statistics and parquet_top_k_string.xml; each changed gate and both places that mark a row group skipped by the threshold have a deletion mutation that reddens its own line, including the object storage read of row groups skipped after their file was started.
e Both directions demonstrated? Master fails the effect arms, the object storage arm and the FLBA arm; the fix passes; 14 mutants each fail their arm. 50/50 randomized and 50 flaky-check runs green.
f Fix is general across code paths? All FormatTopKFilterInfo consumers (File, object storage; Memory excluded), both skip sites, all four query condition cache gates, and no File TopK cache key for such a read (it would track per-row best values).
g Fix generalizes across inputs (params/datatypes/wrappers)? Row groups skipped for String, Nullable(String), LowCardinality(String) and LowCardinality(Nullable(String)); NULLS FIRST/LAST, collation, shared bound, ties, OFFSET, PREWHERE, preserve_order, the LIMIT 1500 boundary, Int64 and FIXED_LEN_BYTE_ARRAY read as String, 1 and 8 threads: results equal to use_top_k_dynamic_filtering = 0.
h Backward compatible? (maintainer-approved exception only) No default changes; results identical; the query condition cache keeps master's behaviour for String keys under every setting.
i Invariants and contracts preserved? A statistics-only read returns the rows of a read without TopN minus row groups proven to hold no top-K row, and its cache verdicts are those of the predicate alone.

Session id: cron:clickhouse-impl-slot-41:20261009-030300

@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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: c5716ee7-029f-4bd2-86c8-eef398e6014c
  • MIRAI run: f4cc915a-54ab-4006-a30c-97df3e049f7e
  • PR check IDs:
    • clickbench_498017_1791528574
    • clickbench_498023_1791528574
    • clickbench_498029_1791528574
    • tpch_adapted_1_official_498039_1791528574
    • tpch_adapted_1_official_498051_1791528574
    • tpch_adapted_1_official_498087_1791528574

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a32dd7a

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
Build (arm_tidy, 2/4) / Build ClickHouse master-side build break, not from this PR (which changes the Parquet reader, optimizeTopK and the object-storage/file read steps): src/Common/Scheduler/Nodes/tests/gtest_throttler_constraint.cpp:25:11: error: use of undeclared identifier 'FifoQueue', the only error in the shard, in a file this PR does not touch. 19 true-master commits and 79 PRs fail this shard since 2026-10-09 00:35Z #124798 (external, open)
Mergeable Check, PR praktika rollups of the row above (Failed: Build (arm_tidy, 2/4), Dropped: 105), no independent failure #124798 (external, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

All check runs completed. The other three arm_tidy shards, Fast test, Style check and Docs check (Mintlify) passed. 105 jobs were dropped behind the shard 2/4 failure, so the functional test matrix and Performance Comparison have not run on this head yet.

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

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 9, 2026
The flaky check stopped 05346 as too slow on amd_tsan (180-192 s of the 180 s limit) and
killed it at the 600 s timeout on amd_binary, amd_debug and amd_asan_ubsan. The check
enables the thread fuzzer, which costs about 40 ms per 100-row Parquet subgroup, so each
full read of the 80000-row file at input_format_parquet_max_block_size = 100 took 31-33 s
there, and the test had about 50 of them: the unoptimized side of the result comparisons,
the reference reads and counts of the cache arm, and the reads of the String-key tripwire.

No full read is left:
- the results of the three queries in four configurations are compared with fixed rows in
  the reference, in order;
- the late-skip and cache arms repeat the read until it skips 38 row groups (at most 20
  times), taking the counters from --print-profile-events;
- the late-skip arms also assert that a skipped row group reads no page: the sort column has
  one page per row group, so skipped plus ParquetReadPages is 40; without rows_pass = 0 the
  counter alone still passed, and the sum is 41-42;
- the String-key tripwire for ClickHouse#124827 runs only when a 4-row probe shows statistics skipping
  String row groups without the per-row filter. The probe prints 0 on master; with ClickHouse#124827
  it prints 1 and the 5 reads and the cache-on count run, so whichever of the two merges
  second updates the reference and adds the skipped_by_top_k mark in scheduleTask;
- the final cache-on count is removed: it only covered the query condition cache rule that
  master already has (no plain-key entry after a top-K read).

Debug build, randomized, -j 8: fix 50/50 OK, base 20/20 FAIL (no read skips 38 row groups),
fix without rows_pass = 0 10/10 FAIL (pages), this branch with ClickHouse#124827 at a32dd7a and the
mark 20/20 OK on the armed reference, without the mark 20/20 FAIL (count 26000-30000 of
40000). From the per-query times of the amd_binary flaky check, the test now takes about
55 s there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 9, 2026
…coding

The check in scheduleTask runs when a row subgroup's step is dequeued. One
scheduling pass can dequeue several row groups' tasks (up to the ColumnData
stage's share of the parsing threads, about 1/5) and batch them, so a task can
still wait behind other decodes, in its batch or in the pool, while the
threshold tightens.

runTask now repeats the check when the step's last unfinished task starts: the
step's other tasks have finished, so no other thread reads filter.rows_pass.
Both sites share skipIfExcludedByTopK. The pages of such a subgroup are already
prefetched, so only the decode is saved.

Debug build, a file of 200 row groups x 100000 random UInt64 keys,
SELECT k ... ORDER BY k LIMIT 10, 20 runs each. Row groups the threshold
excluded when their first decode task started, decoded anyway, per query:
- 32 parsing threads, one subgroup per row group: 8.15 (max 32) -> 0
- 32 parsing threads, default block size: 3.1 (max 12) -> 0
- 20 parsing threads: 1.6-1.75 -> 0
- 8 parsing threads: 0 -> 0
Results equal use_top_k_dynamic_filtering = 0 in 180 runs (5 queries; 2, 8
and 32 threads; 3 block sizes; PREWHERE on and off) and in 90 under TSan with
no report; the parquet top-K tests pass, under TSan too.

The skipped_by_top_k mark of ClickHouse#124827 now goes into skipIfExcludedByTopK.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits October 23, 2026 12:09
… condition cache after the master merge

Master (ClickHouse#124808) added a TopK query condition cache key for data lake reads and made a TopN read of
object storage neither consult nor write the plain predicate key while
`use_query_condition_cache_for_top_k` is off. A statistics-only read (a `String` sort key without
`use_top_k_dynamic_filtering_for_variable_length_types`) compares no row with the threshold, so, as for
`File` tables and as the setting's documentation says, it stays a plain read for the cache:

- the plain key is consulted (merge resolution) and written whatever the value of the setting;
- `ReadFromObjectStorageStep::makeTopKQueryConditionCacheKey` makes no TopK key for it, as
  `ReadFromFile` already does: the key would make the reader track the best value of every row group,
  a per-row comparison on the `String` column that the statistics-only mode exists to avoid.

Test: a statistics-only read with the setting off populates the cache (File, S3); an Iceberg read
without a filter consults the cache with the opt-in and not without it.
Mutants, each red on exactly its line: write gate without `filter_rows`, consult gate without
`filter_rows`, no early return in the data lake key.

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

mintlify Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 794a551.

Approve preview

@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 794a5513b with master 9f79cc172 (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

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

Job report

… check

The flaky check runs eight copies of the test at once with the thread fuzzer on, where every process
start and every query is slow: the test took 161-180 s in the debug and 254-263 s in the ASan flaky
check, over the 180 s limit.

- clickhouse-local starts 4 times instead of 19: the fixtures in one process, the `rows_read` checks in
  one (a JSON document per query), all modes of the result comparison in one (switched with SET, the
  query condition cache off so that no mode reads the entries of an earlier one, as a process per mode
  guaranteed before), the Memory check in one.
- The 8-thread run compares only the optimization against the result without it, computed once: every
  query orders by a unique key, so that result does not depend on the threads. The 8-thread opt-in run
  is dropped: this change touches the opt-in path only by the FIXED_LEN_BYTE_ARRAY guard, which the
  single-thread opt-in run still checks.
- The server part runs one client call per group of queries, tags queries by `log_comment`, flushes and
  scans `system.query_log` once instead of nine times, counts without the cache once per table, and makes
  two attempts instead of three for the cache checks: no test of the parallel phase drops the cache.
- The skipped-row-group arms also read the `File` table's data as `Nullable(String)`,
  `LowCardinality(String)` and `LowCardinality(Nullable(String))`. The `rows_read` bound that the
  clickhouse-local checks assert for these wrappers holds with a per-row filter too, so only
  `ParquetRowsFilterExpression = 0` shows that they get none: a mutant that gives them the per-row
  filter is red on exactly these lines.

The reference loses one header line and gains the three wrapper lines. Debug, single run: 9.9 s ->
3.3 s; eight copies on 16 CPUs with the flaky check's thread fuzzer (no CPU migration) 47-50 s ->
18-21 s; one copy with the full thread fuzzer on 16 CPUs 465 s -> 231 s.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c31f42d

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
Stress test (arm_asan_ubsan, s3) / Logical error: Duplicate announcement received for replica number A (STID 8765-6e14) not from this PR, which changes only Parquet top-K reads: the parallel replicas coordinator aborts in handleInitialAllRangesAnnouncement, reached from createLocalPlanForParallelReplicas inside a nested read built by MergeTreeAnalyzeIndexSource / buildOrderedSetInplace. The same STID fired on 9 other PRs and 1 master run in 30 days #115916 (mine, open)
Mergeable Check, PR praktika rollups of the row above #115916 (the owner of the row above)

The 05339_parquet_top_k_string_statistics TOO_LONG of the previous head is fixed in this one: all five flaky checks pass (max 127.5 s, limit 180 s).

Session id: cron:our-pr-ci-monitor:20261023-220003

@alexey-milovidov alexey-milovidov self-assigned this Oct 27, 2026
alexey-milovidov and others added 2 commits October 28, 2026 03:43
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeTopK.cpp
#	src/Storages/StorageFile.cpp
…llel replicas

Since ClickHouse#127138 a persistent `S3` table is read over the replicas when parallel replicas are
enabled, so in the `ParallelReplicas` job the `ProfileEvents` of the initial query no longer
count the query condition cache lookups and the skipped row groups of the `t_05339_s3` and
`t_05339_s3_glob` reads, and four lines of the reference read 0. Pin
`enable_parallel_replicas = 0` for every server read of the test, as the `IcebergLocal` reads
already did, instead of tagging the whole test `no-parallel-replicas`.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 009e161

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
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 79 of 79 runs in the last 6 hours are red, on 76 PRs #126200 (mine, open)
PR praktika rollup of the row above #126200 (the owner of the row above)

05339_parquet_top_k_string_statistics now passes in Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) and in all five flaky check builds. No job was dropped. CIDB has no other FAIL or ERROR row in this run.

Session id: cron:our-pr-ci-monitor:20261028-120007

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (no conflicts; the touched Parquet / optimizeTopK / storage translation units compile). The only red check, Stress test (amd_tsan) — ThreadSanitizer: data race on exit_code in ClientEmbeddedRunner::clientRoutine (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124827&sha=b552a9cc6e8b6c4fb986a1818201b05a29458d73&name_0=PR&name_1=Stress%20test%20(amd_tsan)) — is unrelated to this PR and is being fixed in #127990.

@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.

LGTM

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 31, 2026
Merged via the queue into ClickHouse:master with commit f221f3e Oct 31, 2026
180 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 31, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 31, 2026
…ache

With one sort column the top-K threshold skips a row group whose minimum
(maximum for DESC) equals the threshold. Such a row group can hold rows equal
to the n-th value, but it returns no row, so the TopK query condition cache
recorded it as holding no row of the result. Overlapping runs that keep
different tied row groups then record all of them, and a later run returns
fewer rows: after 16 overlapping `ORDER BY k LIMIT 1` reads of 16 Parquet
files, the next read returned no row in 5 of 100 cycles (0 of 120 with this
change, 0 of 40 on master).

`getMatchedBuckets` now counts a row group skipped by the threshold of a
single sort column as matched, as it already did for statistics-only reads,
and `getTopKBestValuesOfBuckets` reports the bound of its statistics as its
best value, so the final-threshold check of the cache writers still records
it as empty when that bound sorts strictly beyond the final threshold.

Master is merged in for `skipped_by_top_k` (ClickHouse#124827), which the fence uses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 1, 2026
…p-k-late-skip

For `RowGroup::skipped_by_top_k` (ClickHouse#124827), which the late top-K skip now has to set.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 1, 2026
ClickHouse#124827 reports a row group skipped by a statistics-only top-K threshold
as possibly matching in the query condition cache, but only if
skipped_by_top_k is set. The late check did not set it, so a String
ORDER BY ... LIMIT read at the default settings recorded such row groups
as not matching its WHERE, and a later read with the same WHERE missed
their rows. skipIfExcludedByTopK now sets the mark for every subgroup and
step it drops, not only where it counts the profile event.

05346: the String key section is no longer conditional, now that ClickHouse#124827
is merged. It runs on its own file of 10 row groups, because the read that
uses the cache entry decodes every row subgroup of every row group (about
50 s for the 40 row groups of t.parquet under the flaky check's thread
fuzzer, locally). The columns cache is disabled in all sections: it reads
each row group in one row subgroup, so no row group waits behind another.

Debug build of this branch merged with master 5053961, 05346 with random
settings: 50 of 50 pass; without the mark the cached count() is 1000 or
2000 instead of 10000 in 20 of 20 runs; with master's ReadManager the late
skip sections fail in 10 of 10. Before the columns cache pin, 13 of 50 runs
failed, all with use_columns_cache = 1 and enable_writes_to_columns_cache = 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 1, 2026
…red-by-streams

Resolve the conflict in PartialSortingTransform.h: keep master's public
`min_limit_for_partial_sort_optimization` (ClickHouse#124827) and the `threshold_collector` member.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 3, 2026
Since ClickHouse#124827 a Parquet top-K read by a `String` column skips row groups
by their statistics alone, without the per-row filter. Such a read does
not set `isTopKFilterApplied()`, so the object-storage writer stored its
row blocks, and the blocks of the skipped row groups, never checked
against the predicate, were stored as not matching. A later plain read
of the same condition then skipped matching rows: with this branch
merged into master and default settings, `SELECT s FROM s3(...) WHERE
k > 0 ORDER BY s LIMIT 10` over 512 row groups, then `SELECT count()
FROM s3(...) WHERE k > 0` returned 5863130 instead of 7190235.

Gate the write on `!top_k_filter`, as the `File` writer already does.
That also covers any other top-K mechanism that leaves blocks unread.

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

Projects

None yet

3 participants