Skip to content

Query condition cache for TopK reads of Parquet files in object storage - #124813

Merged
alexey-milovidov merged 33 commits into
masterfrom
topk-qcc-plain-object-storage
Nov 7, 2026
Merged

alexey-milovidov merged 33 commits into
masterfrom
topk-qcc-plain-object-storage

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

Implements the query condition cache for TopN (ORDER BY <column> LIMIT n) reads of Parquet files in plain object storage (S3, AzureBlobStorage), continuing #124808 (data lakes).

A TopN read now records the row groups which hold no row of its result, and a rerun of the same query over the same objects skips them - also without any WHERE.

  • Under which key. The threshold of the TopN filter comes from the rows of every object the query reads, so the key covers the TopK plan, the predicate if any, and the paths and ETags of all objects (the same per-file keys the plain cache entries use, sorted). Unlike a data lake, plain object storage has no snapshot that identifies the set of files, so ObjectIteratorListingAllForTopKQueryConditionCache lists all objects on the first call of next (when the pipeline already runs, as some iterators apply a _path / _file filter only then) before returning the first one. A TopN read reads all objects anyway, so this adds no requests. With more than 100000 objects, or an object without a usable ETag, inside an archive or split into buckets, no key is made and the objects are read as before.
  • Overwrites. An object can be overwritten after it was listed. If another object's entry were used while this one is read in a version the key does not describe, rows of the result could be skipped. So the key is made only when every read is pinned to the listed ETag: S3 with s3_validate_etag_on_read (not for GCS) or Azure with azure_validate_etag_on_read, both enabled by default. Then an overwrite between the listing and the read fails the read. The check is shared with lazy materialization, which has the same requirement (isReadPinnedToListedGeneration).

The test covers repeated queries with and without a predicate, a different LIMIT / direction / plain read not reusing the entries, a rewrite of one object of a glob (without the ETags in the key, the rerun returns 999, 998, 997 instead of 100999, 100998, 100997 - checked by building with them removed), unpinned reads, and use_query_condition_cache_for_top_k = 0.

Benchmark (local build, local MinIO; 32 Parquet objects in one glob, 32M rows, 3200 row groups of 10000 rows; SELECT * FROM t ORDER BY k DESC LIMIT 10 with k = cityHash64(number); medians of 3 runs):

run ms S3GetObject ReadBufferFromS3Bytes
use_query_condition_cache_for_top_k = 0 120 165 1.15 GiB
cold cache 93 158 1.30 GiB
warm cache 47 38 7.59 MiB

A cold run costs the same as the read without the cache, since listing the glob ahead adds no requests. With a WHERE the numbers are similar (111 / 110 / 40 ms; 1.95 GiB / 1.95 GiB / 6.64 MiB). Details: #124813 (comment)

Related: #124785
Related: #124808
Related: #122064

Changelog category (leave one):

  • Performance Improvement

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

The query condition cache now also works for ORDER BY ... LIMIT n queries over Parquet files in S3 and AzureBlobStorage: a rerun of such a query over the same objects skips the row groups which held no row of the result.

🤖 Generated with Claude Code


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

Version info

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

A TopN (`ORDER BY ... LIMIT n`) read of Parquet files in `S3` or `AzureBlobStorage` now records in
the query condition cache the row groups which hold no row of the result, and a rerun skips them.
The threshold of the TopN filter comes from the rows of all objects of the query, so the key covers
the paths and ETags of all of them: `ObjectIteratorListingAllForTopKQueryConditionCache` lists the
objects before returning the first one (up to 100000 objects). An object can be overwritten after
it was listed, so the key is made only when every read is pinned to the listed ETag
(`s3_validate_etag_on_read`, `azure_validate_etag_on_read`).

Related: #124785

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

mintlify Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 2, 2026, 11:23 AM

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d6d53d0]

Summary: ✅


AI Review

Summary

This PR extends the query condition cache to TopK reads of Parquet files in S3 and AzureBlobStorage, tying cached row-group exclusions to the query semantics and object generations. Reviewed head d6d53d0307c886a029d843e4b7b366081afc601f, the full diff, surrounding read paths, and all prior discussion. No unresolved actionable findings remain.

Missing context / blind spots
  • ⚠️ Full CI for the current head is still running. Confirm the remaining builds and functional tests pass before merging; this review did not run a local build or tests. Current CI report.
Final Verdict

