Skip to content

Query condition cache for TopK reads of data lakes - #124808

Merged
alexey-milovidov merged 19 commits into
masterfrom
topk-qcc-object-storage
Oct 22, 2026
Merged

alexey-milovidov merged 19 commits into
masterfrom
topk-qcc-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 data lake tables (Iceberg, DeltaLake with Delta Kernel, Paimon) with Parquet data files - the same as #122064 did for the File engine. So far such reads only consulted the entries written by plain reads with the same predicate, and never wrote any themselves.

A TopN read now records the row groups which hold no row of its result, and a rerun of the same query skips them - also without any WHERE, e.g. SELECT * FROM iceberg_table ORDER BY k DESC LIMIT 10.

  • Under which key. The threshold of the TopN filter comes from the rows of every file the query reads, so the key covers the TopK plan (the hash optimizeTopK computes), the predicate if any, and the serialized snapshot of the table (datalake_table_state pinned in the storage metadata, which the file iterator reads). A snapshot identifies the set of data files and deletes, and data lake files are never modified in place, so no per-file versions are needed: each new snapshot gets fresh entries. No key is made for tables without a UUID (table functions), with distributed processing, with a row policy, for incremental Paimon reads (paimon_incremental_read, which return a different batch of files for the same snapshot), or for configurations without a snapshot state (Hudi, the legacy Delta Lake reader).
  • What is recorded and when. As for File: a row group that returned no row, or whose best returned value of the sort column is strictly beyond the final threshold, holds no row of the result. Deletes only remove rows after the reader, so this stays sound. The entries are written when the source is destroyed, against the final threshold; a cancelled read writes nothing. A file which the iterator split into buckets neither consults nor writes the key.
  • Consulting. A TopN read consults both the plain predicate key and the TopK key, and skips a row group if either verdict excludes it. A file that does not apply the TopN filter (e.g. sorted by an identity partition column) keeps writing plain entries, unless the TopK entries made it skip row groups the predicate alone would not.

The test covers repeated queries with and without a predicate, a different LIMIT / direction / plain read not reusing the entries, the use_query_condition_cache_for_top_k setting, and a new snapshot after ALTER TABLE ... DELETE: without the snapshot in the key, the rerun returns 6, 5, 4 instead of 100999, 100998, 100997 (checked by building with it removed).

Related: #124785
Related: #122064
Related: #122109

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 data lake tables (Iceberg, DeltaLake, Paimon): a rerun of such a query skips the Parquet row groups which held no row of the result in the same snapshot.

🤖 Generated with Claude Code


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

Version info

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

A TopN (`ORDER BY ... LIMIT n`) read of a data lake table (`Iceberg`, `DeltaLake`, `Paimon`) with
Parquet data files now records in the query condition cache the row groups which hold no row of the
result, and a rerun of the same query skips them, also without a `WHERE`. The entries are keyed by
the TopK plan, the predicate, and the snapshot of the table: the snapshot identifies the set of data
files (and deletes), which are never modified in place, and the threshold of the TopN filter comes
from the rows of all of them.

The same was done for the `File` engine in #122064.

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 Oct 21, 2026, 2:30 AM

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [77e72b4]

Summary: ✅


AI Review

Summary

Extends the query condition cache to TopK reads of data lake tables with Parquet files, partitioning threshold-dependent entries by the predicate, TopK plan, and pinned table snapshot. No unresolved actionable findings remain at 77e72b479a8dd6c86f7ad77a5d708bae8f639177; the previous review findings are addressed in the current code.

Missing context / blind spots
  • ⚠️ Full CI for the latest head is still running. No local ClickHouse build was available to rerun the functional tests. Runtime evidence includes the author's Iceberg and DeltaLake rerun measurements and passing metadata/rename regressions in the preceding stateless CI report. Completion of the latest CI closes the remaining validation gap.
Final Verdict

Status: ✅ Approve. No code changes requested; merge remains subject to the required CI checks.

