Repository navigation
Derive deterministic conditions from conditions involving the current time for the query condition cache - #115522
Conversation
… time for the query condition cache A condition like `time >= now() - INTERVAL 10 DAY` reaches the storage layer with the current-time expression folded into a non-deterministic constant, so it could never be served by the query condition cache: its hash changes with every query, and the cache refuses non-deterministic conditions anyway. Derive a deterministic condition from such conditions by rounding the folded time constants onto a time grid whose step is proportional to the distance between the constant and the current time (capped at one day). Cache writes round toward the condition (the derived condition implies the observed one), cache reads round away from it (the actual condition implies the derived one), so every cache entry remains a true statement and reads can only skip granules soundly. When the constant is already grid-aligned (`today() - 10`, `toStartOfDay(now())`), both directions agree and the cache is effective for the whole grid cell, e.g. until the end of the day. Otherwise entries written during one grid cell serve the queries of the next one: yesterday's queries prime the cache for today's dashboards. Closes #115504 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [2ab128f] Summary: ✅
AI ReviewSummaryThis PR extends the Findings
Final Verdict
|
|
@shankar-iyer Do you like to review this PR? |
Initialize `rounded_seconds` and `rounded_ticks` (`cppcoreguidelines-init-variables`), drop the link to the not-yet-generated settings page for `query_condition_cache_time_condition_grid_factor`, and scope the new setting descriptions and documentation to `MergeTree`, since the file and object storage read paths still use the query condition cache only for deterministic conditions.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes110 object files changed (+188.66 KiB total), 1 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units357 translation units recompiled, 3349 s compile time in total, 356 of them have a recent master baseline. Median compile-time ratio to the baselines is ×0.91 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
|
📊 Cloud Performance Report ✅ AI verdict: This PR lets the query condition cache handle filters that depend on the current time, such as clickbenchFlagged queries (2 of 43)
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_officialFlagged queries (2 of 22)
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
|
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
…ry condition cache tests The test failed in the "old analyzer" CI configuration: the query condition cache only works with the analyzer (`query_info` has no filter DAG without it), so no entries were cached and no hits happened. All other `query_condition_cache` tests already force the analyzer for the same reason (`SET allow_experimental_analyzer = 1`). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115522&sha=af8112e0405b98a3ea1e1cb0b14c4ef360ba699c&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20sequential%2C%202%2F2%29 PR: #115522 Co-Authored-By: Claude Fable 5 <[email protected]>
With `time` in the primary key, the granules holding only old rows are excluded by index analysis, so the cache entries for them can only have been written by `ReadFromMergeTree` under the skip-index-profiled hash of the derived condition (the filter transforms never read those granules). The second query probes the cache before index analysis runs and proves the reuse via `QueryConditionCacheHits`. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 The The |
…y.cpp` Master moved the current version block to `26.9`, so `use_query_condition_cache_for_time_conditions` and `query_condition_cache_time_condition_grid_factor` have to be recorded there instead of `26.8`.
Address review: TopK dynamic filtering folds the internal `__topKFilter` function into the storage filter as `and(__topKFilter(...), time >= ...)`, and `deriveDeterministicTimeCondition` rejected any non-deterministic function outside its `and` / `or` / `not` / comparison spine. A query like `SELECT ... WHERE time >= now() - INTERVAL 10 DAY ORDER BY ... LIMIT n` therefore derived nothing and bypassed the query condition cache entirely, even though the plain `WHERE`, `PREWHERE` and index-analysis paths support it. `deriveDeterministicTimeCondition` now takes `allow_top_k_filter`, which treats `__topKFilter` as an opaque deterministic leaf, mirroring `isDeterministicAllowingTopKFilter` in `updateQueryConditionCache` and `ReadFromMergeTree`. It is passed only where the cache key is additionally partitioned by the TopK plan parameters (the `WHERE` write paths and the `WHERE` consult), because granule exclusions produced under a running `__topKFilter` threshold may only be reused under the same TopK plan. The `PREWHERE` write and consult paths do not apply that salt, so they keep rejecting `__topKFilter`. The predicate-only reuse hash - which lets a TopK read consume entries primed by a plain `SELECT ... WHERE` - is now derived the same way, so a current-time predicate reuses those entries too; `getTopKReusePredicateOnlyConditionHash` became `getTopKReusePredicateOnlyNode` and the caller turns the node into a key. Adds `05054_query_condition_cache_time_conditions_top_k`, covering the TopK write/read round trip, the reuse of plain `WHERE` entries by a TopK read, and the setting being off.
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115522&sha=47c15d694d6ac9b740df5b5fb52113d377ae81ba&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. The This is the known open issue #102331 ( |
|
The fix is already merged: #117218 (mine, merged 2026-09-02T14:31:57Z as What that run hit:
Nothing to do on your side: the job checks out the PR merged into master ( What #117218 does not do: #102331 stays open. The entry suppresses the message in that one log scan, on the grounds that only a mutation command naming |
|
🕵 The only red check on f1cbf2e was |
…the start of an hour The recent rows were inserted in the hour before `now()`. When the test ran right after the start of an hour (or a day), `time >= toStartOfHour(now())` (or `time >= today()`) matched no row of the part at all, so the automatic `minmax` statistics on `time` pruned the whole part before reading. Nothing was read, so nothing was recorded in the query condition cache, and all three retries reported `0 0`. Insert the recent rows in the hour after `now()`, so they always match these conditions. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115522&sha=089cf7272fd81a92a3ef12944d2aede5b000e24d&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29 #115522 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 The only red check on 089cf72 was |
… lower bounds The description of `use_query_condition_cache_for_time_conditions` said that entries written during one grid cell are used during the next one for every unaligned constant. That only holds for lower bounds like `time >= now() - INTERVAL 10 DAY`: an unaligned upper bound like `time < now()` (alone or in a sliding window) is never contained in the condition of an earlier query, so it is not reused. Say so in the setting description and in the query condition cache documentation. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 The only CI failure, |
|
🕵 Pushed 21d12f9, which merges
|
Conflict in `MergeTreeSelectProcessor::read`: master added a second write of the static PREWHERE conditions (`query_condition_cache_attribution`) next to the main PREWHERE write, which this PR had moved to a precomputed `prewhere_condition_for_query_condition_cache`. Keep both: the main write uses the precomputed condition when present, and the attribution write is done independently of it (so the outer guard no longer requires the precomputed condition). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed 2ab128f, which merges The red checks on 21d12f9 are not caused by this PR:
|
… runtime filter in the query condition cache" This reverts commit 64da8a0, reversing changes made to be89302. Conflicts resolved by keeping the later changes in the same lines: `is_query_prewhere` (ClickHouse#130645), the `last_reader_evaluating_defaults` argument (ClickHouse#128452), `readsSameColumns` (ClickHouse#124880), `follows_top_k_filter` (ClickHouse#129882), and the PREWHERE query condition cache write of ClickHouse#115522 in its own form before it merged ClickHouse#122380. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
The query condition cache now serves conditions that involve the current time, e.g.
WHERE time >= now() - INTERVAL 10 DAY, when reading fromMergeTreetables, by deriving a deterministic condition from them with the current-time constant rounded onto a time grid. Closes #115504.Documentation entry for user-facing changes
Documented in
docs/concepts/features/performance/caches/query-condition-cache.mdxand in the new settings' descriptions.A condition like
time >= now() - INTERVAL 10 DAYreaches the storage layer with the current-time expression folded into a non-deterministic constant. It could never benefit from the query condition cache: the constant (and hence the condition hash) changes with every query, and the cache refuses non-deterministic conditions anyway (#81506, #84508).This PR derives a deterministic condition from such conditions by rounding the folded time constants onto a time grid:
The grid step is proportional to the distance between the constant and the current time — one day for a condition looking back ten days, one hour for a condition looking back ninety minutes — multiplied by a configurable factor (
query_condition_cache_time_condition_grid_factor, default 1.0) and capped at one day. This bounds the boundary error relative to the window the query looks at, and makes the cache key rotate roughly once per the same fraction of the window, balancing cache usefulness against staleness of the boundary.Soundness. The two sides of the cache round in opposite directions, so each cache entry stays a true statement regardless of clocks, concurrency, shards or replicas:
updateQueryConditionCache/FilterTransform), the PREWHERE filter (MergeTreeSelectProcessor), and the index-analysis granule exclusions (ReadFromMergeTree, under the skip-index-profiled key as before).filterPartsByQueryConditionCache) probe a weakened condition — the actual filter implies the derived one, so "no rows match the derived condition" makes skipping the granule sound.Each side only needs its own implication, verified locally against its own condition; a hit is possible only when the two derived conditions are structurally identical (same rounded constant), so entries can never be misapplied.
Behavior. When the folded constant is already aligned to the grid —
today() - 10,toStartOfDay(now()),toStartOfHour(now())(rounding is DST-aware, in the timezone of the constant's type) — rounding up and down coincide, so the very next query already reuses the cache, and the key stays stable until the constant changes (e.g. until the end of the day). This exactly matches the issue's example: the derived condition "can be used until the end of day". For an unaligned constant like rawnow() - INTERVAL 10 DAY, writes go to the grid point above the constant and reads probe the grid point below, so entries written during one grid cell serve the queries of the next one: yesterday's queries prime the cache for today's dashboards.The derivation understands monotone condition shapes:
AND/ORchains,NOT(which flips the rounding direction), and comparisons of a deterministic expression with a non-deterministic constant of typeDate/Date32/DateTime/DateTime64. Anything else non-deterministic (e.g.rand(),__topKFiltermixes, equality with a time constant, non-temporal folded constants such asshardNum()arithmetic) keeps the previous behavior: not cached. Deterministic conditions are entirely unaffected — they keep their existing hashes.Verified locally (single part of 2M rows, half of them older than the condition boundary): the second run of
SELECT sum(x) FROM tab WHERE time >= today() - 100drops 122/245 granules through the PREWHERE consult path and 117/245 through the WHERE path.New settings:
use_query_condition_cache_for_time_conditions(default:true)query_condition_cache_time_condition_grid_factor(default:1.0; values <= 0 disable the derivation)Possible follow-ups (out of scope here): same-cell reuse for unaligned constants by additionally evaluating the weakened condition at the write sites; applying the derivation to the object-storage read paths and to the TopK predicate-only reuse hash.
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/115522]
Version info
26.10.1.2322-master(included in26.10and later)