Status: ✅ Approve — no code changes requested; final CI results remain pending.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. labels Oct 9, 2026
alexey-milovidov and others added 2 commits October 10, 2026 12:17
…state; fix the object limit and the build on Apple/WASM

- Extract the repair of a missing `datalake_table_state` from `createFileIterator` into
  `StorageObjectStorageSource::ensureDataLakeTableState`, and call it in
  `ReadFromObjectStorageStep::createIterator`, so the TopK key is made from the same
  snapshot the files are read from, also when the state was missing in the storage metadata.
- `ObjectIteratorListingAllForTopKQueryConditionCache` lists one object more than
  `MAX_OBJECTS`, so exactly `MAX_OBJECTS` objects still make a key.
- Use `size_t` hash seeds for `boost::hash_combine`, which did not compile on Apple and
  WASM where `UInt64` is a different type than `size_t`.

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

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d6d53d030 with master f2187aa97 (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.

Object file sizes

521 object files changed (+85.14 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/StorageObjectStorageSource.cpp.o 1.10 MiB 1.13 MiB +27.79 KiB (+2.46%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromObjectStorageStep.cpp.o 431.40 KiB 457.41 KiB +26.01 KiB (+6.03%)

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

3348 translation units recompiled, 18692 s compile time in total, 3347 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.9 s

Job report

alexey-milovidov and others added 2 commits October 11, 2026 12:04
…at use the TopK query condition cache key

For plain object storage, the key may turn out not to be made (too many objects, an archive member,
a bucketed read, an object without a usable `ETag`), and then the per-row-group `top_k_best_value`
bookkeeping was paid for nothing. Read only the files that actually use the key with a
`FormatFilterInfo` with `track_row_group_best_values`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Processors/QueryPlan/ReadFromObjectStorageStep.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124813&sha=da25e86336b792e034ea0b003dd17bccbbe4566f&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29 (Logical error: Inconsistent KeyCondition behavior, STID 5182-4365: MergeTree with a Nullable key, IN (..., NULL) with transform_null_in = 1; this PR only changes object storage reads, and #121089 may cover it) and provide a fix in a separate PR. If the fix is already in progress, link it here.

Also: Stateless tests (arm_asan_ubsan, azure, sequential) hit the 9000 s job timeout (https://s3.amazonaws.com/clickhouse-test-reports/PRs/124813/da25e86336b792e034ea0b003dd17bccbbe4566f/pr/stateless_tests_arm_asan_ubsan_azure_sequential/job.log). The slowest tests were 03988_cached_read_big_at (342 s, see #125010) and 01111_create_drop_replicated_db_stress, and the new tests of this PR do not appear among them. 05238_pretty_squash_broken_pipe on Fast test (arm_darwin) is addressed by #125102.

@groeneai

Copy link
Copy Markdown
Collaborator

The AST fuzzer (amd_debug) failure is fixed by my open PR #121089 (CI green, waiting for review).

I checked it against this exact query. On a master debug build (46dfb815), SELECT count() over the 03733_has_function_key_condition table with key_nullable IN (-9223372036854775808, -2147483649, -9223372036854775807, NULL) SETTINGS transform_null_in = 1 aborts with the same Inconsistent KeyCondition behavior. With #121089 applied to current master (b7cc9968), it returns 10000, the same as with use_primary_key = 0. The cause is that the nullable-key exact-count safeguard treats nullIn like in (NULL for a NULL key), but nullIn matches NULL keys definitely.

The job timeout: #123849 (mine) splits Stateless tests (arm_asan_ubsan, azure, sequential) into 2 batches.

@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

One query was flagged: clickbench Q20 is -42.7% faster (220 ms to 126 ms), and CPU time dropped from about 2898 ms to 1538 ms, so the gain reflects less work done, not a timing quirk. The PR does not explain it. Every source change is in the object-storage read path: a TopK query condition cache for S3, Azure and data-lake Parquet reads, plus a refactor of the existing ETag-pinning check into a helper. ClickBench reads a local MergeTree table, so Q20 never runs that code. The result clears the thresholds that lock a verdict in place, so it stays an improvement, but it should not be credited to this PR; it most likely comes from other changes between the base build and the PR build, and a re-run against the PR's exact merge base would confirm that.

clickbench

🟢 1 improved

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 126 -42.7% <0.0001 The -42.7% result passes the hard trust thresholds and CPU time also roughly halved, but this PR changes only object-storage and data-lake TopK reads, which Q20 on MergeTree never runs. The speedup most likely comes from other code that differs between the base build and the PR build.

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: 100ac588-6672-436d-82e2-b46857e638d9
  • MIRAI run: 0ef919cf-bcce-48d9-942c-a59d6a4e6c39
  • PR check IDs:
    • clickbench_130207_1791952364
    • clickbench_130213_1791952364
    • clickbench_130229_1791952364
    • tpch_adapted_1_official_130551_1791952402
    • tpch_adapted_1_official_130658_1791952407
    • tpch_adapted_1_official_130681_1791952408

alexey-milovidov and others added 2 commits October 12, 2026 14:55
…rage

Take the key of the base PR (the whole filter of the step, `SipHash` of the
condition, the TopK plan and the table state) and keep the plain object
storage part: `condition_hash_without_files` is the hash of the condition and
the TopK plan, to which the hash of the set of files is added later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y condition cache key

`getDataLakeSettings` throws `NOT_IMPLEMENTED` for plain object storage, so after
the merge of the base branch every TopN read over `S3` failed.

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

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai, noted: the AST fuzzer Inconsistent KeyCondition behavior failure is tracked by #121089 and the azure sequential timeout by #123849.

Update: merged the base PR branch (topk-qcc-object-storage, with current master), which keys the TopK entries by the whole filter of the step, and fixed a merge issue where the paimon_incremental_read check called getDataLakeSettings for plain S3 (NOT_IMPLEMENTED). 05320, 05339 and 05340 pass locally against MinIO.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124813&sha=4cdf05d99b254b5a94f96ee7fbe4b705e7647609&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29 (TLP Aggregate oracle mismatch for SELECT count() FROM test_hilbert_encode__fuzz_12 WHERE (x >= 10) AND (x <= 20) AND (y >= 20) AND (toLowCardinality(30) <= y) - a MergeTree with a hilbertEncode key and analyze_index_with_space_filling_curves, unrelated to this PR) and provide a fix in a separate PR. If the fix is already in progress, link it here.

The test_storage_delta (test_writes_timestamp_ntz_annotation_nested, test_write_to_table_with_unsupported_writer_feature_is_rejected) and test_storage_iceberg_concurrent failures also failed on master on 2026-10-12 and pass there after #125455, so I merged master into this branch to pick that up.

…n cache key

A URL with `versionId` makes every read fetch that version, bypassing the
listed-`ETag` validation, while the object metadata (and so the `ETag` in the
per-file key) describes the latest version. After `ALTER NAMED COLLECTION`
and `DETACH` / `ATTACH`, the table keeps its UUID, paths and `ETag`s, so the
entries of another version could be reused and rows of the result skipped.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124813&sha=3d741af8db977bc1427159d9a86b4239b9f35274&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29 (abort in LocalConnection::sendCancel from ClientBase::processInsertQuery, unrelated to this PR) and provide a fix in a separate PR. If the fix is already in progress, link it here — it looks like #127364. The Build profile diff failure is CI infrastructure (LogClusterNotReady).

@groeneai

Copy link
Copy Markdown
Collaborator

Same bug as #127364, which is the fix (open, CI green at d72ee5c, waiting for review).

The stack on 3d741af (STID 2905-3cdd) is the one #127364 targets: an INSERT in the embedded client (web terminal / SSH) throws after LocalConnection::finishQuery has already reset state, the catch in ClientBase::processInsertQuery calls sendCancel, and LocalConnection::sendCancel dereferences the empty std::optional<LocalQueryState>. The PR adds if (!state) return; there, plus chassert(state) in pullBlock and finishQuery, and test 05443_local_cancel_after_insert_finished (aborts on master, passes with the fix).

Master still has the unguarded dereference. Since #125517 routed stress load through the web terminal and SSH, this abort has failed 11 stress jobs today under three STIDs (2905-3cdd, 2360-3d86, 3554-3f66), 4 of them on master.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai - agreed, the Stress test (arm_asan_ubsan, s3) abort in LocalConnection::sendCancel is fixed by #127364 and is unrelated to this PR.

Update: the CH Inc sync conflict is resolved (the sync PR is mergeable again). The remaining Build profile diff failure is CI infrastructure (LogClusterNotReady: the endpoint never became ready).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Update: merged current master (6624a338714) into the branch. The merge is clean and does not touch the files this PR changes, and the result builds.

The previous red checks were not caused by this PR:

  • Build profile diff is CI infrastructure (LogClusterNotReady: the endpoint never became ready).
  • CH Inc sync (https://github.com/ClickHouse/clickhouse-private/pull/80259) failed on tests outside the object-storage TopK read path: 01173_transaction_control_queries, 05449_radix_uniq_exact_spill_bounded_sets, 05453_webterminal_close_at_binary_format_question, 05161_blob_killer_on_cached_plain_disk, two MSan timeouts in 05296/05300_json_shared_typed_paths_*, test_storage_iceberg_with_spark/test_compaction_file_size.py, and test_shared_merge_tree_lightweight_snapshot. The new commit starts the sync and CI again.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check was Fast test (arm_darwin) failing 05397_clickhouse_local_locked_path_untouched, which is unrelated to this PR and already fixed on master by 59f220cb8187 ("Skip 05397_clickhouse_local_locked_path_untouched on macOS"). Merged current master (4e3df38e874c) to pick up the fix; the merge is clean, only adds new settings to src/Core/Settings.cpp among the files this PR touches, and the affected translation units build.

alexey-milovidov and others added 2 commits October 31, 2026 05:47
…ull`

A URL with `versionId` makes `ReadBufferFromS3` request that version instead
of checking the listed `ETag`. For a real version this pins the read, but the
null version is mutable: in a bucket with versioning suspended, an upload
under the same key overwrites it in place. So a rerun could read a replaced
object while reusing entries recorded for the old one, and skip row groups
of other objects that now hold rows of the result.

`isReadPinnedToListedGeneration` now returns false for `versionId=null`.

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

Copy link
Copy Markdown
Member Author

🕵 The only red check, Stress test (amd_tsan) (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124813&sha=b879d02bddfb0011480713e05f3fd7a680f55165&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29), is a data race in ClientBase::onProgress in the embedded client (LocalServerPty): LocalConnection calls the progress callback from a pipeline thread that runs a scalar subquery of a materialized view, while the client thread calls it too. The ReadTaskIterator frames are only where the pool threads were first created. It is unrelated to this PR and is being fixed by #128395 and #128019.

Update: merged current master (c189bd99fbda) into the branch. The merge is clean. Master's statistics-only TopK change (filter_rows) touches the same functions in ReadFromObjectStorageStep.cpp and StorageObjectStorageSource.cpp. The merged code is consistent: a statistics-only read makes no TopK cache key and is treated as a plain read. The result builds. All review threads are resolved.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check was CH Inc sync (tests failed). In the sync PR, Integration tests (amd_msan, 7/8) and (amd_tsan, 7/8) failed test_storage_iceberg_with_spark/test_compaction_file_size.py::test_compaction_splits_a_file_above_the_upper_threshold[s3-2] (the oversized file is rewritten into one file instead of being split). This PR doesn't cause it: the test is private-only, and on 2026-10-31 and 2026-11-01 it failed the same way in unrelated sync PRs (sync-upstream/pr/118465, sync-upstream/pr/68493, sync-upstream/pr/110886). The same job passes in more recent runs. The third failure, Integration tests E2E test_e2e_databricks_rest_catalog/test.py::test_show_tables_in_alias, tests an external Databricks catalog and isn't touched by this change either.

Merged current master (92ff9284e05) into the branch. The merge has no conflicts, StorageObjectStorageSource.cpp, ReadFromObjectStorageStep.cpp and FormatFactory.cpp compile, and clickhouse links. The merge also triggers a new run of the sync PR.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

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 self-assigned this Nov 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 7, 2026
Merged via the queue into master with commit 04bdff2 Nov 7, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the topk-qcc-plain-object-storage branch November 7, 2026 16:59
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 7, 2026
murphy-4o pushed a commit that referenced this pull request Nov 15, 2026
Resolve the conflicts in ReadFromObjectStorageStep.cpp/.h and StorageObjectStorageSource.cpp/.h: keep the 26.10 side and take only the lines of #113095. The conflicting master context is the TopK query condition cache for object storage (#124808, #124813) and the declarations next to it, none of which is in 26.10. So the in-order sources are built without a TopK query condition cache key, and createIterator keeps its 26.10 form, which has no iterator_metadata to preserve.

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

This branch was successfully deployed

1 active deployment
staging - docs — d6d53d03 Deployed Nov 2, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. 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.

3 participants