alexey-milovidov and others added 2 commits October 9, 2026 15:46
…imon` reads

An incremental `Paimon` read iterates only the delta since the watermark committed in Keeper
(or of `paimon_target_snapshot_id`, bounded by `max_consume_snapshots`), so the same pinned
`datalake_table_state` yields different sets of data files from query to query. A TopK entry
recorded for one batch could then wrongly skip row groups in another one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 10, 2026 12:09
…ion cache as a whole

`boost::hash_combine` takes `std::size_t &`, which is not `UInt64` on Darwin and WASM,
so combine the key with `SipHash` instead.

Address review: with `use_query_condition_cache_for_top_k = 0` a TopN read neither consults
nor populates the plain predicate entries, also for the files that do not apply the TopN
filter (`ORC`, schema evolution, identity-partitioned sort column), as `File` and `MergeTree` do.

https://s3.amazonaws.com/clickhouse-test-reports/PRs/124808/08f892a6e0762c92e0e5bc00b67ea6d300bf53ba/pr/build_amd_darwin/build_clickhouse/build_clickhouse.log

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=124808&sha=08f892a6e0762c92e0e5bc00b67ea6d300bf53ba&name_0=PR&name_1=Performance%20Comparison%20(amd_release%2C%20master_head%2C%202%2F6) (general_purpose_hashes #1 regression; this PR only touches the query condition cache of data lake TopK reads, not hash functions) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

Withdrawn: the PIE attribution below was wrong. The measured cause is in #124808 (comment)

Original comment

Investigated. Not caused by this PR: general_purpose_hashes #1 (cityHash64(materialize('')) over numbers_mt(500000000)) is the amd per-process slow mode that came with the PIE release build (#117449, reverted in #119279, re-landed in #119284).

No fix PR is in progress yet. The remedy is the open choice in #122447 (comment): (A) build amd_release and arm_release position dependent again, as before #117449, or (B) keep PIE and have the harness confirm failing rows after two restarts. I still recommend (A). I will post the fixing PR here once one of them is chosen.

alexey-milovidov and others added 2 commits October 11, 2026 12:19
…es` for the TopK cache gate

This PR intentionally makes `use_query_condition_cache_for_top_k = 0` keep a TopN read of a data
lake table out of the query condition cache as a whole, also for the files that do not apply the
TopN filter (as `File` and `MergeTree` do, requested in review). The test added on master pinned
the previous per-file behaviour, so the `05320_top_k_off` query now has no cache hits.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124808&sha=89e62924aac1ac2e6655a41bd72ddb4d976a687a&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20sequential%29
#124808

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

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 77e72b479 with master c238db144 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of d320d8e21; 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

12 object files changed (+80.09 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromObjectStorageStep.cpp.o 381.24 KiB 420.43 KiB +39.19 KiB (+10.28%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/StorageObjectStorageSource.cpp.o 1.05 MiB 1.08 MiB +28.51 KiB (+2.65%)

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

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

Job report

@groeneai groeneai mentioned this pull request Oct 11, 2026
1 task done
@groeneai

groeneai commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Fixing PR for the amd_release 2/6 perf red (general_purpose_hashes #1): #125278 (closed unmerged: the release binaries stay PIE). A fix task is moved to pending; the fixing-PR link will follow here. Result: #124808 (comment) (owner: #124676).

alexey-milovidov and others added 3 commits October 12, 2026 14:38
… the step

The TopK entries of `ReadFromObjectStorageStep` were keyed by the `condition_hash` of the format filter, which lacks the conjuncts on virtual columns such as `_path`. Those narrow down the set of files read, so a query with such a conjunct could reuse the row group skips of a broader query and lose rows of its result. Key by the whole filter of the step, as `StorageFile` does.

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

Copy link
Copy Markdown
Member Author

🕵 The Stress test (amd_msan) failure (Segmentation fault, STID 2395-4d91, in KeyCondition under a materialized view insert) is not caused by this PR; it is fixed by #125990, which cites this run. Merged master into the branch to refresh CI.

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/updateQueryConditionCache.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124808&sha=c4e1c93cea5cf3fc1a02858ff717e8ff8f5e80c0&name_0=PR&name_1=Stress%20test%20%28amd_debug%29 (Server unresponsive: memory limit exceeded in Stress test (amd_debug); over the last 14 days it also failed on master and about a dozen unrelated PRs) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in progress: #125706 (approved, merge state clean).

This run has the same cause as the ones on #100377, #104965 and #114043. At 01:15:57 a fuzzed secondary query of 04035_url_cluster_callback_cancel_race (urlCluster) got an injected MEMORY_LIMIT_EXCEEDED in ExecutingGraph::addNode, inside the PipelineExecutor constructor, and the pipeline dump was appended to it (25,888 nodes, 2,183,279 bytes in query_log). Since #121503 that exception is copied into the processors_profile_log row of every processor. The next flush of that log started 5 seconds later and reserved 3.13 GiB. (total) memory went from 9.4 GiB at 01:16:03 to 35 GiB at 01:16:47, hit the 42.58 GiB limit at 01:17:05, and dmesg.log has a memcg OOM kill of the server at 01:18:45.

The master run (6ecd0f46846a, amd_msan) has the same 04035 dump (25,902 nodes) and a memcg kill 35 seconds after it. 13 of the 14 rows of this check in the last 14 days are from 2026-10-11 or later, after #124906 (memory-tracked containers in ExecutingGraph, so the allocation there can now throw) joined #121503 on master.

alexey-milovidov and others added 2 commits October 18, 2026 16:58
…`_table` condition

`RENAME TABLE` and `EXCHANGE TABLES` keep the UUID and the data lake snapshot
but change `_table`, so the TopK query condition cache key of a read of object
storage stays the same while a condition on `_table` lets other files make the
threshold. Treat `_table` like `_time`, `_etag` and `_tags` and disable the TopK
entries when the filter or PREWHERE reads it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/ObjectStorage/StorageObjectStorageSource.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124808&sha=9004f7b8dfd988ec312571e7ebb70289d88f5ca2&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 (05241_vector_search_quantize_codec_read_task_subcolumn returns different data from a Compact part with index_granularity = 7952, reproducible with the same randomized settings) and provide a fix in a separate PR. If the fix is already in progress, link it here - possibly #125446.

The other failure, 03821_drop_workload_during_query_race, is fixed on master by 741c1e5, which is now merged into this branch.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is #125446 (open; the changes requested in its review are in b58c6f8, waiting for re-review).

Cause: with index_granularity = 7952 the last granule's vec elements fill exactly one 1 MiB block, so the vec.quantized mark is (block, 1048576). id and vec.size0 are read by readBig straight into the columns, then CompressedReadBufferFromFile::seek takes its shortcut on the stale block left in the buffer, and vec.quantized gets the float elements from offset 0. It is not arm-specific: install.sh picks the server's default_compression_codec at random, this job got ZSTD(1) (that is why it reproduced with the same settings), and on x86 I get the same wrong hash with ZSTD and the right one with LZ4.

Details and a smaller 26.3 case: #125446 (comment). Both are correct with b58c6f8.

}
catch (...)
{
tryLogCurrentException(log, "Failed to write to query condition cache");

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.

Why do we need try/catch? Better to just let the error propagate.

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.

This runs in the destructor: the verdict needs the final TopK threshold, which is known only after the sorting transforms are done with the rows, so the write cannot happen earlier (e.g. in onFinish). Letting the exception escape the destructor would call std::terminate. StorageFileSource::~StorageFileSource uses the same pattern.

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

Everything else LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Oct 21, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 21, 2026
Merged via the queue into master with commit c186988 Oct 22, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the topk-qcc-object-storage branch October 22, 2026 01:26
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 22, 2026
alexey-milovidov added a commit that referenced this pull request Oct 23, 2026
Resolve conflicts with the TopK query condition cache of object storage
(#124808) and the query condition
cache of `URL`: the plain predicate is consulted under the `table_id` and key for
files, so table functions keep using it; the TopK key stays with tables having a UUID.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 23, 2026
… 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]>
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 — 77e72b47 Deployed Oct 21, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. 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